设置keras图层的权重

时间:2020-05-03 00:57:56

标签: python keras genetic-algorithm

我正在尝试使用遗传算法和Keras制作Snake游戏。

我现在的问题是:

我创建了每个蛇具有X个基因的初始种群,其中X为NUMBER_WEIGHTS:

INPUT = 24
NEURONS_HIDDEN_1 = 16
NEURONS_HIDDEN_2 = 16
OUTPUT = 3
NUMBER_WEIGHTS = INPUT * NEURONS_HIDDEN_1 + NEURONS_HIDDEN_1 * NEURONS_HIDDEN_2 + NEURONS_HIDDEN_2 * OUTPUT

然后我像这样创建初始人口:

population = numpy.random.choice(numpy.arange(-1, 1, step=0.01), size=(config.NUMBER_OF_POPULATION, config.NUMBER_WEIGHTS))

我有一个for周期,可以为种群中的每条蛇启动pygame脚本,在pygame脚本中,我具有Keras NN,但是我想将自己生成的权重传递给NN。

我的NN现在是这样的:

from keras.layers import Dense, Activation
from keras.models import Sequential
from keras.optimizers import SGD

from utils import config
def neural_net(weights):
    model = Sequential()

    model.add(Dense(config.INPUT, input_shape=(config.INPUT,)))
    model.add(Activation('relu'))
    # create the dense input layer
    # model.add(Dense(config.INPUT, activation=keras.activations.relu(4,), input_dim=4))
    # model.add(Activation('sigmoid'))

    # create first hidden layer
    model.add(Dense(config.NEURONS_HIDDEN_1, input_shape=(config.INPUT,)))
    model.add(Activation('relu'))
    # create second hidden layer
    model.add(Dense(config.NEURONS_HIDDEN_2, input_shape=(config.NEURONS_HIDDEN_1,)))
    model.add(Activation('relu'))
    # create output layer
    model.add(Dense(config.OUTPUT, input_shape=(config.NEURONS_HIDDEN_2,)))
    model.add(Activation('softmax'))

    print(weights.shape[0])
    model.set_weights(weights)

    # create the optimizer (Stochastic Gradient Descent)
    sgd = SGD(lr=0.01, decay=0.0, momentum=0.0, nesterov=False)
    # Use mean squared error loss and SGD as optimizer
    model.compile(loss='mse', optimizer=sgd)

    return model

但是model.set_weights(weights)返回此异常:

File "neural_network.py", line 28, in neural_net
    model.set_weights(weights)
  File "C:\Users\Davide\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\engine\network.py", line 527, in set_weights
    K.batch_set_value(tuples)
  File "C:\Users\Davide\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\backend\tensorflow_backend.py", line 2960, in batch_set_value
    tf_keras_backend.batch_set_value(tuples)
  File "C:\Users\Davide\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\backend.py", line 3323, in batch_set_value
    x.assign(np.asarray(value, dtype=dtype(x)))
  File "C:\Users\Davide\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\ops\resource_variable_ops.py", line 819, in assign
    self._shape.assert_is_compatible_with(value_tensor.shape)
  File "C:\Users\Davide\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\tensor_shape.py", line 1110, in assert_is_compatible_with
    raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (24, 24) and () are incompatible

Process finished with exit code 1

我们在隐藏的第1层上有24个输入* 16个神经元,然后在隐藏的第2层上有16个神经元* 16个神经元,最后在第2层的第16个神经元隐藏了* 3输入= 24 * 16 + 16 * 16 + 16 * 3 = 688

还有

print(weights.shape[0])

是688。那为什么我不能设置正确的权重?

第一次使用AI进行项目,所以我可能完全误解了它的工作原理

1 个答案:

答案 0 :(得分:2)

我确定模型的重量和您提供的重量存在形状不匹配的情况。您需要提供与每个图层相对应的权重,如下例所示。

from bs4 import BeautifulSoup as bs
import requests

r = requests.get(url='https://ca.indeed.com/cmp/Abb/jobs')
soup = bs(r.text, 'html.parser')
jobkeys = []
jobs = soup.findAll("li", {"class": "cmp-JobListItem"})
for job in jobs:
    s = job.attrs.get('data-tn-entityid')
    jobkey = s[s.find(',')+1:s.rfind(',')]
    jobkeys.append(jobkey)

print(len(jobkeys))

希望此示例将为您解决问题提供一些见识。
完整的代码是here供您参考。