📓
Study
  • README
  • Application
    • Contest
      • 竞赛trick
  • Basic Know
    • 半监督学习
    • 贝叶斯
      • 朴素贝叶斯分类器
    • 对抗训练
    • 概率图模型
      • CRF
      • HMM
      • 概率图模型
    • 关联分析
    • 归纳偏置
      • [什么是 Inductive bias(归纳偏置)?](BasicKnow/归纳偏置/什么是 Inductive bias(归纳偏置)?.md)
    • 聚类
    • 决策树
    • 绿色深度学习
    • 树模型&集成学习
      • 提升树
      • Ada Boost
      • [集成学习]
    • 特征工程
      • 数据分桶
      • 特征工程概述
      • 特征选择
      • LDA
      • PCA
    • 线性模型
      • 感知机
      • 最大熵模型
      • SVM
        • SVM支持向量机
      • 逻辑回归
      • 线性回归
    • 优化算法
      • 拉格朗日对偶性
      • 牛顿法
        • 牛顿法&拟牛顿法
      • 梯度下降法
        • 梯度下降算法
      • 优化算法
    • 预处理
      • [1-1]正则表达式
      • [1-2]文本预处理
      • [1-3]词性
      • [1-4]语法分析
      • [1-6]文本分类
      • [1-7]网络爬取
      • 【备用】正则表达式
      • 7.re模块
      • 词典匹配
      • 分词
      • 子表达式
      • Todo
    • 主题模型
      • LDA
    • Deep Learning
      • 反向传播
      • 梯度消失&梯度爆炸
      • Batch Size
      • 1.DLbasis
      • 小概念
      • MLstrategy
      • CNN
      • RNN及其应用
      • 关于深度学习实践
      • 神经网络概述
      • Batch Normalization
      • Program CNN
      • Program D Lbasis
      • Program DN Nimprove
      • Program Neural Style Transfer
      • Summer DL
    • EM算法
    • GAN
      • Gans In Action Master
    • GNN
      • 搜广推之GNN
      • Representation Learning
        • Anomalydetection
        • Conclusion
        • Others
        • Papernotes
        • Recommadation
    • k近邻法
      • K近邻
    • Language Model
      • 语言模型解码采样策略
      • [1-1][语言模型]从N-gram模型讲起
      • [1-2][语言模型]NNLM(神经网络语言模型)
      • [1-3][语言模型]基于RNN的语言模型
      • [1-4][语言模型]用N-gram来做完形填空
      • [1-5][语言模型]用KenLM来做完形填空
    • Loss Function
      • 常用损失函数
      • Focal Loss
      • softmax+交叉熵
    • Machine Learning
      • [基础]概念
      • 待整合
      • 交叉验证
      • 无监督学习
      • 优缺点
      • ML Yearning
      • SVD
    • Statistics Math
      • 程序员的数学基础课
      • 数学基础
      • 统计&高数
      • 统计题目
      • 线性代数
      • 组合数学
      • Discrete Choice Model
      • Nested Choice Model
  • Course Note
    • 基于TensorFlow的机器学习速成课程
      • [Key ML Terminology](CourseNote/基于TensorFlow的机器学习速成课程/Key ML Terminology.md)
    • 集训营
      • 任务说明
      • 算法实践1.1模型构建
      • 算法实践1.2模型构建之集成模型
      • 算法实践2.1数据预处理
    • 李宏毅机器学习
      • 10DNN训练Tips
        • Chapter 18
      • 16无监督学习
        • Chapter 25
    • 贪心NLP
      • 贪心NLP笔记
    • Cs 224 N 2019
      • [A Simple But Tough To Beat Baseline For Sentence Embeddings](CourseNote/cs224n2019/A Simple but Tough-to-beat Baseline for Sentence Embeddings.md)
      • [Lecture 01 Introduction And Word Vectors](CourseNote/cs224n2019/Lecture 01 Introduction and Word Vectors.md)
      • [Lecture 02 Word Vectors 2 And Word Senses](CourseNote/cs224n2019/Lecture 02 Word Vectors 2 and Word Senses.md)
      • [Lecture 03 Word Window Classification Neural Networks And Matrix Calculus](CourseNote/cs224n2019/Lecture 03 Word Window Classification, Neural Networks, and Matrix Calculus.md)
      • [Lecture 04 Backpropagation And Computation Graphs](CourseNote/cs224n2019/Lecture 04 Backpropagation and Computation Graphs.md)
      • [Lecture 05 Linguistic Structure Dependency Parsing](CourseNote/cs224n2019/Lecture 05 Linguistic Structure Dependency Parsing.md)
      • [Lecture 06 The Probability Of A Sentence Recurrent Neural Networks And Language Models](CourseNote/cs224n2019/Lecture 06 The probability of a sentence Recurrent Neural Networks and Language Models.md)
      • Stanford NLP
    • Deep Learning Book Goodfellow
      • Books
        • Deep Learning Book Chapter Summaries Master
      • 提纲
      • C 5
      • C 6
      • [Part I Applied Math And Machine Learning Basics](CourseNote/Deep-Learning-Book-Goodfellow/Part I - Applied Math and Machine Learning basics.md)
    • Lihang
    • NLP实战高手课
      • 极客时间_NLP实战高手课
    • 工具&资料
    • 机器学习、深度学习面试知识点汇总
    • 七月kaggle课程
    • 算法工程师
    • 贪心科技机器学习必修知识点特训营
    • 唐宇迪机器学习
    • 语言及工具
    • AI技术内参
    • Suggestions
  • Data Related
    • 数据质量
      • 置信学习
    • 自然语言处理中的数据增广_车万翔
      • 自然语言处理中的数据增广
    • Mixup
    • 数据不均衡问题
    • 数据增强的方法
  • Knowledge Graph
    • Information Extraction
      • 联合抽取
        • PRGC
      • Code
        • BERT微调
      • NER
        • 阅读理解做NER
          • MRC
        • FLAT
        • Global Pointer
        • 命名实体识别NER
    • Keyword Extraction
      • 关键词抽取
    • 小米在知识表示学习的探索与实践
    • KG
  • Multi Task
    • EXT 5
      • Ex T 5
  • NLG
    • Dailogue
      • 比赛
        • 对话评估比赛
          • [simpread-DSTC10 开放领域对话评估比赛冠军方法总结](NLG/Dailogue/比赛/对话评估比赛/simpread-DSTC10 开放领域对话评估比赛冠军方法总结.md)
      • 任务型对话
        • DST
          • DST概述
        • NLG
          • NLG概述
        • NLU
          • NLU概述
        • 任务型对话概述
        • simpread-任务型对话系统预训练最新研究进展
      • 问答型对话
        • 检索式问答
          • 基于预训练模型的检索式对话系统
          • 检索式文本问答
        • 业界分享
          • 低资源场景下的知识图谱表示学习和问答_阿里_李杨
          • QQ浏览器搜索智能问答
        • 问答型对话系统概述
      • 闲聊型对话
        • 闲聊型对话系统概述
      • 业界分享
        • 人工智能与心理咨询
        • 腾讯多轮对话机器人
        • 微软小冰
        • 小布助手闲聊生成式算法
        • 美团智能客服实践_江会星
        • 去哪儿智能客服探索和实践
        • 实时语音对话场景下的算法实践_阿里_陈克寒
        • 智能语音交互中的无效query识别_小米_崔世起
        • UNIT智能对话
      • 主动对话
      • EVA
        • EVA分享
        • EVA模型
      • PLATO
      • RASA
    • Machine Translation
      • 业界分享
        • 爱奇艺台词翻译分享
      • Paper
        • Deep Encoder Shallow Decoder
    • RAGRelated
    • Text 2 SQL
      • M SQL
        • [M SQL 2](NLG/Text2SQL/M-SQL/M-SQL (2).md)
      • [Text2SQL Baseline解析](NLG/Text2SQL/Text2SQL Baseline解析.md)
      • Text 2 SQL
    • Text Summarization
      • [文本摘要][paper]CTRLSUM
      • 文本摘要
  • Pre Training
    • 业界分享
      • 超大语言模型与语言理解_黄民烈
        • 超大语言模型与语言理解
      • 大模型的加速算法_腾讯微信
        • 大模型的加速算法
      • 孟子轻量化预训练模型
      • 悟道文汇文图生成模型
      • 悟道文澜图文多模态大模型
      • 语义驱动可视化内容创造_微软
        • 语义驱动可视化内容创造
    • Base
      • Attention
      • Mask
        • NLP中的Mask
      • Position Encoding
        • 位置编码
    • BERT
      • ALBERT
      • Bert
        • Venv
          • Lib
            • Site Packages
              • idna-3.2.dist-info
                • LICENSE
              • Markdown-3.3.4.dist-info
                • LICENSE
              • Tensorflow
                • Include
                  • External
                    • Libjpeg Turbo
                      • LICENSE
                  • Unsupported
                    • Eigen
                      • CXX 11
                        • Src
                          • Tensor
              • Werkzeug
                • Debug
                  • Shared
                    • ICON LICENSE
        • CONTRIBUTING
        • Multilingual
      • Ro BER Ta
      • BERT
      • BERT面试问答
      • BERT源码解析
      • NSP BERT
    • BERT Flow
    • BERT Zip
      • Distilling The Knowledge In A Neural Network
      • TINYBERT
      • 模型压缩
    • CPM
    • CPT
      • 兼顾理解和生成的中文预训练模型CPT
    • ELECTRA
    • EL Mo
    • ERNIE系列语言模型
    • GPT
    • MBART
    • NEZHA
    • NLG Sum
      • [simpread-预训练时代下的文本生成|模型 & 技巧](Pre-training/NLGSum/simpread-预训练时代下的文本生成|模型 & 技巧.md)
    • Prompt
      • 预训练模型的提示学习方法_刘知远
        • 预训练模型的提示学习方法
    • T 5
      • Unified SKG
      • T 5
    • Transformer
    • Uni LM
    • XL Net
    • 预训练语言模型
    • BERT变种
  • Recsys
    • 多任务Multi-task&推荐
    • 推荐介绍
    • 推荐系统之召回与精排
      • 代码
        • Python
          • Recall
            • Deep Match Master
              • Docs
                • Source
                  • Examples
                  • FAQ
                  • Features
                  • History
                  • Model Methods
                  • Quick Start
    • 业界分享
      • 腾讯基于知识图谱长视频推荐
    • 召回
    • Sparrow Rec Sys
    • 深度学习推荐系统实战
    • 推荐模型
    • Deep FM
  • Search
    • 搜索
    • 业界分享
      • 爱奇艺搜索排序算法实践
      • 语义搜索技术和应用
    • 查询关键字理解
    • 搜索排序
    • BM 25
    • KDD21-淘宝搜索中语义向量检索技术
    • query理解
    • TFIDF
  • Self Supervised Learning
    • Contrastive Learning
      • 业界分享
        • 对比学习在微博内容表示的应用_张俊林
      • Paper
      • R Drop
      • Sim CSE
    • 自监督学习
  • Text Classification
    • [多标签分类(Multi-label Classification)](TextClassification/多标签分类(Multi-label Classification)/多标签分类(Multi-label Classification).md)
    • Fast Text
    • Text CNN
    • 文本分类
  • Text Matching
    • 文本匹配和多轮检索
    • CNN SIM
    • Word Embedding
      • Skip Gram
      • Glove
      • Word 2 Vec
    • 文本匹配概述
  • Tool
    • 埋点
    • 向量检索(Faiss等)
    • Bigdata
      • 大数据基础task1_创建虚拟机+熟悉linux
      • 任务链接
      • Mr
      • Task1参考答案
      • Task2参考答案
      • Task3参考答案
      • Task4参考答案
      • Task5参考答案
    • Docker
    • Elasticsearch
    • Keras
    • Numpy
    • Python
      • 可视化
        • Interactivegraphics
        • Matplotlib
        • Tkinter
        • Turtle
      • 数据类型
        • Datatype
      • python爬虫
        • Python Scraping Master
          • phantomjs-2.1.1-windows
        • Regularexp
        • Scrapying
        • Selenium
      • 代码优化
      • 一行代码
      • 用python进行语言检测
      • Debug
      • Exception
      • [Features Tricks](Tool/python/Features & Tricks.md)
      • Fileprocess
      • Format
      • Functional Programming
      • I Python
      • Magic
      • Math
      • Os
      • Others
      • Pandas
      • Python Datastructure
      • Python操作数据库
      • Streamlit
      • Time
    • Pytorch
      • Dive Into DL Py Torch
        • 02 Softmax And Classification
        • 03 Mlp
        • 04 Underfit Overfit
        • 05 Gradient Vanishing Exploding
        • 06 Text Preprocess
        • 07 Language Model
        • 08 Rnn Basics
        • 09 Machine Translation
        • 10 Attention Seq 2 Seq
        • 11 Transformer
        • 12 Cnn
        • 14 Batchnorm Resnet
        • 15 Convexoptim
        • 16 Gradientdescent
        • 17 Optim Advance
    • Spark
      • Pyspark
        • pyspark之填充缺失的时间数据
      • Spark
    • SQL
      • 数据库
      • Hive Sql
      • MySQL实战45讲
    • Tensor Flow
      • TensorFlow入门
  • Common
  • NLP知识体系
Powered by GitBook
On this page
  • 机器学习应用领域
  • 机器学习常用算法
  • 常用工具
  • 建模与问题解决流程
  • kaggle wiki
  • 经济金融相关问题
  • 排序与CTR预估问题
  • 自然语言处理类问题
  • 能源资源相关问题

Was this helpful?

  1. Course Note

七月kaggle课程

Previous机器学习、深度学习面试知识点汇总Next算法工程师

Last updated 2 years ago

Was this helpful?

机器学习应用领域

经济相关:股市、房价等 能源相关:产能预测、分配与合理利用 NLP相关:检索、分类、主题、相似度 互联网用户行为:CTR预测 销量预测:电商、连锁店、超市… 深度学习应用:图像内容理解 推荐系统相关:电商推荐 其他预测:气候、社交网络分析

机器学习常用算法

SVM-中小型数据集,NB-NLP大型数据集

常用工具

scikit-learn,NLP的gensim,Natural Language Toolkit

建模与问题解决流程

了解场景和目标 了解评估准则 认识数据:平衡否? 数据预处理(清洗,调权) 特征工程 模型调参 模型状态分析 模型融合

http://blog.csdn.net/han_xiaoyang/article/details/50469334 http://blog.csdn.net/han_xiaoyang/article/details/52910022

