【问题标题】:Cannot convert Numpy array as tensor for input无法将 Numpy 数组转换为输入的张量
【发布时间】:2021-06-26 02:44:19
【问题描述】:

当我想使用 lstm 模型根据各种因素生成文本时,当我尝试使用我想要使用的数据时,我收到一个 Failed to convert a NumPy array to a Tensor (Unsupported object type list) 错误在接受输入时。以下是我给定的数据:

state district month rainfall max_temp min_temp max_rh min_rh wind_speed advice
[1] [1] 2 0.0 34.6 19.4 88.2 29.6 12.0 [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 10, 1, 11, 12, 13, 3, 4, 5],[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 14, 15, 2, 16, 17, 6, 7, 2, 18, 19, 20, 8, 4],[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 21, 9, 22, 5, 23, 24, 2, 25, 26, 6, 27]]
[2] [2,3] 2 0 35.2 16.6 29.4 11.2 3.6 [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 55, 21, 56, 57, 3,22, 19, 58, 6, 59, 4, 60, 1, 61, 62, 23, 63, 23, 64], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 65, 7, 66, 2, 67, 68, 3, 69, 70], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12, 5, 13, 14, 9, 10, 5, 15, 16, 17, 2, 8], [ 0, 0, 0, 0, 0, 2, 71, 1, 72, 73, 74, 7, 75, 76, 77, 3, 20, 78, 18, 79, 1, 21, 80, 81, 3, 82, 83, 84, 6, 85]]

我用来输入标签和数据的代码如下。

labels=data.pop('advices')
ds= tf.data.Dataset.from_tensor_slices((dict(data), labels))

我得到的错误如下。

TypeError: Could not build a TypeSpec for 0       [1]
1       [1]
2       [1]
3    [2, 3]
4    [2, 3]
Name: district, dtype: object with type Series

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
     96       dtype = dtypes.as_dtype(dtype).as_datatype_enum
     97   ctx.ensure_initialized()
---> 98   return ops.EagerTensor(value, ctx.device_name, dtype)
     99 
    100 

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

我是这个领域的新手,请有人帮助我。

【问题讨论】:

  • 基于错误,我猜问题是你的数组中的元素不是标量而是序列本身
  • 是的,就是这样。而且我知道我以后也会在建议列中得到同样的错误。我不知道如何解决它。
  • @Santosh Kumar:您是否已经找到了解决问题的方法,如果找到了,您会好心与我们分享吗?

标签: python numpy tensorflow machine-learning lstm


【解决方案1】:

将 numpy 数组转换为张量的示例代码。

import numpy as np
import tensorflow as tf
a = [0.1, 0.2, 0.3, 0.4]
arg = tf.convert_to_tensor(a, dtype=tf.float32)

输出

<tf.Tensor: shape=(4,), dtype=float32, numpy=array([0.1, 0.2, 0.3, 0.4], dtype=float32)>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2021-10-19
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多