Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >KeyError:1 python ID3算法?

KeyError:1 python ID3算法?

提问于 2019-10-27 14:54:09
回答 0关注 0查看 380

我想实现一个有连续值的决策树ID3算法,第一次输出的最优特征值没有问题,迭代的话就会报错,求帮忙

代码语言:js
AI代码解释
复制
def load_data():
    # Only include the first 8 descriptive features and the target label
    data = pd.read_csv("heart.csv", usecols=[
                       "age", "sex", "cp", "trestbps", "chol", "fbs", "restecg", "thalach", "target"]) #filter the features we are interested in
    return data


def describe_partitions(ps):
    for target, p in sorted(ps.items(), key=lambda k: k[0]):
        print(f"{target}\t{p.shape[0]}")
    print("")

# more frequently,higher entropy
def entropy(data):
    counts = data["target"].value_counts()
    # print(counts)
    """
        Similar to doing the following manually:
            counts = {}
            for val in data["target"]:
                counts[val] = counts.get(val, 0) + 1
    """
    total = data["target"].shape[0]
    # print(data)
    sum = 0.
    for count in counts:
        p = count/total
        sum += p * math.log(p) 
    return - sum


def partitions(data, feature, thresholds):
    def find_threshold(feature, val):
        # Guaranteed to find a threshold somewhere between min and max
        for t in reversed(thresholds[feature]):
            if val >= t:
                return t
        raise Exception("Unexpected return without threshold")

    features = data.columns
    ps = {}
    for j, val in enumerate(data[feature]):
        # Treat categorical and continuous feature values differently
        if feature in thresholds:
            val = find_threshold(feature, val)
        p = ps.get(val, pd.DataFrame(columns=features))
        ps[val] = p.append(data.loc[j, features])
    return ps


def create_thresholds(data, names, nstds=3):
    # Assume the data is normally-distributed
    thresholds = {}
    for feature in names:
        col = data[feature]
        mint, maxt = np.min(col), np.max(col)
        mean, stddev = np.mean(col), np.std(col)
        ts = [mint]
        for n in range(-nstds - 1, nstds):
            t = round(n * stddev + mean)
            if t >= mint and t <= maxt:
                ts.append(t)
        thresholds[feature] = ts
    return thresholds


def gain(data, H, feature, thresholds):
    ps = partitions(data, feature, thresholds)
    # describe_partitions(ps)
    sum = 0.
    for p in ps.values():
        if feature in p.columns:
            sum += (p.shape[0] / data.shape[0]) * entropy(p)
    return H - sum

# return if the target_attr have only one value in data set
def unique(data):
    value_count=data['target'].value_counts()
    total=data['target'].shape[0]
    if value_count[0]==total:
        return data['target'].values[0],1
    else:
        return False,0

# return maximum occurence of a unique value of target_attr in data
def common_value(data):
    c=data['target'].value_counts()
    sc=sorted(c.iteritems(), key=operator.itemgetter(1), reverse=True)
    return sc[0][0]

def best_attribute(data,attr,thresholds):
    Gains=np.zeros(len(attr))
    h=entropy(data)
    for i,feature in enumerate(data.columns[attr]):
        Gains[i]=gain(data,h,feature,thresholds)
    best=data.columns[np.argmax(Gains)+1] #'+1' is because the first column is 'index',so the attribute features start at 1
    return best,np.argmax(Gains)+1

def ID3(data,attr,thresholds):
    tree={}
    record,truth=unique(data)

    # all examples have same value of attribute in the data
    if truth!=0:
        tree = record
    # no more attributes to be considered
    elif len(attr)==0:
        # return tree with single node root labelled with most common value of target_attr in the data 
        tree=common_value(data) 
    else:
        A,Anumber=best_attribute(data,attr,thresholds) 
        # print(A)
        tree={A:{}}
        values=data[A].values
        attr.pop()
        for vi in values:
            #add subtree to tree
            tree[A][vi]=ID3(data[data[A] == vi].drop(A, axis=1),attr,thresholds)
        # print(examples)
    return tree
    
    def main():
    data = load_data()
    # Split into training and test data sets
    train_data, test_data = train_test_split(data, test_size=0.25)
    # Compute the total entropy for the full data set with respect to the target label
    H = entropy(train_data)
    print(f"Total Entropy: {H}")
    # Generate threshold values for the continuous value descriptive features
    thresholds = create_thresholds(
        train_data, ["age", "chol", "trestbps", "thalach"], nstds=3)
    # Compute the level=0 information gain when partitioned on each descriptive feature
    IG = np.zeros(8)
    for i, feature in enumerate(data.columns[:8]):
        IG[i] = gain(train_data, H, feature, thresholds)
    
    # Print the best one (at the level=0)
    print(IG)
    A=data.columns[np.argmax(IG)]
    print("Best IG feature: "+A)
    l=list(range(1,9))
    # print(train_data)
    DecisionTree=ID3(train_data,l,thresholds)
    print(DecisionTree)

回答 4

军哥

发布于 2016-03-02 06:09:34

经测试,可以连接的,请确保本地网络是否存在问题.

我测试连接的图片如下(本地网络重庆电信):

telnet 56d6516144f13.sh.cdb.myqcloud.com 3403

拾叁

发布于 2016-08-04 05:33:24

朋友,你数据库那一栏没有填写哦,自然链接不上去,请到后台建立一个数据库

merlini

发布于 2016-03-02 06:25:49

请问我用SQLyog怎么填可以连接上去?

