tensorflow的tensor数据切片

问题遇到的现象和发生背景

在程序中我已经实现了单因子输入进行预测,想进一步输入多因子以提高预测准确性

问题相关代码,请勿粘贴截图
#———————————————————定义神经网络变量—————————————————————
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
import os
os.chdir(r'C:/dissertation')
#数据标准化
from sklearn import preprocessing
#配置matplotlib画图的符号
plt.rcParams['font.sans-serif'] = ['SimHei']  #显示中文
plt.rcParams['axes.unicode_minus']=False #用来正常显示坐标中的负号

def read_data(code):
    try:
        data = pd.read_csv('C:/dissertation/data/bar/' + code + '_bardata.csv')
        data = np.array(data.iloc[10:,2:])#还没对数据进行清洗,所以手动去除了有空值的部分
        print(code,'股票数据读取完成!')
        return data
    except Exception:
        print(code,'股票数据读取失败!')  
data = read_data('000001.SZ')
normalize_data = preprocessing.scale(data)#对每列分别进行数据标准化

#———————————————————形成训练集—————————————————————
#设置rnn网络的常量
time_step=20     #时间步 ,rnn每迭代20次,就向前推进一步
rnn_unit=10       # hidden layer units
batch_size=60     # 每一批训练多少个样例
input_size=1      # 输入层数维度
output_size=1     # 输出层数维度
lr=0.0006         # 学习率
train_x,train_y=[],[]   #训练集
for i in range(len(normalize_data)-time_step-1):
    x=normalize_data[i:i+time_step]
    y=normalize_data[i+1:i+time_step+1]
    y=y[:,4]
    train_x.append(x.tolist())
    train_y.append(y.tolist()) 
X=tf.placeholder(tf.float32, [None,time_step,input_size])    #每批次输入网络的tensor
Y=tf.placeholder(tf.float32, [None,time_step,output_size])   # 每批次tensor对应的标签
#输入层、输出层的权重和偏置
weights={
         'in':tf.Variable(tf.random_normal([input_size,rnn_unit])),
         'out':tf.Variable(tf.random_normal([rnn_unit,1]))
         } 
biases={
        'in':tf.Variable(tf.constant(0.1,shape=[rnn_unit,])),  
        'out':tf.Variable(tf.constant(0.1,shape=[1,]))
        }
#———————————————————定义lstm网络—————————————————————
def lstm(batch):      #参数:输入网络批次数
    pred = 0
    for factor_number in range(len(x[0])):
        w_in=weights['in']
        b_in=biases['in']
########################问题句########################################################
        input=tf.reshape(list(map(lambda x:[[y] for y in x.tolist()],np.array(X)[:,:,factor_number])),[-1,input_size])  
#此处X由后面的语句传入train_x,train_x为三层嵌套的list,经过X传入变为tensor,所以提示numpy不能处理
#######################################################################################
        input_rnn=tf.matmul(input,w_in)+b_in
        input_rnn=tf.reshape(input_rnn,[-1,time_step,rnn_unit])   
        cell=tf.nn.rnn_cell.BasicLSTMCell(rnn_unit)  
        init_state=cell.zero_state(batch,dtype=tf.float32)
        output_rnn,final_states=tf.nn.dynamic_rnn(cell, input_rnn,initial_state=init_state, dtype=tf.float32)
        output=tf.reshape(output_rnn,[-1,rnn_unit])
        w_out=weights['out']
        b_out=biases['out']
        pred+=tf.matmul(output,w_out)+b_out
    pred = pred / len(x[0])
    return pred,final_states
#———————————————————对模型进行训练—————————————————————
def train_lstm():
    global batch_size
    with tf.variable_scope("sec_lstm"):
        pred,_=lstm(batch_size)
    #定义损失函数
    loss=tf.reduce_mean(tf.square(tf.reshape(pred,[-1])-tf.reshape(Y, [-1])))
    train_op=tf.train.AdamOptimizer(lr).minimize(loss)
    saver=tf.train.Saver(tf.global_variables())
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        
        for i in range(100): #We can increase the number of iterations to gain better result.
            step=0
            start=0
            end=start+batch_size
            while(end<len(train_x)):
################################此处将train_x传入###########################################
                _,loss_=sess.run([train_op,loss],feed_dict={X:train_x[start:end],Y:train_y[start:end]})
                start+=batch_size
                end=start+batch_size
                #每训练10次保存一次参数
                if step%10==0:
                    print("Number of iterations:",i," loss:",loss_) #输出训练次数,输出损失值
                    print("model_save",saver.save(sess,'C:/dissertation/model_save1/modle.ckpt')) 
                step+=1
        print("The train has finished")
train_lstm()

由于我是初学者,所以我尝试在单因子能成功运行的基础上分别将不同因子输入,预测值求平均,希望程序可以运行。如果可以直接输入多因子那就更棒了,感谢!

你需要看一个简单的例子:

import tensorflow as tf
a=tf.constant([[[1,2,3,4],[4,5,6,7],[7,8,9,10]],
            [[11,12,13,14],[20,21,22,23],[15,16,17,18]]])
print(a.shape)
b,c=tf.split(a,2,0)  #参数1、张量  2、获得的切片数 3、切片的维度     将两个切片分别赋值给b,c
print(b.shape)
print(c.shape
with tf.Session() as sess:  #查看运行结果
    print(sess.run(b))
    print(sess.run(c))

输出结果为

(2, 3, 4)
(1, 3, 4)
(1, 3, 4)
[[[ 1  2  3  4]
  [ 4  5  6  7]
  [ 7  8  9 10]]]
[[[11 12 13 14]
  [20 21 22 23]
  [15 16 17 18]]]

注意到此时b,c均为三维张量数据,若想转换为二维数组,可使用tf.reshape命令

d=tf.reshape(b,[3,4])
print(d.shape)      

#output
(3, 4)




我记得我预测图片的 时候时,直接读10张图片,转换成张量,用reshape

看你的数据划分,time_step=20,stride=1.
那么你得单因子和多因子是指什么?
是指用前一天的数据预测下一天还是前n天的数据推理下一天?用预测单词举例来说,比如你说用前一个单词预测出后面一个单词,还是用前面几个单词预测后面一个?
还是说time_step天中的一个因素(时间段)还是time_step天中多个因素(时间,新闻,天气,经济等等)。如果是前者的话相当于推理的时候需要指定time_step即可,后者需要你有训练多因素模型才行。同样用单词预测举例,比如用全部用主语这一个因子来预测动词,还是用主谓宾等词语(多因子)来预测动词。

另外还有一个就是楼上说的一次性10张图片,这个是batch size,这个相当于一次性推理不同的输入,得到对应的输出,看你对这些输出是否有关联,不然的话一般推理的时候都是将其设置为1.