数据清洗

  • 不可信的样本丢掉

  • 缺省值极多的字段考虑不用

数据采样

  • 下/上采样

  • 保证样本均衡

工具

  • hive sql/spark sql

  • pandas:数据量少的时候

特征工程

特征处理

数值型 类别型 时间类:可以变成间隔型;或者组合型,如一周内登录网页多少次;饭点,非饭点、工作日,非工作日 文本型:n-gram,bag of words,TF-IDF 统计型:相对值 组合特征

参考 课程提供特征工程PDF http://scikit-learn.org/stable/modules/preprocessing.html http://scikit-learn.org/stable/modules/classes.html#modulesklearn.feature_extraction

特征选择 http://scikit-learn.org/stable/modules/feature_selection.html 过滤型:用得少 sklearn.feature_selection.SelectKBest

包裹型 sklearn.feature_selection.RFE

嵌入型 feature_selection.SelectFromModel Linear model,L1正则化

模型选择

sklearn cheetsheet提供的候选 课程案例经验 交叉验证(cross validation)

  • K折交叉验证(K-fold cross validation)

  • http://scikit-learn.org/stable/modules/cross_validation.html

模型参数选择

交叉验证(cross validation) http://scikit-learn.org/stable/modules/grid_search.html http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html

模型状态评估

