bp神经网络python
时间: 2023-08-25 18:07:37 浏览: 53
在Python中,可以使用多种库来实现BP神经网络,其中最常用的是NumPy和Keras。
1. 使用NumPy实现BP神经网络:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义sigmoid函数的导数
def sigmoid_derivative(x):
return x * (1 - x)
# 定义BP神经网络类
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
# 初始化权重矩阵
self.weights1 = np.random.randn(input_size, hidden_size)
self.weights2 = np.random.randn(hidden_size, output_size)
def forward(self, X):
# 前向传播
self.hidden_layer = sigmoid(np.dot(X, self.weights1))
self.output_layer = sigmoid(np.dot(self.hidden_layer, self.weights2))
return self.output_layer
def backward(self, X, y, output):
# 反向传播
self.output_error = y - output
self.output_delta = self.output_error * sigmoid_derivative(output)
self.hidden_error = np.dot(self.output_delta, self.weights2.T)
self.hidden_delta = self.hidden_error * sigmoid_derivative(self.hidden_layer)
self.weights2 += np.dot(self.hidden_layer.T, self.output_delta)
self.weights1 += np.dot(X.T, self.hidden_delta)
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 self.forward(X)
```
2. 使用Keras实现BP神经网络:
```python
from keras.models import Sequential
from keras.layers import Dense
# 定义BP神经网络模型
model = Sequential()
model.add(Dense(10, input_dim=8, activation='sigmoid'))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=100, batch_size=10)
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 预测结果
y_pred = model.predict(X_test)
```
阅读全文