Makine Öğrenmesi Nedir?
Makine öğrenmesi, bilgisayarların örnek verilerden örüntü öğrenerek tahmin veya gruplama yapmasını sağlar. Denetimli ve denetimsiz öğrenmenin farkını, eğitim-test ayrımını ve sınıflandırma, regresyon, kümeleme algoritmalarını gerçek hayat örnekleriyle keşfedin.
- Makine Öğrenmesi

Makine öğrenmesinin temel mantığı
Bir makine öğrenmesi sistemi, örneklerden girdiler ile sonuçlar arasındaki ilişkiyi öğrenen bir model kurar. Örneğin önceki ev satışlarında oda sayısı, konum ve metrekare bilgileriyle satış fiyatı arasındaki örüntüyü öğrenip yeni bir ev için tahmin üretir.
Modelin girdileri özellikler (X), tahmin etmek istediğimiz çıktı ise hedef/değişken (y) olarak adlandırılır. Eğitim sırasında algoritma model parametrelerini veriye göre ayarlar; model daha sonra görmediği örneklerde tahmin yapar.
Veri
Geçmiş gözlemler ve özellikler
Öğrenme
Model parametrelerinin ayarlanması
Değerlendirme
Görülmemiş veride performansı ölçme
Kullanım
Yeni örnekler için tahmin/segment
Denetimli ve denetimsiz öğrenme
| Özellik | Denetimli öğrenme | Denetimsiz öğrenme |
|---|---|---|
| Eğitim verisi | Girdiler ve bilinen hedef etiket birlikte bulunur. | Genellikle hedef etiketi yoktur; algoritma yapıyı veriden arar. |
| Ana amaç | Yeni örneğin hedefini tahmin etmek. | Benzerlik, grup, yoğunluk veya düşük boyutlu yapı keşfetmek. |
| Örnek sorusu | Bu işlem sahte mi? Bu evin fiyatı ne olur? | Müşteriler hangi davranış gruplarına ayrılıyor? |
| Tipik görev | Sınıflandırma ve regresyon | Kümeleme ve boyut indirgeme |
Denetimli öğrenmede doğru cevapları içeren geçmiş kayıtlar modelin öğrenmesine rehberlik eder. Denetimsiz öğrenmede ise önceden verilmiş sınıf adları olmayabilir; keşfedilen grupları analist yorumlar ve iş anlamı kazandırır.
Sınıflandırma: kategori tahmini
Sınıflandırma, hedef değişkeni kategorik olan denetimli öğrenme problemidir. İki sınıflı örneklerde sonuç “evet/hayır”, çok sınıflı örneklerde “ürün A/B/C” olabilir.
- Spam tespiti: e-posta metninden spam / spam değil sınıfı tahmini.
- Kredi riski: başvuru ve ödeme geçmişine göre temerrüt risk sınıfı.
- Arıza uyarısı: sensör değerlerinden cihazın arıza verip vermeyeceğini tahmin.
Lojistik regresyon, karar ağaçları, rastgele ormanlar, destek vektör makineleri ve k-en yakın komşu yaygın sınıflandırma algoritmalarıdır. Algoritma seçimi; veri miktarı, yorumlanabilirlik, gecikme ve hata maliyetine bağlıdır.
Basit scikit-learn örneği
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
pred = model.predict(X_test)
print("Test doğruluğu:", accuracy_score(y_test, pred))
Doğruluk, doğru sınıflandırılan örneklerin payıdır. Sınıflar dengesizse tek başına yanıltıcı olabilir; precision, recall, F1 ve confusion matrix gibi ölçüleri de inceleyin.
Regresyon: sayısal değer tahmini
Regresyon, sürekli veya sayısal bir hedefi tahmin eder. Bir e-ticaret şirketinde talep miktarı, bir belediyede günlük su tüketimi veya bir ev için satış fiyatı tahmini örnek verilebilir.
Doğrusal regresyon ilişkiyi doğrusal biçimde ifade eder; karar ağaçları, rastgele orman ve gradient boosting daha karmaşık örüntüleri öğrenebilir. Karmaşık model her zaman daha iyi değildir: aşırı uyum, açıklanabilirlik ve bakım maliyetlerini gözetin.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error
import numpy as np
housing = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(
housing.data, housing.target, test_size=0.2, random_state=42
)
reg = LinearRegression().fit(X_train, y_train)
pred = reg.predict(X_test)
mae = mean_absolute_error(y_test, pred)
rmse = np.sqrt(mean_squared_error(y_test, pred))
print(f"MAE={mae:.2f}, RMSE={rmse:.2f}")
MAE, tahminlerle gerçek değerler arasındaki mutlak hataların ortalamasını; RMSE ise büyük hataları daha fazla cezalandıran karekök ortalama kare hatayı verir. Ölçeği hedef değişkenle aynıdır. İyi/kötü değerlendirmesi kullanım amacına ve basit bir başlangıç modeline göre yapılır.
Kümeleme: etiketsiz grupları keşfetme
Kümeleme, benzer gözlemleri aynı grupta toplamaya çalışan denetimsiz öğrenme görevidir. Örneğin müşteriler satın alma sıklığı ve harcama tutarına göre segmentlere ayrılabilir; bir haber arşivi benzer içerik kümelerine bölünebilir.
K-Means algoritması seçilen k adet merkez etrafında gruplar oluşturur. Öznitelikleri ölçeklemek önemlidir; çünkü büyük sayısal aralığa sahip bir özellik mesafe hesabını baskılayabilir. Kümeleri “yüksek değerli müşteri” gibi adlandırmadan önce her grubun profilini inceleyin.
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
import numpy as np
# X: satırlar müşteriler, sütunlar ör. aylık sipariş ve harcama
cluster_model = make_pipeline(
StandardScaler(),
KMeans(n_clusters=3, random_state=42, n_init=10)
)
labels = cluster_model.fit_predict(X)
print(np.bincount(labels))
Kümeleme hedef etiketi olmadığından “doğru sınıfı buldu” diye doğrudan değerlendirilemez. Silhouette skoru gibi iç ölçüler yardımcı olabilir; fakat iş açısından anlamlı gruplar üretip üretmediğini alan uzmanıyla kontrol edin. K-Means’te küme sayısı seçimi ve aykırı gözlemler sonucu etkiler.
Eğitim ve test verisi ne işe yarar?
Modelin başarısını eğitimde gördüğü örneklerde ölçmek genellikle iyimser sonuç verir. Veri kümesini eğitim (train) ve test parçalarına ayırmak, modeli bir bölümde öğrenip diğer bölümde daha önce görmediği örneklerde değerlendirmeye yarar.
Train
Model parametrelerini öğrenmek için kullanılır.
Validation
Model/ayar seçimi için; çoğunlukla çapraz doğrulamayla.
Test
Son karar verilince genel performansın tarafsız değerlendirmesi.
Canlı veri
Gerçek kullanımda dağılım ve performans izleme.
Basit başlangıçta örneğin %80 eğitim / %20 test kullanılabilir; oran evrensel kural değildir. Küçük veri, sınıf dengesizliği, kullanıcı grupları veya zaman sıralı kayıtlar farklı bölme yöntemleri gerektirebilir. Sınıflandırmada stratify=y sınıf oranlarını korumaya yardımcı olur. Zaman serisinde geçmişten geleceğe doğru bölün; rastgele karıştırmak geleceğin bilgisini geçmiş tahminine sızdırabilir.
Aşırı uyum, yetersiz uyum ve genelleme
- Aşırı uyum (overfitting): Model eğitim örneklerine ve gürültüye fazla uyum sağlar; eğitim skoru yüksekken yeni veri başarısı düşük olabilir.
- Yetersiz uyum (underfitting): Model ilişkileri yakalayamayacak kadar basittir; eğitim ve test başarısı düşüktür.
- Genelleme: Modelin eğitimde görmediği, hedef kullanım koşullarına benzeyen örneklerde işe yarar tahmin üretmesidir.
Çapraz doğrulama, eğitim verisini farklı parçalara bölerek model/ayarların daha kararlı değerlendirilmesini sağlar. Test kümesini tekrar tekrar ayar seçmek için kullanmak, test bilgisinin karar sürecine sızmasına ve performans tahmininin iyimserleşmesine yol açabilir.
Uçtan uca makine öğrenmesi iş akışı
- Problemi tanımla: Tahmin edilecek hedefi ve kararın nasıl kullanılacağını belirle.
- Veriyi hazırla: Birim, eksik değer, aykırı değer, etiket kalitesi ve zaman kapsamını incele.
- Doğru görev türünü seç: Kategori için sınıflandırma, sayısal değer için regresyon, etiketsiz grup keşfi için kümeleme.
- Veriyi böl: Test kümesini mümkün olduğunca son değerlendirmeye kadar ayır.
- Basit bir başlangıç kur: Baseline ile performansı karşılaştır; gereken ön işleme adımlarını pipeline içine al.
- Uygun metrikle değerlendir: Hata türlerinin iş maliyetini dikkate al.
- Yorumla ve izle: Hedef gruplardaki performansı, veri kaymasını ve üretim sonuçlarını takip et.
Özet
Makine öğrenmesi, örnek verilerden örüntü öğrenerek tahmin veya yapı keşfi yapar. Etiketli hedef varsa denetimli öğrenme; hedef etiketi olmadan grup/yapı arıyorsanız denetimsiz öğrenme kullanılır. Sınıflandırma kategori, regresyon sayısal değer tahmin eder; kümeleme benzer gözlemleri gruplar. Modeli daha önce görmediği uygun veride değerlendirmek, veri sızıntısını önlemek ve başarıyı doğru metrikle ölçmek güvenilir sonuç için temel adımlardır.
Kaynaklar
The basic logic of machine learning
A machine learning system builds a model that learns the relationship between inputs and outcomes from examples. From past house sales, for instance, it learns the pattern between the number of rooms, the location and the floor area on one side and the sale price on the other, then produces a prediction for a new house.
The model's inputs are called features (X) and the output we want to predict is the target variable (y). During training the algorithm tunes the model parameters against the data; the model then makes predictions on examples it has not seen.
Data
Past observations and features
Learning
Tuning the model parameters
Evaluation
Measuring performance on unseen data
Use
Predictions or segments for new examples
Supervised and unsupervised learning
| Feature | Supervised learning | Unsupervised learning |
|---|---|---|
| Training data | Inputs come together with a known target label. | There is usually no target label; the algorithm looks for structure in the data. |
| Main goal | Predict the target for a new example. | Discover similarity, groups, density or low-dimensional structure. |
| Example question | Is this transaction fraudulent? What will this house sell for? | Which behavioural groups do the customers fall into? |
| Typical task | Classification and regression | Clustering and dimensionality reduction |
In supervised learning, past records containing the right answers guide the model's learning. In unsupervised learning there may be no class names given in advance; the analyst interprets the groups that emerge and gives them business meaning.
Classification: predicting a category
Classification is the supervised problem in which the target variable is categorical. In two-class examples the outcome may be "yes/no", in multi-class ones "product A/B/C".
- Spam detection: predicting the spam / not-spam class from the text of an e-mail.
- Credit risk: a default risk class based on the application and the payment history.
- Failure warning: predicting from sensor readings whether a device will fail.
Logistic regression, decision trees, random forests, support vector machines and k-nearest neighbours are common classification algorithms. The choice depends on the amount of data, interpretability, latency and the cost of an error.
A simple scikit-learn example
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
pred = model.predict(X_test)
print("Test accuracy:", accuracy_score(y_test, pred))
Accuracy is the share of correctly classified examples. On its own it can mislead when the classes are imbalanced; look at measures such as precision, recall, F1 and the confusion matrix too.
Regression: predicting a numeric value
Regression predicts a continuous or numeric target. Demand volume at an e-commerce company, daily water consumption at a municipality, or the sale price of a house are all examples.
Linear regression expresses the relationship in linear form; decision trees, random forests and gradient boosting can learn more complex patterns. A complex model is not always better: weigh overfitting, explainability and maintenance cost.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error
import numpy as np
housing = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(
housing.data, housing.target, test_size=0.2, random_state=42
)
reg = LinearRegression().fit(X_train, y_train)
pred = reg.predict(X_test)
mae = mean_absolute_error(y_test, pred)
rmse = np.sqrt(mean_squared_error(y_test, pred))
print(f"MAE={mae:.2f}, RMSE={rmse:.2f}")
MAE gives the mean of the absolute errors between the predictions and the actual values; RMSE gives the root mean squared error, which penalises large errors more. Both are on the same scale as the target variable. Whether a value counts as good or bad depends on the intended use and on a simple baseline model.
Clustering: discovering unlabelled groups
Clustering is the unsupervised task of gathering similar observations into the same group. Customers can be split into segments by purchase frequency and spend, say, or a news archive divided into clusters of similar content.
The K-Means algorithm forms groups around a chosen number of centres, k. Scaling the features matters, because a feature with a large numeric range can dominate the distance calculation. Examine the profile of each group before naming a cluster something like "high-value customers".
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
import numpy as np
# X: rows are customers, columns e.g. monthly orders and spend
cluster_model = make_pipeline(
StandardScaler(),
KMeans(n_clusters=3, random_state=42, n_init=10)
)
labels = cluster_model.fit_predict(X)
print(np.bincount(labels))
Because clustering has no target label, it cannot be judged directly on whether it "found the right class". Internal measures such as the silhouette score can help; but check with a domain expert whether it produces groups that mean something for the business. In K-Means, the choice of cluster count and the presence of outlying observations both affect the result.
What are training and test data for?
Measuring a model's success on the examples it saw during training usually gives an optimistic answer. Splitting the data set into training and test parts lets you learn the model on one portion and evaluate it on the other, on examples it has not seen before.
Train
Used to learn the model parameters.
Validation
For choosing models and settings, mostly via cross-validation.
Test
An unbiased read on overall performance once the final decision is made.
Live data
Monitoring distribution and performance in real use.
A simple start might use 80% training and 20% test; that ratio is not a universal rule. Small data sets, class imbalance, user groups or time-ordered records can all call for different splitting methods. In classification, stratify=y helps preserve the class proportions. In a time series, split from past to future; shuffling at random can leak information about the future into predictions about the past.
Overfitting, underfitting and generalisation
- Overfitting: the model fits the training examples and their noise too closely; the training score can be high while performance on new data is poor.
- Underfitting: the model is too simple to capture the relationships; both training and test scores are low.
- Generalisation: the model producing useful predictions on examples it did not see in training that resemble the intended conditions of use.
Cross-validation splits the training data into several parts, giving a more stable evaluation of models and settings. Using the test set over and over to pick settings can leak test information into the decision process and make the performance estimate optimistic.
An end-to-end machine learning workflow
- Define the problem: settle on the target to be predicted and how the decision will be used.
- Prepare the data: examine units, missing values, outliers, label quality and the time span covered.
- Pick the right task type: classification for a category, regression for a numeric value, clustering to discover unlabelled groups.
- Split the data: hold the test set back until the final evaluation as far as you can.
- Set up a simple baseline: compare performance against it, and move the preprocessing steps you need into a pipeline.
- Evaluate with a suitable metric: account for the business cost of each type of error.
- Interpret and monitor: follow performance across target groups, data drift and the outcomes in production.
Summary
Machine learning makes predictions or discovers structure by learning patterns from example data. Where there is a labelled target you use supervised learning; where you are looking for groups or structure without one, unsupervised learning. Classification predicts a category and regression a numeric value, while clustering groups similar observations. Evaluating the model on appropriate data it has not seen, preventing data leakage and measuring success with the right metric are the basic steps towards a trustworthy result.