成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

TensorFlow和Keras解決大數據量內存溢出問題

存儲 存儲軟件
解決思路其實說來也簡單,打破思維定式就好了,不是把所有圖片讀到內存中,而是只把所有圖片的路徑一次性讀到內存中。

以前做的練手小項目導致新手產生一個慣性思維——讀取訓練集圖片的時候把所有圖讀到內存中,然后分批訓練。

其實這是有問題的,很容易導致OOM。現在內存一般16G,而訓練集圖片通常是上萬張,而且RGB圖,還很大,VGG16的圖片一般是224x224x3,上萬張圖片,16G內存根本不夠用。這時候又會想起——設置batch,但是那個batch的輸入參數卻又是圖片,它只是把傳進去的圖片分批送到顯卡,而我OOM的地方恰是那個“傳進去”的圖片,怎么辦?

解決思路其實說來也簡單,打破思維定式就好了,不是把所有圖片讀到內存中,而是只把所有圖片的路徑一次性讀到內存中。

[[229304]]

大致的解決思路為:

將上萬張圖片的路徑一次性讀到內存中,自己實現一個分批讀取函數,在該函數中根據自己的內存情況設置讀取圖片,只把這一批圖片讀入內存中,然后交給模型,模型再對這一批圖片進行分批訓練,因為內存一般大于等于顯存,所以內存的批次大小和顯存的批次大小通常不相同。

下面代碼分別介紹Tensorflow和Keras分批將數據讀到內存中的關鍵函數。Tensorflow對初學者不太友好,所以我個人現階段更習慣用它的高層API Keras來做相關項目,下面的TF實現是之前不會用Keras分批讀時候參考的一些列資料,在模型訓練上仍使用Keras,只有分批讀取用了TF的API。

TensorFlow

在input.py里寫get_batch函數。

  1. def get_batch(X_train, y_train, img_w, img_h, color_type, batch_size, capacity): 
  2.    ''
  3.    Args: 
  4.        X_train: train img path list 
  5.        y_train: train labels list 
  6.        img_w: image width 
  7.        img_h: image height 
  8.        batch_size: batch size 
  9.        capacity: the maximum elements in queue 
  10.    Returns
  11.        X_train_batch: 4D tensor [batch_size, width, height, chanel],\ 
  12.                        dtype=tf.float32 
  13.        y_train_batch: 1D tensor [batch_size], dtype=int32 
  14.    ''
  15.    X_train = tf.cast(X_train, tf.string) 
  16.  
  17.    y_train = tf.cast(y_train, tf.int32)     
  18.    # make an input queue 
  19.    input_queue = tf.train.slice_input_producer([X_train, y_train]) 
  20.  
  21.    y_train = input_queue[1] 
  22.    X_train_contents = tf.read_file(input_queue[0]) 
  23.    X_train = tf.image.decode_jpeg(X_train_contents, channels=color_type) 
  24.  
  25.    X_train = tf.image.resize_images(X_train, [img_h, img_w],  
  26.                                     tf.image.ResizeMethod.NEAREST_NEIGHBOR) 
  27.  
  28.    X_train_batch, y_train_batch = tf.train.batch([X_train, y_train], 
  29.                                                  batch_size=batch_size, 
  30.                                                  num_threads=64, 
  31.                                                  capacity=capacity) 
  32.    y_train_batch = tf.one_hot(y_train_batch, 10)    return X_train_batch, y_train_batch 

