给定python中的二维数组,我想用以下规范标准化每一行:
我已经启动了这段代码:
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) 可以将类实例变量分配给方法内的局部变量,例如:
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?