gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:33:24 24 4
gpt4 key购买 nike

我目前正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com