【发布时间】:2020-01-01 10:23:02
【问题描述】:
这是我从 Coursera 深度学习专业化中修改的神经网络,用于在包含扁平化训练数据数组的数据集上进行训练:
%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)
这按预期工作,但我很难预测一个例子。
如果我使用:
predict(w , b, X[0])
返回错误:
ValueError: shapes (6,4) and (6,) not aligned: 4 (dim 1) != 6 (dim 0)
如何重新排列矩阵运算以预测单个实例?
【问题讨论】:
标签: python numpy tensorflow deep-learning pytorch