<jupyter_start><jupyter_text>Getting started with neural networks: Classification and regression  Classifying movie reviews: A binary classification example  The IMDB dataset 50,000 highly polarized review from the Internet movie database.  25000 traing data, 25000 test data  50% positive, 50% negative  **Loading the IMDB dataset**<jupyter_code>from tensorflow.keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(
    num_words=10000) # only keep 10,000 most frequently occuriring word in the training data
train_data[0]
train_labels[0]
max([max(sequence) for sequence in train_data]) # because we  restricited to the top 10000 most frequent words<jupyter_output><empty_output><jupyter_text>**Decoding reviews back to text**<jupyter_code>word_index = imdb.get_word_index() # word -> integer index 매핑 dictionary
reverse_word_index = dict(
    [(value, key) for (key, value) in word_index.items()])
decoded_review = " ".join( #.join -> list를 문자열로 
    [reverse_word_index.get(i - 3, "?") for i in train_data[0]])
# indices are offset by 3 because 0,1,2 are "padding","start of sequence", "unknown"
decoded_review<jupyter_output><empty_output><jupyter_text>Preparing the data **Encoding the integer sequences via multi-hot encoding** 원-핫 인코딩은 단어 집합의 크기를 벡터의 차원으로 하고, 표현하고 싶은 단어의 인덱스에 1의 값을 부여하고, 다른 인덱스에는 0을 부여하는 단어의 벡터 표현 방식입니다. 이렇게 표현된 벡터를 원-핫 벡터(One-Hot vector)라고 합니다.<jupyter_code>import numpy as np
def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        for j in sequence:
            results[i, j] = 1.
    return results
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
x_train[0]
y_train = np.asarray(train_labels).astype("float32")
y_test = np.asarray(test_labels).astype("float32")<jupyter_output><empty_output><jupyter_text>Building your model 2 intermediate layers with 16 units each  3rd layer will output the scalar prediction regarding the sentiment of the curruent revies **Model definition**<jupyter_code>from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(16, activation="relu"), # 중간 계층 -> relu 함수 사용(음수를 0으로 만드는 함수)
    layers.Dense(16, activation="relu"), 
    layers.Dense(1, activation="sigmoid") # 임의의 값을 [0,1] interval로 나타냄 (1을 가질 가능성)
])<jupyter_output><empty_output><jupyter_text>more unit(a higher-dimensional representation spae) -> 더 복잡한 표현을 학습할 수 있으나, overfit 될 수 있다.  **Compiling the model** - loss choice : binary classification, output of you model is a probability(single unnit layer with a sigmoid activation)     -> **binary cossentropy loss** is best chois - optimizer choice : rmsprob is usually good defalt choice<jupyter_code>model.compile(optimizer="rmsprop",
              loss="binary_crossentropy",
              metrics=["accuracy"])<jupyter_output><empty_output><jupyter_text>Validating your approach **Setting aside a validation set**<jupyter_code>x_val = x_train[:10000] # train data 중 10000개를 validation data에 할당 
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]<jupyter_output><empty_output><jupyter_text>**Training your model**<jupyter_code>history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=20,
                    batch_size=512,
                    validation_data=(x_val, y_val))
history_dict = history.history
history_dict.keys()<jupyter_output><empty_output><jupyter_text>**Plotting the training and validation loss**<jupyter_code>import matplotlib.pyplot as plt
history_dict = history.history
loss_values = history_dict["loss"]
val_loss_values = history_dict["val_loss"]
epochs = range(1, len(loss_values) + 1)
plt.plot(epochs, loss_values, "bo", label="Training loss")
plt.plot(epochs, val_loss_values, "b", label="Validation loss")
plt.title("Training and validation loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>**Plotting the training and validation accuracy**<jupyter_code>plt.clf()
acc = history_dict["accuracy"]
val_acc = history_dict["val_accuracy"]
plt.plot(epochs, acc, "bo", label="Training acc")
plt.plot(epochs, val_acc, "b", label="Validation acc")
plt.title("Training and validation accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>약 4 epochs 이후로는 loss가 커지고 accuracy가 줄어듦-> 4 epochs까지만 진행  **Retraining a model from scratch**<jupyter_code>model = keras.Sequential([
    layers.Dense(16, activation="relu"),
    layers.Dense(16, activation="relu"),
    layers.Dense(1, activation="sigmoid")
])
model.compile(optimizer="rmsprop",
              loss="binary_crossentropy",
              metrics=["accuracy"])
