实验目标:
创建实验样本,这些文本被切分成一系列词条集合,将标点符号从文本中去除。另外返回类别标签的集合,代表侮辱性和非侮辱性。
from numpy import *
def loadDataSet():
postingList = [[‘my‘, ‘dog‘, ‘has‘, ‘flea‘, ‘problems‘, ‘help‘, ‘please‘],
[‘maybe‘, ‘not‘, ‘take‘,‘him‘, ‘to‘, ‘dog‘, ‘park‘, ‘stupid‘],
[‘my‘, ‘dalmation‘, ‘is‘, ‘so‘, ‘cute‘, ‘I‘, ‘love‘, ‘him‘],
[‘stop‘, ‘posting‘, ‘stupid‘, ‘worthless‘, ‘garbage‘],
[‘mr‘, ‘licks‘, ‘ate‘, ‘my‘, ‘steak‘, ‘how‘, ‘to‘, ‘stop‘, ‘him‘],
[‘quit‘, ‘buying‘, ‘worthless‘, ‘dog‘, ‘food‘, ‘stupid‘]]
classVec = [0, 1, 0, 1, 0, 1] # 1 代表具有侮辱性, 0 表示没有侮辱性 类别标签的集合
return postingList, classVec
优化词条列表,形成不重复词的列表。
def createVocabList(dataSet):
vocabSet = set([]) # 创建一个空集
for document in dataSet:
vocabSet = vocabSet | set(document)
# 创建两个集合的并集 每篇文档返回的新词集合添加到该集合中
return list(vocabSet)
vocabSet = createVocabList(loadDataSet()[0])
train_classVec = loadDataSet()[1]
# 返回值类似[1,0,1,0,0,0,...]
def setOfWords2Vec(vocabList, inputSet):
returnVec = [0] * len(vocabList) #创建一个元素均为0的向量 与词汇表等长
for word in inputSet:
if word in vocabList: #遍历文档中所有单词,如果出现了词汇表中的单词,则将输出的文档向量中的对应值设为1
returnVec[vocabList.index(word)] = 1
else:
print("the word: %s is not in my Vocabulary!" % word)
return returnVec # 返回文档向量
trainMatrix = [setOfWords2Vec(vocabSet, loadDataSet()[0][0]),
setOfWords2Vec(vocabSet, loadDataSet()[0][1]),
setOfWords2Vec(vocabSet, loadDataSet()[0][2]),
setOfWords2Vec(vocabSet, loadDataSet()[0][3]),
setOfWords2Vec(vocabSet, loadDataSet()[0][4]),
setOfWords2Vec(vocabSet, loadDataSet()[0][5])]
训练算法:从词向量计算概率
伪代码如下:
计算每个类别中的文档数目
对每篇训练文档:
对每个类别:
如果词条出现在文档中 增加该词条的计数值(for 循环或者矩阵相加)
增加所有词条的计数值
对每个类别:
对每个词条:
该词条的数目/总词条数目=条件概率(P(词条|类别))
返回每个类别的条件概率(P(类别|文档的所有词条))
def trainNB0(trainMatrix, trainCategory):
numTrainDocs = len(trainMatrix) # 文件数
numWords = len(trainMatrix[0]) # 单词数
pAbusive = sum(trainCategory) / float(numTrainDocs)
p0Num = ones(numWords);
p1Num = ones(numWords) # change to ones() 初始化概率 初始化分子变量和分母变量
p0Denom = 2.0;
p1Denom = 2.0 # change to 2.0
for i in range(numTrainDocs): # 遍历训练集trainMatrix中的所有文档
if trainCategory[i] == 1: # 一旦某个词在某一文档中出现,则该词的个数+1 所有文档中,该文档的总词数也+1
p1Num += trainMatrix[i] # 向量相加
p1Denom += sum(trainMatrix[i])
else:
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
p1Vect = log(p1Num / p1Denom) # 对每个元素做除法 对每个元素除以该类别中的总词数
p0Vect = log(p0Num / p0Denom)
return p0Vect, p1Vect, pAbusive
result = trainNB0(trainMatrix, train_classVec)
p0Vect = result[0];
p1Vect = result[1];
pAbusive = result[2];
朴素贝叶斯分类函数
def classifyNB(vec2Classify, p0Vec, p1Vec,
pClass1): # 四个输入值 要分类的向量vec2Classify
# 使用trainNB0计算得到的三个概率 使用numpy的数组计算两个向量相乘的结果
# 比较类别的概率返回大概率对应的类别标签
# 做对数映射
p1 = sum(vec2Classify * p1Vec) + log(pClass1) # element-wise mult 元素相乘
p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
if p1 > p0:
return 1
else:
return 0
词袋模型中,每个单词可以出现多次,当遇到一个单词时,就会增加词向量中的对应值,而
不只将对一个数值设为 1。
其中,词集模型的 setOfWords2Vec( )被替换为 bagOfWords2Vec( ),详细代码如下:
def bagOfWords2VecMN(vocabList, inputSet):
returnVec = [0] * len(vocabList)
for word in inputSet:
if word in vocabList:
# 记录每个单词出现的次数,而不是出现与否
returnVec[vocabList.index(word)] += 1
return returnVec
test = [["It’s", "worthless", "to", "stop", "my", "dog", "eating", "food"],
["Please", "help", "me", "to", "solve", "this", "problem"],
["This", "dog", "is", "stupid", "But", "that", "one", "is", "so", "cute"]]
vec_1 = setOfWords2Vec(vocabSet, test[0]);
vec_2 = setOfWords2Vec(vocabSet, test[1]);
vec_3 = setOfWords2Vec(vocabSet, test[2]);
the word: It’s is not in my Vocabulary!
the word: eating is not in my Vocabulary!
the word: Please is not in my Vocabulary!
the word: me is not in my Vocabulary!
the word: solve is not in my Vocabulary!
the word: this is not in my Vocabulary!
the word: problem is not in my Vocabulary!
the word: This is not in my Vocabulary!
the word: But is not in my Vocabulary!
the word: that is not in my Vocabulary!
the word: one is not in my Vocabulary!
classifyNB(vec_1, p0Vect, p1Vect, pAbusive)
1
classifyNB(vec_2, p0Vect, p1Vect, pAbusive)
0
classifyNB(vec_3, p0Vect, p1Vect, pAbusive)
1
bag_vec_1 = bagOfWords2VecMN(vocabSet, test[0])
bag_vec_2 = bagOfWords2VecMN(vocabSet, test[1])
bag_vec_3 = bagOfWords2VecMN(vocabSet, test[2])
classifyNB(bag_vec_1, p0Vect, p1Vect, pAbusive)
1
classifyNB(bag_vec_2, p0Vect, p1Vect, pAbusive)
0
classifyNB(bag_vec_3, p0Vect, p1Vect, pAbusive)
1
词向量模型和词袋模型的预测结果都为1, 0, 1。即第一句话和第三句话预测结果均含有侮辱性。
从结果来看,第三句的预测是不太准确的,“This dog is so stupid,But that one is so cute”这句话转折后面才是真正的想表达的,但是在词向量模型和词袋模型中,它均被预测为1,原因是在训练集中,cute虽然在非侮辱性文档中,但stupid出现在侮辱性文档中。预测错误的根本性原因是训练集过小,导致模型拟合的不好,预测出现偏差。
上面的第 3 步骤,为什么要对分类器进行两个修改?
第一处修改:将所有词的出现数初始化为 1,并将分?初始化为2是一种平滑行为。在计算条件概率的乘积的时候,如果其中?个概率值为0,那么最后的乘积也为0。为降低这种影响,需要进行上述平滑行为。第二处修改:添加 log。计算 log 是为了避免累乘时概率值过小导致溢出,同时也能将概率乘法转化为对数加法。
试用词袋模型对实验要求 1 中的三句话进行分类,分析结果,并说明代码中做了哪些具体改动?
使用“词袋模型”(即:bagOfWords2VecMN),不仅记录文本中每个单词出现与否,还会统计出现的次数,具体改动returnVec[vocabList.index(word)] += 1
。
根据实验结果我们可以发现,两种模型的分类结果是一致的
原文:https://www.cnblogs.com/Dallas98/p/14623769.html