顯示具有 tensorflow 標籤的文章。 顯示所有文章
顯示具有 tensorflow 標籤的文章。 顯示所有文章

2021年10月1日 星期五

tensorflow logging.h編譯失敗的解法

標題:tensorflow logging.h編譯失敗的解法


今天編譯tensorflow C++的時候,發現logging.h無法編譯(編譯失敗),如圖:



那個叫「TF_DEFINE_CHECK_OP_IMPL」的東西總是給紅底線的報錯。


如何解決呢。

去專案屬性的地方,在C/C++/前置處理器/前置處理器定義的地方,新增「NOMINMAX」。


新增完成後套用確定。

接著回到code的地方,會看見「TF_DEFINE_CHECK_OP_IMPL」的紅底線已經消失,而且已經可以編譯了。


2021年9月30日 星期四

在Visual Studio安裝TensorFlow C語言環境

標題:在Visual Studio 2019安裝Tensorflow C語言環境

搜尋標題:Visual Studio 2019 install Tensorflow for C


今天要來用Visual Studio 2019執行C語言版本的Tensorflow。

這個教學給的範例應該不難,有問題再留言問我。


直接進入正題吧!


首先,點進去這個網址:

https://www.tensorflow.org/install/lang_c


然後依照作業系統和CPU/GPU等需求下載檔案。



然後會下載到一個檔名類似「libtensorflow-gpu-windows-x86_64-2.6.0.zip」的檔案,把它解壓縮。


解壓縮後把資料夾貼到C磁碟機或你想要的地方。

我們會看到資料夾中有個include資料夾和lib資料夾。

這兩個資料夾的名稱,要記好,等一下會使用好幾次。



然後開啟Visual Studio,建立C++版本的主控台應用程式。


建立好後按專案/<專案名稱>屬性。



在VC++目錄的「include目錄」加上include資料夾的路徑。

我的範例是「C:\libtensorflow-gpu-windows-x86_64-2.6.0\include」

在VC++目錄的「程式庫目錄」加上lib資料夾的路徑。

我的範例是「C:\libtensorflow-gpu-windows-x86_64-2.6.0\lib」



然後去連接器/輸入/其他相依性 的地方,輸入tensorflow.lib。

「tensorflow.lib」存在於lib資料夾。

都設定完成後按套用確定。



然後輸入以下程式碼(可以直接複製):

#include <iostream>
#include <stdio.h>
#include <tensorflow/c/c_api.h> 
using namespace std;
int main()
{
    printf("Hello from TensorFlow C library version %s\n"TF_Version());
    int a;
    cin >> a;
}

如圖:


這段程式是要把TensorFlow的版本print出來的,可用來確認有正確使用到TensorFlow。
然後cin是為了防止TensorFlow版本印出來後發生視窗立即閃退的情況。

輸入完程式碼後建置程式:



接著去專案中的「Debug/Release」資料夾開啟該程式。

可能會出現「找不到tensorflow.dll」之類的錯誤。


沒關係,我們去剛才解壓縮後的lib資料夾,找到「tensorflow.dll」檔案,複製到跟執行檔相同資料夾位置的地方。


複製dll檔過去後,再次啟動程式,就可以讀取到TensorFlow了。


顯示出來的,就是TensorFlow的版本(我的版本是2.6.0),如果看見TensorFlow的版本被顯示出來了,代表TensorFlow的環境建置成功了喔。

2020年6月9日 星期二

[tf.keras]利用LSTM預測泵傳感器剩餘壽命(四)—驗證

在上一章節我們訓練完成了模型檔,並儲存為LSTM_result.h5的檔案,現在,我們在資料檔的同一個資料夾建立名為lstm_verification.py的檔案,並使用程式碼編輯器開啟它。

驗證前將引入以下套件:
import pandas as pd
import numpy as np
from tensorflow.keras.models import load_model

import copy

利用pandas讀取上一章節建立的正規化前資料。
valueList= pd.read_csv('./ValueList.csv')

利用pandas讀取一開始建立的訓練檔資料。
df2 = pd.read_csv('./test_sensor.csv')