model.fit(x_train, y_train, epochs=4, batch_size=512)
results = model.evaluate(x_test, y_test)
results #test loss, accuracy<jupyter_output><empty_output><jupyter_text>Using a trained model to generate predictions on new data<jupyter_code>model.predict(x_test)

# 일부 표본의 경우 모델이 신뢰 가능하지만(0.99 이상, 0.01이하), 다른 표본(0.6,0.4)의 경우 신뢰도가 낮다<jupyter_output><empty_output><jupyter_text>Further experiments - 최종 분류 전 2개의 layor 사용 -> 1개 또는 3개의 layor 사용해보기- 더 많거나 적은 units 사용해보기- binary crossentropy 대신 mse사용해보기- relu 대신 tanh 활성화함수 사용해보기   Wrapping up  Classifying newswires: A multiclass classification example - singlelabel multiclass classification : 하나의 data는 한 class에만 속함- multilabel multiclass classification : 하나의 data가 여러 class에 속함  The Reuters dataset reuters가 출간한 짧은 뉴스 와이어  46개의 토픽이 있으며, 각 토픽에 10개 이상의 example을 가지고 있음 **Loading the Reuters dataset**<jupyter_code>from tensorflow.keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(
    num_words=10000)
len(train_data)
len(test_data)
train_data[10]<jupyter_output><empty_output><jupyter_text>**Decoding newswires back to text**<jupyter_code>word_index = reuters.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_newswire = " ".join([reverse_word_index.get(i - 3, "?") for i in
    train_data[0]])
train_labels[10]
decoded_newswire<jupyter_output><empty_output><jupyter_text>Preparing the data **Encoding the input data**<jupyter_code>x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)<jupyter_output><empty_output><jupyter_text>**Encoding the labels**<jupyter_code>def to_one_hot(labels, dimension=46):
    results = np.zeros((len(labels), dimension))
    for i, label in enumerate(labels):
        results[i, label] = 1.
    return results
y_train = to_one_hot(train_labels)
y_test = to_one_hot(test_labels)
# one hot encoding (keras 내장)
from tensorflow.keras.utils import to_categorical
y_train = to_categorical(train_labels)
y_test = to_categorical(test_labels)<jupyter_output><empty_output><jupyter_text>Building your model **Model definition**<jupyter_code>model = keras.Sequential([
    layers.Dense(64, activation="relu"), # 조금 더 큰 층을 사용하자! 16차원 공간으로는 46차원 클래스를 구분하기에 너무 작음 
    layers.Dense(64, activation="relu"),
    layers.Dense(46, activation="softmax") # softmax함수의 output[i]은 i에 속할 prob며, 46개의 값을 모두 더하면 1이 된다 
])<jupyter_output><empty_output><jupyter_text>**Compiling the model**<jupyter_code>model.compile(optimizer="rmsprop",
              loss="categorical_crossentropy", #  두 확률 분포 사이의 거리를 측정하는 loss function.
              metrics=["accuracy"])<jupyter_output><empty_output><jupyter_text>Validating your approach **Setting aside a validation set**<jupyter_code>x_val = x_train[:1000]
partial_x_train = x_train[1000:]
y_val = y_train[:1000]
partial_y_train = y_train[1000:]<jupyter_output><empty_output><jupyter_text>**Training the model**<jupyter_code>history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=20,
                    batch_size=512,
                    validation_data=(x_val, y_val))<jupyter_output>Epoch 1/20
16/16 [==============================] - 2s 64ms/step - loss: 2.7331 - accuracy: 0.5247 - val_loss: 1.8661 - val_accuracy: 0.6360
Epoch 2/20
16/16 [==============================] - 1s 52ms/step - loss: 1.4837 - accuracy: 0.7035 - val_loss: 1.3390 - val_accuracy: 0.7160
Epoch 3/20
16/16 [==============================] - 1s 50ms/step - loss: 1.0751 - accuracy: 0.7795 - val_loss: 1.1495 - val_accuracy: 0.7550
Epoch 4/20
16/16 [==============================] - 1s 51ms/step - loss: 0.8368 - accuracy: 0.8281 - val_loss: 1.0556 - val_accuracy: 0.7710
Epoch 5/20
16/16 [==============================] - 1s 49ms/step - loss: 0.6637 - accuracy: 0.8624 - val_loss: 0.9694 - val_accuracy: 0.7950
Epoch 6/20
16/16 [==============================] - 1s 49ms/step - loss: 0.5314 - accuracy: 0.8908 - val_loss: 0.9372 - val_accuracy: 0.8010
Epoch 7/20
16/16 [==============================] - 1s 49ms/step - loss: 0.4217 - accuracy: 0.9131 - val_loss: 0.8984 - val_accuracy: 0.8110
Epoch 8/20
16[...]<jupyter_text>**Plotting the training and validation loss**<jupyter_code>import matplotlib.pyplot as plt
loss = history.history["loss"]
val_loss = history.history["val_loss"]
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, "bo", label="Training loss")
plt.plot(epochs, val_loss, "b", label="Validation loss")
plt.title("Training and validation loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>**Plotting the training and validation accuracy**<jupyter_code>plt.clf()
acc = history.history["accuracy"]
val_acc = history.history["val_accuracy"]
plt.plot(epochs, acc, "bo", label="Training accuracy")
plt.plot(epochs, val_acc, "b", label="Validation accuracy")
plt.title("Training and validation accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>epochs = 9 정도에서 오버피팅이 발생한다. **Retraining a model from scratch**<jupyter_code>model = keras.Sequential([
  layers.Dense(64, activation="relu"),
  layers.Dense(64, activation="relu"),
  layers.Dense(46, activation="softmax")
])
model.compile(optimizer="rmsprop",
              loss="categorical_crossentropy",
              metrics=["accuracy"])
