InvalidArgumentError: incompatible shapes: [32,153] vs [32,5] , when using VAERetain similarity distances when using an autoencoder for dimensionality reductionGeneral unsupervised learning strategy when using convolutional autoencoder (CAE)Keras VAE example loss functionHow to set input for proper fit with lstm?What mu and sigma vector really mean in VAE?KL divergence in VAEVariational auto-encoders (VAE): why the random sample?Understanding ELBO Learning Dynamics for VAE?Using VAE with Sequence to Sequence ApproachWhy use Variational Autoencoders VAE insted of Autoencoders AE in Anomaly Detection?

Pressure inside an infinite ocean?

Can't remove one character of space in my environment

Does this article imply that Turing-Computability is not the same as "effectively computable"?

A mathematically illogical argument in the derivation of Hamilton's equation in Goldstein

Why are prions in animal diets not destroyed by the digestive system?

What was the state of the German rail system in 1944?

How long would it take for people to notice a mass disappearance?

Selecting a secure PIN for building access

Can the 歳 counter be used for architecture, furniture etc to tell its age?

Should I replace my bicycle tires if they have not been inflated in multiple years

How to give very negative feedback gracefully?

Independent, post-Brexit Scotland - would there be a hard border with England?

Why is B♯ higher than C♭ in 31-ET?

What are the differences between credential stuffing and password spraying?

What are the spoon bit of a spoon and fork bit of a fork called?

What to use instead of cling film to wrap pastry

I caught several of my students plagiarizing. Could it be my fault as a teacher?

Can there be a single technologically advance nation, in a continent full of non-technologically advance nations

Is this homebrew life-stealing melee cantrip unbalanced?

Enumerate Derangements

If I readied a spell with the trigger "When I take damage", do I have to make a constitution saving throw to avoid losing Concentration?

I need a disease

What is Shri Venkateshwara Mangalasasana stotram recited for?

I drew a randomly colored grid of points with tikz, how do I force it to remember the first grid from then on?



InvalidArgumentError: incompatible shapes: [32,153] vs [32,5] , when using VAE


Retain similarity distances when using an autoencoder for dimensionality reductionGeneral unsupervised learning strategy when using convolutional autoencoder (CAE)Keras VAE example loss functionHow to set input for proper fit with lstm?What mu and sigma vector really mean in VAE?KL divergence in VAEVariational auto-encoders (VAE): why the random sample?Understanding ELBO Learning Dynamics for VAE?Using VAE with Sequence to Sequence ApproachWhy use Variational Autoencoders VAE insted of Autoencoders AE in Anomaly Detection?













0












$begingroup$


I'm working on a sequence to sequence model using LSTM, the model worked perfectly with an autoencoder, but when I try to use a Variational autoencoder by adding the mean and deviation layer and changing the loss function , I get this error:




InvalidArgumentError: Incompatible shapes: [32,153] vs [32,5]




 # Train - Test Split
X, y = lines.eng, lines.fr
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =
0.1)

def generate_batch(X = X_train, y = y_train, batch_size = 32):
''' Generate a batch of data '''
while True:
for j in range(0, len(X), batch_size):
encoder_input_data = np.zeros((batch_size
,max_len_eng),dtype='float32') #max_len_eng = 3
decoder_input_data = np.zeros((batch_size,
max_len_fr),dtype='float32')
#max_len_french =5
decoder_target_data = np.zeros((batch_size,max_len_fr,
num_decoder_tokens), dtype='float32')

for i, (input_text, target_text) in
enumerate(zip(X[j:j+batch_size], y[j:j+batch_size])):
for t, word in enumerate(input_text.split()):
encoder_input_data[i, t] = input_token_index[word]
for t, word in enumerate(target_text.split()):
# decoder_target_data is ahead of decoder_input_data by one timestep
if t<len(target_text.split())-1:
decoder_input_data[i, t] =
target_token_index[word]
if t > 0:
# decoder_target_data will be ahead by one timestep
# and will not include the start character.
decoder_target_data[i, t - 1,
target_token_index[word]] = 1
yield([encoder_input_data, decoder_input_data],
decoder_target_data)