利用drop移除不需要的欄位,並利用fillna將空白資料填滿0。
df2 = df2.drop(['timestamp','sensor_15','sensor_50','Unnamed: 0','machine_status'],axis=1)
df2 =df2.fillna(value=0)

建立正規化的函數,使用訓練時儲存的參數。
def normalize(train2):
    for i in train2:
        max11=valueList[i][0]
        min11=valueList[i][1]
        mean11=valueList[i][2]
        train2[i]= train2[i].apply(lambda x: (x - mean11) / (max11 - min11))
        train2[i][train2[i]>(max11 - mean11) / (max11 - min11)]=(max11 - mean11) / (max11 - min11)
        train2[i][train2[i]<(min11 - mean11) / (max11 - min11)]=(min11 - mean11) / (max11 - min11)

    return train2

建立反正規化函數,依然是使用訓練時儲存的參數。
def unnormalize(train):
  train2 = copy.deepcopy(train) 
  for i in range(len(train)):
      train2[i]=train[i]*(valueList['time_left'][0]-valueList['time_left'][1])+valueList['time_left'][2]

  return train2

資料的X刪除剩餘時間,而Y則是只保留剩餘時間。
def buildTrain(train):
  X_train, Y_train = [], []
  train2=train.drop(['time_left'],axis=1)
  #for i in range(train.shape[0]):
  X_train=np.array(train2.iloc[:][:]).tolist()
  Y_train=np.array(train.iloc[:]["time_left"]).tolist()
  return np.array(X_train), np.array(Y_train)

工具函數都訂好了之後,將資料除60再除24,能夠將分鐘換算成天,我們就以天為單位做驗證。
df2["time_left"]=df2["time_left"]/60/24

替驗證資料做正規化及上一章節提到過的動作。
test_norm =normalize(df2)
X_val, Y_val = buildTrain(test_norm)

X_val = X_val[:,np.newaxis]

載入訓練完成的模型。
model=load_model("LSTM_result.h5")

進行預測
prediction=model.predict(X_val)
count=0
prediction1=prediction
for i in range(prediction1.shape[0]):
    prediction1[i]=unnormalize(prediction[i])
Y_val1=unnormalize(Y_val)
for i in range(len(Y_val)):
    if prediction1[i][0][0]<=Y_val1[i]+0.5 and prediction1[i][0][0]>=Y_val1[i]-0.5:
        count=count+1
print(count/len(Y_val1))

最後驗證的準確度為:0.9955842595373986
意謂著,若以天為單位(正負誤差12小時),訓練集跟驗證集的準確度差不多,都有99%的準確度。

[tf.keras]利用LSTM預測泵傳感器剩餘壽命(三)—訓練

我們在資料檔的同一個資料夾建立名為lstm_train.py的檔案,並使用程式碼編輯器開啟它。

訓練前將引入以下套件:
import pandas as pd
import numpy as np
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector
from tensorflow.python.keras.layers.normalization import BatchNormalization
from tensorflow.python.keras.optimizer_v2.adam import Adam
from tensorflow.python.keras.callbacks import EarlyStopping, ModelCheckpoint
import matplotlib.pyplot as plt
from tensorflow.keras.models import load_model
import copy

利用pandas讀取上一章節建立的訓練檔資料。
df = pd.read_csv('./train_sensor.csv')

利用drop移除不需要的欄位,並利用fillna將空白資料填滿0。
df = df.drop(['timestamp','sensor_15','sensor_50','Unnamed: 0','machine_status'],axis=1)
df =df.fillna(value=0)

定義正規化函數,將資料正規化為:

(值-平均)/(對大值-最小值)
/def normalize(train):
  train_norm = train.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
  return train_norm

定義反正規化函數,目的是最後在驗證時要把正規化後的剩餘時間反轉回原來的數字。
註:valueList為之後才會宣告的物件。
def unnormalize(train):
  train2 = copy.deepcopy(train) 
  for i in range(len(train)):
      train2[i]=train[i]*(valueList['time_left'][0]-valueList['time_left'][1])+valueList['time_left'][2]

  return train2

