Skip to content

Instantly share code, notes, and snippets.

@chunrapeepat
Created July 1, 2017 12:21
Show Gist options
  • Save chunrapeepat/f166b20937b44c705a4900a2f46245ac to your computer and use it in GitHub Desktop.
Save chunrapeepat/f166b20937b44c705a4900a2f46245ac to your computer and use it in GitHub Desktop.
Linear Regression Example
# -*- coding: utf-8 -*-
from numpy import *
def compute_error_function(dataset, current_m, current_c):
error = 0
for i in range(0, len(dataset)):
x = dataset[i, 0]
y = dataset[i, 1]
error += (y - (current_m * x + current_c)) ** 2
return (error / float(len(dataset))) * 0.5
def gradient_descent(dataset, learning_rate, init_m, init_c, iterator):
m = init_m
c = init_c
for i in range(iterator):
m_gradient = 0
c_gradient = 0
for j in range(0, len(dataset)):
x = dataset[j, 0]
y = dataset[j, 1]
# partial dirivitive
m_gradient += -(1/float(len(dataset))) * x * (y - (m * x + c))
c_gradient += -(1/float(len(dataset))) * (y - (m * x + c))
m = m - learning_rate * m_gradient
c = c - learning_rate * c_gradient
if i % 2000 == 0:
print 'train({0})> y = {1}x + {2} & error = {3}'.format(i, m, c, compute_error_function(dataset, m, c))
return [m, c]
def execute():
# ค่าอัตราการเรียนรู้
learning_rate = 0.0001
# ค่าเริ่มต้นความชัน (จะเป็นเท่าไรก็ได้)
init_m = 0
# ค่าเริ่มต้นจุดตัดแกน Y (จะเป็นเท่าไรก็ได้)
init_c = 0
# จำนวนครั้งในการเรียนรู้
iterator = 10000
# อ่านข้อมูลจากไฟล์ แล้วเปลี่ยนเป็น Array
dataset = genfromtxt('dataset.csv', delimiter = ',')
# รับค่า m, c มาจากการประมวลผล (y = mx + c)
[m, c] = gradient_descent(dataset, learning_rate, init_m, init_c, iterator)
# แสดงค่าหลังจากประมวลผลแล้่ว
print 'done!!!> y = {0}x + {1} & error = {2}'.format(m, c, compute_error_function(dataset, m, c))
if __name__ == '__main__':
# ประมวลผล
execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment