np.c_
是做阵列的另一种方式串联
In [701]: np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
Out[701]: array([[1, 2, 3, 0, 0, 4, 5, 6]])
In [702]: np.concatenate([np.array([[1,2,3]]), [[0]], [[0]], np.array([[4,5,6]])],
axis=1)
Out[702]: array([[1, 2, 3, 0, 0, 4, 5, 6]])
输出形状是在两种情况下(1,8);级联在轴= 1上,第二轴。
c_
负责将0
的尺寸扩展到np.array([[0]])
,2d(1,1)需要连接。
np.c_
(和np.r_
)实际上是一个带有__getitem__
方法的类对象,因此它可以与[]
语法一起使用。 numpy/lib/index_tricks.py
源文件是有教育意义的阅读。
注意,row
版本的作品与:切片语法,产生1D(8)阵列(相同的数字,但在1D)
In [706]: np.r_[1:4,0,0,4:7]
Out[706]: array([1, 2, 3, 0, 0, 4, 5, 6])
In [708]: np.concatenate((np.arange(4),[0],[0],np.arange(4,7)))
Out[708]: array([0, 1, 2, 3, 0, 0, 4, 5, 6])
In [710]: np.hstack((np.arange(4),0,0,np.arange(4,7)))
Out[710]: array([0, 1, 2, 3, 0, 0, 4, 5, 6])
np.c_
是一个方便的,但你必须不是了解。我认为能够直接使用concatenate
更有用。它迫使你明确地思考输入的维度。
[[1,2,3]]
实际上是一个列表 - 一个包含一个列表的列表。 np.array([[1,2,3]])
是一个具有形状(1,3)的二维数组。 np.arange(1,4)
产生一个具有相同数字的(3,)数组。 np.arange(1,4)[None,:]
使其成为(1,3)阵列。
slice(1,4)
是切片对象。 np.r_
和np.c_
可以将切片对象转换为数组 - 通过实际使用np.arange
。
In [713]: slice(1,4)
Out[713]: slice(1, 4, None)
In [714]: np.r_[slice(1,4)]
Out[714]: array([1, 2, 3])
In [715]: np.c_[slice(1,4)] # (3,1) array
Out[715]:
array([[1],
[2],
[3]])
In [716]: np.c_[1:4] # equivalent with the : notation
Out[716]:
array([[1],
[2],
[3]])
而且要回到最初的例子(这可能不是最好的):
In [722]: np.c_[[np.r_[1:4]],0,0,[np.r_[4:7]]]
Out[722]: array([[1, 2, 3, 0, 0, 4, 5, 6]])
==========
In [731]: np.c_[np.ones((5,3)),np.random.randn(5,10)].shape
Out[731]: (5, 13)
对于np.c_
两者的第一维需要匹配。
在learn
示例中,n_samples
是X
(行)的第1个dim,而randn
也需要有那么多行。
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
np.concatenate([(X, randn(n_samples...)], axis=1)
应该在这里工作。有点话语,但在功能上是相同的。
谢谢hpaulj,很好的答复和投票。其实我的困惑来自这个例子,参考这一行'X = np.c_ [X,random_state.randn(n_samples,200 * n_features)]',实际上X的形状是150 * 4,但是'random_state.randn'会生成一些标量随机数落入正态分布,如何将它们连接在一起,我认为为了与X连接,我们需要150 * some_number_of_columns的形状,是正确的吗? http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html#multiclass-settings –
对,'n_samples'是'X'的第一个维度,所以它们将在正确的维度上匹配。 'X'和'randn'的列数可以不同。 – hpaulj
谢谢hpaulj,我觉得X是150 * 4形状,怎么能'random_state.randn(n_samples,200 * n_features)'输出150 * 4形状?我知道'n_samples'是150,但是从哪里来的? –