ためすう
matplotlib.pyplot.barh を使って、棒グラフを表示する
2019-08-15やったこと
matplotlib.pyplot.barh を使ってみます
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
import matplotlib
matplotlib.__version__
出力結果
'2.0.2'
調査
import matplotlib.pyplot as plt
%matplotlib inline
y = [10, 20, 30]
x = [60, 50, 80]
plt.barh(y, x, height=5)
出力結果
<Container object of 3 artists>
参考
matplotlib.pyplot.subplot を使ってみる
2019-08-15やったこと
matplotlib.pyplot.subplot を使ってみます
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
import matplotlib
matplotlib.__version__
出力結果
'2.0.2'
調査
import matplotlib.pyplot as plt
%matplotlib inline
plt.subplot(221)
plt.plot([1,2,3])
plt.subplot(223)
plt.plot([4, 5, 6])
plt.subplot(224)
plt.plot([100, 101, 6])
出力結果
参考
やったこと
sklearn.ensemble.RandomForestClassifier を利用して、
RandomForest 学習させてみます。
確認環境
$ 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
調査
特徴のラベル
1) Alcohol
2) Malic acid
3) Ash
4) Alcalinity of ash
5) Magnesium
6) Total phenols
7) Flavanoids
8) Nonflavanoid phenols
9) Proanthocyanins
10)Color intensity
11)Hue
12)OD280/OD315 of diluted wines
13)Proline
RandoForest で学習してみる
import pandas as pd
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)
from sklearn.ensemble import RandomForestClassifier
X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
forest = RandomForestClassifier(n_estimators=10000, random_state=0, n_jobs=-1)
forest.fit(X_train, y_train)
# 特徴の重要度を取得
importances = forest.feature_importances_
結果を表示する
indicies = np.argsort(importances)[::-1]
for f in range(X_train.shape[1]):
print("%2d) label: %s importance: %f" % (f + 1, indicies[f], importances[indicies[f]]))
出力結果
1) label: 9 importance: 0.182483
2) label: 12 importance: 0.158610
3) label: 6 importance: 0.150948
4) label: 11 importance: 0.131987
5) label: 0 importance: 0.106589
6) label: 10 importance: 0.078243
7) label: 5 importance: 0.060718
8) label: 3 importance: 0.032033
9) label: 1 importance: 0.025400
10) label: 8 importance: 0.022351
11) label: 4 importance: 0.022078
12) label: 7 importance: 0.014645
13) label: 2 importance: 0.013916
参考
やったこと
sklearn.preprocessing.MinMaxScaler を使いデータを正規化します。
データを 0~1 の範囲にスケーリングし直します。
確認環境
$ 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
調査
def printout(data):
print("平均X: ", data[:, 0].mean())
print("平均Y: ", data[:, 1].mean())
print("標準偏差X: ", data[:, 0].std())
print("標準偏差Y: ", data[:, 1].std())
print("MIN X: ", data[:, 0].min())
print("MIN Y: ", data[:, 1].min())
print("MAX X: ", data[:, 0].max())
print("MAX Y: ", data[:, 1].max())
from sklearn.preprocessing import MinMaxScaler
np.random.seed(seed=1)
data = np.random.multivariate_normal( [5, 5], [[5, 0],[0, 2]], 10 )
print("元データ")
print(data)
printout(data)
print("---")
scaler = MinMaxScaler()
print("正規化")
data_norm = scaler.fit_transform(data)
print(data_norm)
printout(data_norm)
出力結果
元データ
[[8.63214665 4.13484578]
[3.81897206 3.48259322]
[6.93511029 1.74513276]
[8.90151771 3.92349088]
[5.71339311 4.64733703]
[8.26937274 2.08652107]
[4.27905321 4.45686512]
[7.53518554 3.44451885]
[4.61443881 3.75852072]
[5.09439281 5.82422518]]
平均X: 6.3793582926820225
平均Y: 3.7504050618892877
標準偏差X: 1.8118979237218
標準偏差Y: 1.128584883455787
MIN X: 3.8189720581437347
MIN Y: 1.7451327605454043
MAX X: 8.901517712729385
MAX Y: 5.82422517959429
---
正規化
[[0.94700076 0.58584429]
[0. 0.4259429 ]
[0.6131058 0. ]
[1. 0.5340301 ]
[0.37273075 0.71148284]
[0.87562434 0.08369222]
[0.0905218 0.66478816]
[0.73117169 0.41660887]
[0.15650951 0.49358724]
[0.25094133 1. ]]
平均X: 0.5037605972566557
平均Y: 0.4915976632398656
標準偏差X: 0.35649417572610337
標準偏差Y: 0.2766754874651595
MIN X: 0.0
MIN Y: 0.0
MAX X: 1.0
MAX Y: 1.0
参考
やったこと
sklearn.preprocessing.StandardScaler を使いデータを標準化します。
平均が0、標準偏差が1の分布に従うように調整されます。
確認環境
$ 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
調査
def printout(data):
print("平均X: ", data[:, 0].mean())
print("平均Y: ", data[:, 1].mean())
print("標準偏差X: ", data[:, 0].std())
print("標準偏差Y: ", data[:, 1].std())
from sklearn.preprocessing import StandardScaler
np.random.seed(seed=1)
data = np.random.multivariate_normal( [5, 5], [[5, 0],[0, 2]], 10 )
print("元データ")
print(data)
printout(data)
print("---")
scaler = StandardScaler()
print("標準化")
data_std = scaler.fit_transform(data)
print(data_std)
printout(data_std)
出力結果
元データ
[[8.63214665 4.13484578]
[3.81897206 3.48259322]
[6.93511029 1.74513276]
[8.90151771 3.92349088]
[5.71339311 4.64733703]
[8.26937274 2.08652107]
[4.27905321 4.45686512]
[7.53518554 3.44451885]
[4.61443881 3.75852072]
[5.09439281 5.82422518]]
平均X: 6.3793582926820225
平均Y: 3.7504050618892877
標準偏差X: 1.8118979237218
標準偏差Y: 1.128584883455787
---
標準化
[[ 1.24333073 0.34063962]
[-1.41309629 -0.2372988 ]
[ 0.30672368 -1.77680238]
[ 1.39199863 0.15336535]
[-0.36755116 0.79474037]
[ 1.04311309 -1.47431001]
[-1.15917406 0.62596981]
[ 0.63790969 -0.27103518]
[-0.97407225 0.007191 ]
[-0.70918205 1.83754022]]
平均X: -1.554312234475219e-16
平均Y: -5.10702591327572e-16
標準偏差X: 0.9999999999999999
標準偏差Y: 1.0000000000000002
参考
str.format でフォーマットする (Python)
2019-08-13やったこと
Python の str.format を使ってみます。
確認環境
$ ipython --version
6.1.0
$ jupyter --version
4.3.0
$ python --version
Python 3.6.2 :: Anaconda custom (64-bit)
調査
print("{}-{}-{}".format("2019", "08", "12"))
出力結果
2019-08-12
参考
やったこと
カテゴリを数値に置き換えるため、sklearn の LabelEncorder を使ってみます。
確認環境
$ 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
調査
from sklearn.preprocessing import LabelEncoder
import pandas as pd
df = pd.DataFrame([
['green', 'M', 10.1, 'class1'],
['red', 'L', 13.5, 'class2'],
['blue', 'XL', 15.3, 'class1']
])
df.columns = ['color', 'size', 'price', 'classlabel']
class_le = LabelEncoder()
y = class_le.fit_transform(df['classlabel'].values)
print(y)
# クラスラベルを整数から文字列に戻す
print(class_le.inverse_transform(y))
出力結果
[0 1 0]
['class1' 'class2' 'class1']
参考
- sklearn.preprocessing.LabelEncoder — scikit-learn 0.21.3 documentation
- Python機械学習プログラミング
numpy.sort、numpy.argsort を使う
2019-08-12やったこと
numpy.sort、numpy.argsort を使い、配列をソートします。
確認環境
$ 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'
調査
numpy.sort
a = np.array([[1,4, 0],[3,1, -2]])
print(np.sort(a))
出力結果
[[ 0 1 4]
[-2 1 3]]
numpy.argsort
a = np.array([[1,4, 0],[3,1, -2]])
print(np.argsort(a))
出力結果
[[2 0 1]
[2 1 0]]
np.argsort
ではインデックスが返却されることが確認できました。
参考
欠損値を補完する (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