Py学习  »  Python

Python可视化神器Yellowbrick使用

Python中文社区 • 4 年前 • 460 次点击  


作者:沂水寒城,CSDN博客专家,个人研究方向:机器学习、深度学习、NLP、CV

Blog: http://yishuihancheng.blog.csdn.net

在机器学习、数据挖掘领域里面,接触到数据处理分析的人来说,数据探索是非常重要的一部分工作,而数据可视化会成为数据分析工程师完成数据探索工作的有力工具。本文主要是介绍一款我日常使用较多的可视化利器Yellowbrick,这是一款基于sklearn+matplotlib模块构建的更加高级的可视化工具,能够更加方便地完成很多数据探索、分词与展示工作。

学习使用一个模块最好的方式就是学习它提供的API,下面先给出来几个比较好的参考地址:

1)官方文档地址(英文)

https://www.scikit-yb.org/en/latest/


2)官方文档地址(中文)

http://www.scikit-yb.org/zh/latest/


Yellowbrick是由一套被称为"Visualizers"组成的可视化诊断工具组成的集合,其由Scikit-Learn API延伸而来,对模型选择过程其指导作用。总之,Yellowbrick结合了Scikit-Learn和Matplotlib并且最好得传承了Scikit-Learn文档,对你的模型进行可视化!

想要了解Yellowbrick就必须先了解Visualizers,它是estimators从数据中学习得的对象,其主要任务是产生可对模型选择过程有更深入了解的视图。从Scikit-Learn来看,当可视化数据空间或者封装一个模型estimator时,其和转换器(transformers)相似,就像"ModelCV" (比如RidgeCV,LassoCV)的工作原理一样。Yellowbrick的主要目标是创建一个和Scikit-Learn类似的有意义的API。

Yellowbrick中最受欢迎的visualizers包括:

如此强大的可视化工具,安装方式却很简单,使用下面的命令:

pip install yellowbrick

如果需要升级最新版本的则可以使用下面的命令:




    
pip install –u yellowbrick

安装完成后,我们就可以进行使用了。该模块提供了几个常用的可用于实验使用的数据集,如下所示:

进入到对应数据集文件夹下面,都会有三个文件,对于bikeshare如下:

其中:bikeshare.csv为数据集文件,如:

Meta.json为字段元信息文件,如:

README.md为介绍说明文件,如:

基于共享单车数据集,简单的数据分析工作实现如下:

def testFunc5(savepath='Results/bikeshare_Rank2D.png'):
    '''
    共享单车数据集预测
    '''

    data=pd.read_csv('bikeshare/bikeshare.csv')
    X=data[["season""month""hour""holiday""weekday""workingday",
            "weather""temp""feelslike""humidity""windspeed"
          ]]
    y=data["riders"]
    visualizer=Rank2D(algorithm="pearson" )
    visualizer.fit_transform(X)
    visualizer.poof(outpath=savepath)


def testFunc6(savepath='Results/bikeshare_temperate_feelslike_relation.png'):
    '''
    进一步考察相关性
    '''

    data=pd.read_csv('bikeshare/bikeshare.csv')
    X=data[["season""month""hour""holiday""weekday""workingday",
            "weather""temp""feelslike""humidity""windspeed"]]
    y=data["riders"]
    visualizer=JointPlotVisualizer(feature='temp', target='feelslike')
    visualizer.fit(X['temp'], X['feelslike'])
    visualizer.poof(outpath=savepath)


def testFunc7(savepath='Results/bikeshare_LinearRegression_ResidualsPlot.png'):
    '''
    基于共享单车数据使用线性回归模型预测
    '''

    data = pd.read_csv('bikeshare/bikeshare.csv')
    X=data[["season""month""hour" "holiday""weekday""workingday",
            "weather""temp""feelslike""humidity""windspeed"]]
    y=data["riders"]
    X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)
    visualizer=ResidualsPlot(LinearRegression())
    visualizer.fit(X_train, y_train)
    visualizer.score(X_test, y_test)
    visualizer.poof(outpath=savepath)