這個是儲存正規化前資料用的csv檔,包含資料欄位的最大值、最小值、平均值。
註:如忽略此項動作,對驗證檔單獨驗證時會比較麻煩。
def save_normalize(df):
    ValueList=copy.deepcopy(df[:][:3])
    for i in df:
        max1=np.max(df[i][:])
        min1=np.min(df[i][:])
        mean1=np.mean(df[i][:])
        ValueList[i][0]=max1
        ValueList[i][1]=min1
        ValueList[i][2]=mean1
    ValueList.to_csv('./ValueList.csv')

這是切分函數,輸入數值(如0.1)將切割成90%的訓練資料及10%的驗證資料並回傳。
def splitData(X,Y,rate):
  X_train = X[int(X.shape[0]*rate):]
  Y_train = Y[int(Y.shape[0]*rate):]
  X_val = X[:int(X.shape[0]*rate)]
  Y_val = Y[:int(Y.shape[0]*rate)]
  return X_train, Y_train, X_val, Y_val

這是將訓練資料的X刪除剩餘時間,而Y則是只保留剩餘時間。
def buildTrain(train):
  X_train, Y_train = [], []
  train2=train.drop(['time_left'],axis=1)
  X_train=np.array(train2.iloc[:][:]).tolist()
  Y_train=np.array(train.iloc[:]["time_left"]).tolist()
  return np.array(X_train), np.array(Y_train)

shuffle函數則是將訓練資料洗牌(由於之前在Excel洗牌過了,所以也可忽略)。
註:np.random.seed相當重要,那代表亂數種子,可以用它來確保每次亂數結果相同,在模型儲存後重開視窗二度訓練時就能使這次的打亂跟上次一樣,否則第二次切分後的訓練集跟驗證集將跟第一次的切分混淆。
def shuffle(X,Y):
  np.random.seed(10)
  randomList = np.arange(X.shape[0])
  np.random.shuffle(randomList)
  return X[randomList], Y[randomList]

工具函數都訂好了之後,將資料除60再除24,能夠將分鐘換算成天,我們就以天為單位做訓練和驗證。
df["time_left"]=df["time_left"]/60/24

儲存正規化前的資料。
save_normalize(df)

將資料正規化,並讓X跟Y分離:
X為sensor的資料,Y為剩餘天數。
train_norm = normalize(df)
X_train, Y_train = buildTrain(train_norm)

將資料洗牌(可斟酌情況忽略)
X_train, Y_train = shuffle(X_train, Y_train)

將資料切分為訓練過程時的訓練,跟驗證(並非驗證檔的驗證)。
X_train, Y_train, X_val, Y_val = splitData(X_train, Y_train, 0.1)

提升X的維度。
X_train = X_train[:,np.newaxis]

X_val = X_val[:,np.newaxis]

建立model用的函數,我們疊了四層LSTM,損失函數為mse,優化器為adam。
註:這些並沒有標準答案,可以自己配置。
def buildOneToOneModel(shape):
  model = Sequential()
  model.add(LSTM(128input_length=shape[1], input_dim=shape[2],return_sequences=True))
  model.add(LSTM(128input_length=shape[1], input_dim=shape[2],return_sequences=True))
  model.add(LSTM(128input_length=shape[1], input_dim=shape[2],return_sequences=True))
  model.add(LSTM(128input_length=shape[1], input_dim=shape[2],return_sequences=True))
  model.add(TimeDistributed(Dense(1)))
  model.compile(loss='mse'optimizer="adam")
  model.summary()
  return model

定義繪製圖形函數,在訓練完後可以輸出訓練過程。
def plot1(history):
     N = np.arange(0len(history['loss']))
     fig=plt.figure()
     fig.set_size_inches(18.510.5)
     plt.plot(N, history['loss'], label = "train_loss")
     plt.plot(N, history['val_loss'], label = "val_loss")
     plt.xlabel("Epoch #")
     plt.ylabel("Loss")
     plt.legend()
     plt.savefig('loss.png'dpi=100)
     plt.close()

建立模型
model = buildOneToOneModel(X_train.shape)

