TensorFlow實現(xiàn)iris數(shù)據(jù)集線性回歸
本文將遍歷批量數(shù)據(jù)點并讓TensorFlow更新斜率和y截距。這次將使用Scikit Learn的內(nèi)建iris數(shù)據(jù)集。特別地,我們將用數(shù)據(jù)點(x值代表花瓣寬度,y值代表花瓣長度)找到最優(yōu)直線。選擇這兩種特征是因為它們具有線性關(guān)系,在后續(xù)結(jié)果中將會看到。本文將使用L2正則損失函數(shù)。
# 用TensorFlow實現(xiàn)線性回歸算法
#----------------------------------
#
# 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損失函數(shù),其為批量損失的平均值。
loss = tf.reduce_mean(tf.square(y_target - model_output))
# 聲明優(yōu)化器 學(xué)習(xí)率設(shè)為0.05
my_opt = tf.train.GradientDescentOptimizer(0.05)
train_step = my_opt.minimize(loss)
# 初始化變量
init = tf.global_variables_initializer()
sess.run(init)
# 批量訓(xùn)練遍歷迭代
# 迭代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))
# 抽取系數(shù)
[slope] = sess.run(A)
[y_intercept] = sess.run(b)
# 創(chuàng)建最佳擬合直線
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正則損失函數(shù)
plt.plot(loss_vec, 'k-')
plt.title('L2 Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('L2 Loss')
plt.show()
結(jié)果:
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


以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- TensorFlow神經(jīng)網(wǎng)絡(luò)構(gòu)造線性回歸模型示例教程
- 詳解TensorFlow2實現(xiàn)線性回歸
- tensorflow基本操作小白快速構(gòu)建線性回歸和分類模型
- Tensorflow實現(xiàn)神經(jīng)網(wǎng)絡(luò)擬合線性回歸
- 使用TensorFlow實現(xiàn)簡單線性回歸模型
- 使用tensorflow實現(xiàn)線性回歸
- Tensorflow使用支持向量機(jī)擬合線性回歸
- 運用TensorFlow進(jìn)行簡單實現(xiàn)線性回歸、梯度下降示例
- 用tensorflow構(gòu)建線性回歸模型的示例代碼
- TensorFlow實現(xiàn)簡單線性回歸
相關(guān)文章
使用python將mysql數(shù)據(jù)庫的數(shù)據(jù)轉(zhuǎn)換為json數(shù)據(jù)的方法
這篇文章主要介紹了使用python將mysql數(shù)據(jù)庫的數(shù)據(jù)轉(zhuǎn)換為json數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Python Django 頁面上展示固定的頁碼數(shù)實現(xiàn)代碼
這篇文章主要介紹了Python Django 頁面上展示固定的頁碼數(shù)實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08

