image_output_1.png
from sklearn.neighbors import KNeighborsRegressor

import datetime

import os

import pandas as pd

root = '/kaggle/input/tabular-playground-series-mar-2022'
train_df = pd.read_csv(os.path.join(root, 'train.csv'))
train_df['datetime'] = pd.to_datetime(train_df.time)
train_df['date'] = train_df.datetime.dt.date
train_df['time'] = train_df.datetime.dt.time
test_df = pd.read_csv(os.path.join(root, 'test.csv'))
test_df['datetime'] = pd.to_datetime(test_df.time)
test_df['date'] = test_df.datetime.dt.date
test_df['time'] = test_df.datetime.dt.time

sep_30 = datetime.date(1991, 9, 30)
mondays = train_df[train_df.datetime.dt.dayofweek == 0]
mondays['is_morning'] = mondays.datetime.dt.hour < 12

labor_day = datetime.date(1991, 9, 2)
memorial_day = datetime.date(1991, 5, 27)
mondays = mondays[(mondays.date != labor_day) & (mondays.date != memorial_day)]
plt.tight_layout()

plt.tight_layout()

for (x, y), G in mondays.groupby(['x', 'y']):
    plt.tight_layout()

for direction, G in mondays.groupby('direction'):
    plt.tight_layout()

train = mondays[mondays.datetime.dt.date < sep_30]
models = {}
for (x, y, direction), G in train.groupby(['x', 'y', 'direction']):
    morning_data = G[G.is_morning]
    afternoon_data = G[~G.is_morning]
    X = morning_data.pivot(index='date', columns='time', values='congestion').reset_index().drop(columns=['date'])
    Y = afternoon_data.pivot(index='date', columns='time', values='congestion').reset_index().drop(columns=['date'])
    model = KNeighborsRegressor()
    models[x, y, direction] = model.fit(X, Y)