2017-04-07 71 views
0

我將numpy數組的字典保存到pickle文件。然後取消它們到新的變量。代碼是這樣的:Python - 保存到Pickle文件中的數據類型保留

酸洗:

# here the variables 'train_dataset', 'train_labels' etc are all np arrays. 
save = { 
    'train_dataset': train_dataset, 
    'train_labels': train_labels, 
    'valid_dataset': valid_dataset, 
    'valid_labels': valid_labels, 
    'test_dataset': test_dataset, 
    'test_labels': test_labels, 
    } 
pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) 

取儲存:

save = pickle.load(f) 
train_dataset_new = save['train_dataset'] 
train_labels_new = save['train_labels'] 
valid_dataset_new = save['valid_dataset'] 
valid_labels_new = save['valid_labels'] 
test_dataset_new = save['test_dataset'] 
test_labels_new = save['test_labels'] 

將從泡菜文件中加載的變量也是NP陣列?如果可以的話,請詳細說明一下。

感謝

回答

1

直接從docs報價:

閱讀從打開的文件對象文件中的字符串,並把它解釋爲一個 泡菜數據流,重建和返還原物 層次。

小測試代碼來檢查裝載的變量,它是<type 'numpy.ndarray'>的數據類型:

import numpy as np 
import pickle 

#f = open("pickled.p", "wb") 

train_dataset = np.ones(5) 
train_labels = np.ones(5) 
valid_dataset = np.ones(5) 
valid_labels = np.ones(5) 
test_dataset = np.ones(5) 
test_labels = np.ones(5) 

print type(train_dataset) # <type 'numpy.ndarray'> 
print train_dataset.shape # <5L,> 

# here the variables 'train_dataset', 'train_labels' etc are all np arrays. 
save = { 
    'train_dataset': train_dataset, 
    'train_labels': train_labels, 
    'valid_dataset': valid_dataset, 
    'valid_labels': valid_labels, 
    'test_dataset': test_dataset, 
    'test_labels': test_labels, 
    } 
pickle.dump(save, open("save.p", "wb"), pickle.HIGHEST_PROTOCOL) 

save = pickle.load(open("save.p", "rb")) 
train_dataset_new = save['train_dataset'] 
train_labels_new = save['train_labels'] 
valid_dataset_new = save['valid_dataset'] 
valid_labels_new = save['valid_labels'] 
test_dataset_new = save['test_dataset'] 
test_labels_new = save['test_labels'] 

print type(train_dataset_new) # <type 'numpy.ndarray'> 
print train_dataset_new.shape # <5L,>