当前位置: 首页 > news >正文

统计学习算法实现(01)——决策数

目录

1.数据集的创建

2.将上述表中文字转为数字编号 ,并转为numpy格式

3.熵与条件熵的计算

4.计算信息增益与信息增益比

5.特征选择

6.完整程序:


1.数据集的创建

import numpy as np
import pandas as pd

#数据集的创建
def create_data():
    datasets = [['青年', '否', '否', '一般', '否'],
               ['青年', '否', '否', '好', '否'],
               ['青年', '是', '否', '好', '是'],
               ['青年', '是', '是', '一般', '是'],
               ['青年', '否', '否', '一般', '否'],
               ['中年', '否', '否', '一般', '否'],
               ['中年', '否', '否', '好', '否'],
               ['中年', '是', '是', '好', '是'],
               ['中年', '否', '是', '非常好', '是'],
               ['中年', '否', '是', '非常好', '是'],
               ['老年', '否', '是', '非常好', '是'],
               ['老年', '否', '是', '好', '是'],
               ['老年', '是', '否', '好', '是'],
               ['老年', '是', '否', '非常好', '是'],
               ['老年', '否', '否', '一般', '否'],
               ]
    labels = [u'年龄', u'有工作', u'有自己的房子', u'信贷情况', u'类别']  #前缀u表示该字符串是unicode编码,防止因为编码问题,导致中文出现乱码
    # 返回数据集和每个维度的名称
    return datasets, labels

datasets, labels = create_data()  #调用数据集创建函数
train_data = pd.DataFrame(datasets, columns=labels)  # 创建DataFrame表

print(train_data)

输出:

 

注意:datasets对应的应该就是数据集,而通过pandas的DataFrame创建得就是一个表。 

 

2.将上述表中文字转为数字编号 ,并转为numpy格式

d = {'青年':1, '中年':2, '老年':3, '一般':1, '好':2, '非常好':3, '是':0, '否':1}
data = []  #定义空表用以存放编号后的数据表
for i in range(15):  #表中一共有15组数据
    tmp = []
    t = datasets[i]  #依次打印表中的各组数据,如:t=datasets[1] ---> ['青年', '否', '否', '好', '否']
    for tt in t:            #此处tt读取的分别是键:'青年', '否', '否', '好', '否'
        tmp.append(d[tt])   # 此步接如上,依次为上行代码的键按 d{} 中规则配对
    data.append(tmp)  # 注意:上步中的tmp中只存了一组编码后的数据。而data中依次存入各组数据构成数据表

data = np.array(data) #将表转为numpy的格式
print(data)
print(data.shape)  #查看数据形状

 输出:

 

3.熵与条件熵的计算

# 熵的计算
def entropy(y):
    N = len(y)
    count = []
    for value in set(y):
        count.append(len(y[y == value]))
    count = np.array(count)
    entro = -np.sum((count / N) * (np.log2(count / N)))
    return entro

# 条件熵的计算
def cond_entropy(X, y, cond):
    N = len(y)
    cond_X = X[:, cond]
    tmp_entro = []
    for val in set(cond_X):
        tmp_y = y[np.where(cond_X == val)]
        tmp_entro.append(len(tmp_y)/N * entropy(tmp_y))
    cond_entro = sum(tmp_entro)
    return cond_entro

#准备好计算熵与条件熵的数据
#data[:,:-1] 依次取每一组数据中除最后一位以外的数
#data[:, -1] 依次取每一组数据中的最后一位
X, y = data[:,:-1], data[:, -1]

Entropy = entropy(y) #计算熵
Cond_entropy = cond_entropy(X, y, 0) #计算条件熵
print("熵:",Entropy)
print("条件熵:",Cond_entropy)

 

 

4.计算信息增益与信息增益比

# 信息增益
def info_gain(X, y, cond):
    return entropy(y) - cond_entropy(X, y, cond)
# 信息增益比
def info_gain_ratio(X, y, cond):
    return (entropy(y) - cond_entropy(X, y, cond))/cond_entropy(X, y, cond)

# A1, A2, A3, A4 =》年龄 工作 房子 信贷
# 信息增益
gain_a1 = info_gain(X, y, 0)
print("年龄信息增益:",gain_a1)
gain_a2 = info_gain(X, y, 1)
gain_a3 = info_gain(X, y, 2)
gain_a4 = info_gain(X, y, 3)
print("工作信息增益:",gain_a2)
print("房子信息增益:",gain_a3)
print("信贷信息增益:",gain_a4)

 

5.特征选择

