"""
演示
张量的创建的基本方式
张量
pytorch中存储数据的一种容器,元素必须是数值,元素类型必须相同
设计到的API:
torch.tensor 根据指定数据创建张量
torch.Tensor 根据形状创建张量, 也可用来创建指定数据的张量
torch.IntTensor、torch.FloatTensor、torch.DoubleTensor 创建指定类型的张量
注意:
torch.Tensor比torch.tensor多一个功能,可以指定形状来创建张量
要掌握的:
torch.tensor(数据,数据类型torch.float32)
"""
# 导包
import torch
# 1.定义函数,演示torch.tensor创建张量
def demo01():
# 1.创建0D/维张量
t1 = torch.tensor(1,dtype=torch.float32)
print(f"0D张量:{t1},维度:{t1.ndim}, shape: {t1.shape}, type: {type(t1)}, dtype: {t1.dtype}")
# 2.创建1D/维张量
t2 = torch.tensor([1.,])
print(f"1D张量:{t2},维度:{t2.ndim}, shape: {t2.shape}, type: {type(t2)}, dtype: {t2.dtype}")
# 3.创建2D/维张量
t3 = torch.tensor([[1,2],[3,4]])
print(f"2D张量:{t3},维度:{t3.ndim}, shape: {t3.shape}, type: {type(t3)}, dtype: {t3.dtype}")
# 4.创建3D/维张量
t4 = torch.tensor([[[1,2],[3,4]],[[5,6],[7,8.]]])
print(f"3D张量:{t4},维度:{t4.ndim}, shape: {t4.shape}, type: {type(t4)}, dtype: {t4.dtype}")
# 2.定义函数,演示torch.Tensor创建张量
def demo02():
# 1.创建0维张量/0D张量,也就是标量
t1 = torch.Tensor(1)
print(f"0D-t1:{t1}, shape: {t1.shape}, type: {type(t1)}, dtype: {t1.dtype}")
# 2.创建1维张量/1D张量
t2 = torch.Tensor([1,2,3])
print(f"1D-t2:{t2}, shape: {t2.shape}, type: {type(t2)}, dtype: {t2.dtype}")
# 3.创建2维张量/2D张量
t3 = torch.Tensor([[1,2,3],[4,5,6]]) # 形状(2,3)
print(f"2D-t3:{t3}, shape: {t3.shape}, type: {type(t3)}, dtype: {t3.dtype}")
# 4.创建3维张量/3D张量
t4 = torch.Tensor([[[1,2,3],[4,5,6]]]) # 形状(1,2,3)
print(f"3D-t4:{t4}, shape: {t4.shape}, type: {type(t4)}, dtype: {t4.dtype}")
# 5.创建指定形状的张量,(3,4)
t5 = torch.Tensor(3,4)
print(f"指定形状-t5:{t5}, shape: {t5.shape}")
# 3.定义函数,演示torch.IntTensor(Int32)、torch.FloatTensor(Float32)、torch.DoubleTensor(Float64)创建张量
def demo03():
# 1.创建0维张量/0D张量,也就是标量
t1 = torch.IntTensor(1)
print(f"0D-t1:{t1}, shape: {t1.shape}, type: {type(t1)}, dtype: {t1.dtype}")
# 2.创建1维张量/1D张量
t2 = torch.IntTensor([1,2,3])
print(f"1D-t2:{t2}, shape: {t2.shape}, type: {type(t2)}, dtype: {t2.dtype}")
# 3.创建2维张量/2D张量
t3 = torch.FloatTensor([[1,2,3],[4,5,6]]) # 形状(2,3)
print(f"2D-t3:{t3}, shape: {t3.shape}, type: {type(t3)}, dtype: {t3.dtype}")
# 4.创建3维张量/3D张量
t4 = torch.DoubleTensor([[[1,2,3],[4,5,6]]]) # 形状(1,2,3)
print(f"3D-t4:{t4}, shape: {t4.shape}, type: {type(t4)}, dtype: {t4.dtype}")
# 4.定义函数,演示张量的属性
# type:对象类型,shape:形状,dtype:数据类型,device:设备,requires_grad:是否开启梯度计算
def demo04():
# 1.创建一个张量,(2,3)
# t1 = torch.tensor([[1,2,3],[4,5,6]],dtype=torch.float32,device="cuda",requires_grad=True)
t1 = torch.tensor([[1,2,3],[4,5,6]], device="cuda")
print(f"t1:{t1}, type: {type(t1)}, shape: {t1.shape}, dtype: {t1.dtype}, device: {t1.device}, requires_grad: {t1.requires_grad}")
# dtype: int32
# device:cpu
# requires_grad: False
...
# 测试
if __name__ == '__main__':
demo01()
# demo02()
# demo03()
# demo04()