LoginSignup
8
3

More than 1 year has passed since last update.

[Python] UserWarning: X has feature names・・・の対処法

Posted at

scikit-learnでpredictを行う際に出力された警告に対し、どのように処理を行ったかを共有させていただきます。誰かのご参考になれば幸いです。

fit と predict の引数の型を確認しましょう

結論から申し上げますと、引数の型が異なっているので警告が出ています。

警告内容:UserWarning: X has feature names, but DecisionTreeClassifier was fitted without feature names

前提処理
1.訓練データとテストデータを分ける

from sklearn.model_selection import train_test_split

# 引数のx,yはデータフレーム型
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.2,random_state = 0)

2.fitの引数は「データフレーム型」

from sklearn import tree

model = tree.DecisionTreeClassifier(max_depth = 3,random_state = 0)

model.fit(x_train,y_train)

重要
fit の引数には「データフレーム型」を渡しています。

警告されるコード

newdata = [[1.56,0.23,-1.1,-2.8]]
answer = model.predict(newdata)

学習時の訓練データはデータフレーム型なのに対し、
predict に渡したnewdataは「リスト型」なので警告が出力されます。

対処

# pandasはインポート済み
# データフレーム型に変換
data = pd.DataFrame(newdata)

リスト型からデータフレーム型に変換することで対処することができました。

上記のコードで対処できない場合には、fit の引数の列名や行の名前を一致させてあげることで対処できました。

# データフレーム型に変換する際に、行の名前を指定
data = pd.DataFrame(newdata,columns = ["x0","x1","x2","x3"])
8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3