python - Scikit 学习,Numpy : Changing the value of an read-only variable

标签 python python-2.7 class numpy scikit-learn

我目前正在使用 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:赋值目标是只读的

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

(我想这样做是因为我想并行化 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]]

关于python - Scikit 学习,Numpy : Changing the value of an read-only variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34827838/

相关文章:

python - 你如何用 pyparsing 解析文字星号?

python - Pandas 中的条件合并

python - 在 python 中,将 redis-py 与多处理模块一起使用,为什么每个进程都是不同的 fd?

python - 为什么我的列表没有按照预期的方式改变?

c# - 带有构造函数的通用类<T>来选择类型

c++在程序中使用私有(private)类数据

python - 当我给它图像时,我的 keras 模型会给出随机预测

python - 如何用匹配的大小写替换正则表达式?

python-2.7 - 在sklearn中生成各向异性数据

linux - python : How to wait until disk activity subsides?