ためすう
欠損値を補完する (scikit-learn SimpleImputer)
2019-08-12やったこと
pandas の isnull を使い欠測値をカウントします。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
import sklearn
print(sklearn.__version__)
出力結果
0.21.2
調査
Imputer (Deprecated)
import pandas as pd
from sklearn.preprocessing import Imputer
df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[1,2,None,None,5], 'C':[None, None, 3, None, 4]})
imr = Imputer(missing_values='NaN', strategy='mean', axis=0)
imr = imr.fit(df)
imr.transform(df.values)
出力結果
/anaconda3/lib/python3.6/site-packages/sklearn/utils/deprecation.py:66: DeprecationWarning: Class Imputer is deprecated; Imputer was deprecated in version 0.20 and will be removed in 0.22. Import impute.SimpleImputer from sklearn instead.
warnings.warn(msg, category=DeprecationWarning)
array([[1. , 1. , 3.5 ],
[2. , 2. , 3.5 ],
[3. , 2.66666667, 3. ],
[4. , 2.66666667, 3.5 ],
[5. , 5. , 4. ]])
SimpleImputer
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[1,2,None,None,5], 'C':[None, None, 3, None, 4]})
imr = SimpleImputer( strategy='mean')
imr.fit(df)
imr.transform(df.values)
出力結果
array([[1. , 1. , 3.5 ],
[2. , 2. , 3.5 ],
[3. , 2.66666667, 3. ],
[4. , 2.66666667, 3.5 ],
[5. , 5. , 4. ]])
参考
numpy.var を使って分散を求める
2019-08-12やったこと
numpy.var を使い分散を求めます。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
import numpy as np
np.__version__
出力結果
'1.16.4'
調査
import numpy as np
a = np.array([[10, 20], [60, 80]])
mean = np.mean(a)
print("平均: ", mean)
print("分散: ", np.var(a))
print('--- 手動計算 ---')
var_result = sum([(x-mean)**2 for x in a.ravel()]) / len(a.ravel())
print("分散: ", var_result)
出力結果
平均: 42.5
分散: 818.75
--- 手動計算 ---
分散: 818.75
参考
numpy.reshape を使ってみる
2019-08-12やったこと
配列を新しい形に変えるため、numpy.reshape を使ってみます。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
import numpy as np
np.__version__
出力結果
'1.16.4'
調査
import numpy as np
a = np.arange(10, 22)
print(a)
print(a.reshape((4, 3)))
出力結果
[10 11 12 13 14 15 16 17 18 19 20 21]
[[10 11 12]
[13 14 15]
[16 17 18]
[19 20 21]]
参考
pandas.DataFrame.dropna で欠損値を削除する
2019-08-11やったこと
pandas の droopna を使い欠測値をカウントします。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
pd.__version__
出力結果
'0.20.3'
調査
import pandas as pd
df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[1,2,None,None,5], 'C':[None, None, 3, None, 4]})
print(df.dropna())
print('---')
print(df.dropna(axis=1))
出力結果
A B C
4 5 5.0 4.0
---
A
0 1
1 2
2 3
3 4
4 5
参考
pandas.DataFrame.isnull で欠損値をカウントする
2019-08-11やったこと
pandas の isnull を使い欠測値をカウントします。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
pd.__version__
'0.20.3'
調査
import pandas as pd
df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[1,2,None,None,5], 'C':[None, None, 3, None, 4]})
print(df.isnull().sum())
print('---')
print(df.isnull().sum(axis=1))
出力結果
A 0
B 2
C 3
dtype: int64
0 1
1 1
2 1
3 2
4 0
dtype: int64
参考
Matplotlib を使ってみる
2019-08-10やったこと
Matplotlib を使って、グラフを描画してみます。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
調査
import matplotlib.pyplot as plt
%matplotlib inline
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
%matplotlib inline
は、Jupyter Notebook でグラフを表示するようにします。
画像
参考
Rails で String#inquiry を使ってみる
2019-08-10やったこと
Rails の ActiveSupport で拡張されている String#inquiry を使ってみます。
確認環境
$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]
$ rails --version
Rails 5.2.3
調査
実行結果
$ rails c
Running via Spring preloader in process 57768
Loading development environment (Rails 5.2.3)
irb(main):001:0> 'prod'.inquiry.prod?
=> true
irb(main):002:0> 'prod'.inquiry.prodfalse?
=> false
参考
sklearn で TF-IDF
2019-08-09やったこと
TF-IDF を用いて、文書内の単語の重み付けをします。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
import sklearn
print(sklearn.__version__)
0.19.0
調査
TF-IDF とは
TF-IDF とは、term frequency-inverse のことで、
TF (単語の出現頻度) X IDF (逆文書頻度) となります。
$$ tf-idf(t,d) = tf(t, d) * idf(t, d) $$
使ってみる
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = [
'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
]
vec = TfidfVectorizer()
X = vec.fit_transform(corpus)
print(vec.get_feature_names())
print(type(X))
print(X.toarray())
出力結果
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
<class 'scipy.sparse.csr.csr_matrix'>
[[0. 0.46979139 0.58028582 0.38408524 0. 0.
0.38408524 0. 0.38408524]
[0. 0.6876236 0. 0.28108867 0. 0.53864762
0.28108867 0. 0.28108867]
[0.51184851 0. 0. 0.26710379 0.51184851 0.
0.26710379 0.51184851 0.26710379]
[0. 0.46979139 0.58028582 0.38408524 0. 0.
0.38408524 0. 0.38408524]]
参考
やったこと
カテゴリ特徴を、エンコーディングします。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
import sklearn
print(sklearn.__version__)
0.19.0
調査
from sklearn.feature_extraction import DictVectorizer
D = [{'name': 'ABC', 'age': 23}, {'name': 'DEF', 'age': 35}, {'name': 'XYZ', 'age': 66}, {'name': 'AAA', 'age': 5}]
v = DictVectorizer(sparse=False)
X = v.fit_transform(D)
print(v.get_feature_names())
print(type(X))
print(X.shape)
print(X)
print('---')
# 疎行列
v2 = DictVectorizer(sparse=True)
X2 = v2.fit_transform(D)
print(X2)
print(v2.get_feature_names())
print(type(X2))
print(X2.shape)
print(X2.toarray())
出力結果
['age', 'name=AAA', 'name=ABC', 'name=DEF', 'name=XYZ']
<class 'numpy.ndarray'>
(4, 5)
[[23. 0. 1. 0. 0.]
[35. 0. 0. 1. 0.]
[66. 0. 0. 0. 1.]
[ 5. 1. 0. 0. 0.]]
---
(0, 0) 23.0
(0, 2) 1.0
(1, 0) 35.0
(1, 3) 1.0
(2, 0) 66.0
(2, 4) 1.0
(3, 0) 5.0
(3, 1) 1.0
['age', 'name=AAA', 'name=ABC', 'name=DEF', 'name=XYZ']
<class 'scipy.sparse.csr.csr_matrix'>
(4, 5)
[[23. 0. 1. 0. 0.]
[35. 0. 0. 1. 0.]
[66. 0. 0. 0. 1.]
[ 5. 1. 0. 0. 0.]]
参考
sklearn の CountVectorizer を使う
2019-08-07やったこと
テキストから単語の数を数えるため、sklearn の CountVectorizer を使ってみます。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
import sklearn
print(sklearn.__version__)
0.19.0
調査
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
]
vec = CountVectorizer()
X = vec.fit_transform(corpus)
print(vec.get_feature_names())
print(type(X))
print(X.toarray())
出力結果
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
<class 'scipy.sparse.csr.csr_matrix'>
[[0 1 1 1 0 0 1 0 1]
[0 2 0 1 0 1 1 0 1]
[1 0 0 1 1 0 1 1 1]
[0 1 1 1 0 0 1 0 1]]
toarray() は 疎行列 -> 配列に変換します。