Deep learning: Compute one neuron

Compute the output of a single artificial neuron.

What to build

A program that computes a neuron's weighted sum and output.

Requirements

  • Activations: relu, sigmoid, tanh or linear.
  • Print z = Z and output = A, each with four decimal places.

Input

Line 1: the inputs. Line 2: the weights. Line 3: the bias. Line 4: the activation.

Output

Two lines.

Constraints

At most 100 inputs.

Example

Input:

1 2
0.5 0.25
0
relu

Output:

z = 1.0000
output = 1.0000

Why it works

The weighted sum measures how strongly the inputs match the neuron's weights, and the activation turns that into the neuron's response.

Examples

Example 1 · Input
1 2
0.5 0.25
0
relu
Expected output
z = 1.0000
output = 1.0000
Example 2 · Input
1 1
1 1
-2
sigmoid
Expected output
z = 0.0000
output = 0.5000

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

z is the sum of input × weight, plus the bias.

Hint 2

Apply the named activation: math.tanh, 1 / (1 + math.exp(−z)), max(0, z) or z itself.

Solution

Show one correct solution (try it yourself first)
import math

xs = list(map(float, input().split()))
ws = list(map(float, input().split()))
b = float(input())
activation = input().strip()
z = sum(x * w for x, w in zip(xs, ws)) + b
functions = {
    "relu": lambda v: max(0.0, v),
    "sigmoid": lambda v: 1 / (1 + math.exp(-v)),
    "tanh": math.tanh,
    "linear": lambda v: v,
}
print(f"z = {z:.4f}")
print(f"output = {functions[activation](z):.4f}")

Lesson: Neurons, layers and activation functions →