1. 程式人生 > >機器學習與Tensorflow(6)——LSTM的Tensorflow實現、Tensorboard簡單實現、CNN應用

機器學習與Tensorflow(6)——LSTM的Tensorflow實現、Tensorboard簡單實現、CNN應用

最近寫的一些程式以及做的一個關於軸承故障診斷的程式

最近學習進度有些慢

而且馬上假期

要去補習班

去賺下學期生活費

額。。。。

抓緊時間再多學習點

1.RNN遞迴神經網路Tensorflow實現程式

 1 import os
 2 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 3 import tensorflow as tf
 4 from tensorflow.examples.tutorials.mnist import input_data
 5 #載入資料集
 6 mnist = input_data.read_data_sets("
MNIST_data/",one_hot=True) 7 8 # 輸入圖片是28*28 9 n_inputs = 28 #輸入一行,一行有28個數據 10 max_time = 28 #一共28行 11 lstm_size = 100 #隱層單元 12 n_classes = 10 # 10個分類 13 batch_size = 50 #每批次50個樣本 14 n_batch = mnist.train.num_examples // batch_size #計算一共有多少個批次 15 16 #這裡的none表示第一個維度可以是任意的長度 17 x = tf.placeholder(tf.float32,[None,784])
18 #正確的標籤 19 y = tf.placeholder(tf.float32,[None,10]) 20 21 #初始化權值 22 weights = tf.Variable(tf.truncated_normal([lstm_size, n_classes], stddev=0.1)) 23 #初始化偏置值 24 biases = tf.Variable(tf.constant(0.1, shape=[n_classes])) 25 26 27 #定義RNN網路 28 def RNN(X,weights,biases): 29 # inputs=[batch_size, max_time, n_inputs]
30 inputs = tf.reshape(X,[-1,max_time,n_inputs]) 31 #定義LSTM基本CELL 32 lstm_cell = tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(lstm_size) 33 # final_state[0]是cell state 34 # final_state[1]是hidden_state 35 outputs,final_state = tf.nn.dynamic_rnn(lstm_cell,inputs,dtype=tf.float32) 36 results = tf.nn.softmax(tf.matmul(final_state[1],weights) + biases) 37 return results 38 39 40 #計算RNN的返回結果 41 prediction= RNN(x, weights, biases) 42 #損失函式 43 cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y)) 44 #使用AdamOptimizer進行優化 45 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 46 #結果存放在一個布林型列表中 47 correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一維張量中最大的值所在的位置 48 #求準確率 49 accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#把correct_prediction變為float32型別 50 #初始化 51 init = tf.global_variables_initializer() 52 53 with tf.Session() as sess: 54 sess.run(init) 55 for epoch in range(6): 56 for batch in range(n_batch): 57 batch_xs,batch_ys = mnist.train.next_batch(batch_size) 58 sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys}) 59 60 acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) 61 print ("Iter " + str(epoch) + ", Testing Accuracy= " + str(acc))
View Code

2.關於Tensorboard的簡單學習(以MNIST手寫資料集程式為例)

 1 import os
 2 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 3 import tensorflow as tf
 4 from tensorflow.examples.tutorials.mnist import input_data
 5 #載入資料集
 6 mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
 7 #每個批次的大小(即每次訓練的圖片數量)
 8 batch_size = 100
 9 #計算一共有多少個批次
10 n_bitch = mnist.train.num_examples // batch_size
11 #引數概要
12 def variable_summaries(var):
13     with tf.name_scope('summaries'):
14         mean = tf.reduce_mean(var)
15         tf.summary.scalar('mean', mean)  #平均值
16         with tf.name_scope('stddev'):
17             stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
18         tf.summary.scalar('stddev', stddev) #標準差
19         tf.summary.scalar('max', tf.reduce_max(var))
20         tf.summary.scalar('min', tf.reduce_min(var))
21         tf.summary.histogram('histogram', var)#直方圖
22 #定義一個名稱空間
23 with tf.name_scope('input'):
24     #定義兩個placeholder
25     x = tf.placeholder(tf.float32, [None, 784], name='x_input')
26     y = tf.placeholder(tf.float32, [None, 10], name='y_input')
27 with tf.name_scope('layer'):
28     #建立一個只有輸入層(784個神經元)和輸出層(10個神經元)的簡單神經網路
29     with tf.name_scope('weights'):
30         Weights = tf.Variable(tf.zeros([784, 10]), name='w')
31         variable_summaries(Weights)
32     with tf.name_scope('biases'):
33         Biases = tf.Variable(tf.zeros([10]), name='b')
34         variable_summaries(Biases)
35     with tf.name_scope('Wx_plus_B'):
36         Wx_plus_B = tf.matmul(x, Weights) + Biases
37     with tf.name_scope('softmax'):
38         prediction = tf.nn.softmax(Wx_plus_B)
39 #二次代價函式
40 with tf.name_scope('loss'):
41     loss = tf.reduce_mean(tf.square(y - prediction))
42     tf.summary.scalar('loss', loss)
43 #使用梯度下降法
44 with tf.name_scope('train'):
45     train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
46 #初始化變數
47 init = tf.global_variables_initializer()
48 #結果存放在一個布林型列表中
49 with tf.name_scope('accuracy'):
50     with tf.name_scope('correct_prediction'):
51         correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) #argmax返回一維張量中最大的值所在的位置,標籤值和預測值相同,返回為True
52 #求準確率
53     with tf.name_scope('correct_prediction'):
54         accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #cast函式將correct_prediction的布林型轉換為浮點型,然後計算平均值即為準確率
55 
56 #合併所有的summary
57 merged = tf.summary.merge_all()
58 
59 #定義會話
60 with tf.Session() as sess:
61     sess.run(init)
62     writer = tf.summary.FileWriter('logs/', sess.graph)
63     #將測試集迴圈訓練50次
64     for epoch in range(51):
65         #將測試集中所有資料迴圈一次
66         for batch in range(n_bitch):
67             batch_xs, batch_ys = mnist.train.next_batch(batch_size)   #取測試集中batch_size數量的圖片及對應的標籤值
68             summary,_= sess.run([merged, train_step], feed_dict={x:batch_xs, y:batch_ys})  #將上一行程式碼取到的資料進行訓練
69         writer.add_summary(summary, epoch)
70         acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})  #準確率的計算
71         print('Iter : ' + str(epoch) + ',Testing Accuracy = ' + str(acc))
View Code

