Tensorflow基本示例-变量初始化

标签 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 变量相关的练习,但失败并出现以下错误:

Attempting to use uninitialized value x_20 [[Node: x_20/read = IdentityT=DT_INT64, _class=["loc:@x_20"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

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

最佳答案

我认为你对 y 的定义有点有趣。

您的代码当前创建了一个变量 y 并将其初始化5*x*x-3*x+15

也许您只是想说 y 的值是根据 x 的值计算出来的:

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

如果您确实想使用 x 上的表达式的初始值初始化新变量 y,那么您需要使用 x.initialized_value() :

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

您获得的回溯来自这样一个事实:初始化操作在初始化 x 之前尝试初始化 y

.initialized_value() 方法强制执行该顺序。

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

关于Tensorflow基本示例-变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40160243/

相关文章:

python-3.x - tflearn DNN 模型给出 TargetsData/Y :0 error

TensorFlow 损失函数在第一个 epoch 后归零

tensorflow - 可变长度 rnn 填充和屏蔽填充梯度

python - `tf.nn.max_pool(input_tensor, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")` 对输入张量形状有什么影响?

python - 属性错误 : 'Tensor' object has no attribute '_keras_shape'

python - interpreter.get_input_details() 中的 'quantization' 是什么意思?

python - 计算每个时间步长的可变长度输出的成本

tensorflow - 在 Datalab 中使用 Python3,我无法将表示 Google Cloud Storage 存储桶中文件的字符串列表作为带有 tensorflow 的 feed_dict

python - Tensorflow 的开端——类的数量

python - tf.nn.l2_loss 和 tf.contrib.layers.l2_regularizer 是否与在 tensorflow 中添加 L2 正则化的目的相同?