gpt4 book ai didi

python - ValueError : Passed Tensor(. ..) 应该具有等于当前图形的图形属性

转载 作者:太空狗 更新时间:2023-10-30 01:47:55 26 4
gpt4 key购买 nike

我根本找不到 tensorflow 的问题。应该是简单的东西。下面的示例(带有噪声分类的简单 XOR)提出了以下问题:

ValueError: Passed Tensor("training_loss:0", shape=(), dtype=float32) should have graph attribute that is equal to current graph <tensorflow.python.framework.ops.Graph object at 0x0000018F142D9AC8>.

我根本看不出问题。

import numpy as np
import pandas as pd
import tensorflow as tf

def xor_data():
np.random.seed(423)
rows = 1000
base_cases = [(1, 1, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1)]
frames = list()

for case in base_cases:
tmp_df = pd.DataFrame(
np.random.uniform(low=-0.3, high=0.3, size=(rows, 2)),
columns=['x_1', 'x_2'])
tmp_df['x_1'] += case[0]
tmp_df['x_2'] += case[1]
tmp_df['y'] = case[2]
frames.append(tmp_df)

return pd.concat(frames, ignore_index=True)

def xor_fun():
x_1 = tf.contrib.layers.real_valued_column("x_1")
x_2 = tf.contrib.layers.real_valued_column("x_2")

model = tf.contrib.learn.DNNClassifier(hidden_units=[2,2 ],
feature_columns=[x_1, x_2])
df = xor_data()
feature_cols = {
'x_1': tf.constant(value=df['x_1'].values),
'x_2': tf.constant(value=df['x_2'].values)}

labels = tf.constant(value=df['y'].values)

def input_fn():
return feature_cols, labels

model.fit(input_fn=input_fn, steps=50)

if __name__ == '__main__':
xor_fun()

最佳答案

从闭包中返回特征或标签失败,因为当您调用 model.fit 时会创建一个新的 tf.Graph,因此对图的任何修改(例如 tf.contrib 调用)需要在 input_fn 中进行(因此在实例化新图之后)。

为了证明,这是可行的

import numpy as np
import tensorflow as tf

def input_fn():
x = np.array([1., 2., 3., 4.])
y = np.array([0., -1., -2., -3.])
feature_cols = {'x': tf.constant(x)}
labels = tf.constant(y)
return feature_cols, labels

features = [tf.contrib.layers.real_valued_column("x", dimension=1)]
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)
estimator.fit(input_fn=input_fn, steps=100)
print(estimator.evaluate(input_fn=input_fn, steps=1))

但这不是

import numpy as np
import tensorflow as tf

x = np.array([1., 2., 3., 4.])
y = np.array([0., -1., -2., -3.])
feature_cols = {'x': tf.constant(x)}
labels = tf.constant(y)
input_fn = lambda: feature_cols, labels

features = [tf.contrib.layers.real_valued_column("x", dimension=1)]
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)
estimator.fit(input_fn=input_fn, steps=100)
print(estimator.evaluate(input_fn=input_fn, steps=1))

另请参阅此答案 https://stackoverflow.com/a/39400592/6536722

关于python - ValueError : Passed Tensor(. ..) 应该具有等于当前图形的图形属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42799041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com