怎么用python实现神经网络的iris数据集的分类
时间: 2023-10-18 10:04:18 浏览: 166
使用Python实现神经网络对iris数据集进行分类的过程大致如下:
1. 导入iris数据集
```python
from sklearn.datasets import load_iris
iris = load_iris()
```
2. 对数据进行预处理
```python
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X = scaler.fit_transform(iris.data)
y = iris.target
```
3. 划分数据集为训练集和测试集
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
4. 构建神经网络模型
```python
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(10, input_dim=4, activation='relu'))
model.add(Dense(3, activation='softmax'))
```
5. 编译模型
```python
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
```
6. 训练模型
```python
from keras.utils import to_categorical
y_train_onehot = to_categorical(y_train)
model.fit(X_train, y_train_onehot, epochs=50, batch_size=5)
```
7. 预测测试集
```python
y_test_onehot = to_categorical(y_test)
_, accuracy = model.evaluate(X_test, y_test_onehot)
print("Accuracy:", accuracy)
```
完整代码如下:
```python
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
# 导入数据集
iris = load_iris()
# 对数据进行预处理
scaler = StandardScaler()
X = scaler.fit_transform(iris.data)
y = iris.target
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 构建神经网络模型
model = Sequential()
model.add(Dense(10, input_dim=4, activation='relu'))
model.add(Dense(3, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
y_train_onehot = to_categorical(y_train)
model.fit(X_train, y_train_onehot, epochs=50, batch_size=5)
# 预测测试集
y_test_onehot = to_categorical(y_test)
_, accuracy = model.evaluate(X_test, y_test_onehot)
print("Accuracy:", accuracy)
```
这段代码使用了Keras库构建了一个包含输入层、隐藏层和输出层的神经网络模型。其中隐藏层使用了10个神经元,激活函数为ReLU,输出层使用了3个神经元,激活函数为Softmax。编译模型时使用了交叉熵作为损失函数,Adam优化器进行参数更新,并且使用准确率作为评估指标。最后通过fit函数进行训练,使用evaluate函数对测试集进行预测并评估模型性能。
阅读全文