小编har*_*les的帖子

规范化矩阵python的行

给定python中的二维数组,我想用以下规范标准化每一行:

  • 规范1:L_1
  • 规范2:L_2
  • Norm Inf:L_Inf

我已经启动了这段代码:

from numpy import linalg as LA
X = np.array([[1, 2, 3, 6],
              [4, 5, 6, 5],
              [1, 2, 5, 5],
              [4, 5,10,25],
              [5, 2,10,25]])

print X.shape
x = np.array([LA.norm(v,ord=1) for v in X])
print x
Run Code Online (Sandbox Code Playgroud)

输出:

   (5, 4)             # array dimension
   [12 20 13 44 42]   # L1 on each Row
Run Code Online (Sandbox Code Playgroud)

如何修改代码,使得不使用LOOP,我可以直接将矩阵的行规范化?(鉴于上面的标准值)

我试过了 :

 l1 = X.sum(axis=1)

 print l1
 print X/l1.reshape(5,1)

 [12 20 13 44 42]
 [[0 0 0 0]
 [0 …
Run Code Online (Sandbox Code Playgroud)

python numpy python-2.x

4
推荐指数
2
解决办法
2万
查看次数

将类实例变量分配给 Python 方法中的局部变量

可以将类实例变量分配给方法内的局部变量,例如:

class Foo(object):
    def __init__(self):
        self.bar = 'bar'

    def baz(self):
        # assign instance variable to local variable with a method
        bar = self.bar

        # do work with local variable
        bar = "qux"

        # update value of instance variable
        self.bar = bar
        return self
Run Code Online (Sandbox Code Playgroud)

通过这样做,人们可以参考bar而不是self.bar在 的范围内Foo.baz()

这样做是错误的还是Unpythonic?

python oop python-3.x

1
推荐指数
1
解决办法
1201
查看次数

标签 统计

python ×2

numpy ×1

oop ×1

python-2.x ×1

python-3.x ×1