Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import random
from matplotlib import pyplot as plt
def makeData(trainNum):
noise = np.random.randn(trainNum) * 0.1 #make a noise
xTrain = np.random.rand(trainNum) #training data
yTrain = np.sin(2 * np.pi * xTrain) + noise #supervised data'xTrain.npy',xTrain)'yTrain.npy',yTrain)
def setTrain():
xTrain = np.load('xTrain.npy')
yTrain = np.load('yTrain.npy')
return xTrain,yTrain
def fitting(M,trainNum):
w = np.random.rand(M+1) #init a weight
xTrain,yTrain = setTrain()
X = np.array([pow(xTrain,i) for i in range(M+1)])
Y =,X)
A = np.array([[pow(xTrain,i+j).sum() for j in range(M+1)] for i in range(M+1)])
T = np.array([(pow(xTrain,i)*yTrain).sum() for i in range(M+1)])
return np.linalg.solve(A,T)
def RMS(y,t,N): # Root Mean Square error
return np.sqrt(pow(y-t,2).sum()/N)
if __name__ == '__main__':
trainNum = 10
x = np.arange(0,1,0.01)
w = fitting(M,trainNum)
xTrain,yTrain = setTrain()
for M in range(10):
w = fitting(M,trainNum)
tmpY = np.array([w[i] * pow(x,i) for i in range(M+1)])
y = tmpY.sum(axis = 0)
plt.plot(x,y,label = 'M = ' + str(M))
plt.plot(x,np.sin(2*np.pi*x),label = 'sin')
plt.ylim(ymin = -1.3,ymax = 1.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment