Tensorflow基本示例 - 变量初始化

时间:2016-10-20 16:56:09

标签: tensorflow

我有这段代码:

import tensorflow as tf
import numpy as np

data = np.random.randint(1000, size=10000)
x = tf.Variable(data, name='x')
y = tf.Variable(5*x*x-3*x+15, name='y')

model = tf.initialize_all_variables();

with tf.Session() as s:
    s.run(model)
    print (s.run(y))

我正在尝试实现与tensorflow变量相关的练习,但它失败并出现以下错误:

  

尝试使用未初始化的值x_20 [[Node:x_20 / read =   IdentityT = DT_INT64,_ class = [" loc:@ x_20"],   _device =" /作业:本地主机/复制:0 /任务:0 / CPU:0"]]

我也尝试用常量初始化x但它仍然失败。我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

I think it's your definition of y that's a bit funny.

Your code currently makes a variable y and initializes it to 5*x*x-3*x+15

Maybe you just mean that the value of y is calculated from the value of x:

y=5*x*x-3*x+15

If you actually want to initialize a new variable y with the initial value of that expression over x, then you need to use x.initialized_value():

x = tf.Variable(data, name='x')
x0 = x.initialized_value()
y = tf.Variable(5*x0*x0-3*x0+15, name='y')

The traceback you're getting is coming from the fact that the initialize operation is trying to initialize y, before initializing x.

The .initialized_value() method enforces the order.

See: https://www.tensorflow.org/versions/r0.11/how_tos/variables/index.html#initialization-from-another-variable

答案 1 :(得分:0)

要解决这个问题,我必须为变量x提供一个常量值。 所以我改变了这一行:

x = tf.Variable(data, name='x')

到以下行:

x = tf.constant(data, name='x')

似乎必须为variable提供constant值。