matplotが上手く動作しない

[vagrant@localhost python]$ python
Python 3.6.4 (default, Sep 5 2019, 00:12:03)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
‘/home/vagrant/.config/matplotlib/matplotlibrc’
>>>

[vagrant@localhost python]$ sudo vi /home/vagrant/.config/matplotlib/matplotlibrc

backendの記載をtkaggに変えます

backend : tkagg
import math
import numpy as np
from matplotlib import pyplot

pi = math.pi   #mathモジュールのπを利用

x = np.linspace(0, 2*pi)
y = np.sin(x)

pyplot.plot(x, y)
pyplot.savefig( 'sinWave.png' ) 

ほう

ReLU関数

活性化関数とは、入力信号の総和がどのように活性化するかを決定する

– 単純パーセプトロンではステップ関数
– 多層パーセプトロンでは、シグモイド関数、ソフトマックス関数、恒等関数など

ステップ関数
入力した値が0以下の時0に成り、0より大きい時1になる

def step_function(x):
	if x>0:
		return 1
	else:
		return 0

print(step_function(5))
print(step_function(-8))

[vagrant@localhost python]$ python myapp.py
1
0
アホみたいだな。概念は凄い大事なんだろうけど。

同じくRelU

def relu(x):
	return np.maximum(0,x)

print(relu(15))
print(relu(-4))

[vagrant@localhost python]$ python myapp.py
15
0
これもそのまんまって感じですな。。

sigmoid関数

Sa(x) = 1 /(x + exp(-ax))
シグモイド関数はxが負の無限大に近づくと分母は正の無限大になるので、yは0に近づき、xが正の無限大に近づくと分母は1に近づくのでyは1に近づく

import numpy as np

def sigmoid(x):
	return 1 / (1 + np.exp(-x))

print(sigmoid(0))

print(sigmoid(-6))

print(sigmoid(6))

[vagrant@localhost python]$ python myapp.py
0.5
0.0024726231566347743
0.9975273768433653

ラムダ式

import numpy as np
sigmoid = lambda x : 1 / (1 + np.exp(-x))

print(sigmoid(0))
print(sigmoid(-5))
print(sigmoid(5))

[vagrant@localhost python]$ python myapp.py
0.5
0.0066928509242848554
0.9933071490757153

計算自体は簡単だなー

自然対数をpythonで表現する

自然対数: 微分しても値が変わらない

import math

print(math.e)

[vagrant@localhost python]$ python myapp.py
2.718281828459045
ほう、

べき乗

print(3**3)
print(pow(2,5))
print(math.pow(2,6))

[vagrant@localhost python]$ python myapp.py
27
32
64.0
冪乗は、用途が多いので、書き方も複数あるようですな。

平方根

print(3**0.5)

print(math.sqrt(3))

print(3**0.5 == math.sqrt(3))

[vagrant@localhost python]$ python myapp.py
1.7320508075688772
1.7320508075688772
True

複素数

import math
import cmath

print(cmath.sqrt(-3 + 4j))

print(cmath.sqrt(-1))

[vagrant@localhost python]$ python myapp.py
(1+2j)
1j

指数関数: eのべき乗

import math

print(math.exp(3))

print(math.exp(2) == math.e**2)

[vagrant@localhost python]$ python myapp.py
20.085536923187668
False
おおお

対数関数

print(math.log(math.e))
print(math.log10(100000))
print(math.log2(1024))

[vagrant@localhost python]$ python myapp.py
1.0
5.0
10.0

pythonで2次方程式を解く

2次式は最高次数が2次の式
y = ax^2 + bx + c とすると、xとyの関係を表すグラフが放物線の軌道を描く

# solving a quadratic equation

def solv_quadratic_equation(a, b, c):
	""" 2次方程式を解く """
	D = (b**2 - 4*a*c) ** (1/2)
	x_1 = (-b + D) / (2 * a)
	x_2 = (-b - D) / (2 * a)

	return x_1, x_2

if __name__ == '__main__':
	a = input('input a: ')
	b = input('input b: ')
	c = input('input c: ')

	print(solv_quadratic_equation.__doc__)
	x1, x2 = solv_quadratic_equation(float(a), float(b), float(c))

	print('x1:{}'.format(x1))
	print('x2:{}'.format(x2))

