- Subject description:
Please use Tensorflow achieve Softmax multi-classification.
- Topics requirements:
① import the necessary dependent libraries, and set the random seed. (5 points)
② definition data set, wherein:
x_data
= [[1, 2, 1, 1], [2, 1, 3, 2], [3, 1, 3, 4], [4, 1, 5, 5], [1, 7, 5, 5], [1, 2,
5, 6], [1, 6, 6, 6], [1, 7, 7, 7]];
y_data
= [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 1, 0], [0, 1, 0], [0, 1, 0],[1, 0, 0], [1, 0, 0]]。(5分)
③ defined placeholders. (5 points)
④ defined weights W and bias b. (5 points)
⑤ defined prediction model, the activation function using the softmax. (5 points)
⑥ definition of the cost or loss function. (5 points)
⑦ defined gradient descent optimization, a learning rate is set to 0.01. (5 points)
⑧ accuracy of calculations. (5 points)
⑨ session is created and initialized global variables. (5 points)
⑩ start training iteration, loop iteration 5000, the convergence of once every 500 print output value of the loss. (5 points)
11 printout accuracy of the model. (5 points)
Given a set of 12 x: [[4,1,2,3], [3,2,4,5]], the set of test data, and print out the test results. (5 points)
import tensorflow as tf
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]="3"
#设置随机种子
tf.set_random_seed(111)
#加载数据
x_data = [[1, 2, 1, 1], [2, 1, 3, 2], [3, 1, 3, 4], [4, 1, 5, 5], [1, 7, 5, 5], [1, 2, 5, 6], [1, 6, 6, 6], [1, 7, 7, 7]]
y_data = [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 1, 0], [0, 1, 0], [0, 1, 0],[1, 0, 0], [1, 0, 0]]
#定义占位符
x = tf.placeholder(tf.float32,shape=[None,4])
y = tf.placeholder(tf.int64,shape=[None,3])
#初始化权重和偏执
w = tf.Variable(tf.random_normal([4,3]),name="w")
b = tf.Variable(tf.random_normal([3]),name="b")
#预测模型
logits = tf.matmul(x,w)+b
hypothesis = tf.nn.softmax(logits)
#定义代价
cost = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y)
#优化器
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
#计算准确率
predict = tf.argmax(hypothesis,1)
correct_pre = tf.equal(predict,tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pre,tf.float32))
#创建会话
sess = tf.Session()
sess.run(tf.global_variables_initializer())
#开始迭代
for step in range(5000):
cost_val,_ = sess.run([cost,train],feed_dict={x:x_data,y:y_data})
if step %500 ==0:
print(step,cost_val)
#打印精确率
print("Accuracy:",sess.run(accuracy,feed_dict={x:x_data,y:y_data}))
#y预测
print(sess.run(predict,feed_dict={x:[[4,1,2,3], [3,2,4,5]]}))
#关闭会话
sess.close()