用线性分类器实现预测鸢尾花的种类(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 在一定时间,我记住了输入的所有的图片.在再次输入一个图片 ...
随机推荐
- c++——对象的构造和析构函数、构造函数的分类及调用
1构造函数和析构函数的概念 有关构造函数 1构造函数定义及调用 1)C++中的类可以定义与类名相同的特殊成员函数,这种与类名相同的成员函数叫做构造函数: 2)构造函数在定义时可以有参数: 3)没有任何 ...
- ddt 接口示范以及报告生成html案例
1.数据构造获取我就不写了直接以test_data=[ ] 构造一个简单数据建模.实际你从哪里获取根据情况excel也好yaml也罢 2.用例套件处理,报告生成处理 import ddtimport ...
- JSONP - 从理论到实践
同源策略 ajax之所以需要“跨域”,罪魁祸首就是浏览器的同源策略.即,一个页面的ajax只能获取这个页面相同源或者相同域的数据. 如何叫“同源”或者“同域”呢?——协议.域名.端口号都必须相同.例如 ...
- 469 B. Intercepted Message
http://codeforces.com/problemset/problem/950/B Hacker Zhorik wants to decipher two secret messages h ...
- STM32定时器输出PWM频率和步进电机控制速度计算
1.STM32F4系列定时器输出PWM频率计算 第一步,了解定时器的时钟多少: 我们知道AHP总线是168Mhz的频率,而APB1和APB2都是挂在AHP总线上的. (1)高级定时器timer1, t ...
- java spring boot项目部署-上
1.编写sh脚本,便于服务器上管理工程: #!/bin/bash source /etc/profile PROG_NAME=$ ACTION=$ usage() { echo "Usage ...
- CodeIgniter Doctrine2基本使用(二)(转)
CodeIgniter Doctrine2基本使用(二) 继上次写的一篇文章<CodeIgniter Doctrine2基本使用(一)>写到操作实体的之通过Channel这个实体向数据库表 ...
- Hadoop系列-MapReduce基础
由于在学习过程中对MapReduce有很大的困惑,所以这篇文章主要是针对MR的运行机制进行理解记录,主要结合网上几篇博客以及视频的讲解内容进行一个知识的梳理. MapReduce on Yarn运行原 ...
- HDFS源码文件过大,IDEA打开失败解决方法
问题现象:hadoop 3.1.0源码文件ClientNamenodeProtocolProtos大小4M+,IDEA打开时加载失败,ClientNamenodeProtocolPB报错找不到类. - ...
- zabbix和elasticsearch数据表
# uint mapping { "settings" : { "index" : { "number_of_replicas" : 1, ...