机器学习:基于逻辑回归和高斯贝叶斯对人口普查数据集的分类与预测

在这里插入图片描述

  • 机器学习:基于逻辑回归和高斯贝叶斯对人口普查数据集的分类与预测

作者:i阿极

作者简介:Python领域新星作者、多项比赛获奖者:博主个人首页

😊😊😊如果觉得文章不错或能帮助到你学习,可以点赞👍收藏📁评论📒+关注哦!👍👍👍

📜📜📜如果有小伙伴需要数据集和学习交流,文章下方有交流学习区!一起学习进步!💪


订阅专栏案例:机器学习
机器学习:基于逻辑回归对某银行客户违约预测分析
机器学习:学习k-近邻(KNN)模型建立、使用和评价
机器学习:基于支持向量机(SVM)进行人脸识别预测
决策树算法分析天气、周末和促销活动对销量的影响
机器学习:线性回归分析女性身高与体重之间的关系
机器学习:基于主成分分析(PCA)对数据降维
机器学习:基于朴素贝叶斯对花瓣花萼的宽度和长度分类预测
机器学习:学习KMeans算法,了解模型创建、使用模型及模型评价
机器学习:基于神经网络对用户评论情感分析预测
机器学习:朴素贝叶斯模型算法原理(含实战案例)
机器学习:逻辑回归模型算法原理(附案例实战)
机器学习:基于逻辑回归对优惠券使用情况预测分析
机器学习:基于逻辑回归对超市销售活动预测分析
机器学习:基于KNN对葡萄酒质量进行分类


1、数据说明

属性数据类型数值类型字段描述
1ID-String
2ageNumericInteger
3workclassCategoricalString
4fnlwgtContinuousInteger
5educationCategoricalString
6education_numNumericInteger
7marital_statusCategoricalString
8occupationCategoricalString
9relationshipCategoricalString
10raceCategoricalString
11genderCategoricalString
12capital_gainNumericInteger
13capital_lossNumericInteger
14hours_per_weekNumericInteger
15native_countryCategoricalString
16income_bracketCategoricalInteger

2、数据探索

导入模块

from plotly import __version__


import plotly.offline as offline
from plotly.offline import init_notebook_mode, iplot

init_notebook_mode(connected=True)
from plotly.graph_objs import *
import colorlover as cl
from plotly import tools
import pandas as pd
import numpy as np
colors = ['#e43620', '#f16d30','#d99a6c','#fed976', '#b3cb95', '#41bfb3','#229bac', 
'#256894', '#fed936', '#f36d30', '#b3cb25', '#f14d30','#49bfb5','#252bac',]

导入数据

data_train = pd.read_csv(r'/home/mw/income_census_train.csv')
data_test = pd.read_csv(r'/home/mw/income_census_test.csv')

数据集实例数与特征数,缺失值查看

print('原训练集shape:',data_train.shape)
print('原测试集shape:',data_test.shape)
print('原数据集实例数:',data_train.shape[0]+data_test.shape[0])

在这里插入图片描述

print('缺失值检测\n原训练集:',data_train.isnull().values.sum(), ',原测试集:',data_test.isnull().values.sum())

在这里插入图片描述

print('所有字段名:',data_train.columns)

在这里插入图片描述
各个特征的描述与相关总结

data_train.describe()

在这里插入图片描述
展示所有类型特征

data_train.describe(include=['O'])

在这里插入图片描述
查看8个categorial数据类型的属性唯一值

print('workclass: ',len(data_train['workclass'].unique()),'个\n',data_train['workclass'].unique())
print('education: ',len(data_train['education'].unique()),'个\n',data_train['education'].unique())
print('marital_status: ',len(data_train['marital_status'].unique()),'个\n',data_train['marital_status'].unique())
print('occupation: ',len(data_train['occupation'].unique()),'个\n',data_train['occupation'].unique())
print('relationship: ',len(data_train['relationship'].unique()),'个\n',data_train['relationship'].unique())
print('race: ',len(data_train['race'].unique()),'个\n',data_train['race'].unique())
print('gender: ',len(data_train['gender'].unique()),'个\n',data_train['gender'].unique())
print('native_country: ',len(data_train['native_country'].unique()),'个\n',data_train['native_country'].unique())

在这里插入图片描述

data = data_train.drop(['ID'],axis = 1)
data.head()

在这里插入图片描述

3、数据预处理

将oject数据转化为int类型

for feature in data.columns:
    if data[feature].dtype == 'object':
        data[feature] = pd.Categorical(data[feature]).codes # codes	这个分类的分类代码
data.head()

在这里插入图片描述

此时在查看数据每个字段的数值类型都是int类型。

data.info()

在这里插入图片描述

4、建立模型

选取特征数据与类别数据

from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X_df = data.iloc[:,data.columns != 'income_bracket']
y_df = data.iloc[:,data.columns == 'income_bracket']
X = np.array(X_df)
y = np.array(y_df)

标准化数据

scaler = StandardScaler()
X = scaler.fit_transform(X)

