Python 当只更新一个索引时,numpy zeros 数组为每个值分配 1
Python numpy zeros array being assigned 1 for every value when only one index is updated
以下是我的代码:
amount_features = X.shape[1]
best_features = np.zeros((amount_features,), dtype=int)
best_accuracy = 0
best_accuracy_index = 0
def find_best_features(best_features, best_accuracy):
for i in range(amount_features):
trial_features = best_features
trial_features[i] = 1
svc = SVC(C = 10, gamma = .1)
svc.fit(X_train[:,trial_features==1],y_train)
y_pred = svc.predict(X_test[:,trial_features==1])
accuracy = metrics.accuracy_score(y_test,y_pred)
if (accuracy > best_accuracy):
best_accuracy = accuracy
best_accuracy_index = i
print(best_accuracy_index)
best_features[best_accuracy_index] = 1
return best_features, best_accuracy
bf, ba = find_best_features(best_features, best_accuracy)
print(bf, ba)
这是我的输出:
25
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] 0.865853658537
我的预期输出:
25
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0] 0.865853658537
我正在尝试使用提供最高准确度的索引更新 zeros 数组。如您所见,它应该是索引 25,然后我将 25 索引分配给我的数组等于 1。但是,当我打印数组时,它显示每个索引都已更新为 1。
不确定发生了什么事故。感谢您在地球上花费有限的时间来帮助我。
将 trial_features = best_features
更改为 trial_features = numpy.copy(best_features)
。 @Michael Butscher 已经给出了更改背后的原因。
以下是我的代码:
amount_features = X.shape[1]
best_features = np.zeros((amount_features,), dtype=int)
best_accuracy = 0
best_accuracy_index = 0
def find_best_features(best_features, best_accuracy):
for i in range(amount_features):
trial_features = best_features
trial_features[i] = 1
svc = SVC(C = 10, gamma = .1)
svc.fit(X_train[:,trial_features==1],y_train)
y_pred = svc.predict(X_test[:,trial_features==1])
accuracy = metrics.accuracy_score(y_test,y_pred)
if (accuracy > best_accuracy):
best_accuracy = accuracy
best_accuracy_index = i
print(best_accuracy_index)
best_features[best_accuracy_index] = 1
return best_features, best_accuracy
bf, ba = find_best_features(best_features, best_accuracy)
print(bf, ba)
这是我的输出:
25
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] 0.865853658537
我的预期输出:
25
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0] 0.865853658537
我正在尝试使用提供最高准确度的索引更新 zeros 数组。如您所见,它应该是索引 25,然后我将 25 索引分配给我的数组等于 1。但是,当我打印数组时,它显示每个索引都已更新为 1。
不确定发生了什么事故。感谢您在地球上花费有限的时间来帮助我。
将 trial_features = best_features
更改为 trial_features = numpy.copy(best_features)
。 @Michael Butscher 已经给出了更改背后的原因。