-
大小: 2KB文件類型: .zip金幣: 2下載: 0 次發(fā)布日期: 2021-05-13
- 語(yǔ)言: Python
- 標(biāo)簽:
資源簡(jiǎn)介
#多元線性回歸預(yù)測(cè)房子的價(jià)格,構(gòu)建一個(gè)房子價(jià)格的python模型。
##ex1data2.txt中包含了房子價(jià)格的訓(xùn)練組。第一列是房子的尺寸(平方英尺),第二列是臥室的數(shù)量,第三列是房子的價(jià)格。

代碼片段和文件信息
##多元線性回歸預(yù)測(cè)房子的價(jià)格,構(gòu)建一個(gè)房子價(jià)格的模型。
##ex1data2.txt中包含了房子價(jià)格的訓(xùn)練組。第一列是房子的尺寸(平方英尺),第二列是臥室的數(shù)量,第三列是房子的價(jià)格。
#-*-?coding:?UTF-8?-*-
import?random
import?numpy?as?np
import?matplotlib.pyplot?as?plt
#加載數(shù)據(jù)
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]?#根據(jù)數(shù)據(jù)輸入的不同確定是int?還是其他類型
????????????#5.52779.1302
????????????data.append(current)
????return?data
data?=?load_exdata(‘ex1data2.txt‘);
data?=?np.array(datanp.int64)??????#根據(jù)數(shù)據(jù)輸入的不同確定是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])?????#?標(biāo)準(zhǔn)差
#?????print(mu)
#?????print(sigma)
????X_norm??=?(X?-?mu)?/?sigma
????return?X_normmusigma
?
#計(jì)算損失
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)
????#?存儲(chǔ)歷史誤差
????J_history?=?np.zeros((num_iters?1))
????for?iter?in?range(num_iters):
????????#?對(duì)J求導(dǎo),得到?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??#迭代次數(shù)
alpha?=?0.01????#學(xué)習(xí)率
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])
?屬性????????????大小?????日期????時(shí)間???名稱
-----------?---------??----------?-----??----
?????文件????????2527??2018-09-26?10:01??多元線性回歸預(yù)測(cè)房?jī)r(jià)算法實(shí)現(xiàn).py
?????文件?????????657??2017-03-14?09:40??ex1data2.txt
- 上一篇:Berlekamp-Massey.py
- 下一篇:百度遷徙自動(dòng)腳本
評(píng)論
共有 條評(píng)論