我正在使用scikit学习的KerasRegressor包装器和Functional API来创建具有多个输出的模型。我的模型有两个分支:一个预测1个值,另一个同时预测3个值。使用的keras版本是可用的最新版本(win64上的2.3.1)
我遇到的问题如下:我的模型可以通过管道进行训练,我可以得到分数,但我无法预测
# To fit the pipeline, this line runs successfully
pipeline.fit(X_train, [y_train_branch_1, y_train_branch_2])`
# To get the score, it works as well
pipeline.score(X_test, [y_test_branch_1, y_test_branch_2])
# To make predictions however, it doesn't
pipeline.predict(X_test)
最后一行不起作用:
ValueError: could not broadcast input array from shape (11963,3) into shape (11963)
发生在这里:
~\Anaconda3\envs\blades\lib\site-packages\keras\wrappers\scikit_learn.py in predict(self, x, **kwargs)
320 """
321 kwargs = self.filter_sk_params(Sequential.predict, kwargs)
--> 322 preds = np.array(self.model.predict(x, **kwargs))
323 if preds.shape[-1] == 1:
324 return np.squeeze(preds, axis=-1)
输入形状为:
使用.predict
时,预测结果(分为两部分)似乎没有正确合并。以前有人遇到过这个问题吗?将模型中的两个输出直接连接起来可能是一种解决方法,但我还是想解决这个问题
谢谢你的帮助
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from keras.wrappers.scikit_learn import KerasRegressor
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras import Input, Model
from keras.layers import Dense, Activation, Concatenate
from keras.optimizers import Adam
def build_branch_1(inputs):
x = Dense(12)(inputs)
x = Activation('elu')(x)
x = Dense(12)(x)
x = Activation('elu')(x)
a = Dense(12)(x)
a = Activation('elu')(a)
a = Dense(1)(a)
b = Dense(12)(x)
b = Activation('elu')(b)
b = Dense(1)(b)
c = Dense(12)(x)
c = Activation('elu')(c)
c = Dense(1)(c)
x = Concatenate(name='branch_1')([a, b, c])
return x
def build_branch_2(inputs):
x = Dense(12)(inputs)
x = Activation('elu')(x)
x = Dense(12)(x)
x = Activation('elu')(x)
x = Dense(12)(x)
x = Activation('elu')(x)
x = Dense(1, name='branch_2')(x)
return x
def build_model():
inputs = Input(shape=(4,))
branch_1 = build_branch_1(inputs)
branch_2 = build_branch_2(inputs)
model = Model(inputs=inputs, outputs=[branch_1, branch_2])
model.compile(optimizer=Adam(), loss='mse')
return model
pipeline = Pipeline([
('stdscaling', StandardScaler()),
('model', KerasRegressor(
build_fn=build_model,
batch_size=128,
epochs=10,
verbose=2,
validation_split=.2,
callbacks=[
EarlyStopping(monitor='loss', min_delta=.01, patience=250,
restore_best_weights=True),
ModelCheckpoint(filepath='model/model_' + model_name + '.hdf5',
monitor='val_loss',
save_best_only=True,
save_weights_only=False)
]
))
])
目前没有回答
相关问题 更多 >
编程相关推荐