使用numpy转置矢量

Ale*_*ame 12 transpose numpy ipython

我遇到了Ipython的问题 - Numpy.我想做以下操作:

x^T.x
Run Code Online (Sandbox Code Playgroud)

x属于R ^ n,x ^ T是向量x上的转置操作.使用以下指令从txt文件中提取x:

x = np.loadtxt('myfile.txt')
Run Code Online (Sandbox Code Playgroud)

问题是,如果我使用转置功能

np.transpose(x)
Run Code Online (Sandbox Code Playgroud)

并使用形状函数来知道x的大小,我得到x和x ^ T的相同尺寸.Numpy在每个尺寸后给出大小为L大写的指示.例如

print x.shape
print np.transpose(x).shape

(3L, 5L)
(3L, 5L)
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这个问题,并将x ^ Tx计算为矩阵乘积?

谢谢!

Jai*_*ime 29

什么np.transpose是反转形状元组,即你给它一个形状的数组(m, n),它返回一个形状的数组(n, m),你给它一个形状的数组(n,)......然后它返回相同的数组形状(n,).

你暗中期待的是numpy将你的一维矢量作为一个二维形状的数组(1, n),将被转换成一个(n, 1)矢量.Numpy不会自己做,但你可以告诉它你想要的,例如:

>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> a.T
array([0, 1, 2, 3])
>>> a[np.newaxis, :].T
array([[0],
       [1],
       [2],
       [3]])
Run Code Online (Sandbox Code Playgroud)


Nat*_*han 7

正如其他人所解释的那样,换位不会像你想要的那样"工作"一维阵列.您可能希望使用np.atleast_2d一致的标量产品定义:

def vprod(x):
    y = np.atleast_2d(x)
    return np.dot(y.T, y)
Run Code Online (Sandbox Code Playgroud)


dav*_*vid 5

我有同样的问题,我用 numpy 矩阵来解决它:

# assuming x is a list or a numpy 1d-array 
>>> x = [1,2,3,4,5]

# convert it to a numpy matrix
>>> x = np.matrix(x)
>>> x
matrix([[1, 2, 3, 4, 5]])

# take the transpose of x
>>> x.T
matrix([[1],
        [2],
        [3],
        [4],
        [5]])

# use * for the matrix product
>>> x*x.T
matrix([[55]])
>>> (x*x.T)[0,0]
55

>>> x.T*x
matrix([[ 1,  2,  3,  4,  5],
        [ 2,  4,  6,  8, 10],
        [ 3,  6,  9, 12, 15],
        [ 4,  8, 12, 16, 20],
        [ 5, 10, 15, 20, 25]])
Run Code Online (Sandbox Code Playgroud)

虽然从编码的角度来看,使用 numpy 矩阵可能不是表示数据的最佳方式,但如果您要进行大量矩阵运算,那就太好了!