ワイン評価
Coding
import numpy as np
import tensorflow as tf
import pandas as pd
dataset = np.genfromtxt("./wine.csv", delimiter=';', dtype=np.float32, filling_values=(0))
_,index = np.unique(dataset[:,0], return_index=True)
dataset = dataset[index]
datas = dataset[:,0:11]
labels = dataset[:,11]
N = len(labels)
vector_labels = np.zeros((N,10))
for i in xrange(N):
vector_labels[i][int(labels[i])] = 1.0
test_data_size = len(dataset) // 8
test_datas = datas[train_data_size:]
test_labels = vector_labels[train_data_size:].reshape(test_data_size, 10)
tf.reset_default_graph()
LOGDIR = './data'
def single_layer(X, num_in, num_out):
"""隠れ層"""
W = tf.Variable(tf.truncated_normal([num_in,num_out]))
b = tf.Variable(tf.zeros([num_out]))
f = tf.matmul(X, W) + b
layer = tf.nn.relu(f)
return layer
def output_layer(layer, num_in, num_out):
"""出力層"""
W = tf.Variable(tf.zeros([num_in,num_out]))
b = tf.Variable(tf.zeros([num_out]))
f = tf.matmul(layer, W) + b
p = tf.nn.softmax(f)
return p
with tf.Graph().as_default():
X = tf.placeholder(tf.float32, shape=(None,11), name="input")
y_ = tf.placeholder(tf.float32, shape=(None,10), name="output")
with tf.name_scope('forward'):
hidden_layer = single_layer(X, 11, 20)
y = output_layer(hidden_layer, 20, 10)
with tf.name_scope('cost'):
cost = -tf.reduce_sum(y_*tf.log(y))
train_op = tf.train.AdagradOptimizer(0.01).minimize(cost)
with tf.name_scope('accuracy'):
correct_pred = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy_op = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
sess = tf.Session()
summary_writer = tf.summary.FileWriter(LOGDIR, sess.graph)
init_op = tf.global_variables_initializer()
sess.run(init_op)
training_step = 20000
validation_step = 100
for step in xrange(training_step):
sess.run(train_op, feed_dict={X:test_datas, y_:test_labels})
if step % validation_step == 0:
accuracy_output,cost_output = sess.run([accuracy_op,cost], feed_dict={X:test_datas, y_:test_labels})
print "step %d, cost %f, accuracy %f" % (step,cost_output,accuracy_output)
summary_writer.flush()