Browse Source

梯度下降法

yufeng0528 4 years ago
parent
commit
cbee0c8a53
1 changed files with 45 additions and 0 deletions
  1. 45 0
      linear/gradient_linear.py

+ 45 - 0
linear/gradient_linear.py

@@ -0,0 +1,45 @@
1
+#!/usr/bin/python
2
+# -*- coding: UTF-8 -*-
3
+'''
4
+最简单的mse
5
+'''
6
+import sys
7
+reload(sys)
8
+sys.setdefaultencoding('utf-8')
9
+
10
+import random
11
+import numpy as np
12
+from sklearn.linear_model import LinearRegression
13
+from sklearn import metrics
14
+from draw import draw_util
15
+
16
+
17
+def read_data(path):
18
+    with open(path) as f :
19
+        lines=f.readlines()
20
+    lines=[eval(line.strip()) for line in lines]
21
+    return lines
22
+
23
+
24
+def cal_step_pow(data, w, b=3):
25
+    p = [(w*item[0][0] + b - item[1][0])*item[0][0]*2  for item in data]
26
+    sum_p = sum(p)
27
+    return sum_p/len(data)
28
+
29
+def cal_mse(data, w, b=3):
30
+    sum_p = sum([(w * item[0][0] + b - item[1][0]) * (w * item[0][0] + b - item[1][0]) for item in data])
31
+    return sum_p / len(data)
32
+
33
+def train():
34
+    train_data = read_data('train_data')
35
+    w = random.uniform(-50, 50)
36
+    for i in range(10):
37
+        step = cal_step_pow(train_data, w)*0.01
38
+        mse = cal_mse(train_data, w)
39
+        print w, step, mse
40
+
41
+        w = w - step
42
+
43
+
44
+if __name__ == '__main__':
45
+    train()