| [サイトマップへ] |
Google Colab はオンラインの Python 開発環境. 使用するには Google アカウントが必要
https://colab.research.google.com
変数: 変数には名前と値がある.
式: 式から値が求まる.式は変数を含むことができる.
x = 100 print(x) print(10 + 20 + 30) a = 100 print(a * 1.08)
類似した複数の式
print(100 * 1.08) print(150 * 1.08) print(400 * 1.08)
上の 3つの式を抽象化すると「a * 1.08」のような式になる. この式「a * 1.08」を含む関数 foo の定義とその使用例は次の通り.
def foo(a):
return(a * 1.08)
print(foo(100))
print(foo(150))
print(foo(400))
関数の中の式の評価では, 最新の変数値が用いられる
x = 30
def foo(a):
return(a * x)
x = 300
print(foo(100))
x = 3000
print(foo(100))
クラス名: C
その属性名: qty, weight, name
class C(object):
def __init__(self, qty, weight, name):
self.qty = qty
self.weight = weight
self.name = name
x = C(5, 170.51, 'apple')
print(vars(x))
y = C(3, 40.97, 'orange')
print(vars(y))
クラス名: D
属性名: s_hour, s_minute, e_hour, e_minute
class D(object):
def __init__(self, s_hour, s_minute):
self.s_hour = s_hour
self.s_minute = s_minute
self.e_hour = None
self.e_minute = None
z = D(15, 30)
print(vars(z))
z2 = D(16, 15)
print(vars(z2))
vars(): 属性表示
「.」+属性名: 属性アクセス
「.」+メソッド名: メソッドアクセス
メソッド内では,self + 「.」で,属性やメソッドにアクセスする
class C(object):
def __init__(self, qty, weight, name):
self.qty = qty
self.weight = weight
self.name = name
def total(self):
return self.qty * self.weight
x = C(5, 170.51, 'apple')
print(vars(x))
print(x.name)
print(x.total())
クラス名: C
その属性名: qty, weight, name
クラス名: E
その属性名: qty, weight, name, price
クラス E は,スーパークラスであるクラス C の属性とメソッドを継承する
class C(object):
def __init__(self, qty, weight, name):
self.qty = qty
self.weight = weight
self.name = name
def total(self):
return self.qty * self.weight
class E(C):
def __init__(self, qty, weight, name, price):
super(E, self).__init__(qty, weight, name)
self.price = price
def payment(self):
return self.qty * self.price
x2 = E(2, 875.34, 'melon', 500)
print(vars(x2))
print(x2.total())
print(x2.payment())
print( type(100) )
print( type(1.23) )
print( type("Hello") )
print( type(True) )
print( type(False) )
print( type([1, 2, 3]) )
import numpy as np
print( type(np.zeros(10)) )
拡張機能の例: 現在の日時, 最大公約数, 方程式を解く, 平方根, 円周率, 三角関数, など
オペレーティングシステム(コンピュータ)のタイマーを利用
import datetime now = datetime.now() print(now)
24 と 18 の最大公約数を求めたい
import math print( math.gcd(24, 18) )
4x + 1 = 0 を解きたい
from scipy import optimize
def foo(x):
return 4 * x + 1
print( optimize.fsolve(foo, 10) )
面積が 7 の正方形の一辺の長さは? 結果 2.6457513110645907 を確認(結果は近似値)
import math print( math.sqrt(7) )
半径 3 の円の面積は? 円周率は, Python の拡張機能の math.pi を使用
import math print( 3 * 3 * math.pi )
三角形の2辺の長さが,4と6で,その間の角度が60度のとき.
import math print( (1/2) * 4 * 6 * math.sin(60 * math.pi / 180) )
age = 18
if (age <= 12):
print(500)
else:
print(1800)
8, 6, 4, 3, 2 というデータについて,合計を求めたい
x = [8, 6, 4, 2, 3] print( sum(x) )
月の日数についてのデータを作る.うるう年のことは考えないことにする
days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] print( days[6] ) print( days[7] )
同じ計算の繰り返し
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for t in x:
print( (9.8 / 2) * t * t )
import sys
for i in range(18):
sys.stdout.write("*")
0要素
import numpy as np x = np.zeros(10) print(x) print(type(x)) print(x.shape)
1要素
import numpy as np x = np.ones(10) print(x) print(type(x)) print(x.shape)
乱数
import numpy as np x = np.random.randn(10) print(x) print(type(x)) print(x.shape)
要素指定
import numpy as np x = np.array([3, 1, 2, 5, 4]) print(x) print(type(x)) print(x.shape)
arange
import numpy as np x = np.arange(-5, 4, 2) print(x) print(type(x)) print(x.shape)
linespace
import numpy as np x = np.linspace(-2, 2, 9) print(x) print(type(x)) print(x.shape)
import numpy as np x = np.zeros((2, 3)) print(x) print(type(x)) print(x.shape)
import numpy as np x = np.ones((2, 3)) print(x) print(type(x)) print(x.shape)
import numpy as np x = np.random.randn(2,3) print(x) print(type(x)) print(x.shape)
import numpy as np X, Y = np.meshgrid( np.array([2, 3, 4]), np.array([10, 20]) ) print(X) print(type(X)) print(X.shape) print(Y) print(type(Y)) print(Y.shape)
CSV ファイル書き出し.pandas 経由で行う
import numpy as np
import pandas as pd
X, Y = np.meshgrid( np.array([2, 3, 4]), np.array([10, 20]) )
XX = pd.DataFrame(X)
print(XX)
XX.to_csv("XX.csv", header=False, index=False)
YY = pd.DataFrame(Y)
print(YY)
YY.to_csv("YY.csv", header=False, index=False)
CSV ファイル読み込み.pandas 経由で行う
pd.read_csv("XX.csv", header=None)
pd.read_csv("YY.csv", header=None)
1次元を2次元に
import numpy as np x = np.array([3, 1, 2, 5, 4]) A = x[:, np.newaxis] B = x[np.newaxis, :] print(A) print(type(A)) print(A.shape) print(B) print(type(B)) print(B.shape)
a = [1, 2, 3, 4] print(a) type(a)
添え字は 0 から開始する
a = [10, 20, 30] print(a[1]) a[2] = 200 print(a)
散布図
import matplotlib.pyplot as plt import numpy as n x = [1, 2, 3, 4, 5] y = [2, 4, 1, 3, 5] plt.scatter(x, y)
3次元散布図
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import axes3d fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') x = [1, 2, 3, 4, 5] y = [2, 4, 1, 3, 5] z = [1, 1, 2, 2, 3] ax.scatter(x, y, z, c='b')
メッシュグリッドと関数の3次元プロット
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
X, Y = np.meshgrid( np.array([-2, -1, 0, 1, 2]), np.array([-3, -2, -1, 0, 1, 2, 3]) )
def f(x,y):
return x * y
Z = f(X, Y)
ax.scatter(X, Y, Z, c='b')
メッシュグリッドと関数の3次元プロット. 今度は x1, x2 のソフトマックス関数
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
X1, X2 = np.meshgrid( np.array([-2, -1, 0, 1, 2]), np.array([-3, -2, -1, 0, 1, 2, 3]) )
def softmax(x):
A = np.exp(x - np.max(x))
return A / A.sum()
def f(x1, x2):
return softmax( np.array([x1, x2]) )
Z = f(X1, X2)
ax.scatter(X1, X2, Z[0], c='b')
fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') ax.scatter(X1, X2, Z[1], c='b')
行列の足し算
import tensorflow as tf import numpy as np with tf.Session(): a = tf.constant( np.reshape([1, 1, 1, 1, 1, 1], (2, 3) ) ) b = tf.constant( np.reshape( [1, 2, 3, 4, 5, 6], (2, 3) ) ) c = tf.add(a, b) result = c.eval() result