jeudi 25 mai 2017

Model weights not changing Keras

I am trying to create neural nets with random weights in keras. I am using set_weights() function of models, to assign random weights. However, model.predict() gives the same output on a certain input regardless of weights. The output differs every time I run the program, but it's same while a program is running. Here is the code:

ConnectFourAI.py:

from keras.models import Sequential
from keras.layers import Dense
from minimax2 import ConnectFour
import numpy as np
from time import sleep
import itertools
import random
import time

def get_model():

    model = Sequential()
    model.add(Dense(630, input_dim=84, kernel_initializer='uniform', activation='relu'))
    model.add(Dense(630,kernel_initializer='normal', activation='relu'))
    model.add(Dense(7, kernel_initializer='normal', activation='relu'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

map = {
    'x':[1,0],
    ' ':[0,0],
    'o':[0,1]
}

model = get_model()

def get_AI_move(grid):
    global model
    inp = np.array(list(itertools.chain.from_iterable([map[t] for t in np.array(grid).reshape(42)]))).reshape(1,84)
    nnout = model.predict(inp)
    # print(list(nnout[0]))
    out = np.argmax(nnout)
    while grid[0][out] != " ":
        out = np.random.randint(7)
    print("out = %d"%out)
    return out

shapes = [(w.shape) for w in model.get_weights()]

print(list(model.get_weights()[0][0][0:5]))
def score_func(x, win):
        if win == "x":
            return 10000
        elif win == " ":
            return 2000
        else:
            return x**2




if __name__=="__main__":

    for i in range(100):
        weights = [np.random.randn(*s) for s in shapes]
        # print(list(weights[0][0][0:5]))
        model.set_weights(weights)
        print(list(model.get_weights()[0][0][0:5]))
        game = ConnectFour()
        game.start_new()
        rounds = game._round
        win = game._winner
        score = score_func(rounds, win)
        print("%dth game scored %.3f"%(i+1,score))

        seed = int(time.time()* 10**6)%(2**32)+1
        np.random.seed(seed)

To recreate this error, you need an extra file. Everything is OK in this file, but the only call to random always gives the same value. Here is the file.




Aucun commentaire:

Enregistrer un commentaire