我有一个来自MNIST数据集的pkl文件,它由手写的数字图像组成。
我想看看每一个数字图像,所以我需要解压pkl文件,但我不知道如何。
有办法解压缩/解压缩pkl文件吗?
发布于 2014-08-01 11:22:08
一般而言
实际上,您的pkl
文件是一个序列化的pickle
文件,这意味着它已经被使用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()
另一种选择是查看原始数据:
http://yann.lecun.com/exdb/mnist/
但这将更加困难,因为您需要创建一个程序来读取这些文件中的二进制数据。因此,我建议您使用Python,并使用pickle
加载数据。正如你所看到的,这很容易。;-)
发布于 2016-12-08 11:01:37
便携单线
pkl() (
python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl
将打印被腌制对象的__str__
。
可视化对象的一般问题当然是未定义的,因此如果__str__
不够,您将需要一个自定义脚本。
发布于 2018-11-23 14:06:29
如果您想使用原始的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
https://stackoverflow.com/questions/24906126
复制相似问题