基于神经网络的预测模型:Python代码实现
import numpy as np import pandas as pd import pickle
读取训练数据
data = pd.read_excel('C题.xlsx') X = data[['接收距离(cm)', '热风速度(r/min)']].values y = data[['厚度mm', '孔隙率(%)', '压缩回弹性率(%)']].values
定义激活函数(sigmoid函数)
def sigmoid(x): return 1 / (1 + np.exp(-x))
定义激活函数的导数
def sigmoid_derivative(x): return x * (1 - x)
初始化权重和偏置
np.random.seed(0) weights1 = 2 * np.random.random((2, 4)) - 1 weights2 = 2 * np.random.random((4, 3)) - 1 bias1 = np.zeros((1, 4)) bias2 = np.zeros((1, 3))
定义训练迭代次数和学习率
epochs = 10000 learning_rate = 0.1
训练模型
for i in range(epochs): # 前向传播 layer1_output = sigmoid(np.dot(X, weights1) + bias1) layer2_output = sigmoid(np.dot(layer1_output, weights2) + bias2)
# 计算误差
layer2_error = y - layer2_output
if i % 1000 == 0:
print('Error after', i, 'epochs:', np.mean(np.abs(layer2_error)))
# 反向传播
layer2_delta = layer2_error * sigmoid_derivative(layer2_output)
layer1_error = layer2_delta.dot(weights2.T)
layer1_delta = layer1_error * sigmoid_derivative(layer1_output)
# 更新权重和偏置
weights2 += layer1_output.T.dot(layer2_delta) * learning_rate
bias2 += np.sum(layer2_delta, axis=0, keepdims=True) * learning_rate
weights1 += X.T.dot(layer1_delta) * learning_rate
bias1 += np.sum(layer1_delta, axis=0, keepdims=True) * learning_rate
保存模型
model = { 'weights1': weights1, 'weights2': weights2, 'bias1': bias1, 'bias2': bias2 } with open('model.pkl', 'wb') as file: pickle.dump(model, file)
读取新数据
pre_data = pd.read_excel('预测数据.xlsx') X_pre = pre_data[['接收距离(cm)', '热风速度(r/min)']].values
加载模型
with open('model.pkl', 'rb') as file: model = pickle.load(file)
weights1 = model['weights1'] weights2 = model['weights2'] bias1 = model['bias1'] bias2 = model['bias2'] layer1_output_pre = sigmoid(np.dot(X_pre, weights1) + bias1) layer2_output_pre = sigmoid(np.dot(layer1_output_pre, weights2) + bias2)
print('Predicted Output:') print(layer2_output_pre)
原文地址: https://www.cveoy.top/t/topic/qqA9 著作权归作者所有。请勿转载和采集!