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

Changed paths for file imports

Browse files
Files changed (1) hide show
  1. SVM/SVM_R.py +130 -130
SVM/SVM_R.py CHANGED
@@ -1,130 +1,130 @@
1
- import os
2
- import pickle
3
- import pandas as pd
4
-
5
- class SVM_Regressor:
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", "svr_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
- Xmean_file = os.path.join("app", "data", "SVR_train_mean.csv")
34
- self.df_mean = pd.read_csv(Xmean_file, index_col=0)
35
-
36
- Xstd_file = os.path.join("app", "data", "SVR_train_std.csv")
37
- self.df_std = pd.read_csv(Xstd_file, index_col=0)
38
-
39
- ynorm_file = os.path.join("app", "data", "svr_y_norms.csv")
40
- df_ynorm = pd.read_csv(ynorm_file, index_col=False)
41
- self.y_mean = df_ynorm['y_mean'].iloc[0]
42
- self.y_std = df_ynorm['y_std'].iloc[0]
43
-
44
- except Exception as e:
45
- print(f"Error loading model files: {str(e)}")
46
- raise
47
-
48
- def make_prediction(self):
49
- try:
50
- num = [self.weight, self.height, self.duration, self.fat, self.freq, self.experience]
51
- self.debug_info['original_values'] = dict(zip(
52
- ['weight', 'height', 'duration', 'fat', 'freq', 'experience'],
53
- num
54
- ))
55
-
56
- m_norm = self.df_mean.values.flatten().tolist()
57
- s_norm = self.df_std.values.flatten().tolist()
58
- self.debug_info['normalization'] = {
59
- 'means': m_norm,
60
- 'stds': s_norm
61
- }
62
-
63
- norm = [(x-y)/z for x, y, z in zip(num, m_norm, s_norm)]
64
- self.debug_info['normalized_values'] = dict(zip(
65
- ['weight', 'height', 'duration', 'fat', 'freq', 'experience'],
66
- norm
67
- ))
68
-
69
- if self.gender == 'Female':
70
- norm.extend([1,0])
71
- self.debug_info['gender_encoding'] = 'Female: [1, 0]'
72
- else:
73
- norm.extend([0,1])
74
- self.debug_info['gender_encoding'] = 'Male: [0, 1]'
75
-
76
- # Add one-hot encoded workout type
77
- workout_encoding = {
78
- 'Cardio': [1, 0, 0, 0],
79
- 'HIIT': [0, 1, 0, 0],
80
- 'Strength': [0, 0, 1, 0],
81
- 'Yoga': [0, 0, 0, 1]
82
- }
83
- norm.extend(workout_encoding[self.workout])
84
- self.debug_info['workout_encoding'] = f'{self.workout}: {workout_encoding[self.workout]}'
85
-
86
- X = pd.DataFrame([norm],columns=self.column_names)
87
- self.debug_info['final_feature_vector'] = X.to_dict('records')[0]
88
-
89
- prediction = self.svm_model.predict(X)
90
- self.debug_info['prediction'] = prediction[0]
91
-
92
- return f"""It is recommended to take {(prediction[0]*self.y_std + self.y_mean):.2f} litres of water for this session."""
93
-
94
- except Exception as e:
95
- self.debug_info['error'] = str(e)
96
- return f"Error: {str(e)}"
97
-
98
- def get_debug_info(self):
99
- """Returns formatted debug information"""
100
- debug_text = "=== DEBUG INFORMATION ===\n\n"
101
-
102
- # Original values
103
- debug_text += "Original Values:\n"
104
- for key, value in self.debug_info['original_values'].items():
105
- debug_text += f"{key}: {value}\n"
106
-
107
- # Normalization parameters
108
- debug_text += "\nNormalization Parameters:\n"
109
- for i, (mean, std) in enumerate(zip(
110
- self.debug_info['normalization']['means'],
111
- self.debug_info['normalization']['stds']
112
- )):
113
- debug_text += f"Feature {i}: mean={mean:.4f}, std={std:.4f}\n"
114
-
115
- # Normalized values
116
- debug_text += "\nNormalized Values:\n"
117
- for key, value in self.debug_info['normalized_values'].items():
118
- debug_text += f"{key}: {value:.4f}\n"
119
-
120
- # Encodings
121
- debug_text += f"\nGender Encoding: {self.debug_info['gender_encoding']}\n"
122
- debug_text += f"Workout Encoding: {self.debug_info['workout_encoding']}\n"
123
-
124
- # Final vector
125
- debug_text += f"\nVector: {self.debug_info['final_feature_vector']}\n"
126
-
127
- # Final prediction
128
- debug_text += f"\nFinal Prediction: {self.debug_info['prediction']}\n"
129
-
130
- return debug_text
 
1
+ import os
2
+ import pickle
3
+ import pandas as pd
4
+
5
+ class SVM_Regressor:
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", "svr_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
+ Xmean_file = os.path.join("data", "SVR_train_mean.csv")
34
+ self.df_mean = pd.read_csv(Xmean_file, index_col=0)
35
+
36
+ Xstd_file = os.path.join("data", "SVR_train_std.csv")
37
+ self.df_std = pd.read_csv(Xstd_file, index_col=0)
38
+
39
+ ynorm_file = os.path.join("data", "svr_y_norms.csv")
40
+ df_ynorm = pd.read_csv(ynorm_file, index_col=False)
41
+ self.y_mean = df_ynorm['y_mean'].iloc[0]
42
+ self.y_std = df_ynorm['y_std'].iloc[0]
43
+
44
+ except Exception as e:
45
+ print(f"Error loading model files: {str(e)}")
46
+ raise
47
+
48
+ def make_prediction(self):
49
+ try:
50
+ num = [self.weight, self.height, self.duration, self.fat, self.freq, self.experience]
51
+ self.debug_info['original_values'] = dict(zip(
52
+ ['weight', 'height', 'duration', 'fat', 'freq', 'experience'],
53
+ num
54
+ ))
55
+
56
+ m_norm = self.df_mean.values.flatten().tolist()
57
+ s_norm = self.df_std.values.flatten().tolist()
58
+ self.debug_info['normalization'] = {
59
+ 'means': m_norm,
60
+ 'stds': s_norm
61
+ }
62
+
63
+ norm = [(x-y)/z for x, y, z in zip(num, m_norm, s_norm)]
64
+ self.debug_info['normalized_values'] = dict(zip(
65
+ ['weight', 'height', 'duration', 'fat', 'freq', 'experience'],
66
+ norm
67
+ ))
68
+
69
+ if self.gender == 'Female':
70
+ norm.extend([1,0])
71
+ self.debug_info['gender_encoding'] = 'Female: [1, 0]'
72
+ else:
73
+ norm.extend([0,1])
74
+ self.debug_info['gender_encoding'] = 'Male: [0, 1]'
75
+
76
+ # Add one-hot encoded workout type
77
+ workout_encoding = {
78
+ 'Cardio': [1, 0, 0, 0],
79
+ 'HIIT': [0, 1, 0, 0],
80
+ 'Strength': [0, 0, 1, 0],
81
+ 'Yoga': [0, 0, 0, 1]
82
+ }
83
+ norm.extend(workout_encoding[self.workout])
84
+ self.debug_info['workout_encoding'] = f'{self.workout}: {workout_encoding[self.workout]}'
85
+
86
+ X = pd.DataFrame([norm],columns=self.column_names)
87
+ self.debug_info['final_feature_vector'] = X.to_dict('records')[0]
88
+
89
+ prediction = self.svm_model.predict(X)
90
+ self.debug_info['prediction'] = prediction[0]
91
+
92
+ return f"""It is recommended to take {(prediction[0]*self.y_std + self.y_mean):.2f} litres of water for this session."""
93
+
94
+ except Exception as e:
95
+ self.debug_info['error'] = str(e)
96
+ return f"Error: {str(e)}"
97
+
98
+ def get_debug_info(self):
99
+ """Returns formatted debug information"""
100
+ debug_text = "=== DEBUG INFORMATION ===\n\n"
101
+
102
+ # Original values
103
+ debug_text += "Original Values:\n"
104
+ for key, value in self.debug_info['original_values'].items():
105
+ debug_text += f"{key}: {value}\n"
106
+
107
+ # Normalization parameters
108
+ debug_text += "\nNormalization Parameters:\n"
109
+ for i, (mean, std) in enumerate(zip(
110
+ self.debug_info['normalization']['means'],
111
+ self.debug_info['normalization']['stds']
112
+ )):
113
+ debug_text += f"Feature {i}: mean={mean:.4f}, std={std:.4f}\n"
114
+
115
+ # Normalized values
116
+ debug_text += "\nNormalized Values:\n"
117
+ for key, value in self.debug_info['normalized_values'].items():
118
+ debug_text += f"{key}: {value:.4f}\n"
119
+
120
+ # Encodings
121
+ debug_text += f"\nGender Encoding: {self.debug_info['gender_encoding']}\n"
122
+ debug_text += f"Workout Encoding: {self.debug_info['workout_encoding']}\n"
123
+
124
+ # Final vector
125
+ debug_text += f"\nVector: {self.debug_info['final_feature_vector']}\n"
126
+
127
+ # Final prediction
128
+ debug_text += f"\nFinal Prediction: {self.debug_info['prediction']}\n"
129
+
130
+ return debug_text