「deeplearning」カテゴリーアーカイブ

Clarifai使い方

2017年11月現在のClarifai使用方法

用意するもの

3つのファイルを用意してサーバにアップロードしてください

  • WEB表示用のHTMLファイル
  • 実行用のjsファイル
  • 解析用画像

このほかにCLIENTキーが必要とかなんとか,,(詳細はここ)これなしでも動いてるけど,,,

HTMLファイル

<!doctype html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>Clarifaiサンプル</title>
  </head>
  <body>
    <h1>Clarifaiサンプル</h1>
<script type="text/javascript" src="https://sdk.clarifai.com/js/clarifai-latest.js"></script>
<script type="text/javascript" src="const.js"></script>


  </body>
</html>

 実行用のjsファイル

// instantiate a new Clarifai app passing in your api key.
const app = new Clarifai.App({
 apiKey: 'Your API KEY'
});

// predict the contents of an image by passing in a url
app.models.predict("e0be3b9d6a454f0493ac3a30784001ff",'YOUR IMAGE URL').then(
  function(response) {
    console.log(response);
  },
  function(err) {
    console.error(err);
  }
);

Your API KEYの部分には自分の作成したAPIキーを

YOUR IMAGE URLには自分のURLを

画像

画像を同じサーバに保存して実行

実行結果はWEBのコンソールに表示されます

Denim Jacket 91.7%

Peacoat 80.8%という結果が表示されています

このデータを自動的にWEBに表示するには

ObjectデータをJsonで解析する方法と,InnetHTMLあたりで実行できるかも

参考ページ

自己画像学習

https://www.tensorflow.org/tutorials/deep_cnn

 

をやるのに,

 

が参考になる

 

 

とりあえず,学習だけやってみる

~/projects/tensorflow/tensorflow/models/tutorials/image/cifar10 $ sudo python3 cifar10_train.py
>> Downloading cifar-10-binary.tar.gz 100.0%
Successfully downloaded cifar-10-binary.tar.gz 170052171 bytes.

160MBくらいある

 

Raspi でDL

この記事のゾウの認識のところまでやってみます

適当なディレクトリに移動し,

git clone https://github.com/fchollet/deep-learning-models.git

deep-learning-models ディレクトリができるので,そこへ移動

cd deep-learning-models

して

ls

で inception_v3.pyがあることを確認

sudo python3 inception_v3.py

エラーが出る

ImportError: No module named ‘scipy’

sudo pip3 install scipy

1時間くらい?インストールして

sudo python3 inception_v3.py

を実行

なんかダウンロードはじまる downloading data from https://github*******

7分くらいでelephant.jpgが無いってでる

リンク先の画像をinception_v3.pyと同じディレクトリに保存し,

sudo python3 inception_v3.py

実行するもまたエラー

lsするとlephant.jpeg
になってた

mv elephant.jpeg elephant.jpg

で拡張子を変更

sudo python3 inception_v3.py

‘n01871265’, ‘tusker’, 0.63436967), (‘n02504458’, ‘African_elephant’, 0.2854473), (‘n02504013’, ‘Indian_elephant’, 0.033294968)
認識成功

おつかれさまでした

服の解析など(メモ)

時間があるときにまとめるよてい

ファッションデータセット

https://sites.google.com/site/fashionparsing/dataset

東北大の研究

http://vision.is.tohoku.ac.jp/~kyamagu/ja/research/clothing_parsing/

 

これはなんだろう?

https://github.com/applebym/project5_final

 

ファッションアイテム検索(コードつき?)

http://gigazine.net/news/20161027-fashion-snap-detection-retrieval/

 

??これは見つけない方が良かったのか,,,まんま?

https://github.com/rivukhoda/claridrobe

ん?JSでAPIでつかえるっぽい.ブラウザで出来てしまう?

https://developer.clarifai.com/quick-start/

クライアントIDとパスをパーミッションかけたJSファイルにして,読まれないようにする必要があります.

 

Tensorflowでopencv

opencvはいってなかった

 

http://qiita.com/suppy193/items/91609e75789e9f458c39

