使用LeNet进行训练python代码
时间: 2023-06-16 16:07:37 浏览: 45
下面是使用LeNet进行训练的Python代码示例:
首先,我们需要导入必要的库:
```python
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.datasets import mnist
from keras.utils import to_categorical
```
然后,我们加载MNIST数据集,并将其分割为训练和测试数据集:
```python
# Load the MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize the input data
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# Reshape the input data to 4D tensor
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
# Convert the labels to categorical format
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
```
接下来,我们定义LeNet模型的架构:
```python
# Define the LeNet model architecture
model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=(28, 28, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
```
然后,我们编译模型并进行训练:
```python
# Compile the model
model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(), metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, batch_size=128, epochs=10, validation_data=(x_test, y_test))
```
最后,我们可以对模型进行评估并输出准确率:
```python
# Evaluate the model
score = model.evaluate(x_test, y_test, verbose=0)
# Print the accuracy
print('Test accuracy:', score[1])
```