【问题标题】:How to implement the remaining 'for loop' in this neural network in TensorFlow如何在 TensorFlow 中的这个神经网络中实现剩余的“for循环”
【发布时间】:2018-10-10 14:51:13
【问题描述】:

我正在尝试让神经网络进入 TensforFlow。数据集只是花瓣的长度和宽度,输出可以是 1/0,具体取决于类型:

x = [[3,1.5],
     [2,1],
     [4,1.5],
     [3,1],
     [3.5,0.5],
     [2,0.5],
     [5.5,1],
     [1,1]]

y = [1,
     0,
     1,
     0,
     1,
     0,
     1,
     0]

到目前为止,我的代码如下所示:

定义变量

x_1 = tf.placeholder(tf.float32, shape=[8,2])
y_1 = tf.placeholder(tf.float32, shape=[8])

w_1 = tf.placeholder(tf.float32, shape=[2,8])
b_1 = tf.placeholder(tf.float32, shape=[8,])

sess = tf.Session()

sess.run(tf.global_variables_initializer())

y_ = tf.matmul(x_1,w_1) + b

sigmoid = tf.nn.sigmoid(y_)

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(sigmoid)

for _ in range(50000):

我的问题是如何安排我的“for”循环,以便它一次获取整个数据集并将其与实际输出进行比较? tensorflow 上的 mnist 数据集使用 softmax 交叉熵,您可以在函数的参数中指定实际输出和预测输出。但是,在这个简单的数据集中,我将如何在剩余的 for 循环中复制相同的内容,以便代码抓取所有数据进行预测并将其与实际输出进行比较?另外请说明我的变量的形状是否有任何问题,谢谢。

【问题讨论】:

  • 到目前为止,您正在尝试最小化神经网络的输出。如果您希望您的输出与 y 匹配(也称为基本事实),那么您应该首先尝试最小化表示输出与 y 之间差异的成本。
  • 另外,如果你想最小化一些东西,你不应该使用占位符,而是使用变量。
  • 长话短说,您最好仔细阅读分步教程。
  • 是否有任何教程可以推荐,在不使用 mnist 数据集的情况下解释这一点
  • This 看起来很适合开始使用低级 API,它使用 iris 数据集(您似乎正在使用相同的数据集)。

标签: python for-loop tensorflow neural-network gradient-descent


【解决方案1】:

你知道,你可以只使用 tflearn。节省大量时间和挫折 =)

import tflearn
from tflearn.layers.core import fully_connected,input_data
from tflearn.layers.estimator import regression

model = input_data(shape=[None,4,1])
model = fully_connected(model,1,activation='sigmoid')
model = regression(model)
model = tflearn.DNN(model)
model.fit(X_inputs=trainX,Y_targets=trainY,n_epoch=20,
          validation_set=(testX,testY),show_metric=True)

【讨论】:

  • 我认为这里的重点是了解幕后发生的事情并学习如何使用 Tensorflow 低级 API。
【解决方案2】:

设法解决我一直在寻找的东西:

import tensorflow as tf
import numpy as np

train_X = np.asarray([[3,1.5],[2,1],[4,1.5],[3,1],[3.5,0.5],[2,0.5],[5.5,1],[1,1]])
train_Y = np.asarray([[1],[0],[1],[0],[1],[0],[1],[0]])

x = tf.placeholder("float",[None, 2])
y = tf.placeholder("float",[None, 1])

W = tf.Variable(tf.zeros([2, 1]))
b = tf.Variable(tf.zeros([1, 1]))

activation = tf.nn.sigmoid(tf.matmul(x, W)+b)
cost = tf.reduce_mean(tf.square(activation - y))
optimizer = tf.train.GradientDescentOptimizer(.2).minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(50000):
        train_data = sess.run(optimizer, feed_dict={x: train_X, y: train_Y})

    result = sess.run(activation, feed_dict={x:train_X})
    print(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 2015-08-07
    • 2016-08-31
    • 2016-08-18
    • 2016-08-12
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多