和开发者交流更多问题细节吧,去 写回答
相关文章
navicat连接MySQL失败,cmd也不能登录MySQL_远程连接mysql
出现 Client does not support authentication protocol requested by server…的解决方案
全栈程序员站长
2022/11/04
5.7K0
解决:Navicat远程连接mysql失败「建议收藏」
sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
全栈程序员站长
2022/11/19
3K0
MySQL远程连接失败(错误码:2003)
1. 环境信息 服务器系统:Centos 7.6 服务器MySQL版本:8.0.25 本地系统:Windows10 本地客户端:navicat 15 2. 本地客户端连接远程服务器MySQL报错 3.
框架师
2021/08/05
17.7K2
mysql远程连接数据库 权限_sql远程连接数据库失败
我们在刚学习MySQL数据库时一般都是连接localhost然后登录root用户创建数据库进行操作,那么问题来了,如何通过其他主机来访问自己的数据库呢?
全栈程序员站长
2022/11/08
14K0
mysql远程连接数据库 权限_sql远程连接数据库失败
pycharm远程部署_远程连接服务器失败
File → Settings → Project:XXX →Python Interpreter
全栈程序员站长
2022/09/25
22.5K0
pycharm远程部署_远程连接服务器失败
SecureCRT远程连接Ubuntu失败解决案例
使用VirtualBox搭建一个Ubuntu14.04的系统环境,为了省去主机与虚拟机直接互相直接一直切换的频繁操作,所以想到了使用SecureCRT连接,但是出现了连接问题,问题如下图:
用户8705036
2021/06/08
2.2K0
MySQL开启远程连接
在Linux上面装完MySQL 或 MariaDB,远程登录报错 Host is not allowed to connect to this MySQL server,是因为没有开启远程登陆。解决方法如下:
摘繁华
2021/12/23
7.6K0
Navicat连接MySQL失败1251
错误提示:1251-Client does not support authentication protocol requested by server; consider upgrading MySQL client
全栈程序员站长
2022/11/04
6.7K0
MySQL 开启远程连接
update user set Host = '%' where Host = 'localhost' and User='root';
IT工作者
2022/01/05
7K0
mysql 允许远程连接
use mysql;进入mysql库 grant all privileges on \*.\* to root@'%'identified by 'ur passwd'; 设置允许远程连接
buiu
2021/10/18
6.5K0
mysql 开启远程连接
1.netstat -anpl | grep mysql 查看mysql的端口 如果没有请确定你的mysql已经成功安装好并运行 ps aux | grep mysql 查看mysql进程
用户5166330
2019/10/12
5.8K0
MySql如何远程连接
通过select*from mysql.user 查看用户及权限这个是可以查看权限的。。
斯文的程序
2019/11/07
7.2K0
mysql 开启远程连接
第一句中”%”表示任何主机都可以远程登录到该服务器上访问。如果要限制只有某台机器可以访问,将其换成相应的IP即可,如:
上山打老虎了
2022/06/14
4.5K0
linux mysql 远程连接
±----------±-----±------------------------------------------+ | host | user | password | ±----------±-----±------------------------------------------+ | localhost | root | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | | node01 | root | | | 127.0.0.1 | root | | | localhost | | | | node01 | | | ±----------±-----±------------------------------------------+
云缓缓知我意
2021/04/15
14.9K0
mysql 开启远程连接
第一句中”%”表示任何主机都可以远程登录到该服务器上访问。如果要限制只有某台机器可以访问,将其换成相应的IP即可,如:
子润先生
2021/06/28
6.5K0
MySQL开启远程连接
前言 学习MySQL重新整理以前非MK的记载 ---- 描述 没有开启的话连接数据库报错:2003-can't connect to MYSQL ---- 方法/步骤 第一步 远程连接上Linux系统,确保Linux系统已经安装上了MySQL数据库。登陆数据库。 mysql -u$user -p $pwd 第二步 创建用户用来远程连接 GRANT ALL PRIVILEGES ON *.* TO '$username'@'%' IDENTIFIED BY '$password' WITH G
AlicFeng
2018/06/08
7K0
mysql 开启 远程连接
安装好 mysql 后,一般会使用客户端连接(必须Navcat)。本文描述了怎么设置远程连接。
张云飞Vir
2020/03/16
7K0
Navicat 远程连接 MySQL
相信大家都有在远程服务器上进行开发吧,其中 MySQL 的使用率应该也会挺高,如果使用 Navicat 等可视化工具来操作远程数据库不失为一种很好的选择,避免了在命令行写 SQL 语句的操作。下面简单介绍一下 Navicat 连接远程数据库的操作。
希希里之海
2018/08/30
26.2K10
Navicat 远程连接 MySQL
解决:navicat for mysql连接失败[通俗易懂]
1、问题描述: 在navicat for mysql 连接mysql 8.0.23时,出现如下错误。
全栈程序员站长
2022/11/04
9.5K0
远程连接Mysql连接报错
这个问题是因为在数据库服务器中的mysql数据库中的user的表中没有权限(也可以说没有用户),下面将记录我遇到问题的过程及解决的方法。
半条命专刊
2020/09/14
5K0

相似问题

远程连接MYSQL失败,提示1045如何解决?

31.9K

远程连接失败咋办??

4628

mysql无法远程连接?

1532

云主机安装mysql,本地可以操作,远程访问失败,连接超时?

1311

求助,远程桌面连接失败?

098
相关问答用户
擅长3个领域
腾讯 | 技术专家擅长2个领域
腾讯云TDP | 高级后端开发工程师擅长3个领域
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档