首页 > 解决方案 > 无法将 numpy 数组转换为张量

问题描述

我尝试在 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)

标签: pythonnumpytensorflow

解决方案


假设x andy应该是类型int并且您在 处遇到错误model.fit,您可以转换为dtypeusing

   x = tf.cast(trainingpreds.values, tf.int32)
   y = tf.cast(traininglabels, tf.int32)

要了解更多信息,请参阅


推荐阅读