Inventory Management Software

Kardex Tauro

Kardex Tauro® Inventory Software is designed to efficiently manage your warehouse or storage facility, and it is quick and easy to learn.

Kardex Tauro is free for non-commercial use.
It does not require an internet connection; it runs on Windows.

Python code: perceptron from scratch to decide whether to reorder

Python code: perceptron from scratch to decide whether to reorder

Every week, in a hardware store, in a spare-parts distributor or in the back room of a small bakery, the same question comes back: do I order this item again, or do I wait? Usually one person answers it from memory and a spreadsheet. The data is not the problem: monthly sales, stock on hand and the supplier lead time are already recorded somewhere. The problem is that nobody has the time to look at those three numbers together, item by item, right before placing the order.

This article is for the business owner, for the accountant who reviews purchases and for the storekeeper who builds the list. Here you can download a Python program that reads from top to bottom, with no machine-learning library at all, that takes three columns of your inventory and learns a simple rule on its own: when it is worth reordering. The whole idea fits in one sentence: a neuron is a rule that adjusts itself. It starts by guessing, gets things wrong, corrects itself and ends up getting them right. There is no magic: there is a short formula repeated thirty times over your data, and the result can be checked line by line.

⬇ Descargar el código (ZIP)

The package is a ZIP with four files and nothing else. It brings no installers and does not need the internet: once you unzip it, everything runs on your own computer.

File in the ZIPWhat it is for
perceptron_reponer.pyThe program, commented line by line
datos/productos.csvThe twelve sample products, already labelled with the reorder column
salida_ejemplo.txtThe exact output you should get when you run it
README.mdThe package instructions: what you need, how to run it and what it does, step by step

What the program does

The program does a narrow job and it does the whole job. From start to finish:

  1. It reads datos/productos.csv: twelve hardware-store products with monthly sales, stock on hand, supplier lead time and a column called reorder, which is one when the buyer did reorder that product and zero when he did not. That column is the correct answer the neuron has to learn to copy; the program does not invent it.
  2. It scales the three inputs to the zero-to-one range. This is the step almost everybody skips and the one that decides whether the experiment is worth anything.
  3. It starts the weights at random values, but with the fixed seed seven, so everyone sees exactly the same numbers when running it, today and a month from now.
  4. It trains the neuron: thirty passes over the file, shuffling the order on every pass, and every time the prediction does not match the correct answer it moves the weights in the direction that reduces the error.
  5. It prints the final weights with their reading in words, so you can follow them even if you do not program.
  6. It predicts product by product and compares the prediction against the correct answer.
  7. It writes salida/predicciones.csv, checks that the same seed returns the same result and warns you if anything does not add up.

How to run it

You need Python 3.11 or newer and absolutely nothing else. Not numpy, not pandas, not any machine-learning library: the program uses only the standard library that ships with Python. If you do not have it yet, download it from the official site and accept the default options.

1. Unzip the ZIP into a folder (for example, Documents/Perceptron).
2. Open the terminal in that folder.
3. Type the command and press Enter:

   python perceptron_reponer.py

On Windows the interpreter is sometimes called py: if the command above does nothing, try py perceptron_reponer.py. On Mac and Linux it is usually python3 perceptron_reponer.py. The only condition is being inside the folder you unzipped, because the program looks for the data file at datos/productos.csv and writes its result to salida/predicciones.csv.

The code, explained

The whole program is a little over two hundred lines and it is commented line by line. Six pieces are enough to understand the entire idea.

The three knobs of learning. At the top, three numbers govern the whole training run. The seed fixes the randomness so the result repeats; the rate says how much each weight is corrected on every mistake; the epochs say how many full passes the file gets. Change the rate or the epochs and the run changes, which is why the program prints their values on screen: that way you know what produced the result.

SEMILLA = 7          # # Fixed seed: with the same data the result is always the same
TASA = 0.1           # # Learning rate: how much the weight is corrected on every error
EPOCAS = 30          # # Epochs: how many full passes over the file

Why the data is scaled. This function takes each column into the zero-to-one range. If the neuron saw stock in units, which runs into the hundreds, next to lead time in days, which never goes past thirty, the sum would be dominated by the biggest column and lead time would barely count. Once everything shares the same scale, every input really pulls, and the weights can be compared against each other.

def normalizar(productos: list[dict], campo: str) -> list[float]:
    """Scales a column to the 0..1 range (min-max): that way stock in units does not crush lead time in days."""
    valores = [producto[campo] for producto in productos]
    minimo, maximo = min(valores), max(valores)
    rango = maximo - minimo

The neuron itself. Here is the core, and it fits in two functions. Each input is multiplied by its weight, the three results are added and the bias is added on top. That total is compared against zero: above zero the answer is reorder, and below zero the answer is do not reorder. Nothing more than that; drawn on paper it is a straight line that cuts the products into two groups.

def suma_pesada(pesos: list[float], sesgo: float, entrada: list[float]) -> float:
    """Weighted sum w*x + b: the value the neuron compares against zero."""
    total = sesgo
    for indice in range(len(ENTRADAS)):
        total += pesos[indice] * entrada[indice]
    return total
def predecir(pesos: list[float], sesgo: float, entrada: list[float]) -> int:
    """Predicts 1 (reorder) when the weighted sum is above zero, and 0 when it is not."""
    return 1 if suma_pesada(pesos, sesgo, entrada) > 0 else 0

The training loop. The weights are not born correct: they are born at random. What makes them useful is the correction rule, applied row after row inside every epoch.

def entrenar(entradas: list[list[float]], etiquetas: list[int]) -> tuple:
    """Trains the neuron with the perceptron rule and returns weights, bias and errors per pass."""
    azar = random.Random(SEMILLA)
    pesos = [azar.uniform(-1.0, 1.0) for _ in ENTRADAS]   # # Each weight says how hard its input pushes towards reordering
    sesgo = azar.uniform(-1.0, 1.0)