def testFunc8(savepath='Results/bikeshare_RidgeCV_AlphaSelection.png'):
    '''
    基于共享单车数据使用AlphaSelection
    '''

    data=pd.read_csv('bikeshare/bikeshare.csv')
    X=data[["season""month""hour""holiday""weekday""workingday",
            "weather""temp""feelslike""humidity""windspeed"]]
    y=data["riders"]
    alphas=np.logspace(-101200)
    visualizer=AlphaSelection(RidgeCV(alphas=alphas))
    visualizer.fit(X, y)
    visualizer.poof(outpath=savepath)


def testFunc9(savepath='Results/bikeshare_Ridge_PredictionError.png'):
    '''
    基于共享单车数据绘制预测错误图
    '''

    data=pd.read_csv('bikeshare/bikeshare.csv')
    X=data[["season""month""hour""holiday""weekday""workingday",
            "weather""temp""feelslike""humidity""windspeed"]]
    y=data["riders"]
    X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)
    visualizer=PredictionError(Ridge(alpha=3.181))
    visualizer.fit(X_train, y_train)
    visualizer.score(X_test, y_test)
    visualizer.poof(outpath=savepath)

bikeshare_Rank2D.png特征相关性计算

bikeshare_LinearRegression_ResidualsPlot.png使用线性回归模型预测

bikeshare_RidgeCV_AlphaSelection.png使用AlphaSelection特征选择

bikeshare_Ridge_PredictionError.png绘制预测错误图

除了可以直接对数据进行分析展示之外,Yellowbrick同样可以对文本数据进行处理分析,下面我们基于爱好数据集进行简单的使用说明,具体代码实现如下所示:




    
def hobbiesFreqDistVisualizer():
    '''
    文本可视化
    Token 频率分布:绘制语料库中令牌的频率
    t-SNE 语料库可视化:绘制更接近发现聚类的类似文档
    '''

    corpus=load_corpus("data/hobbies")
    vectorizer = CountVectorizer()
    docs       = vectorizer.fit_transform(corpus.data)
    features   = vectorizer.get_feature_names()
    visualizer = FreqDistVisualizer(features=features)
    visualizer.fit(docs)
    visualizer.poof(outpath='text_hobbies_FreqDistVisualizer.png')
    #去停用词
    vectorizer = CountVectorizer(stop_words='english')
    docs       = vectorizer.fit_transform(corpus.data)
    features   = vectorizer.get_feature_names()
    visualizer = FreqDistVisualizer(features=features)
    visualizer.fit(docs)
    visualizer.poof(outpath='text_hobbies_FreqDistVisualizer_stop_words.png')


def hobbiesFreqDistVisualizer2():
    '''
    探索 烹饪和游戏 两种爱好的频度分布
    (报错:没有label,应该为corpus.target)
    '''

    corpus=load_corpus("data/hobbies")
    #烹饪爱好频度分布统计图
    hobbies=defaultdict(list)
    for text,label in zip(corpus.data,corpus.target):
        hobbies[label].append(text)
    vectorizer = CountVectorizer(stop_words='english')
    docs       = vectorizer.fit_transform(text for text in  hobbies['cooking'])
    features   = vectorizer.get_feature_names()
    visualizer = FreqDistVisualizer(features=features)
    visualizer.fit(docs)
    visualizer.poof(outpath='text_hobbies_cooking_FreqDistVisualizer.png')
    #游戏爱好频度分布统计图
    hobbies=defaultdict(list)
    for text,label in zip(corpus.data, corpus.target):
        hobbies[label].append(text)
    vectorizer = CountVectorizer(stop_words='english')
    docs       = vectorizer.fit_transform(text for text in hobbies['gaming'])
    features   = vectorizer.get_feature_names()
    visualizer = FreqDistVisualizer(features=features)
    visualizer.fit(docs)
    visualizer.poof(outpath='text_hobbies_gaming_FreqDistVisualizer.png')


