Skip to content

Instantly share code, notes, and snippets.

@moratorium08
Last active September 5, 2016 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moratorium08/527aebb4b6d8e17b8ab6249e9c2945e4 to your computer and use it in GitHub Desktop.
Save moratorium08/527aebb4b6d8e17b8ab6249e9c2945e4 to your computer and use it in GitHub Desktop.
# coding:utf-8
import numpy as np
import math
import random
import matplotlib.pyplot as plt
def sinpi(x):
return math.sin(2*math.pi * x)
def base(x, n):
return x**n
def makeData(N):
l = []
for i in range(N):
x = random.random()
error = np.random.normal(0,0.1)
l.append((x,sinpi(x)+error))
return l
def main():
N = 100
M = 8
data = makeData(N)
phi = [[base(data[i][0], j) for j in range(M)] for i in range(N)]
phi = np.matrix(phi)
t = np.matrix([x[1] for x in data]).T
w = np.linalg.inv(phi.T.dot(phi)).dot(phi.T).dot(t)
def f(v):
s = 0
for i in range(M):
s += base(v,i)*w[i,0]
return s
x = np.arange(0,1,0.01)
y = f(x)
plt.plot(x, y)
plt.scatter([x[0] for x in data], [x[1] for x in data], c="red")
plt.show()
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment