提交 13159bef 编写于 作者: A Aston Zhang

fix code in cnn and cv

上级 4f2fb5ef
......@@ -20,7 +20,7 @@
* `linreg`[线性回归的从零开始实现](../chapter_deep-learning-basics/linear-regression-scratch.md)
* `load_data_fashion_mnist`
* `load_data_fashion_mnist`[“深度卷积神经网络(AlexNet)”](../chapter_convolutional-neural-networks/alexnet.md)
* `load_data_pascal_voc`
......
......@@ -115,7 +115,7 @@ finetune_net.output.initialize(init.Xavier())
我们先定义一个可以重复使用的训练函数。
```{.python .input n=12}
def train(net, learning_rate, batch_size=128, epochs=5):
def train_fine_tuning(net, learning_rate, batch_size=128, epochs=5):
train_iter = gdata.DataLoader(
train_imgs.transform_first(train_augs), batch_size, shuffle=True)
test_iter = gdata.DataLoader(
......@@ -133,7 +133,7 @@ def train(net, learning_rate, batch_size=128, epochs=5):
因为微调的网络中的主要层的已经训练的足够好,所以一般采用比较小的学习率,防止过大的步长对训练好的层产生过多影响。
```{.python .input n=13}
train(finetune_net, 0.01)
train_fine_tuning(finetune_net, 0.01)
```
作为对比,我们训练一个同样的模型,但将所有参数都初始化为随机值。我们使用较大的学习率来加速收敛。
......@@ -141,7 +141,7 @@ train(finetune_net, 0.01)
```{.python .input n=14}
scratch_net = model_zoo.vision.resnet18_v2(classes=2)
scratch_net.initialize(init=init.Xavier())
train(scratch_net, 0.1)
train_fine_tuning(scratch_net, 0.1)
```
可以看到,微调的模型因为初始值更好,收敛速度比从头开始训练要快很多。在很多情况下,微调的模型最终的收敛到的结果也可能比非微调的模型更好。
......
......@@ -86,8 +86,7 @@ apply(img, augs)
接下来我们来看一个将图片增广应用在实际训练中的例子,并比较其与不使用时的区别。这里我们使用CIFAR-10数据集,而不是之前我们一直使用的FashionMNIST。原因在于FashionMNIST中物体位置和尺寸都已经归一化了,而CIFAR-10中物体颜色和大小区别更加显著。下面我们展示CIFAR-10中的前32张训练图片。
```{.python .input n=10}
gb.show_images(gluon.data.vision.CIFAR10(train=True)[0:32][0], 4, 8,
scale=0.8);
gb.show_images(gdata.vision.CIFAR10(train=True)[0:32][0], 4, 8, scale=0.8);
```
我们通常将图片增广用在训练样本上,但是在预测的时候并不使用随机增广。这里我们仅仅使用最简单的随机水平翻转。此外,我们使用`ToTensor`变换来将图片转成MXNet需要的格式,即格式为(批量,通道,高,宽)以及类型为32位浮点数。
......@@ -107,8 +106,8 @@ test_augs = gdata.vision.transforms.Compose([
```{.python .input n=12}
def load_cifar10(is_train, augs, batch_size):
return gluon.data.DataLoader(gluon.data.vision.CIFAR10(
train=is_train).transform_first(augs),
return gdata.DataLoader(
gdata.vision.CIFAR10(train=is_train).transform_first(augs),
batch_size=batch_size, shuffle=is_train, num_workers=2)
```
......
......@@ -50,12 +50,13 @@ AlextNet与LeNet的设计理念非常相似。但也有非常显著的区别。
下面我们实现(稍微简化过的)Alexnet:
```{.python .input}
```{.python .input n=1}
import sys
sys.path.append('..')
import gluonbook as gb
from mxnet import nd, init, gluon
from mxnet.gluon import data as gdata, loss as gloss, nn
import os
net = nn.Sequential()
net.add(
......@@ -82,7 +83,7 @@ net.add(
我们构造一个高和宽均为224像素的单通道数据点来观察每一层的输出大小。
```{.python .input}
```{.python .input n=2}
X = nd.random.uniform(shape=(1, 1, 224, 224))
net.initialize()
for layer in net:
......@@ -90,34 +91,48 @@ for layer in net:
print(layer.name, 'output shape:\t', X.shape)
```
## 读取数据
虽然论文中Alexnet使用Imagenet数据,但因为Imagenet数据训练时间较长,我们仍用前面的FashionMNIST来演示。读取数据的时候我们额外做了一步将图片高宽扩大到原版Alexnet使用的224,这个可以通过Resize来实现。即我们在ToTenor前使用Resize,然后使用Compose来将这两个变化合并成一个来方便调用。
```{.python .input}
transformer = gdata.vision.transforms.Compose(
[gdata.vision.transforms.Resize(224),
gdata.vision.transforms.ToTensor()])
```{.json .output n=2}
[
{
"name": "stdout",
"output_type": "stream",
"text": "conv0 output shape:\t (1, 96, 54, 54)\npool0 output shape:\t (1, 96, 26, 26)\nconv1 output shape:\t (1, 256, 26, 26)\npool1 output shape:\t (1, 256, 12, 12)\nconv2 output shape:\t (1, 384, 12, 12)\nconv3 output shape:\t (1, 384, 12, 12)\nconv4 output shape:\t (1, 256, 12, 12)\npool2 output shape:\t (1, 256, 5, 5)\ndense0 output shape:\t (1, 4096)\ndropout0 output shape:\t (1, 4096)\ndense1 output shape:\t (1, 4096)\ndropout1 output shape:\t (1, 4096)\ndense2 output shape:\t (1, 10)\n"
}
]
```
数据读取的其他部分跟前面一致。
```{.python .input}
batch_size = 128
## 读取数据
mnist_train = gdata.vision.FashionMNIST(train=True)
mnist_test = gdata.vision.FashionMNIST(train=False)
train_iter = gdata.DataLoader(mnist_train.transform_first(transformer),
batch_size, shuffle=True, num_workers=4)
test_iter = gdata.DataLoader(mnist_test.transform_first(transformer),
batch_size, shuffle=False, num_workers=4)
虽然论文中Alexnet使用Imagenet数据,但因为Imagenet数据训练时间较长,我们仍用前面的Fashion-MNIST来演示。读取数据的时候我们额外做了一步将图片高宽扩大到原版Alexnet使用的224,这个可以通过`Resize`来实现。即我们在`ToTenor`前使用`Resize`,然后使用`Compose`来将这两个变化合并成一个来方便调用。数据读取的其他部分跟前面一致。
```{.python .input n=3}
def load_data_fashion_mnist(batch_size, resize=None,
root=os.path.join('~', '.mxnet', 'datasets',
'fashion-mnist')):
root = os.path.expanduser(root) # 展开用户路径 '~'。
transformer = []
if resize:
transformer += [gdata.vision.transforms.Resize(resize)]
transformer += [gdata.vision.transforms.ToTensor()]
transformer = gdata.vision.transforms.Compose(transformer)
mnist_train = gdata.vision.FashionMNIST(root=root, train=True)
mnist_test = gdata.vision.FashionMNIST(root=root, train=False)
train_iter = gdata.DataLoader(mnist_train.transform_first(transformer),
batch_size, shuffle=True, num_workers=4)
test_iter = gdata.DataLoader(mnist_test.transform_first(transformer),
batch_size, shuffle=False, num_workers=4)
return train_iter, test_iter
train_iter, test_iter = load_data_fashion_mnist(batch_size=128, resize=224)
```
我们将`load_data_fashion_mnist`函数定义在`gluonbook`包中供后面章节调用。
## 训练
这时候我们可以开始训练。相对于上节的LeNet,这里的主要改动是使用了更小的学习率。
```{.python .input}
```{.python .input n=5}
lr = 0.01
ctx = gb.try_gpu()
net.initialize(force_reinit=True, ctx=ctx, init=init.Xavier())
......@@ -126,6 +141,16 @@ loss = gloss.SoftmaxCrossEntropyLoss()
gb.train(train_iter, test_iter, net, loss, trainer, ctx, num_epochs=5)
```
```{.json .output n=5}
[
{
"name": "stdout",
"output_type": "stream",
"text": "training on gpu(0)\nepoch 1, loss 1.2884, train acc 0.515, test acc 0.760, time 20.3 sec\nepoch 2, loss 0.6309, train acc 0.763, test acc 0.805, time 18.7 sec\nepoch 3, loss 0.5170, train acc 0.808, test acc 0.844, time 18.7 sec\nepoch 4, loss 0.4537, train acc 0.832, test acc 0.858, time 19.2 sec\nepoch 5, loss 0.4146, train acc 0.848, test acc 0.867, time 18.8 sec\n"
}
]
```
## 小结
AlexNet跟LeNet结构类似,但使用了更多的卷积层和更大的参数空间来拟合大规模数据集ImageNet。它是浅层神经网络和深度神经网络的分界线。虽然看上去AlexNet的实现比LeNet也就就多了几行而已。但这个观念上的转变和真正优秀实验结果的产生,学术界整整花了20年。
......
......@@ -85,7 +85,7 @@ test_iter = gdata.DataLoader(mnist_test.transform_first(transformer),
batch_size, shuffle=False, num_workers=4)
```
我们将获取并读取Fashion-MNIST数据集的逻辑封装在`gluonbook.load_data_fashion_mnist`函数中供后面章节调用。
我们将获取并读取Fashion-MNIST数据集的逻辑封装在`gluonbook.load_data_fashion_mnist`函数中供后面章节调用。随着本书内容的不断深入,我们会进一步改进该函数。它的完整实现将在[“深度卷积神经网络(AlexNet)”](../chapter_convolutional-neural-networks/alexnet.md)一节中描述。
## 初始化模型参数
......
# 训练词嵌入模型
#TODO(@astonzhang) Need edit.
我们在[“词向量:word2vec”](./word2vec.md)introduced the word2vec word embedding model. In this notebook we will show how to train a word2vec model with Gluon. We will introduce training the model with the skip-gram objective and negative sampling. Besides mxnet Gluon we will only use standard Python language features but note that specific toolkits for Natural Language Processing, such as the Gluon-NLP toolkit exist.
首先导入实验所需的包或模块,并抽取数据集。
......
......@@ -378,8 +378,6 @@ def train(train_iter, test_iter, net, loss, trainer, ctx, num_epochs,
ctx = [ctx]
for epoch in range(1, num_epochs + 1):
train_l_sum, train_acc_sum, n, m = 0.0, 0.0, 0.0, 0.0
if isinstance(train_iter, mx.io.MXDataIter):
train_iter.reset()
start = time()
for i, batch in enumerate(train_iter):
Xs, ys, batch_size = _get_batch(batch, ctx)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册