スキップしてメイン コンテンツに移動

投稿

5月, 2018の投稿を表示しています

線形SVMの実装

Introduction English ver 今日は線形SVMの実装をしました。 SVMはDeep learningが主流になる前、人気だったとどこかで拝見しました。 SVMの詳しい理論の説明は別の機会に必ず書きます。 # 第一弾書きました。 SVMの理論 part 1 computerはwindowsでOSはwindows10です。Python3で実装します。 このプログラムには内点法という最適化を使っています。 Dataset 次の二つのdastasetを使います。 一つは、完全に分離できるような分布のデータです・ もう一つは完全に分離できないような分布のデータです。 例えば、data1の分布はこのような形になります。 この分布ならきれいに二つのクラスを分けるような線が引けそうですね。 もう一つのデータは次のようなデータを使います。 このデータはきれいに分けるような線は引けなさそうです。 この二つのデータを用いて、線形SVMを使っていきましょう。 Implementation data1 この線が分離面になります。 きれいにいい感じのところに引けてます。 data2 このデータについては様々なCを用いて計算してみました。 Cの値が小さければ小さいほど、誤分類を認めてしまうことになります。 このデータではCの影響を確認しずらいかもしれませんが、\(C=1\) の時、よく見ると、赤色のデータが一つ境界面を飛び出しています。 線形でないSVMを使うとCの影響がもっとわかりやすいかもしれません。 非線形なSVMについては、別の記事で書こうと思います。 CODE コードはすべてgithubに乗せています。 My SVM code is here 今回使ったファイルはgit_SVM_check.pyとgit_SVM_def.pyです。 git_SVM_check.py には次のようなコードが入ったメインファイルです。 if __name__ == '__main__': git_SVM_def にはSVMのクラスと、内点法の実装が入っています。 次は非線形のSVMについても書きたいと思います。 もし、そちらの記事も見ていただけたらハッピーです。

Implement linear SVM

Introduction 日本語 ver Today, I implement liner SVM (support vector machine). SVM is one of the most strong algorithm of machine learning before becoming popular Deep learning. I will write detail of Logic of liner SVM in other posts. # I finished writing theorem of SVM. Theorem of SVM part1 My computer is windows. OS is windows. Program is written by Python3. This program is used Interrior point method in Oputimization. Dataset I used two dataset. First, I used data separated by hyper plane. Second, I used data mixed \(C_1\) and \(C_2\). First data is distributed such as the following. I can write separate line of distribution. Second data is distributed such as the following. I can not write separate line of distribution. I will try liner SVM about these data. Implementation data1 This line is hyper plane. It is written like copperplate. data2 I tried to estimate hyper plane by variable C. C value cause this line. The smoller C value is the ea

Pythonでグラフ理論

Introduction English ver 今日はnetworkxというpythonのモジュールについて書きます。 グラフ理論の定義などの情報は ここ の記事に書いてあります。 この記事ではグラフ理論の中身については扱いませんが、Pythonでのnetworkxというモジュールについてメモをしておきます。 Networkx Python3にはnetworkxはすでに入っています。 Python2の方はpipを使ってinstallしてください。コマンドラインで以下のコマンドを実行します。 pip install networkx ではNetworkxを使ってグラフを作っていきます。 初めにimportをしてインスタンスを作っていきます。 import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() 次にグラフにノード(頂点)とエッジ(枝)を入れていきます。 G.add_node(1) # add Multiple nodes G.add_nodes_from([2,3,4]) G.add_edge(1,2) # add Multiple edges G.add_edges_from([(3,4),(1,2),(4,6)]) ではこのGのグラフを描画していきましょう。 以下のコードで描画できます。 nx.draw(G) plt.show() Networkxはたくさんの関数を持っています。 また、随時追記していきたいと思います。 Reference https://qiita.com/kzm4269/items/081ff2fdb8a6b0a6112f http://akiniwa.hatenablog.jp/entry/2013/05/12/012459

Graph theory in Python

Introduction 日本語 ver Today, I write the networkx module for graph theory in Python. I write about basis of Gragh theory. Please look at this page . This post is not written Graph theory, but I want to share module in Python for Graph theory. Networkx Python3 have Networkx module. If you have python2, you should install by pip pip install networkx Make Graph by Networkx first, import networkx module and make instance. import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() next, add node and edge G.add_node(1) # add Multiple nodes G.add_nodes_from([2,3,4]) G.add_edge(1,2) # add Multiple edges G.add_edges_from([(3,4),(1,2),(4,6)]) next, plot G nx.draw(G) plt.show() networkx have many function. I will write new learning about networkx in this post. Reference https://qiita.com/kzm4269/items/081ff2fdb8a6b0a6112f http://akiniwa.hatenablog.jp/entry/2013/05/12/012459

