简体   繁体   中英

Invalid syntax in model architecture in keras.layers

Below is the code of a simple MLP but it's showing invalid syntax at the last line. How is it an error?

#model architecture
model = keras.Sequential([
                          keras.layers.Flatten(input_shape=(32*32),
                          keras.layers.Dense(512, activation='relu'),
                          keras.layers.Dropout(0.4),
                          keras.layers.Dense(120, activation='relu'),
                          keras.layers.Dropout(0.2),
                          keras.layers.Dense(labels, activation='softmax')])

Attached image with error and code fragment. error image

You don't need to pass the shape of input in flatten layer, It will automatically convert the input into a 1d Row.

try:

model = keras.Sequential([
                  keras.layers.Flatten(),
                  keras.layers.Dense(512, activation='relu'),
                  keras.layers.Dropout(0.4),
                  keras.layers.Dense(120, activation='relu'),
                  keras.layers.Dropout(0.2),
                  keras.layers.Dense(2, activation='softmax')])

The SyntaxError message can be quite misleading:

c:\a\bin>py toto.py 
  File "c:\a\bin\toto.py", line 8
keras.layers.Dense(labels, activation='softmax')])
                                                ^
SyntaxError: positional argument follows keyword argument

(that's because the parser itself is somewhat confused) but it does point to a closing square bracket , so this should tell you that you have a mis-matched parenthesis somewhere. One way to get help is to ask your editor to indent the code. Emacs does it like this:

#model architecture
model = keras.Sequential([
keras.layers.Flatten(input_shape=(32*32),
                     keras.layers.Dense(512, activation='relu'),
                     keras.layers.Dropout(0.4),
                     keras.layers.Dense(120, activation='relu'),
                     keras.layers.Dropout(0.2),
                     keras.layers.Dense(labels, activation='softmax')])

It puts the call to keras.layers.Dense at the same level as the input_shape parameter, so clearly we're missing a parenthesis after input_shape=(32*32) . Indenting again confirms that adding a parenthesis here fixes the problem:

#model architecture
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(32*32)),
    keras.layers.Dense(512, activation='relu'),
    keras.layers.Dropout(0.4),
    keras.layers.Dense(120, activation='relu'),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(labels, activation='softmax')])

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