Skip to content

Commit ffebb85

Browse files
committed
Word2Vec example works, but still has a minor display issue.
1 parent 09a434d commit ffebb85

3 files changed

Lines changed: 109 additions & 11 deletions

File tree

‎src/TensorFlowNET.Core/Sessions/BaseSession.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ private NDArray _run(object fetches, FeedItem[] feed_dict = null)
8080
case int val:
8181
feed_dict_tensor[subfeed_t] = (NDArray)val;
8282
break;
83+
case int[] val:
84+
feed_dict_tensor[subfeed_t] = (NDArray)val;
85+
break;
8386
case string val:
8487
feed_dict_tensor[subfeed_t] = (NDArray)val;
8588
break;

‎test/TensorFlowNET.Examples/ObjectDetection.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,9 @@ private void buildOutputImage(NDArray[] resultArr)
123123
}
124124
}
125125

126-
bitmap.Save(Path.Join(imageDir, "output.jpg"));
126+
string path = Path.Join(imageDir, "output.jpg");
127+
bitmap.Save(path);
128+
Console.WriteLine($"Processed image is saved as {path}");
127129
}
128130

129131
private void drawObjectOnBitmap(Bitmap bmp, Rectangle rect, float score, string name)

‎test/TensorFlowNET.Examples/Text/Word2Vec.cs‎

Lines changed: 103 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System;
1+
using NumSharp;
2+
using System;
23
using System.Collections.Generic;
34
using System.IO;
45
using System.Linq;
@@ -22,13 +23,15 @@ public class Word2Vec : Python, IExample
2223
// Training Parameters
2324
float learning_rate = 0.1f;
2425
int batch_size = 128;
25-
int num_steps = 3000000;
26-
int display_step = 10000;
27-
int eval_step = 200000;
26+
int num_steps = 30000; //3000000;
27+
int display_step = 1000; //10000;
28+
int eval_step = 5000;//200000;
2829

2930
// Evaluation Parameters
3031
string[] eval_words = new string[] { "five", "of", "going", "hardware", "american", "britain" };
3132
string[] text_words;
33+
List<WordId> word2id;
34+
int[] data;
3235

3336
// Word2Vec Parameters
3437
int embedding_size = 200; // Dimension of the embedding vector
@@ -38,7 +41,9 @@ public class Word2Vec : Python, IExample
3841
int num_skips = 2; // How many times to reuse an input to generate a label
3942
int num_sampled = 64; // Number of negative examples to sample
4043

41-
int data_index;
44+
int data_index = 0;
45+
int top_k = 8; // number of nearest neighbors
46+
float average_loss = 0;
4247

4348
public bool Run()
4449
{
@@ -48,21 +53,109 @@ public bool Run()
4853

4954
tf.train.import_meta_graph("graph/word2vec.meta");
5055

56+
// Input data
57+
Tensor X = graph.OperationByName("Placeholder");
58+
// Input label
59+
Tensor Y = graph.OperationByName("Placeholder_1");
60+
61+
// Compute the average NCE loss for the batch
62+
Tensor loss_op = graph.OperationByName("Mean");
63+
// Define the optimizer
64+
var train_op = graph.OperationByName("GradientDescent");
65+
Tensor cosine_sim_op = graph.OperationByName("MatMul_1");
66+
5167
// Initialize the variables (i.e. assign their default value)
5268
var init = tf.global_variables_initializer();
5369

5470
with(tf.Session(graph), sess =>
5571
{
72+
// Run the initializer
5673
sess.run(init);
74+
75+
var x_test = (from word in eval_words
76+
join id in word2id on word equals id.Word into wi
77+
from wi2 in wi.DefaultIfEmpty()
78+
select wi2 == null ? 0 : wi2.Id).ToArray();
79+
80+
foreach (var step in range(1, num_steps + 1))
81+
{
82+
// Get a new batch of data
83+
var (batch_x, batch_y) = next_batch(batch_size, num_skips, skip_window);
84+
85+
var result = sess.run(new ITensorOrOperation[] { train_op, loss_op }, new FeedItem(X, batch_x), new FeedItem(Y, batch_y));
86+
average_loss += result[1];
87+
88+
if (step % display_step == 0 || step == 1)
89+
{
90+
if (step > 1)
91+
average_loss /= display_step;
92+
93+
print($"Step {step}, Average Loss= {average_loss.ToString("F4")}");
94+
average_loss = 0;
95+
}
96+
97+
// Evaluation
98+
if (step % eval_step == 0 || step == 1)
99+
{
100+
print("Evaluation...");
101+
var sim = sess.run(cosine_sim_op, new FeedItem(X, x_test));
102+
foreach(var i in range(len(eval_words)))
103+
{
104+
var nearest = sim[i].argsort<float>()
105+
.Data<float>()
106+
.Take(top_k)
107+
.ToArray();
108+
string log_str = $"\"{eval_words[i]}\" nearest neighbors:";
109+
foreach (var k in range(top_k))
110+
log_str = $"{log_str} {word2id.First(x => x.Id == nearest[k]).Word},";
111+
print(log_str);
112+
}
113+
}
114+
}
57115
});
58116

59-
return false;
117+
return average_loss < 100;
60118
}
61119

