图片分类python
时间: 2023-06-30 09:19:36 浏览: 98
要用Python进行图片分类,可以使用深度学习框架进行模型训练和分类。常用的深度学习框架有TensorFlow、PyTorch和Keras等。以下是一个基于TensorFlow的图片分类示例代码:
```python
import tensorflow as tf
import numpy as np
import os
# 加载数据和标签
def load_data():
train_path = "./train/"
test_path = "./test/"
categories = os.listdir(train_path)
categories.sort()
num_classes = len(categories)
train_data = []
train_labels = []
test_data = []
test_labels = []
for index, category in enumerate(categories):
train_label = np.zeros(num_classes)
train_label[index] = 1
test_label = np.zeros(num_classes)
test_label[index] = 1
for img in os.listdir(train_path+category):
img_path = os.path.join(train_path, category, img)
img = tf.keras.preprocessing.image.load_img(img_path, target_size=(224, 224))
img = tf.keras.preprocessing.image.img_to_array(img)
train_data.append(img)
train_labels.append(train_label)
for img in os.listdir(test_path+category):
img_path = os.path.join(test_path, category, img)
img = tf.keras.preprocessing.image.load_img(img_path, target_size=(224, 224))
img = tf.keras.preprocessing.image.img_to_array(img)
test_data.append(img)
test_labels.append(test_label)
train_data = np.array(train_data)
train_labels = np.array(train_labels)
test_data = np.array(test_data)
test_labels = np.array(test_labels)
return train_data, train_labels, test_data, test_labels, num_classes
# 构建模型
def build_model(num_classes):
base_model = tf.keras.applications.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights='imagenet')
x = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)
x = tf.keras.layers.Dense(1024, activation='relu')(x)
x = tf.keras.layers.Dropout(0.5)(x)
output = tf.keras.layers.Dense(num_classes, activation='softmax')(x)
model = tf.keras.models.Model(inputs=base_model.input, outputs=output)
return model
# 训练模型
def train_model(train_data, train_labels, num_classes):
model = build_model(num_classes)
model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(train_data, train_labels, epochs=10, batch_size=32)
model.save('./model.h5')
# 测试模型
def test_model(test_data, test_labels):
model = tf.keras.models.load_model('./model.h5')
loss, accuracy = model.evaluate(test_data, test_labels)
print('Test Loss:', loss)
print('Test Accuracy:', accuracy)
if __name__ == '__main__':
train_data, train_labels, test_data, test_labels, num_classes = load_data()
train_model(train_data, train_labels, num_classes)
test_model(test_data, test_labels)
```
这个示例代码使用了MobileNetV2模型进行特征提取,并添加了一些全连接层进行分类。在训练时,使用了Adam优化器和交叉熵损失函数。在测试时,加载了已经训练好的模型,计算了测试数据的损失和准确率。代码中的数据集路径需要根据实际情况进行修改。
阅读全文