基于python使用卷积神经网络算法对鸢尾花数据集进行分类。
时间: 2024-12-19 15:19:54 浏览: 24
基于Python的卷积神经网络(Convolutional Neural Network,简称CNN)对鸢尾花数据集进行分类是一个常见的机器学习任务,尤其当涉及到图像识别或特征提取时。这里我们将使用深度学习库Keras,它在TensorFlow或PyTorch等后端上运行。
首先,你需要安装必要的库,如NumPy、Pandas、Keras以及matplotlib:
```bash
pip install numpy pandas scikit-learn tensorflow keras matplotlib
```
然后,我们从sklearn库导入鸢尾花数据集并预处理数据:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X = iris.data
y = iris.target
# 将类别编码为one-hot形式
num_classes = len(np.unique(y))
y = to_categorical(y, num_classes)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,定义一个简单的卷积神经网络模型:
```python
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense
model = Sequential([
Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(4, 1)), # 4特征维度,1通道(因为鸢尾花数据不是图像)
MaxPooling1D(pool_size=2),
Conv1D(filters=32, kernel_size=3, activation='relu'),
MaxPooling1D(pool_size=2),
Flatten(), # 展平输入,准备全连接层
Dense(64, activation='relu'),
Dense(num_classes, activation='softmax') # 输出层,根据分类数设定节点数
])
```
然后编译模型,设置损失函数、优化器和评估指标:
```python
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
```
最后,训练模型:
```python
history = model.fit(X_train.reshape(-1, 4, 1), y_train, epochs=50, validation_data=(X_test.reshape(-1, 4, 1), y_test))
```
阅读全文