繁体   English   中英

如何解压pkl文件?

[英]How to unpack pkl file?

我有一个来自 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()

mnist_digit

另一种选择是查看原始数据:

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

需要使用pickle (如果文件被压缩,则为gzip )模块

注意:这些已经在标准 Python 库中。 无需安装任何新东西

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM