Tensorflow csv文件读写与分批训练

来源:互联网 发布:锐速破解版 windows 编辑:程序博客网 时间:2024/06/05 18:23


Tensorflow-1: csv文件读写与分批训练

原创 2017年04月29日 22:28:23

今天尝试了一下读写csv文件并使用tensorflow训练数据,很方便。

程序训练的一个单隐藏层的网络,程序中所用到的m3c_data_train.csv和m3c_data_test.csv文件都是由17列若干行的数据组成,17列包括输入12列、输出4列和用来打乱数据用的随机列。

[python] view plain copy
  1. <span style="font-family:'Times New Roman';font-size:18px;" deep="5"># -*- coding: utf-8 -*-  
  2. import tensorflow as tf  
  3. import numpy as np  
  4. import pandas as pd  
  5. import matplotlib.pyplot as plt  
  6. import csv  
  7. import os  
  8.   
  9. os.chdir("/Users/apple/Desktop/")  
  10. print(os.getcwd())  
  11.   
  12. def read_data(file_queue):  
  13.     reader = tf.TextLineReader(skip_header_lines=0)  
  14.     key, value = reader.read(queue=file_queue)  
  15.     defaults = list([0.for i in range(17))  
  16.     input_Idq_s_1, input_Idq_s_2, input_Edq_s_1, input_Edq_s_2, input_MagV_s, input_Idq_m_1, input_Idq_m_2, \  
  17.         input_Edq_m_1, input_Edq_m_2, input_MagV_m, input_Vdc, input_Pt, output_Vdq_s_1, output_Vdq_s_2, \  
  18.         output_Vdq_m_1, output_Vdq_m_2, rand = tf.decode_csv(records=value, record_defaults=defaults)  
  19.     input_list = list([input_Idq_s_1, input_Idq_s_2, input_Edq_s_1, input_Edq_s_2, input_MagV_s, input_Idq_m_1, \  
  20.         input_Idq_m_2, input_Edq_m_1, input_Edq_m_2, input_MagV_m, input_Vdc, input_Pt])  
  21.     output_list = list([output_Vdq_s_1, output_Vdq_s_2, output_Vdq_m_1, output_Vdq_m_2])  
  22.     input_minimum = list([26.9223227068843, -98.478034501763594.2182270883746, -2547.04028098514188.434752223462,   
  23.         -3074.24987628734, -80.066303079208394.3688439437233, -4294.32895768398188.73790394315911.3363750371760, \  
  24.         14.5698874167718])  
  25.     input_maximum = list([338.471317085834132.4250438755578178.666797590723962.0409275484714196.4064943722, \  
  26.         1551.6871626409575.95588046772498170.273989304534158.2888384473514515.086530737820098.8974807069, \  
  27.         12123066.0740678])  
  28.     output_minimum = list([-105.675264765919, -3839.50483890428, -9675.45018951087, -3704.86493155417])  
  29.     output_maximum = list([10981.38243307065832.43660916112105.5365925102228641.08573453797])  
  30.     input_normalization = list(map(lambda x, min_x, max_x: (x - min_x) / (max_x - min_x), input_list, \  
  31.         input_minimum, input_maximum))  
  32.     output_normalization = list(map(lambda x, min_x, max_x: (x - min_x) / (max_x - min_x), output_list, \  
  33.         output_minimum, output_maximum))  
  34.     return input_normalization, output_normalization[3]  
  35.   
  36. def create_pipeline(filename, batch_size, num_epochs=None):  
  37.     file_queue = tf.train.string_input_producer(string_tensor=[filename], num_epochs=num_epochs)  
  38.     example, label = read_data(file_queue=file_queue)  
  39.     min_after_dequeue = 1000  
  40.     capacity = min_after_dequeue + batch_size  
  41.     example_batch, label_batch = tf.train.shuffle_batch(  
  42.         tensors=[example, label],  
  43.         batch_size=batch_size,  
  44.         capacity=capacity,  
  45.         min_after_dequeue=min_after_dequeue  
  46.     )  
  47.     return example_batch, label_batch  
  48.   
  49. def relu(x, alpha=0., max_value=None):  
  50.     negative_part = tf.nn.relu(-x)  
  51.     x = tf.nn.relu(x)  
  52.     if max_value is not None:  
  53.         x = tf.clip_by_value(x, tf.cast(0., dtype=tf.float32),  
  54.                              tf.cast(max_value, dtype=tf.float32))  
  55.     x -= tf.constant(alpha, dtype=tf.float32) * negative_part  
  56.     return x  
  57.   
  58. def add_layer(inputs, in_size, out_size, activation_function=None, layer_name='Layer'):  
  59.     with tf.name_scope(layer_name):  
  60.         with tf.name_scope('Weights'):  
  61.             Weights = tf.Variable(initial_value=tf.random_normal([in_size, out_size]))  
  62.         with tf.name_scope('Biases'):  
  63.             biases = tf.Variable(initial_value=tf.zeros(shape=[1, out_size]) + 0.1)  
  64.         with tf.name_scope('Wx_plus_b'):  
  65.             Wx_plus_b = tf.matmul(inputs, Weights) + biases  
  66.         if activation_function is None:  
  67.             outputs = Wx_plus_b  
  68.         elif activation_function == tf.nn.relu:  
  69.             outputs = relu(Wx_plus_b, alpha=0.05)  
  70.         else:  
  71.             outputs = activation_function(Wx_plus_b)  
  72.         return outputs, Weights, biases  
  73.   
  74. x_train_batch, y_train_batch = create_pipeline(filename='m3c_data_train.csv', batch_size=50, num_epochs=1000)  
  75. x_test, y_test = create_pipeline(filename='m3c_data_test.csv', batch_size=60)  
  76. global_step = tf.Variable(initial_value=0, trainable=False)  
  77. #learning_rate = tf.constant(1e-3, dtype=tf.float32)  
  78. learning_rate = tf.train.exponential_decay(1e-4, global_step, 1e41e-5)  
  79.   
  80. with tf.name_scope('InputLayer'):  
  81.     x = tf.placeholder(dtype=tf.float32, shape=[None12])  
  82.     y = tf.placeholder(dtype=tf.float32, shape=[None])  
  83.       
  84. hidden_0, Weights_hidden_0, biases_hidden_0 = add_layer(inputs=x, in_size=12, out_size=5, \  
  85.     activation_function=tf.nn.relu, layer_name='HiddenLayer0')  
  86. hidden_1, Weights_hidden_1, biases_hidden_1 = add_layer(inputs=hidden_0, in_size=5, out_size=5, \  
  87.     activation_function=tf.nn.relu, layer_name='HiddenLayer1')  
  88. prediction, Weights_prediction, biases_prediction = add_layer(inputs=hidden_1, in_size=5, out_size=1, \  
  89.     activation_function=None, layer_name='OutputLayer')  
  90.   
  91. with tf.name_scope('Loss'):  
  92.     loss = tf.reduce_mean(tf.reduce_sum(input_tensor=tf.square(y-prediction), reduction_indices=[1]))  
  93. tf.summary.scalar(name='Loss', tensor=loss)  
  94.   
  95. with tf.name_scope('Train'):  
  96.     train_step = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss=loss, \  
  97.         global_step=global_step)  
  98.   
  99. correct_prediction = tf.equal(tf.argmax(input=prediction, axis=1), tf.cast(y, tf.int64))  
  100. accuracy = tf.reduce_mean(input_tensor=tf.cast(correct_prediction, tf.float32))  
  101. tf.summary.scalar(name='Accuracy', tensor=accuracy)  
  102.   
  103. init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())  
  104. merged_summary = tf.summary.merge_all()  
  105.   
  106. sess = tf.Session()  
  107. train_writer = tf.summary.FileWriter(logdir='logs/train', graph=sess.graph)  
  108. test_writer = tf.summary.FileWriter(logdir='logs/test', graph=sess.graph)  
  109. sess.run(init)  
  110.   
  111. coord = tf.train.Coordinator()  
  112. threads = tf.train.start_queue_runners(sess=sess, coord=coord)  
  113.   
  114. try:  
  115.     print("Training: ")  
  116.     count = 0  
  117.     curr_x_test_batch, curr_y_test_batch = sess.run([x_test, y_test])  
  118.   
  119.     while not coord.should_stop():  
  120.         count += 1  
  121.         curr_x_train_batch, curr_y_train_batch = sess.run([x_train_batch, y_train_batch])  
  122.         sess.run(train_step, feed_dict={  
  123.             x: curr_x_train_batch, y: curr_y_train_batch  
  124.         })  
  125.         lr = sess.run(learning_rate)  
  126.         loss_, summary = sess.run([loss, merged_summary], feed_dict={  
  127.             x: curr_x_train_batch, y: curr_y_train_batch  
  128.         })  
  129.         train_writer.add_summary(summary, count)  
  130.         loss_, test_acc, test_summary = sess.run([loss, accuracy, merged_summary], feed_dict={  
  131.             x: curr_x_test_batch, y: curr_y_test_batch  
  132.         })  
  133.         test_writer.add_summary(summary=summary, global_step=count)  
  134.         print('Batch =', count, 'LearningRate =', lr, 'Loss =', loss_)  
  135.   
  136. except tf.errors.OutOfRangeError:  
  137.     print('Done training -- epoch limit reached')  
  138.   
  139. finally:  
  140.     writer = tf.summary.FileWriter("logs/", sess.graph)  
  141.     Weights_hidden_0_, biases_hidden_0_, Weights_hidden_1_, biases_hidden_1_, Weights_prediction_, \  
  142.         biases_prediction_ = sess.run([Weights_hidden_0, biases_hidden_0, Weights_hidden_1, biases_hidden_1, \  
  143.         Weights_prediction, biases_prediction])  
  144.     export_data = pd.DataFrame(data=list(Weights_hidden_0_)+list(biases_hidden_0_)+list(Weights_hidden_1_)+\  
  145.         list(biases_hidden_1_)+list(Weights_prediction_)+list(biases_prediction_))  
  146.     export_data.to_csv('results_output_3.csv')  
  147.   
  148. coord.request_stop()  
  149. coord.join(threads=threads)  
  150. sess.close()</span> 

原创粉丝点击