Keras 在fit_generator訓(xùn)練方式中加入圖像random_crop操作
使用Keras作前端寫(xiě)網(wǎng)絡(luò)時(shí),由于訓(xùn)練圖像尺寸較大,需要做類(lèi)似 tf.random_crop 圖像裁剪操作。
為此研究了一番Keras下已封裝的API。
Data Augmentation(數(shù)據(jù)擴(kuò)充)
Data Aumentation 指使用下面或其他方法增加輸入數(shù)據(jù)量。我們默認(rèn)圖像數(shù)據(jù)。
旋轉(zhuǎn)&反射變換(Rotation/reflection): 隨機(jī)旋轉(zhuǎn)圖像一定角度; 改變圖像內(nèi)容的朝向;
翻轉(zhuǎn)變換(flip): 沿著水平或者垂直方向翻轉(zhuǎn)圖像;
縮放變換(zoom): 按照一定的比例放大或者縮小圖像;
平移變換(shift): 在圖像平面上對(duì)圖像以一定方式進(jìn)行平移;
可以采用隨機(jī)或人為定義的方式指定平移范圍和平移步長(zhǎng), 沿水平或豎直方向進(jìn)行平移. 改變圖像內(nèi)容的位置;
尺度變換(scale): 對(duì)圖像按照指定的尺度因子, 進(jìn)行放大或縮小; 或者參照SIFT特征提取思想, 利用指定的尺度因子對(duì)圖像濾波構(gòu)造尺度空間. 改變圖像內(nèi)容的大小或模糊程度;
對(duì)比度變換(contrast): 在圖像的HSV顏色空間,改變飽和度S和V亮度分量,保持色調(diào)H不變. 對(duì)每個(gè)像素的S和V分量進(jìn)行指數(shù)運(yùn)算(指數(shù)因子在0.25到4之間), 增加光照變化;
噪聲擾動(dòng)(noise): 對(duì)圖像的每個(gè)像素RGB進(jìn)行隨機(jī)擾動(dòng), 常用的噪聲模式是椒鹽噪聲和高斯噪聲;
Data Aumentation 有很多好處,比如數(shù)據(jù)量較少時(shí),用數(shù)據(jù)擴(kuò)充來(lái)增加訓(xùn)練數(shù)據(jù),防止過(guò)擬合。
ImageDataGenerator
在Keras中,ImageDataGenerator就是專(zhuān)門(mén)做數(shù)據(jù)擴(kuò)充的。
from keras.preprocessing.image import ImageDataGenerator
注:Using TensorFlow backend.
官方寫(xiě)法如下:
(x_train, y_train), (x_test, y_test) = cifar10.load_data() datagen = ImageDataGenerator( featurewise_center=True, ... horizontal_flip=True) # compute quantities required for featurewise normalization datagen.fit(x_train) # 使用fit_generator的【自動(dòng)】訓(xùn)練方法: fits the model on batches with real-time data augmentation model.fit_generator(datagen.flow(x_train, y_train, batch_size=32), steps_per_epoch=len(x_train), epochs=epochs) # 自己寫(xiě)range循環(huán)的【手動(dòng)】訓(xùn)練方法 for e in range(epochs): print 'Epoch', e batches = 0 for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32): loss = model.train(x_batch, y_batch) batches += 1 if batches >= len(x_train) / 32: # we need to break the loop by hand because # the generator loops indefinitely break
ImageDataGenerator的參數(shù)說(shuō)明見(jiàn)官網(wǎng)文檔。
上面兩種訓(xùn)練方法的差異不討論,我們要關(guān)注的是:官方封裝的訓(xùn)練集batch生成器是ImageDataGenerator對(duì)象的flow方法(或flow_from_directory),該函數(shù)返回一個(gè)和python定義相似的generator。在它前一步,數(shù)據(jù)變換是ImageDataGenerator對(duì)象的fit方法。
random_crop并未在ImageDataGenerator中內(nèi)置,但參數(shù)中給了一個(gè)preprocessing_function,我們可以利用它自定義my_random_crop函數(shù),像下面這樣寫(xiě):
def my_random_crop(image): random_arr = numpy.random.randint(img_sz-crop_sz+1, size=2) y = int(random_arr[0]) x = int(random_arr[1]) h = img_crop w = img_crop image_crop = image[y:y+h, x:x+w, :] return image_crop datagen = ImageDataGenerator( featurewise_center=False, ··· preprocessing_function=my_random_crop) datagen.fit(x_train)
fit方法調(diào)用時(shí)將預(yù)設(shè)的變換應(yīng)用到x_train的每張圖上,包括圖像crop,因?yàn)槭菃螐堃来翁幚恚繌垐D的crop位置隨機(jī)。
在訓(xùn)練數(shù)據(jù)(x=image, y=class_label)時(shí)這樣寫(xiě)已滿(mǎn)足要求;
但在(x=image, y=image_mask)時(shí)該方法就不成立了。圖像單張?zhí)幚淼木壒?,一?duì)(image, image_mask)分別crop的位置無(wú)法保持一致。
雖然官網(wǎng)也給出了同時(shí)變換image和mask的寫(xiě)法,但它提出的方案能保證二者內(nèi)置函數(shù)的變換一致,自定義函數(shù)的random變量仍是隨機(jī)的。
fit_generator
既然ImageDataGenerator和flow方法不能滿(mǎn)足我們的random_crop預(yù)處理要求,就在fit_generator函數(shù)處想方法修改。
先看它的定義:
def fit_generator(self, generator, samples_per_epoch, nb_epoch, verbose=1, callbacks=[], validation_data=None, nb_val_samples=None, class_weight=None, max_q_size=10, **kwargs):
第一個(gè)參數(shù)generator,可以傳入一個(gè)方法,也可以直接傳入數(shù)據(jù)集。前面的 datagen.flow() 即是Keras封裝的批量數(shù)據(jù)傳入方法。
顯然,我們可以自定義。
def generate_batch_data_random(x, y, batch_size): """分批取batch數(shù)據(jù)加載到顯存""" total_num = len(x) batches = total_num // batch_size while (True): i = randint(0, batches) x_batch = x[i*batch_size:(i+1)*batch_size] y_batch = y[i*batch_size:(i+1)*batch_size] random_arr = numpy.random.randint(img_sz-crop_sz+1, size=2) y_pos = int(random_arr[0]) x_pos = int(random_arr[1]) x_crop = x_batch[:, y_pos:y_pos+crop_sz, x_pos:x_pos+crop_sz, :] y_crop = y_batch[:, y_pos:y_pos+crop_sz, x_pos:x_pos+crop_sz, :] yield (x_crop, y_crop)
這樣寫(xiě)就符合我們同組image和mask位置一致的random_crop要求。
注意:
由于沒(méi)有使用ImageDataGenerator內(nèi)置的數(shù)據(jù)變換方法,數(shù)據(jù)擴(kuò)充則也需要自定義;由于沒(méi)有使用flow(…, shuffle=True,)方法,每個(gè)epoch的數(shù)據(jù)打亂需要自定義。
generator自定義時(shí)要寫(xiě)成死循環(huán),因?yàn)樵诿總€(gè)epoch內(nèi),generate_batch_data_random是不會(huì)重復(fù)調(diào)用的。
補(bǔ)充知識(shí):tensorflow中的隨機(jī)裁剪函數(shù)random_crop
tf.random_crop是tensorflow中的隨機(jī)裁剪函數(shù),可以用來(lái)裁剪圖片。我采用如下圖片進(jìn)行隨機(jī)裁剪,裁剪大小為原圖的一半。

