Невозможно распечатать правильную матрицу путаницы, а также в значениях тепловой карты печатаются в примере 2e + 2, e + 4 и т. Д. И т. Д. - PullRequest
1 голос
/ 18 апреля 2019

Не в состоянии правильно распечатать матрицу замешательства, а также при печати карты тепла значения в некоторых блоках или столбцах печатаются в примере 2e + 2, e + 4 и т. Д. И т. Д. Пожалуйста, помогите мне в этом

import numpyas np импортировать matplotlib.pyplot как plt импортировать seaborn as sns импортировать панд как pd из keras.models import Последовательный из keras.layers импортировать Convolution2D из keras.layers импортировать MaxPooling2D из keras.layersимпортировать классификационный_отчет, confusion_matrix

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

# Initialising the CNN
classifier = Sequential()

# Step 1 - Convolution
classifier.add(Convolution2D(64, 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(Convolution2D(64, 3, 3, activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))


classifier.add(Convolution2D(64, 3, 3, activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))


# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dense(output_dim = 128, activation = 'relu'))
classifier.add(Dense(output_dim = 10, activation = 'sigmoid'))

# Compiling the CNN
classifier.compile(optimizer = 'Adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Part 2 - Fitting the CNN to the images

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.4,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

#importing training data

training_set = train_datagen.flow_from_directory('Dataset/train',
                                                 target_size = (64,64),
                                                 batch_size = 64,
                                                 class_mode = 'categorical')

#importing test data
test_set = test_datagen.flow_from_directory('Dataset/test',target_size = (64,64),
                                            batch_size = 64,
                                            class_mode = 'categorical',shuffle=False)

#storing all the history

history = classifier.fit_generator(
        training_set,
        steps_per_epoch=20,
        epochs=5,
        validation_data=test_set,
        validation_steps=2000)
print(history.history.keys())

# суммировать точность

plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

#Confution Matrix 
Y_pred = classifier.predict_generator(test_set, steps=len(test_set), max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0)
y_pred = np.argmax(Y_pred, axis=1)

#assigning values 
confusion=(confusion_matrix(test_set.classes, y_pred))
confusion_df = pd.DataFrame(confusion,
                     index = ['Airplan','Car','Birds','Cats','Deer', 'Dogs','Frog', 'Horse','Ship','Truck'], 
                     columns = ['Airplan','Car','Birds','Cats','Deer', 'Dogs','Frog', 'Horse','Ship','Truck'])

#heatmap    
sns.heatmap(confusion_df, annot=True)
print(confusion_df)

#classification report
print('Classification Report')
target_names = ['Airplan','Car','Birds','Cats','Deer', 'Dogs','Frog', 'Horse','Ship','Truck']
print(classification_report(test_set.classes, y_pred, target_names=target_names))

1 Ответ

0 голосов
/ 13 мая 2019

Можете ли вы попробовать это.

sns.heatmap(confusion_df, annot=True, fmt='.2f')
...