Dineflow commited on
Commit
322a716
·
verified ·
1 Parent(s): af165e9

Update inference.py

Browse files
Files changed (1) hide show
  1. inference.py +39 -38
inference.py CHANGED
@@ -1,38 +1,39 @@
1
- import joblib
2
- from sklearn.feature_extraction.text import TfidfVectorizer
3
- from sklearn.linear_model import LogisticRegression
4
-
5
- # Load the model and vectorizer from the saved files
6
- logistic_classifier = joblib.load('logistic_classifier.joblib')
7
- vectorizer = joblib.load('vectorizer.joblib')
8
-
9
- # Function to predict rating for a new review
10
- def predict_rating(review):
11
- review_tfidf = vectorizer.transform([review])
12
- predicted_rating = logistic_classifier.predict(review_tfidf)[0]
13
- return predicted_rating
14
-
15
- # Function to map numerical rating to description
16
- def map_rating_to_description(rating):
17
- if rating == 1:
18
- return "Poor"
19
- elif rating == 2:
20
- return "Unsatisfactory"
21
- elif rating == 3:
22
- return "Average"
23
- elif rating == 4:
24
- return "Satisfactory"
25
- elif rating == 5:
26
- return "Outstanding"
27
- else:
28
- return "Invalid rating"
29
-
30
- # Define the inference function
31
- def inference(request):
32
- review = request.get("review", "")
33
- predicted_rating = predict_rating(review)
34
- predicted_description = map_rating_to_description(predicted_rating)
35
- return {
36
- "predicted_rating": int(predicted_rating),
37
- "predicted_description": predicted_description
38
- }
 
 
1
+ import joblib
2
+ from sklearn.feature_extraction.text import TfidfVectorizer
3
+ from sklearn.linear_model import LogisticRegression
4
+
5
+ class Handler:
6
+ def __init__(self, model_dir):
7
+ self.vectorizer = joblib.load(f'{model_dir}/vectorizer.joblib')
8
+ self.model = joblib.load(f'{model_dir}/logistic_classifier.joblib')
9
+
10
+ # Function to predict rating for a new review
11
+ def predict_rating(review):
12
+ review_tfidf = vectorizer.transform([review])
13
+ predicted_rating = logistic_classifier.predict(review_tfidf)[0]
14
+ return predicted_rating
15
+
16
+ # Function to map numerical rating to description
17
+ def map_rating_to_description(rating):
18
+ if rating == 1:
19
+ return "Poor"
20
+ elif rating == 2:
21
+ return "Unsatisfactory"
22
+ elif rating == 3:
23
+ return "Average"
24
+ elif rating == 4:
25
+ return "Satisfactory"
26
+ elif rating == 5:
27
+ return "Outstanding"
28
+ else:
29
+ return "Invalid rating"
30
+
31
+ # Define the inference function
32
+ def inference(request):
33
+ review = request.get("review", "")
34
+ predicted_rating = predict_rating(review)
35
+ predicted_description = map_rating_to_description(predicted_rating)
36
+ return {
37
+ "predicted_rating": int(predicted_rating),
38
+ "predicted_description": predicted_description
39
+ }