1661821500
Saiba mais sobre os pipelines SimpleImputer, IterativeImputer, KNNImputer e machine learning do Scikit-learn.
Se você tiver alguns valores ausentes em seu conjunto de dados, poderá descartar a linha ou até a coluna de valores ausentes. Esse método é altamente desencorajado, pois reduz o tamanho dos dados e a análise de dados pode ser distorcida da verdade básica. Em vez disso, devemos usar algoritmos de aprendizado de máquina que não sejam afetados por valores ausentes ou usar imputadores para preencher as informações ausentes.
O imputador é um estimador usado para preencher os valores ausentes em conjuntos de dados. Para valores numéricos, usa média , mediana e constante . Para valores categóricos, ele usa o valor constante e usado com mais frequência . Você também pode treinar seu modelo para prever os rótulos ausentes.
No tutorial, aprenderemos sobre SimpleImputer , IterativeImputer e KNNImputer do Scikit -learn . Também criaremos um pipeline para imputar recursos categóricos e numéricos e alimentá-los em um modelo de aprendizado de máquina.
As funções de imputação do scikit-learn nos fornecem uma opção fácil de preencher com poucas linhas de código. Podemos integrar esses imputadores e criar pipelines para reproduzir resultados e melhorar os processos de desenvolvimento de machine learning.
Usaremos o ambiente Deepnote , que é semelhante ao Jupyter Notebook, mas na nuvem.
Para baixar e descompactar dados do Kaggle . Você precisa instalar o pacote Kaggle Python e baixar o conjunto de dados spaceship-titanic usando a API. Por fim, descompacte os dados na pasta do conjunto de dados.
%%capture
!pip install kaggle
!kaggle competitions download -c spaceship-titanic
!unzip -d ./dataset spaceship-titanic
Em seguida, importaremos os pacotes Python necessários para ingestão de dados, imputação e criação de pipelines de transformação.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer,KNNImputer
from sklearn.pipeline import FeatureUnion,make_pipeline,Pipeline
from sklearn.compose import ColumnTransformer
O conjunto de dados Spaceship Titanic faz parte da competição de previsão inicial da Kaggle. Ele consiste em treinar, testar e enviar arquivos CSV. Usaremos train.csv , que contém informações de passageiros em naves espaciais.
A função read_csv() do pandas lê o train.csv e exibe o dataframe.
df = pd.read_csv("dataset/train.csv")
df
Nesta seção, exploraremos as colunas com valores ausentes, mas primeiro precisamos verificar a forma do conjunto de dados. Tem 8693 linhas e 14 colunas.
df.shape
>>> (8693, 14)
Agora exibiremos a contagem e a porcentagem de valores ausentes com base nas colunas. Para exibi-lo em um dataframe, criaremos um novo dataframe de valores ausentes e aplicaremos gradientes de estilo à coluna NA Count .
NA = pd.DataFrame(data=[df.isna().sum().tolist(), ["{:.2f}".format(i)+'%' \
for i in (df.isna().sum()/df.shape[0]*100).tolist()]],
columns=df.columns, index=['NA Count', 'NA Percent']).transpose()
NA.style.background_gradient(cmap="Pastel1_r", subset=['NA Count'])
Exceto para PassengerID e Transported , há valores ausentes em todas as colunas.
Usaremos as informações nas colunas ausentes e as dividiremos em colunas categóricas e numéricas. Vamos tratá-los de forma diferente.
Para imputação numérica, selecionaremos a coluna Idade e exibiremos o valor ausente do número. Isso nos ajudará a validar os resultados antes e depois.
all_col = df.columns
cat_na = ['HomePlanet', 'CryoSleep','Destination','VIP']
num_na = ['Age','RoomService', 'FoodCourt', 'ShoppingMall', 'Spa', 'VRDeck']
data1 = df.copy()
data2 = df.copy()
data1['Age'].isna().sum()
>>> 179
data1.Age[0:5]
>>> 0 39.0
>>> 1 24.0
>>> 2 58.0
>>> 3 33.0
>>> 4 16.0
Em seguida, usaremos o SimpleImputer do sklearn e o aplicaremos à coluna Age . Ele substituirá os dados ausentes pelo valor médio da coluna.
Como podemos observar, não há valores ausentes na coluna Idade .
imp = SimpleImputer(strategy='mean')
data1['Age'] = imp.fit_transform(data1['Age'].values.reshape(-1, 1) )
data1['Age'].isna().sum()
>>> 0
Para colunas numéricas, você pode usar a estratégia constante , média e mediana e para colunas categóricas, você pode usar a estratégia most_frequent e constante .
Para imputação categórica, usaremos a coluna HomePlanet que contém 201 valores ausentes.
data1['HomePlanet'].isna().sum()
>>> 201
data1.HomePlanet[0:5]
>>> 0 Europa
>>> 1 Earth
>>> 2 Europa
>>> 3 Europa
>>> 4 Earth
Para preencher os valores omissos categóricos, usaremos SimpleImputer com a estratégia most_frequent .
imp = SimpleImputer(strategy="most_frequent")
data1['HomePlanet'] = imp.fit_transform(data1['HomePlanet'].values.reshape(-1, 1))
Preenchemos todos os valores ausentes na coluna HomePlanet.
data1['HomePlanet'].isna().sum()
>>> 0
No Imputer univariado, o valor omisso é calculado usando o mesmo recurso, enquanto que nos algoritmos do Imputer multivariado usam todo o conjunto de dimensões do recurso disponíveis para prever o valor omisso.
Estaremos imputando colunas numéricas de uma só vez e, como podemos ver, todas elas têm mais de 150 valores ausentes.
data2[num_na].isna().sum()
>>> Age 179
>>> RoomService 181
>>> FoodCourt 183
>>> ShoppingMall 208
>>> Spa 183
>>> VRDeck 188
Usaremos IterativeImputer com 10 max_iter para estimar e preencher valores ausentes em colunas numéricas. O algoritmo considerará todas as colunas ao fazer a estimativa de valor.
imp = IterativeImputer(max_iter=10, random_state=0)
data2[num_na] = imp.fit_transform(data2[num_na])
data2[num_na].isna().sum()
>>> Age 0
>>> RoomService 0
>>> FoodCourt 0
>>> ShoppingMall 0
>>> Spa 0
>>> VRDeck 0
Por que o Imputer do Scikit-learn? Além do Imputer, a estrutura de aprendizado de máquina fornece transformação de recursos, manipulação de dados, pipelines e algoritmos de aprendizado de máquina. Todos eles se integram sem problemas. Com algumas linhas de código, você pode imputar, normalizar, transformar e treinar seu modelo em qualquer conjunto de dados.
Nesta seção, aprenderemos como integrar o Imputer em um projeto de aprendizado de máquina para obter melhores resultados.
from sklearn.preprocessing import LabelEncoder, StandardScaler, OrdinalEncoder
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
X,y = df.drop(['Transported','PassengerId','Name','Cabin'],axis = 1) , df['Transported']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=100, random_state=0)
Para criar pipelines de dados de transformação numérica e categórica, usaremos a função Pipeline do sklearn.
Para numeric_transformer , usamos:
Para categórico_transformer , usamos:
numeric_transformer = Pipeline(steps=[
('imputer', KNNImputer(n_neighbors=2, weights="uniform")),
('scaler', StandardScaler())])
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OrdinalEncoder())])
Agora, processaremos e transformaremos o recurso de treinamento usando ColumnTransformer . Para numeric_transformer, fornecemos uma lista de colunas numéricas e para categórico_transformer, usaremos uma lista de colunas categóricas.
Nota: estamos apenas preparando tubulações e transformadores. Ainda não processamos nenhum dado.
preprocessor = ColumnTransformer(
remainder = 'passthrough',
transformers=[
('numeric', numeric_transformer, num_na),
('categorical', categorical_transformer, cat_na)
])
Por fim, criaremos um pipeline de transformação que contém um processador e um DecisionTreeClassifier para a tarefa de classificação binária. Esse pipeline primeiro processará e transformará os dados e, em seguida, treinará o modelo do classificador.
transform = Pipeline(
steps=[
("processing", preprocessor),
("DecisionTreeClassifier", DecisionTreeClassifier()),
]
)
É aqui que a mágica acontece. Ajustaremos o conjunto de dados de treinamento no pipeline de transformação . Depois disso, avaliaremos nosso modelo usando um conjunto de dados de teste.
Obtivemos 75% de precisão com a configuração padrão. Nada mal!!!
model = transform.fit(X_train,y_train)
model.score(X_test, y_test)
>>> 0.75
Em seguida, executaremos previsões em um conjunto de dados de teste e criaremos um relatório de classificação estruturado .
from sklearn.metrics import classification_report
prediction = model.predict(X_test)
print(classification_report(prediction, y_test))
Como podemos ver, temos pontuações estáveis para as classes True e False .
precision recall f1-score support
False 0.70 0.74 0.72 43
True 0.80 0.75 0.77 57
accuracy 0.75 100
macro avg 0.75 0.75 0.75 100
weighted avg 0.75 0.75 0.75 100
Para maior precisão, os cientistas de dados estão usando uma abordagem de aprendizado profundo para a imputação de valores ausentes. Novamente, você precisa decidir quanto tempo e recursos são necessários para construir um sistema e qual valor ele traz. Na maioria dos casos, os Imputers do Scikit-learn fornecem maior valor e foram necessárias algumas linhas de código para imputar todo o conjunto de dados.
Neste blog, aprendemos sobre Imputação e como a biblioteca Scikit-learn funciona na estimativa de valores ausentes. Também aprendemos sobre imputações univariadas, multivariadas, categóricas e numéricas. Na parte final, usamos pipelines de dados, transformadores de coluna e pipelines de aprendizado de máquina para imputar, transformar, treinar e avaliar nosso modelo.
Fonte: https://www.kdnuggets.com
#machine-learning #scikitlearn
1618278600
Amilestone for open source projects — French President Emmanuel Macron has recently been introduced to Scikit-learn. In fact, in a recent tweet, Scikit-learn creator and Inria tenured research director, Gael Varoquaux announced the presentation of Scikit-Learn, with applications of machine learning in digital health, to the president of France.
He stated the advancement of this free software machine learning library — “started from the grassroots, built by a community, we are powering digital revolutions, adding transparency and independence.”
#news #application of scikit learn for machine learning #applications of scikit learn for digital health #scikit learn #scikit learn introduced to french president
1622792520
Scikit-Learn is one of the popular software machine learning libraries. The library is built on top of NumPy, SciPy, and Matplotlib and supports supervised and unsupervised learning as well as provides various tools for model fitting, data preprocessing, model selection and evaluation.
About: From the developers of Scikit-Learn, this tutorial provides an introduction to machine learning with Scikit-Learn. It includes topics such as problem setting, loading an example dataset, learning and predicting. The tutorial is suitable for both beginners and advanced students.
**About: **In this project-based course, you will learn the fundamentals of sentiment analysis, and build a logistic regression model to classify movie reviews as either positive or negative. You will learn how to develop and employ a logistic regression classifier using Scikit-Learn, perform feature extraction with The Natural Language Toolkit (NLTK), tune model hyperparameters and evaluate model accuracy etc.
**About: **Python Machine Learning: Scikit-Learn tutorial will help you learn the basics of Python machine learning. You will learn how to use Python and its libraries to explore your data with the help of Matplotlib and Principal Component Analysis (PCA). You will also learn how to work with the KMeans algorithm to construct an unsupervised model, fit this model to your data, predict values, and validate the model.
**About: **Edureka’s video tutorial introduces machine learning in Python. It will take you through regression and clustering techniques along with a demo of SVM classification on the famous iris dataset. This video helps you to learn the introduction to Scikit-learn and how to install it, understand how machine learning works, among other things.
About: In this Coursera offering, you will learn about Linear Regression, Regression using Random Forest Algorithm, Regression using Support Vector Machine Algorithm. Scikit-Learn provides a comprehensive array of tools for building regression models.
About: In this course, you will learn about machine learning, algorithms, and how Scikit-Learn makes it all so easy. You will get to know the machine learning approach, jargons to understand a dataset, features of supervised and unsupervised learning models, algorithms such as regression, classification, clustering, and dimensionality reduction.
About: In this two-hour long project-based course, you will build and evaluate a simple linear regression model using Python. You will employ the Scikit-Learn module for calculating the linear regression while using pandas for data management and seaborn for plotting. By the end of this course, you will be able to build a simple linear regression model in Python with Scikit-Learn, employ Exploratory Data Analysis (EDA) to small data sets with seaborn and pandas.
**About: **This tutorial is available on GitHub. It includes an introduction to machine learning with sample applications, data formats, preparation and representation, supervised learning: training and test data, the Scikit-Learn estimator interface and more.
About: This is a two-hour long project-based course, where you will understand the business problem and the dataset and learn how to generate a hypothesis to create new features based on existing data. You will learn to perform text pre-processing and create custom transformers to generate new features. You will also learn to implement an NLP pipeline, create custom transformers and build a text classification model.
#developers corner #learn scikit-learn #machine learning library #scikit learn
1618280760
Undoubtedly, Scikit-learn is one of the best machine learning libraries available today. There are several reasons for that. The consistency among Scikit-learn estimators is one reason. You cannot find such consistency in any other machine learning library. The .fit()/.predict() paradigm best describes the consistency. Another reason is that Scikit-learn has a variety of uses. It can be used for classification, regression, clustering, dimensionality reduction, anomaly detection.
Therefore, Scikit-learn is a must-have Python library in your data science toolkit. But, learning to use Scikit-learn is not straightforward. It’s not simple as you imagine. You have to set up some background before learning it. Even while you learning Scikit-learn, you should follow some guidelines and best practices. In this article, I’m happy to share 9 guidelines that worked for me to master the Scikit-learn without giving up the learning process in the middle. Whenever possible, I will include the links to my previous posts which will help you to set up the background and continue to learn the Scikit-learn.
#data-science #scikit-learn #machine-learning #unsupervised-learning #supervised-learning
1598891580
Recently, researchers from Google proposed the solution of a very fundamental question in the machine learning community — What is being transferred in Transfer Learning? They explained various tools and analyses to address the fundamental question.
The ability to transfer the domain knowledge of one machine in which it is trained on to another where the data is usually scarce is one of the desired capabilities for machines. Researchers around the globe have been using transfer learning in various deep learning applications, including object detection, image classification, medical imaging tasks, among others.
#developers corner #learn transfer learning #machine learning #transfer learning #transfer learning methods #transfer learning resources
1620898103
Check out the 5 latest technologies of machine learning trends to boost business growth in 2021 by considering the best version of digital development tools. It is the right time to accelerate user experience by bringing advancement in their lifestyle.
#machinelearningapps #machinelearningdevelopers #machinelearningexpert #machinelearningexperts #expertmachinelearningservices #topmachinelearningcompanies #machinelearningdevelopmentcompany
Visit Blog- https://www.xplace.com/article/8743
#machine learning companies #top machine learning companies #machine learning development company #expert machine learning services #machine learning experts #machine learning expert