#目的:如何找到最佳訓練週期epochs(看驗證資料的history圖) #☎在history = model.fit(參數)裡面,加上參數validation_data=(X_test,Y_test) #☎然後觀察history歷史圖,畫出val_loss(validation loss)歷史圖,當val_loss最低點就是最佳訓練週期 #1.載入tensorflow(含keras)等函數庫 import numpy as np import pandas as pd import tensorflow as tf #2.指定亂數種子參數=10(可自行指定不同的參數種子值) #目的:讓每次的執行結果,可以在相同亂數起始值下,進行比較 np.random.seed(10) #3.載入糖尿病資料集(讀入自己電腦硬碟的csv檔案) #在colaboratory的python讀入自己的個人電腦硬碟裡的diabetes.csv ####################################上傳diabetes.csv from google.colab import files uploaded = files.upload() for fn in uploaded.keys(): print('User uploaded file "{name}" with length {length} bytes'.format( name=fn, length=len(uploaded[fn]))) # 確認diabetes.csv是否已上載 !ls *.* -l ########################## #4.把csv檔案讀入成dataframe結構資料(use Pandas to read diabetes.csv) df = pd.read_csv("./diabetes.csv") #5.df.values指令,可以把dataframe轉成Numppy陣列資料(dataset) dataset = df.values #6.函數random.shuffle(dataset),可以把dataset陣列,打亂資料次序,成隨機次序(使用亂數打亂資料) np.random.shuffle(dataset) #7.將資料分割成輸入的訓練資料X,和標籤資料Y #特徵資料集 = X = 前8個欄位(0~7) = 訓練資料用 #標籤資料集 = Y = 第9個欄位(8) = 目標值 X = dataset[:, 0:8] Y = dataset[:, 8] #8.特徵標準化 X -= X.mean(axis=0) X /= X.std(axis=0) #9.把資料集分割成訓練資料集,測試資料集 #前690筆,是訓練用資料 X_train, Y_train = X[:690], Y[:690] #最後78筆(690以後筆數),是測試用資料 X_test, Y_test = X[690:], Y[690:] #10.定義模型(加入三層網絡) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Dense(10, input_shape=(8,), activation="relu")) model.add(tf.keras.layers.Dense(6, activation="relu")) model.add(tf.keras.layers.Dense(1, activation="sigmoid")) #11.顯示神經網絡模型的摘要資訊 model.summary() #12.編譯模型 #目的:把上面keras建立好的四層神經網絡,編譯成低階的tensorflow計算圖
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) #13.訓練模型(用X_test,Y_test來做訓練)(加上參數validation_data=(X_test,Y_test)) #結果:輸出訊息,多了兩個:val_loss驗證資料的損失,val_accuracy驗證資料的準確率 history = model.fit(X_train, Y_train, epochs=10, validation_split=0.2, batch_size=10, verbose=1) #14.評估模型的效能(比較用『訓練用資料集,測試資料集』的模型準確率) loss, accuracy = model.evaluate(X_train, Y_train) print("訓練用資料集的準確度 = {:.2f}".format(accuracy)) loss, accuracy = model.evaluate(X_test, Y_test) print("測試資料集的準確度 = {:.2f}".format(accuracy)) #15.畫出val_loss(validation loss)歷史圖,當val_loss最低點就是最佳訓練週期 import matplotlib.pyplot as plt loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1,len(loss)+1) plt.plot(epochs, loss, "bo", label="Training_loss") plt.plot(epochs, val_loss, "r", label="Validation_loss") plt.title("Training_loss vs Validation_loss") plt.xlabel("epochs") plt.ylabel("loss") plt.legend() plt.show() #16.畫出train_accuracy訓練資料集的準確率,Validation_Accuracy驗證資料集的準確率之歷史圖,當Validation_Accuracy最高點就是最佳訓練週期 acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] epochs = range(1,len(loss)+1) plt.plot(epochs, acc, "b-", label="Training_Accuracy") plt.plot(epochs, val_acc, "r--", label="Validation_Accuracy") plt.title("Training_Accuracy vs Validation_Accuracy") plt.xlabel("epochs") plt.ylabel("Accuracy") plt.legend() plt.show()