質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

16217閲覧

エラー(setting an array element with a sequence.)について

masa.taka

総合スコア22

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

1グッド

1クリップ

投稿2020/01/13 03:52

編集2020/01/14 00:04

以下のコードを書いておりますが、
最後の「# GBDTモデルのパラメータ探索」以降のコード入力追加で、
以下のようなエラー(setting an array element with a sequence.)が出ます。
(それまでは出ていないことを確認済みです)

修正点等をご存知の方、教えて頂ければ大変嬉しいです。
よろしくお願い致します。

import pandas as pd df=train from sklearn.preprocessing import LabelEncoder le = LabelEncoder() df.keyword = le.fit_transform(df.keyword.fillna("Na")) le = LabelEncoder() df.location = le.fit_transform(df.location.fillna("Na")) from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() df.text = vectorizer.fit_transform(df.text) X_train=df.iloc[:,1:4].values y_train=df.iloc[:,-1].values # GBDTモデルのパラメータ探索 from sklearn.model_selection import GridSearchCV from xgboost import XGBClassifier max_depth=np.arange(5,10,1) colsample_bylevel=np.arange(0.1,0.6,0.1) min_child_weight=[1,2,4,8,16,32] gscv=GridSearchCV(XGBClassifier(), {"max_depth":max_depth, "colsample_bylevel":colsample_bylevel, "min_child_weight":min_child_weight}, scoring="accuracy",cv=3 ) gscv.fit(X_train,y_train) gscv.best_params_
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-10-e418a6eefe52> in <module> 14 scoring="accuracy",cv=3 15 ) ---> 16 gscv.fit(X_train,y_train) 17 gscv.best_params_ /opt/conda/lib/python3.6/site-packages/sklearn/model_selection/_search.py in fit(self, X, y, groups, **fit_params) 686 return results 687 --> 688 self._run_search(evaluate_candidates) 689 690 # For multi-metric evaluation, store the best_index_, best_params_ and /opt/conda/lib/python3.6/site-packages/sklearn/model_selection/_search.py in _run_search(self, evaluate_candidates) 1147 def _run_search(self, evaluate_candidates): 1148 """Search all candidates in param_grid""" -> 1149 evaluate_candidates(ParameterGrid(self.param_grid)) 1150 1151 /opt/conda/lib/python3.6/site-packages/sklearn/model_selection/_search.py in evaluate_candidates(candidate_params) 665 for parameters, (train, test) 666 in product(candidate_params, --> 667 cv.split(X, y, groups))) 668 669 if len(out) < 1: /opt/conda/lib/python3.6/site-packages/joblib/parallel.py in __call__(self, iterable) 1001 # remaining jobs. 1002 self._iterating = False -> 1003 if self.dispatch_one_batch(iterator): 1004 self._iterating = self._original_iterator is not None 1005 /opt/conda/lib/python3.6/site-packages/joblib/parallel.py in dispatch_one_batch(self, iterator) 832 return False 833 else: --> 834 self._dispatch(tasks) 835 return True 836 /opt/conda/lib/python3.6/site-packages/joblib/parallel.py in _dispatch(self, batch) 751 with self._lock: 752 job_idx = len(self._jobs) --> 753 job = self._backend.apply_async(batch, callback=cb) 754 # A job can complete so quickly than its callback is 755 # called before we get here, causing self._jobs to /opt/conda/lib/python3.6/site-packages/joblib/_parallel_backends.py in apply_async(self, func, callback) 199 def apply_async(self, func, callback=None): 200 """Schedule a func to be run""" --> 201 result = ImmediateResult(func) 202 if callback: 203 callback(result) /opt/conda/lib/python3.6/site-packages/joblib/_parallel_backends.py in __init__(self, batch) 580 # Don't delay the application, to avoid keeping the input 581 # arguments in memory --> 582 self.results = batch() 583 584 def get(self): /opt/conda/lib/python3.6/site-packages/joblib/parallel.py in __call__(self) 254 with parallel_backend(self._backend, n_jobs=self._n_jobs): 255 return [func(*args, **kwargs) --> 256 for func, args, kwargs in self.items] 257 258 def __len__(self): /opt/conda/lib/python3.6/site-packages/joblib/parallel.py in <listcomp>(.0) 254 with parallel_backend(self._backend, n_jobs=self._n_jobs): 255 return [func(*args, **kwargs) --> 256 for func, args, kwargs in self.items] 257 258 def __len__(self): /opt/conda/lib/python3.6/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) 514 estimator.fit(X_train, **fit_params) 515 else: --> 516 estimator.fit(X_train, y_train, **fit_params) 517 518 except Exception as e: /opt/conda/lib/python3.6/site-packages/xgboost/sklearn.py in fit(self, X, y, sample_weight, eval_set, eval_metric, early_stopping_rounds, verbose, xgb_model, sample_weight_eval_set, callbacks) 724 else: 725 train_dmatrix = DMatrix(X, label=training_labels, --> 726 missing=self.missing, nthread=self.n_jobs) 727 728 self._Booster = train(xgb_options, train_dmatrix, self.get_num_boosting_rounds(), /opt/conda/lib/python3.6/site-packages/xgboost/core.py in __init__(self, data, label, missing, weight, silent, feature_names, feature_types, nthread) 402 self._init_from_csc(data) 403 elif isinstance(data, np.ndarray): --> 404 self._init_from_npy2d(data, missing, nthread) 405 elif isinstance(data, DataTable): 406 self._init_from_dt(data, nthread) /opt/conda/lib/python3.6/site-packages/xgboost/core.py in _init_from_npy2d(self, mat, missing, nthread) 476 # we try to avoid data copies if possible (reshape returns a view when possible 477 # and we explicitly tell np.array to try and avoid copying) --> 478 data = np.array(mat.reshape(mat.size), copy=False, dtype=np.float32) 479 handle = ctypes.c_void_p() 480 missing = missing if missing is not None else np.nan ValueError: setting an array element with a sequence.
DrqYuto👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

X_trainとy_trainの数が異なっていませんか?

投稿2020/01/13 10:24

meg_

総合スコア10577

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

masa.taka

2020/01/13 10:42

X_train.shape,y_train.shape を確認しましたところ、 ((7613, 3), (7613,)) となります。 y_train.shapeの1は省略されているので、問題ない認識です。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問