gpt4 book ai didi

python - PCA:结果矩阵 n-1 行

转载 作者:行者123 更新时间:2023-11-30 08:54:09 25 4
gpt4 key购买 nike

我在 Python 中使用 PCA 来降低我所拥有的数据的维度。当前数据有768行10列。

我使用以下代码来实现 PCA:

import numpy as np
from sklearn import decomposition

demo_df = pd.read_csv('data.csv')
pca = decomposition.PCA(n_components=4)

comps = pca.fit(demo_df).transform(demo_df)

np.savetxt('data_reduced.csv', comps, delimiter=',')

根据我的理解,生成的文件应包含 768 行和 4 列(因为 n_components =4)。

但结果数据有 n-1 行,即 767 行。

为什么数据中缺少一行?

最佳答案

是的,您的理解是正确的。但在将 demo_df 传递给 PCA 之前检查它的形状。它的长度必须为 767。PCA 不会从您的数据中删除任何样本。

差异源于 read_csv() 的使用。请查看documentation of pandas.read_csv() 。它有一个参数header,其描述如下:

header : int or list of ints, default ‘infer’

Row number(s) to use as the column names, and the start of the data. Default behavior is as if set to 0 if no names passed, otherwise None. Explicitly pass header=0 to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if skip_blank_lines=True, so header=0 denotes the first line of data rather than the first line of the file.

如果未使用另一个参数 names 显式提供这些标题,则默认情况下使用文件第一行作为列标题。

因此,如果您不想使用文件的第一行作为列标题,则应该在 read_csv() 中传递 header = None,如下所示:

demo_df = pd.read_csv('data.csv', header = None)

关于python - PCA:结果矩阵 n-1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com