def best_split(X, y, method='info_gain'):
    """根据method指定的方法使用信息增益或信息增益比来计算各个维度的最大信息增益(比),返回特征的axis"""
    _, M = X.shape
    info_gains = []
    if method == 'info_gain':
        split = info_gain
    elif method == 'info_gain_ratio':
        split = info_gain_ratio
    else:
        print('No such method')
        return
    for i in range(M):
        tmp_gain = split(X, y, i)
        info_gains.append(tmp_gain)
    best_feature = np.argmax(info_gains)

    return best_feature

print(best_split(X,y)) #result--> 2

def majorityCnt(y):
    """当特征使用完时,返回类别数最多的类别"""
    unique, counts = np.unique(y, return_counts=True)
    max_idx = np.argmax(counts)
    return unique[max_idx]

print(majorityCnt(y))

输出:0.

6.完整程序:

import numpy as np
import pandas as pd
# import matplotlib.pyplot as plt
# #matplotlib inline
#
# from sklearn.datasets import load_iris
# from sklearn.model_selection import train_test_split
#
# from collections import Counter
# import math
# from math import log
#
# import pprint

#数据集的创建
def create_data():
    datasets = [['青年', '否', '否', '一般', '否'],
               ['青年', '否', '否', '好', '否'],
               ['青年', '是', '否', '好', '是'],
               ['青年', '是', '是', '一般', '是'],
               ['青年', '否', '否', '一般', '否'],
               ['中年', '否', '否', '一般', '否'],
               ['中年', '否', '否', '好', '否'],
               ['中年', '是', '是', '好', '是'],
               ['中年', '否', '是', '非常好', '是'],
               ['中年', '否', '是', '非常好', '是'],
               ['老年', '否', '是', '非常好', '是'],
               ['老年', '否', '是', '好', '是'],
               ['老年', '是', '否', '好', '是'],
               ['老年', '是', '否', '非常好', '是'],
               ['老年', '否', '否', '一般', '否'],
               ]
    labels = [u'年龄', u'有工作', u'有自己的房子', u'信贷情况', u'类别']  #前缀u表示该字符串是unicode编码,防止因为编码问题,导致中文出现乱码
    # 返回数据集和每个维度的名称
    return datasets, labels

# 熵的计算
def entropy(y):
    N = len(y)
    count = []
    for value in set(y):
        count.append(len(y[y == value]))
    count = np.array(count)
    entro = -np.sum((count / N) * (np.log2(count / N)))
    return entro

# 条件熵的计算
def cond_entropy(X, y, cond):
    N = len(y)
    cond_X = X[:, cond]
    tmp_entro = []
    for val in set(cond_X):
        tmp_y = y[np.where(cond_X == val)]
        tmp_entro.append(len(tmp_y)/N * entropy(tmp_y))
    cond_entro = sum(tmp_entro)
    return cond_entro


datasets, labels = create_data()  #调用数据集创建函数
train_data = pd.DataFrame(datasets, columns=labels)  # 创建DataFrame表

print(train_data)
print("-----------------如下将上述表中文字转为数字编号----------------")

"""
测试:
t = datasets[1]
d = {'青年':1, '中年':2, '老年':3, '一般':1, '好':2, '非常好':3, '是':0, '否':1}
print(t)
['青年', '否', '否', '好', '否']
print(d['青年'])
1
"""

d = {'青年':1, '中年':2, '老年':3, '一般':1, '好':2, '非常好':3, '是':0, '否':1}
data = []  #定义空表用以存放编号后的数据表
for i in range(15):  #表中一共有15组数据
    tmp = []
    t = datasets[i]  #依次打印表中的各组数据,如:t=datasets[1] ---> ['青年', '否', '否', '好', '否']
    for tt in t:            #此处tt读取的分别是键:'青年', '否', '否', '好', '否'
        tmp.append(d[tt])   # 此步接如上,依次为上行代码的键按 d{} 中规则配对
    data.append(tmp)  # 注意:上步中的tmp中只存了一组编码后的数据。而data中依次存入各组数据构成数据表

data = np.array(data) #将表转为numpy的格式
print(data)
print(data.shape)  #查看数据形状

#准备好计算熵与条件熵的数据
#data[:,:-1] 依次取每一组数据中除最后一位以外的数
#data[:, -1] 依次取每一组数据中的最后一位
X, y = data[:,:-1], data[:, -1]

Entropy = entropy(y) #计算熵
Cond_entropy = cond_entropy(X, y, 0) #计算条件熵
print("熵:",Entropy)
print("条件熵:",Cond_entropy)

# 信息增益
def info_gain(X, y, cond):
    return entropy(y) - cond_entropy(X, y, cond)