encoder_inputs = Input(shape=(None,))
en_x= Embedding(num_encoder_tokens, embedding_size,mask_zero = True)
(encoder_inputs)
encoder = LSTM(50, return_state=True)
encoder_outputs, state_h, state_c = encoder(en_x) #initialisé à 0
encoder_states = [state_h, state_c]

""" -------- ADD VAE -------"""
latent_dim =embedding_size
# output layer for mean and log variance
z_mu = Dense(latent_dim)(encoder_outputs) #remplacer h
z_log_var = Dense(latent_dim)(encoder_outputs)
def sampling(args):
batch_size=1
z_mean, z_log_sigma = args
epsilon = K.random_normal(shape=(batch_size, latent_dim),
mean=0., stddev=1.)
return z_mean + K.exp(z_log_sigma) * epsilon

z = Lambda(sampling, output_shape=(latent_dim,))([z_mu, z_log_var])

state_h= z
state_c = z
encoder_states = [state_h, state_c]
#loss function with VAE
def vae_loss(y_true, y_pred):
""" Calculate loss = reconstruction loss + KL loss for each data in
minibatch """
# E[log P(X|z)]
recon = K.sum(K.binary_crossentropy(y_pred, y_true), axis=1)
# D_KL(Q(z|X) || P(z|X)); calculate in closed form as both dist.
are Gaussian
kl = 0.5 * K.sum(K.exp(z_log_var) + K.square(z_mu) - 1. -
z_log_var, axis=1)
return recon + kl[:, None]


# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None,))
dex= Embedding(num_decoder_tokens, embedding_size,mask_zero = True)
#num_decoder_tokens = 152
final_dex= dex(decoder_inputs)
decoder_lstm = LSTM(50, return_sequences=True, return_state=True)
decoder_outputs, _, _ =
decoder_lstm(final_dex,initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(optimizer='rmsprop', loss=vae_loss, metrics=['acc'])
model.summary()
train_samples = len(X_train)
val_samples = len(X_test)
batch_size = 32
epochs = 5
model.fit_generator(generator = generate_batch(X_train, y_train,
batch_size = batch_size),
steps_per_epoch = train_samples//batch_size,
epochs=epochs,
validation_data = generate_batch(X_test, y_test,
batch_size = batch_size),
validation_steps = 1)

end = time.time()
print("temp d'exec:", end-start)


I tried all solutions suggested on other posts, but no one helped me.
Thanks.










share|improve this question









$endgroup$
















    0












    $begingroup$


    I'm working on a sequence to sequence model using LSTM, the model worked perfectly with an autoencoder, but when I try to use a Variational autoencoder by adding the mean and deviation layer and changing the loss function , I get this error:




    InvalidArgumentError: Incompatible shapes: [32,153] vs [32,5]




     # Train - Test Split
    X, y = lines.eng, lines.fr
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =
    0.1)

    def generate_batch(X = X_train, y = y_train, batch_size = 32):
    ''' Generate a batch of data '''
    while True:
    for j in range(0, len(X), batch_size):
    encoder_input_data = np.zeros((batch_size
    ,max_len_eng),dtype='float32') #max_len_eng = 3
    decoder_input_data = np.zeros((batch_size,
    max_len_fr),dtype='float32')
    #max_len_french =5
    decoder_target_data = np.zeros((batch_size,max_len_fr,
    num_decoder_tokens), dtype='float32')

    for i, (input_text, target_text) in
    enumerate(zip(X[j:j+batch_size], y[j:j+batch_size])):
    for t, word in enumerate(input_text.split()):
    encoder_input_data[i, t] = input_token_index[word]
    for t, word in enumerate(target_text.split()):
    # decoder_target_data is ahead of decoder_input_data by one timestep
    if t<len(target_text.split())-1:
    decoder_input_data[i, t] =
    target_token_index[word]
    if t > 0:
    # decoder_target_data will be ahead by one timestep
    # and will not include the start character.
    decoder_target_data[i, t - 1,
    target_token_index[word]] = 1
    yield([encoder_input_data, decoder_input_data],
    decoder_target_data)

    encoder_inputs = Input(shape=(None,))
    en_x= Embedding(num_encoder_tokens, embedding_size,mask_zero = True)
    (encoder_inputs)
    encoder = LSTM(50, return_state=True)
    encoder_outputs, state_h, state_c = encoder(en_x) #initialisé à 0
    encoder_states = [state_h, state_c]

    """ -------- ADD VAE -------"""
    latent_dim =embedding_size
    # output layer for mean and log variance
    z_mu = Dense(latent_dim)(encoder_outputs) #remplacer h
    z_log_var = Dense(latent_dim)(encoder_outputs)
    def sampling(args):
    batch_size=1
    z_mean, z_log_sigma = args
    epsilon = K.random_normal(shape=(batch_size, latent_dim),
    mean=0., stddev=1.)
    return z_mean + K.exp(z_log_sigma) * epsilon

    z = Lambda(sampling, output_shape=(latent_dim,))([z_mu, z_log_var])

    state_h= z
    state_c = z
    encoder_states = [state_h, state_c]
    #loss function with VAE
    def vae_loss(y_true, y_pred):
    """ Calculate loss = reconstruction loss + KL loss for each data in
    minibatch """
    # E[log P(X|z)]
    recon = K.sum(K.binary_crossentropy(y_pred, y_true), axis=1)
    # D_KL(Q(z|X) || P(z|X)); calculate in closed form as both dist.
    are Gaussian
    kl = 0.5 * K.sum(K.exp(z_log_var) + K.square(z_mu) - 1. -
    z_log_var, axis=1)
    return recon + kl[:, None]


    # Set up the decoder, using `encoder_states` as initial state.
    decoder_inputs = Input(shape=(None,))
    dex= Embedding(num_decoder_tokens, embedding_size,mask_zero = True)
    #num_decoder_tokens = 152
    final_dex= dex(decoder_inputs)
    decoder_lstm = LSTM(50, return_sequences=True, return_state=True)
    decoder_outputs, _, _ =
    decoder_lstm(final_dex,initial_state=encoder_states)
    decoder_dense = Dense(num_decoder_tokens, activation='softmax')
    decoder_outputs = decoder_dense(decoder_outputs)
    model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
    model.compile(optimizer='rmsprop', loss=vae_loss, metrics=['acc'])
    model.summary()
    train_samples = len(X_train)
    val_samples = len(X_test)
    batch_size = 32
    epochs = 5
    model.fit_generator(generator = generate_batch(X_train, y_train,
    batch_size = batch_size),
    steps_per_epoch = train_samples//batch_size,
    epochs=epochs,
    validation_data = generate_batch(X_test, y_test,
    batch_size = batch_size),
    validation_steps = 1)

    end = time.time()
    print("temp d'exec:", end-start)


    I tried all solutions suggested on other posts, but no one helped me.
    Thanks.










    share|improve this question









    $endgroup$














      0












      0








      0





      $begingroup$


      I'm working on a sequence to sequence model using LSTM, the model worked perfectly with an autoencoder, but when I try to use a Variational autoencoder by adding the mean and deviation layer and changing the loss function , I get this error:




      InvalidArgumentError: Incompatible shapes: [32,153] vs [32,5]




       # Train - Test Split
      X, y = lines.eng, lines.fr
      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =
      0.1)

      def generate_batch(X = X_train, y = y_train, batch_size = 32):
      ''' Generate a batch of data '''
      while True:
      for j in range(0, len(X), batch_size):
      encoder_input_data = np.zeros((batch_size
      ,max_len_eng),dtype='float32') #max_len_eng = 3
      decoder_input_data = np.zeros((batch_size,
      max_len_fr),dtype='float32')
      #max_len_french =5
      decoder_target_data = np.zeros((batch_size,max_len_fr,
      num_decoder_tokens), dtype='float32')

      for i, (input_text, target_text) in
      enumerate(zip(X[j:j+batch_size], y[j:j+batch_size])):
      for t, word in enumerate(input_text.split()):
      encoder_input_data[i, t] = input_token_index[word]
      for t, word in enumerate(target_text.split()):
      # decoder_target_data is ahead of decoder_input_data by one timestep
      if t<len(target_text.split())-1:
      decoder_input_data[i, t] =
      target_token_index[word]
      if t > 0:
      # decoder_target_data will be ahead by one timestep
      # and will not include the start character.
      decoder_target_data[i, t - 1,
      target_token_index[word]] = 1
      yield([encoder_input_data, decoder_input_data],
      decoder_target_data)

      encoder_inputs = Input(shape=(None,))
      en_x= Embedding(num_encoder_tokens, embedding_size,mask_zero = True)
      (encoder_inputs)
      encoder = LSTM(50, return_state=True)
      encoder_outputs, state_h, state_c = encoder(en_x) #initialisé à 0
      encoder_states = [state_h, state_c]

      """ -------- ADD VAE -------"""
      latent_dim =embedding_size
      # output layer for mean and log variance
      z_mu = Dense(latent_dim)(encoder_outputs) #remplacer h
      z_log_var = Dense(latent_dim)(encoder_outputs)
      def sampling(args):
      batch_size=1
      z_mean, z_log_sigma = args
      epsilon = K.random_normal(shape=(batch_size, latent_dim),
      mean=0., stddev=1.)
      return z_mean + K.exp(z_log_sigma) * epsilon

      z = Lambda(sampling, output_shape=(latent_dim,))([z_mu, z_log_var])

      state_h= z
      state_c = z
      encoder_states = [state_h, state_c]
      #loss function with VAE
      def vae_loss(y_true, y_pred):
      """ Calculate loss = reconstruction loss + KL loss for each data in
      minibatch """
      # E[log P(X|z)]
      recon = K.sum(K.binary_crossentropy(y_pred, y_true), axis=1)
      # D_KL(Q(z|X) || P(z|X)); calculate in closed form as both dist.
      are Gaussian
      kl = 0.5 * K.sum(K.exp(z_log_var) + K.square(z_mu) - 1. -
      z_log_var, axis=1)
      return recon + kl[:, None]


      # Set up the decoder, using `encoder_states` as initial state.
      decoder_inputs = Input(shape=(None,))
      dex= Embedding(num_decoder_tokens, embedding_size,mask_zero = True)
      #num_decoder_tokens = 152
      final_dex= dex(decoder_inputs)
      decoder_lstm = LSTM(50, return_sequences=True, return_state=True)
      decoder_outputs, _, _ =
      decoder_lstm(final_dex,initial_state=encoder_states)
      decoder_dense = Dense(num_decoder_tokens, activation='softmax')
      decoder_outputs = decoder_dense(decoder_outputs)
      model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
      model.compile(optimizer='rmsprop', loss=vae_loss, metrics=['acc'])
      model.summary()
      train_samples = len(X_train)
      val_samples = len(X_test)
      batch_size = 32
      epochs = 5
      model.fit_generator(generator = generate_batch(X_train, y_train,
      batch_size = batch_size),
      steps_per_epoch = train_samples//batch_size,
      epochs=epochs,
      validation_data = generate_batch(X_test, y_test,
      batch_size = batch_size),
      validation_steps = 1)

      end = time.time()
      print("temp d'exec:", end-start)


      I tried all solutions suggested on other posts, but no one helped me.
      Thanks.










      share|improve this question









      $endgroup$




      I'm working on a sequence to sequence model using LSTM, the model worked perfectly with an autoencoder, but when I try to use a Variational autoencoder by adding the mean and deviation layer and changing the loss function , I get this error:




      InvalidArgumentError: Incompatible shapes: [32,153] vs [32,5]




       # Train - Test Split
      X, y = lines.eng, lines.fr
      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =
      0.1)

      def generate_batch(X = X_train, y = y_train, batch_size = 32):
      ''' Generate a batch of data '''
      while True:
      for j in range(0, len(X), batch_size):
      encoder_input_data = np.zeros((batch_size
      ,max_len_eng),dtype='float32') #max_len_eng = 3
      decoder_input_data = np.zeros((batch_size,
      max_len_fr),dtype='float32')
      #max_len_french =5
      decoder_target_data = np.zeros((batch_size,max_len_fr,
      num_decoder_tokens), dtype='float32')

      for i, (input_text, target_text) in
      enumerate(zip(X[j:j+batch_size], y[j:j+batch_size])):
      for t, word in enumerate(input_text.split()):
      encoder_input_data[i, t] = input_token_index[word]
      for t, word in enumerate(target_text.split()):
      # decoder_target_data is ahead of decoder_input_data by one timestep
      if t<len(target_text.split())-1:
      decoder_input_data[i, t] =
      target_token_index[word]
      if t > 0:
      # decoder_target_data will be ahead by one timestep
      # and will not include the start character.
      decoder_target_data[i, t - 1,
      target_token_index[word]] = 1
      yield([encoder_input_data, decoder_input_data],
      decoder_target_data)

      encoder_inputs = Input(shape=(None,))
      en_x= Embedding(num_encoder_tokens, embedding_size,mask_zero = True)
      (encoder_inputs)
      encoder = LSTM(50, return_state=True)
      encoder_outputs, state_h, state_c = encoder(en_x) #initialisé à 0
      encoder_states = [state_h, state_c]

      """ -------- ADD VAE -------"""
      latent_dim =embedding_size
      # output layer for mean and log variance
      z_mu = Dense(latent_dim)(encoder_outputs) #remplacer h
      z_log_var = Dense(latent_dim)(encoder_outputs)
      def sampling(args):
      batch_size=1
      z_mean, z_log_sigma = args
      epsilon = K.random_normal(shape=(batch_size, latent_dim),
      mean=0., stddev=1.)
      return z_mean + K.exp(z_log_sigma) * epsilon

      z = Lambda(sampling, output_shape=(latent_dim,))([z_mu, z_log_var])

      state_h= z
      state_c = z
      encoder_states = [state_h, state_c]
      #loss function with VAE
      def vae_loss(y_true, y_pred):
      """ Calculate loss = reconstruction loss + KL loss for each data in
      minibatch """
      # E[log P(X|z)]
      recon = K.sum(K.binary_crossentropy(y_pred, y_true), axis=1)
      # D_KL(Q(z|X) || P(z|X)); calculate in closed form as both dist.
      are Gaussian
      kl = 0.5 * K.sum(K.exp(z_log_var) + K.square(z_mu) - 1. -
      z_log_var, axis=1)
      return recon + kl[:, None]


      # Set up the decoder, using `encoder_states` as initial state.
      decoder_inputs = Input(shape=(None,))
      dex= Embedding(num_decoder_tokens, embedding_size,mask_zero = True)
      #num_decoder_tokens = 152
      final_dex= dex(decoder_inputs)
      decoder_lstm = LSTM(50, return_sequences=True, return_state=True)
      decoder_outputs, _, _ =
      decoder_lstm(final_dex,initial_state=encoder_states)
      decoder_dense = Dense(num_decoder_tokens, activation='softmax')
      decoder_outputs = decoder_dense(decoder_outputs)
      model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
      model.compile(optimizer='rmsprop', loss=vae_loss, metrics=['acc'])
      model.summary()
      train_samples = len(X_train)
      val_samples = len(X_test)
      batch_size = 32
      epochs = 5
      model.fit_generator(generator = generate_batch(X_train, y_train,
      batch_size = batch_size),
      steps_per_epoch = train_samples//batch_size,
      epochs=epochs,
      validation_data = generate_batch(X_test, y_test,
      batch_size = batch_size),
      validation_steps = 1)

      end = time.time()
      print("temp d'exec:", end-start)


      I tried all solutions suggested on other posts, but no one helped me.
      Thanks.







      python neural-network lstm autoencoder vae






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 9 at 15:04









      KikioKikio

      9110




      9110




















          0






          active

          oldest

          votes












          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "557"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f48970%2finvalidargumenterror-incompatible-shapes-32-153-vs-32-5-when-using-vae%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Data Science Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f48970%2finvalidargumenterror-incompatible-shapes-32-153-vs-32-5-when-using-vae%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

          Tähtien Talli Jäsenet | Lähteet | NavigointivalikkoSuomen Hippos – Tähtien Talli

          Do these cracks on my tires look bad? The Next CEO of Stack OverflowDry rot tire should I replace?Having to replace tiresFishtailed so easily? Bad tires? ABS?Filling the tires with something other than air, to avoid puncture hassles?Used Michelin tires safe to install?Do these tyre cracks necessitate replacement?Rumbling noise: tires or mechanicalIs it possible to fix noisy feathered tires?Are bad winter tires still better than summer tires in winter?Torque converter failure - Related to replacing only 2 tires?Why use snow tires on all 4 wheels on 2-wheel-drive cars?