简体   繁体   中英

How to set custom weights on a Keras Sequential Model?

So i want to set weights on my own for a Sequential keras model. To get the number of weights, i multiplied adjacent layer's node counts by each other.

here is my code:

model.add(Dense(units=3, activation='relu', input_dim=4))
model.add(Dense(3, activation='relu'))
model.add(Dense(5, activation='softmax'))

weights_count = []

weights_count.append(4*3)
weights_count.append(3*3)
weights_count.append(3*5)

weights = []

for count in weights_count:
    curr_weights = []
    for i in range(count):
        curr_weights.append(random.random())
    weights.append(curr_weights)
model.set_weights(weights)

This code generates this error:

ValueError: Shapes must be equal rank, but are 2 and 1 for 'Assign' (op: 'Assign') with input shapes: [4,3], [12].

why is this so?

The shapes are not aligned.

You might be better off doing something like this:

import numpy as np

# create weights with the right shape, e.g.
weights = [np.random.rand(*w.shape) for w in model.get_weights()]

# update
model.set_weights(weights)

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM