简体   繁体   中英

Keras - copy Conv2D layer

I want to make a copy of a Conv2D layer.

I tried this:

Edit: I've changed the example code to a mcve

Edit2: I've changed the code based on fuglede 's answer

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
from keras.datasets import mnist
from keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np
import random

(X_train, y_train), (X_test, y_test) = mnist.load_data()


X_train = X_train.reshape(60000, 28, 28, 1)
X_test = X_test.reshape(10000, 28, 28, 1)

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

model = Sequential()

model.add(Conv2D(random.randint(32, 64), kernel_size=random.randint(1, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(Conv2D(32, kernel_size=3, activation='relu'))
model.add(Flatten())
model.add(Dense(10, activation='softmax'))

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

other_model = Sequential()

layer = model.layers[1]

other_model.add(Conv2D(random.randint(32, 64), kernel_size=random.randint(1, 3), activation='relu', input_shape=(28, 28, 1)))

copy_layer = Conv2D(layer.filters, kernel_size=layer.kernel_size, activation='relu')
other_model.add(copy_layer)
copy_layer.set_weights(layer.get_weights())

But I'm getting this error:

ValueError: Layer weight shape (3L, 3L, 61L, 32L) not compatible with provided weight shape (3L, 3L, 40L, 32L)

Edit: The purpose of this is, I'm using a genetic algorithm to evolve/"train" a set a neural networks, and this a part of the crossover step.

This happens because the layer is only initialized once it's added to a model. If you swap the two last lines of your example, it should work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM