gpt4 book ai didi

r - Keras R 图像分类模型中的形状错误

转载 作者:行者123 更新时间:2023-11-30 09:16:49 24 4
gpt4 key购买 nike

我在某个区域的代码上遇到了问题,这使我无法完成我的研究论文。我是机器学习和 R 的新手,但到目前为止我已经学到了很多东西。这是我的代码:

    # Install packages and libraries 
install.packages("keras")
source("http://bioconductor.org/biocLite.R")
library(keras)
library(EBImage)

# Read images
setwd('C:/Users/ebarn/Desktop/DataSet')
pics <- c('p1.jpg', 'p2.jpg', 'p3.jpg', 'p4.jpg', 'p5.jpg',
'p6.jpg','c1.jpg', 'c2.jpg', 'c3.jpg', 'c4.jpg', 'c5.jpg',
'c6.jpg')

mypic <- list()
for (i in 1:12) {mypic[[i]] <- readImage(pics[i])}

# Explore
print(mypic[[1]])
display(mypic[[1]])
display(mypic[[8]])
summary(mypic[[1]])
hist(mypic[[12]])
str(mypic)

# Resize
for (i in 1:12) {mypic[[i]] <- resize(mypic[[i]], 28, 28)}
str(mypic)

# Reshape
28*28*3
for (i in 1:12) {mypic[[i]] <- array_reshape(mypic[[i]], c(28,
28, 3))}
str(mypic)

# Row Bind
trainx <- NULL
for(i in 1:5) {trainx <- rbind(trainx, mypic[[i]])}
str(trainx)

for(i in 7:11) {trainx <- rbind(trainx, mypic[[i]])}
str(trainx)

testx <- rbind(mypic[[6]], mypic[[12]])
trainy <- c(0,0,0,0,0,1,1,1,1,1)
testy <- c(0, 1)

# One Hot Encoding
trainLabels <- to_categorical(trainy)
testLabels <- to_categorical(testy)
trainLabels

# Model
model <- keras_model_sequential()
model %>%
layer_dense(units = 256, activation = 'relu', input_shape =
c(2352))
%>%
layer_dense(units = 128, activation = 'relu')
%>%
layer_dense(units = 2, activation = 'softmax')

summary(model)

# Compile
model %>%
compile(loss = 'sparse_categorical_crossentropy',
optimizer = optimizer_rmsprop(),
metrics = c('accuracy'))

# model.add(Dense(10, activation = 'softmax'))

# Fit Model
history <- model %>%
fit(trainx, trainLabels, epochs = 30, batch_size = 32,
validation_split = 0.2)

plot(history)

# Evaluation & Prediction - train data
model %>% evaluate(trainx, trainLabels)

“拟合模型”方法不会打印出我的图表。这是它给我的错误:

ValueError: Error when checking target: expected dense _1 to have shape (1,) but got array with shape (2,)

最佳答案

您正在对标签进行一次性编码:

# One Hot Encoding 
trainLabels <- to_categorical(trainy)
testLabels <- to_categorical(testy)

因此,它们不再是稀疏标签,您需要使用 categorical_crossentropy 作为损失函数,而不是 sparse_categorical_crossentropy。或者,您可以注释 one-hot 编码行。

关于r - Keras R 图像分类模型中的形状错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53784354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com