用Python写一个完整的神经网络
时间: 2023-12-02 09:06:33 浏览: 24
作为AI助手,我可以给您提供一个示例代码:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
# 定义sigmoid函数的导数
def sigmoid_derivative(x):
return sigmoid(x) * (1 - sigmoid(x))
# 定义神经网络类
class NeuralNetwork:
def __init__(self, layers):
self.layers = layers
self.weights = [np.random.randn(self.layers[i], self.layers[i+1]) for i in range(len(self.layers)-1)]
self.biases = [np.random.randn(1, self.layers[i+1]) for i in range(len(self.layers)-1)]
def feedforward(self, x):
a = x
for i in range(len(self.layers)-1):
z = np.dot(a, self.weights[i]) + self.biases[i]
a = sigmoid(z)
return a
def backpropagation(self, x, y, learning_rate):
activations = [x]
zs = []
a = x
for i in range(len(self.layers)-1):
z = np.dot(a, self.weights[i]) + self.biases[i]
zs.append(z)
a = sigmoid(z)
activations.append(a)
delta = (activations[-1] - y) * sigmoid_derivative(zs[-1])
for i in range(len(self.layers)-2, -1, -1):
delta = np.dot(delta, self.weights[i].T) * sigmoid_derivative(zs[i])
self.weights[i] -= learning_rate * np.dot(activations[i].T, delta)
self.biases[i] -= learning_rate * np.sum(delta, axis=0, keepdims=True)
def train(self, X, y, learning_rate, epochs):
for i in range(epochs):
for j in range(len(X)):
x = X[j]
y_true = y[j]
self.backpropagation(x, y_true, learning_rate)
def predict(self, X):
y_pred = []
for x in X:
y_pred.append(self.feedforward(x))
return np.array(y_pred)
# 测试
X = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([[0], [1], [1], [0]])
nn = NeuralNetwork([2, 2, 1])
nn.train(X, y, 0.5, 10000)
print("Predictions: ", nn.predict(X))
```
这是一个简单的2层神经网络,用于解决XOR问题。您可以根据需要对其进行修改,以适应您的项目。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)