Resnet网络无法按预期工作

时间:2018-03-12 00:05:25

标签: python keras conv-neural-network tensorboard resnet

您好我正在尝试使用微调方法使用Resnet神经网络训练癌症数据集

以下是我过去常常对其进行微调的方法。

image_input = Input(shape=(224, 224, 3))

model = ResNet50(input_tensor=image_input, include_top=True,weights='imagenet')
model.summary()
last_layer = model.get_layer('avg_pool').output
x= Flatten(name='flatten')(last_layer)
out = Dense(num_classes, activation='softmax', name='output_layer')(x)
custom_resnet_model = Model(inputs=image_input,outputs= out)
custom_resnet_model.summary()

for layer in custom_resnet_model.layers[:-1]:
    layer.trainable = False

custom_resnet_model.layers[-1].trainable

custom_resnet_model.compile(Adam(lr=0.001),loss='categorical_crossentropy',metrics=['accuracy'])

custom_resnet_model.summary()

tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0,
                      write_graph=True, write_images=False)

hist = custom_resnet_model.fit(X_train, X_valid, batch_size=32, epochs=nb_epoch, verbose=1, validation_data=(Y_train, Y_valid),callbacks=[tensorboard])

(loss, accuracy) = custom_resnet_model.evaluate(Y_train,Y_valid,batch_size=batch_size,verbose=1)

print("[INFO] loss={:.4f}, accuracy: {:.4f}%".format(loss,accuracy * 100))

df = pd.read_csv('C:/CT_SCAN_IMAGE_SET/resnet_50/dbs2017/data/stage1_sample_submission.csv')
df2 = pd.read_csv('C:/CT_SCAN_IMAGE_SET/resnet_50/dbs2017/data/stage1_solution.csv')
x = np.array([np.mean(np.load('E:/224x224/%s.npy' % str(id)), axis=0) for id in df['id'].tolist()])

x = x.transpose(0,2,3,1)
# Make predictions 
pred = model.predict(x, batch_size=batch_size, verbose=1) #predict(self, x, batch_size=None, verbose=0, steps=None)

print (pred)

我使用验证集来预测我的最终结果。 但即使有100个时代,我的预测班级概率也非常低。

 5.41865666e-05 2.16298591e-04 2.77880055e-04 7.53038039e-05
 6.03657216e-04 1.30494649e-04 4.92068466e-05 5.37877844e-04
 1.61486780e-04 6.16881996e-04 9.92802554e-04 5.50923753e-04
 3.62671199e-05 3.44127137e-03 7.17231014e-05 2.79643398e-04
 2.86785862e-03 1.70384112e-04 6.59705256e-05 7.11611006e-04
 2.09898906e-04 1.82953620e-04 8.88684444e-05 1.87824480e-04
 1.32007655e-04 2.11239138e-04 7.63713342e-06 1.29785520e-04
 1.09007429e-04 3.14327976e-04 4.73849563e-04 4.22359008e-04
 6.27386966e-04 2.03593503e-04 1.72056989e-05 8.38911365e-05
 1.91937244e-04 1.59160278e-04 5.24159847e-03 1.45429352e-04
 4.30631888e-04 6.92744215e-04 1.00537611e-04 6.27409827e-05
 3.87431937e-04 1.37840703e-04 1.04467930e-04 1.74013167e-05
 1.18957250e-04 2.77637475e-04 2.25973461e-04 1.21678226e-04
 2.42197304e-04 2.99750012e-04 1.16530759e-03 1.29382452e-03
 7.35349662e-04 5.71311277e-04 1.26631945e-04 4.74024746e-05
 3.71460657e-04 1.23646241e-04]

这是张量板结果的显示方式。

enter image description here

有人可以告诉我,为什么概率没有得到改善?或者我可以用来改善这个的任何建议?

PS:

答案建议的resnet网络部分摘要

add_15 (Add)                    (None, 7, 7, 2048)   0           bn5b_branch2c[0][0]              
                                                                 activation_43[0][0]              
