字幕表 動画を再生する
[MUSIC PLAYING]
{ 機械学習 }
Hey, everyone.
{ 機械学習 } レシピ
Welcome back.
皆さん こんにちは
In this episode, we're going to do something special,
ようこそ
and that's write our own classifier from scratch.
今回は特別なことをします
If you're new to machine learning,
それは自分の分類器を 一から作ることです
this is a big milestone.
機械学習が初めての方なら
Because if you can follow along and do this on your own,
これは大きな指標です
it means you understand an important piece of the puzzle.
ついて来て自分でこれができれば
The classifier we're going to write today
パズルの重要なピースを理解する という意味ですからね
is a scrappy version of k-Nearest Neighbors.
今日書く分類器は
That's one of the simplest classifiers around.
K 近傍法の簡易版です
First, here's a quick outline of what we'll do in this episode.
それは現存の最もシンプルな 分類器の1つです
We'll start with our code from Episode 4, Let's
まず これが今回やることの ざっとした概略です
Write a Pipeline.
第4回の Let's Write a Pipeline の このコードで始めます
Recall in that episode we did a simple experiment.
その回で簡単な実験をしましたね
We imported a data set and split it into train and test.
データセットをインポートして それを学習とテストに分けました
We used train to train a classifier,
学習は分類器を学習させる為に
and test to see how accurate it was.
テストはその精度を見る為に 使いました
Writing the classifier is the part
分類器を書くことが
we're going to focus on today.
今日的を絞る部分です
Previously we imported the classifier
前に 分類器をライブラリから
from a library using these two lines.
これらの2行を使って インポートしました
Here we'll comment them out and write our own.
ここではそれらをコメントアウトして 自分のを書きます
The rest of the pipeline will stay exactly the same.
あとのパイプラインは 全く同じにしておきます
I'll pop in and out of the screencast to explain things
私は進行中に説明の為に スクリーンキャストに出入りします
as we go along.
まず パイプラインを実行して
To start, let's run our pipeline to remind ourselves
精度がどうだったか思い出してみましょう
what the accuracy was.
ご覧のように 90% 以上です
As you can see, it's over 90%.
これが私達自身が作る 分類器のゴールです
And that's the goal for the classifier
では このインポートを コメントアウトしましょう
we'll write ourselves.
即座に これでコードが壊れます
Now let's comment out that import.
ですから まずはパイプラインを 直す必要があります
Right off the bat, this breaks our code.
その為に 分類器にクラスを 実装します
So the first thing we need to do is fix our pipeline.
それを ScrappyKNN と呼びます
And to do that, we'll implement a class for our classifier.
scrappy とは最も簡素な という意味です
I'll call it ScrappyKNN.
動けばいいだけのものです
And by scrappy, I mean bare bones.
次にそれを使う為に パイプラインを変えます
Just enough to get it working.
では どのメソッドを実装する 必要があるか見てみましょう
Next, I'll change our pipeline to use it.
分類器のインターフェースを見ると
Now let's see what methods we need to implement.
配慮する2つが見えます 学習をする fit と
Looking at the interface for a classifier,
予測をする predict です
we see there are two we care about-- fit,
まず fit メソッドを宣言します
which does the training, and predict,
これが学習セットの特徴と ラベルを入力としてとるのですから
which does the prediction.
それらにパラメーターを付けます
First we'll declare our fit method.
では predict メソッドに移りましょう
Remember this takes the features and labels for the training set
入力として これはテストデータの 特徴を受け取り
as input, so we'll add parameters for those.
出力として ラベルの予測を返します
Now let's move on to our predict method.
私達の最初の目標は パイプラインを機能させ
As input, this receives the features for our testing data.
これらのメソッドが何をするか 理解することです
And as output, it returns predictions for the labels.
そこで私達の本当の 分類器を書く前に
Our first goal is to get the pipeline working,
もっとシンプルなことから 始めましょう
and to understand what these methods do.
ランダム分類器を書きます
So before we write our real classifier,
ランダムとはラベルを推量するだけ という意味です
we'll start with something simpler.
まず fit と predict メソッドに コードを付け足します
We'll write a random classifier.
fit にはこのクラスの 学習データを格納します
And by random, I mean we'll just guess the label.
これを記憶するものと 思っていいです
To start, we'll add some code to the fit and predict methods.
なぜそうするか後でわかります
In fit, I'll store the training data in this class.
predict メソッドの中には
You can think of this as just memorizing it.
予測のリストを返す 必要がありますね
And you'll see why we do that later on.
なぜならパラメーター X_test は
Inside the predict method, remember
実は2次元配列 または 一覧の一覧だからです
that we'll need to return a list of predictions.
各行には1つのテスト例の 特徴が入ります
That's because the parameter, X_test, is actually
各行の予測をする為に
a 2D array, or list of lists.
学習データからランダムに ラベルを選び
Each row contains the features for one testing example.
それを予測に付けます
To make a prediction for each row,
この時点でパイプラインは また機能しています
I'll just randomly pick a label from the training data
では実行してどの位うまく 働くか見てみましょう
and append that to our predictions.
アイリスデータセットでは 異なる花の種類は3つでしたよね
At this point, our pipeline is working again.
ですから精度は約 33% の筈です
So let's run it and see how well it does.
これで分類器のインターフェースは 分かりましたね
Recall there are three different types of flowers
ですが この試みを始めた時
in the iris dataset, so accuracy should be about 33%.
精度は約 90% でした
Now we know the interface for a classifier.
ではもっと良くやれるか 見てみましょう
But when we started this exercise,
その為に 私達の分類器を実装します
our accuracy was above 90%.
それは K 近傍法に基づいています
So let's see if we can do better.
ここにそのアルゴリズムの 働き方の直観があります
To do that, we'll implement our classifier,
前回の緑の点と赤の点の図に 戻ってみましょう
which is based on k-Nearest Neighbors.
画面上に見える点が
Here's the intuition for how that algorithm works.
fit メソッドで記憶した 学習データだと思ってください
Let's return to our drawings of green dots and red dots
例えば トイデータセットだと
from the last episode.
ここにグレーで描いた このテストポイントに
Imagine the dots we see on the screen
予測を求められたとして
are the training data we memorized in the fit method,
それをどうやればいいでしょうか
say for a toy dataset.
近傍分類器では
Now imagine we're asked to make a prediction for this testing
全くその名の通りに働きます
point that I'll draw here in gray.
テスト点に最も近い学習点を 見つけます
How can we do that?
この点が最近傍です
Well in a nearest neighbor classifier,
次にこのテスト点が 同じラベルになると予測します
it works exactly like it sounds.
例えばこのテスト点が緑だと推量します
We'll find the training point that's
それが最近傍の色だからです
closest to the testing point.
別の例として こっちにテスト点が あったとすれば
This point is the nearest neighbor.
それが赤だと推量します
Then we'll predict that the testing
では中間のこれはどうでしょう
point has the same label.
この点が最近傍の緑の点と 最近傍の赤の点から
For example, we'll guess that this testing dot is green,
等距離だと思ってください
because that's the color of its nearest neighbor.
タイですから どう分類すればいいのでしょう
As another example, if we had a testing dot over here,
1つの方法はタイを任意に 破ってもいいでしょうが
we'd guess that it's red.
別の方法として そんな時に K が便利です
Now what about this one right in the middle?
K は予測をしている時考える 近傍の数です
Imagine that this dot is equidistant to the nearest
K が1なら最近傍の 学習点を見るだけです
green dot and the nearest red one.
しかし K が3なら 3つの最近傍を見ます
There's a tie, so how could we classify it?
この場合 そのうちの2つは緑で 1つは赤です
Well one way is we could randomly break the tie.
予測するには 投票し 過半数クラスを予測します
But there's another way, and that's where k comes in.
さて このアルゴリズムには もっと詳細がありますが
K is the number of neighbors we consider
始めるにはこれで十分です
when making our prediction.
これをコードに書くには
If k was 1, we'd just look at the closest training point.
まず最近傍を見つける 方法が必要です
But if k was 3, we'd look at the three closest.
その為に2点間の 直線距離を
In this case, two of those are green and one is red.
定規で測るのと同じように 測ります
To predict, we could vote and predict the majority class.
ユークリッド距離という その為の計算式があります
Now there's more detail to this algorithm,
その計算式はこんな風です
but that's enough to get us started.
それで2点間の距離を測ります
To code this up, first we'll need a way
ちょっとピタゴラスの定理に 似ていて
to find the nearest neighbor.
A の2乗足す B の2乗 イコール C の2乗ですね
And to do that, we'll measure the straight line
この項を A 最初の2つの特徴の差と
distance between two points, just like you do with a ruler.
みなしていいでしょう
There's a formula for that called the Euclidean Distance,
同様に この項を B
and here's what the formula looks like.
特徴の2番目のペア間の 差と思ってください
It measures the distance between two points,
計算するこの距離は 斜辺の長さです
and it works a bit like the Pythagorean Theorem.
ここにいいものがあります
A squared plus B squared equals C squared.
今は2次元空間の距離を 計算しています
You can think of this term as A, or the difference
トイデータセットに特徴は 2つあるだけですからね
between the first two features.
だが もし特徴が3つ 3次元ならどうでしょう
Likewise, you can think of this term as B,
すると立方体になります
or the difference between the second pair of features.
やはり定規で空間の 距離を測る方法を可視化できます
And the distance we compute is the length of the hypotenuse.
だが 特徴が4つ 4次元ならどうでしょう
Now here's something cool.
アイリスでやるように?
Right now we're computing distance
今度は超立方体になり
in two-dimensional space, because we have just two
これを簡単には可視化できません
features in our toy dataset.
うまい具合に ユークリッド距離は
But what if we had three features or three dimensions?
次元の数に関わりなく 同様に機能します
Well then we'd be in a cube.
特徴が多くなれば 等式にもっと 項を足せばいいだけです
We can still visualize how to measure distance
これに関してオンラインで もっと詳細を見つけられます
in the space with a ruler.
ではユークリッド距離を コードに書きましょう
But what if we had four features or four dimensions,
それをする方法は沢山ありますが
like we do in iris?
scipy というライブラリを使います
Well, now we're in a hypercube, and we
それはもう Anaconda によって インストールされています
can't visualize this very easy.
ここで A と B は数の特徴のリストです
The good news is the Euclidean Distance
例えば A は学習データからの点で
works the same way regardless of the number of dimensions.
B はテストデータからの点です
With more features, we can just add more terms to the equation.
この関数はそれらの間の 距離を返します
You can find more details about this online.
これで必要な数学は全部です
Now let's code up Euclidean distance.
では分類器用のアルゴリズムを 見てみましょう
There are plenty of ways to do that,
テスト点の予測をする為に
but we'll use a library called scipy that's
学習点全部に対する距離を計算します
already installed by Anaconda.
次にテスト点が最も近い点と 同じラベルになると予測します
Here, A and B are lists of numeric features.
さっき作ったランダム予測を削除して
Say A is a point from our training data,
テスト点と最も近い学習点を 捜すメソッドで置き換えます
and B is a point from our testing data.
このビデオ用に 私は K を1にハードコードします
This function returns the distance between them.
ですから 最近傍分類器を 書いています
That's all the math we need, so now
K 変数はコードに出てきません
let's take a look at the algorithm for a classifier.
常に最も近い点を 見つけるだけですからね
To make a prediction for a test point,
このメソッド内に 学習点全てをループ処理させ
we'll calculate the distance to all the training points.
とりあえず最も近い点を追跡します
Then we'll predict the testing point has the same label
fit 関数内で 学習データを 記憶しておきましたね
as the closest one.
X_train に特徴が入ります
I'll delete the random prediction we made,
始めに テスト点から 最初の学習点までの距離を計算します
and replace it with a method that finds the closest training
この変数を使って 見つけた 最短距離を追跡します
point to the test point.
この変数を使って
For this video hard, I'll hard-code k to 1,
最も近い学習ポイントの インデックスを追跡します
so we're writing a nearest neighbor classifier.
そのラベルを取得する為に あとでこれが必要になります
The k variable won't appear in our code,
他の学習点全てに繰り返し 処理します
since we'll always just find the closest point.
より近いものが見つかるたびに
Inside this method, we'll loop over all the training points
変数を更新します
and keep track of the closest one so far.
最後にそのインデックスを使って
Remember that we memorized the training data in our fit
最も近い学習例のラベルを返します
function, and X_train contains the features.
この時点で最近傍分類器は 機能するので
To start, I'll calculate the distance from the test point
実行して精度がどうか 見てみましょう
to the first training point.
ご覧のように 90% 以上です
I'll use this variable to keep track of the shortest
やりましたね
distance we've found so far.
皆さんが自分でこれを実行すると
And I'll use this variable to keep
精度はちょっと違うかもしれません
track of the index of the training point that's closest.
学習とテスト分割で任意だったためです
We'll need this later to retrieve its label.
さて皆さんがこれをコード化でき 理解したなら
Now we'll iterate over all the other training points.
大きな成果です
And every time we find a closer one,
単純な分類器を一から 書けるという意味ですからね
we'll update our variables.
このアルゴリズムには 幾つか長所と短所があり
Finally, we'll use the index to return
その多くはネットで見つけられます
the label for the closest training example.
基本的な長所は比較的 理解が簡単で
At this point, we have a working nearest neighbor classifier,
問題によってはそこそこ良く 機能することです
so let's run it and see what the accuracy is.
基本的な短所はのろいことです
As you can see, it's over 90%.
予測をする為にあらゆる学習点を 繰り返し処理する必要があるからです
And we did it.
特に 第3回目で見たように
When you run this on your own, the accuracy
特徴には他より情報量の 多いものがあります
might be a bit different because of randomness in the train test
しかし K 近傍法にはそれを表す 簡単な方法がありません
split.
詰まり 私達は特徴と 予測しようとするラベル間の
Now if you can code this up and understand it,
もっと複雑な関係を学ぶ 分類器が欲しいんです
that's a big accomplishment because it
決定木がそれの好例です
means you can write a simple classifier from scratch.
TensorFlow Playground で 見たようなニューラルネットワークは
Now, there are a number of pros and cons
さらに良いです
to this algorithm, many of which you can find online.
役に立てたことを願っています
The basic pro is that it's relatively easy to understand,
ご視聴ありがとう
and works reasonably well for some problems.
更新情報は Twitter や 無論 Google Developersでどうぞ
And the basic cons are that it's slow,
では皆さん 次回にお会いしましょう
because it has to iterate over every training point
to make a prediction.
And importantly, as we saw in Episode 3,
some features are more informative than others.
But there's not an easy way to represent
that in k-Nearest Neighbors.
In the long run, we want a classifier
that learns more complex relationships between features
and the label we're trying to predict.
A decision tree is a good example of that.
And a neural network like we saw in TensorFlow Playground
is even better.
OK, hope that was helpful.
Thanks as always for watching.
You can follow me on Twitter for updates and, of course,
Google Developers.
And I'll see you guys next time.
[MUSIC PLAYING]