Python TensorFlow 动物分类卷积神经网络示例代码
以下是一个示例代码,展示了如何使用Python和TensorFlow框架搭建、训练和测试一个卷积神经网络模型来进行动物分类任务。请注意,这只是一个示例,实际应用中可能需要根据需求进行调整和扩展。
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
# 设置训练集和测试集的路径
train_dir = 'path/to/train/directory'
test_dir = 'path/to/test/directory'
# 设置图像的尺寸和批量大小
img_size = (150, 150)
batch_size = 32
# 数据增强和预处理
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=img_size,
batch_size=batch_size,
class_mode='categorical')
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=img_size,
batch_size=batch_size,
class_mode='categorical')
# 构建卷积神经网络模型
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
# 编译模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
history = model.fit(train_generator,
steps_per_epoch=train_generator.n//batch_size,
epochs=10,
validation_data=test_generator,
validation_steps=test_generator.n//batch_size)
# 可视化训练集和测试集的损失率和准确率
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
# 在测试集上评估模型
loss, accuracy = model.evaluate(test_generator)
print('Test Loss:', loss)
print('Test Accuracy:', accuracy)
# 使用模型进行预测
class_names = train_generator.class_indices
inv_class_names = {v: k for k, v in class_names.items()}
# 加载测试图片
test_image_path = 'path/to/test/image.jpg'
test_image = tf.keras.preprocessing.image.load_img(test_image_path, target_size=img_size)
test_image = tf.keras.preprocessing.image.img_to_array(test_image)
test_image = tf.expand_dims(test_image, axis=0)
# 预测图像的类别
prediction = model.predict(test_image)
predicted_class = inv_class_names[np.argmax(prediction)]
print('Predicted Class:', predicted_class)
请确保将代码中的相关路径进行正确设置,并根据实际情况调整模型的架构和训练参数。此外,还需安装TensorFlow和matplotlib等相关依赖库。
原文地址: https://www.cveoy.top/t/topic/tM5 著作权归作者所有。请勿转载和采集!