Python环境下基于机器学习和深度学习的轴承故障诊断方法

发布于:2024-03-29 ⋅ 阅读:(24) ⋅ 点赞:(0)

旋转机械作为机械传动系统中的关键部件,是设备发生故障的常见部位。对于轴承、齿轮、轴等旋转机械,国内外学者提出了许多故障诊断方法。这些方法大致可分为基于模型驱动的方法和基于数据驱动的方法两种。基于模型驱动的故障诊断方法的准确性取决于建立的数学、物理模型的准确性,如何创建旋转机械更有效的诊断模型仍是当前研究的重点。

基于数据驱动的故障诊断首先需要采集大量的设备故障信号,其次通过先进算法提取信号中的故障特征,最后对故障特征进行识别。基于振动信号的故障诊断是当前研究中最为广泛的。局部平均分解、小波变换、主成分分析方法、Wigner分布、EMD经验模态分解等基于振动信号的故障诊断方法已经被证明是较为有效的方法,但上述基于传统信号分析的方法往往存在以下问题:(1)信号特征提取依赖于人员的专业知识;(2)从高维数据中提取低维特征将不可避免的导致部分信息缺失。基于深度学习的算法可能是解决此类问题的有效方法。

基于深度学习的故障诊断方法通过高质量的故障数据集来训练算法模型,通过各层网络间的权重以及偏置来拟合故障数据模型,最后通过损失函数不断强化算法模型对数据分布规律的感知以及学习能力,从而创建出高效、准确的故障识别模型。与基于传统信号分析的故障诊断方法相比,深度学习模型效率以及准确率更高。

鉴于此,本项目采用机器学习和深度学习模型对滚动轴承进行故障诊断,数据集为西储大学轴承数据集,程序运行环境为Python,采用tensorflow,keras和sklearn等模块,执行基于机器学习和深度学习模型的轴承故障诊断。主要内容包括:

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

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

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

所用主要模块的版本如下:

tensorflow=2.8.0
keras=2.8.0
sklearn=1.0.2

以基于GRU的轴承故障诊断为例,代码如下:

from time import sleep
from tensorflow import keras
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)

x_train = tf.reshape(x_train, (len(x_train), 49, 16))
x_valid = tf.reshape(x_valid, (len(x_valid), 49, 16))
x_test = tf.reshape(x_test, (len(x_test), 49, 16))


# 模型定义
def mymodel():
    inputs = keras.Input(shape=(x_train.shape[1], x_train.shape[2]))

    h1 = layers.GRU(32, return_sequences=False, activation='relu')(inputs)
    h1 = layers.Dense(10, activation='softmax')(h1)

    deep_model = keras.Model(inputs, h1, name="cnn")
    return deep_model

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_gru.h5')])

#加载模型
model.load_weights(filepath='best_sign_gru.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()

完整代码可由知乎学术咨询获得或面包多官网下载

https://www.toutiao.com/article/7350462797958693412/?log_from=a69df7404d8a2_1711414971730

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

本文含有隐藏内容,请 开通VIP 后查看