Movatterモバイル変換


[0]ホーム

URL:


Uploaded byMasaruOinaga
164 views

Introduction to Numpy (and Python) [JPN]

Introduction to Numpy and Python in Japanese.Intended to programmers interested in Python.The original motivation was to share information inside the lab where I belong.

Embed presentation

Download to read offline
Numpy および Python
プログラミング言語22018年3月1日 D-WiSE LTC言語✦ 1972年に開発された汎用高級言語✦ 機械語に近い構成による高速な実行速度✦ ポインタのポインタに代表される難解な仕様✦ 習得難易度が高いPython✦ 1991年に開発された汎用高級言語✦ 豊富なライブラリ(モジュール)による拡張✦ 簡易な文法により記述することができる✦ 習得難易度が低い✦ 速度がC言語と比較して劣る
プログラミング言語32018年3月1日 D-WiSE LTC言語 Python✦ 科学計算用に設計された言語ではない✦ 自分で多くを定義する必要があるe.g. 構造体,クラス,関数✦ 本来の趣旨から離れた作業が必要✦ 科学計算用に設計されたPythonのライブラリ✦ 行列演算など算術計算が高速Numpyを使おう!
Numpy42018年3月1日 D-WiSE LTPythonで用いられる科学計算用ライブラリ✦ 内部は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 World62018年3月1日 D-WiSE LTC言語#include <stdio.h>int main(void){printf(“Hello Worldn”);return 0;}❖ hello.c✤ コンパイル$ gcc hello.c✤ 実行$ ./a.outHello World
Hello World72018年3月1日 D-WiSE LTPythonprint(“Hello World”)❖ hello.py❖ 実行$ python hello.pyHello Worlddef main():print("Hello World")if __name__ == "__main__":main()❖ hello_main.py逐次コンパイルを行うため事前コンパイルは不要
Hello World82018年3月1日 D-WiSE LT比較❖ hello.cprint(“Hello World”)❖ hello.py#include <stdio.h>int main(void){printf("Hello Worldn");return 0;}同じ処理を少ない行数で記述することが可能デバッグの負担を軽減する
Hello World92018年3月1日 D-WiSE LTdef 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 LTC言語int main(void){int array[10];for(int i = 0; i < 10; i++){array[i] = 0;}return 0;}❖ array.carray[] = {0,0,0,0,0,0,0,0,0,0}
配列の初期化112018年3月1日 D-WiSE LTPythondef 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.cint 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.cint main(void){int array[10];for(int i = 0; i <10; i++){array[i] = 0;def main():lst = []for i inrange(10):lst.append(0)変数の型付け✤ C言語: 静的型付け (変数宣言時に型宣言を行う)✤ Python: 動的型付け (右辺により型変化)配列の初期化
配列の初期化142018年3月1日 D-WiSE LTリスト内包表記リストの初期化は「リスト内包表記」で一文で書ける❖ array_comp.pydef main():lst = [0 for i in range(10)]if __name__ == "__main__":main()
配列の初期化152018年3月1日 D-WiSE LTコンストラクタ❖ array_const.pydef main():lst = list(range(10))if __name__ == "__main__":main()for文を使わない分リスト内包表記より(おそらく)速い
配列を出力する162018年3月1日 D-WiSE LTC言語❖ 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.out0123456789
配列を出力する172018年3月1日 D-WiSE LTPython❖ array_print.pydef 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.py0123456789
Pythonにおける出力182018年3月1日 D-WiSE LTprint()❖ 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.pyHello World❖ hello_main.py
配列を出力する192018年3月1日 D-WiSE LTC言語で同様の動作を実装する (関数 )❖ 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 LTC言語で同様の動作を実装する (関数 )❖ 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 LTC言語で同様の動作を実装する (構造体 )❖ array_print3.c (1/3)#include <stdio.h>#include <stdlib.h>#define ARRAY_SIZE 10typedef struct{int array[ARRAY_SIZE];int size;} Array;配列とサイズで構成される構造体を定義
配列を出力する222018年3月1日 D-WiSE LTC言語で同様の動作を実装する (構造体 )❖ 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 LTC言語で同様の動作を実装する (構造体 )❖ 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 LTint型の(一次元の)配列にしか有効ではない❖ 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 10typedef 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 LTPythonの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.pydef main():lst = [i for i in range(10)]print(lst)if __name__ == ‘__main__’:main()❖ array_print2.c
262018年3月1日 D-WiSE LTPythonのlistの凄さ$ pythonPython 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 darwinType "help", "copyright", "credits" or "license"for more information.>>> exit()$✤ 対話型インタープリタの起動簡単な動作確認をすることができるPythonのデバッグのお供
272018年3月1日 D-WiSE LTPythonの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.creal 0m0.007suser 0m0.002ssys 0m0.002s$ time python array_print2.py[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]real 0m0.062suser 0m0.039ssys 0m0.015sPythonは遅い!
Numpy302018年3月1日 D-WiSE LTPythonのNumpyの凄さ$ pythonPython 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 darwinType "help", "copyright", "credits" or "license"for more information.>>>✤ 対話型インタープリタの起動
Numpy312018年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()
Numpy322018年3月1日 D-WiSE LTPythonの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',✤ 豊富な関数群
Numpy332018年3月1日 D-WiSE LTPythonの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)に限っても豊富
Numpy342018年3月1日 D-WiSE LTlistからnp.ndarrayへの変換import numpy as npdef 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 LTnumpyで定義された関数を用いるNumpyimport numpy as npdef 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.062suser 0m0.039ssys 0m0.015s❖ np_array2.py$ time python np_array2.py[0 1 2 3 4 5 6 7 8 9]real 0m0.239suser 0m0.161ssys 0m0.062s実行時間の計測: Python
372018年3月1日 D-WiSE LTnumpyをimportするオーバーヘッド❖ import_numpy.py$ cat import_numpy.pyimport numpy as np$ time python import_numpy.pyreal 0m0.226suser 0m0.149ssys 0m0.062s❖ array_print2.pyreal 0m0.062suser 0m0.039ssys 0m0.015s❖ array_print2.pyreal 0m0.013suser 0m0.012ssys 0m0.000sreal 0m0.239suser 0m0.161ssys 0m0.062s→実行時間の計測: Python
382018年3月1日 D-WiSE LTipythonを利用する$ ipythonPython 3.6.2 |Anaconda custom (64-bit)| (default,Jul 20 2017, 13:14:59)Type 'copyright', 'credits' or 'license' for moreinformationIPython 6.2.1 -- An enhanced Interactive Python.Type '?' for help.In [1]: list.append?Docstring: L.append(object) -> None -- appendobject to endType: method_descriptorIn [2]:✤ 多機能の対話型インタープリタの起動実行時間の計測: Python
392018年3月1日 D-WiSE LTIn [1]: import numpy as npipythonを利用する✤ NumpyをimportIn [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 LTipythonを利用する✤ %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 LTipythonを利用する✤ %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
実行時間: C422018年3月1日 D-WiSE LTtime.hを利用する❖ array_10k.c (1/3)#include <stdio.h>#include <stdlib.h>#include <time.h>#define ARRAY_SIZE 10000#define TRIAL 100000typedef 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;}}配列の初期化を関数として切り出す実行時間: Ctime.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;}実行時間: Ctime.hを利用する
452018年3月1日 D-WiSE LT❖ array_10k.c$ ./array_10k.out0.000034実行時間time.hを利用する種類 実行時間Pythonlist 238 [µs]numpy 5.86 [µs]C 34 [µs]比較Pythonは遅い!
Numpy - 配列の初期化462018年3月1日 D-WiSE LTipythonを利用する$ ipythonPython 3.6.2 |Anaconda custom (64-bit)| (default,Jul 20 2017, 13:14:59)Type 'copyright', 'credits' or 'license' for moreinformationIPython 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 LTIn [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 12 3
492018年3月1日 D-WiSE LTIn [6]: np.zeros([2,2])Out[6]:array([[ 0., 0.],[ 0., 0.]])全零行列 np.zeros()0 00 0In [7]: np.ones([2,2])Out[7]:array([[ 1., 1.],[ 1., 1.]])全一行列 np.ones()1 11 1In [8]: np.identity(2)Out[8]:array([[ 1., 0.],[ 0., 1.]])単位行列 np.identity()1 00 1Numpy - 多次元行列を定義
502018年3月1日 D-WiSE LTNumpy - 行列演算a =2412335 , b =2445635In [9]: a = np.array([1,2,3])In [9]: b = np.array([4,5,6])In [10]: a + bOut[10]: array([5, 7, 9])加算In [11]: a - bOut[11]: array([-3, -3, -3])減算
512018年3月1日 D-WiSE LTNumpy - 行列演算a =2412335 , b =2445635In [9]: a = np.array([1,2,3])In [9]: b = np.array([4,5,6])In [12]: a * bOut[12]: array([ 4, 10, 18])乗算In [13]: a / bOut[13]: array([ 0.25, 0.4 , 0.5 ])除算
522018年3月1日 D-WiSE LTNumpy - 線形代数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 LTNumpy - 線形代数In [14]: c = np.arange(1,5).reshape(2,2)In [15]: np.linalg.det(c)Out[15]: -2.0000000000000004行列式: det cIn [16]: np.linalg.norm(c)Out[16]: 5.4772255750516612ノルム: ||c||c =1 23 4
542018年3月1日 D-WiSE LTNumpy - 線形代数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-1c =1 23 4
552018年3月1日 D-WiSE LTNumpy - 乱数生成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 LTNumpy - 乱数生成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 LTNumpy - 異なる分布による乱数生成一様分布: np.random.rand()import numpy as npimport matplotlib.pyplot as pltdef 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 LTNumpy - 異なる分布による乱数生成標準正規分布 N(0,1): np.random.randn()import numpy as npimport matplotlib.pyplot as pltdef 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 LTNumpy - 分布関数で決定ランダムに選択: np.random.choice()import numpy as npimport matplotlib.pyplot as pltdef main():array = np.arange(9)pmf = np.zeros(9)pmf[2] = 0.5pmf[3] = 0.28pmf[8] = 0.22R = 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 LTNumpy - 分布関数で決定ランダムに選択: np.random.choice()import numpy as npimport matplotlib.pyplot as pltdef main():array = np.arange(9)pmf = np.zeros(9)pmf[2] = 0.5pmf[3] = 0.28pmf[8] = 0.22R = 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 LTNumpyおよび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 Fortran1960s BASIC1970s C SQL SmallTalk1980s C++ Common Lisp Perl1990s Python Ruby Haskell2000s C# Go Nim2010s Rust Julia Kotlinプログラミング言語年代記
672018年3月1日 D-WiSE LTPythonを使いつつ速度を求めるCython• PythonをCに変換する• コードが汚くなる代わりに速いNumba• JIT (Just-In-Time)コンパイラ• 機械語に変換し速度向上を目指すPypy• 速度向上を目指すPythonのヴァージョン

Recommended

PPTX
2018/1/30 Django勉強会
PDF
Rにおける大規模データ解析(第10回TokyoWebMining)
PPTX
PythonとRによるデータ分析環境の構築と機械学習によるデータ認識
PDF
静的解析を使った開発ツールの開発
PDF
Python 機械学習プログラミング データ分析ライブラリー解説編
PDF
Goで言語処理系(の途中まで)を作ろう
PDF
Python入門
PDF
Python東海Vol.5 IPythonをマスターしよう
PDF
Go静的解析ハンズオン
PDF
使ってみませんか?pg hint_plan
PDF
【20211202_toranoana.deno#3】denoでFFI
PPTX
Boost.python
PDF
TensorFlow White Paperを読む
PPT
Python twitterとtkinterのことはじめ
PDF
scikit-learnを用いた機械学習チュートリアル
PDF
パッケージングの呼び声 Python Charity Talks in Japan 2021.02
PDF
Gensim
PPTX
rpi_handson_2.5
PDF
Pyconjp2014_implementations
PDF
Goにおける静的解析と製品開発への応用
PDF
Rでreproducible research
PDF
boost::shared_ptr tutorial
 
PDF
R3.0.0 is relased
PDF
【20220120 toranoana.deno#4】denoでffiの続き
PPTX
2017/12/21 虎の穴 Python勉強会
PDF
Cython intro prelerease
PDF
NumPyが物足りない人へのCython入門
PDF
Pythonの処理系はどのように実装され,どのように動いているのか? 我々はその実態を調査すべくアマゾンへと飛んだ.
KEY
ひのきのぼうだけで全クリ目指す
PDF
Wrapping a C++ library with Cython

More Related Content

PPTX
2018/1/30 Django勉強会
PDF
Rにおける大規模データ解析(第10回TokyoWebMining)
PPTX
PythonとRによるデータ分析環境の構築と機械学習によるデータ認識
PDF
静的解析を使った開発ツールの開発
PDF
Python 機械学習プログラミング データ分析ライブラリー解説編
PDF
Goで言語処理系(の途中まで)を作ろう
PDF
Python入門
PDF
Python東海Vol.5 IPythonをマスターしよう
2018/1/30 Django勉強会
Rにおける大規模データ解析(第10回TokyoWebMining)
PythonとRによるデータ分析環境の構築と機械学習によるデータ認識
静的解析を使った開発ツールの開発
Python 機械学習プログラミング データ分析ライブラリー解説編
Goで言語処理系(の途中まで)を作ろう
Python入門
Python東海Vol.5 IPythonをマスターしよう

What's hot

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

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

PPTX
2017/12/21 虎の穴 Python勉強会
PDF
Cython intro prelerease
PDF
NumPyが物足りない人へのCython入門
PDF
Pythonの処理系はどのように実装され,どのように動いているのか? 我々はその実態を調査すべくアマゾンへと飛んだ.
KEY
ひのきのぼうだけで全クリ目指す
PDF
Wrapping a C++ library with Cython
PPTX
Python 学習教材 (~299ページ)
PPTX
PythonとRによるデータ分析環境の構築と機械学習によるデータ認識 第3版
PDF
ALPSチュートリアル(4) Python入門
PDF
「Python言語」はじめの一歩 / First step of Python / 2016 Jan 12
PDF
「Python言語」はじめの一歩 / First step of Python
PDF
Python Kyoto study
ODP
Introduction of Python
PDF
LLdeade Python Language Update
PDF
DATUM STUDIO PyCon2016 Turorial
KEY
Hello World Python featuring GAE
PPTX
Wacode5thでのpython講義資料
PPTX
NumPyのすゝめ
PDF
Pythonで始めるDropboxAPI
PPT
Pythonintro
2017/12/21 虎の穴 Python勉強会
Cython intro prelerease
NumPyが物足りない人へのCython入門
Pythonの処理系はどのように実装され,どのように動いているのか? 我々はその実態を調査すべくアマゾンへと飛んだ.
ひのきのぼうだけで全クリ目指す
Wrapping a C++ library with Cython
Python 学習教材 (~299ページ)
PythonとRによるデータ分析環境の構築と機械学習によるデータ認識 第3版
ALPSチュートリアル(4) Python入門
「Python言語」はじめの一歩 / First step of Python / 2016 Jan 12
「Python言語」はじめの一歩 / First step of Python
Python Kyoto study
Introduction of Python
LLdeade Python Language Update
DATUM STUDIO PyCon2016 Turorial
Hello World Python featuring GAE
Wacode5thでのpython講義資料
NumPyのすゝめ
Pythonで始めるDropboxAPI
Pythonintro

Introduction to Numpy (and Python) [JPN]

  • 1.
  • 2.
    プログラミング言語22018年3月1日 D-WiSE LTC言語✦1972年に開発された汎用高級言語✦ 機械語に近い構成による高速な実行速度✦ ポインタのポインタに代表される難解な仕様✦ 習得難易度が高いPython✦ 1991年に開発された汎用高級言語✦ 豊富なライブラリ(モジュール)による拡張✦ 簡易な文法により記述することができる✦ 習得難易度が低い✦ 速度がC言語と比較して劣る
  • 3.
    プログラミング言語32018年3月1日 D-WiSE LTC言語Python✦ 科学計算用に設計された言語ではない✦ 自分で多くを定義する必要があるe.g. 構造体,クラス,関数✦ 本来の趣旨から離れた作業が必要✦ 科学計算用に設計されたPythonのライブラリ✦ 行列演算など算術計算が高速Numpyを使おう!
  • 4.
    Numpy42018年3月1日 D-WiSE LTPythonで用いられる科学計算用ライブラリ✦内部は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 World62018年3月1日 D-WiSELTC言語#include <stdio.h>int main(void){printf(“Hello Worldn”);return 0;}❖ hello.c✤ コンパイル$ gcc hello.c✤ 実行$ ./a.outHello World
  • 7.
    Hello World72018年3月1日 D-WiSELTPythonprint(“Hello World”)❖ hello.py❖ 実行$ python hello.pyHello Worlddef main():print("Hello World")if __name__ == "__main__":main()❖ hello_main.py逐次コンパイルを行うため事前コンパイルは不要
  • 8.
    Hello World82018年3月1日 D-WiSELT比較❖ hello.cprint(“Hello World”)❖ hello.py#include <stdio.h>int main(void){printf("Hello Worldn");return 0;}同じ処理を少ない行数で記述することが可能デバッグの負担を軽減する
  • 9.
    Hello World92018年3月1日 D-WiSELTdef 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 LTC言語intmain(void){int array[10];for(int i = 0; i < 10; i++){array[i] = 0;}return 0;}❖ array.carray[] = {0,0,0,0,0,0,0,0,0,0}
  • 11.
    配列の初期化112018年3月1日 D-WiSE LTPythondefmain():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.cint 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.cint main(void){int array[10];for(int i = 0; i <10; i++){array[i] = 0;def main():lst = []for i inrange(10):lst.append(0)変数の型付け✤ C言語: 静的型付け (変数宣言時に型宣言を行う)✤ Python: 動的型付け (右辺により型変化)配列の初期化
  • 14.
  • 15.
    配列の初期化152018年3月1日 D-WiSE LTコンストラクタ❖array_const.pydef main():lst = list(range(10))if __name__ == "__main__":main()for文を使わない分リスト内包表記より(おそらく)速い
  • 16.
    配列を出力する162018年3月1日 D-WiSE LTC言語❖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.out0123456789
  • 17.
    配列を出力する172018年3月1日 D-WiSE LTPython❖array_print.pydef 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.py0123456789
  • 18.
    Pythonにおける出力182018年3月1日 D-WiSE LTprint()❖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.pyHello World❖ hello_main.py
  • 19.
    配列を出力する192018年3月1日 D-WiSE LTC言語で同様の動作を実装する(関数 )❖ 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 LTC言語で同様の動作を実装する(関数 )❖ 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 LTC言語で同様の動作を実装する(構造体 )❖ array_print3.c (1/3)#include <stdio.h>#include <stdlib.h>#define ARRAY_SIZE 10typedef struct{int array[ARRAY_SIZE];int size;} Array;配列とサイズで構成される構造体を定義
  • 22.
    配列を出力する222018年3月1日 D-WiSE LTC言語で同様の動作を実装する(構造体 )❖ 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 LTC言語で同様の動作を実装する(構造体 )❖ 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 LTint型の(一次元の)配列にしか有効ではない❖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 10typedef 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 LTPythonの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.pydef main():lst = [i for i in range(10)]print(lst)if __name__ == ‘__main__’:main()❖ array_print2.c
  • 26.
    262018年3月1日 D-WiSE LTPythonのlistの凄さ$pythonPython 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 darwinType "help", "copyright", "credits" or "license"for more information.>>> exit()$✤ 対話型インタープリタの起動簡単な動作確認をすることができるPythonのデバッグのお供
  • 27.
    272018年3月1日 D-WiSE LTPythonの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.creal 0m0.007suser 0m0.002ssys 0m0.002s$ time python array_print2.py[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]real 0m0.062suser 0m0.039ssys 0m0.015sPythonは遅い!
  • 30.
    Numpy302018年3月1日 D-WiSE LTPythonのNumpyの凄さ$pythonPython 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 darwinType "help", "copyright", "credits" or "license"for more information.>>>✤ 対話型インタープリタの起動
  • 31.
    Numpy312018年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.
    Numpy322018年3月1日 D-WiSE LTPythonの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.
    Numpy332018年3月1日 D-WiSE LTPythonの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.
    Numpy342018年3月1日 D-WiSE LTlistからnp.ndarrayへの変換importnumpy as npdef 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 LTnumpyで定義された関数を用いるNumpyimportnumpy as npdef 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.062suser 0m0.039ssys 0m0.015s❖ np_array2.py$ time python np_array2.py[0 1 2 3 4 5 6 7 8 9]real 0m0.239suser 0m0.161ssys 0m0.062s実行時間の計測: Python
  • 37.
    372018年3月1日 D-WiSE LTnumpyをimportするオーバーヘッド❖import_numpy.py$ cat import_numpy.pyimport numpy as np$ time python import_numpy.pyreal 0m0.226suser 0m0.149ssys 0m0.062s❖ array_print2.pyreal 0m0.062suser 0m0.039ssys 0m0.015s❖ array_print2.pyreal 0m0.013suser 0m0.012ssys 0m0.000sreal 0m0.239suser 0m0.161ssys 0m0.062s→実行時間の計測: Python
  • 38.
    382018年3月1日 D-WiSE LTipythonを利用する$ipythonPython 3.6.2 |Anaconda custom (64-bit)| (default,Jul 20 2017, 13:14:59)Type 'copyright', 'credits' or 'license' for moreinformationIPython 6.2.1 -- An enhanced Interactive Python.Type '?' for help.In [1]: list.append?Docstring: L.append(object) -> None -- appendobject to endType: method_descriptorIn [2]:✤ 多機能の対話型インタープリタの起動実行時間の計測: Python
  • 39.
    392018年3月1日 D-WiSE LTIn[1]: import numpy as npipythonを利用する✤ NumpyをimportIn [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 LTipythonを利用する✤%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 LTipythonを利用する✤%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.
    実行時間: C422018年3月1日 D-WiSELTtime.hを利用する❖ array_10k.c (1/3)#include <stdio.h>#include <stdlib.h>#include <time.h>#define ARRAY_SIZE 10000#define TRIAL 100000typedef 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;}}配列の初期化を関数として切り出す実行時間: Ctime.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;}実行時間: Ctime.hを利用する
  • 45.
    452018年3月1日 D-WiSE LT❖array_10k.c$ ./array_10k.out0.000034実行時間time.hを利用する種類 実行時間Pythonlist 238 [µs]numpy 5.86 [µs]C 34 [µs]比較Pythonは遅い!
  • 46.
    Numpy - 配列の初期化462018年3月1日D-WiSE LTipythonを利用する$ ipythonPython 3.6.2 |Anaconda custom (64-bit)| (default,Jul 20 2017, 13:14:59)Type 'copyright', 'credits' or 'license' for moreinformationIPython 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 LTIn [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 12 3
  • 49.
    492018年3月1日 D-WiSE LTIn[6]: np.zeros([2,2])Out[6]:array([[ 0., 0.],[ 0., 0.]])全零行列 np.zeros()0 00 0In [7]: np.ones([2,2])Out[7]:array([[ 1., 1.],[ 1., 1.]])全一行列 np.ones()1 11 1In [8]: np.identity(2)Out[8]:array([[ 1., 0.],[ 0., 1.]])単位行列 np.identity()1 00 1Numpy - 多次元行列を定義
  • 50.
    502018年3月1日 D-WiSE LTNumpy- 行列演算a =2412335 , b =2445635In [9]: a = np.array([1,2,3])In [9]: b = np.array([4,5,6])In [10]: a + bOut[10]: array([5, 7, 9])加算In [11]: a - bOut[11]: array([-3, -3, -3])減算
  • 51.
    512018年3月1日 D-WiSE LTNumpy- 行列演算a =2412335 , b =2445635In [9]: a = np.array([1,2,3])In [9]: b = np.array([4,5,6])In [12]: a * bOut[12]: array([ 4, 10, 18])乗算In [13]: a / bOut[13]: array([ 0.25, 0.4 , 0.5 ])除算
  • 52.
    522018年3月1日 D-WiSE LTNumpy- 線形代数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 LTNumpy- 線形代数In [14]: c = np.arange(1,5).reshape(2,2)In [15]: np.linalg.det(c)Out[15]: -2.0000000000000004行列式: det cIn [16]: np.linalg.norm(c)Out[16]: 5.4772255750516612ノルム: ||c||c =1 23 4
  • 54.
    542018年3月1日 D-WiSE LTNumpy- 線形代数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-1c =1 23 4
  • 55.
    552018年3月1日 D-WiSE LTNumpy- 乱数生成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 LTNumpy- 乱数生成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 LTNumpy- 異なる分布による乱数生成一様分布: np.random.rand()import numpy as npimport matplotlib.pyplot as pltdef 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 LTNumpy- 異なる分布による乱数生成標準正規分布 N(0,1): np.random.randn()import numpy as npimport matplotlib.pyplot as pltdef 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 LTNumpy- 分布関数で決定ランダムに選択: np.random.choice()import numpy as npimport matplotlib.pyplot as pltdef main():array = np.arange(9)pmf = np.zeros(9)pmf[2] = 0.5pmf[3] = 0.28pmf[8] = 0.22R = 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 LTNumpy- 分布関数で決定ランダムに選択: np.random.choice()import numpy as npimport matplotlib.pyplot as pltdef main():array = np.arange(9)pmf = np.zeros(9)pmf[2] = 0.5pmf[3] = 0.28pmf[8] = 0.22R = 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などに具体的に値を代入する必要がない• 極限などよりテーラー展開など応用数学分野に強い• 式の展開とか整理に利用?
  • 63.
  • 64.
    642018年3月1日 D-WiSE LTおすすめ•YouTubeなどでカンファレンス動画を観る• PyData, Enthought, Next Day Video, PyCon• オライリー本を買う• GitHubなどでコードを漁る• 公式ドキュメントを熟読する• 新しいメソッドを知るごとに処理速度が変化
  • 65.
  • 66.
    662018年3月1日 D-WiSE LTまとめ1950sFortran1960s BASIC1970s C SQL SmallTalk1980s C++ Common Lisp Perl1990s Python Ruby Haskell2000s C# Go Nim2010s Rust Julia Kotlinプログラミング言語年代記
  • 67.
    672018年3月1日 D-WiSE LTPythonを使いつつ速度を求めるCython•PythonをCに変換する• コードが汚くなる代わりに速いNumba• JIT (Just-In-Time)コンパイラ• 機械語に変換し速度向上を目指すPypy• 速度向上を目指すPythonのヴァージョン

[8]ページ先頭

©2009-2025 Movatter.jp