机器学习人工神经网络算法代码
时间: 2023-08-31 11:05:11 浏览: 81
以下是一个简单的神经网络算法的 Python 代码示例:
```
import numpy as np
# 定义激活函数
def sigmoid(x):
return 1/(1+np.exp(-x))
# 定义神经网络类
class NeuralNetwork:
def __init__(self, input_dim, hidden_dim, output_dim):
# 初始化权重矩阵
self.weights1 = np.random.randn(input_dim, hidden_dim)
self.weights2 = np.random.randn(hidden_dim, output_dim)
def forward(self, X):
# 前向传播
self.z2 = np.dot(X, self.weights1)
self.a2 = sigmoid(self.z2)
self.z3 = np.dot(self.a2, self.weights2)
y_hat = sigmoid(self.z3)
return y_hat
def backward(self, X, y, y_hat, learning_rate):
# 反向传播
delta3 = (y_hat - y) * sigmoid(self.z3) * (1 - sigmoid(self.z3))
d_weights2 = np.dot(self.a2.T, delta3)
delta2 = np.dot(delta3, self.weights2.T) * sigmoid(self.z2) * (1 - sigmoid(self.z2))
d_weights1 = np.dot(X.T, delta2)
# 更新权重矩阵
self.weights2 -= learning_rate * d_weights2
self.weights1 -= learning_rate * d_weights1
def train(self, X, y, learning_rate, epochs):
for i in range(epochs):
y_hat = self.forward(X)
self.backward(X, y, y_hat, learning_rate)
# 测试
X = np.array([[0,0],[0,1],[1,0],[1,1]])
y = np.array([[0],[1],[1],[0]])
nn = NeuralNetwork(input_dim=2, hidden_dim=4, output_dim=1)
nn.train(X, y, learning_rate=0.1, epochs=10000)
# 预测
y_pred = nn.forward(X)
print(y_pred)
```
这是一个简单的三层神经网络,使用 sigmoid 作为激活函数,采用随机梯度下降法更新权重矩阵。你可以根据具体需求修改代码,例如更改激活函数、优化算法等等。
阅读全文