我正在尝试使用这个程序在Python3.2中加载链接到here的MNIST数据集:
import pickle
import gzip
import numpy
with gzip.open('mnist.pkl.gz', 'rb') as f:
l = list(pickle.load(f))
print(l)
不幸的是,它给出了一个错误:
Traceback (most recent call last):
File "mnist.py", line 7, in <module>
train_set, valid_set, test_set = pickle.load(f)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 614: ordinal not in range(128)
然后,我尝试在Python2.7中解码这个酸洗过的文件,然后重新编码。所以,我在Python2.7中运行了这个程序:
import pickle
import gzip
import numpy
with gzip.open('mnist.pkl.gz', 'rb') as f:
train_set, valid_set, test_set = pickle.load(f)
# Printing out the three objects reveals that they are
# all pairs containing numpy arrays.
with gzip.open('mnistx.pkl.gz', 'wb') as g:
pickle.dump(
(train_set, valid_set, test_set),
g,
protocol=2) # I also tried protocol 0.
它运行没有错误,所以我在Python 3.2中重新运行了这个程序:
import pickle
import gzip
import numpy
# note the filename change
with gzip.open('mnistx.pkl.gz', 'rb') as f:
l = list(pickle.load(f))
print(l)
然而,它给了我和以前一样的错误。我怎么才能让它工作呢?
发布于 2012-07-03 23:48:54
这看起来像是某种不兼容。它试图加载一个"binstring“对象,该对象被假定为ASCII,而在本例中它是二进制数据。如果这是Python3Unpicler中的一个bug,或者是numpy对pickler的“误用”,我不知道。
下面是一个变通方法,但我不知道数据在这一点上有多大意义:
import pickle
import gzip
import numpy
with open('mnist.pkl', 'rb') as f:
u = pickle._Unpickler(f)
u.encoding = 'latin1'
p = u.load()
print(p)
在Python 2中解压它,然后再重新酸洗,只会再次产生同样的问题,因此您需要将其保存为另一种格式。
发布于 2016-12-29 01:17:30
如果你在python3中得到这个错误,那么这可能是Python2和Python3之间的不兼容问题,对我来说,解决方案是使用latin1
编码的load
:
pickle.load(file, encoding='latin1')
发布于 2017-02-03 11:49:37
这似乎是Python 2和Python 3之间的不兼容问题。我尝试使用加载MNIST数据集
train_set, valid_set, test_set = pickle.load(file, encoding='iso-8859-1')
它适用于Python 3.5.2
https://stackoverflow.com/questions/11305790
复制相似问题