ValueError: could not convert string to float: 

2019-08-28 01:52发布

问题:

I'm facing this error: ValueError: could not convert string to float: 'nonPdr', when I run this code:

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' is one of my 2 img classes

UPDATE My readImg method

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:

In your ReadImages function, you are making list of strings:

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

And later when you use ReadImages function, you are trying to convert this list of strings into numpy array. Here:

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

Possible solution might be assigning your class names to numbers:

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

0 will be appended to LabelList when your class is "nonPdr", and 1 will be append if your class is "other_class".