Python进行特征提取的示例代码

#过滤式特征选择
#根据方差进行选择,方差越小,代表该属性识别能力很差,可以剔除
from sklearn.feature_selection import VarianceThreshold
x=[[100,1,2,3],
  [100,4,5,6],
  [100,7,8,9],
  [101,11,12,13]]
selector=VarianceThreshold(1) #方差阈值值,
selector.fit(x)
selector.variances_ #展现属性的方差
selector.transform(x)#进行特征选择
selector.get_support(True) #选择结果后,特征之前的索引
selector.inverse_transform(selector.transform(x)) #将特征选择后的结果还原成原始数据
                         #被剔除掉的数据,显示为0

#单变量特征选择
from sklearn.feature_selection import SelectKBest,f_classif
x=[[1,2,3,4,5],
  [5,4,3,2,1],
  [3,3,3,3,3],
  [1,1,1,1,1]]
y=[0,1,0,1]
selector=SelectKBest(score_func=f_classif,k=3)#选择3个特征,指标使用的是方差分析F值
selector.fit(x,y)
selector.scores_ #每一个特征的得分
selector.pvalues_
selector.get_support(True) #如果为true,则返回被选出的特征下标,如果选择False,则
              #返回的是一个布尔值组成的数组,该数组只是那些特征被选择
selector.transform(x)

#包裹时特征选择
from sklearn.feature_selection import RFE
from sklearn.svm import LinearSVC #选择svm作为评定算法
from sklearn.datasets import load_iris #加载数据集
iris=load_iris()
x=iris.data
y=iris.target
estimator=LinearSVC()
selector=RFE(estimator=estimator,n_features_to_select=2) #选择2个特征
selector.fit(x,y)
selector.n_features_  #给出被选出的特征的数量
selector.support_   #给出了被选择特征的mask
selector.ranking_   #特征排名,被选出特征的排名为1

#注意:特征提取对于预测性能的提升没有必然的联系,接下来进行比较;
from sklearn.feature_selection import RFE
from sklearn.svm import LinearSVC
from sklearn import cross_validation
from sklearn.datasets import load_iris

#加载数据
iris=load_iris()
X=iris.data
y=iris.target
#特征提取
estimator=LinearSVC()
selector=RFE(estimator=estimator,n_features_to_select=2)
X_t=selector.fit_transform(X,y)
#切分测试集与验证集
x_train,x_test,y_train,y_test=cross_validation.train_test_split(X,y,
                  test_size=0.25,random_state=0,stratify=y)
x_train_t,x_test_t,y_train_t,y_test_t=cross_validation.train_test_split(X_t,y,
                  test_size=0.25,random_state=0,stratify=y)

clf=LinearSVC()
clf_t=LinearSVC()
clf.fit(x_train,y_train)
clf_t.fit(x_train_t,y_train_t)
print('origin dataset test score:',clf.score(x_test,y_test))
#origin dataset test score: 0.973684210526
print('selected Dataset:test score:',clf_t.score(x_test_t,y_test_t))
#selected Dataset:test score: 0.947368421053

import numpy as np
from sklearn.feature_selection import RFECV
from sklearn.svm import LinearSVC
from sklearn.datasets import load_iris
iris=load_iris()
x=iris.data
y=iris.target
estimator=LinearSVC()
selector=RFECV(estimator=estimator,cv=3)
selector.fit(x,y)
selector.n_features_
selector.support_
selector.ranking_
selector.grid_scores_

#嵌入式特征选择
import numpy as np
from sklearn.feature_selection import SelectFromModel
from sklearn.svm import LinearSVC
from sklearn.datasets import load_digits
digits=load_digits()
x=digits.data
y=digits.target
estimator=LinearSVC(penalty='l1',dual=False)
selector=SelectFromModel(estimator=estimator,threshold='mean')
selector.fit(x,y)
selector.transform(x)
selector.threshold_
selector.get_support(indices=True)

#scikitlearn提供了Pipeline来讲多个学习器组成流水线,通常流水线的形式为:将数据标准化,
#--》特征提取的学习器————》执行预测的学习器,除了最后一个学习器之后,
#前面的所有学习器必须提供transform方法,该方法用于数据转化(如归一化、正则化、
#以及特征提取
#学习器流水线(pipeline)
from sklearn.svm import LinearSVC
from sklearn.datasets import load_digits
from sklearn import cross_validation
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
def test_Pipeline(data):
  x_train,x_test,y_train,y_test=data
  steps=[('linear_svm',LinearSVC(C=1,penalty='l1',dual=False)),
      ('logisticregression',LogisticRegression(C=1))]
  pipeline=Pipeline(steps)
  pipeline.fit(x_train,y_train)
  print('named steps',pipeline.named_steps)
  print('pipeline score',pipeline.score(x_test,y_test))

