2017-08-24 43 views
1

我是一名编程初学者,现在我的项目涉及图像分类。在深度学习课程的下面的代码中,有maybe_pickle这个功能,但我不知道“pickle”是做什么的,它有多大帮助,虽然我尝试过寻找一些答案。什么是“泡菜”实际用于?

def maybe_pickle(data_folders, min_num_images_per_class, force=False): 


dataset_names = [] 
    for folder in data_folders: 
    set_filename = folder + '.pickle' 
    dataset_names.append(set_filename) 
    if os.path.exists(set_filename) and not force: 
     # You may override by setting force=True. 
     print('%s already present - Skipping pickling.' % set_filename) 
    else: 
     print('Pickling %s.' % set_filename) 
     dataset = load_letter(folder, min_num_images_per_class) 
     try: 
     with open(set_filename, 'wb') as f: 
      pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) 
     except Exception as e: 
     print('Unable to save data to', set_filename, ':', e) 

    return dataset_names 

train_datasets = maybe_pickle(train_folders, 45000) 
test_datasets = maybe_pickle(test_folders, 1800) 
# import pickle 

# Create a list 
test_values = ['test value','test value 2','test value 3'] 


file_Name = "testfile" 
# Open the file for writing 
fileObject = open(file_Name,'wb') 

# This writes the object a to the 
# file named 'testfile' 
pickle.dump(test_values, fileObject) 

# Then we close the fileObject 
fileObject.close() 

# We then open the file for reading 
fileObject = open(file_Name,'r') 

# And the object from the file into var b 
test_values_loaded = pickle.load(fileObject) 
+1

酸洗将对象保存到文件中,以便它们可以在稍后再次加载它只是对象序列化如果你正在制作一个游戏,你可能会腌制玩家的游戏保存,所以它可能会稍后加载。 – Carcigenicate

+1

可能的重复[了解Python中的酸洗](https://stackoverflow.com/questions/7501947/understanding-pickling-in-python) –

+0

也请参阅:https://stackoverflow.com/questions/8968884/python-serialization-why-pickle和https://stackoverflow.com/questions/21752259/python-why-pickle –

回答

0

首先检查官方pickle documentation。它需要一个可以序列化的Python对象,并将它转换为一个可以保存到磁盘的字节流(或者反过来,从一个文件开始,然后将其重新转换为一个Python对象,这通常是在您希望保存状态运行或者如果你想缓存长时间运行的结果(例如maybe_ *就像函数通常用于这个目的)