Python 张量流函数中的随机整数

Python 张量流函数中的随机整数,python,tensorflow,Python,Tensorflow,我想用一个普通的python函数获得一个随机整数来生成一个合成的tensorflow数据集。如果我使用numpy,那么对于数据集中的所有迭代,我只得到一个常量。当我使用tensorflow函数时,我得到了一个我的函数不接受的张量,我似乎无法将它转换为一个普通的python整数,我可以将它用作函数的输入。我做错了什么 @tf.function def number(_): #not working x,y = np.random.randint(2,100,size=2)

我想用一个普通的python函数获得一个随机整数来生成一个合成的tensorflow数据集。如果我使用numpy,那么对于数据集中的所有迭代,我只得到一个常量。当我使用tensorflow函数时,我得到了一个我的函数不接受的张量,我似乎无法将它转换为一个普通的python整数,我可以将它用作函数的输入。我做错了什么


@tf.function
def number(_):
    #not working
    x,y = np.random.randint(2,100,size=2)
    #x,y = tf.random.uniform((2,0),minval=0,maxval=0,dtype=tf.int32)#.numpy() also not working
    #x = tf.random.uniform(shape=(), minval=1, maxval=5, dtype=tf.int32)
    #x,y = tf.experimental.numpy.random.randint(2,100)
    string = f'Image with {x} cats and {x+y} dogs'
    return(string)

import numpy as np
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices(list(range(10)))
dataset = dataset.map(number)
for label in dataset.take(5):
    print(label)
输出:

tf.Tensor(b'Image with 21 cats and 59 dogs', shape=(), dtype=string)
tf.Tensor(b'Image with 21 cats and 59 dogs', shape=(), dtype=string)
tf.Tensor(b'Image with 21 cats and 59 dogs', shape=(), dtype=string)
tf.Tensor(b'Image with 21 cats and 59 dogs', shape=(), dtype=string)
tf.Tensor(b'Image with 21 cats and 59 dogs', shape=(), dtype=string)
像这样的

import numpy as np
import tensorflow as tf

@tf.function
def number(_):
    noise = tf.random.uniform(shape=(), minval=1, maxval=20)
    return int(noise)

dataset = tf.data.Dataset.from_tensor_slices(list(range(10)))
dataset = dataset.map(number)
for label in dataset.take(5):
    print(label.numpy())

11
7
3
19
8

你的问题我不清楚。基本上你想要什么?在我用numpy的输出中,你可以看到我没有得到随机数。每次函数映射到datasethanks时,我想得到一个不同的随机数。hanks不知道你可以把它变成这样的int。同时我还发现了tf.py_函数。我将尝试两种方法