マハラノビス距離

Introduction English ver 今日はマハラノビス距離について書いていきます。 マハラノビス距離はそれぞれの次元に相関があるときに有効とされています。 ある特徴と特徴に相関があることは往々にしてあると思います。 この距離は距離の公理を満たします。 また、統計学において大事な距離関数になります。 もし、統計や機械学習に興味がおありでしたらぜひこのブログをご覧ください。 概要 距離の公理 マンハッタン距離の定義 マンハッタン距離のイメージ 距離の公理 もし、dが距離関数であるならば、dは次を満たします。 \(d:X \times X -> R\) \(d(x,y) \geq 0\) \(d(x,y) = 0 \leftrightarrow x = y\) \(d(x,y) = d(y,x)\) \(d(x,z) \leq d(x,y) + d(y,z)\) マハラノビス距離 マハラノビス距離は距離関数です。 次のように定義されます。 \[D_{M}(x) = \sqrt{(x-\mu)^T \Sigma^{-1} (x-\mu)}\] ここで、 \(\mu\) is mean vector \[\mu = (\mu_1,\mu_2,....,\mu_n)\] さらに \(\Sigma\) は共分散行列です。 xとyのマハラノビス距離は \begin{eqnarray*} d(x,y) &=& \sqrt{(x-\mu-(y-\mu)^T \Sigma^{-1} (x-\mu-(y-\mu)}\\ &=& \sqrt{(x-y)^T \Sigma^{-1} (x-y)} \end{eqnarray*}です。 マハラノビス距離のイメージ 初めに、ユークリッド距離を見てみましょう。 \[d(x,y) = \sqrt{<x^T,y>}\] ユークリッド距離は \(x\) and \(y\) がもし、ある円の上にあるのなら、同じ距離としてみます。 これはデータが円状に分布しているときに有効になります。 しかし、データが楕円上に分布しているときは、ユークリッド距離は有効ではありません。 なぜなら、上のXとYを同じ距離

Mahalanobis' Distance

Introduction 日本語 ver Today, I will write about Mahalanobis’ Distance. Mahalanobis’ Distance is used when each dimension has a relationship. This distance is fulfilled definition of distance. Mahalanobis’ Distance is important for Statics. If you interested in Statics or Machine Learning, Please see my this blog. Overview definition of distance deficition of Mahalanobis’ Distance image of Mahalanobis’ Distance definition of distance if d is distance function, d if fulfilled following condtion. \(d:X \times X -> R\) \(d(x,y) \geq 0\) \(d(x,y) = 0 \leftrightarrow x = y\) \(d(x,y) = d(y,x)\) \(d(x,z) \leq d(x,y) + d(y,z)\) Mahalanobis’ Distance Mahalanobis’ Distance is distance function. Mahalanobis’ Distance is defined by following from \[D_{M}(x) = \sqrt{(x-\mu)^T \Sigma^{-1} (x-\mu)}\] here, \(\mu\) is mean vector \[\mu = (\mu_1,\mu_2,....,\mu_n)\] and, \(\Sigma\) is variance-convariance matrix. Mahalanobis’ Distance between x and y is \begin{eqnarray*} d

ロジスティック回帰の実装

Introduction English ver 今日はロジスティック回帰の実装を行いました。 初めに、僕のComputerはosはwindowsです。実装はPython3で行います。 最適化にはIRLSを用いています。 ロジスティック回帰の理論偏にロジスティック回帰の詳しい理論や説明を書いています。 ロジスティック回帰の理論編 概要 使うデータ集合について Pythonでのコードを紹介 コマンドラインでの実行結果 Dataset データセットはこちらを使います。 dataset このデータセットには住宅街のデータが入っています。 Python3のPandas.DataFrameでの表示を貼っておきます。 上から五行目までを貼っています。 もし、その家に住人がいるのであれば、Occupancyには1が入っています。 反対に、その家に住人がいるのであれば、Ouucpancyには0が入ります。 このデータセットは約8000個のサンプルが入ったトレーニング用データと、約2000個のサンプルが入ったテスト用のデータがあります。 しかし、今回はトレーニング用に100個、テスト用に100個のデータを使います。僕のcomputerがプログラミング用ではないためです。。。 すいません。。。 CODE このコードはとても長いので、僕のGithubのページに乗せてあるものを見てください。。 githubのページ ロジスティック回帰(def file) ロジスティック回帰(main file) mainファイルには、以下のようなコードが入っているファイルです。コマンドラインで入力するファイルになります。 if __name__ == '__mian__' defファイルには様々な関数が入っています。クラスも使われています。Pythonのクラスについてはまた、機会があれば書きたいと思います。 いざ、実行! w を推定します… wが更新されるごとのクロスエントロピー誤差関数の様子をplotしておきます。 scatterplot でクロスエントロピー誤差関数をplotした画像です。 うまく減少しているのがわかります。 最適化は終わりました。 ではこのモデルのテストを行っていきましょう

Implementation of Logistic Regression

Introduction 日本語ver Today, I implement Logistic Regression. My OS of computer is the windows10. Implementation is used by Python3. I use the IRLS to estimate optimization value. I introduce the theory of Logistic Regression in another post. If you interested, look at  this post . Overview I will introduce used data set I will introduce my code in Python I will show you result on Command line. Dataset I use this dataset to implement Logistic Regression. This dataset is Residential area data. I diplay this data in Pandas DataFrame Python3. This is data set from top to five elements. if people live the house, occupancy is 1. if people do not live the house, occupancy is 0. This data consist of 8000 samples to use as training data, and 2000 samples to use as test data. However I use 100 samples as training data and 100 samples as test data, because my computer is not designated programing. Sorry, . CODE This code is very long. Thus, I publish my code of L

ロジスティック回帰 理論編

Introduction English ver 今日はロジスティック回帰について書こうと思います。ロジスティック回帰は機械学習の中でも基本とされています。ロジスティック回帰は二値を分類するためのアルゴリズム、モデルです。 概要 この記事はPRMLを参考に書かせていただいています。 最適化には反復再重みづけ最小二乗法を用いています。 シグモイド関数 分類のための確率を定義 交差エントロピー誤差関数 反復再重みづけ最小二乗法 シグモイド関数 初めにシグモイド関数を定義します。 以下のような関数です。 \[\sigma(a) = \frac{1}{1+\exp(a)}\] 後に扱うので、シグモイド関数の微分を計算しておきます。きれいな形をしています。 \begin{eqnarray*} \frac{d}{d a} \frac{1}{1+\exp(a)} &=& \frac{\exp(-a)}{(1+\exp(-a))^2} \\ &=& \frac{1}{1+\exp(-a)} \frac{\exp(-a)}{1+\exp(-a)}\\ &=& \frac{1}{1+\exp(-a)} \{ \frac{1+\exp(-a)}{1+\exp(-a)} - \frac{1}{1+\exp(-a)} \} \\ &=& \sigma(a)(1-\sigma(a)) \end{eqnarray*} シグモイド関数は機械学習において大事な役割を果たしています。 シグモイド関数は以下のような形をしています。 これを見てわかる通り、シグモイド関数は次のような性質を持っています。 シグモイド関数は 定義域は\((-\infty,\infty)\)で定義され、値域は\((0,1)\)で定義されています シグモイド関数は単調増加関数です シグモイド関数は(0,0.5)で点対称です シグモイド関数の値を確率として考えることができるようになります。 分類のための確率の定義 初めにデータが正しく分類されたかの確率を考えてみる。 この直線は超平面だと思ってください。 超平面は以下のように表されます。 \[w^T x= 0\] wは超平面に対する法線ベク

Theorem of Logistic regression.

Introduction 日本語ver Today, I will write about Logistic regression. Logistic regression is the basis of Machine Learning. Logistic regression is the model to classify two value Overview This post is written by using PRML for reference. Optimization is used for Iterative reweighted least squares method. First, I will introduce the sigmoid function Second, I will define probability to classify Third, I will write cross-entropy error function Fourth, I will explain IRLS Firstly, We define Sigmoid function. sigmoid function is following. \[\sigma(a) = \frac{1}{1+\exp(a)}\] I will compute differential of this function. \begin{eqnarray*} \frac{d}{d a} \frac{1}{1+\exp(a)} &=& \frac{\exp(-a)}{(1+\exp(-a))^2} \\ &=& \frac{1}{1+\exp(-a)} \frac{\exp(-a)}{1+\exp(-a)}\\ &=& \frac{1}{1+\exp(-a)} \{ \frac{1+\exp(-a)}{1+\exp(-a)} - \frac{1}{1+\exp(-a)} \} \\ &=& \sigma(a)(1-\sigma(a)) \end{eqnarray*} This function is very important in terms in

ヘッセ行列

Introduction English ver 今日は、ヘッセ行列を用いたテイラー展開について書こうと思います。 これは最適化を勉強するにあたって、とても大事になってくるので自分でまとめて残しておくことにしました。とくに、機械学習では最適化を必ず行うため、このブログのタイトルにもマッチした内容だと思います。 . 概要 ヘッセ行列の定義 ベクトルを用いたテイラー展開 関数の最適性 ヘッセ行列の定義 仮定 f は次のような条件を満たす関数です。. f はn次元ベクトルから実数値を出力します。 このベクトルは次のように表せます。 \[x = [x_1,x_2,,,,x_n]\] \(\forall x_i , i \in {1,2,,,n}\), f は二回偏微分可能です。 定義 ヘッセ行列は \(\frac{\partial^2}{\partial x_i \partial x_j}を (i,j)要素に持ちます。\) よってヘッセ行列は次のように表せます。 \[ H(f) = \left( \begin{array}{cccc} \frac{\partial^ 2}{\partial x_1^2} & \frac{\partial^2 f}{\partial x_1 \partial x_2} & &\ldots \frac{\partial^2 f}{\partial x_1 \partial x_n} \\ \frac{\partial^ 2 f}{\partial x_1 \partial x_2} & \frac{\partial^ 2 f}{\partial x_2^ 2} & \ldots & \frac{\partial^2 f}{\partial x_2 \partial x_n} \\ \vdots & \vdots & \ddots & \vdots \\ \frac{\partial^ 2 f}{\partial x_n \partial x_2} & \frac{\partial^ 2 f}{\partial x_n \partial x_2} & \ldo

Hessian Matrix

Introduction 日本語ver Today, I will talk about Taylor expansion with Hessian matrix. It is important for optimization to understand Taylor expansion with Hessian matrix. Especially, Machine learning has always situation about thinking optimization. Thus I will write it to save knowledge about Hessian matrix. Overview Definition of Hessian matrix Expression Taylor expansion with vector Optimality of the function Definition of Hessian matrix Assumption f is a function which meets a condition as follows. f output Real value after getting the n-dimensional vector. This vector is expressed as follows. \[x = [x_1,x_2,,,,x_n]\] \(\forall x_i , i \in {1,2,,,n}\), f have twice partial differential Definition Hessian matrix Hessian matrix have \(\frac{\partial^2}{\partial x_i \partial x_j} f(x) ~in~ ~element~ ~of~ (i,j)\) Thus Hessian matrix is expressed following. \[ H(f) = \left( \begin{array}{cccc} \frac{\partial^ 2}{\partial x_1^2} & \frac{\partial^2 f}{\

ロルの定理

Introduction English ver 今回はロルの定理について書いていきます・ ロルの定理は平均値の定理の証明に使われる定理です。 平均値の定理についてはまた、今度書こうと思います。 ロルの定理の前に最大値原理というものを紹介しておきます。(後で証明に使います。) 最大値原理 fが閉区間上で連続な関数 \(\implies\) fは最大値を持つ(有限値) 証明 最大値原理の証明は難しいです。この投稿で書いてしまうのは大変なので、また、別の投稿で書きたいと思います。 Maximum Principle ロルの定理 fは区間[a,b]で連続で、(a,b)で微分可能とします。 この時 \[f(a) = f(b) \implies \exists ~~c ~~s.t~~ f'(c) = 0 , a<c<b\] 証明 f(x) が定数関数の時、 \[\forall c \in (a,b) , f'(c) = 0\] f(x)が定数関数でない時、 \(\exists t ~~s.t~~f(a) < f(t)\), \(\exists c ~~s.t~~ \max f(x) = f(c)\) by Maximum principle I proof \(f'(c)=0\) f は\(x = c\) で微分可能で、\(f(c) >= f(c+h)\). よって \[f'(c) = \lim_{h \rightarrow +0} \frac{f(c+h) - f(c)}{h} \leq 0\] \[f'(c) = \lim_{h \rightarrow -0} \frac{f(c+h) - f(c)}{h} \geq 0\] よって \[0 \leq \lim_{h \rightarrow -0} \frac{f(c+h) - f(c)}{h} =f'(c) = \lim_{h \rightarrow +0} \frac{f(c+h) - f(c)}{h} \leq 0\] \[f'(c)=0\] \(\exists t ~~s.t f(a)>f(t)\) の時も同様です。 イメージ \(f(3)=

テイラー展開

Introduction English ver 今日はテイラー展開について紹介します。 ここでは、一変数関数だけでなく、多変数関数のテイラー展開も紹介します。 一変数関数のテイラー展開 f(X) は区間(a,b)で連続であり、また、n回微分可能とします。 すると、f(x) は以下のように表せます。 \[\exists c ~~s.t~~ f(b) = \sum_{k=0}^{n-1} f^{(k)}(a)\frac{(b-a)^k}{k!} + f^{(n)}(c) \frac{(b-a)^n}{n!}, c \in (a,b)\] このf(x)を多項式で表したものをテイラー展開といいます。 最後の項は、剰余項と呼ばれます。 多変数関数のテイラー展開 多変数関数のテイラー展開はかなり複雑な形をしています。 fは多変数関数とします。 さらに、m回微分可能な連続関数とします。 この時、 \(f(x_1+h_1,x_2+h_2,.....,x_n+h_n)\) は次のように表せます。 \[\exists \theta ~~s.t~~\] \[f(x_1+h_1,x_2+h_2,...,x_n+h_n)=f(x_1,x_2,...,x_n) + \] \[\sum_{m=0}^{n-1} \frac{1}{m-1} \sum_{k_1=1}^{n} \sum{k_2=1}^{n} ... \sum{k_{m-1}=1}^{n} \frac{\partial^{m-1} f}{\partial x_{k_1} \partial x_{k_2} .... \partial x_{k_{m-1}} }(x_1,x_2,..,x_n)h_{k_1}h_{k_2} ..... h_{k_m-1} \] \[+ \frac{1}{m} \sum_{k_1=1}^{n} \sum_{k_2=1}^{n} ... \sum_{k_m=1}^{n} \frac{\partial^{m} f}{\partial x_{k_1} \partial x_{k_2} ... \partial x_{k_m} }(x_1 + \theta h_1, x_2 + \theta h_2,...., x_n + \theta h_n) h_k{k_1}h_{

Rolle’s theorem

Introduction 日本語 ver This post is written Rolle’s theorem. The mean-value theorem is proved by Rolle’s theorem. I will write Mean-value theorem at a later. I introduce Maximum principle because proving Rolle’s theorem need Maximum principle. Maximum principle It is very easy. f is continuous function on bounded closed interval.\(\implies\)** f have max value.** Proof This proof is difficult. I write this proof in other posts. Maximum Principle Rolle’s theorem f is continuous function on [a,b] and differentiable function on (a,b). \[f(a) = f(b) \implies \exists ~~c ~~s.t~~ f'(c) = 0 , a<c<b\] Proof f(x) is constant function \[\forall c \in (a,b) , f'(c) = 0\] else when \(\exists t ~~s.t~~f(a) < f(t)\), \(\exists c ~~s.t~~ \max f(x) = f(c)\) by Maximum principle I proof \(f'(c)=0\) f is differentiable on \(x = c\) and \(f(c) >= f(c+h)\). Thus \[f'(c) = \lim_{h \rightarrow +0} \frac{f(c+h) - f(c)}{h} \leq 0\] \[f'(c) = \lim

Taylor Expannsion

Introdction 日本語 ver Today, I introduce Taylor Expansion. I write not only One dimensional Taylor Expansion but also Multi dimensional Taylor Expansion. One dimensional Taylor Expansion f(X) is continuously differentiable for n-times on (a,b) f(x) is expressed following. \[\exists c ~~s.t~~ f(b) = \sum_{k=0}^{n-1} f^{(k)}(a)\frac{(b-a)^k}{k!} + f^{(n)}(c) \frac{(b-a)^n}{n!}, c \in (a,b)\] This is called Maclaurin Expansion. The last item is called Remainder term. Multi dimensional Taylor Expansion Multi dimensional Taylor Expansion is complex. f is n-variable function. f is continuously differentiable for m-times. \(f(x_1+h_1,x_2+h_2,.....,x_n+h_n)\) is expressed following. \[\exists \theta ~~s.t~~\] \[f(x_1+h_1,x_2+h_2,...,x_n+h_n)=f(x_1,x_2,...,x_n) + \] \[\sum_{m=0}^{n-1} \frac{1}{m-1} \sum_{k_1=1}^{n} \sum{k_2=1}^{n} ... \sum{k_{m-1}=1}^{n} \frac{\partial^{m-1} f}{\partial x_{k_1} \partial x_{k_2} .... \partial x_{k_{m-1}} }(x_1,x_2,..,x_n)h_{k_1}h_{k_2} .....