Goalist Developers Blog

センチメント分析用の言葉辞書と遊んでみました。綺麗なグラフをいっぱい描けました。

こんにちは、皆さん。ゴーリストのチナパです!

f:id:c-pattamada:20190228110449p:plain

こういうキャラらしいです。

以前はこちら http://developers.goalist.co.jp/entry/2018/11/16/150000 の辺りに顔の気持ちのを機械学習で当ててみるような記事もありますが、 この度は、顔の気持ちではなく、言葉の気持ちについての記事です。

文書の気持ちを理解するためにはまずは言葉の気持ちを理解しないといけません。今日はセンチメント分析によく利用される「辞書」のデータを調べてみます。

こちらの辞書を使わせていただいてます。

http://www.lr.pi.titech.ac.jp/\~takamura/pubs/pn_ja.dic

同じく英語の辞書もありましたので、そちらもみてみたいです!

http://www.lr.pi.titech.ac.jp/\~takamura/pubs/pn_en.dic

こちらの辞書では言葉、ふりがな、品詞、と 1から-1までの数字があります。 最後の数字の方は「ポジティブ性」や「ネガティブ性」を表そうとしてます。では、中身はどうなのかを調べてみましょう!

まずは開く

必要なインポートは以下

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

先ほどのurlでダウンロードし、パイソンに入れておきましょう。

english_words = pd.read_csv(en_dict_path, sep=':', ['words', 'type', 'score']) jp_words = pd.read_csv(jp_dict_path, sep=':', names=['words', 'reading', 'type', 'score'], header=None)

なんとなく何が入っているのかをみてみましょう print(jp_words.type.unique()) => ['動詞' '形容詞' '名詞' '副詞' '助動詞'] print(jp_words.groupby('type').type.count()) =>

type
副詞      1207
助動詞        2
動詞      4252
名詞     48999
形容詞      665

Pandasの力で割と簡単にできますね。 つまり、圧倒的に名詞が多くて、助動詞は無視できそうですね。

グラッフを書こう!

これで、項目名も設定されます。

sns.set(style='ticks', palette='Set2')
sns.despine()

そして、グラフが綺麗に出るような設定をしました。

では全体のデータの偏りなどをみてみましょう。

sns.distplot(jp_words.score)

f:id:c-pattamada:20190228003327p:plain
日本語単語のネガポジグラフ

おー、意外ですね!全体的に言葉が左に片よっれます。なんででしょうね。英語に比較しましょう!

sns.distplot(englishwords.score)

f:id:c-pattamada:20190228003247p:plain
英語単語のネガポジグラフ

こっちは偏ってないですね。でも非常に真ん中に集まってます。これは、、日本語にはちょっとだけネガティブなニュアンスが入っている言葉が多そうですね。理由を当てようとしますと、この辞書が作られた元のサンプルでのネガティブな気持ちが入っていた日本語文章が多かったとか…しか思い当たらないですね。

さて、最後にもう一つの軸でみたいですね。言葉の種類5つありましたが、それぞれの偏りがどうなのかも調べてみたいです。

軸が分けられたグラフ

つまり、動詞、名詞、などのそれぞれのカテゴリー別にもどんな感じなのかもみてみたいということです。

g = sns.FacetGrid(jp_words, hue='type', height=6)
g.map(plt.hist, 'score')
g.add_legend()
new_labels = ['verb', 'adj', 'adv', 'ex']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

f:id:c-pattamada:20190228014530p:plain
名詞が多い!

うげ、、、名詞が多い!何も見えないですね。下の辺の副詞の気配を薄くしか感じないですね。もちろん、名詞のデータが全部のデータの形に非常に似ています。量が圧倒的なので、当然ですが。仕方ありません、名詞を抜いてグラフをみましょう。

sns.FacetGrid(jp_words[jp_words.type != '名詞'], hue='type', height=6)

上記のコードをこう編集しますとできます。

f:id:c-pattamada:20190228014611p:plain
名詞なしの図

なるほどですね、形容詞がすごく極端になってます。動詞が割と多く、名詞よりちょっと左に肩よっています。

結論

これで、pandasとseabornを利用し、持っているデータをより把握できるようなったかなと思います。この次には「なんで単語が左偏ってる?」みたいな質問も聞いて調べるのが次の段階です。そこでまた新たな質問が出てくるかも知れませんし、プロジェクトに対してこの辞書を本当に活かせる方法はなんでしょうかを判断できるようになりますが、そこは時と場合に応じて違う答えだと思います。旅みたいなものです。「データ」を利用して「情報」を得る「情報」を利用して「決断」をする。それがデータサイエンスの中心だと思います。

一緒に旅しましょう〜

Data Visualization in Python

こんにちは、 ゴーリストのビベックです。
Hello World! This is Vivek from Goalist.

