【发布时间】:2020-03-19 06:09:32
【问题描述】:
我是 pytorch 的新手。我试图通过计算绝对和相对距离并将它们连接起来来实现自定义损失函数。
def distance(p1, p2,labels):
"""
Returns the distance between the point sets p1 and p2
p1 = m by d matrix containing a set of points
p2 = m by d matrix containing a different set of points
returns: an m-length vector containing the distance from each point in
p1 to the corresponding point in p2
"""
if not np.all(p1.shape == p2.shape):
raise ValueError("p1 and p2 must be the same shape.")
d = p1.shape[1]
features = np.zeros(dtype=np.float32, shape=(p1.shape[0], d * 2))
features[:, :d] = np.abs(p1 - p2)
features[:, d:] = (p1 + p2) / 2
return features
当我尝试运行它时出现问题并且我得到以下错误:
文件“...第 34 行,远处
features[:, :d] = np.abs(p1 - p2)
文件“...\Anaconda2\envs\tensorflow_gpuenv\lib\site-packages\tensorflow\python\util\dispatch.py”,第 180 行,在包装器中 返回目标(*args, **kwargs)
文件“...\lib\site-packages\tensorflow\python\ops\math_ops.py”,第 266 行,abs x = ops.convert_to_tensor(x, name="x")
文件“...\lib\site-packages\tensorflow\python\framework\ops.py”,第 1087 行,在 convert_to_tensor 中 return convert_to_tensor_v2(value, dtype, preferred_dtype, name)
RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
【问题讨论】:
-
你在混合使用 tensorflow 和 pytorch 吗?
-
我是 pytorch 新手,如果有什么可以纠正我的话
-
Pytorch 和 Tensorflow 是两个完全不同的东西。它们不能混合。您必须在 Pytorch 的帮助和文档中搜索您想要的功能。它与带有自定义训练循环的 Tensorflow 的 Eager 模式非常相似,并且模型的创建类似于新的 keras“子类化”样式。学起来不会很难,但是如果你用 PyTorch,你就只能用 PyTorch。
-
所以我要纠正这个问题...你能帮帮我吗?
-
只使用pytorch函数,不要使用numpy函数,不要使用tensorflow函数。