+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

我需要为CNN模型制作一个混淆矩阵

发布于2021-01-23 19:51     阅读(337)     评论(0)     点赞(2)     收藏(5)


0

1

2

3

4

5

6

7

8

9

嗨,我是机器学习的新手,我只是想知道如何从这段代码中制作一个混淆矩阵,我只是按照youtube上的说明进行操作,我认为我迷路了,我只需要绘制混淆矩阵,我的数据集全部是关于癌症的,并且2个患有癌症和患有癌症的类别,我刚刚关注了senddex的视频,并更改了他的数据集

import tensorflow as tf
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
import numpy
import matplotlib.pyplot as plt
import os
import cv2

DATADIR = "C:/Users/Acer/imagerec/MRI"

CATEGORIES = ["yes", "no"]

for category in CATEGORIES:
    path = os.path.join(DATADIR,category)
    for img in os.listdir(path):
        img_array = cv2.imread(os.path.join(path,img) ,cv2.IMREAD_GRAYSCALE)
        plt.imshow(img_array, cmap='gray')
        plt.show()

        break
    break
print(img_array)
print(img_array.shape)

IMG_SIZE = 50

new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
plt.imshow(new_array, cmap='gray')
plt.show()

training_data = []

def create_training_data():
    for category in CATEGORIES:
        path = os.path.join(DATADIR, category)
        class_num = CATEGORIES.index(category)
        for img in os.listdir(path):
            try:
                img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)
                new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
                training_data.append([new_array, class_num])
            except Exception as e:
                pass


create_training_data()

print(len(training_data))

import random

random.shuffle(training_data)
for sample in training_data[:10]:
    print(sample[1])

X = []
y = []
for features, label in training_data:
    X.append(features)
    y.append(label)

X = numpy.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)

import pickle

pickle_in = open("X.pickle","rb")
X = pickle.load(pickle_in)



pickle_in = open("y.pickle","rb")
y = pickle.load(pickle_in)

X = X/255.0

model = Sequential()

model.add(Conv2D(256, (3, 3), input_shape=X.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(256, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X, y, batch_size=5, epochs=1, validation_split=0.1)



model.save('64x2-CNN.model')

解决方案


这将向您显示分类器在训练数据上预测对/错的位置(因为代码中没有测试集)。

from sklearn.metrics import confusion_matrix

pred = model.predict(X)

conf = confusion_matrix(y, pred)
Out[1]: 
array([[5, 8], # rows are actual classes, columns are predicted classes 
       [9, 3]], dtype=int64)

绘制(最小示例):

import seaborn as sns
sns.heatmap(conf, annot=True)

热图

0

1

2

3

4

5

6

7



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接: https://www.pythonheidong.com/blog/article/787087/ada4394df1e235208d3d/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

2 0
收藏该文
已收藏

评论内容:(最多支持255个字符)