Skip to content

Commit 840682c

Browse files
committed
2 parents 31c6bdf + 93e469f commit 840682c

File tree

3 files changed

+209
-2
lines changed

3 files changed

+209
-2
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@ dive into deep learning tensorflow 2.0 implementation
44
Dive into Deep Learning is a fantastic book and the code in there is based on MXnet.
55
In this repo we're trying to rewrite all the code in the book on tensorflow 2.0.
66

7-
learn tf2.0 with Tricky
7+
learn tf2.0 with Tricky and Archersama !
88

99
本项目将[《动手学深度学习》](http://zh.d2l.ai/) 原书中MXNet代码实现改为tensorflow2.0实现。原书作者:阿斯顿·张、李沐、扎卡里 C. 立顿、亚历山大 J. 斯莫拉以及其他社区贡献者,GitHub地址:https://github.com/d2l-ai/d2l-zh
1010

1111
## 简介
12+
### 目前处于代码编写状态,未包含文本,请参照原书阅读本项目对应代码
1213
本仓库主要包含每章相关jupyter notebook代码(基于tensorflow2.0);欢迎对本项目做出贡献或提出issue。
1314

1415
## 面向人群
1516
本项目面向对深度学习感兴趣,尤其是使用tensorflow。本项目并不要求你有任何深度学习或者机器学习的背景知识,你只需了解基础的数学和编程,如基础的线性代数、微分和概率,以及基础的Python编程。
1617

1718
## 目录
18-
### [1. 深度学习简介]
19+
### 1. 深度学习简介
1920
### 2. 预备知识
2021
[2.1 环境配置]
2122
[2.2 数据操作]
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
#%% md
2+
3+
3.5. 图像分类数据集(Fashion-MNIST)¶
4+
在介绍softmax回归的实现前我们先引入一个多类图像分类数据集。它将在后面的章节中被多次使用,以方便我们观察比较算法之间在模型精度和计算效率上的区别。图像分类数据集中最常用的是手写数字识别数据集MNIST [1]。但大部分模型在MNIST上的分类精度都超过了95%。为了更直观地观察算法之间的差异,我们将使用一个图像内容更加复杂的数据集Fashion-MNIST [2]。
5+
6+
#%% md
7+
8+
3.5.1. 获取数据集
9+
首先导入本节需要的包或模块。
10+
11+
#%%
12+
13+
import tensorflow as tf
14+
from tensorflow import keras
15+
import numpy as np
16+
import time
17+
import matplotlib.pyplot as plt
18+
import d2lzh as d2l
19+
20+
#%% md
21+
22+
下面,我们通过keras的dataset包来下载这个数据集。第一次调用时会自动从网上获取数据。我们通过参数train来指定获取训练数据集或测试数据集(testing data set)。测试数据集也叫测试集(testing set),只用来评价模型的表现,并不用来训练模型。
23+
24+
#%%
25+
26+
from tensorflow.keras.datasets import fashion_mnist
27+
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
28+
29+
#%% md
30+
31+
训练集中和测试集中的每个类别的图像数分别为6,000和1,000。因为有10个类别,所以训练集和测试集的样本数分别为60,000和10,000。
32+
33+
#%%
34+
35+
len(x_train),len(x_test)
36+
37+
#%% md
38+
39+
我们可以通过方括号[]来访问任意一个样本,下面获取第一个样本的图像和标签。
40+
41+
#%%
42+
43+
feature,label=x_train[0],y_train[0]
44+
45+
#%% md
46+
47+
变量feature对应高和宽均为28像素的图像。每个像素的数值为0到255之间8位无符号整数(uint8)。它使用三维的NDArray存储。其中的最后一维是通道数。因为数据集中是灰度图像,所以通道数为1。为了表述简洁,我们将高和宽分别为 h 和 w 像素的图像的形状记为 h×w 或(h,w)。
48+
49+
#%%
50+
51+
feature.shape, feature.dtype
52+
53+
#%% md
54+
55+
图像的标签使用NumPy的标量表示。它的类型为32位整数(int32)。
56+
57+
#%%
58+
59+
label, type(label), label.dtype
60+
61+
#%% md
62+
63+
Fashion-MNIST中一共包括了10个类别,分别为t-shirt(T恤)、trouser(裤子)、pullover(套衫)、dress(连衣裙)、coat(外套)、sandal(凉鞋)、shirt(衬衫)、sneaker(运动鞋)、bag(包)和ankle boot(短靴)。以下函数可以将数值标签转成相应的文本标签。
64+
65+
#%%
66+
67+
68+
# 本函数已保存在d2lzh包中方便以后使用
69+
def get_fashion_mnist_labels(labels):
70+
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
71+
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
72+
return [text_labels[int(i)] for i in labels]
73+
74+
#%% md
75+
76+
下面定义一个可以在一行里画出多张图像和对应标签的函数。
77+
78+
#%%
79+
80+
def show_fashion_mnist(images, labels):
81+
_, figs = plt.subplots(1, len(images), figsize=(12, 12))
82+
for f, img, lbl in zip(figs, images, labels):
83+
f.imshow(img.reshape((28, 28)))
84+
f.set_title(lbl)
85+
f.axes.get_xaxis().set_visible(False)
86+
f.axes.get_yaxis().set_visible(False)
87+
plt.show()
88+
89+
#%% md
90+
91+
现在,我们看一下训练数据集中前9个样本的图像内容和文本标签
92+
93+
#%%
94+
95+
X, y = [], []
96+
for i in range(10):
97+
X.append(x_train[i])
98+
y.append(y_train[i])
99+
show_fashion_mnist(X, get_fashion_mnist_labels(y))
100+
101+
#%% md
102+
103+
3.5.2. 读取小批量
104+
我们将在训练数据集上训练模型,并将训练好的模型在测试数据集上评价模型的表现。虽然我们可以像“线性回归的从零开始实现”一节中那样通过yield来定义读取小批量数据样本的函数,但为了代码简洁,这里我们直接创建DataLoader实例。该实例每次读取一个样本数为batch_size的小批量数据。这里的批量大小batch_size是一个超参数。
105+
106+
在实践中,数据读取经常是训练的性能瓶颈,特别当模型较简单或者计算硬件性能较高时。Gluon的DataLoader中一个很方便的功能是允许使用多进程来加速数据读取(暂不支持Windows操作系统)。这里我们通过参数num_workers来设置4个进程读取数据。
107+
108+
此外,我们通过ToTensor实例将图像数据从uint8格式变换成32位浮点数格式,并除以255使得所有像素的数值均在0到1之间。ToTensor实例还将图像通道从最后一维移到最前一维来方便之后介绍的卷积神经网络计算。通过数据集的transform_first函数,我们将ToTensor的变换应用在每个数据样本(图像和标签)的第一个元素,即图像之上。
109+
110+
#%%
111+
112+
batch_size = 256
113+
if sys.platform.startswith('win'):
114+
num_workers = 0 # 0表示不用额外的进程来加速读取数据
115+
else:
116+
num_workers = 4
117+
train_iter = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(256)
118+
119+
#%% md
120+
121+
最后我们查看读取一遍训练数据需要的时间。
122+
123+
#%%
124+
125+
start = time.time()
126+
for X, y in train_iter:
127+
continue
128+
print('%.2f sec' % (time.time() - start))
129+
130+
#%% md
131+
132+
3.5.3. 小结¶
133+
Fashion-MNIST是一个10类服饰分类数据集,之后章节里将使用它来检验不同算法的表现。
134+
我们将高和宽分别为 h 和 w 像素的图像的形状记为 h×w 或(h,w)。
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#%% md
2+
3+
我们在“线性回归的简洁实现”一节中已经了解了使用tensorflow2.0实现模型的便利。下面,让我们再次使用Gluon来实现一个softmax回归模型。首先导入所需的包或模块。
4+
5+
#%%
6+
7+
import tensorflow as tf
8+
9+
#%% md
10+
11+
3.7.1. 获取和读取数据¶
12+
我们仍然使用Fashion-MNIST数据集和上一节中设置的批量大小。
13+
14+
#%%
15+
16+
from tensorflow import keras
17+
fashion_mnist = keras.datasets.fashion_mnist
18+
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
19+
20+
#%% md
21+
22+
对数据进行处理,归一化,便于训练
23+
24+
#%%
25+
26+
x_train = x_train / 255.0
27+
x_test = x_test / 255.0
28+
29+
#%% md
30+
31+
在“softmax回归”一节中提到,softmax回归的输出层是一个全连接层。因此,我们添加一个输出个数为10的全连接层。
32+
第一层是Flatten,将28 * 28的像素值,压缩成一行 (784, )
33+
第二层还是Dense,因为是多分类问题,激活函数使用softmax
34+
35+
#%%
36+
37+
from tensorflow import keras
38+
model = keras.Sequential([
39+
keras.layers.Flatten(input_shape=(28, 28)),
40+
keras.layers.Dense(10, activation=tf.nn.softmax)
41+
])
42+
43+
#%% md
44+
45+
使用交叉熵损失函数和学习率为0.1的小批量随机梯度下降作为优化算法对模型进行训练
46+
47+
#%%
48+
49+
model.compile(optimizer=tf.keras.optimizers.SGD(0.1),
50+
loss = 'sparse_categorical_crossentropy',
51+
metrics=['accuracy'])
52+
53+
#%% md
54+
55+
选用batch的大小为256,对模型进行训练
56+
57+
#%%
58+
59+
model.fit(x_train,y_train,epochs=5,batch_size=256)
60+
61+
#%% md
62+
63+
接下来,比较模型在测试数据集上的表现情况
64+
65+
#%%
66+
67+
test_loss, test_acc = model.evaluate(x_test, y_test)
68+
print('Test Acc:',test_acc)
69+
70+
#%%
71+
72+

0 commit comments

Comments
 (0)