EEM-272 Makine Öğrenmesine Giriş
Ders 9
Yapay sinir ağları, tensorflow uygulaması
MNIST veri seti örnekler
0 ve 1 rakamlarının sınıflandırılması
Sigmoid fonksiyonu
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.losses import BinaryCrossentropy
# MNIST veri setini yükle
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
# sadece 0 ve 1 olanları filtrele
mask = (y_train == 0) | (y_train == 1)
X = X_train[mask]
y = y_train[mask]
# 0 ve 1 indekslerini al
idx0 = np.where(y == 0)[0][:1000]
idx1 = np.where(y == 1)[0][:1000]
# 1000 tane 0 ve 1000 tane 1 seç
indices = np.concatenate([idx0, idx1])
X = X[indices]
y = y[indices]
# veriyi karıştır
perm = np.random.permutation(len(X))
X = X[perm]
y = y[perm]
# rastgele bir görüntü göster
rand_index = np.random.randint(len(X))
plt.imshow(X[rand_index], cmap='gray')
plt.title(f"Label: {y[rand_index]}")
plt.axis("off")
plt.show()
X = X.astype("float32") / 255.0
# modeli beslemek için flatten yap (28x28 -> 784)
X = X_train.reshape(X.shape[0], -1)
X.shape
# model oluştur
model = Sequential([
Input(shape=(784,)),
Dense(units=25, activation='sigmoid'),
Dense(units=15, activation='sigmoid'),
Dense(units=1, activation='sigmoid')
])
# compile
# default learning_rate = 0.01
model.compile(
loss=BinaryCrossentropy(),
optimizer='SGD',
metrics=['accuracy']
)
model.summary()
# modeli eğit
model.fit(X, y, epochs=30)
# rastgele bir örnek seç
idx = np.random.randint(0, X.shape[0])
# görüntüyü al (flatten olduğu için tekrar 28x28 yapıyoruz)
image = X[idx].reshape(28,28)
# tahmin için modele uygun hale getir
sample = X[idx].reshape(1, -1)
# model tahmini
prediction = model.predict(sample)
# sınıfa çevir
predicted_class = (prediction > 0.5).astype(int)
# görüntüyü çizdir
plt.imshow(image, cmap='gray')
plt.title(f"Gerçek: {y[idx]} | Tahmin: {predicted_class[0][0]} (olasılık: {prediction[0][0]:.3f})")
plt.axis("off")
plt.show()
ReLU fonksiyonu
# model oluştur
model = Sequential([
Input(shape=(784,)),
Dense(units=25, activation='relu', input_shape=(784,)),
Dense(units=15, activation='relu'),
Dense(units=1, activation='sigmoid')
])
# compile
# default learning_rate = 0.01
model.compile(
loss=BinaryCrossentropy(),
optimizer='SGD',
metrics=['accuracy']
)
model.summary()
# modeli eğit
model.fit(X, y, epochs=30)
# rastgele bir örnek seç
idx = np.random.randint(0, X.shape[0])
# görüntüyü al (flatten olduğu için tekrar 28x28 yapıyoruz)
image = X[idx].reshape(28,28)
# tahmin için modele uygun hale getir
sample = X[idx].reshape(1, -1)
# model tahmini
prediction = model.predict(sample)
# sınıfa çevir
predicted_class = (prediction > 0.5).astype(int)
# görüntüyü çizdir
plt.imshow(image, cmap='gray')
plt.title(f"Gerçek: {y[idx]} | Tahmin: {predicted_class[0][0]} (olasılık: {prediction[0][0]:.3f})")
plt.axis("off")
plt.show()
sigmoid fonksiyonu, normalizasyonlu
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.losses import BinaryCrossentropy
# MNIST veri setini yükle
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
# sadece 0 ve 1 olanları filtrele
mask = (y_train == 0) | (y_train == 1)
X = X_train[mask]
y = y_train[mask]
# 0 ve 1 indekslerini al
idx0 = np.where(y == 0)[0][:1000]
idx1 = np.where(y == 1)[0][:1000]
# 1000 tane 0 ve 1000 tane 1 seç
indices = np.concatenate([idx0, idx1])
X = X[indices]
y = y[indices]
# veriyi karıştır
perm = np.random.permutation(len(X))
X = X[perm]
y = y[perm]
# rastgele bir görüntü göster
rand_index = np.random.randint(len(X))
plt.imshow(X[rand_index], cmap='gray')
plt.title(f"Label: {y[rand_index]}")
plt.axis("off")
plt.show()
X_train = X.astype("float32") / 255.0
# modeli beslemek için flatten yap (28x28 -> 784)
X_train = X_train.reshape(X.shape[0], -1)
X_train.shape
# model oluştur
model = Sequential([
Input(shape=(784,)),
Dense(units=25, activation='sigmoid'),
Dense(units=15, activation='sigmoid'),
Dense(units=1, activation='sigmoid')
])
# compile
# default learning_rate = 0.01
model.compile(
loss=BinaryCrossentropy(),
optimizer='SGD',
metrics=['accuracy']
)
model.summary()
# modeli eğit
model.fit(X_train, y, epochs=30)
# rastgele bir örnek seç
idx = np.random.randint(0, X.shape[0])
# görüntüyü al (flatten olduğu için tekrar 28x28 yapıyoruz)
image = X[idx].reshape(28,28)
# tahmin için modele uygun hale getir
sample = X_train[idx].reshape(1, -1)
# model tahmini
prediction = model.predict(sample)
# sınıfa çevir
predicted_class = (prediction > 0.5).astype(int)
# görüntüyü çizdir
plt.imshow(image, cmap='gray')
plt.title(f"Gerçek: {y[idx]} | Tahmin: {predicted_class[0][0]} (olasılık: {prediction[0][0]:.3f})")
plt.axis("off")
plt.show()
ReLU fonksiyonu, normalizasyonlu
# model oluştur
model = Sequential([
Input(shape=(784,)),
Dense(units=25, activation='relu', input_shape=(784,)),
Dense(units=15, activation='relu'),
Dense(units=1, activation='sigmoid')
])
# compile
# default learning_rate = 0.01
model.compile(
loss=BinaryCrossentropy(),
optimizer='SGD',
metrics=['accuracy']
)
model.summary()
# modeli eğit
model.fit(X_train, y, epochs=30)
# rastgele bir örnek seç
idx = np.random.randint(0, X.shape[0])
# görüntüyü al (flatten olduğu için tekrar 28x28 yapıyoruz)
image = X[idx].reshape(28,28)
# tahmin için modele uygun hale getir
sample = X_train[idx].reshape(1, -1)
# model tahmini
prediction = model.predict(sample)
# sınıfa çevir
predicted_class = (prediction > 0.5).astype(int)
# görüntüyü çizdir
plt.imshow(image, cmap='gray')
plt.title(f"Gerçek: {y[idx]} | Tahmin: {predicted_class[0][0]} (olasılık: {prediction[0][0]:.3f})")
plt.axis("off")
plt.show()
Multi-class classification - Çok sınıflı sınıflandırma
SparseCategoricalCrossentropy versiyonu
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
# MNIST veri setini yükle
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
# Her sınıftan 1000 örnek seç
selected_indices = []
for digit in range(10):
idx = np.where(y_train == digit)[0][:1000]
selected_indices.append(idx)
selected_indices = np.concatenate(selected_indices)
X = X_train[selected_indices]
y = y_train[selected_indices]
# veriyi karıştır
perm = np.random.permutation(len(X))
X = X[perm]
y = y[perm]
# rastgele bir görüntü göster
rand_index = np.random.randint(len(X))
plt.imshow(X[rand_index], cmap='gray')
plt.title(f"Label: {y[rand_index]}")
plt.axis("off")
plt.show()
# normalize et (0-255 → 0-1)
X = X.astype("float32") / 255.0
# flatten (28x28 → 784)
X = X.reshape(X.shape[0], -1)
# model oluştur
model = Sequential([
Dense(units=25, activation='relu', input_shape=(784,)),
Dense(units=15, activation='relu'),
Dense(units=10, activation='softmax')
])
model.summary()
from tensorflow.keras.losses import SparseCategoricalCrossentropy
# compile
model.compile(
loss=SparseCategoricalCrossentropy(),
optimizer='SGD',
metrics=['accuracy']
)
# eğit
model.fit(X, y, epochs=30)
CategoricalCrossentropy versiyonu
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.losses import CategoricalCrossentropy
# MNIST veri setini yükle
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
# Her sınıftan 1000 örnek seç
selected_indices = []
for digit in range(10):
idx = np.where(y_train == digit)[0][:1000]
selected_indices.append(idx)
selected_indices = np.concatenate(selected_indices)
X = X_train[selected_indices]
y = y_train[selected_indices]
# veriyi karıştır
perm = np.random.permutation(len(X))
X = X[perm]
y = y[perm]
# normalize
X = X.astype("float32") / 255.0
# flatten
X = X.reshape(X.shape[0], -1)
# one-hot encoding
y = to_categorical(y, num_classes=10)
# model
model = Sequential([
Dense(units=25, activation='relu', input_shape=(784,)),
Dense(units=15, activation='relu'),
Dense(units=10, activation='softmax')
])
model.summary()
# compile
model.compile(
loss=CategoricalCrossentropy(),
optimizer='SGD',
metrics=['accuracy']
)
# eğit
model.fit(X, y, epochs=30)
Adam optimizastonu versiyonu
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.losses import CategoricalCrossentropy
# MNIST veri setini yükle
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
# Her sınıftan 1000 örnek seç
selected_indices = []
for digit in range(10):
idx = np.where(y_train == digit)[0][:1000]
selected_indices.append(idx)
selected_indices = np.concatenate(selected_indices)
X = X_train[selected_indices]
y = y_train[selected_indices]
# veriyi karıştır
perm = np.random.permutation(len(X))
X = X[perm]
y = y[perm]
# normalize
X = X.astype("float32") / 255.0
# flatten
X = X.reshape(X.shape[0], -1)
# one-hot encoding
y = to_categorical(y, num_classes=10)
# model
model = Sequential([
Dense(units=25, activation='relu', input_shape=(784,)),
Dense(units=15, activation='relu'),
Dense(units=10, activation='softmax')
])
model.summary()
# compile
model.compile(
loss=CategoricalCrossentropy(),
optimizer='adam',
metrics=['accuracy']
)
# eğit
model.fit(X, y, epochs=30)