【问题标题】:Tensorflow: Numpy equivalent of tf batches and reshapeTensorflow:Numpy 相当于 tf 批次和重塑
【发布时间】:2016-09-20 23:46:24
【问题描述】:

我正在尝试使用 Tensorflow 对一些图像进行分类,使用 LSTM 方法在图像分类中使用 one-hot 编码输出和最后一个 LSTM 输出的 softmax 分类器。我的数据集是 CSV,必须在 Numpy 和 Tensorflow 中进行大量研究以了解如何进行一些修改。我仍然收到错误消息:

AttributeError: 'numpy.ndarray' object has no attribute 'next_batch'

如果您会看到,我不能将 next_batch(batch_size) 与我的数据集一起使用,并且下一个 tf.reshape 需要替换为它的 Numpy 等效项。

我的问题:我应该如何纠正这两个问题?

'''
Tensorflow LSTM classification of 16x30 images.
'''

from __future__ import print_function

import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell
import numpy as np
from numpy import genfromtxt
from sklearn.cross_validation import train_test_split
import pandas as pd

'''
a Tensorflow LSTM that will sequentially input several lines from each single image 
i.e. The Tensorflow graph will take a flat (1,480) features image as it was done in Multi-layer
perceptron MNIST Tensorflow tutorial, but then reshape it in a sequential manner with 16 features each and 30 time_steps.
'''

blaine = genfromtxt('./Desktop/Blaine_CSV_lstm.csv',delimiter=',')  # CSV transform to array
target = [row[0] for row in blaine]             # 1st column in CSV as the targets
data = blaine[:, 1:480]                          #flat feature vectors
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.05, random_state=42)

f=open('cs-training.csv','w')       #1st split for training
for i,j in enumerate(X_train):
        k=np.append(np.array(y_train[i]),j   )
        f.write(",".join([str(s) for s in k]) + '\n')
f.close()
f=open('cs-testing.csv','w')        #2nd split for test
for i,j in enumerate(X_test):
        k=np.append(np.array(y_test[i]),j   )
        f.write(",".join([str(s) for s in k]) + '\n')
f.close()

ss = pd.Series(y_train)     #indexing series needed for later Pandas Dummies one-hot vectors
gg = pd.Series(y_test)

new_data = genfromtxt('cs-training.csv',delimiter=',')  # Training data
new_test_data = genfromtxt('cs-testing.csv',delimiter=',')  # Test data

x_train=np.array([ i[1::] for i in new_data])
y_train_onehot = pd.get_dummies(ss)

x_test=np.array([ i[1::] for i in new_test_data])
y_test_onehot = pd.get_dummies(gg)


# General Parameters
learning_rate = 0.001
training_iters = 100000
batch_size = 128
display_step = 10

# Tensorflow LSTM Network Parameters
n_input = 16 # MNIST data input (img shape: 28*28)
n_steps = 30 # timesteps
n_hidden = 128 # hidden layer num of features
n_classes = 20 # MNIST total classes (0-9 digits)

# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
y = tf.placeholder("float", [None, n_classes])

# Define weights
weights = {
    'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
}
biases = {
    'out': tf.Variable(tf.random_normal([n_classes]))
}


def RNN(x, weights, biases):

    # Prepare data shape to match `rnn` function requirements
    # Current data input shape: (batch_size, n_steps, n_input)
    # Required shape: 'n_steps' tensors list of shape (batch_size, n_input)

    # Permuting batch_size and n_steps
    x = tf.transpose(x, [1, 0, 2])
    # Reshaping to (n_steps*batch_size, n_input)
    x = tf.reshape(x, [-1, n_input])
    # Split to get a list of 'n_steps' tensors of shape (batch_size, n_input)
    x = tf.split(0, n_steps, x)

    # Define a lstm cell with tensorflow
    lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)

    # Get lstm cell output
    outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)

    # Linear activation, using rnn inner loop last output
    return tf.matmul(outputs[-1], weights['out']) + biases['out']

pred = RNN(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    step = 1
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        x_train, y_train = new_data.next_batch(batch_size)
        # Reshape data to get 30 seq of 16 elements
        x_train = x_train.reshape((batch_size, n_steps, n_input))
        # Run optimization op (backprop)
        sess.run(optimizer, feed_dict={x: x_train, y: y_train})
        if step % display_step == 0:
            # Calculate batch accuracy
            acc = sess.run(accuracy, feed_dict={x: x_train, y: y_train})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: x_train, y: y_train})
            print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                  "{:.6f}".format(loss) + ", Training Accuracy= " + \
                  "{:.5f}".format(acc))
        step += 1
    print("Optimization Finished!")

【问题讨论】:

  • @SerialDev 我做了解决方案中确切提到的事情

标签: python numpy machine-learning tensorflow


【解决方案1】:

您可以创建自己的函数,称为 next batch,给定一个 numpy 数组,并且索引将为您返回该 numpy 数组的切片。

def nextbatch(x,i,j):
    return x[i:j,...]

你也可以传递你所处的步骤,也许做模,但这是让它工作的基础。

至于改形使用:

x_train = np.reshape(x_train,(batch_size, n_steps, n_input))

【讨论】:

  • 我测试了一个小例子: In [1]: a = x_test[33:22, ...] 并收到: Out[1]: array([], shape=(0, 479 ), dtype=float64)。这是批处理的一种形式吗?
  • 批次只是感兴趣对象的集合。假设您正在处理图像。如果我想要 10 个图像的批量大小,那么数组的格式为 [batch_size, height, width, 3]。 3 代表 RGB。
  • 所以它不是一个真正的数组,它只是一种指向数组内某个索引范围的指针,对吧?
  • 它是一个数组(或者在 tensorflow 中是一个张量)。我需要更多关于 x_train 中的内容的信息才能回答您的具体问题。
  • 完全不用担心,我研究了它并且可以处理将 2D 数组转换为 3D 张量,然后可以轻松地遍历 Batch 索引。非常感谢朋友!
猜你喜欢
  • 2019-05-17
  • 1970-01-01
  • 2017-07-04
  • 2017-11-05
  • 2017-03-31
  • 2018-02-07
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多