Python机器学习实战_Logistic-Regression(梯度上升)
最近半年开始用python做数据分析的项目,作为一个new pythoner, 多数情况下都是直接调包。在想能不能自己开始尝试去深入算法内核。。。
一般机器学习开始就会直接来线性回归,但是python机器学习这本书貌似一开始上来的是knn..
虽然KNN也比较简单,但我还是选择了拿逻辑回归来试手。
这本书基本的数据结构采用ndarray, dict结构比较多。
开始为了加快速度了解python自己写算法的速度,就不贴(不会)算法推导的过程了。直接上代码,记下遇到的坑!
import numpy as np
import pandas as pd
import operator
import os
import sys
import matplotlib.pylab as plt
#设置python运行环境在指定目录下,方便直接读入文件
os.getcwd()
os.chdir('E:\\Python\\2_book_practise\\2_ml\\practise\\chap5')
#定义一个读入本地txt文件的函数
#数据格式长成这样
#第1-2列是输入,3列是输出
-0.017612 14.053064 0
-1.395634 4.662541 1
-0.752157 6.538620 0
-1.322371 7.152853 0
0.423363 11.054677 0
0.406704 7.067335 1
0.667394 12.741452 0
-2.460150 6.866805 1
0.569411 9.548755 0
-0.026632 10.427743 0
0.850433 6.920334 1
1.347183 13.175500 0
1.176813 3.167020 1
-1.781871 9.097953 0
-0.566606 5.749003 1
0.931635 1.589505 1
#定义读入的函数
def loadDataSet():
dataMat = [];labelMat = []
fr = open('testSet.txt') #读入数据
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])]) #这里额外添加了一列全部是1的值,就是常规线性回归中的那个常数项
labelMat.append(int(lineArr[2]))
return dataMat, labelMat
#通过下面的定义可以直接获取loadDataset 返回的两个list- dataMat & labelMat
dataMat, labelMat = loadDataSet()
#定义sigmoid函数
def sigmoid(inX):
return 1.0/(1 + np.exp(-inX))
#定义梯度上升函数
def gradAscent(dataMatIn, classLabelIn, maxCycles):
#这里用矩阵数据结构而非ndarray,因为ndarray不能做非对称矩阵乘法
dataMatrix = np.mat(dataMatIn)
labelMatrix = np.mat(classLabelIn).transpose()
m,n = dataMatrix.shape
alpha = 0.01
#maxCycles = 1000
weights = np.ones((n,1))
for k in range(maxCycles):
h = sigmoid(dataMatrix * weights)
error = (labelMatrix - h)
weights = weights + alpha * dataMatrix.transpose() * error
return weights
#返回每一次迭代的每个变量的回归系数
#并且可视化
def get_iter_coef(iters=100000, coefs=3):
coefMatrix = np.ones((iters, coefs))
for i in range(iters):
weights = gradAscent(dataMat, labelMat, i)
coefMatrix[i, :] = np.array(weights).reshape((1,3))
return coefMatrix
coefMatrix = get_iter_coef(1000, 3)
f, ax = plt.subplots(figsize = (10,7), nrows = 3)
ax[0].plot(coefMatrix[:,0])
ax[0].set_title('coef0')
ax[1].plot(coefMatrix[:,1])
ax[1].set_title('coef1')
ax[2].plot(coefMatrix[:,2])
ax[2].set_title('coef2')
画图展示每次迭代回归系数的变化
coef0代表全部值是1的那一列的回归系数,
coef1 & coef2代表的是原始读入文件的第一列与第二列的系数
观察发现,在迭代400次以内,每项回归系数都得到了收敛
下一章看看,如果没有添加的一列常数项,会对回归系数收敛有什么影响