一,数学运算
乘方: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()