我正在尝试在keras中创建具有随机权重的神经网络。我正在使用模型的set_weights()函数来分配随机权重。但是,无论权重如何,model.predict()都会在某个输入上提供相同的输出。每次运行程序时输出都不同,但在程序运行时它是相同的。这是代码:
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)
要重新创建此错误,您需要一个额外的文件。在这个文件中一切都很好,但对random的唯一调用总是给出相同的值。这是file。
答案 0 :(得分:0)
我不知道到底出了什么问题,但我想出了一个解决方法。显然,随机模块中存在一些问题,因为当从2个不同的文件调用随机模块时会发生这种行为。所以我使用了一个文件而不是两个文件,并得到了我期望的结果。