Introdução ao Machine Learning com Python e Scikit-Learn (2023)

Introduction to Machine Learning with Python and Scikit-Learn (1)

Olá, %username%!

Meu nome é Alex. Eu lido com aprendizado de máquina e análise de gráficos da web (principalmente em teoria). Também trabalho no desenvolvimento de produtos de Big Data para uma das operadoras móveis da Rússia. É a primeira vez que escrevo um post, então, por favor, não me julgue com muita severidade.

Hoje em dia, muitas pessoas querem desenvolver algoritmos eficientes e participar de competições de aprendizado de máquina. Então eles vêm até mim e perguntam: “Por onde começar?”. Há algum tempo, liderei o desenvolvimento de ferramentas de Big Data para análise de mídia e redes sociais em uma das instituições do Governo da Federação Russa. Ainda tenho alguma documentação que minha equipe usou e gostaria de compartilhá-la com você. Supõe-se que o leitor tenha um bom conhecimento de matemática e aprendizado de máquina (minha equipe consistia principalmente de MIPT (Instituto de Física e Tecnologia de Moscou) e graduados da Escola de Análise de Dados).

Na verdade, foi a introduçãociência de dados. Esta ciência tornou-se bastante popular recentemente. Competições em aprendizado de máquina são cada vez mais realizadas (por exemplo,Kaggle,estudouIT), e seu orçamento costuma ser bastante considerável.

As ferramentas mais comuns para um Cientista de Dados hoje sãoRePitão. Cada ferramenta tem seus prós e contras, mas o Python venceu recentemente em todos os aspectos (isso é apenasNa minha humilde opinião, eu uso R e Python). Isso aconteceu depois que apareceu um muito bem documentadoScikit-Learnbiblioteca que contém um grande número de algoritmos de aprendizado de máquina.

Observe que vamos nos concentrar nos algoritmos de aprendizado de máquina no artigo. Geralmente é melhor realizar a análise dos dados primários por meio dopandaspacote que é bastante simples de lidar por conta própria. Então, vamos nos concentrar na implementação. Para definitividade, assumimos que existe uma matriz objeto-característica na entrada e ela é armazenada em um*.csvarquivo.

Carregamento de Dados

Em primeiro lugar, os dados devem ser carregados na memória, para que possamos trabalhar com eles. A biblioteca Scikit-Learn usa arrays NumPy em sua implementação, então usaremos NumPy para carregar arquivos *.csv. Vamos baixar um dos conjuntos de dados doRepositório de aprendizado de máquina UCI.

import numpy as npimport urllib# url with dataseturl = "http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"# baixe o arquivoraw_data = urllib.urlopen(url)# carrega o arquivo CSV como um numpy matrixdataset = np.loadtxt(raw_data, delimiter=",")# separa os dados dos atributos de destinoX = dataset[:,0:8]y = dataset[: ,8]

Vamos trabalhar com este conjunto de dados em todos os exemplos, ou seja, com oxmatriz objeto-recurso e valores doyvariável alvo.

Normalização de dados

Todos nós sabemos bem que a maioria dos métodos de gradiente (nos quais se baseiam quase todos os algoritmos de aprendizado de máquina) é altamente sensível ao escalonamento de dados. Portanto, antes de executar um algoritmo, devemos executarnormalização, ou o chamadoestandardização. A normalização envolve a substituição de características nominais, de modo que cada uma delas fique na faixa de 0 a 1. Já a padronização envolve o pré-processamento dos dados, após o qual cada característica tem uma dispersão média de 0 e 1. A biblioteca Scikit-Learn fornece funções prontas para isso:

from sklearn import preprocessing# normalizar os atributos de dadosnormalized_X = preprocessing.normalize(X)# padronizar os atributos de dadosstandardized_X = preprocessing.scale(X)

Seleção de recursos

