深度学习第二周周考题-softmaxs的使用

  1. 题目描述:

请利用Tensorflow实现Softmax多分类。

  1. 题目要求:

① 导入必要的依赖库,同时设置随机种子。(5分)

② 定义数据集,其中:

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分)

③ 定义占位符。(5分)

④ 定义权重W和偏置b。(5分)

⑤ 定义预测模型,激活函数采用softmax。(5分)

⑥ 定义代价或损失函数。(5分)

⑦ 定义梯度下降优化器,学习率设置为0.01。(5分)

⑧ 准确率计算。(5分)

⑨ 创建会话,并全局变量初始化。(5分)

⑩ 开始迭代训练,循环迭代5000次,每500次打印输出一次损失值的收敛情况。(5分)

11 打印输出模型的准确率。(5分)

12 给定一组x:[[4,1,2,3], [3,2,4,5]],对该组数据进行测试,并打印输出测试结果。(5分)

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()

猜你喜欢

转载自blog.csdn.net/weixin_43696515/article/details/92617244