python搭建bp神经网络解决红酒问题
时间: 2023-09-06 09:14:20 浏览: 162
红酒问题是一个经典的机器学习问题,可以用神经网络来解决。下面是一个用 Python 搭建 BP 神经网络解决红酒问题的示例代码:
首先,需要导入需要用到的库:
```python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
```
然后,读取红酒数据集:
```python
data = pd.read_csv('winequality-red.csv', sep=';')
```
接着,将数据集中的标签值转换成类别:
```python
data['quality'] = pd.cut(data['quality'], bins=[0, 6, 10], labels=[0, 1])
```
然后,将数据集分成训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(data.drop('quality', axis=1), data['quality'], test_size=0.33, random_state=42)
```
接下来,对数据进行标准化:
```python
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
然后,定义 BP 神经网络模型:
```python
class NeuralNetwork:
def __init__(self, layers):
self.layers = layers
self.weights = []
for i in range(1, len(layers)):
self.weights.append(np.random.randn(layers[i-1], layers[i]))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, x):
a = x
for w in self.weights:
a = self.sigmoid(np.dot(a, w))
return a
def backward(self, x, y, output):
error = y - output
delta = error * self.sigmoid_derivative(output)
for i in range(len(self.weights)-1, -1, -1):
output = self.sigmoid(np.dot(x, self.weights[i]))
error = delta.dot(self.weights[i].T)
delta = error * self.sigmoid_derivative(output)
self.weights[i] += x.T.dot(delta)
x = output
def train(self, X, y, epochs):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
return np.round(self.forward(X))
```
最后,训练模型并进行预测:
```python
nn = NeuralNetwork([11, 6, 1])
nn.train(X_train, y_train, 10000)
y_pred = nn.predict(X_test)
```
这样就完成了用 BP 神经网络解决红酒问题的过程。
阅读全文