这题主要是训练调参数的技能。其实做模型也是不断调参换模型的过程。
(i)使用不同的学习速率
尝试了一下从1到24的迭代次数
随着学习速率的不断增加,迭代次数变小,但是当迭代次数大于28的时候,又不收敛了。所以在收敛的情况下,学习速率越大,收敛速度越快。
(ii)随着迭代次数的增加,降低学习速率
先是使用了e.g中的内容,让学习速率为1/迭代次数,a的收敛速度变很慢,又没法收敛了。
又尝试了将初始学习速率调为100/迭代次数,依旧不收敛……
(iii)给损益方程增加一个正则化
本题中本身使用的权益方程如下
增加正则化后
运行程序后发现无法收敛
iv 线性缩小输入数据的特征
本题目中一共是100个数据,而我测试了只使用前50个数据,51个数据,52个数据……直到100个数据分别进行了迭代运算,并进行了画图
从图中可以看出,并不是数据量越少,迭代速度越快。
v 增加0均值的高斯分布
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
try: #处理异常,若发生NameError则xrange = range
xrange
except NameError:
xrange = range
# def add_intercept(X_): #将X的数据加上一列1
# m, n = X_.shape
# X = np.zeros((m, n + 2))
# X[:, 0] = 1
# mu = 0 # 期望为1
# sigma = 3 # 标准差为3
# num = 100 # 个数为10000
# X[:, 1] = np.random.normal(mu, sigma, num)
# X[:, 2:] = X_
#
# return X
def load_data(filename): #读取数据,X的数据为两列,Y得数据为1列
D = np.loadtxt(filename)
Y = D[:, 0]
X = D[:, 1:]
# ax = plt.subplot(111, projection='3d')
# ax.scatter(X[:,0], X[:,1], Y, c='y')
# plt.show()
# return add_intercept(X), Y
return X,Y
def calc_grad(X, Y, theta): #计算梯度
m, n = X.shape
grad = np.zeros(theta.shape)
margins = Y * X.dot(theta)
probs = 1. / (1 + np.exp(margins))
grad = -(1./m) * (X.T.dot(probs * Y))
return grad
def logistic_regression(X, Y):
m, n = X.shape
theta = np.zeros(n)
i = 0
error=[]
while True:
i += 1
learning_rate=10
prev_theta = theta
grad = calc_grad(X, Y, theta)
theta = theta - learning_rate * (grad)
error.append(np.linalg.norm(prev_theta - theta))
if i % 10000 == 0:
print('Finished %d iterations' % i)
if np.linalg.norm(prev_theta - theta) < 1e-15 :
print('Converged in %d iterations' % i)
plt.figure(1)
plt.title('data B iteration')
plt.xlabel('iteration')
plt.ylabel('error')
x = len(error) # 设置x轴,以y轴数组长度为宽度
x = range(x)
plt.scatter(x,error, marker='.', color='g', s=5)
plt.show()
break
return i
def main():
print('\n==== Training model on data set A ====')
Xa, Ya = load_data('data_a.txt')
logistic_regression(Xa, Ya)
n=len(Ya)
iteration_times = []
for i in range(50,n):
Xa1,Ya1=Xa[0:i],Ya[0:i]
iteration_times.append(logistic_regression(Xa1, Ya1))
x = len(iteration_times) # 设置x轴,以y轴数组长度为宽度
x = range(50,x+50)
fig = plt.figure()
plt.bar(x, iteration_times, 0.4, color="green")
plt.xlabel("data size")
plt.ylabel("iteration")
plt.title("data size and iteration")
plt.show()
print('\n==== Training model on data set B ====')
Xb, Yb = load_data('data_b.txt')
logistic_regression(Xb, Yb)
return
x,y = load_data('data_a.txt')
x1,y1 = load_data('data_b.txt')
def figure(x,y): #画图
plt.title('data_b.txt')
plt.xlabel('x1')
plt.ylabel('x2')
m=[]
n=[]
for i in range(len(y)):
if y[i]==1:
m.append(i)
else:
n.append(i)
p1 = plt.scatter(x[n,0], x[n, 1], marker='x', color='m', label='1', s=30)
p2 = plt.scatter(x[m,0], x[m, 1], marker='+', color='c', label='-1', s=50)
plt.legend(loc='upper right')
plt.show()
figure(x, y)
figure(x1, y1)
if __name__ == '__main__':
main()
尝试了下各种不同的标准差,感觉标准差小一点迭代速度更好一些,当然因为是随机生成,每次迭代次数也有所不同……
我觉得是不会,SVM中的hinge loss是挑选少量数据进行拟合,而logistic是用所有数据迭代下降求得参数。