欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

TensorFlow实现iris数据集线性回归

程序员文章站 2022-05-18 22:22:11
本文将遍历批量数据点并让tensorflow更新斜率和y截距。这次将使用scikit learn的内建iris数据集。特别地,我们将用数据点(x值代表花瓣宽度,y值代表花瓣...

本文将遍历批量数据点并让tensorflow更新斜率和y截距。这次将使用scikit learn的内建iris数据集。特别地,我们将用数据点(x值代表花瓣宽度,y值代表花瓣长度)找到最优直线。选择这两种特征是因为它们具有线性关系,在后续结果中将会看到。本文将使用l2正则损失函数。

# 用tensorflow实现线性回归算法
#----------------------------------
#
# this function shows how to use tensorflow to
# solve linear regression.
# y = ax + b
#
# we will use the iris data, specifically:
# y = sepal length
# x = petal width

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

# create graph
sess = tf.session()

# load the 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])

# 批量大小
batch_size = 25

# initialize 占位符
x_data = tf.placeholder(shape=[none, 1], dtype=tf.float32)
y_target = tf.placeholder(shape=[none, 1], dtype=tf.float32)

# 模型变量
a = tf.variable(tf.random_normal(shape=[1,1]))
b = tf.variable(tf.random_normal(shape=[1,1]))

# 增加线性模型,y=ax+b
model_output = tf.add(tf.matmul(x_data, a), b)

# 声明l2损失函数,其为批量损失的平均值。
loss = tf.reduce_mean(tf.square(y_target - model_output))

# 声明优化器 学习率设为0.05
my_opt = tf.train.gradientdescentoptimizer(0.05)
train_step = my_opt.minimize(loss)

# 初始化变量
init = tf.global_variables_initializer()
sess.run(init)

# 批量训练遍历迭代
# 迭代100次,每25次迭代输出变量值和损失值
loss_vec = []
for i in range(100):
  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)
  if (i+1)%25==0:
    print('step #' + str(i+1) + ' a = ' + str(sess.run(a)) + ' b = ' + str(sess.run(b)))
    print('loss = ' + str(temp_loss))

# 抽取系数
[slope] = sess.run(a)
[y_intercept] = sess.run(b)

# 创建最佳拟合直线
best_fit = []
for i in x_vals:
 best_fit.append(slope*i+y_intercept)

# 绘制两幅图
# 拟合的直线
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
# 迭代100次的l2正则损失函数
plt.plot(loss_vec, 'k-')
plt.title('l2 loss per generation')
plt.xlabel('generation')
plt.ylabel('l2 loss')
plt.show()

结果:

step #25 a = [[ 1.93474162]] b = [[ 3.11190438]]
loss = 1.21364
step #50 a = [[ 1.48641717]] b = [[ 3.81004381]]
loss = 0.945256
step #75 a = [[ 1.26089203]] b = [[ 4.221035]]
loss = 0.254756
step #100 a = [[ 1.1693294]] b = [[ 4.47258472]]
loss = 0.281654

TensorFlow实现iris数据集线性回归

TensorFlow实现iris数据集线性回归

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。