模型状态

  • 过拟合(overfitting/high variance)

  • 欠拟合(underfitting/high bias)

Learning curve:学习曲线

plot learning curve:绘制学习曲线 https://www.zybuluo.com/hanxiaoyang/note/545131

模型融合

简单说来,我们信奉几条信条

群众的力量是伟大的,集体智慧是惊人的

  • Bagging:http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingClassifier.html

  • 随机森林/Random forest

站在巨人的肩膀上,能看得更远

  • 模型stacking:用多种predictor结果作为特征训练

一万小时定律

  • Adaboost:http://scikit-learn.org/stable/modules/classes.html#module-sklearn.ensemble

  • 逐步增强树/Gradient Boosting Tree

kaggle wiki

看

经济金融相关问题

解决高维数据分类/回归问题

  • 线性/非线性回归方程:如预测股票收盘价等,可以用前10天的数据预测当天的

  • 决策树

    • 优势:非黑盒;轻松去除无关attribute(Gain=0);Test起来很快(O(depth))

    • 劣势:只能线性分隔数据;贪婪算法(可能找不到最好的树)

  • 弱分类器的进化-Ensemble:Bagging,Random Forest,Boosting

  • 神经网络

kaggle竞赛:房价预测

https://www.kaggle.com/c/house-prices-advanced-regression-techniques

