当前位置: 首页 > news >正文

使用tensorflow的线性回归的例子(二)

#List3-30

拟合y=2x

%matplotlib inline

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

x_train = np.linspace(-1, 1, 101)

y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33

plt.scatter(x_train, y_train)

w = tf.Variable(np.random.randn(),tf.float32)

b = tf.Variable(np.random.randn(),tf.float32)

#设置迭代次数和学习率

learning_rate = 0.01

training_epochs = 100

loss = []

count = 0

display_count = 10 #控制显示粒度的参数,每训练10个样本输出一次损失值

#定义模型函数

def model(x,w,b):

    return tf.multiply(x,w)+b

def loss_fun(x,y,w,b):

    err = model(x,w,b)-y

    squared_err = tf.square(err)

    return tf.reduce_mean(squared_err)

def grad(x,y,w,b):

    with tf.GradientTape() as tape:

        loss_ = loss_fun(x,y,w,b)

    return tape.gradient(loss_,[w,b])

#optimizer= tf.keras.optimizers.Adam(learning_rate=0.01)

for epoch in range(training_epochs):

    for (x, y) in zip(x_train, y_train):

        loss_ =loss_fun(x,y,w,b)

        loss.append(loss_)

        #计算当前[w,b]的梯度

        delta_w,delta_b = grad(x,y,w,b)

        change_w = delta_w * learning_rate

        change_b = delta_b * learning_rate

        w.assign_sub(change_w)

        b.assign_sub(change_b)

        #训练步数加1

        count = count +1

        if count % display_count == 0:

            print('train epoch : ','%02d'%(epoch+1),'step:%03d' % (count),'loss= ','{:.9f}'.format(loss_))

plt.scatter(x_train, y_train)

y_learned = x_train*w.numpy()+b.numpy()

plt.plot(x_train, y_learned, 'r')

plt.show()

         

http://www.dtcms.com/a/263745.html

相关文章:

  • 数字雨动画背景
  • TensorFlow源码深度阅读指南
  • 工作中常用的Git操作命令(一)
  • 深度解析服务级别协议(SLA):保障业务稳定性的关键承诺
  • RabbitMQ简单消息发送
  • Reactor Hot Versus Cold
  • 比Axure更简单?墨刀高保真原型交互“监听变量”使用教程
  • 基于中国印尼会计准则差异,中国企业在印尼推广ERP(SAP、Oracle)系统需要注意的细节
  • 应用场景全解析:飞算 JavaAI 的实战舞台
  • python+uniapp基于微信小程序的适老化背景下老年人康养知识线上学习系统nodejs+java
  • C++ 11 中 condition_variable 的探索与实践
  • 解锁阿里云日志服务SLS:云时代的日志管理利器
  • 【AI 时代的网络爬虫新形态与防护思路研究】
  • iOS 越狱插件 主动调用C函数和OC函数
  • DBA 命令全面指南:核心操作、语法与最佳实践
  • 【仿muduo库实现并发服务器】Channel模块
  • 大规模分布式数据库读写分离架构:一致性、可用性与性能的权衡实践
  • opencv使用 GStreamer 硬解码和 CUDA 加速的方案
  • Java ArrayList 扩容机制
  • 【MobaXterm、Vim】使用合集1
  • 结构体实战:用Rust编写矩形面积计算器
  • Electron 沙箱模式深度解析:构建更安全的桌面应用
  • Let‘s Encrypt 免费证书使用
  • 2022/7 N2 jlpt词汇
  • STM32作为主机识别鼠标键盘
  • Vue-16-前端框架Vue之应用基础集中式状态管理pinia(一)
  • SeaTunnel 社区月报(5-6 月):全新功能上线、Bug 大扫除、Merge 之星是谁?
  • 从零到一搭建远程图像生成系统:Stable Diffusion 3.5+内网穿透技术深度实战
  • 密码学(斯坦福)
  • 数字图像处理学习笔记