#目的:一次讀入已經儲存的結構與權重檔案(學習波士頓房屋資料集,評估模型準確率)#目的:建立模型,學習波士頓房屋資料集,評估模型準確率,一次儲存結構與權重
#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.定義模型(加入三層網絡:輸入層,隱藏層,輸出層)
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(32, activation="relu"))
model.add(tf.keras.layers.Dense(1))
#11.顯示神經網絡模型的摘要資訊
model.summary()
#12.編譯模型
#目的:把上面keras建立好的四層神經網絡,編譯成低階的tensorflow計算圖
model.compile(loss="mse", optimizer="adam", metrics=["mae"])
#若要顯示其它評估函數,則要全部列出('mse', 'mae', 'mape')
#model.compile(loss='mse', optimizer='adam', metrics=['mse', 'mae', 'mape'])
#13.訓練模型(用X_train, Y_train來做訓練)
history = model.fit(X_train, Y_train, epochs=80, batch_size=10, verbose=0)
#14.評估模型的效能(比較用『訓練用資料集,測試資料集』的模型準確率)
mse,mae = model.evaluate(X_train, Y_train)
print("訓練用資料集的損失函數 = 均方誤差(mse) = {:.2f}".format(mse))
print("訓練用資料集的評估效率 = 平均絕對誤差(mae) = {:.2f}".format(mae))
mse,mae = model.evaluate(X_test, Y_test)
print("測試用資料集的損失函數 = 均方誤差(mse) = {:.2f}".format(mse))
print("測試資料集的評估效率 = 平均絕對誤差(mae) = {:.2f}".format(mae))
#15.同時一次儲存模型的『結構,權重』
#from tensorflow.keras.models import load_model
model.save('k11-2g-1.h5')
#1.載入tensorflow(含keras)等函數庫
import numpy as np
import pandas as pd
import tensorflow as tf
#2.指定亂數種子參數=7(可自行指定不同的參數種子值)
#目的:讓每次的執行結果,可以在相同亂數起始值下,進行比較
np.random.seed(7)
#3..載入波士頓房屋資料集(讀入自己電腦硬碟的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
##########################
#4.把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.讀入模型
model = tf.keras.models.Sequential()
model = tf.keras.models.load_model("k11-2g-1.h5")
#11.編譯模型
#目的:把上面keras建立好的四層神經網絡,編譯成低階的tensorflow計算圖
model.compile(loss="mse", optimizer="adam", metrics=["mae"])
#若要顯示其它評估函數,則要全部列出('mse', 'mae', 'mape')
#model.compile(loss='mse', optimizer='adam', metrics=['mse', 'mae', 'mape'])
#12.訓練模型(用X_train, Y_train來做訓練)
history = model.fit(X_train, Y_train, epochs=80, batch_size=10, verbose=0)
#13.評估模型的效能(比較用『訓練用資料集,測試資料集』的模型準確率)
mse,mae = model.evaluate(X_train, Y_train)
print("訓練用資料集的損失函數 = 均方誤差(mse) = {:.2f}".format(mse))
print("訓練用資料集的評估效率 = 平均絕對誤差(mae) = {:.2f}".format(mae))
mse,mae = model.evaluate(X_test, Y_test)
print("測試用資料集的損失函數 = 均方誤差(mse) = {:.2f}".format(mse))
print("測試資料集的評估效率 = 平均絕對誤差(mae) = {:.2f}".format(mae))