當前位置: 首頁>>代碼示例>>Python>>正文


Python imagenet_utils.decode_predictions方法代碼示例

本文整理匯總了Python中keras.applications.imagenet_utils.decode_predictions方法的典型用法代碼示例。如果您正苦於以下問題:Python imagenet_utils.decode_predictions方法的具體用法?Python imagenet_utils.decode_predictions怎麽用?Python imagenet_utils.decode_predictions使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在keras.applications.imagenet_utils的用法示例。


在下文中一共展示了imagenet_utils.decode_predictions方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_model

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def test_model(model, preprocessing_func, sample, ground_truth):

    x = preprocessing_func(sample)
    x = np.expand_dims(x, 0)
    y = model.predict(x)

    print('[INFO]', decode_predictions(y))

    pred = get_top(y)
    if is_equal(pred, ground_truth):
        print('[INFO] Test passed...\n')
    else:
        print('[WARN] TEST FAILED...')
        print('[WARN] PREDICTION', pred)
        print('[WARN] GROUND TRUTH', ground_truth)
        print() 
開發者ID:SpaceNetChallenge,項目名稱:SpaceNet_Off_Nadir_Solutions,代碼行數:18,代碼來源:test_imagenet.py

示例2: _decodeOutputAsPredictions

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def _decodeOutputAsPredictions(self, df):
        # If we start having different weights than imagenet, we'll need to
        # move this logic to individual model building in NamedImageTransformer.
        # Also, we could put the computation directly in the main computation
        # graph or use a scala UDF for potentially better performance.
        topK = self.getOrDefault(self.topK)

        def decode(predictions):
            pred_arr = np.expand_dims(np.array(predictions), axis=0)
            decoded = decode_predictions(pred_arr, top=topK)[0]
            # convert numpy dtypes to python native types
            return [(t[0], t[1], t[2].item()) for t in decoded]

        decodedSchema = ArrayType(
            StructType([
                StructField("class", StringType(), False),
                StructField("description", StringType(), False),
                StructField("probability", FloatType(), False)
            ]))
        decodeUDF = udf(decode, decodedSchema)
        interim_output = self._getIntermediateOutputCol()
        return df \
            .withColumn(self.getOutputCol(), decodeUDF(df[interim_output])) \
            .drop(interim_output) 
開發者ID:databricks,項目名稱:spark-deep-learning,代碼行數:26,代碼來源:named_image.py

示例3: decode_prob

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def decode_prob(self, class_probabilities):
        r = imagenet_utils.decode_predictions(class_probabilities,
                                              top=self.top_probs)
        results = [
            [{'code': entry[0],
              'name': entry[1],
              'prob': '{:.3f}'.format(entry[2])}
             for entry in row]
            for row in r
        ]
        classes = imagenet_utils.CLASS_INDEX
        class_keys = list(classes.keys())
        class_values = list(classes.values())

        for result in results:
            for entry in result:
                entry['index'] = int(
                    class_keys[class_values.index([entry['code'],
                                                   entry['name']])])
        return results 
開發者ID:merantix,項目名稱:picasso,代碼行數:22,代碼來源:model.py

示例4: load_fine_tune_googlenet_v3

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def load_fine_tune_googlenet_v3(img):
    # 加載fine-tuning googlenet v3模型,並做預測
    model = InceptionV3(include_top=True, weights='imagenet')
    model.summary()
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = model.predict(x)
    print('Predicted:', decode_predictions(preds))
    plt.subplot(212)
    plt.plot(preds.ravel())
    plt.show()
    return model, x 
開發者ID:huxiaoman7,項目名稱:PaddlePaddle_code,代碼行數:15,代碼來源:keras_model_visualization.py

