【问题标题】:what is the tensorflow equivalent for pytorch probability function: torch.bernoulli?pytorch 概率函数的等效张量流是什么:torch.bernoulli?
【发布时间】:2018-10-31 19:36:36
【问题描述】:

在 Pytorch 中,您可以执行以下操作:

x = torch.bernoulli(my_data)

张量流中有类似的功能吗?输入可以是二维张量,比如(batch, len)吗?

我试过 tensorflow.contrib.distributions.Bernoulli:

import numpy as np
tmp_x1 = np.random.rand(20,5) 
new_data_2 = tf.convert_to_tensor(tmp_x1)
from tensorflow.contrib.distributions import  Bernoulli
tmp2_x1 = Bernoulli(probs=new_data_2)

出现错误:

return math_ops.log(probs) - math_ops.log1p(-1. * probs), probs
TypeError: unsupported operand type(s) for *: 'float' and 'Tensor'

【问题讨论】:

    标签: python tensorflow pytorch


    【解决方案1】:

    看来tf.distributions.Bernoulli 可以满足您的需求。输入可以是 N-D 张量,其中包括 2D 张量。

    编辑:示例使用

    在您发表评论后,我尝试了以下对我有用的方法(使用 tensorflow 1.11):

    import numpy as np
    import tensorflow
    import tensorflow as tf
    from tensorflow.distributions import  Bernoulli
    
    tmp_x1 = np.random.rand(20,5)
    new_data_2 = tf.convert_to_tensor(tmp_x1)
    tmp2_x1 = Bernoulli(probs=new_data_2)
    sess = tf.Session()
    print sess.run(tmp2_x1.sample())
    

    【讨论】:

    • 我试过:import numpy as np tmp_x1 = np.random.rand(20,5) new_data = (1-0.1)*(tmp_x1*0.0 +1.0) print(new_data.shape[0] ) for i in range(new_data.shape[0]): one = np.random.randint(0, new_data.shape[1]-1) new_data[i][one] = 1 #new_data[i][one] = 1 new_data_2 = tf.convert_to_tensor(new_data) from tensorflow.contrib.distributions import Bernoulli tmp2_x1 = Bernoulli(probs=new_data_2)
    • error: return math_ops.log(probs) - math_ops.log1p(-1. * probs), probs TypeError: unsupported operand type(s) for *: 'float' and 'Tensor'跨度>
    • 不要在注释中放代码,不可读。相反,您可以在问题中修改并添加它。
    • @jimsha 我已经用一个工作示例更新了答案
    • Thnx Matt!,解决了我的问题,升级到 tf 版本 1.11 后可以使用
    猜你喜欢
    • 2021-03-16
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多