【Torch巩固复习记录】Tensors

        开个新坑。最近在准备面试的时候,突然被一个写神经网络的题给难住了,因此也意识到了我很长一段时间内忘了去巩固pytorch的基本矩阵操作知识,太过于依赖调包+google搜索文档(甚至现在开始依赖chatgpt)。虽然不关注代码细节,关注输入输出,然后cv+拼积木的做法在短期内可以搭建出合格的框架,但是这显然缺少更深入的理解。遂决定,要把pytorch的一些基本概念再复习复习。

        本坑的所有内容都来自于:Welcome to PyTorch Tutorials — PyTorch Tutorials 2.0.0+cu117 documentationhttps://pytorch.org/tutorials/index.html


 Tensor的基本概念:tensor是很像numpy的一种矩阵存储方式,甚至在很多时候和numpy公用一个存储空间。

Tensor的初始化

1、直接从list初始化:

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

2、从numpy初始化:

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

3、从另一个tensor初始化:

x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

4、random或固定值初始化:

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")

Tensor的固有属性

三个固有属性,shape,dtype,device

tensor = torch.rand(3,4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

Tensor的基本操作

1、默认情况下用cpu运行,需要用gpu的话需要用.to方法

# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')

2、基础操作

#Standard numpy-like indexing and slicing:
tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0

#Joining tensors
t1 = torch.cat([tensor, tensor, tensor], dim=1)

# 叉乘This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)


# 点乘This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

3、单值用.item()提取

agg = tensor.sum()
agg_item = agg.item()

与NumPy的联结

numpy()和.from_numpy()共享存储空间。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值