示例5: test_decode_predictions

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def test_decode_predictions():
    x = np.zeros((2, 1000))
    x[0, 372] = 1.0
    x[1, 549] = 1.0
    outs = utils.decode_predictions(x, top=1)
    scores = [out[0][2] for out in outs]
    assert scores[0] == scores[1]

    # the numbers of columns and ImageNet classes are not identical.
    with pytest.raises(ValueError):
        utils.decode_predictions(np.ones((2, 100))) 
開發者ID:hello-sea,項目名稱:DeepLearning_Wavelet-LSTM,代碼行數:13,代碼來源:imagenet_utils_test.py

示例6: testTFwPrediction

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def testTFwPrediction(self):
        keras.backend.set_image_dim_ordering('tf')
        model = SqueezeNet()
        img = image.load_img('images/cat.jpeg', target_size=(227, 227))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)
        preds = model.predict(x)
        decoded_preds = decode_predictions(preds)
        #print('Predicted:', decoded_preds)
        self.assertIn(decoded_preds[0][0][1], 'tabby')
        #self.assertAlmostEqual(decode_predictions(preds)[0][0][2], 0.82134342) 
開發者ID:rcmalli,項目名稱:keras-squeezenet,代碼行數:14,代碼來源:test.py

示例7: testTHPrediction

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def testTHPrediction(self):
        keras.backend.set_image_dim_ordering('th')
        model = SqueezeNet()
        img = image.load_img('images/cat.jpeg', target_size=(227, 227))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)
        preds = model.predict(x)
        decoded_preds = decode_predictions(preds)
        #print('Predicted:', decoded_preds)
        self.assertIn(decoded_preds[0][0][1], 'tabby')
        #self.assertAlmostEqual(decode_predictions(preds)[0][0][2], 0.82134342) 
開發者ID:rcmalli,項目名稱:keras-squeezenet,代碼行數:14,代碼來源:test.py

示例8: predict

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def predict():
	# initialize the data dictionary that will be returned from the
	# view
	data = {"success": False}

	# ensure an image was properly uploaded to our endpoint
	if flask.request.method == "POST":
		if flask.request.files.get("image"):
			# read the image in PIL format
			image = flask.request.files["image"].read()
			image = Image.open(io.BytesIO(image))

			# preprocess the image and prepare it for classification
			image = prepare_image(image, target=(224, 224))

			# classify the input image and then initialize the list
			# of predictions to return to the client
			preds = model.predict(image)
			results = imagenet_utils.decode_predictions(preds)
			data["predictions"] = []

			# loop over the results and add them to the list of
			# returned predictions
			for (imagenetID, label, prob) in results[0]:
				r = {"label": label, "probability": float(prob)}
				data["predictions"].append(r)

			# indicate that the request was a success
			data["success"] = True

	# return the data dictionary as a JSON response
	return flask.jsonify(data)

# if this is the main thread of execution first load the model and
# then start the server 
開發者ID:jrosebr1,項目名稱:simple-keras-rest-api,代碼行數:37,代碼來源:run_keras_server.py

示例9: predict

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def predict():
    # Initialize result:
    result = {"success": False}

    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            # Read input image in PIL format:
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            # Pre-process the image to be classified:
            image = preprocessing_image(image, target=(224, 224))

            # Classify the input image:
            with graph.as_default():
                predictions = model.predict(image)
            results = imagenet_utils.decode_predictions(predictions)
            result["predictions"] = []

            # Add the predictions to the result:
            for (imagenet_id, label, prob) in results[0]:
                r = {"label": label, "probability": float(prob)}
                result["predictions"].append(r)

            # At this point we can say that the request was dispatched successfully:
            result["success"] = True

    # Return result as a JSON response:
    return flask.jsonify(result) 
開發者ID:PacktPublishing,項目名稱:Mastering-OpenCV-4-with-Python,代碼行數:31,代碼來源:keras_server.py

