基于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等。

相关推荐
qyr67892 分钟前
深度解析:3D细胞培养透明化试剂供应链与主要制造商分布
大数据·人工智能·3d·市场分析·市场报告·3d细胞培养·细胞培养
软件开发技术深度爱好者2 分钟前
浅谈人工智能(AI)对个人发展的影响
人工智能
一路向北he7 分钟前
esp32 arduino环境的搭建
人工智能
SmartBrain16 分钟前
Qwen3-VL 模型架构及原理详解
人工智能·语言模型·架构·aigc
renhongxia121 分钟前
AI算法实战:逻辑回归在风控场景中的应用
人工智能·深度学习·算法·机器学习·信息可视化·语言模型·逻辑回归
民乐团扒谱机29 分钟前
【AI笔记】精密光时频传递技术核心内容总结
人工智能·算法·光学频率梳
不惑_41 分钟前
通俗理解GAN的训练过程
人工智能·神经网络·生成对抗网络
OpenCSG1 小时前
对比分析:CSGHub vs. Hugging Face:模型管理平台选型对
人工智能·架构·开源
云上凯歌2 小时前
传统老旧系统的“AI 涅槃”:从零构建企业级 Agent 集群实战指南
人工智能
cskywit2 小时前
破解红外“魅影”难题:WMRNet 如何以频率分析与二阶差分重塑小目标检测?
人工智能·深度学习