从零开始的神经网络-预测单个示例

时间:2019-08-28 08:36:24

标签: python numpy tensorflow deep-learning pytorch

这是我根据Coursera深度学习专业课程修改的神经网络,用于在包含平坦训练数据数组的数据集上进行训练:

array([[0., 0., 0., 0., 0.],
       [3., 1., 3., 6., 0.],
       [0., 0., 0., 0., 0.],
       [4., 9., 0., 0., 0.],
       [5., 9., 6., 0., 0.]])

这可以按预期工作,但是我很难预测一个例子。

如果我使用:

var requests = [];
requests.push($http.get('FIRSTRESTURL', {'cache': false}));
requests.push($http.get('SECONDRESTURL', {'cache': false}));

$q.all(requests).then(function (responses) {
  var values = [];
  for (var x in responses) {
    responses[x].success(function(data){
      values.push(data);
    });
  }
  $scope.results = MyService.doCalculation(values);
});

返回错误:

%reset -s -f

import numpy as np
import math

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def initialize_with_zeros(dim):

    w = np.zeros(shape=(dim, 1))
    b = 0

    return w, b

X = np.array([[1,1,1,1],[1,0,1,0] , [1,1,1,0], [0,0,0,0], [0,1,0,0], [0,1,0,1]])
Y = np.array([[1,0,1,1,1,1]])

X = X.reshape(X.shape[0], -1).T
Y = Y.reshape(Y.shape[0], -1).T

print('X shape' , X.shape)
print('Y shape' , Y.shape)

b = 1
w, b = initialize_with_zeros(4)

def propagate(w, b, X, Y) : 

    m = X.shape[1]

    A = sigmoid(np.dot(w.T, X) + b)  # compute activation
    cost = (- 1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A)))  # compute cost
    dw = (1./m)*np.dot(X,((A-Y).T))
    db = (1./m)*np.sum(A-Y, axis=1)
    cost = np.squeeze(cost)

    grads = {"dw": dw,
             "db": db}

    return grads, cost

propagate(w , b , X , Y)

learning_rate = .001
costs = []

def optimize(w , b, X , Y) :
    for i in range(2):

        grads, cost = propagate(w=w, b=b, X=X, Y=Y)

        dw = grads["dw"]
        db = grads["db"]

        w = w - learning_rate*dw
        b = b -  learning_rate*db

        if i % 100 == 0:
            costs.append(cost)

    return w , b

w , b = optimize(w , b , X , Y)

def predict(w, b, X):

    m = 6
    Y_prediction = np.zeros((1,m))
#     w = w.reshape(X.shape[0], 1)

    A = sigmoid(np.dot(w.T, X) + b)
    for i in range(A.shape[1]):

        if A[0, i] >= 0.5:
            Y_prediction[0, i] = 1

        else:
            Y_prediction[0, i] = 0

    return Y_prediction

predict(w , b, X)

如何重新安排矩阵运算以预测单个实例?

2 个答案:

答案 0 :(得分:1)

尝试

x <= L = 10^9

似乎您L函数期望pi(x)是二维的,当仅传递一个predict(w, b, X[:1]) 时,它应该具有单调的第二维(即shape =(6,1 )),而不是一维(即shape =(6,))。

答案 1 :(得分:0)

该错误来自以下事实:预测期望在形状为... * bs的一批数据上调用。为了预测单个元素,您可以使用np.expand_dims创建一批大小为1的

predict(w, b, np.expand_dims(X[0], axis=1)

应该工作。