Grokking Deep Learning
1.权重的调节
代码如下
import math
weight = 0.5
input = 0.5
goal_prediction = 0.8
step_amount = 0.1
num = math.ceil(1.1 / step_amount) + 1 # 迭代次数与(goal_prediction/weight)-weight有关 只要
for iteration in range(num):
print("weight:{}".format(weight), num)
prediction = input * weight
error = (prediction - goal_prediction) ** 2
print("Error:" + str(error) + " Prediction:" + str(prediction))
up_prediction = input * (weight + step_amount)
up_error = (goal_prediction - up_prediction) ** 2
down_prediction = input * (weight - step_amount)
down_error = (goal_prediction - down_prediction) ** 2
if (down_error < up_error):
weight = weight - step_amount
if (down_error > up_error):
weight = weight + step_amount
2.牛顿迭代法
牛顿迭代法(Newton’s method)又称为牛顿-拉夫逊(拉弗森)方法(Newton-Raphson method),它是牛顿在17世纪提出的一种在实数域和复数域上近似求解方程的方法。
原理
牛顿迭代法即是在函数中随机选取一个点Xn,一次点做切线,这个切线在切点附近近似于曲线。切线与x轴的交点为Xn+1以Xn+1做垂直于x轴的线与函数相交,得到的交点在做切线,一直循环,发现这种情况是收敛的,离函数的根越来越近
注意事项
此法对选取的点有一定要求
1.选取的点距离解越近越好
2.例如抛物线不可选区驻点,例如f(x)=X^2,f’(x)=2x=x*0=0,它与曲线只有一个交点,这种情况下就没有意义
3.不能求出全部的根
4.在特殊情况下会导致不收敛导致离根越来越远
改进代码
weight = 0.5
goal_pred = 0.8
input = 0.5
for iteration in range(20):
pred = input * weight
error = (pred - goal_pred) ** 2
direction_and_amount = (pred - goal_pred) * input
weight = weight - direction_and_amount
print("Error:" + str(error) + " Prediction:" + str(pred))
此代码比上面的代码up_error以及down_error因为direction_and_amount采取了有符号当预测的小了direction_and_amount为负值,相减为正为加上一个正数,当预测的过大时direction_and_amount为正值相减为减去一个正数。
一个简单的解决一元二次方程问题神经元
代码如下:
import re
import math
while True:
fun = input("输入你要计算的二元一次方程,格式(ax^2+b*x+c),a不能为零:")
try:
ret = re.match(r"(\d+)x\^2\+(\d+)\*x\+(\d+)", fun)
a = float(ret.group(1))
b = float(ret.group(2))
c = float(ret.group(3))
except:
print("输入错误请按如下格式输出")
else:
break
print(ret.group())
if b**2-4*a*c<0:
print("此方程无实数根")
else:
x1 = ((-b)+math.sqrt(b**2-4*a*c))/2
x2 = ((-b) - math.sqrt(b ** 2 - 4 * a * c)) / 2
print(f"x1={x1},x2={x2}")
参考
牛顿迭代法参考:https://blog.csdn.net/ccnt_2012/article/details/81837154
此文为本人学习所创,如有错误请多多指教
联系QQ1135999353