用线性分类器实现预测鸢尾花的种类(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 在一定时间,我记住了输入的所有的图片.在再次输入一个图片 ...
随机推荐
- Centos7安装anaconda3
Centos7安装anaconda3 1. 安装bunzip2 yum install bunzip2 2. 下载anaconda3 wget https://repo.anaconda.com/ar ...
- centos下mysqlreport安装和使用
首先查看你的机器是否安装了perl: #perl -v 显示版本号即表示已安装 然后: #yum install perl-DBD-mysql perl-DBI #yum install mysqlr ...
- Day2 Mybatis初识(二)
mapper接口开发 传统dao的开发问题(ibatis) 方法调用:字符串易错,硬编码 mapper代理开发 a) 编写全局配置 b) 编写接口(自动根据接口和映射文件创建实现类) c) 编写映射文 ...
- 重载全局new/delete实现内存检测
下面介绍用重载new/delete运算符的方式来实现一个简单的内存泄露检测工具,基本思想是重载全局new/delete运算符,被检测代码调用new和delete运算符时就会调用重载过的operator ...
- CSS+JQuery实现Tabs效果,点击更改背景色(不含图片)
1,Html代码 <body> <div id="box"> <ul id="tab_nav"> <li class= ...
- head 标签里有什么?
head 标签里有什么? 每一个 HTML 文档中,都有一个不可或缺的标签:<head> ,它作为一个容器,主要包含了用于描述 HTML 文档自身信息(元数据)的标签,这些标签一般不会在页 ...
- mapreduce二次排序详解
什么是二次排序 待排序的数据具有多个字段,首先对第一个字段排序,再对第一字段相同的行按照第二字段排序,第二次排序不破坏第一次排序的结果,这个过程就称为二次排序. 如何在mapreduce中实现二次排序 ...
- NGS检测SNP
1,Fastq数据质控 2,Fastq转化成bam,包含头文件 bwa aln ref.fa test_1.fq > test_1.sai bwa aln ref.fa test_2.fq &g ...
- JavaWeb基础—Http协议
一.什么是Http协议 超文本传输协议的简称,用于定义客户端与web服务器通迅的格式. 关于[标准的HTTP协议是无状态的],请参见:http://www.cnblogs.com/bellkosmos ...
- ZJOI2018 round^2 游记
Day0 一早起来6点左右,吃完早饭去班里拿了书包就来机房,说实话怕被打[手动滑稽]. 在车上大约经历了3个半小时的车程,终于到达了目的地:余姚.当然基本上大家的设备电量都不多了,除了某些上车睡觉的大 ...