-
Notifications
You must be signed in to change notification settings - Fork 117
/
main.py
1978 lines (1543 loc) · 59.5 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Import pandas and numpy for data manipulation
import pandas as pd
import numpy as np
# Import warnings to control warning messages
import warnings
# Import BeautifulSoup for web scraping and parsing HTML/XML
from bs4 import BeautifulSoup, MarkupResemblesLocatorWarning
# Import SimpleImputer for handling missing values
from sklearn.impute import SimpleImputer
# Import ConvergenceWarning for optimization convergence issues
from sklearn.exceptions import ConvergenceWarning
# Import TfidfVectorizer for text feature extraction
from sklearn.feature_extraction.text import TfidfVectorizer
# Import LabelEncoder for categorical label encoding
from sklearn.preprocessing import LabelEncoder
# Import LinearRegression and LogisticRegression for regression and classification
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
# import transformers for classifying drug reviews
import torch
from transformers import (
DistilBertTokenizerFast,
DistilBertForSequenceClassification,
Trainer,
TrainingArguments,
)
from sklearn import metrics
# Import catboost for gradient boosting
import catboost as cbt
# Import optuna for hyperparameter optimization
import optuna
# Import MLPClassifier for training MLP neural networks
from sklearn.neural_network import MLPClassifier
# Import DecisionTreeClassifier for training decision tree models
from sklearn.tree import DecisionTreeClassifier
# Import gensim for topic modeling and document similarity
import gensim
# Import evaluation metrics and visualization functions
from sklearn.metrics import (
mean_squared_error,
r2_score,
accuracy_score,
confusion_matrix,
ConfusionMatrixDisplay,
mean_absolute_error,
)
# Import RandomForestRegressor for regression with random forests
from sklearn.ensemble import RandomForestRegressor
# Import RandomizedSearchCV for hyperparameter tuning
from sklearn.model_selection import RandomizedSearchCV
# Import seaborn and matplotlib.pyplot for data visualization
import seaborn as sns
import matplotlib.pyplot as plt
# Import PorterStemmer for word stemming
from gensim.parsing.porter import PorterStemmer
# Import StandardScaler and MinMaxScaler for feature scaling
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Import RandomOverSampler for oversampling imbalanced datasets
from imblearn.over_sampling import RandomOverSampler
from keras.utils import to_categorical
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
# Import Sequential, Dense, LSTM, and Embedding for building neural network models
from keras.models import Sequential
from keras.layers import (
Dense,
Flatten,
LSTM,
GRU,
Embedding,
Conv1D,
MaxPooling1D,
GlobalMaxPooling1D,
)
# Define the data types for each column
dtypes = {
"Unnamed: 0": "int32",
"drugName": "category",
"condition": "category",
"review": "category",
"rating": "float16",
"date": "string",
"usefulCount": "int16",
}
# Read the training dataset from a TSV file, specifying the column separator as tab
train_df = pd.read_csv(
r"datasets\drugsComTrain_raw.tsv", quoting=2, dtype=dtypes, on_bad_lines="skip"
)
# Sample a fraction (80%) of the training dataset with a random seed of 42
train_df = train_df.sample(frac=0.8, random_state=42)
# Read the testing dataset from a TSV file, specifying the column separator as tab
test_df = pd.read_csv(
r"datasets\drugsComTest_raw.tsv", quoting=2, dtype=dtypes, on_bad_lines="skip"
)
# Convert the "date" column to datetime format in the training and testing datasets
train_df["date"], test_df["date"] = pd.to_datetime(
train_df["date"], format="%d-%b-%y"
), pd.to_datetime(test_df["date"], format="%d-%b-%y")
## Extracting day, month, and year into separate columns
for df in [train_df, test_df]:
df["day"] = df["date"].dt.day.astype("int8")
df["month"] = df["date"].dt.month.astype("int8")
df["year"] = df["date"].dt.year.astype("int16")
## Suppressing MarkupResemblesLocatorWarning, FutureWarning and ConvergenceWarning
warnings.filterwarnings("ignore", category=MarkupResemblesLocatorWarning)
warnings.simplefilter(action="ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=ConvergenceWarning)
## Defining function to decode HTML-encoded characters
def decode_html(text):
decoded_text = BeautifulSoup(text, "html.parser").get_text()
return decoded_text
## Applying the function to the review column
train_df["review"], test_df["review"] = train_df["review"].apply(decode_html), test_df[
"review"
].apply(decode_html)
## Dropped the original date column and removed the useless column
train_df, test_df = [
df.drop("date", axis=1).drop(df.columns[0], axis=1) for df in (train_df, test_df)
]
## Handling the missing values and assigning old column names
train_imp, test_imp = [
pd.DataFrame(
SimpleImputer(strategy="most_frequent").fit_transform(df), columns=df.columns
)
for df in (train_df, test_df)
]
# Assign new column names to the training dataset
train_imp.columns = [
"drugName",
"condition",
"review",
"rating",
"usefulCount",
"day",
"month",
"year",
]
# Assign new column names to the testing dataset
test_imp.columns = [
"drugName",
"condition",
"review",
"rating",
"usefulCount",
"day",
"month",
"year",
]
# Tokenize the text in the "review" column of the training dataset
train_imp["tokenized_text"] = [
gensim.utils.simple_preprocess(line, deacc=True) for line in train_imp["review"]
]
# Tokenize the text in the "review" column of the testing dataset
test_imp["tokenized_text"] = [
gensim.utils.simple_preprocess(line, deacc=True) for line in test_imp["review"]
]
# Create an instance of the PorterStemmer
porter_stemmer = PorterStemmer()
# Perform stemming on the tokenized text in the training dataset
train_imp["stemmed_tokens"] = [
[porter_stemmer.stem(word) for word in tokens]
for tokens in train_imp["tokenized_text"]
]
# Perform stemming on the tokenized text in the testing dataset
test_imp["stemmed_tokens"] = [
[porter_stemmer.stem(word) for word in tokens]
for tokens in test_imp["tokenized_text"]
]
##Applying Word2vec
from gensim.models import Word2Vec
# Skip-gram model (sg = 1)
size = 1000
window = 3
min_count = 1 # The minimum count of words to consider when training the model; words with occurrence less than this count will be ignored.
workers = 3
sg = 1 # The training algorithm, either CBOW(0) or skip gram(1). The default training algorithm is CBOW.
## Merging values from both train and test dataframe
stemmed_tokens_train = pd.Series(train_imp["stemmed_tokens"]).values
stemmed_tokens_test = pd.Series(test_imp["stemmed_tokens"]).values
stemmed_tokens_merged = np.append(stemmed_tokens_train, stemmed_tokens_test, axis=0)
w2vmodel = Word2Vec(
stemmed_tokens_merged,
min_count=min_count,
vector_size=size,
workers=workers,
window=window,
sg=sg,
)
### Store the vectors for train data in following file
index = 0
word2vec_filename = "train_review_word2vec.csv"
with open(word2vec_filename, "w") as word2vec_file:
for i in range(129038):
model_vector = (
np.mean(
[w2vmodel.wv[token] for token in train_imp["stemmed_tokens"][i]], axis=0
)
).tolist()
if index == 0:
header = ",".join(str(ele) for ele in range(1000))
word2vec_file.write(header)
word2vec_file.write("\n")
index += 1
# Check if the line exists else it is vector of zeros
if type(model_vector) is list:
line1 = ",".join([str(vector_element) for vector_element in model_vector])
word2vec_file.write(line1)
word2vec_file.write("\n")
review_vector = pd.read_csv(r"train_review_word2vec.csv")
### Store the vectors for test data in following file
index = 0
word2vec_filename = "test_review_word2vec.csv"
with open(word2vec_filename, "w") as word2vec_file:
for i in range(53766):
model_vector = (
np.mean(
[w2vmodel.wv[token] for token in test_imp["stemmed_tokens"][i]], axis=0
)
).tolist()
if index == 0:
header = ",".join(str(ele) for ele in range(1000))
word2vec_file.write(header)
word2vec_file.write("\n")
index += 1
# Check if the line exists else it is vector of zeros
if type(model_vector) is list:
line1 = ",".join([str(vector_element) for vector_element in model_vector])
word2vec_file.write(line1)
word2vec_file.write("\n")
reivew_vector1 = pd.read_csv(r"test_review_word2vec.csv")
## Joining vector and dropping necessary columns
train_imp = pd.concat([train_imp, review_vector], axis="columns")
train_imp.drop(
["review", "tokenized_text", "stemmed_tokens"], axis="columns", inplace=True
)
test_imp = pd.concat([test_imp, reivew_vector1], axis="columns")
test_imp.drop(
["review", "tokenized_text", "stemmed_tokens"], axis="columns", inplace=True
)
## Encoding the categorical columns
for i in ["drugName", "condition"]:
train_imp[i] = LabelEncoder().fit_transform(train_imp[i])
test_imp[i] = LabelEncoder().fit_transform(test_imp[i])
## Converting the data types of columns to reduce the memory usage
train_imp, test_imp = train_imp.astype("float16"), test_imp.astype("float16")
train_imp[["drugName", "condition", "usefulCount", "year"]] = train_imp[
["drugName", "condition", "usefulCount", "year"]
].astype("int16")
test_imp[["drugName", "condition", "usefulCount", "year"]] = test_imp[
["drugName", "condition", "usefulCount", "year"]
].astype("int16")
train_imp[["rating"]] = train_imp[["rating"]].astype("float16")
test_imp[["rating"]] = test_imp[["rating"]].astype("float16")
train_imp[["day", "month"]] = train_imp[["day", "month"]].astype("int8")
test_imp[["day", "month"]] = test_imp[["day", "month"]].astype("int8")
"""
Implementation of pycaret on the Preprocessed data (given datasets)
requirements: pip install pycaret
Regression
PyCaret’s Regression Module is a supervised machine learning module that is used for estimating the relationships between a dependent variable (often called the ‘outcome variable’, or ‘target’) and one or more independent variables (often called ‘features’, ‘predictors’, or ‘covariates’).
The objective of regression is to predict continuous values such as predicting sales amount, predicting quantity, predicting temperature, etc.
From line 297 to 325 depict the Implementation of Accuracy enhancement using multiple regression models at a time
"""
# setup
from pycaret.regression import *
s = setup(train_imp, target="rating")
# s = setup(test_imp, target = 'rating')
# compare models
best = compare_models()
print(best)
# analyze models
evaluate_model(best)
plot_model(best, plot="residuals")
plot_model(best, plot="feature")
# predictions
predict_model(best)
predictions = predict_model(best, data=train_df)
predictions.head()
# save the model
save_model(best, "my_best_pipeline")
# load the saved model
loaded_model = load_model("my_best_pipeline")
print(loaded_model)
# print(train_imp.iloc[:,:15].dtypes)
# print(test_imp.iloc[:,:15].dtypes)
# Split the training dataset into feature variables (X_train) and the target variable (Y_train)
X_train, Y_train = train_imp.drop("rating", axis=1), train_imp["rating"]
# Split the testing dataset into feature variables (X_test) and the target variable (Y_test)
X_test, Y_test = test_imp.drop("rating", axis=1), test_imp["rating"]
# Convert the column names to string type in the training dataset
X_train.columns = X_train.columns.astype(str)
# Convert the column names to string type in the testing dataset
X_test.columns = X_test.columns.astype(str)
# Plot a scatter chart between Drug Name and Ratings in the testing dataset
# Encode the drug names using LabelEncoder for visualization purposes
plt.scatter(LabelEncoder().fit_transform(test_df.drugName), test_df.rating)
plt.xlabel("Drug Name")
plt.ylabel("Ratings")
plt.title("Scatter Plot: Drug Name vs Ratings (Testing Data)")
plt.show()
# Generate multiple scatter plots and histograms for the training dataset
feature = ["drugName", "condition", "rating", "usefulCount"]
pd.plotting.scatter_matrix(train_imp[feature])
plt.suptitle("Scatter Matrix For Training DataSet")
plt.show()
plt.title("Drug Name Histogram (Training Dataset)")
plt.hist(train_imp["drugName"], bins=50)
plt.xlabel("Bins")
plt.ylabel("Drug Name")
plt.show()
# Classify drug reviews as either positive or negative
# use the non vectorised original dataset
data = train_df[["review", "rating"]] # the "review" and "rating" columns
# A rating of 5 or more is considered towards the positive side according to dataset
train_labels = torch.tensor([1 if rating >= 5 else 0 for rating in data["rating"]])
# Split the data into training, validation, and testing sets
train_texts, temp_texts, train_labels, temp_labels = train_test_split(
data["review"], train_labels, random_state=42, test_size=0.3
)
val_texts, test_texts, val_labels, test_labels = train_test_split(
temp_texts, temp_labels, random_state=42, test_size=0.5
)
# Initialize the tokenizer
tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
# Tokenize the data
train_encodings = tokenizer(
train_texts.tolist(), truncation=True, padding=True, max_length=256
)
val_encodings = tokenizer(
val_texts.tolist(), truncation=True, padding=True, max_length=256
)
test_encodings = tokenizer(
test_texts.tolist(), truncation=True, padding=True, max_length=256
)
# Prepare the data
class DrugReviewsDataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {k: torch.tensor(v[idx]) for k, v in self.encodings.items()}
item["labels"] = torch.tensor(
self.labels[idx]
) # Use the modified labels directly
return item
def __len__(self):
return len(self.encodings["input_ids"])
train_dataset = DrugReviewsDataset(train_encodings, train_labels)
val_dataset = DrugReviewsDataset(val_encodings, val_labels)
test_dataset = DrugReviewsDataset(test_encodings, test_labels)
# Initialize the model
model = DistilBertForSequenceClassification.from_pretrained(
"distilbert-base-uncased", num_labels=2
)
training_args = TrainingArguments(
output_dir="./results",
num_train_epochs=3,
per_device_train_batch_size=16,
per_device_eval_batch_size=64,
warmup_steps=500,
weight_decay=0.01,
logging_dir="./logs",
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=val_dataset,
compute_metrics=compute_metrics,
)
# Train the model
print("Training the model...")
trainer.train()
# Save the trained model and tokenizer
model.save_pretrained("./save_model/")
tokenizer.save_pretrained("./save_model/")
# Evaluate the model on the test set
print("Evaluating the model on the test set...")
eval_result = trainer.evaluate(test_dataset)
for key, value in eval_result.items():
print(f"{key}: {value}")
# Test the model with new reviews
new_reviews = [
"What is wrong with these drugs? They gave me a ton of side effects.",
"I loved these, it cured all my acne",
]
new_encodings = tokenizer(new_reviews, truncation=True, padding=True, max_length=256)
new_dataset = DrugReviewsDataset(new_encodings, [0, 1]) # Dummy labels for testing
preds = trainer.predict(new_dataset)
predicted_labels = preds.predictions.argmax(axis=1)
print("\nPredictions for new reviews:")
for review, label in zip(new_reviews, predicted_labels):
sentiment = "Positive" if label == 1 else "Negative"
print(f"Review: {review}\nSentiment: {sentiment}\n")
##### LinearRegression regression algorithm #####
##### EDA
##### 1) Summary and Stats
# a) Checking Null Values
print("Null Values in Train Data:\n", X_train.isnull().sum())
print("Null Values in Test Data:\n", X_test.isnull().sum())
# b) Checking the shape of the data
print("Shape of Train Data:", X_train.shape)
print("Shape of Test Data:", X_test.shape)
# c) Zero Counts
print("Zero Counts in Train Data:\n", (X_train == 0).sum())
print("Zero Counts in Test Data:\n", (X_test == 0).sum())
##### 2) Visualizations
# a) Box Plot
plt.figure(figsize=(10, 6))
sns.boxplot(x="rating", data=train_imp)
plt.title("Box Plot of Rating")
plt.show()
# b) Class Imbalance
plt.figure(figsize=(10, 6))
sns.countplot(x="rating", data=train_imp)
plt.title("Class Imbalance of Rating")
plt.show()
### Over Sampling to handle Class Imbalance
ros = RandomOverSampler(random_state=0)
X_train, Y_train = ros.fit_resample(X_train, Y_train)
plt.hist(Y_train, bins=10)
plt.xlabel("Class")
plt.ylabel("Count")
plt.show()
plt.figure(figsize=(10, 6))
sns.countplot(x="rating", data=train_imp)
plt.title("Class Imbalance of Rating after OverSampling")
plt.show()
##################################################
# Create an instance of the LinearRegression algorithm
linear = LinearRegression()
# Fit the LinearRegression model on the training data
linear.fit(X_train, Y_train)
# Make predictions on the training and testing data using the LinearRegression model
line_train = linear.predict(X_train)
line_test = linear.predict(X_test)
# Print the evaluation metrics for Linear Regression
print("Linear Regression Metrics:")
print("MSE for training: ", mean_squared_error(Y_train, line_train))
print("MSE for testing: ", mean_squared_error(Y_test, line_test))
print("R2 score for training: ", r2_score(Y_train, line_train))
print("R2 score for testing: ", r2_score(Y_test, line_test))
# Plotting the scatter plot of predicted vs actual values for training data
plt.scatter(Y_train, line_train)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("Linear Regression - Training Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs actual values for testing data
plt.scatter(Y_test, line_test)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("Linear Regression - Testing Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs true values for both training and testing sets
plt.figure(figsize=(8, 6))
plt.scatter(Y_train, line_train, alpha=0.3, label="Training")
plt.scatter(Y_test, line_test, alpha=0.3, label="Testing")
plt.plot([0, 10], [0, 10], linestyle="--", color="k", label="Perfect prediction")
plt.xlabel("True Ratings")
plt.ylabel("Predicted Ratings")
plt.title("Linear regression - Training and Testing Sets Scatter Plot")
plt.legend()
plt.show()
# Plotting the residual plot for testing data
plt.scatter(line_test, line_test - Y_test, c="g", s=40, alpha=0.5)
plt.hlines(y=0, xmin=0, xmax=10)
plt.xlabel("Predicted Ratings")
plt.ylabel("Residuals")
plt.title("Linear Regression - Testing Data Residual Plot")
plt.show()
for i in range(len(line_test)):
line_test[i] = line_test[i].round()
# Pie Chart
correct_predictions = sum(Y_test == line_test)
incorrect_predictions = len(Y_test) - correct_predictions
labels = ["Correct Predictions", "Incorrect Predictions"]
sizes = [correct_predictions, incorrect_predictions]
colors = ["green", "red"]
plt.pie(sizes, labels=labels, colors=colors, autopct="%1.1f%%", startangle=90)
plt.axis("equal") # Equal aspect ratio ensures a circular pie chart
plt.title("Prediction Accuracy")
# Bar Chart
prediction_column = "predicted_rating"
target_column = "actual_rating"
# Get the predicted ratings and actual ratings from the dataset
predicted_ratings = line_test
actual_ratings = Y_test
# Convert decimal predictions to discrete values (1-10)
rounded_predictions = np.round(predicted_ratings)
# Count the number of correct predictions falling into each range
bins = range(1, 12)
correct_predictions, _ = np.histogram(
rounded_predictions[actual_ratings == rounded_predictions], bins=bins
)
# Create the bar chart
plt.bar(range(1, 11), correct_predictions)
plt.xlabel("Range")
plt.ylabel("Count of Correct Predictions")
plt.title("Bar Chart of Correct Predictions")
# Display the bar chart
plt.show()
# Histogram
plt.hist(Y_test, bins="auto", alpha=0.5, color="blue", label="Actual")
plt.hist(line_test, bins="auto", alpha=0.5, color="red", label="Predicted")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Actual vs Predicted Histogram")
plt.legend()
plt.grid(True)
plt.show()
# Line Chart
predicted_ratings = line_test
actual_ratings = Y_test
# Convert decimal predictions to discrete values (1-10)
rounded_predictions = np.round(predicted_ratings)
# Calculate the number of correct predictions falling into each range
bins = range(1, 12)
correct_predictions, _ = np.histogram(
rounded_predictions[rounded_predictions == actual_ratings], bins=bins
)
# Create a line chart for the number of correct predictions
x = range(1, 11)
plt.plot(x, correct_predictions)
plt.xlabel("Range")
plt.ylabel("Count of Correct Predictions")
plt.title("Line Chart of Correct Predictions")
plt.show()
# Area Chart
predicted_ratings = line_test
actual_ratings = Y_test
# Convert decimal predictions to discrete values (1-10)
rounded_predictions = np.round(predicted_ratings)
# Calculate the number of correct predictions falling into each range
bins = range(1, 12)
correct_predictions, _ = np.histogram(
rounded_predictions[rounded_predictions == actual_ratings], bins=bins
)
# Create an area chart for the number of correct predictions
x = range(1, 11)
plt.fill_between(x, correct_predictions, color="blue", alpha=0.3)
plt.plot(x, correct_predictions, color="blue", linewidth=2)
plt.xlabel("Range")
plt.ylabel("Count of Correct Predictions")
plt.title("Area Chart of Correct Predictions")
plt.show()
##### ANN algorithm #####
from sklearn.neural_network import MLPClassifier
# Create an instance of the MLPClassifier model
model = MLPClassifier(
solver="lbfgs", alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1
)
# Fit the MLPClassifier model on the training data
model.fit(X_train, Y_train)
# Make predictions on the training and testing data using the MLPClassifier model
model_train = model.predict(X_train)
model_test = model.predict(X_test)
# Calculate accuracy scores for the training and testing predictions
train_accuracy = accuracy_score(model_train, Y_train)
test_accuracy = accuracy_score(model_test, Y_test)
# Print the evaluation metrics for the MLPClassifier model
print("\nANN METRICS:")
print("Accuracy for training: ", train_accuracy)
print("Accuracy for testing: ", test_accuracy)
print("MSE for training: ", mean_squared_error(Y_train, model_train))
print("MSE for testing: ", mean_squared_error(Y_test, model_test))
print("R2 score for training: ", r2_score(Y_train, model_train))
print("R2 score for testing: ", r2_score(Y_test, model_test))
# Plotting the scatter plot of predicted vs actual values for training data
plt.scatter(Y_train, model_train)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("ANN - Training Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs actual values for testing data
plt.scatter(Y_test, model_test)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("ANN - Testing Data Scatter Plot")
plt.show()
# Plotting the Accuracy Plot
plt.plot(["Training", "Testing"], [train_accuracy, test_accuracy], marker="o")
plt.title("ANN Accuracy")
plt.xlabel("Dataset")
plt.ylabel("Accuracy")
plt.show()
# Plotting the confusion matrix
cm = confusion_matrix(Y_test, model_test, labels=model.classes_)
ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=model.classes_).plot()
plt.title("ANN Confusion Matrix")
plt.show()
##### ADABOOST algorithm #####
from sklearn.ensemble import AdaBoostClassifier
from sklearn.datasets import make_classification
# Generate a synthetic dataset for training
X_train, Y_train = make_classification(
n_samples=1006,
n_features=1006,
n_informative=2,
n_redundant=0,
random_state=0,
shuffle=False,
)
# Create an instance of the AdaBoostClassifier model
clf = AdaBoostClassifier(n_estimators=100, random_state=0)
# Fit the AdaBoostClassifier model on the training data
clf.fit(X_train, Y_train)
# Make predictions on the training and testing data using the AdaBoostClassifier model
ada_train = clf.predict(X_train)
ada_test = clf.predict(X_test)
# Calculate accuracy scores for the training and testing predictions
ada_train_accuracy = accuracy_score(ada_train, Y_train)
ada_test_accuracy = accuracy_score(ada_test, Y_test)
# Print the evaluation metrics for the AdaBoostClassifier model
print("\nAdaBOOST METRICS:")
print("Accuracy for training: ", ada_train_accuracy)
print("Accuracy for testing: ", ada_test_accuracy)
print("MSE for training: ", mean_squared_error(Y_train, ada_train))
print("MSE for testing: ", mean_squared_error(Y_test, ada_test))
print("R2 score for training: ", r2_score(Y_train, ada_train))
print("R2 score for testing: ", r2_score(Y_test, ada_test))
# Plotting the scatter plot of predicted vs actual values for training data
plt.scatter(Y_train, ada_train)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("AdaBoost - Training Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs actual values for testing data
plt.scatter(Y_test, ada_test)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("AdaBoost - Testing Data Scatter Plot")
plt.show()
# Plotting the Accuracy Plot
plt.plot(["Training", "Testing"], [ada_train_accuracy, ada_test_accuracy], marker="o")
plt.title("AdaBoost Accuracy")
plt.xlabel("Dataset")
plt.ylabel("Accuracy")
plt.show()
# Plotting the confusion matrix
cm = confusion_matrix(Y_test, ada_test, labels=clf.classes_)
ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=clf.classes_).plot()
plt.title("AdaBoost Confusion Matrix")
plt.show()
##### XGBOOST ####
import xgboost
# Create an instance of the XGBRegressor model with specified parameters
model = xgboost.XGBRegressor(
n_estimators=1000, max_depth=7, eta=0.1, subsample=0.7, colsample_bytree=0.8
)
# Fit the XGBRegressor model on the training data
model.fit(X_train, Y_train)
# Make predictions on the training and testing data using the XGBRegressor model
xg_train = model.predict(X_train)
xg_test = model.predict(X_test)
# Print the evaluation metrics for XGBoost
print("XGBoost Metrics:")
print("MSE for training: ", mean_squared_error(Y_train, xg_train))
print("MSE for testing: ", mean_squared_error(Y_test, xg_test))
print("R2 score for training: ", r2_score(Y_train, xg_train))
print("R2 score for testing: ", r2_score(Y_test, xg_test))
# Plotting the scatter plot of predicted vs actual values for training data
plt.scatter(Y_train, xg_train)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("XGBoost Regression - Training Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs actual values for testing data
plt.scatter(Y_test, xg_test)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("XGBoost Regression - Testing Data Scatter Plot")
plt.show()
##### LGBM ####
from lightgbm import LGBMRegressor
# Create an instance of the LGBMRegressor model
lgbmodel = LGBMRegressor()
# Fit the LGBMRegressor model on the training data
lgbmodel.fit(X_train, Y_train)
# Make predictions on the training and testing data using the LGBMRegressor model
lgb_train = lgbmodel.predict(X_train)
lgb_test = lgbmodel.predict(X_test)
# Print the evaluation metrics for LGBMRegressor
print("LGBM Metrics:")
print("MSE for training: ", mean_squared_error(Y_train, lgb_train))
print("MSE for testing: ", mean_squared_error(Y_test, lgb_test))
print("R2 score for training: ", r2_score(Y_train, lgb_train))
print("R2 score for testing: ", r2_score(Y_test, lgb_test))
# Plotting the scatter plot of predicted vs actual values for training data
plt.scatter(Y_train, lgb_train)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("LGBM Regression - Training Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs actual values for testing data
plt.scatter(Y_test, lgb_test)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("LGBM Regression - Testing Data Scatter Plot")
plt.show()
##### SVR #####
from sklearn import svm
# Create an instance of the Support Vector Machine (SVM) model for regression
svm_model = svm.SVR()
# Fit the SVM model on the training data
svm_model.fit(X_train, Y_train)
# Make predictions on the training and testing data using the SVM model
svm_train = svm_model.predict(X_train)
svm_test = svm_model.predict(X_test)
# Print the evaluation metrics for SVM regression
print("SVM Regression Metrics:")
print("MSE for training: ", mean_squared_error(Y_train, svm_train))
print("MSE for testing: ", mean_squared_error(Y_test, svm_test))
print("R2 score for training: ", r2_score(Y_train, svm_train))
print("R2 score for testing: ", r2_score(Y_test, svm_test))
# Plotting the scatter plot of predicted vs actual values for training data
plt.scatter(Y_train, svm_train)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("LGBM Regression - Training Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs actual values for testing data
plt.scatter(Y_test, svm_test)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("LGBM Regression - Testing Data Scatter Plot")
plt.show()
##### Randomized Random Forest Regression algorithm #####
param = [
{
"n_estimators": [100, 200, 300],
"max_depth": [3, 4, 6],
"max_leaf_nodes": [15, 20, 25],
},
]
rf = RandomForestRegressor()
rs_rf = RandomizedSearchCV(rf, param, cv=2, n_jobs=-1, verbose=1)
rs_rf.fit(X_train, Y_train)
rs_rf_train = rs_rf.predict(X_train)
rs_rf_test = rs_rf.predict(X_test)
print("Randomized RandomForestRegressor Metrics:")
print("MSE for training: ", mean_squared_error(Y_train, rs_rf_train))
print("MSE for testing: ", mean_squared_error(Y_test, rs_rf_test))
print("R2 score for training: ", r2_score(Y_train, rs_rf_train))
print("R2 score for testing: ", r2_score(Y_test, rs_rf_test))
# Plotting the scatter plot of predicted vs actual values for training data
plt.scatter(Y_train, rs_rf_train)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("Randomized RandomForestRegressor - Training Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs actual values for testing data
plt.scatter(Y_test, rs_rf_test)
plt.xlabel("Actual Ratings")
plt.ylabel("Predicted Ratings")
plt.title("Randomized RandomForestRegressor - Testing Data Scatter Plot")
plt.show()
# Plotting the scatter plot of predicted vs true values for both training and testing sets
plt.figure(figsize=(8, 6))
plt.scatter(Y_train, rs_rf_train, alpha=0.3, label="Training")
plt.scatter(Y_test, rs_rf_test, alpha=0.3, label="Testing")
plt.plot([0, 10], [0, 10], linestyle="--", color="k", label="Perfect prediction")
plt.xlabel("True Ratings")
plt.ylabel("Predicted Ratings")
plt.title("Randomized RandomForestRegressor - Training and Testing Sets Scatter Plot")
plt.legend()
plt.show()
# Plotting the residual plot for testing data
plt.scatter(rs_rf_test, rs_rf_test - Y_test, c="g", s=40, alpha=0.5)
plt.hlines(y=0, xmin=0, xmax=10)
plt.xlabel("Predicted Ratings")
plt.ylabel("Residuals")
plt.title("Randomized RandomForestRegressor - Testing Data Residual Plot")
plt.show()
##### GriSearch LogisticRegression classification algorithm #####
param = [
{
"penalty": ["l1", "l2", "elasticnet", None],
"solver": ["lbfgs", "liblinear", "newton-cg", "newton-cholesky"],
},
]
logi = LogisticRegression()
gs_logi = GridSearchCV(logi, param, cv=2, n_jobs=-1, verbose=1)
gs_logi.fit(X_train, Y_train)
logi_train = gs_logi.predict(X_train)
logi_test = gs_logi.predict(X_test)
train_accuracy = accuracy_score(logi_train, Y_train)
test_accuracy = accuracy_score(logi_test, Y_test)
print("\nLogistic Regression Metrics:")