垃圾分类的Python代码
时间: 2024-06-17 10:01:58 浏览: 122
垃圾分类的Python代码通常涉及到图像识别和分类算法,例如使用深度学习库(如TensorFlow或PyTorch)结合卷积神经网络(CNN)。以下是一个简单的概念性的代码示例,用于说明如何用Python进行垃圾分类:
```python
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model
# 加载预训练模型ResNet50
base_model = ResNet50(weights='imagenet', include_top=False)
# 定义新的顶部分类层
num_classes = 4 # 假设我们有4种垃圾类别
x = base_model.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(num_classes, activation='softmax')(x)
# 创建新模型
model = Model(inputs=base_model.input, outputs=predictions)
# 冻结预训练模型的权重
for layer in base_model.layers:
layer.trainable = False
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 数据预处理,这里使用ImageDataGenerator处理图片数据增强
train_datagen = ImageDataGenerator(rescale=1./255) # 预处理
train_generator = train_datagen.flow_from_directory(
'path_to_train_data',
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
# 训练模型
model.fit(train_generator, epochs=10)
# 使用模型进行预测
def classify_image(image_path):
img = preprocess_input(tf.keras.preprocessing.image.load_img(image_path, target_size=(224, 224)))
img = tf.keras.preprocessing.image.img_to_array(img)
img = tf.expand_dims(img, axis=0)
predictions = model.predict(img)
return np.argmax(predictions)
# 示例
image_path = 'path_to_test_image'
predicted_class = classify_image(image_path)
print(f"Predicted class: {predicted_class}")
阅读全文