基于卷积神经网络的肺部ct图片识别代码
时间: 2023-06-26 13:06:13 浏览: 112
基于三维卷积神经网络模型的肺癌CT图像识别.caj
以下是一个基于卷积神经网络的肺部CT图片识别代码的示例:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split
# 读取数据
df = pd.read_csv('data.csv')
# 将像素值转换为0-1之间的浮点数
df['Image'] = df['Image'].apply(lambda x: np.fromstring(x, sep=' ') / 255.0)
# 重新构造图像大小并转换为数组
X = np.vstack(df['Image']).reshape(-1, 64, 64, 1)
# 提取标签信息
y = to_categorical(df['Label'], num_classes=2)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 构建卷积神经网络模型
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 1)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(128, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dropout(0.5),
Dense(2, activation='softmax')
])
# 编译模型
model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit(X_train, y_train, batch_size=32, epochs=20, validation_data=(X_test, y_test))
# 可视化训练过程
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# 评估模型
score = model.evaluate(X_test, y_test)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
需要注意的是,这只是一个简单的示例代码,实际应用中可能需要对模型结构和参数进行进一步的优化。同时,数据集的准备和预处理也需要根据具体情况进行调整。
阅读全文