def hobbiesTSNEVisualizer():
    '''
    t-SNE语料库可视化
    T分布随机邻域嵌入,t-SNE。Scikit-Learn将此分解方法实现为sklearn.manifold.TSNE转换器。
     通过使用来自原始维度和分解维度的不同分布将高维文档向量分解为二维。 通过分解为2维或3维,
     可以使用散点图来显示文档。
    '''

    corpus=load_corpus("data/hobbies")
    tfidf  = TfidfVectorizer()
    docs   = tfidf.fit_transform(corpus.data)
    labels = corpus.target
    tsne = TSNEVisualizer()
    tsne.fit(docs, labels)
    tsne.poof(outpath='text_hobbies_TSNEVisualizer.png')
    #Don't color points with their classes
    tsne = TSNEVisualizer(labels=["documents"])
    tsne.fit(docs)
    tsne.poof(outpath='text_hobbies_TSNEVisualizer_nocolor.png')


def hobbiesClusterTSNEVisualizer():
    '''
    聚类应用
    '''

    corpus=load_corpus("data/hobbies")
    tfidf  = TfidfVectorizer()
    docs   = tfidf.fit_transform(corpus.data)
    clusters=KMeans(n_clusters=5)
    clusters.fit(docs)
    tsne=TSNEVisualizer()
    tsne.fit(docs,["c{}".format(c) for c in clusters.labels_])
    tsne.poof(outpath='text_hobbies_cluster_TSNEVisualizer.png')

text_hobbies_FreqDistVisualizer.png

text_hobbies_FreqDistVisualizer_stop_words.png

text_hobbies_cooking_FreqDistVisualizer.png

text_hobbies_gaming_FreqDistVisualizer.png

text_hobbies_TSNEVisualizer.png

text_hobbies_TSNEVisualizer_nocolor.png

text_hobbies_cluster_TSNEVisualizer.png

这里简单介绍一些TSNE,t-distributed Stochastic Neighbor Embedding(t-SNE)是目前来说效果最好的数据降维与可视化方法,但是它的缺点也很明显,比如:占内存大,运行时间长。但是,当我们想要对高维数据进行分类,又不清楚这个数据集有没有很好的可分性(即同类之间间隔小,异类之间间隔大),可以通过 t-SNE 投影到 2 维或者3维的空间中观察一下。如果在低维空间中具有可分性,则数据是可分的;如果在高维空间中不具有可分性,可能是数据不可分,也可能仅仅是因为不能投影到低维空间。

TSNE将数据点之间的相似度转换为概率。原始空间中的相似度由高斯联合概率表示,嵌入空间的相似度由“Student t 分布”表示。虽然 Isomap,LLE 和 variants等数据降维和可视化方法,更适合展开单个连续的低维的manifold。但如果要准确的可视化样本间的相似度关系,t-SNE表现更好。因为t-SNE主要是关注数据的局部结构。

Yellowbrick对数据的可视化有更加高级的封装和实现,对于新手和有一定经验的分析人员来说都是非常友好的,这里强烈推荐入门这款神器,一篇文章的内容有限不足以讲清楚整个模块,感兴趣的话可以阅读我的系列文章。

很高兴在自己温习回顾知识的同时能写下点分享的东西出来,如果说您觉得我的内容还可以或者是对您有所启发、帮助,还希望得到您的鼓励支持!

赞 赏 作 者



Python中文社区作为一个去中心化的全球技术社区,以成为全球20万Python中文开发者的精神部落为愿景,目前覆盖各大主流媒体和协作平台,与阿里、腾讯、百度、微软、亚马逊、开源中国、CSDN等业界知名公司和技术社区建立了广泛的联系,拥有来自十多个国家和地区数万名登记会员,会员来自以工信部、清华大学、北京大学、北京邮电大学、中国人民银行、中科院、中金、华为、BAT、谷歌、微软等为代表的政府机关、科研单位、金融机构以及海内外知名公司,全平台近20万开发者关注。


▼ 点击成为社区注册会员          「在看」一下,一起PY

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48423
 
460 次点击