letnet神经网络python
时间: 2023-10-17 09:05:35 浏览: 78
LeNet是一种早期的卷积神经网络,用于手写数字识别。下面是使用Python实现LeNet神经网络的示例代码:
```python
import tensorflow as tf
from tensorflow.keras import layers
# 定义LeNet神经网络结构
def LeNet(input_shape, num_classes):
model = tf.keras.Sequential()
model.add(layers.Conv2D(6, kernel_size=(5, 5), strides=(1, 1), activation='relu', input_shape=input_shape))
model.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(layers.Conv2D(16, kernel_size=(5, 5), strides=(1, 1), activation='relu'))
model.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(120, activation='relu'))
model.add(layers.Dense(84, activation='relu'))
model.add(layers.Dense(num_classes, activation='softmax'))
return model
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 数据预处理
x_train, x_test = x_train / 255.0, x_test / 255.0
# 将数据集的维度从 (num_samples, 28, 28) 转换成 (num_samples, 28, 28, 1)
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
# 定义LeNet神经网络
model = LeNet(input_shape=(28, 28, 1), num_classes=10)
# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
```
这个示例代码中,我们使用TensorFlow和Keras库来定义LeNet神经网络结构,加载MNIST数据集,并对数据进行预处理。然后编译模型,使用训练集对模型进行训练,最后在测试集上进行评估。
阅读全文