Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何用图像测试CNN模型? 介绍/设置_Python 3.x_Tensorflow_Keras_Jupyter Notebook_Conv Neural Network - Fatal编程技术网

Python 3.x 如何用图像测试CNN模型? 介绍/设置

Python 3.x 如何用图像测试CNN模型? 介绍/设置,python-3.x,tensorflow,keras,jupyter-notebook,conv-neural-network,Python 3.x,Tensorflow,Keras,Jupyter Notebook,Conv Neural Network,我是编程新手,我从一个教程中制作了我的第一个CNN模型。 我已经在C:\Users\labadmin中设置了jupyter/tensorflow/keras 我所理解的是,为了实现用于测试和培训的数据,我只需要输入来自labadmin的路径 因为我不确定是什么导致了错误,所以我粘贴了整个代码和错误,我认为这是因为系统没有获得数据 包含以下数据设置的文件夹: labadmin有一个名为data的文件夹,其中包含两个文件夹 培训和测试 猫图像和狗图像在这两个文件夹中都被洗牌。每个文件夹中有10000

我是编程新手,我从一个教程中制作了我的第一个CNN模型。 我已经在C:\Users\labadmin中设置了jupyter/tensorflow/keras

我所理解的是,为了实现用于测试和培训的数据,我只需要输入来自labadmin的路径

因为我不确定是什么导致了错误,所以我粘贴了整个代码和错误,我认为这是因为系统没有获得数据

包含以下数据设置的文件夹:

labadmin有一个名为data的文件夹,其中包含两个文件夹 培训测试

猫图像和狗图像在这两个文件夹中都被洗牌。每个文件夹中有10000张图片,因此应该有足够的:

这篇教程教你。 1.如何创建模型 2.定义您的标签 3.创建您的培训数据 4.创建和构建层 5.创建您的测试数据 6.(据我所知)我创建的代码的最后一部分是
验证我的模型

