【Tensorflow】Tensorflow实现简单模型

之前我们说了一下Tensorflow的基本内容,这次我们用它来实现一些简单模型。包括线性回归模型,logistic回归,最近邻分类。

首先理顺一下思维,无论是要做什么模型,必须要有的几个是:

输入值输出值实际值模型参数损失函数。

步骤一般是 inference、losstraining。

inference指的是构建好模型,使其能够完成预测的要求。

loss指的是确定好损失函数。

training指的是对模型进行拟合。

下面我们来用线性回归,logistic回归和KNN算法来说明一下一个简单模型如何在tf中构建。

线性回归

import tensorflow as tf
import numpy as np
# 简单的线性模型可以用y=x*w+b来表示

# 输入占位符,这个不是输入值,是拟合模型的时候代表了输入值
x=tf.placeholder('float')
# 这个不是输出值,是计算损失函数的时候用到的实际值
y=tf.placeholder('float')

# ----Inference
# 下面这两个就是模型的参数
# 权重参量
W=tf.Variable(np.random.randn(),name='weight')
# 偏移参量
b=tf.Variable(np.random.randn(),name='bias')
# tf里面任何操作都是一个op,不能简单得用*这些符号代替,例如下面这个是错的
#pred=x*W+b
# 下面这种表达就是两个op
pred=tf.add(tf.multiply(x,W),b)

# ----loss
loss=tf.reduce_sum(tf.pow(pred-y,2))
learning_rate=0.01
optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
init=tf.global_variables_initializer()

# ----training
with tf.Session() as sess:
    sess.run(init)
    train_x=np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])
    train_y=np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3])
    training_epochs=1000
    for epoch in range(training_epochs):
        for (x,y) in zip(train_x,train_y):
            sess.run(optimizer,feed_dict={x:x,y:y})

上面这些有一些没有提到的,比如说learning_rate,training_epochs这些参数。这些就是在inference,loss,training这三个过程中可能需要的参数,视情况而定。

另外,如果按照上面代码来运行,我们不知道模型的好坏,因为看不到模型的具体信息,因此需要下面的。

train_cost=sess.run(lost,feed_dict={x:train_x,y:trian_y})
print(train_cost)

如果嫌数字表示不好看出趋势,可以用matplotlib.pyplot来绘制相关图。

logistic回归

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
# 输入占位符,跟线性回归不一样,这个是tensor。不是一个值,所以要用tf.float32。mnist数据的shape是28*28=784
x=tf.placeholder(tf.float32,[None,784])
# 输出占位符,mnist的标签值是10个数字0-9
y=tf.placeholder(tf.float32,[None,10])
# 将784转化为10维,权重参量
W=tf.Variable(tf.zeros([784,10]))
# 偏移参量
b=tf.Variable(tf.zeros([10]))
# 这个不知道为什么不用tf.add,直接用+就可以了。
#pred=tf.nn.softmax(tf.add(tf.matmul(x,W),b)
pred=tf.nn.softmax(tf.matmul(x,W)+b)
# 交叉熵,reduce的意思是坍塌的意思,就是坍塌完之后进行计算。
cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
training_rate=0.01
optimizer=tf.train.GradientDescentOptimizer(training_rate).minimize(cost)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    training_epochs=1000
    batch_size=50
    mnist = input_data.read_data_sets('/tmp/data', one_hot=True)
    for epoch in range(training_epochs):
        total_batch=int(mnist.train.num_examples/batch_size)
        for batch in range(total_batch):
            batch_xs,batch_ys=mnist.train.next_batch(batch_size)
            # sess.run的时候可以用list来同时启动两个op
            _,c=sess.run([optimizer,cost],feed_dict={x:batch_xs,y:batch_ys}

这次跟线性回归除了模型不同之外还有训练数据的不同,线性回归模型我们使用的是自己创的数据集,而logistic回归用的是mnist数据集,这个是数字识别数据集。这点不同导致了,我们需要对输入输出占位符,模型参数,训练数据集进行修改。比如batch,是因为mnist的数据集过于大,因此需要分批训练拟合。

另外,关于logistic回归代码中,tf.matmul和tf.multiply的区别,交叉熵的意义。


KNN算法

import tensorflow as tf
import numpy as np
mnist=input_data.read_data_sets('/tmp/data/',one_hot=True)
Xtr,Ytr=mnist.train.next_batch(2000)
Xte,Yte=mnist.test.next_batch(200)
xtr=tf.placeholder('float',[None,784])
xte=tf.placeholder('float',[784])
distance=tf.reduce_sum(tf.abs(tf.add(xtr,tf.negative(xte))),reduction_indices=1)
pred=tf.arg_min(distance,0)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for i in range(len(Xte)):
        nn_index=sess.run(pred,feed_dict={xtr:Xtr,xte:Xte[i,:]})
        print('Test',i,'Prediction:',np.argmax(Ytr[nn_index]),'True class',np.argmax(Yte[i]))

上面的代码简单的说就是从数据集中取出一部分作训练集,一部分作测试集。对测试集中每一个跟训练集进行距离比较。取出距离最小的索引,这个索引对应预测的标签。

总结

从上面三个简单模型来看,如果要构建一个模型,一般的步骤就是:

  1. 构建能够得到预测结果的模型
  2. 如果需要的话,确定好损失函数
  3. 确定好训练模型的相关参数,进行训练
  4. 评价模型

以上代码均来自TensorFlow-Examples ,可以到此查看详细代码。

猜你喜欢

转载自blog.csdn.net/ximingren/article/details/79941618
今日推荐