TensorFlow 1.14中CNN初始化后核形状异常问题咨询
Hey there! Let's clear up the confusion around your convolution kernel shape and how to access those 2×2 matrices you're expecting.
First: What Does the [2,2,1,3] Shape Mean?
In TensorFlow 1.x, the standard shape for a convolution kernel follows the order: [filter_height, filter_width, in_channels, out_channels]. Breaking down your kernel's shape:
2: Height of each individual filter2: Width of each individual filter1: Number of input channels (matches the channel count of your input tensor)3: Number of output channels (this means you do have 3 separate 2×2 filters—they're just stored in the last dimension of the 4D tensor)
The 4D structure is TensorFlow's way of organizing filters to align with convolution operations, but your expected 2×2 matrices are all there—you just need to know how to extract them.
Why You Couldn't Traverse the Kernels Easily
When you printed a_value, you saw the full 4D tensor output. To get each individual 2×2 kernel, you need to index into the last dimension (since that's where the separate filters are stored). Since your input channel count is 1, you can safely ignore that middle dimension when indexing.
Fixed Code with Kernel Access
Also, note that tf.initialize_all_variables() is deprecated in TensorFlow 1.14—use tf.global_variables_initializer() instead to avoid warnings or compatibility issues. Here's a modified version of your code that extracts and prints each 2×2 kernel:
import tensorflow as tf # Define kernel with shape [height, width, in_channels, out_channels] kernel = tf.Variable(tf.random.truncated_normal([2,2,1,3], stddev=0.1)) # Use the recommended initializer instead of the deprecated one init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) kernel_value = sess.run(kernel) print(f"Full kernel shape: {kernel_value.shape}") # Traverse and print each of the 3 2×2 kernels print("\nIndividual 2×2 kernels:") for i in range(3): # Index into the last dimension to get the i-th filter # Since in_channels=1, we pick index 0 for that dimension single_kernel = kernel_value[:, :, 0, i] print(f"\nKernel {i+1}:") print(single_kernel)
What This Does
kernel_value[:, :, 0, i]selects:- All rows (
:) and columns (:) of the filter - The only input channel (
0) - The i-th output channel/filter (
i)
- All rows (
- This will output exactly the 3 separate 2×2 matrices you expected.
Quick Recap
Your original code was creating the correct number of kernels—you just needed to adjust how you index into the 4D tensor to access each individual filter. The key takeaway is remembering TensorFlow 1.x's convolution kernel dimension order: height → width → input channels → output channels.
内容的提问来源于stack exchange,提问作者ashish_2001

