Files
2025-11-11 11:17:35 +01:00

32 KiB

In [7]:
import pandas as pd

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
In [8]:
FEATURE_PATH = "output/feature_vectors.csv"
In [9]:
df = pd.read_csv(FEATURE_PATH, sep=",")
In [10]:
# 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   
6        7   8.18  19.05  6.07         0.43  2.03  -1.41  12762.97   
7        8  11.38  26.98  8.27         0.48  1.63  -1.40  11034.29   
8        9   5.04  11.61  3.98         0.48  1.34  -1.09    907.83   
9       10   8.76  18.22  4.28         0.86  3.65  -2.05   2532.81   
10      11   0.00   0.00   NaN          NaN  0.00   0.00      0.00   

   transport_mode_curr  
              <lambda>  
0              Driving  
1              Walking  
2              Walking  
3              Driving  
4              Walking  
5              Walking  
6              Driving  
7              Driving  
8              Driving  
9              Driving  
10             Walking  
In [11]:
X = df_features.drop(columns=["transport_mode_curr"])
y = df_features["transport_mode_curr"]

print(X)
print(y)

# Split the data into training and testing sets
X_train, X_test = X.iloc[:5], X.iloc[5:]
y_train, y_test = y.iloc[:5], y.iloc[5:]

print(X_train.shape, X_test.shape)

# Initialize and train the Random Forest Classifier
clf = RandomForestClassifier(random_state=42)

clf.fit(X_train, y_train)

print("Random forrest acc.:" + str(clf.score(X_test, y_test)))
   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
6        7   8.18  19.05  6.07         0.43  2.03  -1.41  12762.97
7        8  11.38  26.98  8.27         0.48  1.63  -1.40  11034.29
8        9   5.04  11.61  3.98         0.48  1.34  -1.09    907.83
9       10   8.76  18.22  4.28         0.86  3.65  -2.05   2532.81
10      11   0.00   0.00   NaN          NaN  0.00   0.00      0.00
   <lambda>
0   Driving
1   Walking
2   Walking
3   Driving
4   Walking
5   Walking
6   Driving
7   Driving
8   Driving
9   Driving
10  Walking
(5, 8) (6, 8)
Random forrest acc.:1.0
/var/folders/jy/q_8fxy9s3zj4zg4knd8kyl5w0000gn/T/ipykernel_45489/3479279711.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)
In [12]:
# Generate predictions
y_pred = clf.predict(X_test)

# Create confusion matrix
cm = confusion_matrix(y_test, y_pred)

# Display confusion matrix
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=clf.classes_)
disp.plot(cmap='Blues', values_format='d')
plt.title('Random Forest Confusion Matrix')
plt.show()

print("\nConfusion Matrix:")
print(cm)
Confusion Matrix:
[[4 0]
 [0 2]]