簡體   English   中英

遍歷Numpy數組以進行Tensorflow

[英]Iterate over Numpy array for Tensorflow

你好,

我是Python的入門級人員,已經在python和numpy上搜索了所有文檔,但沒有找到。我想訓練我的多變量邏輯回歸模型。 我有用於train_x數據的100x2 numpy數組和作為train_y數據的100x1 numpy數組。我只是無法提供占位符。我認為我無法按照占位符的需要迭代多維矩陣。

這是我的原始代碼,可以更好地理解:

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傳遞了二維矩陣切片。 也許我從頭到尾都是錯的

問題是循環中的xy是1維,而占位符是2維。 (請注意,將占位符定義為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])})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM