Machine Learning for Beginners: 5 Easy Steps with scikit-learn

Machine learning for beginners is easier than it sounds when you treat it as a short checklist: get data, split it, train a model, test it and improve it. In this guide you build a complete first project in Python with scikit-learn. The task is an engineering one: predict whether a weld is good or bad from welding current, travel speed and plate thickness. Every number below is the real output from running the code.

Machine learning for beginners: five steps from getting data to splitting, training, evaluating and improving
Machine learning for beginners: the five steps used in this project.

What Is Machine Learning in Simple Words?

Machine learning means giving a program many examples and letting it find the pattern, instead of writing every rule by hand. Here the examples are 600 welds, each with three inputs (current, speed, thickness) and one label, good or bad. The model learns which input combinations usually give a good weld, then predicts the label for welds it has not seen.

An honest note: the weld data in this tutorial is generated by the code using a simple rule plus random noise, so you can run it anywhere with no download. With a real project you replace it with measurements from your own tests. The steps do not change.

Step 1: Create and Look at the Data

We build a table with pandas. Heat input is roughly current divided by speed, and thicker plates are harder to weld well, so we use both ideas to label each weld.

import numpy as np, pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

rng = np.random.default_rng(42)
n = 600
current = rng.uniform(80, 220, n)   # welding current, A
speed = rng.uniform(2, 8, n)        # travel speed, mm/s
thick = rng.uniform(2, 10, n)       # plate thickness, mm
heat = current / speed              # simple heat-input proxy
score = 0.045*heat - 0.9*thick + rng.normal(0, 1.0, n)
good = (score > np.median(score)).astype(int)
df = pd.DataFrame({'current_A': current, 'speed_mm_s': speed,
                   'thickness_mm': thick, 'weld_good': good})

Print the first rows and the shape to check the table before you trust it:

current_A  speed_mm_s  thickness_mm  weld_good
0     188.35        4.87          6.53          1
1     141.44        6.57          6.41          0
2     200.20        7.42          8.63          0
3     177.63        6.32          7.68          0
4      93.18        7.78          2.21          1
(600, 4) 0.5

The data has 600 rows, and half the welds are good, so the two classes are balanced. That makes plain accuracy a fair first score.

Step 2: Split Into Training and Test Sets

Never test a model on the data it learned from, because it can simply memorise. We keep 25% of the rows hidden until the end. The stratify=y option keeps the good and bad shares the same in both parts.

Step 3: Train Three Models and Compare

We try three standard models. A scaler is used with logistic regression because it works best when inputs are on similar scales.

X = df[['current_A', 'speed_mm_s', 'thickness_mm']]
y = df.weld_good
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25,
                                      random_state=42, stratify=y)

models = {
  'Logistic regression': make_pipeline(StandardScaler(), LogisticRegression()),
  'Decision tree (depth 4)': DecisionTreeClassifier(max_depth=4, random_state=42),
  'Random forest': RandomForestClassifier(n_estimators=200, random_state=42),
}
for name, m in models.items():
    m.fit(Xtr, ytr)
    pred = m.predict(Xte)
    cv = cross_val_score(m, Xtr, ytr, cv=5).mean()
    print(f'{name}: test {accuracy_score(yte, pred):.3f}  cv {cv:.3f}')
Logistic regression: test 0.887  cv 0.869
Decision tree (depth 4): test 0.847  cv 0.853
Random forest: test 0.867  cv 0.867
ModelTest accuracy5-fold cross-validation
Logistic regression0.8870.869
Decision tree (depth 4)0.8470.853
Random forest0.8670.867
Machine learning for beginners: accuracy of logistic regression, decision tree and random forest on weld quality data
Test accuracy and cross-validation score for the three models.

The simplest model won on the test set. That is a useful lesson for beginners: a complex model is not automatically better. Cross-validation, which repeats the train and test process on five slices of the training data, shows all three models are close, so we should not claim a big difference from one split.

Step 4: Read the Confusion Matrix, Not Only Accuracy

Accuracy hides which mistakes the model makes. The confusion matrix counts them for the random forest on the 150 test welds:

[[63 12]
 [ 8 67]]
              precision    recall  f1-score   support
           0      0.887     0.840     0.863        75
           1      0.848     0.893     0.870        75
    accuracy                          0.867       150
{'current_A': 0.158, 'speed_mm_s': 0.156, 'thickness_mm': 0.686}
CellCountMeaning
True bad, predicted bad63Correctly flagged bad welds
True bad, predicted good12Missed bad welds (the costly mistake)
True good, predicted bad8False alarms
True good, predicted good67Correct good welds

In a real shop the 12 missed bad welds matter most, so you would aim to raise recall for the bad class even if accuracy drops a little. The feature importance line also tells a story: thickness carries about 69% of the importance, while current and speed share the rest.

best = models['Random forest']
pred = best.predict(Xte)
print(confusion_matrix(yte, pred))
print(classification_report(yte, pred, digits=3))
print(dict(zip(X.columns, best.feature_importances_.round(3))))

Step 5: Improve the Model Step by Step

IdeaWhat to tryWhy it helps
More dataAdd more welds from real testsModels learn stable patterns from more examples
Better featuresUse heat input (current divided by speed) as its own columnA physical feature can beat a raw input
TuningChange tree depth or number of trees with grid searchFinds a better setting than the default
Different error costSet class_weight to punish missed bad weldsMatches the real cost of mistakes
Honest checkTest on data from a different day or machineShows if the model works outside your lab

Machine Learning Words Beginners Should Know

New words slow down most people who start machine learning for beginners guides, so here is a short list of the terms used above.

TermSimple meaning
FeatureAn input column the model uses, such as welding current
LabelThe answer you want to predict, such as good or bad weld
Training setRows the model learns from
Test setRows kept hidden to check the model honestly
OverfittingA model that memorises training data and fails on new data
Cross-validationRepeating train and test on several slices to get a steadier score
RecallOf all real bad welds, the share the model caught

A good habit for any beginner project is to write one line for each of these terms about your own data before you train anything. If you cannot say what your label is or how you will test it, fix that first.

Common Beginner Mistakes

  • Testing on training data. The score looks perfect and means nothing.
  • Scaling before splitting. Put the scaler inside a pipeline, as we did, so test data never leaks into training.
  • Trusting one split. Use cross-validation before comparing models.
  • Ignoring the cost of errors. Choose the score that matches the real problem.
  • Skipping the data check. Look at missing values, units and outliers first. Our data cleaning in Python guide and pandas tutorial cover this.

Where to Go Next

Once this works, try a numeric prediction with linear regression in Python, then a machine fault example in predictive maintenance in Python. For bigger ideas, see our list of machine learning projects for final year, practise with machine learning interview questions, or explore Python for mechanical engineers. The official scikit-learn user guide explains every model used here in more depth.

If you want guidance on your own dataset, model choice or report, you can reach us through the Python for mechanical engineers page. We explain the method and help you understand your results.

A note on the code in this guide. It is a small learning demo that shows how the method works, using generated data. For a full project with your own data, complete analysis, code and report, we offer paid project support, where we plan the work with you and explain every step. Contact us through the Python for mechanical engineers page to discuss your topic and the cost.

FAQs

Which language is best for machine learning for beginners?

Python, because scikit-learn, pandas and NumPy give you ready tools for every step in this guide, and the community help is huge.

How much maths do I need to start?

Basic statistics, a little linear algebra and the idea of a function are enough for your first projects. You learn the rest as the models get harder.

Why did the simple model win here?

The pattern in this data is close to a straight boundary, so logistic regression fits it well. Complex models help only when the pattern is complex. Always start simple.

Is 87% accuracy good?

It depends on the cost of mistakes. For a weld check, a missed bad weld costs more than a false alarm, so you would look at recall for the bad class, not accuracy alone.

Can I use this for my final year project?

Yes, as a starting structure. Replace the generated data with measured data from your own experiment, and explain your features and your test method in the report.

Interested in this project? Get the details, files and guidance from our team.

Enquire on WhatsApp
Scroll to Top