<jupyter_start><jupyter_text>텐서플로우로 회귀 모델 만들기* [첫 번째 신경망 훈련하기: 기초적인 분류 문제  |  TensorFlow Core](https://www.tensorflow.org/tutorials/keras/classification)<jupyter_code>import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv("data/diabetes.csv")
df.shape
df.head()
df = df[df["Insulin"] > 0]
df.shape
df.groupby("Outcome")["Insulin"].describe()
df["Insulin"].hist(bins=100)
train = df.sample(frac=0.8,random_state=0)
test = df.drop(train.index)

train.shape, test.shape
label_name = "Insulin"
X_train = train.drop(label_name, axis=1)
y_train = train[label_name]

X_train.shape, y_train.shape
X_test = test.drop(label_name, axis=1)
y_test = test[label_name]

X_test.shape, y_test.shape
df.sample()
data = df.drop(label_name, axis=1)
input_shape = data.shape[1]
input_shape<jupyter_output><empty_output><jupyter_text>* 이미지 출처 : https://cs231n.github.io/neural-networks-1/  딥러닝 레이어 만들기<jupyter_code>import tensorflow as tf

model = tf.keras.models.Sequential([
  tf.keras.layers.Input(shape=(input_shape)),
  tf.keras.layers.Dense(128, activation='relu'), # relu, swish
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(1)
])

optimizer = tf.keras.optimizers.RMSprop(0.001)

model.compile(loss='mse',
            optimizer=optimizer,
            metrics=['mae', 'mse'])
model.summary()<jupyter_output>Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 128)               1152      
_________________________________________________________________
dropout (Dropout)            (None, 128)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 129       
=================================================================
Total params: 1,281
Trainable params: 1,281
Non-trainable params: 0
_________________________________________________________________<jupyter_text>학습<jupyter_code>early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)

history = model.fit(X_train, y_train, epochs=100,
                    validation_split = 0.2, verbose=0, callbacks=early_stop)
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
hist.tail()
import matplotlib.pyplot as plt

def plot_history(history):
    hist = pd.DataFrame(history.history)
    hist['epoch'] = history.epoch

    plt.figure(figsize=(8,12))

    plt.subplot(2,1,1)
    plt.xlabel('Epoch')
    plt.ylabel('Mean Abs Error')
    plt.plot(hist['epoch'], hist['mae'],
           label='Train Error')
    plt.plot(hist['epoch'], hist['val_mae'],
           label = 'Val Error')
    plt.legend()

    plt.subplot(2,1,2)
    plt.xlabel('Epoch')
    plt.ylabel('Mean Square Error')
    plt.plot(hist['epoch'], hist['mse'],
           label='Train Error')
    plt.plot(hist['epoch'], hist['val_mse'],
           label = 'Val Error')
    plt.legend()
    plt.show()

plot_history(history)<jupyter_output><empty_output><jupyter_text>예측<jupyter_code>y_pred = model.predict(X_test)
y_pred[:5]
y_predict = y_pred.flatten()
y_predict<jupyter_output><empty_output><jupyter_text>평가<jupyter_code>loss, mae, mse = model.evaluate(X_test, y_test, verbose=2)

print("테스트 세트의 평균 절대 오차: {:5.2f}".format(mae))
sns.jointplot(x=y_test, y=y_predict, kind="reg")<jupyter_output><empty_output><jupyter_text>MAE<jupyter_code>error = y_test - y_predict
mae = abs(error).mean()
mae<jupyter_output><empty_output><jupyter_text>MAPE(Mean absolute percentage error)<jupyter_code>mape = abs((y_test - y_predict) / y_test).mean()
mape<jupyter_output><empty_output><jupyter_text>MSE<jupyter_code>mse = (error) ** 2
mse = mse.mean()
mse<jupyter_output><empty_output><jupyter_text>RMSE<jupyter_code>np.sqrt(mse)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16763885366472228, 'fraction_numerical': 0.018260207963479585, 'mean_word_length': 4.817109144542773, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 37, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '523856', 'license': 'MIT', 'n_tokens_mistral': 1507, 'n_tokens_neox': 1485, 'n_words': 217, 'path': 'pima-indians-diabetes/baseline-tensorflow2-regression.ipynb', 'repo_name': 'DamiSoh/KaggleStruggle', 'size': '3943'}