【发布时间】:2018-12-15 23:50:24
【问题描述】:
我最近开始使用决策树,我想用一些人造数据训练我自己的简单模型。我想用这个模型来预测一些进一步的模拟数据,只是为了了解它是如何工作的,但后来我卡住了。训练模型后,如何将数据传递给 predict()?
http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html
文档状态: clf.predict(X)
参数: X : 形状的类数组或稀疏矩阵 = [n_samples, n_features]
但是当试图传递 np.array、np.ndarray、list、tuple 或 DataFrame 时,它只会抛出一个错误。你能帮我理解为什么吗?
代码如下:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
import graphviz
import pandas as pd
import numpy as np
import random
from sklearn import tree
pd.options.display.max_seq_items=5000
pd.options.display.max_rows=20
pd.options.display.max_columns=150
lenght = 50000
miles_commuting = [random.choice([2,3,4,5,7,10,20,25,30]) for x in range(lenght)]
salary = [random.choice([1300,1600,1800,1900,2300,2500,2700,3300,4000]) for x in range(lenght)]
full_time = [random.choice([1,0,1,1,0,1]) for x in range(lenght)]
DataFrame = pd.DataFrame({'CommuteInMiles':miles_commuting,'Salary':salary,'FullTimeEmployee':full_time})
DataFrame['Moving'] = np.where((DataFrame.CommuteInMiles > 20) & (DataFrame.Salary > 2000) & (DataFrame.FullTimeEmployee == 1),1,0)
DataFrame['TargetLabel'] = np.where((DataFrame.Moving == 1),'Considering move','Not moving')
target = DataFrame.loc[:,'Moving']
data = DataFrame.loc[:,['CommuteInMiles','Salary','FullTimeEmployee']]
target_names = DataFrame.TargetLabel
features = data.columns.values
clf = tree.DecisionTreeClassifier()
clf = clf.fit(data, target)
clf.predict(?????) #### <===== What should go here?
clf.predict([30,4000,1])
ValueError: Expected 2D array, got 1D array instead: 数组=[3.e+01 4.e+03 1.e+00]。 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果数据包含单个样本,则使用 array.reshape(1, -1)。
clf.predict(np.array(30,4000,1))
ValueError: 只接受 2 个非关键字参数
【问题讨论】:
-
是的,谢谢你的清晰解释
标签: python-3.x scikit-learn classification sklearn-pandas