# =========================
# 学習済みモデルの保存まで
# =========================
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import os, random
from tensorflow.keras import models, layers

# データの読み込み
df = pd.read_csv('wine_class.csv')

# 目的変数
t = df['Class']

# 入力変数
x = df.drop('Class', axis=1)

# ラベルを 0 から始める
t = t.values - 1
x = x.values


# 学習データとテストデータの分割
x_train, x_test, t_train, t_test = train_test_split(x, t, train_size=0.7, random_state=0)

# 32 bit にキャスト
x_train = np.array(x_train, np.float32)
x_test = np.array(x_train, np.float32)
t_train = np.array(t_train, np.int32)
t_test = np.array(t_train, np.int32)

def reset_seed(seed=0):
    os.environ['PYTHONHASHSEED'] = '0'
    random.seed(seed) # random関数のシードを固定
    np.random.seed(seed) # numpyのシードを固定
    tf.random.set_seed(seed) # tensorflowのシードを固定

# シードの固定
reset_seed(0)

# モデルの構築
model = tf.keras.models.Sequential([
    tf.keras.layers.BatchNormalization(input_shape=(10,)),
    tf.keras.layers.Dense(10, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

# モデルのコンパイル
model.compile(optimizer='sgd',
               loss='sparse_categorical_crossentropy',
               metrics=['accuracy'])

# モデルの学習
history = model.fit(x_train, t_train,
          batch_size=10,
          epochs=50,
          validation_data=(x_test, t_test))

# 正解率と損失を Pandas の形式に変換
result_batchnorm = pd.DataFrame(history.history)
print(result_batchnorm)

# 目的関数の値
result_batchnorm[['loss', 'val_loss']].plot()
plt.show()

# 正解率
result_batchnorm[['accuracy', 'val_accuracy']].plot()
plt.show()

# モデルの保存
model.save(filepath='wine_model.h5', save_format='h5')