После полудня. У меня проблемы с моим сценарием. В частности, я хотел бы сохранить сингулярные значения и соответствующие им собственные векторы, когда сумма подмножества собственных значений больше, чем 0,9 * сумма всех собственных значений. До сих пор мне удавалось использовать цикл for и функцию добавления, которая создает список кортежей, представляющих сингулярные значения и собственные векторы. Однако, когда я пытаюсь вложить оператор if в цикл for, чтобы выполнить условие, я его нарушаю. вот мой код.
o = np.genfromtxt (r"C:\Users\Python\Desktop\PCADUMMYDATADUMP.csv", delimiter=",")
o_m=np.matrix(o)
#We define the covariance matrix of our data accordingly This is the mean centered data approx
#of the covariance matrix.
def covariance_matrix(x):
#create the mean centered data matrix. this is the data matrix minus the matrix augmented from the vector that represents the column average
m_c_d=x-np.repeat(np.mean(x, axis=0,), len(x), axis=0)
#we compute the matrix operations here
m_c_c=np.multiply(1/((len(m_c_d)-1)),np.transpose(m_c_d)*m_c_d)
return m_c_c
#Define the correlation matrix for our mean adjsuted data matrix
def correlation_matrix(x):
C_M = covariance_matrix(x)
#matrix operation is diagonal(covariance_matrix)^-1/2*(covaraince_matrix)*diagonal(covariance_matrix)^-1/2
c_m=fractional_matrix_power(np.diag(np.diag(C_M)),-1/2)*C_M*fractional_matrix_power(np.diag(np.diag(C_M)),-1/2)
return c_m
def s_v_d(x):
C_M=covariance_matrix(x)
#create arrays that hold the left singular vectors(u), the right singular vectors(v), and the singular values (s)
u,s,v=np.linalg.svd(C_M)
#not sure if we should keep this here but this is how we can grab the eigenvalues which are the sqares of the singular values
eigenvalues=np.square(s)
singular_array=[]
for i in range(0,len(s)-1):
if np.sum(singular_array,axis=1) < (.9*np.sum(s)):
singular_pairs=[s[i],v[:,i]]
singular_array.append(singular_pairs)
else:
break
return np.sum(s,axis=0)
в частности, рассмотрите цикл for и if после single[array]. Спасибо!