softmax python function to achieve

Import numpy AS NP 

DEF softmax (x):
     "" " 
    computing softmax each line of the input x. 

    The function is the input vector (the vector as a separate row) or a matrix (M x N) are applicable. 
    
    Code using the softmax properties function: softmax (x) = softmax ( x + c) 

    parameters: 
    . X - a N-dimensional vector, or M x N dimensional matrix numpy 

    return value: 
    X - X in the internal function of the processing 
    "" " 
    orig_shape = x.shape 

    # according to the input type is a matrix or vector respectively calculated SoftMax 
    IF len (x.shape)>. 1 :
         # matrix 
        tmp = np.max (X, Axis =. 1) # obtain a maximum value for each row, for scaling elements of each row, to avoid overflow. shape is (x.shape [0],) 
        X - = tmp.reshape ((x.shape [0],. 1)) # using the scaling properties of the element 
        x = np.exp (x)# Index calculation all values 
        tmp = np.sum (X, Axis =. 1) # each row summation         
        X / tmp.reshape = ((x.shape [0],. 1)) # find SoftMax 
    the else :
         # Vector 
        tmp = np.max (X) # give maximum 
        X - = tmp # using the maximum value scaled data 
        X = np.exp (X) # exponential all elements         
        tmp = np.sum (X) # find elements and 
        x / = tmp # find somftmax 
    return X 

X = np.array ([[l, 2,3], [4,7,6 ]])
 Print (SoftMax (X))

 

Guess you like

Origin www.cnblogs.com/ljygoodgoodstudydaydayup/p/10944431.html