質問するログイン新規登録
機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

Q&A

解決済

1回答

665閲覧

要素数がなぜか減っている

Kojki

総合スコア1

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

0グッド

0クリップ

投稿2025/07/29 06:07

編集2025/08/02 10:16

0

0

実現したいこと

要因がどこにあるのかを把握したい。

発生している問題・分からないこと

表を作る際にいつの間にか項目ごとの要素数が減っていることに気づいたが、原因がわからない。

エラーメッセージ

error

1--------------------------------------------------------------------------- 2ValueError Traceback (most recent call last) 3Cell In[14], line 3 4 1 x = train_val3.loc[ : ,['duration', 'housing_yes', 'campaign', 'contact_sending _document']] 5 2 t = train_val3[['y']] 6----> 3 s1, s2 = learn(x, t) 7 4 print(s1, s2) 8 9Cell In[9], line 12, in learn(x, t) 10 9 sc_y_train = sc_model_y.transform(y_train) 11 11 model = LinearRegression() 12---> 12 model.fit(sc_x_train, sc_y_train) 13 13 sc_x_val = sc_model_x.transform(x_val) 14 14 sc_y_val = sc_model_y.transform(y_val) 15 16File ~\anaconda3\Lib\site-packages\sklearn\base.py:1389, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs) 17 1382 estimator._validate_params() 18 1384 with config_context( 19 1385 skip_parameter_validation=( 20 1386 prefer_skip_nested_validation or global_skip_validation 21 1387 ) 22 1388 ): 23-> 1389 return fit_method(estimator, *args, **kwargs) 24 25File ~\anaconda3\Lib\site-packages\sklearn\linear_model\_base.py:601, in LinearRegression.fit(self, X, y, sample_weight) 26 597 n_jobs_ = self.n_jobs 27 599 accept_sparse = False if self.positive else ["csr", "csc", "coo"] 28--> 601 X, y = validate_data( 29 602 self, 30 603 X, 31 604 y, 32 605 accept_sparse=accept_sparse, 33 606 y_numeric=True, 34 607 multi_output=True, 35 608 force_writeable=True, 36 609 ) 37 611 has_sw = sample_weight is not None 38 612 if has_sw: 39 40File ~\anaconda3\Lib\site-packages\sklearn\utils\validation.py:2961, in validate_data(_estimator, X, y, reset, validate_separately, skip_check_array, **check_params) 41 2959 y = check_array(y, input_name="y", **check_y_params) 42 2960 else: 43-> 2961 X, y = check_X_y(X, y, **check_params) 44 2962 out = X, y 45 2964 if not no_val_X and check_params.get("ensure_2d", True): 46 47File ~\anaconda3\Lib\site-packages\sklearn\utils\validation.py:1389, in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, force_all_finite, ensure_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator) 48 1370 X = check_array( 49 1371 X, 50 1372 accept_sparse=accept_sparse, 51 (...) 52 1384 input_name="X", 53 1385 ) 54 1387 y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric, estimator=estimator) 55-> 1389 check_consistent_length(X, y) 56 1391 return X, y 57 58File ~\anaconda3\Lib\site-packages\sklearn\utils\validation.py:475, in check_consistent_length(*arrays) 59 473 uniques = np.unique(lengths) 60 474 if len(uniques) > 1: 61--> 475 raise ValueError( 62 476 "Found input variables with inconsistent numbers of samples: %r" 63 477 % [int(l) for l in lengths] 64 478 ) 65 66ValueError: Found input variables with inconsistent numbers of samples: [17360, 4340]

該当のソースコード

