mnist案例
数据加载
数据处理
模型构建
模型编译和训练
模型评估和保存
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Dropout,Activation,BatchNormalization
from tensorflow.keras import utils
from tensorflow.keras import regularizers
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
(x_train,y_train),(x_test,y_test)=mnist.load_data()
print(x_train.shape)
print(y_train)
plt.figure()
plt.imshow(x_train[1],cmap="gray")
x_train=x_train.reshape(60000,784)
x_test = x_test.reshape(10000,784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train = x_train/255
x_test = x_test/255
y_train=utils.to_categorical(y_train,10)
y_test = utils.to_categorical(y_test,10)
print(y_train)
model = Sequential()
model.add(Dense(512,activation="relu",input_shape=(784,)))
model.add(BatchNormalization())
model.add(Dropout(0.2))
model.add(Dense(512,kernel_regularizer=regularizers.l2(0.01)))
model.add(BatchNormalization())
model.add(Activation("relu"))
model.add(Dropout(0.2))
model.add(Dense(10,activation="softmax"))
print(model.summary())
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(x_train,y_train,
batch_size=128,epochs=4,verbose=1,
validation_data=(x_test,y_test))
plt.figure()
plt.plot(history.history['loss'],label="train")
plt.plot(history.history["val_loss"],label="val")
plt.legend()
plt.grid()
plt.figure()
plt.plot(history.history['accuracy'],label="train")
plt.plot(history.history["val_accuracy"],label="val")
plt.legend()
plt.grid()
model.save("my_model.h5")
model=tf.keras.models.load_model("my_model.h5")
model.evaluate(x_test,y_test,verbose=1)
卷积神经网络
卷积层
池化层
全连接层
卷积神经网络的构建LeNet-5
import tensorflow as tf
from tensorflow.keras.datasets import mnist
(train_images,train_labels),(test_images,test_labels)=mnist.load_data()
train_images = tf.reshape(train_images,(train_images.shape[0],train_images.shape[1],train_images.shape[2],1))
print(train_images.shape)
test_images=tf.reshape(test_images,(test_images.shape[0],test_images.shape[1],test_images.shape[2],1))
print(test_images.shape)
net = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=6,kernel_size=5,
activation="sigmoid",input_shape=(28,28,1)),
tf.keras.layers.MaxPool2D(pool_size=2,strides=2),
tf.keras.layers.Conv2D(filters=16,kernel_size=5,activation="sigmoid"),
tf.keras.layers.MaxPool2D(pool_size=2,strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(120,activation="sigmoid"),
tf.keras.layers.Dense(84,activation="sigmoid"),
tf.keras.layers.Dense(10,activation="softmax")
])
optimizer = tf.keras.optimizers.SGD(learning_rate=0.9)
net.compile(optimizer=optimizer,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
net.fit(train_images,train_labels,epochs=5,validation_split=0.1)
score = net.evaluate(test_images,test_labels,verbose=1)
print('Test accuracy:',score[1])