SciSharp / TensorFlow.NET

.NET Standard bindings for Google's TensorFlow for developing, training and deploying Machine Learning models in C# and F#.
https://scisharp.github.io/tensorflow-net-docs
Apache License 2.0
3.2k stars 514 forks source link

¿how to set a random seed? #1095

Closed IgnacioRodriguez98 closed 1 year ago

IgnacioRodriguez98 commented 1 year ago

Description

Hi there.

I´m came from python and there is necessary to set a random seed to ensure that results are reproducible, how can I set that seed in tensorflow.net?

here are examples to set it in python:

np.random.seed(7) tf.set_random_seed(7)

Wanglongzhi2001 commented 1 year ago

In TensorFlow.NET, you can use tf.set_random_seed. Here is an example:

using static Tensorflow.Binding;

tf.set_random_seed(10);
var randNum = tf.random.uniform(1);
Console.WriteLine($"randnum: {randNum}"); // randnum: tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.6364622])
IgnacioRodriguez98 commented 1 year ago

In TensorFlow.NET, you can use tf.set_random_seed. Here is an example:

using static Tensorflow.Binding;

tf.set_random_seed(10);
var randNum = tf.random.uniform(1);
Console.WriteLine($"randnum: {randNum}"); // randnum: tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.6364622])

Excuse my ignorance, but if I put my code like this (in python if it works for me like this) I would already have my seed and could I have my reproducible experiment?

var LSTM = new Sequential();
      LSTM.Add(new Bidirectional(new LSTM(50, activation: "relu", input_shape: input_shape)));
      LSTM.Add(new Dense(1));
      LSTM.Compile(optimizer: "adam", loss: "mean_squared_error");
tf.set_random_seed(7);
LSTM.fit()
Wanglongzhi2001 commented 1 year ago

Sorry, even though TensorFlow and TensorFlow.NET use the same random seed and the same way random numbers are generated, they can't currently produce the same random number. BTW, tf.set_random_seed is used in tf1, you are better use tf.random.set_seed in tf2, and there is no alignment tf.random.set_seed yet in TensorFlow.NET, you can use tf.set_random_seed in TensorFlow.NET instead.