If you want to build a very powerful machine learning algorithm on structured data then the first step to take is to explore the data every which way you can. You draw a Histogram; you draw a Correlogram; you draw Cross Plots, you really want to understand what is in that data what does each variable mean, what's its distribution ideally how was it collected.

Once you have a real rock solid understanding of what's in the data, only then can you smoothly move into creating your machine learning model.

f:id:vivek081166:20190227141304j:plain

In this post, let's go through the different libraries in Python and gain some insight into our data by visualizing it.

Along with me, you may want to try and experiment with the packages that we are about to explore. Use Google Colab to follow along.

Well, you may ask what is Google Colab?

Colaboratory is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud.
With Colaboratory you can write and execute code, save and share your analyses, and access powerful computing resources, all for free from your browser.

Learn more about Google Colab here…

youtu.be

Follow this URL to create your notebook

colab.research.google.com

So let's get started…
We'll be using the following packages to plot different graphs

  • Matplotlib
  • Seaborn
  • Bokeh

Out of these, Matplotlib is the most common charting package, see its documentation for details, and its examples for inspiration.

1) Line Graphs

A line graph is commonly used to show trends over time. It can help readers to understand your data in a few seconds.

f:id:vivek081166:20190227145617p:plain

Sample code to generate a Line Graph is given below. Go ahead and open the sample code in Colab and experiment with it.

gist.github.com

2) Bar Charts

Bar graphs, also known as column charts, use vertical or horizontal bars to represent data along both an x-axis and a y-axis visually. Each bar represents one value. When the bars are stacked next to one another, the viewer can compare the different bars, or values, at a glance.

f:id:vivek081166:20190227201142p:plain

Sample code to generate a Bar Chart and 3D Bar Chart is given below.

gist.github.com

3) Histogram

A histogram is used to summarize discrete or continuous data. In other words, it provides a visual interpretation of numerical data by showing the number of data points that fall within a specified range of values (called "bins"). 

It is similar to a vertical bar graph. However, a histogram, unlike a vertical bar graph, shows no gaps between the bars.

f:id:vivek081166:20190227201314p:plain

gist.github.com

4) Scatter Plots

Scatter Plot is a graph in which the values of two variables are plotted along two axes, the pattern of the resulting points revealing any correlation present.

f:id:vivek081166:20190227201410p:plain

Sample code to generate a Scatter Plot and 3D Scatter Plot is given below.

gist.github.com

5) Pie Charts

A pie chart (or a circle chart) is a circular statistical graphic, which is divided into slices to illustrate numerical proportion. In a pie chart, the arc length of each slice (and consequently its central angle and area), is proportional to the quantity it represents.

f:id:vivek081166:20190227201516j:plain
(A Donut Chart is a variation of a Pie Chart but with a space in the center.)

gist.github.com

6) Wireframe Plots

Wireframe plots are used to graphically represent skeletal sketches of functions defined over a rectangular grid. Geographic data is an example of where this type of graph would be used.

f:id:vivek081166:20190227201611j:plain

gist.github.com

7) Regplot

Regplot is a simple scatterplot with a nice regression line fit to it. 
We'll use Seaborn's regplot to draw Regplot

f:id:vivek081166:20190227202106p:plain

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
Here are some more examples of Seaborn for inspiration

gist.github.com

8) HeatMap

A heat map is a graphical representation of data where the individual values contained in a matrix are represented as colors. Github's contribution calendar is an example of a heatmap.

f:id:vivek081166:20190227202430p:plain

gist.github.com

9) Bubble Chart

A bubble chart is similar to a scatter plot in that it can show distribution or relationship. There is a third data set, which is indicated by the size of the bubble or circle.
f:id:vivek081166:20190227202519p:plain

To draw an interactive bubble chart let's use bokeh

Bokeh is an interactive visualization library that targets modern web browsers for presentation. Its goal is to provide elegant, concise construction of versatile graphics, and to extend this capability with high-performance interactivity over very large or streaming datasets. Bokeh can help anyone who would like to quickly and easily create interactive plots, dashboards, and data applications.

gist.github.com

That's all for this post see you soon with one of such next time; until then, 
Happy Learning :)

Scan documents using OpenCV python

こんにちは、 ゴーリストのビベックです。 Hello World! This is Vivek from Goalist.

In this blog post, let's play around OpenCV library and write our own python script to scan documents like receipts, business cards, pages of book etc.

f:id:vivek081166:20190212112431p:plain

For those who are not aware of OpenCV, let's quickly answer a few questions about this library

What is OpenCV?
OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. The library is cross-platform and free for use under the open-source BSD license. OpenCV supports the deep learning frameworks TensorFlow, PyTorch, and Caffe.

What OpenCV can do?
1. Read and Write Images
2. Detection of faces and its features
3. Detection of shapes like Circle, rectangle etc in an image
4. Text recognition in images
5. Modifying image quality and colors
6. Developing Augmented reality apps
and much more.....

