DL:基于sklearn的加利福尼亚房价数据集实现GD算法
生活随笔
收集整理的這篇文章主要介紹了
DL:基于sklearn的加利福尼亚房价数据集实现GD算法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
DL:基于sklearn的加利福尼亞房?jī)r(jià)數(shù)據(jù)集實(shí)現(xiàn)GD算法
?
?
目錄
輸出結(jié)果
代碼設(shè)計(jì)
?
?
輸出結(jié)果
? ? ?該數(shù)據(jù)包含9個(gè)變量的20640個(gè)觀測(cè)值,該數(shù)據(jù)集包含平均房屋價(jià)值作為目標(biāo)變量和以下輸入變量(特征):平均收入、房屋平均年齡、平均房間、平均臥室、人口、平均占用、緯度和經(jīng)度。
更新……
?
代碼設(shè)計(jì)
#DL:基于sklearn的加利福尼亞房?jī)r(jià)數(shù)據(jù)集實(shí)現(xiàn)GD算法 import tensorflow as tf import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.preprocessing import StandardScaler scaler = StandardScaler() #將特征進(jìn)行標(biāo)準(zhǔn)歸一化 #獲取房?jī)r(jià)數(shù)據(jù) housing = fetch_california_housing() m,n = housing.data.shape print (housing.keys()) #輸出房?jī)r(jià)的key print (housing.feature_names) #輸出房?jī)r(jià)的特征: print (housing.target) print (housing.DESCR) housing_data_plus_bias = np.c_[np.ones((m,1)), housing.data] scaled_data = scaler. fit_transform(housing.data) data = np.c_[np.ones((m,1)),scaled_data] #設(shè)置參數(shù) n_epoch = 1000 learning_rate = 0.01 #設(shè)置placeholder即灌入數(shù)據(jù) X = tf.constant(data,dtype = tf.float32,name = "X") y = tf.constant(housing.target.reshape(-111),dtype=tf.float32,name='y') #theta理解為權(quán)重,random_uniform途中創(chuàng)建包含隨機(jī)值的節(jié)點(diǎn)即初始權(quán)重是隨機(jī)賦值的,理解為numpy的random函數(shù) theta = tf.Variable(tf.random_uniform([n+1, 1], -1, 1),name='theta') y_pred = tf.matmul(X,theta,name='prediction') error = y_pred - y mse = tf.reduce_mean(tf.square(error),name='mse') #采用的成本函數(shù)是mse即Mean Squared Error均方誤差#計(jì)算梯度公式,關(guān)鍵一步 # #T1、手動(dòng)求導(dǎo) # gradient = 2/m * tf.matmul(tf.transpose(X),error) # training_op = tf.assign(theta,theta - learning_rate * gradient) #assign將新值賦值給一個(gè)變量的節(jié)點(diǎn),即權(quán)重更新公式的迭代過(guò)程#T2、自動(dòng)求導(dǎo) optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate)#參數(shù)初始化,啟動(dòng)session,將graph放入session進(jìn)行每一步的更新 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(n_epoch): if epoch % 100 == 0: print ("Epoch",epoch, "MSE =", mse.eval()) # sess.run(training_op)print('best theta:',theta.eval())?
GitHub相關(guān)文章
DL:基于sklearn的加利福尼亞房?jī)r(jià),數(shù)據(jù)集較多時(shí)采用mini-batch方式訓(xùn)練會(huì)更快
TF保存模型:基于TF進(jìn)行模型的保存與恢復(fù)加載,調(diào)用Save()函數(shù)即可
?
?
?
總結(jié)
以上是生活随笔為你收集整理的DL:基于sklearn的加利福尼亚房价数据集实现GD算法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: TF之LoR:基于tensorflow利
- 下一篇: Dataset:数据集集合(综合性)——