cnn实现一维震动信号故障诊断

cnn实现一维震动信号故障诊断

import os
os.environ[‘TF_CPP_MIN_LOG_LEVEL’] = ‘2’
import numpy as np
import scipy.io as sio
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import xlrd
from openpyxl import Workbook

以交互式方式启动session

如果不使用交互式session,则在启动session前必须构建整个计算图,才能启动该计算图

#sess = tf.InteractiveSession()

data = sio.loadmat(‘ballfault_DE.mat’)
sensorlenth=2048*36
condition=4#工况数
classification=10#类别
L=2048#网络输入长度
evfisam_num=int(sensorlenth/L)

evfitrain_num=int(evfisam_num3/4)#每个工况用于训练的样本数
evfitest_num=evfisam_num-evfitrain_num#每个工况用于测试的样本数
div=1
C=4
al=512
evdoctrain_num=condition
(evfitrain_num-1)C
evdoctest_num=condition
evfitest_num#类别数×工况数×每个文件的样本数
batch_num=int(evdoctrain_num/div)
train_num=evdoctrain_numclassification
test_num=evfitest_num
condition*classification

cnn_train=np.zeros((train_num,L))
cnn_test=np.zeros((test_num,L))
sensor_1=data[‘ballfault’]
for i in range(classification*condition):
sensor=sensor_1[0:sensorlenth,i]

cnn_train_1=sensor[0:L*evfitrain_num]

for j in range(C):#数据增强C次
	cnn_train[(i*C+j)*(evfitrain_num-1):(i*C+j+1)*(evfitrain_num-1),:]=cnn_train_1[j*al:(evfitrain_num-1)*L+j*al].reshape((evfitrain_num-1),L)

cnn_test_1=sensor[L*evfitrain_num:evfisam_num*L]
cnn_test[i*evfitest_num:(i+1)*evfitest_num,:]=cnn_test_1[0:evfitest_num*L].reshape(evfitest_num,L)

lable_train=np.zeros(train_num)
lable_test=np.zeros(test_num)
for num_dir in range(0,classification):
lable_train[num_dir*evdoctrain_num:(num_dir+1)*evdoctrain_num]=(num_dir+1)np.ones(evdoctrain_num)
lable_test[num_dir
evdoctest_num:(num_dir+1)*evdoctest_num]=(num_dir+1)*np.ones(evdoctest_num)

expect_y=np.zeros((train_num,classification))
m=0
for l in lable_train:
expect_y[m,int(l-1)]=1
m+=1

test_expect_y=np.zeros((test_num,classification))
m=0
for l in lable_test:
test_expect_y[m,int(l-1)]=1
m+=1

merge = np.append(cnn_train,expect_y,axis=1)
np.random.shuffle(merge)#tf.random_shuffle(a)
cnn_train=merge[:,0:L]
expect_y=merge[:,L:L+classification]

kernel_length1=16
kernel_length2=10
kernel_length3=8
kernel_length4=6
kernel_length5=16
kernel_length6=10
kernel_length7=8
kernel_length8=6
#L_1=int((L-kernel_length1+1)/4)
#L_2=int((L_1-kernel_length2+1)/4)
#L_3=int((L_2-kernel_length3+1)/4)
B=np.power(2,8)
L_end=int(L/B)

kernel_num_1=8
kernel_num_2=16
kernel_num_3=9
kernel_num_4=12
kernel_num_5=8
kernel_num_6=16
kernel_num_7=9
kernel_num_8=12

out_num=100

“”“构建计算图”""

通过占位符来为输入图像和目标输出类别创建节点

shape参数是可选的,有了它tensorflow可以自动捕获维度不一致导致的错误

initial_input = tf.placeholder(“float”, shape=[None, L]) # 原始输入
initial_y = tf.placeholder(“float”, shape=[None, classification]) # 目标值

为了不在建立模型的时候反复做初始化操作,

我们定义两个函数用于初始化

def weight_variable(shape):
# 截尾正态分布,stddev是正态分布的标准偏差
initial = tf.truncated_normal(shape=shape, stddev=0.05)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)

卷积核池化,步长为1,0边距

def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=‘SAME’)
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 1, 2, 1], strides=[1, 1, 2, 1], padding=‘SAME’)

“”“第一层卷积”""

由一个卷积和一个最大池化组成。滤波器1x16中算出32个特征,是因为使用32个滤波器进行卷积

卷积的权重张量形状是[1, 16, 1, 32],1是输入通道的个数,32是输出通道个数

W_conv1 = weight_variable([1, kernel_length1, 1, kernel_num_1])

每一个输出通道都有一个偏置量

b_conv1 = bias_variable([kernel_num_1])

位了使用卷积,必须将输入转换成4维向量,2、3维表示图片的宽、高

最后一维表示图片的颜色通道(因为是灰度图像所以通道数维1,RGB图像通道数为3)

