2
2
import math
3
3
import matplotlib .pyplot as plt
4
4
5
+ #特征缩放
6
+ def FeatureScaling (X ,n ):
7
+ X_fs = X
8
+ avg_fs = []
9
+ s_fs = []
10
+ for i in range (0 ,n - 1 ):
11
+ x_i = []
12
+ for x in X :
13
+ x_i .append (x [i ])
14
+ avg = sum (x_i )/ (len (X ))
15
+ s = max (x_i )- min (x_i )
16
+ avg_fs .append (avg )
17
+ s_fs .append (s )
18
+ for j in range (0 ,len (X )):
19
+ x_i [j ] = (x_i [j ]- avg )/ s
20
+ for k in range (0 ,len (X )):
21
+ X [k ][i ] = x_i [k ]
22
+
23
+ return X_fs ,avg_fs ,s_fs
24
+
25
+
5
26
#求h(x,theta)
6
27
def GetHThetaX (x ,theta ):
7
28
theta_1 = theta [1 :]
@@ -29,17 +50,23 @@ def GetGradient(X,Y,theta,j):
29
50
30
51
31
52
#n表示n维的特征向量
32
- def LMS_Prediction (X ,X1 , Y ,n , year ):
53
+ def LMS_theta (X ,Y ,n ):
33
54
#theta全都初始化为0
34
55
#theta = [i for i in range(0,n)]
35
- theta = [- 1500 ,1 ]
56
+ theta = [0 ]* n
57
+
58
+ X1 = []
59
+ for x in X :
60
+ X1 .append (x [0 ])
61
+
62
+ print (X1 )
36
63
37
64
plt .plot (X1 ,Y ,'ro' )
38
- plt .axis ([2000 , 2015 ,1 ,15 ])
65
+ plt .axis ([- 0.8 , 0.8 ,1 ,15 ])
39
66
plt .plot (X1 ,[theta [0 ]+ theta [1 ]* x for x in X1 ],'y-' )
40
67
41
68
#learning rate设置
42
- alpha = 0.00000001
69
+ alpha = 0.1
43
70
44
71
steps = 0
45
72
@@ -66,13 +93,20 @@ def LMS_Prediction(X,X1,Y,n,year):
66
93
plt .plot (X1 ,[theta [0 ]+ theta [1 ]* x for x in X1 ],'r-' )
67
94
plt .show ()
68
95
96
+ return theta
97
+
69
98
70
99
71
100
if __name__ == '__main__' :
72
101
X = [[2000 ],[2001 ],[2002 ],[2003 ],[2004 ],[2005 ],[2006 ],[2007 ],[2008 ],[2009 ],[2010 ],[2011 ],[2012 ],[2013 ]]
73
102
Y = [2.000 ,2.500 ,2.900 ,3.147 ,4.515 ,4.903 ,5.365 ,5.704 ,6.853 ,7.971 ,8.561 ,10.000 ,11.280 ,12.900 ]
74
- X1 = [2000 ,2001 ,2002 ,2003 ,2004 ,2005 ,2006 ,2007 ,2008 ,2009 ,2010 ,2011 ,2012 ,2013 ]
75
- LMS_Prediction (X ,X1 ,Y ,2 ,2014 )
103
+ X_fs ,avg_fs ,s_fs = FeatureScaling (X ,2 )
104
+ theta = LMS_theta (X_fs ,Y ,2 )
105
+ print (theta )
106
+ x_p = [2014 ]
107
+ for i in range (0 ,2 - 1 ):
108
+ x_p [i ] = (x_p [i ]- avg_fs [i ])/ s_fs [i ]
109
+ print (GetHThetaX (x_p ,theta ))
76
110
#X = [[1],[2],[5],[7], [10], [15]]
77
111
#Y = [2, 6, 7, 9, 14, 19]
78
112
#X = [[2000],[2001],[2002],[2003],[2004],[2005],[2006],[2007],[2008],[2009],[2010],[2011],[2012],[2013]]
0 commit comments