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

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

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

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

Q&A

解決済

1回答

1083閲覧

python:ValueError: Found input variables with inconsistent numbers of samples: [70000, 21000]

退会済みユーザー

退会済みユーザー

総合スコア0

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

0グッド

0クリップ

投稿2017/12/08 10:37

###前提・実現したいこと
mnistデータでk近傍の最適なkを探すプログラムを作っています。
このようなエラーが出た場合どうすればいいですか・

###発生している問題・エラーメッセージ

python

1--------------------------------------------------------------------------- 2ValueError Traceback (most recent call last) 3<ipython-input-4-a49f56a69ab6> in <module>() 4 45 5 46 if __name__ == '__main__': 6---> 47 main() 7 8<ipython-input-4-a49f56a69ab6> in main() 9 27 10 28 # 正解率を計算 11---> 29 score = accuracy_score(targets, predicted_label) 12 30 print('k={}: {}'.format(k, score)) 13 31 14 15~\Anaconda3\lib\site-packages\sklearn\metrics\classification.py in accuracy_score(y_true, y_pred, normalize, sample_weight) 16 174 17 175 # Compute accuracy for each possible representation 18--> 176 y_type, y_true, y_pred = _check_targets(y_true, y_pred) 19 177 if y_type.startswith('multilabel'): 20 178 differing_labels = count_nonzero(y_true - y_pred, axis=1) 21 22~\Anaconda3\lib\site-packages\sklearn\metrics\classification.py in _check_targets(y_true, y_pred) 23 69 y_pred : array or indicator matrix 24 70 """ 25---> 71 check_consistent_length(y_true, y_pred) 26 72 type_true = type_of_target(y_true) 27 73 type_pred = type_of_target(y_pred) 28 29~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_consistent_length(*arrays) 30 202 if len(uniques) > 1: 31 203 raise ValueError("Found input variables with inconsistent numbers of" 32--> 204 " samples: %r" % [int(l) for l in lengths]) 33 205 34 206 35 36 37ValueError: Found input variables with inconsistent numbers of samples: [70000, 21000]

###該当のソースコード

python

1from collections import Counter 2from matplotlib import pyplot as plt 3from sklearn import datasets, model_selection, metrics 4from sklearn.metrics import accuracy_score 5from sklearn.neighbors import KNeighborsClassifier 6import sklearn.datasets as datasets 7import numpy as np 8import pandas as pd 9import time 10state = np.random.RandomState(1) 11 12mnist = datasets.fetch_mldata('MNIST original', data_home='data/src/download/') 13 14def main(): 15 16 # 特徴データとラベルデータを取り出す 17 features = mnist.data 18 targets = mnist.target 19 20 train_dataX, test_dataX, train_dataY, test_dataY = model_selection.train_test_split(features,targets,test_size=0.3) 21 22 23 # 検証する近傍数 24 K = 10 25 ks = range(1, K + 1) 26 27 # 使う近傍数ごとに正解率&各経過時間を計算 28 accuracy_scores = [] 29 start = time.time() 30 for k in ks: 31 predicted_labels = [] 32 elapsed_time = time.time() - start 33 34 # モデルを学習 35 model = KNeighborsClassifier(n_neighbors=k, metric='euclidean') 36 model.fit(train_dataX,train_dataY) 37 38 # 一つだけ取り除いたテストデータを識別 39 predicted_label = model.predict(test_dataX) 40 41 # 正解率を計算 42 score = accuracy_score(targets, predicted_label) 43 print('k={}: {}'.format(k, score)) 44 45 accuracy_scores.append(score) 46 47 # 各経過時間を表示 48 print("経過時間:{:.2f}".format(elapsed_time)) 49 50 # 使う近傍数ごとの正解率を折れ線グラフ 51 X = list(ks) 52 plt.plot(X, accuracy_scores) 53 54 plt.xlabel('k') 55 plt.ylabel('正解率') 56 plt.show() 57 58 59if __name__ == '__main__': 60 main()

###補足情報(言語/FW/ツール等のバージョンなど)
Anaconda3 python

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

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

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

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

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

guest

回答1

0

ベストアンサー

targetspredicted_labelを同じ数にすればよいです。
.shapeすると1つ目の数字がデータの数になります。
変数名のミスで評価用の値が正しくないことが想定されます。

投稿2017/12/08 15:40

mkgrei

総合スコア8560

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

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

退会済みユーザー

退会済みユーザー

2017/12/08 16:18

回答ありがとうございます それはどのように書いたらいいのでしょうか
mkgrei

2017/12/08 16:24

test_dataXをモデルに入れたのならtargetsではなくtest_dataYを評価に入れるべきではないでしょうか。
退会済みユーザー

退会済みユーザー

2017/12/09 11:48

これでできました!けど、時間かかってしまうのはしょうがないですよね?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問