1. 程式人生 > 程式設計 >python 實現一個簡單的線性迴歸案例

python 實現一個簡單的線性迴歸案例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : 自實現一個線性迴歸.py
# @Author: 趙路倉
# @Date : 2020/4/12
# @Desc :
# @Contact : [email protected]
import os

import tensorflow as tf


def linear_regression():
  """
  自實現一個線性迴歸
  :return:
  """
  # 名稱空間
  with tf.variable_scope("prepared_data"):
    # 準備資料
    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.建構函式
    # 定義模型變數引數
    weights = tf.Variable(initial_value=tf.random_normal(shape=[1,name="Weights"))
    bias = tf.Variable(initial_value=tf.random_normal(shape=[1,name="Bias"))
    y_predit = tf.matmul(x,weights) + bias

  with tf.variable_scope("loss_function"):
    # 3.構造損失函式
    error = tf.reduce_mean(tf.square(y_predit - y_true))

  with tf.variable_scope("optimizer"):
    # 4.優化損失
    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()

  # 建立saver物件
  saver = tf.train.Saver()

  # 顯式的初始化變數
  init = tf.global_variables_initializer()

  # 開啟會話
  with tf.Session() as sess:
    # 初始化變數
    sess.run(init)

    # 建立事件檔案
    file_writer = tf.summary.FileWriter("E:/tmp/linear",graph=sess.graph)

    # print(x.eval())
    # print(y_true.eval())
    # 檢視初始化變數模型引數之後的值
    print("訓練前模型引數為:權重%f,偏置%f" % (weights.eval(),bias.eval()))

    # 開始訓練
    for i in range(1000):
      sess.run(optimizer)
      print("第%d次引數為:權重%f,偏置%f,損失%f" % (i + 1,weights.eval(),bias.eval(),error.eval()))

      # 執行合併變數操作
      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("引數為:權重%f,損失%f" % (weights.eval(),error.eval()))
    pre = [[0.5]]
    prediction = tf.matmul(pre,weights) + bias
    sess.run(prediction)
    print(prediction.eval())

  return None


if __name__ == "__main__":
  linear_regression()

以上就是python 實現一個簡單的線性迴歸案例的詳細內容,更多關於python 實現線性迴歸的資料請關注我們其它相關文章!