tensorflow基础

匿名 (未验证) 提交于 2019-12-02 23:48:02

<h1>tensorflow基础代码实现</h1>
1.导入相应的包
Import tensorflow as tf
from tensorsorflow.examples.tutorials.mnist as input_data tutorials(教程)
Import matplotlib.pyplot as plt
Import numpy as np
Import pandas as pd

2.定义各种常量,及设置随机种子
Learning_rate = 0.1
tf.set_random_seed(777)
n_classses = 10

3.定义数据集
此时的数据可能是自己定义,也可能是从文件中读取(例如:mnist手写体识别)
导入的情况可能分一下几类:
mnist = input_data.read_data_sets(‘MNIST_data’,one_hot=True)
data = np.loadtxt(‘data.csv’,delimiter=’,’)
data = pd.read_csv(data.csv')

如果是多分类问题,必须给y值变为独热编码
Y_one_hot = tf.one_hot(Y, nb_classes)
Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes])

4.定义占位符
首先,tensorflow通过计算流图的方式,帮你优化整个session需要执行的代码。而placeholder()只是在模型中的占位,此时并没有把要输入的数据传入模型,它只会分配必要的内存。等建立session,在会话中,运行模型的时候通过feed_dict()函数向占位符喂入数据。
M―样本数 ,n―特征数,n_classse―类别数
X= tf.placeholder("float", shape=[None, n]) None是为了预测数据是可以传入任意条数据
Y = tf.placeholder(tf.float32, [None,n_classes ])


5.定义权重和偏置,模型和前向传播

w1 = tf.Veriable(tf.random_normal([特征数,单元数]),name=’weight1’)
b1 = tf.Veriable(tf.random_normal([单元数]),name=’bias1’)
(此时b不写第一个维度是为了a1=x*w+b时利用广播的机制,进行初始化,使之加上相同的b,如果写上第一个维度,就会随机产生不同的数据,不能够达到效果)
回归模型:hypothesis = tf.matmul(X, W) + b
分类模型:hypothesis = tf.sigmoid(tf.matmul(X, W) + b)
如果是多分类需要使用softmax处理
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)
如果是前向传播:
W1 = tf.Variable(tf.random_normal([2, 3]), name='weight1')
b1 = tf.Variable(tf.random_normal([3]), name='bias1')
a1 = tf.sigmoid(tf.matmul(X, W1) + b1)

W2 = tf.Variable(tf.random_normal([3, 1]), name='weight2')
b2 = tf.Variable(tf.random_normal([1]), name='bias2')
a2 = tf.sigmoid(tf.matmul(a1, W2) + b2)

6.代价或者损失函数
回归代价:cost = tf.reduce_mean(tf.square(hypothesis - Y))
分类代价:
二分类:cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))
多分类:cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
(axis=0代表往跨行,而axis=1代表跨列)

cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=hypothesis,labels=Y_one_hot))
此函数计算过程一共分为两步:1.将logits转换成概率;2.计算交叉熵损失 可以代替上文多分类问题的softmax和cost代码


7.梯度下降优化器
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

手写反向传播,更新参数
#BP反向传播

#第2层
dz2 = a2 - Y
dW2 = tf.matmul(tf.transpose(a1), dz2) / tf.cast(tf.shape(a1)[0], dtype=tf.float32)
db2 = tf.reduce_mean(dz2)

#第1层
da1 = tf.matmul(dz2, tf.transpose(W2))
dz1 = da1 * a1 * (1 - a1)
dW1 = tf.matmul(tf.transpose(X), dz1) / tf.cast(tf.shape(X)[0], dtype=tf.float32)
db1 = tf.reduce_mean(dz1, axis=0)

# 参数更新
update = [
tf.assign(W2, W2 - learning_rate * dW2),
tf.assign(b2, b2 - learning_rate * db2),
tf.assign(W1, W1 - learning_rate * dW1),
tf.assign(b1, b1 - learning_rate * db1)
]

8.分类准确率
predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))

多分类准确率:
prediction = tf.argmax(hypothesis, 1)
correct_prediction = tf.equal(prediction, tf.argmax(y_data, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


9.创建会话,初始化全局变量
sess = tf.Session()
sess.run(tf.global_variables_initializer())

10.迭代训练
for step in range(迭代次数):
cost_val, acc, _ = sess.run([cost, accuracy, train], feed_dict={X: x_data, Y: y_data})
if step % 500 == 0: # 每500次输出一次代价值,显示代价值收敛情况
print(step, cost_val, acc)

11.输出预测结果,准确率等
h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict={X: x_data, Y: y_data})
print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)

12.验证或预测
h1, p1 = sess.run([hypothesis, predicted], feed_dict={X: [[1, 1]]})
print(h1, p1)
h2, p2 = sess.run([hypothesis, predicted], feed_dict={X: [[4,1], [3,100]]})
print(h2, p2)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!