【问题标题】:Python: PCA issue with data analysisPython:数据分析的 PCA 问题
【发布时间】:2020-04-13 10:27:26
【问题描述】:

我正在尝试使用 PCA sklearn 包进行一些数据分析。我目前遇到的问题是我的代码分析数据的方式。

部分数据示例如下

波长强度 ; [嗯] [W/m**2/um/sr] 196.078431372549 1.108370393265022E-003 192.307692307692 1.163428008597600E-003 188.679245283019 1.223639983609668E-003

目前编写的代码如下:

scaler = StandardScaler(with_mean=True, with_std=True) #scales the data

data_crescent=ascii.read('earth_crescent.dat',data_start=4958, data_end=13300, delimiter=' ')#where the data is being read


#where each variable comes from in the dat 
y_intensity_crescent=data_crescent['col2'][:]
x_wave_crescent=data_crescent['col1'][:]

standard_y_crescent=StandardScaler().fit_transform(y_intensity_crescent)#standardizing the intensity variable

#PCA runthrough of data 
pca= PCA(n_components=2)
principalCrescentY=pca.fit_transform(standard_y_crescent)
principalDfcrescent = pd.DataFrame(data = principalCrescentY
             , columns = ['principal component 1', 'principal component 2'])



finalDfcrescent = pd.concat([principalDfcrescent, [y_intensity_crescent]], axis = 1)

一旦运行,数据就会产生这个错误:

    ValueError: Expected 2D array, got 1D array instead:

Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample

为了通过 PCA 分析数据,需要将数据转换为 2D 模型,以产生预期的结果。任何解决方法将不胜感激!

【问题讨论】:

    标签: python python-3.x scikit-learn ascii pca


    【解决方案1】:

    问题是您通过执行以下操作为您的 pca 对象提供了一个功能 y_intensity_crescentprincipalCrescentY=pca.fit_transform(standard_y_crescent)。实际上,您只为您的 pca 算法提供了一个维度。粗略地说:主成分分析采用多个特征时间序列,并将它们组合成组件,这些组件是特征的组合。如果您想要 2 个组件,则需要超过 1 个功能。

    以下是一些如何正确使用它的示例:PCA tutorial using sklearn

    【讨论】:

    • 你是对的。 X 只是一个向量。采用 2 个组件是没有意义的,因为甚至没有 2 个功能。请注意,您得到的错误是由于X 的形状造成的。它应该是二维数组,因此,您应该使用X.reshape(-1, 1) 来获得单个特征数组。但是您仍然会遇到前面提到的问题。请注意,您应该使用sklearn.pipeline.Pipeline 连接标准化和 PCA:transformer = make_pipeline(StandardScaler(), PCA()); transformer.fit_transform(X)
    • 是的,就是这样。此外,数据不一定需要标准化。感谢您的帮助。
    • @domryan 很高兴它有帮助!不要忘记接受其他用户的答案
    猜你喜欢
    • 2012-10-24
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 2012-07-24
    • 2017-04-09
    • 2013-03-28
    • 1970-01-01
    • 2012-09-23
    相关资源
    最近更新 更多