user3062572
user3062572

Reputation: 126

Multiple labels with tensorflow

I am trying to modify this code (see GitHub link below), so that I can use my own data and predict more than one label using the same set of features.

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/input_fn/boston.py

I have it working when I use one label at a time. However when I try to create a tensor which contains more than one label, I run into problems. Any suggestions?

My modified LABELS and input_fn look like this:

LABELS = ["Label1", "Label2", "Label3"]

def input_fn(data_set):
  feature_cols = {k: tf.constant(len(data_set), shape=[data_set[k].size, 1]) for k in FEATURES}
  labels_data = []
  for i in range(0, len(data_set)):
    temp = []
    for label in LABELS:
        temp.append(data_set[label].values[i])
    labels_data.append(temp)
  labels = tf.constant(labels_data, shape=[len(data_set), len(LABELS)])
  return feature_cols, labels 

This is the end of the error message I get:

  File "/usr/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py", line 175, in _dnn_model_fn
return head.head_ops(features, labels, mode, _train_op_fn, logits)
  File "/usr/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 403, in head_ops
head_name=self.head_name)
  File "/usr/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 1358, in _training_loss
loss_fn(logits, labels),
  File "/usr/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/head.py", line 330, in _mean_squared_loss
logits.get_shape().assert_is_compatible_with(labels.get_shape())
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/tensor_shape.py", line 735, in assert_is_compatible_with
raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (118, 1) and (118, 3) are incompatible

Upvotes: 2

Views: 5182

Answers (2)

JulesKzl
JulesKzl

Reputation: 90

From here, you have to change this parameter :

label_dimension: Dimension of the label for multilabels. Defaults to 1.

So this should work :

regressor = tf.contrib.learn.DNNRegressor(feature_columns=feature_cols,
                                        label_dimension=3,
                                        hidden_units=[10, 10],
                                        model_dir="/tmp/boston_model")

Upvotes: 2

Teo Cherici
Teo Cherici

Reputation: 121

from this link it seems like you have to specify the number of classes (labels) to 3:

regressor = tf.contrib.learn.DNNRegressor(feature_columns=feature_cols,
                                        n_classes=3,
                                        hidden_units=[10, 10],
                                        model_dir="/tmp/boston_model")

the n_classes value should perhaps be set to 2 instead of 3, see which one works

Upvotes: 4

Related Questions