import pandas as pd from sklearn.linear_model import LinearRegression df = pd.read_csv('Bank.csv') df.head(2) get_dummies = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month'] GET_DUMMIES = pd.get_dummies(df[get_dummies], drop_first = True, dtype = int) df2 = pd.concat([df, GET_DUMMIES], axis = 1) df2 = df2.drop(get_dummies, axis = 1) df2.head(2) from sklearn.model_selection import train_test_split train_val, test = train_test_split(df2, test_size = 0.2, random_state = 0) train_val.isnull().sum() train_val_mean = train_val.mean(numeric_only = True) train_val2 = train_val.fillna(train_val_mean) colname = train_val2.columns for name in colname: train_val2.plot(kind = 'scatter', x = name, y = 'y') outline1 = train_val2[(train_val2['duration'] > 1400) & (train_val2['y'] < 0.2)] outline2 = train_val2[(train_val2['amount'] > 100000) & (train_val2['y'] < 0.2)] outline3 = train_val2[(train_val2['previous'] > 250) & (train_val2['y'] < 0.2)] print(outline1, outline2, outline3) train_val3 = train_val2.drop([3140, 16312], axis = 0) from sklearn.preprocessing import StandardScaler def learn(x, t): x_train, y_train, x_val, y_val = train_test_split(x, t, test_size = 0.2, random_state = 0) sc_model_x = StandardScaler() sc_model_y = StandardScaler() sc_model_x.fit(x_train) sc_x_train = sc_model_x.transform(x_train) sc_model_y.fit(y_train) sc_y_train = sc_model_y.transform(y_train) model = LinearRegression() model.fit(sc_x_train, sc_y_train) sc_x_val = sc_model_x.transform(x_val) sc_y_val = sc_model_y.transform(y_val) train_score = model.score(sc_x_train, sc_y_train) val_score = model.score(sc_x_val, sc_y_train) return train_score, val_score train_cor = train_val3.corr()['y'] train_cor abs_cor = train_cor.map(abs) abs_cor.sort_values(ascending = False) x = train_val3.loc[ : ,['duration', 'housing_yes', 'campaign', 'contact_sending _document']] t = train_val3[['y']] s1, s2 = learn(x, t) print(s1, s2)

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

Google,ChatGPTなどで様々な提案を受けて改善しようとしたのですが、エラーの種類が若干変わるだけで自分の力では何がどうなっているのかすらわかりません。
参考情報としては薄いですが、おそらくネット検索では解決法は見つからないのではないかと思います。

補足

全体のプログラム

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

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

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

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

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

fiveHundred

2025/07/29 07:52

コードが見れませんし、それはリンクではなく、質問文に貼り付けるべきだと思います。
meg_

2025/07/29 10:04

「該当のソースコード」が「特になし」となっていますが、「表を作る際にいつの間にか項目ごとの要素数が減っていることに気づいた」のであればその「表を作る際」のコードを質問に掲載してください。 また「減っていることに気づいた」ということは「17360」の数値の方があるべき数ということですか?
meg_

2025/07/29 10:07

> 自分の力では何がどうなっているのかすらわかりません。 「表を作る際にいつの間にか項目ごとの要素数が減っていることに気づいた」とのことなので、デバッグしてその「いつの間にか」がいつ(何処)なのか確かめていけば原因と対策が分かるようになると思います。コードが不明なので原因は分かりませんがフィルタリングしている箇所などを重点的に確認されてはどうでしょうか?地道に調査してみてください。
Kojki

2025/07/31 01:32

@meg_ コードをコピーしようといろいろ試してみたのですが、コピーできません。 もしよろしければ、コピーの方法を教えていただけないでしょうか。 Jupytor Labを使っています。
fiveHundred

2025/07/31 01:34

普通にctrl+c→ctrl+vでいいのではないでしょうか。
Kojki

2025/08/01 14:07 編集

