使用Tensorflow將自己的數(shù)據(jù)分割成batch訓(xùn)練實(shí)例
學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)的時(shí)候,網(wǎng)上的數(shù)據(jù)集已經(jīng)分割成了batch,訓(xùn)練的時(shí)候直接使用batch.next()就可以獲取batch,但是有的時(shí)候需要使用自己的數(shù)據(jù)集,然而自己的數(shù)據(jù)集不是batch形式,就需要將其轉(zhuǎn)換為batch形式,本文將介紹一個(gè)將數(shù)據(jù)打包成batch的方法。
一、tf.slice_input_producer()
首先需要講解兩個(gè)函數(shù),第一個(gè)函數(shù)是 :tf.slice_input_producer(),這個(gè)函數(shù)的作用是從輸入的tensor_list按要求抽取一個(gè)tensor放入文件名隊(duì)列,下面解釋下各個(gè)參數(shù):
tf.slice_input_producer(tensor_list, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None)
tensor_list 這個(gè)就是輸入,格式為tensor的列表;一般為[data, label],即由特征和標(biāo)簽組成的數(shù)據(jù)集
num_epochs 這個(gè)是你抽取batch的次數(shù),如果沒(méi)有給定值,那么將會(huì)抽取無(wú)數(shù)次batch(這會(huì)導(dǎo)致你訓(xùn)練過(guò)程停不下來(lái)),如果給定值,那么在到達(dá)次數(shù)之后就會(huì)報(bào)OutOfRange的錯(cuò)誤
shuffle 是否隨機(jī)打亂,如果為False,batch是按順序抽?。蝗绻麨門(mén)rue,batch是隨機(jī)抽取
seed 隨機(jī)種子
capcity 隊(duì)列容量的大小,為整數(shù)
name 名稱
舉個(gè)例子:我的data的shape為(4000,10),label的shape為(4000,2),運(yùn)行下面這行代碼
input_queue = tf.train.slice_input_producer([data, label], num_epochs=1, shuffle=True, capacity=32 )
結(jié)果如圖,可以看出返回值為一個(gè)包含兩組數(shù)據(jù)的list,每個(gè)list的shape與輸入的data和label的shape對(duì)應(yīng)
二、tf.train.batch()& tf.train.shuffle_batch()
第二個(gè)函數(shù)為:tf.train.batch(),tf.train.shuffle_batch(),這個(gè)函數(shù)的作用為生成大小為batch_size的tensor,下面解釋下各個(gè)參數(shù):
tf.train.batch([data, label], batch_size=batch_size, capacity=capacity,num_threads=num_thread,allow_smaller_final_batch= True) tf.train.shuffle_batch([example, label], batch_size=batch_size, capacity=capacity,num_threads=num_thread,allow_smaller_final_batch=True)
[data,label] 輸入的樣本和標(biāo)簽
batch_size batch的大小
capcity 隊(duì)列的容量
num_threads 線程數(shù),使用多少個(gè)線程來(lái)控制整個(gè)隊(duì)列
allow_smaller_final_batch 這個(gè)是當(dāng)最后的幾個(gè)樣本不夠組成一個(gè)batch的時(shí)候用的參數(shù),如果為T(mén)rue則會(huì)重新組成一個(gè)batch
下面給出生成batch的函數(shù),由上面兩個(gè)函數(shù)組成:
def get_Batch(data, label, batch_size): print(data.shape, label.shape) input_queue = tf.train.slice_input_producer([data, label], num_epochs=1, shuffle=True, capacity=32 ) x_batch, y_batch = tf.train.batch(input_queue, batch_size=batch_size, num_threads=1, capacity=32, allow_smaller_final_batch=False) return x_batch, y_batch
還是同樣的輸入,batch_size設(shè)為2000,看下運(yùn)行后的返回值的shape:
可以發(fā)現(xiàn),返回是樣本數(shù)目為2000的tensor,也就是達(dá)到了將自己的數(shù)據(jù)打包成batch的功能
三、batch的使用方法
生成batch只完成了一半,后面的使用方法也比較復(fù)雜,直接上一個(gè)完整的程序來(lái)講解會(huì)方便理解一些:下面代碼構(gòu)建了一個(gè)單層感知機(jī),對(duì)數(shù)據(jù)進(jìn)行分類,主要看一下訓(xùn)練過(guò)程中如何使用生成好了的batch,具體細(xì)節(jié)都寫(xiě)在注釋里面了。
import tensorflow as tf import scipy.io as sio import numpy as np def get_Batch(data, label, batch_size): print(data.shape, label.shape) input_queue = tf.train.slice_input_producer([data, label], num_epochs=1, shuffle=True, capacity=32 ) x_batch, y_batch = tf.train.batch(input_queue, batch_size=batch_size, num_threads=1, capacity=32, allow_smaller_final_batch=False) return x_batch, y_batch data = sio.loadmat('data.mat') train_x = data['train_x'] train_y = data['train_y'] test_x = data['test_x'] test_y = data['test_y'] x = tf.placeholder(tf.float32, [None, 10]) y = tf.placeholder(tf.float32, [None, 2]) w = tf.Variable(tf.truncated_normal([10, 2], stddev=0.1)) b = tf.Variable(tf.truncated_normal([2], stddev=0.1)) pred = tf.nn.softmax(tf.matmul(x, w) + b) loss = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices=[1])) optimizer = tf.train.AdamOptimizer(2e-5).minimize(loss) correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(pred, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='evaluation') x_batch, y_batch = get_Batch(train_x, train_y, 1000) # 訓(xùn)練 with tf.Session() as sess: #初始化參數(shù) sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) # 開(kāi)啟協(xié)調(diào)器 coord = tf.train.Coordinator() # 使用start_queue_runners 啟動(dòng)隊(duì)列填充 threads = tf.train.start_queue_runners(sess, coord) epoch = 0 try: while not coord.should_stop(): # 獲取訓(xùn)練用的每一個(gè)batch中batch_size個(gè)樣本和標(biāo)簽 data, label = sess.run([x_batch, y_batch]) sess.run(optimizer, feed_dict={x: data, y: label}) train_accuracy = accuracy.eval({x: data, y: label}) test_accuracy = accuracy.eval({x: test_x, y: test_y}) print("Epoch %d, Training accuracy %g, Testing accuracy %g" % (epoch, train_accuracy, test_accuracy)) epoch = epoch + 1 except tf.errors.OutOfRangeError: # num_epochs 次數(shù)用完會(huì)拋出此異常 print("---Train end---") finally: # 協(xié)調(diào)器coord發(fā)出所有線程終止信號(hào) coord.request_stop() print('---Programm end---') coord.join(threads) # 把開(kāi)啟的線程加入主線程,等待threads結(jié)束
總共訓(xùn)練的次數(shù)為(樣本數(shù)目/batch_size)*num_epochs
四、 簡(jiǎn)單生成Batch的方法
最近發(fā)現(xiàn)了一種簡(jiǎn)單生生成batch的方法,實(shí)現(xiàn)簡(jiǎn)單,操作方便,就是時(shí)間復(fù)雜度可能高了一點(diǎn),直接上代碼。通過(guò)np.random.choice方法每次在范圍[0, len(all_data))內(nèi)抽取大小為size的索引。然后通過(guò)這部分索引構(gòu)建batch。
epoch = 150 for i in tqdm(range(epoch)): # 在total_train_xs, total_train_ys數(shù)據(jù)集中隨機(jī)抽取batch_size個(gè)樣本出來(lái) # 作為本輪迭代的訓(xùn)練數(shù)據(jù)batch_xs, batch_ys batch_size = 1000 sample_idxs = np.random.choice(range(len(all_data)), size=batch_size) batch_xs = [] batch_ys = [] val_sample_idxs = np.random.choice(range(len(all_data)), size=batch_size) val_batch_xs = [] val_batch_ys = [] for j in range(batch_size): train_id = sample_idxs[j] batch_xs.append(all_data[train_id]) batch_ys.append(all_label[train_id]) val_id = val_sample_idxs[j] val_batch_xs.append(all_data[val_id]) val_batch_ys.append(all_label[val_id]) batch_xs = np.array(batch_xs) batch_ys = np.array(batch_ys) val_batch_xs = np.array(val_batch_xs) val_batch_ys = np.array(val_batch_ys) # 喂訓(xùn)練數(shù)據(jù)進(jìn)去訓(xùn)練 sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) if i % 50 == 0: y_train_pred = np.array(sess.run(y, feed_dict={x: batch_xs})).reshape(len(batch_xs)) y_pred = np.array(sess.run(y, feed_dict={x: val_batch_xs})).reshape(len(val_batch_xs)) # draw(y_test, y_pred) print("Iteration %d, train RMSE %f, val RMSE %f" % (i, calcaulateRMSE(batch_ys, y_train_pred), calcaulateRMSE(val_batch_ys, y_pred)))
以上這篇使用Tensorflow將自己的數(shù)據(jù)分割成batch訓(xùn)練實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
對(duì)Tensorflow中tensorboard日志的生成與顯示詳解
今天小編就為大家分享一篇對(duì)Tensorflow中tensorboard日志的生成與顯示詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02Python全面解析json數(shù)據(jù)并保存為csv文件
這篇文章主要介紹了Python全面解析json數(shù)據(jù)并保存為csv文件,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07Python用imghdr模塊識(shí)別圖片格式實(shí)例解析
這篇文章主要介紹了Python用imghdr模塊識(shí)別圖片格式實(shí)例解析,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01詳解利用Pandas求解兩個(gè)DataFrame的差集,交集,并集
這篇文章主要和大家講解一下如何利用Pandas函數(shù)求解兩個(gè)DataFrame的差集、交集、并集,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-07-07python socket網(wǎng)絡(luò)編程步驟詳解(socket套接字使用)
這篇文章主要介紹了什么是套接字、PYTHON套接字模塊,提供一個(gè)簡(jiǎn)單的python socket編程,大家參考使用2013-12-12django 解決擴(kuò)展自帶User表遇到的問(wèn)題
這篇文章主要介紹了django 解決擴(kuò)展自帶User表遇到的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05