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)