Implements the softmax function Parameters: vector (np.array,list,tuple): A numpy array of shape (1,n) consisting of real values or a similar list,tuple Returns: softmax_vec (np.array): The input numpy array after applying softmax. The softmax v
(vector)
| 14 | |
| 15 | |
| 16 | def softmax(vector): |
| 17 | """ |
| 18 | Implements the softmax function |
| 19 | |
| 20 | Parameters: |
| 21 | vector (np.array,list,tuple): A numpy array of shape (1,n) |
| 22 | consisting of real values or a similar list,tuple |
| 23 | |
| 24 | |
| 25 | Returns: |
| 26 | softmax_vec (np.array): The input numpy array after applying |
| 27 | softmax. |
| 28 | |
| 29 | The softmax vector adds up to one. We need to ceil to mitigate for |
| 30 | precision |
| 31 | >>> float(np.ceil(np.sum(softmax([1,2,3,4])))) |
| 32 | 1.0 |
| 33 | |
| 34 | >>> vec = np.array([5,5]) |
| 35 | >>> softmax(vec) |
| 36 | array([0.5, 0.5]) |
| 37 | |
| 38 | >>> softmax([0]) |
| 39 | array([1.]) |
| 40 | """ |
| 41 | |
| 42 | # Calculate e^x for each x in your vector where e is Euler's |
| 43 | # number (approximately 2.718) |
| 44 | exponent_vector = np.exp(vector) |
| 45 | |
| 46 | # Add up the all the exponentials |
| 47 | sum_of_exponents = np.sum(exponent_vector) |
| 48 | |
| 49 | # Divide every exponent by the sum of all exponents |
| 50 | softmax_vector = exponent_vector / sum_of_exponents |
| 51 | |
| 52 | return softmax_vector |
| 53 | |
| 54 | |
| 55 | if __name__ == "__main__": |