【问题标题】:R keras Beginner Question predict_classesR keras初学者问题predict_classes
【发布时间】:2022-11-19 12:55:48
【问题描述】:

我以前没有使用 Tensorflow 或 Keras 的经验。 我正在尝试按照教程https://tensorflow.rstudio.com/tutorials/beginners/

library(keras)


mnist <- dataset_mnist()
mnist$train$x <- mnist$train$x/255
mnist$test$x <- mnist$test$x/255

model <- keras_model_sequential() %>% 
  layer_flatten(input_shape = c(28, 28)) %>% 
  layer_dense(units = 128, activation = "relu") %>% 
  layer_dropout(0.2) %>% 
  layer_dense(10, activation = "softmax")

summary(model)

model %>% 
  compile(
    loss = "sparse_categorical_crossentropy",
    optimizer = "adam",
    metrics = "accuracy"
  )

#Note that compile and fit (which we are going to see next) modify the model object in place, unlike most R functions.

model %>% 
  fit(
    x = mnist$train$x, y = mnist$train$y,
    epochs = 5,
    validation_split = 0.3,
    verbose = 2
  )

predictions <- predict(model, mnist$test$x)
head(predictions, 2)

class_predictions <- predict(model, mnist$test$x) %>% k_argmax()
class_predictions

predict_classes 已弃用。 k_armax() 被宣传为错误中的替代方法。 但是我不知道如何将预测的类(在本例中为数字 0-9)作为向量在 confusionMatrix 中使用它,就像其他 R 模型一样。 任何帮助,将不胜感激。

【问题讨论】:

  • 请选择一个真正描述您的问题的标题。

标签: r tensorflow keras


【解决方案1】:

对于此问题,以下代码有效

predictions <- predict(model, mnist$test$x)
pred_digits <- apply(predictions, 1, which.max) -1
confusionMatrix(as.factor(pred_digits), as.factor(mnist$test$y))

但是,我仍然认为 predict_classes 已被弃用而没有替换,这很奇怪。到目前为止我看过的所有教程都使用它。

【讨论】:

    【解决方案2】:

    predict() %&gt;% k_argmax() 返回一个 Tensor 对象。要复制 predict_classes() 的结果,您要做的是将该 Tensor 对象转换为向量。你可以这样做:

    class_predictions <- predict(model, mnist$test$x) %>% k_argmax() %>% as.vector()
    

    此外,this page may be useful

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 2020-11-23
      • 2015-03-16
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多