python - 如何创建多层神经网络
问题描述
感谢您提前为我提供的任何帮助!我已经获得了用于简单单层感知器的 python 代码,其任务是更改代码,使其成为多层感知器。我对这一切还是很陌生,但据我了解,重复的前馈和反向传播循环是创建隐藏层的原因。给定以下代码,应该改变什么来帮助创建这些隐藏层?
# Creating a numerically stable logistic s-shaped definition to call
def sigmoid(x):
x = np.clip(x, -500, 500)
if x.any()>=0:
return 1/(1 + np.exp(-x))
else:
return np.exp(x)/(1 + np.exp(x))
# define the dimentions and set the weights to random numbers
def init_parameters(dim1, dim2=1,std=1e-1, random = True):
if(random):
return(np.random.random([dim1,dim2])*std)
else:
return(np.zeros([dim1,dim2]))
# Single layer network: Forward Prop
# Passed in the weight vectors, bias vector, the input vector and the Y
def fwd_prop(W1, bias, X, Y):
Z1 = np.dot(W1, X) + bias # dot product of the weights and X + bias
A1 = sigmoid(Z1) # Uses sigmoid to create a predicted vector
return(A1)
#Single layer network: Backprop
def back_prop(A1, W1, bias, X, Y):
m = np.shape(X)[1] # used the calculate the cost by the number of inputs -1/m
# Cross entropy loss function
cost = (-1/m)*np.sum(Y*np.log(A1) + (1-Y)*np.log(1-A1)) # cost of error
dZ1 = A1 - Y # subtract actual from pred weights
dW1 = (1/m) * np.dot(dZ1, X.T) # calc new weight vector
dBias = (1/m) * np.sum(dZ1, axis = 1, keepdims = True) # calc new bias vector
grads ={"dW1": dW1, "dB1":dBias} # Weight and bias vectors after backprop
return(grads, cost)
def run_grad_desc(num_epochs, learning_rate, X, Y, n_1):
n_0, m = np.shape(X)
W1 = init_parameters(n_1, n_0, True)
B1 = init_parameters(n_1,1, True)
loss_array = np.ones([num_epochs])*np.nan # resets the loss_array to NaNs
for i in np.arange(num_epochs):
A1 = fwd_prop(W1, B1, X, Y) # get predicted vector
grads, cost = back_prop(A1, W1, B1, X, Y) # get gradient and the cost from BP
W1 = W1 - learning_rate*grads["dW1"] # update weight vector LR*gradient*[BP weights]
B1 = B1 - learning_rate*grads["dB1"] # update bias LR*gradient[BP bias]
loss_array[i] = cost # loss array gets cross ent values
parameter = {"W1":W1, "B1":B1} # assign
return(parameter, loss_array)
我们还被要求能够调整隐藏层中的节点。老实说,我在这里完全迷失了,甚至不清楚节点代表什么,所以这里的帮助也将不胜感激。谢谢大家。
解决方案
看起来这个网络甚至不是单层的。通常“单层”是指一层隐藏的神经元。该网络输出通常是隐藏层的激活。
我对你的建议是开始学习神经网络的基础知识。有很多很棒的资源,包括在 Youtube 上。对于反向传播,这里是一个很好的起点
另请注意,如果您赶时间,使用 TensorFlow 或 Pytorch 等 autograd 工具会为您处理差异化。当然,如果您这样做是为了了解神经网络的细节,那么从头开始构建一个会好得多。
推荐阅读
- c# - Blazor:在不锁定组件的 ctor 或 InvokeAsync 的情况下增加静态字段是否安全?
- angular - 在角度 10 的 tsconfig.json 中找不到 typeRoots
- docker - 为什么我在使用 MySQL 的 docker 中使用几乎相同的命令得到不同的结果?
- java - 如何将多个 json url 的内容添加到单个 json 对象中
- c# - 哪个参数需要在 switch 中使用 Case 来调用对象的方法?
- javascript - 如果键值为数字,如何更改对象中的键?
- python - 如何解决线性搜索算法中的索引错误?
- list - 如何从 Flutter 的列表中为模型类赋值?
- datatables - 对其他列进行排序时,不要对第一列进行排序
- nginx - nginx中rewrite uri和set variable语句之间的关系