SlideShare a Scribd company logo
Numpy および Python
プログラミング言語
22018年3月1日 D-WiSE LT
C言語
✦ 1972年に開発された汎用高級言語
✦ 機械語に近い構成による高速な実行速度
✦ ポインタのポインタに代表される難解な仕様
✦ 習得難易度が高い
Python
✦ 1991年に開発された汎用高級言語
✦ 豊富なライブラリ(モジュール)による拡張
✦ 簡易な文法により記述することができる
✦ 習得難易度が低い
✦ 速度がC言語と比較して劣る
プログラミング言語
32018年3月1日 D-WiSE LT
C言語 Python
✦ 科学計算用に設計された言語ではない
✦ 自分で多くを定義する必要がある
e.g. 構造体,クラス,関数
✦ 本来の趣旨から離れた作業が必要
✦ 科学計算用に設計されたPythonのライブラリ
✦ 行列演算など算術計算が高速
Numpyを使おう!
Numpy
42018年3月1日 D-WiSE LT
Pythonで用いられる科学計算用ライブラリ
✦ 内部はCで実装されている
✦ その他の数学・解析系ライブラリにおける基盤
✦ JuliaやRubyなど多言語での利用も可能
本編の前に…
52018年3月1日 D-WiSE LT
表記
#include <stdio.h>
int main(void){
return 0;
}
❖ コード名
https://github.com/Scstechr/D-WiSE_LT/tree/
master/180301/codes
リンク
Pythonのヴァージョン
Python 3.6.4
Hello World
62018年3月1日 D-WiSE LT
C言語
#include <stdio.h>
int main(void){
printf(“Hello Worldn”);
return 0;
}
❖ hello.c
✤ コンパイル
$ gcc hello.c
✤ 実行
$ ./a.out
Hello World
Hello World
72018年3月1日 D-WiSE LT
Python
print(“Hello World”)
❖ hello.py
❖ 実行
$ python hello.py
Hello World
def main():
print("Hello World")
if __name__ == "__main__":
main()
❖ hello_main.py
逐次コンパイルを行うため事前コンパイルは不要
Hello World
82018年3月1日 D-WiSE LT
比較
❖ hello.c
print(“Hello World”)
❖ hello.py
#include <stdio.h>
int main(void){
printf("Hello Worldn");
return 0;
}
同じ処理を少ない行数で記述することが可能
デバッグの負担を軽減する
Hello World
92018年3月1日 D-WiSE LT
def main():
print("Hello World")
if __name__ == "__main__":
main()
#include <stdio.h>
int main(void){
printf("Hello Worldn");
return 0;
}
比較
❖ hello.c
❖ hello_main.py
配列の初期化
102018年3月1日 D-WiSE LT
C言語
int main(void){
int array[10];
for(int i = 0; i < 10; i++){
array[i] = 0;
}
return 0;
}
❖ array.c
array[] = {0,0,0,0,0,0,0,0,0,0}
配列の初期化
112018年3月1日 D-WiSE LT
Python
def main():
lst = []
for i in range(10):
lst.append(0)
if __name__ == "__main__":
main()
❖ array.py
リスト ( list )
✤ 多機能なPythonの配列
✤ lst.append() は()の中身を末尾に追加
lst = [0 0 0 0 0 0 0 0 0 0]
配列の初期化
122018年3月1日 D-WiSE LT
比較
❖ array.py❖ array.c
int main(void){
int array[10];
for(int i = 0; i < 10; i++){
array[i] = 0;
}
return 0;
}
def main():
lst = []
for i in range(10):
lst.append(0)
if __name__ == "__main__":
main()
132018年3月1日 D-WiSE LT
比較
❖ array.py❖ array.c
int main(void){
int array[10];
for(int i = 0; i <
10; i++){
array[i] = 0;
def main():
lst = []
for i in
range(10):
lst.append(0)
変数の型付け
✤ C言語: 静的型付け (変数宣言時に型宣言を行う)
✤ Python: 動的型付け (右辺により型変化)
配列の初期化
配列の初期化
142018年3月1日 D-WiSE LT
リスト内包表記
リストの初期化は「リスト内包表記」で一文で書ける
❖ array_comp.py
def main():
lst = [0 for i in range(10)]
if __name__ == "__main__":
main()
配列の初期化
152018年3月1日 D-WiSE LT
コンストラクタ
❖ array_const.py
def main():
lst = list(range(10))
if __name__ == "__main__":
main()
for文を使わない分リスト内包表記より(おそらく)速い
配列を出力する
162018年3月1日 D-WiSE LT
C言語
❖ array_print.c
#include <stdio.h>
int main(void){
int array[10];
for(int i = 0; i < 10; i++){
array[i] = i;
}
for(int i = 0; i < 10; i++){
printf(“%dn”, array[i]);
}
return 0;
}
$ gcc array_print.c
$ ./a.out
0
1
2
3
4
5
6
7
8
9
配列を出力する
172018年3月1日 D-WiSE LT
Python
❖ array_print.py
def main():
lst = [i for i in range(10)]
for i in lst:
print(i)
# [print(i) for i in lst]
if __name__ == ‘__main__’:
main()
$ python array_print2.py
0
1
2
3
4
5
6
7
8
9
Pythonにおける出力
182018年3月1日 D-WiSE LT
print()
❖ array_print2.py
$ python array_print2.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print()
✤ ()の中身に合わせて出力を変化
def main():
lst = [i for i in range(10)]
print(lst)
if __name__ == ‘__main__’:
main()
def main():
print(‘Hello World’)
if __name__ == ‘__main__’:
main()
$ python hello_main.py
Hello World
❖ hello_main.py
配列を出力する
192018年3月1日 D-WiSE LT
C言語で同様の動作を実装する (関数 )
❖ array_print2.c (1/2)
#include <stdio.h>
void print(int *array, int size){
printf("[");
for(int i = 0; i < size; i++){
printf("%d,", array[i]);
}
printf("b]n");
}
配列のポインタとサイズを受け取る関数を定義
配列を出力する
202018年3月1日 D-WiSE LT
C言語で同様の動作を実装する (関数 )
❖ array_print2.c (2/2)
int main(void){
int array[10];
for(int i = 0; i < 10; i++){
array[i] = i;
}
print(array, 10);
return 0;
}
配列を出力する
212018年3月1日 D-WiSE LT
C言語で同様の動作を実装する (構造体 )
❖ array_print3.c (1/3)
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 10
typedef struct{
int array[ARRAY_SIZE];
int size;
} Array;
配列とサイズで構成される構造体を定義
配列を出力する
222018年3月1日 D-WiSE LT
C言語で同様の動作を実装する (構造体 )
❖ array_print3.c (2/3)
void print(Array *array){
printf("[");
for(int i = 0; i < array->size; i++){
printf("%d,", array->array[i]);
}
printf("b]n");
}
構造体のポインタを受け取る関数を定義
配列を出力する
232018年3月1日 D-WiSE LT
C言語で同様の動作を実装する (構造体 )
❖ array_print3.c (3/3)
int main(void){
Array *array = (Array*)malloc(sizeof(Array));
array->size = 10;
for(int i = 0; i < array->size; i++){
array->array[i] = i;
}
print(array);
free(array);
return 0;
}
配列を出力する
242018年3月1日 D-WiSE LT
int型の(一次元の)配列にしか有効ではない
❖ array_print3.c❖ array_print2.c
#include <stdio.h>
void print(int *array, int size){
printf("[");
for(int i = 0; i < size; i++){
printf("%d,", array[i]);
}
printf("b]n");
}
int main(void){
int array[10];
for(int i = 0; i < 10; i++){
array[i] = i;
}
print(array, 10);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 10
typedef struct{
int array[ARRAY_SIZE];
int size;
} Array;
void print(Array *array){
printf("[");
for(int i = 0; i < array->size; i++){
printf("%d,", array->array[i]);
}
printf("b]n");
}
int main(void){
Array *array = (Array*)malloc(sizeof(Array));
array->size = 10;
for(int i = 0; i < array->size; i++){
array->array[i] = i;
}
print(array);
free(array);
return 0;
}
配列を出力する
252018年3月1日 D-WiSE LT
Pythonのprint()の凄さ
#include <stdio.h>
void print(int *array, int size){
printf("[");
for(int i = 0; i < size; i++){
printf("%d,", array[i]);
}
printf("b]n");
}
int main(void){
int array[10];
for(int i = 0; i < 10; i++){
array[i] = i;
}
print(array, 10);
return 0;
}
❖ array_print2.py
def main():
lst = [i for i in range(10)]
print(lst)
if __name__ == ‘__main__’:
main()
❖ array_print2.c
262018年3月1日 D-WiSE LT
Pythonのlistの凄さ
$ python
Python 3.6.2 |Anaconda custom (64-bit)| (default,
Jul 20 2017, 13:14:59)
[ G C C 4 . 2 . 1 C o m p a t i b l e A p p l e L L V M 6 . 0
(clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license"
for more information.
>>> exit()
$
✤ 対話型インタープリタの起動
簡単な動作確認をすることができる
Pythonのデバッグのお供
272018年3月1日 D-WiSE LT
Pythonのlistの凄さ
>>> dir(list)
[ ' _ _ a d d _ _ ' , ' _ _ c l a s s _ _ ' , ' _ _ c o n t a i n s _ _ ' ,
'__delattr__', '__delitem__', '__dir__', '__doc__',
' _ _ e q _ _ ' , ' _ _ f o r m a t _ _ ' , ' _ _ g e _ _ ' ,
'__getattribute__', '__getitem__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__',
' _ _ r e p r _ _ ' , ' _ _ r e v e r s e d _ _ ' , ' _ _ r m u l _ _ ' ,
'__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'clear',
'copy', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
✤ 充実した既存の関数群
Pythonのデバッグのお供
Pythonのデバッグのお供
282018年3月1日 D-WiSE LT
その他の有用な機能
>>> help(list.append)
Help on method_descriptor:
append(...)
L.append(object) -> None -- append object to end
✤ help(): 関数その他の詳細をviで出力 (qで抜け出す)
>>> lst = list(range(10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> type(lst)
<class 'list'>
✤ type(): インスタンスの種類を出力
実行時間
292018年3月1日 D-WiSE LT
比較
$ time ./a.out
[0,1,2,3,4,5,6,7,8,9]
❖ array_print2.py
❖ array_print3.c
real 0m0.007s
user 0m0.002s
sys 0m0.002s
$ time python array_print2.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
real 0m0.062s
user 0m0.039s
sys 0m0.015s
Pythonは遅い!
Numpy
302018年3月1日 D-WiSE LT
PythonのNumpyの凄さ
$ python
Python 3.6.2 |Anaconda custom (64-bit)| (default,
Jul 20 2017, 13:14:59)
[ G C C 4 . 2 . 1 C o m p a t i b l e A p p l e L L V M 6 . 0
(clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license"
for more information.
>>>
✤ 対話型インタープリタの起動
Numpy
312018年3月1日 D-WiSE LT
>>> import numpy as np
✤ importする
Pythonのライブラリ利用法
★ C言語の類似表記:
numpyを書くのは長いのでnpと表記する (慣例)
#include <stdio.h>
#include “myheader.h”
★ Pythonの場合は出自を記す必要がある
import numpy as np
#numpyで定義されたsum()を使いたい
np.sum()
Numpy
322018年3月1日 D-WiSE LT
PythonのNumpyの凄さ
>>> dir(np)
['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource',
'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT',
'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO',
'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf',
'Infinity', 'MAXDIMS', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'MachAr',
'ModuleDeprecationWarning', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF',
'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO',
'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType',
'Tester', 'TooHardError', 'True_', 'UFUNC_BUFSIZE_DEFAULT',
'UFUNC_PYVALS_NAME', 'VisibleDeprecationWarning', 'WRAP', '_NoValue',
'__NUMPY_SETUP__', '__all__', '__builtins__', '__cached__',
'__config__', '__doc__', '__file__', '__git_revision__', '__loader__',
'__name__', '__package__', '__path__', '__spec__', '__version__',
'_import_tools', '_mat', 'abs', 'absolute', 'absolute_import', 'add',
'add_docstring', 'add_newdoc', 'add_newdoc_ufunc', 'add_newdocs',
'alen', 'all', 'allclose', 'alltrue', 'alterdot', 'amax', 'amin',
'angle', 'any', 'append', 'apply_along_axis', 'apply_over_axes',
'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2',
'arctanh', 'argmax', 'argmin', 'argpartition', 'argsort', 'argwhere',
✤ 豊富な関数群
Numpy
332018年3月1日 D-WiSE LT
PythonのNumpyの凄さ
>>> dir(np.ndarray)
[ ' T ' , ' _ _ a b s _ _ ' , ' _ _ a d d _ _ ' , ' _ _ a n d _ _ ' , ' _ _ a r r a y _ _ ' ,
'__array_finalize__', '__array_interface__', '__array_prepare__',
'__array_priority__', '__array_struct__', '__array_wrap__', '__bool__',
'__class__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dir__', '__divmod__', '__doc__', '__eq__',
'__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__',
'__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__',
'__index__', '__init__', '__init_subclass__', '__int__', '__invert__',
'__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__',
'__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__',
'__matmul__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__',
'__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__',
'__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__',
'__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__',
'__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
'__rxor__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__',
'__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__',
'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype',
✤ 多次元行列(np.ndarray)に限っても豊富
Numpy
342018年3月1日 D-WiSE LT
listからnp.ndarrayへの変換
import numpy as np
def main():
lst = [i for i in range(10)]
print(lst, type(lst))
array = np.array(lst)
print(array, type(array))
if __name__ == "__main__":
main()
❖ np_array.py
$ python np_array.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
[0 1 2 3 4 5 6 7 8 9] <class ‘numpy.ndarray'>
352018年3月1日 D-WiSE LT
numpyで定義された関数を用いる
Numpy
import numpy as np
def main():
#array = np.array([i for i in range(10)])
array = np.arange(10)
print(array)
if __name__ == "__main__":
main()
np.arange(n): 0~n-1で初期化された一次元配列
❖ np_array2.py
362018年3月1日 D-WiSE LT
比較
❖ array_print2.py
$ time python array_print2.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
real 0m0.062s
user 0m0.039s
sys 0m0.015s
❖ np_array2.py
$ time python np_array2.py
[0 1 2 3 4 5 6 7 8 9]
real 0m0.239s
user 0m0.161s
sys 0m0.062s
実行時間の計測: Python
372018年3月1日 D-WiSE LT
numpyをimportするオーバーヘッド
❖ import_numpy.py
$ cat import_numpy.py
import numpy as np
$ time python import_numpy.py
real 0m0.226s
user 0m0.149s
sys 0m0.062s
❖ array_print2.py
real 0m0.062s
user 0m0.039s
sys 0m0.015s
❖ array_print2.py
real 0m0.013s
user 0m0.012s
sys 0m0.000s
real 0m0.239s
user 0m0.161s
sys 0m0.062s
→
実行時間の計測: Python
382018年3月1日 D-WiSE LT
ipythonを利用する
$ ipython
Python 3.6.2 |Anaconda custom (64-bit)| (default,
Jul 20 2017, 13:14:59)
Type 'copyright', 'credits' or 'license' for more
information
IPython 6.2.1 -- An enhanced Interactive Python.
Type '?' for help.
In [1]: list.append?
Docstring: L.append(object) -> None -- append
object to end
Type: method_descriptor
In [2]:
✤ 多機能の対話型インタープリタの起動
実行時間の計測: Python
392018年3月1日 D-WiSE LT
In [1]: import numpy as np
ipythonを利用する
✤ Numpyをimport
In [2]: def range_list(n):
...: lst = list(range(n))
...:
In [3]: def arange_np(n):
...: array = np.arange(n)
...:
✤ nを引数とする関数を定義
実行時間の計測: Python
402018年3月1日 D-WiSE LT
ipythonを利用する
✤ %timeitで計測 (要素数10の1次元配列)
In [4]: %timeit range_list(10)
878 ns ± 31.8 ns per loop (mean ± std.
dev. of 7 runs, 1000000 loops each)
In [5]: %timeit arange_np(10)
872 ns ± 32.8 ns per loop (mean ± std.
dev. of 7 runs, 1000000 loops each)
実行時間の計測: Python
412018年3月1日 D-WiSE LT
ipythonを利用する
✤ %timeitで計測 (要素数10000の1次元配列)
In [6]: %timeit range_list(10000)
238 µs ± 9.11 µs per loop (mean ± std.
dev. of 7 runs, 1000 loops each)
In [7]: %timeit arange_np(10000)
5.87 µs ± 179 ns per loop (mean ± std.
dev. of 7 runs, 100000 loops each)
実行時間の計測: Python
実行時間: C
422018年3月1日 D-WiSE LT
time.hを利用する
❖ array_10k.c (1/3)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAY_SIZE 10000
#define TRIAL 100000
typedef struct{
int data[ARRAY_SIZE];
int size;
} Array;
ヘッダのincludeと定数・構造体の定義
432018年3月1日 D-WiSE LT
❖ array_10k.c (2/3)
void process(){
Array *array = (Array*)malloc(sizeof(Array));
array->size = 10000;
for(int i = 0; i < array->size; i++){
array->data[i] = i;
}
}
配列の初期化を関数として切り出す
実行時間: C
time.hを利用する
442018年3月1日 D-WiSE LT
❖ array_10k.c (3/3)
int main(){
clock_t t1, t2;
double sum; sum = 0;
for(int i = 0; i < TRIAL; i++){
t1 = clock();process();t2 = clock();
sum += (double)(t2-t1)/CLOCKS_PER_SEC;
}
printf("%fn", (double)sum / TRIAL);
return 0;
}
実行時間: C
time.hを利用する
452018年3月1日 D-WiSE LT
❖ array_10k.c
$ ./array_10k.out
0.000034
実行時間
time.hを利用する
種類 実行時間
Python
list 238 [µs]
numpy 5.86 [µs]
C 34 [µs]
比較
Pythonは遅い!
Numpy - 配列の初期化
462018年3月1日 D-WiSE LT
ipythonを利用する
$ ipython
Python 3.6.2 |Anaconda custom (64-bit)| (default,
Jul 20 2017, 13:14:59)
Type 'copyright', 'credits' or 'license' for more
information
IPython 6.2.1 -- An enhanced Interactive Python.
Type '?' for help.
✤ 多機能型の対話型インタープリタの起動
In [1] : import numpy as np
✤ Numpyをimport
472018年3月1日 D-WiSE LT
全零行列
In [2]: np.zeros(10)
Out[2]: array([ 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0.])
✤ np.zeros()
全一行列
In [3]: np.ones(10)
Out[3]: array([ 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1.])
✤ np.ones()
Numpy - 配列の初期化
Numpy - 多次元行列を定義
482018年3月1日 D-WiSE LT
In [4]: np.array([[0,1],[2,3]])
Out[4]:
array([[0, 1],
[2, 3]])
listを変換
In [5]: np.arange(4).reshape([2,2])
Out[5]:
array([[0, 1],
[2, 3]])
np.reshape()で1次元配列を多次元へ変換

0 1
2 3
492018年3月1日 D-WiSE LT
In [6]: np.zeros([2,2])
Out[6]:
array([[ 0., 0.],
[ 0., 0.]])
全零行列 np.zeros()

0 0
0 0
In [7]: np.ones([2,2])
Out[7]:
array([[ 1., 1.],
[ 1., 1.]])
全一行列 np.ones()

1 1
1 1
In [8]: np.identity(2)
Out[8]:
array([[ 1., 0.],
[ 0., 1.]])
単位行列 np.identity()

1 0
0 1
Numpy - 多次元行列を定義
502018年3月1日 D-WiSE LT
Numpy - 行列演算
a =
2
4
1
2
3
3
5 , b =
2
4
4
5
6
3
5
In [9]: a = np.array([1,2,3])
In [9]: b = np.array([4,5,6])
In [10]: a + b
Out[10]: array([5, 7, 9])
加算
In [11]: a - b
Out[11]: array([-3, -3, -3])
減算
512018年3月1日 D-WiSE LT
Numpy - 行列演算
a =
2
4
1
2
3
3
5 , b =
2
4
4
5
6
3
5
In [9]: a = np.array([1,2,3])
In [9]: b = np.array([4,5,6])
In [12]: a * b
Out[12]: array([ 4, 10, 18])
乗算
In [13]: a / b
Out[13]: array([ 0.25, 0.4 , 0.5 ])
除算
522018年3月1日 D-WiSE LT
Numpy - 線形代数
np.linalg
>>> dir(np.linalg)
['LinAlgError', '__builtins__', '__cached__',
'__doc__', '__file__', '__loader__', '__name__',
' _ _ p a c k a g e _ _ ' , ' _ _ p a t h _ _ ' , ' _ _ s p e c _ _ ' ,
' _ n u m p y _ t e s t e r ' , ' _ u m a t h _ l i n a l g ' ,
'absolute_import', 'bench', 'cholesky', 'cond',
'det', 'division', 'eig', 'eigh', 'eigvals',
'eigvalsh', 'info', 'inv', 'lapack_lite', 'linalg',
' l s t s q ' , ' m a t r i x _ p o w e r ' , ' m a t r i x _ r a n k ' ,
'multi_dot', 'norm', 'pinv', 'print_function',
'qr', 'slogdet', 'solve', 'svd', 'tensorinv',
'tensorsolve', 'test']
>>>
532018年3月1日 D-WiSE LT
Numpy - 線形代数
In [14]: c = np.arange(1,5).reshape(2,2)
In [15]: np.linalg.det(c)
Out[15]: -2.0000000000000004
行列式: det c
In [16]: np.linalg.norm(c)
Out[16]: 5.4772255750516612
ノルム: ||c||
c =

1 2
3 4
542018年3月1日 D-WiSE LT
Numpy - 線形代数
In [14]: c = np.arange(1,5).reshape(2,2)
In [17]: np.linalg.inv(c)
Out[17]:
array([[-2. , 1. ],
[ 1.5, -0.5]])
逆行列: c-1
c =

1 2
3 4
552018年3月1日 D-WiSE LT
Numpy - 乱数生成
random (既存ライブラリ)
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random',
' S G _ M A G I C C O N S T ' , ' S y s t e m R a n d o m ' , ' T W O P I ' ,
'_BuiltinMethodType', '_MethodType', '_Sequence', '_Set',
'__all__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__',
'__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e',
'_exp', '_inst', '_itertools', '_log', '_pi', '_random',
'_sha512', '_sin', '_sqrt', '_test', '_test_generator',
'_urandom', '_warn', 'betavariate', 'choice', 'choices',
'expovariate', 'gammavariate', 'gauss', 'getrandbits',
' g e t s t a t e ' , ' l o g n o r m v a r i a t e ' , ' n o r m a l v a r i a t e ' ,
'paretovariate', 'randint', 'random', 'randrange', 'sample',
'seed', 'setstate', 'shuffle', 'triangular', 'uniform',
'vonmisesvariate', 'weibullvariate']
562018年3月1日 D-WiSE LT
Numpy - 乱数生成
np.random
>>> dir(np.random)
['Lock', 'RandomState', '__RandomState_ctor', '__all__',
'__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__path__',
'__spec__', '_numpy_tester', 'absolute_import', 'bench',
'beta', 'binomial', 'bytes', 'chisquare', 'choice',
'dirichlet', 'division', 'exponential', 'f', 'gamma',
'geometric', 'get_state', 'gumbel', 'hypergeometric', 'info',
'laplace', 'logistic', 'lognormal', 'logseries', 'mtrand',
'multinomial', 'multivariate_normal', 'negative_binomial',
'noncentral_chisquare', 'noncentral_f', 'normal', 'np',
'operator', 'pareto', 'permutation', 'poisson', 'power',
'print_function', 'rand', 'randint', 'randn', 'random',
'random_integers', 'random_sample', 'ranf', 'rayleigh',
'sample', 'seed', 'set_state', 'shuffle', 'standard_cauchy',
'standard_exponential', 'standard_gamma', 'standard_normal',
'standard_t', 'test', 'triangular', 'uniform', 'vonmises',
'wald', 'warnings', 'weibull', 'zipf']
572018年3月1日 D-WiSE LT
Numpy - 異なる分布による乱数生成
一様分布: np.random.rand()
import numpy as np
import matplotlib.pyplot as plt
def main():
R = np.random.rand(10000)
plt.hist(R, bins=1000)
plt.show()
if __name__ == "__main__":
main()
❖ np_rand.py
一様分布
582018年3月1日 D-WiSE LT
Numpy - 異なる分布による乱数生成
標準正規分布 N(0,1): np.random.randn()
import numpy as np
import matplotlib.pyplot as plt
def main():
R = np.random.randn(10000)
plt.hist(R, bins=1000)
plt.show()
if __name__ == "__main__":
main()
❖ np_randn.py
標準正規分布
N(0, 1)
592018年3月1日 D-WiSE LT
Numpy - 分布関数で決定
ランダムに選択: np.random.choice()
import numpy as np
import matplotlib.pyplot as plt
def main():
array = np.arange(9)
pmf = np.zeros(9)
pmf[2] = 0.5
pmf[3] = 0.28
pmf[8] = 0.22
R = np.random.choice(array, size = 10000, p=pmf)
#print(R)
plt.hist(R, bins=100)
plt.show()
if __name__ == "__main__":
main()
❖ np_rand_choice.py
⇤8(x) = 0.5x2
+ 0.28x3
+ 0.22x8
602018年3月1日 D-WiSE LT
Numpy - 分布関数で決定
ランダムに選択: np.random.choice()
import numpy as np
import matplotlib.pyplot as plt
def main():
array = np.arange(9)
pmf = np.zeros(9)
pmf[2] = 0.5
pmf[3] = 0.28
pmf[8] = 0.22
R = np.random.choice(array, size = 10000, p=pmf)
#print(R)
plt.hist(R, bins=100)
plt.show()
if __name__ == "__main__":
main()
❖ np_rand_choice.py
⇤8(x) = 0.5x2
+ 0.28x3
+ 0.22x8
612018年3月1日 D-WiSE LT
まとめ
Python
• 簡潔に記述できるためデバッグしやすい
• C言語と比較すると実行速度が遅い
• そのままでは科学計算用には適していない
Numpy
• Pythonの科学計算用ライブラリ
• 内部がCで記述されており高速な演算が可能
• 豊富なライブラリ関数による簡易な実装
622018年3月1日 D-WiSE LT
その他の数学用ライブラリ
Scipy: 算術計算用のライブラリ
• 微分積分や疎行列などを定義している
• NumpyにないものはおそらくScipyにある
Sympy: 変数をシンボルとして扱うためのライブラリ
• x, yなどに具体的に値を代入する必要がない
• 極限などよりテーラー展開など応用数学分野に強い
• 式の展開とか整理に利用?
632018年3月1日 D-WiSE LT
NumpyおよびPythonの使い方
処理の流れをPythonで決める
実行速度に満足したか?
Cで書き直す?
いいえはい
いいえはい
修羅の道へ…
642018年3月1日 D-WiSE LT
おすすめ
• YouTubeなどでカンファレンス動画を観る
• PyData, Enthought, Next Day Video, PyCon
• オライリー本を買う
• GitHubなどでコードを漁る
• 公式ドキュメントを熟読する
• 新しいメソッドを知るごとに処理速度が変化
652018年3月1日 D-WiSE LT
補助
662018年3月1日 D-WiSE LT
まとめ
1950s Fortran
1960s BASIC
1970s C SQL SmallTalk
1980s C++ Common Lisp Perl
1990s Python Ruby Haskell
2000s C# Go Nim
2010s Rust Julia Kotlin
プログラミング言語年代記
672018年3月1日 D-WiSE LT
Pythonを使いつつ速度を求める
Cython
• PythonをCに変換する
• コードが汚くなる代わりに速い
Numba
• JIT (Just-In-Time)コンパイラ
• 機械語に変換し速度向上を目指す
Pypy
• 速度向上を目指すPythonのヴァージョン

More Related Content

What's hot (16)

PDF
R3.0.0 is relased
Shintaro Fukushima
 
PDF
【20211202_toranoana.deno#3】denoでFFI
虎の穴 開発室
 
PDF
scikit-learnを用いた機械学習チュートリアル
敦志 金谷
 
PDF
【20220120 toranoana.deno#4】denoでffiの続き
虎の穴 開発室
 
PDF
使ってみませんか?pg hint_plan
Masao Fujii
 
PDF
パッケージングの呼び声 Python Charity Talks in Japan 2021.02
Atsushi Odagiri
 
PDF
Go静的解析ハンズオン
Takuya Ueda
 
PDF
Rでreproducible research
Shintaro Fukushima
 
PPTX
Boost.python
fate_fox
 
PDF
Goにおける静的解析と製品開発への応用
Takuya Ueda
 
PPTX
rpi_handson_2.5
teruyaono1
 
PDF
TensorFlow White Paperを読む
Yuta Kashino
 
PDF
Pyconjp2014_implementations
masahitojp
 
PPT
Python twitterとtkinterのことはじめ
Yukitaka Uchikoshi
 
PDF
boost::shared_ptr tutorial
NU_Pan
 
PDF
Gensim
saireya _
 
R3.0.0 is relased
Shintaro Fukushima
 
【20211202_toranoana.deno#3】denoでFFI
虎の穴 開発室
 
scikit-learnを用いた機械学習チュートリアル
敦志 金谷
 
【20220120 toranoana.deno#4】denoでffiの続き
虎の穴 開発室
 
使ってみませんか?pg hint_plan
Masao Fujii
 
パッケージングの呼び声 Python Charity Talks in Japan 2021.02
Atsushi Odagiri
 
Go静的解析ハンズオン
Takuya Ueda
 
Rでreproducible research
Shintaro Fukushima
 
Boost.python
fate_fox
 
Goにおける静的解析と製品開発への応用
Takuya Ueda
 
rpi_handson_2.5
teruyaono1
 
TensorFlow White Paperを読む
Yuta Kashino
 
Pyconjp2014_implementations
masahitojp
 
Python twitterとtkinterのことはじめ
Yukitaka Uchikoshi
 
boost::shared_ptr tutorial
NU_Pan
 
Gensim
saireya _
 

Similar to Introduction to Numpy (and Python) [JPN] (20)

PPT
Pythonintro
Mikio Kubo
 
PDF
Python Kyoto study
Naoya Inada
 
PDF
「Python言語」はじめの一歩 / First step of Python / 2016 Jan 12
Takanori Suzuki
 
ODP
Introduction of Python
Tomoya Nakayama
 
PPTX
2017/12/21 虎の穴 Python勉強会
虎の穴 開発室
 
PDF
Pythonで始めるDropboxAPI
Daisuke Igarashi
 
PDF
DATUM STUDIO PyCon2016 Turorial
Tatsuya Tojima
 
PPTX
Wacode5thでのpython講義資料
丈 宮本
 
PDF
NumPyが物足りない人へのCython入門
Shiqiao Du
 
KEY
ひのきのぼうだけで全クリ目指す
AromaBlack
 
PDF
「Python言語」はじめの一歩 / First step of Python
Takanori Suzuki
 
PDF
LLdeade Python Language Update
Atsushi Shibata
 
PDF
Wrapping a C++ library with Cython
fuzzysphere
 
PDF
Pythonの処理系はどのように実装され,どのように動いているのか? 我々はその実態を調査すべくアマゾンへと飛んだ.
kiki utagawa
 
PPTX
NumPyのすゝめ
iPride Co., Ltd.
 
KEY
Hello World Python featuring GAE
Maito Kuwahara
 
PDF
Cython intro prelerease
Shiqiao Du
 
PPTX
PythonとRによるデータ分析環境の構築と機械学習によるデータ認識 第3版
Katsuhiro Morishita
 
PDF
ALPSチュートリアル(4) Python入門
Computational Materials Science Initiative
 
PPTX
Python 学習教材 (~299ページ)
Jun MITANI
 
Pythonintro
Mikio Kubo
 
Python Kyoto study
Naoya Inada
 
「Python言語」はじめの一歩 / First step of Python / 2016 Jan 12
Takanori Suzuki
 
Introduction of Python
Tomoya Nakayama
 
2017/12/21 虎の穴 Python勉強会
虎の穴 開発室
 
Pythonで始めるDropboxAPI
Daisuke Igarashi
 
DATUM STUDIO PyCon2016 Turorial
Tatsuya Tojima
 
Wacode5thでのpython講義資料
丈 宮本
 
NumPyが物足りない人へのCython入門
Shiqiao Du
 
ひのきのぼうだけで全クリ目指す
AromaBlack
 
「Python言語」はじめの一歩 / First step of Python
Takanori Suzuki
 
LLdeade Python Language Update
Atsushi Shibata
 
Wrapping a C++ library with Cython
fuzzysphere
 
Pythonの処理系はどのように実装され,どのように動いているのか? 我々はその実態を調査すべくアマゾンへと飛んだ.
kiki utagawa
 
NumPyのすゝめ
iPride Co., Ltd.
 
Hello World Python featuring GAE
Maito Kuwahara
 
Cython intro prelerease
Shiqiao Du
 
PythonとRによるデータ分析環境の構築と機械学習によるデータ認識 第3版
Katsuhiro Morishita
 
ALPSチュートリアル(4) Python入門
Computational Materials Science Initiative
 
Python 学習教材 (~299ページ)
Jun MITANI
 
Ad

Recently uploaded (8)

PDF
[Hardening Designers Confernece 2025]ランサムウェアでの見えざるログ・見えるログ
kataware
 
PDF
プライバシ保護のためのインターネットアーキテクチャの進化 (2025-07-11)
Jun Kurihara
 
PDF
20250711_日本IBM ミドルウエア・ユーザー研究会(JIMUC)総会_中村会長資料.pdf
ChikakoInami1
 
PDF
20250710_Devinで切り拓くDB革命_〜価値創出に集中せよ〜.pdf
Masaki Yamakawa
 
PDF
人気ブロックチェーン基盤「Hyperledger Fabric」最新版を動かしてみた!
LFDT Tokyo Meetup
 
PDF
PostgreSQL18新機能紹介(db tech showcase 2025 発表資料)
NTT DATA Technology & Innovation
 
PDF
Hyperledger Fabric最新v3.x系での機能強化、変更点にキャッチアップ!
LFDT Tokyo Meetup
 
PDF
Hyperledger Fabric公式サンプル fabric-samples徹底解説
LFDT Tokyo Meetup
 
[Hardening Designers Confernece 2025]ランサムウェアでの見えざるログ・見えるログ
kataware
 
プライバシ保護のためのインターネットアーキテクチャの進化 (2025-07-11)
Jun Kurihara
 
20250711_日本IBM ミドルウエア・ユーザー研究会(JIMUC)総会_中村会長資料.pdf
ChikakoInami1
 
20250710_Devinで切り拓くDB革命_〜価値創出に集中せよ〜.pdf
Masaki Yamakawa
 
人気ブロックチェーン基盤「Hyperledger Fabric」最新版を動かしてみた!
LFDT Tokyo Meetup
 
PostgreSQL18新機能紹介(db tech showcase 2025 発表資料)
NTT DATA Technology & Innovation
 
Hyperledger Fabric最新v3.x系での機能強化、変更点にキャッチアップ!
LFDT Tokyo Meetup
 
Hyperledger Fabric公式サンプル fabric-samples徹底解説
LFDT Tokyo Meetup
 
Ad

Introduction to Numpy (and Python) [JPN]

  • 2. プログラミング言語 22018年3月1日 D-WiSE LT C言語 ✦ 1972年に開発された汎用高級言語 ✦ 機械語に近い構成による高速な実行速度 ✦ ポインタのポインタに代表される難解な仕様 ✦ 習得難易度が高い Python ✦ 1991年に開発された汎用高級言語 ✦ 豊富なライブラリ(モジュール)による拡張 ✦ 簡易な文法により記述することができる ✦ 習得難易度が低い ✦ 速度がC言語と比較して劣る
  • 3. プログラミング言語 32018年3月1日 D-WiSE LT C言語 Python ✦ 科学計算用に設計された言語ではない ✦ 自分で多くを定義する必要がある e.g. 構造体,クラス,関数 ✦ 本来の趣旨から離れた作業が必要 ✦ 科学計算用に設計されたPythonのライブラリ ✦ 行列演算など算術計算が高速 Numpyを使おう!
  • 4. Numpy 42018年3月1日 D-WiSE LT Pythonで用いられる科学計算用ライブラリ ✦ 内部はCで実装されている ✦ その他の数学・解析系ライブラリにおける基盤 ✦ JuliaやRubyなど多言語での利用も可能
  • 5. 本編の前に… 52018年3月1日 D-WiSE LT 表記 #include <stdio.h> int main(void){ return 0; } ❖ コード名 https://github.com/Scstechr/D-WiSE_LT/tree/ master/180301/codes リンク Pythonのヴァージョン Python 3.6.4
  • 6. Hello World 62018年3月1日 D-WiSE LT C言語 #include <stdio.h> int main(void){ printf(“Hello Worldn”); return 0; } ❖ hello.c ✤ コンパイル $ gcc hello.c ✤ 実行 $ ./a.out Hello World
  • 7. Hello World 72018年3月1日 D-WiSE LT Python print(“Hello World”) ❖ hello.py ❖ 実行 $ python hello.py Hello World def main(): print("Hello World") if __name__ == "__main__": main() ❖ hello_main.py 逐次コンパイルを行うため事前コンパイルは不要
  • 8. Hello World 82018年3月1日 D-WiSE LT 比較 ❖ hello.c print(“Hello World”) ❖ hello.py #include <stdio.h> int main(void){ printf("Hello Worldn"); return 0; } 同じ処理を少ない行数で記述することが可能 デバッグの負担を軽減する
  • 9. Hello World 92018年3月1日 D-WiSE LT def main(): print("Hello World") if __name__ == "__main__": main() #include <stdio.h> int main(void){ printf("Hello Worldn"); return 0; } 比較 ❖ hello.c ❖ hello_main.py
  • 10. 配列の初期化 102018年3月1日 D-WiSE LT C言語 int main(void){ int array[10]; for(int i = 0; i < 10; i++){ array[i] = 0; } return 0; } ❖ array.c array[] = {0,0,0,0,0,0,0,0,0,0}
  • 11. 配列の初期化 112018年3月1日 D-WiSE LT Python def main(): lst = [] for i in range(10): lst.append(0) if __name__ == "__main__": main() ❖ array.py リスト ( list ) ✤ 多機能なPythonの配列 ✤ lst.append() は()の中身を末尾に追加 lst = [0 0 0 0 0 0 0 0 0 0]
  • 12. 配列の初期化 122018年3月1日 D-WiSE LT 比較 ❖ array.py❖ array.c int main(void){ int array[10]; for(int i = 0; i < 10; i++){ array[i] = 0; } return 0; } def main(): lst = [] for i in range(10): lst.append(0) if __name__ == "__main__": main()
  • 13. 132018年3月1日 D-WiSE LT 比較 ❖ array.py❖ array.c int main(void){ int array[10]; for(int i = 0; i < 10; i++){ array[i] = 0; def main(): lst = [] for i in range(10): lst.append(0) 変数の型付け ✤ C言語: 静的型付け (変数宣言時に型宣言を行う) ✤ Python: 動的型付け (右辺により型変化) 配列の初期化
  • 15. 配列の初期化 152018年3月1日 D-WiSE LT コンストラクタ ❖ array_const.py def main(): lst = list(range(10)) if __name__ == "__main__": main() for文を使わない分リスト内包表記より(おそらく)速い
  • 16. 配列を出力する 162018年3月1日 D-WiSE LT C言語 ❖ array_print.c #include <stdio.h> int main(void){ int array[10]; for(int i = 0; i < 10; i++){ array[i] = i; } for(int i = 0; i < 10; i++){ printf(“%dn”, array[i]); } return 0; } $ gcc array_print.c $ ./a.out 0 1 2 3 4 5 6 7 8 9
  • 17. 配列を出力する 172018年3月1日 D-WiSE LT Python ❖ array_print.py def main(): lst = [i for i in range(10)] for i in lst: print(i) # [print(i) for i in lst] if __name__ == ‘__main__’: main() $ python array_print2.py 0 1 2 3 4 5 6 7 8 9
  • 18. Pythonにおける出力 182018年3月1日 D-WiSE LT print() ❖ array_print2.py $ python array_print2.py [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print() ✤ ()の中身に合わせて出力を変化 def main(): lst = [i for i in range(10)] print(lst) if __name__ == ‘__main__’: main() def main(): print(‘Hello World’) if __name__ == ‘__main__’: main() $ python hello_main.py Hello World ❖ hello_main.py
  • 19. 配列を出力する 192018年3月1日 D-WiSE LT C言語で同様の動作を実装する (関数 ) ❖ array_print2.c (1/2) #include <stdio.h> void print(int *array, int size){ printf("["); for(int i = 0; i < size; i++){ printf("%d,", array[i]); } printf("b]n"); } 配列のポインタとサイズを受け取る関数を定義
  • 20. 配列を出力する 202018年3月1日 D-WiSE LT C言語で同様の動作を実装する (関数 ) ❖ array_print2.c (2/2) int main(void){ int array[10]; for(int i = 0; i < 10; i++){ array[i] = i; } print(array, 10); return 0; }
  • 21. 配列を出力する 212018年3月1日 D-WiSE LT C言語で同様の動作を実装する (構造体 ) ❖ array_print3.c (1/3) #include <stdio.h> #include <stdlib.h> #define ARRAY_SIZE 10 typedef struct{ int array[ARRAY_SIZE]; int size; } Array; 配列とサイズで構成される構造体を定義
  • 22. 配列を出力する 222018年3月1日 D-WiSE LT C言語で同様の動作を実装する (構造体 ) ❖ array_print3.c (2/3) void print(Array *array){ printf("["); for(int i = 0; i < array->size; i++){ printf("%d,", array->array[i]); } printf("b]n"); } 構造体のポインタを受け取る関数を定義
  • 23. 配列を出力する 232018年3月1日 D-WiSE LT C言語で同様の動作を実装する (構造体 ) ❖ array_print3.c (3/3) int main(void){ Array *array = (Array*)malloc(sizeof(Array)); array->size = 10; for(int i = 0; i < array->size; i++){ array->array[i] = i; } print(array); free(array); return 0; }
  • 24. 配列を出力する 242018年3月1日 D-WiSE LT int型の(一次元の)配列にしか有効ではない ❖ array_print3.c❖ array_print2.c #include <stdio.h> void print(int *array, int size){ printf("["); for(int i = 0; i < size; i++){ printf("%d,", array[i]); } printf("b]n"); } int main(void){ int array[10]; for(int i = 0; i < 10; i++){ array[i] = i; } print(array, 10); return 0; } #include <stdio.h> #include <stdlib.h> #define ARRAY_SIZE 10 typedef struct{ int array[ARRAY_SIZE]; int size; } Array; void print(Array *array){ printf("["); for(int i = 0; i < array->size; i++){ printf("%d,", array->array[i]); } printf("b]n"); } int main(void){ Array *array = (Array*)malloc(sizeof(Array)); array->size = 10; for(int i = 0; i < array->size; i++){ array->array[i] = i; } print(array); free(array); return 0; }
  • 25. 配列を出力する 252018年3月1日 D-WiSE LT Pythonのprint()の凄さ #include <stdio.h> void print(int *array, int size){ printf("["); for(int i = 0; i < size; i++){ printf("%d,", array[i]); } printf("b]n"); } int main(void){ int array[10]; for(int i = 0; i < 10; i++){ array[i] = i; } print(array, 10); return 0; } ❖ array_print2.py def main(): lst = [i for i in range(10)] print(lst) if __name__ == ‘__main__’: main() ❖ array_print2.c
  • 26. 262018年3月1日 D-WiSE LT Pythonのlistの凄さ $ python Python 3.6.2 |Anaconda custom (64-bit)| (default, Jul 20 2017, 13:14:59) [ G C C 4 . 2 . 1 C o m p a t i b l e A p p l e L L V M 6 . 0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> exit() $ ✤ 対話型インタープリタの起動 簡単な動作確認をすることができる Pythonのデバッグのお供
  • 27. 272018年3月1日 D-WiSE LT Pythonのlistの凄さ >>> dir(list) [ ' _ _ a d d _ _ ' , ' _ _ c l a s s _ _ ' , ' _ _ c o n t a i n s _ _ ' , '__delattr__', '__delitem__', '__dir__', '__doc__', ' _ _ e q _ _ ' , ' _ _ f o r m a t _ _ ' , ' _ _ g e _ _ ' , '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', ' _ _ r e p r _ _ ' , ' _ _ r e v e r s e d _ _ ' , ' _ _ r m u l _ _ ' , '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ✤ 充実した既存の関数群 Pythonのデバッグのお供
  • 28. Pythonのデバッグのお供 282018年3月1日 D-WiSE LT その他の有用な機能 >>> help(list.append) Help on method_descriptor: append(...) L.append(object) -> None -- append object to end ✤ help(): 関数その他の詳細をviで出力 (qで抜け出す) >>> lst = list(range(10)) >>> lst [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> type(lst) <class 'list'> ✤ type(): インスタンスの種類を出力
  • 29. 実行時間 292018年3月1日 D-WiSE LT 比較 $ time ./a.out [0,1,2,3,4,5,6,7,8,9] ❖ array_print2.py ❖ array_print3.c real 0m0.007s user 0m0.002s sys 0m0.002s $ time python array_print2.py [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] real 0m0.062s user 0m0.039s sys 0m0.015s Pythonは遅い!
  • 30. Numpy 302018年3月1日 D-WiSE LT PythonのNumpyの凄さ $ python Python 3.6.2 |Anaconda custom (64-bit)| (default, Jul 20 2017, 13:14:59) [ G C C 4 . 2 . 1 C o m p a t i b l e A p p l e L L V M 6 . 0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> ✤ 対話型インタープリタの起動
  • 31. Numpy 312018年3月1日 D-WiSE LT >>> import numpy as np ✤ importする Pythonのライブラリ利用法 ★ C言語の類似表記: numpyを書くのは長いのでnpと表記する (慣例) #include <stdio.h> #include “myheader.h” ★ Pythonの場合は出自を記す必要がある import numpy as np #numpyで定義されたsum()を使いたい np.sum()
  • 32. Numpy 322018年3月1日 D-WiSE LT PythonのNumpyの凄さ >>> dir(np) ['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'MachAr', 'ModuleDeprecationWarning', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'TooHardError', 'True_', 'UFUNC_BUFSIZE_DEFAULT', 'UFUNC_PYVALS_NAME', 'VisibleDeprecationWarning', 'WRAP', '_NoValue', '__NUMPY_SETUP__', '__all__', '__builtins__', '__cached__', '__config__', '__doc__', '__file__', '__git_revision__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_import_tools', '_mat', 'abs', 'absolute', 'absolute_import', 'add', 'add_docstring', 'add_newdoc', 'add_newdoc_ufunc', 'add_newdocs', 'alen', 'all', 'allclose', 'alltrue', 'alterdot', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition', 'argsort', 'argwhere', ✤ 豊富な関数群
  • 33. Numpy 332018年3月1日 D-WiSE LT PythonのNumpyの凄さ >>> dir(np.ndarray) [ ' T ' , ' _ _ a b s _ _ ' , ' _ _ a d d _ _ ' , ' _ _ a n d _ _ ' , ' _ _ a r r a y _ _ ' , '__array_finalize__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_wrap__', '__bool__', '__class__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', ✤ 多次元行列(np.ndarray)に限っても豊富
  • 34. Numpy 342018年3月1日 D-WiSE LT listからnp.ndarrayへの変換 import numpy as np def main(): lst = [i for i in range(10)] print(lst, type(lst)) array = np.array(lst) print(array, type(array)) if __name__ == "__main__": main() ❖ np_array.py $ python np_array.py [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'> [0 1 2 3 4 5 6 7 8 9] <class ‘numpy.ndarray'>
  • 35. 352018年3月1日 D-WiSE LT numpyで定義された関数を用いる Numpy import numpy as np def main(): #array = np.array([i for i in range(10)]) array = np.arange(10) print(array) if __name__ == "__main__": main() np.arange(n): 0~n-1で初期化された一次元配列 ❖ np_array2.py
  • 36. 362018年3月1日 D-WiSE LT 比較 ❖ array_print2.py $ time python array_print2.py [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] real 0m0.062s user 0m0.039s sys 0m0.015s ❖ np_array2.py $ time python np_array2.py [0 1 2 3 4 5 6 7 8 9] real 0m0.239s user 0m0.161s sys 0m0.062s 実行時間の計測: Python
  • 37. 372018年3月1日 D-WiSE LT numpyをimportするオーバーヘッド ❖ import_numpy.py $ cat import_numpy.py import numpy as np $ time python import_numpy.py real 0m0.226s user 0m0.149s sys 0m0.062s ❖ array_print2.py real 0m0.062s user 0m0.039s sys 0m0.015s ❖ array_print2.py real 0m0.013s user 0m0.012s sys 0m0.000s real 0m0.239s user 0m0.161s sys 0m0.062s → 実行時間の計測: Python
  • 38. 382018年3月1日 D-WiSE LT ipythonを利用する $ ipython Python 3.6.2 |Anaconda custom (64-bit)| (default, Jul 20 2017, 13:14:59) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: list.append? Docstring: L.append(object) -> None -- append object to end Type: method_descriptor In [2]: ✤ 多機能の対話型インタープリタの起動 実行時間の計測: Python
  • 39. 392018年3月1日 D-WiSE LT In [1]: import numpy as np ipythonを利用する ✤ Numpyをimport In [2]: def range_list(n): ...: lst = list(range(n)) ...: In [3]: def arange_np(n): ...: array = np.arange(n) ...: ✤ nを引数とする関数を定義 実行時間の計測: Python
  • 40. 402018年3月1日 D-WiSE LT ipythonを利用する ✤ %timeitで計測 (要素数10の1次元配列) In [4]: %timeit range_list(10) 878 ns ± 31.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [5]: %timeit arange_np(10) 872 ns ± 32.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 実行時間の計測: Python
  • 41. 412018年3月1日 D-WiSE LT ipythonを利用する ✤ %timeitで計測 (要素数10000の1次元配列) In [6]: %timeit range_list(10000) 238 µs ± 9.11 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [7]: %timeit arange_np(10000) 5.87 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 実行時間の計測: Python
  • 42. 実行時間: C 422018年3月1日 D-WiSE LT time.hを利用する ❖ array_10k.c (1/3) #include <stdio.h> #include <stdlib.h> #include <time.h> #define ARRAY_SIZE 10000 #define TRIAL 100000 typedef struct{ int data[ARRAY_SIZE]; int size; } Array; ヘッダのincludeと定数・構造体の定義
  • 43. 432018年3月1日 D-WiSE LT ❖ array_10k.c (2/3) void process(){ Array *array = (Array*)malloc(sizeof(Array)); array->size = 10000; for(int i = 0; i < array->size; i++){ array->data[i] = i; } } 配列の初期化を関数として切り出す 実行時間: C time.hを利用する
  • 44. 442018年3月1日 D-WiSE LT ❖ array_10k.c (3/3) int main(){ clock_t t1, t2; double sum; sum = 0; for(int i = 0; i < TRIAL; i++){ t1 = clock();process();t2 = clock(); sum += (double)(t2-t1)/CLOCKS_PER_SEC; } printf("%fn", (double)sum / TRIAL); return 0; } 実行時間: C time.hを利用する
  • 45. 452018年3月1日 D-WiSE LT ❖ array_10k.c $ ./array_10k.out 0.000034 実行時間 time.hを利用する 種類 実行時間 Python list 238 [µs] numpy 5.86 [µs] C 34 [µs] 比較 Pythonは遅い!
  • 46. Numpy - 配列の初期化 462018年3月1日 D-WiSE LT ipythonを利用する $ ipython Python 3.6.2 |Anaconda custom (64-bit)| (default, Jul 20 2017, 13:14:59) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. ✤ 多機能型の対話型インタープリタの起動 In [1] : import numpy as np ✤ Numpyをimport
  • 47. 472018年3月1日 D-WiSE LT 全零行列 In [2]: np.zeros(10) Out[2]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) ✤ np.zeros() 全一行列 In [3]: np.ones(10) Out[3]: array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) ✤ np.ones() Numpy - 配列の初期化
  • 48. Numpy - 多次元行列を定義 482018年3月1日 D-WiSE LT In [4]: np.array([[0,1],[2,3]]) Out[4]: array([[0, 1], [2, 3]]) listを変換 In [5]: np.arange(4).reshape([2,2]) Out[5]: array([[0, 1], [2, 3]]) np.reshape()で1次元配列を多次元へ変換  0 1 2 3
  • 49. 492018年3月1日 D-WiSE LT In [6]: np.zeros([2,2]) Out[6]: array([[ 0., 0.], [ 0., 0.]]) 全零行列 np.zeros()  0 0 0 0 In [7]: np.ones([2,2]) Out[7]: array([[ 1., 1.], [ 1., 1.]]) 全一行列 np.ones()  1 1 1 1 In [8]: np.identity(2) Out[8]: array([[ 1., 0.], [ 0., 1.]]) 単位行列 np.identity()  1 0 0 1 Numpy - 多次元行列を定義
  • 50. 502018年3月1日 D-WiSE LT Numpy - 行列演算 a = 2 4 1 2 3 3 5 , b = 2 4 4 5 6 3 5 In [9]: a = np.array([1,2,3]) In [9]: b = np.array([4,5,6]) In [10]: a + b Out[10]: array([5, 7, 9]) 加算 In [11]: a - b Out[11]: array([-3, -3, -3]) 減算
  • 51. 512018年3月1日 D-WiSE LT Numpy - 行列演算 a = 2 4 1 2 3 3 5 , b = 2 4 4 5 6 3 5 In [9]: a = np.array([1,2,3]) In [9]: b = np.array([4,5,6]) In [12]: a * b Out[12]: array([ 4, 10, 18]) 乗算 In [13]: a / b Out[13]: array([ 0.25, 0.4 , 0.5 ]) 除算
  • 52. 522018年3月1日 D-WiSE LT Numpy - 線形代数 np.linalg >>> dir(np.linalg) ['LinAlgError', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', ' _ _ p a c k a g e _ _ ' , ' _ _ p a t h _ _ ' , ' _ _ s p e c _ _ ' , ' _ n u m p y _ t e s t e r ' , ' _ u m a t h _ l i n a l g ' , 'absolute_import', 'bench', 'cholesky', 'cond', 'det', 'division', 'eig', 'eigh', 'eigvals', 'eigvalsh', 'info', 'inv', 'lapack_lite', 'linalg', ' l s t s q ' , ' m a t r i x _ p o w e r ' , ' m a t r i x _ r a n k ' , 'multi_dot', 'norm', 'pinv', 'print_function', 'qr', 'slogdet', 'solve', 'svd', 'tensorinv', 'tensorsolve', 'test'] >>>
  • 53. 532018年3月1日 D-WiSE LT Numpy - 線形代数 In [14]: c = np.arange(1,5).reshape(2,2) In [15]: np.linalg.det(c) Out[15]: -2.0000000000000004 行列式: det c In [16]: np.linalg.norm(c) Out[16]: 5.4772255750516612 ノルム: ||c|| c =  1 2 3 4
  • 54. 542018年3月1日 D-WiSE LT Numpy - 線形代数 In [14]: c = np.arange(1,5).reshape(2,2) In [17]: np.linalg.inv(c) Out[17]: array([[-2. , 1. ], [ 1.5, -0.5]]) 逆行列: c-1 c =  1 2 3 4
  • 55. 552018年3月1日 D-WiSE LT Numpy - 乱数生成 random (既存ライブラリ) >>> import random >>> dir(random) ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', ' S G _ M A G I C C O N S T ' , ' S y s t e m R a n d o m ' , ' T W O P I ' , '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', ' g e t s t a t e ' , ' l o g n o r m v a r i a t e ' , ' n o r m a l v a r i a t e ' , 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
  • 56. 562018年3月1日 D-WiSE LT Numpy - 乱数生成 np.random >>> dir(np.random) ['Lock', 'RandomState', '__RandomState_ctor', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_numpy_tester', 'absolute_import', 'bench', 'beta', 'binomial', 'bytes', 'chisquare', 'choice', 'dirichlet', 'division', 'exponential', 'f', 'gamma', 'geometric', 'get_state', 'gumbel', 'hypergeometric', 'info', 'laplace', 'logistic', 'lognormal', 'logseries', 'mtrand', 'multinomial', 'multivariate_normal', 'negative_binomial', 'noncentral_chisquare', 'noncentral_f', 'normal', 'np', 'operator', 'pareto', 'permutation', 'poisson', 'power', 'print_function', 'rand', 'randint', 'randn', 'random', 'random_integers', 'random_sample', 'ranf', 'rayleigh', 'sample', 'seed', 'set_state', 'shuffle', 'standard_cauchy', 'standard_exponential', 'standard_gamma', 'standard_normal', 'standard_t', 'test', 'triangular', 'uniform', 'vonmises', 'wald', 'warnings', 'weibull', 'zipf']
  • 57. 572018年3月1日 D-WiSE LT Numpy - 異なる分布による乱数生成 一様分布: np.random.rand() import numpy as np import matplotlib.pyplot as plt def main(): R = np.random.rand(10000) plt.hist(R, bins=1000) plt.show() if __name__ == "__main__": main() ❖ np_rand.py 一様分布
  • 58. 582018年3月1日 D-WiSE LT Numpy - 異なる分布による乱数生成 標準正規分布 N(0,1): np.random.randn() import numpy as np import matplotlib.pyplot as plt def main(): R = np.random.randn(10000) plt.hist(R, bins=1000) plt.show() if __name__ == "__main__": main() ❖ np_randn.py 標準正規分布 N(0, 1)
  • 59. 592018年3月1日 D-WiSE LT Numpy - 分布関数で決定 ランダムに選択: np.random.choice() import numpy as np import matplotlib.pyplot as plt def main(): array = np.arange(9) pmf = np.zeros(9) pmf[2] = 0.5 pmf[3] = 0.28 pmf[8] = 0.22 R = np.random.choice(array, size = 10000, p=pmf) #print(R) plt.hist(R, bins=100) plt.show() if __name__ == "__main__": main() ❖ np_rand_choice.py ⇤8(x) = 0.5x2 + 0.28x3 + 0.22x8
  • 60. 602018年3月1日 D-WiSE LT Numpy - 分布関数で決定 ランダムに選択: np.random.choice() import numpy as np import matplotlib.pyplot as plt def main(): array = np.arange(9) pmf = np.zeros(9) pmf[2] = 0.5 pmf[3] = 0.28 pmf[8] = 0.22 R = np.random.choice(array, size = 10000, p=pmf) #print(R) plt.hist(R, bins=100) plt.show() if __name__ == "__main__": main() ❖ np_rand_choice.py ⇤8(x) = 0.5x2 + 0.28x3 + 0.22x8
  • 61. 612018年3月1日 D-WiSE LT まとめ Python • 簡潔に記述できるためデバッグしやすい • C言語と比較すると実行速度が遅い • そのままでは科学計算用には適していない Numpy • Pythonの科学計算用ライブラリ • 内部がCで記述されており高速な演算が可能 • 豊富なライブラリ関数による簡易な実装
  • 62. 622018年3月1日 D-WiSE LT その他の数学用ライブラリ Scipy: 算術計算用のライブラリ • 微分積分や疎行列などを定義している • NumpyにないものはおそらくScipyにある Sympy: 変数をシンボルとして扱うためのライブラリ • x, yなどに具体的に値を代入する必要がない • 極限などよりテーラー展開など応用数学分野に強い • 式の展開とか整理に利用?
  • 64. 642018年3月1日 D-WiSE LT おすすめ • YouTubeなどでカンファレンス動画を観る • PyData, Enthought, Next Day Video, PyCon • オライリー本を買う • GitHubなどでコードを漁る • 公式ドキュメントを熟読する • 新しいメソッドを知るごとに処理速度が変化
  • 66. 662018年3月1日 D-WiSE LT まとめ 1950s Fortran 1960s BASIC 1970s C SQL SmallTalk 1980s C++ Common Lisp Perl 1990s Python Ruby Haskell 2000s C# Go Nim 2010s Rust Julia Kotlin プログラミング言語年代記
  • 67. 672018年3月1日 D-WiSE LT Pythonを使いつつ速度を求める Cython • PythonをCに変換する • コードが汚くなる代わりに速い Numba • JIT (Just-In-Time)コンパイラ • 機械語に変換し速度向上を目指す Pypy • 速度向上を目指すPythonのヴァージョン