<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nana-Korobi &#187; 機械学習</title>
	<atom:link href="http://aokiji.science/blog/?cat=30&#038;feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://aokiji.science/blog</link>
	<description>Without haste, but without rest.</description>
	<lastBuildDate>Mon, 18 Apr 2016 01:53:08 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.1</generator>
	<item>
		<title>最急降下法</title>
		<link>http://aokiji.science/blog/?p=206</link>
		<comments>http://aokiji.science/blog/?p=206#comments</comments>
		<pubDate>Mon, 06 Apr 2015 02:56:18 +0000</pubDate>
		<dc:creator><![CDATA[AoYu]]></dc:creator>
				<category><![CDATA[機械学習]]></category>

		<guid isPermaLink="false">http://aokiji.science/blog/?p=206</guid>
		<description><![CDATA[15/04/06 書きかけ 以下の情報を参考にさせていただきました。  http://gihyo.jp/dev/serial/01/machine-learning]]></description>
				<content:encoded><![CDATA[<p>15/04/06 書きかけ</p>
<h6>以下の情報を参考にさせていただきました。</h6>
<ul>
<li> <a href="http://gihyo.jp/dev/serial/01/machine-learning" target="_blank">http://gihyo.jp/dev/serial/01/machine-learning</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://aokiji.science/blog/?feed=rss2&#038;p=206</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Theano -基本編-</title>
		<link>http://aokiji.science/blog/?p=112</link>
		<comments>http://aokiji.science/blog/?p=112#comments</comments>
		<pubDate>Fri, 03 Apr 2015 03:16:48 +0000</pubDate>
		<dc:creator><![CDATA[AoYu]]></dc:creator>
				<category><![CDATA[Theano]]></category>
		<category><![CDATA[機械学習]]></category>

		<guid isPermaLink="false">http://aokiji.science/blog/?p=112</guid>
		<description><![CDATA[Pythonの数値計算用モジュールの一つである Theano について、基本的な使い方を整理する。余裕があれば、最終的には 公式チュートリアル の和訳版とする。 事前準備 以下の3つは常にimportしておく。 tens [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Pythonの数値計算用モジュールの一つである <a href="http://deeplearning.net/software/theano/index.html">Theano</a> について、基本的な使い方を整理する。余裕があれば、最終的には <a href="http://deeplearning.net/software/theano/tutorial/index.html">公式チュートリアル</a> の和訳版とする。</p>
<p></p>
<h4>事前準備</h4>
<p>以下の3つは常にimportしておく。</p>
<pre class="brush: python; title: ; notranslate">
import numpy as np
from theano import *
import theano.tensor as T
</pre>
<p><code>tensor</code> サブモジュールは頻繁に使うので、扱いやすい名前 (ここでは<strong>T</strong>) でimportしておく。</p>
<h4>NumPyのおさらい</h4>
<p>機械学習において、<a href="http://deeplearning.net/software/theano/index.html">Theano</a> と併せて使うことが多い <a href="http://www.numpy.org">NumPy</a> モジュールについて、基本的な使い方 (主に行列演算の方法) を整理する。</p>
<blockquote><p><ins datetime="2015-04-03T07:04:01+00:00">そのうちまとめる</ins></p></blockquote>
<h4>基本的な使い方</h4>
<ol>
<li><strong>シンボル (変数) </strong>の宣言</li>
<p>数値計算で変数として扱う記号を<strong>シンボル</strong>として宣言する。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dscalar('x')
y = T.dscalar('y')
</pre>
<p>ここでは、倍精度浮動小数点数 (d, double) のスカラー (scalar) を表すシンボル <strong>x</strong> と <strong>y</strong> を宣言している。<code>dscalar</code> というクラスはなく、 <strong>x</strong> や <strong>y</strong> はあくまで <code>TensorVariable</code> クラスのインスタンスである。各インスタンスのtypeという変数に、<strong>変数の型</strong>を示す情報が収納される。</p>
<pre class="brush: python; title: ; notranslate">
type(x)
x.type
T.dscalar
x.type is T.dscalar
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
&lt;class 'theano.tensor.basic.TensorVariable'&gt;
TensorType(float64, scalar)
TensorType(float64, scalar)
True
</pre>
<p>また、括弧の中の文字列はシンボルの名前を指定するもので、必須ではないが、名前を与えておくとエラーメッセージ上に表示されるためデバッグしやすくなる。シンボルの宣言についての詳細は、<strong>4. Tips</strong> で解説する。</p>
<li><strong>数式</strong>の定義</li>
<p>1.で宣言した<strong>シンボル</strong>を組み合わせて、計算したい<strong>数式</strong>を定義する。</p>
<pre class="brush: python; title: ; notranslate">
z = x + y
</pre>
<p>xやyは値を持たない<strong>シンボル</strong>なので、zにも具体的な値は入らず、<strong>&#8216;x + y&#8217;</strong> を意味する<strong>シンボル</strong>になる。<code>theano.pp</code> を用いることで、数式の中身を確認することができる。</p>
<pre class="brush: python; title: ; notranslate">
print pp(z)
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
(x + y)
</pre>
<li><strong>関数</strong>の生成</li>
<p>2.で定義した<strong>数式</strong>を実際に計算するための<strong>関数</strong>を生成する。<strong>関数</strong>は、 <code>theano.function</code> を用いて生成する。第1引数として<strong>シンボルのリスト</strong>、第2引数として<strong>計算したい数式</strong>を与える。それぞれ、<strong>inputs</strong>・<strong>outputs</strong>というキーワード引数としても指定可能。</p>
<pre class="brush: python; title: ; notranslate">
f = function([x, y], z)
# f = function(inputs=[x, y], outputs=z)
</pre>
<p>作成した関数に具体的な値を引数として与えて実行すると、数式の計算結果が返される。引数はNumPy配列 (<code>numpy.array</code>) として解釈され、戻り値もNumPy配列となる。</p>
<pre class="brush: python; title: ; notranslate">
f(2, 3)
f(16.3, 12.1)
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array(5.0)
array(28.4)
</pre>
<p><code>theano.function</code> を呼び出した際に、対象の数式を実現するC言語の計算プログラムがコンパイルされる。そのため、この関数の実行には少し時間がかかる。1つの関数で複数の計算結果を出力したい場合は、<strong>outputs</strong>を数式シンボルのリストにすることもできる。この場合は、<strong>inputs</strong>に与える変数シンボルのリストが全ての数式をカバーしている必要がある。</p>
<pre class="brush: python; title: ; notranslate">
y2 = T.dscalar('y2')
z2 = x + y2
f2 = function([x, y, y2], [z, z2])
f2(3, 5, 9)
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
[array(8.0), array(12.0)]
</pre>
<li><strong>Tips</strong></li>
<p>1.の<strong>シンボル</strong>宣言の際に、<strong>変数の型</strong>を適切に指定することで、スカラー演算のみならず、ベクトル演算や行列演算も計算できる。<strong>変数の型</strong>には、<strong>テンソルの階数</strong>（スカラー・ベクトル・行列などの次元的な概念）と<strong>数値の型</strong>があり、これらを組み合わせることによって指定する。例えば、<code>dmatrix</code> は、倍精度浮動小数点数 (d, double) の行列 (matrix) を意味する。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
f = function([x, y], z)
f([[1, 2], [3, 4]], [[10, 20], [30, 40]])
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array([[ 11.,  22.],
       [ 33.,  44.]])
</pre>
<p>指定できる<strong>変数の型</strong>は、以下の通り (<a href="http://deeplearning.net/software/theano/tutorial/adding.html#adding-two-matrices">公式チュートリアル</a>より引用)。詳細は<a href="http://deeplearning.net/software/theano/library/tensor/basic.html">こちら</a>も参照。</p>
<ul>
<li><strong>byte</strong>: bscalar, bvector, bmatrix, brow, bcol, btensor3, btensor4</li>
<li><strong>16-bit integers</strong>: wscalar, wvector, wmatrix, wrow, wcol, wtensor3, wtensor4</li>
<li><strong>32-bit integers</strong>: iscalar, ivector, imatrix, irow, icol, itensor3, itensor4</li>
<li><strong>64-bit integers</strong>: lscalar, lvector, lmatrix, lrow, lcol, ltensor3, ltensor4</li>
<li><strong>float</strong>: fscalar, fvector, fmatrix, frow, fcol, ftensor3, ftensor4</li>
<li><strong>double</strong>: dscalar, dvector, dmatrix, drow, dcol, dtensor3, dtensor4</li>
<li><strong>complex</strong>: cscalar, cvector, cmatrix, crow, ccol, ctensor3, ctensor4</li>
</ul>
</ol>
<h4>微分の計算</h4>
<p><code>theano.tensor.grad</code> を用いて微分を計算することができる。第1引数として<strong>微分の対象となる数式</strong>、第2引数として<strong>微分を取るシンボル</strong>を与える。それぞれ、 <strong>cost</strong>・<strong>wrt</strong> (with respect to ?) というキーワード引数としても指定可能。実際に数値を求めるためには、通常の<strong>数式</strong>と同じように<strong>関数</strong>を生成する必要がある。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dscalar('x')
y = x ** 2
gy = T.grad(y, x)
f = function([x], gy)
f(4)
f(94.2)
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array(8.0)
array(188.4)
</pre>
<p><code>theano.pp</code> を用いることで、微分式の中身を確認することができる。また、 <code>theano.function.maker.fgraph.outputs[0]</code> に対して <code>theano.pp</code> を用いることで、最適化された微分式を確認することができる。</p>
<pre class="brush: python; title: ; notranslate">
pp(gy)
pp(f.maker.fgraph.outputs[0])
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
'((fill((x ** TensorConstant{2}), TensorConstant{1.0}) * TensorConstant{2}) * (x ** (TensorConstant{2} - TensorConstant{1})))'
'(TensorConstant{2.0} * x)'
</pre>
<p><strong>wrt</strong> に微分を取るシンボルのリストを与えれば、最終的に偏微分値のリストが返される。ここで、偏微分値の順番は、<strong>wrt</strong> に与えたシンボルの順番に対応する。</p>
<pre class="brush: python; title: ; notranslate">
x1, x2, x3 = T.dscalars('x1', 'x2', 'x3')
y = x1 ** 3 + x2 ** 2 + x3
gy = T.grad(y, [x1, x2, x3])
f = function([x1, x2, x3], gy)
f(1, 1, 1)
f(2, 4, 6)
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
[array(3.0), array(2.0), array(1.0)]
[array(12.0), array(8.0), array(1.0)]
</pre>
<h4>tensorのメソッド</h4>
<p>微分以外にも、<code>theano.tensor.XXX</code> を用いて様々な計算をすることができる。以下に、主要なものをまとめる。詳細は<a href="http://deeplearning.net/software/theano/library/tensor/basic.html">こちら</a>を参照。</p>
<ul>
<li>tensor.sum()</li>
<p>引数として与えた<strong>シンボル</strong>（ベクトルなど）の<strong>総和</strong>を返す。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dvector('x')
sum_x = T.sum(x)
f = function([x], sum_x)
f([1, 2, 3, 4, 5])
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array(15.0)
</pre>
<li>tensor.prod()</li>
<p>引数として与えた<strong>シンボル</strong>（ベクトルなど）の<strong>総乗</strong>を返す。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dvector('x')
prod_x = T.prod(x)
f = function([x], prod_x)
f([1, 2, 3, 4, 5])
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array(120.0)
</pre>
<li>tensor.mean()</li>
<p>引数として与えた<strong>シンボル</strong>（ベクトルなど）の<strong>平均</strong>を返す。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dvector('x')
mean_x = T.mean(x)
f = function([x], mean_x)
f([1, 2, 3, 4, 5])
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array(3.0)
</pre>
<li>tensor.var()</li>
<p>引数として与えた<strong>シンボル</strong>（ベクトルなど）の<strong>分散</strong>を返す。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dvector('x')
var_x = T.var(x)
f = function([x], var_x)
f([1, 2, 3, 4, 5])
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array(2.0)
</pre>
<li>tensor.std()</li>
<p>引数として与えた<strong>シンボル</strong>（ベクトルなど）の<strong>標準偏差</strong>を返す。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dvector('x')
std_x = T.std(x)
f = function([x], std_x)
f([1, 2, 3, 4, 5])
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array(1.4142135623730951)
</pre>
<li>tensor.exp()</li>
<p>引数として与えた<strong>シンボル</strong>（スカラー）を冪指数とする<strong>ネイピア数の冪乗</strong>を返す。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dscalar('x')
exp_x = T.exp(x)
sigmoid_x = 1.0 / (1.0 + T.exp(-x))
f = function([x], [exp_x, sigmoid_x])
for x in [-4, -2, -1, 0, 1, 2, 4]:
    print x, f(x)
# Create Sigmoid Curve
X = range(-10,11)
Y = []
for x in X:
    Y.append(f(x)[1])
import matplotlib.pyplot as plt
plt.plot(X, Y)
plt.show()
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
-4 [array(0.01831563888873418), array(0.01798620996209156)]
-2 [array(0.1353352832366127), array(0.11920292202211755)]
-1 [array(0.36787944117144233), array(0.2689414213699951)]
0 [array(1.0), array(0.5)]
1 [array(2.718281828459045), array(0.7310585786300049)]
2 [array(7.38905609893065), array(0.8807970779778823)]
4 [array(54.598150033144236), array(0.9820137900379085)]
</pre>
<p><a href="http://aokiji.science/blog/wp-content/uploads/2015/04/sigmoid1.png"><img src="http://aokiji.science/blog/wp-content/uploads/2015/04/sigmoid1.png" alt="sigmoid" width="800" height="502" class="alignnone size-full wp-image-200" /></a></p>
<li>tensor.log()</li>
<p>引数として与えた<strong>シンボル</strong>（スカラー）の<strong>自然対数</strong>を返す。<code>tensor.log2()</code> および <code>tensor.log()</code> を用いることで、底を2または10とした対数を返すこともできる。</p>
<pre class="brush: python; title: ; notranslate">
x = T.dscalar('x')
log_x = T.log(x)
log2_x = T.log2(x)
log10_x = T.log10(x)
f = function([x], [log_x, log2_x, log10_x])
f(8)
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
[array(2.0794415416798357), array(3.0), array(0.9030899869919435)]
</pre>
<li>tensor.dot()</li>
<p>引数として与えた<strong>2つのシンボル</strong>（ベクトルか行列）の<strong>内積</strong>を返す。</p>
<pre class="brush: python; title: ; notranslate">
x1, x2 = T.dvectors('x1', 'x2')
dot_x = T.dot(x1, x2)
f = function([x1, x2], dot_x)
f([1, 2, 3], [6, -5, 4])
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
array(8.0)
</pre>
</ul>
<h4>共有変数</h4>
<p><code>theano.shared</code> を用いて<strong>共有変数</strong>を宣言することができる。<strong>共有変数</strong>は、複数の関数から参照することができる。値の参照には <code>shared.get_value()</code> を、値の変更には <code>shared.set_value()</code> を用いる。</p>
<pre class="brush: python; title: ; notranslate">
s = shared(5, name='s')
x = T.iscalar('x')
f1 = function([x], x+s)
f2 = function([x], x-s)
f3 = function([], s*3)
s.get_value()
f1(7), f2(7), f3()
s.set_value(-10)
s.get_value()
f1(7), f2(7), f3()
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
5
(array(12), array(2), array(15))
-10
(array(-3), array(17), array(-30))
</pre>
<p>確率モデルのパラメータなどの計算過程で頻繁に更新する変数は、<strong>共有変数</strong>で宣言しておくことで無駄なメモリコピーを削減できる。<code>theano.function</code> のパラメータの1つである <code>updates</code> と組み合わせることで効率的な計算が可能となる。</p>
<pre class="brush: python; title: ; notranslate">
state = shared(0)
inc = T.iscalar('inc')
accumulator = function([inc], state, updates=[(state, state+inc)])
decrementor = function([inc], state, updates=[(state, state-inc)])
state.get_value()
accumulator(5)
state.get_value()
decrementor(3)
state.get_value()
</pre>
<pre class="brush: plain; title: 実行結果; notranslate">
0
array(0)
5
array(5)
2
</pre>
<h4>応用例：ロジスティック回帰</h4>
<p>上述した<strong>基本的な使い方</strong>、<strong>微分の計算</strong>、<strong>共有変数</strong>を組み合わせることで、ロジスティック回帰を実装することができる (<a href="http://deeplearning.net/software/theano/tutorial/examples.html#a-real-example-logistic-regression">公式チュートリアル</a>より引用)。最急降下法については<a href="http://aokiji.science/blog/?p=206" title="最急降下法">こちらの記事</a>を参照。</p>
<pre class="brush: python; title: ; notranslate">
import numpy
import theano
import theano.tensor as T
rng = numpy.random

N = 400
feats = 784
D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2))
training_steps = 10000

# Declare Theano symbolic variables
x = T.matrix(&quot;x&quot;)
y = T.vector(&quot;y&quot;)
w = theano.shared(rng.randn(feats), name=&quot;w&quot;)
b = theano.shared(0., name=&quot;b&quot;)
print &quot;Initial model:&quot;
print w.get_value(), b.get_value()

# Construct Theano expression graph
p_1 = 1 / (1 + T.exp(-T.dot(x, w) - b))   # Probability that target = 1
prediction = p_1 &gt; 0.5                    # The prediction thresholded
xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) # Cross-entropy loss function
cost = xent.mean() + 0.01 * (w ** 2).sum()# The cost to minimize
gw, gb = T.grad(cost, [w, b])             # Compute the gradient of the cost
                                          # (we shall return to this in a
                                          # following section of this tutorial)

# Compile
train = theano.function(
          inputs=[x,y],
          outputs=[prediction, xent],
          updates=((w, w - 0.1 * gw), (b, b - 0.1 * gb)))
predict = theano.function(inputs=[x], outputs=prediction)

# Train
for i in range(training_steps):
    pred, err = train(D[0], D[1])

print &quot;Final model:&quot;
print w.get_value(), b.get_value()
print &quot;target values for D:&quot;, D[1]
print &quot;prediction on D:&quot;, predict(D[0])
</pre>
<h6>以下の情報を参考にさせていただきました。</h6>
<ul>
<li> <a href="http://d.hatena.ne.jp/saket/20121207/1354867911" target="_blank">http://d.hatena.ne.jp/saket/20121207/1354867911</a></li>
<li> <a href="http://qiita.com/mokemokechicken/items/3fbf6af714c1f66f99e9" target="_blank">http://qiita.com/mokemokechicken/items/3fbf6af714c1f66f99e9</a></li>
<li> <a href="http://www.chino-js.com/ja/tech/theano-rbm/" target="_blank">http://www.chino-js.com/ja/tech/theano-rbm/</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://aokiji.science/blog/?feed=rss2&#038;p=112</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
