用线性分类器实现预测鸢尾花的种类(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 在一定时间,我记住了输入的所有的图片.在再次输入一个图片 ...
随机推荐
- SSM框架之RestFul示例
演示环境:maven+Spring+SpringMVC+MyBatis Plus或MyBatis都行+JDK8 JDK7我想应该没有问题,原因是用的基本都是JDK6或者JDK7的相关特性. 当然了,J ...
- hdfs的java接口简单示例
public class HDFSDemo { private FileSystem fs = null; @Before public void init() throws IOException, ...
- (转)Jmeter http请求之content-type
原文传送门:http://www.cnblogs.com/dinghanhua/p/5646435.html 第一部分:目前工作中涉及到的content-type 有三种: content-type: ...
- Jmeter之八大可执行元件及执行顺序
初步接触Jmeter,对比LoadRunner进行熟悉,╮(╯▽╰)╭.毕竟我对LoadRunner还是比Jmeter熟悉. 1.配置元件 用来提供对静态数据配置的支持.例CSV Data Set c ...
- chrome 浏览器插件开发(一)—— 创建第一个chrome插件
最近在开发一个chrome插件,在网上找到了一些的文章,虽说按照文章可以写出对应的例子,但若要进行实际开发,发现还是有不少文章中没有的坑.下面我将结合我在开发过程中遇到的几个方面,对这些坑做一下补充. ...
- boost::bind 学习
最近学习了太多与MacOS与Iphone相关的东西,因为不会有太多人有兴趣,学习的平台又是MacOS,不太喜欢MacOS下的输入法,所以写下来的东西少了很多. 等我学习的东西慢慢的与平台无关的时 ...
- GitHub 源码,Framework 框架
https://github.com/CoderLN/Apple-GitHub-Codeidea Apple 译文.GitHub 源码,随原作者 (大版本) 迭代注解.--- 不知名开发者 https ...
- 文本处理三剑客之 awk
GAWK:报告生成器,格式化文本输出 awk [options] ‘program’ var=value file… awk [options] -f programfile var=value fi ...
- zabbix服务快速搭建指南
zabbix监控服务快速安装指南 1.更换centos7-base源为阿里源 wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.ali ...
- mac下安装phalcon
PHP版本:7.1.16 1. 安装 brew tap tigerstrikemedia/homebrew-phalconphp brew install php71-phalcon 2.配置php. ...