【问题标题】:class_weight parameter in keras::fit() error. Classes exist in data but not in class_weightkeras::fit() 错误中的 class_weight 参数。类存在于数据中,但不存在于 class_weight
【发布时间】:2019-04-08 15:56:56
【问题描述】:

我尝试为其分配权重的数据集略有不平衡。

How to set class_weight in keras package of R? 中提供的示例不适用于我。当我尝试相同时,使用我的代码:

system.time ( 
  baseline_history <- fit (
    object           = model_baseline,            
    x                = as.matrix(x_train_tbl), 
    y                = y_train_vec,             
    batch_size       = 1024,    
    epochs           = 30,    
    class_weight = list("0" = 1, "1" = 1.67),
    validation_split = 0.2) )

我收到以下错误:

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  ValueError: `class_weight` must contain all classes in the data. The classes {'0', '1'} exist in the data but not in `class_weight`.

我有点不知所措,因为我在 class_weights 中明确声明它是一个列表。我什至尝试过

weights <- list("0" = 1, "1" = 1.67)
> weights
$`0`
[1] 1

$`1`
[1] 1.67

is.list(weights)
[1] TRUE

为了确保它有效,但我仍然遇到同样的错误。有什么想法吗?

【问题讨论】:

    标签: r class keras deep-learning


    【解决方案1】:

    我假设您将y_train_vec 作为一个因素,这就是问题所在。

    由于某种原因,class_weight 似乎不适用于因子,因此您可以简单地将其更改为数字

    y_train_vec = as.numeric(y_train_vec)

    这应该给你你的因素的内部表示(它应该给你一个 1 和 2 的列表),然后你可以相应地指定 class_weight

    system.time(
        baseline_history <- fit (
            object           = model_baseline,            
            x                = as.matrix(x_train_tbl), 
            y                = as.matrix(y_train_vec),             
            batch_size       = 1024,    
            epochs           = 30,    
            class_weight = list("1" = 1, "2" = 1.67),
            validation_split = 0.2)
        )
    )
    

    现在注意class_weight 中的类是“1”和“2”

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 1970-01-01
      • 2020-01-15
      • 2018-09-23
      • 2019-02-05
      • 2018-09-06
      • 2019-11-08
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多