【问题标题】:Python numpy zeros array being assigned 1 for every value when only one index is updated当仅更新一个索引时,Python numpy zeros 数组为每个值分配 1
【发布时间】:2018-04-10 21:14:10
【问题描述】:

以下是我的代码:

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,然后我通过为数组分配等于 1 的 25 索引来遵循这一点。但是,当我打印数组时,它显示每个索引都已更新为 1。

不知道发生了什么意外。感谢您在地球上花费有限的时间来帮助我。

【问题讨论】:

  • trial_features = best_features 仅复制对创建的 numpy 数组的引用,因此对 trial_features 的更改也会发生在 best_features
  • 很有趣,谢谢

标签: python python-3.x numpy machine-learning svm


【解决方案1】:

trial_features = best_features 更改为trial_features = numpy.copy(best_features)。 @Michael Butscher 已经给出了更改背后的原因。

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 2020-10-27
    • 1970-01-01
    • 2018-07-01
    • 2022-11-07
    • 2018-10-25
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多