# -*- coding: utf-8 -*-
'''
Created on 2018年1月18日
@author: Jason.F
@summary: 特征抽取-LDA方法,监督、分类
'''
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.lda import LDA
#定义绘制函数
def plot_decision_regions(X, y, classifier, resolution=0.02):# setup marker generator and color mapmarkers = ('s', 'x', 'o', '^', 'v')colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')cmap = ListedColormap(colors[:len(np.unique(y))])# plot the decision surfacex1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),np.arange(x2_min, x2_max, resolution))Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)Z = Z.reshape(xx1.shape)plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)plt.xlim(xx1.min(), xx1.max())plt.ylim(xx2.min(), xx2.max())# plot class samplesfor idx, cl in enumerate(np.unique(y)):plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],alpha=0.8, c=cmap(idx),marker=markers[idx], label=cl)#第一步:导入数据,对原始d维数据集做标准化处理
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data',header=None)
df_wine.columns=['Class label','Alcohol','Malic acid','Ash','Alcalinity of ash','Magnesium','Total phenols','Flavanoids','Nonflavanoid phenols','Proanthocyanins','Color intensity','Hue','OD280/OD315 of diluted wines','Proline']
print ('class labels:',np.unique(df_wine['Class label']))
#print (df_wine.head(5))
#分割训练集合测试集
X,y=df_wine.iloc[:,1:].values,df_wine.iloc[:,0].values
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=0)
#特征值缩放-标准化
stdsc=StandardScaler()
X_train_std=stdsc.fit_transform(X_train)
X_test_std=stdsc.fit_transform(X_test)
#第二步:PCA降维
lda=LDA(n_components=2)#参数设置选择前2个最能优化分类的特征子空间
lr=LogisticRegression()
X_train_lda=lda.fit_transform(X_train_std,y_train)
X_test_lda=lda.transform(X_test_std)
lr.fit(X_train_lda,y_train)
plot_decision_regions(X_train_lda,y_train,classifier=lr)
plt.xlabel('LD1')
plt.ylabel('LD2')
plt.legend(loc='lower left')
plt.show()
plot_decision_regions(X_test_lda,y_test,classifier=lr)
plt.xlabel('LD1')
plt.ylabel('LD2')
plt.legend(loc='lower left')
plt.show()

结果:

【Python-ML】SKlearn库特征抽取-LDA相关推荐

  1. Python安装sklearn库时出现异常:ERROR: Could not install packages due to an EnvironmentError: [Errno 2]

    文章目录 一.问题描述 二.问题解决 一.问题描述 今天在学习python机器学习时,需要安装python的sklearn库,在安装的过程中出现了以下错误 上CSDN上找了好多文章,都没办法解决问题 ...

  2. 用Python的sklearn库进行PCA(主成分分析)

    在python的sklearn的库里面集成很多机器学习算法的库,其中也包括主成分分析的方法. 1.PCA算法的原理: PCA主要是用来数据降维,将高纬度的特征映射到低维度的特征,加快机器学习的速度.比 ...

  3. ID3决策树 Python实现 + sklearn库决策树模型的应用

    本文介绍机器学习中决策树算法的python实现过程 共介绍两类方法: (1)亲手实习Python ID3决策树经典算法 (2)利用sklearn库实现决策树算法 关于决策树的原理,指路:机器学习 第四 ...

  4. 【Python-ML】SKlearn库特征抽取-PCA

    # -*- coding: utf-8 -*- ''' Created on 2018年1月18日 @author: Jason.F @summary: 特征抽取-PCA方法,无监督.线性 ''' i ...

  5. 每天进步一点点《ML - Sklearn库简单学习》

    一:Sklearn介绍 Sklearn是一个强大的机器学习库,基于python的.官方文档(http://scikit-learn.org/stable/ ).如下列举部分的使用场景. 由图中,可以看 ...

  6. Python初探——sklearn库中数据预处理函数fit_transform()和transform()的区别

    敲<Python机器学习及实践>上的code的时候,对于数据预处理中涉及到的fit_transform()函数和transform()函数之间的区别很模糊,查阅了很多资料,这里整理一下: ...

  7. 【Python-ML】SKlearn库特征抽取-KPCA

    # -*- coding: utf-8 -*- ''' Created on 2018年1月18日 @author: Jason.F @summary: 特征抽取-KPCA方法 ''' import ...

  8. python中sklearn库更新_python库之sklearn

    一.安装sklearn conda install scikit-learn 参考文献 [1]整体介绍sklearn https://blog.csdn.net/u014248127/article/ ...

  9. python分类算法的应用_Python基于sklearn库的分类算法简单应用示例

    Python基于sklearn库的分类算法简单应用示例 来源:中文源码网    浏览: 次    日期:2018年9月2日 [下载文档:  Python基于sklearn库的分类算法简单应用示例.tx ...

最新文章

  1. cve-2017–10271 XMLDecoder 反序列化漏洞 原理分析
  2. 了解区块链,从挖矿开始
  3. Graph Search就是语义搜索
  4. 多线程与单核cpu,多核cpu概念
  5. python社招面试_百度大牛总结十条Python面试题陷阱,看看你是否会中招
  6. 天猫回应“双11数据造假”:已启动司法流程;小米折叠手机专利曝光;ASP.NET感染勒索软件|极客头条...
  7. C# ITextSharp pdf 自动打印
  8. IDL | 实验三、IDL编程演练
  9. java获得数据后如何插入数据表_java如何实现对数据库的插入
  10. debian9中文办公环境字体设置
  11. android webview 刷新当前页面,android webview肿么刷新网页
  12. Android必知必会-App 常用图标尺寸规范汇总
  13. 线性组合(linear combinations), 生成空间(span), 基向量(basis vectors)——线性代数本质(二)
  14. 瑞芯微rv1126/1109软硬件解压缩对比---附:关于内存对齐的那些事
  15. Kingdom Rush 国王保卫战图文攻略
  16. word、excel文档内容更新技术方案
  17. NoSql的四大类型
  18. 使用 UltraISO 将系统写入U盘
  19. 项目实训-关键词提取-任务理解工作分配
  20. Redis Queue使用第一天报错

热门文章

  1. 延大计算机文化基础课程作业,基于项目学习的大学《计算机文化基础课》教学设计...
  2. java query接口_「软帝学院」Java零基础学习详解
  3. PAT1052---------初步了解正则表达式
  4. Golang结构体struct的使用(结构体嵌套, 匿名结构体等)
  5. 织梦CMS调用指定顶级栏目名称的方法
  6. bzoj1045: [HAOI2008] 糖果传递
  7. springboot profiles
  8. JavaScript 面试中常见算法问题详解
  9. i春秋30强挑战赛pwn解题过程
  10. petshop 出现没有为 SQL 缓存通知启用数据库“MSPetShop4”