3. CNN應用——簡單的軸承故障診斷模型

3.1資料來源及介紹

軸承、軸、齒輪是旋轉機械重要組成部分,為了驗證深度學習在旋轉裝備故障分類識別的有效性,

選取凱斯西儲大學軸承資料庫(Case Western Reserve University, CWRU)為驗證資料。

軸承通過電火花加工設定成四種尺寸的故障直徑,分別為0.007、0.014、0.021、0.028英寸。

實驗中使用加速度感測器採集振動訊號,感測器分別被放置在電機驅動端與風扇端。

由於驅動端採集到的振動訊號資料全面,並且收到其他部件和環境噪聲的干擾較少,選取驅動端採集的振動訊號作為實驗資料。

實驗資料包括4種軸承狀態下采集到的振動訊號,分別為正常狀態(Normal,N)、滾珠故障狀態(Ball Fault,BF)、外圈故障狀態(Outer Race Fault,ORF)以及內圈故障狀態(Inner Race Fault,IRF),

每種狀態下采集到的訊號又按照故障直徑與負載的大小進行分類,其中故障直徑分別為0.007、0.014、0.021、0.028英寸,負載大小從0Hp-3Hp(1Hp=746W),對應轉速為1797rpm、1772rpm、1750rpm、1730rpm。

選取CWRU資料集中取樣頻率為12k Hz的各個狀態的樣本,通過深度學習建立故障診斷模型,對電機軸承的四種故障進行分類識別。

由於負載的不同,轉速不恆定,但採集的轉速都在1800rpm左右,取樣頻率為12kHz,轉軸轉一圈,約採集400(60/1800*12000 = 400)個數據點。

由於採用原始資料切分方式,通常取稍微大於一個週期的點數比較合適,為了便於多層CNN網路的輸入,以24*24=576點作為輸入長度。

 

3.2 Matlab資料處理程式

 1 clear all;
 2 clc;
 3 load DataSet;
 4 [iType, iCondition] = size(A);
 5 iExtSize = 24*24;
 6 iSampleRate = 12000;
 7 iTime = 10;
 8 iOverlap = floor(iExtSize * 0.9);
 9 iUCover = iExtSize - iOverlap;
