当前位置:   article > 正文

基于机器学习和深度学习的轴承故障诊断方法(Python)_机器学习故障诊断

机器学习故障诊断

在工业早期,设备故障诊断通常由专家通过观察设备运行中的变量参数并结合自身知识进行诊断。但相比传统的机理分析方法,数据驱动的智能设备故障诊断更能充分提取数据中隐含的故障征兆、因果逻辑等关系。智能设备故障诊断的优势表现在其对海量、多源、高维数据进行统计分析和信息提取的直接性和有效性。该技术以采集不同来源、不同类型的监测数据作为基底,利用各种数据挖掘技术获取其中隐含的有用信息,表征系统运行的模式和状态,进而达到检测与诊断的目的。整体诊断过程可分为信号获取、特征工程、故障分类3个模块。

信号获取负责对检测数据进行采样分段,特征工程用于提取数据特征,最后通过故障分类模块对设备故障状态进行诊断。智能设备故障诊断方法的性能极大地依赖于所提取的特征质量,即数据的表示学习能力,而传统的特征学习方法存在以下4个方面的不足:(1)特征提取方法的设计依赖专家对该领域的先验信息、专业知识和深厚的数学基础。(2)特征提取能力有限,模型提取的大多是浅层特征,在面对复杂分类问题时,其泛化能力受到一定制约。(3)特征提取方法健壮性弱,容易受机械系统的物理特性和故障条件变化影响而改变模型组件以及评价标准。(4)不能提取未知特征,特征提取源于已有特征和评估标准,对新特征的挖掘具有局限性。

程序运行环境为Python,采用tensorflow,keras和sklearn等模块,执行基于机器学习和深度学习模型的滚动轴承故障诊断。主要内容包括:

[1]基于一维深度残差收缩网络DRSN的轴承故障诊断

[2]基于蝴蝶优化算法优化支持向量机的轴承故障诊断

[3]基于门控循环单元GRU,Inception网络,LSTM网络,随机森林的轴承故障诊断。

Inception网络为例,运行代码如下:

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

图片

图片

图片

工学博士,担任《Mechanical System and Signal Processing》《中国电机工程学报》《控制与决策》等期刊审稿专家,擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

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

闽ICP备14008679号