2017-04-03 38 views
0

我用tensorflow的LinearClassifier数据与着名的泰坦尼克号数据集一起玩过。可视化tf.contrib.learn.LinearClassifier权重

(我的问题本身就是下跌的底部 - 这是模型本身都有些代码)

所以,我有我的特色栏目:

CONTINUOUS_COLS = ['Age', 'Fare'] 
CATEGORICAL_COLS = ['Sex', 'Pclass', 'Title'] 
LABELS_COL = 'Survived' 

sex_col = sparse_column_with_keys('Sex', keys=['male', 'female']) 
title_col = sparse_column_with_hash_bucket('Title', 10) 
fare_class_col = sparse_column_with_keys('Pclass', keys=['1','2','3']) 
age_col = real_valued_column('Age') 
fare_col = real_valued_column('Fare') 

我输入功能:

def create_input_fn(df): 
    continous_features = {k: tf.constant(df[k].values) for k in CONTINUOUS_COLS} 
    categorical_features = {k : tf.SparseTensor(
     indices=[[0,i] for i in range(df[k].size)], 
     values=df[k].values, 
     dense_shape=[df[k].size, 1] 
    ) for k in CATEGORICAL_COLS} 
    feature_cols = {**continous_features, **categorical_features} 
    labels = tf.constant(df[LABELS_COL].values) 
    return feature_cols, labels 

和我的模型:

clf = LinearClassifier(feature_columns=[sex_col, fare_class_col, age_col, fare_col, title_col], 
    optimizer=tf.train.FtrlOptimizer(
     learning_rate=0.5, 
     l1_regularization_strength=1.0, 
     l2_regularization_strength=1.0), 
    model_dir=tempfile.TemporaryDirectory().name) 

现在,当我运行模型时,它确实会出现波折,我想查看模型的权重以更好地观察它们。

所以clf.weights_存在(尽管它被列为不推荐使用),所以我只是将它们拉出来手动:

for var in clf.get_variable_names(): 
    if var.endswith('weights'): 
     print(f'{var} -> {clf.get_variable_value(var)}') 

我也得到了一些不错的成绩:

linear/Pclass/weights -> [[ 0.  ] 
[ 0.  ] 
[-0.01772301]] 
linear/Sex/weights -> [[-0.07285357] 
[ 0.  ]] 
linear/Title/weights -> [[ 0.  ] 
[ 0.  ] 
[ 0.  ] 
[-0.03760524] 
[ 0.  ] 
[ 0.  ] 
[ 0.  ] 
[ 0.  ] 
[ 0.  ] 
[ 0.  ]] 

现在我的问题是 - 我如何取出最初使用的? 因此,我可以更好地匹配数字,例如与性别 - 键最初映射到男性/女性。

谢谢!

回答

0

对于sparse_column_with_keys
sex_col.lookup_config.keys # ('male', 'female')

因此,像:

matched = {} 
weights = clf.get_variable_value('linear/Sex/weights') # np array 
for index, key in enumerate(sex_col.lookup_config.keys): 
    matched[key] = weights[index] 

还有其他一些有趣的属性,当你dir(sex_col.lookup_config)和检查方法的文档字符串:Source for SparseColumn Feature classes https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/feature_column.py

我没有弄清楚的地图尚

如果你有tf.contrib.layers.bucketized_column像教程age_buckets: age_buckets.boundaries