Python实现分类算法

前言:出自于学校课程数据挖掘与分析布置的实验小作业,案例经典,代码注释较全,供大家参考 。
题目:
现有西瓜挑选数据文件:dataset.txt,编程实现朴素贝叶斯算法,并判断有如下特征的瓜是否好瓜:青绿,稍蜷,浊响,清晰,凹陷,硬滑 。
实验数据如下:
要求:
1、自行采用一种语言编程实现算法(注意:计算条件概率、判别分类等核心算法需自己编程实现)2、用课堂例子进行正确性检验3、用户界面友好,要考虑到输入输出4、分析结果,说明理论分析到数值计算的注意问题
实现
import sys# readfile, remove_place, get_conditions, NoneException都是自己封装的方法from FirstExp.kam import readfile, remove_place, get_conditions, NoneExceptionimport easygui as gui'''这里捕获一下异常,文本中的数据如果有空格、空隙则需要处理文本信息处理数据数据中的空格,导致的Bug是因为取值的方法不对,parameters["好瓜"] => parameters[col[columns - 2]] 则不会引起这样的问题'''try:# 读取txt文件df = readfile()txt = df.data# 获取列数columns = txt.shape[1]# 算好瓜与坏瓜的概率col = txt.columns[1:columns]# 好瓜、不好的瓜分别是多少parameters = txt[col]# 总体为好瓜的个数good_num_y = parameters["好瓜"].value_counts()["是"]# 总体不是好瓜的个数good_num_n = parameters["好瓜"].value_counts()["否"]# 是好瓜的概率p_y = parameters["好瓜"].value_counts(normalize=True)["是"]# 不是好瓜的概率p_n = parameters["好瓜"].value_counts(normalize=True)["否"]# 获取用户输入条件,如果用户选进行条件选择时,点击了“cancel”,或直接关闭选择框# 则会引起异常,给出异常原因try:conditions = get_conditions(txt)except NoneException as e:print(e)sys.exit(0)# 判断条件是否符合要求j = 0# 临时变量yes = 1no = 1# 使用双层遍历获取各个属性下指定类别的概率for i in col[: columns - 2]:while j < len(conditions):# 满足各个条件为好瓜的数量condition_num_y = parameters[(parameters["好瓜"] == "是") & (parameters[i] == conditions[j])].shape[0]# 满足各个条件不是好瓜的数量condition_num_n = parameters[(parameters["好瓜"] == "否") & (parameters[i] == conditions[j])].shape[0]# 使用累乘获取是好瓜的概率yes = yes * (condition_num_y / good_num_y)# 使用累乘获取不是好瓜的概率no = no * (condition_num_n / good_num_n)j = j + 1# 这里必须添加break,内层循环只需要循环一次break# 结果是好瓜的概率yes = yes * p_y# 结果不是好瓜的概率no = no * p_nyes_msg = "此瓜是好瓜的概率为:" + str(yes) + "\n此瓜不是好瓜的概率为:" + str(no) + "\n所以条件为:" + ",".join(conditions) + "是好瓜"no_msg = "此瓜是好瓜的概率为:" + str(yes) + "\n此瓜不是好瓜的概率为:" + str(no) + "\n所以条件为:" + ",".join(conditions) + "不是好瓜"if yes > no:gui.msgbox(msg=yes_msg, title="结果", ok_button="确认")else:gui.msgbox(msg=no_msg, title="结果", ok_button="确认")except KeyError:print(remove_place(df.path))

Python实现分类算法

文章插图
kam.py
"""用户选择文件,并以矩阵的形式返回主要思想还是使用pandas库下的read函数"""# Author: KamTang# Date:November28, 2021import osimport timeimport pandas as pdimport numpy as npimport tkinter as tkfrom tkinter import filedialogimport easygui as guiclass KamData(object):"""自定义返回类Parameters----------data : 数据部分path : 路径"""def __init__(self, data, path):self.data = http://www.kingceram.com/post/dataself.path = pathdef readfile():"""读取文件param select_path:文件路径return: 根据文件类型,返回数据"""# 开启选择文件窗口root = tk.Tk()root.withdraw()# 获取选择好的文件select_path = filedialog.askopenfilename()# 获取文件类型(后缀)file_type = os.path.splitext(select_path)[1]if file_type == ".csv" or file_type == ".txt":data = http://www.kingceram.com/post/pd.read_csv(select_path, encoding="utf-8")res = KamData(data, select_path)return reselif file_type == ".excel":return pd.read_excel(select_path)else:return "该文件类型暂时无法读取"def remove_place(path):"""去除文件中的空格Parameters----------path : 选择的文件路劲Returns-------new_path : 重新生成的文件路径,基于你所选择的文件位置"""# 获取文件路径out_path = path.rsplit("/", 1)[0]# 获取文件类型file_type = os.path.splitext(path)[1]f = open(path, 'r+', encoding='utf-8')new_f = open(out_path + "/" + time.strftime('%Y%m%d', time.localtime(time.time())) + file_type, 'w',encoding='utf8')for line in f.readlines():new_str = line.replace(" ", "")new_f.write(new_str)f.close()new_f.close()# 使用字符串拼接获取新文件路径new_path = out_path + "/" + time.strftime('%Y%m%d', time.localtime(time.time())) + file_typeprint("由于选择的文件数据存在脏数据,现已重新为您生成与您选择文件数据一致的文件,路径为:")return new_path# 自定义异常class NoneException(Exception):passdef get_conditions(read_file):""":param read_file: 读取的文件:return: 用户选择的条件"""# 获取列数columns = read_file.shape[1]# 算好瓜与坏瓜的概率col = read_file.columns[1:columns]# 好瓜、不好的瓜分别是多少parameters = read_file[col]conditions = {}# 使用字典的形式存入各个类别for i in col[: columns - 2]:conditions[i] = np.unique(parameters[i].values)# 获取所有元素下标index = conditions.keys()# 存入用户选择的类别temp = []j = 0for i in index:while j