process_image = tf.reshape(initial_input, [-1, 1, L, 1])

第一层的卷积结果,使用Relu作为激活函数

h_conv1 = tf.nn.relu(conv2d(process_image, W_conv1)+b_conv1)

第一层卷积后的池化结果

h_pool1 = max_pool_2x2(h_conv1)

“”“第二层卷积”""
W_conv2 = weight_variable([1, kernel_length2, kernel_num_1, kernel_num_2])
b_conv2 = bias_variable([kernel_num_2])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

“”“第三层卷积”""
W_conv3 = weight_variable([1, kernel_length3, kernel_num_2, kernel_num_3])
b_conv3 = bias_variable([kernel_num_3])
h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)
h_pool3 = max_pool_2x2(h_conv3)

“”“第四层卷积”""
W_conv4 = weight_variable([1, kernel_length4, kernel_num_3, kernel_num_4])
b_conv4 = bias_variable([kernel_num_4])
h_conv4 = tf.nn.relu(conv2d(h_pool3, W_conv4) + b_conv4)
h_pool4 = max_pool_2x2(h_conv4)

“”“第五层卷积”""
W_conv5 = weight_variable([1, kernel_length5, kernel_num_4, kernel_num_5])
b_conv5 = bias_variable([kernel_num_5])
h_conv5 = tf.nn.relu(conv2d(h_pool4, W_conv5) + b_conv5)
h_pool5 = max_pool_2x2(h_conv5)

“”“第六层卷积”""
W_conv6 = weight_variable([1, kernel_length6, kernel_num_5, kernel_num_6])
b_conv6 = bias_variable([kernel_num_6])
h_conv6 = tf.nn.relu(conv2d(h_pool5, W_conv6) + b_conv6)
h_pool6 = max_pool_2x2(h_conv6)

“”“第七层卷积”""
W_conv7 = weight_variable([1, kernel_length7, kernel_num_6, kernel_num_7])
b_conv7 = bias_variable([kernel_num_7])
h_conv7 = tf.nn.relu(conv2d(h_pool6, W_conv7) + b_conv7)
h_pool7 = max_pool_2x2(h_conv7)

“”“第八层卷积”""
W_conv8 = weight_variable([1, kernel_length8, kernel_num_7, kernel_num_8])
b_conv8 = bias_variable([kernel_num_8])
h_conv8 = tf.nn.relu(conv2d(h_pool7, W_conv8) + b_conv8)
h_pool8 = max_pool_2x2(h_conv8)

“”“全连接层”""
W_fc1 = weight_variable([int(L_end*kernel_num_8), out_num])
b_fc1 = bias_variable([out_num])

将最后的池化层输出张量reshape成一维向量

h_pool8_flat = tf.reshape(h_pool8, [-1, int(L_end*kernel_num_8)])

全连接层的输出

h_fc1 = tf.nn.relu(tf.matmul(h_pool8_flat, W_fc1) + b_fc1)
“”“使用Dropout减少过拟合”""

使用placeholder占位符来表示神经元的输出在dropout中保持不变的概率

在训练的过程中启用dropout,在测试过程中关闭dropout

keep_prob = tf.placeholder(“float”)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
“”“输出层”""
W_fc2 = weight_variable([out_num, classification])
b_fc2 = bias_variable([classification])

模型预测输出

yconv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

交叉熵损失

cross_entropy_1=tf.reduce_sum(initial_y * yconv,1)
cross_entropy = -tf.reduce_sum(tf.log(cross_entropy_1))/train_num

模型训练,使用AdamOptimizer来做梯度最速下降

train_step = tf.train.AdamOptimizer(0.00015).minimize(cross_entropy)

正确预测,得到True或False的List

correct_prediction = tf.equal(tf.argmax(yconv, 1), tf.argmax(initial_y, 1))

将布尔值转化成浮点数,取平均值作为精确度

accuracy = tf.reduce_mean(tf.cast(correct_prediction, “float”))
init=tf.global_variables_initializer()

迭代优化模型

with tf.Session() as sess:
sess.run(init)
for i in range(300):
k=0
while (kdiv):
a=cnn_train[kbatch_num:(k+1)batch_num]
b=expect_y[k
batch_num:(k+1)*batch_num]
#if (i+1)%10 == 0:
#print(“test accuracy: %g” % accuracy.eval(feed_dict={initial_input: cnn_test,initial_y: test_expect_y, keep_prob: 1.0}))
train_step.run(feed_dict={initial_input: a, initial_y: b, keep_prob: 0.5})
#print(sess.run(cross_entropy,feed_dict={initial_input: a, initial_y: b, keep_prob: 1.0}))
k+=1
print(“accurate: %g” % sess.run(accuracy,feed_dict={initial_input: a, initial_y: b, keep_prob: 1.0}))

注:如何将全连接h_fc1的矩阵保存到本地??????

你可能感兴趣的:(cnn实现一维震动信号故障诊断)