Which Languages does OpenCV support?
1. C++
2. Python
3. Java
4. Matlab/Octave
5. C
6. There are wrappers in other languages like Javascript, C#, Perl, Haskell, and Ruby to encourage adoption by a wider audience.

The initial version of OpenCV was released in June 2000, that does mean; (at the time of writing this post) it's almost 19 years this library is in use.

Some papers also highlight the fact that OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products.

So let's get started and let's see what we can build with it...

Step 1: Setting up the environement

We will be using Python 3 for our project, so, ensure that you have Python version 3 as your development environment.
You may refer the following link to set up Python on your machine.

www.python.org

Step 2: Gather required packages

We will be needing following packages in our project
1) Pre-built OpenCV packages for Python
opencv-python==4.0.0.21
opencv-contrib-python==4.0.0.21

2) For Array computation
numpy==1.16.1

3) For applying filters to image (image processing)
scikit-image==0.14.2

4) Utility package for image manupulation
imutils==0.5.2

Step 3: Let's make it work

Import the installed packages into your python script

import cv2 # opencv-python
import numpy as np
from skimage.filters import threshold_local # scikit-image
import imutils

Read the image to be scanned into your script by using OpenCV's imread() function.

We are going to perform edge detection on the input image hence in order to increase accuracy in edge detection phase we may want to resize the image. So, compute the ratio of the old height to the new height and resize() it using imutils

Also keep the cloned copy of original_image for later use

# read the input image
image = cv2.imread("test_image.jpg")

# clone the original image
original_image = image.copy()

# resize using ratio (old height to the new height)
ratio = image.shape[0] / 500.0
image = imutils.resize(image, height=500)

Generally paper (edges, at least) is white so you may have better luck by going to a different color space like YUV which better separates luminosity. (Read more about this here YUV - Wikipedia )
In order to change the color space of the input image use OpenCV's cvtColor() function.
From YUV image let's get rid of chrominance {color} (UV) components and only use luma {black-and-white} (Y) component for further proccesing.

#  change the color space to YUV
image_yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)

# grap only the Y component
image_y = np.zeros(image_yuv.shape[0:2], np.uint8)
image_y[:, :] = image_yuv[:, :, 0]

f:id:vivek081166:20190212132516p:plain

The text on the paper is another problem while detecting edges so let's use blurring effect GaussianBlur(), to remove these high-frequency noises (hopefully to some extent)

# blur the image to reduce high frequency noises
image_blurred = cv2.GaussianBlur(image_y, (3, 3), 0)

It's time to detect edges in our input image.
Use Canny() function to detect edges. You may have to tweak threshold parameters of this function in order to get the desired output.

# find edges in the image
edges = cv2.Canny(image_blurred, 50, 200, apertureSize=3)

f:id:vivek081166:20190212142140p:plain

Now that we have detected edges in our input image let's find contours around the edges and draw it on the original image

# find contours
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# draw all contours on the original image
cv2.drawContours(image, contours, -1, (0, 255, 0), 1)
# !! Attention !! Do not draw contours on the image at this point
# I have drawn all the contours just to show below image

f:id:vivek081166:20190212142135p:plain

Now that we should have a bunch of contours with us, it's time to find the right ones.
For each contour cnt, first, find the Convex Hull (Convex hull - Wikipedia), then use approaxPolyDP to simplify the contour as much as possible.

# to collect all the detected polygons
polygons = []

# loop over the contours
for cnt in contours:
    # find the convex hull
    hull = cv2.convexHull(cnt)
    
    # compute the approx polygon and put it into polygons
    polygons.append(cv2.approxPolyDP(hull, 0.01 * cv2.arcLength(hull, True), False))

Sort the detected polygons in the descending order of contour area so that we will get a polygon with the largest areas found inside the image

# sort polygons in desc order of contour area
sortedPoly = sorted(polygons, key=cv2.contourArea, reverse=True)

# draw points of the intersection of only the largest polyogon with red color
cv2.drawContours(image, sortedPoly[0], -1, (0, 0, 255), 5)

f:id:vivek081166:20190212155446p:plain

We now check if the largest detected polygon has four points.
If the polygon has four points congratulations we have detected four corners of the document in the image.

It's time to crop the image and transform the perspective of the image with respect to these four points

# get the contours of the largest polygon in the image
simplified_cnt = sortedPoly[0]

# check if the polygon has four point
if len(simplified_cnt) == 4:
    # trasform the prospective of original image
    cropped_image = four_point_transform(original_image, simplified_cnt.reshape(4, 2) * ratio)

Refer the following to get to know about four_point_transform() function in detail.

Finally binarize the image to have scanned version of the cropped image

# Binarize the cropped image
gray_image = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2GRAY)
T = threshold_local(gray_image, 11, offset=10, method="gaussian")
binarized_image = (gray_image > T).astype("uint8") * 255

