ValueError:无法将字符串转换为float:'nonPdr'

2024-04-26 04:17:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到以下错误:ValueError:无法将字符串转换为float:'nonPdr',当我运行以下代码时:

model = Sequential()
model.add(Conv2D(input_shape=(605,700,3), filters=64, kernel_size=(3,3), padding="valid",activation="tanh"))
model.add(Flatten())
model.add(Dense(32, activation='tanh', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])

data, labels = ReadImages(TRAIN_DIR)

# Train the model, iterating on the data in batches of 32 samples
model.fit(np.array(data), np.array(labels), epochs=10, batch_size=32)

Detail:'nonPdr'是我的两个img类之一

更新我的readImg方法

def ReadImages(Path):
    ImageList = list()
    LabelList = list()
    ImageCV = list()

    # Get all subdirectories
    FolderList = os.listdir(Path)

    # Loop over each directory
    for File in FolderList:
        if(os.path.isdir(os.path.join(Path, File))):
            for Image in os.listdir(os.path.join(Path, File)):
                # Add the image path to the list
                ImageList.append(os.path.join(Path, File) + os.path.sep + Image)
                # Convert the path into a file
                ImageCV.append(cv2.imread(os.path.join(Path, File) + os.path.sep + Image))    
                # Add a label for each image and remove the file extension
                LabelList.append(os.path.splitext(File)[0])
        else:
            ImageList.append(os.path.join(Path, File))

            ImageCV.append(cv2.imread(os.path.join(Path, File) + os.path.sep + Image))    
            # Add a label for each image and remove the file extension
            LabelList.append(os.path.splitext(File)[0])

    return ImageCV, LabelList

Tags: thepathimageaddformodelosactivation
1条回答
网友
1楼 · 发布于 2024-04-26 04:17:33

在ReadImages函数中,您正在创建字符串列表:

LabelList.append(os.path.splitext(File)[0])

稍后当您使用ReadImages函数时,您将尝试将此字符串列表转换为numpy数组。此处:

data, labels = ReadImages(TRAIN_DIR)
model.fit(np.array(data), np.array(labels), epochs=10, batch_size=32)

可能的解决方案是将类名指定给数字:

classes = ["nonPdr", "another_class"]
LabelList.append(classes.index[os.path.splitext(File)[0]])

当您的类为“nonPdr”时,0将附加到LabelList;如果您的类为“other\u class”,则1将附加到LabelList。你知道吗

相关问题 更多 >