非标准数据的处理

  • 文本处理:记录每个单词的出现次数,记录每个单词的出现频率,用语义网络表示

  • 图片处理:用RGB点阵表示

  • 视频处理:

    • 音轨:声波;语音识别:文本

    • 视频:一堆图片:图片;图片识别:文本

排序与CTR预估问题

Online advertising and click through rate prediction

Types of online advertising

Retargeting – Using cookies, track if a user left a webpage without making a purchase and retarget the user with ads from that site Behavioral targeting – Data related to user’s online activity is collected from multiple websites, thus creating a detailed picture of the user’s interests to deliver more targeted advertising Contextual advertising – Display ads related to the content of the webpage

广告主,平台方,用户方

CPM (Cost-Per-Mille): is an inventory based pricing model. Is when the price is based on 1,000 impressions. 按照曝光 CPC (Cost-Per-Click): Is a performance-based metric.This means the Publisher only gets paid when (and if) a user clicks on an ad 按照点击 CPA (Cost Per Action): Best deal of all for Advertisers in terms of risk because they only pay for media when it results in a sale

Click-through rate (CTR)

Ratio of users who click on an ad to the number of total users who view the ad

CTR=Clicks / Impressions * 100%

Today, typical click through rate is less than 1%

In a pay-per-click setting, revenue can be maximized by choosing to display ads that have the maximum CTR, hence the problem of CTR Prediction.

Predict CTR – a Scalable Machine Learning success story

Predict conditional probability that the ad will be clicked by the user given the predictive features of ads Predictive features are: – Ad’s historical performance – Advertiser and ad content info – Publisher info – User Info (eg: search/ click history) Data set is high dimensional, sparse and skewed: – Hundreds of millions of online users – Millions of unique publisher pages to display ads – Millions of unique ads to display – Very few ads get clicked by users

Data set and features

Sample of the dataset used for the Display Advertising Challenge hosted by Kaggle: https://www.kaggle.com/c/criteo-display-ad-challenge/

链接: https://pan.baidu.com/s/1qYVhaJq 密码: 8fyn

Spark MLlib and the Pipeline API

MLlib pipeline for Click Through Rate Prediction

Step 1 - Parse Data into Spark SQL DataFrames

Step 2 – Feature Transformer using StringIndexer类别型转成0,1,2,3,...这种

Step 3 - Feature Transformer using One Hot Encoding

Step 4 – Feature Selector using Vector Assembler将特征列表转化成一个向量

Step 5 – Train a model using Estimator Logistic Regression

Apply the pipeline to make predictions

Random Forest/GBDT/FM/FFM/DNN

Some alternatives:

Use Hashed features instead of OHE Use Log loss evaluation or ROC to evaluate Logistic Regression Perform feature selection Use Naïve Bayes or other binary classification algorithms

Random Forest GBDT FM(factorization machine) 请参见比赛 https://www.kaggle.com/c/avazu-ctrprediction Rank 2nd Owen Zhang的解法: https://github.com/owenzhang/kaggle-avazu

要用格点搜索,交叉验证找到最好的参数

LibFM,LibMF,SVDfeature

FFM(field-aware factorization machine)

工业界数据与代码 数据可以在百度云下载到 链接: https://pan.baidu.com/s/1qYRM2cs 密码: twa7

Google Wide && Deep model 说明: https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html 代码: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py

FNN 说明: http://arxiv.org/pdf/1601.02376.pdf 代码: https://github.com/wnzhang/deep-ctr

