python 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的線性回歸案例
#!/usr/bin/env python# -*- coding: utf-8 -*-# @File : 自實(shí)現(xiàn)一個(gè)線性回歸.py# @Author: 趙路倉# @Date : 2020/4/12# @Desc :# @Contact : [email protected] osimport tensorflow as tfdef linear_regression(): ''' 自實(shí)現(xiàn)一個(gè)線性回歸 :return: ''' # 命名空間 with tf.variable_scope('prepared_data'): # 準(zhǔn)備數(shù)據(jù) x = tf.random_normal(shape=[100, 1], name='Feature') y_true = tf.matmul(x, [[0.08]]) + 0.7 # x = tf.constant([[1.0], [2.0], [3.0]]) # y_true = tf.constant([[0.78], [0.86], [0.94]]) with tf.variable_scope('create_model'): # 2.構(gòu)造函數(shù) # 定義模型變量參數(shù) weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1], name='Weights')) bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1], name='Bias')) y_predit = tf.matmul(x, weights) + bias with tf.variable_scope('loss_function'): # 3.構(gòu)造損失函數(shù) error = tf.reduce_mean(tf.square(y_predit - y_true)) with tf.variable_scope('optimizer'): # 4.優(yōu)化損失 optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error) # 收集變量 tf.summary.scalar('error', error) tf.summary.histogram('weights', weights) tf.summary.histogram('bias', bias) # 合并變量 merged = tf.summary.merge_all() # 創(chuàng)建saver對(duì)象 saver = tf.train.Saver() # 顯式的初始化變量 init = tf.global_variables_initializer() # 開啟會(huì)話 with tf.Session() as sess: # 初始化變量 sess.run(init) # 創(chuàng)建事件文件 file_writer = tf.summary.FileWriter('E:/tmp/linear', graph=sess.graph) # print(x.eval()) # print(y_true.eval()) # 查看初始化變量模型參數(shù)之后的值 print('訓(xùn)練前模型參數(shù)為:權(quán)重%f,偏置%f' % (weights.eval(), bias.eval())) # 開始訓(xùn)練 for i in range(1000): sess.run(optimizer) print('第%d次參數(shù)為:權(quán)重%f,偏置%f,損失%f' % (i + 1, weights.eval(), bias.eval(), error.eval())) # 運(yùn)行合并變量操作 summary = sess.run(merged) # 將每次迭代后的變量寫入事件 file_writer.add_summary(summary, i) # 保存模型 if i == 999:saver.save(sess, './tmp/model/my_linear.ckpt') # # 加載模型 # if os.path.exists('./tmp/model/checkpoint'): # saver.restore(sess, './tmp/model/my_linear.ckpt') print('參數(shù)為:權(quán)重%f,偏置%f,損失%f' % (weights.eval(), bias.eval(), error.eval())) pre = [[0.5]] prediction = tf.matmul(pre, weights) + bias sess.run(prediction) print(prediction.eval()) return Noneif __name__ == '__main__': linear_regression()
以上就是python 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的線性回歸案例的詳細(xì)內(nèi)容,更多關(guān)于python 實(shí)現(xiàn)線性回歸的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. XHTML 1.0:標(biāo)記新的開端3. HTML5 Canvas繪制圖形從入門到精通4. XML解析錯(cuò)誤:未組織好 的解決辦法5. ASP基礎(chǔ)知識(shí)VBScript基本元素講解6. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. 利用CSS3新特性創(chuàng)建透明邊框三角9. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法10. XML入門的常見問題(四)
