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

时间:2019-08-20 17:32:03

标签: python tensorflow machine-learning image-processing keras

我遇到此错误: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)

详细信息:“ nonPdr”是我的2个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

1 个答案:

答案 0 :(得分:0)

在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_class”,则将附加1。