# Show images
cv2.imshow("Original", original_image)
cv2.imshow("Scanned", binarized_image)
cv2.imshow("Cropped", cropped_image)
cv2.waitKey(0)

f:id:vivek081166:20190212161727p:plain

🎉There we go... we just managed to scan a document from a raw image with the help of OpenCV.

That's all for this post see you soon with one of such next time; until then,
Happy Learning :)

一般化がいつも重要!(これも一般化なのかな)

チナパです! 早速ですが、A few useful things to know about machine learning - Pedro Domingos

https://homes.cs.washington.edu/~pedrod/papers/cacm12.pdf

f の続きをしたいと思います!以前、この論文にまとめられてる分類器の3つの部分(表現、評価、改善)について書きましたので、気になる方はこちらで読んでみてください!

developers.goalist.co.jp

その続きには、まず一般化について説明したいと思います!

一般化が全て!

学校・社会では「一般化」はあんまり良いイメージを持ってないかも知れません。例えば、数学がいやな友達が「インド人みんな二桁乗算できるじゃん!」ということに対していつも「それはただ一般化だよ!人はそれぞれ!」みたいに強く否定することもあります。そんな状況には確かに、一般化の弱点が明確に見えますが、その限られた視点を使って「すべての一般化が悪い」という結論にたどり着くのも…

人間も使ってる重要な道具

一般化は完璧ではありませんが、人間が持つ思考道具のとても重要な一つです。なぜなら、世界の「すべて」を経験していない限り、新しい状況に入ってしまう時には一般化を無くして他に頼る物が心細い。中学生が高校に行く時にも、大学生が社会人になった時にも、今までの経験から学んだことを新しく入る場所にもちろん使おうとします。完璧ではないが、人間が新しい状況で素早く活躍し、新しい学びを作ることができる理由は一般化にあると思います。

その力は今になってパソコンも使うとしています。

機械学習も今まで見たデータを「経験」として生かして、見たことがない新しい(似ているかも知れない)問題を解決しようとしています。

機械学習のモデルを作る時に、データ・サイエンティストあるいはAIエンジニアとしての責任はモデルが一般化の力を身につけるように作ることです。

どうやって一般化できるモデルが作れます?

作る方法の前に、確認の方法があるのが重要です。

まずはですね、学習データ、バリデーションデータと評価データをそれぞれ持ちましょう。

学習データの精度は「このモデルがパターンを見つけられるかどうか」をわかるためには便利ですが、実際のモデルの良さが分かりません。言い換えましょう。学習データでの精度が低ければ、「モデルが良くない」のが分かりますが、学習データでの精度が100%でも、「モデルが良い」を言い切れません。

人間の学生が教科書の通りの言葉を繰り返しても本当のコンセプトが理解できているのが言い切れないことと同じです。そのために、教科書・学習データと異なるものに対しての評価が必要です。これは「テストデータ」と言います。

このように、学習データ(教科書)とテストデータ(試験)が全く同じような物ではないことによって、一般化の確認ができたかどうかが分かるはず…よね?

そうですね、、、、まだです。

その理由を知るために、まず、実践的な状況を想像しましょう。

現実はこうですよ

研究者Aくんがモデルを作ろうとしています。データを100件持っているとしましょう。上記のように、ちゃんと持ってるデータを学習データ(90件)とテストデータ(10件)に分けてます。ここまでよし。

Round 1:いくつかのフィーチャを使って、学習させます。 結果:テストしたら40%なので、もっかい!

Round 2:フィーチャをちょっと改善して、新しいのを作成し、学習させます。 結果:テストしたら41%なので、もっかい!

Round 3:モデルをちょっと変換して、フィーチャも編集して、学習させます。 結果:テストしたら50%なのでよし、がもっかい!

1ヶ月後

Round 21:何回も何回もモデルとフィーチャーを編集して、学習させました。 結果:テストしたら93%なのでやった!90%以上だし、すごい!

と思ってます。

お試しで他の人に使わせてみたら、

「え?」

友達がやってみたら、80%ぐらいの正答率しか出てこない。しかも、微妙に二つのクラスに混乱するのが多い。

何が行われたのでしょう?

絶望の原因をしっかり把握しましょう

ここで、確かに、学習の時に別なデータを利用して、評価の時に別なデータを利用したためにそこでオーバーフィッティング(一般化できないこと)がそんなに見えなかったが、テスト結果に応じてのモデル編集自体を何度も、行なったため、テストデータに特に合いそうなモデルを作ってしまいました。

そこで、本当の状況を知らず、みんなに「90%以上!」と自慢してた….絶望的。

一般化を確認するための理想的なプロセス

学習するたびに毎回一般化の確認を含まなくても良いですが、最終的にいくつかの検討できるモデルの中で、実際に使いたい時にこのような形で一般化の確認ができます。

