首页 > 解决方案 > 张量流错误。TypeError:张量对象仅在启用急切执行时才可迭代。要迭代此张量,请使用 tf.map_fn

问题描述

我正在尝试在 Amazon Sagemaker 上运行它,但是当我尝试在本地计算机上运行它时出现此错误,它运行良好。

这是我的代码:

import tensorflow as tf

import IPython.display as display

import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (12,12)
mpl.rcParams['axes.grid'] = False

import numpy as np
import PIL.Image
import time
import functools
    
def tensor_to_image(tensor):
  tensor = tensor*255
  tensor = np.array(tensor, dtype=np.uint8)
  if np.ndim(tensor)>3:
    assert tensor.shape[0] == 1
    tensor = tensor[0]
  return PIL.Image.fromarray(tensor)

content_path = tf.keras.utils.get_file('YellowLabradorLooking_nw4.jpg', 'https://example.com/IMG_20200216_163015.jpg')


style_path = tf.keras.utils.get_file('kandinsky3.jpg','https://example.com/download+(2).png')


def load_img(path_to_img):
    max_dim = 512
    img = tf.io.read_file(path_to_img)
    img = tf.image.decode_image(img, channels=3)
    img = tf.image.convert_image_dtype(img, tf.float32)

    shape = tf.cast(tf.shape(img)[:-1], tf.float32)
    long_dim = max(shape)
    scale = max_dim / long_dim

    new_shape = tf.cast(shape * scale, tf.int32)

    img = tf.image.resize(img, new_shape)
    img = img[tf.newaxis, :]
    return img


def imshow(image, title=None):
  if len(image.shape) > 3:
    image = tf.squeeze(image, axis=0)

  plt.imshow(image)
  if title:
    plt.title(title)


content_image = load_img(content_path)
style_image = load_img(style_path)

plt.subplot(1, 2, 1)
imshow(content_image, 'Content Image')

plt.subplot(1, 2, 2)
imshow(style_image, 'Style Image')

import tensorflow_hub as hub
hub_module = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/1')
stylized_image = hub_module(tf.constant(content_image), tf.constant(style_image))[0]
tensor_to_image(stylized_image)


file_name = 'stylized-image5.png'
tensor_to_image(stylized_image).save(file_name)

这是我得到的确切错误:

---------------------------------------------------------------------------

TypeError Traceback(最近一次调用最后一次)

<ipython-input-24-c47a4db4880c> in <module>()
     53 
     54 
---> 55 content_image = load_img(content_path)
     56 style_image = load_img(style_path)
     57 

在 load_img(path_to_img)

     34 
     35     shape = tf.cast(tf.shape(img)[:-1], tf.float32)
---> 36     long_dim = max(shape)
     37     scale = max_dim / long_dim
     38 

~/anaconda3/envs/amazonei_tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in iter (self)

    475     if not context.executing_eagerly():
    476       raise TypeError(
--> 477           "Tensor objects are only iterable when eager execution is "
    478           "enabled. To iterate over this tensor use tf.map_fn.")
    479     shape = self._shape_tuple()

TypeError:张量对象仅在启用急切执行时才可迭代。要迭代此张量,请使用 tf.map_fn。

标签: pythonpython-3.xtensorflowdata-scienceamazon-sagemaker

解决方案


此函数中引发了您的错误load_img

def load_img(path_to_img):
    max_dim = 512
    img = tf.io.read_file(path_to_img)
    img = tf.image.decode_image(img, channels=3)
    img = tf.image.convert_image_dtype(img, tf.float32)

    shape = tf.cast(tf.shape(img)[:-1], tf.float32)
    long_dim = max(shape)
    scale = max_dim / long_dim

    new_shape = tf.cast(shape * scale, tf.int32)

    img = tf.image.resize(img, new_shape)
    img = img[tf.newaxis, :]
    return img

具体来说,这一行:

    long_dim = max(shape)

您在图形执行模式下将张量传递给内置的 Python max 函数。您只能在急切执行模式下遍历张量。您可能想改用tf.reduce_max

    long_dim = tf.reduce_max(shape)

推荐阅读