是否可以更改张量流预训练模型的输入形状?

Is it possible to change the input shape of a tensorflow pretrained model?

我有一个用于图像分割的 Tensorflow 预训练模型,它接收 6 个波段作为输入,我想更改模型的输入大小以接收 4 个波段,这样我就可以用我自己的数据集重新训练,但仍然不行能做到吗,不知道这是否可行?

我尝试按名称获取输入节点并使用 import_graph_def 更改它但没有成功,似乎它要求在尝试替换时尊重尺寸。

graph = tf.get_default_graph()
tf_new_input = tf.placeholder(shape=(4, 256, 256), dtype='float32', name='new_input')
tf.import_graph_def(graph_def, input_map={"ImageInputLayer": tf_new_input})

但我收到以下错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Dimensions must be equal, but are 4 and 6 for 'import/ImageInputLayer_Sub' (op: 'Sub') with input shapes: [4,256,256], [6,256,256]

您必须将您的 4 通道占位符输入转换为 6 通道输入,并且输入图像的形状应该与您的 6 通道模型期望的相同。您可以使用任何操作,但 conv2d 是在将其输入现有模型之前执行的简单操作。这就是你的做法。

with tf.Graph().as_default() as old_graph:
  # You have to load your 6 channel input graph here
  saver.restore(tf.get_default_session(), <<save_path>>)
  # Assuming that input node is named as 'input_node' and 
  # final node is named as 'softmax_node'

with tf.Graph().as_default() as new_graph:
  tf_new_input = tf.placeholder(shape=(None, 256, 256, 4), dtype='float32')

  # Map 4 channeled input to 6 channel and 
  # image input shape should be same as expected by old model.
  new_node = tf.nn.conv2d(tf_new_input, (3, 3, 4, 6), strides=1, padding='SAME')

  # If you want to obtain output node so that you can further perform operations.
  softmax_node = tf.import_graph_def(old_graph, input_map={'input_node:0': new_node}, 
                                     return_elements=['softmax_node:0'])

user1190882这个问题回答的很好。仅将此部分用于 post 代码以供将来参考,我不得不通过在单独的变量中创建过滤器来进行小的更改,因为我收到错误:Shape must be rank 4 but is rank 1 for 'Conv2D'。我还做了一个小改动,因为我的模型的输入格式是 "Channels First",我添加了 data_format 标志。

with tf.Graph().as_default() as new_graph:

tf_new_input = tf.placeholder(shape=(None, 4, 256, 256), dtype='float32')
# Creating separate variable for filter  
filterc = tf.Variable(tf.random_normal([3, 3, 4, 6]))
new_node = tf.nn.conv2d(tf_new_input, filterc, strides=1, padding='SAME',  data_format='NCHW')
tf.import_graph_def(old_graph, input_map={'ImageInputLayer': new_node})