2017-01-10 12 views
-1

我使用tf.contrib.layers.fully_connected在下面的代碼中創建一個圖層。如何從tf.contrib.layers.fully_connected創建的圖層訪問權重?

library(tensorflow) 

x <- tf$placeholder(tf$float32, shape(NULL, 784L)) 
logits <- tf$contrib$layers$fully_connected(x, 10L) 
y <- tf$nn$softmax(logits) 

如何訪問權,我會在下面的代碼塊與sess$run(W)

x <- tf$placeholder(tf$float32, shape(NULL, 784L)) 
W <- tf$Variable(tf$zeros(shape(784L, 10L))) 
b <- tf$Variable(tf$zeros(shape(10L))) 
y <- tf$nn$softmax(tf$matmul(x, W) + b) 

注:我使用TensorFlow對R但這應該通過改變$.是一樣的TensorFlow爲Python。

回答

0

您將張量的名稱傳遞給run函數。您應該檢查圖形以查看從函數添加到圖形的張量的名稱。

1

您可以使用tf$global_variables()獲取所有全局變量的列表。不是一個理想的解決方案(因爲它檢索一個未命名的變量列表),但它應該爲你提供你所需要的。下面是可重複使用的示例

library(tensorflow) 

datasets <- tf$contrib$learn$datasets 
mnist <- datasets$mnist$read_data_sets("MNIST-data", one_hot = TRUE) 

x <- tf$placeholder(tf$float32, shape(NULL, 784L)) 
logits <- tf$contrib$layers$fully_connected(x, 10L) 

y <- tf$nn$softmax(logits) 
y_ <- tf$placeholder(tf$float32, shape(NULL,10L)) 

cross_entropy <- tf$reduce_mean(-tf$reduce_sum(y_ * tf$log(y), reduction_indices=1L)) 
train_step <- tf$train$GradientDescentOptimizer(0.5)$minimize(cross_entropy) 

sess <- tf$Session() 
sess$run(tf$global_variables_initializer()) 

for (i in 1:1000) { 
    batches <- mnist$train$next_batch(100L) 
    batch_xs <- batches[[1]] 
    batch_ys <- batches[[2]] 
    sess$run(train_step, 
      feed_dict = dict(x = batch_xs, y_ = batch_ys)) 
} 

lst.variables <- sess$run(tf$global_variables()) 
str(lst.variables) 
相關問題