独热编码即 One-Hot 编码,又称一位有效编码。其方法是使用 N位状态寄存器来对 N个状态进行编码,每个状态都有它独立的寄存器位,并且在任意时候,其中只有一位有效。
One-Hot 编码是分类变量作为二进制向量的表示。(1) 将分类值映射到整数值。(2) 然后,每个整数值被表示为二进制向量,除了整数的索引之外,它都是零值,它被标记为1。是一种十分常用的类别处理手段,当特征是离散的,无序的,就可以通过one hot 进行特征数字化,比如一个特征有高、中、低三个值,通过独热编码,就可以分别编码为001,010,100。
一、one-hot 编码优缺点
优点:
(1) 解决了分类器不好处理离散数据 的问题。
a. 欧式空间。在回归,分类,聚类等机器学习算法中,特征之间距离计算 或 相似度计算是非常重要的,而我们常用的距离或相似度的计算都是在欧式空间的相似度计算,计算余弦相似性,基于的就是欧式空间。
b. one-hot 编码。使用 one-hot 编码,将离散特征的取值扩展到了欧式空间,离散特征的某个取值 就 对应欧式空间的某个点。将离散型特征使用 one-hot 编码,确实会让 特征之间的距离计算 更加合理。
(2) 在一定程度上也起到了 扩充特征 的作用。
缺点:
在文本特征表示上有些缺点就非常突出了。
(1) 它是一个词袋模型,不考虑 词与词之间的顺序(文本中词的顺序信息也是很重要的);
(2) 它 假设词与词相互独立(在大多数情况下,词与词是相互影响的);
(3) 它得到的 特征是离散稀疏 的 (这个问题最严重)。
ps:One-Hot在分类器变量中的应用
类似 SVM中,原本线性不可分的特征,经过project之后到高维之后变得可分了 GBDT处理高维稀疏矩阵的时候效果并不好,即使是低维的稀疏矩阵也未必比SVM好
import numpy as np
#分词过的语料
corpus=[
'这 是 第一个 文档',
'这是 第二个 文档',
'这是 最后 一个 文档'
]
#手动实现
words=[]
for corpu in corpus:
words.extends(corpu.split())
words=list(set(words))
#构建词表 编码
word_dict={word:index for index, word in enumerate(words)}
print(word_sict)
vocab_size=len(word_dict(
def get_one_hot(index):
获得一个one_hot编码
#全零矩阵
one_hot=[0 for _in range(vocab_size)]
#指定位置1
one_hot[index]=1
return np.array(one_hot)
#原始句子
print(corpus[0])
#转换成index
indexs=[word_dict[word] for word in corpus[0].split()]
#转换成one_hot
one_hot_np=np.array([get_one_hot(index) for index in indexs])
print(one_hot_np)
##Sklearn实现
from sklearn.preprocessing import LabelBinarizer
#初始化编码器
lb=LabelBinarizer()
lb.fit_transform(words)
print(lb.classes_)
#所有句子
sentence=corpus[0].split()
print(sentence)
one_hot_np2=lb.transform(sentence)
print(one_hot_np2)
#解码
print(lb.inverse_transform(one_hot_np2))
Q3:指定位置
Q1:.extend(),.split(),list(),set()
Q1.1:list(set())
Q2:wordL index for index
Q4:for xx in xx
Q6:师出同门,有很多for in 的构造
不用enumerate就不行吗?
range里边一定要加上len吗?
python中for循环输出(index,value)的两种方法
index索引 |
value索引值 |
方法一、利用enumerate() |
如果是实例数组应该是没有问题的吧
不能直接for i in range?
内部必须加个数字,外边套上个range?
方法二:
Q3:jion()以需求为导向,确定哪几个种类的函数能够满足这种操作
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
import seaborn as sns
import matplotlib.pyplot as plt
import jieba
import jieba,analyse
#独热表示从一个0向量开始,若单词出现在句子或文档中,则将向量相应的条目设置为1
#英文的处理和展示
corpus=['xxx'.'xxx']
one_hot_vectorizer=CountVectorizer(binary=True)
one_hot=one_hot_vectorizer.fit_transform(corpus).toarray()
sns.heatmap(one_hot, annot=True, char=False, yticklabels=['Sentence 1','Sentence 2'])
plt.show()
# 中文的处理和展示
# 获取停用词列表
def get_stopwords_list(stopwordfile):
stopwords = [line.strip() for line in open(stopwordfile, encoding='UTF-8').readlines()]
return stopwords
# 移除停用词
def movestopwords(sentence):
stopwords = get_stopwords_list('stopwords.txt') # 这里加载停用词的路径
santi_words = [x for x in sentence if len(x) > 1 and x not in stopwords]
return santi_words
# 语料
corpus = ["小明硕士毕业于中国科学院计算所,后在日本京都大学深造。",
"小王本科在清华大学,后在南京计算所工作和深造,后在日本早稻田大学深造",
"小李本科在清华大学,硕士毕业于中国科学院计算所,博士在南京大学"]
newcorpus = []
for str in corpus:
orgwordlist = jieba.lcut(str) # jieba分词
wordlist = movestopwords(orgwordlist) # 移除停用词
newword = " ".join(wordlist) # 按照语料库要求进行空格分隔
newcorpus.append(newword) # 按照语料库要求转换成列表
# newcorpus
# ['小明 硕士 毕业 中国科学院 计算所 日本京都大学 深造',
# '小王 本科 清华大学 南京 计算所 工作 深造 日本早稻田大学 深造',
# '小李 本科 清华大学 硕士 毕业 中国科学院 计算所 博士 南京大学']
one_hot_vectorizer = CountVectorizer(binary=True) # 创建词袋数据结构
one_hot = one_hot_vectorizer.fit_transform(newcorpus).toarray() # 转换语料,并矩阵化
# 下面为热词的输出结果
# one_hot_vectorizer.vocabulary_
# {'小明': 4, '硕士': 14, '毕业': 11, '中国科学院': 0, '计算所': 15, '日本京都大学': 8, '深造': 12, '小王': 6, '本科': 10, '清华大学': 13, '南京': 1, '工作': 7, '日本早稻田大学': 9, '小李': 5, '博士': 3, '南京大学': 2}
# one_hot_vectorizer.get_feature_names()
# ['中国科学院', '南京', '南京大学', '博士', '小明', '小李', '小王', '工作', '日本京都大学', '日本早稻田大学', '本科', '毕业', '深造', '清华大学', '硕士', '计算所']
# one_hot
# [[1 0 0 0 1 0 0 0 1 0 0 1 1 0 1 1]
# [0 1 0 0 0 0 1 1 0 1 1 0 1 1 0 1]
# [1 0 1 1 0 1 0 0 0 0 1 1 0 1 1 1]]
sns.set_style({'font.sans-serif': ['SimHei', 'Arial']})
sns.heatmap(one_hot, annot=True, cbar=False, xticklabels=one_hot_vectorizer.get_feature_names(),
yticklabels=['语句1', '语句2', '语句3'])
plt.show()
tfidf_vectorizer = TfidfVectorizer() # 创建词袋数据结构
tfidf = tfidf_vectorizer.fit_transform(newcorpus).toarray() # 转换语料,并矩阵化
# 下面为热词的输出结果
# tfidf_vectorizer.vocabulary_
# '小明': 4, '硕士': 14, '毕业': 11, '中国科学院': 0, '计算所': 15, '日本京都大学': 8, '深造': 12, '小王': 6, '本科': 10, '清华大学': 13, '南京': 1, '工作': 7, '日本早稻田大学': 9, '小李': 5, '博士': 3, '南京大学': 2}
# tfidf_vectorizer.get_feature_names()
# ['中国科学院', '南京', '南京大学', '博士', '小明', '小李', '小王', '工作', '日本京都大学', '日本早稻田大学', '本科', '毕业', '深造', '清华大学', '硕士', '计算所']
# tfidf
# [[0.35221512 0. 0. 0. 0.46312056 0. 0. 0. 0.46312056 0. 0. 0.35221512 0.35221512 0. 0.35221512 0.27352646]
# [0. 0.35761701 0. 0. 0. 0. 0.35761701 0.35761701 0. 0.35761701 0.27197695 0. 0.54395391 0.27197695 0. 0.21121437]
# [0.30443385 0. 0.40029393 0.40029393 0. 0.40029393 0. 0. 0. 0. 0.30443385 0.30443385 0. 0.30443385 0.30443385 0.23642005]]
sns.heatmap(tfidf, annot=True, cbar=False, xticklabels=tfidf_vectorizer.get_feature_names(),
yticklabels=['语句1', '语句2', '语句3'], vmin=0, vmax=1, cmap="YlGnBu")
plt.show()
Q1:CountVectorizer(binary=True)
.fit_transform(xx)
.toarray()
.heatmap(one_hot, xxx)
数据预处理中,fit(),transform(),fit_transform()
Q2:停用词的什么诡异操作?
xx 后面的 for 相当于做一步筛选