About Data 需要大规模数据做实验/学习的同学,可以在Cretio实验数据下载1TB的CTR预估所需数据。 http://labs.criteo.com/downloads/download-terabyte-click-logs

自然语言处理类问题

NLP的基本思路与技法

NLTK

http://www.nltk.org/ NLTK是Python上著名的⾃然语⾔处理库

⾃带语料库,词性分类库 ⾃带分类,分词,等等功能 强⼤的社区⽀持 还有N多的简单版wrapper

文本处理流程

Preprocess——Tokenize——Make Featurees——ML

Tokenize:把长句⼦拆成有“意义”的⼩部件

英文:

import nltk
sentence = “hello, world"
tokens = nltk.word_tokenize(sentence)

中文:

启发式Heuristic

机器学习/统计方法:HMM,CRF

jieba,讯飞的,斯坦福corenlp

社交⽹络语⾔的tokenize,如@某⼈, 表情符号, URL, #话题符号,难以分隔

from nltk.tokenize import word_tokenize
tweet = 'RT @angelababy: love you baby! :D http://ah.love #168cm'
print(word_tokenize(tweet))
# ['RT', '@', 'angelababy', ':', 'love', 'you', 'baby', '!', ':',
# ’D', 'http', ':', '//ah.love', '#', '168cm']
import re
emoticons_str = r"""
(?:
[:=;] # 眼睛
[oO\-]? # ⿐子
[D\)\]\(\]/\\OpP] # 嘴
)"""
regex_str = [
emoticons_str,
r'<[^>]+>', # HTML tags
r'(?:@[\w_]+)', # @某⼈人
r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # 话题标签
r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+',
# URLs
r'(?:(?:\d+,?)+(?:\.?\d+)?)', # 数字
r"(?:[a-z][a-z'\-_]+[a-z])", # 含有 - 和 ‘ 的单词
r'(?:[\w_]+)', # 其他
r'(?:\S)' # 其他
]

正则表达式对照表 http://www.regexlab.com/zh/regref.htm

tokens_re = re.compile(r'('+'|'.join(regex_str)+')', re.VERBOSE | re.IGNORECASE)
emoticon_re = re.compile(r'^'+emoticons_str+'$', re.VERBOSE | re.IGNORECASE)
def tokenize(s):
return tokens_re.findall(s)
def preprocess(s, lowercase=False):
tokens = tokenize(s)
if lowercase:
tokens = [token if emoticon_re.search(token) else token.lower() for token in
tokens]
return tokens
tweet = 'RT @angelababy: love you baby! :D http://ah.love #168cm'
print(preprocess(tweet))
# ['RT', '@angelababy', ':', 'love', 'you', 'baby',
# ’!', ':D', 'http://ah.love', '#168cm']

纷繁复杂的词形

Inflection变化: walk => walking => walked 不影响词性

derivation 引申: nation (noun) => national (adjective) => nationalize (verb) 影响词性

词形归⼀化

Stemming 词⼲提取:⼀般来说,就是把不影响词性的inflection的⼩尾巴砍掉 walking 砍ing = walk walked 砍ed = walk

Lemmatization 词形归⼀:把各种类型的词的变形,都归为⼀个形式 went 归⼀ = go are 归⼀ = be

>>> from nltk.stem.porter import PorterStemmer
>>> porter_stemmer = PorterStemmer()
>>> porter_stemmer.stem(‘maximum’)
u’maximum’
>>> porter_stemmer.stem(‘presumably’)
u’presum’
>>> porter_stemmer.stem(‘multiply’)
u’multipli’
>>> porter_stemmer.stem(‘provision’)
u’provis’
>>> from nltk.stem import SnowballStemmer
>>> snowball_stemmer = SnowballStemmer(“english”)
>>> snowball_stemmer.stem(‘maximum’)
u’maximum’
>>> snowball_stemmer.stem(‘presumably’)
u’presum’
>>> from nltk.stem.lancaster import LancasterStemmer
>>> lancaster_stemmer = LancasterStemmer()
>>> lancaster_stemmer.stem(‘maximum’)
‘maxim’
>>> lancaster_stemmer.stem(‘presumably’)
‘presum’
>>> lancaster_stemmer.stem(‘presumably’)
‘presum’
>>> from nltk.stem.porter import PorterStemmer
>>> p = PorterStemmer()
>>> p.stem('went')
'went'
>>> p.stem('wenting')
'went'
>>> from nltk.stem import WordNetLemmatizer
>>> wordnet_lemmatizer = WordNetLemmatizer()
>>> wordnet_lemmatizer.lemmatize(‘dogs’)
u’dog’
>>> wordnet_lemmatizer.lemmatize(‘churches’)
u’church’
>>> wordnet_lemmatizer.lemmatize(‘aardwolves’)
u’aardwolf’
>>> wordnet_lemmatizer.lemmatize(‘abaci’)
u’abacus’
>>> wordnet_lemmatizer.lemmatize(‘hardrock’)
‘hardrock’

