我在训练LSTM模型时损失值显示为NaN,准确率为0

我试图根据历史数据预测股票价格。我使用LSTM来训练我的模型。但在训练过程中,损失值显示为NaN,准确率为0。我使用的数据来自Yahoo Finance,是Yes Bank股票5年的数据。我已经将数据分为测试集和训练集,并进行了特征缩放(虽然不是必需的)。添加了两个LSTM层来训练模型。

我的代码如下:

import pandas as pdimport matplotlib.pyplot as pltimport numpy as npfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import LSTMfrom keras.layers import Dropout#Get the Datadata = pd.read_csv('YESBANK.NS.csv')X = data.iloc[:, [5]].values# Splitting the dataset into the Training set and Test setfrom sklearn.model_selection import train_test_splitX_train, X_test = train_test_split(X, test_size = 0.2, random_state = 0)# Feature Scalingfrom sklearn.preprocessing import MinMaxScalersc = MinMaxScaler(feature_range = (0, 1))training_set_scaled = sc.fit_transform(X_train)# Creating a data structure with 60 timesteps and 1 outputX_train1 = []y_train1 = []for i in range(60, training_set_scaled.shape[0]):    X_train1.append(training_set_scaled[i-60:i, 0])    y_train1.append(training_set_scaled[i, 0])X_train, y_train = np.array(X_train1), np.array(y_train1)# Reshaping for LSTM X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))#Initialize the RNNmodel = Sequential()#Adding first LSTM layermodel.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))model.add(Dropout(0.2))# #Adding second LSTM layer# model.add(LSTM(units=50, return_sequences=True))# model.add(Dropout(0.2))# #Adding third LSTM layer# model.add(LSTM(units= 50, return_sequences=True))# model.add(Dropout(0.2))#Adding fourth LSTM layermodel.add(LSTM(units=50, return_sequences=False))model.add(Dropout(0.2))#Adding Output layermodel.add(Dense(units=1))#Compiling the RNNmodel.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics = ['accuracy'])#Fitiing the RNNmodel.fit(X_train, y_train, epochs = 500, batch_size = 10) ```

回答:

最有可能的情况是你的输入数据中包含NaN。如果你使用的是这份数据,那么在撰写本文时,第142行除了日期列之外全部是NaN。这些值会在缩放过程中传播,并导致网络返回NaN。一个快速且合理的解决方案是在读取数据后添加以下这行代码:

data = data.fillna(data.mean())

另外需要注意的几点:

  1. pd.read_csv可以直接从URL读取数据。
  2. 对于时间序列问题,简单地使用train_test_split并设置shuffle=True并不是理想的做法,如果你想使用模型进行预测。测试集的目的是充当未见数据,而这种安排并未满足这一要求。你应该考虑在某个截止日期之前的数据作为train,之后的数据作为test,这样更能代表预测情况(如果这是你的意图,考虑到神经网络的不可解释性,我假设这是你的意图)。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注