wangtaiyangqaq
2022-03-03 15:18
采纳率: 75%
浏览 34

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()

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题