-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfinal code for task 1
1599 lines (1366 loc) · 74 KB
/
final code for task 1
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 requests
from bs4 import BeautifulSoup
import pandas as pd
base_url = "https://www.airlinequality.com/airline-reviews/british-airways"
pages = 10
page_size = 100
reviews= []
base_url = "https://www.airlinequality.com/airline-reviews/british-airways"
pages = 10
page_size = 100
reviews = []
# for i in range(1, pages + 1):
for i in range(1, pages + 1):
print(f"Scraping page {i}")
# Create URL to collect links from paginated data
url = f"{base_url}/page/{i}/?sortby=post_date%3ADesc&pagesize={page_size}"
# Collect HTML data from this page
response = requests.get(url)
# Parse content
content = response.content
parsed_content = BeautifulSoup(content, 'html.parser')
for para in parsed_content.find_all("div", {"class": "text_content"}):
reviews.append(para.get_text())
print(f" ---> {len(reviews)} total reviews")
Scraping page 1
---> 100 total reviews
Scraping page 2
---> 200 total reviews
Scraping page 3
---> 300 total reviews
Scraping page 4
---> 400 total reviews
Scraping page 5
---> 500 total reviews
Scraping page 6
---> 600 total reviews
Scraping page 7
---> 700 total reviews
Scraping page 8
---> 800 total reviews
Scraping page 9
---> 900 total reviews
Scraping page 10
---> 1000 total reviews
df.to_csv("data/BA_reviews.csv")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[4], line 1
----> 1 df.to_csv("data/BA_reviews.csv")
NameError: name 'df' is not defined
df = pd.DataFrame()
df["reviews"] = reviews
df.head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 1
----> 1 df = pd.DataFrame()
2 df["reviews"] = reviews
3 df.head()
NameError: name 'pd' is not defined
df.to_csv("data/BA_reviews.csv")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[2], line 1
----> 1 df.to_csv("data/BA_reviews.csv")
NameError: name 'df' is not defined
import pandas as pd
Df = pd.read_csv("/Users/ayodejioyesanya/Desktop/BA_reviews_20231121_123616.csv")
Df
docs = df.reviews.tolist()
docs [0]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[3], line 4
2 Df = pd.read_csv("/Users/ayodejioyesanya/Desktop/BA_reviews_20231121_123616.csv")
3 Df
----> 4 docs = df.reviews.tolist()
5 docs [0]
NameError: name 'df' is not defined
import pandas as pd
Df = pd.read_csv("/Users/ayodejioyesanya/Desktop/BA_reviews_20231121_123616.csv")
Df
docs = Df.reviews.tolist()
docs [0]
'✅ Trip Verified | 4 Hours before takeoff we received a Mail stating a cryptic message that there are disruptions to be expected as there is a limit on how many planes can leave at the same time. So did the capacity of the Heathrow Airport really hit British Airways by surprise, 4h before departure? Anyhow - we took the one hour delay so what - but then we have been forced to check in our Hand luggage. I travel only with hand luggage to avoid waiting for the ultra slow processing of the checked in luggage. Overall 2h later at home than planed, with really no reason, just due to incompetent people. Service level far worse then Ryanair and triple the price. Really never again. Thanks for nothing.'
df = pd.read_csv("data/BA_reviews.csv")
print(df.head())
df['reviews'] = df['reviews'].str.replace('✅ Trip Verified', '')
print(df.head())
df.to_csv("data/cleaned_BA_reviews.csv", index=False)
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[5], line 1
----> 1 df = pd.read_csv("data/BA_reviews.csv")
2 print(df.head())
3 df['reviews'] = df['reviews'].str.replace('✅ Trip Verified', '')
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/parsers/readers.py:948, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)
935 kwds_defaults = _refine_defaults_read(
936 dialect,
937 delimiter,
(...)
944 dtype_backend=dtype_backend,
945 )
946 kwds.update(kwds_defaults)
--> 948 return _read(filepath_or_buffer, kwds)
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/parsers/readers.py:611, in _read(filepath_or_buffer, kwds)
608 _validate_names(kwds.get("names", None))
610 # Create the parser.
--> 611 parser = TextFileReader(filepath_or_buffer, **kwds)
613 if chunksize or iterator:
614 return parser
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/parsers/readers.py:1448, in TextFileReader.__init__(self, f, engine, **kwds)
1445 self.options["has_index_names"] = kwds["has_index_names"]
1447 self.handles: IOHandles | None = None
-> 1448 self._engine = self._make_engine(f, self.engine)
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/parsers/readers.py:1705, in TextFileReader._make_engine(self, f, engine)
1703 if "b" not in mode:
1704 mode += "b"
-> 1705 self.handles = get_handle(
1706 f,
1707 mode,
1708 encoding=self.options.get("encoding", None),
1709 compression=self.options.get("compression", None),
1710 memory_map=self.options.get("memory_map", False),
1711 is_text=is_text,
1712 errors=self.options.get("encoding_errors", "strict"),
1713 storage_options=self.options.get("storage_options", None),
1714 )
1715 assert self.handles is not None
1716 f = self.handles.handle
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/common.py:863, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
858 elif isinstance(handle, str):
859 # Check whether the filename is to be opened in binary mode.
860 # Binary mode does not support 'encoding' and 'newline'.
861 if ioargs.encoding and "b" not in ioargs.mode:
862 # Encoding
--> 863 handle = open(
864 handle,
865 ioargs.mode,
866 encoding=ioargs.encoding,
867 errors=errors,
868 newline="",
869 )
870 else:
871 # Binary mode
872 handle = open(handle, ioargs.mode)
FileNotFoundError: [Errno 2] No such file or directory: 'data/BA_reviews.csv'
df = pd.read_csv(""/Users/ayodejioyesanya/Desktop/BA_reviews_20231121_123616.csv")
print(df.head())
df['reviews'] = df['reviews'].str.replace('✅ Trip Verified', '')
print(df.head())
df.to_csv("data/cleaned_BA_reviews_20231121_123616.csv", index=False)
Cell In[6], line 1
df = pd.read_csv(""/Users/ayodejioyesanya/Desktop/BA_reviews_20231121_123616.csv")
^
SyntaxError: unterminated string literal (detected at line 1)
df = pd.read_csv("/Users/ayodejioyesanya/Desktop/BA_reviews_20231121_123616.csv")
print(df.head())
df['reviews'] = df['reviews'].str.replace('✅ Trip Verified', '')
print(df.head())
df.to_csv("data/cleaned_BA_reviews_20231121_123616.csv", index=False)
Unnamed: 0 reviews
0 0 ✅ Trip Verified | 4 Hours before takeoff we r...
1 1 ✅ Trip Verified | I recently had a delay on B...
2 2 Not Verified | Boarded on time, but it took a...
3 3 ✅ Trip Verified | 5 days before the flight, w...
4 4 Not Verified | \r\nWe traveled to Lisbon for ...
Unnamed: 0 reviews
0 0 | 4 Hours before takeoff we received a Mail ...
1 1 | I recently had a delay on British Airways ...
2 2 Not Verified | Boarded on time, but it took a...
3 3 | 5 days before the flight, we were advised ...
4 4 Not Verified | \r\nWe traveled to Lisbon for ...
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
Cell In[7], line 5
3 df['reviews'] = df['reviews'].str.replace('✅ Trip Verified', '')
4 print(df.head())
----> 5 df.to_csv("data/cleaned_BA_reviews_20231121_123616.csv", index=False)
File ~/anaconda3/lib/python3.10/site-packages/pandas/core/generic.py:3902, in NDFrame.to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, lineterminator, chunksize, date_format, doublequote, escapechar, decimal, errors, storage_options)
3891 df = self if isinstance(self, ABCDataFrame) else self.to_frame()
3893 formatter = DataFrameFormatter(
3894 frame=df,
3895 header=header,
(...)
3899 decimal=decimal,
3900 )
-> 3902 return DataFrameRenderer(formatter).to_csv(
3903 path_or_buf,
3904 lineterminator=lineterminator,
3905 sep=sep,
3906 encoding=encoding,
3907 errors=errors,
3908 compression=compression,
3909 quoting=quoting,
3910 columns=columns,
3911 index_label=index_label,
3912 mode=mode,
3913 chunksize=chunksize,
3914 quotechar=quotechar,
3915 date_format=date_format,
3916 doublequote=doublequote,
3917 escapechar=escapechar,
3918 storage_options=storage_options,
3919 )
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/formats/format.py:1152, in DataFrameRenderer.to_csv(self, path_or_buf, encoding, sep, columns, index_label, mode, compression, quoting, quotechar, lineterminator, chunksize, date_format, doublequote, escapechar, errors, storage_options)
1131 created_buffer = False
1133 csv_formatter = CSVFormatter(
1134 path_or_buf=path_or_buf,
1135 lineterminator=lineterminator,
(...)
1150 formatter=self.fmt,
1151 )
-> 1152 csv_formatter.save()
1154 if created_buffer:
1155 assert isinstance(path_or_buf, StringIO)
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/formats/csvs.py:247, in CSVFormatter.save(self)
243 """
244 Create the writer & save.
245 """
246 # apply compression and byte/text conversion
--> 247 with get_handle(
248 self.filepath_or_buffer,
249 self.mode,
250 encoding=self.encoding,
251 errors=self.errors,
252 compression=self.compression,
253 storage_options=self.storage_options,
254 ) as handles:
255 # Note: self.encoding is irrelevant here
256 self.writer = csvlib.writer(
257 handles.handle,
258 lineterminator=self.lineterminator,
(...)
263 quotechar=self.quotechar,
264 )
266 self._save()
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/common.py:739, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
737 # Only for write methods
738 if "r" not in mode and is_path:
--> 739 check_parent_directory(str(handle))
741 if compression:
742 if compression != "zstd":
743 # compression libraries do not like an explicit text-mode
File ~/anaconda3/lib/python3.10/site-packages/pandas/io/common.py:604, in check_parent_directory(path)
602 parent = Path(path).parent
603 if not parent.is_dir():
--> 604 raise OSError(rf"Cannot save file into a non-existent directory: '{parent}'")
OSError: Cannot save file into a non-existent directory: 'data'
df.to_csv("/Users/ayodejioyesanya/Desktop/cleaned_BA_reviews_20231121_123616.csv", index=False)
import pandas as pd
Df = pd.read_csv("/Users/ayodejioyesanya/Desktop/BA_reviews_20231121_123616.csv")
Df
docs = Df.reviews.tolist()
docs [0]
import pandas as pd
Df = pd.read_csv("/Users/ayodejioyesanya/Desktop/cleaned_BA_reviews_20231121_123616.csv")
Df
docs = Df.reviews.tolist()
docs [0]
' | 4 Hours before takeoff we received a Mail stating a cryptic message that there are disruptions to be expected as there is a limit on how many planes can leave at the same time. So did the capacity of the Heathrow Airport really hit British Airways by surprise, 4h before departure? Anyhow - we took the one hour delay so what - but then we have been forced to check in our Hand luggage. I travel only with hand luggage to avoid waiting for the ultra slow processing of the checked in luggage. Overall 2h later at home than planed, with really no reason, just due to incompetent people. Service level far worse then Ryanair and triple the price. Really never again. Thanks for nothing.'
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.manifold import TSNE
from umap import UMAP
from wordcloud import WordCloud
from nltk.sentiment import SentimentIntensityAnalyzer
# Assuming you have a function 'use_embed' for USE embeddings
# import tensorflow_hub as hub
# Function to perform clustering
def perform_clustering(embeddings, n_clusters=3):
kmeans = KMeans(n_clusters=n_clusters, n_init=10, random_state=42)
cluster_labels = kmeans.fit_predict(embeddings)
return cluster_labels
# Function to extract keywords using TF-IDF
def extract_keywords(reviews, n_keywords=10):
vectorizer = TfidfVectorizer(max_features=n_keywords)
tfidf_matrix = vectorizer.fit_transform(reviews)
feature_names = vectorizer.get_feature_names_out()
return pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)
# Function to perform topic modeling using LDA
def perform_topic_modeling(reviews, n_topics=5):
vectorizer = TfidfVectorizer(max_features=5000, stop_words='english')
tfidf_matrix = vectorizer.fit_transform(reviews)
lda = LatentDirichletAllocation(n_components=n_topics, random_state=42)
lda.fit(tfidf_matrix)
return lda, vectorizer
# Function to visualize word cloud
def visualize_word_cloud(text, title):
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title(title)
plt.show()
# Function to perform sentiment analysis using VADER
def perform_sentiment_analysis(reviews):
analyzer = SentimentIntensityAnalyzer()
sentiments = [analyzer.polarity_scores(review)['compound'] for review in reviews]
return sentiments
# Function to visualize t-SNE
def visualize_tsne(embeddings, labels):
tsne = TSNE(n_components=2, perplexity=5, random_state=42, n_jobs=1) # Adjusted perplexity value and set n_jobs explicitly
tsne_result = tsne.fit_transform(embeddings)
plt.figure(figsize=(8, 6))
sns.scatterplot(x=tsne_result[:, 0], y=tsne_result[:, 1], hue=labels, palette="viridis")
plt.title('t-SNE Visualization')
plt.show()
# Function to perform UMAP dimensionality reduction
def visualize_umap(embeddings, labels):
umap_result = UMAP(n_neighbors=5, min_dist=0.3, random_state=42, n_jobs=1).fit_transform(embeddings) # Set n_jobs explicitly
plt.figure(figsize=(8, 6))
sns.scatterplot(x=umap_result[:, 0], y=umap_result[:, 1], hue=labels, palette="viridis")
plt.title('UMAP Visualization')
plt.show()
# Example British Airways reviews
reviews = [
"London to Gothenburg. BA are getting a lot of bad press - deservedly so at present with strikes, IT glitches, baggage problems...",
"London Heathrow to Inverness. Having previously written a review about the shockingly appalling experience with BA so far this summer...",
"Heathrow to Glasgow. Again flight is delayed. It’s easier to use the train than fly with BA the staff don’t even get embarrassed anymore...",
"I was flying BA to Delhi in economy because my original flight with Swissair was cancelled. The 777 aircraft is looking old, the economy class seat is small and fairly cramped...",
"BA 2616 and 2617 return trip from Gatwick to Cagliari. Both flights on a Saturday and were full. Aircraft was an A320-200 on both legs...",
"The flight was delayed but the crew was helpful."
]
# Assuming 'review_embeddings' is the result of USE embeddings
# Use your actual embedding function or method
# import tensorflow as tf
# use_embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
# review_embeddings = use_embed(reviews).numpy()
# Visualize t-SNE with modified perplexity
visualize_tsne(review_embeddings, labels=reviews)
# Perform clustering
cluster_labels = perform_clustering(review_embeddings, n_clusters=3)
# Visualize UMAP
visualize_umap(review_embeddings, labels=cluster_labels)
# Extract keywords using TF-IDF
keywords_df = extract_keywords(reviews, n_keywords=10)
print("Top Keywords:")
print(keywords_df)
# Perform topic modeling using LDA
lda_model, vectorizer = perform_topic_modeling(reviews)
print("Top Words in Topics:")
for i, topic in enumerate(lda_model.components_):
top_words_idx = topic.argsort()[-5:][::-1]
top_words = [vectorizer.get_feature_names_out()[idx] for idx in top_words_idx]
print(f"Topic {i}: {', '.join(top_words)}")
# Function to perform clustering
def perform_clustering(embeddings, n_clusters=3):
kmeans = KMeans(n_clusters=n_clusters, n_init=10, random_state=42)
cluster_labels = kmeans.fit_predict(embeddings)
return cluster_labels
import tensorflow_hub as hub
use_embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
review_embeddings = use_embed(reviews).numpy()
# ... (previous code)
# Function to perform topic modeling using LDA
def perform_topic_modeling(reviews, n_topics=5):
vectorizer = TfidfVectorizer(max_features=5000, stop_words='english')
tfidf_matrix = vectorizer.fit_transform(reviews)
lda = LatentDirichletAllocation(n_components=n_topics, random_state=42)
lda.fit(tfidf_matrix)
return lda, vectorizer
# Function to visualize word cloud
def visualize_word_cloud(text, title):
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title(title)
plt.show()
# Function to perform sentiment analysis using VADER
def perform_sentiment_analysis(reviews):
analyzer = SentimentIntensityAnalyzer()
sentiments = [analyzer.polarity_scores(review)['compound'] for review in reviews]
return sentiments
# Function to visualize t-SNE
def visualize_tsne(embeddings, labels):
tsne = TSNE(n_components=2, perplexity=5, random_state=42, n_jobs=1) # Adjusted perplexity value and set n_jobs explicitly
tsne_result = tsne.fit_transform(embeddings)
plt.figure(figsize=(8, 6))
sns.scatterplot(x=tsne_result[:, 0], y=tsne_result[:, 1], hue=labels, palette="viridis")
plt.title('t-SNE Visualization')
plt.show()
# Function to perform UMAP dimensionality reduction
def visualize_umap(embeddings, labels):
umap_result = UMAP(n_neighbors=5, min_dist=0.3, random_state=42, n_jobs=1).fit_transform(embeddings) # Set n_jobs explicitly
plt.figure(figsize=(8, 6))
sns.scatterplot(x=umap_result[:, 0], y=umap_result[:, 1], hue=labels, palette="viridis")
plt.title('UMAP Visualization')
plt.show()
# Example British Airways reviews
reviews = [
"London to Gothenburg. BA are getting a lot of bad press - deservedly so at present with strikes, IT glitches, baggage problems...",
"London Heathrow to Inverness. Having previously written a review about the shockingly appalling experience with BA so far this summer...",
"Heathrow to Glasgow. Again flight is delayed. It’s easier to use the train than fly with BA the staff don’t even get embarrassed anymore...",
"I was flying BA to Delhi in economy because my original flight with Swissair was cancelled. The 777 aircraft is looking old, the economy class seat is small and fairly cramped...",
"BA 2616 and 2617 return trip from Gatwick to Cagliari. Both flights on a Saturday and were full. Aircraft was an A320-200 on both legs...",
"The flight was delayed but the crew was helpful."
]
# Assuming 'review_embeddings' is the result of USE embeddings
# Use your actual embedding function or method
# import tensorflow as tf
# use_embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
# review_embeddings = use_embed(reviews).numpy()
# Visualize t-SNE with modified perplexity
visualize_tsne(review_embeddings, labels=reviews)
# Perform clustering
cluster_labels = perform_clustering(review_embeddings, n_clusters=3)
# Visualize UMAP
visualize_umap(review_embeddings, labels=cluster_labels)
# Extract keywords using TF-IDF
keywords_df = extract_keywords(reviews, n_keywords=10)
print("Top Keywords:")
print(keywords_df)
# Perform topic modeling using LDA
lda_model, vectorizer = perform_topic_modeling(reviews)
print("Top Words in Topics:")
for i, topic in enumerate(lda_model.components_):
top_words_idx = topic.argsort()[-5:][::-1]
top_words = [vectorizer.get_feature_names_out()[idx] for idx in top_words_idx]
print(f"Topic {i}: {', '.join(top_words)}")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[2], line 65
49 reviews = [
50 "London to Gothenburg. BA are getting a lot of bad press - deservedly so at present with strikes, IT glitches, baggage problems...",
51 "London Heathrow to Inverness. Having previously written a review about the shockingly appalling experience with BA so far this summer...",
(...)
55 "The flight was delayed but the crew was helpful."
56 ]
58 # Assuming 'review_embeddings' is the result of USE embeddings
59 # Use your actual embedding function or method
60 # import tensorflow as tf
(...)
63
64 # Visualize t-SNE with modified perplexity
---> 65 visualize_tsne(review_embeddings, labels=reviews)
67 # Perform clustering
68 cluster_labels = perform_clustering(review_embeddings, n_clusters=3)
NameError: name 'review_embeddings' is not defined
# Assuming 'review_embeddings' is the result of USE embeddings
# Use your actual embedding function or method
import tensorflow as tf
import tensorflow_hub as hub
# Assuming 'use_embed' is your embedding function or model
use_embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
review_embeddings = use_embed(reviews).numpy()
# Visualize t-SNE with modified perplexity
visualize_tsne(review_embeddings, labels=reviews)
# Perform clustering
cluster_labels = perform_clustering(review_embeddings, n_clusters=3)
# Visualize UMAP
visualize_umap(review_embeddings, labels=cluster_labels)
# Extract keywords using TF-IDF
keywords_df = extract_keywords(reviews, n_keywords=10)
print("Top Keywords:")
print(keywords_df)
# Perform topic modeling using LDA
lda_model, vectorizer = perform_topic_modeling(reviews)
print("Top Words in Topics:")
for i, topic in enumerate(lda_model.components_):
top_words_idx = topic.argsort()[-5:][::-1]
top_words = [vectorizer.get_feature_names_out()[idx] for idx in top_words_idx]
print(f"Topic {i}: {', '.join(top_words)}")
pip install seaborn
Requirement already satisfied: seaborn in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (0.13.0)
Requirement already satisfied: numpy!=1.24.0,>=1.20 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from seaborn) (1.26.0)
Requirement already satisfied: matplotlib!=3.6.1,>=3.3 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from seaborn) (3.8.1)
Requirement already satisfied: pandas>=1.2 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from seaborn) (2.1.3)
Requirement already satisfied: packaging>=20.0 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (23.1)
Requirement already satisfied: pyparsing>=2.3.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (3.1.1)
Requirement already satisfied: python-dateutil>=2.7 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (2.8.2)
Requirement already satisfied: kiwisolver>=1.3.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (1.4.5)
Requirement already satisfied: contourpy>=1.0.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (1.2.0)
Requirement already satisfied: pillow>=8 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (10.0.1)
Requirement already satisfied: cycler>=0.10 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (4.44.0)
Requirement already satisfied: tzdata>=2022.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from pandas>=1.2->seaborn) (2023.3)
Requirement already satisfied: pytz>=2020.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from pandas>=1.2->seaborn) (2023.3.post1)
Requirement already satisfied: six>=1.5 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from python-dateutil>=2.7->matplotlib!=3.6.1,>=3.3->seaborn) (1.16.0)
Note: you may need to restart the kernel to use updated packages.
pip install seaborn
Requirement already satisfied: seaborn in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (0.13.0)
Requirement already satisfied: pandas>=1.2 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from seaborn) (2.1.3)
Requirement already satisfied: numpy!=1.24.0,>=1.20 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from seaborn) (1.26.0)
Requirement already satisfied: matplotlib!=3.6.1,>=3.3 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from seaborn) (3.8.1)
Requirement already satisfied: pillow>=8 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (10.0.1)
Requirement already satisfied: python-dateutil>=2.7 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (2.8.2)
Requirement already satisfied: cycler>=0.10 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (0.12.1)
Requirement already satisfied: kiwisolver>=1.3.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (1.4.5)
Requirement already satisfied: fonttools>=4.22.0 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (4.44.0)
Requirement already satisfied: pyparsing>=2.3.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (3.1.1)
Requirement already satisfied: contourpy>=1.0.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (1.2.0)
Requirement already satisfied: packaging>=20.0 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.3->seaborn) (23.1)
Requirement already satisfied: pytz>=2020.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from pandas>=1.2->seaborn) (2023.3.post1)
Requirement already satisfied: tzdata>=2022.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from pandas>=1.2->seaborn) (2023.3)
Requirement already satisfied: six>=1.5 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from python-dateutil>=2.7->matplotlib!=3.6.1,>=3.3->seaborn) (1.16.0)
Note: you may need to restart the kernel to use updated packages.
import seaborn as sns
# Function to perform clustering
def perform_clustering(embeddings, n_clusters=3):
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
cluster_labels = kmeans.fit_predict(embeddings)
return cluster_labels
#reads a CSV file into a pandas DataFrame, displays the DataFrame, extracts the 'reviews' column as a list, and then prints the first element of that list
import pandas as pd
Df = pd.read_csv("/Users/ayodejioyesanya/Desktop/cleaned_BA_reviews_20231121_123616.csv")
Df
docs = Df.reviews.tolist()
docs [0]
' | 4 Hours before takeoff we received a Mail stating a cryptic message that there are disruptions to be expected as there is a limit on how many planes can leave at the same time. So did the capacity of the Heathrow Airport really hit British Airways by surprise, 4h before departure? Anyhow - we took the one hour delay so what - but then we have been forced to check in our Hand luggage. I travel only with hand luggage to avoid waiting for the ultra slow processing of the checked in luggage. Overall 2h later at home than planed, with really no reason, just due to incompetent people. Service level far worse then Ryanair and triple the price. Really never again. Thanks for nothing.'
# Function to extract keywords using TF-IDF
def extract_keywords(reviews, n_keywords=10):
vectorizer = TfidfVectorizer(max_features=n_keywords)
tfidf_matrix = vectorizer.fit_transform(reviews)
feature_names = vectorizer.get_feature_names_out()
return pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)
# Function to perform topic modeling using LDA
def perform_topic_modeling(reviews, n_topics=5):
vectorizer = TfidfVectorizer(max_features=5000, stop_words='english')
tfidf_matrix = vectorizer.fit_transform(reviews)
lda = LatentDirichletAllocation(n_components=n_topics, random_state=42)
lda.fit(tfidf_matrix)
return lda, vectorizer
# Function to visualize word cloud
def visualize_word_cloud(text, title):
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title(title)
plt.show()
# Function to perform sentiment analysis using VADER
def perform_sentiment_analysis(reviews):
analyzer = SentimentIntensityAnalyzer()
sentiments = [analyzer.polarity_scores(review)['compound'] for review in reviews]
return sentiments
# Function to visualize t-SNE
def visualize_tsne(embeddings, labels):
tsne = TSNE(n_components=2, perplexity=5, random_state=42, n_jobs=1)
tsne_result = tsne.fit_transform(embeddings)
plt.figure(figsize=(8, 6))
sns.scatterplot(x=tsne_result[:, 0], y=tsne_result[:, 1], hue=labels, palette="viridis")
plt.title('t-SNE Visualization')
plt.show()
# Function to perform UMAP dimensionality reduction
def visualize_umap(embeddings, labels):
umap_result = UMAP(n_neighbors=5, min_dist=0.3, random_state=42, n_jobs=1).fit_transform(embeddings)
plt.figure(figsize=(8, 6))
sns.scatterplot(x=umap_result[:, 0], y=umap_result[:, 1], hue=labels, palette="viridis")
plt.title('UMAP Visualization')
plt.show()
# Example British Airways reviews
reviews = [
"London to Gothenburg. BA are getting a lot of bad press - deservedly so at present with strikes, IT glitches, baggage problems...",
"London Heathrow to Inverness. Having previously written a review about the shockingly appalling experience with BA so far this summer...",
"Heathrow to Glasgow. Again flight is delayed. It’s easier to use the train than fly with BA the staff don’t even get embarrassed anymore...",
"I was flying BA to Delhi in economy because my original flight with Swissair was cancelled. The 777 aircraft is looking old, the economy class seat is small and fairly cramped...",
"BA 2616 and 2617 return trip from Gatwick to Cagliari. Both flights on a Saturday and were full. Aircraft was an A320-200 on both legs...",
"The flight was delayed but the crew was helpful."
]
# Load pre-trained USE model
use_embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
# Get USE embeddings for reviews
review_embeddings = use_embed(reviews).numpy()
# Visualize t-SNE with modified perplexity
visualize_tsne(review_embeddings, labels=reviews)
# Perform clustering
cluster_labels = perform_clustering(review_embeddings, n_clusters=3)
# Visualize UMAP
visualize_umap(review_embeddings, labels=cluster_labels)
# Extract keywords using TF-IDF
keywords_df = extract_keywords(reviews, n_keywords=10)
print("Top Keywords:")
print(keywords_df)
# Perform topic modeling using LDA
lda_model, vectorizer = perform_topic_modeling(reviews)
print("Top Words in Topics:")
for i, topic in enumerate(lda_model.components_):
top_words_idx = topic.argsort()[-5:][::-1]
top_words = [vectorizer.get_feature_names_out()[idx] for idx in top_words_idx]
print(f"Topic {i}: {', '.join(top_words)}")
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
import tensorflow_hub as hub
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.manifold import TSNE
from umap import UMAP
from wordcloud import WordCloud
from nltk.sentiment import SentimentIntensityAnalyzer
# Function to perform clustering
def perform_clustering(embeddings, n_clusters=3):
kmeans = KMeans(n_clusters=n_clusters, n_init=10, random_state=42)
cluster_labels = kmeans.fit_predict(embeddings)
return cluster_labels
pip install --user -U nltk
Requirement already satisfied: nltk in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (3.8.1)
Requirement already satisfied: joblib in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from nltk) (1.3.2)
Requirement already satisfied: tqdm in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from nltk) (4.65.0)
Requirement already satisfied: regex>=2021.8.3 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from nltk) (2023.10.3)
Requirement already satisfied: click in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from nltk) (8.1.7)
Note: you may need to restart the kernel to use updated packages.
import pandas as pd
from nltk.sentiment import SentimentIntensityAnalyzer
import matplotlib.pyplot as plt
import nltk
print(nltk.data.path)
['/Users/ayodejioyesanya/nltk_data', '/Users/ayodejioyesanya/anaconda3/nltk_data', '/Users/ayodejioyesanya/anaconda3/share/nltk_data', '/Users/ayodejioyesanya/anaconda3/lib/nltk_data', '/usr/share/nltk_data', '/usr/local/share/nltk_data', '/usr/lib/nltk_data', '/usr/local/lib/nltk_data']
import nltk
nltk.download('vader_lexicon')
[nltk_data] Downloading package vader_lexicon to
[nltk_data] /Users/ayodejioyesanya/nltk_data...
True
# Load the scraped data into a pandas DataFrame
df = pd.read_csv("/Users/ayodejioyesanya/Desktop/cleaned_BA_reviews_20231121_123616.csv")
# Perform sentiment analysis
analyzer = SentimentIntensityAnalyzer()
df['sentiment_score'] = df['reviews'].apply(lambda x: analyzer.polarity_scores(x)['compound'])
# Display sentiment distribution
df['sentiment_score'].hist(bins=20)
plt.title('Sentiment Distribution')
plt.xlabel('Sentiment Score')
plt.ylabel('Frequency')
plt.show()
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# Concatenate all reviews into a single string
all_reviews = ' '.join(df['reviews'].astype(str))
# Generate word cloud
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(all_reviews)
# Display the word cloud
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Word Cloud of Reviews')
plt.show()
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
# Example: Perform topic modeling using LDA
vectorizer = TfidfVectorizer(max_features=5000, stop_words='english')
tfidf_matrix = vectorizer.fit_transform(df['reviews'])
lda = LatentDirichletAllocation(n_components=5, random_state=42)
lda.fit(tfidf_matrix)
# Display top words in each topic
feature_names = vectorizer.get_feature_names_out()
for i, topic in enumerate(lda.components_):
top_words_idx = topic.argsort()[-5:][::-1]
top_words = [feature_names[idx] for idx in top_words_idx]
print(f"Topic {i}: {', '.join(top_words)}")
Topic 0: fco, valencia, alaska, wir, yo
Topic 1: calgary, notified, redeem, test, lucia
Topic 2: flight, ba, service, london, good
Topic 3: berlin, zurich, bangalore, delightful, unexpected
Topic 4: cityflyer, norwegian, test, zrh, santorini
pip install gensim
Requirement already satisfied: gensim in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (4.3.2)
Requirement already satisfied: smart-open>=1.8.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from gensim) (6.4.0)
Requirement already satisfied: numpy>=1.18.5 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from gensim) (1.26.0)
Requirement already satisfied: scipy>=1.7.0 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from gensim) (1.11.4)
Note: you may need to restart the kernel to use updated packages.
# Tokenize the reviews (i.e. assuming each review is a string)
tokenized_reviews = [review.split() for review in df['reviews']]
# Train Word2Vec model
w2v_model = Word2Vec(sentences=tokenized_reviews, vector_size=100, window=5, min_count=1, workers=4)
# Visualize Word Embeddings using t-SNE
words = list(w2v_model.wv.index_to_key)
vectors = [w2v_model.wv[word] for word in words]
tsne_model = TSNE(n_components=2, random_state=42)
tsne_embeddings = tsne_model.fit_transform(vectors)
tsne_df = pd.DataFrame(tsne_embeddings, columns=['x', 'y'])
tsne_df['word'] = words
# Visualize t-SNE
plt.figure(figsize=(12, 8))
sns.scatterplot(data=tsne_df, x='x', y='y', hue='word', palette='viridis', alpha=0.6)
plt.title('t-SNE Visualization of Word Embeddings')
plt.show()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[11], line 5
2 tokenized_reviews = [review.split() for review in df['reviews']]
4 # Train Word2Vec model
----> 5 w2v_model = Word2Vec(sentences=tokenized_reviews, vector_size=100, window=5, min_count=1, workers=4)
7 # Visualize Word Embeddings using t-SNE
8 words = list(w2v_model.wv.index_to_key)
NameError: name 'Word2Vec' is not defined
from gensim.models import Word2Vec
# Tokenize the reviews (i.e. assuming each review is a string)
tokenized_reviews = [review.split() for review in df['reviews']]
# Train Word2Vec model
w2v_model = Word2Vec(sentences=tokenized_reviews, vector_size=100, window=5, min_count=1, workers=4)
# Visualize Word Embeddings using t-SNE
words = list(w2v_model.wv.index_to_key)
vectors = [w2v_model.wv[word] for word in words]
tsne_model = TSNE(n_components=2, random_state=42)
tsne_embeddings = tsne_model.fit_transform(vectors)
tsne_df = pd.DataFrame(tsne_embeddings, columns=['x', 'y'])
tsne_df['word'] = words
# Visualize t-SNE
plt.figure(figsize=(12, 8))
sns.scatterplot(data=tsne_df, x='x', y='y', hue='word', palette='viridis', alpha=0.6)
plt.title('t-SNE Visualization of Word Embeddings')
plt.show()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[13], line 11
8 words = list(w2v_model.wv.index_to_key)
9 vectors = [w2v_model.wv[word] for word in words]
---> 11 tsne_model = TSNE(n_components=2, random_state=42)
12 tsne_embeddings = tsne_model.fit_transform(vectors)
14 tsne_df = pd.DataFrame(tsne_embeddings, columns=['x', 'y'])
NameError: name 'TSNE' is not defined
pip install -U scikit-learn
Requirement already satisfied: scikit-learn in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (1.3.2)
Requirement already satisfied: joblib>=1.1.1 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from scikit-learn) (1.3.2)
Requirement already satisfied: threadpoolctl>=2.0.0 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from scikit-learn) (3.2.0)
Requirement already satisfied: numpy<2.0,>=1.17.3 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from scikit-learn) (1.26.0)
Requirement already satisfied: scipy>=1.5.0 in /Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages (from scikit-learn) (1.11.4)
Note: you may need to restart the kernel to use updated packages.
import numpy as np
# Convert the list of vectors to a NumPy array
vectors = np.array([w2v_model.wv[word] for word in words])
# Visualize Word Embeddings using t-SNE
words = list(w2v_model.wv.index_to_key)
vectors = np.array([w2v_model.wv[word] for word in words])
tsne_model = TSNE(n_components=2, random_state=42)
tsne_embeddings = tsne_model.fit_transform(vectors)
tsne_df = pd.DataFrame(tsne_embeddings, columns=['x', 'y'])
tsne_df['word'] = words
import numpy as np
# Convert the list of vectors to a NumPy array
vectors = np.array([w2v_model.wv[word] for word in words])
# Visualize Word Embeddings using t-SNE
words = list(w2v_model.wv.index_to_key)
vectors = np.array([w2v_model.wv[word] for word in words])
tsne_model = TSNE(n_components=2, random_state=42)
tsne_embeddings = tsne_model.fit_transform(vectors)
tsne_df = pd.DataFrame(tsne_embeddings, columns=['x', 'y'])
tsne_df['word'] = words
import pandas as pd
from nltk.sentiment import SentimentIntensityAnalyzer
import matplotlib.pyplot as plt
from gensim.models import Word2Vec
from sklearn.manifold import TSNE
import seaborn as sns
import numpy as np
# Tokenize the reviews (assuming each review is a string)
tokenized_reviews = [review.split() for review in df['reviews']]
# Train Word2Vec model
w2v_model = Word2Vec(sentences=tokenized_reviews, vector_size=100, window=5, min_count=1, workers=4)
# Visualize Word Embeddings using t-SNE
words = list(w2v_model.wv.index_to_key)
vectors = np.array([w2v_model.wv[word] for word in words])
tsne_model = TSNE(n_components=2, random_state=42)
tsne_embeddings = tsne_model.fit_transform(vectors)
tsne_df = pd.DataFrame(tsne_embeddings, columns=['x', 'y'])
tsne_df['word'] = words
# Visualize t-SNE
plt.figure(figsize=(12, 8))
sns.scatterplot(data=tsne_df, x='x', y='y', hue='word', palette='viridis', alpha=0.6)
plt.title('t-SNE Visualization of Word Embeddings')
plt.show()
/Users/ayodejioyesanya/anaconda3/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning: Glyph 10062 (\N{NEGATIVE SQUARED CROSS MARK}) missing from current font.
fig.canvas.print_figure(bytes_io, **kw)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
File ~/anaconda3/lib/python3.10/site-packages/IPython/core/formatters.py:340, in BaseFormatter.__call__(self, obj)
338 pass
339 else:
--> 340 return printer(obj)
341 # Finally look for special method names
342 method = get_real_method(obj, self.print_method)
File ~/anaconda3/lib/python3.10/site-packages/IPython/core/pylabtools.py:152, in print_figure(fig, fmt, bbox_inches, base64, **kwargs)
149 from matplotlib.backend_bases import FigureCanvasBase
150 FigureCanvasBase(fig)
--> 152 fig.canvas.print_figure(bytes_io, **kw)
153 data = bytes_io.getvalue()
154 if fmt == 'svg':
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/backend_bases.py:2164, in FigureCanvasBase.print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
2161 # we do this instead of `self.figure.draw_without_rendering`
2162 # so that we can inject the orientation
2163 with getattr(renderer, "_draw_disabled", nullcontext)():
-> 2164 self.figure.draw(renderer)
2165 if bbox_inches:
2166 if bbox_inches == "tight":
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/artist.py:95, in _finalize_rasterization.<locals>.draw_wrapper(artist, renderer, *args, **kwargs)
93 @wraps(draw)
94 def draw_wrapper(artist, renderer, *args, **kwargs):
---> 95 result = draw(artist, renderer, *args, **kwargs)
96 if renderer._rasterizing:
97 renderer.stop_rasterizing()
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/artist.py:72, in allow_rasterization.<locals>.draw_wrapper(artist, renderer)
69 if artist.get_agg_filter() is not None:
70 renderer.start_filter()
---> 72 return draw(artist, renderer)
73 finally:
74 if artist.get_agg_filter() is not None:
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/figure.py:3154, in Figure.draw(self, renderer)
3151 # ValueError can occur when resizing a window.
3153 self.patch.draw(renderer)
-> 3154 mimage._draw_list_compositing_images(
3155 renderer, self, artists, self.suppressComposite)
3157 for sfig in self.subfigs:
3158 sfig.draw(renderer)
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/image.py:132, in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
130 if not_composite or not has_images:
131 for a in artists:
--> 132 a.draw(renderer)
133 else:
134 # Composite any adjacent images together
135 image_group = []
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/artist.py:72, in allow_rasterization.<locals>.draw_wrapper(artist, renderer)
69 if artist.get_agg_filter() is not None:
70 renderer.start_filter()
---> 72 return draw(artist, renderer)
73 finally:
74 if artist.get_agg_filter() is not None:
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/axes/_base.py:3070, in _AxesBase.draw(self, renderer)
3067 if artists_rasterized:
3068 _draw_rasterized(self.figure, artists_rasterized, renderer)
-> 3070 mimage._draw_list_compositing_images(
3071 renderer, self, artists, self.figure.suppressComposite)
3073 renderer.close_group('axes')
3074 self.stale = False
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/image.py:132, in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
130 if not_composite or not has_images:
131 for a in artists:
--> 132 a.draw(renderer)
133 else:
134 # Composite any adjacent images together
135 image_group = []
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/artist.py:72, in allow_rasterization.<locals>.draw_wrapper(artist, renderer)
69 if artist.get_agg_filter() is not None:
70 renderer.start_filter()
---> 72 return draw(artist, renderer)
73 finally:
74 if artist.get_agg_filter() is not None:
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/legend.py:769, in Legend.draw(self, renderer)
765 self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
767 # update the location and size of the legend. This needs to
768 # be done in any case to clip the figure right.
--> 769 bbox = self._legend_box.get_window_extent(renderer)
770 self.legendPatch.set_bounds(bbox.bounds)
771 self.legendPatch.set_mutation_scale(fontsize)
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/offsetbox.py:399, in OffsetBox.get_window_extent(self, renderer)
397 if renderer is None:
398 renderer = self.figure._get_renderer()
--> 399 bbox = self.get_bbox(renderer)
400 try: # Some subclasses redefine get_offset to take no args.
401 px, py = self.get_offset(bbox, renderer)
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/offsetbox.py:366, in OffsetBox.get_bbox(self, renderer)
364 def get_bbox(self, renderer):
365 """Return the bbox of the offsetbox, ignoring parent offsets."""
--> 366 bbox, offsets = self._get_bbox_and_child_offsets(renderer)
367 return bbox
File ~/anaconda3/lib/python3.10/site-packages/matplotlib/offsetbox.py:484, in VPacker._get_bbox_and_child_offsets(self, renderer)
481 if isinstance(c, PackerBase) and c.mode == "expand":