我已经使用scikit学习算法创建了一个模型。
rf = RandomForestClassifier(n_estimators = 10,random_state=seed)
rf.fit(X_train,Y_train)
shift_id=2099.0
user_id=1402.0
status=['S']
shift_organisation_id=15.0
shift_department_id=20.0
open_positions=71.0
city=['taunton']
role_id=3.0
specialty_id=16.0
years_of_experience=10.0
nurse_zip=2780.0
shifts_zip=2021.0
status = status_encoder.transform(status)
city = city_encoder.transform(city)
X = np.array([shift_id, user_id, status, shift_organisation_id, shift_department_id, open_positions, city, role_id, specialty_id, years_of_experience, nurse_zip, shifts_zip])
location_id = rf.predict(X.reshape(1,-1))
print(location_id)
给出这样的结果
[25]
我了解的是25
是此模型的最佳预测值。但我想获得最高的最佳3个值。我怎么能得到它?
在那种情况下,预测结果将是
[23,45,25]
答案 0 :(得分:1)
您可以使用predict_proba
方法返回类概率并从中获取前3个值ref
rf = RandomForestClassifier(n_estimators = 10,random_state=seed)
rf.fit(X_train,Y_train)
shift_id=2099.0
user_id=1402.0
status=['S']
shift_organisation_id=15.0
shift_department_id=20.0
open_positions=71.0
city=['taunton']
role_id=3.0
specialty_id=16.0
years_of_experience=10.0
nurse_zip=2780.0
shifts_zip=2021.0
status = status_encoder.transform(status)
city = city_encoder.transform(city)
X = np.array([shift_id, user_id, status, shift_organisation_id, shift_department_id, open_positions, city, role_id, specialty_id, years_of_experience, nurse_zip, shifts_zip])
location_id = rf.predict_proba(X.reshape(1,-1))
print(location_id)
答案 1 :(得分:1)
您可以使用predict_proba
方法,该方法返回对类概率的预测。
让我们使用iris dataset来检查示例:
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features.
y = iris.target
# train/test split
X_train, X_test, y_train, y_test = train_test_split(X, y)
rf = RandomForestClassifier(n_estimators = 10, random_state=10)
rf.fit(x_train,y_train)
如果您现在按预期方式调用predict
方法,则将获得最高的概率类别:
rf.predict(X_test)
# array([1, 2, 1, 0, 2, 0, 2, 0, 0, 1, 2, ...
无论如何致电predict_proba
,您都会获得相应的概率:
rf.predict_proba(X_test)
array([[0. , 1. , 0. ],
[0.11 , 0.1 , 0.79 ],
[0. , 0.7 , 0.3 ],
[0.5 , 0.4 , 0.1 ],
[0. , 0.3 , 0.7 ],
[0.5 , 0.2 , 0.3 ],
[0.4 , 0. , 0.6 ],
...
为了获得最高的k
概率,您可以使用argsort
并索引相应的概率rf.classes_
:
k = 2
rf.classes_[rf.predict_proba(X_test).argsort()[:,-k:]]
array([[2, 1],
[0, 2],
[2, 1],
[1, 0],
[1, 2],
[2, 0],
[0, 2],
[1, 0],
[1, 0],
[2, 1],
...
在上述情况中,可以使用argpartition
进行改进,因为我们只对排名靠前的k
概率感兴趣:
rf.classes_[rf.predict_proba(X_test).argpartition(range(k))[:,-k:]]