Pytorch基础语法学习

12月30日学习记录

 

学习了Pytorch的基本语法,包含以下几个

import torch as t
import numpy as np

t.size()

t.shape()

t.numel()

a = t.arange(0,6)

b = t.eye()

c = t.view()

a = t.squeeze()

b = t.unsqueeze()

c = t.resize_(1,3)

学这个基础理论感觉还是比较无聊的,觉得还是通过具体的项目来学习是比较有效的。

 

我在本地配置了Pytorch,网页上使用jupyter notebook,在使用之前需要进行一些环境的搭建,我配置的虚拟环境名称是pytorch,搭配的Anaconda,激活虚拟环境后,输入命令如下:

pip install ipykernel

python -m ipykernel install --user --name=pytorch

运行第一行比较耗费时间,你需要做的就是安静等待。等环境配置完成后在命令行直接输入jupyter notebook,就可以直接在网页上运行python代码了。

 

Pytorch基础语法学习_第1张图片

 

关于Sequeeze的解释,直接贴一段代码,要注意的就是看清楚输入和输出。

import torch

x = torch.zeros(3, 2, 4, 1, 2, 1)  # dimension of 3*2*4*1*2
print(x.size())  # torch.Size([3, 2, 4, 1, 2, 1])
print(x.shape)
# print(x)

y = torch.squeeze(x)  # Returns a tensor with all the dimensions of input of size 1 removed.
print(y.size())  # torch.Size([3, 2, 4, 2])
print(y.shape)

z = torch.unsqueeze(y, dim=0)  # Add a dimension of 1 in the 0th position
print(z.size())  # torch.Size([1, 3, 2, 4, 2])
print(z.shape)

z = torch.unsqueeze(y, dim=1)  # Add a dimension of 1 in the 1st position
print(z.size())  # torch.Size([3, 1, 2, 4, 2])
print(z.shape)

z = torch.unsqueeze(y, dim=2)  # Add a dimension of 1 in the 2nd position
print(z.size())  # torch.Size([3, 2, 1, 4, 2])
print(z.shape)

y = torch.squeeze(x, dim=0)  # remove the 0th position of 1 (no 1)
print('dim=0', y.size())  # torch.Size([3, 2, 4, 1, 2, 1])
print('dim=0', y.shape)

y = torch.squeeze(x, dim=1)  # remove the 1st position of 1 (no 1)
print('dim=1', y.size())  # torch.Size([3, 2, 4, 1, 2, 1])
print('dim=1', y.shape)

y = torch.squeeze(x, dim=2)  # remove the 2nd position of 1 (no 1)
print('dim=2', y.size())  # torch.Size([3, 2, 4, 1, 2])
print('dim=2', y.shape)

y = torch.squeeze(x, dim=3)  # remove the 3rd position of 1 (yes)
print('dim=3', y.size())  # torch.Size([3, 2, 4, 2])
print('dim=3', y.shape)

y = torch.squeeze(x, dim=4)  # remove the 4th position of 1 (no 1)
print('dim=4', y.size())  # torch.Size([3, 2, 4, 1, 2, 1])
print('dim=4', y.shape)

y = torch.squeeze(x, dim=5)  # remove the 5th position of 1 (yes)
print('dim=5', y.size())  # torch.Size([3, 2, 4, 1, 2])
print('dim=5', y.shape)

y = torch.squeeze(x, dim=6)  # RuntimeError: Dimension out of range (expected to be in range of [-6, 5], but got 6)
print('dim=6', y.size())
print('dim=6', y.shape)

 

你可能感兴趣的:(个人学习,pytorch)