首页 > 解决方案 > 如何在 python 中对模型进行评分和测量准确性(泰坦尼克号数据集,RandomForestRegressor)

问题描述

我创建了一个在 Titanic 数据集上训练的模型,我想查看我的模型的准确率百分比。我以前做过,但遗憾的是,我不记得了。我查看了互联网,我找不到任何东西。要么我输入了错误的词,要么没有任何他们的词。

# the tts function is `train_test_split` from `sklearn.model_selection`
train_X, val_X, train_y, val_y = tts(X, y, random_state = 0) # y is the state of survival

forest_model = RandomForestRegressor(random_state=0)
forest_model.fit(train_X, train_y)
val_predictions = forest_model.predict(val_X)

如何计算准确度?

标签: pythonscikit-learn

解决方案


我想知道你为什么要使用RandomForestRegressor,因为 Titanic 数据集可以表述为二元分类问题。假设这是一个错误,要测量 a 的准确度RandomForestClassifier,您可以执行以下操作:

>>> from sklearn.metrics import accuracy_score
>>> accuracy_score(val_y, val_predictions)

但是,通常最好使用K-fold cross-validation,它可以为您提供更可靠的准确性:

>>> from sklearn.model_selection import cross_val_score
>>> cross_val_score(forest_model, X, y, cv=10, scoring='accuracy') #10-fold cross validation, notice that I am giving X,y not X_train, y_train 

K-fold cross-validation为您提供 10 个准确度值,因为它将数据分成 10 倍(即部分)。然后,您可以获得 ameanstandard deviation准确度值,如下所示:

>>> import numpy as np
>>> accuracy =  np.array(cross_val_score(forest_model, X, y, cv=10, scoring='accuracy'))
>>> accuracy.mean() #mean of accuracies
0.81
>>> accuracy.std() #standard deviation of accuracies
0.04

您还可以使用其他评分指标,例如F1-score, Precision, Recallcohen_kappa_score


推荐阅读