numpy - 从深度学习人工神经网络的训练代码中去除 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)
解决方案
推荐阅读
- mysql - MySQL 中位数与 3 个表之间的连接
- python - Python 无法导入“nbt”,即使它已安装
- apache-nifi - 带有 Ambari 的 NiFi 集群 - 维护的最佳实践是什么?
- ruby-on-rails - 链轮错误:链轮::Rails::Helper::AssetNotFound
- java - 在没有硬编码的情况下,如何让我的项目内部数据库的搜索路径正常工作?
- python - 如何从字符串中提取英国县名匹配
- postgresql - postgresql - bytea v jsonb vs xml
- python - 有没有办法将 python 烧瓶中的 Web 应用程序转换为移动设备?
- javascript - 如何在 laravel 路由中访问 JavaScript 变量
- javascript - Webpack Unexpected Token / 没有文件类型的加载器