python pytorch_Python:PyTorch 保存和加载训练过的网络 (八十)

保存和加载模型

在这个 notebook 中,我将为你展示如何使用 Pytorch 来保存和加载模型。这个步骤十分重要,因为你一定希望能够加载预先训练好的模型来进行预测,或是根据新数据继续训练。

%matplotlib inline

%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt

import torch

from torch import nn

from torch import optim

import torch.nn.functional as F

from torch.autograd import Variable

from torchvision import datasets, transforms

import helper

# Define a transform to normalize the data

transform = transforms.Compose([transforms.ToTensor(),

transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

# Download and load the training data

trainset = datasets.FashionMNIST('F_MNIST_data/', download=True, train=True, transform=transform)

trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

# Download and load the test data

testset = datasets.FashionMNIST('F_MNIST_data/', download=True, train=False, transform=transform)

testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)

在这里我们可以看见一张图片。

image, label = next(iter(trainloader))

helper.imshow(image[0,:]);

构建网络

在这里,我将使用与第五部分中一样的模型。

class Network(nn.Module):

def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):

''' Builds a feedforward network with arbitrary hidden layers.

Arguments

---------

input_size: integer, size of the input layer

output_size: integer, size of the output layer

hidden_layers: list of integers, the sizes of the hidden layers

'''

super().__init__()

# Input to a hidden layer

self.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])])

# Add a variable number of more hidden layers

layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:])

self.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])

self.output = nn.Linear(hidden_layers[-1], output_size)

self.dropout = nn.Dropout(p=drop_p)

def forward(self, x):

''' Forward pass through the network, returns the output logits '''

for each in self.hidden_layers:

x = F.relu(each(x))

x = self.dropout(x)

x = self.output(x)

return F.log_softmax(x, dim=1)

训练网络

并使用之前一样的方法来训练网络。

# Create the network, define the criterion and optimizer

model = Network(784, 10, [500, 100])

criterion = nn.NLLLoss()

optimizer &

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值