线性回归的构造,tf2.0

tensorflow构造简单的线性回归模型,如下所示:

#预测酸奶日销量y,x1、x2是影响日销量的因素,从全局视角构建真实的模型y_ = x1 + x2,然后通过数据输入生成的函数来拟合这个真实的模型
#输入的数据集自己构造
import tensorflow as tf
import numpy as np 

SEED=23455
COST = 1
PROFIT = 99
rdm = np.random.RandomState(seed = SEED)
x=rdm.rand(32,2)
y_ = [[x1 + x2 + (rdm.rand()/10.0 - 0.05)] for (x1,x2) in x]
x = tf.cast(x,dtype = tf.float32)

w1 = tf.Variable(tf.random.normal([2,1],stddev = 1,seed =1))
epoch = 15000
Ir = 0.002

for epoch in range(epoch):
    with tf.GradientTape() as tape:
        y = tf.matmul(x,w1)
        #loss_mse = tf.reduce_mean(tf.square(y_ - y))
        loss_mse = tf.reduce_sum(tf.where(tf.greater(y,y_),(y-y_)*COST,(y_-y)*PROFIT))
    
    grads =tape.gradient(loss_mse,w1)
    w1.assign_sub(Ir*grads)
    
    if epoch %500 ==0:
        print("After %d training steps,w1 is"%(epoch))
        print(w1.numpy(),"\n")
        
print("final w1 is:",w1.numpy())

print(y_)
print(y)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值