numpy np.c_返回行向量,而不是列

zengzsys  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(99)

我想写一个线性/多项式回归。
我正试图手工设计我的三阶多项式特征,而不是使用scikit-learn。
我已经从CSV文件导入数据并将此数据转换为行向量。现在我尝试创建一个三列矩阵(原始特征,特征平方,特征立方)。
我希望使用numpy.c_来实现这一点,但是我没有创建一个三列的矩阵,而是得到了一个(非常)长的行向量。
截图说明了我正在尝试做什么,以及我希望它如何表现(带有x和X的简短部分),以及它正在做什么(带有弗朗西斯_guide_vane_pos和francis_[...]_engineered的部分)我正在使用Python v。3.11.4

# what I expected to happen
x = np.arange(0,20,1)
X = np.c_[x, x**2, x**3]
print(x, x.shape)
print(X, X.shape)

# what is actually happning
francis_guide_vane_pos_engineered = np.c_[francis_guide_vane_pos, francis_guide_vane_pos**2, francis_guide_vane_pos**3]
print(francis_guide_vane_pos, francis_guide_vane_pos.shape)
print(francis_guide_vane_pos_engineered, francis_guide_vane_pos_engineered.shape)

测试结果:

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19] (20,)
[[   0    0    0]
 [   1    1    1]
 [   2    4    8]
 [   3    9   27]
 [   4   16   64]
 [   5   25  125]
 [   6   36  216]
 [   7   49  343]
 [   8   64  512]
 [   9   81  729]
 [  10  100 1000]
 [  11  121 1331]
 [  12  144 1728]
 [  13  169 2197]
 [  14  196 2744]
 [  15  225 3375]
 [  16  256 4096]
 [  17  289 4913]
 [  18  324 5832]
 [  19  361 6859]] (20, 3)

[[89.8 89.8 89.7 ... 14.8 14.8 14.8]] (1, 286996)
[[  89.8     89.8     89.7   ... 3241.792 3241.792 3241.792]] (1, 860988)

Screenshot of expected result and achieved result

7kqas0il

7kqas0il1#

请注意,在第一个示例中,x是一个一维数组,形状为(20,)。您可以使用np.c_将它们堆叠以获得(20, 3)数组。
在第二种情况下,francis_guide_vane_pos是形状为(1, 286996)二维数组。要将其堆叠为列,首先将数组转置,或者将squeeze it转换为一维数组:

>>> arr = np.c_[francis_guide_vane_pos.T, francis_guide_vane_pos.T**2, francis_guide_vane_pos.T**3]
>>> print(arr.shape) # (286996, 3)

>>> francis_guide_vane_pos = francis_guide_vane_pos.squeeze()
>>> arr = np.c_[francis_guide_vane_pos, francis_guide_vane_pos**2, francis_guide_vane_pos**3]
>>> print(arr.shape) # (286996, 3)

为什么堆叠二维数组会给予 “错误” 的结果?

根据docs for np.c_
阵列将在升级到至少2-D并将1后置到形状后,沿其最后一个轴沿着堆叠
由于francis_guide_vane_pos(以及它的元素级正方形和立方体数组)已经是二维的,它们只是沿着最后一个轴沿着堆叠,即添加了更多列。

相关问题