ありがとうございます。コピペしたものを下にのせます。 import pandas as pd from sklearn.linear_model import LinearRegression df = pd.read_csv('Bank.csv') df.head(2) get_dummies = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month'] GET_DUMMIES = pd.get_dummies(df[get_dummies], drop_first = True, dtype = int) df2 = pd.concat([df, GET_DUMMIES], axis = 1) df2 = df2.drop(get_dummies, axis = 1) df2.head(2) from sklearn.model_selection import train_test_split train_val, test = train_test_split(df2, test_size = 0.2, random_state = 0) train_val.isnull().sum() train_val_mean = train_val.mean(numeric_only = True) train_val2 = train_val.fillna(train_val_mean) colname = train_val2.columns for name in colname: train_val2.plot(kind = 'scatter', x = name, y = 'y') outline1 = train_val2[(train_val2['duration'] > 1400) & (train_val2['y'] < 0.2)] outline2 = train_val2[(train_val2['amount'] > 100000) & (train_val2['y'] < 0.2)] outline3 = train_val2[(train_val2['previous'] > 250) & (train_val2['y'] < 0.2)] print(outline1, outline2, outline3) train_val3 = train_val2.drop([3140, 16312], axis = 0) from sklearn.preprocessing import StandardScaler def learn(x, t): x_train, y_train, x_val, y_val = train_test_split(x, t, test_size = 0.2, random_state = 0) sc_model_x = StandardScaler() sc_model_y = StandardScaler() sc_model_x.fit(x_train) sc_x_train = sc_model_x.transform(x_train) sc_model_y.fit(y_train) sc_y_train = sc_model_y.transform(y_train) model = LinearRegression() model.fit(sc_x_train, sc_y_train) sc_x_val = sc_model_x.transform(x_val) sc_y_val = sc_model_y.transform(y_val) train_score = model.score(sc_x_train, sc_y_train) val_score = model.score(sc_x_val, sc_y_train) return train_score, val_score train_cor = train_val3.corr()['y'] train_cor abs_cor = train_cor.map(abs) abs_cor.sort_values(ascending = False) x = train_val3.loc[ : ,['duration', 'housing_yes', 'campaign', 'contact_sending _document']] t = train_val3[['y']] s1, s2 = learn(x, t) print(s1, s2) 最後の4行を実行したところでエラーが発生しました。 参照しているcsvファイルには各項目ごとに27128個のデータが存在しています。
meg_

2025/08/01 14:33

> コピペしたものを下にのせます。 質問は編集できます。質問の「該当のソースコード」のところに記入いただけませんか?
meg_

2025/08/01 15:03

エラーの発生元は変わらず「model.fit(sc_x_train, sc_y_train)」ですか?「x_train, y_train, x_val, y_val = train_test_split(x, t, test_size = 0.2, random_state = 0)」ではエラー発生しないのに不思議ですね。
bsdfan

2025/08/02 04:25

他に原因があるかもしれませんが、x_train, y_train, x_val, y_val = train_test_split(...) の代入の順番がおかしいと思います。(x_train, x_val, y_train, y_val = ... の順が正しい)
meg_

2025/08/02 06:41

> 代入の順番がおかしいと思います。 それですね。。。learn()の中の処理が怪しいとは思ってましたが、見落としてましたね。
Kojki

2025/08/02 10:20

