2016-07-04 61 views
16

Ho voluto inizializzare alcune delle variabili sulla mia rete con valori numpy. Per il bene della esempio si consideri:Come si inizializza una variabile con tf.get_variable e un valore numpy in TensorFlow?

init=np.random.rand(1,2) 
tf.get_variable('var_name',initializer=init) 

quando faccio che ottengo un errore:

ValueError: Shape of a new variable (var_name) must be fully defined, but instead was <unknown>. 

perché è che sto ottenendo questo errore?

Per cercare di risolvere il problema Ho provato a fare:

tf.get_variable('var_name',initializer=init, shape=[1,2]) 

che ha prodotto un errore di ancora più strano:

TypeError: 'numpy.ndarray' object is not callable 

ho provato leggendo the docs and examples ma non ha davvero aiutare.

Non è possibile inizializzare le variabili con gli array numpy con il metodo get_variable in TensorFlow?

risposta

25

le seguenti opere:

init = tf.constant(np.random.rand(1, 2)) 
tf.get_variable('var_name', initializer=init) 

La documentazione per get_variable è un po 'carente in effetti. Solo per riferimento, l'argomento initializer deve essere un oggetto TensorFlow Tensor (che può essere costruito chiamando tf.constant su un valore numpy nel tuo caso) o un 'callable' che accetta due argomenti, shape e dtype, la forma e tipo di dati del valore che dovrebbe restituire. Ancora una volta, nel tuo caso, è possibile scrivere quanto segue nel caso in cui si volesse utilizzare il meccanismo di 'callable':

init = lambda shape, dtype: np.random.rand(*shape) 
tf.tf.get_variable('var_name', initializer=init, shape=[1, 2]) 
+2

[Questo] (http://stackoverflow.com/questions/111234/what-is-a-callable-in-python) è una grande risposta alla tua domanda. – keveman

+0

Un 'callable' è una funzione o qualcosa che può essere chiamato come una funzione. – hpaulj

+0

'tf.get_variable ('var_name', initializer = np.random.rand (1, 2))' sembra funzionare ora su r0.10. – ldavid

6

@keveman risposto bene, e per il supplemento, non v'è l'utilizzo di tf.get_variable (' var_name ', initializer = init), il documento di tensorflow ha fornito un esempio esauriente.

import numpy as np 
import tensorflow as tf 

value = [0, 1, 2, 3, 4, 5, 6, 7] 
# value = np.array(value) 
# value = value.reshape([2, 4]) 
init = tf.constant_initializer(value) 

print('fitting shape:') 
tf.reset_default_graph() 
with tf.Session() : 
    x = tf.get_variable('x', shape = [2, 4], initializer = init) 
    x.initializer.run() 
    print(x.eval()) 

    fitting shape : 
[[0. 1. 2. 3.] 
[4. 5. 6. 7.]] 

print('larger shape:') 
tf.reset_default_graph() 
with tf.Session() : 
    x = tf.get_variable('x', shape = [3, 4], initializer = init) 
    x.initializer.run() 
    print(x.eval()) 

    larger shape : 
[[0. 1. 2. 3.] 
[4. 5. 6. 7.] 
[7. 7. 7. 7.]] 

print('smaller shape:') 
tf.reset_default_graph() 
with tf.Session() : 
    x = tf.get_variable('x', shape = [2, 3], initializer = init) 

    * <b>`ValueError`</b > : Too many elements provided.Needed at most 6, but received 8 

https://www.tensorflow.org/api_docs/python/tf/constant_initializer

2

Se la variabile è stata già creata (cioè da qualche funzione complessa), basta usare load.

https://www.tensorflow.org/api_docs/python/tf/Variable#load

x_var = tf.Variable(tf.zeros((1, 2), tf.float32)) 
x_val = np.random.rand(1,2).astype(np.float32) 

sess = tf.Session() 
x_var.load(x_val, session=sess) 

# test 
assert np.all(sess.run(x_var) == x_val)