当前位置:   article > 正文

基于CNN、GRU、Inception、LSTM、随机森林和SVM的轴承故障诊断

基于CNN、GRU、Inception、LSTM、随机森林和SVM的轴承故障诊断

传感器采集到振动信号后,由于其特征并不明显且可能受到噪声的影响,所以需要对信号进行处理并提取特征,以便进一步对故障进行分类。传统的故障诊断方法中,通常从时域、频域、时频域对信号进行特征提取。

但时域、频域、时频域特征提取方法均需要通过人工提取信号的故障特征,过于依赖专家经验知识,这种故障诊断方法较为传统,而实际工业中的设备数据量较大,且由于工作环境的影响,会导致信号中掺杂大量冗余噪声,这时如果使用传统的故障诊断方法,将会导致信号处理困难,特征提取不完全,耗费大量的人力资源。相较传统的故障诊断方法,结合了深度学习的故障诊断方法可以通过训练模型,自适应地从振动信号中提取特征,替代了传统故障诊断方法中的特征提取、选择和故障分类的步骤,节省了大量的人力,且故障诊断的效果优于传统方法。目前已有大量深度学习模型被应用于故障诊断领域中,例如:自动编码器、卷积神经网络CNN、循环神经网络等。

本项目采用CNN、GRU、Inception、LSTM、随机森林和SVM等模型对滚动轴承进行故障识别,数据集采用西储大学轴承数据集,运行环境为Python。

所用模块如下:

  1. from time import sleep
  2. from tensorflow import keras
  3. from OriginalVibrationSignal import ovs_preprocess
  4. from sklearn.metrics import confusion_matrix
  5. import matplotlib.pyplot as plt
  6. import random
  7. import tensorflow.keras as keras
  8. import tensorflow.keras.layers as layers
  9. from datetime import datetime
  10. import numpy as np
  11. import tensorflow as tf
  12. from sklearn.manifold import TSNE

主要模块版本如下:

  1. tensorflow=2.8.0
  2. keras=2.8.0
  3. sklearn=1.0.2
  4. Python=3.9.0

