import gzip import os import pickle import numpy as np def load_mnist(path, kind='train'): labels_path = os.path.join(path, '%s-labels-idx1-ubyte.gz' % kind) images_path = os.path.join(path, '%s-images-idx3-ubyte.gz' % kind) with gzip.open(labels_path, 'rb') as lbpath: labels = np.frombuffer(lbpath.read(), dtype=np.uint8, offset=8) with gzip.open(images_path, 'rb') as imgpath: images = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels), 784) return images, labels def get_mnist_data(num_training=5000, num_validation=500, num_test=500): mnist_dir = r'D:\daima\mnist' # 修改为mnist数据集所在的目录 X_train, y_train = load_mnist(mnist_dir, kind='train') X_test, y_test = load_mnist(mnist_dir, kind='t10k') print(X_train.shape) mask = range(num_training, num_training + num_validation) X_val = X_train[mask] y_val = y_train[mask] mask = range(num_training) X_train = X_train[mask] y_train = y_train[mask] mask = range(num_test) X_test = X_test[mask] y_test = y_test[mask] X_train = X_train.astype('float32') / 255 X_val = X_val.astype('float32') / 255 X_test = X_test.astype('float32') / 255 return { 'X_train': X_train, 'y_train': y_train, 'X_val': X_val, 'y_val': y_val, 'X_test': X_test, 'y_test': y_test, },这是读取mnist的函数,如何把解包时给定的值数量从两个增加到4个
时间: 2024-03-03 11:51:00 浏览: 125
在这个函数中,load_mnist函数返回了两个值,即images和labels,但是这个函数只使用了一个返回值,所以只需要将这个函数的返回值改为一个元组即可。具体来说,将return images, labels改为return (images, labels)即可。这样get_mnist_data函数就可以使用解包时给定的值数量为4了。修改后的代码如下:
```
import gzip
import os
import pickle
import numpy as np
def load_mnist(path, kind='train'):
labels_path = os.path.join(path, '%s-labels-idx1-ubyte.gz' % kind)
images_path = os.path.join(path, '%s-images-idx3-ubyte.gz' % kind)
with gzip.open(labels_path, 'rb') as lbpath:
labels = np.frombuffer(lbpath.read(), dtype=np.uint8, offset=8)
with gzip.open(images_path, 'rb') as imgpath:
images = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels), 784)
return images, labels
def get_mnist_data(num_training=5000, num_validation=500, num_test=500):
mnist_dir = r'D:\daima\mnist' # 修改为mnist数据集所在的目录
X_train, y_train = load_mnist(mnist_dir, kind='train')
X_test, y_test = load_mnist(mnist_dir, kind='t10k')
print(X_train.shape)
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
X_train = X_train.astype('float32') / 255
X_val = X_val.astype('float32') / 255
X_test = X_test.astype('float32') / 255
return X_train, y_train, X_val, y_val, X_test, y_test
```
阅读全文