In [ ]:
# windows only hack for graphviz path
import os
for path in os.environ['PATH'].split(os.pathsep):
if path.endswith("Library\\bin"):
os.environ['PATH']+=os.pathsep+os.path.join(path, 'graphviz')
In [ ]:
# 設定環境變數來控制 keras, theano
os.environ['KERAS_BACKEND']="tensorflow"
#os.environ['THEANO_FLAGS']="floatX=float32, device=cuda"
In [ ]:
import keras
from keras.models import Sequential
from PIL import Image
import numpy as np
In [ ]:
import keras.backend as K
# 設定 channels_first 或 channels_last
K.set_image_data_format('channels_last')
In [ ]:
pretrained = keras.applications.xception.Xception()
In [ ]:
from IPython.display import SVG, display
from keras.utils.vis_utils import model_to_dot
SVG(model_to_dot(pretrained, show_shapes=True).create(prog='dot', format='svg'))
In [ ]:
from keras.applications import imagenet_utils
In [ ]:
# 讀取圖片,使用 image.load_img
from keras.preprocessing import image
from glob import glob
imgs = []
files = list(glob('ILSVRC2012_img_val/ILSVRC2012_val_*.JPEG'))
for fn in files:
img = image.load_img(fn, target_size=(299,299))
imgs.append(np.array(img))
imgs = np.array(imgs)
In [ ]:
# 使用 xception 的 preprocess
from keras.applications.xception import preprocess_input
p_imgs = preprocess_input(np.float32(imgs))
del imgs
In [ ]:
# 如果 channel_first 可以調整
#import numpy as np
#p_imgs = np.moveaxis(p_imgs, 3, 1)
In [ ]:
# 實際
predictions = pretrained.predict(p_imgs)
In [ ]:
# 對應編碼
results = imagenet_utils.decode_predictions(predictions)
In [ ]:
from IPython.display import Image, HTML, display
for fn, res in zip(files[:100], results[:100]):
res_text = "".join("<li>{:05.2f}% : {}</li>".format(x[2]*100, x[1]) for x in res)
display(HTML("""
<table><tr>
<td><img width=200 src="{}" /></td>
<td><ul>{}</ul></td>
</tr>
</table>
""".format(fn, res_text)))