学習データとテストデータを分ける

全てのデータをまず二つに分ける。例えば、8割・2割で学習とテストデータを作りましょう。(割合に多少融通が利きます)

ここのテストデータを一旦放置して、残っている学習データをさらに8割・2割に分けましょう。今回の2割は「クロスバリデーションデータ」と言います。

クロスバリデーションデータを使う

学習して→クロスバリデーションデータで評価しましょう。 何度も編集しても、このクロスバリデーションに対しての評価が高くなっていっても、まだ一度も利用されてないテストデータが残ってます。

クロスバリデーションデータはずっと同じデータでもなくても良いです。

学習データとテストデータと学習データをシャッフル

テストデータを使わずに、一般化ができていると確認したい場合に、クロスバリデーションデータと学習データを混ぜて、もう一回ランダムで分け直しましょう。

例:最初に1-64まで、が学習データとして、

65-80がクロスバリデーションとして使っていた場合、にシャッフルして

1-16までをクロスバリデーションに使い、今度学習データを17-80まで使って、

それぞれの状態の評価には変動が激しくないと確認できます。

テストデータで評価

モデル修正が色々満足した時に、やっとテストデータを利用して、公開できる評価を今までみていない、ランダムのはずのデータに対して得られます。

まとめ

この度、一般化について詳しく説明いたしました。これで、一般化がなんで重要なのか、そして、一般化できないモデルの騙されない方法をいくつか使えるようになりましたかな!

では、また今度!

チナパ。

Business Card Reader : Part 2 : Frontend (Ionic App)

Hello World! My name is Vivek Amilkanthawar
In the last blog post, we had written cloud function for our Business Card Reader app to do the heavy lifting of text recognition and storing the result into database by using Firebase, Google Cloud Vision API and Google Natural Language API.

We had broken down the entire process into the following steps.
1) User uploads an image to Firebase storage via @angular/fire in Ionic.
2) The upload triggers a storage cloud function.
3) The cloud function sends the image to the Cloud Vision API
4) Result of image analysis is then sent to Cloud Language API and the final results are saved in Firestore.
5) The final result is then updated in realtime in the Ionic UI.

Out of these, step #2, step #3 and step #4 are explained in last blog post
If you have missed the last post, you can find it here...

developers.goalist.co.jp

In this blog post, we'll be working on the frontend to create an Ionic app for iOS and Android (step #1 and step #5)

The final app will look something like on iOS platform

f:id:vivek081166:20190121142143g:plain

So let's get started

Step 1: Create and initialize an Ionic project

Let’s generate a new Ionic app using the blank template. I have named my app as meishi (めいし) it means 'business card' in Japanese.

ionic start meishi blank
cd meishi

Making sure you are in the Ionic root director then generate a new page with the following command

ionic g page vision

We'll use the VisionPage as our Ionic root page inside the app.component.ts

import { VisionPage } from '../pages/vision/vision';
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = VisionPage;
  // ...skipped
}

Add @angular/fire and firebase dependencies to our Ionic project for communicating with firebase.

npm install @angular/fire firebase --save

Add @ionic-native/camera to use native camera to capture buisness card image for processing.

ionic cordova plugin add cordova-plugin-camera
npm install --save @ionic-native/camera

At this point, let's register AngularFire and the native camera plugin in the app.module.ts
(add your own Firebase project credentials in firebaseConfig)

import {BrowserModule} from '@angular/platform-browser';
import {ErrorHandler, NgModule} from '@angular/core';
import {IonicApp, IonicErrorHandler, IonicModule} from 'ionic-angular';
import {SplashScreen} from '@ionic-native/splash-screen';
import {StatusBar} from '@ionic-native/status-bar';

import {MyApp} from './app.component';
import {HomePage} from '../pages/home/home';
import {VisionPage} from '../pages/vision/vision';

import {AngularFireModule} from '@angular/fire';
import {AngularFirestoreModule} from '@angular/fire/firestore';
import {AngularFireStorageModule} from '@angular/fire/storage';

import {Camera} from '@ionic-native/camera';

const firebaseConfig = {
  apiKey: 'xxxxxx',
  authDomain: 'xxxxxx.firebaseapp.com',
  databaseURL: 'https://xxxxxx.firebaseio.com',
  projectId: 'xxxxxx',
  storageBucket: 'xxxx.appspot.com',
  messagingSenderId: 'xxxxxx',
};

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    VisionPage,
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFirestoreModule,
    AngularFireStorageModule,
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    VisionPage,
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Camera,
  ],
})
export class AppModule {
}

Step 2: Let's make it work

There is so much going on in the VisionPage component, let's break it down and see it step by step.

1) User clicks "Capture Image" button which triggerscaptureAndUpload()to bring up the device camera.

