五层全连接神经网络拟合函数y=x^2+2x-3的不使用pytorch框架的python代码
时间: 2023-03-16 09:44:13 浏览: 125
使用Python编写五层全连接神经网络来拟合函数y=x^2 2x-3,可以使用以下代码:import numpy as np
import matplotlib.pyplot as plt# 生成数据
x = np.arange(-5, 5, 0.1)
y = x**2 + 2*x - 3# 定义模型
num_epochs = 500
learning_rate = 1e-3# 初始化参数
w1 = np.random.randn(1, 5)
b1 = np.zeros((1, 5))
w2 = np.random.randn(5, 1)
b2 = np.zeros((1, 1))# 训练
for epoch in range(num_epochs):
# 前向传播
h = x.dot(w1) + b1
a = np.maximum(h, 0)
y_pred = a.dot(w2) + b2
# 计算损失
loss = np.square(y_pred - y).sum() # 反向传播
grad_y_pred = 2.0 * (y_pred - y)
grad_w2 = a.T.dot(grad_y_pred)
grad_b2 = grad_y_pred.sum(axis=0)
grad_a = grad_y_pred.dot(w2.T)
grad_h = grad_a.copy()
grad_h[h < 0] = 0
grad_w1 = x.T.dot(grad_h)
grad_b1 = grad_h.sum(axis=0) # 更新参数
w1 -= learning_rate * grad_w1
b1 -= learning_rate * grad_b1
w2 -= learning_rate * grad_w2
b2 -= learning_rate * grad_b2# 绘制结果
plt.plot(x, y, 'b.', label='data')
plt.plot(x, y_pred, 'r.', label='prediction')
plt.legend()
plt.show()
阅读全文