用用TensorFlow实现实现lasso回归和岭回归算法的示例回归和岭回归算法的示例
本篇文章主要介绍了用TensorFlow实现lasso回归和岭回归算法的示例,小编觉得挺不错的,现在分享给大家,
也给大家做个参考。一起跟随小编过来看看吧
也有些正则方法可以限制回归算法输出结果中系数的影响,其中最常用的两种正则方法是lasso回归和岭回归。
lasso回归和岭回归算法跟常规线性回归算法极其相似,有一点不同的是,在公式中增加正则项来限制斜率(或者净斜率)。
这样做的主要原因是限制特征对因变量的影响,通过增加一个依赖斜率A的损失函数实现。
对于lasso回归算法,在损失函数上增加一项:斜率A的某个给定倍数。我们使用TensorFlow的逻辑操作,但没有这些操作相
关的梯度,而是使用阶跃函数的连续估计,也称作连续阶跃函数,其会在截止点跳跃扩大。一会就可以看到如何使用lasso回
归算法。
对于岭回归算法,增加一个L2范数,即斜率系数的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)