r/learnmachinelearning • • 16d ago

I accidentally made a preceptron from scratch

Post image

So today in AI ESSENTIALS LAB at my uni, they went, "make a perceptron."

We had only covered half-baked theory class (almost nothing, really) and a diagram of a perceptron in our theory class before this.

So I brute-forced my way through it, one step at a time. I did think of using numpy arrays, but for simplicity, went with regular python lists.

Made this in less than an hour, mostly based on the vague diagram and whatever I could figure out along the way.

And turns out, we were supposed to just use an sklearn model, not make one from scratch. LMAO 😭

And I had asked and even explained this whole code to the lab assistants and we then had a whole half hour discussion over it (the lab is 2 hour long and I'm in sem 1 btw)

Yes I guessed it via the vague diagram I saw 2 weeks ago in the theory class

0 Upvotes

4 comments sorted by

1

u/Fluffy_white_fox 16d ago

I just realised its cutting off here is the full code

def collect_data(str_input):
  #making it into a list
  spe_str_input = str_input.split(",")
  # Convert the elements to integers
  int_input = [int(x.strip()) for x in spe_str_input if x.strip()]
  return int_input

x_input = input("enter first numbers (x1,x2,....xn) sep by comma: ")
x_values = collect_data(x_input)

x2_input = input("enter second numbers (x2_1, x2_2,....x2_n) sep by comma: ")
x2_values = collect_data(x2_input)

# Automatically pad the shorter list with zeros so they have the same length
max_len = max(len(x_values), len(x2_values))
while len(x_values) < max_len:
  x_values.append(0)
while len(x2_values) < max_len:
  x2_values.append(0)

#creates a list of ones that automatically matches the padded length
weights = [1.0] * max_len
bias = 1.0
learning_rate = 0.1

times = int(input("Enter number of times to loop (epochs): "))

for run in range(times):
  # Loop over both patterns to train
  for current_x in [x_values, x2_values]:
    # DYNAMIC TARGET RULE: Target is 1 if sum of inputs is positive, else 0
    target = 1 if sum(current_x) > 0 else 0

    total = 0.0
    for i in range(len(current_x)):
      total += current_x[i] * weights[i]
    total += bias

    # Step activation function
    prediction = 1 if total > 0 else 0

    # Perceptron Learning Rule: Update weights and bias based on prediction error
    error = target - prediction
    if error != 0:
      for i in range(len(weights)):
        weights[i] += learning_rate * error * current_x[i]
      bias += learning_rate * error

    print(f"Loop {run+1} with inputs {current_x} -> Target: {target}, Total: {total:.2f}, Prediction: {prediction}, Error: {error}, Updated Weights: {[round(w, 2) for w in weights]}, Updated Bias: {bias:.2f}")

print("\nFinal Inputs:", x_values, "and", x2_values)
print("Final Weights:", [round(w, 2) for w in weights])
print("Final Bias:", round(bias, 2))

1

u/[deleted] 16d ago

[removed] — view removed comment

1

u/Fluffy_white_fox 16d ago

It's x2_input