用python写基于卷积神经网络的岩石图像分类识别
时间: 2023-10-27 15:19:07 浏览: 154
岩石图像分类识别是一个典型的图像分类问题,可以使用卷积神经网络(CNN)来解决。下面是一个基于CNN的岩石图像分类识别的Python示例代码。
首先,我们需要导入必要的库:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import rockpaperscissors
```
接下来,我们需要加载数据集并对其进行预处理:
```python
(X_train, y_train), (X_test, y_test) = rockpaperscissors.load_data()
# 将像素值缩放到0到1之间
X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32') / 255
# 对标签进行编码
y_train = np_utils.to_categorical(y_train, 3)
y_test = np_utils.to_categorical(y_test, 3)
# 调整图像大小
X_train = np.array([keras.preprocessing.image.img_to_array(keras.preprocessing.image.load_img(img, target_size=(150, 150))) for img in X_train])
X_test = np.array([keras.preprocessing.image.img_to_array(keras.preprocessing.image.load_img(img, target_size=(150, 150))) for img in X_test])
# 确认输入形状
input_shape = X_train[0].shape
```
接下来,我们可以定义CNN模型:
```python
model = Sequential()
# 添加卷积层和最大池化层
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# 添加全连接层和输出层
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(3, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
```
接下来,我们可以训练模型:
```python
history = model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=1, validation_data=(X_test, y_test))
```
最后,我们可以评估模型性能并进行预测:
```python
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 进行预测
predictions = model.predict(X_test)
```
这是一个基于CNN的岩石图像分类识别的Python示例代码。使用这个代码,你可以构建一个能够对岩石图像进行分类的模型。
阅读全文