您好,登錄后才能下訂單哦!
小編給大家分享一下關于keras訓練模型fit和fit_generator的案例,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討方法吧!
第一種,fit
import keras from keras.models import Sequential from keras.layers import Dense import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import train_test_split #讀取數據 x_train = np.load("D:\\machineTest\\testmulPE_win7\\data_sprase.npy")[()] y_train = np.load("D:\\machineTest\\testmulPE_win7\\lable_sprase.npy") # 獲取分類類別總數 classes = len(np.unique(y_train)) #對label進行one-hot編碼,必須的 label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(y_train) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) y_train = onehot_encoder.fit_transform(integer_encoded) #shuffle X_train, X_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.3, random_state=0) model = Sequential() model.add(Dense(units=1000, activation='relu', input_dim=784)) model.add(Dense(units=classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit(X_train, y_train, epochs=50, batch_size=128) score = model.evaluate(X_test, y_test, batch_size=128) # #fit參數詳情 # keras.models.fit( # self, # x=None, #訓練數據 # y=None, #訓練數據label標簽 # batch_size=None, #每經過多少個sample更新一次權重,defult 32 # epochs=1, #訓練的輪數epochs # verbose=1, #0為不在標準輸出流輸出日志信息,1為輸出進度條記錄,2為每個epoch輸出一行記錄 # callbacks=None,#list,list中的元素為keras.callbacks.Callback對象,在訓練過程中會調用list中的回調函數 # validation_split=0., #浮點數0-1,將訓練集中的一部分比例作為驗證集,然后下面的驗證集validation_data將不會起到作用 # validation_data=None, #驗證集 # shuffle=True, #布爾值和字符串,如果為布爾值,表示是否在每一次epoch訓練前隨機打亂輸入樣本的順序,如果為"batch",為處理HDF5數據 # class_weight=None, #dict,分類問題的時候,有的類別可能需要額外關注,分錯的時候給的懲罰會比較大,所以權重會調高,體現在損失函數上面 # sample_weight=None, #array,和輸入樣本對等長度,對輸入的每個特征+個權值,如果是時序的數據,則采用(samples,sequence_length)的矩陣 # initial_epoch=0, #如果之前做了訓練,則可以從指定的epoch開始訓練 # steps_per_epoch=None, #將一個epoch分為多少個steps,也就是劃分一個batch_size多大,比如steps_per_epoch=10,則就是將訓練集分為10份,不能和batch_size共同使用 # validation_steps=None, #當steps_per_epoch被啟用的時候才有用,驗證集的batch_size # **kwargs #用于和后端交互 # ) # # 返回的是一個History對象,可以通過History.history來查看訓練過程,loss值等等
第二種,fit_generator(節省內存)
# 第二種,可以節省內存 ''' Created on 2018-4-11 fit_generate.txt,后面兩列為lable,已經one-hot編碼 1 2 0 1 2 3 1 0 1 3 0 1 1 4 0 1 2 4 1 0 2 5 1 0 ''' import keras from keras.models import Sequential from keras.layers import Dense import numpy as np from sklearn.model_selection import train_test_split count =1 def generate_arrays_from_file(path): global count while 1: datas = np.loadtxt(path,delimiter=' ',dtype="int") x = datas[:,:2] y = datas[:,2:] print("count:"+str(count)) count = count+1 yield (x,y) x_valid = np.array([[1,2],[2,3]]) y_valid = np.array([[0,1],[1,0]]) model = Sequential() model.add(Dense(units=1000, activation='relu', input_dim=2)) model.add(Dense(units=2, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit_generator(generate_arrays_from_file("D:\\fit_generate.txt"),steps_per_epoch=10, epochs=2,max_queue_size=1,validation_data=(x_valid, y_valid),workers=1) # steps_per_epoch 每執行一次steps,就去執行一次生產函數generate_arrays_from_file # max_queue_size 從生產函數中出來的數據時可以緩存在queue隊列中 # 輸出如下: # Epoch 1/2 # count:1 # count:2 # # 1/10 [==>...........................] - ETA: 2s - loss: 0.7145 - acc: 0.3333count:3 # count:4 # count:5 # count:6 # count:7 # # 7/10 [====================>.........] - ETA: 0s - loss: 0.7001 - acc: 0.4286count:8 # count:9 # count:10 # count:11 # # 10/10 [==============================] - 0s 36ms/step - loss: 0.6960 - acc: 0.4500 - val_loss: 0.6794 - val_acc: 0.5000 # Epoch 2/2 # # 1/10 [==>...........................] - ETA: 0s - loss: 0.6829 - acc: 0.5000count:12 # count:13 # count:14 # count:15 # # 5/10 [==============>...............] - ETA: 0s - loss: 0.6800 - acc: 0.5000count:16 # count:17 # count:18 # count:19 # count:20 # # 10/10 [==============================] - 0s 11ms/step - loss: 0.6766 - acc: 0.5000 - val_loss: 0.6662 - val_acc: 0.5000
補充知識:
自動生成數據還可以繼承keras.utils.Sequence,然后寫自己的生成數據類:
keras數據自動生成器,繼承keras.utils.Sequence,結合fit_generator實現節約內存訓練
#coding=utf-8 ''' Created on 2018-7-10 ''' import keras import math import os import cv2 import numpy as np from keras.models import Sequential from keras.layers import Dense class DataGenerator(keras.utils.Sequence): def __init__(self, datas, batch_size=1, shuffle=True): self.batch_size = batch_size self.datas = datas self.indexes = np.arange(len(self.datas)) self.shuffle = shuffle def __len__(self): #計算每一個epoch的迭代次數 return math.ceil(len(self.datas) / float(self.batch_size)) def __getitem__(self, index): #生成每個batch數據,這里就根據自己對數據的讀取方式進行發揮了 # 生成batch_size個索引 batch_indexs = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # 根據索引獲取datas集合中的數據 batch_datas = [self.datas[k] for k in batch_indexs] # 生成數據 X, y = self.data_generation(batch_datas) return X, y def on_epoch_end(self): #在每一次epoch結束是否需要進行一次隨機,重新隨機一下index if self.shuffle == True: np.random.shuffle(self.indexes) def data_generation(self, batch_datas): images = [] labels = [] # 生成數據 for i, data in enumerate(batch_datas): #x_train數據 image = cv2.imread(data) image = list(image) images.append(image) #y_train數據 right = data.rfind("\\",0) left = data.rfind("\\",0,right)+1 class_name = data[left:right] if class_name=="dog": labels.append([0,1]) else: labels.append([1,0]) #如果為多輸出模型,Y的格式要變一下,外層list格式包裹numpy格式是list[numpy_out1,numpy_out2,numpy_out3] return np.array(images), np.array(labels) # 讀取樣本名稱,然后根據樣本名稱去讀取數據 class_num = 0 train_datas = [] for file in os.listdir("D:/xxx"): file_path = os.path.join("D:/xxx", file) if os.path.isdir(file_path): class_num = class_num + 1 for sub_file in os.listdir(file_path): train_datas.append(os.path.join(file_path, sub_file)) # 數據生成器 training_generator = DataGenerator(train_datas) #構建網絡 model = Sequential() model.add(Dense(units=64, activation='relu', input_dim=784)) model.add(Dense(units=2, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) model.fit_generator(training_generator, epochs=50,max_queue_size=10,workers=1)
看完了這篇文章,相信你對關于keras訓練模型fit和fit_generator的案例有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。