• Skip to main content
  • Skip to primary sidebar

学習記録

プログラミング

データの選択、特定

2018年1月16日 by 河副 太智 Leave a Comment

選択、特定

1
2
3
4
5
6
df[col] # Returns column with label col as Series
df[[col1, col2]] # Returns Columns as a new DataFrame
s.iloc[0] # Selection by position (selects first element)
s.loc[0] # Selection by index (selects element at index 0)
df.iloc[0,:] # First row
df.iloc[0,0] # First element of first column

 

Filed Under: Pandas

データクリーニング

2018年1月16日 by 河副 太智 Leave a Comment

データクリーニング、データクレンジング

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Data CleaningPython
 
df.columns = ['a','b','c'] # Renames columns
pd.isnull() # Checks for null Values, Returns Boolean Array
pd.notnull() # Opposite of s.isnull()
df.dropna() # Drops all rows that contain null values
df.dropna(axis=1) # Drops all columns that contain null values
df.dropna(axis=1,thresh=n) # Drops all rows have have less than n non null values
df.fillna(x) # Replaces all null values with x
s.fillna(s.mean()) # Replaces all null values with the mean (mean can be replaced with almost any function from the statistics section)
s.astype(float) # Converts the datatype of the series to float
s.replace(1,'one') # Replaces all values equal to 1 with 'one'
s.replace([1,3],['one','three']) # Replaces all 1 with 'one' and 3 with 'three'
df.rename(columns=lambda x: x + 1) # Mass renaming of columns
df.rename(columns={'old_name': 'new_ name'}) # Selective renaming
df.set_index('column_one') # Changes the index
df.rename(index=lambda x: x + 1) # Mass renaming of index

 

Filed Under: データクレンジング

機械学習コード全体像

2018年1月16日 by 河副 太智 Leave a Comment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Machine LearningPython
 
# Import libraries and modules
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.externals import joblib
# Load red wine data.
dataset_url = 'http://mlr.cs.umass.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv'
data = pd.read_csv(dataset_url, sep=';')
# Split data into training and test sets
y = data.quality
X = data.drop('quality', axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.2,
                                                    random_state=123,
                                                    stratify=y)
# Declare data preprocessing steps
pipeline = make_pipeline(preprocessing.StandardScaler(),
                         RandomForestRegressor(n_estimators=100))
# Declare hyperparameters to tune
hyperparameters = { 'randomforestregressor__max_features' : ['auto', 'sqrt', 'log2'],
                  'randomforestregressor__max_depth': [None, 5, 3, 1]}
# Tune model using cross-validation pipeline
clf = GridSearchCV(pipeline, hyperparameters, cv=10)
clf.fit(X_train, y_train)
# Refit on the entire training set
# No additional code needed if clf.refit == True (default is True)
# Evaluate model pipeline on test data
pred = clf.predict(X_test)
print r2_score(y_test, pred)
print mean_squared_error(y_test, pred)
# Save model for future use
joblib.dump(clf, 'rf_regressor.pkl')
# To load: clf2 = joblib.load('rf_regressor.pkl')

 

Filed Under: 作成実績, 教師有り, 機械学習

カテゴリ変数の変換

2018年1月15日 by 河副 太智 Leave a Comment

タイタニックのデータmaleを1、femaleを0に変換し、
搭乗地域S,C,Qを0,1,2に変換