__________________________________________________________________________________________________
activation_46 (Activation)      (None, 7, 7, 2048)   0           add_15[0][0]                     
__________________________________________________________________________________________________
res5c_branch2a (Conv2D)         (None, 7, 7, 512)    1049088     activation_46[0][0]              
__________________________________________________________________________________________________
bn5c_branch2a (BatchNormalizati (None, 7, 7, 512)    2048        res5c_branch2a[0][0]             
__________________________________________________________________________________________________
activation_47 (Activation)      (None, 7, 7, 512)    0           bn5c_branch2a[0][0]              
__________________________________________________________________________________________________
res5c_branch2b (Conv2D)         (None, 7, 7, 512)    2359808     activation_47[0][0]              
__________________________________________________________________________________________________
bn5c_branch2b (BatchNormalizati (None, 7, 7, 512)    2048        res5c_branch2b[0][0]             
__________________________________________________________________________________________________
activation_48 (Activation)      (None, 7, 7, 512)    0           bn5c_branch2b[0][0]              
__________________________________________________________________________________________________
res5c_branch2c (Conv2D)         (None, 7, 7, 2048)   1050624     activation_48[0][0]              
__________________________________________________________________________________________________
bn5c_branch2c (BatchNormalizati (None, 7, 7, 2048)   8192        res5c_branch2c[0][0]             
__________________________________________________________________________________________________
add_16 (Add)                    (None, 7, 7, 2048)   0           bn5c_branch2c[0][0]              
                                                                 activation_46[0][0]              
__________________________________________________________________________________________________
activation_49 (Activation)      (None, 7, 7, 2048)   0           add_16[0][0]                     
__________________________________________________________________________________________________
avg_pool (AveragePooling2D)     (None, 1, 1, 2048)   0           activation_49[0][0]              
__________________________________________________________________________________________________
flatten_1 (Flatten)             (None, 2048)         0           avg_pool[0][0]                   
__________________________________________________________________________________________________
fc1000 (Dense)                  (None, 1000)         2049000     flatten_1[0][0]                  
__________________________________________________________________________________________________
dense_1 (Dense)                 (None, 512)          512512      fc1000[0][0]                     
__________________________________________________________________________________________________
dropout_1 (Dropout)             (None, 512)          0           dense_1[0][0]                    
__________________________________________________________________________________________________
dense_2 (Dense)                 (None, 512)          262656      dropout_1[0][0]                  
__________________________________________________________________________________________________
dropout_2 (Dropout)             (None, 512)          0           dense_2[0][0]                    
__________________________________________________________________________________________________
output_layer (Dense)            (None, 2)            1026        dropout_2[0][0]                  
==================================================================================================

2 个答案:

答案 0 :(得分:11)

从我的阴谋中可以看出,你过度拟合了。为避免过度拟合,您应该使用Dropout。下面我添加了2个新的密集层,然后是2个Dropout图层(可以减少到1对或增加到更多)。你可以微调他们的参数。

我还想提出一个更简单的网络表示,但你的方式会很好。

base_model = ResNet50(input_shape=(224, 224, 3), include_top=False,weights='imagenet',pooling='avg')
x=base_model.output

x = Dense(512, activation='relu')(x) #add new layer
x = Dropout(0.5)(x) #add new layer
x = Dense(512, activation='relu')(x) #add new layer
x = Dropout(0.5)(x) #add new layer

out = Dense(62, activation='softmax', name='output_layer')(x)
custom_resnet_model = Model(inputs=base_model.input,outputs= out)

for layer in base_model.layers:
    layer.trainable = False


custom_resnet_model.compile(Adam(lr=0.001),loss='categorical_crossentropy',metrics=['accuracy'])

custom_resnet_model.summary()
...

最后,您可以尝试不同的学习速率参数和不同的预训练模型。

答案 1 :(得分:4)

不,我认为不会过度拟合。为什么要使include_top = True?微调应该是假的。

取自Keras应用程序(文档)。(https://keras.io/applications/

base_model = InceptionV3(weights='imagenet', include_top=False)

- 这是错误的,因为你在卷积后不需要Inception的密集层,因为它对于Imagenet而且它有1000个类(Dense(1000,“softmax”),而不是你的数据集。

x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(num_classes, activation='softmax')(x)

model = Model(inputs=base_model.input, outputs=predictions)

根据我的经验,避免这4行,我认为它有问题。但是,试试吧。但我认为不要先尝试并保持低学习率。然后你应该在另一个.py文件中尝试。

for layer in model.layers[:249]:
   layer.trainable = False
for layer in model.layers[249:]:
   layer.trainable = True

# compile the model (should be done *after* setting layers to non-trainable)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

# train the model on the new data for a few epochs
model.fit_generator(...)