1.构造sigmoid函数
import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function()
def sigmoid(x):
s=none
s=1.0/(1.0+np.exp(-x)
return s
2.构造ds
import numpy as np
def sigmoid_derivative(x):
s=1.0/(1.0+np.exp(-x))
ds=s*(1-s)
return ds
x = np.array([1, 2, 3])
print ("sigmoid_derivative(x) = " + str(sigmoid_derivative(x)))
-
维数转换,将一幅RBG图片转换为一维数组。
def image2vector(image): v=None v=image.reshape((image.shape[0]*image.shape[1]*image.shape[2]),1) return v
-
矩阵规范化处理
将矩阵x规范化的函数:
def normalizeRows(x):
x_norm=None
x_norm=np.linalg.norm(x,axis=1,keepdims=True)
x=x/x_norm
return x
注:这里得到的x_norm是每行各元素的,平方和,再开根号。
4.1 softmax函数
def softmax(x):
### START CODE HERE ### (≈ 3 lines of code)
# Apply exp() element-wise to x. Use np.exp(…).
x_exp = np.exp(x)
# Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).
x_sum = np.sum(x_exp,axis = 1,keepdims = True)
# Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.
s = x_exp/x_sum
### END CODE HERE ###
return s
axis=1 表示以竖轴为基准,同行相加。
keepdims主要用于保持矩阵的二维特性。
-
L1正则化
def L1(yhat, y):
loss = sum(abs(yhat-y))
return lossL2正则化
def L2(yhat, y):
loss=np.dot(y-yhat,y-yhat)
return loss