动手学深度学习:数据基本操作(创建、索引、合并、python转换)

中文版官网:http://courses.d2l.ai/zh-v2/

https://d2l.ai/chapter_preliminaries/ndarray.html

https://zh-v2.d2l.ai/chapter_preliminaries/ndarray.html

1. 创建

import torch

x = torch.arange(12, dtype=torch.float32).reshape((3,4))

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

help(torch.tensor) 查询帮助

x = torch.arange(12) # 0~11

x.shape

x.size()

reshape为浅复制,改变它会改变原有的

b = x.reshape((3, 4))

torch.empty(2, 3)

torch.zeros(2, 3, 4)

torch.ones((2, 3, 4))

torch.randn(3, 4) # double

2. 数据索引

x[0]

x[-1]

x[1:3] 包含第一个、第二个

3. 两个Tensor合并

dim 倒着数

torch.cat((X, Y), dim=0) # 纵向,"列"对齐

torch.cat((X, Y), dim=1) # 横向,"行"对齐

4. pytorch和numpy转换 

*.numpy() # 转换为numpy数据

torch.tensor(*) # 转换为pytorch格式数据

猜你喜欢

转载自blog.csdn.net/yaked/article/details/115037539