Python numpy浮点数组精度

2024-04-20 14:00:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Pegasos小批量算法(如图2)解决SVM优化问题,链接:http://www.cs.huji.ac.il/~shais/papers/ShalevSiSrCo10.pdf

#X: m*n matrix with m examples and n features per example (m=4000 and n=784 in my case), Y: m length vector containing 1 or -1 for each example, l: lambda as given in algorithm (l=1 in my code), itr: number of iterations, k: size of batch (100) in my case
def pegasos(X,Y,l,n,m,itr,k):
w = np.zeros((1,n),dtype=np.float32)
print m, n
diff = 0.0
for t in range(1,itr+1):
    A = random.sample(range(1,m),k)
    total = np.zeros((1,n),dtype=np.float32)
    eta = 1/(l*t)
    for i in A:
        x = X[i]
        y = Y[i]
        p = y*(np.dot(w,x.T))
        if p < 1:
            p1 = y*x
            total = np.add(total,p1)
    #update rule
    w = np.add((w*(1-(1/t))) , (eta*total*(1/k)))
return w

我的数据集是这样的,当我的变量total被计算时,我得到的大部分是0,但是有一些值的顺序是10^(-1)到10^(-5)。在更新规则中将total乘以(eta/k)后,所有值都变为0。因此在每次迭代中,我得到的w是0。不应该是这样的。我试过各种方法来提高我的浮动精度,但它们似乎根本不起作用。当我使用基本的Pegasos算法(如上面链接中的图1所示)时,我没有遇到任何问题,因此我的数据集并不是非常奇怪。 如果您在这个问题上有任何帮助,我们将不胜感激:)


Tags: andofin算法for链接examplemy