用TensorFlow實(shí)現(xiàn)lasso回歸和嶺回歸算法的示例
也有些正則方法可以限制回歸算法輸出結(jié)果中系數(shù)的影響,其中最常用的兩種正則方法是lasso回歸和嶺回歸。
lasso回歸和嶺回歸算法跟常規(guī)線性回歸算法極其相似,有一點(diǎn)不同的是,在公式中增加正則項(xiàng)來(lái)限制斜率(或者凈斜率)。這樣做的主要原因是限制特征對(duì)因變量的影響,通過(guò)增加一個(gè)依賴(lài)斜率A的損失函數(shù)實(shí)現(xiàn)。
對(duì)于lasso回歸算法,在損失函數(shù)上增加一項(xiàng):斜率A的某個(gè)給定倍數(shù)。我們使用TensorFlow的邏輯操作,但沒(méi)有這些操作相關(guān)的梯度,而是使用階躍函數(shù)的連續(xù)估計(jì),也稱(chēng)作連續(xù)階躍函數(shù),其會(huì)在截止點(diǎn)跳躍擴(kuò)大。一會(huì)就可以看到如何使用lasso回歸算法。
對(duì)于嶺回歸算法,增加一個(gè)L2范數(shù),即斜率系數(shù)的L2正則。
# LASSO and Ridge Regression
# lasso回歸和嶺回歸
#
# This function shows how to use TensorFlow to solve LASSO or
# Ridge regression for
# y = Ax + b
#
# We will use the iris data, specifically:
# y = Sepal Length
# x = Petal Width
# import required libraries
import matplotlib.pyplot as plt
import sys
import numpy as np
import tensorflow as tf
from sklearn import datasets
from tensorflow.python.framework import ops
# Specify 'Ridge' or 'LASSO'
regression_type = 'LASSO'
# clear out old graph
ops.reset_default_graph()
# Create graph
sess = tf.Session()
###
# Load iris data
###
# iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)]
iris = datasets.load_iris()
x_vals = np.array([x[3] for x in iris.data])
y_vals = np.array([y[0] for y in iris.data])
###
# Model Parameters
###
# Declare batch size
batch_size = 50
# Initialize placeholders
x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
# make results reproducible
seed = 13
np.random.seed(seed)
tf.set_random_seed(seed)
# Create variables for linear regression
A = tf.Variable(tf.random_normal(shape=[1,1]))
b = tf.Variable(tf.random_normal(shape=[1,1]))
# Declare model operations
model_output = tf.add(tf.matmul(x_data, A), b)
###
# Loss Functions
###
# Select appropriate loss function based on regression type
if regression_type == 'LASSO':
# Declare Lasso loss function
# 增加損失函數(shù),其為改良過(guò)的連續(xù)階躍函數(shù),lasso回歸的截止點(diǎn)設(shè)為0.9。
# 這意味著限制斜率系數(shù)不超過(guò)0.9
# Lasso Loss = L2_Loss + heavyside_step,
# Where heavyside_step ~ 0 if A < constant, otherwise ~ 99
lasso_param = tf.constant(0.9)
heavyside_step = tf.truediv(1., tf.add(1., tf.exp(tf.multiply(-50., tf.subtract(A, lasso_param)))))
regularization_param = tf.multiply(heavyside_step, 99.)
loss = tf.add(tf.reduce_mean(tf.square(y_target - model_output)), regularization_param)
elif regression_type == 'Ridge':
# Declare the Ridge loss function
# Ridge loss = L2_loss + L2 norm of slope
ridge_param = tf.constant(1.)
ridge_loss = tf.reduce_mean(tf.square(A))
loss = tf.expand_dims(tf.add(tf.reduce_mean(tf.square(y_target - model_output)), tf.multiply(ridge_param, ridge_loss)), 0)
else:
print('Invalid regression_type parameter value',file=sys.stderr)
###
# Optimizer
###
# Declare optimizer
my_opt = tf.train.GradientDescentOptimizer(0.001)
train_step = my_opt.minimize(loss)
###
# Run regression
###
# Initialize variables
init = tf.global_variables_initializer()
sess.run(init)
# Training loop
loss_vec = []
for i in range(1500):
rand_index = np.random.choice(len(x_vals), size=batch_size)
rand_x = np.transpose([x_vals[rand_index]])
rand_y = np.transpose([y_vals[rand_index]])
sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
loss_vec.append(temp_loss[0])
if (i+1)%300==0:
print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b)))
print('Loss = ' + str(temp_loss))
print('\n')
###
# Extract regression results
###
# Get the optimal coefficients
[slope] = sess.run(A)
[y_intercept] = sess.run(b)
# Get best fit line
best_fit = []
for i in x_vals:
best_fit.append(slope*i+y_intercept)
###
# Plot results
###
# Plot regression line against data points
plt.plot(x_vals, y_vals, 'o', label='Data Points')
plt.plot(x_vals, best_fit, 'r-', label='Best fit line', linewidth=3)
plt.legend(loc='upper left')
plt.title('Sepal Length vs Pedal Width')
plt.xlabel('Pedal Width')
plt.ylabel('Sepal Length')
plt.show()
# Plot loss over time
plt.plot(loss_vec, 'k-')
plt.title(regression_type + ' Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('Loss')
plt.show()
輸出結(jié)果:
Step #300 A = [[ 0.77170753]] b = [[ 1.82499862]]
Loss = [[ 10.26473045]]
Step #600 A = [[ 0.75908542]] b = [[ 3.2220633]]
Loss = [[ 3.06292033]]
Step #900 A = [[ 0.74843585]] b = [[ 3.9975822]]
Loss = [[ 1.23220456]]
Step #1200 A = [[ 0.73752165]] b = [[ 4.42974091]]
Loss = [[ 0.57872057]]
Step #1500 A = [[ 0.72942668]] b = [[ 4.67253113]]
Loss = [[ 0.40874988]]

通過(guò)在標(biāo)準(zhǔn)線性回歸估計(jì)的基礎(chǔ)上,增加一個(gè)連續(xù)的階躍函數(shù),實(shí)現(xiàn)lasso回歸算法。由于階躍函數(shù)的坡度,我們需要注意步長(zhǎng),因?yàn)樘蟮牟介L(zhǎng)會(huì)導(dǎo)致最終不收斂。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- tensorflow實(shí)現(xiàn)簡(jiǎn)單邏輯回歸
- Tensorflow使用支持向量機(jī)擬合線性回歸
- TensorFlow實(shí)現(xiàn)iris數(shù)據(jù)集線性回歸
- 用TensorFlow實(shí)現(xiàn)戴明回歸算法的示例
- 詳解用TensorFlow實(shí)現(xiàn)邏輯回歸算法
- TensorFlow實(shí)現(xiàn)Softmax回歸模型
- 運(yùn)用TensorFlow進(jìn)行簡(jiǎn)單實(shí)現(xiàn)線性回歸、梯度下降示例
- 用tensorflow構(gòu)建線性回歸模型的示例代碼
- 用tensorflow實(shí)現(xiàn)彈性網(wǎng)絡(luò)回歸算法
- TensorFlow實(shí)現(xiàn)Logistic回歸
相關(guān)文章
python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式
這篇文章主要介紹了python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Python繪制loss曲線和準(zhǔn)確率曲線實(shí)例代碼
pytorch雖然使用起來(lái)很方便,但在一點(diǎn)上并沒(méi)有tensorflow方便,就是繪制模型訓(xùn)練時(shí)在訓(xùn)練集和驗(yàn)證集上的loss和accuracy曲線(共四條),下面這篇文章主要給大家介紹了關(guān)于Python繪制loss曲線和準(zhǔn)確率曲線的相關(guān)資料,需要的朋友可以參考下2022-08-08
Python爬蟲(chóng)實(shí)現(xiàn)獲取動(dòng)態(tài)gif格式搞笑圖片的方法示例
這篇文章主要介紹了Python爬蟲(chóng)實(shí)現(xiàn)獲取動(dòng)態(tài)gif格式搞笑圖片的方法,結(jié)合實(shí)例形式分析了Python針對(duì)gif格式圖片的爬取、下載等相關(guān)操作技巧,需要的朋友可以參考下2018-12-12
python3 將階乘改成函數(shù)形式進(jìn)行調(diào)用的操作
這篇文章主要介紹了python3 將階乘改成函數(shù)形式進(jìn)行調(diào)用的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03
使用Python編寫(xiě)一個(gè)簡(jiǎn)單的tic-tac-toe游戲的教程
這篇文章主要介紹了使用Python編寫(xiě)一個(gè)簡(jiǎn)單的tic-tac-toe游戲的教程,有利于Python初學(xué)者進(jìn)行上手實(shí)踐,需要的朋友可以參考下2015-04-04
Python遇到“No?module?named?cv2“錯(cuò)誤的詳細(xì)解決方法
這篇文章主要介紹了Python遇到“No?module?named?cv2“錯(cuò)誤的詳細(xì)解決方法,這個(gè)問(wèn)題通常是因?yàn)槲凑_安裝OpenCV,解決方法包括安裝opencv-python包、驗(yàn)證安裝、處理操作系統(tǒng)依賴(lài)問(wèn)題,需要的朋友可以參考下2025-04-04
使用Python實(shí)現(xiàn)一鍵往Word文檔的表格中填寫(xiě)數(shù)據(jù)
在工作中,我們經(jīng)常遇到將Excel表中的部分信息填寫(xiě)到Word文檔的對(duì)應(yīng)表格中,以生成報(bào)告,方便打印,所以本文小編就給大家介紹了如何使用Python實(shí)現(xiàn)一鍵往Word文檔的表格中填寫(xiě)數(shù)據(jù),文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2023-12-12
python Pandas高級(jí)功能之?dāng)?shù)據(jù)透視表和字符串操作
Pandas是Python中用于數(shù)據(jù)處理和分析的強(qiáng)大庫(kù),這篇文章將深入探討Pandas庫(kù)的高級(jí)功能:數(shù)據(jù)透視表和字符串操作,需要的朋友可以參考下2023-07-07

