1. 数学の基礎とPythonによる表現
demorran1.pyfor P in [False, True]:
for Q in [False, True]:
print(P, Q, not P, not Q, P and Q,
not(P and Q), (not P) or (not Q))
planet.pyC = {'Earth': '3rd', 'Mars': '4th', 'Jupiter': '5th'}
for x in C:
print(f'{x} is the {C[x]} planet in the solar system.')
print()
for x in sorted(C):
print(f'{x} is the {C[x]} planet in the solar system.')
matrix.pyA = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(3):
for j in range(3):
print(f'A[{i}][{j}]=={A[i][j]}', end=', ')
print()
lena1.pyimport PIL.Image as Img
from numpy import array
im1 = Img.open('lena.png').convert('L')
im1.thumbnail((100, 100))
A = array(im1)
m, n = A.shape
B = A < 128
h = max(m, n)
y0, x0 = m / h, n / h
def f(i, j):
return (x0 * (-1 + 2 * j / (n - 1)), y0 * (1 - 2 * i / (m - 1)))
P = [f(i, j) for i in range(m) for j in range(n) if B[i, j]]
with open('lena.txt', 'w') as fd:
fd.write(repr(P))
画像の第i行第j列の画素を、x-y座標平面の-1\leqq x\leqq 1,\ -1\leqq y\leqq 1である点\left(x, y\right)に対応させる関数fを定義します。
f\ :\ \left(i,j\right)\ \mapsto\ \left(x_0\left(-1+\dfrac{2j}{n-1}\right),\ y_0\left(1-\dfrac{2i}{m-1}\right)\right)
fによって
\left(0,0\right)\ \mapsto\ \left(-x_0,\phantom{-}y_0\right)
\left(0,n-1\right)\ \mapsto\ \left(\phantom{-}x_0,\phantom{-}y_0\right)
\left(m-1,0\right)\ \mapsto\ \left(-x_0,-y_0\right)
\left(m-1,n-1\right)\ \mapsto\ \left(\phantom{-}x_0,-y_0\right)
と変換されます。画像が正方形であれば、即ちm=n=100ならばx_0=y_0=1ですが、そうでない場合は長辺がちょうど-1と1の間に収まるようにします。
lena2.pyimport matplotlib.pyplot as plt
with open('lena.txt', 'r') as fd:
P = eval(fd.read())
x, y = zip(*P)
plt.scatter(x, y, s=3)
plt.axis('scaled'), plt.xlim(-1, 1), plt.ylim(-1, 1), plt.show()
open('lena.txt', 'r')
の 'r'
はファイルを読み込みのためにオープンするという意味です。 'r'
と 'w'
を間違えると、既にあるファイルを壊すことになりますので、注意してください。 Data = fd.read()
でファイルの全データが文字列として Data
に代入されます。 numpy.array(eval(Data))
は、 Data
にある文字列をPythonの式として評価してリストに戻し、さらにそれをアレイにしています。 Z
はxy座標の列であり、 Z[: , 0]
でx座標だけの列、 Z[: , 1]
でy座標だけの列を取り出せます。 plt.scatter
はxy座標平面に点をプロットする関数で、 s = 3
は点の大きさを指定しています。
複素平面に線図形を描くGUI
tablet.pyfrom tkinter import Tk, Button, Canvas
def point(x, y):
return C.create_oval(x - 1, y - 1, x + 1, y + 1, fill='black')
def PushButton(event):
x, y = event.x, event.y
Segs.append([((x, y), point(x, y))])
def DragMouse(event):
x, y = event.x, event.y
Segs[-1].append(((x, y), point(x, y)))
def Erase():
if Segs != []:
seg = Segs.pop()
for p in seg:
C.delete(p[1])
def Save():
if Segs != []:
L = []
for seg in Segs:
for (x, y), _ in seg:
L.append((x - 160) / 160 + 1j * (160 - y) / 160)
with open(filename, 'w') as fd:
fd.write(repr(L))
print('saved!')
filename = 'tablet.txt'
Segs = []
tk = Tk()
Button(tk, text="erase", command=Erase).pack()
C = Canvas(tk, width=320, height=320)
C.pack()
C.bind("<Button-1>", PushButton)
C.bind("<B1-Motion>", DragMouse)
Button(tk, text="save", command=Save).pack()
tk.mainloop()
次は、よく機械学習の実験に使われるMNISTの手書き数字のデータの一部を表示したものです。
train-images-idx3-ubyte.gz: training set images (9912422 bytes)
train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)
の四つのファイルがあります。こららをダウンロードして解凍してできたものを、これから作成するプログラムmnist.pyと同じフォルダに置きます。ファイル名をそれぞれ
train-images.bin
train-labels.bin
test-images.bin
test-labels.bin
としておくことにします。train-images.bin(test-images.bin)のファイルには、全部で60,000個(10,000個)の画像があります。各画像のラベル(画像が表す数字)がtrain-labels.bin(test-labels)のファイルにあります。通常、train-*の方が機械学習の学習に使われ、test-*の方が学習結果の検証に用いられます。これらはバイナリファイルですが、どのようなデータ形式となっているかは上のページの最後の方に書いてありますので、それに従って次のプログラムで中身を覗いてみましょう。
mnist.pyimport numpy as np
import matplotlib.pyplot as plt
N = 10000
with open('test-images.bin', 'rb') as f1:
X = np.fromfile(f1, 'uint8', -1)[16:]
X = X.reshape((N, 28, 28))
with open('test-labels.bin', 'rb') as f2:
Y = np.fromfile(f2, 'uint8', -1)[8:]
D = {y: [] for y in set(Y)}
for x, y in zip(X, Y):
D[y].append(x)
print([len(D[y]) for y in sorted(D)])
fig, ax = plt.subplots(10, 10))
for y in D:
for k in range(10):
A = 255 - D[y][k]
ax[y][k].imshow(A, 'gray')
ax[y][k].tick_params(labelbottom=False, labelleft=False,
color='white')
plt.show()
PyX
comp.pyfrom pyx import *
C = canvas.canvas()
text.set(text.LatexRunner)
text.preamble(r'\usepackage{amsmath, amsfonts, amssymb}')
C.stroke(path.circle(0, 0, 1),[style.linewidth.thick, deco.filled([color.gray(0.75)])])
C.stroke(path.line(-5, 0, 5, 0),[style.linewidth.THick, deco.earrow.Large])
C.stroke(path.line(0, -5, 0, 5),[style.linewidth.THick, deco.earrow.Large])
C.stroke(path.line(1, -0.1, 1, 0.1))
C.stroke(path.line(-0.1, 1, 0.1, 1))
C.text(-0.1, -0.1, r"\huge 0" ,[text.halign.right, text.valign.top])
C.text(1, -0.2, r"\huge 1" ,[text.halign.left, text.valign.top])
C.text(-0.2, 1, r"\huge $i$" ,[text.halign.right, text.valign.bottom])
C.stroke(path.circle(2, 3, 0.05), [deco.filled([color.grey.black])])
C.text(2.1, 3.1, r"\huge $z=x+iy$" ,[text.halign.left, text.valign.bottom])
C.stroke(path.line(2, 3, 2, 0),[style.linewidth.thick, style.linestyle.dashed])
C.stroke(path.line(2, 3, 0, 3),[style.linewidth.thick, style.linestyle.dashed])
C.text(2, -0.3, r"\huge $x$" ,[text.halign.center, text.valign.top])
C.text(-0.1, 3, r"\huge $iy$" ,[text.halign.right, text.valign.middle])
C.writePDFfile('comp.pdf')