想请老师帮忙看一下代码,谢谢
来源:4-5 VGG-ResNet实战(2)
战战的坚果
2020-05-06
老师,我想把resnet的实战代码转成tf2.0下的代码,我改写成了下面的样子,但是运行有错,想请您帮忙看下,该怎么修改,报错在最后粘贴。
def residual_block(x,output_channel):
"""residual connection implementation"""
input_channel = 32
if input_channel * 2 == output_channel:
increase_dim = True
strides = (2, 2)
elif input_channel == output_channel:
increase_dim = False
strides = (1, 1)
else:
raise Exception("input channel can't match output channel")
conv1 = keras.layers.Conv2D(filters=output_channel, kernel_size=3,
strides = strides,
padding='same',
activation='relu')
conv2 = keras.layers.Conv2D(filters=output_channel, kernel_size=3,
strides = (1, 1),
padding='same',
activation='relu')
if increase_dim:
#[None, image_width, image_height, channel] -> [,,,channel*2]
pooled_x = keras.layers.MaxPool2D(input_shape=train_data_scaled.shape[1:],
pool_size=2)
#做一个padding,padding在通道上
padded_x = tf.pad(pooled_x,
[[0,0],
[0,0],
[0,0],
[input_channel // 2, input_channel // 2]])
else:
padded_x = x
output_x = conv2 + padded_x
layers.append(output_x)
return output_x
layers = []
num_residual_blocks = [2,3,2]
num_subsampling = len(num_residual_blocks)
model = keras.models.Sequential()
conv0 = keras.layers.Conv2D(filters=32, kernel_size=3,
padding='same',
activation='relu',
input_shape=train_data_scaled.shape[1:])
model.add(conv0)
layers.append(conv0)
for sample_id in range(num_subsampling):
for i in range(num_residual_blocks[sample_id]):
model.add(residual_block(layers[-1],32 * (2 ** sample_id)))
TypeError Traceback (most recent call last)
in
49 for sample_id in range(num_subsampling):
50 for i in range(num_residual_blocks[sample_id]):
—> 51 model.add(residual_block(layers[-1],32 * (2 ** sample_id)))
52
in residual_block(x, output_channel)
32 else:
33 padded_x = x
—> 34 output_x = conv2 + padded_x
35 layers.append(output_x)
36 return output_x
TypeError: unsupported operand type(s) for +: ‘Conv2D’ and ‘Conv2D’
写回答
1回答
-
正十七
2020-05-07
同学你好,在这里你要加两个tensor,得让它们先是tensor,所以你应该用函数式的方式来使用这些定义的层次。
00
相似问题
2.7 节代码
回答 1
准确率与损失函数的作用,有点混淆!
回答 2