[英]TypeError: only length-1 arrays can be converted to Python scalars with NUMPY
[英]How to sort a numpy tuple without an error about only length-1 arrays can be converted to python scalars
我正在使用numpy來生成特征向量和特征值。 當形成它們的元組並嘗試對這些對進行分類時會出現問題。 我收到錯誤消息:TypeError:只有length-1數組可以轉換為python標量。
這是代碼:
import numpy as np
import pandas as pd
df=\
pd.read_csv(r'C:\Users\james\Desktop\Documents\Downloads\bpAFTPosWords.csv'
#df.head()
#Drop columns whose sum is less than 30
df.sum(axis = 0, skipna = True)
df_to_save = df.loc[:, (df.sum(axis=0, skipna=True) >= 30)]
#df_to_save.head()
#Standardize the data
from sklearn.preprocessing import StandardScaler
X_std = StandardScaler().fit_transform(df_to_save)
#Compute correlations
cor_mat1 = np.corrcoef(X_std.T)
#Produce PCA eigenvector and eigenvalues
eig_vals, eig_vecs = np.linalg.eig(cor_mat1)
#print('Eigenvectors \n%s' %eig_vecs)
#print('\nEigenvalues \n%s' %eig_vals)
# Make a list of (eigenvalue, eigenvector) tuples
eig_pairs = np.array(list(zip(eig_vals,eig_vecs)))
eig_pairs = eig_pairs[
eig_pairs[:,0].argsort()[::-1]]
# Visually confirm that the list is correctly sorted by decreasing
print('Eigenvalues in descending order:')
for i in eig_pairs:
print(i[0])
#Here is the context for the error:
TypeError Traceback (most recent call last)
<ipython-input-7-2342d13b7710> in <module>
21
22 # Make a list of (eigenvalue, eigenvector) tuples
---> 23 eig_pairs = np.array(list(zip(eig_vals,eig_vecs)))
24
25 eig_pairs = eig_pairs[
TypeError: only length-1 arrays can be converted to Python scalars
如果我的數據有助於你解決問題,這里是.csv文件:
https://docs.google.com/spreadsheets/d/1GRPbfHHB1mbO5Eo26B6crTl7FN1cNnLoU-oRQCEu7v8/edit?usp=sharing
我的第二個問題是如何輸出每個特征向量上每行的加載到文件。 還沒有能夠通過谷歌搜索和文檔來解決這個問題。
謝謝你的幫助!
我無法重現您的錯誤,但這是基於numpy排序的解決方案。
import numpy as np
X_std = np.random.random((8,8))
cor_mat1 = np.corrcoef(X_std.T)
eig_vals, eig_vecs = np.linalg.eig(cor_mat1)
print('Eigenvectors \n%s' %eig_vecs)
print('\nEigenvalues \n%s' %eig_vals)
# Make a list of (eigenvalue, eigenvector) tuples
eig_pairs = np.array(list(zip(eig_vals,eig_vecs)))
eig_pairs = eig_pairs[
eig_pairs[:,0].argsort()[::-1]
]
# Visually confirm that the list is correctly sorted by decreasing
print('Eigenvalues in descending order:')
for i in eig_pairs:
print(i[0])
在這里你可以閱讀有關 zip
功能的內容, 這里有關 argsort
希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.