用Python写一个3层全连接的深度神经网络
时间: 2024-02-12 09:08:43 浏览: 28
好的,这里给您提供一个使用Python实现的三层全连接的深度神经网络的示例代码:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, input_dim, hidden_dim, output_dim):
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.output_dim = output_dim
# 初始化权重和偏置值
self.weights1 = np.random.randn(self.input_dim, self.hidden_dim)
self.bias1 = np.zeros((1, self.hidden_dim))
self.weights2 = np.random.randn(self.hidden_dim, self.output_dim)
self.bias2 = np.zeros((1, self.output_dim))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def softmax(self, x):
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=0)
def forward(self, X):
# 计算第一层的结果
self.layer1 = self.sigmoid(np.dot(X, self.weights1) + self.bias1)
# 计算第二层的结果
self.layer2 = self.softmax(np.dot(self.layer1, self.weights2) + self.bias2)
return self.layer2
def backward(self, X, y, output):
# 计算输出层的误差
self.output_error = y - output
# 计算输出层的梯度
self.output_gradient = self.output_error * self.sigmoid_derivative(output)
# 计算隐藏层的误差
self.hidden_error = np.dot(self.output_gradient, self.weights2.T)
# 计算隐藏层的梯度
self.hidden_gradient = self.hidden_error * self.sigmoid_derivative(self.layer1)
# 更新权重和偏置值
self.weights2 += np.dot(self.layer1.T, self.output_gradient)
self.bias2 += np.sum(self.output_gradient, axis=0, keepdims=True)
self.weights1 += np.dot(X.T, self.hidden_gradient)
self.bias1 += np.sum(self.hidden_gradient, axis=0)
def train(self, X, y, epochs):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
output = self.forward(X)
return output.argmax(axis=1)
```
这个神经网络使用sigmoid作为隐藏层的激活函数,使用softmax作为输出层的激活函数,使用交叉熵作为损失函数,使用随机梯度下降算法来更新参数。您可以根据自己的需求来修改激活函数、损失函数和优化算法等参数。