【问题标题】:Issue with dataframe dates, concat takes too much time, wrong graph output数据框日期问题,concat 花费太多时间,图形输出错误
【发布时间】:2020-08-12 04:35:41
【问题描述】:

我有一些我无法解决的问题,我真的不明白发生了什么。

我有原始数据集 lrdata4

	year	total_vehicles
0	2000	419587299
1	2001	425832533
2	2002	430480581
3	2003	434270003
4	2004	442680113

from statsmodels.tools.eval_measures import rmse
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dropout
import warnings

warnings.filterwarnings('ignore')

当我这样做时

lrdata4.year = pd.to_datetime(lrdata4.year)
lrdata4 = lrdata4.set_index('year')
lrdata4.tail(10)

岁月变了,我不知道为什么。有什么帮助吗?

total_vehicles
year	
1970-01-01 00:00:00.000002009	443333980
1970-01-01 00:00:00.000002010	438827716
1970-01-01 00:00:00.000002011	440461505
1970-01-01 00:00:00.000002012	440073277
1970-01-01 00:00:00.000002013	441751395
1970-01-01 00:00:00.000002014	451394270
1970-01-01 00:00:00.000002015	460050397
1970-01-01 00:00:00.000002016	470256985
1970-01-01 00:00:00.000002017	474693803
1970-01-01 00:00:00.000002018	473765568

那么我正在准备模型来进行时间序列预测

train, test = lrdata4[:-12], lrdata4[-12:]

enter code herescaler = MinMaxScaler()
scaler.fit(train)
train = scaler.transform(train)
test = scaler.transform(test)


n_input = 24
n_features = 1

generator = TimeseriesGenerator(train, train, length = n_input, batch_size =1000)

model = Sequential()
model.add(LSTM(200, activation= 'relu', input_shape=(n_input, n_features)))
model.add(Dropout(0.15))
model.add(Dense(1))
model.compile(optimizer='adam', loss ='mse')

model.fit_generator(generator, epochs=20)

我得到预测并将它们附加到列表中

pred_list = []

batch = train[-n_input:].reshape((1 ,n_input, n_features))

for i in range(n_input):
    pred_list.append(model.predict(batch)[0])
    batch = np.append(batch[:, 1:,:],[[pred_list[i]]], axis=1)

我正在尝试连接我的原始数据帧 lrdata4 和新的数据帧 df_predict

df_predict = pd.DataFrame(scaler.inverse_transform(pred_list), index= lrdata4[-n_input:].index,columns=['Predictions'])
df_test = pd.concat([lrdata4, df_predict], axis = 1)

但是 concat 需要永远。我把它放了4个小时,它还在继续。是因为我的原始数据集有 200k 数据吗?还有其他方法吗?

我尝试过以不同的方式绘制它们

plt.figure(figsize= (20,5))
plt.plot(lrdata4.index, lrdata4['total_vehicles'])
plt.plot(df_predict.index, df_predict['Predictions'], color ='r')
plt.show()

但是该图不是带有原始数据的折线图,而预测数据是连续折线图,而且年份是错误的,我不明白为什么 This is how the graph looks like

【问题讨论】:

    标签: python dataframe time-series forecasting


    【解决方案1】:

    这里的年份是一个整数 - 因此尝试转换为日期是行不通的。如果你真的希望它是一个日期时间,那么你可以尝试使用类似的东西来转换年份;

    df['year'] = df['year'].apply(lambda x: '{}-01-01'.format(x))
    

    然后使用pd.to_datetime 转换为日期时间。

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 2023-03-17
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多