困惑于numpy.c_文档和示例代码

Lin*_* Ma 5 python numpy machine-learning python-2.7

我多次阅读关于numpy.c_的文档,但仍然感到困惑.据说 - "将切片对象转换为沿第二轴的连接." 在以下文件中.有谁可以在下面的例子中澄清,什么是切片对象,什么是第二轴?我看到它们都是一个维度而且混淆了第二轴的来源.

在Windows上使用Python 2.7.

http://docs.scipy.org/doc/numpy-1.6.0/reference/generated/numpy.c_.html#numpy.c_

>>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
array([[1, 2, 3, 0, 0, 4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)

hpa*_*ulj 13

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]])
Run Code Online (Sandbox Code Playgroud)

两种情况下的输出形状均为(1,8); 串联在轴= 1,第二轴.

c_把扩大的尺寸的照顾0np.array([[0]]),所需的2D(1,1)来连接.

np.c_(和np.r_)实际上是一个带有__getitem__方法的类对象,因此它适用于[]语法.在numpy/lib/index_tricks.py源文件是指导性的阅读.

请注意,该row版本使用:slice语法,生成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])
Run Code Online (Sandbox Code Playgroud)

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]])
Run Code Online (Sandbox Code Playgroud)

并回到最初的例子(可能不是最好的):

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]])
Run Code Online (Sandbox Code Playgroud)

==========

In [731]: np.c_[np.ones((5,3)),np.random.randn(5,10)].shape
Out[731]: (5, 13)
Run Code Online (Sandbox Code Playgroud)

对于np.c_两个需要匹配的第一维度.

在这个learn例子中,n_samplesX(行)的第一个暗淡,并且randn还需要有那么多行.

n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
Run Code Online (Sandbox Code Playgroud)

np.concatenate([(X, randn(n_samples...)], axis=1)应该在这里工作得很好.有点讽刺,但功能相同.