Scikit-learn、Numpy:更改只读变量的值

Scikit-learn, Numpy: Changing the value of an read-only variable

我目前正在使用 scikit-learn 训练 SVM

根据我的数据训练模型后,我想更改 coef_ 我的模型。

#initiate svm
model = svm.SVC(Parameters...)

#train the model with data
model.fit(X,y)

#Now i want to change the coef_ attribute(A numpy array)
model.coef_ = newcoef

问题:它给了我一个 AttributeError: can't set attribute。或者当我尝试访问它给我的属性中的 numpy 数组时 ValueError: assignment destination is read-only

有没有办法改变现有模型的属性?

(我想这样做是因为我想并行化 SVM 训练, 并且必须为此更改 coef_ 属性。)

来自SVM doc

coef_ is a readonly property derived from dual_coef_ and support_vectors_

并从 model.coef_ 的执行:

@property
def coef_(self):
    if self.kernel != 'linear':
        raise AttributeError('coef_ is only available when using a '
                             'linear kernel')

    coef = self._get_coef()

    # coef_ being a read-only property, it's better to mark the value as
    # immutable to avoid hiding potential bugs for the unsuspecting user.
    if sp.issparse(coef):
        # sparse matrix do not have global flags
        coef.data.flags.writeable = False
    else:
        # regular dense array
        coef.flags.writeable = False
    return coef

def _get_coef(self):
    return safe_sparse_dot(self._dual_coef_, self.support_vectors_)

可以看到model.coef_是一个property,每次访问都会计算它的值

所以不能给它赋值。相反,可以更改 model.dual_coef_model.support_vectors_ 的值,以便随后更新 model.coef_

示例如下:

model = svm.SVC(kernel='linear')
model.fit(X_train, y_train)
print(model.coef_)
#[[ 0.          0.59479519 -0.96654219 -0.44609639]
#[ 0.04016065  0.16064259 -0.56224908 -0.24096389]
#[ 0.7688616   1.11070473 -2.13349078 -1.88291061]]

model.dual_coef_[0] = 0
model.support_vectors_[0] = 0

print(model.coef_)
#[[ 0.          0.          0.          0.        ]
#[ 0.          0.          0.          0.        ]
#[ 0.7688616   1.11070473 -2.13349078 -1.88291061]]