level 1
UMBRELLAZG
楼主

import tensorflow as tfimport numpy as np
from tensorflow import keras
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import os
import matplotlib;
matplotlib.use('QT5Agg')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = np.expand_dims(x_train, axis=3)
x_test = np.expand_dims(x_test, axis=3)
x_train, y_train = x_train / 255.0, y_train / 255.0
print(x_train.shape, ' ', y_train.shape)
print(x_test.shape, ' ', y_test.shape)
print(x_train.dtype);
model = models.Sequential()
model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape = (x_train.shape[1:])))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test,y_test))
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
plt.show()
model.summary()
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(test_acc)