Commits

Takayuki KONDO  committed 521cfba

numpy: add lstsq sample

  • Participants
  • Parent commits bfa3e12

Comments (0)

Files changed (1)

File py/numpy/lstsq_sample.py

+# -*- coding: utf-8 -*-
+# http://stmind.hatenablog.com/entry/20120424/1335307505
+
+import numpy as np
+import matplotlib.pylab as plt
+
+
+x = np.arange(-3, 10, 0.07)
+# shape(x) = (400,)
+y = 2.5 * np.exp(-(x)**2/9) + 3.2 * np.exp(-(x-0.5)**2/4)
+y += np.random.normal(0.0, 1.0, len(x))
+# shape(y) = (400,)
+nParam = 2
+A = np.zeros((len(x), nParam), float)
+A[:, 0] = np.exp(-(x)**2/9)
+A[:, 1] = np.exp(-(x-0.5)**2/4)
+# shape(A) = (400, 2)
+
+(p, residuals, rank, s) = np.linalg.lstsq(A, y)
+print "p=", p
+print "residuals=", residuals
+print "rank=", rank
+print "s=", s
+
+plt.plot(x, y, '.')
+
+plt.plot(x, p[0]*A[:, 0] + p[1]*A[:, 1], label='measured')
+plt.plot(x, 2.5*A[:, 0] + 3.2*A[:, 1], label='expected')
+
+
+plt.legend()
+plt.show()