我有一个来自 MNIST 数据集的 pkl 文件,它由手写数字图像组成。
我想看看这些数字图像中的每一个,所以我需要解压缩 pkl 文件,但我不知道如何解压。
有没有办法解压/解压缩 pkl 文件?
一般来说
您的 pkl
文件实际上是一个序列化的 pickle
文件,这意味着它已使用 Python 的 pickle
模块转储。
要取消腌制数据,您可以:
import pickle
with open('serialized.pkl', 'rb') as f:
data = pickle.load(f)
对于 MNIST 数据集
注意 gzip
仅在文件被压缩时才需要:
import gzip
import pickle
with gzip.open('mnist.pkl.gz', 'rb') as f:
train_set, valid_set, test_set = pickle.load(f)
其中每组可以进一步划分(即对于训练集):
train_x, train_y = train_set
这些将是您的集合的输入(数字)和输出(标签)。
如果要显示数字:
import matplotlib.cm as cm
import matplotlib.pyplot as plt
plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()
https://i.stack.imgur.com/c4JXq.png
另一种选择是查看原始数据:
http://yann.lecun.com/exdb/mnist/
但这会更难,因为您需要创建一个程序来读取这些文件中的二进制数据。所以我建议您使用 Python,并使用 pickle
加载数据。如您所见,这非常容易。 ;-)
方便的单线
pkl() (
python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl
将为腌制的对象打印 __str__
。
可视化对象的一般问题当然是未定义的,因此如果 __str__
不够,您将需要自定义脚本。
如果您想使用原始 MNIST 文件,可以使用以下方法对它们进行反序列化。
如果您尚未下载文件,请先在终端中运行以下命令:
wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
然后将以下内容另存为 deserialize.py
并运行它。
import numpy as np
import gzip
IMG_DIM = 28
def decode_image_file(fname):
result = []
n_bytes_per_img = IMG_DIM*IMG_DIM
with gzip.open(fname, 'rb') as f:
bytes_ = f.read()
data = bytes_[16:]
if len(data) % n_bytes_per_img != 0:
raise Exception('Something wrong with the file')
result = np.frombuffer(data, dtype=np.uint8).reshape(
len(bytes_)//n_bytes_per_img, n_bytes_per_img)
return result
def decode_label_file(fname):
result = []
with gzip.open(fname, 'rb') as f:
bytes_ = f.read()
data = bytes_[8:]
result = np.frombuffer(data, dtype=np.uint8)
return result
train_images = decode_image_file('train-images-idx3-ubyte.gz')
train_labels = decode_label_file('train-labels-idx1-ubyte.gz')
test_images = decode_image_file('t10k-images-idx3-ubyte.gz')
test_labels = decode_label_file('t10k-labels-idx1-ubyte.gz')
该脚本不会像在腌制文件中那样标准化像素值。要做到这一点,你所要做的就是
train_images = train_images/255
test_images = test_images/255
不定期副业成功案例分享
pkl
文件,pickle.load
可用于解包——尽管我猜它的性能不如cPickle.load
。对于较小一侧的pkl
文件,性能差异并不明显。open
函数的默认值 mode 设置为r
(读取),因此以rb
模式打开文件很重要。如果未添加b
(二进制)模式,则 unpickling 可能会导致UnicodeDecodeError
。