使用input_data函数从python中读取数据集
发布时间:2023-12-26 03:11:38
input_data函数是TensorFlow中提供的一个函数,用于从本地文件系统或远程服务器中读取数据集。该函数可以读取多种格式的数据集,如文本文件、图片文件、TFRecord文件等。
以下是一个使用input_data函数读取MNIST手写数字数据集的例子:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 下载并加载MNIST数据集
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 获取训练集的样本和标签
train_images = mnist.train.images
train_labels = mnist.train.labels
# 获取测试集的样本和标签
test_images = mnist.test.images
test_labels = mnist.test.labels
# 打印训练集和测试集的大小
print("训练集大小:", train_images.shape)
print("测试集大小:", test_images.shape)
在上述代码中,首先通过read_data_sets函数从MNIST_data/目录中下载并加载MNIST数据集。参数one_hot=True表示将标签转换为one-hot编码。
然后,可以通过mnist.train.images和mnist.train.labels获取训练集的样本和标签,通过mnist.test.images和mnist.test.labels获取测试集的样本和标签。
最后,使用print函数打印训练集和测试集的大小。
需要注意的是,在运行该代码之前,需要确保已经安装了TensorFlow和MNIST数据集。如果没有安装,可以通过以下命令安装:
pip install tensorflow pip install python-mnist
