0

我是深度学习的新手。我想使用 rbf 神经网络在自定义数据集上构建人脸识别模型。我有 17 个类别的 187 个图像的数据集。我训练并保存模型但不能使用它。我的代码:

from keras import backend as K
from keras.engine.topology import Layer
from keras.initializers import RandomUniform, Initializer, Constant
import numpy as np


class InitCentersRandom(Initializer):
""" Initializer for initialization of centers of RBF network
    as random samples from the given data set.
# Arguments
    X: matrix, dataset to choose the centers from (random rows
      are taken as centers)
"""

def __init__(self, X):
    self.X = X

def __call__(self, shape, dtype=None):
    assert shape[1] == self.X.shape[1]
    idx = np.random.randint(self.X.shape[0], size=shape[0])
    return self.X[idx, :]


class RBFLayer(Layer):

def __init__(self, output_dim, initializer=None, betas=1.0, **kwargs):
    self.output_dim = output_dim
    self.init_betas = betas
    if not initializer:
        self.initializer = RandomUniform(0.0, 1.0)
    else:
        self.initializer = initializer
    super(RBFLayer, self).__init__(**kwargs)

def build(self, input_shape):

    self.centers = self.add_weight(name='centers',
                                   shape=(self.output_dim, input_shape[1]),
                                   initializer=self.initializer,
                                   trainable=True)
    self.betas = self.add_weight(name='betas',
                                 shape=(self.output_dim,),
                                 initializer=Constant(
                                     value=self.init_betas),
                                 # initializer='ones',
                                 trainable=True)

    super(RBFLayer, self).build(input_shape)

def call(self, x):

    C = K.expand_dims(self.centers)
    H = K.transpose(C-K.transpose(x))
    return K.exp(-self.betas * K.sum(H**2, axis=1))

    # C = self.centers[np.newaxis, :, :]
    # X = x[:, np.newaxis, :]

    # diffnorm = K.sum((C-X)**2, axis=-1)
    # ret = K.exp( - self.betas * diffnorm)
    # return ret

def compute_output_shape(self, input_shape):
    return (input_shape[0], self.output_dim)

def get_config(self):
    # have to define get_config to be able to use model_from_json
    config = {
        'output_dim': self.output_dim
    }
    base_config = super(RBFLayer, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

拟合模型.......

# creating RBF network

from keras import Sequential
from keras import layers
from keras.layers import *
rbflayer = RBFLayer(136,
                initializer=InitCentersRandom(X),
                betas=2.0,
                input_shape=X.shape[1:])

model = Sequential()
#model.add(Flatten(input_shape=(28, 28)))
model.add(rbflayer)
#model.add(Dense(1))
model.add(layers.Dense(17, activation='softmax'))
model.summary()
import numpy as np
from keras.layers.core import Dense
from keras.optimizers import RMSprop
#from rbflayer import RBFLayer, InitCentersRandom
import matplotlib.pyplot as plt

from sklearn.metrics import mean_squared_error
model.compile(loss='mean_squared_error',
              optimizer=RMSprop())


print(y.shape)
X = X.reshape(187,4900)
model.fit(X, y,
        batch_size=32,
        epochs=10,
        #steps_per_epoch=500,
        verbose=True
     )
model.save('rbfworks.model')

在加载模型上它说:

from keras.models import load_model
model=load_model('rbfworks.model')

ValueError:未知层:RBFLayer

怎么了?我需要做什么?

4

1 回答 1

0

您需要注册自定义层(https://www.tensorflow.org/guide/keras/save_and_serialize):

# At loading time, register the custom objects with a `custom_object_scope`:
custom_objects = {"RBFLayer": RBFLayer}
with keras.utils.custom_object_scope(custom_objects):
  model=load_model('rbfworks.model')
于 2020-11-10T10:07:19.107 回答