使用tensorflow2.0非重写方式,运用tensorflow2.0自带的keras建立全连接网络

直接上代码:
import tensorflow as tf

# 下载mnist手写数据集
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)

# 建立网络,这里采用的是Sequential结构,全连接层第一层512个神经元,第二层10个神经元
network = tf.keras.models.Sequential()
network.add(tf.keras.layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(tf.keras.layers.Dense(10, activation='softmax'))

# 编译网络,优化器采用'rmsprop',损失函数采用'categorical_crossentropy',监控指标为'accuracy'。
network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

# reshape数据,再归一化处理数据
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

# 将标签变为one-hot编码
train_labels = tf.keras.utils.to_categorical(train_labels)
test_labels = tf.keras.utils.to_categorical(test_labels)

# 加载输入开始训练,训练轮数为5轮,采用批处理方式,每一批数据的大小为128
network.fit(train_images, train_labels, epochs=5, batch_size=128)

# 评估模型,在测试集上评估模型准确率
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)
运行结果如下:
(60000, 28, 28)
(60000,)
(10000, 28, 28)
(10000,)

Train on 60000 samples
Epoch 1/5

  128/60000 [..............................] - ETA: 5:18 - loss: 2.3173 - accuracy: 0.0938
 1280/60000 [..............................] - ETA: 33s - loss: 1.2775 - accuracy: 0.6305 
 2304/60000 [>.............................] - ETA: 19s - loss: 0.9732 - accuracy: 0.7283
 3584/60000 [>.............................] - ETA: 13s - loss: 0.7996 - accuracy: 0.7835
 4736/60000 [=>............................] - ETA: 10s - loss: 0.7055 - accuracy: 0.8104
 6016/60000 [==>...........................] - ETA: 8s - loss: 0.6474 - accuracy: 0.8263 
……
58880/60000 [============================>.] - ETA: 0s - loss: 0.0371 - accuracy: 0.9886
60000/60000 [==============================] - 3s 50us/sample - loss: 0.0371 - accuracy: 0.9886

10000/1 [==============================] - 0s 40us/sample - loss: 0.0347 - accuracy: 0.9793
test_acc: 0.9793

Process finished with exit code 0

测试准确率比训练准确率低一些是因为在训练集上会有过拟合现象产生,需要用新的数据进行测试。

上面是Sequential模式,下面的代码是Functional函数式编程模式:
import tensorflow as tf

# 下载mnist手写数据集
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)

# 建立网络,这里采用的是Functional结构,全连接层第一层32个神经元,第二层10个神经元
input_tensor = tf.keras.layers.Input(shape=(28 * 28,))
x = tf.keras.layers.Dense(32, activation='relu')(input_tensor)
output_tensor = tf.keras.layers.Dense(10, activation='softmax')(x)
model = tf.keras.models.Model(inputs=input_tensor, outputs=output_tensor)

# 编译网络,优化器采用'rmsprop',损失函数采用'mse',监控指标为'accuracy'。
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.001), loss='mse', metrics=['accuracy'])

# reshape数据,再归一化处理数据
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

# 将标签变为one-hot编码
train_labels = tf.keras.utils.to_categorical(train_labels)
test_labels = tf.keras.utils.to_categorical(test_labels)

# 加载输入开始训练,训练轮数为5轮,采用批处理方式,每一批数据的大小为128
model.fit(train_images, train_labels, epochs=5, batch_size=128)

# 评估模型,在测试集上评估模型准确率
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('test_acc:', test_acc)
运行结果如下:
(60000, 28, 28)
(60000,)
(10000, 28, 28)
(10000,)

Train on 60000 samples
Epoch 1/5

  128/60000 [..............................] - ETA: 5:19 - loss: 0.0919 - accuracy: 0.0703
 4992/60000 [=>............................] - ETA: 8s - loss: 0.0610 - accuracy: 0.6170  
……
39808/60000 [==================>...........] - ETA: 0s - loss: 0.0078 - accuracy: 0.9515
44160/60000 [=====================>........] - ETA: 0s - loss: 0.0078 - accuracy: 0.9516
48256/60000 [=======================>......] - ETA: 0s - loss: 0.0078 - accuracy: 0.9514
53376/60000 [=========================>....] - ETA: 0s - loss: 0.0078 - accuracy: 0.9513
57984/60000 [===========================>..] - ETA: 0s - loss: 0.0077 - accuracy: 0.9518
60000/60000 [==============================] - 1s 12us/sample - loss: 0.0077 - accuracy: 0.9520
10000/1 [==============================] - 0s 27us/sample - loss: 0.0049 - accuracy: 0.9486
test_acc: 0.9486

Process finished with exit code 0

你可能感兴趣的:(使用tensorflow2.0非重写方式,运用tensorflow2.0自带的keras建立全连接网络)