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.
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
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のデバッグのお供
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.
>>>
✤ 対話型インタープリタの起動
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
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
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']