使用卷积神经网络预测之后输出了实际与预测的曲线图,我想知道实际与预测的在图中的具体的点的坐标,如何将其输出。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Conv1D, MaxPooling1D, Flatten, Dense
1.
#数据清洗
data = pd.read_csv('zhendaorushuju.csv', encoding='gb18030')
2.
#特征选择
features = ['Nb%', 'Ti%', 'AL%', 'V%', 'Cr%', 'Mo%', 'C%', 'Mn%', 'P%', 'Ni%', 'Cu%', 'Si%', 'S%', '奥氏体化温度0℃',
'油冷时间0min', '保温时间0min', '上下窜动时间0min', '回火0退火温度0℃', '保温时间0min']
X = data[features]
y = data['硬度']
3.
#特征缩放
scaler = MinMaxScaler()
X = scaler.fit_transform(X)
4.
#数据划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=400)
5.
#重塑数据为三维数组
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
6.
#构建卷积神经网络模型
model = Sequential()
model.add(Conv1D(filters=33, kernel_size=6, activation='relu', input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(MaxPooling1D(pool_size=1))
model.add(Flatten())
model.add(Dense(2000, activation='relu'))
model.add(Dense(1))
7.
#编译模型
model.compile(optimizer='adam', loss='mse')
8.
#训练模型
history = model.fit(X_train, y_train, epochs=78, batch_size=6, validation_data=(X_test, y_test), verbose=0)
9.
#评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score)
10.
#使用模型进行预测
y_pred = model.predict(X_test)
11.
#绘制预测结果与真实结果的对比图
plt.plot(y_test.values, label='true')
plt.plot(y_pred, label='pred')
plt.legend()
plt.show()
可以使用matplotlib库进行输出。可以使用matplotlib.pyplot.plot函数输出曲线图,matplotlib.pyplot.get_lines函数用来获取xdata和ydata数据,用于表示实际与预测在图中的具体点的坐标。例如:
import matplotlib.pyplot as plt
# plot the line chart
plt.plot(x_data, y_data)
# get the coordinates of each point
lines = plt.get_lines()
# loop through all lines
for line in lines:
x_points = line.get_xdata()
y_points = line.get_ydata()
print('x points: %s, y points: %s' % (x_points, y_points))
# show the line chart
plt.show()
我们假设温度的时间序列是连续的,并且每天的温度是周期性变化的。这种情况下,可以大胆假设未来 24 小时的温度等于当前的温度。
我们就以此基于常识的非机器学习方法作为基准,用平均绝对误差(MAE)为指标来评估衡量它:
mae = np.mean(np.abs(preds - targets))
我们之后做的机器学习模型应该超过这个基准,才能说明机器学习是有效的。
# 计算基于常识的基准方法的 MAE
def evaluate_naive_method():
batch_maes = []
for step in range(val_steps):
samples, targets = next(val_gen)
preds = samples[:, -1, 1]
mae = np.mean(np.abs(preds - targets))
batch_maes.append(mae)
return np.mean(batch_maes)
mae = evaluate_naive_method()
celsius_mae = mae * std[1]
print(f'mae={mae}, 温度的平均绝对误差={celsius_mae}°C')
mae=0.2897359729905486, 温度的平均绝对误差=2.564887434980494°C
这个误差还是比较大的,所以接下来的目标就是用深度学习的方法来超过这个基准。