Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8f67fa7

Browse files
author
sherlock-coding
committed
update
1 parent a2207b3 commit 8f67fa7

File tree

1 file changed

+40
-6
lines changed

1 file changed

+40
-6
lines changed

Homework/HousingPricePrediction.py

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,27 @@
22
import math
33
import matplotlib.pyplot as plt
44

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+
526
#求h(x,theta)
627
def GetHThetaX(x,theta):
728
theta_1 = theta[1:]
@@ -29,17 +50,23 @@ def GetGradient(X,Y,theta,j):
2950

3051

3152
#n表示n维的特征向量
32-
def LMS_Prediction(X,X1,Y,n,year):
53+
def LMS_theta(X,Y,n):
3354
#theta全都初始化为0
3455
#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)
3663

3764
plt.plot(X1,Y,'ro')
38-
plt.axis([2000,2015,1,15])
65+
plt.axis([-0.8,0.8,1,15])
3966
plt.plot(X1,[theta[0]+theta[1]*x for x in X1],'y-')
4067

4168
#learning rate设置
42-
alpha = 0.00000001
69+
alpha = 0.1
4370

4471
steps = 0
4572

@@ -66,13 +93,20 @@ def LMS_Prediction(X,X1,Y,n,year):
6693
plt.plot(X1,[theta[0]+theta[1]*x for x in X1],'r-')
6794
plt.show()
6895

96+
return theta
97+
6998

7099

71100
if __name__ == '__main__':
72101
X = [[2000],[2001],[2002],[2003],[2004],[2005],[2006],[2007],[2008],[2009],[2010],[2011],[2012],[2013]]
73102
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))
76110
#X = [[1],[2],[5],[7], [10], [15]]
77111
#Y = [2, 6, 7, 9, 14, 19]
78112
#X = [[2000],[2001],[2002],[2003],[2004],[2005],[2006],[2007],[2008],[2009],[2010],[2011],[2012],[2013]]

0 commit comments

Comments
 (0)