用tensorflow实现弹性网络回归算法

作者:xckkcxxck 时间:2023-07-21 16:52:18 

本文实例为大家分享了tensorflow实现弹性网络回归算法,供大家参考,具体内容如下

python代码:


#用tensorflow实现弹性网络算法(多变量)
#使用鸢尾花数据集,后三个特征作为特征,用来预测第一个特征。

#1 导入必要的编程库,创建计算图,加载数据集
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn import datasets
from tensorflow.python.framework import ops

ops.get_default_graph()
sess = tf.Session()
iris = datasets.load_iris()

x_vals = np.array([[x[1], x[2], x[3]] for x in iris.data])
y_vals = np.array([y[0] for y in iris.data])

#2 声明学习率,批量大小,占位符和模型变量,模型输出
learning_rate = 0.001
batch_size = 50
x_data = tf.placeholder(shape=[None, 3], dtype=tf.float32) #占位符大小为3
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
A = tf.Variable(tf.random_normal(shape=[3,1]))
b = tf.Variable(tf.random_normal(shape=[1,1]))
model_output = tf.add(tf.matmul(x_data, A), b)

#3 对于弹性网络回归算法,损失函数包括L1正则和L2正则
elastic_param1 = tf.constant(1.)
elastic_param2 = tf.constant(1.)
l1_a_loss = tf.reduce_mean(abs(A))
l2_a_loss = tf.reduce_mean(tf.square(A))
e1_term = tf.multiply(elastic_param1, l1_a_loss)
e2_term = tf.multiply(elastic_param2, l2_a_loss)
loss = tf.expand_dims(tf.add(tf.add(tf.reduce_mean(tf.square(y_target - model_output)), e1_term), e2_term), 0)

#4 初始化变量, 声明优化器, 然后遍历迭代运行, 训练拟合得到参数
init = tf.global_variables_initializer()
sess.run(init)
my_opt = tf.train.GradientDescentOptimizer(learning_rate)
train_step = my_opt.minimize(loss)

loss_vec = []
for i in range(1000):
  rand_index = np.random.choice(len(x_vals), size=batch_size)
  rand_x = 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)
  if (i+1)%250 == 0:
    print('Step#' + str(i+1) +'A = ' + str(sess.run(A)) + 'b=' + str(sess.run(b)))
    print('Loss= ' +str(temp_loss))

#现在能观察到, 随着训练迭代后损失函数已收敛。
plt.plot(loss_vec, 'k--')
plt.title('Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('Loss')
plt.show()

本文参考书《Tensorflow机器学习实战指南》

来源:http://blog.csdn.net/xckkcxxck/article/details/78992345

标签:tensorflow,回归算法
0
投稿

猜你喜欢

  • python中pd.Series()函数的使用

    2023-10-04 08:28:05
  • SQL Server 2008数据挖掘查询任务

    2009-03-16 16:50:00
  • redis查看连接数及php模拟并发创建redis连接的方法

    2023-11-16 11:47:14
  • Python深度学习实战PyQt5菜单和工具栏功能作用

    2021-04-04 16:09:40
  • Python实现简单猜数字游戏

    2021-03-22 14:31:50
  • Go语言的变量定义详情

    2024-04-27 15:41:03
  • Python字符串和文件操作常用函数分析

    2023-07-25 08:42:23
  • pytorch中交叉熵损失(nn.CrossEntropyLoss())的计算过程详解

    2021-06-03 09:28:09
  • TensorFlow中权重的随机初始化的方法

    2023-01-02 06:11:32
  • python条件语句和while循环语句

    2023-08-31 06:17:56
  • python实战小游戏之考验记忆力

    2023-02-23 14:29:54
  • Python 批量合并多个txt文件的实例讲解

    2022-09-18 07:39:47
  • python 基本结构语句(函数和模块)

    2023-06-14 00:37:56
  • MySQL中登录与退出超全图文讲解

    2024-01-19 20:24:43
  • 在ASP中改善动态分页的性能

    2008-05-08 14:27:00
  • python代码过长的换行方法

    2022-12-25 07:19:59
  • Go语言Handler详细说明

    2024-04-27 15:32:50
  • python标准库OS模块详解

    2022-08-21 21:47:06
  • JS实现选项卡实例详解

    2024-04-19 10:43:37
  • Python 做曲线拟合和求积分的方法

    2021-03-03 01:46:07
  • asp之家 网络编程 m.aspxhome.com