python实现wine数据集实现一个神经网络分类器
时间: 2023-11-10 10:33:05 浏览: 126
基于Python实现神经网络分类MNIST数据集【100011708】
5星 · 资源好评率100%
好的,以下是python实现wine数据集的神经网络分类器的步骤:
1. 导入需要的库:
```python
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
```
2. 加载wine数据集:
```python
wine = load_wine()
X = wine.data
y = wine.target
```
3. 数据预处理:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
```
4. 定义神经网络模型并进行训练:
```python
model = Sequential()
model.add(Dense(10, input_dim=X_train.shape[1], activation='relu'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=50, batch_size=16, verbose=2)
```
5. 进行预测并计算准确率:
```python
_, acc = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy:", acc)
```
完整代码如下:
```python
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
# 加载wine数据集
wine = load_wine()
X = wine.data
y = wine.target
# 数据预处理
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# 定义神经网络模型并进行训练
model = Sequential()
model.add(Dense(10, input_dim=X_train.shape[1], activation='relu'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=50, batch_size=16, verbose=2)
# 进行预测并计算准确率
_, acc = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy:", acc)
```
希望这个例子能够帮助到你。
阅读全文