Tensorflow错误:" Tensor必须与Tensor相同的图形..."

时间:2016-07-17 15:18:30

标签: python python-2.7 tensorflow

我正在尝试使用Tensorflow(版本0.9.0)以与beginner's tutorial非常相似的方式训练一个简单的二元逻辑回归分类器,并且在拟合模型时遇到以下错误:

ValueError: Tensor("centered_bias_weight:0", shape=(1,), dtype=float32_ref) must be from the same graph as Tensor("linear_14/BiasAdd:0", shape=(?, 1), dtype=float32).

这是我的代码:

import tempfile
import tensorflow as tf
import pandas as pd

# Customized training data parsing
train_data = read_train_data()
feature_names = get_feature_names(train_data)
labels = get_labels(train_data)

# Construct dataframe from training data features
x_train = pd.DataFrame(train_data , columns=feature_names)
x_train["label"] = labels

y_train = tf.constant(labels)

# Create SparseColumn for each feature (assume all feature values are integers and either 0 or 1)
feature_cols = [ tf.contrib.layers.sparse_column_with_integerized_feature(f,2) for f in feature_names ]

# Create SparseTensor for each feature based on data
categorical_cols = { f: tf.SparseTensor(indices=[[i,0] for i in range(x_train[f].size)],
               values=x_train[f].values,
               shape=[x_train[f].size,1]) for f in feature_names }

# Initialize logistic regression model
model_dir = tempfile.mkdtemp()
model = tf.contrib.learn.LinearClassifier(feature_columns=feature_cols, model_dir=model_dir)

def eval_input_fun():
    return categorical_cols, y_train

# Fit the model - similarly to the tutorial
model.fit(input_fn=eval_input_fun, steps=200)

我觉得我错过了一些关键的东西......可能是教程中假设但没有明确提到的东西?

另外,每次调用fit()时都会收到以下警告:

WARNING:tensorflow:create_partitioned_variables is deprecated.  Use tf.get_variable with a partitioner set, or tf.get_partitioned_variable_list, instead.

1 个答案:

答案 0 :(得分:6)

执行model.fit时,LinearClassifiercreating a separate tf.Graph,基于eval_input_fun函数中包含的操作。但是,在创建此图表期间,LinearClassifier无权访问您全局保存的categorical_colsy_train的定义。

解决方案:将所有Ops定义(及其依赖项)移到eval_input_fun