Myriam  Rogahn

Myriam Rogahn

1599227100

Pre-Process Data Like a Pro: Intro to Scikit-Learn Pipelines

You wrote all your queries, gathered all the data and are all fired up to implement the latest machine learning algorithm you read about on Medium. Wait! You soon realize you need to deal with missing data, imputation, categorical data, standardization, etc.

Instead of “manually” pre-processing data you can start writing functions and data pipelines that you can apply to any data set. Luckily for us, python’s Scikit-Learn library has several classes that will make all of this a piece of cake!

In this article you will learn how to :

  • Reproduce transformations easily on any dataset.
  • Easily track all transformations you apply to your dataset.
  • Start building your library of transformations you can use later on different projects.

tl:dr: Let’s build a pipeline where we can impute, transform, scale, and encode like this:

from sklearn.compose import ColumnTransformer

data_pipeline = ColumnTransformer([
    ('numerical', num_pipeline, num_vars),
    ('categorical', OneHotEncoder(), cat_vars),

])
airbnb_processed = data_pipeline.fit_transform(airbnb_data)

Without knowing much you can infer that different transformations are applied to numerical variables and categorical variables. Let’s go into the proverbial weeds and see how we end up with this pipeline.

Data

For all of these examples, I will be using the airbnb NYC listings dataset from insideairbnb.com . This is a real dataset containing information scraped from airbnb and has all the information related to a listing on the site.

Let us imagine we want to predict the price of a listing given some variables like the property type and neighborhood.

raw_data = pd.read_csv('http://data.insideairbnb.com/united-states/ny/new-york-city/2020-07-07/data/listings.csv.gz',
                        compression='gzip')

Let’s start by getting our categorical and numerical variables that we want to work with. We will keep it simple by removing data with missing values in our categorical variables of interest and with no reviews.

Imputation

Is a dataset even real if it isn’t missing data? The reality is that we have to deal with missing data all the time. You will have to decide how to deal with missing data for your specific use

  • You can dropna() rows with missing data. Might drop too much data.
  • Drop the variable that has missing data. What if you really want that variable?
  • Replace NAs with zero, the mean, median, or some other calculation.

Scikit-Learn provides us with a nice simple class to deal with missing values.

Let us impute numerical variables such as price or security deposit with the median. For simplicity, we do this for all numerical variables.

#data #data-preprocessing #data-science #python

What is GEEK

Buddha Community

Pre-Process Data Like a Pro: Intro to Scikit-Learn Pipelines
Siphiwe  Nair

Siphiwe Nair

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

Getting Started with scikit-learn Pipelines for Machine Learning

Why Use Pipelines?

The typical overall machine learning workflow with scikit-learn looks something like this:

  1. Load all data into X and y
  2. Use X and y to perform a train-test split, creating X_trainX_testy_train, and y_test
  3. Fit preprocessors such as StandardScaler and SimpleImputer on X_train
  4. Transform X_train using the fitted preprocessors, and perform any other preprocessing steps (such as dropping columns)
  5. Create various models, tune hyperparameters, and pick a final model that is fit on the preprocessed X_train as well as y_train
  6. Transform X_test using the fitted preprocessors, and perform any other preprocessing steps (such as dropping columns)
  7. Evaluate the final model on the preprocessed X_test as well as y_test

Here is an example code snippet that follows these steps, using an antelope dataset (“antelope.csv”) from a statistics textbook. The goal is to predict the number of spring fawns based on the adult antelope population, annual precipitation, and winter severity. This is a very tiny dataset and should only be used for example purposes! This example skips any hyperparameter tuning, and simply fits a vanilla linear regression model on the preprocessed training data before evaluating it on the preprocessed testing data.

# Step 0: import relevant packages
	import pandas as pd

	from sklearn.model_selection import train_test_split
	from sklearn.preprocessing import OneHotEncoder
	from sklearn.linear_model import LinearRegression

	# Step 1: load all data into X and y
	antelope_df = pd.read_csv("antelope.csv")
	X = antelope_df.drop("spring_fawn_count", axis=1)
	y = antelope_df["spring_fawn_count"]

	# Step 2: train-test split
	X_train, X_test, y_train, y_test = train_test_split(
	    X, y, random_state=42, test_size=3)

	# Step 3: fit preprocessor
	ohe = OneHotEncoder(sparse=False, handle_unknown="ignore")
	ohe.fit(X_train[["winter_severity_index"]])

	# Step 4: transform X_train with fitted preprocessor(s), and perform
	# custom preprocessing step(s)

	train_winter_array = ohe.transform(X_train[["winter_severity_index"]])
	train_winter_df = pd.DataFrame(train_winter_array, index=X_train.index)
	X_train = pd.concat([train_winter_df, X_train], axis=1)
	X_train.drop("winter_severity_index", axis=1, inplace=True)

	# for the sake of example, this "feature engineering" encodes a numeric column
	# as a binary column also ("low" meaning "less than 12" here)
	X_train["low_precipitation"] = [int(x < 12) for x in X_train["annual_precipitation"]]

	# Step 5: create a model (skipping cross-validation and hyperparameter tuning
	# for the moment) and fit on preprocessed training data
	model = LinearRegression()
	model.fit(X_train, y_train)

	# Step 6: transform X_test with fitted preprocessor(s), and perform
	# custom preprocessing step(s)

	test_winter_array = ohe.transform(X_test[["winter_severity_index"]])
	test_winter_df = pd.DataFrame(test_winter_array, index=X_test.index)
	X_test = pd.concat([test_winter_df, X_test], axis=1)
	X_test.drop("winter_severity_index", axis=1, inplace=True)

	X_test["low_precipitation"] = [int(x < 12) for x in X_test["annual_precipitation"]]

	# Step 7: evaluate model on preprocessed testing data
	print("Final model score:", model.score(X_test, y_test))
view raw
ml_example_without_pipelines.py hosted with ❤ by GitHub

An example without pipelines

The train-test split is one of the most important components of a machine learning workflow. It helps a data scientist understand model performance, particularly in terms of overfitting. A proper train-test split means that we have to perform the preprocessing steps on the training data and testing data separately, so there is no “leakage” of information from the testing set into the training set.

#scikit-learn #data-preparation #machine-learning #data-pipeline #data-science #data analysis

Myriam  Rogahn

Myriam Rogahn

1599227100

Pre-Process Data Like a Pro: Intro to Scikit-Learn Pipelines

You wrote all your queries, gathered all the data and are all fired up to implement the latest machine learning algorithm you read about on Medium. Wait! You soon realize you need to deal with missing data, imputation, categorical data, standardization, etc.

Instead of “manually” pre-processing data you can start writing functions and data pipelines that you can apply to any data set. Luckily for us, python’s Scikit-Learn library has several classes that will make all of this a piece of cake!

In this article you will learn how to :

  • Reproduce transformations easily on any dataset.
  • Easily track all transformations you apply to your dataset.
  • Start building your library of transformations you can use later on different projects.

tl:dr: Let’s build a pipeline where we can impute, transform, scale, and encode like this:

from sklearn.compose import ColumnTransformer

data_pipeline = ColumnTransformer([
    ('numerical', num_pipeline, num_vars),
    ('categorical', OneHotEncoder(), cat_vars),

])
airbnb_processed = data_pipeline.fit_transform(airbnb_data)

Without knowing much you can infer that different transformations are applied to numerical variables and categorical variables. Let’s go into the proverbial weeds and see how we end up with this pipeline.

Data

For all of these examples, I will be using the airbnb NYC listings dataset from insideairbnb.com . This is a real dataset containing information scraped from airbnb and has all the information related to a listing on the site.

Let us imagine we want to predict the price of a listing given some variables like the property type and neighborhood.

raw_data = pd.read_csv('http://data.insideairbnb.com/united-states/ny/new-york-city/2020-07-07/data/listings.csv.gz',
                        compression='gzip')

Let’s start by getting our categorical and numerical variables that we want to work with. We will keep it simple by removing data with missing values in our categorical variables of interest and with no reviews.