10 iGetDataLen = iSampleRate*iTime + iExtSize;
11 iLen2 = floor((iGetDataLen-iExtSize)/iUCover) + 1;
12 iLen1 =  floor(iLen2/100)*100;
13 iGetDataLen = iLen1*iUCover + iExtSize;
14 fExtSamp = zeros(iType, iGetDataLen);
15  
16 tmp = 0;
17 for jCnt = 1: iType
18     str1 = sprintf('%03d',A(jCnt,1));
19     szValName = strcat('X', str1, '_DE_time');
20     eval(strcat('tmp=',szValName,';'));
21     fExtSamp(jCnt,:) = tmp(1:iGetDataLen);
22 end
23 iLen = iLen1;
24 iSampSize = iLen * iType;
25 fData = zeros(iSampSize, iExtSize);
26 fLabel = zeros(iSampSize, 4);
27  
28 for iCnt = 1:1:iLen
29     iInterval = (iCnt -1)*iUCover + (1:1:iExtSize);
30     for jCnt =1:1:iType
31         fData((iCnt - 1)*iType + jCnt,:) = fExtSamp(jCnt, iInterval);
32         if (jCnt ==1)
33             fLabel((iCnt - 1)*iType + jCnt,:) = [1 0 0 0];
34         end
35         if (jCnt >=2 && jCnt<=5)
36             fLabel((iCnt - 1)*iType + jCnt,:) = [0 1 0 0];
37         end
38         if (jCnt >=6 && jCnt<=9)
39             fLabel((iCnt - 1)*iType + jCnt,:) = [0 0 1 0];
40         end
41         if (jCnt >=10)
42             fLabel((iCnt - 1)*iType + jCnt,:) = [0 0 0 1];
43         end
44     end
45 end
46 save('DL_Data90.mat','fData', 'fLabel');  
View Code

3.3 CNN軸承故障診斷模型

  1 import os
  2 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  3 import numpy as np
  4 import tensorflow as tf
  5 from tensorflow.contrib import rnn
  6 import matplotlib.pyplot as plt
  7  
  8 nSampleSize = 20000     # 總樣本數
  9 nSig_dim = 576          # 單個樣本維度
 10 nLab_dim = 4            # 類別維度
 11  
 12 learning_rate = 1e-3
 13 batch_size = tf.placeholder(tf.int32, [])   # 在訓練和測試,用不同的 batch_size
 14 input_size = 24     # 每個時刻的輸入維數為 24
 15 timestep_size = 24  # 時序長度為24
 16 hidden_size = 128   # 每個隱含層的節點數
 17 layer_num = 3       # LSTM layer 的層數
 18 class_num = nLab_dim       # 類別維數
 19  
 20 def getdata(nSampSize=20000):
 21     # 讀取float型二進位制資料
 22     signal = np.fromfile('DLdata90singal.raw', dtype=np.float64)
 23     labels = np.fromfile('DLdata90labels.raw', dtype=np.float64)
 24     #由於matlab 矩陣寫入檔案是按照【列】優先, 需要按行讀取
 25     mat_sig = np.reshape(signal,[-1, nSampSize])
 26     mat_lab = np.reshape(labels,[-1, nSampSize])
 27     mat_sig = mat_sig.T # 轉換成正常樣式 【樣本序號,樣本維度】
 28     mat_lab = mat_lab.T
 29     return mat_sig, mat_lab
 30  
 31 def zscore(xx):
 32     # 樣本歸一化到【-1,1】,逐條對每個樣本進行自歸一化處理
 33     max1 = np.max(xx,axis=1)    #按行或者每個樣本,並求出單個樣本的最大值
 34     max1 = np.reshape(max1,[-1,1])  # 行向量 ->> 列向量
 35     min1 = np.min(xx,axis=1)    #按行或者每個樣本,並求出單個樣本的最小值
 36     min1 = np.reshape(min1,[-1,1])  # 行向量 ->> 列向量
 37     xx = (xx-min1)/(max1-min1)*2-1
 38     return xx
 39  
 40 def NextBatch(iLen, n_batchsize):
 41     # iLen: 樣本總數
 42     # n_batchsize: 批處理大小
 43     # 返回n_batchsize個隨機樣本(序號)
 44     ar = np.arange(iLen)    # 生成0到iLen-1,步長為1的序列
 45     np.random.shuffle(ar)   # 打亂順序
 46     return ar[0:n_batchsize]
 47  
 48 xs = tf.placeholder(tf.float32, [None, nSig_dim])
 49 ys = tf.placeholder(tf.float32, [None, class_num])
 50 keep_prob = tf.placeholder(tf.float32)
 51  
 52 x_input = tf.reshape(xs, [-1, 24, 24])
 53  
 54 # 搭建LSTM 模型
 55 def unit_LSTM():
 56     # 定義一層 LSTM_cell,只需要說明 hidden_size
 57     lstm_cell = rnn.BasicLSTMCell(num_units=hidden_size, forget_bias=1.0, state_is_tuple=True)
 58     #新增 dropout layer, 一般只設置 output_keep_prob
 59     lstm_cell = rnn.DropoutWrapper(cell=lstm_cell, input_keep_prob=1.0, output_keep_prob=keep_prob)
 60     return lstm_cell
 61  
 62 #呼叫 MultiRNNCell 來實現多層 LSTM
 63 mLSTM_cell = rnn.MultiRNNCell([unit_LSTM() for icnt in range(layer_num)], state_is_tuple=True)
 64  
 65 #用全零來初始化state
 66 init_state = mLSTM_cell.zero_state(batch_size, dtype=tf.float32)
 67 outputs, state = tf.nn.dynamic_rnn(mLSTM_cell, inputs=x_input,initial_state=init_state, time_major=False)
 68 h_state = outputs[:, -1, :]  # 或者 h_state = state[-1][1]
 69  
 70 #設定 loss function 和 優化器
 71 W = tf.Variable(tf.truncated_normal([hidden_size, class_num], stddev=0.1), dtype=tf.float32)
 72 bias = tf.Variable(tf.constant(0.1,shape=[class_num]), dtype=tf.float32)
 73 y_pre = tf.nn.softmax(tf.matmul(h_state, W) + bias)
 74 
 75 #損失和評估函式
 76 cross_entropy = tf.reduce_mean(tf.reduce_sum(-ys*tf.log(y_pre),reduction_indices=[1]))
 77 train_op = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)
 78 correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(ys,1))
 79 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
 80  
 81  
 82 mydata = getdata()
 83 iTrainSetSize =  np.floor(nSampleSize*3/4).astype(int) # 訓練樣本個數
 84 iIndex = np.arange(nSampleSize) # 按照順序,然後劃分訓練樣本、測試樣本
 85 train_index = iIndex[0:iTrainSetSize]
 86 test_index = iIndex[iTrainSetSize:nSampleSize]
 87  
 88 train_data = mydata[0][train_index]     # 訓練資料
 89 train_y = mydata[1][train_index]        # 訓練標籤
 90 test_data = mydata[0][test_index]       # 測試資料
 91 test_y = mydata[1][test_index]          # 測試標籤
 92  
 93 train_x = zscore(train_data)        # 對訓練資料進行歸一化
 94 test_x = zscore(test_data)          # 對測試資料進行歸一化
 95  
 96 init = tf.global_variables_initializer()
 97 
 98 with tf.Session() as sess:
 99     sess.run(init)