以CNN模型为例,部分代码如下:

  1. #加载相关模块
  2. from time import sleep
  3. from tensorflow import keras
  4. from OriginalVibrationSignal import ovs_preprocess
  5. from sklearn.metrics import confusion_matrix
  6. import matplotlib.pyplot as plt
  7. import random
  8. import tensorflow.keras as keras
  9. import tensorflow.keras.layers as layers
  10. from datetime import datetime
  11. import numpy as np
  12. import tensorflow as tf
  13. from sklearn.manifold import TSNE
  14. #如果是GPU,需要去掉注释,如果是CPU,则注释
  15. # gpu = tf.config.experimental.list_physical_devices(device_type='GPU')
  16. # assert len(gpu) == 1
  17. # tf.config.experimental.set_memory_growth(gpu[0], True)
  18. def subtime(date1, date2):
  19. return date2 - date1
  20. num_classes = 10 # 样本类别
  21. length = 784 # 样本长度
  22. number = 300 # 每类样本的数量
  23. normal = True # 是否标准化
  24. rate = [0.5, 0.25, 0.25] # 测试集验证集划分比例
  25. path = r'data/0HP'
  26. x_train, y_train, x_valid, y_valid, x_test, y_test = ovs_preprocess.prepro(
  27. d_path=path,
  28. length=length,
  29. number=number,
  30. normal=normal,
  31. rate=rate,
  32. enc=False, enc_step=28)
  33. x_train = np.array(x_train)
  34. y_train = np.array(y_train)
  35. x_valid = np.array(x_valid)
  36. y_valid = np.array(y_valid)
  37. x_test = np.array(x_test)
  38. y_test = np.array(y_test)
  39. print(x_train.shape)
  40. print(x_valid.shape)
  41. print(x_test.shape)
  42. print(y_train.shape)
  43. print(y_valid.shape)
  44. print(y_test.shape)
  45. y_train = [int(i) for i in y_train]
  46. y_valid = [int(i) for i in y_valid]
  47. y_test = [int(i) for i in y_test]
  48. # 打乱顺序
  49. index = [i for i in range(len(x_train))]
  50. random.seed(1)
  51. random.shuffle(index)
  52. x_train = np.array(x_train)[index]
  53. y_train = np.array(y_train)[index]
  54. index1 = [i for i in range(len(x_valid))]
  55. random.shuffle(index1)
  56. x_valid = np.array(x_valid)[index1]
  57. y_valid = np.array(y_valid)[index1]
  58. index2 = [i for i in range(len(x_test))]
  59. random.shuffle(index2)
  60. x_test = np.array(x_test)[index2]
  61. y_test = np.array(y_test)[index2]
  62. print(x_train.shape)
  63. print(x_valid.shape)
  64. print(x_test.shape)
  65. print(y_train)
  66. print(y_valid)
  67. print(y_test)
  68. print("x_train的最大值和最小值:", x_train.max(), x_train.min())
  69. print("x_test的最大值和最小值:", x_test.max(), x_test.min())
  70. x_train = tf.reshape(x_train, (len(x_train), 784, 1))
  71. x_valid = tf.reshape(x_valid, (len(x_valid), 784, 1))
  72. x_test = tf.reshape(x_test, (len(x_test), 784, 1))
  73. # 保存最佳模型
  74. class CustomModelCheckpoint(keras.callbacks.Callback):
  75. def __init__(self, model, path):
  76. self.model = model
  77. self.path = path
  78. self.best_loss = np.inf
  79. def on_epoch_end(self, epoch, logs=None):
  80. val_loss = logs['val_loss']
  81. if val_loss < self.best_loss:
  82. print("\nValidation loss decreased from {} to {}, saving model".format(self.best_loss, val_loss))
  83. self.model.save_weights(self.path, overwrite=True)
  84. self.best_loss = val_loss
  85. # t-sne初始可视化函数
  86. def start_tsne():
  87. print("正在进行初始输入数据的可视化...")
  88. x_train1 = tf.reshape(x_train, (len(x_train), 784))
  89. X_tsne = TSNE().fit_transform(x_train1)
  90. plt.figure(figsize=(10, 10))
  91. plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y_train)
  92. plt.colorbar()
  93. plt.show()
  94. start_tsne()
  95. # sleep(600000)
  96. # 模型定义
  97. def mymodel():
  98. model = mymodel()
  99. model.summary()
  100. startdate = datetime.utcnow() # 获取当前时间
  101. # 编译模型
  102. model.compile(
  103. optimizer=keras.optimizers.Adam(),
  104. loss='sparse_categorical_crossentropy',
  105. metrics=['accuracy'])
  106. history = model.fit(x_train, y_train,
  107. batch_size=256, epochs=50, verbose=1,
  108. validation_data=(x_valid, y_valid),
  109. callbacks=[CustomModelCheckpoint(
  110. model, r'best_sign_cnn.h5')])
  111. #加载模型
  112. # filepath = r'best_sign_cnn.h5'
  113. model.load_weights(filepath='best_sign_cnn.h5')
  114. # 编译模型
  115. model.compile(loss='sparse_categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])
  116. # 评估模型
  117. scores = model.evaluate(x_test, y_test, verbose=1)
  118. print('%s: %.2f%%' % (model.metrics_names[1], scores[1] * 100))
  119. y_predict = model.predict(x_test)
  120. y_pred_int = np.argmax(y_predict, axis=1)
  121. print(y_pred_int[0:5])
  122. from sklearn.metrics import classification_report
  123. print(classification_report(y_test, y_pred_int, digits=4))
  124. def acc_line():
  125. # 绘制acc和loss曲线
  126. acc = history.history['accuracy']
  127. val_acc = history.history['val_accuracy']
  128. loss = history.history['loss']
  129. val_loss = history.history['val_loss']
  130. epochs = range(len(acc)) # Get number of epochs
  131. # 画accuracy曲线
  132. plt.plot(epochs, acc, 'r', linestyle='-.')
  133. plt.plot(epochs, val_acc, 'b', linestyle='dashdot')
  134. plt.title('Training and validation accuracy')
  135. plt.xlabel("Epochs")
  136. plt.ylabel("Accuracy")
  137. plt.legend(["Accuracy", "Validation Accuracy"])
  138. plt.figure()
  139. # 画loss曲线
  140. plt.plot(epochs, loss, 'r', linestyle='-.')
  141. plt.plot(epochs, val_loss, 'b', linestyle='dashdot')
  142. plt.title('Training and validation loss')
  143. plt.xlabel("Epochs")
  144. plt.ylabel("Loss")
  145. plt.legend(["Loss", "Validation Loss"])
  146. # plt.figure()
  147. plt.show()
  148. acc_line()
  149. # 绘制混淆矩阵
  150. def confusion():
  151. y_pred_gailv = model.predict(x_test, verbose=1)
  152. y_pred_int = np.argmax(y_pred_gailv, axis=1)
  153. print(len(y_pred_int))
  154. con_mat = confusion_matrix(y_test.astype(str), y_pred_int.astype(str))
  155. print(con_mat)
  156. classes = list(set(y_train))
  157. classes.sort()
  158. plt.imshow(con_mat, cmap=plt.cm.Blues)
  159. indices = range(len(con_mat))
  160. plt.xticks(indices, classes)
  161. plt.yticks(indices, classes)
  162. plt.colorbar()
  163. plt.xlabel('guess')
  164. plt.ylabel('true')
  165. for first_index in range(len(con_mat)):
  166. for second_index in range(len(con_mat[first_index])):
  167. plt.text(first_index, second_index, con_mat[second_index][first_index], va='center', ha='center')
  168. plt.show()
  169. confusion()

出图如下:

完整代码可通过知乎学术咨询获得:

基于CNN、GRU、Inception、LSTM、随机森林和SVM的轴承故障诊断

工学博士,担任《Mechanical System and Signal Processing》审稿专家,担任《中国电机工程学报》优秀审稿专家,《控制与决策》,《系统工程与电子技术》,《电力系统保护与控制》,《宇航学报》等EI期刊审稿专家。

擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/336961
推荐阅读
相关标签
  

闽ICP备14008679号