【问题标题】:catch R tryCatch() out of bounds exception in order to ignore execption捕获 R tryCatch() 越界异常以忽略异常
【发布时间】:2020-05-31 19:25:07
【问题描述】:

问题:

R tryCatch() 需要处理已知错误。

我正在使用词向量矩阵来运行向量词位置。我正在寻求添加一个 R tryCatch() 来处理或捕获这个下标越界。这是单词搜索的预期行为。 在 R 中捕获、忽略异常的确切方法是什么?我应该使用什么异常代码来捕获越界?

例如:

word1 = 'This'
word2 = 'Happy'

这个组合在词向量内的上下文搜索中不应该匹配。所以下标越界表示这个匹配不存在。

代码:

'''
    word_vectors[word1, , drop=FALSE] + word_vectors[word2, , drop=FALSE]
'''

错误信息:

'''
run_glove_search(word1, word2, word_vectors)
Error in word_vectors[word1, , drop = FALSE] : subscript out of bounds
> View(word_vectors)
'''

错误是由于下标超出范围,这在不匹配的单词组合上是预期的。因此,这是预期的行为。

数据示例: 注意:词矩阵是75800的大矩阵,所以我只展示1行统计示例

'''
This    0.175438308 0.1229126933    -0.792327086    -0.698233553    0.407953490 0.362040523 0.258780885 0.352198675 -0.170637061    -0.512016098    0.408881291 -0.0866425339   0.0510299517    -0.150036589    0.002336813 0.390699917 -0.635815296    -0.295312958
'''

【问题讨论】:

    标签: exception try-catch-finally


    【解决方案1】:

    代码解决方案: TryCatch() with error = function(e) 并且什么也不做,因为我知道并期望会发生此错误,因此我可以将 NULL 分配给 function(e) 的 e,因为我不需要任何错误消息。

      tryCatch({
        gws <- word_vectors[word1, , drop=FALSE] + word_vectors[word2, , drop=FALSE]
        cos_sim = sim2(x = word_vectors, y = gws, method = "cosine", norm = "l2")
        head(sort(cos_sim[,1], decreasing = TRUE), 7)
        },
        error = function(e){e=NULL}
      ) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 2018-06-07
      • 2013-11-28
      • 2013-03-23
      相关资源
      最近更新 更多