でOpencv2.7いれて

http://arkouji.cocolog-nifty.com/blog/2016/08/tensorflowraspb.html

でclassfy_image.pyがない(そもそもmodelsディレクトリがない)ので、TensorFlowのソースみて

nano classify_image.py

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Simple image classification with Inception.

Run image classification with Inception trained on ImageNet 2012 Challenge data
set.

This program creates a graph from a saved GraphDef protocol buffer,
and runs inference on an input JPEG image. It outputs human readable
strings of the top 5 predictions along with their probabilities.

Change the --image_file argument to any jpg image to compute a
classification of that image.

Please see the tutorial and website for a detailed description of how
to use this script to perform image recognition.

https://tensorflow.org/tutorials/image_recognition/
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os.path
import re
import sys
import tarfile

import numpy as np
from six.moves import urllib
import tensorflow as tf

FLAGS = None

# pylint: disable=line-too-long
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
# pylint: enable=line-too-long


class NodeLookup(object):
  """Converts integer node ID's to human readable labels."""

  def __init__(self,
               label_lookup_path=None,
               uid_lookup_path=None):
    if not label_lookup_path:
      label_lookup_path = os.path.join(
          FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
    if not uid_lookup_path:
      uid_lookup_path = os.path.join(
          FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')
    self.node_lookup = self.load(label_lookup_path, uid_lookup_path)

  def load(self, label_lookup_path, uid_lookup_path):
    """Loads a human readable English name for each softmax node.

    Args:
      label_lookup_path: string UID to integer node ID.
      uid_lookup_path: string UID to human-readable string.

    Returns:
      dict from integer node ID to human-readable string.
    """
    if not tf.gfile.Exists(uid_lookup_path):
      tf.logging.fatal('File does not exist %s', uid_lookup_path)
    if not tf.gfile.Exists(label_lookup_path):
      tf.logging.fatal('File does not exist %s', label_lookup_path)

    # Loads mapping from string UID to human-readable string
    proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
    uid_to_human = {}
    p = re.compile(r'[n\d]*[ \S,]*')
    for line in proto_as_ascii_lines:
      parsed_items = p.findall(line)
      uid = parsed_items[0]
      human_string = parsed_items[2]
      uid_to_human[uid] = human_string

    # Loads mapping from string UID to integer node ID.
    node_id_to_uid = {}
    proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
    for line in proto_as_ascii:
      if line.startswith('  target_class:'):
        target_class = int(line.split(': ')[1])
      if line.startswith('  target_class_string:'):
        target_class_string = line.split(': ')[1]
        node_id_to_uid[target_class] = target_class_string[1:-2]

    # Loads the final mapping of integer node ID to human-readable string
    node_id_to_name = {}
    for key, val in node_id_to_uid.items():
      if val not in uid_to_human:
        tf.logging.fatal('Failed to locate: %s', val)
      name = uid_to_human[val]
      node_id_to_name[key] = name

    return node_id_to_name

  def id_to_string(self, node_id):
    if node_id not in self.node_lookup:
      return ''
    return self.node_lookup[node_id]


def create_graph():
  """Creates a graph from saved GraphDef file and returns a saver."""
  # Creates graph from saved graph_def.pb.
  with tf.gfile.FastGFile(os.path.join(
      FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')


def run_inference_on_image(image):
  """Runs inference on an image.

  Args:
    image: Image file name.

  Returns:
    Nothing
  """
  if not tf.gfile.Exists(image):
    tf.logging.fatal('File does not exist %s', image)
  image_data = tf.gfile.FastGFile(image, 'rb').read()

  # Creates graph from saved GraphDef.
  create_graph()

  with tf.Session() as sess:
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
    predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg/contents:0': image_data})
    predictions = np.squeeze(predictions)

    # Creates node ID --> English string lookup.
    node_lookup = NodeLookup()

    top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
    for node_id in top_k:
      human_string = node_lookup.id_to_string(node_id)
      score = predictions[node_id]
      print('%s (score = %.5f)' % (human_string, score))


def maybe_download_and_extract():
  """Download and extract model tar file."""
  dest_directory = FLAGS.model_dir
  if not os.path.exists(dest_directory):
    os.makedirs(dest_directory)
  filename = DATA_URL.split('/')[-1]
  filepath = os.path.join(dest_directory, filename)
  if not os.path.exists(filepath):
    def _progress(count, block_size, total_size):
      sys.stdout.write('\r>> Downloading %s %.1f%%' % (
          filename, float(count * block_size) / float(total_size) * 100.0))
      sys.stdout.flush()
    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
    print()
    statinfo = os.stat(filepath)
    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
  tarfile.open(filepath, 'r:gz').extractall(dest_directory)


def main(_):
  maybe_download_and_extract()
  image = (FLAGS.image_file if FLAGS.image_file else
           os.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))
  run_inference_on_image(image)


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  # classify_image_graph_def.pb:
  #   Binary representation of the GraphDef protocol buffer.
  # imagenet_synset_to_human_label_map.txt:
  #   Map from synset ID to a human readable string.
  # imagenet_2012_challenge_label_map_proto.pbtxt:
  #   Text representation of a protocol buffer mapping a label to synset ID.
  parser.add_argument(
      '--model_dir',
      type=str,
      default='/tmp/imagenet',
      help="""\
      Path to classify_image_graph_def.pb,
      imagenet_synset_to_human_label_map.txt, and
      imagenet_2012_challenge_label_map_proto.pbtxt.\
      """
  )
  parser.add_argument(
      '--image_file',
      type=str,
      default='',
      help='Absolute path to image file.'
  )
  parser.add_argument(
      '--num_top_predictions',
      type=int,
      default=5,
      help='Display this many predictions.'
  )
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

で、

python classify_image.py

やって

giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca (score = 0.89107)
indri, indris, Indri indri, Indri brevicaudatus (score = 0.00779)
lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens (score = 0.00296)
custard apple (score = 0.00147)
earthstar (score = 0.00117)

パンダ89% インドリ(サル)0.7%、レッサーパンダ0.2%、custard apple(リンゴの仲間?)0.14%、アーススターって謎の花0.11% じゃないって出る

 

自分で作る参考

http://arkouji.cocolog-nifty.com/blog/2016/08/tensorflow-76e9.html

このサイトとそこにのってる参考サイト

http://qiita.com/khayate/items/bb7c61f447b4c579ddd1

 

わかりやすい解説

WEBアプリ化する

 

いろいろ入れるの

http://qiita.com/PonDad/items/9fbdf4d694f825dd1b6e

deep learning そのご

面倒なので、最近なにかと話題のTesor Flowにしてみる

インストはこっち

http://tech.mof-mof.co.jp/blog/tensorflow-tutorial.html

参考

https://github.com/samjabrahams/tensorflow-on-raspberry-pi

追記 インストはできったっぽい

動作確認はここ

http://qiita.com/mix_dvd/items/6b38859148a988c3fe06

エラー出たので

sudo pip install –upgrade html5lib==1.0b8

したら、またエラー

sudo pip install -U pandas

した

python mnist_softmax.py

やって、

Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
0.9193

でた。たぶんこれでOK

ーーおまけーー

ブラウザでできるとかなんとk

http://qiita.com/payashim/items/d4fe5227b21a5215e78b

 

Chainerも考えたけど、まぁ簡単そうなのから。

 

deep celief SDK

raspi de caffe

make runtest

.build_release/tools/caffe: error while loading shared libraries: libglog.so.0: cannot open shared object file: No such file or directory

が出る

対策?

sudo nano /etc/ld.so.conf

して、

末尾に

/usr/local/lib
/usr/lib

を追加

sudo ldconfig

する。

おわり

 

runtestで


[  FAILED  ] SGDSolverTest/0.TestSnapshotShare, where TypeParam = caffe::CPUDevice&lt;float&gt;

出るので

cd /etc

sudo nano profile

export CUDA_VISIBLE_DEVICES=0
export MKL_CBWR=AUTO