【发布时间】:2018-02-03 09:47:45
【问题描述】:
我想为我的 tensorflow 运行获得可重现的结果。我试图实现这一点的方法是设置 numpy 和 tensorflow 种子:
import numpy as np
rnd_seed = 1
np.random.seed(rnd_seed)
import tensorflow as tf
tf.set_random_seed(rnd_seed)
除了确保我使用tf.truncated_normal 初始化的神经网络的权重也使用该种子:tf.truncated_normal(..., seed=rnd_seed)
由于超出本问题范围的原因,我正在使用采样的 softmax 损失函数 tf.nn.sampled_softmax_loss,但不幸的是,我无法使用随机种子控制此函数的随机性。
通过查看此函数 (https://www.tensorflow.org/api_docs/python/tf/nn/sampled_softmax_loss) 的 TensorFlow 文档,我可以看到参数 sampled_values 应该是影响随机化的唯一参数,但我无法理解如何实际使用种子.
[已编辑] 这是(部分)我的脚本
import numpy as np
# set a seed so that the results are consistent
rnd_seed = 1
np.random.seed(rnd_seed)
import tensorflow as tf
tf.set_random_seed(rnd_seed)
embeddings_ini = np.random.uniform(low=-1, high=1, size=(self.vocabulary_size, self.embedding_size))
with graph.as_default(), tf.device('/cpu:0'):
train_dataset = tf.placeholder(tf.int32, shape=[None, None])
train_labels = tf.placeholder(tf.int32, shape=[None, 1])
valid_dataset = tf.constant(self.valid_examples, dtype=tf.int32)
# Variables.
initial_embeddings = tf.placeholder(tf.float32, shape=(self.vocabulary_size, self.embedding_size))
embeddings = tf.Variable(initial_embeddings)
softmax_weights = tf.Variable(
tf.truncated_normal([self.vocabulary_size, self.embedding_size],
stddev=1.0 / math.sqrt(self.embedding_size), seed=rnd_seed))
softmax_biases = tf.Variable(tf.zeros([self.vocabulary_size]))
# Model.
# Look up embeddings for inputs.
if self.model == "skipgrams":
# Skipgram model
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
elif self.model == "cbow":
# CBOW Model
embeds = tf.nn.embedding_lookup(embeddings, train_dataset)
embed = tf.reduce_mean(embeds, 1, keep_dims=False)
# Compute the softmax loss, using a sample of the negative labels each time.
loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(weights=softmax_weights,
biases=softmax_biases,
inputs=embed,
labels=train_labels,
num_sampled=self.num_sampled,
num_classes=self.vocabulary_size))
【问题讨论】:
-
您能否提供完整的脚本,以便我们了解不受控制的随机性的可能来源?
-
sampled_values参数的想法是传递*_candidate_sampler函数之一的输出(您可以查找它们here,尽管它们没有分组到公共部分或任何事物)。但是,如果您使用tf.set_random_seed,即使您没有通过,它也应该是可重现的。你能确认你是setting the seed within the graph吗? -
我同意。
_compute_sampled_logits不会将任何种子传递给候选样本,因此这一切都归结为您的图表的种子。 -
@Anis 我编辑了帖子并包含了我的脚本中应该与问题相关的部分。你知道出了什么问题吗?
-
你看过我们所说的关于设置图表种子的内容吗?
标签: python numpy random tensorflow