import sqlite3
dbpath = "./hw.sqlite3"
sql = '''
CREATE TABLE IF NOT EXISTS person (
id INTEGER PRIMARY KEY,
height NUMBER,
weight NUMBER,
typeNo INTEGER
)
'''
with sqlite3.connect(dbpath) as conn:
conn.execute(sql)
import sqlite3
import random
dbpath = "./hw.sqlite3"
def insert_db(conn):
# ダミーで身長と体重と体型データを作る --- (*1)
height = random.randint(130, 180)
weight = random.randint(30, 100)
# 体型データはBMIに基づいて自動生成 --- (*2)
type_no = 1
bmi = weight / (height / 100) ** 2
if bmi < 18.5:
type_no = 0
elif bmi < 25:
type_no = 1
elif bmi < 30:
type_no = 2
elif bmi < 35:
type_no = 3
elif bmi < 40:
type_no = 4
else:
type_no = 5
# SQLと値を指定してDBに値を挿入 --- (*3)
sql = '''
INSERT INTO person (height, weight, typeNo)
VALUES (?,?,?)
'''
values = (height,weight, type_no)
print(values)
conn.executemany(sql,[values])
# DBに接続して100件のデータを挿入
with sqlite3.connect(dbpath) as conn:
# データを100件挿入 --- (*4)
for i in range(5000):
insert_db(conn)
# トータルで挿入した行数を調べる --- (*5)
c = conn.execute('SELECT count(*) FROM person')
cnt = c.fetchone()
print(cnt[0])
import sqlite3
dbpath = "./hw.sqlite3"
select_sql = "SELECT * FROM person"
with sqlite3.connect(dbpath) as conn:
for row in conn.execute(select_sql):
print(row)
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
in_size = 2 # 身長と体重の二次元
nb_classes = 6 # 体型を6段階に分ける
# MLPモデル構造を定義
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(in_size,)))
model.add(Dropout(0.5))
model.add(Dense(nb_classes, activation='softmax'))
# モデルをコンパイル
model.compile(
loss='categorical_crossentropy',
optimizer=RMSprop(),
metrics=['accuracy'])
model.save('hw_model.h5')
print("saved")
from tensorflow.keras.utils import to_categorical
import keras
import numpy as np
import sqlite3
import os
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
# データベースから最新の5000件を読み出す
dbpath = "./hw.sqlite3"
select_sql = "SELECT * FROM person ORDER BY id DESC LIMIT 5000" # 修正
x = []
y = []
with sqlite3.connect(dbpath) as conn:
for row in conn.execute(select_sql):
id, height, weight, type_no = row
# 正規化
height = height / 200
weight = weight / 150
y.append(type_no)
x.append(np.array([height, weight]))
# モデルを読み込む
model = load_model('hw_model.h5')
# 既に学習データがあれば読み込む
if os.path.exists('hw_weights.weights.h5'):
model.load_weights('hw_weights.weights.h5') # ファイル名の変更
nb_classes = 6 # 体型を6段階に分ける
y = to_categorical(y, num_classes=nb_classes) # 修正
# モデルをコンパイル
model.compile(
optimizer=RMSprop(),
loss='categorical_crossentropy',
metrics=['accuracy']
)
# モデルを訓練
model.fit(np.array(x), y, epochs=100, batch_size=32)
# 結果を保存する
model.save_weights('hw_weights.weights.h5') # 修正
from keras.models import load_model
import numpy as np
# 学習モデルを読み込む --- (*1)
model = load_model('hw_model.h5')
# 学習済みデータを読み込む --- (*2)
model.load_weights('hw_weights.weights.h5')
# ラベル
LABELS = [
'低体重(痩せ型)', '普通体重', '肥満(1度)',
'肥満(2度)', '肥満(3度)', '肥満(4度)'
]
# テストデータを指定 --- (*3)
height = 160
weight = 50
# 0-1の範囲に収まるようにデータを正規化 --- (*4)
test_x = [height / 200, weight / 150]
# 予測 --- (*5)
pre = model.predict(np.array([test_x]))
idx = pre[0].argmax()
print(LABELS[idx], '/可能性', pre[0][idx])
import os
from keras.models import load_model
import numpy as np
import random
from tensorflow.keras.utils import to_categorical
# 学習モデルを読み込む
model = load_model('hw_model.h5')
# 学習済みデータを読み込む前に存在確認
weights_path = 'hw_weights.weights.h5'
if os.path.exists(weights_path):
model.load_weights(weights_path)
else:
print(f"File not found: {weights_path}.")
# ここで適切な対処を行う
# 例:モデルの再トレーニング、重みの初期化など
# 正解データを1000件作成
x = []
y = []
for i in range(1000):
h = random.randint(130, 180)
w = random.randint(30, 100)
bmi = w / ((h / 100) ** 2)
# タイプ番号を決定
if bmi < 18.5:
type_no = 0
elif bmi < 25:
type_no = 1
elif bmi < 30:
type_no = 2
elif bmi < 35:
type_no = 3
elif bmi < 40:
type_no = 4
else:
type_no = 5
x.append(np.array([h / 200, w / 150]))
y.append(type_no)
# 形式を変換
x = np.array(x)
y = to_categorical(y, 6)
# 正解率を評価
if model is not None:
score = model.evaluate(x, y, verbose=1)
print("正解率=", score[1], "ロス=", score[0])
else:
print("Model is not loaded correctly.")