AmberL0uise
AmberL0uise

Reputation: 35

How to get a single value from model.predict() results

I am trying to use a neural network to predict actions for a car simulator game that runs in another file. I need to get the value predicted for an action to pass into the game but i am struggling to do this. After calling model.predict i have attempted to access the value as if from an array but this returns an out of bounds error.

I am fairly new to python in general, never mind using keras, but the idea i had is that the neural network would be trained on some data (saved in a CSV file) gathered by someone else playing the game. Then when it came time for the neural network to play, I would be able to pass in the game values at each frame to generate a predicted action. I think i have done that but am unable to get a predicted action. Here is neural network;

  def build_nn(self):
    model = Sequential()
    model.add(Dense(12, input_dim=8, activation='relu')) 
    model.add(Dense(8, activation='relu'))
    model.add(Dense(1, activation='linear'))
    model.compile(loss='mean_squared_error', optimizer=Adam(lr=self.learning_rate))

    return model

And my code for predicting the action (stateVector wasnt accepted as is, so I had to get the values from it)

 def action(self, stateVector):
    a_action = stateVector['lastAction']
    currentLane = stateVector['currentLane']
    offRoad = stateVector['offRoad']
    collision = stateVector['collision']
    lane1 = stateVector['lane1Distance']
    lane2 = stateVector['lane2Distance']
    lane3 = stateVector['lane3Distance']
    a = [currentLane, offRoad, collision, lane1, lane2, lane3, reward, a_action]   

    act_value = self.model.predict(a)
    act = act_values[a_action]

    return act 

Upvotes: 0

Views: 5888

Answers (1)

KonstantinosKokos
KonstantinosKokos

Reputation: 3453

You're feeding your network a list of 8 elements, when it expected an iterable of 8-dimensional samples. Practically:

>>> a = [currentLane, offRoad, collision, lane1, lane2, lane3, reward, a_action]
>>> a = np.array(a) # convert to a numpy array
>>> a = np.expand_dims(a, 0) # change shape from (8,) to (1,8)
>>> model.predict(a) # voila!

Upvotes: 2

Related Questions