[英]write or write binary for saving data to file in python?
我正在嘗試將功能從目錄保存到文件中。 數據和錯誤已顯示在下面。 open語句中保存數據而不失真的正確“字母”應該是什么?
錯誤
write() argument must be str, not numpy.ndarray
碼
generator1 = ImageDataGenerator(rescale=1. / 255).flow_from_directory(train_data_dir,target_size=(img_width, img_height),batch_size=batch_size,shuffle=False)
print("generator1 images loaded")
for i in range(len(generator1)):
kl = generator1[i]
bottleneck_features_train = model.predict_on_batch(kl[0])
print("first prediction")
print (bottleneck_features_train)
file =open('/home/rehan/predictions/bottleneck_features_train_%s.py'%i, 'w')
file.write(bottleneck_features_train)
file.close()
數據
[[[ 0.50452518 0. 0. ..., 0. 0.84091663 0. ]
[ 0.538715 0. 0.07498804 ..., 0. 0.50906491 0. ]
[ 0.5355916 0. 1.27406454 ..., 0.14854321 0.55418521 0. ]
[ 1.24407315 0. 1.74664402 ..., 0.11201498 0.55507243 0. ]]
[[ 0.05677766 0. 0. ..., 0. 0.82949859 0. ]
[ 0. 0. 0.19032657 ..., 0.12606588 0.02242988 0. ]
[ 0.10961182 0. 1.54800272 ..., 0.37970039 0. 0. ]
[ 0.42456442 0. 1.87542152 ..., 0.36944041 0.29935738 0. ]]
[[ 0.04067653 0. 0. ..., 0. 0.55476826 0. ]
[ 0.31820443 0. 0. ..., 0. 0. 0. ]
[ 0.58587539 0. 0.25692856 ..., 0.03251171 0. 0. ]
[ 0.66836131 0. 0.19993514 ..., 0. 0.19460687 0. ]]
[[ 0.46838504 0. 0. ..., 0. 0.91270626 0. ]
[ 1.46697009 0. 0. ..., 0. 0.53989708 0. ]
[ 2.26325178 0. 0. ..., 0. 0. 0. ]
[ 1.71381867 0. 0. ..., 0. 0.34278265 0. ]]]]
如果要直接將numpy數組寫入文件並能夠再次加載,則應使用pickle
要編寫它:
import pickle
with open("pickle_file.pickle", "wb") as handle:
pickle.dump(your_array, handle)
閱讀:
with open("pickle_file.pickle", "rb") as handle:
your_array = pickle.load(handle)
將其轉換為字符串對象。
例如:
generator1 = ImageDataGenerator(rescale=1. / 255).flow_from_directory(train_data_dir,target_size=(img_width, img_height),batch_size=batch_size,shuffle=False)
print("generator1 images loaded")
for i in range(len(generator1)):
kl = generator1[i]
bottleneck_features_train = model.predict_on_batch(kl[0])
print("first prediction")
print (bottleneck_features_train)
file =open('/home/rehan/predictions/bottleneck_features_train_%s.py'%i, 'w')
file.write(str(bottleneck_features_train))
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.