Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a9e8768

Browse files
Support weighted sparse column in sdca optimizer.
Change: 127093435
1 parent cd2162b commit a9e8768

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

tensorflow/contrib/learn/python/learn/estimators/linear_test.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,33 @@ def input_fn():
203203
scores = classifier.evaluate(input_fn=input_fn, steps=2)
204204
self.assertGreater(scores['accuracy'], 0.9)
205205

206+
def testSdcaOptimizerWeightedSparseFeatures(self):
207+
"""LinearClasssifier with SDCAOptimizer and weighted sparse features."""
208+
209+
def input_fn():
210+
return {
211+
'example_id': tf.constant(['1', '2', '3']),
212+
'price': tf.SparseTensor(values=[2., 3., 1.],
213+
indices=[[0, 0], [1, 0], [2, 0]],
214+
shape=[3, 5]),
215+
'country': tf.SparseTensor(values=['IT', 'US', 'GB'],
216+
indices=[[0, 0], [1, 0], [2, 0]],
217+
shape=[3, 5])
218+
}, tf.constant([[1], [0], [1]])
219+
220+
country = tf.contrib.layers.sparse_column_with_hash_bucket(
221+
'country', hash_bucket_size=5)
222+
country_weighted_by_price = tf.contrib.layers.weighted_sparse_column(
223+
country, 'price')
224+
sdca_optimizer = tf.contrib.learn.SDCAOptimizer(
225+
example_id_column='example_id')
226+
classifier = tf.contrib.learn.LinearClassifier(
227+
feature_columns=[country_weighted_by_price],
228+
optimizer=sdca_optimizer)
229+
classifier.fit(input_fn=input_fn, steps=50)
230+
scores = classifier.evaluate(input_fn=input_fn, steps=2)
231+
self.assertGreater(scores['accuracy'], 0.9)
232+
206233
def testSdcaOptimizerCrossedFeatures(self):
207234
"""Tests LinearClasssifier with SDCAOptimizer and crossed features."""
208235

tensorflow/contrib/learn/python/learn/estimators/sdca_optimizer.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,17 @@ def _training_examples_and_variables():
124124
column.length)
125125
sparse_features.append(math_ops.to_float(sparse_features_tensor))
126126
sparse_features_weights.append(columns_to_variables[column][0])
127+
elif isinstance(
128+
column,
129+
layers.feature_column._WeightedSparseColumn): # pylint: disable=protected-access
130+
id_tensor = column.id_tensor(transformed_tensor)
131+
weight_tensor = column.weight_tensor(transformed_tensor)
132+
sparse_features_tensor = sparse_ops.sparse_merge(
133+
id_tensor, weight_tensor, column.length,
134+
name="{}_sparse_merge".format(column.name))
135+
sparse_features.append(math_ops.to_float(
136+
sparse_features_tensor, name="{}_to_float".format(column.name)))
137+
sparse_features_weights.append(columns_to_variables[column][0])
127138
else:
128139
raise ValueError("SDCAOptimizer does not support column type %s." %
129140
type(column).__name__)

0 commit comments

Comments
 (0)