Machine Learning-多層感知器程式範例 使用python (Multilayer perceptron case using python keras)

手上剛好有一份冷媒的溫壓對照表,如下連結
R245fa

但當你的數值不能剛好match還需要一個一個換算,因此直接用MLP訓練個擬合模型來換算。

目標就是希望壓力經過模型後自動換算成溫度,就直接看code。

import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, LSTM, TimeDistributed, RepeatVector

#讀取資料
xls_file = pd.ExcelFile('R245fa溫壓表.xlsx')
df = xls_file.parse('工作表1')
print(df.columns)
print(df)

#分別把壓力當input與溫度當output
train=df
X = train.iloc[:,1:] 
Y = train.iloc[:,0]
X=X.values
Y=Y.values

#故意打亂1~120的順序,可讓訓練結果更好
def shuffle(X,Y):
  np.random.seed(10)
  randomList = np.arange(X.shape[0])
  np.random.shuffle(randomList)
  return X[randomList], Y[randomList]

#區分訓練集與測試集
def splitSet(X,Y,rate):
    count=int(round(len(X)*rate))
    X_train, Y_train = X[:count], Y[:count]   
    X_test, Y_test = X[count:], Y[count:]
    return X_train, Y_train, X_test, Y_test 

#再切一份驗證集可讓訓練結果更好
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=shuffle(X, Y)

X_train, Y_train, X_test, Y_test=splitSet(X,Y,0.8)

X_train, Y_train, X_val, Y_val = splitData(X_train, Y_train, 0.1)

#建立模型 1-256-1的MLP神經網路
model = Sequential()
model.add(Dense(256, input_dim=1, kernel_initializer='normal', activation='relu'))
model.add(Dense(1,kernel_initializer='normal'))


"""訓練模型"""
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X_train, Y_train, epochs=50000, batch_size=128, validation_data=(X_val, Y_val))


# 秀出測試集的MSE cost
print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=20000)
print('test cost:', cost)

#列出測試集前10比與預測結果是否相近可用
Y_pred = model.predict(X_test)
print(Y_pred[0:10],Y_test[0:10])

#儲存模型
model.save('R245fa溫壓表_model.h5')

最終的訓練結果
loss: 0.0067 - val_loss: 0.0105
test cost: 0.013776754029095173
預測
[ 72.1291 , 32.943 , 62.166 , 87.9613 , 54.0276 , 11.0907 , 119.175 , 15.8531 , 35.9908 , 39.9254 ]
真實
[ 72  33  62  88  54  11 119  16  36  40]

相關更深入寫法可以參考這本書:Deep learning 深度學習必讀

留言

這個網誌中的熱門文章

Python-相關係數矩陣實作(python-correlation matrix )

ASP.NET-後端將值傳給javascript

ASP.NET-FileUpload上傳後自動觸發button click(FileUpload upload auto trigger button click)