[深度學習]python深度學習 實現一個簡單的線性回歸案例


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 自實現一個線性回歸.py
# @Author: 趙路倉
# @Date  : 2020/4/12
# @Desc  :
# @Contact : 398333404@qq.com
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, 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.構造損失函數
        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,損失%f" % (weights.eval(), bias.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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM