-
Notifications
You must be signed in to change notification settings - Fork 1
/
WordEmbeddingsModels.vb
2298 lines (1885 loc) · 107 KB
/
WordEmbeddingsModels.vb
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
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Numerics
Imports System.Windows.Forms
Imports Embeddings.Factory
Imports Embeddings.Models.Text
Imports MathNet.Numerics.IntegralTransforms
Namespace Factory
Public MustInherit Class WordEmbeddingsModel
' A simple vocabulary for demonstration purposes.
Private iVocabulary As New List(Of String) From {"apple", "orange", "banana", "grape", "cherry"}
Public Property Vocabulary As List(Of String)
Get
Return iVocabulary
End Get
Set(value As List(Of String))
iVocabulary = value
End Set
End Property
' Word embeddings dictionary to store the learned word vectors.
Public WordEmbeddings As New WordEmbedding
' Hyperparameters for training.
Public EmbeddingSize As Integer = 50 ' Size of word vectors.
Public WindowSize As Integer = 2 ' Context window size.
Public LearningRate As Double = 0.01 ' Learning rate for gradient descent.
Public NumEpochs As Integer = 1000 ' Number of training epochs.
' Random number generator for initialization.
Public Shared ReadOnly Rand As New Random()
Public MustOverride Sub Train()
Public MustOverride Sub Train(corpus As List(Of List(Of String)))
Public Sub New(ByRef model As WordEmbeddingsModel)
iVocabulary = model.Vocabulary
WordEmbeddings = model.WordEmbeddings
EmbeddingSize = model.EmbeddingSize
WindowSize = model.WindowSize
LearningRate = model.LearningRate
NumEpochs = model.NumEpochs
End Sub
Public Sub New(ByRef Vocabulary As List(Of String))
iVocabulary = Vocabulary
End Sub
Public Function ExportModel() As WordEmbeddingsModel
Return Me
End Function
Public Sub SetTrainingParameters(ByRef Embeddingsize As Integer,
ByRef WindowSize As Integer,
ByRef LearningRate As Double, ByRef Epochs As Integer)
Me.EmbeddingSize = Embeddingsize
Me.WindowSize = WindowSize
Me.LearningRate = LearningRate
Me.NumEpochs = Epochs
End Sub
' WordEmbedding class to store word vectors and handle operations on word embeddings.
Public Class WordEmbedding
Public embeddings As Dictionary(Of String, Double())
Public Sub New()
Me.embeddings = New Dictionary(Of String, Double())()
End Sub
Public Sub Add(word As String, vector As Double())
embeddings(word) = vector
End Sub
Public Function GetVector(word As String) As Double()
Return embeddings(word)
End Function
' Implement other operations as needed for word embeddings.
' E.g., similarity, word lookup, etc.
End Class
Public Function ComputeDotProduct(vec1 As Double(), vec2 As Double()) As Double
Return Enumerable.Range(0, EmbeddingSize).Sum(Function(i) vec1(i) * vec2(i))
End Function
Public Function Sigmoid(x As Double) As Double
Return 1.0 / (1.0 + Math.Exp(-x))
End Function
''' <summary>
''' Cosine Similarity(A, B) = (A dot B) / (||A|| * ||B||)
''' where:
''' A And B are the word vectors of two words.
''' A dot B Is the dot product Of the two vectors.
''' ||A|| And ||B|| are the magnitudes (Euclidean norms) of the vectors.
''' The cosine similarity ranges from -1 To 1, where 1 indicates the highest similarity, 0 indicates no similarity, And -1 indicates the highest dissimilarity.
''' </summary>
''' <param name="word1"></param>
''' <param name="word2"></param>
''' <param name="wordEmbeddings"></param>
''' <returns></returns>
Public Function CosineSimilarity(word1 As String, word2 As String, wordEmbeddings As WordEmbedding) As Double
Dim vector1 As Double() = wordEmbeddings.GetVector(word1)
Dim vector2 As Double() = wordEmbeddings.GetVector(word2)
' Calculate the dot product of the two vectors.
Dim dotProduct As Double = 0
For i As Integer = 0 To vector1.Length - 1
dotProduct += vector1(i) * vector2(i)
Next
' Calculate the magnitudes of the vectors.
Dim magnitude1 As Double = Math.Sqrt(vector1.Sum(Function(x) x * x))
Dim magnitude2 As Double = Math.Sqrt(vector2.Sum(Function(x) x * x))
' Calculate the cosine similarity.
Dim similarity As Double = dotProduct / (magnitude1 * magnitude2)
Return similarity
End Function
Public Function DisplayMatrix(matrix As Dictionary(Of String, Dictionary(Of String, Double))) As DataGridView
Dim dataGridView As New DataGridView()
dataGridView.Dock = DockStyle.Fill
dataGridView.AutoGenerateColumns = False
dataGridView.AllowUserToAddRows = False
' Add columns to the DataGridView
Dim wordColumn As New DataGridViewTextBoxColumn()
wordColumn.HeaderText = "Word"
wordColumn.DataPropertyName = "Word"
dataGridView.Columns.Add(wordColumn)
For Each contextWord As String In matrix.Keys
Dim contextColumn As New DataGridViewTextBoxColumn()
contextColumn.HeaderText = contextWord
contextColumn.DataPropertyName = contextWord
dataGridView.Columns.Add(contextColumn)
Next
' Populate the DataGridView with the matrix data
For Each word As String In matrix.Keys
Dim rowValues As New List(Of Object)
rowValues.Add(word)
For Each contextWord As String In matrix.Keys
Dim count As Object = If(matrix(word).ContainsKey(contextWord), matrix(word)(contextWord), 0)
rowValues.Add(count)
Next
dataGridView.Rows.Add(rowValues.ToArray())
Next
Return dataGridView
End Function
Public Sub DisplayEmbeddingsModel()
Dim dgv = DisplayMatrix(WordEmbeddings.embeddings)
' Create a form and add the DataGridView to it
Dim kform As New Form
kform.Text = "Embedding Matrix"
kform.Size = New Size(800, 600)
kform.Controls.Add(dgv)
' Display the form
Application.Run(kform)
End Sub
Public Function DisplayMatrix(matrix As Dictionary(Of String, Double())) As DataGridView
Dim dataGridView As New DataGridView()
dataGridView.Dock = DockStyle.Fill
dataGridView.AutoGenerateColumns = False
dataGridView.AllowUserToAddRows = False
' Add columns to the DataGridView
Dim wordColumn As New DataGridViewTextBoxColumn()
wordColumn.HeaderText = "Word"
wordColumn.DataPropertyName = "Word"
dataGridView.Columns.Add(wordColumn)
For Each contextWord As String In matrix.Keys
Dim contextColumn As New DataGridViewTextBoxColumn()
contextColumn.HeaderText = contextWord
contextColumn.DataPropertyName = contextWord
dataGridView.Columns.Add(contextColumn)
Next
' Populate the DataGridView with the matrix data
For Each word As String In matrix.Keys
Dim rowValues As New List(Of Object)()
rowValues.Add(word)
For Each contextWord As String In matrix.Keys
Dim count As Integer = If(matrix.ContainsKey(contextWord), matrix(word)(contextWord), 0)
rowValues.Add(count)
Next
dataGridView.Rows.Add(rowValues.ToArray())
Next
Return dataGridView
End Function
Public Class WordListReader
Private wordList As List(Of String)
Public Sub New(filePath As String)
wordList = New List(Of String)()
ReadWordList(filePath)
End Sub
Private Sub ReadWordList(filePath As String)
Using reader As New StreamReader(filePath)
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If Not String.IsNullOrEmpty(line) Then
wordList.Add(line.Trim.ToLower)
End If
End While
End Using
End Sub
Public Function GetWords() As List(Of String)
Return wordList
End Function
' Usage Example:
Public Shared Sub Main()
' Assuming you have a wordlist file named 'words.txt' in the same directory
Dim corpusRoot As String = "."
Dim wordlistPath As String = Path.Combine(corpusRoot, "wordlist.txt")
Dim wordlistReader As New WordListReader(wordlistPath)
Dim words As List(Of String) = wordlistReader.GetWords()
For Each word As String In words
Console.WriteLine(word)
Next
Console.ReadLine()
' Rest of your code...
End Sub
End Class
Public Class PMI
Public cooccurrenceMatrix As Dictionary(Of String, Dictionary(Of String, Double))
Public vocabulary As Dictionary(Of String, Integer)
Private wordToIndex As Dictionary(Of String, Integer)
Private indexToWord As Dictionary(Of Integer, String)
Private embeddingSize As Integer = embeddingMatrix.Length
Private embeddingMatrix As Double(,)
Public Sub New(vocabulary As Dictionary(Of String, Integer))
If vocabulary Is Nothing Then
Throw New ArgumentNullException(NameOf(vocabulary))
End If
Me.vocabulary = vocabulary
End Sub
''' <summary>
''' Discovers collocations among the specified words based on the trained model.
''' </summary>
''' <param name="words">The words to discover collocations for.</param>
''' <param name="threshold">The similarity threshold for collocation discovery.</param>
''' <returns>A list of collocations (word pairs) that meet the threshold.</returns>
Public Function DiscoverCollocations(words As String(), threshold As Double) As List(Of Tuple(Of String, String))
Dim collocations As New List(Of Tuple(Of String, String))
For i As Integer = 0 To words.Length - 2
For j As Integer = i + 1 To words.Length - 1
Dim word1 As String = words(i)
Dim word2 As String = words(j)
If vocabulary.Keys.Contains(word1) AndAlso vocabulary.Keys.Contains(word2) Then
Dim vector1 As Double() = GetEmbedding(wordToIndex(word1))
Dim vector2 As Double() = GetEmbedding(wordToIndex(word2))
Dim similarity As Double = CalculateSimilarity(vector1, vector2)
If similarity >= threshold Then
collocations.Add(Tuple.Create(word1, word2))
End If
End If
Next
Next
Return collocations
End Function
Private Function CalculateSimilarity(vectorA As Double(), vectorB As Double()) As Double
Dim dotProduct As Double = 0
Dim magnitudeA As Double = 0
Dim magnitudeB As Double = 0
For i As Integer = 0 To vectorA.Length - 1
dotProduct += vectorA(i) * vectorB(i)
magnitudeA += vectorA(i) * vectorA(i)
magnitudeB += vectorB(i) * vectorB(i)
Next
If magnitudeA <> 0 AndAlso magnitudeB <> 0 Then
Return dotProduct / (Math.Sqrt(magnitudeA) * Math.Sqrt(magnitudeB))
Else
Return 0
End If
End Function
Private Sub InitializeEmbeddings()
Dim vocabSize As Integer = vocabulary.Count
embeddingMatrix = New Double(vocabSize - 1, embeddingSize - 1) {}
Dim random As New Random()
For i As Integer = 0 To vocabSize - 1
For j As Integer = 0 To embeddingSize - 1
embeddingMatrix(i, j) = random.NextDouble()
Next
Next
End Sub
Private Function GetEmbedding(index As Integer) As Double()
If indexToWord.ContainsKey(index) Then
Dim vector(embeddingSize - 1) As Double
For i As Integer = 0 To embeddingSize - 1
vector(i) = embeddingMatrix(index, i)
Next
Return vector
Else
Return Nothing
End If
End Function
''' <summary>
''' Calculates the Pointwise Mutual Information (PMI) matrix for the trained model.
''' </summary>
''' <returns>A dictionary representing the PMI matrix.</returns>
Public Function CalculatePMI() As Dictionary(Of String, Dictionary(Of String, Double))
Dim pmiMatrix As New Dictionary(Of String, Dictionary(Of String, Double))
Dim totalCooccurrences As Double = GetTotalCooccurrences()
For Each targetWord In cooccurrenceMatrix.Keys
Dim targetOccurrences As Double = GetTotalOccurrences(targetWord)
If Not pmiMatrix.ContainsKey(targetWord) Then
pmiMatrix(targetWord) = New Dictionary(Of String, Double)
End If
For Each contextWord In cooccurrenceMatrix(targetWord).Keys
Dim contextOccurrences As Double = GetTotalOccurrences(contextWord)
Dim cooccurrences As Double = cooccurrenceMatrix(targetWord)(contextWord)
Dim pmiValue As Double = Math.Log((cooccurrences * totalCooccurrences) / (targetOccurrences * contextOccurrences))
pmiMatrix(targetWord)(contextWord) = pmiValue
Next
Next
Return pmiMatrix
End Function
Private Function GetTotalCooccurrences() As Double
Dim total As Double = 0
For Each targetWord In cooccurrenceMatrix.Keys
For Each cooccurrenceValue In cooccurrenceMatrix(targetWord).Values
total += cooccurrenceValue
Next
Next
Return total
End Function
Private Function GetTotalOccurrences(word As String) As Double
Dim total As Double = 0
If cooccurrenceMatrix.ContainsKey(word) Then
total = cooccurrenceMatrix(word).Values.Sum()
End If
Return total
End Function
Private Function GenerateCooccurrenceMatrix(corpus As String(), windowSize As Integer) As Dictionary(Of String, Dictionary(Of String, Double))
Dim matrix As New Dictionary(Of String, Dictionary(Of String, Double))
For Each sentence In corpus
Dim words As String() = sentence.Split(" "c)
Dim length As Integer = words.Length
For i As Integer = 0 To length - 1
Dim targetWord As String = words(i)
If Not matrix.ContainsKey(targetWord) Then
matrix(targetWord) = New Dictionary(Of String, Double)
End If
For j As Integer = Math.Max(0, i - windowSize) To Math.Min(length - 1, i + windowSize)
If i = j Then
Continue For
End If
Dim contextWord As String = words(j)
Dim distance As Double = 1 / Math.Abs(i - j)
If matrix(targetWord).ContainsKey(contextWord) Then
matrix(targetWord)(contextWord) += distance
Else
matrix(targetWord)(contextWord) = distance
End If
Next
Next
Next
Return matrix
End Function
Public Function DisplayMatrix(matrix As Dictionary(Of String, Dictionary(Of String, Integer))) As DataGridView
Dim dataGridView As New DataGridView()
dataGridView.Dock = DockStyle.Fill
dataGridView.AutoGenerateColumns = False
dataGridView.AllowUserToAddRows = False
' Add columns to the DataGridView
Dim wordColumn As New DataGridViewTextBoxColumn()
wordColumn.HeaderText = "Word"
wordColumn.DataPropertyName = "Word"
dataGridView.Columns.Add(wordColumn)
For Each contextWord As String In matrix.Keys
Dim contextColumn As New DataGridViewTextBoxColumn()
contextColumn.HeaderText = contextWord
contextColumn.DataPropertyName = contextWord
dataGridView.Columns.Add(contextColumn)
Next
' Populate the DataGridView with the matrix data
For Each word As String In matrix.Keys
Dim rowValues As New List(Of Integer)
rowValues.Add(word)
For Each contextWord As String In matrix.Keys
Dim count As Object = If(matrix(word).ContainsKey(contextWord), matrix(word)(contextWord), 0)
rowValues.Add(count)
Next
dataGridView.Rows.Add(rowValues.ToArray())
Next
Return dataGridView
End Function
End Class
End Class
''' <summary>
''' One possible way to combine the approaches is by using a two-step training process:
''' Pre-training Using Skip-gram With Negative Sampling:
''' In this step,
''' you can pre-train the word embeddings using the skip-gram model
''' with negative sampling on a large dataset Or a diverse corpus.
''' This step allows you to efficiently learn word embeddings
''' in a computationally efficient
''' manner while capturing semantic relationships between words.
''' Fine-tuning using Hierarchical Softmax:
''' After pre-training the word embeddings,
''' you can perform fine-tuning Using the hierarchical softmax technique.
''' During the fine-tuning Step,
''' you can use a smaller dataset
''' Or a more domain-specific corpus
''' To train the model Using hierarchical softmax.
''' This Step enables you To refine the word embeddings
''' And make them more accurate And context-specific.
''' </summary>
Public Class HybridWordEmbeddingsModel
Inherits WordEmbeddingsModel
Public Sub New(ByRef model As WordEmbeddingsModel)
MyBase.New(model)
End Sub
Public Sub New(ByRef Vocabulary As List(Of String))
MyBase.New(Vocabulary)
End Sub
Public Enum ModelType
Skipgram
Glove
SoftMax
CBOW
FastText
End Enum
Public Function PreTrain(ByRef model As WordEmbeddingsModel, ByRef iModelType As ModelType) As WordEmbeddingsModel
model.Train()
Dim preTrainedModel As WordEmbeddingsModel
Select Case iModelType
Case ModelType.Skipgram
preTrainedModel = New WordEmbeddingsWithNegativeSampling(model.Vocabulary)
preTrainedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for pre-training
preTrainedModel.Train() ' Pre-train the word embeddings using Skip-gram with Negative Sampling
Return preTrainedModel
Case ModelType.Glove
preTrainedModel = New WordEmbeddingsWithGloVe(model.Vocabulary)
preTrainedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for pre-training
preTrainedModel.Train() ' Pre-train the word embeddings using Skip-gram with Negative Sampling
Return preTrainedModel
Case ModelType.FastText
preTrainedModel = New WordEmbeddingsWithFastText(model.Vocabulary)
preTrainedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for pre-training
preTrainedModel.Train() ' Pre-train the word embeddings using Skip-gram with Negative Sampling
Return preTrainedModel
Case ModelType.CBOW
preTrainedModel = New WordEmbeddingsWithCBOW(model.Vocabulary)
preTrainedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for pre-training
preTrainedModel.Train() ' Pre-train the word embeddings using Skip-gram with Negative Sampling
Return preTrainedModel
Case ModelType.SoftMax
preTrainedModel = New WordEmbeddingsWithHierarchicalSoftmax(model.Vocabulary)
preTrainedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for pre-training
preTrainedModel.Train() ' Pre-train the word embeddings using Skip-gram with Negative Sampling
Return preTrainedModel
End Select
Return model
End Function
Public Function FineTune(ByRef Model As WordEmbeddingsModel, ByRef iModelType As ModelType) As WordEmbeddingsModel
Dim fineTunedModel As WordEmbeddingsModel
Model.Train()
Select Case iModelType
Case ModelType.CBOW
fineTunedModel = New WordEmbeddingsWithCBOW(Model.Vocabulary)
fineTunedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for fine-tuning
fineTunedModel.Train() ' Fine-tune the word embeddings using Hierarchical Softmax
Return fineTunedModel
Case ModelType.FastText
fineTunedModel = New WordEmbeddingsWithFastText(Model.Vocabulary)
fineTunedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for fine-tuning
fineTunedModel.Train() ' Fine-tune the word embeddings using Hierarchical Softmax
Return fineTunedModel
Case ModelType.Glove
fineTunedModel = New WordEmbeddingsWithGloVe(Model.Vocabulary)
fineTunedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for fine-tuning
fineTunedModel.Train() ' Fine-tune the word embeddings using Hierarchical Softmax
Return fineTunedModel
Case ModelType.Skipgram
fineTunedModel = New WordEmbeddingsWithNegativeSampling(Model.Vocabulary)
fineTunedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for fine-tuning
fineTunedModel.Train() ' Fine-tune the word embeddings using Hierarchical Softmax
Return fineTunedModel
Case ModelType.SoftMax
fineTunedModel = New WordEmbeddingsWithHierarchicalSoftmax(Model.Vocabulary)
fineTunedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for fine-tuning
fineTunedModel.Train() ' Fine-tune the word embeddings using Hierarchical Softmax
Return fineTunedModel
End Select
Return Model
End Function
Public Overloads Sub Train(Optional PretrainModel As ModelType = ModelType.Skipgram, Optional FineTuneModel As ModelType = ModelType.Glove)
Dim hybrid As New HybridWordEmbeddingsModel(Vocabulary)
Dim preTrainedModel = PreTrain(hybrid, PretrainModel)
Dim fineTunedModel = FineTune(preTrainedModel, FineTuneModel)
'set model
Me.WordEmbeddings = fineTunedModel.WordEmbeddings
End Sub
Public Overrides Sub Train(corpus As List(Of List(Of String)))
' Step 1: Pre-training using Skip-gram with Negative Sampling.
Console.WriteLine("Pre-training using Skip-gram with Negative Sampling...")
Dim preTrainedModel As New WordEmbeddingsWithNegativeSampling(Vocabulary)
preTrainedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for pre-training
preTrainedModel.Train(corpus) ' Pre-train the word embeddings using Skip-gram with Negative Sampling
' Step 3: Fine-tuning using Hierarchical Softmax.
Console.WriteLine("Fine-tuning using Hierarchical Softmax...")
Dim fineTunedModel As New WordEmbeddingsWithHierarchicalSoftmax(Vocabulary)
fineTunedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for fine-tuning
fineTunedModel.Train(corpus) ' Fine-tune the word embeddings using Hierarchical Softmax
' Step 4: Set the fine-tuned word embeddings as the model's word embeddings.
WordEmbeddings = fineTunedModel.WordEmbeddings
Console.WriteLine("Training completed!")
End Sub
Public Overrides Sub Train()
' Step 1: Pre-training using Skip-gram with Negative Sampling.
Console.WriteLine("Pre-training using Skip-gram with Negative Sampling...")
Dim preTrainedModel As New WordEmbeddingsWithNegativeSampling(Vocabulary)
preTrainedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for pre-training
preTrainedModel.train() ' Pre-train the word embeddings using Skip-gram with Negative Sampling
' Step 3: Fine-tuning using Hierarchical Softmax.
Console.WriteLine("Fine-tuning using Hierarchical Softmax...")
Dim fineTunedModel As New WordEmbeddingsWithHierarchicalSoftmax(Vocabulary)
fineTunedModel.SetTrainingParameters(EmbeddingSize, WindowSize, LearningRate, NumEpochs) ' Set appropriate parameters for fine-tuning
fineTunedModel.Train() ' Fine-tune the word embeddings using Hierarchical Softmax
' Step 4: Set the fine-tuned word embeddings as the model's word embeddings.
WordEmbeddings = fineTunedModel.WordEmbeddings
Console.WriteLine("Training completed!")
End Sub
End Class
End Namespace
Namespace Models
Namespace Text
''' <summary>
'''Skip-gram with Negative Sampling:
''' Pros:
''' More computationally efficient: Negative sampling reduces the computational cost by Using a small number Of negative samples For Each positive context pair during training.
''' Simpler to implement: It's relatively easier to implement skip-gram with negative sampling compared to hierarchical softmax.
''' Performs well With large vocabularies: Negative sampling Is well-suited For training word embeddings With large vocabularies As it scales well.
''' Cons:
''' May sacrifice quality: With negative sampling, some negative samples may Not be truly informative, potentially leading To a slight degradation In the quality Of learned word embeddings compared To hierarchical softmax.
''' Tuning hyperparameters: The effectiveness Of negative sampling depends On the selection Of the number Of negative samples And learning rate, which may require tuning.
''' </summary>
Public Class WordEmbeddingsWithNegativeSampling
Inherits WordEmbeddingsModel
Public NumNegativeSamples As Integer = 5 ' Number of negative samples per positive sample.
Public Sub New(ByRef Vocabulary As List(Of String), Optional NumberOfNegativeSamples As Integer = 5)
MyBase.New(Vocabulary)
Me.NumNegativeSamples = NumberOfNegativeSamples
End Sub
Public Sub New(ByRef model As WordEmbeddingsModel)
MyBase.New(model)
End Sub
Public Overrides Sub train()
' Initialize word embeddings randomly.
For Each word In Vocabulary
WordEmbeddings.Add(word, Enumerable.Range(0, EmbeddingSize).Select(Function(_i) Rand.NextDouble() - 0.5).ToArray())
Next
' Simulate training data (context pairs).
Dim trainingData As New List(Of (String, String))()
For i As Integer = 0 To Vocabulary.Count - 1
For j As Integer = Math.Max(0, i - WindowSize) To Math.Min(Vocabulary.Count - 1, i + WindowSize)
If i <> j Then
trainingData.Add((Vocabulary(i), Vocabulary(j)))
End If
Next
Next
' Training loop.
For epoch As Integer = 1 To NumEpochs
Console.WriteLine($"Training Epoch {epoch}/{NumEpochs}")
' Shuffle the training data to avoid learning order biases.
trainingData = trainingData.OrderBy(Function(_item) Rand.Next()).ToList()
' Gradient descent for each context pair.
For Each item In trainingData
' Generate negative samples.
Dim negativeSamples As New List(Of String)()
While negativeSamples.Count < NumNegativeSamples
Dim randomWord = Vocabulary(Rand.Next(Vocabulary.Count))
If randomWord <> item.Item1 AndAlso randomWord <> item.Item2 AndAlso Not negativeSamples.Contains(randomWord) Then
negativeSamples.Add(randomWord)
End If
End While
' Compute the gradients and update the word embeddings.
Update(item.Item1, item.Item2, negativeSamples)
Next
Next
' Print the learned word embeddings.
For Each word In Vocabulary
Console.WriteLine($"{word}: {String.Join(", ", WordEmbeddings.GetVector(word))}")
Next
' Now you have learned word embeddings for the given vocabulary.
End Sub
Public Overrides Sub Train(corpus As List(Of List(Of String)))
' Initialize word embeddings randomly.
For Each word In Vocabulary
Dim vector As Double() = Enumerable.Range(0, EmbeddingSize).Select(Function(i) Rand.NextDouble()).ToArray()
WordEmbeddings.Add(word, vector)
Next
' Training loop.
For epoch As Integer = 1 To NumEpochs
For Each document In corpus
For wordIndex As Integer = 0 To document.Count - 1
Dim targetWord As String = document(wordIndex)
Dim contextStart As Integer = Math.Max(0, wordIndex - WindowSize)
Dim contextEnd As Integer = Math.Min(document.Count - 1, wordIndex + WindowSize)
' Skip-gram with negative sampling.
For contextIndex As Integer = contextStart To contextEnd
If contextIndex = wordIndex Then Continue For ' Skip the target word itself.
Dim contextWord As String = document(contextIndex)
Dim loss As Double = 0
' Positive pair (target word, context word).
Dim targetVector As Double() = WordEmbeddings.GetVector(targetWord)
Dim contextVector As Double() = WordEmbeddings.GetVector(contextWord)
Dim dotProduct As Double = ComputeDotProduct(targetVector, contextVector)
Dim sigmoidDotProduct As Double = Sigmoid(dotProduct)
loss += -Math.Log(sigmoidDotProduct)
' Negative sampling (sample k negative words).
Dim numNegativeSamples As Integer = 5
For i As Integer = 1 To numNegativeSamples
Dim negativeWord As String = Vocabulary(Rand.Next(Vocabulary.Count))
If negativeWord = targetWord OrElse negativeWord = contextWord Then Continue For ' Skip positive pairs.
Dim negativeVector As Double() = WordEmbeddings.GetVector(negativeWord)
Dim negDotProduct As Double = ComputeDotProduct(targetVector, negativeVector)
Dim sigmoidNegDotProduct As Double = Sigmoid(negDotProduct)
loss += -Math.Log(1 - sigmoidNegDotProduct)
Next
' Update word vectors using gradient descent.
Dim learningRateFactor As Double = LearningRate * (1 - (epoch / NumEpochs)) ' Reduce learning rate over epochs.
Dim gradient As Double = sigmoidDotProduct - 1 ' Gradient for positive pair.
For i As Integer = 0 To EmbeddingSize - 1
targetVector(i) -= learningRateFactor * gradient * contextVector(i)
contextVector(i) -= learningRateFactor * gradient * targetVector(i)
Next
' Update word vectors for negative samples.
For i As Integer = 1 To numNegativeSamples
Dim negativeWord As String = Vocabulary(Rand.Next(Vocabulary.Count))
If negativeWord = targetWord OrElse negativeWord = contextWord Then Continue For ' Skip positive pairs.
Dim negativeVector As Double() = WordEmbeddings.GetVector(negativeWord)
Dim negDotProduct As Double = ComputeDotProduct(targetVector, negativeVector)
Dim sigmoidNegDotProduct As Double = Sigmoid(negDotProduct)
Dim negGradient As Double = sigmoidNegDotProduct ' Gradient for negative pair.
For j As Integer = 0 To EmbeddingSize - 1
targetVector(j) -= learningRateFactor * negGradient * negativeVector(j)
negativeVector(j) -= learningRateFactor * negGradient * targetVector(j)
Next
Next
' Update the embeddings for target and context words.
WordEmbeddings.Add(targetWord, targetVector)
WordEmbeddings.Add(contextWord, contextVector)
Next
Next
Next
Next
End Sub
Private Sub Update(targetWord As String, contextWord As String, negativeSamples As List(Of String))
Dim targetEmbedding = WordEmbeddings.GetVector(targetWord)
Dim contextEmbedding = WordEmbeddings.GetVector(contextWord)
Dim targetLoss As Double = 0
Dim contextLoss As Double = 0
' Compute the loss for the positive context pair.
Dim positiveScore As Double = ComputeDotProduct(targetEmbedding, contextEmbedding)
Dim positiveSigmoid As Double = Sigmoid(positiveScore)
targetLoss += -Math.Log(positiveSigmoid)
contextLoss += -Math.Log(positiveSigmoid)
' Compute the loss for the negative samples.
For Each negativeWord In negativeSamples
Dim negativeEmbedding = WordEmbeddings.GetVector(negativeWord)
Dim negativeScore As Double = ComputeDotProduct(targetEmbedding, negativeEmbedding)
Dim negativeSigmoid As Double = Sigmoid(negativeScore)
targetLoss += -Math.Log(1 - negativeSigmoid)
Next
' Compute the gradients and update the word embeddings.
Dim targetGradient = contextEmbedding.Clone()
Dim contextGradient = targetEmbedding.Clone()
targetGradient = targetGradient.Select(Function(g) g * (positiveSigmoid - 1)).ToArray()
contextGradient = contextGradient.Select(Function(g) g * (positiveSigmoid - 1)).ToArray()
For Each negativeWord In negativeSamples
Dim negativeEmbedding = WordEmbeddings.GetVector(negativeWord)
Dim negativeSigmoid As Double = Sigmoid(ComputeDotProduct(targetEmbedding, negativeEmbedding))
For i As Integer = 0 To EmbeddingSize - 1
targetGradient(i) += negativeSigmoid * negativeEmbedding(i)
negativeEmbedding(i) += negativeSigmoid * targetEmbedding(i)
Next
Next
' Update the word embeddings using the computed gradients.
For i As Integer = 0 To EmbeddingSize - 1
targetEmbedding(i) -= LearningRate * targetGradient(i)
contextEmbedding(i) -= LearningRate * contextGradient(i)
Next
End Sub
End Class
''' <summary>
'''Hierarchical Softmax
''' Pros:
''' Theoretically more accurate: Hierarchical softmax provides more accurate training by transforming the softmax operation into a binary tree-based probability calculation, ensuring that Each word Is considered during training.
''' Better performance With smaller datasets: Hierarchical softmax Is more suitable For smaller datasets, where negative sampling might Not perform As well due To a limited number Of contexts.
''' Cons:
''' Computationally expensive For large vocabularies: Hierarchical softmax can become computationally expensive With larger vocabularies, As it requires traversing a binary tree To compute probabilities For Each word during training.
''' More complex To implement: Implementing hierarchical softmax can be more complex compared To negative sampling.
''' </summary>
Public Class WordEmbeddingsWithHierarchicalSoftmax
Inherits WordEmbeddingsModel
Public Sub New(ByRef model As WordEmbeddingsModel)
MyBase.New(model)
End Sub
Public Sub New(ByRef Vocabulary As List(Of String))
MyBase.New(Vocabulary)
End Sub
Public Overrides Sub Train()
' Initialize word embeddings randomly.
For Each word In Vocabulary
WordEmbeddings.Add(word, Enumerable.Range(0, EmbeddingSize).Select(Function(_i) Rand.NextDouble() - 0.5).ToArray())
Next
' Simulate training data (context pairs).
Dim trainingData As New List(Of (String, String))()
For i As Integer = 0 To Vocabulary.Count - 1
For j As Integer = Math.Max(0, i - WindowSize) To Math.Min(Vocabulary.Count - 1, i + WindowSize)
If i <> j Then
trainingData.Add((Vocabulary(i), Vocabulary(j)))
End If
Next
Next
' Training loop.
For epoch As Integer = 1 To NumEpochs
Console.WriteLine($"Training Epoch {epoch}/{NumEpochs}")
' Shuffle the training data to avoid learning order biases.
trainingData = trainingData.OrderBy(Function(_item) Rand.Next()).ToList()
' Gradient descent for each context pair.
For Each item In trainingData
' Compute the gradients and update the word embeddings.
Update(item.Item1, item.Item2)
Next
Next
' Print the learned word embeddings.
For Each word In Vocabulary
Console.WriteLine($"{word}: {String.Join(", ", WordEmbeddings.GetVector(word))}")
Next
' Now you have learned word embeddings for the given vocabulary.
End Sub
Public Overrides Sub Train(corpus As List(Of List(Of String)))
' Initialize word embeddings randomly.
For Each word In Vocabulary
WordEmbeddings.Add(word, Enumerable.Range(0, EmbeddingSize).Select(Function(_i) Rand.NextDouble() - 0.5).ToArray())
Next
' Build the hierarchical softmax binary tree.
Dim rootNode As New Node(Enumerable.Range(0, EmbeddingSize).Select(Function(_i) Rand.NextDouble() - 0.5).ToArray())
For Each word In Vocabulary
Dim pathToWord As List(Of Node) = GetPathToWord(rootNode, word)
Dim currentNode As Node = rootNode
For Each node In pathToWord
If node Is Nothing Then
Dim newNode As New Node(Enumerable.Range(0, EmbeddingSize).Select(Function(_i) Rand.NextDouble() - 0.5).ToArray())
newNode.Parent = currentNode
If currentNode.Left Is Nothing Then
currentNode.Left = newNode
Else
currentNode.Right = newNode
End If
currentNode = newNode
Else
currentNode = node
End If
Next
currentNode.Word = word
Next
' Training loop.
For epoch As Integer = 1 To NumEpochs
Console.WriteLine($"Training Epoch {epoch}/{NumEpochs}")
' Shuffle the training data to avoid learning order biases.
Dim trainingData As New List(Of (String, String))()
For Each document In corpus
For wordIndex As Integer = 0 To document.Count - 1
Dim targetWord As String = document(wordIndex)
Dim contextStart As Integer = Math.Max(0, wordIndex - WindowSize)
Dim contextEnd As Integer = Math.Min(document.Count - 1, wordIndex + WindowSize)
For contextIndex As Integer = contextStart To contextEnd
If contextIndex = wordIndex Then Continue For ' Skip the target word itself.
trainingData.Add((targetWord, document(contextIndex)))
Next
Next
Next
' Shuffle the training data.
trainingData = trainingData.OrderBy(Function(_item) Rand.Next()).ToList()
' Gradient descent for each context pair.
For Each item In trainingData
' Compute the gradients and update the word embeddings.
Update(item.Item1, item.Item2, rootNode)
Next
Next
' Print the learned word embeddings.
For Each word In Vocabulary
Console.WriteLine($"{word}: {String.Join(", ", WordEmbeddings.GetVector(word))}")
Next
' Now you have learned word embeddings for the given vocabulary.
End Sub
Private Sub Update(targetWord As String, contextWord As String, rootNode As Node)
Dim targetEmbedding = WordEmbeddings.GetVector(targetWord)
Dim contextEmbedding = WordEmbeddings.GetVector(contextWord)
Dim pathToContext = GetPathToWord(rootNode, contextWord)
Dim targetLoss As Double = 0
Dim contextLoss As Double = 0
' Compute the loss for the positive context pair.
Dim positiveScore As Double = 0
For Each node In pathToContext
positiveScore += ComputeDotProduct(targetEmbedding, node.Vector)
Next
Dim positiveSigmoid As Double = Sigmoid(positiveScore)
targetLoss += -Math.Log(positiveSigmoid)
contextLoss += -Math.Log(positiveSigmoid)
' Update the gradients for the target word.
For Each node In pathToContext
Dim sigmoidGradient As Double = (positiveSigmoid - 1.0) * LearningRate
For i As Integer = 0 To EmbeddingSize - 1
node.Vector(i) -= sigmoidGradient * targetEmbedding(i)
targetEmbedding(i) -= sigmoidGradient * node.Vector(i)
Next
' Move to the parent node.
node = node.Parent
Next
' Update the gradients for the context word.
For Each node In pathToContext
Dim sigmoidGradient As Double = (positiveSigmoid - 1.0) * LearningRate
For i As Integer = 0 To EmbeddingSize - 1
node.Vector(i) -= sigmoidGradient * contextEmbedding(i)
contextEmbedding(i) -= sigmoidGradient * node.Vector(i)
Next
Next
End Sub
Private Function GetPathToWord(startNode As Node, word As String) As List(Of Node)
Dim path As New List(Of Node)()
Dim currentNode As Node = startNode
While currentNode IsNot Nothing
path.Add(currentNode)
If currentNode.Word = word Then
Exit While
ElseIf WordEmbeddings.GetVector(word)(0) < 0 Then
currentNode = currentNode.Left
Else
currentNode = currentNode.Right
End If
End While
Return path
End Function
Private Sub Update(targetWord As String, contextWord As String)
Dim targetEmbedding = WordEmbeddings.GetVector(targetWord)
Dim contextEmbedding = WordEmbeddings.GetVector(contextWord)
Dim pathToTarget = GetPathToWord(targetWord)
Dim pathToContext = GetPathToWord(contextWord)
Dim targetLoss As Double = 0
Dim contextLoss As Double = 0
' Compute the loss for the positive context pair.