当前位置:   article > 正文

python 深度学习 解决遇到的报错问题_modulenotfounderror: no module named 'tensorflow.e

modulenotfounderror: no module named 'tensorflow.examples

目录

一、解决报错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文件内容放在下面,需要的自取。

  1. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Functions for downloading and reading MNIST data (deprecated).
  16. This module and all its submodules are deprecated.
  17. """
  18. from __future__ import absolute_import
  19. from __future__ import division
  20. from __future__ import print_function
  21. import collections
  22. import gzip
  23. import os
  24. import numpy
  25. from six.moves import urllib
  26. from six.moves import xrange # pylint: disable=redefined-builtin
  27. from tensorflow.python.framework import dtypes
  28. from tensorflow.python.framework import random_seed
  29. from tensorflow.python.platform import gfile
  30. from tensorflow.python.util.deprecation import deprecated
  31. _Datasets = collections.namedtuple('_Datasets', ['train', 'validation', 'test'])
  32. # CVDF mirror of http://yann.lecun.com/exdb/mnist/
  33. DEFAULT_SOURCE_URL = 'https://storage.googleapis.com/cvdf-datasets/mnist/'
  34. def _read32(bytestream):
  35. dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  36. return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
  37. @deprecated(None, 'Please use tf.data to implement this functionality.')
  38. def _extract_images(f):
  39. """Extract the images into a 4D uint8 numpy array [index, y, x, depth].
  40. Args:
  41. f: A file object that can be passed into a gzip reader.
  42. Returns:
  43. data: A 4D uint8 numpy array [index, y, x, depth].
  44. Raises:
  45. ValueError: If the bytestream does not start with 2051.
  46. """
  47. print('Extracting', f.name)
  48. with gzip.GzipFile(fileobj=f) as bytestream:
  49. magic = _read32(bytestream)
  50. if magic != 2051:
  51. raise ValueError('Invalid magic number %d in MNIST image file: %s' %
  52. (magic, f.name))
  53. num_images = _read32(bytestream)
  54. rows = _read32(bytestream)
  55. cols = _read32(bytestream)
  56. buf = bytestream.read(rows * cols * num_images)
  57. data = numpy.frombuffer(buf, dtype=numpy.uint8)
  58. data = data.reshape(num_images, rows, cols, 1)
  59. return data
  60. @deprecated(None, 'Please use tf.one_hot on tensors.')
  61. def _dense_to_one_hot(labels_dense, num_classes):
  62. """Convert class labels from scalars to one-hot vectors."""
  63. num_labels = labels_dense.shape[0]
  64. index_offset = numpy.arange(num_labels) * num_classes
  65. labels_one_hot = numpy.zeros((num_labels, num_classes))
  66. labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
  67. return labels_one_hot
  68. @deprecated(None, 'Please use tf.data to implement this functionality.')
  69. def _extract_labels(f, one_hot=False, num_classes=10):
  70. """Extract the labels into a 1D uint8 numpy array [index].
  71. Args:
  72. f: A file object that can be passed into a gzip reader.
  73. one_hot: Does one hot encoding for the result.
  74. num_classes: Number of classes for the one hot encoding.
  75. Returns:
  76. labels: a 1D uint8 numpy array.
  77. Raises:
  78. ValueError: If the bystream doesn't start with 2049.
  79. """
  80. print('Extracting', f.name)
  81. with gzip.GzipFile(fileobj=f) as bytestream:
  82. magic = _read32(bytestream)
  83. if magic != 2049:
  84. raise ValueError('Invalid magic number %d in MNIST label file: %s' %
  85. (magic, f.name))
  86. num_items = _read32(bytestream)
  87. buf = bytestream.read(num_items)
  88. labels = numpy.frombuffer(buf, dtype=numpy.uint8)
  89. if one_hot:
  90. return _dense_to_one_hot(labels, num_classes)
  91. return labels
  92. class _DataSet(object):
  93. """Container class for a _DataSet (deprecated).
  94. THIS CLASS IS DEPRECATED.
  95. """
  96. @deprecated(None, 'Please use alternatives such as official/mnist/_DataSet.py'
  97. ' from tensorflow/models.')
  98. def __init__(self,
  99. images,
  100. labels,
  101. fake_data=False,
  102. one_hot=False,
  103. dtype=dtypes.float32,
  104. reshape=True,
  105. seed=None):
  106. """Construct a _DataSet.
  107. one_hot arg is used only if fake_data is true. `dtype` can be either
  108. `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
  109. `[0, 1]`. Seed arg provides for convenient deterministic testing.
  110. Args:
  111. images: The images
  112. labels: The labels
  113. fake_data: Ignore inages and labels, use fake data.
  114. one_hot: Bool, return the labels as one hot vectors (if True) or ints (if
  115. False).
  116. dtype: Output image dtype. One of [uint8, float32]. `uint8` output has
  117. range [0,255]. float32 output has range [0,1].
  118. reshape: Bool. If True returned images are returned flattened to vectors.
  119. seed: The random seed to use.
  120. """
  121. seed1, seed2 = random_seed.get_seed(seed)
  122. # If op level seed is not set, use whatever graph level seed is returned
  123. numpy.random.seed(seed1 if seed is None else seed2)
  124. dtype = dtypes.as_dtype(dtype).base_dtype
  125. if dtype not in (dtypes.uint8, dtypes.float32):
  126. raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
  127. dtype)
  128. if fake_data:
  129. self._num_examples = 10000
  130. self.one_hot = one_hot
  131. else:
  132. assert images.shape[0] == labels.shape[0], (
  133. 'images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
  134. self._num_examples = images.shape[0]
  135. # Convert shape from [num examples, rows, columns, depth]
  136. # to [num examples, rows*columns] (assuming depth == 1)
  137. if reshape:
  138. assert images.shape[3] == 1
  139. images = images.reshape(images.shape[0],
  140. images.shape[1] * images.shape[2])
  141. if dtype == dtypes.float32:
  142. # Convert from [0, 255] -> [0.0, 1.0].
  143. images = images.astype(numpy.float32)
  144. images = numpy.multiply(images, 1.0 / 255.0)
  145. self._images = images
  146. self._labels = labels
  147. self._epochs_completed = 0
  148. self._index_in_epoch = 0
  149. @property
  150. def images(self):
  151. return self._images
  152. @property
  153. def labels(self):
  154. return self._labels
  155. @property
  156. def num_examples(self):
  157. return self._num_examples
  158. @property
  159. def epochs_completed(self):
  160. return self._epochs_completed
  161. def next_batch(self, batch_size, fake_data=False, shuffle=True):
  162. """Return the next `batch_size` examples from this data set."""
  163. if fake_data:
  164. fake_image = [1] * 784
  165. if self.one_hot:
  166. fake_label = [1] + [0] * 9
  167. else:
  168. fake_label = 0
  169. return [fake_image for _ in xrange(batch_size)
  170. ], [fake_label for _ in xrange(batch_size)]
  171. start = self._index_in_epoch
  172. # Shuffle for the first epoch
  173. if self._epochs_completed == 0 and start == 0 and shuffle:
  174. perm0 = numpy.arange(self._num_examples)
  175. numpy.random.shuffle(perm0)
  176. self._images = self.images[perm0]
  177. self._labels = self.labels[perm0]
  178. # Go to the next epoch
  179. if start + batch_size > self._num_examples:
  180. # Finished epoch
  181. self._epochs_completed += 1
  182. # Get the rest examples in this epoch
  183. rest_num_examples = self._num_examples - start
  184. images_rest_part = self._images[start:self._num_examples]
  185. labels_rest_part = self._labels[start:self._num_examples]
  186. # Shuffle the data
  187. if shuffle:
  188. perm = numpy.arange(self._num_examples)
  189. numpy.random.shuffle(perm)
  190. self._images = self.images[perm]
  191. self._labels = self.labels[perm]
  192. # Start next epoch
  193. start = 0
  194. self._index_in_epoch = batch_size - rest_num_examples
  195. end = self._index_in_epoch
  196. images_new_part = self._images[start:end]
  197. labels_new_part = self._labels[start:end]
  198. return numpy.concatenate((images_rest_part, images_new_part),
  199. axis=0), numpy.concatenate(
  200. (labels_rest_part, labels_new_part), axis=0)
  201. else:
  202. self._index_in_epoch += batch_size
  203. end = self._index_in_epoch
  204. return self._images[start:end], self._labels[start:end]
  205. @deprecated(None, 'Please write your own downloading logic.')
  206. def _maybe_download(filename, work_directory, source_url):
  207. """Download the data from source url, unless it's already here.
  208. Args:
  209. filename: string, name of the file in the directory.
  210. work_directory: string, path to working directory.
  211. source_url: url to download from if file doesn't exist.
  212. Returns:
  213. Path to resulting file.
  214. """
  215. if not gfile.Exists(work_directory):
  216. gfile.MakeDirs(work_directory)
  217. filepath = os.path.join(work_directory, filename)
  218. if not gfile.Exists(filepath):
  219. urllib.request.urlretrieve(source_url, filepath)
  220. with gfile.GFile(filepath) as f:
  221. size = f.size()
  222. print('Successfully downloaded', filename, size, 'bytes.')
  223. return filepath
  224. @deprecated(None, 'Please use alternatives such as:'
  225. ' tensorflow_datasets.load(\'mnist\')')
  226. def read_data_sets(train_dir,
  227. fake_data=False,
  228. one_hot=False,
  229. dtype=dtypes.float32,
  230. reshape=True,
  231. validation_size=5000,
  232. seed=None,
  233. source_url=DEFAULT_SOURCE_URL):
  234. if fake_data:
  235. def fake():
  236. return _DataSet([], [],
  237. fake_data=True,
  238. one_hot=one_hot,
  239. dtype=dtype,
  240. seed=seed)
  241. train = fake()
  242. validation = fake()
  243. test = fake()
  244. return _Datasets(train=train, validation=validation, test=test)
  245. if not source_url: # empty string check
  246. source_url = DEFAULT_SOURCE_URL
  247. train_images_file = 'train-images-idx3-ubyte.gz'
  248. train_labels_file = 'train-labels-idx1-ubyte.gz'
  249. test_images_file = 't10k-images-idx3-ubyte.gz'
  250. test_labels_file = 't10k-labels-idx1-ubyte.gz'
  251. local_file = _maybe_download(train_images_file, train_dir,
  252. source_url + train_images_file)
  253. with gfile.Open(local_file, 'rb') as f:
  254. train_images = _extract_images(f)
  255. local_file = _maybe_download(train_labels_file, train_dir,
  256. source_url + train_labels_file)
  257. with gfile.Open(local_file, 'rb') as f:
  258. train_labels = _extract_labels(f, one_hot=one_hot)
  259. local_file = _maybe_download(test_images_file, train_dir,
  260. source_url + test_images_file)
  261. with gfile.Open(local_file, 'rb') as f:
  262. test_images = _extract_images(f)
  263. local_file = _maybe_download(test_labels_file, train_dir,
  264. source_url + test_labels_file)
  265. with gfile.Open(local_file, 'rb') as f:
  266. test_labels = _extract_labels(f, one_hot=one_hot)
  267. if not 0 <= validation_size <= len(train_images):
  268. raise ValueError(
  269. 'Validation size should be between 0 and {}. Received: {}.'.format(
  270. len(train_images), validation_size))
  271. validation_images = train_images[:validation_size]
  272. validation_labels = train_labels[:validation_size]
  273. train_images = train_images[validation_size:]
  274. train_labels = train_labels[validation_size:]
  275. options = dict(dtype=dtype, reshape=reshape, seed=seed)
  276. train = _DataSet(train_images, train_labels, **options)
  277. validation = _DataSet(validation_images, validation_labels, **options)
  278. test = _DataSet(test_images, test_labels, **options)
  279. 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版本情况,代码如下,

  1. import torch
  2. 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了,之前的老版本只是部分保留,找不到的版本不行

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

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57613
推荐阅读
相关标签
  

闽ICP备14008679号