简体   繁体   中英

i'm getting loss = nan and accuracy = 0 for classification using LSTM, keras model

I'm Trying motion classification using lstm. this is my model

def evaluate_model(trainX, trainy, testX, testy):
    verbose, epochs, batch_size = 0, 10, 32
    n_timesteps, n_features, n_outputs = trainX.shape[1], trainX.shape[2], trainy.shape[1]
    model = Sequential()
    model.add(LSTM(32, input_shape=(n_timesteps,n_features)))
    # model.add(Dropout(0.5))
    # model.add(Dense(32, activation='relu'))
    model.add(Dense(n_outputs, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, verbose=verbose)
    loss, accuracy = model.evaluate(testX, testy, batch_size=batch_size, verbose=0)
    return loss, accuracy


for r in range(repeats):
    loss, score = evaluate_model(trainx, trainy, testx, testy)
    score = score * 100.0
    print('>#%d: %.3f' % (r+1, score))
    print('>#%d: %.3f' % (r+1, loss))

this is my output

>#1: 0.000
>#1: nan
>#2: 0.000
>#2: nan
>#3: 0.000
>#3: nan
>#4: 0.000
>#4: nan
>#5: 0.000
>#5: nan
>#6: 0.000
>#6: nan
>#7: 0.000
>#7: nan
>#8: 0.000
>#8: nan
>#9: 0.000
>#9: nan
>#10: 0.000
>#10: nan
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
Accuracy: 0.000% (+/-0.000)

where did I go wrong? I have seen some regression models get nan loss but I'm using a classification model. is it because of my data?

these are the sizes of test and train

Check your data.

Your model wirks well on random data:

import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import LSTM, Dense
def evaluate_model(trainX, trainy, testX, testy):
    verbose, epochs, batch_size = 0, 10, 32
    n_timesteps, n_features, n_outputs = trainX.shape[1], trainX.shape[2], trainy.shape[1]
    model = Sequential()
    model.add(LSTM(32, input_shape=(n_timesteps,n_features)))
    model.add(Dense(n_outputs, activation='softmax'))
    #model.summary()
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, verbose=verbose)
    loss, accuracy = model.evaluate(testX, testy, batch_size=batch_size, verbose=0)
    return loss, accuracy


for r in range(5):
    trainx = tf.random.uniform([10, 10, 10])
    trainy = tf.random.uniform([10, 10])
    testx = tf.random.uniform([10, 10, 10])
    testy = tf.random.uniform([10, 10])
    loss, score = evaluate_model(trainx, trainy, testx, testy)
    score = score * 100.0
    print('>#%d: %.3f' % (r+1, score))
    print('>#%d: %.3f' % (r+1, loss))
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM