第一章基本操作-基本使用方法 (1.torch.empty, 2.torch.rand, 3.torch.zeros, 4.torch.tensor, 5.x.new_ones,6.torch.rand_like, 7.torch.randn, 8.torch.from_numpy, 9.x.view(改变维度))

import torch


x = torch.empty(5, 3) # 生成空的矩阵
print(x)

x = torch.rand(5, 4) # 生成随机矩阵
print(x)


x = torch.zeros(5, 4, dtype=torch.long) # 生成空矩阵
print(x)

x = torch.tensor([5, 3]) # 将列表转换维tensor类型
print(x)

x = x.new_ones([5, 3], dtype=torch.double) # 构造全1的数组
print(x)
x = torch.rand_like(x, dtype=torch.float) # 生成相同维度的随机矩阵
print(x.size())

y = torch.rand(5, 3) # 构造随机的矩阵
print(x + y)

torch.add(x, y) # 进行矩阵的相加操作

# 索引
print(x[:, 1])

# view操作可以改变矩阵维度

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)

a = torch.ones(5)  # tensor
b = a.numpy()  # 将tensor转换为numpy格式

import numpy as np
a = np.ones([3, 2])
b = torch.from_numpy(a) # 将a转换为tensor格式
print(b)

猜你喜欢

转载自www.cnblogs.com/my-love-is-python/p/12643068.html
今日推荐