机器学习——糖尿病预测

  • 实验目的

表格数据分类,糖尿病预测。

根据生活、饮食、教育、收入等属性,预测得1型、2型和不得糖尿病的概率。

  • 实验内容
  1. 获得数据
  2. 从数据探索和数据可视化中获得洞见
  3. 数据探索
  4. 数据预处理
  5. 划分数据并训练模型
  6. 微调模型
  • 编码

#获取数据

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]])

输出结果:

你可能感兴趣的:(机器学习,python,人工智能)