sklearn Ridge和sample_weight给出内存错误

ADJ*_*ADJ 3 python regression scikit-learn

我正在尝试使用一系列样本权重来运行简单的Sklearn Ridge回归.X_train是一个~200k×100的2D Numpy阵列.我尝试使用sample_weight选项时出现内存错误.没有这个选项,它工作得很好.为了简单起见,我将功能减少到2,而sklearn仍然会让我感到内存错误.有任何想法吗?

model=linear_model.Ridge()

model.fit(X_train, y_train,sample_weight=w_tr)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/g/anaconda/lib/python2.7/site-packages/sklearn/linear_model/ridge.py", line 449, in fit
    return super(Ridge, self).fit(X, y, sample_weight=sample_weight)
  File "/home/g/anaconda/lib/python2.7/site-packages/sklearn/linear_model/ridge.py", line 338, in fit
    solver=self.solver)
  File "/home/g/anaconda/lib/python2.7/site-packages/sklearn/linear_model/ridge.py", line 286, in ridge_regression
    K = safe_sparse_dot(X, X.T, dense_output=True)
  File "/home/g/anaconda/lib/python2.7/site-packages/sklearn/utils/extmath.py", line 83, in safe_sparse_dot
    return np.dot(a, b)
MemoryError
Run Code Online (Sandbox Code Playgroud)

eic*_*erg 8

设置样本权重会导致sklearn linear_model Ridge对象处理数据的方式存在很大差异 - 特别是如果矩阵很高(n_samples> n_features),就像你的情况一样.如果没有样本权重将利用以下事实:XTdot(X)是一个相对较小矩阵(100×100在您的情况),因此将反转特征空间的矩阵.对于给定的样本权重,Ridge对象决定留在样本空间中(为了能够单独对样本进行加权,请参见此处此处的相关行以分支到样本空间中的_solve_dense_cholesky_kernel),因此需要反转矩阵大小相同X.dot(XT)的(在你的情况是N_SAMPLES次X N_SAMPLES次= 200000 X 200000和将导致存储器错误甚至创建之前).这实际上是一个实现问题,请参阅下面的手动解决方法.

TL; DR: Ridge对象无法处理特征空间中的样本权重,并将生成矩阵n_samples x n_samples,这会导致内存错误

在等待scikit学习中可能的补救措施时,您可以尝试明确地解决特征空间中的问题,就像这样

import numpy as np
alpha = 1.   # You did not specify this in your Ridge object, but it is the default penalty for the Ridge object
sample_weights = w_tr.ravel()  # make sure this is 1D
target = y.ravel()  # make sure this is 1D as well
n_samples, n_features = X.shape
coef = np.linalg.inv((X.T * sample_weights).dot(X) + 
                      alpha * np.eye(n_features)).dot(sample_weights * target)
Run Code Online (Sandbox Code Playgroud)

对于新的样本X_new,您的预测将是

prediction = np.dot(X_new, coef)
Run Code Online (Sandbox Code Playgroud)

为了确认这种方法的有效性,你可以将这些系数与你的代码中的model.coef_(在你的模型之后)进行比较,当它应用于较小数量的样本(例如300)时,不会导致内存错误.与Ridge对象一起使用.

重要提示:如果您的数据已经居中,上面的代码只与sklearn实现一致,即您的数据必须具有均值0.在此处使用截距拟合实现完整岭回归将相当于对scikit学习的贡献,因此最好发布它在那里.使数据居中的方法如下:

X_mean = X.mean(axis=0)
target_mean = target.mean()   # Assuming target is 1d as forced above
Run Code Online (Sandbox Code Playgroud)

然后使用提供的代码

X_centered = X - X_mean
target_centered = target - target_mean
Run Code Online (Sandbox Code Playgroud)

有关新数据的预测,您需要

prediction = np.dot(X_new - X_mean, coef) + target_mean
Run Code Online (Sandbox Code Playgroud)

编辑:截至2014年4月15日,scikit-learn ridge回归可以解决这个问题(前沿代码).它将在0.15版本中提供.