简体   繁体   中英

How to define model input and outputs in tensorflow keras?

I'm trying to create a model what should have nx8x8 input and 8x8 output or like below 64 units output, but don't know how to create it to make it work. I'm trying with the below code:

model = tf.keras.Sequential()

input = tf.keras.layers.Flatten(input_shape=(8,8), name='input')
model.add(input)

middle = tf.keras.layers.Dense(256, activation='sigmoid',  name='a')
model.add(middle)

output = tf.keras.layers.Dense(64, activation='softmax',  name='b')
model.add(output)
print(model.input_shape)

model.compile(optimizer='adam',
            loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
            metrics=['accuracy'])

train_input = np.array(
    [
        [0, 1, 0, 1, 0, 1, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0],
        [0, 1, 0, 1, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 0, 0, 0, 3],
        [3, 0, 3, 0, 3, 0, 0, 0],
        [0, 3, 0, 3, 0, 3, 0, 3],
        [3, 0, 3, 0, 3, 0, 3, 0]
    ],
    [
        [0, 1, 0, 1, 0, 1, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0],
        [0, 0, 0, 1, 0, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 3],
        [3, 0, 3, 0, 3, 0, 0, 0],
        [0, 3, 0, 3, 0, 3, 0, 3],
        [3, 0, 3, 0, 3, 0, 3, 0]
    ]
)
train_output = np.array([
    0, 1, 0, 1, 0, 1, 0, 1,
    1, 0, 1, 0, 1, 0, 1, 0,
    0, 0, 0, 1, 0, 1, 0, 1,
    1, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 3,
    3, 0, 3, 0, 3, 0, 0, 0,
    0, 3, 0, 3, 0, 3, 0, 3,
    3, 0, 3, 0, 3, 0, 3, 0,
])
model.fit(train_input, train_output, epochs=10)

What I'm doing bad? How to define input and outputs shape?

You need to add one more instance to your train_output . You have two samples on your train_input but only one label. You need the same amount of labels as instances of input. This solves your cardinality issue.

However your data is formatted in a very strange way, I'm pretty sure you will have more issues when training. You're doing a classification task but your labels are not enconded as they should. You should enconde your labels into classes (eg 0,1,2) and then your model will only output a classification.

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