2) Camera returns the image as a Base64 string. I have reduced the quality of the image in order to reduce processing time. For me, even with 50% of the image quality, Google Vision API is doing well.

3) We generate an ID that is used for both the image filename and the Firestore document ID.

4) We then listen to this location in Firestore.

5) An upload task is created to transfer the file to storage.

6) We wait for the cloud function (refer my last post) to update Firestore.

7) Once the data is received from Firestore we use helper methods extractEmail() and extractContact() to extract email and contact information from the received string.

8) And it's done!!

import {Component} from '@angular/core';
import {IonicPage, Loading, LoadingController} from 'ionic-angular';

import {Observable} from 'rxjs/Observable';
import {filter, tap} from 'rxjs/operators';

import {AngularFireStorage, AngularFireUploadTask} from 'angularfire2/storage';
import {AngularFirestore} from 'angularfire2/firestore';

import {Camera, CameraOptions} from '@ionic-native/camera';

@IonicPage()
@Component({
  selector: 'page-vision',
  templateUrl: 'vision.html',
})
export class VisionPage {

  // Upload task
  task: AngularFireUploadTask;

  // Firestore data
  result$: Observable<any>;

  loading: Loading;
  image: string;

  constructor(
    private storage: AngularFireStorage,
    private afs: AngularFirestore,
    private camera: Camera,
    private loadingCtrl: LoadingController) {

    this.loading = this.loadingCtrl.create({
      content: 'Running AI vision analysis...',
    });
  }

  startUpload(file: string) {

    // Show loader
    this.loading.present();

    // const timestamp = new Date().getTime().toString();
    const docId = this.afs.createId();

    const path = `${docId}.jpg`;

    // Make a reference to the future location of the firestore document
    const photoRef = this.afs.collection('photos').doc(docId);

    // Firestore observable
    this.result$ = photoRef.valueChanges().pipe(
      filter(data => !!data),
      tap(_ => this.loading.dismiss()),
    );

    // The main task
    this.image = 'data:image/jpg;base64,' + file;
    this.task = this.storage.ref(path).putString(this.image, 'data_url');
  }

  // Gets the pic from the native camera then starts the upload
  async captureAndUpload() {
    const options: CameraOptions = {
      quality: 50,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    };

    const base64 = await this.camera.getPicture(options);

    this.startUpload(base64);
  }

  extractEmail(str: string) {
    const emailRegex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
    const {matches, cleanedText} = this.removeByRegex(str, emailRegex);
    return matches;
  };

  extractContact(str: string) {
    const contactRegex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/;
    const {matches, cleanedText} = this.removeByRegex(str, contactRegex);
    return matches;
  }

  removeByRegex(str, regex) {
    const matches = [];
    const cleanedText = str.split('\n').filter(line => {
      const hits = line.match(regex);
      if (hits != null) {
        matches.push(hits[0]);
        return false;
      }
      return true;
    }).join('\n');
    return {matches, cleanedText};
  };

}

Step 3: Display your result

Let's create a basic UI using ionic components

<!--
  Generated template for the VisionPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>Meishi</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
  <ion-row>

    <ion-col col-12 text-center>

      <button ion-button icon-start (tap)="captureAndUpload()">
        <ion-icon name="camera"></ion-icon>
        Capture Image
      </button>

    </ion-col>

    <ion-col col-12>
      <img width="100%" height="auto" [src]="image">
    </ion-col>

    <ion-col *ngIf="result$ | async as result">

      <h4>
        <span class="title">名前: </span><br>
        {{result.requiredEntities.PERSON}}
      </h4>
      <h4>
        <span class="title">Email:</span><br>
        <span *ngFor="let email of extractEmail(result.text)">{{email}}<br></span>
      </h4>
      <h4>
        <span class="title">電話番号:</span><br>
        <span *ngFor="let phone of extractContact(result.text)">{{phone}}<br></span>
      </h4>
      <h4>
        <span class="title">組織:</span><br>
        {{result.requiredEntities.ORGANIZATION}}
      </h4>
      <h4>
        <span class="title">住所:</span><br>
        {{result.requiredEntities.LOCATION}}
      </h4>

      <h4><span class="title">認識されたテキスト</span></h4>

      <h5>
        {{result.text}}
      </h5>


    </ion-col>
  </ion-row>

</ion-content>

Step 4: Generate an app into platform of your choice

Finally, let's generate an application into iOS or Android
Run the following command to create a build of the app for iOS

 ionic cordova build ios

In a similar way to generate android app, run the following command

 ionic cordova build an Android

Open the app on an emulator or on an actual device and test it yourself

Congrats!! we just create a Business Card Reader app powered with Machine Learning :)

That's it for this post see you soon with one of such next time; until then,
Happy Learning :)

機械学習・学ぶアルゴリズムの3つの大事な部分

