前提・実現したいこと
今タイタニックの機械学習をしておりました。しかし予測のところでエラーが出てしまいます。どうすれば良いでしょうか?
発生している問題・エラーメッセージ
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-447-a88d82d7d4a6> in <module> 2 lr = RandomForestClassifier(criterion='gini', max_depth=6, n_estimators=500, random_state=7) 3 lr.fit(x_train, y_train) ----> 4 y_pred = lr.predict(x_test) 5 y_pred 6 /opt/conda/lib/python3.6/site-packages/sklearn/ensemble/forest.py in predict(self, X) 543 The predicted classes. 544 """ --> 545 proba = self.predict_proba(X) 546 547 if self.n_outputs_ == 1: /opt/conda/lib/python3.6/site-packages/sklearn/ensemble/forest.py in predict_proba(self, X) 586 check_is_fitted(self, 'estimators_') 587 # Check data --> 588 X = self._validate_X_predict(X) 589 590 # Assign chunk of trees to jobs /opt/conda/lib/python3.6/site-packages/sklearn/ensemble/forest.py in _validate_X_predict(self, X) 357 "call `fit` before exploiting the model.") 358 --> 359 return self.estimators_[0]._validate_X_predict(X, check_input=True) 360 361 @property /opt/conda/lib/python3.6/site-packages/sklearn/tree/tree.py in _validate_X_predict(self, X, check_input) 400 "match the input. Model n_features is %s and " 401 "input n_features is %s " --> 402 % (self.n_features_, n_features)) 403 404 return X ValueError: Number of features of the model must match the input. Model n_features is 10 and input n_features is 11
該当のソースコード
Python3
1# モジュールのインポート 2%matplotlib inline 3import numpy as np 4import pandas as pd 5import seaborn as sns 6import matplotlib.pyplot as plt 7from sklearn.ensemble import RandomForestClassifier 8from sklearn.model_selection import StratifiedKFold 9 10# ファイルの読み込み 11train = pd.read_csv('../input/titanic/train.csv') 12test = pd.read_csv('../input/titanic/test.csv') 13 14corr = train.corr() 15sns.heatmap(corr, 16 vmin=-1.0, 17 vmax=1.0, 18 center=0, 19 fmt='.1f') 20 21# 特徴量の削除 22train.drop('Name', axis=1, inplace=True) 23train.drop('Ticket', axis=1, inplace=True) 24train.drop('Cabin', axis=1, inplace=True) 25train.drop('PassengerId', axis=1, inplace=True) 26 27test.drop('Name', axis=1, inplace=True) 28test.drop('Ticket', axis=1, inplace=True) 29test.drop('Cabin', axis=1, inplace=True) 30test.drop('PassengerId', axis=1, inplace=True) 31 32# 欠損値の確認 33print('train' + '\n') 34print(train.isnull().sum()) 35print('\n') 36print('test' + '\n') 37print(test.isnull().sum()) 38 39# 欠損値の補完 40train_age_median = train['Age'].median() 41train['Age'].fillna(train_age_median, inplace=True) 42train['Embarked'].fillna('S', inplace=True) 43 44test_age_median = test['Age'].median() 45test['Age'].fillna(test_age_median, inplace=True) 46test['Fare'].fillna(test['Fare'].mean(), inplace=True) 47 48# 特徴量の加工、エンコーディング 49train['Pclass_1'] = train['Pclass'].apply(lambda x : 1 if x == 1 else 0) 50train['Pclass_2'] = train['Pclass'].apply(lambda x : 1 if x == 2 else 0) 51train['Pclass_3'] = train['Pclass'].apply(lambda x : 1 if x == 3 else 0) 52train.drop('Pclass', axis=1, inplace=True) 53 54train['Embarked_S'] = train['Embarked'].apply(lambda x : 1 if x == 'S' else 0) 55train['Embarked_Q'] = train['Embarked'].apply(lambda x : 1 if x == 'Q' else 0) 56train['Embarked_C'] = train['Embarked'].apply(lambda x : 1 if x == 'C' else 0) 57train.drop('Embarked', axis=1, inplace=True) 58 59# 特徴量をまとめる 60train['Familysize'] = train['SibSp'] + train['Parch'] + 1 61train.drop('SibSp', axis=1, inplace=True) 62train.drop('Parch', axis=1, inplace=True) 63 64train['Sex'].replace({'male' : 0, 'female' : 1}, inplace=True) 65 66# int型にして反転する 67train = train.astype(int) 68train = train[train.columns[::-1]] 69 70train.head(3) 71 72# 特徴量の加工、エンコーディング 73test['Pclass_1'] = test['Pclass'].apply(lambda x : 1 if x == 1 else 0) 74test['Pclass_2'] = test['Pclass'].apply(lambda x : 1 if x == 2 else 0) 75test['Pclass_3'] = test['Pclass'].apply(lambda x : 1 if x == 3 else 0) 76test.drop('Pclass', axis=1, inplace=True) 77 78test['Embarked_S'] = test['Embarked'].apply(lambda x : 1 if x == 'S' else 0) 79test['Embarked_Q'] = test['Embarked'].apply(lambda x : 1 if x == 'Q' else 0) 80test['Embarked_C'] = test['Embarked'].apply(lambda x : 1 if x == 'C' else 0) 81test.drop('Embarked', axis=1, inplace=True) 82 83# 特徴量をまとめる 84test['Familysize'] = test['SibSp'] + test['Parch'] + 1 85test.drop('Parch', axis=1, inplace=True) 86 87test['Sex'].replace({'male' : 0, 'female' : 1}, inplace=True) 88 89# int型にして反転する 90test = test.astype(int) 91test = test[test.columns[::-1]] 92 93test.head(3) 94 95# 目的変数と説明変数の定義 96x_train = train.loc[:, 'Familysize':'Sex'] 97y_train = train['Survived'] 98 99x_test = test 100 101# グリッドサーチ 102from sklearn.model_selection import GridSearchCV 103 104forest = RandomForestClassifier() 105# パラメータの候補 106pram = {'n_estimators' : [10,100,500,1000], 107 'max_depth' : [3,6,12], 108 'criterion' : ['gini','entropy'], 109 'random_state' : [7]} 110# 交差検証を行う 111grid_forest = GridSearchCV(forest, pram) 112grid_forest.fit(x_train,y_train) 113# 最適なパラメータを出力する 114grid_forest.best_params_ 115 116# モデルの作成 117lr = RandomForestClassifier(criterion='gini', max_depth=6, n_estimators=1000, random_state=7) 118lr.fit(x_train, y_train) 119y_pred = lr.predict(x_test) 120y_pred 121 122# 提出できるようにする 123sub = pd.DataFrame(pd.read_csv("../input/titanic/test.csv")['PassengerId']) 124sub['Survived'] = list(map(int, y_pred)) 125sub.to_csv("submission.csv", index=False)
試したこと
ここに問題に対して試したことを記載してください。
補足情報(FW/ツールのバージョンなど)
カラムはPassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarkedです。
featureの数を合わせれば良いのではないでしょうか?
上記のカラムはモデルのカラムですか?インプットのですか? それとも元のデータのものですか?
回答1件
あなたの回答
tips
プレビュー