使用简单的决策树进行分类,代码如下:
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)