チナパです! ちょっと久しぶりに機械学習に本格できるようになりましたので、大好きなところから始め、論文を読んでました。 そこで、皆さんにもシェアしたいのがありましてーーーここ!

A few useful things to know about machine learning - Pedro Domingos https://homes.cs.washington.edu/~pedrod/papers/cacm12.pdf

とシェアしたら、「英語のハードルが!!」と言われそうでしたので、こうして日本語でまとめます!(優しいでしょう?)

分類系の機械学習(分類器? 難しい日本語だな。クラシファイアの種類です!)に集中していますが、とりあえず始めましょう。

学ぶ者(アルゴリズムね)の3つの部分

f:id:c-pattamada:20190125203246p:plain
こんな感じです!

機械学習がとても大きな箱です。その中にあるそれぞれの手段、技術などはどう分担すればよいのでしょうかとずっと思っていたところで、この論文で綺麗にまとめられました。

「機械学習 = Deep Learning = Neural Network」と思う方(昔の私)もいるかもしれないが、実際はこんな感じです。

表現

分類器(クラシファイア君)を作るためには、コンピュータが理解できる言語で作られた何らかの形を選択する必要があります。これはクラシファイア君の「表現」と言われます。 ニューラルネットワークはもしかして一番有名な表現かもしれません、つまり

f:id:c-pattamada:20190125202443p:plain
ニューラルネットワーク

こんな感じの表現です。生のデータげ左に入って、複数のレイヤーでフィーチャーの関係を見つけ出して答えにたどり着くような表現です。

ニューラルネットワークの他に、以下のような決定木もよく使われます。

f:id:c-pattamada:20190125202544p:plain
決定木

こちらでは、順番の判断によって結論にたどり着きます。

それぞれは得意分野と弱点を持っています。なんでかというと、表現によって見つけられる答えが限られてきます。なぜなら、それぞれの表現には「仮説スペース」があるからです。仮説スペースに入っていない答えを見つけるのが不可能です(鍵を車に忘れている場合、いくら家に探しても見つからないでしょう?そういうものです。)

他の表現の例は

ナイブベイズ K-最近傍法 (kNN) SVM などなど。

機械学習は一般的にこの「表現」についてまとめられるのが多いですが、他の部分もとても大事です。

もう、表現について長く語りました。次に移しましょう。

評価

形がどうであれ、機械学習にはデータを利用して仮説を改善し、正しい答えに近づこうとするのが共通です。「改善」ができる前に、まずは現状況の良さ・悪さを把握しなければなりません。

場合によって「正答率」のが一番直感かもしれませんが ここ で書いたように、正答率は全てではありません。悪人判定しようとしながら、「99.99%の人は悪人でないから、とりあえず「悪人ではない」と言えば99.99%正解じゃん!」という無意味なプログラムを釣りたくはないでしょう。

Fバリュー(Precision and recall)についても書いたことがありますが、それ以外にも評価のやり方がたくさんあります。

developers.goalist.co.jp

クラス分類ではなく、連続分布からのバリューを予想とするときは二乗誤差(Squared error)なども使えます。

改善・最適化

現在の表現で見つけている答えの質を評価できた上で、そのモデルを変更して改善することが可能となります。

Deep Learning でよく使われてるのが最急降下法(Gradient Descent)です。偏微分を使って、現在の状況に比べて、少しだけの変更でどう「評価」改善できるかを計算するアルゴリズムです。

例えをしますと、坂登りで、めを閉じる場合にも下り道が分かるではないか(危険ですよ、実際に転び落ちたことがあります)、最急降下法それに似ています。この例えでは周りに比べてた「最善」が坂の底です。

上記のGradient Descent(最急降下法)の他にも改善のやり方があります。

Greedy SearchとBeam Searchでもあります。(辞書にも出てこないですけど!欲深い検索ではありません!)最急降下法と違って、こちらの二つはいくつかの有限な選択肢をよりよく組み合わせようとする方法です。

巻き

書き始めた時には、5つぐらいのトピックはこの記事で書こうと思ってましたが、もう結構長いですね。

上記には、機械学習、いわゆる「学ぶプログラム」を作成するための大事なみつの部分について説明しました。

詳細書きすぎたかも知れませんが、この続きには機械学習のモデルなどを作る時に重要なポイントを他にも説明します。

次回は「一般化できるか?」と長くなければ「データだけでは足りぬ!」というワクワクできそうなトピックを書きたいです!

以上チナパでした!

Business Card Reader : Part 1 : Backend (Cloud Functions)

Hello World! My name is Vivek Amilkanthawar
In this and the subsequent blog posts, we'll be creating a Business Card Reader as an iOS App with the help of Ionic, Firebase, Google Cloud Vision API and Google Natural Language API

The final app will look something like this

f:id:vivek081166:20190121142143g:plain

