Keras形状(无,3)和(无,4,3)不兼容

whitzsjs  于 2023-02-23  发布在  其他
关注(0)|答案(1)|浏览(171)
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.utils import to_categorical
import numpy as np
x=[[[13.0, 10.0], [12.0, 28.0], [10.0, 14.0], [6.0, 53.0]], [[12.0, 53.0], [13.0, 53.0], [10.0, 53.0], [3.0, 31.44]], [[15.0, 28.0], [16.0, 28.0], [13.0, 28.0], [6.0, 28.0]]]
y=[0, 1, 2]
x=np.array(x).reshape(-1,4,2)
y=to_categorical(np.array(y),num_classes=3)
model = Sequential()
model.add(Dense(16, activation='relu',input_shape=(4,2)))
model.add(Dropout(0.5))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

model.fit(x, y, epochs=20)

获取错误:值错误:形状(无,3)和(无,4,3)不兼容
我已经尝试了所有方法,我希望将4个元素(每个元素中有2个值)馈送到输入,并将class 01或2馈送到输出

fhg3lkii

fhg3lkii1#

问题出在模型的末尾,当你添加输出层时,它的形状是(None,3),而其他层仍然是(None,4,3)。你所需要做的就是添加一个Flatten()层,它应该可以正常工作!

import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.utils import to_categorical
import numpy as np
x=[[[13.0, 10.0], [12.0, 28.0], [10.0, 14.0], [6.0, 53.0]], [[12.0, 53.0], [13.0, 53.0], [10.0, 53.0], [3.0, 31.44]], [[15.0, 28.0], [16.0, 28.0], [13.0, 28.0], [6.0, 28.0]]]
y=[0, 1, 2]
x=np.array(x).reshape(-1,4,2)
y=to_categorical(np.array(y),num_classes=3)
model = Sequential()
model.add(Dense(16, activation='relu', input_shape=(4,2)))
model.add(Dropout(0.5))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

model.fit(x, y, epochs=20)

相关问题