[英]ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1. tensorflow
I want to use the Conditional Variational AutoEncoder, here is my dataset.我想使用条件变分自动编码器,这是我的数据集。 My inputs is a time-series data with a shape 1000 20, and my output is 50 5. when I try to train the model, this error appears.
我的输入是形状为 1000 20 的时间序列数据,我的 output 是 50 5。当我尝试训练 model 时,会出现此错误。 Could you help me to solve that?
你能帮我解决这个问题吗?
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]```
you just messed up the dimensions.你只是搞砸了尺寸。
Just change只是改变
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)
to至
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.