本文主要总结神经网络图文检索部分语义对齐模型的代码,主要用于记录笔者的学习过程,如有不准确之处,欢迎各路大神指出!谢谢!
1.图像分类神经网络
def predict(model, img):
with torch.no_grad():
out = model(img)
_, pre = torch.max(out.data, 1)
return pre.item()
torch.no_grad()一般用于神经网络的推理阶段,表示张量的计算过程中无需计算梯度。
out = model(img)用来进行前向传播。
torch.max的用法如下:
a = torch.randn(1, 3)
>>0.4729 -0.2266 -0.2085
torch.max(a) #也可以写成a.max()
>>0.4729
torch.randn()用于生成随机矩阵。
torch.max用于取随机矩阵中相应维度的最大值,并返回最大值和对应的行(或列)。
例:torch.max(a,0)返回每一列中最大值的那个元素,且返回索引(返回最大元素在这一列的行索引)。返回的最大值和索引各是一个tensor(张量),一起构成元组(Tensor, LongTensor)。
a = torch.randn(3,3)
>>
0.2252 -0.0901 0.5663
-0.4694 0.8073 1.3596
0.1073 -0.7757 -0.8649
torch.max(a,0)
>>
(
0.2252
0.8073
1.3596
[torch.FloatTensor of size 3]
,
0
1
1
[torch.LongTensor of size 3]
torch.max(a,1)返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)
pre.item()的用法如下:
import torch
x = torch.randn(2, 2)
print(x)
print(x[1,1])
print(x[1,1].item())
结果如下:
tensor([[ 0.4702, 0.5145],
[-0.0682, -1.4450]])
tensor(-1.4450)
-1.445029854774475
可以看出,.item的使用使得精度更高。
2.设置神经网络的框架
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(28 * 28, 200)
self.fc2 = nn.Linear(200, 200)
self.fc3 = nn.Linear(200, 10)
nn.Linear()用于设置神经网络中的全连接层。第一层输入28 x 28像素的图像,并连接着200个节点的第一个隐藏层,第一个隐藏层后连接着200个节点的第二个隐藏层,第二个隐藏层和具有10个节点的输出层连接。
3.数据通过网络流动
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return F.log_softmax(x)
将图像x输入到第一个完全连接层self.fc1(x),然后使用F.relu()对该层中的节点应用ReLU激活函数。我们在每一阶段替换x,将它送入下一层。
F.log_softmax()用法如下:
F.softmax()函数的作用是按照行或者列来做归一化,0是对列做归一化,1是对行做归一化
例:F.softmax(x,dim=1) 或者 F.softmax(x,dim=0)。
F.log_softmax是在softmax的结果上再做多一次log运算。
参考文章:
(21条消息) python中.item()的讲解_爱听许嵩歌的博客-CSDN博客_python中item
(21条消息) 详解用PyTorch搭建一个图像分类神经网络_AndyZzz~的博客-CSDN博客