首页 > 解决方案 > ValueError: Argument must be a dense tensor...形状为 [80, 3, 8, 8],但想要 [80] 与 estimator.predict

问题描述

我正在尝试使用 TPUEstimator.predict 方法生成一些图像。这是我的代码

    generated_iter = model.predict(input_fn=noise_input_fn)                  #generating images
    images = [p['fake_images'][:, :, :] for p in generated_iter]             #writing to array
    assert len(images) == 80                                                 #asserting number of images
    rgb_images = convert_to_rgb_images(images)                               #transposing and converting
    image_rows = [np.concatenate(rgb_images[i:i + 10], axis=0)               #making a 8x10 matrix of images
                  for i in range(0, 80, 10)]
    tiled_image = np.concatenate(image_rows, axis=1)

    img = Image.fromarray(tiled_image)

它在标题中给了我错误,然后是这样的几个例外:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/content/stylegan-reproduced/train.py", line 326, in <module>
    main()
  File "/content/stylegan-reproduced/train.py", line 321, in main
    train(model_dir, n_images_to_show, batch_size, estimator_params, estimator_ws=ws)
  File "/content/stylegan-reproduced/train.py", line 157, in train
    rgb_images = convert_to_rgb_images(images)
  File "/content/stylegan-reproduced/network/model_fn.py", line 113, in convert_to_rgb_images
    output = tf.transpose(images, perm=[0, 2, 3, 1])
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/array_ops.py", line 1738, in transpose
    ret = transpose_fn(a, perm, name=name)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 11046, in transpose
    "Transpose", x=x, perm=perm, name=name)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py", line 545, in _apply_op_helper
    (input_name, err))
ValueError: Tried to convert 'x' to a tensor and failed. Error: Argument must be a dense tensor:

最后got shape [80, 3, 8, 8], but wanted [80]。据我了解,convert_to_rgb 函数有问题,但我不明白究竟是什么。这是函数本身。

   def convert_to_rgb_images(images):
drange_min, drange_max = -1.0, 1.0
scale = 255.0 / (drange_max - drange_min)

output = tf.transpose(images, perm=[0, 2, 3, 1])
output = output * scale + (0.5 - drange_min * scale)
output = tf.clip_by_value(output, 0.0, 255.0)
output = tf.cast(output, dtype=tf.uint8)
return output

在 model_fn 中调用它可以正常工作,但在 model.predict 之后会出错。我错过了什么?

标签: pythonpython-3.xtensorflow

解决方案


推荐阅读