if __name__=='__main__':
  data=load_digits()
  x=data.data
  y=data.target
  test_Pipeline(cross_validation.train_test_split(x,y,test_size=0.25,
                  random_state=0,stratify=y))

以上就是Python进行特征提取的示例代码的详细内容,更多关于Python 特征提取的资料请关注我们其它相关文章!

(0)

相关推荐

  • python利用小波分析进行特征提取的实例

    如下所示: #利用小波分析进行特征分析 #参数初始化 inputfile= 'C:/Users/Administrator/Desktop/demo/data/leleccum.mat' #提取自Matlab的信号文件 from scipy.io import loadmat #mat是MATLAB专用格式,需要用loadmat读取它 mat = loadmat(inputfile) signal = mat['leleccum'][0] import pywt #导入PyWavelets co

  • python实现信号时域统计特征提取代码

    1.实验数据需求 为了对采集的压力实验数据做特征工程,需要对信号进行时域的统计特征提取,包含了均值.均方根.偏度.峭度.波形因子.波峰因子.脉冲因子.峭度因子等,现用python对其进行实现. 2.python实现 其中的输入参数含义: ① data:实验数据的DataFrame ② p1:所截取实验信号的起始采样点位置 ③ p2:所截取实验信号的终止采样点位置 from pandas import Series import math pstf_list=[] def psfeatureTim

  • Python + OpenCV 实现LBP特征提取的示例代码

    背景 看了些许的纹理特征提取的paper,想自己实现其中部分算法,看看特征提取之后的效果是怎样 运行环境 Mac OS Python3.0 Anaconda3(集成了很多包,浏览器界面编程,清爽) 步骤 导入包 from skimage.transform import rotate from skimage.feature import local_binary_pattern from skimage import data, io,data_dir,filters, feature fro

  • 使用python实现语音文件的特征提取方法

    概述 语音识别是当前人工智能的比较热门的方向,技术也比较成熟,各大公司也相继推出了各自的语音助手机器人,如百度的小度机器人.阿里的天猫精灵等.语音识别算法当前主要是由RNN.LSTM.DNN-HMM等机器学习和深度学习技术做支撑.但训练这些模型的第一步就是将音频文件数据化,提取当中的语音特征. MP3文件转化为WAV文件 录制音频文件的软件大多数都是以mp3格式输出的,但mp3格式文件对语音的压缩比例较重,因此首先利用ffmpeg将转化为wav原始文件有利于语音特征的提取.其转化代码如下: fr

  • python实现图片处理和特征提取详解

    这是一张灵异事件图...开个玩笑,这就是一张普通的图片. 毫无疑问,上面的那副图画看起来像一幅电脑背景图片.这些都归功于我的妹妹,她能够将一些看上去奇怪的东西变得十分吸引眼球.然而,我们生活在数字图片的年代,我们也很少去想这些图片是在怎么存储在存储器上的或者去想这些图片是如何通过各种变化生成的. 在这篇文章中,我将带着你了解一些基本的图片特征处理.data massaging 依然是一样的:特征提取,但是这里我们还需要对跟多的密集数据进行处理,但同时数据清理是在数据库.表.文本等中进行.这是如何

  • python利用opencv实现SIFT特征提取与匹配

    本文实例为大家分享了利用opencv实现SIFT特征提取与匹配的具体代码,供大家参考,具体内容如下 1.SIFT 1.1.sift的定义 SIFT,即尺度不变特征变换(Scale-invariant feature transform,SIFT),是用于图像处理领域的一种描述.这种描述具有尺度不变性,可在图像中检测出关键点,是一种局部特征描述子. 1.2.sift算法介绍 SIFT由David Lowe在1999年提出,在2004年加以完善 .SIFT在数字图像的特征描述方面当之无愧可称之为最红

  • Python实现的特征提取操作示例

    本文实例讲述了Python实现的特征提取操作.分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- """ Created on Mon Aug 21 10:57:29 2017 @author: 飘的心 """ #过滤式特征选择 #根据方差进行选择,方差越小,代表该属性识别能力很差,可以剔除 from sklearn.feature_selection import VarianceThreshold x=[[100

  • Python进行特征提取的示例代码

    #过滤式特征选择 #根据方差进行选择,方差越小,代表该属性识别能力很差,可以剔除 from sklearn.feature_selection import VarianceThreshold x=[[100,1,2,3], [100,4,5,6], [100,7,8,9], [101,11,12,13]] selector=VarianceThreshold(1) #方差阈值值, selector.fit(x) selector.variances_ #展现属性的方差 selector.tra

  • Python Flask基础教程示例代码

    本文研究的主要是Python Flask基础教程,具体介绍如下. 安装:pip install flask即可 一个简单的Flask from flask import Flask #导入Flask app = Flask(__name__) #创建一个Flask实例 #设置路由,即url @app.route('/') #url对应的函数 def hello_world(): #返回的页面 return 'Hello World!' #这个不是作为模块导入的时候运行,比如这个文件为aa.py,

  • Python安装OpenCV的示例代码

    OpenCV介绍 OpenCV是一个基于BSD许可(开源)发行的跨平台计算机视觉库,可以运行在Linux.Windows.Android和Mac OS操作系统上.它轻量级而且高效--由一系列 C 函数和少量 C++ 类构成,同时提供了Python.Ruby.MATLAB等语言的接口,实现了图像处理和计算机视觉方面的很多通用算法. OpenCV用C++语言编写,它的主要接口也是C++语言,但是依然保留了大量的C语言接口.该库也有大量的Python.Java and MATLAB/OCTAVE(版本

  • 利用python生成照片墙的示例代码

    PIL(Python Image Library)是python的第三方图像处理库,但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了.其官方主页为:PIL. PIL历史悠久,原来是只支持python2.x的版本的,后来出现了移植到python3的库pillow,pillow号称是friendly fork for PIL,其功能和PIL差不多,但是支持python3.本文只使用了PIL那些最常用的特性与用法,主要参考自:http://www.effbot.org

  • Python无损压缩图片的示例代码

    每个设计师.摄影师或有图片处理需求小编,都会面临批量高清大图的困扰. 因为高清大图放到网站上会严重拖慢加载速度,或是有的地方明确限制了图片大小,因此,为了完成工作,他们总是需要先把图片压缩,再上传. 当需要处理的图片多至十张.百张.千张,则严重影响工作效率.这时候,就可以交给Python啦! 只需要20行Python代码,就可以批量帮你无损压缩数张照片. ---1--- 前期工作 安装Python中现成的图片处理模块,然后将图片打包好导入,用循环的方式自动化处理图片就可以了! ---2--- 运

  • python操作链表的示例代码

    class Node: def __init__(self,dataval=None): self.dataval=dataval self.nextval=None class SLinkList: def __init__(self): self.headval=None # 遍历列表 def traversal_slist(self): head_node=self.headval while head_node is not None: print(head_node.dataval)

  • python调用摄像头的示例代码

    一.打开摄像头 import cv2 import numpy as np def video_demo(): capture = cv2.VideoCapture(0)#0为电脑内置摄像头 while(True): ret, frame = capture.read()#摄像头读取,ret为是否成功打开摄像头,true,false. frame为视频的每一帧图像 frame = cv2.flip(frame, 1)#摄像头是和人对立的,将图像左右调换回来正常显示. cv2.imshow("vi

  • Python调用Redis的示例代码

    #!/usr/bin/env python # -*- coding:utf-8 -*- # ************************************* # @Time : 2019/8/12 # @Author : Zhang Fan # @Desc : Library # @File : MyRedis.py # @Update : 2019/8/23 # ************************************* import redis class MyR

  • Python 实现二叉查找树的示例代码

    二叉查找树 所有 key 小于 V 的都被存储在 V 的左子树 所有 key 大于 V 的都存储在 V 的右子树 BST 的节点 class BSTNode(object): def __init__(self, key, value, left=None, right=None): self.key, self.value, self.left, self.right = key, value, left, right 二叉树查找 如何查找一个指定的节点呢,根据定义我们知道每个内部节点左子树的

  • Python实现区域填充的示例代码

    所用的库及环境: IDE:Pycharm Python环境:python3.7 Matplotlib: Matplotlib 1.11 Numpy: Numpy1.15. 区域填充 前言 如何填充一块区域,就是给一块区域上色 代码及效果图 fill()函数介绍 文档:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.fill.html 介绍:绘制填充多边形 属性: args:是一个x,y的序列,每个多边形由其节点x和y的位置列表定义 col

随机推荐