我正在寻找的是有这样的东西:
self.info['key'].attr2
Run Code Online (Sandbox Code Playgroud)
但我不确定实现它的最优雅的方式是什么。到目前为止,我已经定义了一个像下面这样的字典,但没有它的属性。
self.info = {}
self.info.update({'key':
{'attr1': 2,
'attr2': lambda: self.func(arg1)}
})
Run Code Online (Sandbox Code Playgroud)
但是我将不得不像这样使用它:
self.info['key']['attr2']()
Run Code Online (Sandbox Code Playgroud)
请注意,我正在寻找的是访问字典值(如属性)。这个线程有一个可以在我的情况下使用的答案,也可能是我从上面的子字典中创建一个对象并将其作为主字典的值。
但我想知道是否有更好的方法,也许使用装饰器和更少的代码行,甚至可能不使用字典来做我在第一行中描述的事情,也许更好:
self['key'].attr2
Run Code Online (Sandbox Code Playgroud) 我正在寻找通过 Pytorch 获取函数的雅可比行列式的最有效方法,并且到目前为止提出了以下解决方案:
# Setup
def func(X):
return torch.stack((X.pow(2).sum(1),
X.pow(3).sum(1),
X.pow(4).sum(1)),1)
X = Variable(torch.ones(1,int(1e5))*2.00094, requires_grad=True).cuda()
Run Code Online (Sandbox Code Playgroud)
# Solution 1:
t = time()
Y = func(X)
J = torch.zeros(3, int(1e5))
for i in range(3):
J[i] = grad(Y[0][i], X, create_graph=True, retain_graph=True, allow_unused=True)[0]
print(time()-t)
>>> Output: 0.002 s
Run Code Online (Sandbox Code Playgroud)
# Solution 2:
def Jacobian(f,X):
X_batch = Variable(X.repeat(3,1), requires_grad=True)
f(X_batch).backward(torch.eye(3).cuda(), retain_graph=True)
return X_batch.grad
t = time()
J2 = Jacobian(func,X)
print(time()-t)
>>> Output: 0.001 s
Run Code Online (Sandbox Code Playgroud)
由于在第一个解决方案中使用循环与在第二个解决方案中使用循环似乎没有太大区别,我想问一下是否还有更快的方法来计算 pytorch 中的雅可比行列式。
我的另一个问题也是关于什么可能是计算 Hessian 的最有效方法。
最后,有谁知道在 TensorFlow 中是否可以更轻松或更高效地完成此类操作?
如果我有一个包含以下脚本的 python 文件:
import pandas as pd
def csv():
r = pd.DataFrame([[1,2,3,6],[1,3,4,5]])
return r
csv()
Run Code Online (Sandbox Code Playgroud)
如何在 Jupyter Notebook 中使用 shell 命令来获取此脚本的输出(即 pandas DataFrame)。或者如何修改 python 脚本来执行此操作,但仍然在 Jupyter 中使用 shell 命令(出于某种原因,我需要一个 shell 命令,而不仅仅是从 python 文件导入函数并执行它)
到目前为止我尝试过以下内容,但没有成功(希望 Pandas DataFrame 作为输出)
import subprocess
result = subprocess.run(['python','MyPythonFile.py'], stdout=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)
或者
result = ! python MyPythonFile.py
Run Code Online (Sandbox Code Playgroud) 如何将以下两个渐变胶带合并为一个:
x = tf.Variable(x, dtype=tf.float32)
with tf.GradientTape() as t:
m, v = DGP.predict(x)
dm_dx = t.gradient(m, x)
with tf.GradientTape() as t:
m, v = DGP.predict(x)
dv_dx = t.gradient(v, x)
Run Code Online (Sandbox Code Playgroud)
这是我更喜欢的,但并不像我写的那样工作:
with tf.GradientTape() as t:
m, v = DGP.predict(x)
dm_dx, dv_dx = t.gradient([m,v], x)
Run Code Online (Sandbox Code Playgroud) python neural-network deep-learning tensorflow tensorflow2.0
我想要一个类似于 python 的函数的输入,这样我就可以在函数内部循环它。但我不确定应该如何定义输入。
func(["a","b","c"])
Run Code Online (Sandbox Code Playgroud)
这样它也可以被称为
func(["a","b","c", "d"])
Run Code Online (Sandbox Code Playgroud)
C++中真的有这种输入方式吗?如果有人也建议一种循环它的方法,我会很高兴,因为我的 C++ 经验非常基础。
- - - -编辑,
如果这种“[]”风格的括号可以代替“{}”,类似于Python并且代码最少,我们会很高兴。
python ×4
attributes ×1
c++ ×1
calculus ×1
command-line ×1
dictionary ×1
list ×1
properties ×1
pytorch ×1
shell ×1
tensorflow ×1
terminal ×1