[Pytorch] study notes (a)

pytorch entry

What is pytorch

PyTorch is a Python-based scientific computing package, mainly located in two populations:

  • NumPy alternatives may be calculated using the performance of the GPU.
  • Depth study and research platform has enough flexibility and speed

Tensor

Tensors similar NumPy of ndarrays, while Tensors can be calculated using the GPU.

Tensor structure

Structure matrix of zeros

1. Import

from __future__ import  print_function
import torch

2. a 5x3 matrix configuration, does not initialize.

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

3. Output

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

Random initialization matrix structure

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

Configuration specified type of matrix

A matrix configuration are all 0, and the data type is long.

Construct a matrix filled zeros and of dtype long:

from __future__ import  print_function
import torch

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

Using the data to create a tensor

x=torch.tensor([5.5,3])
print(x)
tensor([5.5000, 3.0000])

According to the existing to create tensor tensor

x=torch.tensor([5.5,3])
print(x)
x=x.new_ones(5,3,dtype=torch.double)
print(x)
# 覆盖类型
x=torch.rand_like(x,dtype=torch.float)

# 结果具有相同的大小
print(x)

#输出自己的维度
print(x.size())

result

tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
tensor([[0.6122, 0.4650, 0.7017],
        [0.6148, 0.9167, 0.0879],
        [0.2891, 0.5855, 0.1947],
        [0.3554, 0.2678, 0.5296],
        [0.6527, 0.9537, 0.3847]])
torch.Size([5, 3])

Tensor operations

Tensor addition

method one

y=torch.rand(5,3);
print(x+y)
tensor([[0.7509, 1.1579, 0.1261],
        [0.6551, 1.0985, 0.4284],
        [1.4595, 0.9757, 1.2582],
        [1.0690, 0.7405, 1.7367],
        [0.6201, 1.3876, 0.8193]])

Second way

print(torch.add(x,y))
tensor([[0.8122, 1.0697, 0.8380],
        [1.4668, 0.2371, 1.0734],
        [0.9489, 1.3252, 1.2579],
        [0.7728, 1.4361, 1.5713],
        [0.7098, 0.9440, 0.4296]])

Three ways

print(y.add_(x))

note

注意 任何使张量会发生变化的操作都有一个前缀 '_'。例如:
x.copy_(y)
, 
x.t_()
, 将会改变 
x

Index Operations

print(x[:,1])
tensor([0.1733, 0.5943, 0.9015, 0.1385, 0.2001])

Resize

import torch

x=torch.rand(4,4)
y=x.view(16)
z=x.view(-1,8)#-1是不用填从其他的维度推测的
print(x.size(),y.size(),z.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

Get the value

import torch
x=torch.rand(1)
print(x)
print(x.item())
tensor([0.5210])
0.5209894180297852

Guess you like

Origin www.cnblogs.com/mengxiaoleng/p/11772812.html