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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Untitled0.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1W3XSMmzxThy87iCQTJmPuUZ-3-o3J5tL
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
import pickle
|
| 13 |
+
import pandas as pd
|
| 14 |
+
import numpy as np
|
| 15 |
+
from scipy.signal import butter, filtfilt, find_peaks, welch
|
| 16 |
+
from scipy import stats
|
| 17 |
+
import antropy as ant
|
| 18 |
+
|
| 19 |
+
# Define global constants used in preprocessing and feature extraction
|
| 20 |
+
FS_ACC, FS_GYR, FS_MAG = 204.0, 204.0, 197.0
|
| 21 |
+
|
| 22 |
+
def butter_filter(cutoff, fs, btype, order=4):
|
| 23 |
+
nyq = 0.5 * fs
|
| 24 |
+
b, a = butter(order, cutoff / nyq, btype=btype, analog=False)
|
| 25 |
+
return b, a
|
| 26 |
+
|
| 27 |
+
def preprocess_signal(arr, fs, lp=20.0, hp=0.1, clip_s=5.0):
|
| 28 |
+
sig = arr.copy().astype(float)
|
| 29 |
+
for i in range(sig.shape[1]):
|
| 30 |
+
mu, sd = np.nanmean(sig[:, i]), np.nanstd(sig[:, i])
|
| 31 |
+
sig[:, i] = np.clip(sig[:, i], mu - clip_s*sd, mu + clip_s*sd)
|
| 32 |
+
nans = np.isnan(sig[:, i])
|
| 33 |
+
if nans.any():
|
| 34 |
+
x = np.arange(len(sig[:, i]))
|
| 35 |
+
sig[nans, i] = np.interp(x[nans], x[~nans], sig[~nans, i])
|
| 36 |
+
b_lp, a_lp = butter_filter(min(lp, fs/2-1), fs, 'low')
|
| 37 |
+
b_hp, a_hp = butter_filter(hp, fs, 'high')
|
| 38 |
+
for i in range(sig.shape[1]):
|
| 39 |
+
if len(sig) > 30:
|
| 40 |
+
sig[:, i] = filtfilt(b_lp, a_lp, sig[:, i])
|
| 41 |
+
sig[:, i] = filtfilt(b_hp, a_hp, sig[:, i])
|
| 42 |
+
sd = np.std(sig[:, i])
|
| 43 |
+
if sd > 1e-8:
|
| 44 |
+
sig[:, i] = (sig[:, i] - np.mean(sig[:, i])) / sd
|
| 45 |
+
return sig
|
| 46 |
+
|
| 47 |
+
def safe_entropy(sig, func, **kwargs):
|
| 48 |
+
try:
|
| 49 |
+
return float(func(sig, **kwargs))
|
| 50 |
+
except Exception:
|
| 51 |
+
return np.nan
|
| 52 |
+
|
| 53 |
+
def time_domain_features(sig, fs):
|
| 54 |
+
f = {}
|
| 55 |
+
f['mean'] = np.mean(sig)
|
| 56 |
+
f['std'] = np.std(sig)
|
| 57 |
+
f['rms'] = np.sqrt(np.mean(sig**2))
|
| 58 |
+
f['range'] = np.max(sig) - np.min(sig)
|
| 59 |
+
f['iqr'] = float(np.percentile(sig, 75) - np.percentile(sig, 25))
|
| 60 |
+
f['skewness'] = float(stats.skew(sig))
|
| 61 |
+
f['kurtosis'] = float(stats.kurtosis(sig))
|
| 62 |
+
zc = np.where(np.diff(np.sign(sig)))[0]
|
| 63 |
+
f['zcr'] = len(zc) / (len(sig) / fs) if len(sig) > 0 else 0
|
| 64 |
+
jerk = np.diff(sig) * fs
|
| 65 |
+
f['jerk_rms'] = np.sqrt(np.mean(jerk**2)) if len(jerk) > 0 else 0
|
| 66 |
+
f['jerk_std'] = np.std(jerk) if len(jerk) > 0 else 0
|
| 67 |
+
f['jerk_max'] = np.max(np.abs(jerk)) if len(jerk) > 0 else 0
|
| 68 |
+
thresh = np.percentile(np.abs(sig), 60)
|
| 69 |
+
min_d = int(0.3 * fs)
|
| 70 |
+
peaks, props = find_peaks(sig, height=thresh, distance=min_d)
|
| 71 |
+
n_steps = len(peaks)
|
| 72 |
+
dur = len(sig) / fs
|
| 73 |
+
f['step_count'] = n_steps
|
| 74 |
+
f['cadence_spm'] = (n_steps / dur) * 60 if dur > 0 else 0
|
| 75 |
+
if n_steps >= 3:
|
| 76 |
+
ivls = np.diff(peaks) / fs
|
| 77 |
+
f['step_ivl_mean'] = np.mean(ivls)
|
| 78 |
+
f['step_ivl_std'] = np.std(ivls)
|
| 79 |
+
f['step_ivl_cv'] = f['step_ivl_std'] / f['step_ivl_mean'] if f['step_ivl_mean'] > 0 else np.nan
|
| 80 |
+
f['step_ivl_range'] = np.max(ivls) - np.min(ivls)
|
| 81 |
+
amps = props['peak_heights']
|
| 82 |
+
f['peak_amp_cv'] = np.std(amps) / np.mean(amps) if np.mean(amps) > 0 else np.nan
|
| 83 |
+
else:
|
| 84 |
+
for k in ['step_ivl_mean','step_ivl_std','step_ivl_cv','step_ivl_range','peak_amp_cv']:
|
| 85 |
+
f[k] = np.nan
|
| 86 |
+
return f
|
| 87 |
+
|
| 88 |
+
def freq_domain_features(sig, fs):
|
| 89 |
+
f = {}
|
| 90 |
+
if len(sig) < 256:
|
| 91 |
+
f['total_power'] = f['dominant_freq'] = f['gait_band_power'] = f['gait_power_ratio'] = np.nan
|
| 92 |
+
f['tremor_band_power'] = f['tremor_power_ratio'] = np.nan
|
| 93 |
+
f['spectral_entropy'] = f['spectral_centroid'] = np.nan
|
| 94 |
+
return f
|
| 95 |
+
|
| 96 |
+
nperseg = min(256, len(sig) // 2)
|
| 97 |
+
freqs, psd = welch(sig, fs=fs, nperseg=nperseg)
|
| 98 |
+
total_pwr = np.trapz(psd, freqs)
|
| 99 |
+
f['total_power'] = total_pwr
|
| 100 |
+
gm = (freqs >= 0.5) & (freqs <= 3.0)
|
| 101 |
+
if gm.any():
|
| 102 |
+
f['dominant_freq'] = freqs[gm][np.argmax(psd[gm])]
|
| 103 |
+
f['gait_band_power'] = np.trapz(psd[gm], freqs[gm])
|
| 104 |
+
f['gait_power_ratio'] = f['gait_band_power'] / total_pwr if total_pwr > 0 else 0
|
| 105 |
+
else:
|
| 106 |
+
f['dominant_freq'] = f['gait_band_power'] = f['gait_power_ratio'] = np.nan
|
| 107 |
+
tm = (freqs >= 3.0) & (freqs <= 8.0)
|
| 108 |
+
if tm.any():
|
| 109 |
+
f['tremor_band_power'] = np.trapz(psd[tm], freqs[tm])
|
| 110 |
+
f['tremor_power_ratio'] = f['tremor_band_power'] / total_pwr if total_pwr > 0 else 0
|
| 111 |
+
else:
|
| 112 |
+
f['tremor_band_power'] = f['tremor_power_ratio'] = np.nan
|
| 113 |
+
psd_n = psd / (psd.sum() + 1e-12)
|
| 114 |
+
f['spectral_entropy'] = -np.sum(psd_n * np.log2(psd_n + 1e-12)) if len(psd_n) > 0 else np.nan
|
| 115 |
+
f['spectral_centroid'] = np.sum(freqs * psd) / (np.sum(psd) + 1e-12) if np.sum(psd) > 0 else np.nan
|
| 116 |
+
return f
|
| 117 |
+
|
| 118 |
+
def entropy_features(sig):
|
| 119 |
+
s = sig[:2000]
|
| 120 |
+
if len(s) < 5:
|
| 121 |
+
return {'app_entropy': np.nan, 'samp_entropy': np.nan, 'perm_entropy': np.nan, 'svd_entropy': np.nan}
|
| 122 |
+
return {
|
| 123 |
+
'app_entropy': safe_entropy(s, ant.app_entropy, order=2, metric='chebyshev'),
|
| 124 |
+
'samp_entropy': safe_entropy(s, ant.sample_entropy, order=2, metric='chebyshev'),
|
| 125 |
+
'perm_entropy': safe_entropy(s, ant.perm_entropy, order=3, normalize=True),
|
| 126 |
+
'svd_entropy': safe_entropy(s, ant.svd_entropy, order=3, delay=1, normalize=True),
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def extract_all_features(subj):
|
| 131 |
+
f = {}
|
| 132 |
+
dur_s = subj['duration_ms'] / 1000.0 if subj['duration_ms'] > 0 else np.nan
|
| 133 |
+
f['walking_speed_ms'] = 10.0 / dur_s if dur_s and dur_s > 0 else np.nan
|
| 134 |
+
f['duration_s'] = dur_s
|
| 135 |
+
f['walking_aids'] = subj['walking_aids']
|
| 136 |
+
f['age'] = subj['age'] if subj['age'] else np.nan
|
| 137 |
+
|
| 138 |
+
# Handle cases where sensor data might be too short for feature extraction
|
| 139 |
+
min_len_acc = len(subj['acc']) if 'acc' in subj and subj['acc'] is not None else 0
|
| 140 |
+
min_len_gyr = len(subj['gyr']) if 'gyr' in subj and subj['gyr'] is not None else 0
|
| 141 |
+
min_len_mag = len(subj['mag']) if 'mag' in subj and subj['mag'] is not None else 0
|
| 142 |
+
|
| 143 |
+
for sensor_name, sig_mag_data, sig_3d_data, fs_val in [
|
| 144 |
+
('acc', subj.get('acc_mag'), subj.get('acc'), FS_ACC),
|
| 145 |
+
('gyr', subj.get('gyr_mag'), subj.get('gyr'), FS_GYR),
|
| 146 |
+
('mag', subj.get('mag_mag'), subj.get('mag'), FS_MAG),
|
| 147 |
+
]:
|
| 148 |
+
# Ensure sensor data is not None and has sufficient length for processing
|
| 149 |
+
if sig_mag_data is not None and len(sig_mag_data) > 0:
|
| 150 |
+
td = time_domain_features(sig_mag_data, fs_val)
|
| 151 |
+
f.update({f'{sensor_name}_mag_{k}': v for k, v in td.items()})
|
| 152 |
+
fd = freq_domain_features(sig_mag_data, fs_val)
|
| 153 |
+
f.update({f'{sensor_name}_mag_{k}': v for k, v in fd.items()})
|
| 154 |
+
if sensor_name in ('acc', 'gyr'): # Only acc and gyr have entropy features
|
| 155 |
+
ent = entropy_features(sig_mag_data)
|
| 156 |
+
f.update({f'{sensor_name}_mag_{k}': v for k, v in ent.items()})
|
| 157 |
+
|
| 158 |
+
if sig_3d_data is not None and len(sig_3d_data) > 0:
|
| 159 |
+
for i, ax in enumerate(['x', 'y', 'z']):
|
| 160 |
+
# Ensure column exists before attempting to extract features for it
|
| 161 |
+
if sig_3d_data.shape[1] > i:
|
| 162 |
+
td_ax = time_domain_features(sig_3d_data[:, i], fs_val)
|
| 163 |
+
f.update({f'{sensor_name}_{ax}_{k}': v for k, v in td_ax.items()})
|
| 164 |
+
|
| 165 |
+
mn = min(min_len_acc, min_len_gyr)
|
| 166 |
+
if mn > 10 and subj.get('acc_mag') is not None and subj.get('gyr_mag') is not None:
|
| 167 |
+
f['acc_gyr_corr'] = float(np.corrcoef(subj['acc_mag'][:mn], subj['gyr_mag'][:mn])[0, 1])
|
| 168 |
+
else:
|
| 169 |
+
f['acc_gyr_corr'] = np.nan
|
| 170 |
+
|
| 171 |
+
acc_e = np.mean(subj['acc_mag']**2) if subj.get('acc_mag') is not None and len(subj['acc_mag']) > 0 else 0
|
| 172 |
+
gyr_e = np.mean(subj['gyr_mag']**2) if subj.get('gyr_mag') is not None and len(subj['gyr_mag']) > 0 else 0
|
| 173 |
+
f['gyr_acc_energy_ratio'] = gyr_e / (acc_e + 1e-12)
|
| 174 |
+
|
| 175 |
+
return f
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def predict_neurological_risk_from_raw_data(acc_df, gyr_df, mag_df, user_data, model_path='/content/drive/MyDrive/neurological_gait_model.pkl'):
|
| 179 |
+
"""
|
| 180 |
+
Predicts the neurological risk from raw sensor data (accelerometer, gyroscope, magnetometer)
|
| 181 |
+
and user demographic/test data using the first LightGBM model.
|
| 182 |
+
|
| 183 |
+
Args:
|
| 184 |
+
acc_df (pd.DataFrame): Raw accelerometer data with 'x', 'y', 'z' columns.
|
| 185 |
+
gyr_df (pd.DataFrame): Raw gyroscope data with 'x', 'y', 'z' columns.
|
| 186 |
+
mag_df (pd.DataFrame): Raw magnetometer data with 'x', 'y', 'z' columns.
|
| 187 |
+
user_data (dict): Dictionary containing user demographic and test data, e.g.,
|
| 188 |
+
{'duration': 25000, 'age': 75, 'walking_aids': 0}.
|
| 189 |
+
model_path (str): Path to the saved neurological_gait_model.pkl file.
|
| 190 |
+
|
| 191 |
+
Returns:
|
| 192 |
+
dict: A dictionary containing the predicted risk score and risk level (LOW, MODERATE, HIGH).
|
| 193 |
+
Returns an error dictionary if the model file is not found or data is insufficient.
|
| 194 |
+
"""
|
| 195 |
+
# Load the model bundle
|
| 196 |
+
try:
|
| 197 |
+
with open(model_path, 'rb') as f:
|
| 198 |
+
bundle = pickle.load(f)
|
| 199 |
+
except FileNotFoundError:
|
| 200 |
+
return {'error': f"Model file not found at {model_path}. Please ensure it's uploaded."}
|
| 201 |
+
|
| 202 |
+
lgb_model = bundle['model']
|
| 203 |
+
scaler = bundle['scaler']
|
| 204 |
+
imputer = bundle['imputer']
|
| 205 |
+
feature_names = bundle['feature_names']
|
| 206 |
+
THRESHOLD_LOW = bundle['threshold_low']
|
| 207 |
+
THRESHOLD_HIGH = bundle['threshold_high']
|
| 208 |
+
|
| 209 |
+
# 1. Preprocess sensor data
|
| 210 |
+
processed_acc = preprocess_signal(acc_df[['x','y','z']].values, FS_ACC)
|
| 211 |
+
processed_gyr = preprocess_signal(gyr_df[['x','y','z']].values, FS_GYR)
|
| 212 |
+
processed_mag = preprocess_signal(mag_df[['x','y','z']].values, FS_MAG)
|
| 213 |
+
|
| 214 |
+
processed_acc_mag = np.sqrt(np.sum(processed_acc**2, axis=1))
|
| 215 |
+
processed_gyr_mag = np.sqrt(np.sum(processed_gyr**2, axis=1))
|
| 216 |
+
processed_mag_mag = np.sqrt(np.sum(processed_mag**2, axis=1))
|
| 217 |
+
|
| 218 |
+
# 2. Construct subject_data dictionary compatible with extract_all_features
|
| 219 |
+
# Ensure minimum lengths are met for feature extraction
|
| 220 |
+
min_len = min(len(processed_acc), len(processed_gyr), len(processed_mag))
|
| 221 |
+
if min_len < 30: # Minimum length for meaningful feature extraction
|
| 222 |
+
return {'error': 'Insufficient sensor data length for feature extraction.'}
|
| 223 |
+
|
| 224 |
+
subject_data_processed = {
|
| 225 |
+
'subject_id': user_data.get('subject_id', -1), # Use provided or dummy ID
|
| 226 |
+
'user_data': user_data, # Pass full user_data
|
| 227 |
+
'acc': processed_acc[:min_len],
|
| 228 |
+
'gyr': processed_gyr[:min_len],
|
| 229 |
+
'mag': processed_mag[:min_len],
|
| 230 |
+
'acc_mag': processed_acc_mag[:min_len],
|
| 231 |
+
'gyr_mag': processed_gyr_mag[:min_len],
|
| 232 |
+
'mag_mag': processed_mag_mag[:min_len],
|
| 233 |
+
'label': 0, # Dummy label, as this model predicts it
|
| 234 |
+
'duration_ms': user_data.get('duration', 0),
|
| 235 |
+
'age': user_data.get('age', None),
|
| 236 |
+
'walking_aids': int(user_data.get('walking_aids', False)),
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
# 3. Extract features
|
| 240 |
+
extracted_features = extract_all_features(subject_data_processed)
|
| 241 |
+
X_single_df = pd.DataFrame([extracted_features])
|
| 242 |
+
|
| 243 |
+
# 4. Impute missing values using the trained imputer
|
| 244 |
+
# Align columns before imputation to avoid errors if some expected features are missing
|
| 245 |
+
X_single_df_aligned = X_single_df.reindex(columns=imputer.feature_names_in_, fill_value=np.nan)
|
| 246 |
+
X_imp_single = imputer.transform(X_single_df_aligned)
|
| 247 |
+
X_df_c_single = pd.DataFrame(X_imp_single, columns=imputer.feature_names_in_)
|
| 248 |
+
|
| 249 |
+
# Filter to only the features the model was trained on
|
| 250 |
+
X_filtered_single = X_df_c_single[feature_names]
|
| 251 |
+
|
| 252 |
+
# Scale the features using the trained scaler
|
| 253 |
+
X_scaled_single = scaler.transform(X_filtered_single)
|
| 254 |
+
|
| 255 |
+
# 5. Make prediction
|
| 256 |
+
score = lgb_model.predict_proba(X_scaled_single)[0, 1]
|
| 257 |
+
|
| 258 |
+
# 6. Determine risk level
|
| 259 |
+
if score < THRESHOLD_LOW:
|
| 260 |
+
level = 'LOW'
|
| 261 |
+
elif score < THRESHOLD_HIGH:
|
| 262 |
+
level = 'MODERATE'
|
| 263 |
+
else:
|
| 264 |
+
level = 'HIGH'
|
| 265 |
+
|
| 266 |
+
return {'score': float(score), 'risk_level': level}
|
| 267 |
+
|
| 268 |
+
def predict_neurological_subtype_from_raw_data(acc_df, gyr_df, mag_df, user_data, model_path='/content/drive/MyDrive/neurological_subtype_model.pkl'):
|
| 269 |
+
"""
|
| 270 |
+
Predicts the neurological subtype from raw sensor data for a subject
|
| 271 |
+
already identified as neurological.
|
| 272 |
+
|
| 273 |
+
Args:
|
| 274 |
+
acc_df (pd.DataFrame): Raw accelerometer data with 'x', 'y', 'z' columns.
|
| 275 |
+
gyr_df (pd.DataFrame): Raw gyroscope data with 'x', 'y', 'z' columns.
|
| 276 |
+
mag_df (pd.DataFrame): Raw magnetometer data with 'x', 'y', 'z' columns.
|
| 277 |
+
user_data (dict): Dictionary containing user demographic and test data, e.g.,
|
| 278 |
+
{'duration': 25000, 'age': 75, 'walking_aids': 0}.
|
| 279 |
+
model_path (str): Path to the saved neurological_subtype_model.pkl file.
|
| 280 |
+
|
| 281 |
+
Returns:
|
| 282 |
+
dict: A dictionary containing the predicted subtype label, the raw probability scores
|
| 283 |
+
for each class, and the highest probability.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
try:
|
| 287 |
+
with open(model_path, 'rb') as f:
|
| 288 |
+
bundle_subtype = pickle.load(f)
|
| 289 |
+
except FileNotFoundError:
|
| 290 |
+
return {'error': f"Model file not found at {model_path}. Please ensure it's uploaded."}
|
| 291 |
+
|
| 292 |
+
lgb_model_second = bundle_subtype['model']
|
| 293 |
+
scaler_second = bundle_subtype['scaler']
|
| 294 |
+
imputer_second = bundle_subtype['imputer']
|
| 295 |
+
feature_names_second = bundle_subtype['feature_names']
|
| 296 |
+
label_encoder_second = bundle_subtype['label_encoder']
|
| 297 |
+
|
| 298 |
+
# 1. Preprocess sensor data
|
| 299 |
+
processed_acc = preprocess_signal(acc_df[['x','y','z']].values, FS_ACC)
|
| 300 |
+
processed_gyr = preprocess_signal(gyr_df[['x','y','z']].values, FS_GYR)
|
| 301 |
+
processed_mag = preprocess_signal(mag_df[['x','y','z']].values, FS_MAG)
|
| 302 |
+
|
| 303 |
+
processed_acc_mag = np.sqrt(np.sum(processed_acc**2, axis=1))
|
| 304 |
+
processed_gyr_mag = np.sqrt(np.sum(processed_gyr**2, axis=1))
|
| 305 |
+
processed_mag_mag = np.sqrt(np.sum(processed_mag**2, axis=1))
|
| 306 |
+
|
| 307 |
+
# 2. Construct subject_data dictionary compatible with extract_all_features
|
| 308 |
+
# Ensure minimum lengths are met for feature extraction
|
| 309 |
+
min_len = min(len(processed_acc), len(processed_gyr), len(processed_mag))
|
| 310 |
+
if min_len < 30: # Minimum length for meaningful feature extraction
|
| 311 |
+
return {'error': 'Insufficient sensor data length for feature extraction.'}
|
| 312 |
+
|
| 313 |
+
subject_data_processed = {
|
| 314 |
+
'subject_id': user_data.get('subject_id', -1), # Use provided or dummy ID
|
| 315 |
+
'user_data': user_data, # Pass full user_data
|
| 316 |
+
'acc': processed_acc[:min_len],
|
| 317 |
+
'gyr': processed_gyr[:min_len],
|
| 318 |
+
'mag': processed_mag[:min_len],
|
| 319 |
+
'acc_mag': processed_acc_mag[:min_len],
|
| 320 |
+
'gyr_mag': processed_gyr_mag[:min_len],
|
| 321 |
+
'mag_mag': processed_mag_mag[:min_len],
|
| 322 |
+
'label': 1, # Assume already identified as neurological for this model
|
| 323 |
+
'duration_ms': user_data.get('duration', 0),
|
| 324 |
+
'age': user_data.get('age', None),
|
| 325 |
+
'walking_aids': int(user_data.get('walking_aids', False)),
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
extracted_features = extract_all_features(subject_data_processed)
|
| 329 |
+
X_single_df = pd.DataFrame([extracted_features])
|
| 330 |
+
X_single_df_aligned = X_single_df.reindex(columns=imputer_second.feature_names_in_, fill_value=np.nan)
|
| 331 |
+
X_imp_single = imputer_second.transform(X_single_df_aligned)
|
| 332 |
+
X_df_c_single = pd.DataFrame(X_imp_single, columns=imputer_second.feature_names_in_)
|
| 333 |
+
|
| 334 |
+
X_filtered_single = X_df_c_single[feature_names_second]
|
| 335 |
+
|
| 336 |
+
X_scaled_single = scaler_second.transform(X_filtered_single)
|
| 337 |
+
|
| 338 |
+
proba_scores = lgb_model_second.predict_proba(X_scaled_single)[0]
|
| 339 |
+
|
| 340 |
+
predicted_class_idx = np.argmax(proba_scores)
|
| 341 |
+
predicted_prob = proba_scores[predicted_class_idx]
|
| 342 |
+
|
| 343 |
+
predicted_label = label_encoder_second.inverse_transform([predicted_class_idx])[0]
|
| 344 |
+
|
| 345 |
+
return {
|
| 346 |
+
'predicted_subtype': predicted_label,
|
| 347 |
+
'probability_scores': dict(zip(label_encoder_second.classes_, proba_scores)),
|
| 348 |
+
'highest_probability': float(predicted_prob)
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
import os
|
| 352 |
+
import pandas as pd
|
| 353 |
+
from fastapi import FastAPI, Body
|
| 354 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 355 |
+
import uvicorn
|
| 356 |
+
|
| 357 |
+
app = FastAPI()
|
| 358 |
+
|
| 359 |
+
app.add_middleware(
|
| 360 |
+
CORSMiddleware,
|
| 361 |
+
allow_origins=["*"],
|
| 362 |
+
allow_credentials=True,
|
| 363 |
+
allow_methods=["*"],
|
| 364 |
+
allow_headers=["*"],
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
@app.get("/")
|
| 368 |
+
def read_root():
|
| 369 |
+
return {"message": "Neurological Risk API is Online on Hugging Face"}
|
| 370 |
+
|
| 371 |
+
@app.post("/predict_risk")
|
| 372 |
+
def predict_risk(dict_in: dict = Body(...)):
|
| 373 |
+
acc_df = pd.DataFrame(dict_in['acc']).T
|
| 374 |
+
acc_df.columns = ['x', 'y', 'z']
|
| 375 |
+
gyr_df = pd.DataFrame(dict_in['gyr']).T
|
| 376 |
+
gyr_df.columns = ['x', 'y', 'z']
|
| 377 |
+
mag_df = pd.DataFrame(dict_in['mag']).T
|
| 378 |
+
mag_df.columns = ['x', 'y', 'z']
|
| 379 |
+
|
| 380 |
+
user_data = dict_in['user']
|
| 381 |
+
|
| 382 |
+
# Logic from your model script
|
| 383 |
+
prediction_result = predict_neurological_risk_from_raw_data(
|
| 384 |
+
acc_df, gyr_df, mag_df, user_data
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
return {
|
| 388 |
+
'error': 'error' in prediction_result,
|
| 389 |
+
'score': prediction_result.get('score'),
|
| 390 |
+
'risk_level': prediction_result.get('risk_level', 'UNKNOWN')
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
@app.post("/predict_subtype")
|
| 394 |
+
def predict_subtype(dict_in: dict = Body(...)):
|
| 395 |
+
acc_df = pd.DataFrame(dict_in['acc']).T
|
| 396 |
+
acc_df.columns = ['x', 'y', 'z']
|
| 397 |
+
gyr_df = pd.DataFrame(dict_in['gyr']).T
|
| 398 |
+
gyr_df.columns = ['x', 'y', 'z']
|
| 399 |
+
mag_df = pd.DataFrame(dict_in['mag']).T
|
| 400 |
+
mag_df.columns = ['x', 'y', 'z']
|
| 401 |
+
|
| 402 |
+
user_data = dict_in['user']
|
| 403 |
+
|
| 404 |
+
prediction_result_standalone = predict_neurological_subtype_from_raw_data(
|
| 405 |
+
acc_df, gyr_df, mag_df, user_data
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
if 'error' in prediction_result_standalone:
|
| 409 |
+
return {"error": True, "Predicted subtype": None, "Probability scores": [], "Highest probability": None}
|
| 410 |
+
|
| 411 |
+
return {
|
| 412 |
+
"error": False,
|
| 413 |
+
"Predicted subtype": str(prediction_result_standalone['predicted_subtype']),
|
| 414 |
+
"Probability scores": {str(k): float(v) for k, v in prediction_result_standalone['probability_scores'].items()},
|
| 415 |
+
"Highest probability": float(prediction_result_standalone['highest_probability'])
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
# 2. Start via Uvicorn on Port 7860
|
| 419 |
+
if __name__ == "__main__":
|
| 420 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 421 |
+
|
| 422 |
+
!ssh -o StrictHostKeyChecking=no -p 443 -R0:localhost:8000 a.pinggy.io x:passpreflight
|
neurological_gait_model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:60a684d727f52944dae006c22904c2c335670297640c500998ebdac398917999
|
| 3 |
+
size 61681
|
neurological_subtype_model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:887f6aec76b79b85ce0c24ae620594ae30ac730bdcb30af1eeae7249dfcca0e5
|
| 3 |
+
size 68236
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas==2.2.2
|
| 2 |
+
numpy==2.0.2
|
| 3 |
+
scipy==1.16.3
|
| 4 |
+
antropy==0.2.1
|
| 5 |
+
fastapi
|
| 6 |
+
uvicorn
|