神经网络模型代码python
时间: 2023-07-22 16:32:18 浏览: 143
基于Python的神经网络模型源代码
以下是一个简单的神经网络模型代码的 Python 实现:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, layers):
self.layers = layers
self.weights = [np.random.randn(layers[i], layers[i+1]) for i in range(len(layers)-1)]
self.biases = [np.zeros((1, layers[i+1])) for i in range(len(layers)-1)]
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def feedforward(self, x):
a = x
for i in range(len(self.weights)):
z = np.dot(a, self.weights[i]) + self.biases[i]
a = self.sigmoid(z)
return a
def backpropagation(self, x, y):
a = [x]
z_list = []
for i in range(len(self.weights)):
z = np.dot(a[i], self.weights[i]) + self.biases[i]
z_list.append(z)
a.append(self.sigmoid(z))
delta = (a[-1] - y) * self.sigmoid_derivative(a[-1])
deltas = [delta]
for i in range(len(self.weights)-1, 0, -1):
delta = np.dot(deltas[-1], self.weights[i].T) * self.sigmoid_derivative(a[i])
deltas.append(delta)
deltas.reverse()
for i in range(len(self.weights)):
self.weights[i] -= 0.1 * np.dot(a[i].T, deltas[i])
self.biases[i] -= 0.1 * deltas[i]
def train(self, X, y, epochs):
for epoch in range(epochs):
for x, y_true in zip(X, y):
self.backpropagation(x, y_true)
def predict(self, X):
return np.array([np.argmax(self.feedforward(x)) for x in X])
```
这个代码实现了一个基本的多层神经网络,使用了 sigmoid 激活函数和反向传播算法来训练模型。你可以传入一个层列表(例如 [2, 3, 1])来定义神经网络的结构,然后使用 train 函数来训练模型,使用 predict 函数来进行预测。
阅读全文