numpy.ones_like(),numpy.zeros_like() >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.ones_like(x) array([[1, 1, 1], [1, 1, 1]])
>>> y = np.arange(3, dtype=float) >>> y array([ 0., 1., 2.]) >>> np.zeros_like(y) array([ 0., 0., 0.])
tf.ones_like(), tf.zeros_like()
tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.ones_like(tensor) # [[1, 1, 1], [1, 1, 1]]
tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.zeros_like(tensor) # [[0, 0, 0], [0, 0, 0]]
全1全0矩阵
import tensorflow as tf
import numpy as np
scale1 = tf.Variable(tf.ones([20],tf.int16))
beta1 = tf.Variable(tf.zeros([20]))
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(scale1))
print(sess.run(beta1))
scale2 = np.ones((5,2),dtype=float)
print(scale2)
输出:
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0.]
[[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]
[ 1. 1.]]
注意:1,numpy和tensorflow的区别在于小括号和中括号
2,这里和matlab可不一样,matlab直接生成20×20矩阵。