python - 随机变量的运算在 Tensorflow 中无法正常工作

标签 python tensorflow

我创建了两个张量(即:x1,y2),它们以均匀分布初始化,但是当我打印出结果时,它们不是我所期望的。

这是我的代码:

x1 = tf.random_uniform([1], 0, 10, tf.int32)
y1 = tf.random_uniform([1], 0, 10, tf.int32)

subtraction = x1 - y1

with tf.Session() as sess:

    print(sess.run(x1))
    print(sess.run(y1))
    print(sess.run(subtraction))

这是结果:

[6]

[2]

[0]

最佳答案

在您的代码中,x1y1 是随机数生成器。每次调用它们时,它们都会采用不同的值。因此,当您调用减法(减法又调用您的数字生成器x1y1)时,没有理由获得与之前一致的结果来电。

要实现您想要的目标,请将值存储在变量中:

import tensorflow as tf

x1 = tf.Variable(tf.random_uniform([1], 0, 10, tf.int32))
y1 = tf.Variable(tf.random_uniform([1], 0, 10, tf.int32))

subtraction = x1 - y1

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(x1))
    print(sess.run(y1))
    print(sess.run(subtraction))

或者,如果您不需要迭代之间的持久性,并且可以一次调用依赖于数字生成器的所有运算符,请将它们打包到对 sess.run 的同一个调用中:

import tensorflow as tf

x1 = tf.random_uniform([1], 0, 10, tf.int32)
y1 = tf.random_uniform([1], 0, 10, tf.int32)

subtraction = x1 - y1

with tf.Session() as sess:
    print(sess.run([x1, y1, subtraction]))

关于python - 随机变量的运算在 Tensorflow 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44129480/

相关文章:

python - tensorflow 梯度为 None ('No gradients provided for any variable' )

python - tensorflow shuffle_batch和feed_dict错误

python-2.7 - AudioSet 和 TensorFlow 的理解

javascript - 从 Tensorflow.js 文本毒性检测模型返回 'predictions'

python - 如何使用运行模块功能在 Komodo IDE 中运行 python 程序,就像在 IDLE(Python GUI) 中一样?

python - 最近 pip 安装 Python 模块后文件版本错误

python - 如何使用python(nltk)匹配段落中的关键字

python - 有没有办法在我的搜索和替换代码中构建异常?

python - 使用 Fabric 从 Python 中在远程服务器上执行代码

python - audio_ops 和 tf.contrib.signal 之间的不同频谱图