代入の順番を変えましたが、同じようにエラーが出ました。 ValueError Traceback (most recent call last) Cell In[12], line 3 1 x = train_val3.loc[ : ,['duration', 'housing_yes', 'campaign', 'contact_sending _document']] 2 t = train_val3[['y']] ----> 3 s1, s2 = learn(x, t) 4 print(s1, s2) Cell In[9], line 16, in learn(x, t) 14 sc_y_val = sc_model_y.transform(y_val) 15 train_score = model.score(sc_x_train, sc_y_train) ---> 16 val_score = model.score(sc_x_val, sc_y_train) 17 return train_score, val_score File ~\anaconda3\Lib\site-packages\sklearn\base.py:663, in RegressorMixin.score(self, X, y, sample_weight) 660 from .metrics import r2_score 662 y_pred = self.predict(X) --> 663 return r2_score(y, y_pred, sample_weight=sample_weight) File ~\anaconda3\Lib\site-packages\sklearn\utils\_param_validation.py:216, in validate_params.<locals>.decorator.<locals>.wrapper(*args, **kwargs) 210 try: 211 with config_context( 212 skip_parameter_validation=( 213 prefer_skip_nested_validation or global_skip_validation 214 ) 215 ): --> 216 return func(*args, **kwargs) 217 except InvalidParameterError as e: 218 # When the function is just a wrapper around an estimator, we allow 219 # the function to delegate validation to the estimator, but we replace 220 # the name of the estimator by the name of the function in the error 221 # message to avoid confusion. 222 msg = re.sub( 223 r"parameter of \w+ must be", 224 f"parameter of {func.__qualname__} must be", 225 str(e), 226 ) File ~\anaconda3\Lib\site-packages\sklearn\metrics\_regression.py:1257, in r2_score(y_true, y_pred, sample_weight, multioutput, force_finite) 1133 """:math:`R^2` (coefficient of determination) regression score function. 1134 1135 Best possible score is 1.0 and it can be negative (because the (...) 1250 -inf 1251 """ 1252 xp, _, device_ = get_namespace_and_device( 1253 y_true, y_pred, sample_weight, multioutput 1254 ) 1256 _, y_true, y_pred, sample_weight, multioutput = ( -> 1257 _check_reg_targets_with_floating_dtype( 1258 y_true, y_pred, sample_weight, multioutput, xp=xp 1259 ) 1260 ) 1262 check_consistent_length(y_true, y_pred, sample_weight) 1264 if _num_samples(y_pred) < 2: File ~\anaconda3\Lib\site-packages\sklearn\metrics\_regression.py:198, in _check_reg_targets_with_floating_dtype(y_true, y_pred, sample_weight, multioutput, xp) 148 """Ensures that y_true, y_pred, and sample_weight correspond to the same 149 regression task. 150 (...) 194 correct keyword. 195 """ 196 dtype_name = _find_matching_floating_dtype(y_true, y_pred, sample_weight, xp=xp) --> 198 y_type, y_true, y_pred, multioutput = _check_reg_targets( 199 y_true, y_pred, multioutput, dtype=dtype_name, xp=xp 200 ) 202 # _check_reg_targets does not accept sample_weight as input. 203 # Convert sample_weight's data type separately to match dtype_name. 204 if sample_weight is not None: File ~\anaconda3\Lib\site-packages\sklearn\metrics\_regression.py:104, in _check_reg_targets(y_true, y_pred, multioutput, dtype, xp) 59 """Check that y_true and y_pred belong to the same regression task. 60 61 To reduce redundancy when calling `_find_matching_floating_dtype`, (...) 100 correct keyword. 101 """ 102 xp, _ = get_namespace(y_true, y_pred, multioutput, xp=xp) --> 104 check_consistent_length(y_true, y_pred) 105 y_true = check_array(y_true, ensure_2d=False, dtype=dtype) 106 y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype) File ~\anaconda3\Lib\site-packages\sklearn\utils\validation.py:475, in check_consistent_length(*arrays) 473 uniques = np.unique(lengths) 474 if len(uniques) > 1: --> 475 raise ValueError( 476 "Found input variables with inconsistent numbers of samples: %r" 477 % [int(l) for l in lengths] 478 ) ValueError: Found input variables with inconsistent numbers of samples: [17360, 4340]
meg_

2025/08/02 10:37

質問文にコード掲載されましたが残念ながらインデントがないです。Pythonはインデントが重要なのでインデントが無いとエラーになってしまいます。 > 代入の順番を変えましたが、同じようにエラーが出ました。 似たようなエラーですが発生個所が異なります。質問文では「model.fit(sc_x_train, sc_y_train)」でエラー発生しているのに対して、現在は「val_score = model.score(sc_x_val, sc_y_train)」でエラー発生しています。 > train_score = model.score(sc_x_train, sc_y_train) > val_score = model.score(sc_x_val, sc_y_train) 下記の sc_y_train が記述ミスではないでしょうか?
Kojki

2025/08/02 12:48

コメントありがとうございます。記述ミスを修正したところ問題が解決しました! ベストアンサーに選びたいので同じ内容を回答欄に投稿いただけますでしょうか? p.s. インデントの件についてですが、コピペをした際に解消されてしまっていたようです。 次回からは気を付けます。
meg_

2025/08/02 14:15

本質問は「model.fit(sc_x_train, sc_y_train)」でのエラーに関するものなのでbsdfanさんの指摘がベストアンサーかと思います。bsdfanさんに回答いただくか質問者さん自身で回答いただくのが良いと思います。
guest

回答1

0

ベストアンサー

python

1x_train, y_train, x_val, y_val = train_test_split(...)

の代入の順番がおかしいと思います。

python

1x_train, x_val, y_train, y_val = train_test_split(....)

の順番が正しいです。

上記修正後、別のエラーが発生するようですが、こちらについては、

python

1train_score = model.score(sc_x_train, sc_y_train) 2val_score = model.score(sc_x_val, sc_y_train)

2行目の方の sc_y_train が記述ミスだと思われます。 (meg_さんのコメントから転記)

投稿2025/08/03 01:08

bsdfan

総合スコア4932

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

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

Kojki

2025/08/04 15:51

まとめていただきありがとうございます。 また、bsdfanさん、meg_さんともにアドバイスをいただきありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.30%

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

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

質問する

関連した質問