什么是Pytorch?
PyTorch 是一个基于 Python 的科学计算包,主要定位两类人群:
- NumPy 的替代品,可以利用 GPU 的性能进行计算
- 深度学习研究平台拥有足够的灵活性和速度
初步了解
tensor对象
在 TensorFlow 中,数据不是以整数,浮点数或者字符串形式存在的,而是被封装在一个叫做 tensor 的对象中。Tensor是张量的意思,张量包含了0到任意维度的量,其中,0维的叫做常数,1维的叫做向量,二维叫做矩阵,多维度的就直接叫张量。
举例:print(x[: ,1]) 输出结果如下:
tensor([ 0.4477, -0.0048, 1.0878, -0.2174, 1.3609])
常用方法
item():如果有一个元素 tensor ,可使用 .item() 来获得这个 value
x = torch.randn(1)
print(x)
print(x.item())
tensor([ 0.9422])
0.9422121644020081
**view():**view()函数作用是将一个多行的Tensor拼接成一行
举例:
import torch
a = torch.Tensor(2,3)
print(a)
# tensor([[0.0000, 0.0000, 0.0000],
# [0.0000, 0.0000, 0.0000]])
print(a.view(1,-1))
tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]))
pytorch神经网络
相关函数说明
神经网络可以通过 torch.nn 包来构建。
神经网络是基于自动梯度 (autograd)来定义一些模型。一个 nn.Module 包括层和一个方法 forward(input) 它会返回输出(output)。
主要方法解释
nn.conv2d():对由多个输入平面组成的输入信号进行二维卷积
参数理解:
in_channels:
1)输入通道数,对于图片层一般为1(灰度)3(RGB)
2)定义一种输入规则,要求上一层的输出必须和这个输入一致,也可以理解为并发in_channels个channel在上一层
out_channels:
1)直观理解是输出层通道数,
2)换一种理解是kernels(卷积核)/filter个数,其中,每个卷积核会输出局部特征
layer = nn.Conv2d(in_channels=1,out_channels=3,kernel_size=3,stride=1,padding=0)
具体可以参考博文:链接入口
人工神经网络举例
定义了Net类,过程:conv1->max_pool->conv2->fc1->reLU()->fc2->reLU()->fc3
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 5x5 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
输出结果:
Net(
(conv1): Conv2d(1, 6, kernel_size=(