Lemma的⼩问题

Went v. go的过去式 n. 英⽂名:温特

NLTK更好地实现Lemma

# ⽊木有POS Tag,默认是NN 名词
>>> wordnet_lemmatizer.lemmatize(‘are’)
‘are’
>>> wordnet_lemmatizer.lemmatize(‘is’)
‘is’
# 加上POS Tag
>>> wordnet_lemmatizer.lemmatize(‘is’, pos=’v’)
u’be’
>>> wordnet_lemmatizer.lemmatize(‘are’, pos=’v’)
u’be’
>>> import nltk
>>> text = nltk.word_tokenize('what does the fox say')
>>> text
['what', 'does', 'the', 'fox', 'say']
>>> nltk.pos_tag(text)
[('what', 'WDT'), ('does', 'VBZ'), ('the', 'DT'), ('fox', 'NNS'), ('say', 'VBP')]

Stopwords

⼀千个HE有⼀千种指代,⼀千个THE有⼀千种指事 对于注重理解⽂本『意思』的应⽤场景来说,歧义太多 全体stopwords列表 http://www.ranks.nl/stopwords

NLTK去除stopwords ⾸先记得在console⾥⾯下载⼀下词库 或者 nltk.download(‘stopwords’)

from nltk.corpus import stopwords
# 先token⼀一把,得到⼀一个word_list
# ...
# 然后filter⼀一把
filtered_words =
[word for word in word_list if word not in stopwords.words('english')]

⼀条typical的⽂本预处理流⽔线

Raw_Text——Tokenize(——POS Tag)——Lemma/Stemming——stopwords——Word_List

原始文本得到有意义的单词列表

NLTK在NLP上的经典应⽤

情感分析

最简单的 sentiment dictionary,类似于关键词打分机制

⽐如:AFINN-111 http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6010

sentiment_dictionary = {}
for line in open('data/AFINN-111.txt')
word, score = line.split('\t')
sentiment_dictionary[word] = int(score)
# 把这个打分表记录在一个Dict上以后
# 跑⼀一遍整个句子,把对应的值相加
total_score = sum(sentiment_dictionary.get(word, 0) for word in words)
# 有值就是Dict中的值,没有就是0
# 于是你就得到了一个 sentiment score

配上ML的情感分析

from nltk.classify import NaiveBayesClassifier
# 随手造点训练集
s1 = 'this is a good book'
s2 = 'this is a awesome book'
s3 = 'this is a bad book'
s4 = 'this is a terrible book'
def preprocess(s):
# Func: 句子处理理
# 这里简单的用了split(), 把句子中每个单词分开
# 显然 还有更多的processing method可以用
return {word: True for word in s.lower().split()}
# return⻓长这样:
# {'this': True, 'is':True, 'a':True, 'good':True, 'book':True}
# 其中, 前⼀一个叫fname, 对应每个出现的文本单词;
# 后⼀一个叫fval, 指的是每个文本单词对应的值。
# 这里我们用最简单的True,来表示,这个词『出现在当前的句子中』的意义。
# 当然啦, 我们以后可以升级这个方程, 让它带有更加牛逼的fval, 比如 word2vec

# 把训练集给做成标准形式
training_data = [[preprocess(s1), 'pos'],
[preprocess(s2), 'pos'],
[preprocess(s3), 'neg'],
[preprocess(s4), 'neg']]
# 喂给model吃
model = NaiveBayesClassifier.train(training_data)
# 打出结果
print(model.classify(preprocess('this is a good book')))