1
2
3
#カテゴリ変数の変換
df['Sex'] = df['Sex'].apply(lambda x: 1 if x == 'male' else 0)
df['Embarked'] = df['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)

 

Filed Under: python3

データ平均値から要素と目的データの関連を可視化

2018年1月15日 by 河副 太智 Leave a Comment

seabornでデータ平均値から要素と目的データの関連を可視化

 

タイタニックの乗客の年齢をx、性別をyとして生存の有無を表示
男性と女性に分けて、更に生存の有無を分け、更に平均年齢をグラフ表示

1
2
3
4
5
6
7
8
9
10
11
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
 
 
#csvファイルをデータフレームに読み込む
df = pd.read_csv('train.csv')
 
#seabornでデータプロットすると
sns.barplot(x="Age",y="Sex",hue='Survived',data=df)

 

 

Filed Under: グラフ

ユーザー、自分の問いに答える(アイリス)

2018年1月1日 by 河副 太智 Leave a Comment

ユーザーがアイリスの形状を4種類指定して、
それがどの種類のアイリスになるのかを予測する

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn
import mglearn
 
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from IPython.display import display
from sklearn.neighbors import KNeighborsClassifier
 
%matplotlib inline
 
 
 
iris_dataset = load_iris()
 
#花の特徴左からガクの長さ、ガクの幅、花弁の長さ、花弁の幅
#トータル150のデータの内10個を表示
print("◆最初の10個のカラムデータ:\n\n{}".format(iris_dataset["data"][:10]))
 
#上記のdataに対する答え [0=setosa,1=versicolor,2=virginica]
print("\n◆上記データに対する答え [0=setosa,1=versicolor,2=virginica]:\n{}".format(iris_dataset["target"][:10]))
 
#学習用に75%テスト用に25%に分ける
X_train,X_test,y_train, y_test = train_test_split(
    iris_dataset["data"],iris_dataset["target"],random_state=0)
 
#X_trainは(112, 4)となる、これは上記で75%に分けた112の花びらのデータ数と
#そのデータの要素4つ分になる
print("\n◆75%に分けた112の花びらのデータ数とそのデータの要素4つ:\n{}".format(X_train.shape))
 
#y_trainは(112)となる、これは上記で75%に分けた花びらの種類の答え(0,1,2)の
#どれか一つが入っている
print("\n◆75%に分けた花びらの種類の答え(0,1,2)のどれか一つ:\n{}".format(y_train.shape))
 
#X_testは(38,4)となるこれは上記で25%に分けた38の花びらのデータ数と
#そのデータの要素4つ分になる
print("\n◆25%に分けた38の花びらのデータ数とそのデータの要素4つ分:\n{}".format(X_test.shape))
 
#y_test shapeは(38.)となるこれは上記で25%に分けた花びらの種類の答え(0,1,2)の
#どれか一つが入っている
print("\n◆25%に分けた38の花びらの種類の答え(0,1,2)のどれか一つ:\n{}".format(y_test.shape))
 
#[データの検査]
#答えである(0,1,2)がある程度分離できているかどうかを可視化する
#アイリスの種類ごとに色を変えて表示する、この場合は3点がある程度分離できていれば
#訓練できる可能性が高いと言える、逆にゴチャゴチャであれば学習は難しい
 
#1.X_trainのデータからDataFrameを作る
#iris_dataset.feature_namesの文字列をつかってカラムに名前を付ける
iris_dataframe = pd.DataFrame(X_train,columns=iris_dataset.feature_names)
 
#データフレームからscatter matrixを作成し、y_trainに従って色をつける
pd.plotting.scatter_matrix(iris_dataframe,c=y_train,figsize=(15,15),marker="o",
                        hist_kwds={"bins":20},s=60,alpha=.8,cmap=mglearn.cm3)
 
#KNeighborsClassifierをfitで(X_train,y_train)を予測
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train,y_train)
 
 
#KNeighborsClassifierにて行った予測の精度を確認
print("◆KNeighborsClassifierにて行った予測の精度を確認:\n{:.2f}".format(knn.score(X_test, y_test)))
 
 
#ユーザーからの問いに対する予測を行う[5,2.9,1,0.2]がユーザーからの問い
X_new = np.array([[5,2.9,1,0.2]])
 
#元のX_test.shapeと同じ配列でなければいけないので配列形式を確認
print("◆元のデータの配列形式:\n{}".format(iris_dataset["data"][:1]))
print("◆ユーザーデータの配列形式(元と同じ形なのでOK):\n{}".format(X_new))
 
 
 
prediction = knn.predict(X_new)
print("◆0,1,2のどれを選択したか:\n{}".format(prediction))
print("◆ターゲット(花の名前):\n{}".format(iris_dataset["target_names"][prediction]))

 

結果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
◆最初の10個のカラムデータ:
 
[[ 5.1  3.5  1.4  0.2]
[ 4.9  3.   1.4  0.2]
[ 4.7  3.2  1.3  0.2]
[ 4.6  3.1  1.5  0.2]
[ 5.   3.6  1.4  0.2]
[ 5.4  3.9  1.7  0.4]
[ 4.6  3.4  1.4  0.3]
[ 5.   3.4  1.5  0.2]
[ 4.4  2.9  1.4  0.2]
[ 4.9  3.1  1.5  0.1]]
 
◆上記データに対する答え [0=setosa,1=versicolor,2=virginica]:
[0 0 0 0 0 0 0 0 0 0]
 
◆75%に分けた112の花びらのデータ数とそのデータの要素4つ:
(112, 4)
 
◆75%に分けた花びらの種類の答え(0,1,2)のどれか一つ:
(112,)
 
◆25%に分けた38の花びらのデータ数とそのデータの要素4つ分:
(38, 4)
 
◆25%に分けた38の花びらの種類の答え(0,1,2)のどれか一つ:
(38,)
◆KNeighborsClassifierにて行った予測の精度を確認:
0.97
◆元のデータの配列形式:
[[ 5.1  3.5  1.4  0.2]]
◆ユーザーデータの配列形式(元と同じ形なのでOK):
[[ 5.   2.9  1.   0.2]]
◆0,1,2のどれを選択したか:
[0]
◆ターゲット(花の名前):
['setosa']

 

 

Filed Under: scikit-learn, グラフ, 作成実績, 教師有り, 機械学習

  • « Go to Previous Page
  • Page 1
  • Interim pages omitted …
  • Page 17
  • Page 18
  • Page 19
  • Page 20
  • Page 21
  • Interim pages omitted …
  • Page 55
  • Go to Next Page »

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in