如何从tf.feature_column.embedding_column中获取具有嵌入权重的张量?

时间:2019-10-10 08:45:00

标签: python tensorflow tensorflow2.0

我正在使用tf.feature_column.embedding_column进行模型训练。

训练后我想获得具有学习过的权重的张量,如何在TensorFlow 2.0中做到这一点?

1 个答案:

答案 0 :(得分:0)

根据您使用的API,在将embedding_column传递给选定的估算器(例如tf.estimator.DNNClassifier)并获取估算器的变量后,您可以在估算器中获得权重:

columns =
    tf.feature_column.embedding_column(categorical_column, dimension=<int>)

estimator = tf.estimator.DNNClassifier(feature_columns=columns, ...)
estimator.train(input_fn, steps)

# ...

variable_names = estimator.get_variable_names()
for variable_name in variable_names:
    variable_value = classifier.get_variable_value(variable_name)
    print(name, repr(variable_value), print(variable_value))

在我的示例模型中,我可以找到例如。那些具有权重数组数据的权重变量:

  • 'dnn/input_from_feature_columns/input_layer/genome_embedding/embedding_weights'
[[-0.40976372 -0.23827374 -0.21227716 ...  0.5545821  -0.39704907
  -0.20433223]
 [-0.09768832  0.10465638 -0.18054526 ...  0.18183397 -0.14111575
  -0.01054266]
 [-0.29748577 -0.32883364  0.16298445 ...  0.04143892  0.19518057
  -0.14070898]
 [ 0.2233038   0.17278355 -0.01609583 ...  0.08676444  0.02549041
  -0.14985928]
 [ 0.13314098  0.01100806 -0.09716068 ...  0.1540673  -0.18161789
   0.28014034]
 [-0.00838758 -0.02734249  0.00528394 ... -0.05435016 -0.01493737
  -0.00866621]]
  • 'dnn/input_from_feature_columns/input_layer/genome_embedding/embedding_weights/t_0/Adagrad'
[[1.44397810e-01 1.19423054e-01 1.70357212e-01 ... 5.23897648e-01
  2.42158890e-01 1.05686426e-01]
 [8.75400330e+02 9.28867065e+02 5.93030273e+02 ... 9.08153442e+02
  9.01593262e+02 9.31873169e+02]
 [4.71744843e+02 5.78124268e+02 6.89979248e+02 ... 6.74259155e+02
  1.01136127e+03 6.12792297e+02]
 [5.25797363e+02 5.61125427e+02 5.83498657e+02 ... 6.07227112e+02
  8.72517883e+02 5.61017639e+02]
 [8.31141296e+02 8.37725464e+02 5.51519714e+02 ... 7.87189575e+02
  8.35132019e+02 8.92976868e+02]
 [1.00000001e-01 1.00000001e-01 1.00000001e-01 ... 1.00000001e-01
  1.00000001e-01 1.00000001e-01]]

希望这会有所帮助,如果对您不起作用,请在注释中告知。