我注意到您的代码段中存在一些错误:
train
方法接受输入 功能 ,所以它应该是input_fn
,不input_fn()
。- 这些功能应作为字典,例如
{'x': features}。 DNNClassifier
使用SparseSoftmaxCrossEntropyWithLogits
损失函数。 稀疏 意味着它采用序数类表示形式,而不是单项表示形式,因此无需进行转换(此问题解释了tf中交叉熵损失之间的区别)。
请尝试以下代码:
import tensorflow as tffrom tensorflow.contrib.data import DatasetNUM_CLASSES = 3def model_fn(): feature_columns = [tf.feature_column.numeric_column("x", shape=[4], dtype=tf.float32)] return tf.estimator.DNNClassifier([10, 20, 10], feature_columns, "tmp/iris_model", NUM_CLASSES)def input_parser(img_path, label): file_contents = tf.read_file(img_path) image_depred = tf.image.depre_png(file_contents, channels=1) image_depred = tf.image.resize_images(image_depred, [2, 2]) image_depred = tf.reshape(image_depred, [4]) label = tf.reshape(label, [1]) return image_depred, labeldef input_fn(): filenames = tf.constant(['input1.jpg', 'input2.jpg']) labels = tf.constant([0,1], dtype=tf.int32) data = Dataset.from_tensor_slices((filenames, labels)) data = data.map(input_parser) data = data.batch(1) iterator = data.make_one_shot_iterator() features, labels = iterator.get_next() return {'x': features}, labelsmodel_fn().train(input_fn, steps=1)