model.fit(x_train,
          y_train,
          epochs=9,
          batch_size=512)
results = model.evaluate(x_test, y_test)
results # 약 78%의 정확도
import copy
test_labels_copy = copy.copy(test_labels)
np.random.shuffle(test_labels_copy)
hits_array = np.array(test_labels) == np.array(test_labels_copy)
hits_array.mean()
# 이건 뭘까....................................................................???<jupyter_output><empty_output><jupyter_text>Generating predictions on new data<jupyter_code>predictions = model.predict(x_test)
predictions[0].shape
predictions[0]
np.sum(predictions[0])
np.argmax(predictions[0])<jupyter_output><empty_output><jupyter_text>A different way to handle the labels and the loss<jupyter_code>y_train = np.array(train_labels)
y_test = np.array(test_labels)
model.compile(optimizer="rmsprop",
              loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])<jupyter_output><empty_output><jupyter_text>The importance of having sufficiently large intermediate layers **A model with an information bottleneck**<jupyter_code>model = keras.Sequential([
    layers.Dense(64, activation="relu"),
    layers.Dense(4, activation="relu"),
    layers.Dense(46, activation="softmax")
])
model.compile(optimizer="rmsprop",
              loss="categorical_crossentropy", 
# categorical crossentropy는 레이블이 범주형 인코딩일 때 -> 정수 레이블을 사용할 때는 sparse_categorical_crossentropy를 사용
              metrics=["accuracy"])
model.fit(partial_x_train,
          partial_y_train,
          epochs=20,
          batch_size=128,
          validation_data=(x_val, y_val))<jupyter_output>Epoch 1/20
63/63 [==============================] - 2s 21ms/step - loss: 3.0788 - accuracy: 0.0873 - val_loss: 2.3693 - val_accuracy: 0.3000
Epoch 2/20
63/63 [==============================] - 1s 18ms/step - loss: 1.8819 - accuracy: 0.5173 - val_loss: 1.6085 - val_accuracy: 0.6550
Epoch 3/20
63/63 [==============================] - 1s 18ms/step - loss: 1.3610 - accuracy: 0.6740 - val_loss: 1.4366 - val_accuracy: 0.6550
Epoch 4/20
63/63 [==============================] - 1s 18ms/step - loss: 1.1712 - accuracy: 0.6963 - val_loss: 1.3801 - val_accuracy: 0.6710
Epoch 5/20
63/63 [==============================] - 1s 18ms/step - loss: 1.0438 - accuracy: 0.7296 - val_loss: 1.3421 - val_accuracy: 0.6820
Epoch 6/20
63/63 [==============================] - 1s 18ms/step - loss: 0.9401 - accuracy: 0.7750 - val_loss: 1.3363 - val_accuracy: 0.6950
Epoch 7/20
63/63 [==============================] - 1s 22ms/step - loss: 0.8520 - accuracy: 0.7934 - val_loss: 1.3570 - val_accuracy: 0.7000
Epoch 8/20
63[...]<jupyter_text>Further experiments - 최종 분류 전 2개의 layor 사용 -> 1개 또는 3개의 layor 사용해보기- 더 많거나 적은 units 사용해보기  Wrapping up  Predicting house prices: A regression example * regression : 예측  logistic regression ; 분류  The Boston Housing Price dataset **Loading the Boston housing dataset**<jupyter_code>from tensorflow.keras.datasets import boston_housing
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
train_data.shape
test_data.shape
train_targets # 주택의 중간 가격, 1000$ 단위<jupyter_output><empty_output><jupyter_text>Preparing the data **Normalizing the data** different scale -> nomalizing 필요<jupyter_code>mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std
test_data -= mean
test_data /= std
# 반드시 train data의 mean과 std를 사용해 정규화<jupyter_output><empty_output><jupyter_text>Building your model **Model definition**<jupyter_code>def build_model():
    model = keras.Sequential([
        layers.Dense(64, activation="relu"), # small trainign data -> overfitting 확률 높음 -> 작은 model
        layers.Dense(64, activation="relu"),
        layers.Dense(1) # linear layor, scalar unit을 위한 구성 
    ])
    model.compile(optimizer="rmsprop", loss="mse", metrics=["mae"]) # loss = mse : 회귀 문제에서 널리 사용됨 / matrics = mean absolute error : 예측과 타깃 사이의 절댓값
    return model<jupyter_output><empty_output><jupyter_text>Validating your approach using K-fold validation **K-fold validation**<jupyter_code>k = 4