62120
// Generate training batch for the skip-gram model
63-
private void next_batch()
121+
private (NDArray, NDArray) next_batch(int batch_size, int num_skips, int skip_window)
64122
{
123+
var batch = np.ndarray((batch_size), dtype: np.int32);
124+
var labels = np.ndarray((batch_size, 1), dtype: np.int32);
125+
// get window size (words left and right + current one)
126+
int span = 2 * skip_window + 1;
127+
var buffer = new Queue<int>(span);
128+
if (data_index + span > data.Length)
129+
data_index = 0;
130+
data.Skip(data_index).Take(span).ToList().ForEach(x => buffer.Enqueue(x));
131+
data_index += span;
132+
133+
foreach (var i in range(batch_size / num_skips))
134+
{
135+
var context_words = range(span).Where(x => x != skip_window).ToArray();
136+
var words_to_use = new int[] { 1, 6 };
137+
foreach(var (j, context_word) in enumerate(words_to_use))
138+
{
139+
batch[i * num_skips + j] = buffer.ElementAt(skip_window);
140+
labels[i * num_skips + j, 0] = buffer.ElementAt(context_word);
141+
}
142+
143+
if (data_index == len(data))
144+
{
145+
//buffer.extend(data[0:span]);
146+
data_index = span;
147+
}
148+
else
149+
{
150+
buffer.Enqueue(data[data_index]);
151+
data_index += 1;
152+
}
153+
}
154+
155+
// Backtrack a little bit to avoid skipping words in the end of a batch
156+
data_index = (data_index + len(data) - span) % len(data);
65157

158+
return (batch, labels);
66159
}
67160

68161
public void PrepareData()
@@ -80,7 +173,7 @@ public void PrepareData()
80173
int wordId = 0;
81174
text_words = File.ReadAllText(@"word2vec\text8").Trim().ToLower().Split();
82175
// Build the dictionary and replace rare words with UNK token
83-
var word2id = text_words.GroupBy(x => x)
176+
word2id = text_words.GroupBy(x => x)
84177
.Select(x => new WordId
85178
{
86179
Word = x.Key,
@@ -97,10 +190,10 @@ public void PrepareData()
97190
.ToList();
98191

99192
// Retrieve a word id, or assign it index 0 ('UNK') if not in dictionary
100-
var data = (from word in text_words
193+
data = (from word in text_words
101194
join id in word2id on word equals id.Word into wi
102195
from wi2 in wi.DefaultIfEmpty()
103-
select wi2 == null ? 0 : wi2.Id).ToList();
196+
select wi2 == null ? 0 : wi2.Id).ToArray();
104197

105198
word2id.Insert(0, new WordId { Word = "UNK", Id = 0, Occurrence = data.Count(x => x == 0) });
106199

0 commit comments

Comments
 (0)