Fine-tuning CaffeNet for Style Recognition on 「Flickr Style」 Data 數據下載遇到的問題

(下載的時候沒有提示 不知道是正在下 仍是出現錯誤 卡着了)。。一直沒有反應 html

下載前要以管理員身份運行 sudo su 再 python examples/finetune_flickr_style/assemble_data.py --workers=1 --images=2000 --seed 831486  python

或者在命令前加sudo服務器

參考了 http://blog.csdn.net/lujiandong1/article/details/50495454多線程

在使用這個教程時,主要遇到了兩個問題:app

一、數據下不下來。dom

[python]  view plain  copy
 
  1. python examples/finetune_flickr_style/assemble_data.py --workers=1 --images=2000 --seed 831486  

運行上述指令時,程序莫名其妙就不動了,也不下載文件,程序也沒有掛掉,好像進入了死鎖狀態。socket

 

查看源程序:assemble_data.py,能夠看出assemble_data.py用了大量多線程,多進程。個人解決方案就是改源程序,不使用進程來下載了。而且,對下載進行了超時限定,超過6s就認爲超時,進而不下載。ui

====================================================================================================url

assemble_data.py中使用多線程,多進程的源代碼以下:spa

 

[python]  view plain  copy
 
  1. pool = multiprocessing.Pool(processes=num_workers)  
  2. map_args = zip(df['image_url'], df['image_filename'])  
  3. results = pool.map(download_image, map_args)  

===================================================================================================

 

我修改後的源碼以下:

 

[python]  view plain  copy
 
  1. #!/usr/bin/env python3  
  2. """ 
  3. Form a subset of the Flickr Style data, download images to dirname, and write 
  4. Caffe ImagesDataLayer training file. 
  5. """  
  6. import os  
  7. import urllib  
  8. import hashlib  
  9. import argparse  
  10. import numpy as np  
  11. import pandas as pd  
  12. from skimage import io  
  13. import multiprocessing  
  14. import socket  
  15.   
  16.   
  17. # Flickr returns a special image if the request is unavailable.  
  18. MISSING_IMAGE_SHA1 = '6a92790b1c2a301c6e7ddef645dca1f53ea97ac2'  
  19.   
  20. example_dirname = os.path.abspath(os.path.dirname(__file__))  
  21. caffe_dirname = os.path.abspath(os.path.join(example_dirname, '../..'))  
  22. training_dirname = os.path.join(caffe_dirname, 'data/flickr_style')  
  23.   
  24.   
  25. def download_image(args_tuple):  
  26.     "For use with multiprocessing map. Returns filename on fail."  
  27.     try:  
  28.         url, filename = args_tuple  
  29.         if not os.path.exists(filename):  
  30.             urllib.urlretrieve(url, filename)  
  31.         with open(filename) as f:  
  32.             assert hashlib.sha1(f.read()).hexdigest() != MISSING_IMAGE_SHA1  
  33.         test_read_image = io.imread(filename)  
  34.         return True  
  35.     except KeyboardInterrupt:  
  36.         raise Exception()  # multiprocessing doesn't catch keyboard exceptions  
  37.     except:  
  38.         return False  
  39.   
  40. def mydownload_image(args_tuple):  
  41.     "For use with multiprocessing map. Returns filename on fail."  
  42.     try:  
  43.         url, filename = args_tuple  
  44.         if not os.path.exists(filename):  
  45.             urllib.urlretrieve(url, filename)  
  46.         with open(filename) as f:  
  47.             assert hashlib.sha1(f.read()).hexdigest() != MISSING_IMAGE_SHA1  
  48.         test_read_image = io.imread(filename)  
  49.         return True  
  50.     except KeyboardInterrupt:  
  51.         raise Exception()  # multiprocessing doesn't catch keyboard exceptions  
  52.     except:  
  53.         return False  
  54.   
  55.   
  56.   
  57. if __name__ == '__main__':  
  58.     parser = argparse.ArgumentParser(  
  59.         description='Download a subset of Flickr Style to a directory')  
  60.     parser.add_argument(  
  61.         '-s', '--seed', type=int, default=0,  
  62.         help="random seed")  
  63.     parser.add_argument(  
  64.         '-i', '--images', type=int, default=-1,  
  65.         help="number of images to use (-1 for all [default])",  
  66.     )  
  67.     parser.add_argument(  
  68.         '-w', '--workers', type=int, default=-1,  
  69.         help="num workers used to download images. -x uses (all - x) cores [-1 default]."  
  70.     )  
  71.     parser.add_argument(  
  72.         '-l', '--labels', type=int, default=0,  
  73.         help="if set to a positive value, only sample images from the first number of labels."  
  74.     )  
  75.   
  76.     args = parser.parse_args()  
  77.     np.random.seed(args.seed)  
  78.     # Read data, shuffle order, and subsample.  
  79.     csv_filename = os.path.join(example_dirname, 'flickr_style.csv.gz')  
  80.     df = pd.read_csv(csv_filename, index_col=0, compression='gzip')  
  81.     df = df.iloc[np.random.permutation(df.shape[0])]  
  82.     if args.labels > 0:  
  83.         df = df.loc[df['label'] < args.labels]  
  84.     if args.images > and args.images < df.shape[0]:  
  85.         df = df.iloc[:args.images]  
  86.   
  87.     # Make directory for images and get local filenames.  
  88.     if training_dirname is None:  
  89.         training_dirname = os.path.join(caffe_dirname, 'data/flickr_style')  
  90.     images_dirname = os.path.join(training_dirname, 'images')  
  91.     if not os.path.exists(images_dirname):  
  92.         os.makedirs(images_dirname)  
  93.     df['image_filename'] = [  
  94.         os.path.join(images_dirname, _.split('/')[-1]) for _ in df['image_url']  
  95.     ]  
  96.   
  97.     # Download images.  
  98.     num_workers = args.workers  
  99.     if num_workers <= 0:  
  100.         num_workers = multiprocessing.cpu_count() + num_workers  
  101.     print('Downloading {} images with {} workers...'.format(  
  102.         df.shape[0], num_workers))  
  103.     #pool = multiprocessing.Pool(processes=num_workers)  
  104.     map_args = zip(df['image_url'], df['image_filename'])  
  105.     #results = pool.map(download_image, map_args)  
  106.     socket.setdefaulttimeout(6)  
  107.     results = []  
  108.     for item in map_args:  
  109.         value = mydownload_image(item)  
  110.         results.append(value)  
  111.         if value == False:  
  112.                 print 'Flase'  
  113.         else:  
  114.                 print '1'  
  115.     # Only keep rows with valid images, and write out training file lists.  
  116.     print len(results)  
  117.     df = df[results]  
  118.     for split in ['train', 'test']:  
  119.         split_df = df[df['_split'] == split]  
  120.         filename = os.path.join(training_dirname, '{}.txt'.format(split))  
  121.         split_df[['image_filename', 'label']].to_csv(  
  122.             filename, sep=' ', header=None, index=None)  
  123.     print('Writing train/val for {} successfully downloaded images.'.format(  
  124.         df.shape[0]))  
 


