【问题标题】:Failed to convert numpy array to tensor无法将 numpy 数组转换为张量
【发布时间】:2020-08-06 20:22:49
【问题描述】:

我尝试在 python 中使用 keras/tensorflow 来使用 model.fit 并收到此错误。所有软件包都安装良好,但在转换为 numpy 数组时遇到问题

~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\constant_op.py in constant(value, dtype, shape, name)
        259     ValueError: if called on a symbolic tensor.
        260   """
    --> 261   return _constant_impl(value, dtype, shape, name, verify_shape=False,
        262                         allow_broadcast=True)
        263 
    
~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\constant_op.py in _constant_impl(value, dtype, shape, name, verify_shape, allow_broadcast)
        268   ctx = context.context()
        269   if ctx.executing_eagerly():
    --> 270     t = convert_to_eager_tensor(value, ctx, dtype)
        271     if shape is None:
        272       return t
    
~\AppData\Roaming\Python\Python38\site-packages\tensorflow\python\framework\constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
         94       dtype = dtypes.as_dtype(dtype).as_datatype_enum
         95   ctx.ensure_initialized()
    ---> 96   return ops.EagerTensor(value, ctx.device_name, dtype)
         97 
         98 
    
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).

我的代码:

X = trainingpreds.values
y = traininglabels.values
# define the keras model model = Sequential()
model.add(Dense(20, input_dim=24, activation='relu'))
model.add(Dense(12, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the keras model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, y)

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    假设xy 应该是int 类型,而您在model.fit 处遇到错误,您可以使用

    转换为dtype
       x = tf.cast(trainingpreds.values, tf.int32)
       y = tf.cast(traininglabels, tf.int32)
    

    了解更多请参考this

    【讨论】:

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