zoukankan      html  css  js  c++  java
  • 4.线性回归

    import tensorflow as tf
    import numpy as np
    import matplotlib.pyplot as plt
    x_data = np.random.rand(100)
    noise = np.random.normal(0,0.01,x_data.shape)
    y_data = x_data*0.1 + 0.2 + noise
    
    plt.scatter(x_data, y_data)
    plt.show()

    # 构建一个线性模型
    d = tf.Variable(np.random.rand(1))
    k = tf.Variable(np.random.rand(1))
    y = k*x_data + d
    
    # 二次代价函数
    loss = tf.losses.mean_squared_error(y_data, y)
    # 定义一个梯度下降法优化器
    optimizer = tf.train.GradientDescentOptimizer(0.3)
    # 最小化代价函数
    train = optimizer.minimize(loss)
    
    # 初始化变量
    init= tf.global_variables_initializer()
    
    with tf.Session() as sess:
        sess.run(init)
        for i in range(201):
            sess.run(train)
            if i%20==0:
                print(i,sess.run([k,d]))
        y_pred = sess.run(y)
        plt.scatter(x_data,y_data)
        plt.plot(x_data,y_pred,'r-',lw=3)
        plt.show()
    0 [array([0.42558686]), array([0.07772181])]
    20 [array([0.24686251]), array([0.1212207])]
    40 [array([0.17103131]), array([0.16282419])]
    60 [array([0.13410329]), array([0.18308412])]
    80 [array([0.1161202]), array([0.19295024])]
    100 [array([0.10736286]), array([0.1977548])]
    120 [array([0.10309823]), array([0.20009452])]
    140 [array([0.10102146]), array([0.2012339])]
    160 [array([0.10001012]), array([0.20178875])]
    180 [array([0.09951763]), array([0.20205895])]
    200 [array([0.09927779]), array([0.20219054])]

    
    
  • 相关阅读:
    python 数据类型 基础第二天
    Python基础第一篇
    前言、入门程序、常量、变量
    win10打开移动热点让手机连接上网教程
    win10移动热点问题
    博客园快速美化
    Idea提示没有符号类错误解决
    mybatis复习01
    test
    d190305面试题01总结
  • 原文地址:https://www.cnblogs.com/liuwenhua/p/11605338.html
Copyright © 2011-2022 走看看