Não é segredo que o mais importante na resolução de uma tarefa é a capacidade de escolher ou até mesmo criar recursos corretamente. É chamadoSeleção de recursoseEngenharia de recursos. Embora a Engenharia do Futuro seja um processo bastante criativo e dependa mais da intuição e do conhecimento especializado, existem muitos algoritmos prontos para Seleção de Recursos. Os algoritmos de árvore permitem calcular a informatividade dos recursos.

from sklearn importmetricfrom sklearn.ensemble import ExtraTreesClassifiermodel = ExtraTreesClassifier()model.fit(X, y)# exibe a importância relativa de cada atributoprint(model.feature_importances_)

Todos os outros métodos se baseiam na busca efetiva de subconjuntos de features para encontrar o melhor subconjunto, no qual o modelo desenvolvido apresenta a melhor qualidade. Um desses algoritmos de pesquisa é o algoritmo de eliminação de recursos recursivos, que também está disponível na biblioteca Scikit-Learn.

from sklearn.feature_selection import RFEfrom sklearn.linear_model import LogisticRegressionmodel = LogisticRegression()# crie o modelo RFE e selecione 3 atributosrfe = RFE(model, 3)rfe = rfe.fit(X, y)# resuma a seleção dos atributosprint(rfe .support_)print(rfe.ranking_)

Desenvolvimento de Algoritmo

Como eu disse, o Scikit-Learn implementou todos os algoritmos básicos de aprendizado de máquina. Vamos dar uma olhada em alguns deles.

Regressão Logística

Mais frequentemente usado para resolver tarefas de classificação (binário), mas a classificação multiclasse (o chamado método um contra todos) também é permitida. A vantagem deste algoritmo é que existe a probabilidade de pertencer a uma classe para cada objeto na saída.

from sklearn importmetricfrom sklearn.linear_model import LogisticRegressionmodel = LogisticRegression()model.fit(X, y)print(model)# faça previsõesexpected = ypredicted = model.predict(X)# resumir o ajuste do modeloprint(metrics.classification_report(esperado , previsto))print(metrics.confusion_matrix(esperado, previsto))

Baías ingénuas

É também um dos algoritmos de aprendizado de máquina mais conhecidos, cuja principal tarefa é restaurar a densidade da distribuição de dados da amostra de treinamento. Este método geralmente oferece boa qualidade em problemas de classificação multiclasse.

de sklearn importar métricas de sklearn.naive_bayes importar GaussianNBmodel = GaussianNB()model.fit(X, y)print(model)# fazer previsõesexpected = ypredicted = model.predict(X)# resumir o ajuste do modeloprint(metrics.classification_report(esperado , previsto))print(metrics.confusion_matrix(esperado, previsto))

k-vizinhos mais próximos

OkNN (k-vizinhos mais próximos)método é freqüentemente usado como parte de um algoritmo de classificação mais complexo. Por exemplo, podemos usar sua estimativa como característica de um objeto. Às vezes, um simples kNN fornece grande qualidade em recursos bem escolhidos. Quando os parâmetros (principalmente métricas) são bem definidos, o algoritmo geralmente oferece boa qualidade em problemas de regressão.

from sklearn importmetricfrom sklearn.neighbors import KNeighborsClassifier# ajusta um modelo de k vizinhos mais próximos ao modelo de dados = KNeighborsClassifier()model.fit(X, y)print(model)# faz previsõesesperadas = yprevisto = model.predict(X)# resumir o ajuste do modeloprint(metrics.classification_report(esperado, previsto))print(metrics.confusion_matrix(esperado, previsto))

Árvores de decisão

Árvores de classificação e regressão (CART)são freqüentemente usados ​​em problemas, nos quais os objetos possuem características de categoria e usados ​​para problemas de regressão e classificação. As árvores são muito adequadas para classificação multiclasse.

from sklearn importmetricfrom sklearn.tree import DecisionTreeClassifier# ajustar um modelo CART ao modelo de dados = DecisionTreeClassifier()model.fit(X, y)print(model)# fazer previsõesesperadas = yprevisto = model.predict(X)# resumir o ajuste de o modeloprint(metrics.classification_report(esperado, previsto))print(metrics.confusion_matrix(esperado, previsto))

Máquinas de vetores de suporte

SVM (Support Vector Machines)é um dos algoritmos de aprendizado de máquina mais populares, usado principalmente para o problema de classificação. Assim como a regressão logística, o SVM permite a classificação multiclasse com a ajuda do método um contra todos.

from sklearn importmetricfrom sklearn.svm import SVC# ajustar um modelo SVM ao modelo de dados = SVC()model.fit(X, y)print(model)# fazer previsõesesperadas = yprevisto = model.predict(X)# resumir o ajuste de o modeloprint(metrics.classification_report(esperado, previsto))print(metrics.confusion_matrix(esperado, previsto))

Além dos algoritmos de classificação e regressão, o Scikit-Learn possui um grande número de algoritmos mais complexos, incluindo clustering, e também implementou técnicas para criar composições de algoritmos, incluindoEnsacamentoeImpulsionando.

Como otimizar parâmetros de algoritmo

Uma das etapas mais difíceis na criação de algoritmos realmente eficientes é a escolha dos parâmetros corretos. Geralmente é mais fácil com a experiência, mas de uma forma ou de outra, temos que fazer a busca. Felizmente, o Scikit-Learn fornece muitas funções implementadas para esse propósito.

Como exemplo, vejamos a seleção do parâmetro de regularização, em que vários valores são buscados sucessivamente:

import numpy as npfrom sklearn.linear_model import Ridgefrom sklearn.grid_search import GridSearchCV# prepare um intervalo de valores alfa para testalphas = np.array([1,0.1,0.01,0.001,0.0001,0])# crie e ajuste um modelo de regressão de crista , testando cada alphamodel = Ridge()grid = GridSearchCV(estimator=model, param_grid=dict(alpha=alphas))grid.fit(X, y)print(grid)# resume os resultados da grade searchprint(grid.best_score_) print(grid.best_estimator_.alpha)

Às vezes é mais eficiente selecionar aleatoriamente um parâmetro de um determinado intervalo, estimar a qualidade do algoritmo para esse parâmetro e escolher o melhor.

import numpy as npfrom scipy.stats import uniform as sp_randfrom sklearn.linear_model import Ridgefrom sklearn.grid_search import RandomizedSearchCV# prepare uma distribuição uniforme para amostrar o alpha parameterparam_grid = {'alpha': sp_rand()}# crie e ajuste um modelo de regressão de ridge , testando valores alfa aleatóriosmodel = Ridge()rsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)rsearch.fit(X, y)print(rsearch)# resumir os resultados do parâmetro aleatório searchprint(rsearch.best_score_ )print(rsearch.best_estimator_.alpha)

Revisamos todo o processo de trabalho com a biblioteca Scikit-Learn, exceto para enviar os resultados de volta para um arquivo. Oferecer a você fazer isso como um exercício, já que a vantagem do Python (e da biblioteca Scikit-Learn), em comparação com o R, é sua excelente documentação.

Nos próximos artigos, consideraremos outros problemas em detalhes. Em particular, vamos tocar em uma coisa tão importante comoEngenharia de recursos.

Eu realmente espero que este material ajude os Cientistas de Dados novatos a começar a resolver problemas de aprendizado de máquina na prática o mais rápido possível.

Para finalizar, gostaria de desejar sucesso e paciência para aqueles que estão apenas começando a participar de competições de aprendizado de máquina!

FAQs

Is scikit-learn used for machine learning in Python? ›

Scikit-learn is an open source data analysis library, and the gold standard for Machine Learning (ML) in the Python ecosystem. Key concepts and features include: Algorithmic decision-making methods, including: Classification: identifying and categorizing data based on patterns.

What is scikit-learn in Python used for? ›

Scikit-Learn, also known as sklearn is a python library to implement machine learning models and statistical modelling. Through scikit-learn, we can implement various machine learning models for regression, classification, clustering, and statistical tools for analyzing these models.

Is scikit-learn good for machine learning? ›

Scikit-learn is mostly used in machine learning applications. The neural network is used indirectly by TensorFlow. In practice, Scikit-learn is utilized with a wide range of models. It provides under-the-hood specialization optimization, making it easier to compare neural network models and TensorFlow models.

What is the difference between scikit-learn and sklearn? ›

scikit-learn and sklearn both refer to the same package however, there are a couple of things you need to be aware of. Firstly, you can install the package by using either of scikit-learn or sklearn identifiers however, it is recommended to install scikit-learn through pip using the skikit -learn identifier.

Do people still use scikit-learn? ›

Scikit-learn is an indispensable part of the Python machine learning toolkit at JPMorgan. It is very widely used across all parts of the bank for classification, predictive analytics, and very many other machine learning tasks.

Which Python should I learn for machine learning? ›

PyTorch is an open-source machine learning Python library based on the C programming language framework, Torch. It is mainly used in ML applications that involve natural language processing or computer vision. PyTorch is known for being exceptionally fast at executing large, dense data sets and graphs.

Is scikit-learn good for beginners? ›

If you are learning machine learning then Scikit-learn is probably the best library to start with. Its simplicity means that it is fairly easy to pick up and by learning how to use it you will also gain a good grasp of the key steps in a typical machine learning workflow.

What language is scikit-learn written in? ›

How many algorithms are there in scikit-learn? ›

As we discussed before, Machine Learning has 2 types of algorithms i.e Supervised and Unsupervised. Let's see some of the most popular offered by Scikit learn in supervised algorithms: Support Vector Machines. Nearest Neighbors.

Do companies use scikit-learn? ›

Scikit-learn is a well-documented and easy-to-use machine learning package leveraged by top tech companies like JP Morgan Chase, Spotify, Hugging Face, and many others.

Which companies use Scikit? ›

Customers of scikit-learn
CustomersEmployee RangeCity
Cuelogic Technologies100 - 249Pune
Arabesque100 - 249London
JAVATPOINT100 - 249Noida
Avinton50 - 99Yokohama
6 more rows

Do data scientists use scikit-learn? ›

A machine learning (ML) library for the Python programming language, Scikit-learn has a large number of algorithms that can be readily deployed by programmers and data scientists in machine learning models.

What is the disadvantage of sklearn? ›

It is not optimized for graph algorithms, and it is not very good at string processing. For example, scikit-learn does not provide a built-in way to produce a simple word cloud. Scikit-learn doesn't have a strong linear algebra library, hence scipy and numpy are used.

What are the prerequisites for scikit-learn? ›

Prerequisites for Sklearn
  • Python (version 3.5 or higher)
  • Joblib (version 0.11 or higher)
  • Scipy (version 0.17. 0 or higher)
  • NumPy (version 1.11. 0 or higher)
  • Matplotlib (version 1.5. 1 or higher) for plotting capabilities.
  • Pandas (version 0.18.
Dec 16, 2022

Should I learn scikit-learn or TensorFlow? ›

Scikit-Learn and TensorFlow are both designed to help developers create and benchmark new models, so their functional implementations are quite similar with the key distinction that Scikit-Learn is used in practice with a wider scope of models as opposed to TensorFlow's implied use for neural networks.

Is scikit-learn free to use? ›

Scikit-learn is a free software machine learning library for the Python programming language.

Is scikit-learn free? ›

learn and also known as sklearn) is a free software machine learning library for the Python programming language.

Is scikit-learn an AI framework? ›

Scikit-learn is a Python package designed to facilitate use of machine learning and AI algorithms. This package includes algorithms used for classification, regression and clustering such as random forests and gradient boosting.

