Keras-复制Conv2D层

时间:2019-09-08 19:10:30

标签: python machine-learning keras deep-learning

我想复制一个Conv2D图层。

我尝试过:

编辑:我已将示例代码更改为mcve

Edit2:我已根据fuglede的答案更改了代码

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())

但是我遇到了这个错误:

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

编辑:这样做的目的是,我正在使用一种遗传算法来进化/“训练”一组神经网络,这是交叉步骤的一部分。

1 个答案:

答案 0 :(得分:1)

之所以会这样,是因为该图层仅在添加到模型后才被初始化。如果您交换示例的最后两行,它应该可以按预期工作。