Files
SuMoC_Task/ml_stuff/feature_vectors.ipynb

9.5 KiB

In [1]:
import pandas as pd
from haversine import haversine, Unit
import os
In [2]:
# Loading all csv files into one df with unique tripIds

DATA_FOLDER = "data/" # Path format for jupyter notebook

df_list = []
trip_id_offset = 0

for file in os.listdir(DATA_FOLDER):
    if file.endswith(".csv"):
        df_temp = pd.read_csv(os.path.join(DATA_FOLDER, file), sep=";")
        df_temp['tripId'] = df_temp['tripId'] + trip_id_offset
        trip_id_offset = df_temp['tripId'].max()
        df_list.append(df_temp)

df_raw = pd.concat(df_list, ignore_index=True)
In [3]:
# Create feature DF with prev information

df_feature = pd.DataFrame({
    'lat_prev': df_raw['latitude'].shift(1),
    'lat_curr': df_raw['latitude'],
    'lon_prev': df_raw['longitude'].shift(1),
    'lon_curr': df_raw['longitude'],
    'timestamp_prev': df_raw['timestamp'].shift(1),
    'timestamp': df_raw['timestamp'],
    'transport_mode_curr': df_raw['transportMode'],
    'trip_id': df_raw['tripId'].astype(int),
    'trip_id_prev': df_raw['tripId'].shift(1).astype('Int64')
})
df_feature = df_feature.dropna().reset_index(drop=True) # Dropping first row that has nan because of the shift

print(df_feature)
       lat_prev   lat_curr   lon_prev   lon_curr  timestamp_prev  \
0     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
1     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
2     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
3     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
4     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
...         ...        ...        ...        ...             ...   
1469  53.868674  53.869151  10.695905  10.695855    1.762679e+12   
1470  53.869151  53.869227  10.695855  10.695225    1.762679e+12   
1471  53.869227  53.869136  10.695225  10.694732    1.762679e+12   
1472  53.869136  53.869209  10.694732  10.693664    1.762679e+12   
1473  53.869209  51.443373  10.693664   6.986519    1.762679e+12   

          timestamp transport_mode_curr  trip_id  trip_id_prev  
0     1762336816629             Driving        1             1  
1     1762336823364             Driving        1             1  
2     1762336830405             Driving        1             1  
3     1762336837274             Driving        1             1  
4     1762336844156             Driving        1             1  
...             ...                 ...      ...           ...  
1469  1762678928349             Driving       10            10  
1470  1762678933343             Driving       10            10  
1471  1762678938340             Driving       10            10  
1472  1762678949373             Driving       10            10  
1473  1762687187275             Walking       11            10  

[1474 rows x 9 columns]
In [4]:
# Calculating distance in meters
df_feature['distance'] = df_feature.apply(
    lambda r: haversine(
        (r['lat_prev'], r['lon_prev']),
        (r['lat_curr'], r['lon_curr']),
        unit=Unit.METERS
    ),
    axis=1
)

# Calculating speed in m/s
df_feature['speed'] = df_feature.apply(
    lambda r: r['distance'] / ((r['timestamp'] - r['timestamp_prev']) / 1000), axis=1
)
In [5]:
# Calculate acceleration using vectorized operations
df_feature['speed_prev'] = df_feature['speed'].shift(1)
df_feature['acceleration'] = (df_feature['speed'] - df_feature['speed_prev']) / ((df_feature['timestamp'] - df_feature['timestamp_prev']) / 1000)

# Drop the temporary column
df_feature = df_feature.drop(columns=['speed_prev'])
print(df_feature)

# Set first row acceleration to NaN or 0
df_feature.loc[0, 'acceleration'] = 0

def clean_first_row_of_trip(row):
    if row['trip_id'] != row['trip_id_prev']:
        row['distance'] = 0
        row['speed'] = 0
        row['acceleration'] = 0
    return row
df_feature = df_feature.apply(clean_first_row_of_trip, axis=1)


# Filtering unrealistic values
def is_valid_row(row):
    if row['transport_mode_curr'] == 'Driving' and (row ['speed'] > 50.00 or row['acceleration'] > 10.0):
        return False
    elif row['transport_mode_curr'] == 'Walking' and (row ['speed'] > 7.00 or row['acceleration'] > 3.0):
        return False
    elif row['transport_mode_curr'] == 'Train' and (row ['speed'] > 100.00 or row['acceleration'] > 15.0):
        return False
    elif row['transport_mode_curr'] == 'Bus' and (row ['speed'] > 80.00 or row['acceleration'] > 12.0):
        return False
    else:
        return True
df_feature = df_feature[df_feature.apply(is_valid_row, axis=1)].reset_index(drop=True)
       lat_prev   lat_curr   lon_prev   lon_curr  timestamp_prev  \
0     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
1     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
2     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
3     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
4     51.445878  51.445878   6.983089   6.983089    1.762337e+12   
...         ...        ...        ...        ...             ...   
1469  53.868674  53.869151  10.695905  10.695855    1.762679e+12   
1470  53.869151  53.869227  10.695855  10.695225    1.762679e+12   
1471  53.869227  53.869136  10.695225  10.694732    1.762679e+12   
1472  53.869136  53.869209  10.694732  10.693664    1.762679e+12   
1473  53.869209  51.443373  10.693664   6.986519    1.762679e+12   

          timestamp transport_mode_curr  trip_id  trip_id_prev       distance  \
0     1762336816629             Driving        1             1       0.000000   
1     1762336823364             Driving        1             1       0.000000   
2     1762336830405             Driving        1             1       0.000000   
3     1762336837274             Driving        1             1       0.000000   
4     1762336844156             Driving        1             1       0.000000   
...             ...                 ...      ...           ...            ...   
1469  1762678928349             Driving       10            10      53.128555   
1470  1762678933343             Driving       10            10      42.130594   
1471  1762678938340             Driving       10            10      33.877720   
1472  1762678949373             Driving       10            10      70.470524   
1473  1762687187275             Walking       11            10  367713.427447   

          speed  acceleration  
0      0.000000           NaN  
1      0.000000      0.000000  
2      0.000000      0.000000  
3      0.000000      0.000000  
4      0.000000      0.000000  
...         ...           ...  
1469  10.638477     -0.114961  
1470   8.436242     -0.440976  
1471   6.779612     -0.331525  
1472   6.387249     -0.035563  
1473  44.636781      0.004643  

[1474 rows x 12 columns]
In [6]:
df_feature.to_csv("output/feature_vectors.csv")