TensorFlow實(shí)現(xiàn)簡(jiǎn)單線性回歸
本文實(shí)例為大家分享了TensorFlow實(shí)現(xiàn)簡(jiǎn)單線性回歸的具體代碼,供大家參考,具體內(nèi)容如下
簡(jiǎn)單的一元線性回歸
一元線性回歸公式:

其中x是特征:[x1,x2,x3,…,xn,]T
w是權(quán)重,b是偏置值
代碼實(shí)現(xiàn)
導(dǎo)入必須的包
import tensorflow as tf import matplotlib.pyplot as plt import numpy as np import os # 屏蔽warning以下的日志信息 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
產(chǎn)生模擬數(shù)據(jù)
def generate_data(): ? ? x = tf.constant(np.array([i for i in range(0, 100, 5)]).reshape(-1, 1), tf.float32) ? ? y = tf.add(tf.matmul(x, [[1.3]]) + 1, tf.random_normal([20, 1], stddev=30)) ? ? return x, y
x是100行1列的數(shù)據(jù),tf.matmul是矩陣相乘,所以權(quán)值設(shè)置成二維的。
設(shè)置的w是1.3, b是1
實(shí)現(xiàn)回歸
def myregression():
? ? """
? ? 自實(shí)現(xiàn)線性回歸
? ? :return:
? ? """
? ? x, y = generate_data()
? ? # ? ? 建立模型 ?y = x * w + b
? ? # w 1x1的二維數(shù)據(jù)
? ? w = tf.Variable(tf.random_normal([1, 1], mean=0.0, stddev=1.0), name='weight_a')
? ? b = tf.Variable(0.0, name='bias_b')
? ? y_predict = tf.matmul(x, a) + b
? ? # 建立損失函數(shù)
? ? loss = tf.reduce_mean(tf.square(y_predict - y))
? ??
? ? # 訓(xùn)練
? ? train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss=loss)
? ? # 初始化全局變量
? ? init_op = tf.global_variables_initializer()
??
? ? with tf.Session() as sess:
? ? ? ? sess.run(init_op)
? ? ? ? print('初始的權(quán)重:%f偏置值:%f' % (a.eval(), b.eval()))
? ??
? ? ? ? # 訓(xùn)練優(yōu)化
? ? ? ? for i in range(1, 100):
? ? ? ? ? ? sess.run(train_op)
? ? ? ? ? ? print('第%d次優(yōu)化的權(quán)重:%f偏置值:%f' % (i, a.eval(), b.eval()))
? ? ? ? # 顯示回歸效果
? ? ? ? show_img(x.eval(), y.eval(), y_predict.eval())使用matplotlib查看回歸效果
def show_img(x, y, y_pre): ? ? plt.scatter(x, y) ? ? plt.plot(x, y_pre) ? ? plt.show()
完整代碼
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def generate_data():
? ? x = tf.constant(np.array([i for i in range(0, 100, 5)]).reshape(-1, 1), tf.float32)
? ? y = tf.add(tf.matmul(x, [[1.3]]) + 1, tf.random_normal([20, 1], stddev=30))
? ? return x, y
def myregression():
? ? """
? ? 自實(shí)現(xiàn)線性回歸
? ? :return:
? ? """
? ? x, y = generate_data()
? ? # 建立模型 ?y = x * w + b
? ? w = tf.Variable(tf.random_normal([1, 1], mean=0.0, stddev=1.0), name='weight_a')
? ? b = tf.Variable(0.0, name='bias_b')
? ? y_predict = tf.matmul(x, w) + b
? ? # 建立損失函數(shù)
? ? loss = tf.reduce_mean(tf.square(y_predict - y))
? ? # 訓(xùn)練
? ? train_op = tf.train.GradientDescentOptimizer(0.0001).minimize(loss=loss)
? ? init_op = tf.global_variables_initializer()
? ? with tf.Session() as sess:
? ? ? ? sess.run(init_op)
? ? ? ? print('初始的權(quán)重:%f偏置值:%f' % (w.eval(), b.eval()))
? ? ? ? # 訓(xùn)練優(yōu)化
? ? ? ? for i in range(1, 35000):
? ? ? ? ? ? sess.run(train_op)
? ? ? ? ? ? print('第%d次優(yōu)化的權(quán)重:%f偏置值:%f' % (i, w.eval(), b.eval()))
? ? ? ? show_img(x.eval(), y.eval(), y_predict.eval())
def show_img(x, y, y_pre):
? ? plt.scatter(x, y)
? ? plt.plot(x, y_pre)
? ? plt.show()
if __name__ == '__main__':
? ? myregression()看看訓(xùn)練的結(jié)果(因?yàn)閿?shù)據(jù)是隨機(jī)產(chǎn)生的,每次的訓(xùn)練結(jié)果都會(huì)不同,可適當(dāng)調(diào)節(jié)梯度下降的學(xué)習(xí)率和訓(xùn)練步數(shù))

35000次的訓(xùn)練結(jié)果

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python如何快速實(shí)現(xiàn)分布式任務(wù)
這篇文章主要介紹了Python如何快速實(shí)現(xiàn)分布式任務(wù),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
python實(shí)現(xiàn)字典(dict)和字符串(string)的相互轉(zhuǎn)換方法
這篇文章主要介紹了python實(shí)現(xiàn)字典(dict)和字符串(string)的相互轉(zhuǎn)換方法,涉及Python字典dict的遍歷與字符串轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下2017-03-03
關(guān)于numpy.concatenate()函數(shù)的使用及說明
這篇文章主要介紹了關(guān)于numpy.concatenate()函數(shù)的使用及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Python可視化Matplotlib散點(diǎn)圖scatter()用法詳解
這篇文章主要介紹了Python可視化中Matplotlib散點(diǎn)圖scatter()的用法詳解,文中附含詳細(xì)示例代碼,有需要得朋友可以借鑒參考下,希望能夠有所幫助2021-09-09
Python?web實(shí)戰(zhàn)教程之Django文件上傳和處理詳解
Django和Flask都是Python的Web框架,用于開發(fā)Web應(yīng)用程序,這篇文章主要給大家介紹了關(guān)于Python?web實(shí)戰(zhàn)教程之Django文件上傳和處理的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12