5、特征选取(Feature Selection)

from sklearn.tree import DecisionTreeClassifier
# from sklearn.decomposition import PCA

# fit an Extra Tree model to the data
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X, y)

# 显示每个属性的相对重要性得分
relval = tree.feature_importances_

trace = Bar(x = X_df.columns.tolist(), y = relval, text = [round(i,2) for i in relval], textposition= "outside", marker = dict(color = colors))
iplot(Figure(data = [trace], layout = Layout(title="特征重要性", width = 800, height = 400, yaxis = dict(range = [0,0.25]))))

from sklearn.feature_selection import RFE

# 使用决策树作为模型
lr = DecisionTreeClassifier()
names = X_df.columns.tolist()

# 将所有特征排序
selector = RFE(lr, n_features_to_select = 10)
selector.fit(X,y.ravel())

print("排序后的特征:",sorted(zip(map(lambda x:round(x,4), selector.ranking_), names)))

# 得到新的dataframe
X_df_new = X_df.iloc[:, selector.get_support(indices = False)]
X_df_new.columns
X_new = scaler.fit_transform(np.array(X_df_new)) # 数组化 + 标准化
X_train, X_test, y_train, y_test = train_test_split(X_new,y) # 切分
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn import metrics
from sklearn.metrics import confusion_matrix,roc_curve, auc, recall_score, classification_report

import matplotlib.pyplot as plt

import itertools

# 绘制混淆矩阵
def plot_confusion_matrix(cm, classes,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=0)
    plt.yticks(tick_marks, classes)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

6、逻辑回归(Logistic Regression)

# instance
lr = LogisticRegression()
# fit
lr_clf = lr.fit(X_train,y_train.ravel())
# predict
y_pred = lr_clf.predict(X_test)

print('LogisticRegression %s' % metrics.accuracy_score(y_test, y_pred))

在这里插入图片描述

cm = confusion_matrix(y_test, y_pred)

class_names = [0,1]
plt.figure()
plot_confusion_matrix(cm , classes=class_names, title='Confusion matrix')
plt.show()

在这里插入图片描述

7、高斯贝叶斯(Gaussian Naive Bayes)

gnb = GaussianNB()
gnb_clf = gnb.fit(X_train, y_train.ravel())
y_pred2 = gnb_clf.predict(X_test)

print('GaussianNB %s' % metrics.accuracy_score(y_test, y_pred2))

在这里插入图片描述

cm = confusion_matrix(y_test, y_pred2)

class_names = [0,1]
plt.figure()
plot_confusion_matrix(cm , classes=class_names, title='Confusion matrix')
plt.show()

在这里插入图片描述


📢文章下方有交流学习区!一起学习进步!💪💪💪
📢首发CSDN博客,创作不易,如果觉得文章不错,可以点赞👍收藏📁评论📒
📢你的支持和鼓励是我创作的动力❗❗❗

  • 48
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 82
    评论
首先,我们需要探索一下数据集。西瓜数据集 2.0 是一个经典的二分类数据集,其中包含 17 个样本和 8 个特征。我们可以使用 Python 中的 Pandas 库来读取数据集。 ```python import pandas as pd # 读取数据集 data = pd.read_csv('watermelon_2.csv') print(data.head()) ``` 接下来,我们需要对数据集进行预处理。首先,我们将数据集划分为训练集和测试集。我们可以使用 Scikit-learn 库中的 train_test_split 方法来实现。 ```python from sklearn.model_selection import train_test_split # 划分数据集 X = data.iloc[:, 1:8] y = data.iloc[:, 8] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) ``` 然后,我们可以使用朴素贝叶斯分类器来训练我们的模型。Scikit-learn 库中提供了多种朴素贝叶斯分类器,例如 GaussianNB、MultinomialNB 和 BernoulliNB。在这里,我们将使用 GaussianNB。 ```python from sklearn.naive_bayes import GaussianNB # 创建模型 model = GaussianNB() # 训练模型 model.fit(X_train, y_train) ``` 最后,我们可以使用测试集来评估我们的模型。 ```python # 预测分类 y_pred = model.predict(X_test) # 计算准确率 accuracy = (y_pred == y_test).sum() / len(y_test) print('准确率:', accuracy) ``` 完整代码如下: ```python import pandas as pd from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB # 读取数据集 data = pd.read_csv('watermelon_2.csv') # 划分数据集 X = data.iloc[:, 1:8] y = data.iloc[:, 8] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) # 创建模型 model = GaussianNB() # 训练模型 model.fit(X_train, y_train) # 预测分类 y_pred = model.predict(X_test) # 计算准确率 accuracy = (y_pred == y_test).sum() / len(y_test) print('准确率:', accuracy) ``` 执行代码后,我们可以得到如下结果: ``` 准确率: 0.6 ``` 因为样本数量比较少,所以准确率并不高。如果我们使用更多的数据或者其他的朴素贝叶斯分类器,可能会得到更好的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 82
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

i阿极

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值