# 信息增益比
def info_gain_ratio(X, y, cond):
    return (entropy(y) - cond_entropy(X, y, cond))/cond_entropy(X, y, cond)

# A1, A2, A3, A4 =》年龄 工作 房子 信贷
# 信息增益
gain_a1 = info_gain(X, y, 0)
print("年龄信息增益:",gain_a1)
gain_a2 = info_gain(X, y, 1)
gain_a3 = info_gain(X, y, 2)
gain_a4 = info_gain(X, y, 3)
print("工作信息增益:",gain_a2)
print("房子信息增益:",gain_a3)
print("信贷信息增益:",gain_a4)


def best_split(X, y, method='info_gain'):
    """根据method指定的方法使用信息增益或信息增益比来计算各个维度的最大信息增益(比),返回特征的axis"""
    _, M = X.shape
    info_gains = []
    if method == 'info_gain':
        split = info_gain
    elif method == 'info_gain_ratio':
        split = info_gain_ratio
    else:
        print('No such method')
        return
    for i in range(M):
        tmp_gain = split(X, y, i)
        info_gains.append(tmp_gain)
    best_feature = np.argmax(info_gains)

    return best_feature

print(best_split(X,y)) #result--> 2

def majorityCnt(y):
    """当特征使用完时,返回类别数最多的类别"""
    unique, counts = np.unique(y, return_counts=True)
    max_idx = np.argmax(counts)
    return unique[max_idx]

print(majorityCnt(y))

(学习笔记,侵删。欢迎讨论呢) 

 

 

 

 

 

 

 

相关文章:

  • Nignx服务器,项目部署和Yapi,Swagger工具
  • Elasticsearch 集群搭建
  • spring cloud 快速上手系列 -> 03-消息队列 Stream -> 035-发送消息
  • 【SpringBoot2】SSMP整合综合案例(上)
  • 【JavaScript】JS开发中五个常用功能/案例(41-45)(牛客题解)
  • Go 语言 设计模式-抽象工厂模式
  • 全网没有之一的API 文档:Swagger
  • dubbo环境搭建ZooKeeper注册中心
  • (附源码)ssm教师工作量核算统计系统 毕业设计 162307
  • 欧拉函数算法的实现
  • Ubuntu 创建本地 Git 并与 Github(私有库) 交互(上传与下载)| 记录 | 踩坑
  • 6.0、软件测试——判定表法
  • 面试题~~
  • 容斥原理算法的实现
  • 【爬虫】Python使用动态IP,多线程,爬取uncomtrade的数据
  • 【Amaple教程】5. 插件
  • 4月23日世界读书日 网络营销论坛推荐《正在爆发的营销革命》
  • co.js - 让异步代码同步化
  • css选择器
  • Hibernate【inverse和cascade属性】知识要点
  • iOS小技巧之UIImagePickerController实现头像选择
  • magento 货币换算
  • Python socket服务器端、客户端传送信息
  • Stream流与Lambda表达式(三) 静态工厂类Collectors
  • v-if和v-for连用出现的问题
  • vue2.0项目引入element-ui
  • 初识 webpack
  • 初识MongoDB分片
  • 分布式任务队列Celery
  • 后端_MYSQL
  • 来,膜拜下android roadmap,强大的执行力
  • 类orAPI - 收藏集 - 掘金
  • 体验javascript之美-第五课 匿名函数自执行和闭包是一回事儿吗?
  • 微服务核心架构梳理
  • 一个JAVA程序员成长之路分享
  • 由插件封装引出的一丢丢思考
  • Linux权限管理(week1_day5)--技术流ken
  • ​iOS实时查看App运行日志
  • #mysql 8.0 踩坑日记
  • #vue3 实现前端下载excel文件模板功能
  • (1)(1.13) SiK无线电高级配置(五)
  • (1)bark-ml
  • (delphi11最新学习资料) Object Pascal 学习笔记---第8章第5节(封闭类和Final方法)
  • (附源码)spring boot智能服药提醒app 毕业设计 102151
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (机器学习-深度学习快速入门)第三章机器学习-第二节:机器学习模型之线性回归
  • (三)SvelteKit教程:layout 文件
  • (转)Unity3DUnity3D在android下调试
  • (转)为C# Windows服务添加安装程序
  • ***检测工具之RKHunter AIDE
  • **CI中自动类加载的用法总结
  • .form文件_SSM框架文件上传篇
  • .htaccess配置重写url引擎
  • .NET Standard、.NET Framework 、.NET Core三者的关系与区别?
  • .Net Winform开发笔记(一)