用python写一段代码:采用LeNet模型对CIFA-100数据集分类,进行模型训练和模型评估
时间: 2024-05-02 07:18:10 浏览: 110
CIFAR100 python-数据集
以下是采用LeNet模型对CIFAR-100数据集进行分类的Python代码,包括模型训练和模型评估:
```
import tensorflow as tf
from tensorflow.keras.datasets import cifar100
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import SparseCategoricalCrossentropy
# 加载CIFAR-100数据集
(x_train, y_train), (x_test, y_test) = cifar100.load_data()
# 数据预处理
x_train = x_train / 255.0
x_test = x_test / 255.0
# 构建LeNet模型
model = Sequential([
Conv2D(filters=6, kernel_size=(5, 5), activation='relu', input_shape=(32, 32, 3)),
MaxPooling2D(pool_size=(2, 2)),
Conv2D(filters=16, kernel_size=(5, 5), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(units=120, activation='relu'),
Dropout(0.5),
Dense(units=84, activation='relu'),
Dropout(0.5),
Dense(units=100, activation='softmax')
])
# 编译模型
model.compile(optimizer=Adam(learning_rate=0.001), loss=SparseCategoricalCrossentropy(), metrics=['accuracy'])
# 训练模型
history = model.fit(x_train, y_train, epochs=20, batch_size=128, validation_data=(x_test, y_test))
# 评估模型
loss, accuracy = model.evaluate(x_test, y_test)
print('Test loss:', loss)
print('Test accuracy:', accuracy)
```
在上述代码中,我们首先加载了CIFAR-100数据集,并进行了数据预处理。然后我们构建了一个LeNet模型,并使用Adam优化器和稀疏分类交叉熵损失函数进行模型编译。接着我们使用训练集对模型进行了训练,并在测试集上进行了模型评估。最后,我们输出了模型在测试集上的损失和准确率。
阅读全文