利用keras框架对已经分好了训练集、验证集、测试集的数据集进行多分类,输入为150✖150的图片,分类数量为10
时间: 2024-02-12 20:02:17 浏览: 105
好的,下面是利用 Keras 框架对已经分好了训练集、验证集、测试集的数据集进行多分类的代码示例,输入为 150x150 的图片,分类数量为 10。
```python
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
# 定义模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=0.001),
metrics=['accuracy'])
# 数据增强生成器
train_datagen = ImageDataGenerator(rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
# 加载数据集
batch_size = 32
train_data_dir = '/path/to/train'
validation_data_dir = '/path/to/validation'
test_data_dir = '/path/to/test'
train_generator = train_datagen.flow_from_directory(train_data_dir,
target_size=(150, 150),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(validation_data_dir,
target_size=(150, 150),
batch_size=batch_size,
class_mode='categorical')
test_generator = test_datagen.flow_from_directory(test_data_dir,
target_size=(150, 150),
batch_size=batch_size,
class_mode='categorical')
# 训练模型
epochs = 50
steps_per_epoch = train_generator.n // batch_size
validation_steps = validation_generator.n // batch_size
history = model.fit_generator(train_generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_steps)
# 评估模型
test_loss, test_acc = model.evaluate_generator(test_generator, steps=test_generator.n // batch_size)
print('Test accuracy:', test_acc)
```
以上就是利用 Keras 框架对已经分好了训练集、验证集、测试集的数据集进行多分类的代码示例,输入为 150x150 的图片,分类数量为 10。希望对你有所帮助。
阅读全文