我想预测2种疾病的种类,但得到的结果是二进制的(例如1.0和0.0)。如何获得这些精度(例如0.7213)?
培训代码:
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Intialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
import h5py
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('training_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('test_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
classifier.fit_generator(training_set,
steps_per_epoch = 100,
epochs = 1,
validation_data = test_set,
validation_steps = 100)
单个预测代码:
import numpy as np
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img,image
test_image = image.load_img('path_to_image', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
print(result[0][0]) # Prints 1.0 or 0.0
# I want accuracy rate for this prediction like 0.7213
文件结构如下:
测试集
训练集
训练集的结构也与测试集相同。
答案 0 :(得分:1)
更新:正如您在评论中所阐明的那样,您正在寻找给定一个测试样本的每个类的概率。因此,您可以使用predict
方法。但是,请注意,您必须首先以与训练阶段相同的方式对图像进行预处理:
test_image /= 255.0
result = classifier.predict(test_image)
result
是给定图像属于第一类(即肯定类)的概率。
如果您具有测试数据生成器,则可以使用evaluate_generator()
获取测试数据上模型的损失以及准确性(或您设置的任何其他指标)。
例如,在拟合模型之后,即使用fit_generator
,您可以在测试数据生成器上使用evaluate_generator
,即test_set
:
loss, acc = evaluate_generator(test_set)