Home > Net >  How to assign a tensor in Tensorflow like Pytorch?
How to assign a tensor in Tensorflow like Pytorch?

Time:06-28

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

CodePudding user response:

Maybe something like this:

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)>

CodePudding user response:

This simplified code removes your error. Did you mean to use pytorch too ?

import tensorflow as tf

p = tf.constant([1])
t = tf.constant([2])
n = tf.constant([2])

def true_positive(pred, target, num_classes): #number of classes
    out = []
    for i in tf.range(num_classes):
        out.append(((pred == i) & (target == i)))
        print(out)
y = true_positive(p,t,n)
  • Related