请使用python语言写一个使用bp神经网络进行混凝土强度预测的代码,要求输出预测图,求得平均绝对误差、平均绝对百分误差和均方根误差等评价指标。
时间: 2024-03-05 13:53:57 浏览: 63
好的,以下是一个使用BP神经网络进行混凝土强度预测的Python代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 构造训练数据
x_train = np.array([[0.1, 0.2, 0.3], [0.2, 0.3, 0.4], [0.3, 0.4, 0.5], [0.4, 0.5, 0.6], [0.5, 0.6, 0.7], [0.6, 0.7, 0.8], [0.7, 0.8, 0.9], [0.8, 0.9, 1.0]])
y_train = np.array([2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0])
# 构造测试数据
x_test = np.array([[0.15, 0.25, 0.35], [0.25, 0.35, 0.45], [0.35, 0.45, 0.55], [0.45, 0.55, 0.65], [0.55, 0.65, 0.75], [0.65, 0.75, 0.85], [0.75, 0.85, 0.95], [0.85, 0.95, 1.05]])
y_test = np.array([2.75, 3.25, 3.75, 4.25, 4.75, 5.25, 5.75, 6.25])
# 定义激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络模型
class BPNN:
def __init__(self, input_size, hidden_size, output_size, learning_rate):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.learning_rate = learning_rate
self.W1 = np.random.randn(input_size, hidden_size)
self.b1 = np.zeros((1, hidden_size))
self.W2 = np.random.randn(hidden_size, output_size)
self.b2 = np.zeros((1, output_size))
def forward(self, x):
self.z1 = np.dot(x, self.W1) + self.b1
self.a1 = sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.W2) + self.b2
self.y = self.z2
def backward(self, x, y_true):
delta2 = self.y - y_true
dW2 = np.dot(self.a1.T, delta2)
db2 = np.sum(delta2, axis=0)
delta1 = np.dot(delta2, self.W2.T) * self.a1 * (1 - self.a1)
dW1 = np.dot(x.T, delta1)
db1 = np.sum(delta1, axis=0)
self.W2 -= self.learning_rate * dW2
self.b2 -= self.learning_rate * db2
self.W1 -= self.learning_rate * dW1
self.b1 -= self.learning_rate * db1
def train(self, x, y, epochs):
self.losses = []
for i in range(epochs):
self.forward(x)
loss = np.mean((self.y - y) ** 2)
self.losses.append(loss)
self.backward(x, y)
def predict(self, x):
self.forward(x)
return self.y
# 创建BP神经网络模型
bpnn = BPNN(3, 5, 1, 0.1)
# 训练模型
bpnn.train(x_train, y_train, epochs=1000)
# 使用测试数据进行预测
y_pred = bpnn.predict(x_test)
# 输出评价指标
mae = np.mean(np.abs(y_pred - y_test))
mape = np.mean(np.abs(y_pred - y_test) / y_test)
rmse = np.sqrt(np.mean((y_pred - y_test) ** 2))
print('MAE:', mae)
print('MAPE:', mape)
print('RMSE:', rmse)
# 绘制预测图
plt.plot(y_test, label='true')
plt.plot(y_pred, label='pred')
plt.legend()
plt.show()
```
注:以上代码中使用的训练数据和测试数据都是人工构造的,实际应用中需要根据实际数据进行调整。
阅读全文