import numpy as np\nimport pandas as pd\nimport pickle\n\n# 读取训练数据\ndata = pd.read_excel('C题.xlsx')\nX = data[['接收距离(cm)', '热风速度(r/min)']].values\ny = data[['厚度mm', '孔隙率(%)', '压缩回弹性率(%)']].values\n\n# 定义激活函数(sigmoid函数)\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n# 定义激活函数的导数\ndef sigmoid_derivative(x):\n return x * (1 - x)\n\n# 初始化权重和偏置\np.random.seed(0)\nweights1 = 2 * np.random.random((2, 4)) - 1\nweights2 = 2 * np.random.random((4, 3)) - 1\nbias1 = np.zeros((1, 4))\nbias2 = np.zeros((1, 3))\n\n# 定义训练迭代次数和学习率\nepochs = 10000\nlearning_rate = 0.1\n\n# 训练模型\nfor i in range(epochs):\n # 前向传播\n layer1_output = sigmoid(np.dot(X, weights1) + bias1)\n layer2_output = sigmoid(np.dot(layer1_output, weights2) + bias2)\n\n # 计算误差\n layer2_error = y - layer2_output\n if i % 1000 == 0:\n print('Error after', i, 'epochs:', np.mean(np.abs(layer2_error)))\n\n # 反向传播\n layer2_delta = layer2_error * sigmoid_derivative(layer2_output)\n layer1_error = layer2_delta.dot(weights2.T)\n layer1_delta = layer1_error * sigmoid_derivative(layer1_output)\n\n # 更新权重和偏置\n weights2 += layer1_output.T.dot(layer2_delta) * learning_rate\n bias2 += np.sum(layer2_delta, axis=0, keepdims=True) * learning_rate\n weights1 += X.T.dot(layer1_delta) * learning_rate\n bias1 += np.sum(layer1_delta, axis=0, keepdims=True) * learning_rate\n\n# 测试模型\ntest_data = pd.read_excel('C题.xlsx')\nX_test = test_data[['接收距离(cm)', '热风速度(r/min)']].values\ny_true = test_data[['厚度mm', '孔隙率(%)', '压缩回弹性率(%)']].values\n\nlayer1_output_test = sigmoid(np.dot(X_test, weights1) + bias1)\nlayer2_output_test = sigmoid(np.dot(layer1_output_test, weights2) + bias2)\n\nprint('Predicted Output:', layer2_output_test)\nprint('True Output:', y_true)\n\n# 保存模型\nmodel = {\n 'weights1': weights1,\n 'weights2': weights2,\n 'bias1': bias1,\n 'bias2': bias2\n}\nwith open('model.pkl', 'wb') as file:\n pickle.dump(model, file)\n\n# 读取新数据\npre_data = pd.read_excel('预测数据.xlsx')\nX_pre = pre_data[['接收距离(cm)', '热风速度(r/min)']].values\n\n# 加载模型\nwith open('model.pkl', 'rb') as file:\n model = pickle.load(file)\n\nweights1 = model['weights1']\nweights2 = model['weights2']\nbias1 = model['bias1']\nbias2 = model['bias2']\nlayer1_output_pre = sigmoid(np.dot(X_pre, weights1) + bias1)\nlayer2_output_pre = sigmoid(np.dot(layer1_output_pre, weights2) + bias2)\n\nprint('Predicted Output:', layer2_output_pre)\n


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

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