笔记
输入N个样本,每个样本是p维向量。包含q个不同类别。注意在输入网络时,由于是多分类模型,y应该做one-hot编码。
python实现
按照上述过程,用python实现。
这里只包含一个隐藏层,如果两个隐藏层可以自行添加。
def softmax(x, axis=1):
# 计算每行的最大值
row_max = x.max(axis=axis)
# 每行元素都需要减去对应的最大值,否则求exp(x)会溢出,导致inf情况
row_max=row_max.reshape(-1, 1)
x = x - row_max
# 计算e的指数次幂
x_exp = np.exp(x)
x_sum = np.sum(x_exp, axis=axis, keepdims=True)
s = x_exp / x_sum
return s
def sigmoid(x, deriv=False):
if deriv==True:
return sigmoid(x)*(1-sigmoid(x))
return 1/(1+np.exp(-x))
def transform_one_hot(labels):
# 转为one-hot编码
n_labels = np.max(labels) + 1
one_hot = np.eye(n_labels)[labels]
return one_hot
hidden_layer = 100
learning_rate = 0.01
"""初始化网络参数"""
# np.random.seed(2)
sample_size = X_train.shape[0]
input_layer_neur