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

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

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

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

所用模块如下:

from time import sleep
from tensorflow import keras
from OriginalVibrationSignal import ovs_preprocess
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import random
import tensorflow.keras as keras
import tensorflow.keras.layers as layers
from datetime import datetime
import numpy as np
import tensorflow as tf
from sklearn.manifold import TSNE

主要模块版本如下:

tensorflow=2.8.0
keras=2.8.0
sklearn=1.0.2
Python=3.9.0

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

#加载相关模块
from time import sleep
from tensorflow import keras
from OriginalVibrationSignal import ovs_preprocess
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import random
import tensorflow.keras as keras
import tensorflow.keras.layers as layers
from datetime import datetime
import numpy as np
import tensorflow as tf
from sklearn.manifold import TSNE

#如果是GPU,需要去掉注释,如果是CPU,则注释
# gpu = tf.config.experimental.list_physical_devices(device_type='GPU')
# assert len(gpu) == 1
# tf.config.experimental.set_memory_growth(gpu[0], True)

def subtime(date1, date2):
    return date2 - date1


num_classes = 10    # 样本类别
length = 784        # 样本长度
number = 300  # 每类样本的数量
normal = True  # 是否标准化
rate = [0.5, 0.25, 0.25]  # 测试集验证集划分比例

path = r'data/0HP'
x_train, y_train, x_valid, y_valid, x_test, y_test = ovs_preprocess.prepro(
    d_path=path,
    length=length,
    number=number,
    normal=normal,
    rate=rate,
    enc=False, enc_step=28)

x_train = np.array(x_train)
y_train = np.array(y_train)
x_valid = np.array(x_valid)
y_valid = np.array(y_valid)
x_test = np.array(x_test)
y_test = np.array(y_test)


print(x_train.shape)
print(x_valid.shape)
print(x_test.shape)
print(y_train.shape)
print(y_valid.shape)
print(y_test.shape)


y_train = [int(i) for i in y_train]
y_valid = [int(i) for i in y_valid]
y_test = [int(i) for i in y_test]

# 打乱顺序
index = [i for i in range(len(x_train))]
random.seed(1)
random.shuffle(index)
x_train = np.array(x_train)[index]
y_train = np.array(y_train)[index]

index1 = [i for i in range(len(x_valid))]
random.shuffle(index1)
x_valid = np.array(x_valid)[index1]
y_valid = np.array(y_valid)[index1]

index2 = [i for i in range(len(x_test))]
random.shuffle(index2)
x_test = np.array(x_test)[index2]
y_test = np.array(y_test)[index2]

print(x_train.shape)
print(x_valid.shape)
print(x_test.shape)
print(y_train)
print(y_valid)
print(y_test)
print("x_train的最大值和最小值:", x_train.max(), x_train.min())
print("x_test的最大值和最小值:", x_test.max(), x_test.min())

x_train = tf.reshape(x_train, (len(x_train), 784, 1))
x_valid = tf.reshape(x_valid, (len(x_valid), 784, 1))
x_test = tf.reshape(x_test, (len(x_test), 784, 1))


# 保存最佳模型
class CustomModelCheckpoint(keras.callbacks.Callback):
    def __init__(self, model, path):
        self.model = model
        self.path = path
        self.best_loss = np.inf

    def on_epoch_end(self, epoch, logs=None):
        val_loss = logs['val_loss']
        if val_loss < self.best_loss:
            print("\nValidation loss decreased from {} to {}, saving model".format(self.best_loss, val_loss))
            self.model.save_weights(self.path, overwrite=True)
            self.best_loss = val_loss

# t-sne初始可视化函数
def start_tsne():
    print("正在进行初始输入数据的可视化...")
    x_train1 = tf.reshape(x_train, (len(x_train), 784))
    X_tsne = TSNE().fit_transform(x_train1)
    plt.figure(figsize=(10, 10))
    plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y_train)
    plt.colorbar()
    plt.show()

start_tsne()
# sleep(600000)

# 模型定义
def mymodel():
model = mymodel()

model.summary()
startdate = datetime.utcnow()  # 获取当前时间

