Tensorflow的MNIST数据集下载脚本(input_data.py)

MNIST数据集下载+idx3-ubyte解析【超详细+上手简单】 下载MNIST数据集并对其进行图片与标签解析 阅读详情

tensorflow网站上的链接有时候无法访问,有需要的同学可以拿走了

#copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import tensorflow.python.platform
import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
def maybe_download(filename, work_directory):
  """Download the data from Yann's website, unless it's already here."""
  if not os.path.exists(work_directory):
    os.mkdir(work_directory)
  filepath = os.path.join(work_directory, filename)
  if not os.path.exists(filepath):
    filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
    statinfo = os.stat(filepath)
    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
  return filepath
def _read32(bytestream):
  dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_images(filename):
  """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
  print('Extracting', filename)
  with gzip.open(filename) as bytestream:
    magic = _read32(bytestream)
    if magic != 2051:
      raise ValueError(
          'Invalid magic number %d in MNIST image file: %s' %
          (magic, filename))
    num_images = _read32(bytestream)
    rows = _read32(bytestream)
    cols = _read32(bytestream)
    buf = bytestream.read(rows * cols * num_images)
    data = numpy.frombuffer(buf, dtype=numpy.uint8)
    data = data.reshape(num_images, rows, cols, 1)
    return data
def dense_to_one_hot(labels_dense, num_classes=10):
  """Convert class labels from scalars to one-hot vectors."""
  num_labels = labels_dense.shape[0]
  index_offset = numpy.arange(num_labels) * num_classes
  labels_one_hot = numpy.zeros((num_labels, num_classes))
  labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
  return labels_one_hot
def extract_labels(filename, one_hot=False):
  """Extract the labels into a 1D uint8 numpy array [index]."""
  print('Extracting', filename)
  with gzip.open(filename) as bytestream:
    magic = _read32(bytestream)
    if magic != 2049:
      raise ValueError(
          'Invalid magic number %d in MNIST label file: %s' %
          (magic, filename))
    num_items = _read32(bytestream)
    buf = bytestream.read(num_items)
    labels = numpy.frombuffer(buf, dtype=numpy.uint8)
    if one_hot:
      return dense_to_one_hot(labels)
    return labels
class DataSet(object):
  def __init__(self, images, labels, fake_data=False, one_hot=False,
               dtype=tf.float32):
    """Construct a DataSet.
    one_hot arg is used only if fake_data is true.  `dtype` can be either
    `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
    `[0, 1]`.
    """
    dtype = tf.as_dtype(dtype).base_dtype
    if dtype not in (tf.uint8, tf.float32):
      raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
                      dtype)
    if fake_data:
      self._num_examples = 10000
      self.one_hot = one_hot
    else:
      assert images.shape[0] == labels.shape[0], (
          'images.shape: %s labels.shape: %s' % (images.shape,
                                                 labels.shape))
      self._num_examples = images.shape[0]
      # Convert shape from [num examples, rows, columns, depth]
      # to [num examples, rows*columns] (assuming depth == 1)
      assert images.shape[3] == 1
      images = images.reshape(images.shape[0],
                              images.shape[1] * images.shape[2])
      if dtype == tf.float32:
        # Convert from [0, 255] -> [0.0, 1.0].
        images = images.astype(numpy.float32)
        images = numpy.multiply(images, 1.0 / 255.0)
    self._images = images
    self._labels = labels
    self._epochs_completed = 0
    self._index_in_epoch = 0
  @property
  def images(self):
    return self._images
  @property
  def labels(self):
    return self._labels
  @property
  def num_examples(self):
    return self._num_examples
  @property
  def epochs_completed(self):
    return self._epochs_completed
  def next_batch(self, batch_size, fake_data=False):
    """Return the next `batch_size` examples from this data set."""
    if fake_data:
      fake_image = [1] * 784
      if self.one_hot:
        fake_label = [1] + [0] * 9
      else:
        fake_label = 0
      return [fake_image for _ in xrange(batch_size)], [
          fake_label for _ in xrange(batch_size)]
    start = self._index_in_epoch
    self._index_in_epoch += batch_size
    if self._index_in_epoch > self._num_examples:
      # Finished epoch
      self._epochs_completed += 1
      # Shuffle the data
      perm = numpy.arange(self._num_examples)
      numpy.random.shuffle(perm)
      self._images = self._images[perm]
      self._labels = self._labels[perm]
      # Start next epoch
      start = 0
      self._index_in_epoch = batch_size
      assert batch_size <= self._num_examples
    end = self._index_in_epoch
    return self._images[start:end], self._labels[start:end]
def read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=tf.float32):
  class DataSets(object):
    pass
  data_sets = DataSets()
  if fake_data:
    def fake():
      return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype)
    data_sets.train = fake()
    data_sets.validation = fake()
    data_sets.test = fake()
    return data_sets
  TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
  TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
  TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
  TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
  VALIDATION_SIZE = 5000
  local_file = maybe_download(TRAIN_IMAGES, train_dir)
  train_images = extract_images(local_file)
  local_file = maybe_download(TRAIN_LABELS, train_dir)
  train_labels = extract_labels(local_file, one_hot=one_hot)
  local_file = maybe_download(TEST_IMAGES, train_dir)
  test_images = extract_images(local_file)
  local_file = maybe_download(TEST_LABELS, train_dir)
  test_labels = extract_labels(local_file, one_hot=one_hot)
  validation_images = train_images[:VALIDATION_SIZE]
  validation_labels = train_labels[:VALIDATION_SIZE]
  train_images = train_images[VALIDATION_SIZE:]
  train_labels = train_labels[VALIDATION_SIZE:]
  data_sets.train = DataSet(train_images, train_labels, dtype=dtype)
  data_sets.validation = DataSet(validation_images, validation_labels,
                                 dtype=dtype)
  data_sets.test = DataSet(test_images, test_labels, dtype=dtype)
  return data_sets

 

MNIST数据集下载与保存为图片格式 阅读详情

相关推荐

torchvision​包下载MNIST数据集

TorchVision是PyTorch项目的一部分,torchvision软件包包括:流行的数据集、模型架构以及。计算机视觉的常见图像转换。

qq_27390023的博客 1147

详解MNIST数据集下载、解析及显示的Python实现

MNIST(modified national institute of standard and technology)数据集由Yann LeCun等人于1994年创建一个大型手写数字数据库(包含0~9十个数字)。MNIST数据集是深度学习和计算机视觉领域入门级的数据集,类似于编程语言的Hello Word。本篇博客完整地给出了多种下载、解析及可视化方案,以供参考和学习。

KRISNAT 16万+

Mnist数据集以及input_data.py的代码

Mnist作为tensorflow的入门,但是很多人都在Mnist的数据集上就已经卡住了。有的人找不到input_data.pyde代码。所以在此给那些找不到input_data.py的人提供代码。仅供学习。源代码来自于https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/examples/tutorials/mnis...

Anthony 1万+

sklearn无法下载MNIST数据集问题解决方法

MNIST数据集下载地址 https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat 首先在网上下载MNIST数据集,然后将下载的mnist-original.mat的数据放如程序的目录下 在代码中添加如下代码 mnist = fetch_mldata('MNIST original',data_home=‘.’) ...

我是小哈哈 4270

TensorFlow MNIST数据集导入遇ModuleNotFoundError: No module named 'input_data'

初学TensorFlow,已下载input_data.py。运行此py程序后获得MNIST数据集,但直接按TensorFlow中文社区教程使用如下代码: import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) 会出现 ModuleNotFoundError: No module named ‘i...

alienanlin的博客 3963

input_data.py

最近研究TensorFlow,学习了TensorFlow中文社区的文档,在MNIST数据下载中有一份下载用于训练和测试的MNIST数据集的源码。由于对numpy和gzip等库不熟悉。将源码和关于源码的注释写在这里,以便以后回顾。MNIST数据下载页面为TensorFlow中文社区# Copyright 2015 Google Inc. All Rights Reserved. # # Licens

Orville的博客 6561

关于TensorFlow的MNIST数据集下载脚本input_data.py的坑

今天用github上的代码入门tensorflow但是发现似乎要下载数据集,但是这个我弄了一会才明白是怎么下的,所以把经验写在下面:(ubuntu14.04环境) 用github上的input_data.py from __future__ import absolute_import from __future__ import division from __future__ im

kaggle expert,全球排名前1000,清华计算机研究生,兴趣算法工程 7160

tensorflow中mnist数据集下载出现错误

mnist数据集下载的代码 from tensorflow.examples.tutorials.mnist import input_data mnist = input.read_data_sets('./data/', one_hot=True) 首先贴出错误的图片 出错的具体原因我也没弄明白,翻译了一下好像是方法被移除了。但我前段时间在黑苹果系统上用这个方法成功过,因此我也不清楚了,下...

weixin_43019705的博客 1243

tensorflow下数据集MNIST下载源代码

本人Tensorflow新手,在下载经典数据集MNIST时遇到问题,input_data.py脚本下载不了。在此给出解决办法

tanlangqie的博客 2344

【上海大学计算机组成原理实验报告】七、程序转移机制

学习实现程序转移的硬件机制//掌握堆栈寄存器的使用//手动方式实现子程序调用转移过程//手动方式实现子程序返回转移过程//编程实现`OUT`寄存器交替显示`11`和`55`//若要求`11`和`55`各显示`50`次后停机,应该如何修改程序?//根据实验指导书的相关内容,实验箱系统的程序转移硬件机制在于,当`LDPC`有效时,如果此时`DUBS`上的值就是转移的目标地址,则此目标地址被打入`PC`,从而实现程序的转移;若`LDPC`为`0`是附带条件的,就形成“条件转移”。

HackerKevon的博客 2471

SFM(structure from motion 从运动恢复结构)和MVS(multi-view stereo 多视图立体视觉)

主要目的:SFM是重建稀疏点云的,MVS重建的是稠密点云。 输入的数据:SFM是没有标定的数据,而MVS输入的是标定的数据。 为什么SFM无法重建出稠密的点云,但是MVS可以? SFM中我们用来做重建的点是由特征匹配提供的!这些匹配点天生不密集!MVS则几乎对照片中的每个像素点都进行匹配,几乎重建每一个像素点的三维坐标,这样得到的点的密集程度可以较接近图像为我们展示出的清晰度。 SFM和MVS关系 SFM给MVS算好了输入视角的位姿,内参,稀疏点云以及它们的共视关系,MVS再利用这些信息以及彩色图

Vpn_zc的博客 1万+

10数据集解压成图片_收藏 | 那些不得不了解的人工智能经典数据集~MNIST数据集下载及可视化!...

点上方蓝字人工智能算法与Python大数据获取更多干货在右上方···设为星标★,第一时间获取资源MNIST数据集介绍MNIST数据集官网:http://yann.lecun.com/exdb/mnist/MNIST数据库是非常经典的一个数据集,就像你学编程起初写一个“Hello Word”的程序一样,学Deep Learning你就会写识别MNIST数据集的Model。MNIST数...

weixin_34642354的博客 182

stable diffusioncontrolNet 预处理器/模型的下载及安装使用教程

首先说明,controlNet 的模型 不同于stable diffusion 模型,这一点一定要区分清楚。下面提供多个ControlNet 预处理器+ 专用模型的百度网盘下载链接,都是由群友整理贡献,但各自包含的版本不同,大家可自行选择。推荐下载紫色链接内的模型,fp16版文件更小,稍微新一些的controlnet插件还添加了对control-lora的支持(注意,要求controlnet插件的版本比12月16号新(1.1.423以上)才能正常识别),推荐下载;

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 3384

手把手教学 Centos 安装anaconda3 机器学习环境(三)

mnist数据集下载地址 百度网盘下载地址 Tensorflow实现卷积神经网络 input_data.py文件 链接:https://pan.baidu.com/s/1JVzVOx9vxAn_tBeXsbAf_g 密码:locq MNIST数据集介绍 MNIST数据集官网:http://yann.lecun.com/exdb/mnist/ MNIST数据库是非常经典的一个数据集,就像你学编程起初写一个“Hello Word”的程序一样,学Deep Learning你就会写识别MNIST数据集的Model。

fuliya005的博客 185

基于Simulink的永磁同步电机力位混合控制(导纳+位置)仿真

本文详细介绍了基于Simulink的永磁同步电机(PMSM)力位混合控制系统实现方法。主要内容包括:1) 通过导纳控制原理(二阶质量-阻尼-弹簧模型)实现机器人柔顺控制;2) 在Simulink中构建虚拟环境、导纳控制器、PMSM驱动系统等完整框架;3) 针对曲面恒力打磨场景,实现20N恒力跟踪(RMS误差1.2N)和位置顺应;4) 支持纯位置/导纳/恒力三种工作模式切换;5) 提供系统性能评估指标和高级扩展功能。该方案显著提升了机器人环境交互的安全性和适应性,适用于精密装配、人机协作等应用场景。

xiaoheshang_123的博客 146

Python爬虫实战:爬取并分析电子商务平台用户评论数据

爬虫(Web Scraping)是指通过编写程序模拟浏览器行为,从网站中提取数据的过程。爬虫技术可以自动化地抓取网站上的信息,广泛应用于数据收集、价格监控、市场研究等多个领域。情感分析(Sentiment Analysis)是一种自然语言处理技术,用于确定文本的情感倾向。对于电子商务平台的评论数据,情感分析可以帮助商家了解消费者的反馈情绪,例如产品的好评、差评或中性评价。本文详细介绍了如何使用Python爬虫技术从电子商务平台抓取并分析用户评论数据。我们展示了如何通过requestsSelenium。

2201_76125261的博客 1174

MNIST数据集简介

MNIST Dataset Introduction 大多数示例使用手写数字的MNIST数据集。 该数据集包含60,000个用于培训的示例和10,000个用于测试的示例。 这些数字已经标准化,并以固定大小的图像(28x28像素)为中心,其值为0到1.为简单起见,每个图像都被展平并转换为784个特征(28 * 28)的一维 numpy数组)。 Overview Usage 在我们的示例中...

Geek 1579

笔试题-2023-思特威-数字电路设计(CIS)【纯净题目版】

10 笔试题-2023-思特威-数字电路设计(CIS)【纯净题目版】

w0shishabi的博客 1471

tensorflow2中fashion_mnist.load_data()失败 ,故导入手动下载好的mnist数据集(一)

转自知乎:使用tensorflow导入手动下载好的mnist数据集https://zhuanlan.zhihu.com/p/133402910 方法一: import tensorflow as tf import numpy as np def load_data(path): with np.load(path) as f: x_train, y_train = f['x_train'], f['y_train'] x_test, y_test = f['x

xioayuner1的专栏 3020

MSBlock赋能C2f模块,让目标检测在轻量化与精度间双向突破

在文件夹下新建,将上述MSBlock和C2f_MS类的代码写入其中。这一步是为了让YOLOv8的代码架构能识别我们的自定义模块。

LXY_LOVE36的博客 143

SkillClaw:让大模型 Agent skill在多用户生态中实现群体进化的框架

随着大模型应用步入深水区,基于 LLM 的智能体(Agent)正从单一的“沙盒玩具”转变为处理真实世界复杂任务的生产力工具。然而,现有的 Agent 系统通常面临一个致命瓶颈——部署即固化。为了解决这一问题,最近有一篇新论文**《SkillClaw: Let Skills Evolve Collectively with Agentic Evolver》**提出了一种多用户生态 Agent 群体进化框架。

kakaZhui的博客 263

简析Tensorflow中examples.tutorials.mnist中 input_data数据类

由于在tensorflow最初时一直用的就是最经典的mnist手写字符识别中的数据集了,而且在tensorflow中直接封装好的是mnist手写字符的数据集类,方便直接用input_data.*中的方法调用其读取数据,读取数据标签,以及对数据feed时的next_batch()等操作,但是涉及后面进一步深入时,如果想要训练和测试自己的数据集时没有封装好的数据类方法,此时就需要自己来进行制作数据集。...

【秋名鱼酱的博客】 1万+

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

tensorflow文档中关于MNIST数据集下载的input_data.py

#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/4/24 下午3:52 # @Author : Dynasty # @File : input_data.py # @Software: PyCharm # Copyright 2015 Google Inc. All Rights Res...

yingqubaifumei的博客 825

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

tensorflow1.8版本及以上加载mnist手写分类数据集 : input_data和 read_data_sets弃用的解决办法

声明一点: 博主的环境是直接安装的 Keras 2.24 ,目前Keras已与tensorflow合并,tensorflow用作Keras的后端,所以直接安装Keras会连带tensorflow一起安装,tensorflow的版本和Keras相匹配的,所以不要考虑tensorflow的版本问题,只需安装Keras就行了 下面的代码使用的是全连接神经网络而不是卷积神经网络的方式:有助于深刻理...

xrinosvip的博客 1万+

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

MNIST数据处理遇到ModuleNotFoundError: No module named ‘tensorflow.examples.tutorials或者No module named ‘ten

MNIST数据处理遇到ModuleNotFoundError: No module named 'tensorflow.examples.tutorials或者No module named 'tensorflow.examples 在看MNIST数据处理遇到的问题,然后网上的资料也都是18、19年的,Tensorflow版本更新也很快,很多包也删除了,这次记录一下排雷过程。 from tensorflow.examples.tutorials.mnist import input_data 首先上面这句

weixin_42390287的博客 3716

TENSORFLOW MNIST数据集无法下载的解决

在tensorflow教程中,用下面这一句下载mnist数据集: mnist = input_data.read_data_sets('MNIST_data', one_hot=True) 但实际运行时根本无法通过网络下载,网上可以查到一些解决方法,但说得不是很清楚,这里整理一下,大小神请无视。 解决方案就是手工下载数据,然后直接导入使用。 一、手工下载地址:http://yann

i8088的博客 1万+
上一篇: Tensorflow的hello world =MNIST入门
下一篇: 关于unix系统编程apue头文件找不到问题处理
杨鑫校
博客等级 码龄11年 24粉丝 113原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值