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)
python类decode_predictions()的实例源码
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)
)
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
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)
def plot(self, vis_func, img_path, label_list, figsize):
img = utils.load_img(img_path, target_size=self.img_shape_)
img = img[:,:,:3]
predictions = self.model_.predict(img2tensor(img, self.img_shape_))
predictions = softmax(predictions)
if not label_list:
prediction_text = decode_predictions(predictions)[0]
def _plot(label_id):
label_id = int(label_id)
text_label = get_pred_text_label(label_id)
label_proba = np.round(predictions[0,label_id], 4)
heatmap = vis_func(img, label_id)
for p in prediction_text:
print(p[1:])
plt.figure(figsize=figsize)
plt.subplot(1,2,1)
plt.title('label:%s\nscore:%s'%(text_label,label_proba))
plt.imshow(overlay(heatmap, img))
plt.subplot(1,2,2)
plt.imshow(img)
plt.show()
else:
def _plot(label_id):
print(pd.DataFrame(predictions, columns=label_list))
label_id = int(label_id)
text_label = label_list[label_id]
label_proba = np.round(predictions[0,label_id], 4)
heatmap = vis_func(img,label_id)
plt.figure(figsize=figsize)
plt.subplot(1,2,1)
plt.title('label:%s\nscore:%s'%(text_label,label_proba))
plt.imshow(overlay(heatmap, img))
plt.subplot(1,2,2)
plt.imshow(img)
plt.show()
return interact(_plot, label_id='1')
def show_predictions(model, img):
preds = model.predict(img)
print('{}'.format(model.metrics_names[1]), 'Prediction: ', decode_predictions(preds))
return