我目前正在学习使用TensorFlow,遇到了一些入门问题。我想使用最新的API,即estimator和dataset。但是当我运行下面展示的代码时,会出现错误。
在TensorFlow的页面https://www.tensorflow.org/api_docs/python/tf/estimator/DNNRegressor上,我发现“该函数应构造并返回以下之一:* tf.data.Dataset对象:Dataset对象的输出必须是元组(features, labels),且需符合下述约束。”
我以为我的代码已经满足了这个要求,但似乎存在问题,我已经没有思路了。
import tensorflow as tfdef input_evaluation_set(): data = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1] labels = [] for d in data: labels.append(1) return tf.data.Dataset.from_tensor_slices((tf.constant(data), tf.constant(labels)))point = tf.feature_column.numeric_column('points')estimator = tf.estimator.DNNRegressor(feature_columns = [point],hidden_units = [100,100,100])estimator.train(input_fn = input_evaluation_set)
我期望在一个具有3个隐藏层,每层100个神经元的深度神经网络上运行训练会话,以近似“常数1”函数;但反而我得到了错误“ValueError: features should be a dictionary of ‘Tensor’s. Given type: class, ‘tensorflow.python.framework.ops.Tensor’
回答:
你需要在你的数据集上使用.batch方法,以便获得正确的格式。
以下代码在我的电脑上可以运行:
import tensorflow as tfimport numpy as npdef basic_dataset(numPoints): data = np.linspace(0,1,numPoints) dataset = dict({'points': data}) labels = [] for d in data: labels.append(1) return tf.data.Dataset.from_tensor_slices((dataset, np.array(labels)))def input_train_set(): dataset = basic_dataset(11) return dataset.repeat(100).shuffle(1000).batch(1)point = tf.feature_column.numeric_column('points')estimator = tf.estimator.DNNRegressor(feature_columns = [point],hidden_units = [100,100,100], label_dimension = 1)estimator.train(input_fn = input_train_set)