Python Numpy小编程

几个关于numpy的编程小问题

1)

计算MSE:\text{MSE} = \frac{1}{n} \sum_{i = 1}^n (Y_{\text{pred}, i} - Y_i)^2

import numpy as np

def mse(Y_pred, Y):
    return np.sum((Y_pred-Y)**2)/len(Y)

Y_pred = np.array([0, 0, 1])
Y = np.array([0.1, 0.1, 0.8])
mse(Y_pred, Y) 

2)计算softmax,公式是:\left( \frac{e^{a_1}}{\sum_{i = 1}^n e^{a_i}}, \dots,\frac{e^{a_n}}{\sum_{i = 1}^n e^{a_i}} \right).

# Suppose you are given an `n` by `m` matrix `A`. Take the column-wise softmax of `A`.
import numpy as np

def softmax(A):
    return np.exp(A)/np.sum(np.exp(A),0)

n, m = 2, 3
A = np.random.randint(10, size=(n,m))
print(A)
print(softmax(A))

这个还可以改进一点,因为exp函数的特性,当x很大的时候,exp(x)可能会导致数值溢出,我们可以小优化一下:

# Suppose you are given an `n` by `m` matrix `A`. Take the column-wise softmax of `A`.
import numpy as np

def softmax(A):
    A_max = np.max(A,0)
    A_exp = np.exp(A - A_max)
    return A_exp/np.sum(A_exp,0)

n, m = 2, 3
A = np.random.randint(10, size=(n,m))
print(A)
print(softmax(A))

3)随机游走模拟

import numpy as np
import random

# simulate one random walk process and return the number of steps
def simulate():
    step = [1, -1]
    store = []
    for i in range(100000):
        start = 0
        count = 0
        while start != 5 and start != -5:
            x = random.choice(step)
            start += x
            count  += 1
        store.append(count)
    E = np.mean(store)
    var = np.var(store)
    return E, var

simulate()

# use the simulate function to approximate the expected value and variance of the number of steps

你可能感兴趣的:(python,numpy,开发语言)