python 深度学习 解决遇到的报错问题

news2024/9/27 7:25:50

目录

一、解决报错ModuleNotFoundError: No module named ‘tensorflow.examples

二、解决报错ModuleNotFoundError: No module named ‘tensorflow.contrib‘

三、安装onnx报错assert CMAKE, ‘Could not find “cmake“ executable!‘

四、ImportError: cannot import name 'builder' from 'google.protobuf.internal'

五、解决ModuleNotFoundError: No module named 'sklearn'

六、解决AttributeError: module ‘torch._C‘ has no attribute ‘_cuda_setDevice‘

七、解决ImportError: Missing optional dependency 'pytables'.  Use pip or conda to install pytables.

八、解决AttributeError: module ‘distutils’ has no attribute ‘version’.


一、解决报错ModuleNotFoundError: No module named ‘tensorflow.examples

注意:MNIST数据集下载完成后不要解压,直接放入mnist_data文件夹下读取即可。

问题:我在用tensorflow做mnist数据集案例,报错了。

原因:tensorflow中没有examples。
解决方法:(1)首先找到对应tensorflow的文件,我的是在D:\python3\Lib\site-packages\tensorflow(python的安装目录),进入tensorflow文件夹,发现没有examples文件夹。 

我们可以进入github下载:mirrors / tensorflow / tensorflow · GitCode。

(2)下载完成后将\tensorflow-master\tensorflow\目录下的examples文件夹复制到本地tensorflow文件夹中,然后在重新运行代码即可。

(3)之后发现还是没能解决问题,发现examples中缺少tutorials文件夹。在官方的github中没发现这个文件,在其他博主那里下载到了该文件。

下载地址: 百度网盘 请输入提取码

提取码:cxy7

(4)但是依旧没有解决问题…
前面博主使用的应该是tf1.0的版本。参考其他博主的方法解决了问题。

  • 在工程下新建一个input_data.py文件,将tutorials文件夹下mnist中的input_data.py的内容复制到该文件中,
  • 再在主文件中import input_data一下。

input_data.py文件内容放在下面,需要的自取。

# Copyright 2016 The TensorFlow Authors. 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 (deprecated).

This module and all its submodules are deprecated.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import gzip
import os

import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
from tensorflow.python.platform import gfile
from tensorflow.python.util.deprecation import deprecated

_Datasets = collections.namedtuple('_Datasets', ['train', 'validation', 'test'])

# CVDF mirror of http://yann.lecun.com/exdb/mnist/
DEFAULT_SOURCE_URL = 'https://storage.googleapis.com/cvdf-datasets/mnist/'


def _read32(bytestream):
  dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]


@deprecated(None, 'Please use tf.data to implement this functionality.')
def _extract_images(f):
  """Extract the images into a 4D uint8 numpy array [index, y, x, depth].

  Args:
    f: A file object that can be passed into a gzip reader.

  Returns:
    data: A 4D uint8 numpy array [index, y, x, depth].

  Raises:
    ValueError: If the bytestream does not start with 2051.

  """
  print('Extracting', f.name)
  with gzip.GzipFile(fileobj=f) as bytestream:
    magic = _read32(bytestream)
    if magic != 2051:
      raise ValueError('Invalid magic number %d in MNIST image file: %s' %
                       (magic, f.name))
    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


