唯物是真 @Scaled_Wurm

プログラミング(主にPython2.7)とか機械学習とか

matplotlibを使おう

Python用のグラフ描画ライブラリのmatplotlibを使って見ました.
使いこなせるようになればRからPythonに完全に移行できそうです.


以前書いたソフトマージンSVMのコードを用いて可視化して見ました.
http://d.hatena.ne.jp/sucrose/20111015/p1
結果は以下のようになりました.
f:id:sucrose:20111112182645p:image

import numpy as np
import openopt as oo
import matplotlib.pyplot as plt

#settings
C = 0.1
EPS = 0.00001

#data generation
x1 = np.random.multivariate_normal([0, 0], np.eye(2), 20)
x2 = np.random.multivariate_normal([2, 2], np.diag([2, 2]), 20)
x = np.vstack((x1, x2))
t = np.array([-1] * x1.shape[0] + [1] * x2.shape[0])

N = x.shape[0]

#optimize
qp = oo.QP((t * np.dot(x, x.T)).T * t, -np.ones(N), Aeq = t, beq = 0, lb = np.zeros(N), ub = np.array([C] * N))
result = qp._solve('cvxopt_qp', iprint = 0)
a = result.xf

#parameter estimation
w = (x.T * t * a).sum(axis = 1)
support_vector = a > EPS
b = (sum(t[support_vector]) - sum(np.dot(w, x[support_vector].T))) / sum(support_vector)

#output
print np.dot(w, x.T) + b

#visualize
plt.scatter(x1[..., 0], x1[..., 1], color='r', marker='x')
plt.scatter(x2[..., 0], x2[..., 1], color='b', marker='x')
plt.plot(range(-3, 6), [-w[1] / w[0] * i - b /w[0] for i in range(-3, 6)], color='g')

plt.show()
plt.close()