Tensorflow 笔记 用 CNN 做预测

2017-01-05 13:47:25 +08:00
 LittleUqeer

看到一个不错的深度学习做预测,在这里分享给大家。

配置环境 deepin 15.3 Anaconda 2.7 pip 清华镜像 tensorflow

%%time
from __future__ import division
from __future__ import print_function  
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
%matplotlib inline
import seaborn as sns

​
import tensorflow as tf

​
fac = np.load('/home/big/Quotes/TensorFlow deal with Uqer/fac16.npy').astype(np.float32)
ret = np.load('/home/big/Quotes/TensorFlow deal with Uqer/ret16.npy').astype(np.float32)
#fac = np.load('/home/big/Quotes/TensorFlow deal with Uqer/fac16.npy')
#ret = np.load('/home/big/Quotes/TensorFlow deal with Uqer/ret16.npy')

​
# Parameters
learning_rate = 0.001 # 学习速率,
training_iters = 20 # 训练次数
batch_size = 1024 # 每次计算数量 批次大小
display_step = 10 # 显示步长

​
# Network Parameters
n_input = 40*17 # 40 天×17 多因子
n_classes = 7 # 根据涨跌幅度分成 7 类别
# 这里注意要使用 one-hot 格式,也就是如果分类如 3 类 -1,0,1 则需要 3 列来表达这个分类结果, 3 类是-1 0 1 然后是哪类,哪类那一行为 1 否则为 0
dropout = 0.8 # Dropout, probability to keep units

​
# tensorflow 图 Graph 输入 input ,这里的占位符均为输入
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)

2 层