Imputation

Is a dataset even real if it isn’t missing data? The reality is that we have to deal with missing data all the time. You will have to decide how to deal with missing data for your specific use

  • You can dropna() rows with missing data. Might drop too much data.
  • Drop the variable that has missing data. What if you really want that variable?
  • Replace NAs with zero, the mean, median, or some other calculation.

Scikit-Learn provides us with a nice simple class to deal with missing values.

Let us impute numerical variables such as price or security deposit with the median. For simplicity, we do this for all numerical variables.

#data #data-preprocessing #data-science #python

Gerhard  Brink

Gerhard Brink

1620629020

Getting Started With Data Lakes

Frameworks for Efficient Enterprise Analytics

The opportunities big data offers also come with very real challenges that many organizations are facing today. Often, it’s finding the most cost-effective, scalable way to store and process boundless volumes of data in multiple formats that come from a growing number of sources. Then organizations need the analytical capabilities and flexibility to turn this data into insights that can meet their specific business objectives.

This Refcard dives into how a data lake helps tackle these challenges at both ends — from its enhanced architecture that’s designed for efficient data ingestion, storage, and management to its advanced analytics functionality and performance flexibility. You’ll also explore key benefits and common use cases.

Introduction

As technology continues to evolve with new data sources, such as IoT sensors and social media churning out large volumes of data, there has never been a better time to discuss the possibilities and challenges of managing such data for varying analytical insights. In this Refcard, we dig deep into how data lakes solve the problem of storing and processing enormous amounts of data. While doing so, we also explore the benefits of data lakes, their use cases, and how they differ from data warehouses (DWHs).


This is a preview of the Getting Started With Data Lakes Refcard. To read the entire Refcard, please download the PDF from the link above.

#big data #data analytics #data analysis #business analytics #data warehouse #data storage #data lake #data lake architecture #data lake governance #data lake management

Angela  Dickens

Angela Dickens

1596657960

Data Preparation Techniques and Its Importance in Machine Learning

What is Data?

Data refers to examples of cases from the domain that characterize the problem you want to solve and the choice of data is dependent on the objective you want to satisfy. Here are some commonly used websites where open-source data is available for each topic so that you can build your own Machine Learning application and contribute to global success.

Kaggle — An organised platform, where each learner will learn to spend time. You will love how futuristic these datasets are, and with the help of kernels, you can process all in the platform without even downloading the data.

UCI Machine Learning Repository — It maintains a huge amount of diversified datasets as a service to the machine learning community

Data.gov — You can download data from multiple Indian government ministries. Data can range from government budgets to school performance scores.

CMU Libraries — High-quality dataset from various domains an initiative by Carnegie Mellon University

Google Dataset Search — This dataset search lets you find datasets wherever they’re hosted, whether it’s a publisher’s site, a digital library, or an author’s web page.

After collecting the data, the first task is to transform the data to meet the requirements of individual machine learning algorithms. The most challenging part of each machine learning project is how to prepare the one thing that is unique to the project i.e. The data used for modelling.

Data preparation is the transformation of raw data into the form that is more suitable for modelling because “the quality of data is more important than using complicated algorithms”. And to transform the raw data into more informative and self-explanatory you need to perform the same type of data preparation task for any modelling problem.

In this article, we will walk you through how to apply Data Preparation techniques using the Car Price Prediction Dataset as an example

Data Preparation tasks are :

  • Data Cleaning
  • Feature Engineering
  • Data Transformation
  • Feature Extraction

datasciencewhoopees/eda_carprice_prediction

Exploratory Data Analysis, Data Preparation, Data Cleaning on Caprice Prediction Dataset …

github.com


Data Cleaning :

This is one of the hardest steps, as most of the real-world data may have incorrect values in the form of misleading observation, wrong entry of data or rows may store incorrect values and many more but to clean data in order to create reliable dataset you need to have domain expertise which helps you to identify and observe abnormalities within attributes.

#data-pre-processing #data-preparation #data-science #data-modeling #machine-learning #data analysis