【问题标题】:How to set the data dimension for GridSearchCV如何为 GridSearchCV 设置数据维度
【发布时间】:2022-01-17 13:06:05
【问题描述】:
def rnn_model(self,activation="relu"):
    in_out_neurons = 50
    n_hidden = 512
    model = Sequential()
    model.add(LSTM(n_hidden, batch_input_shape=(None, self.seq_len, in_out_neurons), return_sequences=True))
    model.add(Dense(in_out_neurons, activation=activation))
    optimizer = Adam(learning_rate=0.001)
    model.compile(loss="mean_squared_error", optimizer=optimizer)
    model.summary()
    return model

# then try to fit the model
final_x = np.zeros((319083, 2, 50))
final_y = np.zeros((319083, 1, 50))

# this works.

model = self.rnn_model()
model.fit(         
    final_x,final_y,
    batch_size=400,
    epochs=10,
    validation_split=0.1
)

#However, when I trid to use hyperparameter sarch, this shows the error `ValueError: Invalid shape for y: (319083, 1, 50)`

activation = ["relu","sigmoid"]
model = KerasClassifier(build_fn=self.rnn_model,verbose=0)
param_grid = dict(activation=activation)
grid = GridSearchCV(estimator=model,param_grid=param_grid)
grid_result= grid.fit(final_x,final_y)

使用GridSearchCV时尺寸如何变化

【问题讨论】:

  • final_y 的形状是什么?
  • 打错字了final_x -> final_y
  • 尝试在 LSTM 中使用 return_sequences=False 并将您的 final_y 重塑为 (319083, 50)
  • @Marco 但他不是说 final_x 等于 final_y 吗?
  • final_x in (n_sample, 2, n_feat) while final_y is (n_sample, 1, n_feat)... np.zeros 仅作为示例

标签: python tensorflow keras


【解决方案1】:

您应该使用KerasRegressor,因为您的模型不是那种意义上的分类器:

import tensorflow as tf
import numpy as np

from sklearn.model_selection import GridSearchCV
from keras.wrappers.scikit_learn import KerasRegressor

def rnn_model(activation="relu"):
    in_out_neurons = 50
    n_hidden = 512
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.LSTM(n_hidden, batch_input_shape=(None, 2, in_out_neurons), return_sequences=True))
    model.add(tf.keras.layers.Dense(in_out_neurons, activation=activation))
    optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
    model.compile(loss="mean_squared_error", optimizer=optimizer)
    model.summary()
    return model

final_x = np.zeros((319083, 2, 50))
final_y = np.zeros((319083, 2, 50))

model = rnn_model()
activation = ["relu","sigmoid"]
model = KerasRegressor(build_fn=rnn_model,verbose=0)
param_grid = dict(activation=activation)
grid = GridSearchCV(estimator=model, param_grid=param_grid)
grid_result= grid.fit(final_x,final_y)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) # run with a way smaller dataset
Best: 0.000000 using {'activation': 'relu'}

【讨论】:

  • 非常感谢,KerasClassifier 用于分类,KerasRegressor 用于回归命名。它对我有用,对制作超参数非常有用
猜你喜欢
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 2021-10-05
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
相关资源
最近更新 更多