BP算法训练一个含m-h-1个隐节点的单隐层单输出感知器网络

# 又是一个大作业

要求隐层各个隐节点的激活函数可以取以下函数:

样本生成:

采用hermit多项式:F(x)=1.1(1-x+2x^2)exp(-\frac{x^2}{2}),产生200个训练样本,样本输入x服从[-4,4]内的均匀分布。要求训练神经网络,并绘制学习曲线。

import numpy as np

# #  生成训练数据
# x在区间【-4,4】之间均匀分布
x = np.linspace(-4, 4, 200)
# # y = 1.1(1-x+2*x^2)exp(-x^2/2) + 噪声符合均值位0,方差为0.15的正态分布
y = 1.1 * (1 - x + 2 * x ** 2) * np.exp(- x ** 2/2) + np.random.normal(loc=0, scale=0.15, size=200)

# # 测试数据
x_test= np.linspace(-4, 4, 300)
y_test = 1.1 * (1 - x_test + 2 * x_test ** 2) * np.exp(- x_test ** 2/2) + np.random.normal(loc=0, scale=0.15, size=300)

# 隐层单元数目m-h-1
N = 100

# # 双极性sigmoid函数
def fc(x):
    return (1 - np.exp(-x))/(1 + np.exp(-x))

def dfc(x):
    return 2 * np.exp(x)/(1 + np.exp(x))**2

def BP_train(X, Y, hidden_units, learning_rate, epochs):
    input = X.shape[1]
    output = Y.shape[1]
    W1 = np.random.randn(input, hidden_units)
    b1 = np.random.randn(hidden_units)
    W2 = np.random.randn(hidden_units, output)
    b2 = np.random.randn(output)

    # 批处理
    for i in range(epochs):
        # 前向传播
        z1 = np.dot(X, W1) + b1
        a1 = fc(z1)
        z2 = np.dot(a1, W2) + b2
        a2 = z2

        # 反向传播
        delta2 = Y - a2
        delta1 = np.dot(delta2, W2.T) * dfc(z1)

        # 更新权重
        W2 -= learning_rate * np.dot(a1.T, delta2)
        b2 -= learning_rate * np.sum(delta2, axis=0)
        W1 -= learning_rate * np.dot(X.T, delta1)
        b1 -= learning_rate * np.sum(delta1, axis=0)

    return W1, b1, W2, b2


def BP_predict(X, W1, b1, W2, b2):
    z1 = np.dot(X, W1) + b1
    a1 = fc(z1)
    z2 = np.dot(a1, W2) + b2
    a2 = z2
    return a2

# # 训练
X = x.reshape(-1, 1)
Y = y.reshape(-1, 1)
W1, b1, W2, b2 = BP_train(X, Y, N, 0.01, 10000)

# # 预测
X_test = x_test.reshape(-1, 1)
Y_test = y_test.reshape(-1, 1)
Y_pred = BP_predict(X_test, W1, b1, W2, b2)

# # 画两个子图,一个是学习曲线,一个是预测曲线
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(x, y, 'ro', label='train')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(x_test, Y_pred, 'g-', label='predict')
plt.plot(x_test, y_test, 'b-', label='test')
plt.legend()
plt.show()

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值