假设我有一个数据集,我将在这个例子中提供一个玩具示例......
data = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
target = "A"
...产生...
A B C D
0 75 38 81 58
1 36 92 80 79
2 22 40 19 3
... ...
这显然是不足够的数据来提供一个良好的精度,但尽管如此,让我们说我喂data
和target
一个random forest
提供的算法scikit学习...
def random_forest(target, data):
# Drop the target label, which we save separately.
X = data.drop([target], axis=1).values
y = data[target].values
# Run Cross Validation on Random Forest Classifier.
clf_tree = ske.RandomForestClassifier(n_estimators=50)
unique_permutations_cross_val(X, y, clf_tree)
unique_permutations_cross_val
只是我制作的交叉验证函数,这就是函数(它也打印出模型的准确性)...
def unique_permutations_cross_val(X, y, model):
# Split data 20/80 to be used in a K-Fold Cross Validation with unique permutations.
shuffle_validator = model_selection.ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)
# Calculate the score of the model after Cross Validation has been applied to it.
scores = model_selection.cross_val_score(model, X, y, cv=shuffle_validator)
# Print out the score (mean), as well as the variance.
print("Accuracy: %0.4f (+/- %0.2f)" % (scores.mean(), scores.std()))
无论如何,我的主要问题是,如何使用我创建的这个模型预测目标标签。例如,假设我给模型喂食[28, 12, 33]
。我希望模型预测target
在这种情况下是"A"
。
发布代码中的此模型尚未安装。您进行了交叉验证,这将告诉您模型在您的数据上的训练效果如何(或不是),但它不会像您想要的那样适合模型对象。cross_val_score()
使用提供的模型对象的克隆来查找分数。
为了预测数据,您需要显式调用fit()
模型。
因此,也许您可以编辑random_forest
方法以返回拟合模型。像这样的东西:
unique_permutations_cross_val(X, y, clf_tree)
clf_tree.fit(X, y)
return clf_tree
然后无论您在何处调用该random_forest
方法,都可以执行以下操作:
fitted_model = random_forest(target, data)
predictions = fitted_model.predict([data to predict])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句