Samuel Tosetto
Samuel Tosetto

Reputation: 11

Recurrent neural network in python (keras) error: ValueError: `logits` and `labels` must have the same shape, received ((None, 90, 1) vs (None,))

I'm developing a recurrent neural network in python using keras to do binary classification on roulette wheel data. I'm trying to compile my code but it's crashing, could you help me fix the code please?

Here is my code:

from keras.models import Sequential
from keras.layers import Dense, Dropout
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import pandas as pd

columns = ['data', 'resultado']
base = pd.read_csv("blaze_values_27_01_2023_VERMELHO_1.csv", header = None, names = columns)
base = base.dropna()
base_treinamento = base.iloc[:, 1:2]

normalizador = MinMaxScaler(feature_range=[0,1])
base_treinamento_normalizada = normalizador.fit_transform(base_treinamento)


previsores = []
saida_real = []

for i in range (90,1809):
    previsores.append(base_treinamento_normalizada[i-90:i,0])
    saida_real.append(base_treinamento_normalizada[i,0])
previsores, saida_real = np.array(previsores), np.array(saida_real)
previsores = np.reshape(previsores, (previsores.shape[0],previsores.shape[1],1))

regressor = Sequential()
regressor.add(Dense(100, input_shape = (previsores.shape[1],1), activation='relu'))



regressor.add(Dense(1, activation = 'sigmoid'))


regressor.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
regressor.fit(previsores, saida_real, epochs = 100, batch_size = 32)

The error I am getting is: Epoch 1/100 Traceback (most recent call last):

File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356, in compat_exec exec(code, globals, locals)

File "/Users/mac/untitled0.py", line 34, in regressor.fit(previsores, saida_real, epochs = 100, batch_size = 32)

File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler raise e.with_traceback(filtered_tb) from None

File "/var/folders/1j/tbck9lp54kndrb4nl53xdjgr0000gp/T/autograph_generated_file27ts368.py", line 15, in tf__train_function retval = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)

ValueError: in user code:

File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/engine/training.py", line 1051, in train_function  *
    return step_function(self, iterator)
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/engine/training.py", line 1040, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/engine/training.py", line 1030, in run_step  **
    outputs = model.train_step(data)
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/engine/training.py", line 890, in train_step
    loss = self.compute_loss(x, y, y_pred, sample_weight)
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/engine/training.py", line 948, in compute_loss
    return self.compiled_loss(
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/engine/compile_utils.py", line 201, in __call__
    loss_value = loss_obj(y_t, y_p, sample_weight=sw)
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/losses.py", line 139, in __call__
    losses = call_fn(y_true, y_pred)
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/losses.py", line 243, in call  **
    return ag_fn(y_true, y_pred, **self._fn_kwargs)
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/losses.py", line 1930, in binary_crossentropy
    backend.binary_crossentropy(y_true, y_pred, from_logits=from_logits),
File "/Users/mac/opt/anaconda3/lib/python3.9/site-packages/keras/backend.py", line 5283, in binary_crossentropy
    return tf.nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)

ValueError: `logits` and `labels` must have the same shape, received ((None, 90, 1) vs (None,)).

Upvotes: 1

Views: 104

Answers (1)

TheEngineerProgrammer
TheEngineerProgrammer

Reputation: 1461

Remove this: previsores = np.reshape(previsores, (previsores.shape[0],previsores.shape[1],1))

And try this:

regressor.add(layers.Dense(100, input_shape = (previsores.shape[1],), activation='relu'))  

instead of regressor.add(Dense(100, input_shape = (previsores.shape[1],1), activation='relu'))


Another thing, a dense layer as the first layer is not a recurrent neural network, you should try LSTM instead. In that case you can keep that shape. For example:

regressor.add(layers.LSTM(100, input_shape = (previsores.shape[1], 1)))

Upvotes: 0

Related Questions