# 2 层 CNN
def CNN_Net_two(x,weights,biases,dropout=0.8,m=1):
    # 将输入张量调整成图片格式
    # CNN 图像识别,这里将前 40 天的多因子数据假设成图片数据
    x = tf.reshape(x, shape=[-1,40,17,1])
    
    # 卷积层 1
    x = tf.nn.conv2d(x, weights['wc1'], strides=[1,m,m,1],padding='SAME')
    # x*W + b
    x = tf.nn.bias_add(x,biases['bc1'])
    # 激活函数
    x = tf.nn.relu(x)
    
    # 卷积层 2 感受野 5 5 16 64 移动步长 1
    x = tf.nn.conv2d(x, weights['wc2'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc2'])
    x = tf.nn.relu(x)
    
    # 全连接层
    x = tf.reshape(x,[-1,weights['wd1'].get_shape().as_list()[0]])
    x = tf.add(tf.matmul(x,weights['wd1']),biases['bd1'])
    x = tf.nn.relu(x)
    
    # Apply Dropout
    x = tf.nn.dropout(x,dropout)
    # Output, class prediction
    x = tf.add(tf.matmul(x,weights['out']),biases['out'])
    return x

# Store layers weight & bias
weights = {
    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 16])),
    'wc2': tf.Variable(tf.random_normal([5, 5, 16, 64])),
    # fully connected, 7*7*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([40*17*64, 1024])),
    'out': tf.Variable(tf.random_normal([1024, n_classes]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([16])),
    'bc2': tf.Variable(tf.random_normal([64])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

3 层

def CNN_Net_three(x,weights,biases,dropout=0.8,m=1):
    
    x = tf.reshape(x, shape=[-1,40,17,1])
    
    # 卷积层 1
    x = tf.nn.conv2d(x, weights['wc1'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc1'])
    x = tf.nn.relu(x)
    
    # 卷积层 2 
    x = tf.nn.conv2d(x, weights['wc2'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc2'])
    x = tf.nn.relu(x)
    
    # 卷积层 3 
    x = tf.nn.conv2d(x, weights['wc3'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc3'])
    x = tf.nn.relu(x)    
    
    # 全连接层
    x = tf.reshape(x,[-1,weights['wd1'].get_shape().as_list()[0]])
    x = tf.add(tf.matmul(x,weights['wd1']),biases['bd1'])
    x = tf.nn.relu(x)
    
    # Apply Dropout
    x = tf.nn.dropout(x,dropout)
    # Output, class prediction
    x = tf.add(tf.matmul(x,weights['out']),biases['out'])
    return x

# Store layers weight & bias
weights = {
    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 16])),
    'wc2': tf.Variable(tf.random_normal([5, 5, 16, 32])),
    'wc3': tf.Variable(tf.random_normal([5, 5, 32, 64])),
    # fully connected, 7*7*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([40*17*64, 1024])),
    'out': tf.Variable(tf.random_normal([1024, n_classes]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([16])),
    'bc2': tf.Variable(tf.random_normal([32])),
    'bc3': tf.Variable(tf.random_normal([64])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

%%time
# 模型优化
pred = CNN_Net_two(x,weights,biases,dropout=keep_prob)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
correct_pred = tf.equal(tf.argmax(pred,1),tf.arg_max(y,1))
# tf.argmax(input,axis=None) 由于标签的数据格式是 -1 0 1 3 列,该语句是表示返回值最大也就是 1 的索引,两个索引相同则是预测正确。
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 更改数据格式,降低均值
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    # for step in range(300):
    for step in range(1):
        for i in range(int(len(fac)/batch_size)):
            batch_x = fac[i*batch_size:(i+1)*batch_size]
            batch_y = ret[i*batch_size:(i+1)*batch_size]
            sess.run(optimizer,feed_dict={x:batch_x,y:batch_y,keep_prob:dropout})
            if i % 10 ==0:
                print(i,'----',(int(len(fac)/batch_size)))
        loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,y: batch_y,keep_prob: 1.})
        print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                  "{:.6f}".format(loss) + ", Training Accuracy= " + \
                  "{:.5f}".format(acc))
    print("Optimization Finished!")   
    sess.close()

5 层

def CNN_Net_five(x,weights,biases,dropout=0.8,m=1):
    
    x = tf.reshape(x, shape=[-1,40,17,1])
    
    # 卷积层 1
    x = tf.nn.conv2d(x, weights['wc1'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc1'])
    x = tf.nn.relu(x)
    
    # 卷积层 2 
    x = tf.nn.conv2d(x, weights['wc2'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc2'])
    x = tf.nn.relu(x)
    
    # 卷积层 3 
    x = tf.nn.conv2d(x, weights['wc3'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc3'])
    x = tf.nn.relu(x)    
    
    # 卷积层 4 
    x = tf.nn.conv2d(x, weights['wc4'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc4'])
    x = tf.nn.relu(x) 
    
    # 卷积层 5 
    x = tf.nn.conv2d(x, weights['wc5'], strides=[1,m,m,1],padding='SAME')
    x = tf.nn.bias_add(x,biases['bc5'])
    x = tf.nn.relu(x) 
    
    # 全连接层
    x = tf.reshape(x,[-1,weights['wd1'].get_shape().as_list()[0]])
    x = tf.add(tf.matmul(x,weights['wd1']),biases['bd1'])
    x = tf.nn.relu(x)
    
    # Apply Dropout
    x = tf.nn.dropout(x,dropout)
    # Output, class prediction
    x = tf.add(tf.matmul(x,weights['out']),biases['out'])
    return x

# Store layers weight & bias
weights = {
    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 16])),
    'wc2': tf.Variable(tf.random_normal([5, 5, 16, 32])),
    'wc3': tf.Variable(tf.random_normal([5, 5, 32, 64])),
    'wc4': tf.Variable(tf.random_normal([5, 5, 64, 32])),
    'wc5': tf.Variable(tf.random_normal([5, 5, 32, 16])),
    # fully connected, 7*7*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([40*17*16, 1024])),
    'out': tf.Variable(tf.random_normal([1024, n_classes]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([16])),
    'bc2': tf.Variable(tf.random_normal([32])),
    'bc3': tf.Variable(tf.random_normal([64])),
    'bc4': tf.Variable(tf.random_normal([32])),
    'bc5': tf.Variable(tf.random_normal([16])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

%%time
# 模型优化
pred = CNN_Net_five(x,weights,biases,dropout=keep_prob)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
correct_pred = tf.equal(tf.argmax(pred,1),tf.arg_max(y,1))
# tf.argmax(input,axis=None) 由于标签的数据格式是 -1 0 1 3 列,该语句是表示返回值最大也就是 1 的索引,两个索引相同则是预测正确。
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 更改数据格式,降低均值
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for step in range(1):
        for i in range(int(len(fac)/batch_size)):
            batch_x = fac[i*batch_size:(i+1)*batch_size]
            batch_y = ret[i*batch_size:(i+1)*batch_size]
            sess.run(optimizer,feed_dict={x:batch_x,y:batch_y,keep_prob:dropout})
            print(i,'----',(int(len(fac)/batch_size)))
        loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,y: batch_y,keep_prob: 1.})
        print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                  "{:.6f}".format(loss) + ", Training Accuracy= " + \
                  "{:.5f}".format(acc))
    print("Optimization Finished!") 
    sess.close()

优化参数之后准确率大概在 94%+

该作者其他有关机器学习,深度学习方面的文章也推荐给大家,希望对大家有帮助:

Tensorflow 笔记 1 CNN : https://uqer.io/community/share/58637c716a5e6d00522939b7
TensorFlow 笔记 2 双向 LSTM : https://uqer.io/community/share/586a4eb889e3ba004defde4b
TensorFlow 笔记 3 多层 LSTM : https://uqer.io/community/share/586bb68423a7d60052a361f6
三个臭皮匠-集成算法框架上手 : https://uqer.io/community/share/58562a9f6a5e6d0052291ebe

10717 次点击
所在节点    Python
2 条回复
melovto
2017-02-09 20:12:47 +08:00
顶一下
liqian123456
2018-03-12 11:12:41 +08:00
请问一下,数据集是什么样的呢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/332386

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX