Pytorch学习(一)Tensor(张量)

构造一个5x3未初始化的矩阵

x = torch.empty(5, 3)
print(x)

打印输出:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])

构造一个5x3随机初始化的矩阵

x = torch.empty(5, 3)
print(x)

打印输出:
tensor([[0.1018, 0.3758, 0.2924],
[0.5437, 0.9374, 0.3051],
[0.6789, 0.5647, 0.4796],
[0.9715, 0.2452, 0.9640],
[0.8287, 0.6694, 0.1598]])

构造一个5x3,全为 0,而且数据类型是 double的矩阵

x = torch.zeros(5, 3, dtype=torch.double)
print(x)

打印输出:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype=torch.float64)

使用数据构造矩阵

x = torch.tensor([0.4, 30])

打印输出:
tensor([ 0.4000, 30.0000])

基于已经存在的 tensor创建一个 tensor

x = torch.rand(5, 3)
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
x = torch.randn_like(x, dtype=torch.float)
print(x)

打印输出:
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[-1.7798, -1.5703, -0.4517],
[-2.9491, -0.7512, 0.7352],
[ 0.0362, 0.1316, -0.2731],
[-0.0340, 0.3277, 1.0320],
[-0.3793, -1.4784, 1.7137]])

进程已结束,退出代码为 0

获取tensor的维度信息

print(x.size())

打印输出:
torch.Size([5, 3])

Tensor加法

方法一
y = torch.rand(5, 3)
print(x + y)
print(torch.add(x, y))
方法二
result = torch.empty(5, 3)
方法三
torch.add(x, y, out=result)
print(result)
方法四
y.add_(x)
print(y)

打印都输出:
tensor([[-0.2675, 1.2879, 0.5673],
[ 0.1053, 0.2051, 0.9510],
[-0.5964, 0.3652, 1.7425],
[ 0.0906, -0.0720, 1.8161],
[ 0.5491, 0.9613, 1.1982]])

将torch的Tensor转化为NumPy数组

y = torch.rand(5, 3)
print(y)
x = y.numpy()
print(x)

打印输出:
tensor([[0.2017, 0.1598, 0.7548],
[0.5265, 0.6292, 0.8907],
[0.7978, 0.9454, 0.9312],
[0.5745, 0.0676, 0.9462],
[0.8151, 0.3962, 0.9715]])
[[0.20172328 0.15981966 0.7547609 ]
[0.52654135 0.6292321 0.89071196]
[0.7977553 0.94538176 0.93118775]
[0.57447416 0.06755042 0.9462166 ]
[0.8150553 0.3961913 0.97154677]]

将NumPy数组转化为Torch张量

import numpy as np
x = np.ones(8)
print(x)
y = torch.from_numpy(x)
print(y)

打印输出:
[1. 1. 1. 1. 1. 1. 1. 1.]
tensor([1., 1., 1., 1., 1., 1., 1., 1.], dtype=torch.float64)

参考于:https://pytorch.org/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值