【问题标题】:Extending an existing python macro from predicting 2 categories to 3 categories将现有的 python 宏从预测 2 个类别扩展到 3 个类别
【发布时间】:2021-12-22 19:46:59
【问题描述】:

我需要一些帮助来获得一个现有的 python 示例,该示例可以很好地分类 2 个类别并将其扩展到分类 3 个类别。 这是工作示例:

import numpy as np
import matplotlib.pyplot as plt
import os
import cv2 as cv
from tqdm import tqdm
import random

import tensorflow as tf
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D

DATADIR = "C:/D/tmp/CNN"
CATEGORIES = ["Cat1","Cat2"]
IMG_SIZE = 100
training_data = []

def create_training_data():
    for category in CATEGORIES:  

        path = os.path.join(DATADIR,category)  
        class_num = CATEGORIES.index(category)  

        for img in tqdm(os.listdir(path)):  
            try:
                img_array = cv.imread(os.path.join(path,img) ,cv.IMREAD_GRAYSCALE)  # convert to array
                new_array = cv.resize(img_array, (IMG_SIZE, IMG_SIZE))  # resize to normalize data size
                training_data.append([new_array, class_num])  
            except Exception as e:  
                pass
            #except OSError as e:
            #    print("OSErrroBad img most likely", e, os.path.join(path,img))
            #except Exception as e:
            #    print("general exception", e, os.path.join(path,img))

create_training_data()

print(len(training_data))
random.shuffle(training_data)

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


#print(X[0].reshape(-1, IMG_SIZE, IMG_SIZE, 1))

X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)
y = np.array(y)

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())  # this converts our 3D feature maps to 1D feature vectors

model.add(Dense(64))

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

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

model.fit(X, y, batch_size=16, epochs=20, validation_split=0.3)

model.save('cat1_2.model') 

我的想法是,除了使用第 3 个类别的图像创建第 3 个文件夹之外:

1- 改为CATEGORIES = ["Cat1","Cat2","Cat3"]

2- 将model.add(Dense(1)) 更改为model.add(Dense(3))

3- 将model.add(Activation('sigmoid')) 更改为model.add(Activation('softmax'))

4- 从loss='binary_crossentropy' 更改为loss='sparse_categorical_crossentropy'

不幸的是,尽管模型似乎收敛到了非常好的准确度(高于 0.95),但它总是可以预测

[[0. 0. 1.]]

不管输入。

我错过了什么?

【问题讨论】:

    标签: python image-classification


    【解决方案1】:

    解决了....新手错误....错误实际上是在预测调用中。基本上我是在没有缩放 01 的情况下将图像传递给模型(即跳水 255)..一旦我这样做了,预测就开始有意义了......

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      相关资源
      最近更新 更多