InvalidArgumentError:不兼容的形状:[2240,17]与[32,17]

时间:2020-11-10 02:45:31

标签: python tensorflow tensor custom-training

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, :]

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

创建RBF网络

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

型号:“ sequential_8”


图层(类型)输出形状参数#

rbf_layer_8(RBFLayer)(无,136)666536


dense_6(Dense)(None,17)2329

总参数:668,865 可训练的参数:668,865 不可训练的参数:0

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(X.shape)

  model.fit(X, y,
        batch_size=32,
        epochs=20,
        #steps_per_epoch=500,
        verbose=True
     )

我的输入和目标的形状是: X:(187,70,70) y:(187,17) 我有错误 InvalidArgumentError:不兼容的形状:[2240,17]与[32,17] 我该怎么处理

0 个答案:

没有答案