如何将随机TensorFlow张量与标量相乘?

时间:2020-02-13 19:00:37

标签: python tensorflow

我在做

    with sess.as_default():
        inputs = tf.random.uniform(
            shape=[10],
            minval=-1,
            maxval=1,
            dtype=tf.dtypes.float32
        )

        outputs = inputs * 2
        return inputs, outputs

但是,这给了我不正确的价值观:

[-0.35871983  0.38419914  0.4842844   0.73863363  0.9198251   0.872777
 -0.02426648 -0.23505187  0.12343764  0.98620296]

[-1.5875583  -0.20895815 -0.38869858 -0.22130203  0.00478601  0.06755686
 -1.2828503   0.13379574  0.91710424  1.2863417 ]

第二张量应该是第一个张量的2倍。

如果这很重要,我正在使用Tensorflow 1.15.0

1 个答案:

答案 0 :(得分:1)

您的代码无法以其当前形式运行。看来您提供了部分功能,但没有提供def语句。无论如何,这是1.15.0中的一个有效示例

import tensorflow as tf

inputs = tf.random.uniform(
    shape=[10],
    minval=-1,
    maxval=1,
    dtype=tf.dtypes.float32
)

outputs = inputs * 2

with tf.Session() as s:
    out = s.run([inputs, outputs])

out的结果是

[array([ 0.39246178,  0.77169394,  0.05202556,  0.979944  , -0.9819634 ,
        -0.56705594,  0.64549136,  0.59383535, -0.5887065 ,  0.90850115],
       dtype=float32),
 array([ 0.78492355,  1.5433879 ,  0.10405111,  1.959888  , -1.9639268 ,
        -1.1341119 ,  1.2909827 ,  1.1876707 , -1.177413  ,  1.8170023 ],
       dtype=float32)]

tensorflow 2.x方式:

您使用哪个版本的tensorflow?使用tensorflow 2.1.0,结果翻倍。虽然我没有显式使用会话(tensorflow 2.x消除了该问题)。

import tensorflow as tf

def func():
    inputs = tf.random.uniform(
        shape=[10],
        minval=-1,
        maxval=1,
        dtype=tf.dtypes.float32
    )
    outputs = inputs * 2
    return inputs, outputs

func()

输出为

(<tf.Tensor: shape=(10,), dtype=float32, numpy=
 array([-0.02820992,  0.50165296, -0.8978882 ,  0.28159666,  0.00776339,
         0.8920951 ,  0.89258003, -0.25228214, -0.25257993, -0.32589626],
       dtype=float32)>,
 <tf.Tensor: shape=(10,), dtype=float32, numpy=
 array([-0.05641985,  1.0033059 , -1.7957764 ,  0.5631933 ,  0.01552677,
         1.7841902 ,  1.7851601 , -0.5045643 , -0.50515985, -0.6517925 ],
       dtype=float32)>)
相关问题