Start learning free

LESSON 65 OF 165 · MACHINE LEARNING: A NEURAL NETWORK FROM SCRATCH

One Neuron in Python

Practice

A neuron is the smallest part of a neural network. It takes a few numbers in, the inputs, and gives back one number. Each input has a weight: a positive weight pushes the output up, a negative one pulls it down. The neuron multiplies each input by its weight, adds the products into the weighted sum, then adds one number of its own, the bias.

numpy does the arithmetic. np.array([...]) turns a list of numbers into an array. Between two arrays of the same length, * multiplies the items in pairs and gives back an array of the products. @ multiplies them in pairs and adds the products, so it gives back one number:

a = np.array([1.0, 3.0])
v = np.array([2.0, -1.0])
print(a * v)   # [ 2. -3.]
print(a @ v)   # -1.0

In this lesson the customer has 4 visits, 2 orders and 10 days since their last order. The weights are 0.5, 1.0 and -0.2, and the bias is -1.0. w[2] is the third weight, the one for days_since_last (positions start at 0), and round(n, 3) keeps 3 decimals. Your program must print:

features: ['visits', 'orders', 'days_since_last']
customer: [ 4.  2. 10.]
weights: [ 0.5  1.  -0.2]
weighted inputs: [ 2.  2. -2.]
output: 1.0
output now: -2.0

The check then calls your function on its own with other numbers, neuron([1, 3], [2, -1], 0.5), and expects -0.5.

Your task: the starting code builds the customer x, the weights w and the bias b and prints them. Print the weighted inputs, write a function neuron(x, w, b) that gives back the weighted sum plus the bias, and print its output for this customer. Then change the weight of days_since_last to -0.5 and print the output again.


Assignment
Follow the Coding Tutorial to print the weighted inputs, write the neuron function and watch one changed weight move its output.


Hint
The body of neuron is one return line: the weights @ the inputs, plus the bias. To print the output, put round(…, 3) around the call.


STEP 1 OF 6
    Ctrl + Enter to check

    Nn Neuron in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free