30天干掉tensorflow2.0-day09 中阶API示范

中阶API示范

下面的范例使用TensorFlow的中阶API实现线性回归模型。

TensorFlow的中阶API主要包括各种模型层,损失函数,优化器,数据管道,特征列等等。

import tensorflow as tf
from tensorflow.keras import layers,losses,metrics,optimizers


#打印时间分割线
@tf.function
def printbar():
    ts = tf.timestamp()
    today_ts = ts%(24*60*60)

    hour = tf.cast(today_ts//3600+8,tf.int32)%tf.constant(24)
    minite = tf.cast((today_ts%3600)//60,tf.int32)
    second = tf.cast(tf.floor(today_ts%60),tf.int32)
    
    def timeformat(m):
        if tf.strings.length(tf.strings.format("{}",m))==1:
            return(tf.strings.format("0{}",m))
        else:
            return(tf.strings.format("{}",m))
    
    timestring = tf.strings.join([timeformat(hour),timeformat(minite),
                timeformat(second)],separator = ":")
    tf.print("=========="*8,end = "")
    tf.print(timestring)
#样本数量
n = 800

# 生成测试用数据集
X = tf.random.uniform([n,2],minval=-10,maxval=10) 
w0 = tf.constant([[2.0],[-1.0]])
b0 = tf.constant(3.0)
Y = X@w0 + b0 + tf.random.normal([n,1],mean = 0.0,stddev= 2.0)  # @表示矩阵乘法,增加正态扰动

#构建输入数据管道
ds = tf.data.Dataset.from_tensor_slices((X,Y)) \
     .shuffle(buffer_size = 1000).batch(100) \
     .prefetch(tf.data.experimental.AUTOTUNE)  

#定义优化器
optimizer = optimizers.SGD(learning_rate=0.001)
linear = layers.Dense(units = 1)
linear.build(input_shape = (2,)) 

@tf.function
def train(epoches):
    for epoch in tf.range(1,epoches+1):
        L = tf.constant(0.0) #使用L记录loss值
        for X_batch,Y_batch in ds:
            with tf.GradientTape() as tape:
                Y_hat = linear(X_batch)
                loss = losses.mean_squared_error(tf.reshape(Y_hat,[-1]),tf.reshape(Y_batch,[-1]))
            grads = tape.gradient(loss,linear.variables)
            optimizer.apply_gradients(zip(grads,linear.variables))
            L = loss
        
        if(epoch%100==0):
            printbar()
            tf.print("epoch =",epoch,"loss =",L)
            tf.print("w =",linear.kernel)
            tf.print("b =",linear.bias)
            tf.print("")

train(500)
================================================================================16:22:49
epoch = 100 loss = 3.95253944
w = [[2.01676154]
 [-1.01275289]]
b = [2.29978585]

================================================================================16:22:51
epoch = 200 loss = 3.60490489
w = [[2.01732683]
 [-1.01249826]]
b = [2.77192116]

================================================================================16:22:53
epoch = 300 loss = 4.19013166
w = [[2.01749277]
 [-1.01428568]]
b = [2.86695313]

================================================================================16:22:56
epoch = 400 loss = 4.73355436
w = [[2.01622605]
 [-1.01426661]]
b = [2.88615513]

================================================================================16:22:59
epoch = 500 loss = 4.5389142
w = [[2.01557302]
 [-1.01302123]]
b = [2.88996792]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在conda中配置Tensorflow 2.0,可以按照以下步骤进行: 1. 首先,确保已经安装了conda和相应的Python版本。如果没有安装,可以从Anaconda官网下载和安装。 2. 打开Anaconda Prompt或者终端,并创建一个新的conda环境,可以使用命令:conda create -n tf2.0 python=3.7 3. 激活新创建的环境,可以使用命令:conda activate tf2.0 4. 使用conda安装Tensorflow 2.0,可以使用命令:conda install tensorflow-gpu=2.0.0 5. 等待安装完成后,就成功配置了conda中的Tensorflow 2.0环境。 另外,如果你想使用pip进行安装,也可以按照以下步骤进行: 1. 激活你的conda环境,可以使用命令:conda activate tf2.0 2. 使用pip安装Tensorflow 2.0,可以使用命令:pip install tensorflow==2.0.0 -i https://pypi.tuna.tsinghua.edu.cn/simple 这样你就成功配置了conda中的Tensorflow 2.0环境。希望对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [深度学习(基于Tensorflow2.0)学习笔记——Day2](https://download.csdn.net/download/weixin_38747211/14884742)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Conda安装Tensorflow2.0](https://blog.csdn.net/u010442263/article/details/125567460)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Anaconda安装+Tensorflow2.0安装配置+Pycharm安装+GCN调试(Window 10)](https://blog.csdn.net/adreammaker/article/details/125506038)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值