修改主要有如下幾點:

 

一、#!/usr/bin/env python3 使用python3

二、

 

[python]  view plain  copy
 
  1. #pool = multiprocessing.Pool(processes=num_workers)  
  2.     map_args = zip(df['image_url'], df['image_filename'])  
  3.     #results = pool.map(download_image, map_args)  
  4.     socket.setdefaulttimeout(6)  
  5.     results = []  
  6.     for item in map_args:  
  7.         value = mydownload_image(item)  
  8.         results.append(value)  
  9.         if value == False:  
  10.                 print 'Flase'  
  11.         else:  
  12.                 print '1'  
  13.     # Only keep rows with valid images, and write out training file lists.  
  14.     print len(results)  

只使用單線程下載,不使用多線程,多進程下載。而且,設定鏈接的超時時間爲6s,socket.setdefaulttimeout(6)。

 

通過上述改進,就能夠把數據下載下來。

===================================================================================================

二、

在運行命令: 

 

[plain]  view plain  copy
 
  1. ./build/tools/caffe train -solver models/finetune_flickr_style/solver.prototxt -weights models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel  


時遇到錯誤:

 

Failed to parse NetParameter file: models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel

出錯的緣由是咱們傳入的數據bvlc_reference_caffenet.caffemodel 並非二進制的。

緣由:由於我是在win7下,把bvlc_reference_caffenet.caffemodel下載下來,再使用winSCP傳輸到服務器上,直接在服務器上使用wget下載,速度太慢了,可是在傳輸的過程當中winSCP就把bvlc_reference_caffenet.caffemodel的格式給篡改了,致使bvlc_reference_caffenet.caffemodel不是二進制的。

解決方案,把winSCP的傳輸格式設置成二進制,那麼就能夠解決這個問題。

詳情見博客:http://blog.chinaunix.net/uid-20332519-id-5585964.html

相關文章
相關標籤/搜索