Numpy实现大矩阵减去小矩阵的方便运算

把一个向量加到矩阵的每一行:
调用numpy库
完成cs231作业1,numpy

参考知乎CS231n课程笔记翻译:Python Numpy教程

使用一重循环

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
import numpy as np
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x)   # Create an empty matrix with the same shape as x

# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
    y[i, :] = x[i, :] + v

# Now y is the following
# [[ 2  2  4]
#  [ 5  5  7]
#  [ 8  8 10]
#  [11 11 13]]
print y

使用二重循环就是有点没必要了

但是要是大矩阵减去小矩阵还是可以用的,速度偏慢就是了

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x)   # Create an empty matrix with the same shape as x

# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
	for j in range(4)
   		 y[i, j] = x[i, j] + v[j]

# Now y is the following
# [[ 2  2  4]
#  [ 5  5  7]
#  [ 8  8 10]
#  [11 11 13]]

不使用循环,使用了numpy的广播机制

>> a = np.arange(15).reshape(3,5)
>> print(a)
array([[ 0,  1,  2,  3,  4],
      [ 5,  6,  7,  8,  9],
      [10, 11, 12, 13, 14]])
>> b = np.arange(5)
>> print(b)
array([0, 1, 2, 3, 4])
>> a-b
array([[ 0,  0,  0,  0,  0],
      [ 5,  5,  5,  5,  5],
      [10, 10, 10, 10, 10]])
>>> b
array([0, 1, 2, 3, 4])
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
#使用过后a,b的大小没有变换

还可以创建一个新的数组,使用numpy 的tile可以实现数组的叠加

np.tile(x,y)
x表示纵向的叠加,y表示横向的复制

import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other
print vv                 # Prints "[[1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]]"
y = x + vv  # Add x and vv elementwise
print y  # Prints "[[ 2  2  4
         #          [ 5  5  7]
         #          [ 8  8 10]
         #          [11 11 13]]"

你可能感兴趣的:(numpy,python)