115 KiB
115 KiB
In [6]:
import gpxpy
import gpxpy.gpx
import numpy as np
from datetime import datetime
class GPXTrack:
def __init__(self, file_path):
self.file_path = file_path
self.points = []
self._parse_gpx()
def _parse_gpx(self):
"""Liest die GPX-Datei ein und speichert alle Trackpunkte, inkl. gpxtpx:speed."""
import xml.etree.ElementTree as ET
with open(self.file_path, 'r', encoding='utf-8') as gpx_file:
gpx = gpxpy.parse(gpx_file)
for track in gpx.tracks:
for segment in track.segments:
for point in segment.points:
speed = None
# Erweiterungen prüfen
if point.extensions:
for ext in point.extensions:
# Alle Unterelemente rekursiv durchsuchen
for elem in ext.iter():
tag = elem.tag.lower()
if 'speed' in tag:
try:
speed = float(elem.text)
except (ValueError, TypeError):
speed = None
self.points.append({
'latitude': point.latitude,
'longitude': point.longitude,
'elevation': point.elevation,
'time': point.time,
'speed': speed
})
def to_dataframe(self):
"""Gibt die GPX-Daten als Pandas DataFrame zurück."""
import pandas as pd
return pd.DataFrame(self.points)
def __repr__(self):
return f"<GPXTrack {self.file_path} | {len(self.points)} Punkte>"
def compute_features(self):
"""Berechnet Zeit-, Distanz-, Geschwindigkeits- und Beschleunigungsdaten."""
import numpy as np
import pandas as pd
df = self.to_dataframe().copy()
# Zeitdifferenzen
df['delta_time_s'] = df['time'].diff().dt.total_seconds()
# Haversine-Formel
R = 6371000 # Erdradius (m)
lat1 = np.radians(df['latitude'])
lat2 = np.radians(df['latitude'].shift())
lon1 = np.radians(df['longitude'])
lon2 = np.radians(df['longitude'].shift())
dlat = lat2 - lat1
dlon = lon2 - lon1
a = np.sin(dlat/2)**2 + np.cos(lat1)*np.cos(lat2)*np.sin(dlon/2)**2
df['distance_m'] = 2 * R * np.arcsin(np.sqrt(a))
# Geschwindigkeit (m/s, km/h)
df['computed_speed_m_s'] = df['distance_m'] / df['delta_time_s']
df['computed_speed_kmh'] = df['computed_speed_m_s'] * 3.6
# Beschleunigung (m/s²)
df['acceleration_m_s2'] = df['computed_speed_m_s'].diff() / df['delta_time_s']
return df
In [ ]:
# Beispiel für eine Datei
track1 = GPXTrack(r"D:\Eigene Dateien\Desktop\master\WS25\Projekt\Anaconda\tracks\tracks\track_20251104_143015.gpx") # steht für raw string. Python interpretiert \\ als eigene sachen
track_gehen = GPXTrack(r"D:\Eigene Dateien\Desktop\master\WS25\Projekt\Anaconda\tracks\tracks\track_20251104_062649.gpx") # zu Fuß gehen
track2_Zug = GPXTrack(r"D:\Eigene Dateien\Desktop\master\WS25\Projekt\Anaconda\tracks (2)\tracks\track_20251107_165150.gpx") # Zug fahren
track3_Tram = GPXTrack(r"D:\Eigene Dateien\Desktop\master\WS25\Projekt\Anaconda\tracks (2)\tracks\track_20251105_231029.gpx") # Bahn fahren
track4_Tram = GPXTrack(r"D:\Eigene Dateien\Desktop\master\WS25\Projekt\Anaconda\tracks (2)\tracks\track_20251105_142907.gpx") # Bahn fahren
track5_Tram = GPXTrack(r"D:\Eigene Dateien\Desktop\master\WS25\Projekt\Anaconda\tracks (2)\tracks\track_20251105_092624.gpx") # Bahn fahren
df_all = pd.concat([
track1.compute_features().assign(is_train=1), # Bahn
track_gehen.compute_features().assign(is_train=0),
track2_Zug.compute_features().assign(is_train=0), # Zug
track3_Tram.compute_features().assign(is_train=1), # Tram
track4_Tram.compute_features().assign(is_train=1), # Tram
track5_Tram.compute_features().assign(is_train=1) # Tram
], ignore_index=True)
print(df_all.shape)
df_all.head()
(165, 11)
| latitude | longitude | elevation | time | speed | delta_time_s | distance_m | computed_speed_m_s | computed_speed_kmh | acceleration_m_s2 | is_train | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 51.459444 | 6.984293 | 22.0 | 2025-11-04 13:30:17.994000+00:00 | 4.80 | NaN | NaN | NaN | NaN | NaN | 1 |
| 1 | 51.459475 | 6.988162 | 98.0 | 2025-11-04 13:31:43+00:00 | 3.77 | 85.006 | 268.085402 | 3.153723 | 11.353404 | NaN | 1 |
| 2 | 51.454727 | 6.990654 | 100.0 | 2025-11-04 13:33:13+00:00 | 0.00 | 90.000 | 555.420018 | 6.171334 | 22.216801 | 0.033529 | 1 |
| 3 | 51.453640 | 6.988935 | 99.0 | 2025-11-04 13:34:43+00:00 | 2.42 | 90.000 | 169.679194 | 1.885324 | 6.787168 | -0.047622 | 1 |
| 4 | 51.452241 | 6.987798 | 103.0 | 2025-11-04 13:36:13+00:00 | 0.57 | 90.000 | 174.419978 | 1.938000 | 6.976799 | 0.000585 | 1 |
In [8]:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
# Merkmale und Zielvariable definierenIn [10]:
print(df_all.shape)
df_all.head()
df_all.info()
(165, 11)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 165 entries, 0 to 164
Data columns (total 11 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 latitude 165 non-null float64
1 longitude 165 non-null float64
2 elevation 165 non-null float64
3 time 165 non-null datetime64[ns, SimpleTZ('Z')]
4 speed 165 non-null float64
5 delta_time_s 159 non-null float64
6 distance_m 159 non-null float64
7 computed_speed_m_s 159 non-null float64
8 computed_speed_kmh 159 non-null float64
9 acceleration_m_s2 153 non-null float64
10 is_train 165 non-null int64
dtypes: datetime64[ns, SimpleTZ('Z')](1), float64(9), int64(1)
memory usage: 14.3 KB
In [12]:
# Features (Eingaben)
features = ['computed_speed_kmh', 'acceleration_m_s2', 'distance_m']
# Zielvariable (Label)
target = 'is_train'
# Eingaben & Ausgaben
X = df_all[features].fillna(0)
y = df_all[target]
# Trainings- und Testdaten aufteilen (80% / 20%)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
model = RandomForestClassifier(
n_estimators=100,
random_state=42,
max_depth=10
)
model.fit(X_train, y_train)
print("✅ Modell erfolgreich trainiert!")
y_pred = model.predict(X_test)
print("Classification Report:")
print(classification_report(y_test, y_pred))
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(5,4))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=['Nicht-Bahn', 'Bahn'],
yticklabels=['Nicht-Bahn', 'Bahn'])
plt.xlabel('Vorhergesagt')
plt.ylabel('Tatsächlich')
plt.title('Konfusionsmatrix')
plt.show()
importances = model.feature_importances_
feat_importance = pd.Series(importances, index=features).sort_values(ascending=False)
plt.figure(figsize=(6,4))
feat_importance.plot(kind='barh')
plt.title("Feature Importance (Random Forest)")
plt.xlabel("Wichtigkeit")
plt.show()
track_neu = GPXTrack(r"D:\Eigene Dateien\Desktop\master\WS25\Projekt\Anaconda\tracks\tracks\track_20251029_141948.gpx")
df_neu = track_neu.compute_features()
X_neu = df_neu[features].fillna(0)
df_neu['predicted_is_train'] = model.predict(X_neu)
plt.figure(figsize=(8,6))
plt.scatter(df_neu['longitude'], df_neu['latitude'],
c=df_neu['predicted_is_train'], cmap='coolwarm', s=8)
plt.title("Vorhersage: Bahn (rot) vs. Nicht-Bahn (blau)")
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.show()
✅ Modell erfolgreich trainiert!
Classification Report:
precision recall f1-score support
0 0.85 0.79 0.82 29
1 0.74 0.81 0.77 21
accuracy 0.80 50
macro avg 0.80 0.80 0.80 50
weighted avg 0.80 0.80 0.80 50
In [45]:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
# Beispiel-Daten
X = np.random.rand(100, 1) * 10
y = 3 * X + np.random.randn(100, 1) * 2
# Training/Test-Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# Modell trainieren
model = LinearRegression()
model.fit(X_train, y_train)
# Vorhersage
y_pred = model.predict(X_test)
# Fehler ausgeben
print("RMSE:", np.sqrt(mean_squared_error(y_test, y_pred)))
# Visualisierung
plt.scatter(X_test, y_test, label="True")
plt.plot(X_test, y_pred, color="red", label="Predicted")
plt.legend()
plt.show()
RMSE: 2.2233251407143673