用Python搭建一个BP神经网络,使用tanh函数作为激活函数的代码
时间: 2023-06-06 19:04:32 浏览: 121
以下是用Python搭建一个BP神经网络,使用tanh函数作为激活函数的代码:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, hidden_layers):
self.hidden_layers = hidden_layers
def fit(self, X, y, alpha=0.1, epochs=1000):
input_size = X.shape[1]
output_size = y.shape[1]
layer_sizes = [input_size] + self.hidden_layers + [output_size]
self.weights = []
self.biases = []
for i in range(len(layer_sizes) - 1):
weight_shape = (layer_sizes[i], layer_sizes[i + 1])
bias_shape = (1, layer_sizes[i + 1])
self.weights.append(np.random.randn(*weight_shape))
self.biases.append(np.random.randn(*bias_shape))
for epoch in range(epochs):
# Forward propagation
outputs = [X]
for i in range(len(self.weights)):
outputs.append(np.tanh(outputs[-1] @ self.weights[i] + self.biases[i]))
# Backpropagation
error = outputs[-1] - y
delta = error
for i in range(len(self.weights) - 1, -1, -1):
delta = delta * (1 - outputs[i + 1] ** 2)
grad_weights = outputs[i].T @ delta
grad_biases = np.sum(delta, axis=0, keepdims=True)
delta = delta @ self.weights[i].T
self.weights[i] -= alpha * grad_weights
self.biases[i] -= alpha * grad_biases
def predict(self, X):
for i in range(len(self.weights)):
X = np.tanh(X @ self.weights[i] + self.biases[i])
return X
```
以上代码定义了一个名为`NeuralNetwork`的类,其中`hidden_layers`参数表示隐藏层的大小(一个由整数组成的列表),`fit`方法用于训练网络,`predict`方法用于进行预测。在训练过程中,代码使用了tanh作为激活函数,使用了随机初始化的权重和偏置。
阅读全文