跟着我们一起学 Python 30天课程-第28天-ML和数据科学II
今天,我探索了Scikit-Learn库,并创建了一个笔记本项目来介绍一些基础知识并尝试创建机器学习模型。Scikit-Learn是一个庞大的图书馆,需要大量的实践和探索才能掌握它。我遵循了一些教程和文章,试图构建一个简单的分类器模型,只是想弄清楚它是如何工作的。这对我来说有点吓人,但我决定在Jupyter Notebook中创建一个基本的工作流程,以便在决定深入学习ML和数据科学领域时可以将其用作参考。
Scikit-Learn是流行的机器学习Python库。Scikit-Learn可以处理提供给它的数据,并创建机器学习模型以学习数据中的模式并使用其工具进行预测。
为什么要学习Scikit?
- 建立在numpy和matplotlib库之上
- 拥有大量内置的机器学习模型
- 很多评估机器学习模型的方法
- 易于理解和精心设计的API
通常,机器学习可能有点不知所措,因为它涉及复杂的算法和统计数据来分析数据。Scikit-learn可以抽象化这种复杂性,并且可以轻松构建模型和对其进行训练,而无需对数学和统计学有太多了解。
这是我今天创建的笔记本。Github存储库的链接是https://github.com/arindamdawn/jupyter_notebooks
scikit-learn库的基础
本笔记本介绍了令人惊叹的scikit-learn python库的一些基础知识。该笔记本中列出了该库的一些重要用例,可用作参考的备忘单。
涉及的主题包括:
- 准备数据
- 为特定问题选择适当的算法/估计器
- 拟合模型/算法以使用它对数据进行预测
- 评估模型
- 改善模型
- 保存加载经过训练的模型
准备数据
该项目使用的数据将是可从https://www.kaggle.com/ronitf/heart-disease-uci获得的心脏病数据集
import pandas as pd
import numpy as np
heart_disease = pd.read_csv('data/heart.csv')
heart_disease.head()
age | sex | cp | trestbps | chol | fbs | restecg | thalach | exang | oldpeak | slope | ca | thal | target | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 63 | 1 | 3 | 145 | 233 | 1 | 0 | 150 | 0 | 2.3 | 0 | 0 | 1 | 1 |
1 | 37 | 1 | 2 | 130 | 250 | 0 | 1 | 187 | 0 | 3.5 | 0 | 0 | 2 | 1 |
2 | 41 | 0 | 1 | 130 | 204 | 0 | 0 | 172 | 0 | 1.4 | 2 | 0 | 2 | 1 |
3 | 56 | 1 | 1 | 120 | 236 | 0 | 1 | 178 | 0 | 0.8 | 2 | 0 | 2 | 1 |
4 | 57 | 0 | 0 | 120 | 354 | 0 | 1 | 163 | 1 | 0.6 | 2 | 0 | 2 | 1 |
目的是基于以上数据预测患者是否患有心脏病。的目标列中的判断结果,在其他列被称为特征
# Create Features Matrix (X)
X = heart_disease.drop('target', axis=1)
# Create Labels (Y)
y = heart_disease['target']
为问题选择合适的模型/估计量
对于此问题,我们将使用sklearn形式的RandomForestClassifier模型,该模型是分类机器学习模型。
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier()
clf.get_params() # lists the hyperparameters
{'bootstrap': True,
'ccp_alpha': 0.0,
'class_weight': None,
'criterion': 'gini',
'max_depth': None,
'max_features': 'auto',
'max_leaf_nodes': None,
'max_samples': None,
'min_impurity_decrease': 0.0,
'min_impurity_split': None,
'min_samples_leaf': 1,
'min_samples_split': 2,
'min_weight_fraction_leaf': 0.0,
'n_estimators': 100,
'n_jobs': None,
'oob_score': False,
'random_state': None,
'verbose': 0,
'warm_start': False}
使模型适合训练数据
在此步骤中,将模型分为训练和测试数据
# fit the model to data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2)
# Means 20% of the data will be used as testing data
clf.fit(X_train, y_train);
# make prediction
y_label = clf.predict(np.array([0,2,3,4]))
y_preds = clf.predict(X_test)
y_preds
array([1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0,
1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=int64)
y_test.head()
72 1
116 1
107 1
262 0
162 1
Name: target, dtype: int64
评估模型
在此步骤中,对训练数据和测试数据进行评估的模型
clf.score(X_train, y_train)
1.0
clf.score(X_test, y_test)
0.7704918032786885
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
print(classification_report(y_test, y_preds))
precision recall f1-score support
0 0.77 0.71 0.74 28
1 0.77 0.82 0.79 33
accuracy 0.77 61
macro avg 0.77 0.77 0.77 61
weighted avg 0.77 0.77 0.77 61
print(confusion_matrix(y_test, y_preds))
[[20 8]
[ 6 27]]
print(accuracy_score(y_test, y_preds))
0.7704918032786885
改善模型
此步骤涉及改进模型以获得更准确的结果
# Try different amount of n_estimators
np.random.seed(42)
for i in range(1, 100, 10):
print(f'Trying model with {i} estimators')
clf = RandomForestClassifier(n_estimators=i).fit(X_train, y_train)
print(f'Model accuracy on test set: {clf.score(X_test, y_test) * 100:.2f}%')
print('')
Trying model with 1 estimators
Model accuracy on test set: 72.13%
Trying model with 11 estimators
Model accuracy on test set: 83.61%
Trying model with 21 estimators
Model accuracy on test set: 78.69%
Trying model with 31 estimators
Model accuracy on test set: 78.69%
Trying model with 41 estimators
Model accuracy on test set: 75.41%
Trying model with 51 estimators
Model accuracy on test set: 75.41%
Trying model with 61 estimators
Model accuracy on test set: 75.41%
Trying model with 71 estimators
Model accuracy on test set: 73.77%
Trying model with 81 estimators
Model accuracy on test set: 73.77%
Trying model with 91 estimators
Model accuracy on test set: 75.41%
保存并加载模型
将使用Python中的pickle库保存模型
import pickle
pickle.dump(clf, open('random_forest_model_1.pkl', 'wb'))
#load the model
loaded_model = pickle.load(open('random_forest_model_1.pkl','rb'))
loaded_model.score(X_test, y_test)
0.7540983606557377
今天就这些。由于机器学习和数据科学本身就是一片海洋,因此我决定更详细地研究它,因为在更加熟悉其工具和概念之后,我将自己的经验作为博客文章和项目来分享。对于此挑战的其余两个部分,我想探索诸如使用Selenium进行Python自动化测试之类的领域,并在Python资源汇编上创建另一篇文章。
跟着我们一起学 Python 30天课程目录:
- 跟着我们一起学 Python 30天课程-第30天-免费Python资源
- 跟着我们一起学 Python 30天课程-第29天-自动化测试
- 跟着我们一起学 Python 30天课程-第28天-ML和数据科学II
- 跟着我们一起学 Python 30天课程-第27天-ML和数据科学I
- 跟着我们一起学 Python 30天课程-第26天-机器学习基础
- 跟着我们一起学 Python 30天课程-第25天-Web 开发进阶
- 跟着我们一起学 Python 30天课程-第24天-Web开发基础
- 跟着我们一起学 Python 30天课程-第23天-网页爬虫
- 跟着我们一起学 Python 30天课程-第22天-脚本额外功能Scripting Extras
- 跟着我们一起学 Python 30天课程-第21天-脚本编写基础
- 跟着我们一起学 Python 30天课程-第20天-调试和测试
- 跟着我们一起学 Python 30天课程-第19天-正则表达式
- 跟着我们一起学 Python 30天课程-第18天-文件I / O
- 跟着我们一起学 Python 30天课程-第17天-外部模块External Modules
- 跟着我们一起学 Python 30天课程-第16天-模块基础Module Basics
- 跟着我们一起学 Python 30天课程-第15天-生成器Generators
- 跟着我们一起学 Python 30天课程-第14天-错误处理Error Handling
- 跟着我们一起学 Python 30天课程-第13天-Decorators
- 跟着我们一起学 Python 30天课程-第12天-Lambda Expressions & Comprehensions
- 跟着我们一起学 Python 30天课程-第11天-函数编程Functional Programming基础
- 跟着我们一起学 Python 30天课程-第10天-OOP Missing Pieces
- 跟着我们一起学 Python 30天课程-第9天-OOP Pillars
- 跟着我们一起学 Python 30天课程-第8天-OOP基础知识
- 跟着我们一起学 Python 30天课程-第7天-开发环境搭建(Developer Environment)
- 跟着我们一起学 Python 30天课程-第6天-循环II和函数(Loops II & Functions)
- 跟着我们一起学 Python 30天课程-第5天-条件和循环I(Conditions & Loops I)
- 跟着我们一起学 Python 30天课程-第4天-数据类型III(Data Types III)
- 跟着我们一起学 Python 30天课程-第3天-数据类型II(Data Types II)
- 跟着我们一起学 Python 30天课程-第2天-数据类型I(Data Types I)
- 跟着我们一起学 Python 30天课程-第1天-简介
1. 本站资源转自互联网,源码资源分享仅供交流学习,下载后切勿用于商业用途,否则开发者追究责任与本站无关!
2. 本站使用「署名 4.0 国际」创作协议,可自由转载、引用,但需署名原版权作者且注明文章出处
3. 未登录无法下载,登录使用金币下载所有资源。
IT小站 » 跟着我们一起学 Python 30天课程-第28天-ML和数据科学II
常见问题FAQ
- 没有金币/金币不足 怎么办?
- 本站已开通每日签到送金币,每日签到赠送五枚金币,金币可累积。
- 所有资源普通会员都能下载吗?
- 本站所有资源普通会员都可以下载,需要消耗金币下载的白金会员资源,通过每日签到,即可获取免费金币,金币可累积使用。