机器学习期末实验报告

本文由用户“bluesea_666”分享发布 更新时间:2022-01-07 18:43:58 举报文档

以下为《机器学习期末实验报告》的无排版文字预览,完整格式请下载

下载前请仔细阅读文字预览以及下方图片预览。图片预览是什么样的,下载的文档就是什么样的。

 

     JISHOU UNIVERSITY

机器学习实验

报告

题 目:

文本类型分类模型



作 者:

杨某某



学 号:

***09



***:

软件工程2019级 5 班



专业年级:

陈某某



指导教师:

2021年12月26日



完成时间:







***制

目录

1. 问题描述 3

2. 设计目的 3

3. 实验需要的平台 3

4. 基本原理分析 4

a) 说明逻辑回归的基本原理; 4

b) 说明支持向某某的基本原理; 5

5. 实验过程阐述及实验结论 5

a) 实验过程 5

6. 分析支持向某某和逻辑回归算法的异同及优缺点 16

一、相同点 16

二、不同点 17

7. 结论:给出研究结论 17

问题描述

基于词袋模型的特征表示,以词为单位,数据集来源于京东买家评论。

/

图 1.1 数据集图片

2. 设计目的

文本分类的目的就是为了进行意图识别,如果我们只有两种意图需要被识别出来,对应的是2分类的问题。

可以想象,如果我们的聊天机器人有多个功能,那么我们需要分类的类别就有多个,这样就是一个多分类的问题。例如,如果希望聊天机器人能够播报当前的时间,那么我们就需要准备关于询问时间的语料,同时其目标值就是一个新的类别。在训练后,通过这个新的模型,判断出用户询问的是当前的时间这个类别,那么就返回当前的时间。

同理,如果还希望聊天机器人能够播报未来某一天的天气,那么这个机器人就还需要增加一个新的进行分类的意图,重新进行训练

3. 实验需要的平台

Jupyter Notebook:upyter Notebook 的本质是一个 Web 应用程序,便于创建和共享程序文档,支持实时代码,数学方程,可视化和 markdown。 用途包括:数据清理和转换,数值模拟,统计建模,机器学习等等。

pandas:pandas 是基于NumPy 的一种工具,该工具是为解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。

Numpy:NumPy(Numerical Python)是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix)),支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。

4. 基本原理分析

a) 说明逻辑回归的基本原理;

Logistic回归通过使用其固有的logistic函数估计概率,来衡量因变量(我们想要预测的标签)与一个或多个自变量(特征)之间的关系。然后这些概率必须二值化才能真地进行预测。这就是logistic函数的任务,也称为sigmoid函数。Sigmoid函数是一个S形曲线,它可以将任意实数值映射到介于0和1之间的值,但并不会取到0/1。然后使用阈值分类器将0和1之间的值转换为0或1。

/

图1.1 sigmoid函数

b) 说明支持向某某的基本原理;

支持向某某(support vector machines, SVM)是一种二分类模型,它的基本模型是定义在特征空间上的间隔最大的线性分类器,间隔最大使它有别于感知机;SVM还包括核技巧,这使它成为实质上的非线性分类器。SVM的的学习策略就是间隔最大化,可形式化为一个求解凸二次规划的问题,也等价于正则化的合页损失函数的最小化问题。SVM的的学习算法就是求解凸二次规划的最优化算法。/

图1.2 分离超平面

5. 实验过程阐述及实验结论

a) 实验过程

1.1 数据预处理,文档切分,文本分词,去停用词,文本特征提取,除去噪声,如:格式转换,去掉符号,整体规范化 遍历的读取一个文件下的每个文本。

import numpy as np

import re

import pandas as pd

# clean useless characters

'''

html_clean = ['& ldquo ;', '& hellip ;', '& rdquo ;', '& yen ;']

punctuation_replace = '[,。!?]+'

strange_num = ['①','②','③','④']

'''

punctuation_remove = '[:;……()『』《》【】~!"#$%&\'()*+,-./:;?@[\\]^_`{|}~]+'

def clean(sent):

sent = re.sub(r'ldquo', "", sent)

