为Tensorflow迭代Numpy数组

时间:2017-04-14 15:42:46

标签: python arrays loops numpy tensorflow

您好

我是Python的入门级。我搜索了python和numpy上的每个文档,但没有找到。我想训练我的多变量逻辑回归模型。我有100x2 numpy数组 train_x数据和 100x1 numpy array 作为train_y数据。我只是无法提供我的占位符。我认为我无法像占位符那样迭代多维矩阵。

以下是我更好理解的原始代码:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as numpy

learning_rate = 0.01
total_iterator = 1500
display_per = 100

data = numpy.loadtxt("ex2data1.txt",dtype=numpy.float32,delimiter=",");

training_X = numpy.asarray(data[:,[0,1]]) # 100 x 2
training_Y = numpy.asarray(data[:,[2]],dtype=numpy.int) # 100 x 1

m = data.shape[0] # thats my sample size = 100

x_i = tf.placeholder(tf.float32,[None,2]) # N x 2
y_i = tf.placeholder(tf.float32,[None,1]) # N x 1

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

h = tf.matmul(W,x_i)+b

cost = tf.reduce_sum(tf.add(tf.multiply(y_i,tf.log(h)),tf.multiply(1-y_i,tf.log(1-h)))) / -m
### I just wanted to try simple cross function as i learned in lesson ###
### I didn't get such error at this scope ###

initializer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for k in range(total_iterator):    
        for (x,y) in  zip(training_X,training_Y):
            sess.run(initializer,feed_dict={x_i: x , y_i: y}) ### ?!??!? ###

            ### AT THIS SCOPE: i get error such as 'can't feed,
            ### placeholder:0'###

        if k % display_per==0:
            print("Iteration: ",k, "cost: ", sess.run(cost,feed_dict={x_i:training_X,y_i:training_Y}),"w: ",sess.run(W),\
                "b: ",sess.run(b))

    print("Optim. finished")
    print("Iteration: ", k, "cost: ", sess.run(cost, feed_dict={x_i: training_X, y_i: training_Y}), "w: ", sess.run(W), \
          "b: ", sess.run(b))

感谢您的任何答案。我想我已经将两维矩阵切片从train_x传递到x_i。也许我从头到尾错了

1 个答案:

答案 0 :(得分:0)

问题是循环中的xy是1-D,而占位符是2-D。 (注意,您将占位符定义为tf.placeholder(tf.float32,[None,2]),它定义了一个二维占位符。这样做是为了批量进行优化和计算。)

最快的解决方案是重塑xy

sess.run(initializer,feed_dict={x_i: np.reshape(x, [1,-1]),
                                y_i: np.reshape(y, [1, -1])})