как получить вероятности обеих категорий вместо одной - PullRequest
0 голосов
/ 08 марта 2020

'' 'import numpy в качестве np # для преобразования изображений в массивы import matplotlib.pyplot в виде plt # для построения графиков значений import os # Использование файлов, сохраненных в компьютере, импорт cv2 # компьютерное зрение для изменения изображений из tqdm import tqdm #progress бар для python DATADIR = "C: / Пользователи / Srujan / Рабочий стол / Животные / PetImages" CATEGORIES = ["Dog", "Cat"]

for category in CATEGORIES:  #dogs and cats
    path = os.path.join(DATADIR,category)  # create path to dogs and cats folder
    for img in os.listdir(path):  # iterate over each image in dogs and cats folder
        img_array = cv2.imread(os.path.join(path,img) ,cv2.IMREAD_GRAYSCALE)  # convert to array
        plt.imshow(img_array, cmap='gray')  # graph it 
        plt.show()  # display the graph

        break  
    break  

IMG_SIZE = 100

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:  #  dogs and cats

        path = os.path.join(DATADIR,category)  # create path to dogs and cats
        class_num = CATEGORIES.index(category)  # get the classification  (0 or a 1). 0=dog 1=cat

        for img in tqdm(os.listdir(path)):  # iterate over each image per dogs and cats
            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])  # add this to our training_data
            except Exception as e: 
                pass

create_training_data()

print(len(training_data))

import random

random.shuffle(training_data) #Shuffling the data in order to get better accuracy
for sample in training_data[:10]: #confirming if the randomisation has been done
    print(sample[1])

X = []
y = []

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

X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1) #Since list datatype cannot be accepted into network input

import pickle

pickle_out = open("X.pickle","wb")
pickle.dump(X, pickle_out)
pickle_out.close()

pickle_out = open("y.pickle","wb")
pickle.dump(y, pickle_out)
pickle_out.close()              

import tensorflow as tf
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D

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(64, (3, 3), input_shape=X.shape[1:]))  #CONV layer 1
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))                           #CONV layer 2
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))                           #CONV layer 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 before passing it to output layer(dense)
model.add(Dense(1))                                     #output layer
model.add(Activation('sigmoid'))

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

y=np.array(y)
hist= model.fit(X, y, batch_size=32, epochs=3, validation_split=0.3)

# Testing the model.......
import cv2
import tensorflow as tf
import os
import matplotlib.pyplot as plt
import numpy as np

CATEGORIES = [" Cats", "Dogs:"]

def prepare(filepath):
    IMG_SIZE = 100
    img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
    img_array=img_array/255            
    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) 
    return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)

model = tf.keras.models.load_model("64x3-CNN.model_2")
DIR="C:/Users/Srujan/Desktop/44.jpeg"
path = os.path.join(DIR)
img_array = cv2.imread(os.path.join(path) ,cv2.IMREAD_GRAYSCALE)  # convert to array
plt.imshow(img_array, cmap='gray')  # graph it 
plt.show()
prediction = model.predict(np.array(prepare(path)))
print (prediction)'''
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...