cifar10数据集----加载数据
import pickle
def load_cifar10_batch(cifar10_dataset_folder_path,batch_id):
with open(cifar10_dataset_folder_path + '/data_batch_' + str(batch_id),mode='rb') as file:
batch = pickle.load(file, encoding = 'latin1')
features = batch['data'].reshape((len(batch['data']),3,32,32)).transpose(0,2,3,1)
labels = batch['labels']
return features, labels
cifar10_path = '/root/zhj/python3/code/data/cifar-10-batches-py'
x_train, y_train = load_cifar10_batch(cifar10_path, 1)
for i in range(2,6):
features,labels = load_cifar10_batch(cifar10_path, i)
x_train, y_train = np.concatenate([x_train, features]),np.concatenate([y_train, labels])
with open(cifar10_path + '/test_batch', mode = 'rb') as file:
batch = pickle.load(file, encoding='latin1')
x_test = batch['data'].reshape((len(batchtch['data']),3,32,32)).transpose(0,2,3,1)
y_test = batch['labels']
---------------------------------------------------------------------------
UnpicklingError Traceback (most recent call last)
in ()
1 # 加载测试数据
2 with open(cifar10_path + '/test_batch', mode = 'rb') as file:
----> 3 batch = pickle.load(file, encoding='latin1')
4 x_test = batch['data'].reshape((len(batchtch['data']),3,32,32)).transpose(0,2,3,1)
5 y_test = batch['labels']
UnpicklingError: invalid load key, '\xfe'.
问题:数据导入是以bytes形式导入的,而在load时出现了无效的字符’\xfe’
解决办法:测试数据上传至云服务器时出现错误,重新上传一次
with open(cifar10_path + '/test_batch', mode = 'rb') as file:
batch = pickle.load(file, encoding='latin1')
x_test = batch['data'].reshape((len(batch['data']),3,32,32)).transpose(0,2,3,1)
y_test = batch['labels']
显示图片
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
fig,axes = plt.subplots(nrows=3,ncols=20, sharex=True, sharey=True, figsize=(80,12))
imgs = x_train[:60]
for imgs, row in zip([imgs[:20],imgs[20:40],imgs[40:60]],axes):
for img, ax in zip(imgs, row):
ax.imshow(img)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
fig.tight_layout(pad=0.1)
plt.show()