num_val_samples = len(train_data) // k
num_epochs = 100
all_scores = []
for i in range(k):
    print(f"Processing fold #{i}")
    val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]
    val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]
    partial_train_data = np.concatenate(
        [train_data[:i * num_val_samples],
         train_data[(i + 1) * num_val_samples:]],
        axis=0)
    partial_train_targets = np.concatenate(
        [train_targets[:i * num_val_samples],
         train_targets[(i + 1) * num_val_samples:]],
        axis=0)
    model = build_model()
    model.fit(partial_train_data, partial_train_targets,
              epochs=num_epochs, batch_size=16, verbose=0)
    val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)
    all_scores.append(val_mae)
all_scores
np.mean(all_scores)<jupyter_output><empty_output><jupyter_text>**Saving the validation logs at each fold** ephochs을 500으로 늘려 훈련<jupyter_code>num_epochs = 500
all_mae_histories = []
for i in range(k):
    print(f"Processing fold #{i}")
    val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]
    val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]
    partial_train_data = np.concatenate(
        [train_data[:i * num_val_samples],
         train_data[(i + 1) * num_val_samples:]],
        axis=0)
    partial_train_targets = np.concatenate(
        [train_targets[:i * num_val_samples],
         train_targets[(i + 1) * num_val_samples:]],
        axis=0)
    model = build_model()
    history = model.fit(partial_train_data, partial_train_targets,
                        validation_data=(val_data, val_targets),
                        epochs=num_epochs, batch_size=16, verbose=0)
    mae_history = history.history["val_mae"]
    all_mae_histories.append(mae_history)<jupyter_output>Processing fold #0
Processing fold #1
Processing fold #2
Processing fold #3<jupyter_text>**Building the history of successive mean K-fold validation scores**<jupyter_code>average_mae_history = [
    np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]<jupyter_output><empty_output><jupyter_text>**Plotting validation scores**<jupyter_code>plt.plot(range(1, len(average_mae_history) + 1), average_mae_history)
plt.xlabel("Epochs")
plt.ylabel("Validation MAE")
plt.show()<jupyter_output><empty_output><jupyter_text>**Plotting validation scores, excluding the first 10 data points**<jupyter_code>truncated_mae_history = average_mae_history[10:]
plt.plot(range(1, len(truncated_mae_history) + 1), truncated_mae_history)
plt.xlabel("Epochs")
plt.ylabel("Validation MAE")
plt.show()<jupyter_output><empty_output><jupyter_text>**Training the final model**<jupyter_code>model = build_model()
model.fit(train_data, train_targets,
          epochs=130, batch_size=16, verbose=0)
test_mse_score, test_mae_score = model.evaluate(test_data, test_targets)
test_mae_score<jupyter_output><empty_output><jupyter_text>Generating predictions on new data<jupyter_code>predictions = model.predict(test_data)
predictions[0]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1447828830379166, 'fraction_numerical': 0.03998164400848964, 'mean_word_length': 5.020027624309392, 'pattern_counts': {'":': 0, '<': 138, '<?xml version=': 0, '>': 150, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '35', 'dir': 'jupyter-structured-clean-dedup', 'id': '469877', 'license': 'Apache-2.0', 'n_tokens_mistral': 7048, 'n_tokens_neox': 6712, 'n_words': 1349, 'path': 'chapter04_getting-started-with-neural-networks.ipynb', 'repo_name': 'oneoclockc/deeplearning-for-AI', 'size': '17433'}