简单二分类神经网络
- 定义神经网络结构(输入层、隐藏层、输出层的神经元数目)。
- 初始化模型的参数(权重和偏置)。
- 选择损失函数和优化算法。
- 循环执行以下操作:
- 前向传播:计算预测输出。
- 计算损失:量化预测值与真实值之间的差异。
- 后向传播:根据损失函数对每个参数进行偏导数计算,以更新模型的权重和偏置。
- 更新参数:根据优化算法调整权重和偏置。
import numpy as np
def sigmoid(x):
"""计算sigmoid激活函数的输出"""
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
"""计算sigmoid函数的导数"""
return x * (1 - x)
input_size = 2
hidden_size = 2
output_size = 1
np.random.seed(42)
weights_input_to_hidden = np.random.uniform(size=(input_size, hidden_size))
weights_hidden_to_output = np.random.uniform(size=(hidden_size, output_size))
learning_rate = 0.1
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
Y = np.array([[0], [1], [1], [0]])
for epoch in range(10000):
hidden_input = np.dot(X, weights_input_to_hidden)
hidden_output = sigmoid(hidden_input)
final_input = np.dot(hidden_output, weights_hidden_to_output)
final_output = sigmoid(final_input)
error = Y - final_output
loss = np.mean(np.square(error)) / 2
d_error = error * sigmoid_derivative(final_output)
d_weights_hidden_to_output = hidden_output.T.dot(d_error)
hidden_error = d_error.dot(weights_hidden_to_output.T) * sigmoid_derivative(hidden_output)
d_weights_input_to_hidden = X.T.dot(hidden_error)
weights_input_to_hidden += learning_rate * d_weights_input_to_hidden
weights_hidden_to_output += learning_rate * d_weights_hidden_to_output
print(final_output)