基于1DCNN(一维卷积神经网络)的机械振动故障诊断

基于1DCNN(一维卷积神经网络)的机械振动故障诊断

机械振动故障诊断最为经典的还是凯斯西储实验室的轴承故障诊断,开学一周了,上次改编鸢尾花分类的代码可用,但是并不准确。开学一周重新改编了别人的一篇代码,亲测好用。不多咧咧直接放上去(基于Tensorflow2.0)(Spyder4 软件上跑的)数据集时本人把凯西轴承实验驱动端内圈损坏尺寸0.14和0.21做的二分类,数据集中0代表的0.14而1代表的0.21具体看下面最后

# -*- coding: utf-8 -*-
"""
Created on Tue Sep  8 19:18:38 2020

@author: pc
"""
import numpy as np
import pandas as pd
import keras
from keras.models import Sequential
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils,plot_model
from sklearn.model_selection import cross_val_score,train_test_split,KFold
from sklearn.preprocessing import LabelEncoder
from keras.models import model_from_json
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
from keras.optimizers import SGD
from keras.layers import Dense, Activation, Flatten, Convolution1D, Dropout,MaxPooling1D,BatchNormalization
from keras.models import load_model
# 载入数据
df = pd.read_csv(r'C:/Users/pc/Desktop/14改.csv')
X = np.expand_dims(df.values[:, 0:1024].astype(float), axis=2)
Y = df.values[:, 1024]
 
# 湿度分类编码为数字
encoder = LabelEncoder()
Y_encoded = encoder.fit_transform(Y)
Y_onehot = np_utils.to_categorical(Y_encoded)
 
# 划分训练集,测试集
X_train, X_test, Y_train, Y_test = train_test_split(X, Y_onehot, test_size=0.3, random_state=0)
 
# 定义神经网络
def baseline_model():
    model = Sequential()
    model.add(Convolution1D(nb_filter=16, filter_length=128,strides=1, input_shape=(1024, 1),padding="same"))
    model.add(Activation('tanh'))
    model.add(MaxPooling1D(2,strides=2,padding='same'))
    #model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None))
    model.add(Convolution1D(32,3,padding='same'))
    model.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None))
    model.add(Activation('tanh'))
    model.add(MaxPooling1D(2,strides=2,padding='same'))
    
    model.add(Flatten())
    model.add(Dropout(0.3))
    model.add(Dense(60, activation='tanh'))
    model.add(Dense(2, activation='softmax'))
    print(model.summary())
    sgd = SGD(lr=0.01, nesterov=True, decay=1e-6, momentum=0.9)
    model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy'])
    return model
 
# 训练分类器
estimator = KerasClassifier(build_fn=baseline_model, epochs=3, batch_size=1, verbose=1)
history=estimator.fit(X_train, Y_train)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.plot(history.history['loss'],label=u'train_loss')
#plt.plot(history.history['val_loss'],label=u'val_loss')
plt.plot(history.history['accuracy'],label=u'train_acc')
#plt.plot(history.history['val_accuracy'],label=u'val_acc')
plt.show()
# 卷积网络可视化
def visual(model, data, num_layer=1):
     layer = keras.backend.function([model.layers[0].input], [model.layers[num_layer].output])
     f1 = layer([data])[0]
     print(f1.shape)
     num = f1.shape[-1]
     print(num)
     plt.figure(figsize=(8, 8))
     for i in range(num):
         plt.subplot(np.ceil(np.sqrt(num)), np.ceil(np.sqrt(num)), i+1)
         plt.imshow(f1[:, :, i] * 255, cmap='gray')
         plt.axis('off')
     plt.show()
 
# 混淆矩阵定义
def plot_confusion_matrix(cm, classes,title='Confusion matrix',cmap=plt.cm.jet):
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks,('good','bad'))
    plt.yticks(tick_marks,('good','bad'))
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, '{:.2f}'.format(cm[i, j]), horizontalalignment="center",color="white" if cm[i, j] > thresh else "black")
    plt.tight_layout()
    plt.ylabel('真实类别')
    plt.xlabel('预测类别')
    plt.savefig('test_xx.png', dpi=200, bbox_inches='tight', transparent=False)
    plt.show()
 
# 显示混淆矩阵
def plot_confuse(model, x_val, y_val):
    predictions = model.predict_classes(x_val)
    truelabel = y_val.argmax(axis=-1)   # 将one-hot转化为label
    conf_mat = confusion_matrix(y_true=truelabel, y_pred=predictions)
    plt.figure()
    plot_confusion_matrix(conf_mat, range(np.max(truelabel)+1))
 
