-
Notifications
You must be signed in to change notification settings - Fork 0
/
ANNTEST.py
340 lines (239 loc) · 9.43 KB
/
ANNTEST.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 7 13:29:44 2017
@author: user98
"""
######CSV Style: 0:ID 1-88:feature 89:weight 90:label
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas as pd
import tensorflow as tf
import numpy as np
import math
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
from tensorflow.contrib import learn
tf.logging.set_verbosity(tf.logging.INFO)
#Generate Training Set
DIR = "../data/stock_train_data_20170901.csv"
COLUMNS = list(range(1,91)) #Read Feature,weight,label
all_set = pd.read_csv(DIR, skipinitialspace=True,
skiprows=0, usecols=COLUMNS).as_matrix()
SORT = list(range(0,89))
SORT.insert(0,89) #89,0-87,88
all_set = all_set[:,np.array(SORT)] #Change into 0Label,Feature,88Weight
np.random.shuffle(all_set)
#training_set=all_set
training_set=all_set[0:math.floor(all_set.shape[0]*0.7)]
prediction_set=all_set[math.floor(all_set.shape[0]*0.7):]
TESTDIR="../data/stock_test_data_20170901.csv"
TRAINING_STEPS =200
LEARNING_RATE = 0.002
MODEL_DIR = "../data/model3"
BATCH_SIZE = 800
OPTIMIZER = "Adam"
#predicted_result = None
exp = None
predicted_prob = None
prediction_set = None
predicted_class = None
bias_3 = None
weight_3 = None
n1= 88
n2=44
n3= 2
n4= 22
n5= 2
'''def normalize(a):
a_norm = tf.norm(a,axis=1,keep_dims=True)
a_normalized = tf.divide(a,a_norm)
return a_normalized'''
def model_fn(features, targets, mode, params):
"""Model function for Estimator."""
#Build the network
#input_layer = tf.contrib.layers.input_from_feature_columns(columns_to_tensors=features, feature_columns=feature_cols)
'''
init3_n1 = tf.constant_initializer(np.eye(n1, M=3))
init_3 = tf.constant_initializer(np.eye(3, M=n3))
init_iden = tf.constant_initializer(np.eye(n1, M=n3))
init3 = tf.constant_initializer(np.eye(n3, M=n2))'''
# Comy_estimatorect the first hidden layer to input layer
first_hidden_layer = tf.layers.dense(features, n1, activation=tf.nn.relu)
first_processed = tf.contrib.layers.dropout(
first_hidden_layer, keep_prob=1)
# Connect the second hidden layer to first hidden layer with relu
second_hidden_layer = tf.layers.dense(first_processed, n2, activation=tf.nn.relu)
second_processed = tf.contrib.layers.dropout(
#tf.contrib.layers.layer_norm(
second_hidden_layer,1
)
third_hidden_layer = tf.layers.dense(second_processed, n3, activation=tf.nn.relu)
third_processed = tf.contrib.layers.dropout(
#tf.contrib.layers.layer_norm(,activation_fn=)
third_hidden_layer,1)
'''
fouth_hidden_layer = tf.layers.dense(third_processed, n4, activation=tf.nn.relu)
fouth_processed = tf.contrib.layers.dropout(
#tf.contrib.layers.layer_norm(,activation_fn=)
fouth_hidden_layer, 0.9)
fifth_hidden_layer = tf.layers.dense(fouth_processed, n4, activation=tf.nn.relu)
fifth_processed = tf.contrib.layers.dropout(
#tf.contrib.layers.layer_norm(,activation_fn=)
fifth_hidden_layer, 1)
'''
# Comy_estimatorect the output layer to second hidden layer (no activation fn)
logits = tf.layers.dense(third_processed, 2, activation=None)
weights = tf.constant(params["weights"])
#logits = tf.contrib.layers.layer_norm(pre_logits,activation_fn=None)
#logits_reshaped = tf.reshape(logits, [-1, 3])
#logits = tf.contrib.layers.unit_norm(pre_logits, 1, epsilon=1e-20)
#softmax_probability = tf.nn.softmax(logits)
#normalized prob
#normalized_prob =
# Generate Predictions
predictions = {
"classes": tf.argmax(
input=logits, axis=1),
"probabilities": tf.nn.softmax(
logits, name="softmax_tensor")
}
# Calculate loss
onehot_labels = tf.reshape(tf.contrib.layers.one_hot_encoding(targets, 2),[-1, 2])
#loss = tf.losses.softmax_cross_entropy(onehot_labels, logits, weights=weights)
#loss = tf.losses.softmax_cross_entropy(onehot_labels, logits)
loss = None
train_op = None
# Calculate Loss (for both TRAIN and EVAL modes)
if mode != learn.ModeKeys.TRAIN:
#onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)
loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits)
# Configure the Training Op (for TRAIN mode)
if mode == learn.ModeKeys.TRAIN:
loss = tf.losses.softmax_cross_entropy(onehot_labels, logits, weights=weights)
train_op = tf.contrib.layers.optimize_loss(
loss=loss,
global_step=tf.contrib.framework.get_global_step(),
learning_rate=params["learning_rate"],
optimizer= OPTIMIZER)
# Return a ModelFnOps object (eval_metrics not included)
return model_fn_lib.ModelFnOps(
mode=mode, predictions=predictions, loss=loss, train_op=train_op)
def input_fn(data_set):
'''feature_cols = {k: tf.constant(data_set[k].values) for k in FEATURES}
#features = tf.constant([data_set[k].values for k in FEATURES])
labels = tf.constant(data_set[LABEL].values)'''
features = tf.constant(np.delete(data_set, 0, 1))
labels = tf.constant(np.int_(np.delete(data_set, np.s_[1:], 1)))
return features, labels
def new_input_fn(data_set):
'''feature_cols = {k: tf.constant(data_set[k].values) for k in FEATURES}
#features = tf.constant([data_set[k].values for k in FEATURES])
labels = tf.constant(data_set[LABEL].values)'''
features = tf.constant(data_set)
labels = tf.constant(np.int_(np.delete(data_set, np.s_[1:], 1)))
return features, labels
def main():
# Load datasets
#skip some rows (use them as test/pred set later)
#not_load = np.random.randint(1000, size=10)
global prediction_set
global training_weight
global training_set
'''
all_set = pd.read_csv(DIR, skipinitialspace=True,
skiprows=0, usecols=COLUMNS).as_matrix()
SORT = list(range(0,89))
SORT.insert(0,89)
all_set = all_set[:,np.array(SORT)]
'''
training_weight=training_set[:,-1]
training_set=training_set[:,:-1]
'''
'''
#Prediction set without HP column, used to calc expectation
# Feature cols
model_params = {"learning_rate": LEARNING_RATE, "model_dir": MODEL_DIR, "weights": training_weight}
configs = tf.contrib.learn.RunConfig(save_summary_steps=500)
my_estimator = tf.contrib.learn.Estimator(model_fn=model_fn, params=model_params,
config=configs,
model_dir= MODEL_DIR)
validation_monitor = tf.contrib.learn.monitors.ValidationMonitor(
input_fn=lambda: input_fn(training_set),
early_stopping_metric="loss",
early_stopping_metric_minimize=True,
early_stopping_rounds=200)
#Initialize the training!!!
my_estimator.fit(input_fn=lambda: input_fn(training_set), steps=TRAINING_STEPS)
#SKCompat Version (accepts using batch size)
global predicted_result
global exp
global predicted_prob
#Removed the outside "list"
predicted_result = my_estimator.predict(input_fn=lambda: new_input_fn(prediction_set),as_iterable=False)
predicted_prob = predicted_result["probabilities"]
predicted_class = predicted_result["classes"]
np.save('result.npy',predicted_prob)
np.savetxt('result.csv',predicted_prob,delimiter=',')
'''
global bias_3
global weight_3
print(my_estimator.get_variable_names())
#bias_3 = my_estimator.get_variable_value('fully_connected_3/biases')
weight_3 = my_estimator.get_variable_value('dense/kernel')'''
'''
exp = np.multiply(predicted_prob, np.array(prediction_set2))
print(exp)
'''
def accuracy():
pass
'''
def profit_rate():
count = 0
profit = 0
for i in range(0,exp.shape[0]):
if np.max(exp[i,:])>1.1:
count += 1
if np.argmax(exp[i,:]) == prediction_set[i, 0]:
profit += prediction_set2.iloc[i,np.argmax(exp[i,:])]
pr = profit/count
print("Profit rate: " + str(pr))
print("Count: " + str(count))
def profit_rate_2():
put = 0
profit = 0
count = 0
def invest(multiple):
nonlocal count
nonlocal profit
nonlocal put
count += 1
put += multiple
if np.argmax(exp[i,:]) == prediction_set[i,0]:
profit += multiple * prediction_set2.iloc[i,np.argmax(exp[i,:])]
for i in range(0,exp.shape[0]):
if np.max(exp[i,:])>1.3:
invest(3)
elif np.max(exp[i,:])>1.2:
invest(2)
elif np.max(exp[i,:])>1.1:
invest(1)
pr = profit/put
print("Profit rate: " + str(pr))
print("Count: " + str(count))
#profit_rate()
#profit_rate_2()
'''
#newaccuracy()
'''
a = tf.reshape(tf.constant(float(input())),[1,None])
b = tf.reshape(tf.constant(float(input())),[1,None])
c = tf.reshape(tf.constant(float(input())),[1,None])
def my_input_fn():
labels = None
input_dict = {'AVG_H': a, 'AVG_D': b, 'AVG_A': c}
return input_dict, labels
input_pro = list(my_estimator.predict_proba(input_fn=my_input_fn
, as_iterable=False))
'''
if __name__ == "__main__":
main()