表格数据分类,糖尿病预测。
根据生活、饮食、教育、收入等属性,预测得1型、2型和不得糖尿病的概率。
#获取数据
import pandas as pd
diabetes = pd.read_csv('糖尿病预测.csv')
print('dataset shape {}'.format(diabetes.shape))
diabetes.head()
结果:
#输出前五行数据
from sklearn.model_selection import train_test_split
diabetes.info()
x_train, x_test, y_train, y_test = train_test_split(
diabetes.loc[:, diabetes.columns != 'Diabetes_012'],
diabetes['Diabetes_012'], stratify=diabetes['Diabetes_012'],
random_state=66)
#数据相关性
corr = diabetes.corr()
Corr
#绘图
import seaborn as sns
import matplotlib.pyplot as plt
sns.countplot(diabetes['Diabetes_012'], label="Count")
plt.show("糖尿病数据处理图片")
输出图片:
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=9)
knn.fit(x_train, y_train)
print("Accuracy of K-NN classifier on training set: {:.2f}".format(knn.score(x_train, y_train)))
print("Accuracy of K-NN classifier on test set: {:.2f}".format(knn.score(x_test, y_test)))
输出结果:
# 数据探索
%matplotlib inline
import matplotlib.pyplot as plt
diabetes.hist(bins=50, figsize=(20,15))
plt.show()
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
y_pred = knn.predict(x_test)
print(classification_report(y_pred, y_test))
confusion = confusion_matrix(y_pred, y_test)
df_cm = pd.DataFrame(confusion)
plt.figure()
sns.heatmap(df_cm, annot=True)
plt.savefig('confusion_matrix')
plt.show()
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()
lr.fit(x_train,y_train)
predictions = lr.predict(x_test)
lr.predict_proba([[0,0,0,30,1,0,0,1,1,0,0,1,0,30,0,13,1,0,11,5,3]])
输出结果: