Scikit-learn:模型选择Model selection之pipline和交叉验证

http://blog.csdn.net/pipisorry/article/details/52250983

选择合适的estimator

通常机器学习最难的一部分是选择合适的estimator,不同的estimator适用于不同的数据集和问题。

sklearn官方文档提供了一个图[flowchart],可以快速地根据你的数据和问题选择合适的estimator,单击相应的区域还可以获得更具体的内容。

代码中我一般这么写

def gen_estimators():
    '''
    List of the different estimators.
    '''
    estimators = [
        # ('Lasso regression', linear_model.Lasso(alpha=0.1), True),
        ('Ridge regression', linear_model.Ridge(alpha=0.1), True),
        # ('Hinge regression', linear_model.Hinge(), True),
        # ('LassoLars regression', linear_model.LassoLars(alpha=0.1), True),
        ('OrthogonalMatchingPursuitCV regression', linear_model.OrthogonalMatchingPursuitCV(), True),
        ('BayesianRidge regression', linear_model.BayesianRidge(), True),
        ('PassiveAggressiveRegressor regression', linear_model.PassiveAggressiveRegressor(), True),
        ('HuberRegressor regression', linear_model.HuberRegressor(), True),
        # ('LogisticRegression regression', linear_model.LogisticRegression(), True),
    ]
    return estimators

然后如下遍历算法

def cross_validate():
    for name, clf, flag in gen_estimators():
        x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=0)
        clf.fit(x_train, y_train)
        print(name, '\n', clf.coef_)
        # scores = cross_val_score(clf, x, y, cv=5, scoring='roc_auc')
        y_score = clf.predict(x_test)
        y_score = np.select([y_score < 0.0, y_score > 1.0, True], [0.0, 1.0, y_score])
        scores = metrics.roc_auc_score(y_true=[1.0 if _ > 0.0 else 0.0 for _ in y_test], y_score=y_score)
        print(scores)

自己写的模型也可以,但是写的estimator类必须有的方法是有:get_params, set_params(**params), fit(x,y), predict(new_samples), score(x, y_true)。其中有的可以直接从from sklearn.base import BaseEstimator中继承。如:

class DriveRiskEstimator(BaseEstimator):
    def __init__(self):
        pass

    def get_params(self, deep=True):
        return {}

    def set_params(self, **params):
        return self

    def fit(self, x, y):
        '''
        模型训练
        '''
        return self

    def predict(self, new_samples):
        '''
        模型预测
        '''
        result = np.zeros(len(new_samples))
        return result

    def score(self, x, y_true):
      y_pred = self.predict(x)
      score = metrics.***(y_true, y_pred)
      return score

[Scikit-learn:模型选择之调参grid search]

皮皮blog

Scikit-klean训练集和测试集分割

sklearn.model_selection.train_test_split(*arrays, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None)

参数

*arrays    sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes.

test_size    float or int, default=None
If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size.

random_state int, RandomState instance or None, default=None
Controls the shuffling applied to the data before applying the split. Pass an int for reproducible output across multiple function calls. 设置成一个定值后续可以复现。

示例

示例:从文件读取后分割

from sklearn import model_selection

with open('***', encoding='utf-8') as f:
    lines = f.readlines()
train_data, eval_data = model_selection.train_test_split(lines, test_size=0.2, shuffle=True, random_state=0)
train_data, test_data = model_selection.train_test_split(train_data, test_size=0.1, shuffle=True, random_state=0)

这里train_data类型是list。

示例:分割dataframe

直接对dataframe分割,如果df存在头部,则分割后的每个部分都会自带头部:

data_df = readCsv(path_train)
train_data, test_data = model_selection.train_test_split(data_df, test_size=0.3)

示例:对ndarray类型的x\y分割

X_train, X_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=0.4, random_state=0)
X_train.shape, y_train.shape
((90, 4), (90,))
X_test.shape, y_test.shape
((60, 4), (60,))

clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)
clf.score(X_test, y_test)                           
0.96...

X_train类型应该是ndarray 

[train_test_split]

Sklearn交叉验证

scores = cross_val_score(clf, x, y, cv=10, scoring=rocAucScorer)

也可以不指定scoring函数,此时自动调用定义的Estimator类中的score函数score(self, x, y_true):

estimator = Estimator().fit(x, y)
scores = cross_val_score(estimator, x, y, cv=cv)

自定义CV策略

(cv是整数的话默认使用KFold):

>>> n_samples = iris.data.shape[0]
>>> cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, test_size=0.3, random_state=0)
>>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=cv)          
array([ 0.97...,  0.97...,  1.        ])

另一个接口cross_val_predict ,可以返回每个元素作为test set时的确切预测值(只有在CV的条件下数据集中每个元素都有唯一预测值时才不会出现异常),进而评估estimator:
>>> predicted = cross_validation.cross_val_predict(clf, iris.data, iris.target, cv=10)
>>> metrics.accuracy_score(iris.target, predicted)
0.966...

[scikit-klean交叉验证]

皮皮blog

from: Scikit-learn:模型选择Model selection之pipline和交叉验证-CSDN博客

ref: [scikit-learn User Guide]

[Model selection and evaluation]

[3.1. Cross-validation: evaluating estimator performance]*

[3.4. Model persistence]

[Sample pipeline for text feature extraction and evaluation*]

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
这个错误通常发生在使用 Pandas 和 scikit-learn 库时,其中一个库使用的数据列名与另一个库不同。出现这种情况的原因可能是数据的列名不一致或者缺少某些列。 解决方法如下: 1. 确保数据列名一致。可以通过使用 `df.columns` 属性查看 Pandas 数据框的列名,并使用 `model.feature_names_` 查看 scikit-learn 模型的特征名称。如果两者不一致,则需要将它们调整成一致的列名。 2. 确保数据中包含所需的列。如果 scikit-learn 模型需要的列在 Pandas 数据框中不存在,则需要添加这些列。 3. 确保数据的顺序正确。有时候,数据的顺序可能不一致,导致 scikit-learn 模型无法识别数据。可以使用 `df.reindex` 对数据进行排序。 举个例子,假设我们有两个数据集,一个是 Pandas 数据框,包括两列 'x' 和 'y',另一个是 scikit-learn 模型,需要特征名称为 'a' 和 'b'。我们需要将 Pandas 数据框的列名 'x' 和 'y' 调整为 scikit-learn 模型的特征名称 'a' 和 'b',并且确保数据顺序正确,如下所示: ``` import pandas as pd from sklearn.linear_model import LinearRegression # 创建 Pandas 数据框 df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) # 创建 scikit-learn 模型 model = LinearRegression() # 将 Pandas 数据框的列名调整为 scikit-learn 模型的特征名称 df.columns = ['a', 'b'] # 确保数据顺序正确 df = df.reindex(columns=model.feature_names_) # 训练模型 model.fit(df, [1, 2, 3]) ``` 这样就可以避免出现 KeyError 错误了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值