5.3 KiB
5.3 KiB
In [1]:
import pandas as pd
from sklearn.ensemble import RandomForestClassifierIn [2]:
FEATURE_PATH = "output/feature_vectors.csv"In [3]:
df = pd.read_csv(FEATURE_PATH, sep=",")In [4]:
# Group by trip_id and calculate aggregated metrics
df_features = df.groupby('trip_id').agg({
'speed': ['mean', 'max', 'std'],
'acceleration': ['std','max', 'min'],
'distance': 'sum',
'transport_mode_curr': lambda x: x.mode()[0] # Most frequent transport mode
}).round(2)
# Reset index to make trip_id a column
df_features = df_features.reset_index()
print(df_features) trip_id speed acceleration distance \
mean max std std max min sum
0 1 4.82 14.19 4.69 1.12 1.22 -13.73 4124.72
1 2 1.12 2.12 0.64 4.14 0.30 -24.11 192.19
2 3 0.28 4.94 0.58 1.43 0.25 -17.19 489.18
3 4 6.88 46.92 7.97 3.50 8.08 -35.32 4674.00
4 5 1.44 3.04 0.49 0.10 0.44 -0.29 657.74
5 6 1.41 3.74 0.57 0.17 1.00 -0.38 678.08
transport_mode_curr
<lambda>
0 Driving
1 Walking
2 Walking
3 Driving
4 Walking
5 Walking
In [13]:
X = df_features.drop(columns=["transport_mode_curr"])
y = df_features["transport_mode_curr"]
print(X)
print(y)
X_train, X_test = X.iloc[:3], X.iloc[3:]
y_train, y_test = y.iloc[:3], y.iloc[3:]
print(X_train.shape, X_test.shape)
clf = RandomForestClassifier(random_state=42)
clf.fit(X_train, y_train)
clf.apply(X)
clf.score(X_test, y_test)Out [13]:
/var/folders/jy/q_8fxy9s3zj4zg4knd8kyl5w0000gn/T/ipykernel_14967/1003445672.py:1: PerformanceWarning: dropping on a non-lexsorted multi-index without a level parameter may impact performance. X = df_features.drop(columns=["transport_mode_curr"]) /opt/anaconda3/envs/sumoc_demo/lib/python3.11/site-packages/sklearn/base.py:1365: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel(). return fit_method(estimator, *args, **kwargs)
trip_id speed acceleration distance
mean max std std max min sum
0 1 4.82 14.19 4.69 1.12 1.22 -13.73 4124.72
1 2 1.12 2.12 0.64 4.14 0.30 -24.11 192.19
2 3 0.28 4.94 0.58 1.43 0.25 -17.19 489.18
3 4 6.88 46.92 7.97 3.50 8.08 -35.32 4674.00
4 5 1.44 3.04 0.49 0.10 0.44 -0.29 657.74
5 6 1.41 3.74 0.57 0.17 1.00 -0.38 678.08
<lambda>
0 Driving
1 Walking
2 Walking
3 Driving
4 Walking
5 Walking
(3, 8) (3, 8)
0.6666666666666666
In [14]:
clf.predict(X_test)Out [14]:
array(['Walking', 'Walking', 'Walking'], dtype=object)