动手学深度学习:softmax完整代码(pytorch + windows+ pycharm)

删去多余的演示部分,解决了图像无法显示的问题

文章目录

  • softmax从零开始实现
  • softmax简洁实现
  • 遇到的问题
    • pycharm无法多进程读取数据导致的报错
    • pycharm绘图不显示/卡顿
    • 无法动态绘制图像
    • PermissionError: [WinError 5] 拒绝访问。: '../data'
    • 图片自动关闭

softmax从零开始实现

import torch
from d2l import torch as d2l
import matplotlib.pyplot as plt
from torchvision import transforms
import torchvision # 计算机视觉相关库
from torch.utils import data
from IPython import display


def get_dataloader_workers():  #@save
    """使用4个进程来读取数据"""
    return 4  # 并行

def load_data_fashion_mnist(batch_size, resize=None):  #@save
    """下载Fashion-MNIST数据集,然后将其加载到内存中"""
    trans = [transforms.ToTensor()]
    if resize:
        trans.insert(0, transforms.Resize(resize))
        #transforms.Resize:调整PILImage对象的尺寸。transforms.Resize([h, w])或transforms.Resize(x)等比例缩放
    trans = transforms.Compose(trans) # 串联多个图片变换的操作
    mnist_train = torchvision.datasets.FashionMNIST(
        root="D:/code/动手学深度学习/pytorch/data", train=True, transform=trans, download=False)
    mnist_test = torchvision.datasets.FashionMNIST(
        root="D:/code/动手学深度学习/pytorch/data", train=False, transform=trans, download=False)
    return (data.DataLoader(mnist_train, batch_size, shuffle=True,
                            num_workers=get_dataloader_workers()),
            data.DataLoader(mnist_test, batch_size, shuffle=False,
                            num_workers=get_dataloader_workers()))


# 定义softmax
def softmax(X):
    X_exp = torch.exp(X)
    return X_exp / X_exp.sum(axis=1, keepdim=True)

def net(X):
    return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)

# 交叉熵损失函数
def cross_entropy(y_hat, y):
    return -torch.log(y_hat[range(len(y_hat)), y])

# 精度
def accuracy(y_hat, y):
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
        y_hat = y_hat.argmax(axis= 1)
    cmp = y_hat == y
    return float(cmp.type(y.dtype).sum())

# 为什么不在accuracy中除以len(y):accuracy函数是一个batch一个batch求的,
# 因为如果样本数不是batch整数倍,
# 最后的batch_size可能与前面不同,所以要求出数量后累计求精度

#
def evaluate_accuracy(net, data_iter):  #@save
    if isinstance(net, torch.nn.Module):
        net.eval()
    metric = Accumulater(2)  # 累加
    with torch.no_grad():
        for X, y in data_iter:
            metric.add(accuracy(net(X), y), y.numel())
    return metric[0]/metric[1]

class Accumulater: #@save
    def __init__(self, n):
        self.data = [0.0] *n

    def add(self, *args):
        self.data = [a + float(b) for a,b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]

# 训练一轮
def train_epoch_ch3(net, train_iter, loss, updater):
    if isinstance(net, torch.nn.Module):
        net.train()
    metric = Accumulater(3)
    for X, y in train_iter:
        y_hat = net(X)
        l = loss(y_hat, y)
        if isinstance(updater, torch.optim.Optimizer):  # 使用torch内置优化器
            updater.zero_grad()
            l.mean().backward()
            updater.step()
        else:
            l.sum().backward()
            updater(X.shape[0])
        metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
    return metric[0]/metric[2], metric[1]/metric[2]

# 绘图
class Animator:  #@save
    """在动画中绘制数据"""
    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
                 ylim=None, xscale='linear', yscale='linear',
                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
                 figsize=(3.5, 2.5)):
        # 增量地绘制多条线
        if legend is None:
            legend = []
        d2l.use_svg_display()
        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes, ]
        # 使用lambda函数捕获参数
        self.config_axes = lambda: d2l.set_axes(
            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
        self.X, self.Y, self.fmts = None, None, fmts

    def add(self, x, y):
        # 向图表中添加多个数据点
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)
        if not hasattr(x, "__len__"):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)]
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        for i, (a, b) in enumerate(zip(x, y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        self.axes[0].cla()
        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()

        display.display(self.fig)
        display.clear_output(wait=True)

        plt.pause(0.001)

# 训练全部
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):
    animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],  # 可视化
                        legend=['train loss', 'train acc', 'test acc'])
    for epoch in range(num_epochs):
        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
        test_acc = evaluate_accuracy(net, test_iter)
        animator.add(epoch + 1, train_metrics + (test_acc,))
    train_loss, train_acc = train_metrics
    assert train_loss < 0.7, train_loss
    assert train_acc <=1 and train_acc > 0.7, train_acc
    assert test_acc <= 1 and test_acc > 0.7, test_acc

