Python独習!

習得したPython知識をペイフォワード

Pythonでラインプロファイルの正規化

釣鐘型のラインプロファイルを正規化して、他サンプルと比較しやすくする。その次のステップとして半値幅を求める、などなど。

結果

プロファイルの形状はそのままで最小値が0、最大値が1のプロファイルが得られた。
f:id:greenhornprofessional:20191225221728p:plain

プログラム

生データをスプライン補間して、標準化する、という内容。
02_Normalization_002.py

import csv
import numpy as np
from scipy import signal, interpolate
from matplotlib import pylab as plt

fn = '02_sample.csv' #.pyファイルと同じ階層に置く
cal = 1 #x軸データの縮尺調整用のパラメータ。他サンプルとの比較に使う。

#標準化の関数定義
def min_max(x, axis=0):
    min = x.min(axis=axis, keepdims=True)
    max = x.max(axis=axis, keepdims=True)
    result = (x-min)/(max-min)
    return result

#csvを読み込んでdata_arrayに格納
with open(fn, mode='r', newline='') as f_in:
    reader = csv.reader(f_in)
    data_array = [row for row in reader]

#data_arrayの中身を確認する
#print(data_array)

#data_arrayをx,yに分けるための配列を定義する
plot_x = []
plot_y = []

#data_arrayの要素を一個ずつ取り出して、各配列に格納する
for i in data_array:
    plot_x.append(float(i[1])*cal) #要素は文字列として扱われているのでfloatに変換する
    plot_y.append(float(i[2]))

#linspaceにx軸データ範囲が必要なのでxの最小値/最大値を調べる
xs = min(plot_x)
xm = max(plot_x)
print("x軸の最小値は",xs)
print("x軸の最大値は",xm)

#lilnspaceでデータ補間数を決める
tt = np.linspace(xs, xm, 1000)

#2次スプライン補間
f = interpolate.interp1d(plot_x, plot_y, kind="quadratic")
y = f(tt)

#配列yを標準化する
yy = min_max(y, axis=0)

#左右軸をつかってデータプロット
fig, ax1 = plt.subplots()
ax1.plot(plot_x, plot_y, 'ob', label=r'$Raw data$')
ax2 = ax1.twinx()  # 2つのプロットを関連付ける
ax2.plot(tt, yy, 'C1', label=r'$Min-Max normalization$')

#凡例を表示
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, loc='upper left')

#軸ラベルの設定
ax1.set_xlabel('x')
ax1.set_ylabel('$Raw data$')
ax2.set_ylabel('$Min-Max normalization$')
plt.show()

参考にさせていただいた記事

deepage.net
qiita.com

/* -----codeの行番号----- */