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_num*3/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_num*classification
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 (k<classification*div):
a=cnn_train[k*batch_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}))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/79425.html
上一篇:小白求教python
