创建一个矩阵的操作
import torch
x = torch.empty(5,3)
if __name__ == '__main__':
print(x)
创建一个有初始化的矩阵:
y = torch.rand(2,4)
y_1 = torch.randn(2,4)
if __name__ == '__main__':
print(y)
print(y_1)
对比有初始化和无初始化的矩阵时,当声明一个未初始化的矩阵的时候,它本身不包活任何确切的值。
创建一个全0的矩阵,指定数据的类型为long
x: Tensor = torch.zeros(5,7,dtype =torch.long )
if __name__ == '__main__':
print(x)
通过数据来创建张量
y: Tensor = torch.tensor([2.5,3.5])
通过已有的一个张量来创建一个相同尺寸的新张量,创建一个与已有张量尺寸相同的张量但是其中的值不同的张量
x: Tensor = torch.zeros(5, 7, dtype=torch.long) '''use new_methods to construct a new tensor which own the same size of the ole ones ''' x = x.new_ones(5, 7, dtype=torch.double) '''use rand_like method to construct a new tensor which own the same size of the old one but the values of the new tensor are random also the type of the values are redefine''' y: Tensor = torch.rand_like(x, dtype=torch.double)
double类型显示的所有张量都带有.
得出张量的尺寸
print(x.size())
注意:x.size()函数本质返回的是一个tuple,因此它支持元组的所有操作。
基本运算操作加法操作
第一种
print(x+y)
第二种
z = torch.add(x,y)
第三种
'''define a new empty tensor, use the parameter of the add method to give the value of the method's result through " out " ''' result = torch.empty(5,7) torch.add(x,y,out=result)
第四种(原地置换)
y.add_(x)
注意:所有的原地置换(in-place)都是存在小下划线的_,并且会改变原来的对象
利用Numpy切片的方式访问张量



