資源簡介
#多元線性回歸預測房子的價格,構建一個房子價格的python模型。
##ex1data2.txt中包含了房子價格的訓練組。第一列是房子的尺寸(平方英尺),第二列是臥室的數量,第三列是房子的價格。

代碼片段和文件信息
##多元線性回歸預測房子的價格,構建一個房子價格的模型。
##ex1data2.txt中包含了房子價格的訓練組。第一列是房子的尺寸(平方英尺),第二列是臥室的數量,第三列是房子的價格。
#-*-?coding:?UTF-8?-*-
import?random
import?numpy?as?np
import?matplotlib.pyplot?as?plt
#加載數據
def?load_exdata(filename):
????data?=?[]
????with?open(filename?‘r‘)?as?f:
????????for?line?in?f.readlines():
????????????line?=?line.split(‘‘)
????????????current?=?[int(item)?for?item?in?line]?#根據數據輸入的不同確定是int?還是其他類型
????????????#5.52779.1302
????????????data.append(current)
????return?data
data?=?load_exdata(‘ex1data2.txt‘);
data?=?np.array(datanp.int64)??????#根據數據輸入的不同確定是int?還是其他類型
#特征縮放
def?featureNormalize(X):
????X_norm?=?X;
????mu?=?np.zeros((1X.shape[1]))
????sigma?=?np.zeros((1X.shape[1]))
????for?i?in?range(X.shape[1]):
????????mu[0i]?=?np.mean(X[:i])?#?均值
????????sigma[0i]?=?np.std(X[:i])?????#?標準差
#?????print(mu)
#?????print(sigma)
????X_norm??=?(X?-?mu)?/?sigma
????return?X_normmusigma
?
#計算損失
def?computeCost(X?y?theta):
????m?=?y.shape[0]
#?????J?=?(np.sum((X.dot(theta)?-?y)**2))?/?(2*m)
????C?=?X.dot(theta)?-?y
????J2?=?(C.T.dot(C))/?(2*m)
????return?J2
?
#梯度下降
def?gradientDescent(X?y?theta?alpha?num_iters):
????m?=?y.shape[0]
????#print(m)
????#?存儲歷史誤差
????J_history?=?np.zeros((num_iters?1))
????for?iter?in?range(num_iters):
????????#?對J求導,得到?alpha/m?*?(WX?-?Y)*x(i),?(3m)*(m1)??X?(m3)*(31)?=?(m1)
????????theta?=?theta?-?(alpha/m)?*?(X.T.dot(X.dot(theta)?-?y))
????????J_history[iter]?=?computeCost(X?y?theta)
????return?J_historytheta
?????
?
iterations?=?10000??#迭代次數
alpha?=?0.01????#學習率
x?=?data[:(01)].reshape((-12))
y?=?data[:2].reshape((-11))
m?=?y.shape[0]
xmusigma?=?featureNormalize(x)
X?=?np.hstack([xnp.ones((x.shape[0]?1))])
#?X?=?X[range(2):]
#?y?=?y[range(2):]
?
theta?=?np.zeros((3?1))
?
j?=?computeCost(Xytheta)
J_historytheta?=?gradientDescent(X?y?theta?alpha?iterations)
?
?
print(‘Theta?found?by?gradient?descent‘theta)
def?predict(data):
????testx?=?np.array(data)
????testx?=?((testx?-?mu)?/?sigma)
????testx?=?np.hstack([testxnp.ones((testx.shape[0]?1))])
????price?=?testx.dot(theta)
????print(‘price?is?%d?‘?%?(price))
?
predict([16503])
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????2527??2018-09-26?10:01??多元線性回歸預測房價算法實現.py
?????文件?????????657??2017-03-14?09:40??ex1data2.txt
- 上一篇:Berlekamp-Massey.py
- 下一篇:百度遷徙自動腳本
評論
共有 條評論