def updater(batch_size):
    return d2l.sgd([W, b], lr, batch_size)

# 预测
def predict_ch3(net, test_iter, n = 6):
    for X, y in test_iter:
        break
    trues = d2l.get_fashion_mnist_labels(y)
    preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis= 1))
    titles = [true + '\n' + pred for true, pred in zip(trues, preds)]
    d2l.show_images(X[0:n].reshape((n,28,28)), 1, n, titles = titles[0:n])


if __name__=='__main__':
    # 初始化模型参数
    batch_size = 256
    train_iter, test_iter = load_data_fashion_mnist(batch_size)

    num_inputs = 784
    num_outputs = 10

    W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True)
    b = torch.zeros(num_outputs, requires_grad=True)

    lr = 0.1
    num_epochs = 10
    train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
    plt.show()

    predict_ch3(net, test_iter)
    plt.show()


softmax简洁实现

import torch
from torch import nn
from d2l import torch as d2l
import matplotlib.pyplot as plt
from torchvision import transforms
import torchvision # 计算机视觉相关库
from torch.utils import data

def get_dataloader_workers():  #@save 
    """使用4个进程来读取数据,可以不写"""
    return 4  # 并行

# 重写load_data_fashion_mnist函数,更改读取图片的地址
def load_data_fashion_mnist(batch_size, resize=None):  #@save
    """下载Fashion-MNIST数据集,然后将其加载到内存中"""
    trans = [transforms.ToTensor()]
    if resize:
        trans.insert(0, transforms.Resize(resize))
        #transforms.Resize:调整PILImage对象的尺寸。transforms.Resize([h, w])或transforms.Resize(x)等比例缩放
    trans = transforms.Compose(trans) # 串联多个图片变换的操作
    mnist_train = torchvision.datasets.FashionMNIST(
        root="D:/code/动手学深度学习/pytorch/data", train=True, transform=trans, download=False)
    mnist_test = torchvision.datasets.FashionMNIST(
        root="D:/code/动手学深度学习/pytorch/data", train=False, transform=trans, download=False)
    return (data.DataLoader(mnist_train, batch_size, shuffle=True,
                            num_workers=get_dataloader_workers()),
            data.DataLoader(mnist_test, batch_size, shuffle=False,
                            num_workers=get_dataloader_workers()))


if __name__=='__main__':
    batch_size = 256
    train_iter, test_iter = load_data_fashion_mnist(batch_size)

    # 初始化模型参数
    net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))  # 线性层之前使用展平层调整输入的形状

    def init_weights(m):
        if type(m) == nn.Linear:
            nn.init.normal_(m.weight, std=0.1)
    net.apply(init_weights)

    # 损失
    loss = nn.CrossEntropyLoss(reduction='none')

    # 优化算法
    trainer = torch.optim.SGD(net.parameters(), lr=0.1)

    # 训练
    num_epoch = 10
    d2l.train_ch3(net, train_iter, test_iter, loss, num_epoch, trainer)
    plt.show()

    # 预测
    d2l.predict_ch3(net, test_iter)
    plt.show()


遇到的问题

pycharm无法多进程读取数据导致的报错

问题描述:报错:
动手学深度学习:softmax完整代码(pytorch + windows+ pycharm)_第1张图片
解决方法(三选一):

  1. 使用cmd / Anaconda Prompt运行python文件
  2. 将进程数更改为0
def get_dataloader_workers(): 
    return 0
  1. 将需要运行的内容放入if __name__=='__main__':(除定义函数/类之外的内容)

pycharm绘图不显示/卡顿

问题描述:使用pycharm画图时弹出的图片窗口显示未响应,或报错

error: failed to send plot to http://127.0.0.1:63342

动手学深度学习:softmax完整代码(pytorch + windows+ pycharm)_第2张图片

解决方法

  1. 解决failed to send plot to http://127.0.0.1:63342
    设置 => Python Scientific => 取消勾选在工具窗口中显示绘图
  2. [解决未响应]
    编辑配置 => 取消勾选使用python控制台运行

无法动态绘制图像

问题描述:无法像jupyter中一样每运行一个epoch显示一段新的图像
解决方法
重写Animato中的add函数,在最后加入plt.pause(0.001),或直接在d2l.torch中更改该函数

PermissionError: [WinError 5] 拒绝访问。: ‘…/data’

问题描述:文件地址问题
动手学深度学习:softmax完整代码(pytorch + windows+ pycharm)_第3张图片
解决方法:重写load_data_fashion_mnist函数或直接在d2l.torch中更改该函数,改为保存数据的绝对地址

图片自动关闭

在运行训练函数和预测函数后分别加

plt.show()

你可能感兴趣的:(动手学深度学习,深度学习,python,pytorch,pycharm)