【问题标题】:Convert matlab method to python将matlab方法转换为python
【发布时间】:2016-12-08 12:31:37
【问题描述】:

matlab 中有一个非常有用的方法,叫做“getwb()”。 对于编码神经网络的开发人员,此方法在最终迭代时返回权重和偏差。 我有神经网络(使用 tensorflow 工具)。 有可能以某种方式转换此方法吗?

我用 tensorFlow.saver() 和 restore() 尝试了很多,但我真的不明白这个问题。

谢谢!

编辑: 我的模型是:

def neuralNetworkModel(x):
  # first step: (input * weights) + bias, linear operation like y = ax + b
  # each layer connection to other layer will represent by nodes(i) * nodes(i+1)

  for i in range(0,numberOfLayers):
    if i == 0:
      hiddenLayers.append({"weights": tensorFlow.Variable(tensorFlow.random_normal([sizeOfRow, nodesLayer[i]])),
                      "biases": tensorFlow.Variable(tensorFlow.random_normal([nodesLayer[i]]))})

    elif i > 0 and i < numberOfLayers-1:
      hiddenLayers.append({"weights" : tensorFlow.Variable(tensorFlow.random_normal([nodesLayer[i], nodesLayer[i+1]])),
                  "biases" : tensorFlow.Variable(tensorFlow.random_normal([nodesLayer[i+1]]))})
    else:
      outputLayer = {"weights": tensorFlow.Variable(tensorFlow.random_normal([nodesLayer[i], classes])),
                  "biases": tensorFlow.Variable(tensorFlow.random_normal([classes]))}


  # create the layers
  for i in range(numberOfLayers):
    if i == 0:
      layers.append(tensorFlow.add(tensorFlow.matmul(x, hiddenLayers[i]["weights"]), hiddenLayers[i]["biases"]))
      layers.append(tensorFlow.nn.relu(layers[i]))  # pass values to activation function (i.e sigmoid, softmax) and add it to the layer

    elif i >0 and i < numberOfLayers-1:
      layers.append(tensorFlow.add(tensorFlow.matmul(layers[i-1], hiddenLayers[i]["weights"]), hiddenLayers[i]["biases"]))
      layers.append(tensorFlow.nn.relu(layers[i]))

  output = tensorFlow.matmul(layers[numberOfLayers-1], outputLayer["weights"]) + outputLayer["biases"]
  finalOutput = output
  return output

【问题讨论】:

  • 考虑添加一些细节和代码:你训练什么模型?你怎么做呢?你尝试了什么,怎么没用?
  • 谢谢,我已经更新了我的帖子。

标签: python matlab machine-learning tensorflow


【解决方案1】:

在您的代码中,您为隐藏层和输出层的权重和偏差创建了一堆变量。您应该能够随时使用 tf.Session.run() 检索它们(当会话处于活动状态时),如下所示:

import tensorflow as tf

tf.reset_default_graph()

v = tf.Variable(tf.random_normal((5, 5)))

init = tf.initialize_all_variables()

with tf.Session() as sess:
  sess.run(init)
  v_val = sess.run(v)  
  print v_val

我还建议使用包含有用抽象的 tf.learn 库,例如 fully_connected 层。

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 2016-03-15
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2021-03-10
    • 2016-09-10
    • 1970-01-01
    相关资源
    最近更新 更多