keras实现回归预测
機器學習小白一枚? 目前在做機器學習和光學的交叉? 希望各位大佬多多指正
背景:通過光纖結構的5個不同參數實現對其純凈度的預測
直接上圖
?我最終的目標是要實現通過圖中 k n L r?λ?這5個參數? 實現對每個模式的purity? Aeff? dispersion?以及keer這四個參數的預測? ? 那么這篇文章只做一個簡單的對其中purity參數的預測? 具體最終的多維度預測我會在接下來的文章中更新...
? 進入代碼
首先就是對數據集的一個讀取? 然后創建兩個數組分別承載他們
這個代碼就是給他轉化成一個np數組然后進行一個預處理? ? 數據分割那塊根據自己的數據集自行決定? ?像我最后的數據集的話可能直接分成了兩個文件? 就不需要在代碼內給他們分割?
一個簡單的網絡架構? ?這里他的輸入維度是隱式包含在第一個Dense層里? 我得輸入維度有5個就設置為5? 第一個全連接層也設置為5?然后再搭一個Dense和一個output (這塊可以根據你自己的需要去調整? 因為對于回歸預測來說的話可能并不需要太復雜的結構? 當然如果你想提高一下模型的擬合能力和泛化效果的話可以加深網絡層數? 但也不是越多越好? 要根據你自己的網絡結構去調試)
下面compile函數就是進行一個擬合?這里選用Adam優化? 學習率設置為0.0001? 損失函數用mse? 評價函數用mae(對于mse?和?mae?這兩個函數可以自行抉擇? 因為看了好多回歸的網絡基本上用的都是這兩個? 甚至有的根本不需要評價函數? 直接上損失就夠了)?
自后fit函數? batchsize和epochs次數也是根據自己決定? bitchsize根據自己電腦計算能力?可以盡可能調小? ?validation_split是一個動態分配訓練集? 比如我設置的是0.2?就是動態分配20%的訓練數據作為測試? 主要目的是為了更直觀的防止一個過擬合問題的出現? verbose就是迭代過程中的詳細程度? 主要有0 1 2? 根據自己需求設置
預測部分代碼? 和最開始對訓練數據的處理差不多
最后是完整代碼
import osimport xlrd import xlwt import numpy as np from random import randint from sklearn.utils import shuffle from sklearn.preprocessing import MinMaxScaler, StandardScaler import tensorflow as tf from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Activation,Dense from tensorflow.keras.optimizers import Adam from tensorflow.keras.metrics import categorical_crossentropy import matplotlib.pyplot as plt# data = xlrd.open_workbook('puity.xlsx') # sheet = data.sheet_by_index(0) #row1 = sheet.row_values(1) #行 #col1 = sheet.col_values(3) #列 #cell = sheet.cell(1,1).valueimport tensorflow as tf print("Num GPUS Available:",len(tf.config.experimental.list_physical_devices('GPUs'))) os.environ["CUDA_VISIBLE_DEVICES"]="0"data = xlrd.open_workbook('puity_train.xlsx') sheet = data.sheet_by_index(0) nrows = sheet.nrows #行數 ncols = sheet.ncols #列數samples = [] #訓練樣本 labels = [] #對應標簽for i in range(nrows):row = sheet.row_values(i)samples.append(row[0:5])labels.append(row[12])from sklearn.model_selection import train_test_split train_samples,test_samples,train_labels,test_labels =train_test_split(samples,labels,random_state = 0,test_size = 0.20)train_labels=np.array(train_labels) train_samples=np.array(train_samples) test_samples=np.array(test_samples) test_labels=np.array(test_labels) # #亂序 train_labels,train_samples=shuffle(train_labels,train_samples)# print(train_samples) # print(test_samples)#數據預處理 scaler = StandardScaler() train_samples = scaler.fit_transform(train_samples) test_samples = scaler.fit_transform(test_samples) # # print(train_samples) # # print(train_labels) # print(test_samples) # # print(test_labels)# # scaler = MinMaxScaler(feature_range=(0,1)) # scaled_train_samples = scaler.fit_transform(np.array(train_samples).reshape(-1,1))model = Sequential([Dense(units=5,input_shape=(5,),activation='relu'),Dense(units=32,activation='relu'),Dense(units=1)]) # # #可視化網絡模型 model.summary() # model.compile(optimizer=Adam(learning_rate=0.0001),loss='mse', metrics='mae')# # # # # 參數 validation_split=0.2 動態分配20%的訓練集作為測試 防止出現過擬合問題 history = model.fit(x=train_samples,y=train_labels,validation_split=0.2,batch_size=64,epochs=2000,shuffle=True,verbose=2) # mae = history.history['mae'] # val_mae = history.history['val_mae'] # loss = history.history['loss'] # val_loss = history.history['val_loss'] # epochs = range(1, len(loss) + 1) # # acc = history.history['acc'] # 獲取訓練集準確性數據 # # val_acc = history.history['val_acc'] # 獲取驗證集準確性數據 # loss = history.history['loss'] # 獲取訓練集錯誤值數據 # val_loss = history.history['val_loss'] # 獲取驗證集錯誤值數據 # epochs = range(1, len(loss) + 1) # # plt.figure() # 創建一個新的圖表 # plt.plot(epochs, loss, 'bo', label='Trainning loss') # plt.plot(epochs, val_loss, 'b', label='Vaildation loss') # plt.legend() ##繪制圖例,即標明圖中的線段代表何種含義 # # plt.show() # 顯示所有圖表 mae = history.history['mae'] val_mae = history.history['val_mae'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.figure() # 創建一個新的圖表 plt.plot(epochs, loss, label='Trainning loss mse',color="blue",linewidth=0.3,linestyle='-.') plt.plot(epochs, val_loss, label='Vaildation loss mse',color="blue",linewidth=0.3,linestyle='--') #預測test_labels,test_samples = shuffle(test_labels,test_samples) print(test_samples) print(test_labels) predictions = model.predict(x=test_samples,batch_size=32,verbose=0) for i in predictions:print(i)x = np.linspace(0,1000,800) y1 = test_labels y2 = predictions plt.figure() plt.plot(x,y1,label='test labels') plt.plot(x,y2,label='predict labels',color="red",linewidth=1.0,linestyle='--') plt.show()?
?
總結
以上是生活随笔為你收集整理的keras实现回归预测的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VUX--小白初学使用安装
- 下一篇: android自动接收并填充短信验证码