我想从存储虹膜值的文件中预测类。 具有值的模型精度似乎不错:
perf = model %>% evaluate(x_test, y_test)
print(perf)
## $loss
## [1] 0.3843208
##
## $acc
## [1] 1
我的问题,我想预测班级;
#load new data from file for prediction
library(readr)
Variants <- read.table(here::here("data","Species_to_predict.csv"), sep=";", header=T, dec=".", fill=TRUE)
# Predicted Class
yhat_keras_class_vec <- predict_classes(object = model, x = as.matrix(Variants))
yhat_keras_class_vec
[1] 2 2 2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1
[30] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
我具有相同的输出值。您知道我在做什么错吗,或者您是否知道keras预测类是否存在错误?
这是我的实现方式:
library("keras")
library("tidyverse")
nn_dat = iris %>% as_tibble %>%
mutate(sepal_l_feat = scale(Sepal.Length),
sepal_w_feat = scale(Sepal.Width),
petal_l_feat = scale(Petal.Length),
petal_w_feat = scale(Petal.Width),
class_num = as.numeric(Species) - 1, # factor, so = 0, 1, 2
class_label = Species) %>%
select(contains("feat"), class_num, class_label)
nn_dat %>% head(3)
test_f = 0.20
nn_dat = nn_dat %>%
mutate(partition = sample(c('train','test'), nrow(.), replace = TRUE, prob = c(1 - test_f, test_f)))
x_train = nn_dat %>% filter(partition == 'train') %>% select(contains("feat")) %>% as.matrix
y_train = nn_dat %>% filter(partition == 'train') %>% pull(class_num) %>% to_categorical(3)
x_test = nn_dat %>% filter(partition == 'test') %>% select(contains("feat")) %>% as.matrix
y_test = nn_dat %>% filter(partition == 'test') %>% pull(class_num) %>% to_categorical(3)
model = keras_model_sequential()
model %>%
layer_dense(units = 4, activation = 'relu', input_shape = 4) %>%
layer_dense(units = 3, activation = 'softmax')
model %>% summary
model %>% compile(
loss = 'categorical_crossentropy',
optimizer = optimizer_rmsprop(),
metrics = c('accuracy')
)
history = model %>% fit(
x = x_train, y = y_train,
epochs = 200,
batch_size = 20,
validation_split = 0
)
perf = model %>% evaluate(x_test, y_test)
print(perf)
plot_dat = nn_dat %>% filter(partition == 'test') %>%
mutate(class_num = factor(class_num),
y_pred = factor(predict_classes(model, x_test)),
Correct = factor(ifelse(class_num == y_pred, "Yes", "No")))
plot_dat %>% select(-contains("feat")) %>% head(3)
#load new data from file for prediction
library(readr)
Variants <- read.table(here::here("data","Species_to_predict.csv"), sep=";", header=T, dec=".", fill=TRUE)
# Predicted Class
yhat_keras_class_vec <- predict_classes(object = model, x = as.matrix(Variants))
yhat_keras_class_vec