# ----------# # In this exercise, you will put the finishing touches on a perceptron class.## Finish writing the activate() method by using np.dot to compute signal# strength and then add in a threshold for perceptron activation.## ----------import numpy as np
classPerceptron:"""
This class models an artificial neuron with step activation function.
"""def__init__(self, weights = np.array([1]), threshold = 0):"""
Initialize weights and threshold based on input arguments. Note that no
type-checking is being performed here for simplicity.
"""
self.weights = weights
self.threshold = threshold
defactivate(self,inputs):"""
Takes in @param inputs, a list of numbers equal to length of weights.
@return the output of a threshold perceptron with given inputs based on
perceptron weights and threshold.
"""# INSERT YOUR CODE HERE# TODO: calculate the strength with which the perceptron fires
output=np.dot(self.weights,inputs)
# TODO: return 0 or 1 based on the thresholdif output>self.threshold:
result = 1else:
result = 0return result
deftest():"""
A few tests to make sure that the perceptron class performs as expected.
Nothing should show up in the output if all the assertions pass.
"""
p1 = Perceptron(np.array([1, 2]), 0.)
assert p1.activate(np.array([ 1,-1])) == 0# < threshold --> 0assert p1.activate(np.array([-1, 1])) == 1# > threshold --> 1assert p1.activate(np.array([ 2,-1])) == 0# on threshold --> 0if __name__ == "__main__":
test()
感知更新规则
# ----------## In this exercise, you will update the perceptron class so that it can update# its weights.## Finish writing the update() method so that it updates the weights according# to the perceptron update rule. Updates should be performed online, revising# the weights after each data point.# # ----------import numpy as np
classPerceptron:"""
This class models an artificial neuron with step activation function.
"""def__init__(self, weights = np.array([1])