Pandas
import pandas as pd
df,dataframe
axisとは。。
列(縦)に沿った処理はaxis=0
行(横)に沿った処理はaxis=1
DataFrameとSeriesの違い。。
Seriesは1つのカラムを指すデータ構造。1次元構造
DataFrameは多数のSeriesの集まり。2次元構造
・pd.read_csv()
csvをdataframeとして読み込む
index_col:indexとするcolumn名
names=['colomnの名前','colomnの名前']
DataFrameをcsvに書き出し
・df.colums
dataframe内の列名のみを表示
・df.dropna(axis=1)
NaNを削除
・df.カラム名
DataFrame内の特定の列を指定する
・まとめて特定の列を一つの変数に入れる
colums=["example1","example2","example3"]
df[colums]
列名をリストにまとめて、dataframe[リスト]とすることで複数の特定の列を一気に読み出せる
・iloc[0]
指定した数字の行数を受け取れる
df.列の名前.iloc[0] 指定した列の0行目の値を取得
.iloc[0:10] 10行目まで取得
.iloc[ [ 0,1,10] , : ] 指定した複数の行(0,1,10)&すべての列を取得
・.loc
.loc[ [ 0,10,100 ] , [ 'country' , 'province' , 'region_1' ] ] 指定した複数の行&指定した複数の列を取得
同じことを.ilocでやろうとしても無理
.loc [ df.country == ' Italy ' ] df.countryがItalyの行を取得
df.loc[(df.country.isin(['Australia','New Zealand'])) & (df.points >= 95)] .locのなかで、.isin(List)を使用すると、listに合致するものを取得
・df.describe()
count,mean, std,min,25%,50%,75%,maxを一括で表示
・df.median()
最頻値を取得
・df.unique()
列の情報を重複なしで取得
・df.value_counts()
それぞれの要素がいくつあるのかを取得
・df.mean()
平均値を取得
センタリングといって、各特徴量の中心を0に揃える。各特徴量において、平均を計算し、それを各値から引く前処理で使用される。↓
df.price - df.price.mean()
・df.groupby()
グループに分ける
・df.groupby().agg([len, min, max])
もう一つのgroupby()メソッドとして、agg()がある。
len,min,maxを出してくれる
・df.dtype
なんのtypeなのかを調査
・df.astype('type名')
dataframeを好きなtypeに変換する
・pd.concat([df,df])
複数のDataFrameを結合
sklearn
・DecisionTreeRegressor(random_state=1)
モデルを定義する。random_state に数値を指定し、毎回同じ結果になるようにする。
・fit()
モデルの学習
・predict()
モデルの推論
・train_test_split()
例:train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)
データを訓練用とテスト用に分ける
割合、個数を指定: 引数test_size, train_size
シャッフルするかを指定: 引数shuffle
乱数シードを指定: 引数random_state
・mean_absolute_error(検証用データ,推論結果)
平均絶対誤差の計算
tensorflow keras
KerasのLiner層(全結合層)
model = keras.Sequential([
#最初だからinput_sizeが必要
layers.Dense(unitサイズ , input_shape=[入力サイズ])
#途中
layers.Dense(unitサイズ)
#最後の全結合層
layers.Dense(1)
])
重みをみる
w, b = model.weights
KerasのActivation層(活性化関数層)
model = keras.Sequential([
layers.Activation('relu'),
layers.Dense(32),
layers.Activation('relu'),
layers.Dense(1),
])
Kerasのロス関数・最適化関数
model.compile(
optimizer = "adam",
loss="mae"
)
optimizerで最適化アルゴリズムを記述
lossでロス関数を記述
optimizerの種類:adam,sgd
lossの種類:mae,binary_crossentropy,
metricsの種類:['binary_accuracy'],
model train
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)
history = model.fit(
train_X,train_y,
validation_data=(val_X,val_y),
batch_size=256,
epochs = 200
)
・trainの様子をgifで表示
learning_rate = 0.05
batch_size = 32
num_examples = 256
animate_sgd(
learning_rate=learning_rate,
batch_size=batch_size,
num_examples=num_examples,
# You can also change these, if you like
steps=50, # total training steps (batches seen)
true_w=3.0, # the slope of the data
true_b=2.0, # the bias of the data
)
・早期終了
early_stopping = EarlyStopping(
min_delta=0.001,
patience=5,
restore_best_weights=True,
)
model = keras.Sequential([
layers.Dense(128, activation='relu', input_shape=input_shape),
layers.Dropout(rate=0.3),
layers.Dense(64, activation='relu'),
layers.Dropout(rate=0.3),
layers.Dense(1)
])
全結合層と全結合層の間にDropout()を挟む
・BatchNormalization
model = keras.Sequential([
layers.BatchNormalization(),
layers.Dense(512, activation='relu', input_shape=input_shape),
layers.BatchNormalization(),
layers.Dense(512, activation='relu'),
layers.BatchNormalization(),
layers.Dense(512, activation='relu'),
layers.BatchNormalization(),
layers.Dense(1),
])
Dropoutと同じく、各層の間に入れる