sent = re.sub(r'hellip', "", sent)

sent = re.sub(r'rdquo', "", sent)

sent = re.sub(r'yen', "", sent)

sent = re.sub(r'⑦', "7", sent)

sent = re.sub(r'(, ){2,}', "", sent)

sent = re.sub(r'(! ){2,}', "", sent) # delete too many!,?,。等

sent = re.sub(r'(? ){2,}', "", sent)

sent = re.sub(r'(。 ){2,}', "", sent)

sent = re.sub(punctuation_remove, "", sent) #delete punctuations

s = ' '.join(sent.split()) #delete additional space

return s

def sent_filter(l):

l_new = []

for s,k in enumerate(l):

if len(k) > 2:

l_new.append(k)

return l_new

# 这里是深度学习模式下的读取数据集

def dl_load_data_and_labels(good_data_file, bad_data_file, mid_data_file):

#load reviews and save them in the list

good_examples = list(open(good_data_file, "r", encoding='utf-8').readlines())

good_examples = [s.strip() for s in good_examples]

bad_examples = list(open(bad_data_file, "r", encoding='utf-8').readlines())

bad_examples = [s.strip() for s in bad_examples]

mid_examples = list(open(mid_data_file, "r", encoding='utf-8').readlines())

mid_examples = [s.strip() for s in mid_examples]

#Call the clean () and sent_filter () functions to process the comments, save them in the x_text list

good_examples = [clean(sent) for sent in good_examples]

bad_examples = [clean(sent) for sent in bad_examples]

mid_examples = [clean(sent) for sent in mid_examples]

good_examples = [i.strip() for i in good_examples]

bad_examples = [i.strip() for i in bad_examples]

mid_examples = [i.strip() for i in mid_examples]

good_examples = sent_filter(good_examples)

bad_examples = sent_filter(bad_examples)

mid_examples = sent_filter(mid_examples)

x_text = good_examples + bad_examples + mid_examples

#Add a label for each comment and save it in y

good_labels = [[1, 0, 0] for _ in good_examples]

bad_labels = [[0, 1, 0] for _ in bad_examples]

mid_labels = [[0, 0, 1] for _ in mid_examples]

y = np.concatenate([good_labels, bad_labels, mid_labels], 0)

return [x_text, y]

# 机器学习模式下的读取到的数据集

def ml_load_data_and_labels(good_data_file, bad_data_file, mid_data_file):

#load reviews and save them in the list

good_examples = list(open(good_data_file, "r", encoding='utf-8').readlines())

good_examples = [s.strip() for s in good_examples]

bad_examples = list(open(bad_data_file, "r", encoding='utf-8').readlines())

bad_examples = [s.strip() for s in bad_examples]

mid_examples = list(open(mid_data_file, "r", encoding='utf-8').readlines())

mid_examples = [s.strip() for s in mid_examples]

#Call the clean () and sent_filter () functions to process the comments, save them in the x_text list

good_examples = [clean(sent) for sent in good_examples]

bad_examples = [clean(sent) for sent in bad_examples]

mid_examples = [clean(sent) for sent in mid_examples]

good_examples = [i.strip() for i in good_examples]

bad_examples = [i.strip() for i in bad_examples]

mid_examples = [i.strip() for i in mid_examples]

good_examples = sent_filter(good_examples)

bad_examples = sent_filter(bad_examples)

mid_examples = sent_filter(mid_examples)

x_text = good_examples + bad_examples + mid_examples

#Add a label for each comment and save it in y

good_labels = [0 for _ in good_examples]

bad_labels = [1 for _ in bad_examples]

mid_labels = [2 for _ in mid_examples]

y = np.concatenate([good_labels, bad_labels, mid_labels], 0)

return [x_text, y]

# when you use tensorflow, you need to generate batches yourself, this function may helpe you

def batch_iter(data, batch_size, num_epochs, shuffle=True):

"""

Generates a batch iterator for a dataset.

"""

data = np.array(data)

data_size = len(data)

num_batches_per_epoch = int((len(data)-1)/batch_size) + 1

for epoch in range(num_epochs):

