这节课说明了 最下二乘法 是怎么来的。
接下来是面试需要问的
误差,(机器学习是建立在独立同分布的基础上,事实上,根本无法证明独立同分布而且是正态分布,我们假设的,只要模型可用,就可以)
独立: 每个人的误差是独立同分布的,如何不独立那就说明有关系了,黑关系,不能考虑这个,
同分布:假定是同一家银行,如果不是同一家银行,不成立。
高斯分布:就是正态分布 大块面积处在-1 ,1 之间。
似然函数(就是根据数据样本预测参数值的),这里就是让我的预测值与接近真实值,换句话说误差的可能性越小越好
注意:θ是一个列向量,x 也是列向量, 是第i个列向量,对应数据第i行的特征,
而y是一个数字,是第i个单个数字,对应数据第i行的标签。
有一点要明白!似然函数越大越好,就越小越好,符合最小二乘法的概念。
最大似然函数:求这个函数的最大值,一般来说这个函数是负的,并且有极大值,我们就是求的极大值。
为什么似然分布函数值越大越好?
因为,我们的样本都是随机抽取出来的,我们在抽取样本的时候,每次抽取的样本的概率密度都是非常大的,
因此将这些样本数据带入密度函数,也都是最大的,因此当选取合适的参数时候,似然函数是非常大的,越大则越服从我们的密度函数。
前面是推导目标函数(比较简单),后面是难点。
是第i行的真实数据
接下来推到最下二乘法:(矩阵求导怎么做?)
下面的 后面等式右边的 的维数m x n 代表特征矩阵m行代表m个例子,n列代表n个特征维度。
y 代表列向量标签m x 1。代表参数是一个列向量 n x 1
上面矩阵对向量的求导公式:由本人博客《数学问题:矩阵运算法则及矩阵求导》中的例子1和例子2有详解
遗留问题:这个式子可逆吗?不管她可你不,先逆一下。
梯度下降法:
logistic regression
现实中,往往先拿逻辑回归试试效果怎样,在去试试其他的算法,优先选择的算法、
sigmod函数求导:
下面的是第i行数据的特征有n个特征,因此是一个列向量。是第i行数据的标签值,这里要么是0要么是1
概率密度函数是我们自己造的:
就是概率密度;也就是y服从这个分布。表示在输入为x的情况下,y值得可能性。y=1或者y=0;
求偏导推导:相当简单了,i:代表第i条数据
大学生按成绩是否被录取案例,代码分析
'''
'''
# %matplotlib inline :表示在notebook中不需要plt.show()即可显示图像,在pycharm中不行,报错
pdData = pd.read_csv('LogiReg_data.txt', header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
'''
我们发现读取这个的文件,第一行竟然是数据,没有列名,因此让header=none,自己指定列名
names=['Exam 1', 'Exam 2', 'Admitted'],第三列位标签项,1:录取;0:没有被录取
'''
positive = pdData[pdData['Admitted'] == 1]
negative = pdData[pdData['Admitted'] == 0]
'''
pdData['Admitted'] == 1 :表示返回一个100x1的矩阵,元素为true或者false
positive = pdData[pdData['Admitted'] == 1] :则是让true为索引的行全部拿出来
negative 同理
'''
fig, ax = plt.subplots(figsize=(10,5))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=30, c='b', marker='o', label='Admitted')
'''
subplots:创建一个子图,大小(10,5),接下来画录取和没有被录取的散点图,做好标记
'''
def model(X, theta):
return sigmoid(np.dot(X, theta.T))
'''
np.dot(X, theta.T) X:为100x3 的矩阵,theta为1x3的矩阵,没毛病
'''
pdData.insert(0, 'Ones', 1)
'''
在第一列的前面插上一列,列名为one 值为1
'''
orig_data = pdData.as_matrix() # convert the Pandas representation of the data to an array useful for further computations
cols = orig_data.shape[1]
X = orig_data[:,0:cols-1]
y = orig_data[:,cols-1:cols]
'''
他这么写,感觉太麻烦了不就是把x和y分离吗,
'''
def cost(X, y, theta):
left = np.multiply(-y, np.log(model(X, theta)))
right = np.multiply(1 - y, np.log(1 - model(X, theta)))
return np.sum(left - right) / (len(X))
'''
multiply(a,b)就是个乘法,如果a,b是两个数组,那么对应元素相乘
'''
def gradient(X, y, theta):
grad = np.zeros(theta.shape) #1x3的矩阵
error = (model(X, theta) - y).ravel()
for j in range(len(theta.ravel())): # for each parmeter
term = np.multiply(error, X[:, j])
grad[0, j] = np.sum(term) / len(X)
'''
我们要求 theta的偏导数,这里面有三个theta,因此求三个
j :代表每一列
----------------------------------------------------------
>>> x.ravel()
array([1, 2, 3, 4])
两者默认均是行序优先
>>> x.flatten('F')
array([1, 3, 2, 4])
>>> x.ravel('F')
array([1, 3, 2, 4])
---------------------------------------------------------------
np.sum(term) #这里term是矩阵怎么求和呢,默认是把矩阵所有元素相加
np.sum 和Python自带的sum不一样,真可气
np.sum(X,axis=1) 每一行相加 axis=0就是纵向相加
'''
def descent(data, theta, batchSize, stopType, thresh, alpha):
# 梯度下降求解
init_time = time.time()
i = 0 # 迭代次数
k = 0 # batch
X, y = shuffleData(data)
grad = np.zeros(theta.shape) # 计算的梯度
costs = [cost(X, y, theta)] # 损失值
while True:
grad = gradient(X[k:k + batchSize], y[k:k + batchSize], theta)
k += batchSize # 取batch数量个数据
if k >= n:
k = 0
X, y = shuffleData(data) # 重新洗牌
theta = theta - alpha * grad # 参数更新
costs.append(cost(X, y, theta)) # 计算新的损失
i += 1
if stopType == STOP_ITER:
value = i
elif stopType == STOP_COST:
value = costs
elif stopType == STOP_GRAD:
value = grad
if stopCriterion(stopType, value, thresh): break
return theta, i - 1, costs, grad, time.time() - init_time
'''
核心代码就这
theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)
其他都是修饰
'''
def runExpe(data, theta, batchSize, stopType, thresh, alpha):
#import pdb; pdb.set_trace();
theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)
name = "Original" if (data[:,1]>2).sum() > 1 else "Scaled"
name += " data - learning rate: {} - ".format(alpha)
if batchSize==n: strDescType = "Gradient"
elif batchSize==1: strDescType = "Stochastic"
else: strDescType = "Mini-batch ({})".format(batchSize)
name += strDescType + " descent - Stop: "
if stopType == STOP_ITER: strStop = "{} iterations".format(thresh)
elif stopType == STOP_COST: strStop = "costs change < {}".format(thresh)
else: strStop = "gradient norm < {}".format(thresh)
name += strStop
print ("***{}\nTheta: {} - Iter: {} - Last cost: {:03.2f} - Duration: {:03.2f}s".format(
name, theta, iter, costs[-1], dur))
#--------------------------上面是打印结果,下面是画图
fig, ax = plt.subplots(figsize=(12,4))
ax.plot(np.arange(len(costs)), costs, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title(name.upper() + ' - Error vs. Iteration')
plt.show()
return theta
'''
开始运行程序
'''
n=100
runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)
# runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)
# runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)
# runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)
全部代码
'''
我们将建立一个逻辑回归模型来预测一个学生是否被大学录取。
假设你是一个大学系的管理员,
你想根据两次考试的结果来决定每个申请人的录取机会。
你有以前的申请人的历史数据,
你可以用它作为逻辑回归的训练集。对于每一个培训例子,
你有两个考试的申请人的分数和录取决定。为了做到这一点,
我们将建立一个分类模型,根据考试成绩估计入学概率
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %matplotlib inline
import os
# ------------------------------------读取数据并画图检查,二维数据
path = 'data' + os.sep + 'LogiReg_data.txt'
pdData = pd.read_csv('LogiReg_data.txt', header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
positive = pdData[pdData['Admitted'] == 1] # returns the subset of rows such Admitted = 1, i.e. the set of *positive* examples
negative = pdData[pdData['Admitted'] == 0] # returns the subset of rows such Admitted = 0, i.e. the set of *negative* examples
fig, ax = plt.subplots(figsize=(10,5))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=30, c='b', marker='o', label='Admitted')
ax.scatter(negative['Exam 1'], negative['Exam 2'], s=30, c='r', marker='x', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')
# plt.show()
# -----------------------------------------------------建立并画出sigmod函数图像
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# nums = np.arange(-10, 10, step=1) #creates a vector containing 20 equally spaced values from -10 to 10
# fig, ax = plt.subplots(figsize=(12,4))
# ax.plot(nums, sigmoid(nums), 'r')
# ---------------------建立预测模型
def model(X, theta):
'''
:param X: 矩阵:每一行是一条数据,每一列是特征,其中第一列全是1为了乘以θ
:param theta: 这里是一个行向量,维数是1xN的矩阵,为了矩阵相乘,在下面进行转置了
:return:是一个列向量对每一条数据进行预测
'''
return sigmoid(np.dot(X, theta.T))
# ----------------------设置数据格式,他的方法有些麻烦,
'''目标:
X.shape, y.shape, theta.shape
((100, 3), (100, 1), (1, 3)) #100条数据,三个维度,本身数据两个维度一个标签,
自己插入一个维度1
'''
pdData.insert(0, 'Ones', 1)
# set X (training data) and y (target variable)
orig_data = pdData.as_matrix() # convert the Pandas representation of the data to an array useful for further computations
cols = orig_data.shape[1]
X = orig_data[:,0:cols-1]
y = orig_data[:,cols-1:cols]
theta = np.zeros([1, 3])
# ----------------------设置数据格式,完毕
#定义损失函数,按照推导的
def cost(X, y, theta):
'''
:param X: Nx3的特征矩阵,
:param y: Nx1的标签矩阵
:param theta: 1X3的参数阵
:return:
'''
left = np.multiply(-y, np.log(model(X, theta)))
right = np.multiply(1 - y, np.log(1 - model(X, theta)))
return np.sum(left - right) / (len(X))
print(X,y,theta)
# --------------------------------计算梯度
def gradient(X, y, theta):
'''
:param X: 特征阵,这里就是一块数据,随机梯度就是一块一块的进行
:param y: Nx1的标签
:param theta: 1x3的矩阵
:return:
'''
grad = np.zeros(theta.shape)
error = (model(X, theta) - y).ravel()
for j in range(len(theta.ravel())): # for each parmeter
term = np.multiply(error, X[:, j])
grad[0, j] = np.sum(term) / len(X)
return grad
STOP_ITER = 0
STOP_COST = 1
STOP_GRAD = 2
def stopCriterion(type, value, threshold):
#设定三种不同的停止策略
if type == STOP_ITER: return value > threshold
elif type == STOP_COST: return abs(value[-1]-value[-2]) < threshold
elif type == STOP_GRAD: return np.linalg.norm(value) < threshold
import numpy.random
#洗牌
def shuffleData(data):
np.random.shuffle(data)
cols = data.shape[1]
X = data[:, 0:cols-1]
y = data[:, cols-1:]
return X, y
import time
def descent(data, theta, batchSize, stopType, thresh, alpha):
# 梯度下降求解
init_time = time.time()
i = 0 # 迭代次数
k = 0 # batch
X, y = shuffleData(data)
grad = np.zeros(theta.shape) # 计算的梯度
costs = [cost(X, y, theta)] # 损失值
while True:
grad = gradient(X[k:k + batchSize], y[k:k + batchSize], theta)
k += batchSize # 取batch数量个数据
if k >= n:
k = 0
X, y = shuffleData(data) # 重新洗牌
theta = theta - alpha * grad # 参数更新
costs.append(cost(X, y, theta)) # 计算新的损失
i += 1
if stopType == STOP_ITER:
value = i
elif stopType == STOP_COST:
value = costs
elif stopType == STOP_GRAD:
value = grad
if stopCriterion(stopType, value, thresh): break
return theta, i - 1, costs, grad, time.time() - init_time
def runExpe(data, theta, batchSize, stopType, thresh, alpha):
#import pdb; pdb.set_trace();
theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)
name = "Original" if (data[:,1]>2).sum() > 1 else "Scaled"
name += " data - learning rate: {} - ".format(alpha)
if batchSize==n: strDescType = "Gradient"
elif batchSize==1: strDescType = "Stochastic"
else: strDescType = "Mini-batch ({})".format(batchSize)
name += strDescType + " descent - Stop: "
if stopType == STOP_ITER: strStop = "{} iterations".format(thresh)
elif stopType == STOP_COST: strStop = "costs change < {}".format(thresh)
else: strStop = "gradient norm < {}".format(thresh)
name += strStop
print ("***{}\nTheta: {} - Iter: {} - Last cost: {:03.2f} - Duration: {:03.2f}s".format(
name, theta, iter, costs[-1], dur))
#--------------------------上面是打印结果,下面是画图
fig, ax = plt.subplots(figsize=(12,4))
ax.plot(np.arange(len(costs)), costs, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title(name.upper() + ' - Error vs. Iteration')
plt.show()
return theta
n=100
runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)
# runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)
# runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)
# runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)
#
# from sklearn import preprocessing as pp
#
# scaled_data = orig_data.copy()
# scaled_data[:, 1:3] = pp.scale(orig_data[:, 1:3])
#
# runExpe(scaled_data, theta, n, STOP_ITER, thresh=5000, alpha=0.001)
# runExpe(scaled_data, theta, n, STOP_GRAD, thresh=0.02, alpha=0.001)
# theta = runExpe(scaled_data, theta, 1, STOP_GRAD, thresh=0.002/5, alpha=0.001)
# runExpe(scaled_data, theta, 16, STOP_GRAD, thresh=0.002*2, alpha=0.001)
# #设定阈值
# def predict(X, theta):
# return [1 if x >= 0.5 else 0 for x in model(X, theta)]
#
# scaled_X = scaled_data[:, :3]
# y = scaled_data[:, 3]
# predictions = predict(scaled_X, theta)
# correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]
# accuracy = (sum(map(int, correct)) % len(correct))
# print ('accuracy = {0}%'.format(accuracy))