The correction. When the prediction matches the correct answer the error is zero and nothing is touched: what is already right does not move. When it does not match, the error pushes each weight in proportion to the input and to the learning rate. The bias is corrected exactly like a weight, except that it multiplies no input.

                for j in range(len(ENTRADAS)):
                    pesos[j] += TASA * error * entradas[indice][j]
                sesgo += TASA * error    # # The bias is corrected like a weight, but it multiplies no input

What you will see on screen

First the data table exactly as the file brings it, and under it the same table scaled: the same products seen on the zero-to-one scale the neuron uses. Note that the stock column is the one that changes shape most dramatically; that is precisely the effect we are after.

SCALED DATA (0 to 1: what the neuron sees)
-------------------------------------------------------------------------------------
Product                         Reorder         Sales 0-1     Stock 0-1      Lead 0-1
-------------------------------------------------------------------------------------
Gray cement 50 kg               YES                  0.26          0.10          0.76
Self-drilling screw 1 in        YES                  1.00          0.26          0.19
Ball-peen hammer                YES                  0.00          0.00          1.00
Coarse sand (bag)               NO                   0.47          1.00          0.00

Then comes the training. The program prints only the passes where it improves, which are the ones that teach: on the first epoch it gets seven items wrong, on the second five, on the third four, on the fourth two, and by the sixth it makes no mistake at all. That is the learning, in plain sight, with no black box.

TRAINING: 30 epochs, rate 0.10, seed 7
  Epoch 1/30 · errors 7
  Epoch 2/30 · errors 5
  Epoch 3/30 · errors 4
  Epoch 4/30 · errors 2
  Epoch 6/30 · errors 0

And at the end, the weights with their reading in words, the result product by product and the check that the run repeats.

FINAL WEIGHTS AND BIAS (read in words)
  weight of monthly_sales = 0.25: the more the product sells, the more reason to reorder
  weight of stock = -0.74: the more stock on hand, the less reason to reorder
  weight of supplier_lead_time = 0.28: the longer the supplier takes, the more reason to reorder
  bias = -0.06: with all three inputs at zero, the neuron leans towards not reordering

Those four numbers are the outcome of the run and they deserve a business reading:

NumberHow to read it
monthly sales = 0.25Positive and small: selling more pushes towards reordering, but gently.
stock = -0.74Negative and the largest of the three: goods sitting on the shelf are what holds a reorder back the most.
supplier lead time = 0.28Positive: the longer the supplier takes, the more reason to order early.
bias = -0.06Almost zero, and negative: with all three inputs at zero the neuron leans slightly towards not reordering.

What matters is not the exact value of each weight but how big they are next to each other. Stock weighs more than the other two inputs together; the bias is so small it hardly matters. And because the data is scaled, those three numbers can be compared at all: if stock were measured in units and lead time in days, a weight of minus zero point seven four would tell you nothing. One detail worth gold: these weights are the fingerprint of these twelve sample products, not a universal recipe. Run it on your own file and different numbers will come out, and that is exactly right.

Hits: 12 of 12
Check (same seed, same result): TIES

The sample run gets all twelve predictions right, that is, the whole hundred per cent of the cases. The program also writes salida/predicciones.csv with four columns, product, expected, predicted and hit, ready to open in Excel or any spreadsheet. That is what you review with your accountant: not the promise of a model, but the list of cases where it was right and where it was wrong.

Common mistakes and tips

  • It cannot find the file. Almost always you are running the command from another folder. Step into the folder you unzipped, or type the full path to the file.
  • Do not move the CSV. The program looks for the data under the exact name datos/productos.csv. Rename it or take it out of its subfolder and nothing works.
  • Keep the CSV a CSV. If you edit it in Excel, keep the same headings, product, monthly_sales, stock, supplier_lead_time and reorder, and keep commas as separators. A regional setting that switches the list separator breaks the reading.
  • No currency signs and no thousands separators. Numbers go in clean, with no money symbol and no thousands dot.
  • The label is one or zero. In the reorder column do not write words such as yes or no: the program expects numbers.
  • One odd cell spoils the table. An empty cell or a word among the numbers throws the arithmetic off; check the file before running.
  • Twelve rows are not a test. The example is short on purpose so it is easy to follow. With your real inventory use several months and a few hundred rows before trusting the rule.
  • Write down the seed. If you later change the seed you will see different weights; the logic is the same but the starting point is not. Keep a note of the values each result came from.

When this is not enough

With this you can already reorder on a rule rather than on last month's hunch. Still, the limits deserve an honest word. The first one is technical: a single neuron only learns straight-border rules, of the kind low stock against sales, or a long lead time. If your real rule carries exceptions, for instance do not reorder the items that are already on order, you need more than one neuron. The second limit is operational: this program is didactic, one person runs it, on a CSV file somebody has to keep up to date.

When the business grows and the spreadsheet plus a few scripts stop being enough, the natural step is inventory software. That is where Kardex Tauro comes in, the tool this workshop was written for: it keeps stock and cost of sales for real, with several users and with backups, instead of depending on somebody remembering to update the file. The program in this article is free and it is there to make the mechanics clear and to get your inventory in order; the software is for when the inventory no longer fits in a file.

⬇ Descargar el código (ZIP)

Download the ZIP, run it exactly as it comes and look at the hit table. Then replace one row of datos/productos.csv with a real product of yours and run it again: you will watch the rule readjust itself, without touching a single line of code. That is the whole trick, and it is also the best way to see why a tidy inventory is worth more than an order placed in a hurry.

Share
Link copied
Microsoft Store from Microsoft StoreDownload free
Chatea por WhatsApp