首页 > 解决方案 > 从深度学习人工神经网络的训练代码中去除 for-loop

问题描述

与神经网络相关的训练代码。有几个功能,但只有火车附加。

我的问题是我可以从这段代码中删除以下三个循环吗?我怎样才能将其删除?如果你使用 NumPy!

我是一个刚开始学习人工智能的学生,但是遇到了一个问题,没有答案,所以我在问一个问题……看来你可以用numpy代替for-loop。

我想知道没有 for 循环的版本。

def train(X, Y, model, lr = 0.1):
  dW1 = np.zeros_like(model.W1)
  db1 = np.zeros_like(model.b1)
  dW2 = np.zeros_like(model.W2)
  db2 = np.zeros_like(model.b2)

  m = len(X)
  cost = 0.0
  for x,y in zip(X,Y):
    a2, (z1,a1,z2, a2) = model.predict(x)
    if y == 1:
      cost -= np.log(a2)
    else:
      cost -= np.log(1-a2)
    diff = a2-y
    db2 += diff


     #here...
    for i in range(model.num_hiddens):
      dW2[i] += a1[i]*diff

    for i in range(model.num_hiddens):
      db1[i] += (1-a1[i]**2)*model.W2[i]*diff

    for i in range(model.num_hiddens):
      for j in range(model.num_input_features):
        dW1[i,j] += x[j]*(1-a1[i]**2)*model.W2[i]*diff


    cost /= m
    model.W1 -= lr * dW1/m
    model.b1 -= lr * db1/m
    model.W2 -= lr * dW2/m
    model.b2 -= lr * db2/m

    return cost

++

class shallow_neural_network():
  def __init__(self, num_input_features, num_hiddens):
    self.num_input_features = num_input_features
    self.num_hiddens = num_hiddens

    self.W1 = np.random.normal(size = (num_hiddens,num_input_features))
    self.b1 = np.random.normal(size = num_hiddens)
    self.W2 = np.random.normal(size = num_hiddens)
    self.b2 = np.random.normal(size = 1)

  def sigmoid(self,z):
      return 1/(1+np.exp(-z))

  def predict(self,x):
      z1 = np.matmul(self.W1,x) + self.b1
      a1 = np.tanh(z1)
      z2 = np.matmul(self.W2,a1) + self.b2
      a2 = self.sigmoid(z2)
      return a2, (z1,a1,z2,a2)

标签: numpytensorflowdeep-learningjupyter-notebook

解决方案


推荐阅读