示例10: lambda_handler

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def lambda_handler(event, context):
    
    url = ''
    try:
        # API Gateway GET method
        if event['httpMethod'] == 'GET':
            url = event['queryStringParameters']['url']
        # API Gateway POST method
        elif event['httpMethod'] == 'POST':
            data = json.loads(event['body'])
            url = data['url']
    except KeyError:
        # direct invocation
        url = event['url']
    
    handler_start_time = time.time()
    start_time = time.time()
    x = download_image(url)
    #requires scipy lib, can't use it since that puts us over 50MB zip limit for Lambda
    #x = preprocess_input(x) 
    preds = model.predict(x)
    end_time = time.time()
    print('Predicted:', decode_predictions(preds))
    h_time = end_time - handler_start_time
    p_time = end_time - start_time
    print("handler:", h_time ,"pred time:", p_time)
    return "%s,%s" % (h_time, p_time) 
開發者ID:sunilmallya,項目名稱:keras-lambda,代碼行數:29,代碼來源:lambda_code.py

示例11: predict

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def predict(self, raw_input):
        try:
            if not self.pretrained:

                pred = self.model.predict(raw_input)

                # get the list of labels
                labels = listdir('data/train')

                # remove hidden files from the labels list
                while labels[0].startswith('.'):
                    labels.pop(0)

                # initialize a dictionary for storing label to probability mappings
                pmap = dict()
                for i in range(len(labels)):
                    pmap[labels[i]] = list(pred[0])[i]
                
                self.prediction = pmap
                print('[+] Prediction successfully completed')

            else:
                # preprocess the image for the pretrained net
                image = preprocess_input(raw_input)

                # make predictions
                prediction = self.model.predict(image)
                preds = imagenet_utils.decode_predictions(prediction)

                # create a dictionary to store the top five predictions with their probabilities
                p = dict()
                for (i, (imagenetID, label, prob)) in enumerate(preds[0]):
                    p[label] = prob

                self.prediction = p
                print('[+] Prediction successfully completed')

        except ValueError as err:
            print('[-] Prediction failed, please check the input shape:')
            print(err)

            

    # method for evaluating the model 
開發者ID:powerhouseofthecell,項目名稱:machine_feeling,代碼行數:46,代碼來源:ml_model.py

示例12: lambda_handler

# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import decode_predictions [as 別名]
def lambda_handler(event, context):
    
    url = ''
    try:
        # API Gateway GET method
        if event['httpMethod'] == 'GET':
            url = event['queryStringParameters']['url']
        # API Gateway POST method
        elif event['httpMethod'] == 'POST':
            data = json.loads(event['body'])
            url = data['url']
    except KeyError:
        # direct invocation
        url = event['url']
    
    handler_start_time = time.time()
    start_time = time.time()
    x = download_image(url)
    #requires scipy lib, can't use it since that puts us over 50MB zip limit for Lambda
    #x = preprocess_input(x) 
    preds = model.predict(x)
    end_time = time.time()
    # [[(u'n02088364', u'beagle', 0.94316888), (u'n04254680', u'soccer_ball', 0.017797621),...]]
    pred_lst = decode_predictions(preds)
    outputs = []
    for _id, lbl, prob in pred_lst[0]:
        ele = {}
        ele["label"] = lbl
        ele["prob"] = str(prob)
        outputs.append(ele)
        
    print('Predicted:', outputs)
    h_time = end_time - handler_start_time
    p_time = end_time - start_time
    print("handler:", h_time ,"pred time:", p_time)
    #return "%s,%s" % (h_time, p_time) 
    out = {
            "headers": {
                "content-type": "application/json",
                "Access-Control-Allow-Origin": "*"
                },
            "body": '{"labels":"%s", "handler_time": "%s", "prediction_time": "%s"}' % (json.dumps(outputs), h_time, p_time),  
            "statusCode": 200
          }
    return out 
開發者ID:sunilmallya,項目名稱:keras-lambda,代碼行數:47,代碼來源:lambda_function.py


注:本文中的keras.applications.imagenet_utils.decode_predictions方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。