# 编译模型
model.compile(
    optimizer=keras.optimizers.Adam(),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'])

history = model.fit(x_train, y_train,
                    batch_size=256, epochs=50, verbose=1,
                    validation_data=(x_valid, y_valid),
                    callbacks=[CustomModelCheckpoint(
  model, r'best_sign_cnn.h5')])

#加载模型
# filepath = r'best_sign_cnn.h5'
model.load_weights(filepath='best_sign_cnn.h5')
# 编译模型
model.compile(loss='sparse_categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])
# 评估模型
scores = model.evaluate(x_test, y_test, verbose=1)
print('%s: %.2f%%' % (model.metrics_names[1], scores[1] * 100))

y_predict = model.predict(x_test)
y_pred_int = np.argmax(y_predict, axis=1)
print(y_pred_int[0:5])
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred_int, digits=4))

def acc_line():
    # 绘制acc和loss曲线
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    loss = history.history['loss']
    val_loss = history.history['val_loss']

    epochs = range(len(acc))  # Get number of epochs

    # 画accuracy曲线
    plt.plot(epochs, acc, 'r', linestyle='-.')
    plt.plot(epochs, val_acc, 'b', linestyle='dashdot')
    plt.title('Training and validation accuracy')
    plt.xlabel("Epochs")
    plt.ylabel("Accuracy")
    plt.legend(["Accuracy", "Validation Accuracy"])

    plt.figure()

    # 画loss曲线
    plt.plot(epochs, loss, 'r', linestyle='-.')
    plt.plot(epochs, val_loss, 'b', linestyle='dashdot')
    plt.title('Training and validation loss')
    plt.xlabel("Epochs")
    plt.ylabel("Loss")
    plt.legend(["Loss", "Validation Loss"])
    # plt.figure()
    plt.show()


acc_line()


# 绘制混淆矩阵
def confusion():
    y_pred_gailv = model.predict(x_test, verbose=1)
    y_pred_int = np.argmax(y_pred_gailv, axis=1)
    print(len(y_pred_int))
    con_mat = confusion_matrix(y_test.astype(str), y_pred_int.astype(str))
    print(con_mat)
    classes = list(set(y_train))
    classes.sort()
    plt.imshow(con_mat, cmap=plt.cm.Blues)
    indices = range(len(con_mat))
    plt.xticks(indices, classes)
    plt.yticks(indices, classes)
    plt.colorbar()
    plt.xlabel('guess')
    plt.ylabel('true')
    for first_index in range(len(con_mat)):
        for second_index in range(len(con_mat[first_index])):
            plt.text(first_index, second_index, con_mat[second_index][first_index], va='center', ha='center')
    plt.show()
confusion()

出图如下:

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

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

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

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

相关推荐
Alluxio24 分钟前
选择Alluxio来解决AI模型训练场景数据访问的五大理由
大数据·人工智能·分布式·ai·语言模型
AIPaPerPass写论文31 分钟前
写论文去哪个网站?2024最佳五款AI毕业论文学术网站
人工智能·深度学习·chatgpt·powerpoint·ai写作
唯创知音33 分钟前
电子烟智能化创新体验:WTK6900P语音交互芯片方案,融合频谱计算、精准语音识别与流畅音频播报
人工智能·单片机·物联网·音视频·智能家居·语音识别
5pace1 小时前
PyTorch深度学习快速入门教程【土堆】基础知识篇
人工智能·pytorch·深度学习
aWty_1 小时前
机器学习--卷积神经网络(包括python实现)
人工智能·机器学习·cnn
wx7408513261 小时前
小琳AI课堂:大语言模型如何符合伦理限制
人工智能·语言模型·自然语言处理
5pace2 小时前
机器学习(西瓜书)第 14 章 概率图模型
人工智能·机器学习
Linux猿2 小时前
828华为云征文 | 云服务器Flexus X实例:部署 AgentOps,全方位监测智能体
人工智能·华为云·agent·autogen·flexus云服务器x实例·华为云服务器·agentops
Rense12 小时前
开源RK3588 AI Module7,并与Jetson Nano生态兼容的低功耗AI模块
人工智能·开源
FL16238631292 小时前
[数据集][目标检测]不同颜色的安全帽检测数据集VOC+YOLO格式7574张5类别
人工智能·yolo·目标检测