Numpy 数组到 Tensor

Numpy array to Tensor

我正在将 numpy 创建的代码更改为 tensorflow 代码。

但是tensorflow不支持指定每个元素,(eg x[i] = 7), boolean(eg.var [x <0.25] = -1) with possible array of numpy 很难。

如何将以下代码更改为张量?

x=np.random.rand((500*300))
var=np.zeros((500*300), dtype=np.uint16)
var[x<.25] = -1
var[x>.75] = 1
S=var.reshape((500, 300))

请帮帮我

注意:我试试这个步骤。

x=tf.random_uniform((500*300), minval=0, maxval=1, dtype=tf.float32)
var=tf.zeros((500*300), int16)
var[x<.25] = -1  # How is the change???????
var[x>.75] = 1   # How is the change???????
S=var.reshape((500, 300))

按照评论中的建议使用tf.where。我在下面提供了示例代码并在必要时进行了评论。

x = tf.random_uniform(shape=[5, 3], minval=0, maxval=1, dtype=tf.float32)

#same shape as x and only contains -1
c1 = tf.multiply(tf.ones(x.shape, tf.int32), -1)
#same shape as x and only contains 1
c2 = tf.multiply(tf.ones(x.shape, tf.int32), 1)

var = tf.zeros([5, 3], tf.int32)

#assign 1 element wise if x< 0.25 else 0
r1 = tf.where(tf.less(x, 0.25), c1, var)
#assign -1 element wise if x> 0.75 else 0
r2 = tf.where(tf.greater(x, 0.75), c2, var)

r = tf.add(r1, r2)

with tf.Session() as sess:
    _x, _r = sess.run([x, r])

    print(_x)
    print(_r)

示例结果

[[0.6438687  0.79183984 0.40236235]
 [0.7848805  0.0117377  0.6858672 ]
 [0.6067281  0.5176437  0.9839716 ]
 [0.15617108 0.28574145 0.31405795]
 [0.28515983 0.6034068  0.9314337 ]]

[[ 0  1  0]
 [ 1 -1  0]
 [ 0  0  1]
 [-1  0  0]
 [ 0  0  1]]

希望对您有所帮助。

我觉得如果把xvar都压平,tf.scatter_update就可以了。然后你可以重塑它。

x = tf.random_uniform((5,3), minval=0, maxval=1, dtype=tf.float32)

var = tf.Variable(tf.zeros((5 , 3), tf.int32))

flattenx = tf.Variable(tf.reshape(x, [-1]))
flattenvar = tf.Variable(tf.reshape(var, [-1]))

minusone = tf.squeeze(tf.where(tf.less(flattenx, .25)))
plusone = tf.squeeze(tf.where(tf.greater(flattenx, .75)))

with tf.Session() as sess :

    sess.run(tf.global_variables_initializer())
    #create the required number of -1's using tile and update
    update = tf.scatter_update(flattenvar,
                               minusone,
                               tf.tile(tf.constant([-1],
                                       tf.int32),
                                       tf.shape(minusone)))
    #create the required number of 1's using tile and update
    update = tf.scatter_update(update,
                               plusone,
                               tf.tile(tf.constant([1],
                                       tf.int32),
                                       tf.shape(plusone)))
    print(sess.run(tf.transpose(tf.reshape(update,(3,5)))))
    print(sess.run(tf.transpose(tf.reshape(flattenx,(3,5)))))

我这样转置是因为如果我直接将它重塑为 (5,3) 位置不匹配。

输出是这样的。

[[ 0  1 -1]
 [ 0  0 -1]
 [ 0  1  0]
 [ 1  0  1]
 [-1  0  0]]
[[0.53033566 0.8070284  0.0320853 ]
 [0.7295474  0.684116   0.18633509]
 [0.4942881  0.89346325 0.5873647 ]
 [0.96912587 0.5400375  0.8372116 ]
 [0.14598823 0.62156534 0.54353106]]