常见machine learning模型实现
一、感知机模型
二、线性回归(Linear Regression)
from numpy import * def loadData(filename):
x = []
y = []
f = open(filename)
for line in f.readlines():
lineData = line.strip().split(',')
x.append([1.0,float(lineData[0])])
y.append(float(lineData[1]))
return x,y #预测函数,theta,x都是一维数组,dot运算得到实数,对于二维数组,dot运算就是矩阵运算
def h(theta,x):
return theta.dot(x) #批量梯度下降
def batch_gradient_descent(alpha,theta,x,y):
m,n = x.shape
newtheta = array([0] * n,dtype = float)
for j in range(n):
count = 0.0
for i in range(m):
count += (h(theta,x[i,:]) - y[i])*x[i,j]
newtheta[j] = newtheta[j] - count * alpha / m
return newtheta #正则方程
def normal_equation(x,y):
return linalg.inv(transpose(x).dot(x)).dot(transpose(x)).dot(y) #损失函数
def cost_function(theta,x,y):
m = x.shape[0]
return (x.dot(theta) - y).dot(x.dot(theta) - y) / (2 * m) def run():
x,y = loadData('ex1data1.txt')
x = array(x)
y = array(y) #列向量
m,n = x.shape
theta = array([0] * n,dtype = float)
costs = []
for iters in range(1000):
costs.append(cost_function(theta,x,y))
theta = batch_gradient_descent(0.01,theta,x,y)
print "batch gradient descent:\n"
print "theta:",theta
print 'cost:\n',costs print "normal equation:\n"
theta = normal_equation(x,y)
print "theta:",theta if __name__ == "__main__":
run()
三、Logistic Regression
def sigmoid(x):
return 1.0/(1 + exp(-x)) def trainLogRegres(x,y,opts):
m,n = x.shape
alpha = opts["alpha"]
maxIter = opts['maxIter']
weight = ones((n,1)) for k in range(maxIter):
if opts['optimizeType'] == 'batchGraDescent':
weight = weight - alpha * x.T * (sigmoid(x*weight) - y)
elif opts['optimizeType'] == 'stocGraDescent':
for i in range(m):
weight = weight - alpha * x[i,:].T * (sigmoid(x[i,:] * weight) - y[i,0])
else:
raise NameError('Not support optimize method type!') return weight def testLogRegres(weight,x,y):
m,n = x.shape
trueNum = 0
for i in range(m):
predict = sigmoid(x[i,:] * weight)[0,0] > 0.5
if predict == bool(y[i,0]):
trueNum += 1
accuracy = float(trueNum) / m
return accuracy #x每行对应一个样本,y是列向量
def loadData():
x = []
y = []
f = open("testSet.txt")
for line in f.readlines():
lineArr = line.strip().split()
x.append([1.0, float(lineArr[0]), float(lineArr[1])])
y.append(float(lineArr[2]))
return mat(x),mat(y).T if __name__ == '__main__':
x,y = loadData()
opts = {'alpha': 0.01, 'maxIter': 50, 'optimizeType': 'stocGraDescent'}
weight = trainLogRegres(x,y,opts)
accuracy = testLogRegres(weight,x,y)
print "accuracy:",accuracy
四、SVM
五、kmeans
https://en.wikipedia.org/wiki/Latent_semantic_analysis
常见machine learning模型实现的更多相关文章
- 机器学习---最小二乘线性回归模型的5个基本假设(Machine Learning Least Squares Linear Regression Assumptions)
在之前的文章<机器学习---线性回归(Machine Learning Linear Regression)>中说到,使用最小二乘回归模型需要满足一些假设条件.但是这些假设条件却往往是人们 ...
- 【Machine Learning】KNN算法虹膜图片识别
K-近邻算法虹膜图片识别实战 作者:白宁超 2017年1月3日18:26:33 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本系列文章是作者结 ...
- 【机器学习Machine Learning】资料大全
昨天总结了深度学习的资料,今天把机器学习的资料也总结一下(友情提示:有些网站需要"科学上网"^_^) 推荐几本好书: 1.Pattern Recognition and Machi ...
- Machine Learning Algorithms Study Notes(4)—无监督学习(unsupervised learning)
1 Unsupervised Learning 1.1 k-means clustering algorithm 1.1.1 算法思想 1.1.2 k-means的不足之处 1 ...
- Machine Learning Algorithms Study Notes(2)--Supervised Learning
Machine Learning Algorithms Study Notes 高雪松 @雪松Cedro Microsoft MVP 本系列文章是Andrew Ng 在斯坦福的机器学习课程 CS 22 ...
- 机器学习(Machine Learning)&深度学习(Deep Learning)资料
<Brief History of Machine Learning> 介绍:这是一篇介绍机器学习历史的文章,介绍很全面,从感知机.神经网络.决策树.SVM.Adaboost到随机森林.D ...
- FAQ: Machine Learning: What and How
What: 就是将统计学算法作为理论,计算机作为工具,解决问题.statistic Algorithm. How: 如何成为菜鸟一枚? http://www.quora.com/How-can-a-b ...
- 机器学习(Machine Learning)&深入学习(Deep Learning)资料
<Brief History of Machine Learning> 介绍:这是一篇介绍机器学习历史的文章,介绍很全面,从感知机.神经网络.决策树.SVM.Adaboost 到随机森林. ...
- Machine Learning - 第6周(Advice for Applying Machine Learning、Machine Learning System Design)
In Week 6, you will be learning about systematically improving your learning algorithm. The videos f ...
随机推荐
- Codeforces Round #539 (Div. 2) C. Sasha and a Bit of Relax(前缀异或和)
转载自:https://blog.csdn.net/Charles_Zaqdt/article/details/87522917 题目链接:https://codeforces.com/contest ...
- tree iview treeData json数据 添加 selected 数据 要进行vue.set 进行响应式添加
tree iview treeData json数据 添加 selected 数据 要进行vue.set 进行响应式添加
- 使用Spring AOP切面解决数据库读写分离
http://blog.jobbole.com/103496/ 为了减轻数据库的压力,一般会使用数据库主从(master/slave)的方式,但是这种方式会给应用程序带来一定的麻烦,比如说,应用程序如 ...
- Hibernate5.x版本HQL限定查询 Legacy-style query parameters (`?`) are no longer supported
在此版本的限定查询和4.0版本的限定查询: 如果查询语句是: String hql = "select u from User u where u.gender = ?"; 会出现 ...
- Maven实战读书笔记(五):聚合与继承
Maven的聚合特性能够把项目的各个模块聚合在一起构建,而继承特性则能够帮助抽取各模块相同的依赖和插件等配置,在简化POM的同时,还能促进各个模块配置的一致性. 5.1 聚合 Maven聚合也称多模块 ...
- 微信小程序:errcode=40029和invalid code, hints: [ req_id: VyLhYa0451hb31 ]
问题: 后台用小程序返回的code请求微信服务器换取session_key和openid,返回错误状态码40029 解决问题 当前小程序绑定的appid和请求微信服务器所带的appid参数不一致导致的 ...
- 695. Max Area of Island@python
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...
- Linux基础学习-RHEL7.4之YUM更换CentOS源
1.配置YUM本地源 1.挂载镜像 [root@qdlinux ~]# mount /dev/cdrom /mnt 2.查看是否挂载成功 [root@qdlinux ~]# df -h Filesys ...
- 激活windows10(已更新工具)
激活windows10 1.用cmd命令: 自己动手,KMS激活win10 2016 长期服务版.步骤如下:命令提示符(管理员),依次输入以下3条命令 slmgr /ipk DCPHK-NFMTC-H ...
- Vijos1144 皇宫看守 (0/1/2三种状态的普通树形Dp)
题意: 给出一个树以及一些覆盖每个点的花费,求每个点都能被自己被覆盖,或者相邻的点被覆盖的最小价值. 细节: 其实我乍一眼看过去还以为是 战略游戏 的复制版 可爱的战略游戏在这里QAQ(请原谅这波广告 ...