gpt4 book ai didi

python - Keras - 复制 Conv2D 层

转载 作者:行者123 更新时间:2023-11-30 09:41:44 25 4
gpt4 key购买 nike

我想制作 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)

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

最佳答案

发生这种情况是因为图层仅在添加到模型后才会初始化。如果交换示例的最后两行,它应该按预期工作。

关于python - Keras - 复制 Conv2D 层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57844987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com