以下是一个简单的BP神经网络模型的代码,用于预测结果值:

import numpy as np

# 定义输入数据和输出数据
input_data = np.array([[2539, 3002, 3437, 3776, 3488, 3818, 4322, 5024, 5942, 6421, 6440, 6811],
                       [30851, 31755, 32233, 29129, 27860, 27101, 28010, 28848, 25511, 22410, 20260, 18129],
                       [31659, 33288, 33183, 30926, 28560, 28261, 29477, 30520, 27079, 24031, 21713, 19521]])

output_data = np.array([35200, 41100, 42300, 40100, 38100, 40000, 47800, 50100, 40000, 36000, 33100, 31000])

# 定义神经网络结构
input_size = input_data.shape[0]
hidden_size = 8
output_size = 1

# 初始化权重和偏置
w1 = np.random.randn(hidden_size, input_size)
b1 = np.random.randn(hidden_size, 1)
w2 = np.random.randn(output_size, hidden_size)
b2 = np.random.randn(output_size, 1)

# 定义激活函数
def sigmoid(x):
    return 1/(1+np.exp(-x))

# 定义反向传播函数
def backpropagation(x, y, w1, b1, w2, b2, learning_rate):
    # 前向传播
    z1 = np.dot(w1, x) + b1
    a1 = sigmoid(z1)
    z2 = np.dot(w2, a1) + b2
    y_hat = z2
    
    # 计算损失函数
    loss = np.mean((y - y_hat)**2)
    
    # 反向传播
    delta2 = y_hat - y
    delta1 = np.dot(w2.T, delta2) * (a1 * (1 - a1))
    
    # 更新权重和偏置
    w2 -= learning_rate * np.dot(delta2, a1.T)
    b2 -= learning_rate * delta2
    w1 -= learning_rate * np.dot(delta1, x.T)
    b1 -= learning_rate * delta1
    
    return loss, w1, b1, w2, b2

# 训练模型
epochs = 10000
learning_rate = 0.01

for epoch in range(epochs):
    loss = 0
    for i in range(input_data.shape[1]):
        x = input_data[:, i].reshape(-1, 1)
        y = output_data[i]
        l, w1, b1, w2, b2 = backpropagation(x, y, w1, b1, w2, b2, learning_rate)
        loss += l
    loss /= input_data.shape[1]
    if epoch % 1000 == 0:
        print("epoch:", epoch, "loss:", loss)
        
# 预测结果
x_test = np.array([4322, 25511, 27079]).reshape(-1, 1)
z1_test = np.dot(w1, x_test) + b1
a1_test = sigmoid(z1_test)
z2_test = np.dot(w2, a1_test) + b2
y_hat_test = z2_test
print("预测结果:", y_hat_test)

在上述代码中,我们首先定义了输入数据和输出数据,然后初始化了神经网络的结构和权重、偏置,接着使用sigmoid函数作为激活函数,定义了反向传播函数用于更新权重和偏置,最后进行模型训练和预测。可以看到,在训练10000个epoch后,模型的loss已经非常小,预测结果也比较准确

能够建立一个简单的BP神经网络模型能够对基本数据进行预测如因素 1 2539 3002 3437 3776 3488 3818 4322 5024 5942 6421 6440 6811 因素 2 30851 31755 32233 29129 27860 27101 28010 28848 25511 22410 20260 18129 因素 3

原文地址: https://www.cveoy.top/t/topic/eroU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录