zoukankan      html  css  js  c++  java
  • Fine-tuning CaffeNet for Style Recognition on “Flickr Style” Data 数据下载遇到的问题

    (下载的时候没有提示 不知道是正在下 还是出现错误 卡着了)。。一直没有反应 

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

    或者在命令前加sudo

    参考了 http://blog.csdn.net/lujiandong1/article/details/50495454

    在使用这个教程时,主要遇到了两个问题:

    1、数据下不下来。

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

    运行上述指令时,程序莫名其妙就不动了,也不下载文件,程序也没有挂掉,好像进入了死锁状态。

    查看源程序:assemble_data.py,可以看出assemble_data.py用了大量多线程,多进程。我的解决方案就是改源程序,不使用进程来下载了。并且,对下载进行了超时限定,超过6s就认为超时,进而不下载。

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

    assemble_data.py中使用多线程,多进程的源代码如下:

    [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]))  
     


    修改主要有以下几点:

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

    2、

    [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)。

    经过上述改进,就可以把数据下载下来。

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

    2、

    在运行命令: 

    [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

  • 相关阅读:
    [LeetCode] Construct Binary Tree from Inorder and Pretorder Traversal
    [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
    [LeetCode] Candy
    [LeetCode] Next Permutation
    [LeetCode] Permutation Sequence
    [LeetCode] Permutations II
    【转载pku】三十分钟掌握STL
    [LeetCode] Permutations
    【附论文】Facebook推面部识别软件 精准度高达97.25%
    【转载】limits.h
  • 原文地址:https://www.cnblogs.com/is-Tina/p/7739163.html
Copyright © 2011-2022 走看看