Pytorch learning (1) Tensor (tensor)

Construct a 5x3 uninitialized matrix

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

Printout:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])

Construct a 5x3 randomly initialized matrix

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

Printout:
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.]).6698,
[0.8287, 0.])

Construct a 5x3 matrix with all 0s and data type double

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

Printout:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype=torch.float64)

Construct a matrix from data

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

Printout:
tensor([ 0.4000, 30.0000])

Create a tensor based on an existing 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)

Printout:
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]])

Process ended with exit code 0

Get dimension information of tensor

print(x.size())

Printout:
torch.Size([5, 3])

Tensor addition

方法一
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)

Printing all output:
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, 2.9] )

Convert torch Tensor to NumPy array

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

Printout:
tensor([[0.2017, 0.1598, 0.7548],
[0.5265, 0.6292, 0.8907],
[0.7978, 0.9454, 0.9312],
[0.5745, 0.0676, 0.9463], [0.8151, 0.6292, 0.8907], [0.7978, 0.9454, 0.9312], [0.5745, 0.0676, 0.9463], [
0.8151, 0.7]) .
0.7547609 0.6292321 0.89071196]
[0.5747416 0.06755042
0.9462166
]
[0.8150553 0.3961913 0.97154677]]]]]]]]]]]]]

Convert NumPy array to Torch tensor

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

Printout:
[1. 1. 1. 1. 1. 1. 1. 1.]
tensor([1., 1., 1., 1., 1., 1., 1., 1.], dtype =torch.float64)

Referenced at: https://pytorch.org/

Guess you like

Origin blog.csdn.net/weixin_44901043/article/details/123724203