Python keras.applications.imagenet_utils.decode_predictions() Examples
The following are 19
code examples of keras.applications.imagenet_utils.decode_predictions().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
keras.applications.imagenet_utils
, or try the search function
.
Example #1
Source File: model.py From picasso with Eclipse Public License 1.0 | 6 votes |
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
Example #2
Source File: test_imagenet.py From dfc2019 with MIT License | 6 votes |
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()
Example #3
Source File: test_imagenet.py From SpaceNet_Off_Nadir_Solutions with Apache License 2.0 | 6 votes |
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()
Example #4
Source File: named_image.py From spark-deep-learning with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: lambda_code.py From keras-lambda with MIT License | 5 votes |
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)
Example #6
Source File: keras_server.py From Mastering-OpenCV-4-with-Python with MIT License | 5 votes |
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)
Example #7
Source File: run_keras_server.py From simple-keras-rest-api with MIT License | 5 votes |
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
Example #8
Source File: test.py From keras-squeezenet with MIT License | 5 votes |
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)
Example #9
Source File: test.py From keras-squeezenet with MIT License | 5 votes |
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)
Example #10
Source File: imagenet_utils_test.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
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)))
Example #11
Source File: imagenet_utils_test.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
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)))
Example #12
Source File: imagenet_utils_test.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
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)))
Example #13
Source File: imagenet_utils_test.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
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)))
Example #14
Source File: imagenet_utils_test.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
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)))
Example #15
Source File: imagenet_utils_test.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
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)))
Example #16
Source File: imagenet_utils_test.py From DeepLearning_Wavelet-LSTM with MIT License | 5 votes |
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)))
Example #17
Source File: keras_model_visualization.py From PaddlePaddle_code with Apache License 2.0 | 5 votes |
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
Example #18
Source File: lambda_function.py From keras-lambda with MIT License | 4 votes |
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
Example #19
Source File: ml_model.py From machine_feeling with MIT License | 4 votes |
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