我想使用条件变分自动编码器,这是我的数据集。我的输入是一个时间序列数据,形状为 100020,我的输出是 505。当我尝试训练模型时,出现此错误。你能帮我解决这个问题吗?
import numpy as np
from keras.layers import Input, Dense, Lambda, concatenate
from keras.models import Model
from keras import backend as K
from keras import objectives
from keras.utils import to_categorical
from scipy.stats import norm
x_tr = np.random.rand(1000, 20)
x_te = np.random.rand(50, 20)
y_tr = np.random.rand(1000, 5)
y_te = np.random.rand(50, 5)
batch_size, n_epoch = 50, 50
n_hidden, z_dim = 512, 2
x = Input(shape=(x_tr.shape[1:]))
condition = Input(shape=(y_tr.shape[1],))
inputs = concatenate([x, condition])
x_encoded = Dense(n_hidden, activation='relu')(inputs)
x_encoded = Dense(n_hidden//2, activation='relu')(x_encoded)
mu = Dense(z_dim, activation='linear')(x_encoded)
log_var = Dense(z_dim, activation='linear')(x_encoded)
# sampling function
def sampling(args):
mu, log_var = args
eps = K.random_normal(shape=(batch_size, z_dim), mean=0., stddev=1.0)
return mu + K.exp(log_var/2.) * eps
z = Lambda(sampling, output_shape=(z_dim,))([mu, log_var])
z_cond = concatenate([z, condition])
z_decoder1 = Dense(n_hidden//2, activation='relu')
z_decoder2 = Dense(n_hidden, activation='relu')
y_decoder = Dense(x_tr.shape[1], activation='sigmoid')
z_decoded = z_decoder1(z_cond)
z_decoded = z_decoder2(z_decoded)
y = y_decoder(z_decoded)
# loss
reconstruction_loss = objectives.binary_crossentropy(x, y) * x_tr.shape[1]
kl_loss = 0.5 * K.sum(K.square(mu) + K.exp(log_var) - log_var - 1, axis = -1)
cvae_loss = reconstruction_loss + kl_loss
# build model
cvae = Model([x, condition], y)
cvae.add_loss(cvae_loss)
cvae.compile(optimizer='adam')
cvae.fit([x_tr, y_tr], epochs=n_epoch, batch_size=batch_size, validation_data=([x_te, y_te], None), verbose=1)```
here is the error
``` ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 40 but received input with shape [50, 4]```
答案 0 :(得分:0)
你只是搞砸了尺寸。
只要改变
x_tr = np.random.rand(1000, 20)
x_te = np.random.rand(50, 20)
y_tr = np.random.rand(1000, 5)
y_te = np.random.rand(50, 5)
到
x_tr = np.random.rand(1000, 20)
y_tr = np.random.rand(1000, 5)
x_te = np.random.rand(50, 20)
y_te = np.random.rand(50, 5)