我不断收到 LinAlgError 消息,指出特征值没有收敛。当我将 x_mean 值的类型更改为 float 时出现此错误,但是当该值未设置为 float 时,我会收到一条错误消息,指出“float”对象没有属性“shape”。我的代码还有其他问题吗?我是否应该将 x_mean 值更改为不同的值?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Read data file
data = pd.read_csv(r"Data.csv", names = ['length',
'width',
'petal length',
'petal width',
'target'])
def iris_PCA(X, num_dimensions):
#calculate the mean for the values
x_mean = data_iris - np.mean(data_iris, axis = 0)
#calculate the covariance matrix
cov_x = np.cov(x_mean.astype(float), rowvar = False)
#calculate the eigenvalues and vectors based on the covariance found
e_values = np.linalg.eigh(cov_x)
e_vectors = np.linalg.eigh(cov_x)
#sorting the eigenvectors in descending order
sorted_index = np.argsor(e_values)[::-1]
sorted_e_values = e_values[sorted_index]
sorted_e_vectors = e_values[sorted_index]
e_subset = sorted_e_vectors[:,0:num_dimensions]
#perform dot product to reduce data to lowered dimensions
reduced_x = np.dot(e_subset.transpose(), x_mean.transpose()).transpose()
return reduced_x
x = data_iris.iloc[:,0:4]
target = data_iris.iloc[:,4]
#displaying the results in the 3rd dimension
reduced_x3 = iris_PCA(x,3)
PCA_df = pd.DataFrame(reduced_x3, columns = ['PCA1', 'PCA2', 'PCA3'])
PCA_df = pd.concat([PCA_df, pd.DataFrame(target)],axis = 1)
plt.figure(figsize = (6,6))