这是密码 第二个出现在:print('model loaded!')
如果os.path.exists(“{}1st:警告消息很清楚,跟随它,警告就会消失。但是不要担心,如果不这样做,您仍然可以正常运行代码

第二:是的。如果未打印出
模型加载!
,则表示模型未加载,请检查模型文件的路径

第三:要在培训后保存模型,请使用
model.save(“PATH-To-save”)
。然后您可以通过
model.load(“PATH-To-model”)
加载它

对于预测,请使用
model.predict({'input':X})
。请参见此处

第二项问题
  • 要保存和加载模型,请使用
  • 请记住,您应该具有模型文件的扩展名,即
    .tflearn

  • 要进行预测,需要加载图像,就像加载图像进行训练一样

  • 谢谢你的快速回复!你能看看我发布的2.答案吗?我已经更新了答案。顺便说一下,你应该通过编辑主要问题将第二个问题从答案转移到主要问题。
    
        import cv2
        import numpy as np
        import os
        from random import shuffle
        from tqdm import tqdm
    
        TRAIN_DIR = "data\\training"
        TEST_DIR = "data\\test"
        IMG_SIZE = 50
    
        LR = 1e-3
    
        MODEL_NAME = 'dogvscats-{}-{}.model'.format(LR, '2cov-basic1')
    
        def label_img(img):
            word_label = img.split('.')[-3]
            if word_label == 'cat': return [1,0]
            elif word_label == 'dog': return [0,1]
    
        def creat_train_data():
            training_data = []
            for img in tqdm(os.listdir(TRAIN_DIR)):
                label = label_img(img)
                path = os.path.join(TRAIN_DIR,img)
                img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_SIZE,IMG_SIZE))
                training_data.append([np.array(img), np.array(label)])
            shuffle(training_data)
            np.save('training.npy', training_data) #save file
            return training_data
    
        import tflearn
        from tflearn.layers.conv import conv_2d, max_pool_2d
        from tflearn.layers.core import input_data, dropout, fully_connected
        from tflearn.layers.estimator import regression
    
    
    
        # Building convolutional convnet
        convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')
        # http://tflearn.org/layers/conv/
        # http://tflearn.org/activations/
        convnet = conv_2d(convnet, 32, 2, activation='relu')
        convnet = max_pool_2d(convnet, 2)
    
        convnet = conv_2d(convnet, 64, 2, activation='relu')
        convnet = max_pool_2d(convnet, 2)
    
        convnet = fully_connected(convnet, 1024, activation='relu')
        convnet = dropout(convnet, 0.8)
    
        #OUTPUT layer
        convnet = fully_connected(convnet, 2, activation='softmax')
        convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')
    
        model = tflearn.DNN(convnet, tensorboard_dir='log')
    
        def process_test_data():
            testing_data = []
            for img in tqdm(os.listdir(TEST_DIR)):
                path = os.path.join(TEST_DIR,img)
                img_num = img.split ('.')[0]  #ID of pic=img_num
                img = cv2.resize(cv2-imread(path, cv2.IMREAD_GRAYSCALE),  (IMG_SIZE,IMG_SIZE))
                testing_data.append([np.array(img), img_num])
    
            np.save('test_data.npy', testing_data)
            return testing_data
    
        train_data = creat_train_data()
        #if you already have train data:
        #train_data = np.load('train_data.npy')
        100%|███████████████████████████████████████████████████████████████████████████| 21756/21756 [02:39<00:00, 136.07it/s]
    
        if os.path.exists('{}<.meta'.format(MODEL_NAME)):
            model.load(MODEL_NAME)
            print('model loaded!')
    
        train = train_data[:-500]
        test = train_data[:-500]
    
        X = np.array([i[0] for i in train]).reshape( -1, IMG_SIZE, IMG_SIZE, 1) #feature set
        Y= [i[1] for i in test] #label
    
        test_x = np.array([i[0] for i in train]).reshape( -1, IMG_SIZE, IMG_SIZE, 1) 
        test_y= [i[1] for i in test] 
    
        model.fit({'input': X}, {'targets': Y}, n_epoch=5, validation_set=({'input': test_x}, {'targets': test_y}), 
            snapshot_step=500, show_metric=True, run_id=MODEL_NAME)
    
        Training Step: 1664  | total loss: 9.55887 | time: 63.467s
        | Adam | epoch: 005 | loss: 9.55887 - acc: 0.5849 -- iter: 21248/21256
        Training Step: 1665  | total loss: 9.71830 | time: 74.722s
        | Adam | epoch: 005 | loss: 9.71830 - acc: 0.5779 | val_loss: 9.81653 - val_acc: 0.5737 -- iter: 21256/21256
        --
    
    
    
        curses is not supported on this machine (please install/reinstall curses for an optimal experience)
        WARNING:tensorflow:From C:\Users\labadmin\Miniconda3\envs\tensorflow\lib\site-packages\tflearn\initializations.py:119: UniformUnitScaling.__init__ (from tensorflow.python.ops.init_ops) is deprecated and will be removed in a future version.
        Instructions for updating:
        Use tf.initializers.variance_scaling instead with distribution=uniform to get equivalent behavior.
        WARNING:tensorflow:From C:\Users\labadmin\Miniconda3\envs\tensorflow\lib\site-packages\tflearn\objectives.py:66: calling reduce_sum (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.
        Instructions for updating:
        keep_dims is deprecated, use keepdims instead
    
    
        if os.path.exists('{}<.meta'.format(MODEL_NAME)):
            model.load(MODEL_NAME)
            print('model loaded!')
    
    
    # Save a model
    model.save('path-to-folder-you-want-to-save/my_model.tflearn')
    # Load a model
    model.load('the-folder-where-your-model-located/my_model.tflearn')
    
    test_image = cv2.resize(cv2.imread("path-of-the-image", cv2.IMREAD_GRAYSCALE),  (IMG_SIZE,IMG_SIZE))
    
    test_image = np.array(test_image).reshape( -1, IMG_SIZE, IMG_SIZE, 1)
    
    prediction = model.predict({'input': test_image })