Search code examples
pythontensorflowboolean-operationsnumpy-ndarray

Numpy array to Tensor


I am changing the code created by numpy to tensorflow code.

However, tensorflow does not support specifying each element, (eg x [i] = 7), boolean (eg.var [x <0.25] = -1) with possible array of numpy It is difficult.

How can I change the following code to tensor?

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))

Please, help me.

Note: I try this step.

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))

Solution

  • Use tf.where as suggested in the comments. I have below provided a sample code and commented where necessary.

    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)
    

    Example Result

    [[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]]
    

    Hope this helps.