@deprecated(None, 'Please use tf.one_hot on tensors.')
def _dense_to_one_hot(labels_dense, num_classes):
  """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


@deprecated(None, 'Please use tf.data to implement this functionality.')
def _extract_labels(f, one_hot=False, num_classes=10):
  """Extract the labels into a 1D uint8 numpy array [index].

  Args:
    f: A file object that can be passed into a gzip reader.
    one_hot: Does one hot encoding for the result.
    num_classes: Number of classes for the one hot encoding.

  Returns:
    labels: a 1D uint8 numpy array.

  Raises:
    ValueError: If the bystream doesn't start with 2049.
  """
  print('Extracting', f.name)
  with gzip.GzipFile(fileobj=f) as bytestream:
    magic = _read32(bytestream)
    if magic != 2049:
      raise ValueError('Invalid magic number %d in MNIST label file: %s' %
                       (magic, f.name))
    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, num_classes)
    return labels


class _DataSet(object):
  """Container class for a _DataSet (deprecated).

  THIS CLASS IS DEPRECATED.
  """

  @deprecated(None, 'Please use alternatives such as official/mnist/_DataSet.py'
              ' from tensorflow/models.')
  def __init__(self,
               images,
               labels,
               fake_data=False,
               one_hot=False,
               dtype=dtypes.float32,
               reshape=True,
               seed=None):
    """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]`.  Seed arg provides for convenient deterministic testing.

    Args:
      images: The images
      labels: The labels
      fake_data: Ignore inages and labels, use fake data.
      one_hot: Bool, return the labels as one hot vectors (if True) or ints (if
        False).
      dtype: Output image dtype. One of [uint8, float32]. `uint8` output has
        range [0,255]. float32 output has range [0,1].
      reshape: Bool. If True returned images are returned flattened to vectors.
      seed: The random seed to use.
    """
    seed1, seed2 = random_seed.get_seed(seed)
    # If op level seed is not set, use whatever graph level seed is returned
    numpy.random.seed(seed1 if seed is None else seed2)
    dtype = dtypes.as_dtype(dtype).base_dtype
    if dtype not in (dtypes.uint8, dtypes.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)
      if reshape:
        assert images.shape[3] == 1
        images = images.reshape(images.shape[0],
                                images.shape[1] * images.shape[2])
      if dtype == dtypes.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, shuffle=True):
    """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
    # Shuffle for the first epoch
    if self._epochs_completed == 0 and start == 0 and shuffle:
      perm0 = numpy.arange(self._num_examples)
      numpy.random.shuffle(perm0)
      self._images = self.images[perm0]
      self._labels = self.labels[perm0]
    # Go to the next epoch
    if start + batch_size > self._num_examples:
      # Finished epoch
      self._epochs_completed += 1
      # Get the rest examples in this epoch
      rest_num_examples = self._num_examples - start
      images_rest_part = self._images[start:self._num_examples]
      labels_rest_part = self._labels[start:self._num_examples]
      # Shuffle the data
      if shuffle:
        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 - rest_num_examples
      end = self._index_in_epoch
      images_new_part = self._images[start:end]
      labels_new_part = self._labels[start:end]
      return numpy.concatenate((images_rest_part, images_new_part),
                               axis=0), numpy.concatenate(
                                   (labels_rest_part, labels_new_part), axis=0)
    else:
      self._index_in_epoch += batch_size
      end = self._index_in_epoch
      return self._images[start:end], self._labels[start:end]


@deprecated(None, 'Please write your own downloading logic.')
def _maybe_download(filename, work_directory, source_url):
  """Download the data from source url, unless it's already here.

  Args:
      filename: string, name of the file in the directory.
      work_directory: string, path to working directory.
      source_url: url to download from if file doesn't exist.

  Returns:
      Path to resulting file.
  """
  if not gfile.Exists(work_directory):
    gfile.MakeDirs(work_directory)
  filepath = os.path.join(work_directory, filename)
  if not gfile.Exists(filepath):
    urllib.request.urlretrieve(source_url, filepath)
    with gfile.GFile(filepath) as f:
      size = f.size()
    print('Successfully downloaded', filename, size, 'bytes.')
  return filepath


@deprecated(None, 'Please use alternatives such as:'
            ' tensorflow_datasets.load(\'mnist\')')
def read_data_sets(train_dir,
                   fake_data=False,
                   one_hot=False,
                   dtype=dtypes.float32,
                   reshape=True,
                   validation_size=5000,
                   seed=None,
                   source_url=DEFAULT_SOURCE_URL):
  if fake_data:

    def fake():
      return _DataSet([], [],
                      fake_data=True,
                      one_hot=one_hot,
                      dtype=dtype,
                      seed=seed)

    train = fake()
    validation = fake()
    test = fake()
    return _Datasets(train=train, validation=validation, test=test)

  if not source_url:  # empty string check
    source_url = DEFAULT_SOURCE_URL

  train_images_file = 'train-images-idx3-ubyte.gz'
  train_labels_file = 'train-labels-idx1-ubyte.gz'
  test_images_file = 't10k-images-idx3-ubyte.gz'
  test_labels_file = 't10k-labels-idx1-ubyte.gz'

  local_file = _maybe_download(train_images_file, train_dir,
                               source_url + train_images_file)
  with gfile.Open(local_file, 'rb') as f:
    train_images = _extract_images(f)

  local_file = _maybe_download(train_labels_file, train_dir,
                               source_url + train_labels_file)
  with gfile.Open(local_file, 'rb') as f:
    train_labels = _extract_labels(f, one_hot=one_hot)

  local_file = _maybe_download(test_images_file, train_dir,
                               source_url + test_images_file)
  with gfile.Open(local_file, 'rb') as f:
    test_images = _extract_images(f)

  local_file = _maybe_download(test_labels_file, train_dir,
                               source_url + test_labels_file)
  with gfile.Open(local_file, 'rb') as f:
    test_labels = _extract_labels(f, one_hot=one_hot)

  if not 0 <= validation_size <= len(train_images):
    raise ValueError(
        'Validation size should be between 0 and {}. Received: {}.'.format(
            len(train_images), validation_size))

  validation_images = train_images[:validation_size]
  validation_labels = train_labels[:validation_size]
  train_images = train_images[validation_size:]
  train_labels = train_labels[validation_size:]

  options = dict(dtype=dtype, reshape=reshape, seed=seed)

  train = _DataSet(train_images, train_labels, **options)
  validation = _DataSet(validation_images, validation_labels, **options)
  test = _DataSet(test_images, test_labels, **options)

  return _Datasets(train=train, validation=validation, test=test)


二、解决报错ModuleNotFoundError: No module named ‘tensorflow.contrib‘

问题:在TensorFlow2.x版本已经不能使用contrib包

三、安装onnx报错assert CMAKE, ‘Could not find “cmake“ executable!‘

经过百度,查得:安装onnx需要protobuf编译所以安装前需要安装protobuf。

四、ImportError: cannot import name 'builder' from 'google.protobuf.internal'

问题:当运行torch转onnx的代码时,出现ImportError: cannot import name 'builder' from 'google.protobuf.internal',如下图:

原因:由于使用的google.protobuf版本太低而引起的。在较新的版本中,builder模块已经移动到了google.protobuf包中,而不再在google.protobuf.internal中。

解决办法:升级protobuf库

pip install --upgrade protobuf

五、解决ModuleNotFoundError: No module named 'sklearn'

问题:sklearn第三方库安装失败

原因:查看别人库的列表,发现sklearn的包名是scikit-learn

解决:安装scikit-learn,

pip install  -i https://pypi.tuna.tsinghua.edu.cn/simple scikit-learn

六、解决AttributeError: module ‘torch._C‘ has no attribute ‘_cuda_setDevice‘

网上查询原因:说我安装的torch是适合CPU的,而不是适合GPU的。于是我查询pytorch版本情况,代码如下,

import torch
torch.cuda.is_available()

结果是False。

显而易见,环境使用的是CPU版本的torch,但是我仔细检查了一下我安装的命令,如下

解决:下载三个安装包,适合GPU版本的,

可以参考这篇(1条消息) GPU版本安装Pytorch教程最新方法_pytorch gpu_水w的博客-CSDN博客

然后分别pip install 他们,这样就能够安装适合GPU版本的torch了。

七、解决ImportError: Missing optional dependency 'pytables'.  Use pip or conda to install pytables.

问题:运行py文件报错

解决历程:按照提示安装pytables,"pip install pytables"安装失败,然后试了"pip install tables"安装上了。

 重新运行代码,发现就不报错了。

八、解决AttributeError: module ‘distutils’ has no attribute ‘version’.

问题: AttributeError: module ‘distutils’ has no attribute ‘version’.

解决: setuptools版本问题”,版本过高导致的问题;setuptools版本

  • 第一步: pip uninstall setuptools【使用pip,不能使用 conda uninstall setuptools ; 【不能使用conda的命令,原因是,conda在卸载的时候,会自动分析与其相关的库,然后全部删除,如果y的话,整个环境都需要重新配置。
  • 第二步: pip或者conda install setuptools==59.5.0【现在最新的版本已经到了65了,之前的老版本只是部分保留,找不到的版本不行

然后重新运行了代码,发现没有报错了。

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/688672.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

67、基于51单片机ADXL345计步器系统设计(程序+原理图+PCB源文件+参考论文+开题报告+设计资料+元器件清单等)

摘 要 计步器是一种颇受欢迎的日常锻炼进度监控器&#xff0c;可以激励人们挑战自己&#xff0c;增强体质&#xff0c;帮助瘦身。早期设计利用加重的机械开关检测步伐&#xff0c;并带有一个简单的计数器。晃动这些装置时&#xff0c;可以听到有一个金属球来回滑动&#xff0c…

MongoDB集群搭建(四)

基础环境准备 安装Docker 创建Docker网络 因为需要使用Docker搭建MongoDB集群&#xff0c;所以先创建Docker网络 docker network create mongo-cluster docker network ls 创建挂载目录 创建对应的挂载目录来存储配置文件以及日志文件 # 创建配置文件目录 mkdir -p /opt/mongo…

MYSQL数据类型介绍

一、MySQL的数据类型 主要包括以下五大类&#xff1a; 整数类型&#xff1a;BIT、BOOL、TINY INT、SMALL INT、MEDIUM INT、 INT、 BIG INT 浮点数类型&#xff1a;FLOAT、DOUBLE、DECIMAL 字符串类型&#xff1a;CHAR、VARCHAR、TINY TEXT、TEXT、MEDIUM TEXT、LONGTEXT、TINY…

测试进阶面试必问12个算法题,洞悉出题思路,拿的就是高薪!

可以明确的一点是&#xff0c;面试算法题目在难度上&#xff08;尤其是代码难度上&#xff09;会略低一些&#xff0c;倾向于考察一些基础数据结构与算法&#xff0c;对于高级算法和奇技淫巧一般不作考察。 代码题主要考察编程语言的应用是否熟练&#xff0c;基础是否扎实&…

GPIO通用输入输出口

GPIO 1、简介1.1、基本结构1.2、工作模式使用库函数的使用方法 2、GPIO输出LED流水灯蜂鸣器 3、GPIO输入按键控制LED光敏传感器控制蜂鸣器 1、简介 1、GPIO(general Purpose Input Output)通用输入输出口&#xff1b; 2、可配置为8种输入输出模式&#xff1b; 3、引脚电平&…

如何在Linux部署Jdk1.8备忘录(高效版)

提示&#xff1a;高效简洁版 文章目录 前言一、整理环境二、部署jdk1.8三、建立Java环境四、生效验证总结 前言 作为备忘录阐述&#xff0c;力求简洁明了&#xff0c;直接开始贴步骤。 一、整理环境 1.首先查看服务器上是否有Java&#xff0c;如果自带恭喜你不用装了。 java…

Linux5.gcc(g++),动静态链接,make和Makefile

1.gcc od 文件 :查看二进制文件。 2.动静态库(此处简单认识&#xff0c;详细内容后面介绍) ldd 文件 :查看文件所依赖的库。 file 文件 :查看文件的具体信息。 在Linux当中&#xff0c;程序在链接的时候&#xff0c;默认是动态链接(后缀是.so) 如果要使用静态链接&#xff…

Redis的3大特殊数据结构(3)-Geospatial

Geospatial地理空间&#xff0c;Redis 在 3.2 版本中加入了地理空间&#xff08;geospatial&#xff09;以及索引半径查询的功能&#xff0c;主要用在需要地理位置的应用上。将指定的地理空间位置&#xff08;经度、纬度、名称&#xff09;添加到指定的 key 中&#xff0c;这些…

JS逆向入门教程p1 浏览器设置 常用工具

1.准备工作 http 编程语言(网络apidavaScript) 逆向(js逆向 安卓逆向 ios逆向 PC逆向)调试 图像识别 下载城南Post助手、fiddler、wireshark(鲨鱼)抓包工具; 通过进程抓包 fiddler插件: f12配置推荐,实验功能全部关闭 时间线上的分配检测:js的运行时间线 关闭时间…

【软考网络管理员】2023年软考网管初级常见知识考点(21)-安装及配置DHCP服务器(图文结合)

涉及知识点 安装DHCP服务器&#xff0c;配置DHCP服务器&#xff0c;如何去安装DHCP服务器&#xff0c;如何去配置DHCP服务器&#xff0c;软考网络管理员常考知识点&#xff0c;软考网络管理员网络安全&#xff0c;网络管理员考点汇总。 原创于&#xff1a;CSDN博主-《拄杖盲学…

项目进度计划表的制作方法解析:简单易懂的步骤指南

项目进度计划表怎么做&#xff1f;创建项目进度表是项目管理的一个重要组成部分&#xff0c;它有助于确保项目的成功完成。它是一个详细的计划&#xff0c;概述了实现项目目标所需的工作范围、时间线、里程碑和资源。本文将讨论制定项目进度表所涉及的步骤。 1、定义项目范围: …

掌握Gradio的Audio模块:实时交互与多功能展示

❤️觉得内容不错的话&#xff0c;欢迎点赞收藏加关注&#x1f60a;&#x1f60a;&#x1f60a;&#xff0c;后续会继续输入更多优质内容❤️ &#x1f449;有问题欢迎大家加关注私戳或者评论&#xff08;包括但不限于NLP算法相关&#xff0c;linux学习相关&#xff0c;读研读博…

C语言学习(二十七)---指针练习题(三)

在上一节的内容中&#xff0c;我们继续学习了字符数组的相关指针练习题&#xff0c;今天我们将继续将练习有关二维数组的指针练习题和有关结构体的指针练习题&#xff0c;好了&#xff0c;话不多说&#xff0c;开整&#xff01;&#xff01;&#xff01;&#xff01; 二维数组…

从零开始学习:如何使用Selenium和Python进行自动化测试?

安装selenium 打开命令控制符输入&#xff1a;pip install -U selenium 火狐浏览器安装firebug&#xff1a;www.firebug.com&#xff0c;调试所有网站语言&#xff0c;调试功能 Selenium IDE 是嵌入到Firefox 浏览器中的一个插件&#xff0c;实现简单的浏览器操 作的录制与回…

开源社 KCC@硅谷正式成立,搭建国际开源交流平台

大家好&#xff01;我很高兴向大家宣布一个重要的消息&#xff1a; 开源社在硅谷的KCC&#xff08;Kaiyuanshe City Community&#xff09;正式成立了&#xff01;作为开源社的一项重要举措&#xff0c;KCC硅谷将成为国际开源交流的桥梁&#xff0c;架起中国和全球开源社区之间…

第十八章、Spring中的事务属性:隔离、传播属性等

1.什么是事务属性 属性&#xff1a;描述物体特征的一系列值 事务属性&#xff1b;描述事务特征的一系列值 1. 隔离属性 2. 传播属性 3. 只读属性 4. 超时属性 5. 异常属性2.如何添加事务属性 Transactional(isloation,propagation,readOnly,timeout,rollbackFor,norollbackFo…

three.js中物体的灯光与阴影设置

一、.设置物体阴影的核心步骤 1. 以平面上有一个球体为例&#xff0c;设置球体的阴影投射到平面上&#xff0c;核心步骤如下&#xff1a; 要让球体的阴影照射到平面上&#xff0c;需要使用阴影映射技术。具体步骤如下&#xff1a; 在渲染器中启用阴影&#xff1a; renderer…

高速下载ChatGLM2模型文件的解决方案

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。喜欢通过博客创作的方式对所学的…

无法使用MBR2GPT创建EFI系统分区?试试这方法!

将MBR转换为GPT的原因 你可能已经了解了GPT和MBR这两种不同类型的磁盘。由于硬盘容量一直在不断增加&#xff0c;人们现在更偏向于使用GPT磁盘。相较于MBR磁盘&#xff0c;GPT磁盘支持更大的存储空间&#xff0c;其限制超过了2TB。另外&#xff0c;GPT磁盘允许几乎无限数量…

【网络编程】网络基础(一)

文章目录 一、计算机网络背景1.网络发展2.认识 "协议" 二、网络协议初识1.协议分层2.OSI七层模型3.TCP/IP五层(或四层)模型 三、网络传输基本流程1.网络传输流程图2.数据包首部&#xff08;报头&#xff09;3.数据包封装和分用封装分用 4. 跨局域网主机通信 四、网络…