以下のようなコードで回帰のグリッドサーチを実行するとエラーが発生します。
InvalidArgumentError: Received a label value of 78 which is outside the valid range of [0, 1). Label values: 8 78
[[{{node loss/dense_3_loss/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]]
お詳しい方、ご指導お願いいたします。
def create_model(optimizer='rmsprop', init='glorot_uniform'): model = keras.models.Sequential() model.add(Dense(units=64,input_dim=13)) model.add(Activation('relu')) model.add(Dropout(0.2)) model.add(Dense(units=32)) model.add(Activation('relu')) #model.add(Dropout(0.2)) model.add(Dense(units=1)) model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy']) return model
# グリッドサーチ(実行) from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV # KerasClassifier/KerasRegressor can be used as same as scikit_learn estimator. model = KerasClassifier(build_fn=create_model, verbose=0) # Grid Search parameters (epochs, batch size and optimizer) optimizers = ['adam']# optimizers = ['rmsprop', 'adam', 'sgd', 'adagrad'] init = ['normal']# init = ['glorot_uniform', 'normal', 'uniform'] epochs = [100,200] batches = [2,4] param_grid = dict(optimizer=optimizers, epochs=epochs, batch_size=batches, init=init) grid = GridSearchCV(estimator=model, param_grid=param_grid) grid_result = grid.fit(x_train_std, y_train) # summarize results # print("Best parameter set: {}".format(grid_result.best_params_)) print(grid.best_params_) print(grid.best_score_)
以下、エラーメッセージ
--------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call last) <ipython-input-9-5288607cc299> in <module> 13 init=init) 14 grid = GridSearchCV(estimator=model, param_grid=param_grid) ---> 15 grid_result = grid.fit(x_train_std, y_train) 16 17 # summarize results C:\python\anaconda\pgm\lib\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params) 685 return results 686 --> 687 self._run_search(evaluate_candidates) 688 689 # For multi-metric evaluation, store the best_index_, best_params_ and C:\python\anaconda\pgm\lib\site-packages\sklearn\model_selection\_search.py in _run_search(self, evaluate_candidates) 1146 def _run_search(self, evaluate_candidates): 1147 """Search all candidates in param_grid""" -> 1148 evaluate_candidates(ParameterGrid(self.param_grid)) 1149 1150 C:\python\anaconda\pgm\lib\site-packages\sklearn\model_selection\_search.py in evaluate_candidates(candidate_params) 664 for parameters, (train, test) 665 in product(candidate_params, --> 666 cv.split(X, y, groups))) 667 668 if len(out) < 1: C:\python\anaconda\pgm\lib\site-packages\joblib\parallel.py in __call__(self, iterable) 919 # remaining jobs. 920 self._iterating = False --> 921 if self.dispatch_one_batch(iterator): 922 self._iterating = self._original_iterator is not None 923 C:\python\anaconda\pgm\lib\site-packages\joblib\parallel.py in dispatch_one_batch(self, iterator) 757 return False 758 else: --> 759 self._dispatch(tasks) 760 return True 761 C:\python\anaconda\pgm\lib\site-packages\joblib\parallel.py in _dispatch(self, batch) 714 with self._lock: 715 job_idx = len(self._jobs) --> 716 job = self._backend.apply_async(batch, callback=cb) 717 # A job can complete so quickly than its callback is 718 # called before we get here, causing self._jobs to C:\python\anaconda\pgm\lib\site-packages\joblib\_parallel_backends.py in apply_async(self, func, callback) 180 def apply_async(self, func, callback=None): 181 """Schedule a func to be run""" --> 182 result = ImmediateResult(func) 183 if callback: 184 callback(result) C:\python\anaconda\pgm\lib\site-packages\joblib\_parallel_backends.py in __init__(self, batch) 547 # Don't delay the application, to avoid keeping the input 548 # arguments in memory --> 549 self.results = batch() 550 551 def get(self): C:\python\anaconda\pgm\lib\site-packages\joblib\parallel.py in __call__(self) 223 with parallel_backend(self._backend, n_jobs=self._n_jobs): 224 return [func(*args, **kwargs) --> 225 for func, args, kwargs in self.items] 226 227 def __len__(self): C:\python\anaconda\pgm\lib\site-packages\joblib\parallel.py in <listcomp>(.0) 223 with parallel_backend(self._backend, n_jobs=self._n_jobs): 224 return [func(*args, **kwargs) --> 225 for func, args, kwargs in self.items] 226 227 def __len__(self): C:\python\anaconda\pgm\lib\site-packages\sklearn\model_selection\_validation.py in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters, return_n_test_samples, return_times, return_estimator, error_score) 512 estimator.fit(X_train, **fit_params) 513 else: --> 514 estimator.fit(X_train, y_train, **fit_params) 515 516 except Exception as e: C:\python\anaconda\pgm\lib\site-packages\keras\wrappers\scikit_learn.py in fit(self, x, y, sample_weight, **kwargs) 208 if sample_weight is not None: 209 kwargs['sample_weight'] = sample_weight --> 210 return super(KerasClassifier, self).fit(x, y, **kwargs) 211 212 def predict(self, x, **kwargs): C:\python\anaconda\pgm\lib\site-packages\keras\wrappers\scikit_learn.py in fit(self, x, y, **kwargs) 150 fit_args.update(kwargs) 151 --> 152 history = self.model.fit(x, y, **fit_args) 153 154 return history C:\python\anaconda\pgm\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 1037 initial_epoch=initial_epoch, 1038 steps_per_epoch=steps_per_epoch, -> 1039 validation_steps=validation_steps) 1040 1041 def evaluate(self, x=None, y=None, C:\python\anaconda\pgm\lib\site-packages\keras\engine\training_arrays.py in fit_loop(model, f, ins, out_labels, batch_size, epochs, verbose, callbacks, val_f, val_ins, shuffle, callback_metrics, initial_epoch, steps_per_epoch, validation_steps) 197 ins_batch[i] = ins_batch[i].toarray() 198 --> 199 outs = f(ins_batch) 200 outs = to_list(outs) 201 for l, o in zip(out_labels, outs): C:\python\anaconda\pgm\lib\site-packages\keras\backend\tensorflow_backend.py in __call__(self, inputs) 2713 return self._legacy_call(inputs) 2714 -> 2715 return self._call(inputs) 2716 else: 2717 if py_any(is_tensor(x) for x in inputs): C:\python\anaconda\pgm\lib\site-packages\keras\backend\tensorflow_backend.py in _call(self, inputs) 2673 fetched = self._callable_fn(*array_vals, run_metadata=self.run_metadata) 2674 else: -> 2675 fetched = self._callable_fn(*array_vals) 2676 return fetched[:len(self.outputs)] 2677 C:\python\anaconda\pgm\lib\site-packages\tensorflow\python\client\session.py in __call__(self, *args, **kwargs) 1456 ret = tf_session.TF_SessionRunCallable(self._session._session, 1457 self._handle, args, -> 1458 run_metadata_ptr) 1459 if run_metadata: 1460 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) InvalidArgumentError: Received a label value of 78 which is outside the valid range of [0, 1). Label values: 8 78 [[{{node loss/dense_3_loss/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]]
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/12/03 05:04
2019/12/03 05:26