【问题标题】:Getting Error in tf.cast while implementing CGAN实现 CGAN 时在 tf.cast 中出错
【发布时间】:2021-11-03 08:59:59
【问题描述】:

问题

您好,我正在 TensorFlow 中实现 CGAN。 请帮助我了解错误的原因以及解决方法。

代码

def train(dataset, epochs):   for epoch in range(epochs):
    start = time.time()
    for image_batch in dataset:
      img = tf.cast(image_batch, tf.float32)
      imgs = normalization(img)
      train_step(imgs,target)

    print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))


train(ds, 200)

归一化函数代码:

@tf.function
def normalization(tensor):
    tensor = tf.image.resize(
    tensor, (128,128))
    tensor = tf.subtract(tf.divide(tensor, 127.5), 1)
    return tensor

错误

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-24-bf631b0ce503> in <module>
     10 
     11 
---> 12 train(ds, 200)

<ipython-input-24-bf631b0ce503> in train(dataset, epochs)
      3     start = time.time()
      4     for image_batch in dataset:
----> 5       img = tf.cast(image_batch, tf.float32)
      6       imgs = normalization(img)
      7       train_step(imgs,target)

E:\Users\Asus\anaconda3\lib\site-packages\tensorflow\python\util\dispatch.py in wrapper(*args, **kwargs)
    199     """Call target, and fall back on dispatchers if there is a TypeError."""
    200     try:
--> 201       return target(*args, **kwargs)
    202     except (TypeError, ValueError):
    203       # Note: convert_to_eager_tensor currently raises a ValueError, not a

E:\Users\Asus\anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py in cast(x, dtype, name)
    919       # allows some conversions that cast() can't do, e.g. casting numbers to
    920       # strings.
--> 921       x = ops.convert_to_tensor(x, name="x")
    922       if x.dtype.base_dtype != base_type:
    923         x = gen_math_ops.cast(x, base_type, name=name)

E:\Users\Asus\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, dtype_hint, ctx, accepted_result_types)
   1497 
   1498     if ret is None:
-> 1499       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
   1500 
   1501     if ret is NotImplemented:

E:\Users\Asus\anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py in _autopacking_conversion_function(v, dtype, name, as_ref)
   1500   elif dtype != inferred_dtype:
   1501     v = nest.map_structure(_cast_nested_seqs_to_dtype(dtype), v)
-> 1502   return _autopacking_helper(v, dtype, name or "packed")
   1503 
   1504 

E:\Users\Asus\anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py in _autopacking_helper(list_or_tuple, dtype, name)
   1406     # checking.
   1407     if all(isinstance(elem, core.Tensor) for elem in list_or_tuple):
-> 1408       return gen_array_ops.pack(list_or_tuple, name=name)
   1409   must_pack = False
   1410   converted_elems = []

E:\Users\Asus\anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py in pack(values, axis, name)
   6456       return _result
   6457     except _core._NotOkStatusException as e:
-> 6458       _ops.raise_from_not_ok_status(e, name)
   6459     except _core._FallbackException:
   6460       pass

E:\Users\Asus\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in raise_from_not_ok_status(e, name)
   6841   message = e.message + (" name: " + name if name is not None else "")
   6842   # pylint: disable=protected-access
-> 6843   six.raise_from(core._status_to_exception(e.code, message), None)
   6844   # pylint: enable=protected-access
   6845 

E:\Users\Asus\anaconda3\lib\site-packages\six.py in raise_from(value, from_value)

**InvalidArgumentError: cannot compute Pack as input #1(zero-based) was expected to be a uint8 tensor but is a int64 tensor [Op:Pack] name: x**

我为解决此问题所做的尝试:

我尝试改变

tensor = tf.subtract(tf.divide(tensor, 127.5), 1) 

tensor = tf.subtract(tf.divide(tensor, 127), 1)

此外,

img = tf.cast(image_batch, tf.float32)

img = tf.cast(image_batch, tf.int64)

但错误仍然相同。任何帮助将不胜感激。

【问题讨论】:

  • 你试过img = tf.cast(image_batch, tf.uint8) 吗?
  • 是的,同样的错误。

标签: python tensorflow deep-learning cgan


【解决方案1】:

您的dataset 可能由一个元组(图像、标签)组成,因此请尝试像这样拆分每个批次:

import tensorflow as tf
import time 
import pathlib

def train(dataset, epochs):   
  for epoch in range(epochs):
    start = time.time()
    for image_batch in dataset:
      images, labels = image_batch
      imgs = tf.cast(images, tf.float32)
      imgs = normalization(imgs)

    print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))

@tf.function
def normalization(tensor):
   
    tensor = tf.image.resize(
    tensor, (128,128))
    tensor = tf.subtract(tf.divide(tensor, 127.5), 1)
    tf.print(tf.shape(tensor))
    return tensor


dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

batch_size = 32

train_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(256, 256),
  batch_size=batch_size)

train(train_ds, 200)

【讨论】:

    猜你喜欢
    • 2012-12-28
    • 2021-05-11
    • 2018-06-04
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多