joppot

コピペで絶対動く。説明を妥協しない

プログラミング

4 functions of scikit-learn preprocesses data such as machine learning

投稿日:


Abstract

Hello every one this is candle. In this time we will prreprocess a data with scikit-learn which is machine learning library of python.

We will use scikit-learn called
With scikit-learn you can use what is called a converter, and you can convert the input data with fit_transform () method.Since there are many converters, I will introduce the following four converters that are often used in machine learning.

Imputer
StandardScaler
MinMaxScaler
OneHotEncorder


Condition

Python3
scikit-learn 0.19.1

For running sample code, you need numpy aside from these libs.



Imputer

http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html#sklearn.preprocessing.Imputer

imuter replaces the missing value (None) contained in the data with another specified value.
These values are set by default as arguments.

Imputer(missing_values='NaN', strategy='mean', axis=0, verbose=0, copy=True)

missing_values is type of float and replaces all values in the data corresponding to the specified value. Use this when you want to replace other real numbers that are not None.
strategy is type of str and sets mean (median), median (mode), mode (mode).
Axis is type of int . When 0 is specified, it replaced with the average value of the column (vertical).
If 1 is specified, replaces with the average value of the row (horizontal).

Let’s try it. Create imputer_test.py file in to the somewhere you like.

touch imputer_test.py

Write this

from sklearn.preprocessing import Imputer
import numpy as np
data = np.array([[7, 2, 3],
                 [8, None, 3],
                 [3, 8, 5]])
imputer = Imputer()
new_data = imputer.fit_transform(data)
print(new_data)

Run it.

python3 imputer_test.py
[[ 7.  2.  3.]
 [ 8.  5.  3.]
 [ 3.  8.  5.]]

The place where None was replaced with 5.

StandardScaler

http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler

Standardize the data.
The following values are set by default as arguments.

StandardScaler(copy=True, with_mean=True, with_std=True)

Create a file.

touch ss.py

Write these.

from sklearn.preprocessing import StandardScaler
import numpy as np
data = np.array([[7., 2., 3.],
                 [8., 5., 3.],
                 [3., 8., 5.]])
standard_scaler = StandardScaler()
new_data = standard_scaler.fit_transform(data)
print(new_data)

Run it.

python3 ss.py

[[ 0.46291005 -1.22474487 -0.70710678]
 [ 0.9258201   0.         -0.70710678]
 [-1.38873015  1.22474487  1.41421356]]

MinMaxScaler

http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html#sklearn.preprocessing.MinMaxScaler

It maps data to the specified range.
The following values are set by default as arguments.

MinMaxScaler(feature_range=(0, 1), copy=True)

feature_range is a tuple, and it is specified as (minimum value, maximum value).
The default value is mapped between 0 and 1.

Create a file.

touch mms.py

Write this

from sklearn.preprocessing import MinMaxScaler
import numpy as np
data = np.array([[0., 2.],
                 [3., 4.],
                 [10., 7.]])
standard_scaler = MinMaxScaler(feature_range=(0, 1))
new_data = standard_scaler.fit_transform(data)
print(new_data)

Run it.

python3 mms.py

[[ 0.   0. ]
 [ 0.3  0.4]
 [ 1.   1. ]]

As you can see from the output results, mapping is performed for each column (axis = 0) when the input of the converter is a two-dimensional array.

OneHotEncorder

http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html#sklearn.preprocessing.OneHotEncoder

Change label of integer value to one-hot label.

OneHotEncoder(n_values='auto', categorical_features='all', dtype=<class 'numpy.float64'>, sparse=True, handle_unknown='error')

Create a file

touch ohe.py

Write this

from sklearn.preprocessing import OneHotEncoder
import numpy as np
data = np.array([0, 2, 1, 1]).reshape(-1, 1)
one_hot = OneHotEncoder()
new_data = one_hot.fit_transform(data).toarray()
print(new_data)

Run it.

python3 ohe.py

[[ 1.  0.  0.]
 [ 0.  0.  1.]
 [ 0.  1.  0.]
 [ 0.  1.  0.]]

Extra

If the label is string, you can use the pandas Series method factorize() to convert the label of an integer value.

import pandas as pd
data = pd.Series(["apple", "orange", "banana", "banana"])
new_data, _ = data.factorize()
print(new_data)
>>
[0 1 2 2]

Conclusion

Preprocessing can be expected to increase learning performance by taking one time before doing machine learning. Please take advantage of it.

スポンサードリンク

If you think this article is good, share it please

-プログラミング
-,

執筆者:


comment

Your email address will not be published. Required fields are marked *

関連記事

React Native slows down when debugging on Google Chrome

English 日本語 Abstract Hello everybody, It’s candle. This time, we will solve the problem that using simulator is going to slow down when debugging on the Google Chrome Anyway, It is solved in a simple way. we use Chromium instead of Google Chrome. Premise React development environment has been established

Ruby regex that does not match if there are keywords that you don’t want included in the string

Abstract Hello everyone it’s me candle. In this time I would like to create a regular expression that does not pass if keywords that I do not want included in the string match. This is such case like this. For example, the regex matches these words “Bitcoin” and “Bitcoin ~” but doesn’t match “BitcoinCash” and “Bitcoin Cash”. ○ Bitcoin ○ Bitcoin Core × BitcoinCash × Bitcoin Cash Condition Nothing Write the regex This is a regex that does not match if there are keywords that you do not want included in the string. /Keyword to include(?!Keywords you do not want …

React Project development environment building command create-react-app is too convenient

English 日本語 Abstract Hello everyone It’s me candle. In this time we will build a “react” development environment with create-react-app command and try to hello world. Past react development was created by installing babel and other packages from npm on your own using gulp or webpack. Past react development installed babel and other packages from npm and built servers with gulp and webpack. If you use the create-react-app command, you can create react environment easily. Let’s do it. Precondition Node is already installed

Lazy load image with react-lazyload

Abstract Hello everyoen it’s me candle. This time let’s make a delayed loading of images with react-lazyload. The problem of SPA is the delay at the time of initial loading. Among them, we feel that the site with many images is even late. Let’s try it. Condition Nothing Prepare If you have already developing react project, use it. But you don’t have yet or try to test. Generate it with this command. create-react-app imageloader-sample cd imageloader-sample We will prepare images for samples with Faker.js, so install it. yarn add faker Ready to develop. Make a sample code Open the src/App.js …

Hiragino Sans How to write to change weight in css

Abstract Hello everyone it’s me candle. In this time I will show you how to write css of Hiragino Sans.The feature of Hiragino Sans is to be able to change the weight of font from 1 to 9 levels. On the other hand, there are various ways of writing css of Hiragino Sans and I did not know exactly how to write it, so I wrote a program and test it. It will help you who will use Hiragino Sans. The quick reference is released here. http://hiragino.joppot.info Condition Nothing SPONSORED LINK How to write css of Hiragino Sans From the …


I work in the venture company as a CTO. I start to write program in University, first I learned java, C++ and PHP. In the company, I'm developing web services by Rails. I do like to automation.