├── .gitignore ├── LICENSE ├── README.md ├── news-analysis ├── LICENSE ├── README.md ├── data │ ├── daily-stock │ │ ├── daily.neg │ │ └── daily.pos │ └── rt-polarity │ │ ├── rt-polarity.neg │ │ └── rt-polarity.pos ├── data_helpers.py ├── eval.py ├── predict.py ├── save │ ├── checkpoints │ │ ├── checkpoint │ │ ├── model-6000.data-00000-of-00001 │ │ ├── model-6000.index │ │ └── model-6000.meta │ ├── prediction.csv │ └── vocab ├── text_cnn.py └── train.py └── stock-analysis └── convnet ├── README.md └── cnn_classifier.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.npy 2 | runs/ 3 | 4 | # Created by https://www.gitignore.io/api/python,ipythonnotebook 5 | 6 | ### Python ### 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | env/ 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *,cover 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | 60 | # Sphinx documentation 61 | docs/_build/ 62 | 63 | # PyBuilder 64 | target/ 65 | 66 | 67 | ### IPythonNotebook ### 68 | # Temporary data 69 | .ipynb_checkpoints/ 70 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keon/deepstock/57bc386914b0c7ea837528ae7c3d180001279da8/LICENSE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DeepStock 2 | 3 | Technical experimentations to beat the stock market using deep learning. 4 | 5 | ## Experimentations 6 | 7 | 1. Deep Learning Stock Prediction with Daily News Headline Analysis 8 | 9 | * An attempt to find the correlation between the daily news headlines and DJIA index. 10 | * More explained in [this slide](http://www.slideshare.net/KeonKim/stock-prediction-using-nlp-and-deep-learning) 11 | 12 | 2. Automated Trading Bot using Deep Learning 13 | 14 | * Predicting a company's stock price based only on the price history of the company. 15 | * Recurrent Neural Networks 16 | * Convolutional Neural Networks 17 | * Deep Q NetWorks 18 | * In-progress 19 | 20 | 3. Complex Analysis on Stock using Deep Learning 21 | 22 | * Take multiple features into account to predict the value of a company. 23 | * In-progress 24 | 25 | 4. Portfolio Management using Deep Learning 26 | 27 | * Planned 28 | 29 | 5. Macro Economics Analysis 30 | 31 | * Currency and Macro-Tracking-ETFs 32 | * Planned 33 | -------------------------------------------------------------------------------- /news-analysis/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /news-analysis/README.md: -------------------------------------------------------------------------------- 1 | # DeepStock 2 | Stock Prediction using ConvNet Headline Analysis 3 | 4 | Building on top of @dennybritz 's implementation. 5 | 6 | It is slightly simplified implementation of Kim's [Convolutional Neural Networks for Sentence Classification](http://arxiv.org/abs/1408.5882) paper in Tensorflow. 7 | 8 | ## Requirements 9 | 10 | - Python 3 11 | - Tensorflow > 0.8 12 | - Numpy 13 | 14 | ## Training 15 | 16 | Print parameters: 17 | 18 | ```bash 19 | ./train.py --help 20 | ``` 21 | 22 | ``` 23 | optional arguments: 24 | -h, --help show this help message and exit 25 | --embedding_dim EMBEDDING_DIM 26 | Dimensionality of character embedding (default: 128) 27 | --filter_sizes FILTER_SIZES 28 | Comma-separated filter sizes (default: '3,4,5') 29 | --num_filters NUM_FILTERS 30 | Number of filters per filter size (default: 128) 31 | --l2_reg_lambda L2_REG_LAMBDA 32 | L2 regularizaion lambda (default: 0.0) 33 | --dropout_keep_prob DROPOUT_KEEP_PROB 34 | Dropout keep probability (default: 0.5) 35 | --batch_size BATCH_SIZE 36 | Batch Size (default: 64) 37 | --num_epochs NUM_EPOCHS 38 | Number of training epochs (default: 100) 39 | --evaluate_every EVALUATE_EVERY 40 | Evaluate model on dev set after this many steps 41 | (default: 100) 42 | --checkpoint_every CHECKPOINT_EVERY 43 | Save model after this many steps (default: 100) 44 | --allow_soft_placement ALLOW_SOFT_PLACEMENT 45 | Allow device soft device placement 46 | --noallow_soft_placement 47 | --log_device_placement LOG_DEVICE_PLACEMENT 48 | Log placement of ops on devices 49 | --nolog_device_placement 50 | 51 | ``` 52 | 53 | Train: 54 | 55 | ```bash 56 | ./train.py 57 | ``` 58 | 59 | ## Evaluating 60 | 61 | ```bash 62 | ./eval.py --eval_train --checkpoint_dir="./runs/1459637919/checkpoints/" 63 | ``` 64 | 65 | Replace the checkpoint dir with the output from the training. To use your own data, change the `eval.py` script to load your data. 66 | 67 | 68 | ## References 69 | 70 | - [Convolutional Neural Networks for Sentence Classification](http://arxiv.org/abs/1408.5882) 71 | - [A Sensitivity Analysis of (and Practitioners' Guide to) Convolutional Neural Networks for Sentence Classification](http://arxiv.org/abs/1510.03820) 72 | -------------------------------------------------------------------------------- /news-analysis/data_helpers.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import re 3 | import itertools 4 | from collections import Counter 5 | 6 | 7 | def clean_str(string): 8 | """ 9 | Tokenization/string cleaning for all datasets except for SST. 10 | Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py 11 | """ 12 | string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) 13 | string = re.sub(r"\'s", " \'s", string) 14 | string = re.sub(r"\'ve", " \'ve", string) 15 | string = re.sub(r"n\'t", " n\'t", string) 16 | string = re.sub(r"\'re", " \'re", string) 17 | string = re.sub(r"\'d", " \'d", string) 18 | string = re.sub(r"\'ll", " \'ll", string) 19 | string = re.sub(r",", " , ", string) 20 | string = re.sub(r"!", " ! ", string) 21 | string = re.sub(r"\(", " \( ", string) 22 | string = re.sub(r"\)", " \) ", string) 23 | string = re.sub(r"\?", " \? ", string) 24 | string = re.sub(r"\s{2,}", " ", string) 25 | return string.strip().lower() 26 | 27 | 28 | def load_data_and_labels(positive_data_file, negative_data_file): 29 | """ 30 | Loads MR polarity data from files, splits the data into words and generates labels. 31 | Returns split sentences and labels. 32 | """ 33 | # Load data from files 34 | positive_examples = list(open(positive_data_file, "r").readlines()) 35 | positive_examples = [s.strip() for s in positive_examples] 36 | negative_examples = list(open(negative_data_file, "r").readlines()) 37 | negative_examples = [s.strip() for s in negative_examples] 38 | # Split by words 39 | x_text = positive_examples + negative_examples 40 | x_text = [clean_str(sent) for sent in x_text] 41 | # Generate labels 42 | positive_labels = [[0, 1] for _ in positive_examples] 43 | negative_labels = [[1, 0] for _ in negative_examples] 44 | y = np.concatenate([positive_labels, negative_labels], 0) 45 | return [x_text, y] 46 | 47 | 48 | def batch_iter(data, batch_size, num_epochs, shuffle=True): 49 | """ 50 | Generates a batch iterator for a dataset. 51 | """ 52 | data = np.array(data) 53 | data_size = len(data) 54 | num_batches_per_epoch = int(len(data)/batch_size) + 1 55 | for epoch in range(num_epochs): 56 | # Shuffle the data at each epoch 57 | if shuffle: 58 | shuffle_indices = np.random.permutation(np.arange(data_size)) 59 | shuffled_data = data[shuffle_indices] 60 | else: 61 | shuffled_data = data 62 | for batch_num in range(num_batches_per_epoch): 63 | start_index = batch_num * batch_size 64 | end_index = min((batch_num + 1) * batch_size, data_size) 65 | yield shuffled_data[start_index:end_index] 66 | -------------------------------------------------------------------------------- /news-analysis/eval.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | import os 6 | import time 7 | import datetime 8 | import data_helpers 9 | from text_cnn import TextCNN 10 | from tensorflow.contrib import learn 11 | import csv 12 | 13 | # Parameters 14 | # ================================================== 15 | 16 | # Data Parameters 17 | tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-polarity.pos", "Data source for the positive data.") 18 | tf.flags.DEFINE_string("negative_data_file", "./data/rt-polaritydata/rt-polarity.neg", "Data source for the positive data.") 19 | 20 | # Eval Parameters 21 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 22 | tf.flags.DEFINE_string("checkpoint_dir", "", "Checkpoint directory from training run") 23 | tf.flags.DEFINE_boolean("eval_train", False, "Evaluate on all training data") 24 | 25 | # Misc Parameters 26 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 27 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 28 | 29 | 30 | FLAGS = tf.flags.FLAGS 31 | FLAGS._parse_flags() 32 | print("\nParameters:") 33 | for attr, value in sorted(FLAGS.__flags.items()): 34 | print("{}={}".format(attr.upper(), value)) 35 | print("") 36 | 37 | x_raw = ["Venezuela seizes 4.8 million toys", "Trump says he's turning away 'billions", "New Zealand elects new leader"] 38 | y_test = [0, 0, 1] 39 | 40 | # Map data into vocabulary 41 | vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab") 42 | vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) 43 | x_test = np.array(list(vocab_processor.transform(x_raw))) 44 | 45 | print("\nEvaluating...\n") 46 | 47 | # Evaluation 48 | # ================================================== 49 | checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) 50 | graph = tf.Graph() 51 | with graph.as_default(): 52 | session_conf = tf.ConfigProto( 53 | allow_soft_placement=FLAGS.allow_soft_placement, 54 | log_device_placement=FLAGS.log_device_placement) 55 | sess = tf.Session(config=session_conf) 56 | with sess.as_default(): 57 | # Load the saved meta graph and restore variables 58 | saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file)) 59 | saver.restore(sess, checkpoint_file) 60 | 61 | # Get the placeholders from the graph by name 62 | input_x = graph.get_operation_by_name("input_x").outputs[0] 63 | # input_y = graph.get_operation_by_name("input_y").outputs[0] 64 | dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0] 65 | 66 | # Tensors we want to evaluate 67 | predictions = graph.get_operation_by_name("output/predictions").outputs[0] 68 | 69 | # Generate batches for one epoch 70 | batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False) 71 | 72 | # Collect the predictions here 73 | all_predictions = [] 74 | 75 | for x_test_batch in batches: 76 | batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0}) 77 | all_predictions = np.concatenate([all_predictions, batch_predictions]) 78 | 79 | # Print accuracy if y_test is defined 80 | if y_test is not None: 81 | print(all_predictions, y_test) 82 | correct_predictions = float(sum(all_predictions == y_test)) 83 | print("Total number of test examples: {}".format(len(y_test))) 84 | print("Accuracy: {:g}".format(correct_predictions/float(len(y_test)))) 85 | 86 | # Save the evaluation to a csv 87 | predictions_human_readable = np.column_stack((np.array(x_raw), all_predictions)) 88 | out_path = os.path.join(FLAGS.checkpoint_dir, "..", "prediction.csv") 89 | print("Saving evaluation to {0}".format(out_path)) 90 | with open(out_path, 'w') as f: 91 | csv.writer(f).writerows(predictions_human_readable) 92 | -------------------------------------------------------------------------------- /news-analysis/predict.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | import os 6 | import time 7 | import datetime 8 | import data_helpers 9 | from text_cnn import TextCNN 10 | from tensorflow.contrib import learn 11 | import csv 12 | 13 | # Parameters 14 | # ================================================== 15 | 16 | # Eval Parameters 17 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 18 | tf.flags.DEFINE_string("checkpoint_dir", "runs/1481506269/checkpoints", "Checkpoint directory from training run") 19 | 20 | 21 | FLAGS = tf.flags.FLAGS 22 | FLAGS._parse_flags() 23 | 24 | inp = input("type in today's news headline: ") 25 | x_raw = [inp] 26 | 27 | # Map data into vocabulary 28 | vocab_path = os.path.join(FLAGS.checkpoint_dir,".." ,"vocab") 29 | vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) 30 | x_test = np.array(list(vocab_processor.transform(x_raw))) 31 | 32 | print("\nEvaluating...\n") 33 | 34 | # Evaluation 35 | # ================================================== 36 | checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) 37 | graph = tf.Graph() 38 | with graph.as_default(): 39 | sess = tf.Session() 40 | with sess.as_default(): 41 | # Load the saved meta graph and restore variables 42 | saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file)) 43 | saver.restore(sess, checkpoint_file) 44 | 45 | # Get the placeholders from the graph by name 46 | input_x = graph.get_operation_by_name("input_x").outputs[0] 47 | # input_y = graph.get_operation_by_name("input_y").outputs[0] 48 | dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0] 49 | 50 | # Tensors we want to evaluate 51 | predictions = graph.get_operation_by_name("output/predictions").outputs[0] 52 | 53 | # Generate batches for one epoch 54 | batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False) 55 | 56 | # Collect the predictions here 57 | all_predictions = [] 58 | 59 | for x_test_batch in batches: 60 | batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0}) 61 | all_predictions = np.concatenate([all_predictions, batch_predictions]) 62 | 63 | print(all_predictions) 64 | 65 | -------------------------------------------------------------------------------- /news-analysis/save/checkpoints/checkpoint: -------------------------------------------------------------------------------- 1 | model_checkpoint_path: "/home/ubuntu/cnn-text-classification-tf/runs/1481506269/checkpoints/model-6000" 2 | all_model_checkpoint_paths: "/home/ubuntu/cnn-text-classification-tf/runs/1481506269/checkpoints/model-6000" 3 | -------------------------------------------------------------------------------- /news-analysis/save/checkpoints/model-6000.data-00000-of-00001: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keon/deepstock/57bc386914b0c7ea837528ae7c3d180001279da8/news-analysis/save/checkpoints/model-6000.data-00000-of-00001 -------------------------------------------------------------------------------- /news-analysis/save/checkpoints/model-6000.index: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keon/deepstock/57bc386914b0c7ea837528ae7c3d180001279da8/news-analysis/save/checkpoints/model-6000.index -------------------------------------------------------------------------------- /news-analysis/save/checkpoints/model-6000.meta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keon/deepstock/57bc386914b0c7ea837528ae7c3d180001279da8/news-analysis/save/checkpoints/model-6000.meta -------------------------------------------------------------------------------- /news-analysis/save/prediction.csv: -------------------------------------------------------------------------------- 1 | Venezuela seizes 4.8 million toys,1.0 2 | Trump says he's turning away 'billions,1.0 3 | New Zealand elects new leader,1.0 4 | -------------------------------------------------------------------------------- /news-analysis/save/vocab: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keon/deepstock/57bc386914b0c7ea837528ae7c3d180001279da8/news-analysis/save/vocab -------------------------------------------------------------------------------- /news-analysis/text_cnn.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | 4 | 5 | class TextCNN(object): 6 | """ 7 | A CNN for text classification. 8 | Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. 9 | """ 10 | def __init__( 11 | self, sequence_length, num_classes, vocab_size, 12 | embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0): 13 | 14 | # Placeholders for input, output and dropout 15 | self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x") 16 | self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y") 17 | self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob") 18 | 19 | # Keeping track of l2 regularization loss (optional) 20 | l2_loss = tf.constant(0.0) 21 | 22 | # Embedding layer 23 | with tf.device('/cpu:0'), tf.name_scope("embedding"): 24 | W = tf.Variable( 25 | tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0), 26 | name="W") 27 | self.embedded_chars = tf.nn.embedding_lookup(W, self.input_x) 28 | self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1) 29 | 30 | # Create a convolution + maxpool layer for each filter size 31 | pooled_outputs = [] 32 | for i, filter_size in enumerate(filter_sizes): 33 | with tf.name_scope("conv-maxpool-%s" % filter_size): 34 | # Convolution Layer 35 | filter_shape = [filter_size, embedding_size, 1, num_filters] 36 | W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W") 37 | b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b") 38 | conv = tf.nn.conv2d( 39 | self.embedded_chars_expanded, 40 | W, 41 | strides=[1, 1, 1, 1], 42 | padding="VALID", 43 | name="conv") 44 | # Apply nonlinearity 45 | h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu") 46 | # Maxpooling over the outputs 47 | pooled = tf.nn.max_pool( 48 | h, 49 | ksize=[1, sequence_length - filter_size + 1, 1, 1], 50 | strides=[1, 1, 1, 1], 51 | padding='VALID', 52 | name="pool") 53 | pooled_outputs.append(pooled) 54 | 55 | # Combine all the pooled features 56 | num_filters_total = num_filters * len(filter_sizes) 57 | self.h_pool = tf.concat(3, pooled_outputs) 58 | self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total]) 59 | 60 | # Add dropout 61 | with tf.name_scope("dropout"): 62 | self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob) 63 | 64 | # Final (unnormalized) scores and predictions 65 | with tf.name_scope("output"): 66 | W = tf.get_variable( 67 | "W", 68 | shape=[num_filters_total, num_classes], 69 | initializer=tf.contrib.layers.xavier_initializer()) 70 | b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b") 71 | l2_loss += tf.nn.l2_loss(W) 72 | l2_loss += tf.nn.l2_loss(b) 73 | self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores") 74 | self.predictions = tf.argmax(self.scores, 1, name="predictions") 75 | 76 | # CalculateMean cross-entropy loss 77 | with tf.name_scope("loss"): 78 | losses = tf.nn.softmax_cross_entropy_with_logits(self.scores, self.input_y) 79 | self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss 80 | 81 | # Accuracy 82 | with tf.name_scope("accuracy"): 83 | correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1)) 84 | self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy") 85 | -------------------------------------------------------------------------------- /news-analysis/train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import datetime 4 | import tensorflow as tf 5 | from tensorflow.contrib import learn 6 | import numpy as np 7 | import data_helpers 8 | from text_cnn import TextCNN 9 | from sklearn import cross-validation 10 | 11 | # Parameters 12 | # ================================================== 13 | 14 | # Data loading params 15 | tf.flags.DEFINE_float("dev_sample_percentage", .1, "Percentage of the training data to use for validation") 16 | tf.flags.DEFINE_string("positive_data_file", "./data/rt-polarity/rt-polarity.pos", "Data source for the positive data.") 17 | tf.flags.DEFINE_string("negative_data_file", "./data/rt-polarity/rt-polarity.neg", "Data source for the positive data.") 18 | 19 | # Model Hyperparameters 20 | tf.flags.DEFINE_integer("embedding_dim", 128, "Dimensionality of character embedding (default: 128)") 21 | tf.flags.DEFINE_string("filter_sizes", "3,4,5", "Comma-separated filter sizes (default: '3,4,5')") 22 | tf.flags.DEFINE_integer("num_filters", 128, "Number of filters per filter size (default: 128)") 23 | tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") 24 | tf.flags.DEFINE_float("l2_reg_lambda", 0.0, "L2 regularizaion lambda (default: 0.0)") 25 | 26 | # Training parameters 27 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 28 | tf.flags.DEFINE_integer("num_epochs", 500, "Number of training epochs (default: 500)") 29 | tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)") 30 | tf.flags.DEFINE_integer("checkpoint_every", 100, "Save model after this many steps (default: 100)") 31 | # Misc Parameters 32 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 33 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 34 | 35 | FLAGS = tf.flags.FLAGS 36 | FLAGS._parse_flags() 37 | print("\nParameters:") 38 | for attr, value in sorted(FLAGS.__flags.items()): 39 | print("{}={}".format(attr.upper(), value)) 40 | print("") 41 | 42 | 43 | # Data Preparatopn 44 | # ================================================== 45 | 46 | # Load data 47 | print("Loading data...") 48 | x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file) 49 | 50 | # Build vocabulary 51 | max_document_length = max([len(x.split(" ")) for x in x_text]) 52 | vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length) 53 | x = np.array(list(vocab_processor.fit_transform(x_text))) 54 | 55 | # Randomly shuffle data 56 | np.random.seed(10) 57 | shuffle_indices = np.random.permutation(np.arange(len(y))) 58 | x_shuffled = x[shuffle_indices] 59 | y_shuffled = y[shuffle_indices] 60 | 61 | # Split train/test set 62 | # TODO: This is very crude, should use cross-validation 63 | 64 | #cross_validation 65 | 66 | x_train, x_dev, y_train, y_dev = sklearn.cross_validation.train_test_split(x_shuffled, y_shuffled, test_size=FLAGS.dev_sample_percentage) 67 | 68 | dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y))) 69 | #x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:] 70 | #y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:] 71 | print("Vocabulary Size: {:d}".format(len(vocab_processor.vocabulary_))) 72 | print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev))) 73 | sequence_length=x_train.shape[1] 74 | num_classes=y_train.shape[1] 75 | print("", sequence_length) 76 | print("", num_classes) 77 | 78 | 79 | # Training 80 | # ================================================== 81 | 82 | with tf.Graph().as_default(): 83 | session_conf = tf.ConfigProto( 84 | allow_soft_placement=FLAGS.allow_soft_placement, 85 | log_device_placement=FLAGS.log_device_placement) 86 | sess = tf.Session(config=session_conf) 87 | with sess.as_default(): 88 | cnn = TextCNN( 89 | sequence_length=x_train.shape[1], 90 | num_classes=y_train.shape[1], 91 | vocab_size=len(vocab_processor.vocabulary_), 92 | embedding_size=FLAGS.embedding_dim, 93 | filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), 94 | num_filters=FLAGS.num_filters, 95 | l2_reg_lambda=FLAGS.l2_reg_lambda) 96 | 97 | # Define Training procedure 98 | global_step = tf.Variable(0, name="global_step", trainable=False) 99 | optimizer = tf.train.AdamOptimizer(1e-3) 100 | grads_and_vars = optimizer.compute_gradients(cnn.loss) 101 | train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) 102 | 103 | # Keep track of gradient values and sparsity (optional) 104 | grad_summaries = [] 105 | for g, v in grads_and_vars: 106 | if g is not None: 107 | grad_hist_summary = tf.histogram_summary("{}/grad/hist".format(v.name), g) 108 | sparsity_summary = tf.scalar_summary("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) 109 | grad_summaries.append(grad_hist_summary) 110 | grad_summaries.append(sparsity_summary) 111 | grad_summaries_merged = tf.merge_summary(grad_summaries) 112 | 113 | # Output directory for models and summaries 114 | timestamp = str(int(time.time())) 115 | out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp)) 116 | print("Writing to {}\n".format(out_dir)) 117 | 118 | # Summaries for loss and accuracy 119 | loss_summary = tf.scalar_summary("loss", cnn.loss) 120 | acc_summary = tf.scalar_summary("accuracy", cnn.accuracy) 121 | 122 | # Train Summaries 123 | train_summary_op = tf.merge_summary([loss_summary, acc_summary, grad_summaries_merged]) 124 | train_summary_dir = os.path.join(out_dir, "summaries", "train") 125 | train_summary_writer = tf.train.SummaryWriter(train_summary_dir, sess.graph) 126 | 127 | # Dev summaries 128 | dev_summary_op = tf.merge_summary([loss_summary, acc_summary]) 129 | dev_summary_dir = os.path.join(out_dir, "summaries", "dev") 130 | dev_summary_writer = tf.train.SummaryWriter(dev_summary_dir, sess.graph) 131 | 132 | # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it 133 | checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) 134 | checkpoint_prefix = os.path.join(checkpoint_dir, "model") 135 | if not os.path.exists(checkpoint_dir): 136 | os.makedirs(checkpoint_dir) 137 | saver = tf.train.Saver(tf.global_variables()) 138 | 139 | # Write vocabulary 140 | vocab_processor.save(os.path.join(out_dir, "vocab")) 141 | 142 | # Initialize all variables 143 | sess.run(tf.global_variables_initializer()) 144 | 145 | def train_step(x_batch, y_batch): 146 | """ 147 | A single training step 148 | """ 149 | feed_dict = { 150 | cnn.input_x: x_batch, 151 | cnn.input_y: y_batch, 152 | cnn.dropout_keep_prob: FLAGS.dropout_keep_prob 153 | } 154 | _, step, summaries, loss, accuracy = sess.run( 155 | [train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy], 156 | feed_dict) 157 | time_str = datetime.datetime.now().isoformat() 158 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 159 | train_summary_writer.add_summary(summaries, step) 160 | 161 | def dev_step(x_batch, y_batch, writer=None): 162 | """ 163 | Evaluates model on a dev set 164 | """ 165 | feed_dict = { 166 | cnn.input_x: x_batch, 167 | cnn.input_y: y_batch, 168 | cnn.dropout_keep_prob: 1.0 169 | } 170 | step, summaries, loss, accuracy = sess.run( 171 | [global_step, dev_summary_op, cnn.loss, cnn.accuracy], 172 | feed_dict) 173 | time_str = datetime.datetime.now().isoformat() 174 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 175 | if writer: 176 | writer.add_summary(summaries, step) 177 | 178 | # Generate batches 179 | batches = data_helpers.batch_iter( 180 | list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) 181 | # Training loop. For each batch... 182 | for batch in batches: 183 | x_batch, y_batch = zip(*batch) 184 | train_step(x_batch, y_batch) 185 | current_step = tf.train.global_step(sess, global_step) 186 | if current_step % FLAGS.evaluate_every == 0: 187 | print("\nEvaluation:") 188 | dev_step(x_dev, y_dev, writer=dev_summary_writer) 189 | print("") 190 | if current_step % FLAGS.checkpoint_every == 0: 191 | path = saver.save(sess, checkpoint_prefix, global_step=current_step) 192 | print("Saved model checkpoint to {}\n".format(path)) 193 | -------------------------------------------------------------------------------- /stock-analysis/convnet/README.md: -------------------------------------------------------------------------------- 1 | # Convolutional Neural Network 2 | Take reference from RobRomijnders's work (http://robromijnders.github.io/CNN_tsc/) 3 | -------------------------------------------------------------------------------- /stock-analysis/convnet/cnn_classifier.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | import matplotlib.pyplot as plt 4 | from tensorflow.python.framework import ops 5 | from tensorflow.python.ops import clip_ops 6 | from bn_class import * 7 | 8 | 9 | # Hyperparameters 10 | num_filt_1 = 15 # Number of filters in first conv layer 11 | num_filt_2 = 8 # Number of filters in second conv layer 12 | num_filt_3 = 8 # Number of filters in thirs conv layer 13 | num_fc_1 = 40 # Number of neurons in hully connected layer 14 | max_iterations = 20000 15 | batch_size = 100 16 | dropout = 0.5 # Dropout rate in the fully connected layer 17 | plot_row = 5 # How many rows do you want to plot in the visualization 18 | regularization = 1e-4 19 | learning_rate = 2e-3 20 | input_norm = False # Do you want z-score input normalization? 21 | 22 | 23 | # load data 24 | dataset = "2330" 25 | datadir = 'data/'+ dataset 26 | data_train = np.loadtxt(datadir+'_train_ma',delimiter=',') 27 | data_test_val = np.loadtxt(datadir+'_test_ma',delimiter=',') 28 | 29 | 30 | # split training and testing data 31 | X_train = data_train[:,1:] 32 | X_test = data_test_val[:,1:] 33 | N = X_train.shape[0] 34 | Ntest = X_test.shape[0] 35 | D = X_train.shape[1] 36 | y_train = data_train[:,0] 37 | y_test = data_test_val[:,0] 38 | 39 | 40 | # normalize x and y 41 | num_classes = len(np.unique(y_train)) 42 | base = np.min(y_train) #Check if data is 0-based 43 | if base != 0: 44 | y_train -=base 45 | y_test -= base 46 | 47 | if input_norm: 48 | mean = np.mean(X_train,axis=0) 49 | variance = np.var(X_train,axis=0) 50 | X_train -= mean 51 | #The 1e-9 avoids dividing by zero 52 | X_train /= np.sqrt(variance)+1e-9 53 | X_test -= mean 54 | X_test /= np.sqrt(variance)+1e-9 55 | 56 | epochs = np.floor(batch_size*max_iterations / N) 57 | print('Train with approximately %d epochs' %(epochs)) 58 | 59 | 60 | # place for the input variables 61 | x = tf.placeholder("float", shape=[None, D], name = 'Input_data') 62 | y_ = tf.placeholder(tf.int64, shape=[None], name = 'Ground_truth') 63 | keep_prob = tf.placeholder("float") 64 | bn_train = tf.placeholder(tf.bool) #Boolean value to guide batchnorm 65 | 66 | 67 | # w and b and conv function 68 | def weight_variable(shape, name): 69 | initial = tf.truncated_normal(shape, stddev=0.1) 70 | return tf.Variable(initial, name = name) 71 | 72 | def bias_variable(shape, name): 73 | initial = tf.constant(0.1, shape=shape) 74 | return tf.Variable(initial, name = name) 75 | 76 | def conv2d(x, W): 77 | return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 78 | 79 | def max_pool_2x2(x): 80 | return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 81 | strides=[1, 2, 2, 1], padding='SAME') 82 | 83 | with tf.name_scope("Reshaping_data") as scope: 84 | x_image = tf.reshape(x, [-1,D,1,1]) 85 | 86 | 87 | # Build the graph 88 | # ewma is the decay for which we update the moving average of the 89 | # mean and variance in the batch-norm layers 90 | with tf.name_scope("Conv1") as scope: 91 | W_conv1 = weight_variable([4, 1, 1, num_filt_1], 'Conv_Layer_1') 92 | b_conv1 = bias_variable([num_filt_1], 'bias_for_Conv_Layer_1') 93 | a_conv1 = conv2d(x_image, W_conv1) + b_conv1 94 | 95 | with tf.name_scope('Batch_norm_conv1') as scope: 96 | ewma = tf.train.ExponentialMovingAverage(decay=0.99) 97 | bn_conv1 = ConvolutionalBatchNormalizer(num_filt_1, 0.001, ewma, True) 98 | update_assignments = bn_conv1.get_assigner() 99 | a_conv1 = bn_conv1.normalize(a_conv1, train=bn_train) 100 | h_conv1 = tf.nn.relu(a_conv1) 101 | 102 | with tf.name_scope("Conv2") as scope: 103 | W_conv2 = weight_variable([4, 1, num_filt_1, num_filt_2], 'Conv_Layer_2') 104 | b_conv2 = bias_variable([num_filt_2], 'bias_for_Conv_Layer_2') 105 | a_conv2 = conv2d(h_conv1, W_conv2) + b_conv2 106 | 107 | with tf.name_scope('Batch_norm_conv2') as scope: 108 | bn_conv2 = ConvolutionalBatchNormalizer(num_filt_2, 0.001, ewma, True) 109 | update_assignments = bn_conv2.get_assigner() 110 | a_conv2 = bn_conv2.normalize(a_conv2, train=bn_train) 111 | h_conv2 = tf.nn.relu(a_conv2) 112 | 113 | with tf.name_scope("Conv3") as scope: 114 | W_conv3 = weight_variable([4, 1, num_filt_2, num_filt_3], 'Conv_Layer_3') 115 | b_conv3 = bias_variable([num_filt_3], 'bias_for_Conv_Layer_3') 116 | a_conv3 = conv2d(h_conv2, W_conv3) + b_conv3 117 | 118 | with tf.name_scope('Batch_norm_conv3') as scope: 119 | bn_conv3 = ConvolutionalBatchNormalizer(num_filt_3, 0.001, ewma, True) 120 | update_assignments = bn_conv3.get_assigner() 121 | a_conv3 = bn_conv3.normalize(a_conv3, train=bn_train) 122 | h_conv3 = tf.nn.relu(a_conv3) 123 | 124 | with tf.name_scope("Fully_Connected1") as scope: 125 | W_fc1 = weight_variable([D*num_filt_3, num_fc_1], 'Fully_Connected_layer_1') 126 | b_fc1 = bias_variable([num_fc_1], 'bias_for_Fully_Connected_Layer_1') 127 | h_conv3_flat = tf.reshape(h_conv3, [-1, D*num_filt_3]) 128 | h_fc1 = tf.nn.relu(tf.matmul(h_conv3_flat, W_fc1) + b_fc1) 129 | 130 | with tf.name_scope("Fully_Connected2") as scope: 131 | h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 132 | W_fc2 = tf.Variable(tf.truncated_normal([num_fc_1, num_classes], stddev=0.1),name = 'W_fc2') 133 | b_fc2 = tf.Variable(tf.constant(0.1, shape=[num_classes]),name = 'b_fc2') 134 | h_fc2 = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 135 | 136 | with tf.name_scope("SoftMax") as scope: 137 | regularizers = (tf.nn.l2_loss(W_conv1) + tf.nn.l2_loss(b_conv1) + 138 | tf.nn.l2_loss(W_conv2) + tf.nn.l2_loss(b_conv2) + 139 | tf.nn.l2_loss(W_conv3) + tf.nn.l2_loss(b_conv3) + 140 | tf.nn.l2_loss(W_fc1) + tf.nn.l2_loss(b_fc1) + 141 | tf.nn.l2_loss(W_fc2) + tf.nn.l2_loss(b_fc2)) 142 | loss = tf.nn.sparse_softmax_cross_entropy_with_logits(h_fc2,y_) 143 | cost = tf.reduce_sum(loss) / batch_size 144 | cost += regularization*regularizers 145 | 146 | 147 | # define train optimizer 148 | with tf.name_scope("train") as scope: 149 | tvars = tf.trainable_variables() 150 | #We clip the gradients to prevent explosion 151 | grads = tf.gradients(cost, tvars) 152 | optimizer = tf.train.AdamOptimizer(learning_rate) 153 | gradients = zip(grads, tvars) 154 | train_step = optimizer.apply_gradients(gradients) 155 | 156 | numel = tf.constant([[0]]) 157 | for gradient, variable in gradients: 158 | if isinstance(gradient, ops.IndexedSlices): 159 | grad_values = gradient.values 160 | else: 161 | grad_values = gradient 162 | 163 | numel +=tf.reduce_sum(tf.size(variable)) 164 | with tf.name_scope("Evaluating_accuracy") as scope: 165 | correct_prediction = tf.equal(tf.argmax(h_fc2,1), y_) 166 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 167 | 168 | 169 | # run session and evaluate performance 170 | perf_collect = np.zeros((3,int(np.floor(max_iterations /100)))) 171 | merged = tf.merge_all_summaries() 172 | with tf.Session() as sess: 173 | writer = tf.train.SummaryWriter("/home/carine/Desktop/eventlog/", sess.graph_def) 174 | sess.run(tf.initialize_all_variables()) 175 | 176 | step = 0 # Step is a counter for filling the numpy array perf_collect 177 | for i in range(max_iterations):#training process 178 | batch_ind = np.random.choice(N,batch_size,replace=False) 179 | 180 | if i==0: 181 | acc_test_before = sess.run(accuracy, feed_dict={ x: X_test, y_: y_test, keep_prob: 1.0, bn_train : False}) 182 | if i%100 == 0: 183 | #Check training performance 184 | result = sess.run(accuracy,feed_dict = { x: X_train, y_: y_train, keep_prob: 1.0, bn_train : False}) 185 | perf_collect[1,step] = result 186 | 187 | #Check validation performance 188 | result = sess.run(accuracy, feed_dict={ x: X_test, y_: y_test, keep_prob: 1.0, bn_train : False}) 189 | acc = result 190 | perf_collect[0,step] = acc 191 | print(" Training accuracy at %s out of %s is %s" % (i,max_iterations, acc)) 192 | step +=1 193 | sess.run(train_step,feed_dict={x:X_train[batch_ind], y_: y_train[batch_ind], keep_prob: dropout, bn_train : True}) 194 | 195 | #training process done! 196 | result = sess.run([accuracy,numel], feed_dict={ x: X_test, y_: y_test, keep_prob: 1.0, bn_train : False}) 197 | 198 | predict=sess.run(tf.argmax(h_fc2,1), feed_dict={ x: X_test, y_: y_test, keep_prob: 1.0, bn_train : False}) 199 | pred_summ=tf.scalar_summary("prediction", predict) 200 | print("pred "+"real") 201 | for x in xrange(0,len(predict)): 202 | print(str(predict[x]+1)+" "+str(int(y_test[x]+1))) 203 | acc_test = result[0] 204 | print('The network has %s trainable parameters'%(result[1])) 205 | 206 | writer.flush() 207 | 208 | # show the graph of validation accuracy 209 | # 2 for drop or same, 1 for rise 210 | print('The accuracy on the test data is %.3f, before training was %.3f' %(acc_test,acc_test_before)) 211 | plt.figure() 212 | plt.plot(perf_collect[0],label='Valid accuracy') 213 | plt.plot(perf_collect[1],label = 'Train accuracy') 214 | plt.axis([0, step, 0, np.max(perf_collect)]) 215 | plt.show() 216 | plt.figure() 217 | 218 | --------------------------------------------------------------------------------