Data preprocessing - sorokinDev/MyWayToML GitHub Wiki

Code for preprocessing data

Python

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import Imputer, LabelEncoder, OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split

np.set_printoptions(threshold=np.inf) #To print full array, instead of "......."

#open Dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values

#fill missing values with mean value(AVG)
imputer = Imputer(missing_values='NaN', strategy='mean', axis = 0)
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])


#encoding categorical data
#encode country names to numbers
labelEncX = LabelEncoder()
X[:, 0] = labelEncX.fit_transform(X[:, 0])

#transform country column to few columns for each country(Dummy variable concept)
onehotEncCountry = OneHotEncoder(categorical_features = [0])
X = onehotEncCountry.fit_transform(X).toarray()

#encode purchased values to numbers
labelEncY = LabelEncoder()
y = labelEncY.fit_transform(y)

#splitting data into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, 
                                                    random_state = 0)

#feature scaling
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test) #sc_X is already fitted to our train_set

RLang

dataset = read.csv('Data.csv')

dataset$Age = ifelse(is.na(dataset$Age),
                     ave(dataset$Age, FUN = function(x) mean(x, na.rm = TRUE)),
                     dataset$Age)
dataset$Salary = ifelse(is.na(dataset$Salary),
                        ave(dataset$Salary, FUN = function(x) mean(x, na.rm = TRUE)),
                        dataset$Salary)

dataset$Country = factor(dataset$Country,
                         levels = unique(dataset$Country),
                         labels = c(1, 2, 3))

dataset$Purchased = factor(dataset$Purchased,
                         levels = c('No', 'Yes'),
                         labels = c(0, 1))

# install.packages('caTools')
library(caTools)
set.seed(0)
split = sample.split(dataset$Purchased, SplitRatio = 0.8)
training_set = subset(dataset, split)
test_set = subset(dataset, !split)

training_set[, 2:3] = scale(training_set[, 2:3])
test_set[, 2:3] = scale(test_set[, 2:3])