我想构建一个线性模型来预测实例类。这些类是元素{-1, 1}
。为此,我想minimize the empirical risk。
我的代码似乎有效,因为它输出一个数组,其大小为输入元素x的特征数量,每个属性都是元素{-1, 1}
。现在我想知道如何继续。我是否只需构建点积并检查它是否为负数或正数?
示例:
一个输入元素,有5个功能:
[1, 1, -1, -1, -1]
模特:
[7, 5, -2, 0, 3]
构建模型的点积并输入x:
7 + 5 + 2 + 0 - 3 = 11
结果:
11 > 0, x should be of class 1
此外:
构建模型的代码
def learn_reg_ERM(X,y,lbda):
# define consts
max_iter = 200
e = 0.001
alpha = 1.
# init model
w = np.random.randn(X.shape[1]);
for k in np.arange(max_iter):
# dot product/scalar product
# [a, b, c] * [d, e, f] = [ad, be, cf]
h = np.dot(X,w)
# calculate (and print) loss and gradient of loss
l,lg = loss(h, y)
# print 'loss: {}'.format(np.mean(l))
# calculate regularizers and gradient of regularizer at point w
r,rg = reg(w, lbda)
# calc loss + regularizer
g = np.dot(X.T,lg) + rg
if (k > 0):
# update alpha
alpha = alpha * (np.dot(g_old.T,g_old))/(np.dot((g_old - g).T,g_old))
w = w - alpha * g
# check if minimum is found
if (np.linalg.norm(alpha * g) < e):
break
g_old = g
return w