Can I teach myself machine learning? ›

Can You Learn Machine Learning on Your Own? Absolutely. Although the long list of ML skills and tools can seem overwhelming, it's definitely possible to self-learn ML. With the sheer amount of free and paid resources available online, you can develop a great understanding of machine learning all by yourself.

How long does it take to learn Python for machine learning? ›

The amount of time it takes to learn Python will depend on your goals. Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes.

How do I start machine learning with Python for beginners? ›

  1. 7 Steps to Mastering Machine Learning with Python in 2022. ...
  2. Step 1: Learn Programming for Machine Learning. ...
  3. Step 2: Data Collection and Pre-Processing in Python. ...
  4. Step 3: Data Analysis in Python. ...
  5. Step 4: Machine Learning with Python. ...
  6. Step 5: Machine Learning Algorithms In Depth. ...
  7. Step 6: Deep Learning. ...
  8. Step 7: Projects.
Sep 30, 2022

What method does scikit-learn use? ›

Scikit-learn provides algorithms like linear regression, logistic regression, decision tree models, random forest regression, gradient boosting regression, gradient boosting classification, K-nearest neighbors, Support Vector Machine, Naive Bayes, neural networks, and a lot more.

What is difference between SciPy and Scikit? ›

In summary, SciPy is a comprehensive library for scientific computing, offering a wide range of mathematical functions and modules. scikit-learn, on the other hand, is a dedicated machine-learning library, providing a rich collection of algorithms and tools specifically designed for machine-learning tasks.

What is the difference between scikit-learn and SciPy? ›

scikit-learn is a Python module for machine learning built on top of SciPy and distributed under the 3-Clause BSD license. On the other hand, SciPy is detailed as "Scientific Computing Tools for Python". Python-based ecosystem of open-source software for mathematics, science, and engineering.

Is hands on machine learning with scikit-learn for beginners? ›

Hands-on machine learning with Scikit-learn, Keras & TensorFlow is a book that will help you get started with machine learning and deep learning. It will give you a solid foundation in the basics of data science and how to use the tools available in Python.

What language does Microsoft use for machine learning? ›

Supported languages

Standard ones are C#, Java, JavaScript, and Python.

What data format does scikit-learn? ›

scikit-learn includes utility functions for loading datasets in the svmlight / libsvm format. In this format, each line takes the form <label> <feature-id>:<feature-value> <feature-id>:<feature-value> ... . This format is especially suitable for sparse datasets.

What are the four 4 types of machine learning algorithms? ›

There are four types of machine learning algorithms: supervised, semi-supervised, unsupervised and reinforcement.

Is scikit-learn good for deep learning? ›

The scikit-learn library in Python is built upon the SciPy stack for efficient numerical computation. It is a fully featured library for general purpose machine learning and provides many useful utilities in developing deep learning models.

Who is scikit-learn competitor? ›

skdag - A more flexible alternative to scikit-learn Pipelines.

Who is the owner of scikit-learn? ›

David Cournapeau is a data scientist. He is the original author of the scikit-learn package, an open source machine learning library in the Python programming language.

How do I master Python for data science? ›

How to Learn Python for Data Science
  1. Step 1: Learn Python fundamentals. Everyone starts somewhere. ...
  2. Step 2: Practice with hands-on learning. ...
  3. Step 3: Learn Python data science libraries. ...
  4. Step 4: Build a data science portfolio as you learn Python. ...
  5. Step 5: Apply advanced data science techniques.
Jul 12, 2022

Should I master Python for data science? ›

Python is one of the most crucial tools for data scientists, as it provides a wide array of libraries and frameworks that can be used for data analysis, manipulation, modeling, and more. Therefore it is very important to master different python tools and frameworks.

Is data science machine learning or AI? ›

