mohli commited on
Commit
d134ff9
·
verified ·
1 Parent(s): 1018eda

Changes paths for file import

Browse files
Files changed (1) hide show
  1. SVM/SVM_C.py +125 -125
SVM/SVM_C.py CHANGED
@@ -1,125 +1,125 @@
1
- import os
2
- import pickle
3
- import pandas as pd
4
-
5
- class SVM_Classifier:
6
- def __init__(self):
7
-
8
- self.weight = 70 # default weight in kg
9
- self.height = 1.75 # default height in m
10
- self.gender = "Male" # default gender
11
- self.duration = 1.0 # default duration in hours
12
- self.fat = 25 # default fat percentage
13
- self.freq = 3 # default workouts per week
14
- self.experience = 1 # default experience level
15
- self.workout = "Cardio" # default workout type
16
-
17
- # Add debug info dictionary
18
- self.debug_info = {}
19
-
20
- # Load the model and required data
21
- try:
22
- # Load the SVM model
23
- model_file = os.path.join("app", "data", "svm_model.pkl")
24
- with open(model_file, 'rb') as f:
25
- self.svm_model = pickle.load(f)
26
-
27
- # Load the column names
28
- cols_file = os.path.join("app", "data", "column_names.csv")
29
- with open(cols_file, 'r') as f:
30
- self.column_names = [line.strip() for line in f]
31
-
32
- # Load normalization parameters
33
- mean_file = os.path.join("app", "data", "SVM_train_mean.csv")
34
- self.df_mean = pd.read_csv(mean_file, index_col=0)
35
-
36
- std_file = os.path.join("app", "data", "SVM_train_std.csv")
37
- self.df_std = pd.read_csv(std_file, index_col=0)
38
-
39
- except Exception as e:
40
- print(f"Error loading model files: {str(e)}")
41
- raise
42
-
43
- def make_prediction(self):
44
- try:
45
- num = [self.weight, self.height, self.duration, self.fat, self.freq, self.experience]
46
- self.debug_info['original_values'] = dict(zip(
47
- ['weight', 'height', 'duration', 'fat', 'freq', 'experience'],
48
- num
49
- ))
50
-
51
- m_norm = self.df_mean.values.flatten().tolist()
52
- s_norm = self.df_std.values.flatten().tolist()
53
- self.debug_info['normalization'] = {
54
- 'means': m_norm,
55
- 'stds': s_norm
56
- }
57
-
58
- norm = [(x-y)/z for x, y, z in zip(num, m_norm, s_norm)]
59
- self.debug_info['normalized_values'] = dict(zip(
60
- ['weight', 'height', 'duration', 'fat', 'freq', 'experience'],
61
- norm
62
- ))
63
-
64
- if self.gender == 'Female':
65
- norm.extend([1,0])
66
- self.debug_info['gender_encoding'] = 'Female: [1, 0]'
67
- else:
68
- norm.extend([0,1])
69
- self.debug_info['gender_encoding'] = 'Male: [0, 1]'
70
-
71
- # Add one-hot encoded workout type
72
- workout_encoding = {
73
- 'Cardio': [1, 0, 0, 0],
74
- 'HIIT': [0, 1, 0, 0],
75
- 'Strength': [0, 0, 1, 0],
76
- 'Yoga': [0, 0, 0, 1]
77
- }
78
- norm.extend(workout_encoding[self.workout])
79
- self.debug_info['workout_encoding'] = f'{self.workout}: {workout_encoding[self.workout]}'
80
-
81
- X = pd.DataFrame([norm],columns=self.column_names)
82
- self.debug_info['final_feature_vector'] = X.to_dict('records')[0]
83
-
84
- prediction = self.svm_model.predict(X)
85
- self.debug_info['prediction'] = prediction[0]
86
-
87
- return prediction[0]
88
-
89
- except Exception as e:
90
- self.debug_info['error'] = str(e)
91
- return f"Error: {str(e)}"
92
-
93
- def get_debug_info(self):
94
- """Returns formatted debug information"""
95
- debug_text = "=== DEBUG INFORMATION ===\n\n"
96
-
97
- # Original values
98
- debug_text += "Original Values:\n"
99
- for key, value in self.debug_info['original_values'].items():
100
- debug_text += f"{key}: {value}\n"
101
-
102
- # Normalization parameters
103
- debug_text += "\nNormalization Parameters:\n"
104
- for i, (mean, std) in enumerate(zip(
105
- self.debug_info['normalization']['means'],
106
- self.debug_info['normalization']['stds']
107
- )):
108
- debug_text += f"Feature {i}: mean={mean:.4f}, std={std:.4f}\n"
109
-
110
- # Normalized values
111
- debug_text += "\nNormalized Values:\n"
112
- for key, value in self.debug_info['normalized_values'].items():
113
- debug_text += f"{key}: {value:.4f}\n"
114
-
115
- # Encodings
116
- debug_text += f"\nGender Encoding: {self.debug_info['gender_encoding']}\n"
117
- debug_text += f"Workout Encoding: {self.debug_info['workout_encoding']}\n"
118
-
119
- # Final vector
120
- debug_text += f"\nVector: {self.debug_info['final_feature_vector']}\n"
121
-
122
- # Final prediction
123
- debug_text += f"\nFinal Prediction: {self.debug_info['prediction']}\n"
124
-
125
- return debug_text
 
