tutorial que modelo libreria español ejemplo python theano keras keras-layer

python - que - ¿Cómo agregar y eliminar nuevas capas en keras después de cargar pesos?



que es keras (2)

Otra forma de hacerlo

from keras.models import Model layer_name = ''relu_conv2'' model2= Model(inputs=model1.input, outputs=model1.get_layer(layer_name).output)

Estoy tratando de hacer un aprendizaje de transferencia; para ello quiero eliminar las dos últimas capas de la red neuronal y agregar otras dos capas. Este es un código de ejemplo que también genera el mismo error.

from keras.models import Sequential from keras.layers import Input,Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.layers.core import Dropout, Activation from keras.layers.pooling import GlobalAveragePooling2D from keras.models import Model in_img = Input(shape=(3, 32, 32)) x = Convolution2D(12, 3, 3, subsample=(2, 2), border_mode=''valid'', name=''conv1'')(in_img) x = Activation(''relu'', name=''relu_conv1'')(x) x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name=''pool1'')(x) x = Convolution2D(3, 1, 1, border_mode=''valid'', name=''conv2'')(x) x = Activation(''relu'', name=''relu_conv2'')(x) x = GlobalAveragePooling2D()(x) o = Activation(''softmax'', name=''loss'')(x) model = Model(input=in_img, output=[o]) model.compile(loss="categorical_crossentropy", optimizer="adam") #model.load_weights(''model_weights.h5'', by_name=True) model.summary() model.layers.pop() model.layers.pop() model.summary() model.add(MaxPooling2D()) model.add(Activation(''sigmoid'', name=''loss''))

Quité la capa usando pop() pero cuando intenté agregar su resultado, se produjo este error.

AttributeError: el objeto ''modelo'' no tiene atributo ''agregar''

Sé que la razón más probable para el error es el uso incorrecto de model.add() . ¿Qué otra sintaxis debo usar?

EDITAR:

Intenté quitar / agregar capas en keras, pero no permite que se agreguen después de cargar pesos externos.

from keras.models import Sequential from keras.layers import Input,Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.layers.core import Dropout, Activation from keras.layers.pooling import GlobalAveragePooling2D from keras.models import Model in_img = Input(shape=(3, 32, 32)) def gen_model(): in_img = Input(shape=(3, 32, 32)) x = Convolution2D(12, 3, 3, subsample=(2, 2), border_mode=''valid'', name=''conv1'')(in_img) x = Activation(''relu'', name=''relu_conv1'')(x) x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name=''pool1'')(x) x = Convolution2D(3, 1, 1, border_mode=''valid'', name=''conv2'')(x) x = Activation(''relu'', name=''relu_conv2'')(x) x = GlobalAveragePooling2D()(x) o = Activation(''softmax'', name=''loss'')(x) model = Model(input=in_img, output=[o]) return model #parent model model=gen_model() model.compile(loss="categorical_crossentropy", optimizer="adam") model.summary() #saving model weights model.save(''model_weights.h5'') #loading weights to second model model2=gen_model() model2.compile(loss="categorical_crossentropy", optimizer="adam") model2.load_weights(''model_weights.h5'', by_name=True) model2.layers.pop() model2.layers.pop() model2.summary() #editing layers in the second model and saving as third model x = MaxPooling2D()(model2.layers[-1].output) o = Activation(''sigmoid'', name=''loss'')(x) model3 = Model(input=in_img, output=[o])

esta mostrando este error

RuntimeError: Graph disconnected: cannot obtain value for tensor input_4 at layer "input_4". The following previous layers were accessed without issue: []


Puede tomar la output del último modelo y crear un nuevo modelo. Las capas inferiores siguen siendo las mismas.

model.summary() model.layers.pop() model.layers.pop() model.summary() x = MaxPooling2D()(model.layers[-1].output) o = Activation(''sigmoid'', name=''loss'')(x) model2 = Model(input=in_img, output=[o]) model2.summary()

Consulte ¿Cómo utilizar los modelos de keras.applications para la transferencia de aprendizaje?

Actualización en Editar:

El nuevo error se debe a que está intentando crear el nuevo modelo en in_img global, que en realidad no se usa en la creación del modelo anterior ... ahí está definiendo un in_img local. Por lo tanto, el in_img global obviamente no está conectado a las capas superiores en el gráfico simbólico. Y no tiene nada que ver con cargar pesos.

Para resolver mejor este problema, debería usar model.input para hacer referencia a la entrada.

model3 = Model(input=model2.input, output=[o])