【问题标题】:TypeError: '(slice(None, None, None), array([ True, False, ... True, True]))' is an invalid keyTypeError: '(slice(None, None, None), array([ True, False, ... True, True]))' 是无效键
【发布时间】:2020-07-10 20:51:30
【问题描述】:

尝试使用 BPSO 进行特征选择,但出现类型错误:TypeError: '(slice(None, None, None), array([ True, False, False, True, False, False, False, True, True, 假,真,假,假,假,假,真,假,真, True, True]))' 是一个无效的键。

from sklearn import linear_model
classifier = linear_model.LogisticRegression()
def f_per_particle(m, alpha):
    total_features = 20
    if np.count_nonzero(m) == 0:
        X_subset = X
    else:
        X_subset = X[:,m==1]
    classifier.fit(X_subset, y)
    P = (classifier.predict(X_subset) == y).mean()
    # Compute for the objective function
    j = (alpha * (1.0 - P)
        + (1.0 - alpha) * (1 - (X_subset.shape[1] / total_features)))
    return j
def f(x, alpha=0.88):
    n_particles = x.shape[0]
    j = [f_per_particle(x[i], alpha) for i in range(n_particles)]
    return np.array(j)    
options = {'c1': 0.5, 'c2': 0.5, 'w':0.9, 'k': 30, 'p':2}
    dimensions = 20 # dimensions should be the number of features
    optimizer.reset()
    optimizer = ps.discrete.BinaryPSO(n_particles=30, dimensions=dimensions, options=options)
    cost, pos = optimizer.optimize(f, iters=1000)

我使用了“bank-additional-full data set”并进行了一些更改,例如清理数据或对分类字段的数据进行编码。

【问题讨论】:

标签: python machine-learning feature-selection particle-swarm


【解决方案1】:

在导入数据框后,您需要将数据框转换为 numpy 数组:


X = X.values

【讨论】:

    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 2020-03-19
    • 2019-09-11
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多