在train.py文件中訓練(下面不是純TF代碼,model.fit是Keras的擬合,用純TF的替換就好了)。

  1. X_train_batch, y_train_batch = inp.get_batch(X_train, y_train,  
  2.                                             img_w, img_h, color_type,  
  3.                                             train_batch_size, capacity) 
  4. X_valid_batch, y_valid_batch = inp.get_batch(X_valid, y_valid,  
  5.                                             img_w, img_h, color_type,  
  6.                                             valid_batch_size, capacity)with tf.Session() as sess: 
  7.  
  8.    coord = tf.train.Coordinator() 
  9.    threads = tf.train.start_queue_runners(coord=coord)    
  10.  try:        
  11.  for step in np.arange(max_step):             
  12. if coord.should_stop() :                 
  13. break 
  14.            X_train, y_train = sess.run([X_train_batch,  
  15.                                             y_train_batch]) 
  16.            X_valid, y_valid = sess.run([X_valid_batch, 
  17.                                             y_valid_batch]) 
  18.               
  19.            ckpt_path = 'log/weights-{val_loss:.4f}.hdf5' 
  20.            ckpt = tf.keras.callbacks.ModelCheckpoint(ckpt_path,  
  21.                                                      monitor='val_loss',  
  22.                                                      verbose=1,  
  23.                                                      save_best_only=True,  
  24.                                                      mode='min'
  25.            model.fit(X_train, y_train, batch_size=64,  
  26.                          epochs=50, verbose=1, 
  27.                          validation_data=(X_valid, y_valid), 
  28.                          callbacks=[ckpt])             
  29.            del X_train, y_train, X_valid, y_valid     
  30. except tf.errors.OutOfRangeError: 
  31.        print('done!')    finally: 
  32.        coord.request_stop() 
  33.    coord.join(threads) 
  34.    sess.close() 

Keras

keras文檔中對fit、predict、evaluate這些函數都有一個generator,這個generator就是解決分批問題的。

關鍵函數:fit_generator

  1. # 讀取圖片函數 
  2. def get_im_cv2(paths, img_rows, img_cols, color_type=1, normalize=True): 
  3.    ''
  4.    參數: 
  5.        paths:要讀取的圖片路徑列表 
  6.        img_rows:圖片行 
  7.        img_cols:圖片列 
  8.        color_type:圖片顏色通道 
  9.    返回:  
  10.        imgs: 圖片數組 
  11.    ''
  12.    # Load as grayscale 
  13.    imgs = []    for path in paths:         
  14. if color_type == 1: 
  15.            img = cv2.imread(path, 0)         
  16. elif color_type == 3: 
  17.            img = cv2.imread(path)         
  18. # Reduce size 
  19.        resized = cv2.resize(img, (img_cols, img_rows))        
  20.  if normalize: 
  21.            resized = resized.astype('float32'
  22.            resized /= 127.5 
  23.            resized -= 1.  
  24.         
  25.        imgs.append(resized)         
  26.    return np.array(imgs).reshape(len(paths), img_rows, img_cols, color_type) 

獲取批次函數,其實就是一個generator

  1. def get_train_batch(X_train, y_train, batch_size, img_w, img_h, color_type, is_argumentation): 
  2.    ''
  3.    參數: 
  4.        X_train:所有圖片路徑列表 
  5.        y_train: 所有圖片對應的標簽列表 
  6.        batch_size:批次 
  7.        img_w:圖片寬 
  8.        img_h:圖片高 
  9.        color_type:圖片類型 
  10.        is_argumentation:是否需要數據增強 
  11.    返回:  
  12.        一個generator, 
  13. x: 獲取的批次圖片  
  14. y: 獲取的圖片對應的標簽 
  15.    ''
  16.    while 1:         
  17. for i in range(0, len(X_train), batch_size): 
  18.            x = get_im_cv2(X_train[i:i+batch_size], img_w, img_h, color_type) 
  19.            y = y_train[i:i+batch_size]             
  20. if is_argumentation:                 
  21. # 數據增強 
  22.                x, y = img_augmentation(x, y)             
  23. # 最重要的就是這個yield,它代表返回,返回以后循環還是會繼續,然后再返回。就比如有一個機器一直在作累加運算,但是會把每次累加中間結果告訴你一樣,直到把所有數加完 
  24.            yield({'input': x}, {'output': y}) 

訓練函數

  1. result = model.fit_generator(generator=get_train_batch(X_train, y_train, train_batch_size, img_w, img_h, color_type, True),  
  2.          steps_per_epoch=1351,  
  3.          epochs=50, verbose=1, 
  4.          validation_data=get_train_batch(X_valid, y_valid, valid_batch_size,img_w, img_h, color_type, False), 
  5.          validation_steps=52, 
  6.          callbacks=[ckpt, early_stop], 
  7.          max_queue_size=capacity, 
  8.          workers=1) 

就是這么簡單。但是當初從0到1的過程很難熬,每天都沒有進展,沒有頭緒,急躁占據了思維的大部,熬過了這個階段,就會一切順利,不是運氣,而是踩過的從0到1的每個腳印累積的靈感的爆發,從0到1的腳印越多,后面的路越順利。

責任編輯:武曉燕 來源: 人工智能LeadAI
相關推薦

2021-03-06 10:25:19

內存Java代碼

2021-02-03 15:12:08

java內存溢出

2010-09-26 15:53:25

JVM內存溢出

2009-12-08 15:19:58

WCF大數據量

2011-08-25 10:50:32

SQL Server數Performance

2024-04-25 10:06:03

內存泄漏

2011-04-18 11:13:41

bcp數據導入導出

2011-08-16 09:21:30

MySQL大數據量快速語句優化

2023-08-29 11:38:27

Java內存

2024-01-31 10:11:41

Redis內存

2010-12-01 09:18:19

數據庫優化

2024-01-29 08:45:38

MySQL大數據分頁

2022-03-25 09:01:16

CSS溢出屬性

2010-07-29 13:30:54

Hibari

2010-05-05 10:30:46

MongoDBNoSQL

2024-07-30 15:56:42

2018-04-02 15:37:33

數據庫MySQL翻頁

2018-09-06 16:46:33

數據庫MySQL分頁查詢

2012-12-26 09:23:56

數據庫優化

2024-09-09 09:41:03

內存溢出golang開發者
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久久久久久一区二区三区 | 日韩成人在线播放 | 老妇激情毛片免费 | 欧美综合一区 | 亚洲二区视频 | 精品乱码一区二区三四区视频 | 亚洲日韩视频 | 日韩二三区 | 日韩成人一区 | 在线观看免费av网 | 一区二区三区观看视频 | 亚洲综合网站 | 精品一区二区三区在线观看国产 | 久草在线 | www精品美女久久久tv | 日一区二区 | 欧美一级在线免费观看 | 97精品国产97久久久久久免费 | 日本在线看片 | 欧美日韩在线一区二区 | 在线观看免费黄色片 | 在线看片国产精品 | 中文字幕av在线 | 日韩一区二区视频 | 欧美精品一区二区三区蜜桃视频 | 色婷婷av99xx| 精品久久久久久久久久久院品网 | 欧美精品久久久久久 | 成年人黄色小视频 | 国产一区二区精品在线 | 国产精品久久久精品 | 精品视频一区二区三区在线观看 | 中文字幕高清 | 久久久久久久久毛片 | 国产激情一区二区三区 | 久草网视频 | 精精精精xxxx免费视频 | 91av视频在线免费观看 | 中文字幕日韩欧美一区二区三区 | 欧美日韩国产在线观看 | 国产精品中文字幕在线观看 |