Challenge: Creating a Neuron
Compito
Swipe to start coding
Your task is to implement the basic structure of a neuron by completing the missing parts.
- Initialize the weights (an array) and bias (a single number) with random values from a uniform distribution in range
[-1, 1)
using NumPy. - Compute the weighted sum of the inputs using the dot product, add the bias, and store the result in
input_sum_with_bias
. - Apply the sigmoid activation function to
input_sum_with_bias
to obtain the neuron's output.
Soluzione
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import numpy as np
# Fix the seed for reproducibility
np.random.seed(10)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class Neuron:
def __init__(self, n_inputs):
# 1. Initialize weights and bias with random values
self.weights = np.random.uniform(-1, 1, size=n_inputs)
self.bias = np.random.uniform(-1, 1)
def activate(self, inputs):
# 2. Compute the weighted sum using dot product and add bias
input_sum_with_bias = np.dot(inputs, self.weights) + self.bias
# 3. Apply the sigmoid activation function
output = sigmoid(input_sum_with_bias)
return output
# Create a neuron with 3 inputs
neuron = Neuron(3)
# Generate inputs for the neuron
neuron_inputs = np.array([0.5, 0.2, -0.8])
# Pass the inputs to the created neuron
neuron_output = neuron.activate(neuron_inputs)
print(f'Output of the neuron is {neuron_output:.3f}')
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 2. Capitolo 2
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import numpy as np
# Fix the seed for reproducibility
np.random.seed(10)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
class Neuron:
def __init__(self, n_inputs):
# 1. Initialize weights and bias with random values
self.weights = ___
self.bias = ___
def activate(self, inputs):
# 2. Compute the weighted sum using dot product and add bias
input_sum_with_bias = ___
# 3. Apply the sigmoid activation function
output = ___
return output
# Create a neuron with 3 inputs
neuron = Neuron(3)
# Generate inputs for the neuron
neuron_inputs = np.array([0.5, 0.2, -0.8])
# Pass the inputs to the created neuron
neuron_output = neuron.activate(neuron_inputs)
print(f'Output of the neuron is {neuron_output:.3f}')
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione