Introduction
学习使用了深度学习Pytorch差不多一年半多了,今天在这里呢,来总结一些不怎么使用的细节方面的代码知识点,为以后方便查找和使用。
1、Pytorch模型调用相关函数
加载模型使用:
model=cnn() #cnn()这里表示为你定义的神经网络模型
model.eval() #这里表示为测试使用
model.load_state_dict(torch.load(param_file)) # load模型
若当你的模型或者你调用他人的模型为在gpu上训练的,但你想cpu上载入时:
model.load_state_dict(t.load(params_file, map_location='cpu'))
2.Pytorch模型测试与单一数据使用
当你需要单独地一个数据来测试时,你可以使用下面的代码:
img0 = Image.open(img0_tuple[0])
img0 = img0.convert("L")
img0 = transform(img0) #这里需要跟你训练数据中的transform一样
img0= Variable(img0.unsqueeze(0)) #添加维度(eg:3->4)
output1 = model(Variable(img0) #Vaariable可求导变量
在这里,我需要强调以下为什么要添加维度,首先我们要知道由于在训练时,我们喂给神经网络的数据格式时这样的:(batch_size,in_channel,height,width),因此呢,我们单一加载一个数据时,也需要满足四个维度。
3、训练结果数据可视化
#首先定义两组数组
loss_history= [] #用来保存训练过程中的loss值
Accuracy_history= [] #用来保存训练时的准确率值
epoch_number = 0
loss_history.append(loss_contrastive.item())
Accuracy_history.append((accuray.item())
epoch_number += 1
#这里保存的数据值为每一次epoch时保存一次.
#注意:当结束完训练时,跳出训练循环时
show_plot(epoch_number,loss_history,Accuracy_history)
#show_plot为自己定义的函数
其中show_plot函数定义如下:
def show_plot(iteration, loss,Accuracy_history):
plt.plot(iteration, loss,color='red',abel="loss_history")
plt.plot(iteration,Accuracy_history,abel="Accuracy_history")
plt.ylabel('loss')
plt.xlabel('Number of training')
plt.show()
当然了,你要是想用上位机界面显示效果的话,可以采用PyQT,这里你可以参考我的另一篇博客
4、一些数据转换
numpy中的ndarray转化成pytorch中的tensor : torch.from_numpy()
pytorch中的tensor转化成numpy中的ndarray : numpy()
例如:
将Variable张量转化为numpy:
V_data = V_data.data.numpy()
import numpy as np
import torch
np_arr = np.array([1,2,3,4])
tensor_=torch.from_numpy(np_arr)
ten_numpy=tensor_.numpy()
这里需要注意的是,你定义的numpy数组或者tensor使用了Variable时,想要转换为tensor或者numpy时,例如:
#mydata为Variable(tensor)类型时,转换为numpy
mydata=mydata.data.numpy()
续
有待补充。。。。