Tensorflow学习日记(二)

一,数学运算

乘方:tf.pow(x,a) 或x**a tf.square(x):平方 tf.sqrt(x):平方根

指数:tf.pow(x,a) 或x**a

自然对数:tf.exp(a) 对数:tf.math.log(x)

二,矩阵相乘运算

tf.matmul(a,b)

a=tf.random.normal([2,3,28,32])
b=tf.random.normal([32,32])
tf.matmul(a,b)

三,线性模型实战

利用梯度下降法来进行更新

import numpy as np
def mse(b,w,points):
    #计算当前的w,b的参数的均方误差
    totoalError=0
    for i in range(0,len(points)):
        x=points[i,0]
        y=points[i,1]
        totoalError+=(y-(w*x+b))**2
    return totoalError/float(len(points))

def step_gradient(b_current,w_current,points,lr):
    #计算误差函数所有点上的导数
    b_gradient=0
    w_gradient=0
    M=float(len(points))
    for i in range(0,len(points)):
        x=points[i,0]
        y=points[i,1]
        b_gradient+=(2/M)*((w_current*x+b_current)-y) #均方差对b求导
        w_gradient+=(2/M)*x*((w_current*x+b_current)-y)#均方差对w求导
    #lr:学习率,更新w,b
    new_b=b_current-(lr*b_gradient)
    new_w=w_current-(lr*w_gradient)
    return [new_b,new_w]

def gradient_descent(points,starting_b,starting_w,lr,num_iterations):
    # 循环更新w,b多次
    b=starting_b
    w=starting_w
    #根据梯度下降算法更新多次
    for step in range(num_iterations):
        b,w=step_gradient(b,w,np.array(points),lr)
        loss=mse(b,w,points)
        if step%50==0:
            print(f"iteration:{step},loss:{loss},w:{w},b:{b}")
    return [b,w]

def main():
    # 加载数据集
    lr=0.01
    initial_b=0
    initial_w=0
    num_iterations=1000
    [b,w]=gradient_descent(data,initial_b,initial_w,lr,num_iterations)
    loss=mse(b,w,data)
    print(f"Final loss:{loss},w:{w},b:{b}")

#构建训练数据
data=[]
for i in range(100):
    x=np.random.uniform(-10.,10.)
    #采样高斯噪声
    eps=np.random.normal(0,0.01)
    y=1.44*x+0.089+eps
    data.append([x,y])
data=np.array(data)
main()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

已忘了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值