OR๊ฒ์ดํธ : 1์ด ํ๋๋ผ๋ ์์ผ๋ฉด 1
x1 x2 y 0 0 0 1 0 1 0 1 1 1 1 1 ๐ผ ๋ฌธ์ ์ ์
๋ฌธ์ ์ ์ : OR ๊ฒ์ดํธ ๊ตฌํ
- 0,0 -> 0
- 1,0 -> 1
- 0,1 -> 1
- 1,1 -> 1
import tensorflow as tf
tf.random.set_seed(777)
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.losses import mse
# ๋ฐ์ดํฐ ์ค๋นํ๊ธฐ
X = np.array([[0,0],[1,0],[0,1],[1,1]])
y = np.array([[0], [1], [1], [1]])
# ๋ชจ๋ธ ๊ตฌ์ฑํ๊ธฐ
model = Sequential()
# ํ๊ฐ์ layer์ ํ๊ฐ์ Dense์ธต
model.add(Dense(1,input_shape=(2,), activation='linear')) # ๋จ์ธต ํผ์
ํธ๋ก
# ๋ชจ๋ธ ์ค์ ํ๊ธฐ
model.compile(optimizer=SGD(), loss=mse, metrics=['acc']) # ์์คํจ์ : mse, ์ ํ๋ acc๋ก ํ์ธ
# ๋ชจ๋ธ ํ์ตํ๊ธฐ
# (ํ์ต๋ฐ์ดํฐ, ์ ๋ต, 500๋ฒ ๊ณต๋ถ)
history = model.fit(X, y, epochs=500)
import matplotlib.pyplot as plt
his_dict = history.history
loss = his_dict['loss']
epochs = range(1, len(loss) + 1)
fig = plt.figure(figsize = (10, 5))
# ํ๋ จ ๋ฐ ๊ฒ์ฆ ์์ค ๊ทธ๋ฆฌ๊ธฐ
ax1 = fig.add_subplot(1, 2, 1)
ax1.plot(epochs, loss, color = 'orange', label = 'train_loss')
ax1.set_title('train loss')
ax1.set_xlabel('epochs')
ax1.set_ylabel('loss')
ax1.legend()
acc = his_dict['acc']
# ํ๋ จ ๋ฐ ๊ฒ์ฆ ์ ํ๋ ๊ทธ๋ฆฌ๊ธฐ
ax2 = fig.add_subplot(1, 2, 2)
ax2.plot(epochs, acc, color = 'blue', label = 'train_accuracy')
ax2.set_title('train accuracy')
ax2.set_xlabel('epochs')
ax2.set_ylabel('accuracy')
ax2.legend()
plt.show()
# ๋ฐ์ดํฐ ์ค๋นํ๊ธฐ
# X1, X2๊ฐ ๋ค๋ฅผ ๋ 1, ๊ฐ์ ๋ 0
X = np.array([[0,0],[1,0],[0,1],[1,1]])
y = np.array([[0], [1], [1], [0]])
๐ OR ๊ฒ์ดํธ์ ๋ฌ๋ฆฌ accuracy๊ฐ ๋์ง ์์ -> ๋ค๋ฅธ ๋ฐฉ๋ฒ ํ์!
# ๋ฐ์ดํฐ ์ค๋นํ๊ธฐ
# X1, X2๊ฐ ๋ค๋ฅผ ๋ 1, ๊ฐ์ ๋ 0
X = np.array([[0,0],[1,0],[0,1],[1,1]])
y = np.array([[0], [1], [1], [0]])
model = Sequential()
# ํ๊ฐ์ layer์ ํ๊ฐ์ Dense์ธต
model.add(Dense(32,input_shape=(2,), activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer=SGD(), loss=mse, metrics=['acc']) # ์์คํจ์ : mse, ์ ํ๋ acc๋ก ํ์ธ
# (ํ์ต๋ฐ์ดํฐ, ์ ๋ต, 500๋ฒ ๊ณต๋ถ)
history = model.fit(X, y, epochs=500)
๐ ์ฌ์ ํ accuracy๊ฐ ๋ฎ์
from tensorflow.keras.optimizers import RMSprop
# ๋ฐ์ดํฐ ์ค๋นํ๊ธฐ
# X1, X2๊ฐ ๋ค๋ฅผ ๋ 1, ๊ฐ์ ๋ 0
X = np.array([[0,0],[1,0],[0,1],[1,1]])
y = np.array([[0], [1], [1], [0]])
xor_model = Sequential()
# ํ๊ฐ์ layer์ ํ๊ฐ์ Dense์ธต
xor_model.add(Dense(32,input_shape=(2,), activation='relu'))
xor_model.add(Dense(1, activation='sigmoid'))
xor_model.compile(optimizer=RMSprop(), loss=mse, metrics=['acc']) # ์์คํจ์ : mse, ์ ํ๋ acc๋ก ํ์ธ
# (ํ์ต๋ฐ์ดํฐ, ์ ๋ต, 100๋ฒ ๊ณต๋ถ)
history = xor_model.fit(X, y, epochs=100)
๐ accuracy๊ฐ epoch๋ฅผ ์ค์์์๋ ์ฌ๋ผ๊ฐ
ํ์ดํผํ๋ผ๋ฏธํฐ ํ๋