V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
LittleUqeer
V2EX  ›  Python

Tensorflow 笔记 用 CNN 做预测

  •  
  •   LittleUqeer · 2017-01-05 13:47:25 +08:00 · 10846 次点击
    这是一个创建于 2877 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    配置环境 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

    2 条回复    2018-03-12 11:12:41 +08:00
    melovto
        1
    melovto  
       2017-02-09 20:12:47 +08:00 via iPhone
    顶一下
    liqian123456
        2
    liqian123456  
       2018-03-12 11:12:41 +08:00
    请问一下,数据集是什么样的呢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2889 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 14:45 · PVG 22:45 · LAX 06:45 · JFK 09:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.