# 将其模型转换为json
model_json = estimator.model.to_json()
with open('C:/Users/pc/Desktop/model', 'w')as json_file:
    json_file.write(model_json)# 权重不在json中,只保存网络结构
estimator.model.save_weights('C:/Users/pc/Desktop/model.json.h5')
 
# 加载模型用做预测
json_file = open(r'C:/Users/pc/Desktop/model')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
loaded_model.load_weights('C:/Users/pc/Desktop/model.json.h5')
print("loaded model from disk")
loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 分类准确率
print("The accuracy of the classification model:")
scores = loaded_model.evaluate(X_test, Y_test, verbose=0)
print('%s: %.2f%%' % (loaded_model.metrics_names[1], scores[1] * 100))
# 输出预测类别
predicted = loaded_model.predict(X)
predicted_label = loaded_model.predict_classes(X)
print("predicted label:\n " + str(predicted_label))
#显示混淆矩阵
plot_confuse(estimator.model, X_test, Y_test)
 
# 可视化卷积层
visual(estimator.model, X_train, 1)在这里插入代码片

运行代码会出来Loss拟合曲线、混淆矩阵、第一个卷积层可视化
基于1DCNN(一维卷积神经网络)的机械振动故障诊断_第1张图片
这个训练的图像还蛮漂亮的
基于1DCNN(一维卷积神经网络)的机械振动故障诊断_第2张图片
准确率可以通过混淆矩阵计算出来(1+1)/(1+0+1+0)=100%
即对角线相加除以每个相加
召回率100%
基于1DCNN(一维卷积神经网络)的机械振动故障诊断_第3张图片
这个图就看不懂了,看文献里,人家振动信号训练第一个卷积层出来还是振动信号曲线,然而我做出来是这个MMP了,由于要用一个框架结构做实验写小论文,所以卷积层只给一层,感兴趣的可以参考VGG16模式改造卷积层。
下面展示用保存的模型预测未知信号

# -*- coding: utf-8 -*-
"""
Created on Thu Sep 10 09:29:15 2020

@author: pc
"""

import numpy as np
import pandas as pd
import keras
from keras.models import Sequential
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils,plot_model
from sklearn.model_selection import cross_val_score,train_test_split,KFold
from sklearn.preprocessing import LabelEncoder
from keras.layers import Dense, Activation, Flatten, Convolution1D, Dropout,MaxPooling1D,BatchNormalization
from keras.models import load_model
#from keras.layers import Dense,Dropout,Flatten,Conv1D,MaxPooling1D
from keras.models import model_from_json
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
from keras.optimizers import SGD
json_file = open(r'C:/Users/pc/Desktop/model')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
loaded_model.load_weights('C:/Users/pc/Desktop/model.json.h5')
print("loaded model from disk")
loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 分类准确率
#print("The accuracy of the classification model:")
#scores = loaded_model.evaluate(X_test, Y_test, verbose=0)
#print('%s: %.2f%%' % (loaded_model.metrics_names[1], scores[1] * 100))
# 输出预测类别
a= pd.read_csv(r'C:/Users/pc/Desktop/8-4.csv')
b=np.array(a)
X=b.reshape(958,1024,1)
model=Sequential()
predicted = loaded_model.predict(X)
predicted_label = loaded_model.predict_classes(X)
print("predicted label:\n " + str(predicted_label))在这里插入代码片

嗯,得劲
下面展示数据集
训练数据集https://pan.baidu.com/s/1WVChuo5d5eNLvctXpWNfEA
密码iulk
用来预测的未知代码
https://pan.baidu.com/s/1F-DYRwdicbfArHXIezMYCA
密码a672
永久有效放心用
直接下载好将两个CSV文件拖到桌面即可使用
数据集最后一行是标签,0代表0.14,1代表0.21
跑代码过程中可能会遇到的问题就是缺少插件报错误,这种情况就直接CSDN上搜索相关解决办法把
毕竟作为一个双非研究生,导师出国留学未归的情况下缺乏指导,技术有限
上次发完帖子有感兴趣的加我微信了,聊了半天感觉自己好牛逼哈哈哈哈哈哈哈哈哈哈
这个代码也是我无意间找到的,经过修改可以运行了
关于如何研究模型的抗噪声能力,等有机会了再写一篇CSDN,虽然已经做了,但是不太理想,故此还需要研究研究网络结构和参数调整。本人邮箱[email protected]

你可能感兴趣的:(深度学习,tensorflow)