本文整理汇总了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()
示例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)
示例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
示例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
示例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)))
示例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)
示例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)
示例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
示例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)
示例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)
示例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
示例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