#目的:建立模型(但是做成定義函數形式:model=def bulid_mode()),然後學習波士頓房屋資料集,評估模型準確率 #1.載入tensorflow(含keras)等函數庫 import numpy as np import pandas as pd import tensorflow as tf #2.指定亂數種子參數=7(可自行指定不同的參數種子值) #目的:讓每次的執行結果,可以在相同亂數起始值下,進行比較 np.random.seed(7) #2..載入波士頓房屋資料集(讀入自己電腦硬碟的csv檔案) #在colaboratory的python讀入自己的個人電腦硬碟裡的boston_housing.csv ####################################上傳boston_housing.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]))) # 確認boston_housing.csv是否已上載 !ls *.* -l ########################## #3.把csv檔案讀入成dataframe結構資料(use Pandas to read boston_housing.csv) df = pd.read_csv("./boston_housing.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~12) = 訓練資料用 #標籤資料集 = Y = 第9個欄位(13) = 目標值 X = dataset[:, 0:13] Y = dataset[:, 13] #8.特徵標準化 X -= X.mean(axis=0) X /= X.std(axis=0) #9.把資料集分割成訓練資料集,測試資料集 #前404筆,是訓練用資料 X_train, Y_train = X[:404], Y[:404] #最後102筆(404以後筆數),是測試用資料 X_test, Y_test = X[404:], Y[404:] print("X_train.shape[1] = 輸入向量size = ",X_train.shape[1]) #10.定義模型(加入四層網絡:輸入層,隱藏層,隱藏層,輸出層) def build_model(): # 建立模型 model = tf.keras.models.Sequential() model.add(tf.keras.layers.Dense(32, input_shape=(X_train.shape[1],), activation="relu")) model.add(tf.keras.layers.Dense(16, activation="relu")) model.add(tf.keras.layers.Dense(1)) # 顯示神經網絡模型的摘要資訊 model.summary() # 編譯模型 #目的:把上面keras建立好的四層神經網絡,編譯成低階的tensorflow計算圖 model.compile(loss="mse", optimizer="adam", metrics=["mae"]) # 傳回模型變數 return model #12.當資料集數目少時可用k-摺疊交叉驗證法(k fold cross validation) #nb_val_samples :每一折的樣本數。
#nb_epochs = 80,nb_epochs是訓練週期數。
#mae_scores = [],mae_scores清單變數,乃是記錄著每次迴圈評估模型的mae。
#for i in range(k):共執行迴圈k=4次,用『切割運算子』取出第k個驗證資料集:X_val,Y_val
#再用concatenate()函數取出剩下的折來建立訓練資料集:X_train_p,Y_train_p
k = 4 nb_val_samples = len(X_train) // k nb_epochs = 80 mse_scores = [] mae_scores = [] for i in range(k): print("Processing Fold #" + str(i)) # 取出驗證資料集 X_val = X_train[i*nb_val_samples: (i+1)*nb_val_samples] Y_val = Y_train[i*nb_val_samples: (i+1)*nb_val_samples] # 結合出訓練資料集 X_train_p = np.concatenate( [X_train[:i*nb_val_samples], X_train[(i+1)*nb_val_samples:]], axis=0) Y_train_p = np.concatenate( [Y_train[:i*nb_val_samples], Y_train[(i+1)*nb_val_samples:]], axis=0) model = build_model() # 訓練模型 model.fit(X_train_p, Y_train_p, epochs=nb_epochs, batch_size=16, verbose=0) # 評估模型 mse, mae = model.evaluate(X_val, Y_val, verbose=0) mse_scores.append(mse) mae_scores.append(mae) #顯示4次迴圈(4折交叉驗證)計算的MSE,MAE的平均值 print("MSE_val: ", np.mean(mse_scores)) print("MAE_val: ", np.mean(mae_scores)) # 使用測試資料評估模型 mse, mae = model.evaluate(X_test, Y_test, verbose=0) print("MSE_test: ", mse) print("MAE_test: ", mae)