这里我参考的博主代码
python调用tensorflow.keras搭建长短记忆型网络(LSTM)——以预测股票收盘价为例 - 爆米LiuChen - 博客园 (cnblogs.com)
数据集:我采用的是2012PHM数据集
代码实现:
1.数据预处理
手动提取了振动信号的二十三维时域与频域特征后,根据相关性分析,选取其中七维数据作为输入。这部分也可以用tsfresh工具箱实现。
对输入进行标准化;
#标准化数据集
outputCol = ['RUL']#输出列
inputCol = ['a','b','c','d','e','f','g','RUL']#输入列
X = data[inputCol]
Y = data[outputCol]
xScaler = StandardScaler()
yScaler = StandardScaler()
X = xScaler.fit_transform(X)
Y = yScaler.fit_transform(Y)
X.shape
将输入格式转换为带有时间维度的输入,LSTM的输入格式中包含时间步长:
#按时间步组成输入输出集
timeStep = 5
outStep = 1
xAll = list()
yAll = list()
#按时间步整理数据 输入数据尺寸是(timeStep,5) 输出尺寸是(outSize)
for row in range(data.shape[0]-timeStep-outStep+1):
x = X[row:row+timeStep]
y = Y[row+timeStep:row+timeStep+outStep]
xAll.append(x)
yAll.append(y)
xAll = np.array(xAll).reshape(-1,timeStep,len(inputCol))
yAll = np.array(yAll).reshape(-1,outStep)
print('输入集尺寸',xAll.shape)
print('输出集尺寸',yAll.shape)
划分测试集,标准集:
#分成测试集,训练集
#分成测试集,训练集
testRate = 0.2#测试比例
splitIndex = int(xAll.shape[0]*(1-testRate))
xTrain = xAll[:splitIndex]
xTest = xAll[splitIndex:]
yTrain = yAll[:splitIndex]
yTest = yAll[splitIndex:]
2.建立LSTM模型
def buildLSTM(timeStep,inputColNum,outStep,learnRate=1e-4):
'''
搭建LSTM网络,激活函数为tanh
timeStep:输入时间步
inputColNum:输入列数
outStep:输出时间步
learnRate:学习率
'''
#输入层
inputLayer = Input(shape=(timeStep,inputColNum))
#中间层
middle = LSTM(100,activation='tanh')(inputLayer)
middle = Dense(100,activation='tanh')(middle)
#输出层 全连接
outputLayer = Dense(outStep)(middle)
#建模
model = Model(inputs=inputLayer,outputs=outputLayer)
optimizer = Adam(lr=learnRate)
model.compile(optimizer=optimizer,loss='mse')
model.summary()
return model
#搭建LSTM
lstm = buildLSTM(timeStep=timeStep,inputColNum=len(inputCol),outStep=outStep,learnRate=1e-4)
最终预测效果:
这是我初步用LSTM实现寿命预测问题,问题很多。用上一个时间步进行训练很容易造成滑移问题,且无实际价值。应当提取特征后建立健康指标,划分失效状态后处理。就相当于在这里记录下学习进展。