gpt4 book ai didi

python - 为什么我的 tanh 激活函数表现如此糟糕?

转载 作者:行者123 更新时间:2023-11-28 17:29:13 26 4
gpt4 key购买 nike

我有两个感知器算法,除了激活函数外,它们都相同。一个使用单步函数 1 if u >= 0 else -1 另一个使用 tanh 函数 np.tanh(u)

我预计 tanh 的性能会优于该步骤,但实际上相比之下它的性能非常糟糕。我在这里做错了什么,或者它在问题集上表现不佳的原因是什么?

enter image description here

import numpy as np
import matplotlib.pyplot as plt

# generate 20 two-dimensional training data
# data must be linearly separable

# C1: u = (0,0) / E = [1 0; 0 1]; C2: u = (4,0), E = [1 0; 0 1] where u, E represent centre & covariance matrix of the
# Gaussian distribution respectively


def step(u):
return 1 if u >= 0 else -1


def sigmoid(u):
return np.tanh(u)

c1mean = [0, 0]
c2mean = [4, 0]
c1cov = [[1, 0], [0, 1]]
c2cov = [[1, 0], [0, 1]]
x = np.ones((40, 3))
w = np.zeros(3) # [0, 0, 0]
w2 = np.zeros(3) # second set of weights to see how another classifier compares
t = [] # target array

# +1 for the first 20 then -1
for i in range(0, 40):
if i < 20:
t.append(1)
else:
t.append(-1)

x1, y1 = np.random.multivariate_normal(c1mean, c1cov, 20).T
x2, y2 = np.random.multivariate_normal(c2mean, c2cov, 20).T

# concatenate x1 & x2 within the first dimension of x and the same for y1 & y2 in the second dimension
for i in range(len(x)):
if i >= 20:
x[i, 0] = x2[(i-20)]
x[i, 1] = y2[(i-20)]
else:
x[i, 0] = x1[i]
x[i, 1] = y1[i]

errors = []
errors2 = []
lr = 0.0001
n = 10

for i in range(n):
count = 0
for row in x:
dot = np.dot(w, row)
response = step(dot)
errors.append(t[count] - response)
w += lr * (row * (t[count] - response))
count += 1

for i in range(n):
count = 0
for row in x:
dot = np.dot(w2, row)
response = sigmoid(dot)
errors2.append(t[count] - response)
w2 += lr * (row * (t[count] - response))
count += 1

print(errors[-1], errors2[-1])

# distribution
plt.figure(1)
plt.plot((-(w[2]/w[0]), 0), (0, -(w[2]/w[1])))
plt.plot(x1, y1, 'x')
plt.plot(x2, y2, 'ro')
plt.axis('equal')
plt.title('Heaviside')

# training error
plt.figure(2)
plt.ylabel('error')
plt.xlabel('iterations')
plt.plot(errors)
plt.title('Heaviside Error')

plt.figure(3)
plt.plot((-(w2[2]/w2[0]), 0), (0, -(w2[2]/w2[1])))
plt.plot(x1, y1, 'x')
plt.plot(x2, y2, 'ro')
plt.axis('equal')
plt.title('Sigmoidal')

plt.figure(4)
plt.ylabel('error')
plt.xlabel('iterations')
plt.plot(errors2)
plt.title('Sigmoidal Error')

plt.show()

编辑:即使从我显示的误差图中,tanh 函数也显示了一些收敛性,因此可以合理地假设只需增加迭代次数或降低学习率就可以减少误差。然而,我想我真的在问,考虑到阶跃函数的显着更好的性能,对于哪些问题集,将 tanh 与感知器一起使用是可行的?

最佳答案

如评论中所述,您的学习率太小,因此需要大量迭代才能收敛。因此,为了获得可比较的输出,您可以增加 n 和/或 lr

如果将 lr 增加到例如0.1(也 1 工作正常)和 n 到 10000,结果看起来几乎相同(见下图)和行

print(errors[-1], errors2[-1])

返回

(0, -8.4289020207961585e-11)

如果您再次运行它,这些值可能会有所不同,因为没有为随机数设置种子。

这是我为上述值得到的图:

enter image description here enter image description here

enter image description here enter image description here

关于python - 为什么我的 tanh 激活函数表现如此糟糕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35803431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com