[英]How to assign a tensor in Tensorflow like Pytorch?
我正在尝试将 Pytorch 脚本转换为 Tensorflow 脚本。 但我无法像 pytorch 一样在 tensorflow 中分配张量。
代码:
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)
TensorFlow 实现:不工作!
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 Traceback (最近一次调用最后一次) 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)
文件 ~/opt/anaconda3/lib/python3.9/site-packages/tensorflow/python/framework/ops.py:1131,在 _EagerTensorBase 中。 index (self) 1130 def index (self): -> 1131 return self._numpy()。 索引()
TypeError:只有整数标量数组可以转换为标量索引
也许是这样的:
import tensorflow as tf
def true_positive(pred, target, num_classes): #number of classes
out = []
for i in tf.range(num_classes):
out.append(tf.reduce_sum(tf.cast((pred == i) & (target == i), dtype=tf.int32)))
return tf.stack(out)
p = tf.constant([4]) #c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
t = tf.constant([4])
n = tf.constant([4])
y = true_positive(p,t,n)
y
# <tf.Tensor: shape=(4,), dtype=int32, numpy=array([0, 0, 0, 0], dtype=int32)>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.