我們使用,EarlyStopping做訓練時的callback,當發生訓練時loss不減反增10次時立即停止訓練。
callback = EarlyStopping(monitor="loss"patience=10verbose=1mode="auto")

這是執行訓練,放入X_train, Y_train分別為訓練的90%資料,validation_data是驗證的資料(10%),epochs為訓練次數,batch_size為每批次訓練的樣本數,callbacks為剛剛指定的EarlyStopping。
history=model.fit(X_train, Y_train, epochs=300batch_size=256validation_data=(X_val, Y_val), callbacks=[callback])

訓練完後將執行這行,輸出訓練過程。
plot1(history.history)

接著讀取訓練前建立的資料檔案,它是正規化之前的最大值、最小值、平均值。
valueList= pd.read_csv('./ValueList.csv')

這是訓練完後對那10%的驗證進行的準確度評估,步驟是預測X_val的結果並儲入prediction並將其反正規化。
然後用迴圈一條一條確認真實結果跟預測的差別,在此範例,誤差半天的range就是24小時,所以以誤差半天作為驗證標準是合理的。
prediction=model.predict(X_val)
count=0
prediction1=prediction
for i in range(prediction1.shape[0]):
    prediction1[i]=unnormalize(prediction[i])
Y_val1=unnormalize(Y_val)
for i in range(len(Y_val)):
    if prediction1[i][0][0]<=Y_val1[i]+0.5 and prediction1[i][0][0]>=Y_val1[i]-0.5:
        count=count+1
print(count/len(Y_val1))  

驗證完後如果評估訓練結果成功,可以將結果儲存。
model.save("LSTM_result.h5")

以後要二次訓練或驗證時,只要將程式碼中的:
model = buildOneToOneModel(X_train.shape)
取代為:
model=load_model("LSTM_result.h5")
即可接續上次的模型繼續訓練或驗證。

=====執行結果=====
執行model.fit時應該會出現類似以下的畫面:

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
lstm (LSTM)                  (None, 1, 128)            92160     
_________________________________________________________________
lstm_1 (LSTM)                (None, 1, 128)            131584    
_________________________________________________________________
lstm_2 (LSTM)                (None, 1, 128)            131584    
_________________________________________________________________
lstm_3 (LSTM)                (None, 1, 128)            131584    
_________________________________________________________________
time_distributed (TimeDistri (None, 1, 1)              129       
=================================================================
Total params: 487,041
Trainable params: 487,041
Non-trainable params: 0
_________________________________________________________________
Train on 119836 samples, validate on 13315 samples
Epoch 1/300
119836/119836 [==============================] - 14s 113us/sample - loss: 0.0385 - val_loss: 0.0258
Epoch 2/300
119836/119836 [==============================] - 7s 58us/sample - loss: 0.0215 - val_loss: 0.0206
Epoch 3/300
119836/119836 [==============================] - 7s 56us/sample - loss: 0.0150 - val_loss: 0.0122
Epoch 4/300
119836/119836 [==============================] - 7s 58us/sample - loss: 0.0117 - val_loss: 0.0107
.
.
.
Epoch 185/300
119836/119836 [==============================] - 7s 55us/sample - loss: 1.9707e-05 - val_loss: 4.0432e-05
Epoch 186/300
119836/119836 [==============================] - 7s 55us/sample - loss: 1.9298e-05 - val_loss: 3.8655e-05
Epoch 187/300
119836/119836 [==============================] - 7s 55us/sample - loss: 9.7278e-05 - val_loss: 6.1180e-05
Epoch 00187: early stopping

訓練過程則會儲存成loss.png檔,可以看出沒有明顯的過擬合。

驗證時則會出現類似以下數字:
0.9960946301164101
這個數字代表準確度99.6%,但,我們還有一份切割20%的驗證檔,利用它評估比較準確,將於下一章節驗證。

另外,神經網路這種東西本來就有運氣成分在,所以執行結果跟本文的結果有微小的誤差是正常的。

[tf.keras]利用LSTM預測泵傳感器剩餘壽命(四)—驗證