Okay so let's get started...
The entire process can be broken down into the following steps.
1) User uploads an image to Firebase storage via @angular/fire in Ionic.
2) The upload triggers a storage cloud function.
3) The cloud function sends the image to the Cloud Vision API
4) Result of image analysis is then sent to Cloud Language API and the final results are saved in Firestore.
5) The final result is then updated in realtime in the Ionic UI.

Let's finish up the important stuff first... the backend. In this blog post we'll be writing Cloud Function to do this job... (step #2, step #3 and step #4 of the above process)

The job of the cloud function that we are about to write can be visualized as below: f:id:vivek081166:20190121151148p:plain

Whenever the new image is uploaded to the storage, our cloud function will get triggered and the function will call Google Machine Learning APIs to perform Vision analysis on the uploaded image. Once the image analysis is over the recognized text is then passed to Language API to separate meaningful information.

Step 1: Set up Firebase CLI

Install Firebase CLI via npm using following command

npm install firebase-functions@latest firebase-admin@latest --save
npm install -g firebase-tools

Step 2: Initialize Firebase SDK for Cloud Functions

To initialize your project:
1) Run firebase login to log in via the browser and authenticate the firebase tool.
2) Go to your Firebase project directory.
3) Run firebase init functions
4) When asked for the language of choice/support chose Typescript

After these commands complete successfully, your project structure should look like this:

myproject
 +- .firebaserc    # Hidden file that helps you quickly switch between
 |                 # projects with `firebase use`
 |
 +- firebase.json  # Describes properties for your project
 |
 +- functions/     # Directory containing all your functions code
      |
      +- tslint.json  # Optional file containing rules for TypeScript linting.
      |
      +- tsconfig.json  # file containing configuration for TypeScript.
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- node_modules/ # directory where your dependencies (declared in package.json) are installed
      |
      +- src/
          |
          +- index.ts      # main source file for your Cloud Functions code

Step 3: Write your code

All you have to edit is the index.ts file

1) Get all your imports correct, we need
@google-cloud/vision for vision analysis
@google-cloud/language for language analysis
firebase-admin for authentication and initialization of app
firebase-functions to get hold on the trigger when a new image file is updated to storage bucket on firebase

2)onFinalize method is triggered when the uploading of the image is completed. The URL of a newly uploaded Image File can be captured here.

3) Pass the image URL to visionClient to perform text detection on the image

4) visionResults is a plain text string containing all the words/characters recognized during image analysis

5) Pass this result to language API to get meaning full information from the text.
Language API categorizes the text into different entities. Out of various entities let's filter only the requiredEntities which are person name, location/address, and organization.
(Phone number and Email can be extracted by using regex, we will do this at the front end)

6) Finally, save the result into Firestore Database

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as vision from '@google-cloud/vision'; // Cloud Vision API
import * as language from '@google-cloud/language'; // Cloud Natural Language API
import * as _ from 'lodash';

admin.initializeApp(functions.config().firebase);

const visionClient = new vision.ImageAnnotatorClient();
const languageClient = new language.LanguageServiceClient();

let text; // recognized text
const requiredEntities = {ORGANIZATION: '', PERSON: '', LOCATION: ''};

// Dedicated bucket for cloud function invocation
const bucketName = 'meishi-13f87.appspot.com';

export const imageTagger = functions.storage.
    object().
    onFinalize(async (object, context) => {

      /** Get the file URL of newly uploaded Image File **/
      // File data
      const filePath = object.name;

      // Location of saved file in bucket
      const imageUri = `gs://${bucketName}/${filePath}`;

      /** Perform vision and language analysis **/
      try {

        // Await the cloud vision response
        const visionResults = await visionClient.textDetection(imageUri);

        const annotation = visionResults[0].textAnnotations[0];
        text = annotation ? annotation.description : '';

        // pass the recognized text to Natural Language API
        const languageResults = await languageClient.analyzeEntities({
          document: {
            content: text,
            type: 'PLAIN_TEXT',
          },
        });

        // Go through detected entities
        const {entities} = languageResults[0];

        _.each(entities, entity => {
          const {type} = entity;
          if (_.has(requiredEntities, type)) {
            requiredEntities[type] += ` ${entity.name}`;
          }
        });

      } catch (err) {
        // Throw an error
        console.log(err);
      }

      /** Save the result into Firestore **/
          // Firestore docID === file name
      const docId = filePath.split('.jpg')[0];
      const docRef = admin.firestore().collection('photos').doc(docId);
      return docRef.set({text, requiredEntities});

    });

Step 4: Deploy your function

Run this command to deploy your functions:

firebase deploy --only functions

Storage f:id:vivek081166:20190121173201p:plain Database f:id:vivek081166:20190121172904p:plain

That's it.. with this our backend is pretty much ready.
Let's work on front-end side in the upcoming blog post till then
Happy Learning :)

Reference:

cloud.google.com

cloud.google.com