如何在R的keras包中设置class_weight? [英] How to set class_weight in keras package of R?

查看:97
本文介绍了如何在R的keras包中设置class_weight?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在R中使用keras包来训练深度学习模型.我的数据集非常不平衡.因此,我想在fit函数中设置class_weight参数.这是我用于模型的拟合函数及其参数

I am using keras package in R to train a deep learning model. My data set is highly imbalanced. Therefore, I want to set class_weight argument in the fit function. Here is the fit function and its arguments that I used for my model

history <- model %>% fit(
  trainData, trainClass, 
  epochs = 5, batch_size = 1000, 
  class_weight = ????,
  validation_split = 0.2
)

在python中,我可以将class_weight设置如下:

In python I can set class_weight as follow:

class_weight={0:1, 1:30}

但是我不确定如何在R中执行此操作.在R的帮助菜单中,它对class_weight的描述如下:

But I am not sure how to do it in R. In the help menu of R it describes class_weight as follow:

可选的命名列表映射索引(整数)到权重(浮点数),以 在此期间将模型的损失应用于该类的样本 训练.这可能有助于告诉模型更多关注" 从一个代表性不足的类中抽取样本.

Optional named list mapping indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class.

有什么想法或建议吗?

推荐答案

Classweight是一个列表,因此

Class_weight needs to be a list, so

    history <- model %>% fit(
        trainData, trainClass, 
        epochs = 5, batch_size = 1000, 
        class_weight = list("0"=1,"1"=30),
        validation_split = 0.2
    )

似乎可以正常工作. Keras内部使用名为as_class_weights的函数将列表更改为python-dictionary(请参阅 https ://rdrr.io/cran/keras/src/R/model.R ).

seems to work. Keras internally uses a function called as_class_weights to change the list to a python-dictionary (see https://rdrr.io/cran/keras/src/R/model.R).

     class_weight <- dict(list('0'=1,'1'=10))
     class_weight
     >>> {0: 1.0, 1: 10.0}

就像您上面提到的python字典一样.

Looks just like the python dictionary that you mentioned above.

这篇关于如何在R的keras包中设置class_weight?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