机器学习算法的Python实现 (1):logistics回归 与 线性判别分析(LDA)
先收藏。。。。。。。。。。。。
本文为笔者在学习周志华老师的机器学习教材后,写的课后习题的的编程题。之前放在答案的博文中,现在重新进行整理,将需要实现代码的部分单独拿出来,慢慢积累。希望能写一个机器学习算法实现的系列。
本文主要包括:
1、logistics回归
2、python库:
- numpy
- matplotlib
- pandas
| Idx | density | ratio_sugar | label |
| 1 | 0.697 | 0.46 | 1 |
| 2 | 0.774 | 0.376 | 1 |
| 3 | 0.634 | 0.264 | 1 |
| 4 | 0.608 | 0.318 | 1 |
| 5 | 0.556 | 0.215 | 1 |
| 6 | 0.403 | 0.237 | 1 |
| 7 | 0.481 | 0.149 | 1 |
| 8 | 0.437 | 0.211 | 1 |
| 9 | 0.666 | 0.091 | 0 |
| 10 | 0.243 | 0.0267 | 0 |
| 11 | 0.245 | 0.057 | 0 |
| 12 | 0.343 | 0.099 | 0 |
| 13 | 0.639 | 0.161 | 0 |
| 14 | 0.657 | 0.198 | 0 |
| 15 | 0.36 | 0.37 | 0 |
| 16 | 0.593 | 0.042 | 0 |
| 17 | 0.719 | 0.103 | 0 |
# -*- coding: cp936 -*-
from numpy import *
import pandas as pd
import matplotlib.pyplot as plt #读入csv文件数据
df=pd.read_csv('watermelon_3a.csv')
m,n=shape(dataMat)
df['norm']=ones((m,1))
dataMat=array(df[['norm','density','ratio_sugar']].values[:,:])
labelMat=mat(df['label'].values[:]).transpose() #sigmoid函数
def sigmoid(inX):
return 1.0/(1+exp(-inX)) #梯度上升算法
def gradAscent(dataMat,labelMat):
m,n=shape(df.values)
alpha=0.1
maxCycles=500
weights=array(ones((n,1))) for k in range(maxCycles):
a=dot(dataMat,weights)
h=sigmoid(a)
error=(labelMat-h)
weights=weights+alpha*dot(dataMat.transpose(),error)
return weights #随机梯度上升
def randomgradAscent(dataMat,label,numIter=50):
m,n=shape(dataMat)
weights=ones(n)
for j in range(numIter):
dataIndex=range(m)
for i in range(m):
alpha=40/(1.0+j+i)+0.2 randIndex_Index=int(random.uniform(0,len(dataIndex)))
randIndex=dataIndex[randIndex_Index]
h=sigmoid(sum(dot(dataMat[randIndex],weights)))
error=(label[randIndex]-h)
weights=weights+alpha*error[0,0]*(dataMat[randIndex].transpose())
del(dataIndex[randIndex_Index])
return weights #画图
def plotBestFit(weights):
m=shape(dataMat)[0]
xcord1=[]
ycord1=[]
xcord2=[]
ycord2=[]
for i in range(m):
if labelMat[i]==1:
xcord1.append(dataMat[i,1])
ycord1.append(dataMat[i,2])
else:
xcord2.append(dataMat[i,1])
ycord2.append(dataMat[i,2])
plt.figure(1)
ax=plt.subplot(111)
ax.scatter(xcord1,ycord1,s=30,c='red',marker='s')
ax.scatter(xcord2,ycord2,s=30,c='green')
x=arange(0.2,0.8,0.1)
y=array((-weights[0]-weights[1]*x)/weights[2])
print shape(x)
print shape(y)
plt.sca(ax)
plt.plot(x,y) #ramdomgradAscent
#plt.plot(x,y[0]) #gradAscent
plt.xlabel('density')
plt.ylabel('ratio_sugar')
#plt.title('gradAscent logistic regression')
plt.title('ramdom gradAscent logistic regression')
plt.show() #weights=gradAscent(dataMat,labelMat)
weights=randomgradAscent(dataMat,labelMat)
plotBestFit(weights)
# -*- coding: cp936 -*-
from numpy import *
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt df=pd.read_csv('watermelon_3a.csv') def calulate_w():
df1=df[df.label==1]
df2=df[df.label==0]
X1=df1.values[:,1:3]
X0=df2.values[:,1:3]
mean1=array([mean(X1[:,0]),mean(X1[:,1])])
mean0=array([mean(X0[:,0]),mean(X0[:,1])])
m1=shape(X1)[0]
sw=zeros(shape=(2,2))
for i in range(m1):
xsmean=mat(X1[i,:]-mean1)
sw+=xsmean.transpose()*xsmean
m0=shape(X0)[0]
for i in range(m0):
xsmean=mat(X0[i,:]-mean0)
sw+=xsmean.transpose()*xsmean
w=(mean0-mean1)*(mat(sw).I)
return w def plot(w):
dataMat=array(df[['density','ratio_sugar']].values[:,:])
labelMat=mat(df['label'].values[:]).transpose()
m=shape(dataMat)[0]
xcord1=[]
ycord1=[]
xcord2=[]
ycord2=[]
for i in range(m):
if labelMat[i]==1:
xcord1.append(dataMat[i,0])
ycord1.append(dataMat[i,1])
else:
xcord2.append(dataMat[i,0])
ycord2.append(dataMat[i,1])
plt.figure(1)
ax=plt.subplot(111)
ax.scatter(xcord1,ycord1,s=30,c='red',marker='s')
ax.scatter(xcord2,ycord2,s=30,c='green')
x=arange(-0.2,0.8,0.1)
y=array((-w[0,0]*x)/w[0,1])
print shape(x)
print shape(y)
plt.sca(ax)
#plt.plot(x,y) #ramdomgradAscent
plt.plot(x,y) #gradAscent
plt.xlabel('density')
plt.ylabel('ratio_sugar')
plt.title('LDA')
plt.show() w=calulate_w()
plot(w)
结果如下:
对应的w值为:
[ -6.62487509e-04, -9.36728168e-01]
由于数据分布的关系,所以LDA的效果不太明显。所以我改了几个label=0的样例的数值,重新运行程序得到结果如下:
效果比较明显,对应的w值为:
[-0.60311161, -0.67601433]
机器学习算法的Python实现 (1):logistics回归 与 线性判别分析(LDA)的更多相关文章
- 机器学习算法与Python实践之(七)逻辑回归(Logistic Regression)
http://blog.csdn.net/zouxy09/article/details/20319673 机器学习算法与Python实践之(七)逻辑回归(Logistic Regression) z ...
- 机器学习算法与Python实践之(四)支持向量机(SVM)实现
机器学习算法与Python实践之(四)支持向量机(SVM)实现 机器学习算法与Python实践之(四)支持向量机(SVM)实现 zouxy09@qq.com http://blog.csdn.net/ ...
- 机器学习算法与Python实践之(三)支持向量机(SVM)进阶
机器学习算法与Python实践之(三)支持向量机(SVM)进阶 机器学习算法与Python实践之(三)支持向量机(SVM)进阶 zouxy09@qq.com http://blog.csdn.net/ ...
- 机器学习算法与Python实践之(二)支持向量机(SVM)初级
机器学习算法与Python实践之(二)支持向量机(SVM)初级 机器学习算法与Python实践之(二)支持向量机(SVM)初级 zouxy09@qq.com http://blog.csdn.net/ ...
- 机器学习算法与Python实践之(五)k均值聚类(k-means)
机器学习算法与Python实践这个系列主要是参考<机器学习实战>这本书.因为自己想学习Python,然后也想对一些机器学习算法加深下了解,所以就想通过Python来实现几个比较常用的机器学 ...
- 机器学习算法与Python实践之(六)二分k均值聚类
http://blog.csdn.net/zouxy09/article/details/17590137 机器学习算法与Python实践之(六)二分k均值聚类 zouxy09@qq.com http ...
- 机器学习 —— 基础整理(四)特征提取之线性方法:主成分分析PCA、独立成分分析ICA、线性判别分析LDA
本文简单整理了以下内容: (一)维数灾难 (二)特征提取--线性方法 1. 主成分分析PCA 2. 独立成分分析ICA 3. 线性判别分析LDA (一)维数灾难(Curse of dimensiona ...
- 机器学习理论基础学习3.2--- Linear classification 线性分类之线性判别分析(LDA)
在学习LDA之前,有必要将其自然语言处理领域的LDA区别开来,在自然语言处理领域, LDA是隐含狄利克雷分布(Latent Dirichlet Allocation,简称LDA),是一种处理文档的主题 ...
- 机器学习中的数学-线性判别分析(LDA)
前言在之前的一篇博客机器学习中的数学(7)——PCA的数学原理中深入讲解了,PCA的数学原理.谈到PCA就不得不谈LDA,他们就像是一对孪生兄弟,总是被人们放在一起学习,比较.这这篇博客中我们就来谈谈 ...
随机推荐
- 天马行空DevOps-Dev平台建设概述
概述 DevOps(Development和Operations的组合词)是一组过程.方法与系统的统称,用于促进开发(应用程序/软件工程).技术运营和质量保障(QA)部门之间的沟通.协作与整合.它是一 ...
- python sys.argv是什么?
1.sys.argv 是获取运行python文件的时候命令行参数,且以list形式存储参数 2.sys.argv[0] 代表当前module的名字 下面的代码文件是a.py,当我不用IDE工具,只用命 ...
- 5个最优秀的微信小程序UI组件库
开发微信小程序的过程中,选择一款好用的组件库,可以达到事半功倍的效果.自从微信小程序面世以来,不断有一些开源组件库出来,下面5款就是排名比较靠前,用户使用量与关注度比较高的小程序UI组件库.还没用到它 ...
- hadoop Datanode Uuid unassigned
在配置hadoop的hdfs的时候,要首先格式化,然后才能启动,但是格式化的方式有的是不对出现Initialization failed for Block pool <registering& ...
- 作业三C++
作业心得 1.本次作业开始使用C++编写了(面向过程的C++,2333) 2.粗略学习了一下文件输入输出,和项目的创建等(在大佬眼里最基本的操作QAQ,然而我还是有点晕晕的,平时都是ctrl+n新建源 ...
- Educational Codeforces Round 16 E. Generate a String dp
题目链接: http://codeforces.com/problemset/problem/710/E E. Generate a String time limit per test 2 seco ...
- UVALive - 6887 Book Club 有向环的路径覆盖
题目链接: http://acm.hust.edu.cn/vjudge/problem/129727 D - Book Club Time Limit: 5000MS 题意 给你一个无自环的有向图,问 ...
- [codecademy]fonts in css
Great job! You learned how to style an important aspect of the user experience: fonts! Let's review ...
- 关于Filter的一点误解
之前一直以为请求达到Web应用时,经过过滤器1,过滤器2……,处理后产生响应再经过过滤器n……过滤器2,过滤器1.这样的阐述似乎没有问题,但我的理解却有问题.比如过滤器1的doFilter方法执行了一 ...
- TCP系列46—拥塞控制—9、SACK下的快速恢复与Limited transmit
一.概述 1.SACK下的特殊处理过程 SACK下的拥塞控制处理是linux中拥塞控制的实现依据,再次强调一遍RFC6675的重要性,linux中拥塞控制主体框架的实现是与RFC6675一致的,所以如 ...