【问题标题】:ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型浮点数)
【发布时间】:2020-02-18 07:32:54
【问题描述】:

我在使用后端 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'

【问题讨论】:

    标签: tensorflow multidimensional-array keras tensor


    【解决方案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()
    

    【讨论】:

    • 这一行没有被执行。 Geeting value error: not able to convert numpy array to tensor loss = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,)) ([y_pred, Y_train, X_train_length, label_length])
    • @neena 是的,那一行是什么?你能详细说明你的问题吗?
    • 这一行 [loss = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,)) ([y_pred, Y_train, X_train_length, label_length])] 没有被执行。获取值错误:无法将 numpy 数组转换为张量
    • 其实我只是写了 loss not (loss_out) 所以根据你在代码中写的来改变它。
    • 我试过这个:loss_out = Lambda(function=ctc_lambda_func, name='ctc', output_shape=(1,))([tf.convert_to_tensor(y_pred, np.float32), tf.convert_to_tensor( Y_train, np.float32), tf.convert_to_tensor(X_train_length, np.float32), tf.convert_to_tensor(label_length, np.float32)]) 现在出现错误:ValueError: setting an array element with a sequence。
    【解决方案2】:

    您可以创建虚拟输入

    # 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)

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 2020-05-04
      • 2020-10-02
      • 1970-01-01
      • 2020-07-05
      • 2020-09-09
      • 2021-02-23
      • 2020-05-10
      相关资源
      最近更新 更多