我正在尝试在Haskell中构建一个感知器单元来学习布尔和/或函数,就像在米切尔的书中一样。
我很确定我的渐变下降是正确的,但我正在努力验证它是否真的学会了算法。我有三个问题,发布在下面的代码之间。
(i)我的梯度下降是否正确?
(ii)如果是,它是否学习“最佳”权重?
(iii)如何验证权重是否正确学习。当你将布尔对插入书中给出的权重时,oor和aand是值,但我认为sgn阈值适用于这些值?如果这是正确的评估假设,那么Mitchells解决方案猜测相同和/或功能。我的学习和/或函数(在ans1,ans2中评估)是不正确的?
import System.Random
-- for generating random initial weights
randomList :: Int -> [Double]
randomList seed = randoms (mkStdGen seed) :: [Double]
dotProd x y = foldr (+) 0 $ zipWith (*) x y
gdHelper [] _ del_w _ _ = del_w
gdHelper (x:xs) (t:ts) y@(weight:weights) w nu = gdHelper xs ts del_w w nu
where del_w = zipWith (+) y (map (*asdf) x)
asdf = nu * (t - o)
o = dotProd w x
gd _ _ _ w _ 0 = w
gd xs ts ws w nu n = gd xs ts [0,0,0] w2 nu (n-1)
where w2 = zipWith (+) w delW
delW = gdHelper xs ts ws w nu
-- initial weights
w = map (/20) $ take 3 $ randomList 30
trainingData = [([1,1],1),([1,-1],-1),([-1,1],-1),([-1,-1],-1)]
andData = map (1:) (map fst trainingData)
andOuts = map snd trainingData
orOuts = [1,1,1,-1]
gdand = gd andData andOuts [0,0,0] w 0.02 10000
gdor = gd andData orOuts [0,0,0] w 0.01 10000
ans1 = map (dotProd gdand) andData
ans2 = map (dotProd gdor) andData
-- trying to verify this from the book
aand = map (dotProd [-0.8,0.5,0.5]) andData
oor = map (dotProd [-0.3,0.5,0.5]) andData
来自米切尔:
编辑:跟进,假设我想复制新的布尔值和和或者布尔值输入的数据。替换以下代码,几何图片保持不变。 (w1 = w2 = 1/2,截距是其原始值的1/2)。但是,因为数据已经缩放(1/2)和翻译(通过(1 / 2,1 / 2)),我的算法现在学习了错误的功能。 `andData = map(1 :) [[x,y] | x < - [0,1],y < - [0,1]]
andData = map (1:) [[x,y] | x <- [0,1], y <- [0,1]]
andOuts = [0,0,0,1]
orOuts = [0,1,1,1]
oor = map (dotProd [-0.5,1,1]) andData
aand = map (dotProd [-1.5,1,1]) andData
我怀疑书中有一个拼写错误:OR的阈值应为0.3,而不是-0.3。在我做出改变后,我通过这种方式验证感知器是否正确:
> map signum aand == andOuts
True
> map signum oor == orOuts
True
> map signum ans1 == andOuts
True
> map signum ans2 == orOuts
True
前两个验证了本书权重的固定版本是否合适;后两者验证了你通过梯度下降学到的权重是合适的。