使用Pytorch对模型进行训练以及使用保存好的模型进行预测

本文是针对使用Pytorch的新手对如何使用Pytorch进行网络的训练以及使用的简单的教程

其中,对于Pytorch的安装等方式就不讲了,默认大家都安装好了,但是实在是不知道的话直接通过conda或者pip安装torch也是可行的。但是直接通过官网下我觉得是最好的方法(官网上有下载最新版的命令)

需要注意的是,这里附上的代码只是一个示意,没有完整的定义和测试,只是告诉你具体的使用的方法和思路,你直接copy下来应该是运行不了的!

使用Pytorch进行模型的训练

首先,在使用pytorch进行训练之前需要有网络,那么首先需要对网络进行定义,使用简单的网络进行举例:

class SelfModel(nn.Module):
	def __init__(self, input_size, hidden_size, output_size, batch_size, is_cuda)super(SelfModel,self).__init__()
	#在初始化的时候将各层定义好
		self.input_layer = torch.Tensor(batch_size, input_size)
		self.hidden_layer = torch.Tensor(batch_size, hidden_size)
		self.output_layer = torch.Tensor(batch_size, output_size)
		
		self.input_to_hidden = nn.Linear(input_size, hidden_size)
		self.hidden_to_output = nn.Linear(hidden_size, output_size)
		#这里使用线性映射,表示各个层之间的传递,可以认为这里存储的是各个层之间映射的权重
		if is_cuda: #如果你有显卡加速的话,需要将各个向量转为cuda向量
			self.input_layer.cuda()
			self.hidden_layer.cuda()
			self.output_layer.cuda()
			self.input_to_hidden.cuda()
			self.hidden_to_output.cuda()
	# 对于input_size,hidden_size,output_size可认为是每一层神经元的数量
	def forward(self, input_data):
		#forward属于是pytorch的一个内置的前导函数,可以认为是网络前导的入口
		input_layer = input_data
		hidden_layer = self.input_to_hidden(input_data)
		out_layer = self.hidden_tu_output(hidden_layer)
		#这个就是从输入到输出的传递过程

对模型进行训练:
假设预先已经对模型进行定义为model

optimizer = optim.Adam(params=model.parameters(), lr=lr, weight_decay=1e-5)
criterion = nn.MSELoss() #定义损失函数
# 使用优化器来更新网络权重,lr为学习率,
for i in range(epoch): #设定训练epoch次
	model.train() #将模型的状态设置为train
	for j in Sample: #对每一个样本进行遍历
		optimizer = zero_grad() #将梯度清理,为这次的梯度计算做准备
		output = model(j)
		loss = criterion(output, target)
		loss.backward()
		optimizer.step() #更新网络权重		

Pytorch 模型保存

#对于pytorch中网络模型的保存挺简单的:
save_checkpoint({'epoch': i, 'state_dict': model.state_dict()},directory)
def save_checkpoint(state, directory): #state是模型的权重和状态
	if not os.path.exists(directory):
		os.makedirs(directory)
	fileName = directory + 'last.pth'
	torch.save(state,fileName)#使用torch.save函数直接对训练好的模型进行保存

至此网络的保存就基本完成了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值