# 深度学习2.0-18.随机梯度下降之手写数字问题实战(层)

1147-柳同学

## 热门标签

, , ,

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics

# 构造预处理函数
def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32) / 255.
y = tf.cast(y, dtype=tf.int32)
return x, y

# x:[60k,28,28] x_test:[10k,28,28]
(x, y), (x_test, y_test) = datasets.fashion_mnist.load_data()
print(x.shape, y.shape)
print(x_test.shape, y_test.shape)

batchsz = 128
# 构造数据集
db = tf.data.Dataset.from_tensor_slices((x, y))
# 预处理,只需要传入函数而无需要传入函数的调用方式
db = db.map(preprocess).shuffle(10000).batch(batchsz)

db_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))
# 预处理,只需要传入函数而无需要传入函数的调用方式
db_test = db_test.map(preprocess).batch(batchsz)

db_iter = iter(db)
sample = next(db_iter)
print('batch:', sample[0].shape, sample[1].shape)

# 构建多层网络-最后一层一般不需要激活函数
model = Sequential([
layers.Dense(256, activation=tf.nn.relu),  # [b,784] => [b,256]
layers.Dense(128, activation=tf.nn.relu),  # [b,256] => [b,128]
layers.Dense(64, activation=tf.nn.relu),  # [b,128] => [b,64]
layers.Dense(32, activation=tf.nn.relu),  # [b,64] => [b,32]
layers.Dense(10),  # [b,32] => [b,10]   330 = 32*10 + 10
])

# 构建输入维度
model.build(input_shape=[None, 28 * 28])
model.summary()

# 构建优化器
# 更新权值- w = w -lr*grad

def main():
for epoch in range(30):

for step, (x, y) in enumerate(db):
# x[b,28,28] => x[b,784]
x = tf.reshape(x, [-1, 28 * 28])

with tf.GradientTape() as tape:
# 构建前向传播
# [b,784] => [b,10]
logits = model(x)
y = tf.one_hot(y, depth=10)
loss_mse = tf.reduce_mean(tf.losses.MSE(y, logits))
loss_ce = tf.losses.categorical_crossentropy(y, logits, from_logits=True)
loss_ce = tf.reduce_mean(loss_ce)

# 利用优化器统一原地更新

if step % 100 == 0:
print(epoch, step, 'loss:', float(loss_ce), float(loss_mse))

# test
total_correct = 0
total_num = 0
for x, y in db_test:
x = tf.reshape(x, [-1, 28 * 28])

# [b,784] => [b,10]
logits = model(x)
prob = tf.nn.softmax(logits, axis=1)
# [b,10] => [b]
pred = tf.argmax(prob, axis=1)
pred = tf.cast(pred, dtype=tf.int32)

# pred:[b]  y:[b]
correct = tf.equal(pred, y)
correct = tf.reduce_sum(tf.cast(correct, dtype=tf.int32))

# tensor => numpy
total_correct += int(correct)
total_num += x.shape[0]

acc = total_correct / total_num
print(epoch, 'test acc:', acc)

if __name__ == '__main__':
main()

(60000, 28, 28) (60000,)
(10000, 28, 28) (10000,)
batch: (128, 28, 28) (128,)
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense (Dense)                multiple                  200960
_________________________________________________________________
dense_1 (Dense)              multiple                  32896
_________________________________________________________________
dense_2 (Dense)              multiple                  8256
_________________________________________________________________
dense_3 (Dense)              multiple                  2080
_________________________________________________________________
dense_4 (Dense)              multiple                  330
=================================================================
Total params: 244,522
Trainable params: 244,522
Non-trainable params: 0
_________________________________________________________________
0 0 loss: 2.303929090499878 0.242684006690979
0 100 loss: 0.5860539674758911 22.32927703857422
0 200 loss: 0.5546977519989014 27.239099502563477
0 300 loss: 0.3866368532180786 25.4809627532959
0 400 loss: 0.3865927457809448 28.153907775878906
0 test acc: 0.8482
1 0 loss: 0.4001665711402893 26.901527404785156
1 100 loss: 0.523040771484375 32.702239990234375
1 200 loss: 0.2962474822998047 37.23288345336914
1 300 loss: 0.5228046774864197 29.088302612304688
1 400 loss: 0.4941650331020355 31.387100219726562
1 test acc: 0.853
2 0 loss: 0.3662468492984772 31.163776397705078
2 100 loss: 0.2790403962135315 37.754085540771484
2 200 loss: 0.3591204583644867 36.052513122558594
2 300 loss: 0.30174970626831055 35.038909912109375
2 400 loss: 0.45119309425354004 33.016700744628906
2 test acc: 0.8629
3 0 loss: 0.3489121198654175 36.01388931274414
3 100 loss: 0.32831019163131714 46.060543060302734
3 200 loss: 0.22170956432819366 41.36198425292969
3 300 loss: 0.284996896982193 34.6197624206543
3 400 loss: 0.3549075722694397 48.20280838012695
3 test acc: 0.8682

...

29 0 loss: 0.1280389428138733 230.05148315429688
29 100 loss: 0.10448945313692093 262.2647705078125
29 200 loss: 0.11969716101884842 239.57110595703125
29 300 loss: 0.10605543851852417 246.7599639892578
29 400 loss: 0.09774138778448105 235.69046020507812
29 test acc: 0.8915


Vieu3.3主题

Q Q 登 录