100     for icnt in range(1000):
101         _batch_size = 100
102         intervals = NextBatch(iTrainSetSize, _batch_size) # 每次從所有樣本中隨機取100個樣本(序號)
103         xx = train_x[intervals]
104         yy = train_y[intervals]   
105         if (icnt+1)%100 == 0:
106             train_accuracy = sess.run(accuracy, feed_dict={
107                 xs:xx, ys: yy, keep_prob: 1.0, batch_size: _batch_size})
108             print("step: " + "{0:4d}".format(icnt+1) + ",  train acc:" + "{:.4f}".format(train_accuracy))
109         sess.run(train_op, feed_dict={ xs:xx, ys: yy, keep_prob: 0.9, batch_size: _batch_size})
110     bsize = test_x.shape[0]
111     test_acc = sess.run(accuracy,feed_dict={xs:test_x, ys:test_y, keep_prob: 1.0, batch_size:bsize})
112     print("test acc:" + "{:.4f}".format(test_acc))
View Code

 

#寫在後面

新的一年了

感覺開始的一塌糊塗

不過這兩天好像調整過來了

讓自己成為一個有計劃的人

堅持健身、堅持減肥、學習理財、學習穿搭、學BEC中級、學機器學習、學Java、學Python、學深度學習框架、準備實習、積極準備找工作!

堅持早點睡覺、堅持早點起床

堅持不拖延

堅持放下手機

堅持不去抱怨生活、不去抱怨別人

堅持!做一個自律、自信的小夥郭

忙碌起來

為最好的那個自己而不斷努力

不要患得患失的去迷茫明天

而是在每一個今天,都活出最精彩的一天

羨慕那些活的精緻的人

我也要好好加油才好!