如下是實(shí)驗(yàn)代碼
import tensorflow as tf
import matplotlib.image as img
import matplotlib.pyplot as plt
sess = tf.InteractiveSession()
image = img.imread('D:/Documents/Pictures/logo3.jpg')
reshaped_image = tf.cast(image,tf.float32)
size = tf.cast(tf.shape(reshaped_image).eval(),tf.int32)
height = sess.run(size[0]//2)
width = sess.run(size[1]//2)
distorted_image = tf.random_crop(reshaped_image,[height,width,3])
print(tf.shape(reshaped_image).eval())
print(tf.shape(distorted_image).eval())
fig = plt.figure()
fig1 = plt.figure()
ax = fig.add_subplot(111)
ax1 = fig1.add_subplot(111)
ax.imshow(sess.run(tf.cast(reshaped_image,tf.uint8)))
ax1.imshow(sess.run(tf.cast(distorted_image,tf.uint8)))
plt.show()
如下是隨機(jī)實(shí)驗(yàn)兩次的結(jié)果


以上這篇Keras 在fit_generator訓(xùn)練方式中加入圖像random_crop操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python random模塊制作簡(jiǎn)易的四位數(shù)驗(yàn)證碼
這篇文章主要介紹了Python random模塊制作簡(jiǎn)易的四位數(shù)驗(yàn)證碼,文中給大家提到了python中random模塊的相關(guān)知識(shí),需要的朋友可以參考下2020-02-02
簡(jiǎn)單了解python中對(duì)象的取反運(yùn)算符
這篇文章主要介紹了簡(jiǎn)單了解python中對(duì)象的取反運(yùn)算符,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
python登陸asp網(wǎng)站頁(yè)面的實(shí)現(xiàn)代碼
這篇文章主要介紹了python登陸asp網(wǎng)站頁(yè)面的實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-01-01
Python利用txt文件對(duì)Mysql進(jìn)行增刪改查移
這篇文章主要介紹了如何在Python中利用TXT文件對(duì)Mysql中的記錄進(jìn)行增刪改查移,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)學(xué)習(xí)2021-12-12
Python pandas 計(jì)算每行的增長(zhǎng)率與累計(jì)增長(zhǎng)率
這篇文章主要介紹了Python pandas 計(jì)算每行的增長(zhǎng)率與累計(jì)增長(zhǎng)率,文章舉例詳細(xì)說(shuō)明。需要的小伙伴可以參考一下2022-03-03
Python Requests訪(fǎng)問(wèn)網(wǎng)絡(luò)更方便
這篇文章主要介紹了使用Python Requests訪(fǎng)問(wèn)網(wǎng)絡(luò),Python Requests 是一個(gè)非常強(qiáng)大的 HTTP 客戶(hù)端庫(kù),用于發(fā)送 HTTP 請(qǐng)求,獲取響應(yīng)等操作,通過(guò)這個(gè)庫(kù),你可以輕松地與 Web 服務(wù)進(jìn)行交互,實(shí)現(xiàn)各種網(wǎng)絡(luò)請(qǐng)求2024-01-01
在pytorch中實(shí)現(xiàn)只讓指定變量向后傳播梯度
今天小編就為大家分享一篇在pytorch中實(shí)現(xiàn)只讓指定變量向后傳播梯度,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
關(guān)于Python排序問(wèn)題(冒泡/選擇/插入)
這篇文章主要介紹了關(guān)于Python排序問(wèn)題(冒泡/選擇/插入),學(xué)過(guò)C語(yǔ)言肯定接觸過(guò)排序問(wèn)題,我們最常用的也就是冒泡排序、選擇排序、插入排序,需要的朋友可以參考下2023-04-04