# Shuffle the data at each epoch

if shuffle:

shuffle_indices = np.random.permutation(np.arange(data_size))

shuffled_data = data[shuffle_indices]

else:

shuffled_data = data

for batch_num in range(num_batches_per_epoch):

start_index = batch_num * batch_size

end_index = min((batch_num + 1) * batch_size, data_size)

yield shuffled_data[start_index:end_index]

文本分类框架的最后一步是利用之前创建的特征训练一个分类器,关于这个最终的模型,机器学习中有很多模型可供选择。我们将使用不同的分类器来做文本分类,包括逻辑回归、多项式贝叶斯、伯努利贝叶斯、支持向某某、决策数、随机森林、KNN分类器

/

代码实现:

import sklearn

#机器学习算法模型

from sklearn.linear_model import LogisticRegression

from sklearn.tree import DecisionTreeClassifier

from sklearn.ensemble import RandomForestClassifier,BaggingClassifier,AdaBoostClassifier

from sklearn.svm import SVC,LinearSVC

from sklearn.naive_bayes import BernoulliNB,MultinomialNB,GaussianNB

from sklearn.neighbors import KNeighborsClassifier

# 特征提取

from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer

from sklearn.model_selection import train_test_split

#Pipeline 使用一系列 (key, value) 键值对来构建,其中 key 是你给这个步骤起的名字, value 是一个评估器对象:

from sklearn.pipeline import Pipeline

#准确率,精确率,召回率,f1

from sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score,classification_report

import xgboost as xgb

import joblib

# 读取数据

def readFile(path):

with open(path, 'r', errors='ignore') as file: # 文档中编码有些问题,所有用errors过滤错误

content = file.read()

return content

# 读取停用词

stwlist=[line.strip() for line in open('stopword.txt','r',encoding='utf-8').readlines()]

文本向量化工具

# 创建各类cv=CountVectorizer()和tf_idf工具

cv=CountVectorizer(min_df=3,

max_df=0.5,

ngram_range=(1,2),

stop_words = stwlist)

tdf=TfidfVectorizer()

#%%

# Count vectoriser --> LogisticRegression()

# 分类模型

#1.逻辑回归

lr=LogisticRegression()

# 贝叶斯

#2.多项式贝叶斯

mb=MultinomialNB()

gb=GaussianNB()

#3.伯努利 内容过长,仅展示头部和尾部部分文字预览,全文请查看图片预览。 聚类的特点,从参数选择、对偶问题求解及簇标定策略等方面分析并总结了影响支持向量聚类算法性能的关键原因及可行的改进方向,并在分析了核函数宽度q与簇的分裂/合并模式之间的关系之后,提出了通过二分查找法快速定位簇规模稳定时的q值来同时取得最优参数和最佳聚类结果。

(2)作为基于边界的聚类方法,能够对具有任意形状或不规则簇轮廓的数据集进行高效率的聚类是支持向量聚类算法相对于其他算法的一大优势。然而,这一优点也导致了支持向量聚类对簇轮廓比较敏感,受一些稀疏分布且干扰簇轮廓或数据分布结构的噪声数据影响较大。针对传统的支持向量聚类算法因未能有效界定噪声数据点和孤立点而允许噪声数据点参与对偶问题求解,降低了训练阶段的效率、影响了算法对数据分布结构探索的有效性等问题,本文首次从分布特点和簇隶属关系的角度给出了噪声数据的定义,并提出了一种无监督的噪声消除算法。利用该算法,可在数据进入对偶问题求解之前的输入空间快速地移除噪声数据,避免了一部分无意义的特征空间映射操作,降低了聚类算法对核矩阵的存储空间要求,并且可在不对数据集的分布结构或簇轮廓造成任何负面影响的前提下,为提升支持向量聚类算法的效率提供帮助。

[文章尾部最后500字内容到此结束,中间部分内容请查看底下的图片预览]

以上为《机器学习期末实验报告》的无排版文字预览,完整格式请下载

下载前请仔细阅读上面文字预览以及下方图片预览。图片预览是什么样的,下载的文档就是什么样的。

图片预览