Torch对张量的计算
import torch
'''张量定义'''
a=torch.FloatTensor(2,3)
b=torch.FloatTensor([2,3,4,5])
c=torch.rand(2,3)
d=torch.randn(2,3)
e=torch.arange(1,20,1)
f=torch.zeros(2,3)
'''张量计算'''
g=torch.abs(d)
g=torch.add(g,d)
g=torch.add(g,10)
g=torch.clamp(g,-0.1,0.1)
g=torch.pow(g,2)
'''矩阵乘法'''
a=torch.randn(2,3)
b=torch.randn(3,2)
c=torch.mm(a,b)
Numpy对数组的计算
import numpy as np
'''numpy定义'''
a=np.array([2,3,4])
b=np.array([(2,3,4), (4,5,6)])
c=np.array([[2,3,4], [4,5,6]])
d=np.array([[2,3,4], [4,5,6]],dtype=complex)
e=np.zeros((3,4))
f=np.ones((3,4))
g=np.empty((3,4))
h=np.arange(5)
i=np.arange(10,30,5)
j=np.linspace(0,2,9)
'''numpy计算'''
k=e-f
l=h**2
n=np.sin(l)
m=h<3
o=b*c
p=np.transpose(c)
q=b.dot(p)
r=h.sum()
s=h.min()
t=h.max()
'''numpy索引'''
u=np.arange(10)**3
print(u[2])
print(u[2:5])
u[0:6:2]=-100
v=u[::-1]
'''遍历数组'''
for i in u:
print(i)
'''用函数创建数组'''
def f(x,y):
return 10*x+y
w=np.fromfunction(f,(5,4),dtype=int)
print(w[2,3])
print(w[0:5,1])
print(w[:,1])
print(w[1:3,:])
print(w[-1])
print(d.dtype)
张量和数组的转换
import torch
'''numpy转tensor'''
color = np.array([[[0, 0, 0], [128, 0, 0], [0, 128, 0]],[[0, 0, 0], [128, 0, 0], [0, 128, 0]]])
b = torch.from_numpy(color)
'''将矩阵展开成一维'''
target = b.contiguous() .view(-1)
'''将矩阵展前面的维度展开,保持最后一维'''
target = b.contiguous() .view(-1,3)
'''维度转换'''
outlabimg = b.transpose(0, 1)
'''相同数值统计'''
a=torch.FloatTensor([[[2,3,0,5],[2,3,0,5]],[[2,3,0,5],[2,3,0,5]]])
b=torch.FloatTensor([[[2,3,4,5],[2,3,0,5]],[[2,3,0,5],[2,3,0,5]]])
equl=(a==b).sum()
print(a.shape)
print(equl)
|