如何在像Pytorch这样的张量流中分配张量?
我正在尝试将Pytorch脚本转换为TensorFlow脚本。但是我无法像pytorch这样的张量张量分配张量。
代码:
import torch
import tensorflow as tf
def true_positive(pred, target, num_classes): #number of classes
out = []
for i in range(num_classes):
out.append(((pred == i) & (target == i)).sum())
return torch.tensor(out)
pytorch实现:工作
p = torch.tensor([1])
t = torch.tensor([2])
n = torch.tensor([2])
y = true_positive(p,t,n)
张量集实现:不起作用!
p = tf.constant([1]) #c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
t = tf.constant([2])
n = tf.constant([2])
y = true_positive(p,t,n)
错误:
---------------------------------------------------------------------- ----------------------------------- typeError Trackback(最近的电话 最后)输入[18],in<单元线:22>() 20 t = tf.constant([2]) 21 n = tf.constant([2]) ---> 22 y = true_positive(p,t,n)
在[18]中输入true_positive(pred,target,num_classes) 5 def true_positive(pred,target,num_classes):#of类 6 out = [] ----> 7对于i在范围内(num_classes): 8 out.append(((((pred == i)&(target == i))。sum()) 10返回火炬。感动(OUT)
文件 〜/opt/anaconda3/lib/python3.9/site-ackages/tensorflow/python/framework/ops.py:1131, 在_eagertenSorbase中。索引(self)1130 def index (self): - > 1131返回self._numpy()。 index ()
TypeError:只有整数标量阵列可以转换为标量 索引
I am trying to convert a Pytorch script into a Tensorflow script. But I am unable to assign a tensor in tensorflow like pytorch.
Code:
import torch
import tensorflow as tf
def true_positive(pred, target, num_classes): #number of classes
out = []
for i in range(num_classes):
out.append(((pred == i) & (target == i)).sum())
return torch.tensor(out)
Pytorch implementation: Working
p = torch.tensor([1])
t = torch.tensor([2])
n = torch.tensor([2])
y = true_positive(p,t,n)
Tensorflow implementation: Not working!
p = tf.constant([1]) #c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
t = tf.constant([2])
n = tf.constant([2])
y = true_positive(p,t,n)
Error :
--------------------------------------------------------------------------- TypeError Traceback (most recent call
last) Input In [18], in <cell line: 22>()
20 t = tf.constant([2])
21 n = tf.constant([2])
---> 22 y = true_positive(p,t,n)Input In [18], in true_positive(pred, target, num_classes)
5 def true_positive(pred, target, num_classes): #number of classes
6 out = []
----> 7 for i in range(num_classes):
8 out.append(((pred == i) & (target == i)).sum())
10 return torch.tensor(out)File
~/opt/anaconda3/lib/python3.9/site-packages/tensorflow/python/framework/ops.py:1131,
in _EagerTensorBase.index(self) 1130 def index(self):
-> 1131 return self._numpy().index()TypeError: only integer scalar arrays can be converted to a scalar
index
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许这样的东西:
Maybe something like this: