Torch
创建初始化零矩阵且数据类型为long:
import torch
x=torch.zeros(3, 2, dtype=torch.long)
print(x)
print (x.size())
输出:
tensor([[0, 0],
[0, 0],
[0, 0]])
torch.Size([3,2])
直接从数据构造张量
x = torch.tensor([5.5, 3])
print (x)
y=torch.FloatTensor([[1,2,3],[4,5,6]])
print (y)
输出:
tensor([5.5000, 3.0000])
tensor([[1.,2.,3.],
[4.,5.,6.]])
输出张量的形状:
print(x.size())
输出:
torch.Size([2])
两个张量x,y相加,结果输出给张量
import torch
x=torch.zeros(3,2,dtype=torch.long)
y=torch.tensor([[1,2],[3,4],[5,6]])
print (x)
print (y)
print (x.sizze())
z=torch.empty(3,2)
torch.add(x.float(),y.float(),out=z)
print (z)
请大家一定注意x y的数据类型, 如果把x,y的float()都删掉,这里会报错
RuntimeError: expected device cpu and dtype Float but got device cpu and dtype long
最终输出
tensor([[0,0],
[0,0],
[0,0]])
tensor([[1,2],
[3,4],
[5,6]])
torch.Size([3,2])
tensor([[1.,2.],
[3.,4.],
[5.,6.]])
张量转化成numpy
z.data.numpy()
输出:
[[1. 2.]
[