-
-
Save dj1711572002/561dbf571f6330d84d95f394cd1a0b5c to your computer and use it in GitHub Desktop.
Python _IMU_GravityAttitude_SVM_classification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding utf-8 | |
import datetime | |
import pickle # モデルをファイルとして使用する用 | |
import keyboard | |
import numpy as np # numpyで2次元配列を扱うため | |
import serial # シリアル通信を行うため | |
from sklearn.svm import SVC, SVR # 学習用 | |
import csv | |
import os | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
import time | |
#----------Global variable---------------- | |
X = [] | |
Y = [] | |
def serTch(filenamei,length:int,gestures:int,cmN): | |
#X = [] | |
#Y = [] | |
wr=[] | |
print("serTch INN") | |
path = os.getcwd() | |
print(path) | |
print(type(path)) | |
#length = 100 #ジェスチャの長さ(連続で受信するデータの個数) | |
#gestures = 3 #ジェスチャの種類の数 | |
times = 1 #各ジェスチャを行う回数 | |
#==================================================== | |
#now = datetime.datetime.now() | |
#name = now.strftime('%m%d_%H%M') | |
#filenamei ='imu.csv' | |
#filename = 'model_' + name + '.sav' # 入力した名前の学習モデルのファイル名 | |
#filename = 'model.sav' # 入力した名前の学習モデルのファイル名 | |
print('Connecting...') | |
ser = serial.Serial(cmN,115200,timeout=None) #ポート番号19からシリアル受信 | |
print("-----Input c:CreateModel,g:Gesture Measuring +ENTER") | |
print("filenamei="+filenamei+"length="+str(length)+"gestures="+str(gestures)) | |
#mx = [] # 各軸ごとの配列を初期化 | |
#my = [] | |
#mz = [] | |
with open(filenamei, 'w', newline='') as f: | |
writer = csv.writer(f) | |
for i in range(gestures * times): | |
cnt = 0 #受信したデータのカウント用 | |
gesture_num = i % gestures + 1 #ジェスチャ番号を指定 | |
print('Push a then Do gesture No.', gesture_num) | |
while True: | |
line=ser.readline()#Binary | |
linestr= line.decode('utf8')#バイナリーをASCII変換 | |
strarr=linestr.split(',') | |
datano=strarr[0] | |
x=strarr[1] | |
y=strarr[2] | |
z=strarr[3] | |
tim=strarr[4] | |
if keyboard.is_pressed('a'): | |
print("key hit") | |
switch = "a" | |
else: | |
switch='' | |
if switch =='a' and cnt == 0: #クリックされたらカウント開始 | |
print("cnt=1") | |
cnt = 1 | |
if cnt != 0: #ジェスチャ中a | |
#print("In gestureNo"+str(gesture_num)+" datacnt="+str(cnt)) | |
print("In gestureNo"+str(gesture_num)+'datanp=' + datano + ',x=' + x + 'y=' + y+ 'z=' + z + 'tim=' + tim) | |
#mx.append(x.rstrip('\r\n')) # シリアルから受け取ってたデータのゴミを取って配列へ追加 | |
#my.append(y.rstrip('\r\n')) | |
#mz.append(z.rstrip('\r\n')) | |
cnt += 1 | |
if cnt == length: #lengthまでいったら次のジェスチャ待ちへ | |
print("length Up") | |
break | |
print("CSV:gnum="+str(gesture_num)+"x="+x+"y="+y+"z="+z) | |
wr = [gesture_num,x, y, z] | |
writer.writerow(wr) | |
#Y.append(str(gesture_num)) # 学習ラベル用リストへ追加 | |
#m = mx + my + mz #三軸の加速度を横一列にする | |
#X.append(m) #学習データ用リストへ追加 | |
#print("Xappend:Gesture_num="+str(gesture_num)) | |
#print(X) | |
print("serial closed") | |
ser.close() # シリアルを閉じ | |
f.close() # isn't actually needed | |
#print("def result:") | |
#print(X) | |
# print(Y) | |
#return [X,Y] | |
#========================================================================== | |
# def onerow(matrix) 行列の行を1行にまとめる | |
def onerow(matrix): | |
target=[] | |
rown=matrix.shape[0] | |
coln=matrix.shape[1] | |
for i in range(rown): | |
for j in range(coln): | |
target.append(str(matrix[i,j])) | |
return target | |
# -----------main--------------------------------------- | |
while True: | |
print("-----Input c:CreateModel,g:Gesture Measuring +ENTER") | |
keys = input() | |
millisec = time.time() * 1000 | |
if keys == 'c': | |
serTch('imu.csv',100,3,'COM28') | |
df = pd.read_csv("imu.csv", sep=",", header=None, names=['gnum', 'gx', 'gy', 'gz']) | |
print(df) | |
#----------データフレームをターゲット別に分割してnumpy行列に変換---------------- | |
df1 = df.loc[df['gnum'] == 1, :] # gnu | |
df1t=df1.T | |
arr1=df1t.values | |
arr1 = arr1[1:4, :] | |
print("arr1=",end='') | |
print(arr1.shape) | |
print(arr1) | |
result1=onerow(arr1) | |
df2 = df.loc[df['gnum'] == 2, :] # gnu | |
df2t=df2.T | |
arr2=df2t.values | |
arr2 = arr2[1:4, :] | |
result2 = onerow(arr2) | |
df3 = df.loc[df['gnum'] == 3, :] # gnu | |
df3t=df3.T | |
arr3=df3t.values | |
arr3 = arr3[1:4, :] | |
result3 = onerow(arr3) | |
print("result1,2,3=") | |
print(result1) | |
print(result2) | |
print(result3) | |
X=[result1,result2,result3] | |
#X= np.array(X, dtype="<U") | |
#listを合体してXを作成 | |
Y=['1','2','3'] | |
print("---X=",end='') | |
print(X) | |
print("---Y=",end='') | |
print(Y) | |
#X = np.array(X).reshape(-1, 1) | |
# SVM start | |
#X = np.array(X).reshape(-1, 1) | |
model = SVC(kernel = 'linear', C=1, gamma=1) #学習モデルのパラメータを指定 | |
model.fit(X,np.ravel(Y)) #学習を行う | |
with open('model.sav', 'wb') as fp_model: # 学習モデルを保存するためのファイルを開く | |
pickle.dump(model, fp_model) # モデルを保存 | |
print('Model created.') | |
#model.fit(X, Y) # 学習を行う | |
# %% サポートベクターマシン分類して性能評価指標算出 | |
from sklearn.svm import SVC | |
from sklearn.metrics import accuracy_score, f1_score | |
# X = iris[['petal_width', 'petal_length']].values # 説明変数 | |
# y = iris['species'].values # 目的変数(3種類のアヤメ種類) | |
#clf = SVC() # SVM分類用インスタンス | |
#clf.fit(X, Y) # 学習 | |
y_pred = model.predict(X) # 推論 | |
print(f'Accuracy={accuracy_score(Y, y_pred)}') # 正解率を表示 | |
print(f'F1={f1_score(Y, y_pred, average="macro")}') # F1-Macroを表示 | |
from seaborn_analyzer import classplot | |
classplot.class_separator_plot(model, ['gx','gy'],'gnum', df) | |
classplot.class_separator_plot(model, ['gy', 'gz'], 'gnum', df) | |
classplot.class_separator_plot(model, ['gz', 'gx'], 'gnum', df) | |
plt.show() | |
# CSV読み込みして散布図プロット | |
#df = pd.read_csv("imu.csv", sep=",", header=None, names=['gnum', 'gyX', 'gyY', 'gyZ']) | |
#df = pd.read_csv("imu.csv", sep=",", header=None, names=['gnum', 'acX', 'acY', 'acZ']) | |
print(df) | |
print(len(df.columns)) | |
print(df.info()) | |
sns.pairplot(df, hue='gnum') | |
plt.tight_layout() | |
plt.show() | |
sns.lineplot(df) | |
plt.show() | |
#df = pd.DataFrame(model) | |
#sns.pairplot(df, height=1.5) | |
#-----------------------------start gesture measuring----------------------------------------------- | |
elif keys=='g': | |
print("=================Test Input MODE================ ") | |
serTch('imut.csv', 100, 1, 'COM28') | |
#print(loaded_model) | |
print('Do any gesture!') | |
with open('imut.csv', 'rb') as fs: | |
writer = csv.writer(fs) | |
dfs = pd.read_csv("imut.csv", sep=",", header=None, names=['gnum', 'gx', 'gy', 'gz']) | |
print(dfs) | |
# ----------データフレームをターゲット別に分割してnumpy行列に変換---------------- | |
df1 = dfs.loc[dfs['gnum'] == 1, :] # gnu | |
df1t = df1.T | |
arr1 = df1t.values | |
arr1 = arr1[1:4, :] | |
result1 = onerow(arr1) | |
print("result1=", end='') | |
print(result1) | |
X = [result1] | |
#X = np.array(X, dtype="<U") | |
#X=[['-0.07','-6.71','7.1']] | |
print("X=", end='') | |
print(X) | |
#======================== predict=============================== | |
with open('model.sav', 'rb') as fp_model: # 学習モデルファイルを開く | |
loaded_model = pickle.load(fp_model) # モデルをロード | |
print("loaded file= model.sav") | |
pre = loaded_model.predict(X) # ジェスチャの判定 | |
print('pre=') | |
print( pre) | |
#sns.lineplot(dfs) | |
#plt.show() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment