在tensorflow2.x上使用1.x版本常见错误

最近想换个框架,然后就选了tensorlow,用的是这本教材在tensorflow2.x上使用1.x版本常见错误_第1张图片
说实话,写的一般,而且它里面的很多程序已经用不了了,tensorflow比较特别,它现在的高版本不适应低版本,我自己拆过很多坑,比如如何在version2里面用version1,以及tensorboard打不开等等情况。

我在下面列出来,有需要的可以看一下,希望大家不要再踩坑了!!!!!我就举相似的例子,实际情况要根据那么自己出的问题来解决,另外我用的是tensorflow2.5

问题一:出现类似报错:error: AttributeError: module ‘tensorflow’ has no attribute ‘placeholder’

我在下面的代码里面的设置了占位符placeholder,但是他给我报错了

import tensorflow as tf

x = tf.placeholder(tf.float32, [None, 28, 28, 1], name='input')
w = tf.Variable([10, 0], name='weight')
b = tf.constant(100)

error: AttributeError: module ‘tensorflow’ has no attribute 'placeholder’

你们网上查到的这种写法也是错的:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

其实是因为1.x版本变成了2.x版本,x、w、b对应的方法已经不能直接调用tensorflow了,而且compat这个包也被移到别的地方去了
改成下面这种:

import tensorflow._api.v2.compat.v1 as tf
tf.disable_v2_behavior()

x = tf.placeholder(tf.float32, [None, 28, 28, 1], name='input')
w = tf.Variable([10, 0], name='weight')
b = tf.constant(100)

问题二:tensorboard给的网址上不去

就像这样:
在这里插入图片描述
在tensorflow2.x上使用1.x版本常见错误_第2张图片
解决方法:
有VPN的建议开一下,然后确保程序没有问题的情况下运行一遍程序,让它生成日志:就是生成这种events开头的文件
在tensorflow2.x上使用1.x版本常见错误_第3张图片
我用的是pytcharm,点击下方的Terminal按钮
在这里插入图片描述
这个时候它会帮我们启动终端:
在tensorflow2.x上使用1.x版本常见错误_第4张图片
输入tensorboard --logdir=日志名字,会得到这样一个结果(中间那些是因为我之前生成过日志,没有也没关系):
在tensorflow2.x上使用1.x版本常见错误_第5张图片
这个不要把这个终端关闭了,把它开着,然后点击网址就进去了:
在tensorflow2.x上使用1.x版本常见错误_第6张图片
最重要的是,一定要把你的log文件放在工程的根目录下面,如果不放在根目录里,肯定是进不去的
意思就是,以我的为例,我的工程是这个:
在tensorflow2.x上使用1.x版本常见错误_第7张图片
看到那个.idea文件了吗,这个你的主程序还有log文件都要和这个.idea放在一起,比如,你把log_mnist_softmax这个日志和主程序softMaxClassitfy放在data这个文件夹里,你再用上面的方法打开tensorboard是打不开的

问题三:2.x版本的mnist数据集怎么用

正常的教材都是以手写数字识别为例子来进行教学,其实处理数据集本来是一个比较容易的问题的,但是这个mnist_data它的文件格式跟我们以前用过的不一样,要经过特殊的处理,tensorflow为了我们用的方便,所以专门做了一个方法用来处理这个数据集,所以我们经常会看到第四行这句代码:

import tensorflow._api.v2.compat.v1 as tf
tf.disable_v2_behavior()

from tensorflow.examples.tutorials.mnist import input_data

但是这个大部分人都用不了,在pycharm里它长这个样:在这里插入图片描述
这个问题有两个解决方办法:

1

其实这个input_data是一个小脚本,不用去下载了,我直接把代码粘出来,你们直接创建一个python文件直接调用就行了

# 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)


2或者是像下面这样(不建议用这个方法)

我们找到安装PY的文件夹:
在tensorflow2.x上使用1.x版本常见错误_第8张图片
它里面有一个lib文件夹,打开它,找到一个叫site-packages的文件夹,再打开它,找到tensorflow:
在这里插入图片描述

新版本里面,tensorflow就只有这几个文件了,你们取网上看的可能还会有一个叫做tensorflow_core的文件夹,但是那个文章是好几年前写的了,现在版本更新,那个文件已经不在了,现在我们打开第一个文件:tensorflow:
在tensorflow2.x上使用1.x版本常见错误_第9张图片
看见了吗?里面有一个core,这个就是以前的tensorflow_core了
打开它,里面有一个叫example的文件夹,它就是我们程序里找不到的example了,里面长这样:
在tensorflow2.x上使用1.x版本常见错误_第10张图片
我们看一下你们有没有第二个文件:
在tensorflow2.x上使用1.x版本常见错误_第11张图片
没有的话就去这里面下载:
https://github.com/tensorflow/tensorflow
下载了以后,再改一下路径,上面的代码就能用了

from tensorflow.core.example.tutorials.mnist import input_data

问题四:出现类似这样的报错:error:could not broadcast input array from shape (784) into shape (1)

要么是你的设置占位符的时候张量的形状本身就不对,要么就是你把他写成了类似下面的样子:

result = sess.run(['input:0', y_conv], feed_dict={x: [img]})

一路看下来这个代码好像都没什么问题,这个是因为我们用这种列表类型的 [] 取出方式会为数据降维,要么写成这样:

result = sess.run(y_conv, feed_dict={x: [img]})

要么参照这篇文章的https://blog.csdn.net/u012796629/article/details/102477500
用tf.slice

问题五:出现这种报错TypeError: Fetch argument array([4], dtype=int64) has invalid type , must be a string or Tensor. (Can not convert a ndarray into a Tensor or Operation.)

看一看你用argmax这个方法的地方,
这两句代码的返回值是完全不同的

# print(sess.run(np.argmax(result, 1))) #报错, 用tf的argmax
print(sess.run(tf.argmax(result, 1)))

tf的argmax返回张量,np返回array
可以看看这篇文章https://blog.csdn.net/weixin_44810016/article/details/91492069

你可能感兴趣的:(机器学习,python,tensorflow)