【问题标题】:How to put multidimensional array input in tensorflow?如何将多维数组输入放入张量流中?
【发布时间】:2021-10-17 00:38:48
【问题描述】:

关注this tutorial

我在 Tensorflow 中有这个功能和标签:

>>> play_features.head()
  enemy_class player_class                                player_cards                                 enemy_cards previous_player_placed_card
0   [0, 0, 0]    [0, 0, 0]  [0, 6, 12, 17, 0, 6, 12, 17, 0, 6, 12, 17]  [0, 6, 12, 17, 0, 6, 12, 17, 0, 6, 12, 17]                [12, 12, 12]
1   [0, 0, 0]    [0, 0, 0]  [0, 6, 12, 17, 0, 6, 12, 17, 0, 6, 12, 17]  [0, 6, 12, 17, 0, 6, 12, 17, 0, 6, 12, 17]                        [-1]
>>> play_label.head()
0    [6, 6, 6]
1          [6]
play_model = tf.keras.Sequential([layers.Dense(64), layers.Dense(1)])
play_model.compile(loss = tf.losses.MeanSquaredError(), optimizer = tf.optimizers.Adam())
play_model.fit(play_features.to_numpy(), play_label.to_numpy(), epochs=10)

鉴于我有这个错误,我怎么能把这个模型融入到 Tensorflow 中?

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

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    试试这个:

    import numpy as np
        
    play_model = tf.keras.Sequential([layers.Dense(64), layers.Dense(1)])
    play_model.compile(loss = tf.losses.MeanSquaredError(), optimizer = tf.optimizers.Adam())
    play_model.fit(np.array(play_features,dtype =np.ndarray), np.array(play_label,dtype =np.ndarray), epochs=10)
    

    【讨论】:

    • 可悲的是,它仍然返回错误Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).
    【解决方案2】:

    我想我现在明白了。

    我应该将每个列表解析为类似this 的数据框列。所以对于这个问题,一个例子是:

    def generate_expanded_dataframe(expand_df, count, prefix):
        column_names = ['{}{}'.format(prefix, str(x + 1)) for x in range(0, count)]
        dataframe = pd.DataFrame()
        dataframe[column_names] = pd.DataFrame(expand_df.to_list())
        return dataframe
    
    play_features_enemy_class = generate_expanded_dataframe(play_features['enemy_class'], 3, 'class')
    
    >>> play_features_enemy_class.head()
       class1  class2  class3
    0       0       0       0
    1       0       0       0
    

    然后每个扩展列表都将像this 一样进行拟合。

    input_enemy_class = keras.layers.Input(shape=(3,))
    ... # One for each expanded list
    merged = keras.layers.Concatenate(axis=1)([input_enemy_class , ...])
    dense = keras.layers.Dense(2, input_dim=2, activation=keras.activations.sigmoid, use_bias=True)(merged)
    output = keras.layers.Dense(1, activation=keras.activations.relu, use_bias=True)(dense)
    model = keras.models.Model(inputs=[input_enemy_class, ...], output=output)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 2021-10-26
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      相关资源
      最近更新 更多