Home > Net >  How to put multidimensional array input in tensorflow?
How to put multidimensional array input in tensorflow?

Time:10-18

Following this tutorial:

I have this feature and label in 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)

How could I fit this model into Tensorflow given that I have this error?

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

CodePudding user response:

Try this :

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)

CodePudding user response:

I think I get it now.

I should have parsed each list as a dataframe column something like this. So for this question, an example would be:

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

Then each of the expanded list will be fitted just like 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)
  • Related