keras 在Tensorflow“回归”模型中报告R2评分

watbbzwu  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(488)

我希望我的模型在确认中报告r2平方,但是我找不到正确的指标来填写???,

model.compile(loss = 'mse',
              optimizer = 'adam',
              metrics = '???')

谢谢你事先的提示

7eumitmz

7eumitmz1#

我对这个问题的回答是,y计算R2分数是R平方分数,但tfa。metrics。R平方需要使用相同的大小,相同的y_true和y_predict顺序,但当需要以通道或离散的形式输入到输出时,可以对多类进行此操作。
示例:自定义多类,它要求tf.float32作为默认tf.变量赋值,并作为多类攻击返回。

import tensorflow as tf

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Class / Definition
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
class MulticlassSumSquare(tf.keras.metrics.Metric):
    def __init__(self, name='multiclass_true_positives', **kwargs):
        super(MulticlassSumSquare, self).__init__(name=name, **kwargs)
        self.value = self.add_weight(name='tp', initializer='zeros')
        
    def update_state(self, y_true, y_pred, sample_weight=None):
        y_pred = tf.reshape( tf.argmax(y_pred, axis=0), shape=(-1, 1))
        y_pred = tf.cast(y_pred, 'float32')
        y_true = tf.cast(y_true, 'float32')
        temp = 1 - ( ( y_pred - y_true ) / ( y_pred + y_true ) )
        self.value.assign_add( tf.reduce_sum(temp) )

    def result(self):
        return self.value

    def reset_state(self):
        # The state of the metric will be reset at the start of each epoch.
        self.value.assign(0.)
        
class MyDenseLayer(tf.keras.layers.Layer):
    def __init__(self, num_outputs):
        super(MyDenseLayer, self).__init__()
        self.num_outputs = num_outputs
        
    def build(self, input_shape):
        min_size_init = tf.keras.initializers.Ones()
        self.kernel = self.add_weight(shape=[int(input_shape[-1]), self.num_outputs],
        initializer = min_size_init, trainable=True)

    def call(self, inputs):
        temp = tf.matmul(inputs, self.kernel)       # , shape=(10, 10), dtype=float32)
        return temp
        
start = 3
limit = 33
delta = 3
sample = tf.range(start, limit, delta)
sample = tf.cast( sample, dtype=tf.float32 )
sample = tf.constant( sample, shape=( 10, 1 ) )
label = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=tf.int64)
layer = MyDenseLayer(10)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
DataSet
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
dataset = tf.data.Dataset.from_tensor_slices((tf.constant(tf.cast(sample, dtype=tf.int64), shape=(1, 10, 1), dtype=tf.int64),tf.constant(label, shape=(1, 10, 1), dtype=tf.int64)))

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Model Initialize
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
model = tf.keras.models.Sequential([
    tf.keras.layers.InputLayer(input_shape=( 1, 1 )),
    layer
])

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Optimizer
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
optimizer = tf.keras.optimizers.Nadam(
    learning_rate=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-07,
    name='Nadam'
)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Loss Fn
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""                               
lossfn = tf.keras.losses.SparseCategoricalCrossentropy(
    from_logits=False,
    reduction=tf.keras.losses.Reduction.AUTO,
    name='sparse_categorical_crossentropy'
)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Model Summary
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
model.compile(optimizer=optimizer, loss=lossfn, metrics=[MulticlassSumSquare()])

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Training
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
history = model.fit( dataset, batch_size=100, epochs=10000 )

输出:单记录R suqare无变化无损失函数返回值。

Epoch 1/10000
1/1 [==============================] - 1s 1s/step - loss: nan - multiclass_true_positives: 7.0621
Epoch 2/10000
1/1 [==============================] - 0s 5ms/step - loss: nan - multiclass_true_positives: 7.0621

示例:游戏中的离散动作

group_2_Heriken_kick_Left = tf.constant([ 0,0,0,0,0,1,0,0,0,0,0,0, 0,0,0,0,0,1,1,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0 ], shape=(1, 1, 1, 48))

相关问题