Kaggle -- Multi-Class Prediction of Obesity Risk

使用简单的决策树进行分类,代码如下:

import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split

df = pd.read_csv("train.csv")

df['Gender'] = df['Gender'].map({'Male': 1,'Female': 0})
print(df.loc[0])

# 肥胖转换
label = df['NObeyesdad'].values
label = np.unique(label)
print(label)

# 将标签转换为 one-hot 编码
encoder = OneHotEncoder(sparse=False)
one_hot_labels = encoder.fit_transform(label.reshape(-1, 1))

print(one_hot_labels)

la = {'Insufficient_Weight': 1,'Normal_Weight':2,'Obesity_Type_I':3,'Obesity_Type_II':4,'Obesity_Type_III':5,'Overweight_Level_I':6,'Overweight_Level_II':7}

df['NObeyesdad'] = df['NObeyesdad'].map(la)
print(df.loc[0])

df['family_history_with_overweight'] = df['family_history_with_overweight'].map({'yes':1,'no':2})
df['FAVC'] = df['FAVC'].map({'yes':1,'no':0})
df['SMOKE'] = df['SMOKE'].map({'yes':1,'no':0})

x_labels = ['Gender','Age','Height','Weight','family_history_with_overweight','FAVC','FCVC','NCP','SMOKE','CH2O','FAF','TUE']
y_labels = ['NObeyesdad']
x = df[x_labels]
y = df[y_labels]


x_train,x_test,y_train,y_test = train_test_split(x,y,shuffle=True,test_size=0.2)
print(x_train.size)

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

clf = DecisionTreeClassifier()
clf.fit(x_train,y_train)
y_pred = clf.predict(x_test)
acc = accuracy_score(y_test,y_pred)

print(f'决策树准确率{acc}')


pred = pd.read_csv("test.csv")
pred['Gender'] = pred['Gender'].map({'Male': 1,'Female': 0})
pred['family_history_with_overweight'] = pred['family_history_with_overweight'].map({'yes':1,'no':2})
pred['FAVC'] = pred['FAVC'].map({'yes':1,'no':2})
pred['SMOKE'] = pred['SMOKE'].map({'yes':1,'no':2})
pred['Weight'] = (pred['Weight'] - np.min(pred['Weight'])) / (np.max(pred['Weight'] - np.min(pred['Weight'])))
pred['Height'] = (pred['Height'] - np.min(pred['Height'])) / (np.max(pred['Height'] - np.min(pred['Height'])))


ans = pd.DataFrame()
ans['id'] = pred['id'].copy()
print(ans.info)

ans['NObeyesdad'] = clf.predict(pred[x_labels])
la_reversed = {v: k for k, v in la.items()}
ans['NObeyesdad'] = ans['NObeyesdad'].map(la_reversed)
print(ans['NObeyesdad'])

ans.to_csv("ans.csv",index=False)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值