Data science focuses on managing, processing, and interpreting big data to effectively inform decision-making. Machine learning leverages algorithms to analyze data, learn from it, and forecast trends. AI requires a continuous feed of data to learn and improve decision-making.

How much data can sklearn handle? ›

Both frameworks can be used with scikit learn. You can load 22 GB of data into Dask or SFrame, then use with sklearn.

Is sklearn an algorithm? ›

Scikit-learn is a free machine learning library for Python. It features various algorithms like support vector machine, random forests, and k-neighbours, and it also supports Python numerical and scientific libraries like NumPy and SciPy .

Does sklearn use CPU? ›

1. Parallelism. Some scikit-learn estimators and utilities parallelize costly operations using multiple CPU cores.

What is the difference between scikit-learn and PyTorch? ›

PyTorch vs Scikit-Learn

Sklearn is built on top of Python libraries like NumPy, SciPy, and Matplotlib, and is simple and efficient for data analysis. However, while Sklearn is mostly used for machine learning, PyTorch is designed for deep learning.

What is difference between machine learning and deep learning? ›

Machine learning and deep learning are both types of AI. In short, machine learning is AI that can automatically adapt with minimal human interference. Deep learning is a subset of machine learning that uses artificial neural networks to mimic the learning process of the human brain.

Is TensorFlow for AI or machine learning? ›

TensorFlow is an end-to-end open source platform for machine learning.

Which language is best for TensorFlow? ›

Python is the recommended language for TensorFlow, although it also uses C++ and JavaScript. Python was developed to help programmers write clear, logical code for both small and large projects. It's often used to build websites and software, automate tasks, and carry out data analysis.

Which Python modules are used in machine learning? ›

Scikit-learn is a Python library which is used for classical machine learning algorithms. It is built on the top of two basic libraries of Python, that is NumPy and SciPy. Scikit-learn is popular in Machine learning developers as it supports supervised and unsupervised learning algorithms.

Can we use TensorFlow with scikit-learn? ›

Since Scikit-Learn allows you to implement your own estimators, there's nothing stopping you from using TensorFlow within Scikit-Learn's framework to compare TensorFlow models against other Scikit-Learn models.

How to build a machine learning classifier in Python with scikit-learn? ›

How to Build a Machine Learning Classifier in Python with Scikit...
  1. Introduction. ...
  2. Prerequisites. ...
  3. Setting Up The Project Virtual Environment. ...
  4. Installing Scikit-Learn. ...
  5. Installing Pandas. ...
  6. Choosing The Dataset. ...
  7. Importing The Dataset. ...
  8. Splitting The Dataset.
Oct 26, 2022

Is pandas part of scikit-learn? ›

¶ Generally, scikit-learn works on any numeric data stored as numpy arrays or scipy sparse matrices. Other types that are convertible to numeric arrays such as pandas DataFrame are also acceptable.

Is machine learning code in Python? ›

The best way to get started using Python for machine learning is to complete a project. It will force you to install and start the Python interpreter (at the very least). It will given you a bird's eye view of how to step through a small project. It will give you confidence, maybe to go on to your own small projects.

What tools do most Python developers use? ›

9 Best Tools for Python Developers
  • IDLE. IDLE is Python's Integrated Development and Learning Environment. ...
  • Sublime Text. Sublime Text is one of the most popular code editors for programmers, supporting almost all platforms. ...
  • Atom. ...
  • Visual Code Studio. ...
  • Jupyter Notebook. ...
  • Spyder. ...
  • PyCharm. ...
  • PyDev.
Dec 13, 2022

What are the most important machine learning Python libraries? ›

Top 9 Python Libraries for Machine Learning in 2023
  • 1) NumPy.
  • 2) SciPy.
  • 3) Scikit-learn.
  • 4) Theano.
  • 5) TensorFlow.
  • 6) Keras.
Oct 3, 2022

References

Top Articles
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated: 13/12/2023

Views: 6071

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.