您好,登錄后才能下訂單哦!
也有些正則方法可以限制回歸算法輸出結(jié)果中系數(shù)的影響,其中最常用的兩種正則方法是lasso回歸和嶺回歸。
lasso回歸和嶺回歸算法跟常規(guī)線性回歸算法極其相似,有一點(diǎn)不同的是,在公式中增加正則項(xiàng)來(lái)限制斜率(或者凈斜率)。這樣做的主要原因是限制特征對(duì)因變量的影響,通過(guò)增加一個(gè)依賴斜率A的損失函數(shù)實(shí)現(xiàn)。
對(duì)于lasso回歸算法,在損失函數(shù)上增加一項(xiàng):斜率A的某個(gè)給定倍數(shù)。我們使用TensorFlow的邏輯操作,但沒(méi)有這些操作相關(guān)的梯度,而是使用階躍函數(shù)的連續(xù)估計(jì),也稱作連續(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í)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。