猫狗分类--Tensorflow实现
貼一張自己畫的思維導圖?
數據集準備?
kaggle貓狗大戰數據集(訓練),微軟的不需要FQ
- 12500張cat
- 12500張dog
生成圖片路徑和標簽的List
step1:獲取D:/Study/Python/Projects/Cats_vs_Dogs/data/Cat下所有的貓圖路徑名,存放到cats中,同時貼上標簽0,存放到label_cats中。狗圖同理。
train_dir = 'D:/Study/Python/Projects/Cats_vs_Dogs/data'def get_files(file_dir): for file in os.listdir(file_dir+'/Cat'): cats.append(file_dir +'/Cat'+'/'+ file) label_cats.append(0) for file in os.listdir(file_dir+'/Dog'): dogs.append(file_dir +'/Dog'+'/'+file) label_dogs.append(1)step2:對生成的圖片路徑和標簽List做打亂處理
#把cat和dog合起來組成一個list(img和lab)image_list = np.hstack((cats, dogs))label_list = np.hstack((label_cats, label_dogs))#利用shuffle打亂順序temp = np.array([image_list, label_list]) temp = temp.transpose() np.random.shuffle(temp) #從打亂的temp中再取出list(img和lab) image_list = list(temp[:, 0]) label_list = list(temp[:, 1]) label_list = [int(i) for i in label_list]生成Batch
step1:將上面生成的List傳入get_batch() ,轉換類型,產生一個輸入隊列queue,因為img和lab是分開的,所以使用tf.train.slice_input_producer(),然后用tf.read_file()從隊列中讀取圖像
- image_W, image_H, :設置好固定的圖像高度和寬度
- 設置batch_size:每個batch要放多少張圖片
- capacity:一個隊列最大多少
step2:將圖像解碼,不同類型的圖像不能混在一起,要么只用jpeg,要么只用png等。
image = tf.image.decode_jpeg(image_contents, channels=3)step3:數據預處理,對圖像進行旋轉、縮放、裁剪、歸一化等操作,讓計算出的模型更健壯。
image = tf.image.resize_image_with_crop_or_pad(image, image_W, image_H)image = tf.image.per_image_standardization(image)4:生成batch
- image_batch: 4D tensor [batch_size, width, height, 3],dtype=tf.float32
- label_batch: 1D tensor [batch_size], dtype=tf.int32
測試
step1:變量初始化,每批2張圖,尺寸208x208,設置好自己的圖像路徑
BATCH_SIZE = 2 CAPACITY = 256 IMG_W = 208 IMG_H = 208 train_dir = 'D:/Study/Python/Projects/Cats_vs_Dogs/data'step2:調用前面的兩個函數,生成batch
image_list, label_list = get_files(train_dir) image_batch, label_batch = get_batch(image_list, label_list, IMG_W, IMG_H, BATCH_SIZE, CAPACITY)step3:開啟會話session,利用tf.train.Coordinator()和tf.train.start_queue_runners(coord=coord)來監控隊列(這里有個問題:官網的start_queue_runners()是有兩個參數的,sess和coord,但是在這里加上sess的話會報錯)。?
利用try——except——finally結構來執行隊列操作(官網推薦的方法),避免程序卡死什么的。i<2執行兩次隊列操作,每一次取出2張圖放進batch里面,然后imshow出來看看效果。
step4:查看結果,會出現4張圖,resize的效果感覺不是很好,不知道是什么問題?
2017.7.10 圖片不正常是因為生成batch的時候將image轉成了浮點型,吧image_batch = tf.cast(image_batch, tf.float32)注釋掉后就好了
?
轉載于:https://www.cnblogs.com/jyxbk/p/7750451.html
總結
以上是生活随笔為你收集整理的猫狗分类--Tensorflow实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MVC Razor模板引擎 @Rende
- 下一篇: 有关Android launchMode