Вот что я сделал:
Я сгруппировал данные в наборы по 4 строки в Excel и перетасовал их в случайном порядке, используя формула =SORTBY(SEQUENCE(...), RANDARRAY(...)).
Затем я рассчитал среднее значение для каждой группы из 4 строк и присвоил это среднее значение группе.
После этого я отсортировал данные на основе вычисленных средних значений.
Кроме того, я сделал первые четыре и последние четыре строки постоянными в Файл Excel.
Проблема возникает на этом этапе:
Код: Выделить всё
windowed_df = df_to_windowed_df(df,
'1986-03-18',
'2024-05-31',
n=3)
print(windowed_df)
KeyError Traceback (most recent call last)
File index.pyx:598, in pandas._libs.index.DatetimeEngine.get_loc()
File pandas\_libs\hashtable_class_helper.pxi:2606, in pandas._libs.hashtable.Int64HashTable.get_item()
File pandas\_libs\hashtable_class_helper.pxi:2630, in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 512092800000000000
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\indexes\base.py:3791, in Index.get_loc(self, key)
3790 try:
-> 3791 return self._engine.get_loc(casted_key)
3792 except KeyError as err:
File index.pyx:566, in pandas._libs.index.DatetimeEngine.get_loc()
File index.pyx:600, in pandas._libs.index.DatetimeEngine.get_loc()
KeyError: Timestamp('1986-03-25 00:00:00')
The above exception was the direct cause of the following exception:
631 return Index.get_loc(self, key)
632 except KeyError as err:
--> 633 raise KeyError(orig_key) from err
KeyError: Timestamp('1986-03-25 00:00:00')Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Вот полный код:
Код: Выделить всё
#Imports
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
import math
import tensorflow as tf
import keras
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.optimizers import Adam
from keras import layers
from copy import deepcopy
#Date Loading
df=pd.read_csv('Microsoft Dataset_sortido.csv', on_bad_lines='skip')
df=df[['Date', 'Close']]
print(df)
def str_to_datetime(s):
split= s.split('-')
year, month, day= int(split[0]), int(split[1]), int(split[2])
return datetime.datetime(year=year, month=month, day=day)
df['Date']=df['Date'].apply(str_to_datetime)
print(df['Date'])
df.index=df.pop('Date')
print(df)
plt.plot(df.index, df['Close'],'.')
plt.xlabel('Date')
plt.ylabel('Closing Price')
plt.title("Microsoft Stock Closing Prices Over Time")
plt.show()
#LSTM MODEL
def df_to_windowed_df(dataframe, first_date_str, last_date_str, n=3): #n=3 por default
first_date = str_to_datetime(first_date_str)
last_date = str_to_datetime(last_date_str)
target_date = first_date
dates = []
X, Y = [], []
last_time = False
while True:
df_subset = dataframe.loc[:target_date].tail(n+1)
if len(df_subset) != n+1:
print(f'Error: Window of size {n} is too large for date {target_date}')
return
values = df_subset['Close'].to_numpy()
x, y = values[:-1], values[-1]
dates.append(target_date)
X.append(x)
Y.append(y)
next_week = dataframe.loc[target_date:target_date + datetime.timedelta(days=7)]
next_datetime_str = str(next_week.head(2).tail(1).index.values[0])
next_date_str = next_datetime_str.split('T')[0]
year_month_day = next_date_str.split('-')
year, month, day = year_month_day
next_date = datetime.datetime(day=int(day), month=int(month), year=int(year))
if last_time:
break
target_date = next_date
if target_date == last_date:
last_time = True
ret_df = pd.DataFrame({})
ret_df['Target Date'] = dates
X = np.array(X)
for i in range(0, n):
X[:, i]
ret_df[f'Target-{n-i}'] = X[:, i]
ret_df['Target'] = Y
return ret_df
#Error right here
windowed_df = df_to_windowed_df(df,
'1986-03-18',
'2024-05-31',
n=3)
print(windowed_df)
Спросил об этом на других форумах и получил вот ответ:
Я думаю, что ошибка находится в строке 68, она пытается найти точный день 1986-03-25 (через 18 дней + 7 дней), но его нет в кадре данных. Если вы хотите включить какие-либо даты до (включительно) 1986-03-25, я думаю, что индексация со строкой «1986-03-25» вместо даты и времени подойдет (соответствия даты и времени точны - строки могут не быть) .
Но я не совсем уверен, как это сделать.
Подробнее здесь: https://stackoverflow.com/questions/792 ... mp-problem