使用tensorflow的线性回归的例子(七)

L1 与L2损失

这个脚本展示如何用TensorFlow求解线性回归。

在算法的收敛性中,理解损失函数的影响是很重要的。这里我们展示L1和L2损失函数是如何影响线性回归的收敛性的。我们使用iris数据集,但是我们将改变损失函数和学习速率来看收敛性的改变。

import matplotlib.pyplot as plt

import numpy as np

import tensorflow as tf

from sklearn import datasets

from tensorflow.python.framework import ops

ops.reset_default_graph()

L1-Loss

这里我们展示使用L1-损失的线性回归。后面展示L2-损失的线性回归。

线性最少二乘的L1损失函数为

其中 N 是数据点数, yi 第i个实际的y值, ^yi^ 是第i个y值的预测值。

我们加载iris数据。

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])

我们定义模型,损失函数,变量的梯度。

def model(x,w,b):

Declare model operations

model_output = tf.add(tf.matmul(x, w), b)

return model_output

def loss1(x, y,w,b):

Declare loss functions

loss_l1 = tf.reduce_mean(tf.abs(y - model(x,w,b)))

Declare loss functions

#loss_l2 = tf.reduce_mean(tf.square(y_target - model_output))

return loss_l1

def grad1(x,y,w,b):

with tf.GradientTape() as tape:

loss_1 = loss1(x,y,w,b)

return tape.gradient(loss_1,[w,b])

设置模型参数。要注意的一个重要参数是学习速率。如果学习速率太大,模型不收敛。如果学习速率太小,模型收敛太慢。这里有两个学习速率来展示收敛与不收敛。收敛的学习速小于0.35。要说明收敛,设置学习速率大于等于0.4。

batch_size = 25

learning_rate = 0.4 # Will not converge with learning rate at 0.4

iterations = 50

我们要初始化变量。

Create variables for linear regression

w1 = tf.Variable(tf.random.normal(shape=[1,1]),tf.float32)

b1 = tf.Variable(tf.random.normal(shape=[1,1]),tf.float32)

我们要告诉模型使用的优化器。

optimizer = tf.optimizers.Adam(learning_rate)

我们进行模型训练。

Training loop

loss_vec_l1=[]

loss_vec_l2=[]

for i in range(5000):

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]])

x=tf.cast(rand_x,tf.float32)

y=tf.cast(rand_y,tf.float32)

grads1=grad1(x,y,w1,b1)

optimizer.apply_gradients(zip(grads1,[w1,b1]))

#sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})

temp_loss1 = loss1(x, y,w1,b1).numpy()

#sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})

loss_vec_l1.append(temp_loss1)

if (i+1)%25==0:

print('Step #' + str(i+1) + ' A = ' + str(w1.numpy()) + ' b = ' + str(b1.numpy()))

print('Loss = ' + str(temp_loss1))

我们得到回归系数和拟合线。

Get the optimal coefficients

slope\] = w1.numpy() \[y_intercept\] = b1.numpy() # Get best fit line best_fit1 = \[

for i in x_vals:

best_fit1.append(slope*i+y_intercept)

我们绘制拟合线。

Plot the result

plt.plot(x_vals, y_vals, 'o', label='Data Points')

plt.plot(x_vals, best_fit1, 'r-', label='Best fit line', linewidth=3)

plt.legend(loc='upper left')

plt.title('Sepal Length vs Petal Width')

plt.xlabel('Petal Width')

plt.ylabel('Sepal Length')

plt.show()

Plot loss over time

plt.plot(loss_vec_l1, 'k-')

plt.title('L1 Loss per Generation')

plt.xlabel('Generation')

plt.ylabel('L1 Loss')

plt.show()

相关推荐
亚马逊云开发者5 分钟前
GenDev 智能开发:Amazon Q Developer CLI 赋能Amazon Code Family实现代码审核
人工智能
weixin_3776348412 分钟前
【强化学习】RLMT强制 CoT提升训练效果
人工智能·算法·机器学习
Francek Chen20 分钟前
【深度学习计算机视觉】14:实战Kaggle比赛:狗的品种识别(ImageNet Dogs)
人工智能·pytorch·深度学习·计算机视觉·kaggle·imagenet dogs
dxnb2224 分钟前
Datawhale25年10月组队学习:math for AI+Task3线性代数(下)
人工智能·学习·线性代数
渡我白衣40 分钟前
《未来的 AI 操作系统(四)——AgentOS 的内核设计:调度、记忆与自我反思机制》
人工智能·深度学习·机器学习·语言模型·数据挖掘·人机交互·语音识别
飞哥数智坊1 小时前
Claude Skills 实测体验:不用翻墙,GLM-4.6 也能玩转
人工智能·claude·chatglm (智谱)
FreeBuf_1 小时前
微软数字防御报告:AI成为新型威胁,自动化漏洞利用技术颠覆传统
人工智能·microsoft·自动化
IT_陈寒1 小时前
Vue3性能优化实战:这7个技巧让我的应用加载速度提升50%!
前端·人工智能·后端
GIS数据转换器1 小时前
带高度多边形,生成3D建筑模型,支持多种颜色或纹理的OBJ、GLTF、3DTiles格式
数据库·人工智能·机器学习·3d·重构·无人机
茜茜西西CeCe1 小时前
数字图像处理-图像编码与压缩
人工智能·计算机视觉·matlab·数字图像处理·图像压缩·图像编码