我想在Keras中使用张量流的度量(皮尔逊相关)

时间:2018-08-01 04:30:25

标签: python tensorflow keras

我想在keras中使用tensorflow的指标(流梨相关)。 我搜索并编写此代码。 但是我的代码计算出的分数与numpy(corrcoef)计算出的分数不匹配。

def correlation_coefficient(y_true, y_pred):


    pearson_r, update_op = tf.contrib.metrics.streaming_pearson_correlation(y_pred, y_true)
    # find all variables created for this metric
    metric_vars = [i for i in tf.local_variables() if 'correlation_coefficient' in i.name.split('/')[1]]

    # Add metric variables to GLOBAL_VARIABLES collection.
    # They will be initialized for new session.
    for v in metric_vars:
        tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, v)

    # force to update metric values
    with tf.control_dependencies([update_op]):
        pearson_r = tf.identity(pearson_r)
        return pearson_r

1 个答案:

答案 0 :(得分:0)

我认为您应该可以这样做:

from keras import backend as K

def tf_pearson(y_true, y_pred):
    return tf.contrib.metrics.streaming_pearson_correlation(y_pred, y_true)[1]

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy', tf_pearson])

# tensorflow variables need to be initialized before calling model.fit()
# there is also a tf.global_variables_initializer(); that one doesn't seem to do the trick
# You will still get a FailedPreconditionError
K.get_session().run(tf.local_variables_initializer())

model.fit()

基本上,这是两件事-编译模型(代码中已使用TF函数/变量)后,您需要初始化变量(使用local函数,而不是global) ),那么您需要从指标中获取元组的第二部分(这是op_update,但似乎存储该值)。