1
+ import os
2
+ import pickle
3
+ import pandas as pd
4
+
5
+ class SVM_Classifier:
6
+ def __init__(self):
7
+
8
+ self.weight = 70 # default weight in kg
9
+ self.height = 1.75 # default height in m
10
+ self.gender = "Male" # default gender
11
+ self.duration = 1.0 # default duration in hours
12
+ self.fat = 25 # default fat percentage
13
+ self.freq = 3 # default workouts per week
14
+ self.experience = 1 # default experience level
15
+ self.workout = "Cardio" # default workout type
16
+
17
+ # Add debug info dictionary
18
+ self.debug_info = {}
19
+
20
+ # Load the model and required data
21
+ try:
22
+ # Load the SVM model
23
+ model_file = os.path.join("data", "svm_model.pkl")
24
+ with open(model_file, 'rb') as f:
25
+ self.svm_model = pickle.load(f)
26
+
27
+ # Load the column names
28
+ cols_file = os.path.join("data", "column_names.csv")
29
+ with open(cols_file, 'r') as f:
30
+ self.column_names = [line.strip() for line in f]
31
+
32
+ # Load normalization parameters
33
+ mean_file = os.path.join("data", "SVM_train_mean.csv")
34
+ self.df_mean = pd.read_csv(mean_file, index_col=0)
35
+
36
+ std_file = os.path.join("data", "SVM_train_std.csv")
37
+ self.df_std = pd.read_csv(std_file, index_col=0)
38
+
39
+ except Exception as e:
40
+ print(f"Error loading model files: {str(e)}")
41
+ raise
42
+
43
+ def make_prediction(self):
44
+ try:
45
+ num = [self.weight, self.height, self.duration, self.fat, self.freq, self.experience]
46
+ self.debug_info['original_values'] = dict(zip(
47
+ ['weight', 'height', 'duration', 'fat', 'freq', 'experience'],
48
+ num
49
+ ))
50
+
51
+ m_norm = self.df_mean.values.flatten().tolist()
52
+ s_norm = self.df_std.values.flatten().tolist()
53
+ self.debug_info['normalization'] = {
54
+ 'means': m_norm,
55
+ 'stds': s_norm
56
+ }
57
+
58
+ norm = [(x-y)/z for x, y, z in zip(num, m_norm, s_norm)]
59
+ self.debug_info['normalized_values'] = dict(zip(
60
+ ['weight', 'height', 'duration', 'fat', 'freq', 'experience'],
61
+ norm
62
+ ))
63
+
64
+ if self.gender == 'Female':
65
+ norm.extend([1,0])
66
+ self.debug_info['gender_encoding'] = 'Female: [1, 0]'
67
+ else:
68
+ norm.extend([0,1])
69
+ self.debug_info['gender_encoding'] = 'Male: [0, 1]'
70
+
71
+ # Add one-hot encoded workout type
72
+ workout_encoding = {
73
+ 'Cardio': [1, 0, 0, 0],
74
+ 'HIIT': [0, 1, 0, 0],
75
+ 'Strength': [0, 0, 1, 0],
76
+ 'Yoga': [0, 0, 0, 1]
77
+ }
78
+ norm.extend(workout_encoding[self.workout])
79
+ self.debug_info['workout_encoding'] = f'{self.workout}: {workout_encoding[self.workout]}'
80
+
81
+ X = pd.DataFrame([norm],columns=self.column_names)
82
+ self.debug_info['final_feature_vector'] = X.to_dict('records')[0]
83
+
84
+ prediction = self.svm_model.predict(X)
85
+ self.debug_info['prediction'] = prediction[0]
86
+
87
+ return prediction[0]
88
+
89
+ except Exception as e:
90
+ self.debug_info['error'] = str(e)
91
+ return f"Error: {str(e)}"
92
+
93
+ def get_debug_info(self):
94
+ """Returns formatted debug information"""
95
+ debug_text = "=== DEBUG INFORMATION ===\n\n"
96
+
97
+ # Original values
98
+ debug_text += "Original Values:\n"
99
+ for key, value in self.debug_info['original_values'].items():
100
+ debug_text += f"{key}: {value}\n"
101
+
102
+ # Normalization parameters
103
+ debug_text += "\nNormalization Parameters:\n"
104
+ for i, (mean, std) in enumerate(zip(
105
+ self.debug_info['normalization']['means'],
106
+ self.debug_info['normalization']['stds']
107
+ )):
108
+ debug_text += f"Feature {i}: mean={mean:.4f}, std={std:.4f}\n"
109
+
110
+ # Normalized values
111
+ debug_text += "\nNormalized Values:\n"
112
+ for key, value in self.debug_info['normalized_values'].items():
113
+ debug_text += f"{key}: {value:.4f}\n"
114
+
115
+ # Encodings
116
+ debug_text += f"\nGender Encoding: {self.debug_info['gender_encoding']}\n"
117
+ debug_text += f"Workout Encoding: {self.debug_info['workout_encoding']}\n"
118
+
119
+ # Final vector
120
+ debug_text += f"\nVector: {self.debug_info['final_feature_vector']}\n"
121
+
122
+ # Final prediction
123
+ debug_text += f"\nFinal Prediction: {self.debug_info['prediction']}\n"
124
+
125
+ return debug_text