2017-04-03 40 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