[vagrant@localhost python]$ python myapp.py
input a: 1
input b: 2
input c: 1
2次方程式を解く
x1:-1.0
x2:-1.0
[vagrant@localhost python]$ python myapp.py
input a: 1
input b: 2
input c: 3
2次方程式を解く
x1:(-0.9999999999999999+1.414213562373

すげーーーーーーーーーーーーーーー&ドウシヨーーーーーーーーーーー

連立一次方程式


A = np.array([[2,4,6,8,10],
			[3,8,7,6,2],
			[5,7,21,44,25]])
b = np.array([[6],[15],[24]])

piA = np.linalg.pinv(A)

x = np.dot(piA, b)

print(x)
print(np.dot(A, x))

[vagrant@localhost python]$ python myapp.py
[[ 0.34401851]
[ 1.0376735 ]
[ 0.68374091]
[ 0.33377396]
[-0.56113681]]
[[ 6.]
[15.]
[24.]]

連立一次方程式、というか、行列の計算か。
keep going, do not stop

numpyの基本

四則計算

import numpy as np

res1 = np.add(20,30)
res2 = np.subtract(20,55)
res3 = np.multiply(40,25)
res4 = np.divide(500,5)

print(
	res1,
	res2,
	res3,
	res4,
)

[vagrant@localhost python]$ python myapp.py
50 -35 1000 100.0

addとsubtractは行列にも適用できる。行列の掛け算はnp.dotでしたね。

累乗と平方根

import numpy as np

res1 = np.power(2,4)
res2 = np.sqrt(2)
res3 = np.sqrt(4)

print(
	res1,
	res2,
	res3,
)

[vagrant@localhost python]$ python myapp.py
16 1.4142135623730951 2.0
なるほどー、power, sqrtか。

res1 = np.sin(30)
res2 = np.cos(30)
res3 = np.tan(30)

[vagrant@localhost python]$ python myapp.py
-0.9880316240928618 0.15425144988758405 -6.405331196646276

引数はradian。通りでおかしなことになってるわけだ。
180°がπ radian

30°を表したいなら

res1 = np.sin(np.pi * 1/6)
res2 = np.cos(np.pi * 1/6)
res3 = np.tan(np.pi * 1/6)

[vagrant@localhost python]$ python myapp.py
0.49999999999999994 0.8660254037844387 0.5773502691896257
あああああああ、誤差がああああああ、というか、これ、途方も無いな。。
全然先が見えないんだが。。ま、phpよりもpythonの方が遥かに計算の相性が良いことがわかってきた。

numpyとは?

-numpyはpythonで学術計算をする為のライブラリ
-機械学習でも頻繁に使われるライブラリ
-基本的な計算はPythonだけでも出来るが、numpyを使うとその計算が高速になったり、より楽になったりする

import numpy as np

vec1 = np.array([1,2,3])
print(vec1)

(anaconda3-2019.03) [vagrant@localhost python]$ pyenv global 3.6.4
[vagrant@localhost python]$ python -V
Python 3.6.4
[vagrant@localhost python]$ python myapp.py
[1 2 3]

ん、配列のカンマが消えてる?
あ、あ、行ベクトルを表現してるのかな。いきなりつまづいたなー

vec1 = np.array([[1,2,3],[4,5,6]])

二次元の行列。配列を入れ子にする。
[vagrant@localhost python]$ python myapp.py
[[1 2 3]
[4 5 6]]

ベクトルの足し算、引き算

vecx = np.array([[1,2,3],[4,5,6]])
vecy = np.array([[4,5,6],[7,8,9]])
vecz = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(vecx + vecy)
print(vecx - vecy)

[vagrant@localhost python]$ python myapp.py
[[ 5 7 9]
[11 13 15]]
[[-3 -3 -3]
[-3 -3 -3]]

ベクトルの掛け算

vecx = np.array([[1,2,3],[4,5,6]])
vecy = np.array([[1,2],[2,3]])
vecz = np.array([[1,2,3],[4,5,6],[7,8,9]])
res = np.dot(vecx, vecz)
print(res)

[vagrant@localhost python]$ python myapp.py
[[30 36 42]
[66 81 96]]

行分の列がないと掛け算は成立しませんね。
vecz = np.array([[1],[4],[7]])

anaconda

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

x = np.arange(0,11)
y = 4*x+3
plt.plot(x,y)
plt.grid()

[vagrant@localhost python]$ python myapp.py
File “myapp.py”, line 3
%matplotlib inline
^
SyntaxError: invalid syntax

ん?これって、anacondaが入ってないって事?

[vagrant@localhost python]$ pyenv -v
pyenv 1.2.13

[vagrant@localhost python]$ pyenv install anaconda3-2019.03
Downloading Anaconda3-2019.03-Linux-x86_64.sh…
-> https://repo.continuum.io/archive/Anaconda3-2019.03-Linux-x86_64.sh
Installing Anaconda3-2019.03-Linux-x86_64…
Installed Anaconda3-2019.03-Linux-x86_64 to /home/vagrant/.pyenv/versions/anaconda3-2019.03

[vagrant@localhost python]$ python –version
Python 3.7.3
(anaconda3-2019.03)

(anaconda3-2019.03) [vagrant@localhost python]$ python myapp.py
File “myapp.py”, line 3
% matplotlib inline
^
SyntaxError: invalid syntax

これはどうやらコマンドラインで画像を描画できないからっぽいですね。
まあよかった、原因がわかって。

centosのpythonをupdateしよう

from sklearn.datasets import load_boston
boston = load_boston()

import pandas as pd
boston_df = pd.DataFrame(boston.data, columns = boston.feature_names)
boston_df['MEDV'] = boston.target

boston_df.head()

TypeError: descriptor ‘__subclasses__’ of ‘type’ object needs an argument

[vagrant@localhost python]$ sudo yum install -y https://centos6.iuscommunity.org/ius-release.rpm

まず、python36を入れます。
[vagrant@localhost python]$ sudo yum install -y python36*

[vagrant@localhost python]$ pyenv versions
system
* 3.5.2 (set by /home/vagrant/.pyenv/version)
[vagrant@localhost python]$ pyenv install 3.6.4
Downloading Python-3.6.4.tar.xz…
-> https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tar.xz
Installing Python-3.6.4…
Installed Python-3.6.4 to /home/vagrant/.pyenv/versions/3.6.4

[vagrant@localhost python]$ pyenv global 3.6.4
[vagrant@localhost python]$ python -V
Python 3.6.4

[vagrant@localhost python]$ pip list
Package Version
——————– ——-
absl-py 0.8.0
astor 0.8.0
chainer 6.3.0
cycler 0.10.0
decorator 4.4.0
filelock 3.0.12
gast 0.2.2
google-pasta 0.1.7
grpcio 1.23.0
h5py 2.9.0
imageio 2.5.0
joblib 0.13.2
Keras 2.2.5
Keras-Applications 1.0.8
Keras-Preprocessing 1.1.0
kiwisolver 1.1.0
Markdown 3.1.1
matplotlib 3.1.1
networkx 2.3
numpy 1.17.1
pandas 0.25.1
Pillow 6.1.0
pip 19.2.3
protobuf 3.7.1
pyparsing 2.4.2
python-dateutil 2.8.0
pytz 2019.2
PyWavelets 1.0.3
PyYAML 5.1.2
scikit-image 0.15.0
scikit-learn 0.21.3
scipy 1.3.1
setuptools 28.8.0
six 1.12.0
tensorboard 1.14.0
tensorflow 1.14.0
tensorflow-estimator 1.14.0
termcolor 1.1.0
Theano 1.0.4
typing 3.6.6
typing-extensions 3.6.6
Werkzeug 0.15.5
wheel 0.33.6
wrapt 1.11.2

[vagrant@localhost python]$ python myapp.py
/home/vagrant/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pandas/compat/__init__.py:84: UserWarning: Could not import the lzma module. Your installed Python is incomplete. Attempting to use lzma compression will result in a RuntimeError.
warnings.warn(msg)
/home/vagrant/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pandas/compat/__init__.py:84: UserWarning: Could not import the lzma module. Your installed Python is incomplete. Attempting to use lzma compression will result in a RuntimeError.
warnings.warn(msg)

なにいいいいいいいいいいいいいいいいいいいいいい