Tensorflow 和 Numpy 不匹配数据格式

Tensorflow and Numpy mismatch data format

编写此代码:

import tensorflow as tf  

w = tf.Variable(tf.random_normal( [ 3 , 3 , 1 , 1  ], stddev = 0.01 )) 
if __name__ == '__main__': 
    initVar = tf.global_variables_initializer()  
    with tf.Session() as sess:  
        sess.run(initVar) 
        print w.eval()

由于数据格式 w = tf.Variable(tf.random_normal( [kernel_height, kernel_width, input_channel, output_chhannel], stddev = 0.01 )),我希望看到这样的矩阵:

[[[[ -0.004  0.003  0.006]
   [ -0.005 -0.008  0.001]
   [  0.006  0.007  0.002]]]]

但它打印了这个:

[[[[ 0.001]] 
  [[-0.031]] 
  [[-0.005]]]

 [[[ 0.006]] 
  [[ 0.011]] 
  [[ 0.006]]]

 [[[ 0.008]] 
  [[-0.001]] 
  [[ 0.014]]]]

我想要的是将我的权重张量值与常数张量 0 和 1 相乘,得到如下掩码权重:

w = [[[[ -0.004  0.003  0.006]
       [ -0.005 -0.008  0.001]
       [  0.006  0.007  0.002]]]]

mask = [[[[ 1  1  1]
          [ 1  1  0]
          [ 0  0  0]]]]

w * mask =  [[[[ -0.004  0.003  0.006]
               [ -0.005 -0.008  0.   ]
               [  0.     0.     0.   ]]]]

我用的代码是这样的:

    mask = np.ones((3, 3, 1, 1), dtype=np.float32)
    mask[1, 2, :, :] = 0.
    mask[2, :, :, :] = 0. 

    weight = tf.get_variable("weight", [3, 3, 1, 1], tf.float32, tf.contrib.layers.xavier_initializer()) 

    weight *= tf.constant(mask, dtype=tf.float32)

但似乎不能正常工作。感谢您的帮助。

你需要

w = tf.Variable(tf.random_normal([1, 1, 3, 3], stddev=0.01)) 

最后,您可以使用

import tensorflow as tf 
import numpy as np

mask = np.ones((1, 1, 3, 3), dtype=np.float32)
mask[:, :, 1, 2] = 0.
mask[:, :, 2, :] = 0. 

print(mask)

weight = tf.get_variable("weight", [3, 3, 1, 1], tf.float32, tf.contrib.layers.xavier_initializer())
weight *= tf.transpose( tf.constant(mask, dtype=tf.float32) )

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(tf.transpose(weight).eval())

你会得到

[[[[ 1.  1.  1.]
   [ 1.  1.  0.]
   [ 0.  0.  0.]]]]

[[[[ 0.88993669  0.80872607  0.57259583]
   [ 0.5067296  -0.20804334 -0.        ]
   [ 0.          0.          0.        ]]]]