用线性分类器实现预测鸢尾花的种类(python)
这是个人学习时跑的代码,结果就不贴了,有需要的可以自己运行,仅供参考,有不知道的可以私下交流,有问题也可以联系我。当然了我也只能提供一点建议,毕竟我也只是初学者
第一个页面
# -*- coding: utf-8 -*-
#previous row is a way to use chinese
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
import matplotlib.pyplot as plt
import sklearn as sk
import numpy as np
from sklearn.linear_model.stochastic_gradient import SGDClassifier
#use the other function instead of it due to not find the function named '.linear_modelsklearn._model' while wrote by the book
from sklearn import metrics
iris = datasets.load_iris()
X_iris, y_iris = iris.data, iris.target
#print X_iris.shape, y_iris.shape
#print X_iris[0],y_iris[0]
X,y = X_iris[:,:2],y_iris
X_train, X_test, y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=33)
#print X_train.shape,y_train.shape
scaler = preprocessing.StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
colors = ['red','greenyellow','blue']
for i in xrange(len(colors)):
xs = X_train[:, 0][y_train==i]
ys = X_train[:, 1][y_train==i]
plt.scatter(xs,ys, c=colors[i])
plt.legend(iris.target_names)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
#plt.show()
clf = SGDClassifier()
clf.fit(X_train, y_train)
#print clf.coef_
#print clf.intercept_
x_min, x_max = X_train[:,0].min()-.5,X_train[:,0].max()+.5
y_min,y_max = X_train[:,1].min() - .5,X_train[:,1].max()+.5
xs=np.arange(x_min,x_max,0.5)
fig,axes=plt.subplots(1,3)
fig.set_size_inches(10,6)
for i in [0,1,2]:
axes[i].set_aspect('equal')
axes[i].set_title('Class '+ str(i)+' versus the rest')
axes[i].set_xlabel('Sepal length')
axes[i].set_ylabel('Sepal width')
axes[i].set_xlim(x_min,x_max)
axes[i].set_ylim(y_min,y_max)
plt.sca(axes[i])#sca is belong to matplotlib.pyplot we couldn't use it directly
plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap=plt.prism())#we can't find the cm so use prism() to replace it
ys=(-clf.intercept_[i]-
xs*clf.coef_[i,0])/clf.coef_[i,1]#Xs is not defined so I use xs to replaced
plt.plot(xs,ys,hold=True)
plt.show()
#print clf.predict(scaler.transform([[4.7,3.1]]))
#print clf.decision_function(scaler.transform([[4.7,3.1]]))
y_train_pred=clf.predict(X_train)
#print metrics.accuracy_score(y_train,y_train_pred)
y_pred=clf.predict(X_test)
#print metrics.accuracy_score(y_test,y_pred)
#print metrics.classification_report(y_test,y_pred,target_names=iris.target_names)
print metrics.confusion_matrix(y_test,y_pred)
第二个页面分开运行就好了,不过可能会调用第一个页面,这个用了交叉验证。
from sklearn.cross_validation import cross_val_score,KFold
from sklearn.pipeline import Pipeline
from sklearn import preprocessing
from sklearn import datasets
from sklearn.linear_model.stochastic_gradient import SGDClassifier
from scipy.stats import sem
import numpy as np
iris = datasets.load_iris()
X_iris, y_iris = iris.data, iris.target
X,y = X_iris[:,:2],y_iris
clf=Pipeline([('scaler',preprocessing.StandardScaler()),('linear_model',SGDClassifier())])
cv=KFold(X.shape[0],5,shuffle=True,random_state=33)
scores=cross_val_score(clf,X,y,cv=cv)
#print scores
def mean_score(scores):
return ("Mean score: {0:.3f} (+/-{1:.3f})").format(np.mean(scores),sem(scores))
print mean_score(scores)
用线性分类器实现预测鸢尾花的种类(python)的更多相关文章
- 机器学习之线性分类器(Linear Classifiers)——肿瘤预测实例
线性分类器:一种假设特征与分类结果存在线性关系的模型.该模型通过累加计算每个维度的特征与各自权重的乘积来帮助决策. # 导入pandas与numpy工具包. import pandas as pd i ...
- cs231n笔记 (一) 线性分类器
Liner classifier 线性分类器用作图像分类主要有两部分组成:一个是假设函数, 它是原始图像数据到类别的映射.另一个是损失函数,该方法可转化为一个最优化问题,在最优化过程中,将通过更新假设 ...
- cs231n笔记:线性分类器
cs231n线性分类器学习笔记,非完全翻译,根据自己的学习情况总结出的内容: 线性分类 本节介绍线性分类器,该方法可以自然延伸到神经网络和卷积神经网络中,这类方法主要有两部分组成,一个是评分函数(sc ...
- Python机器学习(基础篇---监督学习(线性分类器))
监督学习经典模型 机器学习中的监督学习模型的任务重点在于,根据已有的经验知识对未知样本的目标/标记进行预测.根据目标预测变量的类型不同,我们把监督学习任务大体分为分类学习与回归预测两类.监督学习任务的 ...
- SVM中的线性分类器
线性分类器: 首先给出一个非常非常简单的分类问题(线性可分),我们要用一条直线,将下图中黑色的点和白色的点分开,很显然,图上的这条直线就是我们要求的直线之一(可以有无数条这样的直线) 假如说, ...
- SVM – 线性分类器
感知机 要理解svm,首先要先讲一下感知机(Perceptron),感知机是线性分类器,他的目标就是通过寻找超平面实现对样本的分类:对于二维世界,就是找到一条线,三维世界就是找到一个面,多维世界就是要 ...
- 2. SVM线性分类器
在一个线性分类器中,可以看到SVM形成的思路,并接触很多SVM的核心概念.用一个二维空间里仅有两类样本的分类问题来举个小例子.如图所示 和是要区分的两个类别,在二维平面中它们的样本如上图所示.中间的直 ...
- cs331n 线性分类器损失函数与最优化
tip:老师语速超快...痛苦= = 线性分类器损失函数与最优化 \(Multiclass SVM loss: L_{i} = \sum_{j \neq y_{i}} max(0,s_{i}-s_{y ...
- 1. cs231n k近邻和线性分类器 Image Classification
第一节课大部分都是废话.第二节课的前面也都是废话. First classifier: Nearest Neighbor Classifier 在一定时间,我记住了输入的所有的图片.在再次输入一个图片 ...
随机推荐
- Day12 Java异常处理与程序调试
什么是异常? 不正常的,会影响程序的正常执行流程. 例如下面的程序 public static void main(String[] args) { TestDemo1 t = new TestDem ...
- Day10 API
String类 String是不可变类:值一旦确定了,就不会更改. public static void main(String[] args) { String s1 = "hello&q ...
- Odoo前端页面模版渲染引擎——Jinja2用法教程
转载请注明原文地址:https://www.cnblogs.com/cnodoo/p/9307200.html 一:渲染模版 要渲染一个qweb模板文件,通过render_template方法即可. ...
- docker常用命令(一)
1. docker命令 docker images //查看本地镜像 docker rmi 镜像名称:标签名称 //删除一个镜像 docker rm 容器ID //删除一个容器 docker comm ...
- 知乎live考研数学冲刺135+资料分享
前言 各位学弟学妹,您好,live中本来是给出了我的邮箱,通过邮箱来获取资料,但是没有想到,后来我每天打开邮箱,都是需要回复的邮件,少则一两封,多则四五封,每天如此,也是一个比较繁琐费时的方式.我决定 ...
- Spring源码分析(二)容器基本用法
摘要:本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. 在正式分析Spring源码之前,我们有必要先来回顾一下Spring中最简 ...
- docker 私有仓库 harbor docker-compose
c创建docker私有仓库 docker pull registry:2.1.1 mkdir /opt/registry#mkdir /var/lib/registry docker run -d - ...
- 什么是控制反转(IOC)?什么是依赖注入?
控制反转是应用于软件工程领域中的,在运行时被装配器对象来绑定耦合对象的一种编程技巧,对象之间耦合关系在编译时通常是未知的.在传统编程方式中,业务逻辑的流程是应用程序中早已被设定好关联关系的对象来决定的 ...
- PHP中const,static,public,private,protected的区别
原文地址:http://small.aiweimeng.top/index.php/archives/54.html const: 定义常量,一般定义后不可改变static: 静态,类名可以访问pub ...
- 一图看懂hadoop MapReduce工作原理
MapReduce执行流程及单词统计WordCount示例