立即学习:https://edu.csdn.net/course/play/26266/334243?utm_source=blogtoedu
给你们源代码
#MNIST数据集预处理 import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() print(x_train.shape, y_train.shape) print(x_test.shape, y_test.shape) import matplotlib.pyplot as plt image_index = 1234 plt.imshow(x_train[image_index],cmap='Greys') plt.show() print(y_train[image_index]) #格式化 import numpy as np x_train = np.pad(x_train,((0,0),(2,2),(2,2)),'constant',constant_values=0) print(x_train.shape) x_train = x_train.astype('float32') x_train /=255 x_train=x_train.reshape(x_train.shape[0],32,32,1) print(x_train.shape) # LeNet模型构建 # 定义模型 # 模型的构建: tf.keras.Model 和tf.keras.layers # 模型的损失函数:tf.keras.losses # 模型的优化器: tf.keras.optimizer # 模型的评估: tf.keras.metrics class LetNet(tf.keras.Model): def __init__(self): super().__init__() #此处添加初始化代码(包含call方法中会用到的层) self.conv_layer_1 = tf.keras.layers.Conv2D( filters=6, kernel_size=(5,5), padding='valid', activation=tf.nn.relu) self.pool_layer_1=tf.keras.layers.MaxPooling2D(pool_size=(2,2),padding='same') self.conv_layer_2=tf.keras.layers.Conv2D( filters=16, kernel_size=(5,5), padding='valid', activation=tf.nn.relu) self.pool_layer_2=tf.keras.layers.MaxPooling2D(padding='same') self.flatten=tf.keras.layers.Flatten() self.fc_layer_1=tf.keras.layers.Dense( units=120, activation=tf.nn.relu) self.fc_layer_2=tf.keras.layers.Dense( units=84, activation=tf.nn.relu) self.output_layer=tf.keras.layers.Dense( units=10, activation=tf.nn.softmax) def call(self,inputs): #[batch_size,28,28,1] x=self.conv_layer_1(inputs) x=self.pool_layer_1(x) x=self.conv_layer_2(x) x=self.pool_layer_2(x) x=self.flatten(x) x=self.fc_layer_1(x) x=self.fc_layer_2(x) output=self.output_layer(x) return output #还可以添加自定义的方法 #模型实例化方法 model=tf.keras.models.Sequential([ tf.keras.layers.Conv2D(filters=6,kernel_size=(5,5),padding='valid',activation=tf.nn.relu,input_shape=(32,32,1)), tf.keras.layers.AveragePooling2D(pool_size=(2,2),strides=(2,2),padding='same'), tf.keras.layers.Conv2D(filters=16,kernel_size=(5,5),padding='valid',activation=tf.nn.relu), tf.keras.layers.AveragePooling2D(pool_size=(2,2),strides=(2,2),padding='same'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(units=120,activation=tf.nn.relu), # tf.keras.layers.Conv2D(filters=120,kernel_size=(5,5),strides=(1,1),activation='tanh',padding='valid'), # tf.keras.layers.Flatten(), tf.keras.layers.Dense(units=84,activation=tf.nn.relu), tf.keras.layers.Dense(units=10,activation=tf.nn.softmax) ]) model.summary()