Tensorflow2.x 线性回归的实现

目录

1.自己学习笔记:

2. tf.random_normal()函数:

3. 遇到的问题:

 解决:tensorflow have no attribute enable_eager_execution()__yuki_-CSDN博客

(11条消息) torch.from_numpy()_NDHuaErFeiFei的博客-CSDN博客

TensorFlow随机值:tf.random_normal函数_w3cschool

4. 整个代码:


1.自己学习笔记:

线性回归的实现一般有以下操作:

这些都是神经网络建立的时候,常用的思路操作:读取数据,预处理数据,定义模型,定义损失函数,定义优化函数,训练函数,拟合分析...

 

调参:调节的是超参数。

 

 

学习书籍:《动手学习深度学习》

内容:线性回归

2. tf.random_normal()函数:

从正态分布中输出随机值.

参数:

  • shape:一维整数张量或 Python 数组.输出张量的形状.
  • mean:dtype 类型的0-D张量或 Python 值.正态分布的均值.
  • stddev:dtype 类型的0-D张量或 Python 值.正态分布的标准差.
  • dtype:输出的类型.
  • seed:一个 Python 整数.用于为分发创建一个随机种子.查看 tf.set_random_seed 行为.
  • name:操作的名称(可选).

3. 遇到的问题:

  1.  解决:tensorflow have no attribute enable_eager_execution()__yuki_-CSDN博客

  2. (11条消息) torch.from_numpy()_NDHuaErFeiFei的博客-CSDN博客

  3. TensorFlow随机值:tf.random_normal函数_w3cschool

在tf2.x中,与之类似的函数为:tf.constant  (创建张量)

4. 整个代码:

%matplotlib inline
from IPython import display
from matplotlib import pyplot as pyplot
import tensorflow as tf
import random
import numpy as np

tf.compat.v1.enable_eager_execution()

#--------------------生成数据集操作---------------------
num_inputs = 2
num_examples = 1000
true_w = [2,-3.4]
true_b = 4.2
# 创建张量
#features = tf.constant(np.random.normal(0, 1, (num_examples,num_inputs)))
features = tf.random.normal(shape=(num_examples,num_inputs),stddev=1)
labels = true_w[0]*features[:,0]+true_w[1]*features[:,1]+true_b
labels += tf.random.normal(shape=(tf.shape(labels)),stddev=0.01)

def use_svg_display():
  #用矢量图显示
  display.set_matplotlib_formats('svg')
def set_figsize(figsize=(3.5,2.5)):
  use_svg_display()
  #设置图的尺寸
  pyplot.rcParams['figure.figsize']=figsize

set_figsize()
pyplot.scatter(features[:,1].numpy(),labels.numpy(),1)

#--------------------读取数据操作---------------------
def data_iter(batch_size,features,labels):
  num_examples=len(features)
  indices=list(range(num_examples))
  random.shuffle(indices)
  for i in range(0,num_examples,batch_size):
        #64位整型?与torch.LongTensor作用一致?
    j=np.array(indices[i:min(i+batch_size,num_examples)])
    yield tf.gather(features,j),tf.gather(labels,j)

batch_size=10
for X,y in data_iter(batch_size,features,labels):
  print(X,y)
  break

#tf.Variable :定义一个变量
#这里为什么不定义一个张量?要定义一个变量?
w=tf.Variable(tf.random.normal(shape=(num_inputs,1),mean=0,stddev=0.01))
b=tf.Variable(tf.zeros(shape=(1,)))

#定义了一个线性模型
def linreg(X,w,b):
  return tf.matmul(X,w)+b

#定义一个损失函数:平方差函数
def squared_loss(y_hat,y):
  return (y_hat-tf.reshape(y,shape=y_hat.shape))**2/2

#训练模型
#超参数配置
lr=0.03  #学习率
num_epochs=4  #迭代周期
net=linreg
loss=squared_loss

for epoch in range(num_epochs):
  for X,y in data_iter(batch_size,features,labels):
    with tf.GradientTape(persistent=True) as t:
      t.watch([w,b])
      l=loss(net(X,w,b),y)
    sgd([w,b],l,t,lr,batch_size)
    #这里为什么没有梯度清零?梯度清零有什么作用?
  train_l=loss(net(features,w,b),labels)
  print('epoch %d,loss %f'%(epoch+1,tf.reduce_mean(train_l).numpy()))
print(true_w)
print(true_b)

结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值