Softmax回归的从零实现

为什么会断言train_loss小于0.5呢

我也出现了这个问题,解决的方式有点莫名其妙,不过如下:
1.插入了这一行,之前运行的时候没有加


2.修改了这里的括号,一定要数清楚这里的括号,象征的意思太多了。

然后我就run出来了,希望有帮助!另外我把b换成了inputs的跑了一遍,额,然后就出来了


这个bug不知道怎么解决,从上到下梳理了一下逻辑,但是没什么问题,而且预测可以输出结果就很迷,希望有大佬可以指点一下迷津,辛苦了 :smiling_face_with_three_hearts:

是不是数据集因为网络问题没有成功下载, :grinning: :grinning: :grinning: :grinning: :grinning:

因为你的train_loss损失大于0.5,所以就停止运行了。根据报错来看,你的train_loss应该是0.786,你把边界值大概改小一点即可

让训练过程在后台线程运行,图形显示在前台主线程中(GUI不能在后台线程),通过后台线程调用API(plt.draw())更新前台打开的绘图窗口。以下是修改代码示意:

import threading

class Animator:  #@save
    def add(self, x, y):
        '''...内容省略...'''
        if 'display' in globals():  # 非Notebook环境不调用display()
            # display:ipython = globals()['display']
            display.display(self.fig)
            display.clear_output(wait=True)

def train(net, train_iter, test_iter, loss, num_epochs, updater):  #@save
    # animator = Animator(...)
    def train_thread():
        for epoch in range(num_epochs):
            '''...原有的训练过程代码...'''
            if 'display' not in globals():
                print('epoch {0}: train loss {1}, train accuracy {2}, test accuracy {3}.'.format(
                    epoch, train_metrics[0], train_metrics[1], test_acc
                ))   # 控制台输出
                d2l.plt.draw()   # 更新绘图
        train_loss, train_acc = train_metrics
        '''...原有的训练过程代码...'''
    if 'display' not in globals():
        th = threading.Thread(target=train_thread, name='training')
        th.start()
        d2l.plt.show(block=True)   # 显示绘图
        th.join() 
2 Likes

感谢!
我也是遇到了这个问题,找不到解决方法,翻了好久评论终于在你这找到了答案!
我也挺好奇为什么其他的同学没有遇到类似的问题 :joy:

Run with Jupyter notebook or add “d2l.plt.show()”

2 Likes


这里执行第二段代码报
UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors. This means you can write to the underlying (supposedly non-writeable) NumPy array using the tensor. You may want to copy the array to protect its data or make it writeable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at .[./learn_/Dive_into_deep_learning/d2l-zh/pytorch/chapter_linear-networks/torch/csrc/utils/tensor_numpy.cpp:180).)
这个错,不过好像不影响运行其他代码,有什么办法修复吗?

cross_entropy只是计算loss,真更新还是靠updater,相当于前面章节的train方法,updater里面就是一个sgd,最后训练好的模型的参数就是W和b了。

def cross_entropy(y_hat, y):
return - torch.log(y_hat[range(len(y_hat)), y])

cross_entropy(y_hat, y)

这里的交叉熵损失函数定义为什么没有y_hat本身与LOG相乘?就是直接使用LOG函数了。

我发现这里每个epoch只训练了一个batchsize的数据,对吗?这好像我以前对于“每个epoch要遍历全体数据集一遍”的认知,并且下载的fashion-mnist数据都是一些无法打开的文件,它们是怎么被读入的?

每个epoch只训练了一个batchsize的数据

不是的,你看Dataloader部分的定义

fashion-mnist数据都是一些无法打开的文件

从名称看应该都是字节数据,直接读取的byte

已经把dataloader里面的num_workers设置成0了,但是还是报错,如何解决?

这个if的两个选择是选择训练的时候使用内置还是自定义的优化器,都是在训练阶段;只有在验证或测试阶段需要with torch.no_grad()

问题5 不就是 word2vec 训练过程遇到的问题么,word2vec 采用了两种训练优化方法:Hierarchical softmax 和 Negative Sampling

Accumulator这个类的add函数设计不好,非常2容易让人产生歧义,metric.add(1,2);让人以为是1和2相加,而实际上是self.data[0] = self.data[0] +1;self.data[1] = self.data[1] +1

应该是内置的loss_function 求的的是均值loss, 这里虽然optim使用的是内置的,但是求l所用的损失函数是自定义的,函数结果没有除以batch,所以先对l求均值

可能现在回复你已经过时了,不过 按我的理解,sum和mean其实主要影响了“梯度的大小”,反向传播时,依据损失求梯度,如果是sum,则梯度会比mean大n倍,那么在学习率不变的情况下,步子会迈得很长,体现到图形上就是正确率提升不了。所以需要缩小学习率。

如有不对还望指正。

    if isinstance(updater, torch.optim.Optimizer):
        # 使用PyTorch内置的优化器和损失函数
        updater.zero_grad()
        l.mean().backward()
        updater.step()
    else:
        # 使用定制的优化器和损失函数
        l.sum().backward()
        updater(X.shape[0])

请问下为什么使用定制的优化器的时候,就不需要清零梯度呢?