如何在Python主程序中打印TensorFlow卷积函数的权重与卷积结果?
Hey there! Let's work through how to print both the weights inside your conv_fn and the convolution result properly. I'll start by pointing out a couple of issues in your current code, then show you the fixed version with clear explanations.
首先,修正代码里的核心问题
Your current main function has a mistake with feed_dict: p_input is a regular Python function parameter (a numpy array), not a TensorFlow placeholder, so you don't need to feed it. Also, to access weights1 from outside conv_fn, we need to make it accessible—either by returning it from the function or referencing it correctly.
1. 打印conv_fn中的weights1
There are two straightforward ways to get and print weights1:
方法一:让conv_fn返回权重和卷积结果(推荐)
Modify conv_fn to return both the ReLU output and the weights tensor. This is the cleanest approach because it makes dependencies explicit and avoids relying on global variable names:
def conv_fn(p_input): # Convolutional Layer #1 weights1 = tf.get_variable("weights1", [3, 3, 3, 32], initializer=tf.random_normal_initializer()) conv1 = tf.nn.conv2d( input=p_input.astype(np.float32), filter=weights1, strides=[1, 1, 1, 1], padding="VALID" ) conv1_relu = tf.nn.relu(conv1) # Return both the convolution result and the weights return conv1_relu, weights1
Then in your main function, capture both values and run them in the session:
def main(argv): sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) im = [1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0, 1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0, 1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0] image = np.reshape(im, [-1, 3, 3, 3]) # Capture both the convolution result and weights tensor con, weights = conv_fn(image) # Fetch and print weights1 weights_val = sess.run(weights) print("weights1 shape:", weights_val.shape) print("weights1 content:\n", weights_val) # Fetch and print convolution result con_val = sess.run(con) print("\nConvolution result shape:", con_val.shape) print("Convolution result content:\n", con_val) sess.close() if __name__ == "__main__": tf.app.run()
方法二:通过变量名获取权重(不推荐,不够直观)
Since weights1 is defined with tf.get_variable (which creates a global variable by default), you can fetch it from the TensorFlow graph using its name:
# In main function, after calling conv_fn(image) weights_tensor = tf.get_default_graph().get_tensor_by_name("weights1:0") weights_val = sess.run(weights_tensor) print("weights1:\n", weights_val)
Note: This is less maintainable—if you ever rename the variable or add a scope, this will break. The first method is much safer for long-term use.
2. 打印卷积运算的结果
Once you remove the unnecessary feed_dict (your input is a numpy array that TensorFlow automatically converts to a tensor), you just need to run the con tensor in the session. The code above already includes this: we use sess.run(con) to get the actual numpy array of the convolution result, then print it.
额外提示:使用占位符提升灵活性(可选)
If you want to reuse conv_fn with different inputs later, it's better to use a TensorFlow placeholder instead of passing numpy arrays directly. Here's how that would look:
def conv_fn(p_input): weights1 = tf.get_variable("weights1", [3, 3, 3, 32], initializer=tf.random_normal_initializer()) conv1 = tf.nn.conv2d( input=p_input, # p_input is now a placeholder tensor filter=weights1, strides=[1, 1, 1, 1], padding="VALID" ) return tf.nn.relu(conv1), weights1 def main(argv): sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) # Create a placeholder for input images input_placeholder = tf.placeholder(tf.float32, shape=[None, 3, 3, 3]) im = [1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0, 1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0, 1.0, 1.0, 2.0, 5.0, 1.0, 1.0, 2.0, 5.0, 5.0] image = np.reshape(im, [-1, 3, 3, 3]) con, weights = conv_fn(input_placeholder) # Use feed_dict to pass the actual image data weights_val = sess.run(weights) con_val = sess.run(con, feed_dict={input_placeholder: image}) print("weights1:\n", weights_val) print("Convolution result:\n", con_val) sess.close()
This setup lets you pass different images to conv_fn by updating the value in feed_dict, which aligns better with typical TensorFlow workflows.
内容的提问来源于stack exchange,提问作者V. Arbez

