PCA:结果矩阵 n-1 行
PCA: resultant matrix n-1 rows
我在 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
.
明确提供这些标题,则它默认使用 文件的第一行 作为列标题
因此,如果您不想将文件的第一行用作列 headers,您应该像这样在 read_csv() 中传递 header = None
:
demo_df = pd.read_csv('data.csv', header = None)
我在 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
.
因此,如果您不想将文件的第一行用作列 headers,您应该像这样在 read_csv() 中传递 header = None
:
demo_df = pd.read_csv('data.csv', header = None)