ValueError:无法将NumPy数组转换为张量(不支持的对象类型float)

时间:2020-02-18 07:32:54

标签: tensorflow multidimensional-array keras tensor

我在后端Tensorflow 2.0的keras中遇到这一行代码的问题:

loss_out = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,))([y_pred, Y_train, X_train_length, label_length])

Y_train,X_train_length为numpy.ndarrays y_pred和label_length是类'tensorflow.python.framework.ops.Tensor'

2 个答案:

答案 0 :(得分:1)

您可以使用

        tf.convert_to_tensor()

示例

        import tensorflow as tf
        import numpy as np


        loss = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,)) 
                       ([y_pred, Y_train, X_train_length, label_length])
        loss_np = np.asarray(loss, np.float32)

        loss_tf = tf.convert_to_tensor(loss_np, np.float32)

        sess = tf.InteractiveSession()  
        print(loss_tf.eval())

        sess.close()

答案 1 :(得分:0)

您可以创建虚拟输入

# you have defined the rest of your graph somewhere here

Y_train = Input(shape=...)
X_train_length = Input(shape=...)

loss = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,)
              )([y_pred, Y_train, X_train_length, label_length])

# defining the model is slightly different with multiple inputs
training_model = Model(inputs=[image_input, Y_train, X_train_length], outputs=[loss])

当您要训练模型时,您将传递参数x作为长度3的列表,例如

x = [<images - np.ndarray shape (batch, h, w, c)>, <Y_train inputs - np.ndarray>,
     <X_train_length inputs - np.ndarray>]

当然还有y

的哑数值
y = np.zeros((batch, 1))

最后从未比training_model.train_on_batch(x, y)

简单

或者使生成器生成上述形式的xy并使用training_model.fit_generator(data_generator)