文本相似度

⽤元素频率表⽰⽂本特征

余弦定理

Frequency 频率统计

import nltk
from nltk import FreqDist
# 做个词库先
corpus = 'this is my sentence ' \
'this is my life ' \
'this is the day'

# 随便便tokenize⼀一下
# 显然, 正如上文提到,
# 这里可以根据需要做任何的preprocessing:
# stopwords, lemma, stemming, etc.
tokens = nltk.word_tokenize(corpus)
print(tokens)
# 得到token好的word list
# ['this', 'is', 'my', 'sentence',
# 'this', 'is', 'my', 'life', 'this',
# 'is', 'the', 'day']

# 借用NLTK的FreqDist统计一下文字出现的频率
fdist = FreqDist(tokens)
# 它就类似于一个Dict
# 带上某个单词, 可以看到它在整个文章中出现的次数
print(fdist['is'])
# 3

# 好, 此刻, 我们可以把最常用的50个单词拿出来
standard_freq_vector = fdist.most_common(50)
size = len(standard_freq_vector)
print(standard_freq_vector)
# [('is', 3), ('this', 3), ('my', 2),
# ('the', 1), ('day', 1), ('sentence', 1),
# ('life', 1)

# Func: 按照出现频率大小, 记录下每一个单词的位置
def position_lookup(v):
    res = {}
    counter = 0
    for word in v:
    	res[word[0]] = counter
    	counter += 1
    return res
# 把标准的单词位置记录下来
standard_position_dict = position_lookup(standard_freq_vector)
print(standard_position_dict)
# 得到一个位置对照表
# {'is': 0, 'the': 3, 'day': 4, 'this': 1,
# 'sentence': 5, 'my': 2, 'life': 6}

# 这时, 如果我们有个新句子:
sentence = 'this is cool'
# 先新建一个跟我们的标准vector同样大小的向量
freq_vector = [0] * size
# 简单的Preprocessing
tokens = nltk.word_tokenize(sentence)
# 对于这个新句子里的每一个单词
for word in tokens:
    try:
        # 如果在我们的词库里出现过
        # 那么就在"标准位置"上+1
    	freq_vector[standard_position_dict[word]] += 1
    except KeyError:
        # 如果是个新词
        # 就pass掉
        continue
print(freq_vector)
# [1, 1, 0, 0, 0, 0, 0]
# 第一个位置代表 is, 出现了一次
# 第二个位置代表 this, 出现了一次
# 后面都木有

文本分类

TF-IDF

TF: Term Frequency, 衡量⼀个term在⽂档中出现得有多频繁。 TF(t) = (t出现在⽂档中的次数) / (⽂档中的term总数). IDF: Inverse Document Frequency, 衡量⼀个term有多重要。 有些词出现的很多,但是明显不是很有卵⽤。⽐如’is',’the‘,’and‘之类的。 为了平衡,我们把罕见的词的重要性(weight)搞⾼,把常见词的重要性搞低。 IDF(t) = log_e(⽂档总数 / 含有t的⽂档总数). TF-IDF = TF * IDF

from nltk.text import TextCollection
# 首先, 把所有的文档放到TextCollection类中。
# 这个类会自动帮你断句, 做统计, 做计算
corpus = TextCollection(['this is sentence one',
'this is sentence two',
'this is sentence three'])
# 直接就能算出tfidf
# (term: 一句话中的某个term, text: 这句话)
print(corpus.tf_idf('this', 'this is sentence four'))
# 0.444342
# 同理, 怎么得到一个标准大小的vector来表示所有的句子?
# 对于每个新句子
new_sentence = 'this is sentence five'
# 遍历一遍所有的vocabulary中的词:
for word in standard_vocab:
	print(corpus.tf_idf(word, new_sentence))
	# 我们会得到一个巨长(=所有vocab长度)的向量

接下来ML

可能的ML模型:SVM,LR,RF,MLP,LSTM,RNN,...

能源资源相关问题

1538445320110
1538446047789
1538447293961
1538620835230
1538621891813