还要这个题目的phyton代码
时间: 2024-10-19 09:02:53 浏览: 19
第十四届蓝桥杯省赛Python大学A组题目pdf
要编写Python代码来实现上述的三层感知机,我们可以使用`numpy`库进行数值计算,并简化代码。首先确保已安装了`numpy`:
```python
import numpy as np
# 定义 sigmoid 函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 初始化权重和输入值
input_dim = 2
hidden_units = 2
output_units = 1
learning_rate = 0.1
max_iterations = 1000
inputs = np.random.rand(100, input_dim)
weights_hidden = np.random.randn(input_dim, hidden_units)
bias_hidden = np.zeros(hidden_units)
weights_output = np.random.randn(hidden_units, output_units)
bias_output = np.zeros(output_units)
for iteration in range(max_iterations):
# 前向传播
hidden_layer_inputs = inputs.dot(weights_hidden) + bias_hidden
hidden_layer_outputs = sigmoid(hidden_layer_inputs)
output_layer_inputs = hidden_layer_outputs.dot(weights_output) + bias_output
output_layer_outputs = sigmoid(output_layer_inputs)
# 计算误差
targets = np.where(inputs[:, 0] * inputs[:, 1] > 0.5, 1, 0) # 异或逻辑
error = targets - output_layer_outputs
# 反向传播
output_error_derivative = error * sigmoid_derivative(output_layer_outputs)
d_weights_output = hidden_layer_outputs.T.dot(output_error_derivative)
d_bias_output = np.sum(error)
hidden_error_derivative = output_error_derivative.dot(weights_output.T) * sigmoid_derivative(hidden_layer_outputs)
d_weights_hidden = inputs.T.dot(hidden_error_derivative)
d_bias_hidden = np.sum(hidden_error_derivative, axis=0)
# 更新权重
weights_output += learning_rate * d_weights_output
bias_output += learning_rate * d_bias_output
weights_hidden += learning_rate * d_weights_hidden
bias_hidden += learning_rate * d_bias_hidden
if iteration % 100 == 0:
print(f"Iteration {iteration}: Loss = {np.mean(np.abs(error))}")
# 预测新数据
new_input = np.array([[0.5, 0.5]])
hidden_output = sigmoid(new_input.dot(weights_hidden) + bias_hidden)
output = sigmoid(hidden_output.dot(weights_output) + bias_output)
prediction = int(output > 0.5) # 转换为0或1
print("Prediction for new data:", prediction)
```
这段代码首先设置网络结构,然后初始化权重和数据。接下来进行训练迭代,包括前向传播、计算误差、反向传播及权重更新。最后,演示如何预测新数据。注意,这里的异或逻辑是理想情况下的,实际训练可能需要调整学习率、迭代次数等参数。
阅读全文