#Função que permitirá rankear as features mais importantes em um barhplot
def ranks_PCA (x_train, y_train, features_train, RESULT_PATH='Results'):
    print("\nMétodo PCA")

    pca = PCA(n_components=58)

    imp_array = np.array(pca.components_)
    imp_order = imp_array.argsort()
    ranks = imp_order.argsort()

    # Plot PCA
    imp = pd.Series(pca.components_, index=x_train.columns)
    imp = imp.sort_values()

    plt.title("Feature importance using PCA")
    # plt.show()
    plt.savefig(RESULT_PATH + '/ranks_DT.png', bbox_inches='tight')

    return ranks

#Função para predição das features dos dados de teste
def predict_PCA(x_test_sel, k_vetor, y_train):
    model = decomposition.PCA()
    model.fit(k_vetor, y_train)
    y_predict = model.predict(x_test_sel)

#Função que calcula o ranking dos dados de treinamento
ranks4 = frk.ranks_PCA(x_train, y_train, features_train, RESULT_PATH)

I have doubts if this implementation is correct to obtain more important features. When trying to run this code, I get the following error:

Traceback (most recent call last): File "feat_test.py", line 235, in 'Results/PDBbind2018_F58_Delta_pKd') File "feat_test.py", line 78, in run_experiment ranks4 = frk.ranks_PCA(x_train, y_train, features_train, RESULT_PATH) File "C:\Users\Patricia\Desktop\VT-58 - Cópia\feature-importance\feature_rank_ ensemble\Scripts\feature_ranks.py", line 121, in ranks_PCA imp = pd.Series(pca.components_, index=x_train.columns) File "C:\Users\Patricia\Desktop\VT-58 - Cópia\feature-importance\feature_rank_ ensemble\env\lib\site-packages\pandas\core\series.py", line 305, in init data = sanitize_array(data, index, dtype, copy, raise_cast_failure=True) File "C:\Users\Patricia\Desktop\VT-58 - Cópia\feature-importance\feature_rank_ ensemble\env\lib\site-packages\pandas\core\construction.py", line 482, in saniti ze_array raise Exception("Data must be 1-dimensional")

Can anybody help me?


pca.components_ is a 2d array, so you cannot make a Series out of it.

  • $\begingroup$ simple answer but it really helped me to find the error, thank you very much. $\endgroup$ Mar 7 '20 at 1:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.