《Tensorflow 从基础到实战》01 安装与基础操作、手写数据集、逻辑回归

书山有路勤为径,学海无涯苦作舟

凡我不能创造的,我就不能理解

1. 安装与简介

1.1 安装

在anaconda的promat

pip install tensorflow

不能安装的话,外部安装网址

https://www.lfd.uci.edu/~gohlke/pythonlibs/#xgboost

该网址可以安装tensorflow和其他库,tensorflow必须是64位

在这里插入图片描述
下好后cd进入该文件的位置,pip安装

pip install 文件名

版本号

tensorflow.version

1.2TensorFlow是什么

Tensorflow是一个Google开发的第二代机器学习系统,克服了第一代系统DistBelief仅能开发神经网络算法、难以配置、依赖Google内部硬件等局限性,应用更加广泛,并且提高了灵活性和可移植性,速度和扩展性也有了大幅提高。字面上理解,TensorFlow就是以张量(Tensor)在计算图(Graph)上流动〈Flow)的方式的实现和执行机器学习算法的框架。具有以下特点:

  • 灵活性。TensorFlow不是一个严格的"神经网络"库。只要可以将计算表示成数据流图,就可以使用TensorFlow,比如科学计算中的偏微分求解等。(实际上其官网的介绍中对TF的定位就是基于数据流图的科学计算库,而非仅仅是机器学习库)
  • 可移植性。同一份代码几乎不经过修改既可以部署到有任意数量CPU、GPU或TPU(Tensor Processing Unit,Google专门为机器学习开发的处理器)的PC、服务器或移动设备上。
  • 自动求微分。同Theano一样,TensorFlow也支持自动求微分,用户不需要再通过反向传播求解梯度。
  • 多语言支持。TensorFlow官方支持Python、C++、Go和Java接口,用户可以在硬件配置较好的机器中用Python进行实验,在资源较紧张或需要低延迟的环境中用C++进行部署。
  • 性能。虽然TensorFlow最开始发布时仅支持单机,在性能评测上并不出色,但是凭借Google强大的开发实力,TensorFlow性能已经追上了其他框架

2. 基础操作

2.1 创建常量与 变量

在TensorFlow中,使用tf.constant来创建常量。

# 创建1*2矩阵常量
c1 = tf.constant([[1., 1.]]) 
# 创建2*1矩阵常量
c2 = tf.constant([[2.],[2.]]) 

在TensorFlow中,使用tf. Variable来创建变量。变量(Variable )是特殊的张量,它的值可以是一个任何类型和形状的张量。TensorFlow必须要定义成一个变量,它才是一个真正的变量。

# 创建一个0阶变量并初始化为0
state = tf.Variable(0, name='counter')

Python中创建变量再赋值只要a = 3

在tensorflow中的所有变量的格式必须是tensor的格式,需要先指定一个标准格式

指定变量,指定操作,但是还没有执行,还没有初始化
在这里插入图片描述

先打开一个session,开辟一个可计算区域,要执行什么,必须要在session的可计算区域中实际的run一下。

定义了全局变量的初始化方法也需要实际的run一下

a = 3 
# 创建一个变量
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]]) 

y = tf.matmul(w, x)  #操作也是一个tensorflow格式


#全局变量初始化
init_op = tf.global_variables_initializer() 
with tf.Session() as sess:
    sess.run(init_op) # run初始化
    print (y.eval())

[[ 2.]]

tensorflow很多操作跟numpy有些类似的

  • tf.zeros([3, 4], int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

  • tf.zeros_like(tensor) ==> [[0, 0, 0], [0, 0, 0]]

  • tf.ones([2, 3], int32) ==> [[1, 1, 1], [1, 1, 1]]

  • tf.ones_like(tensor) ==> [[1, 1, 1], [1, 1, 1]]

  • tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]

  • tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.] [-1. -1. -1.]]

  • tf.linspace(10.0, 12.0, 3, name=“linspace”) => [ 10.0 11.0 12.0]

  • tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]

#生成的值服从具有指定平均值和标准偏差的正态分布
norm = tf.random_normal([2, 3], mean=-1, stddev=4)

# 洗牌
c = tf.constant([[1, 2], [3, 4], [5, 6]])
shuff = tf.random_shuffle(c)

# 每一次执行结果都会不同
sess = tf.Session()
print (sess.run(norm))
print (sess.run(shuff))

[[-5.58110332 0.84881377 7.51961231]
[ 3.27404118 -7.22483826 7.70631599]]
[[5 6]
[1 2]
[3 4]]

在session中run才能得到值

tensor每次加1操作,assign是赋值操作,用session运行全局变量的初始化,再执行更新操作

state = tf.Variable(0)
new_value = tf.add(state, tf.constant(1))
update = tf.assign(state, new_value) # 更新: new_value变量加载到state中 state当前变量即为new_value

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer()) # Tensorflow中需要初始化所有变量才能激活
    print(sess.run(state))  
    # 三次循环更新变量  
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

0
1
2
3

案例:

import tensorflow as tf

# 定义变量
a = tf.constant([5, 3], name='input_a')

# 计算
b = tf.reduce_prod(a, name='prod_b')
c = tf.reduce_sum(a, name='sum_c')
d = tf.add(b, c, name='add_d')

# Session
with tf.Session() as sess:
    print('a:', sess.run(a))
    print('b:', sess.run(b))
    print('c:', sess.run(c))
    print('d:', sess.run(d))

节点a接收了一个tensor,该tensor从节点a流出后,分别流向了节点b和c,节点b执行的是prod操作5*3,节点c执行的是sum操作5+3。当tensor从节点b流出时变成了15,从节点c流出时变成了8。此时,2个tensor又同时流入节点d,接受的是add操作15+8,最后从节点d流出的tensor就是23。

tensor是在graph中流动的过程如下图所示。当我们把图中的一个节点传递给Session.un( )的时候,实际上就是在对TensorFlow说’Hi,,我想要这个node的输出,请帮我运行相应的操作来得到它,谢谢!”"这时,Session会找到这个node所依赖的所有操作,然后按照从前到后的顺序依次进行计算,直到得出你所需要的结果。
在这里插入图片描述
运算操作

a = tf.constant(5.0)
b = tf.constant(10.0)

x = tf.add(a, b, name="add")
y = tf.div(a, b, name="divide")

with tf.Session() as sess:
    print("a =", sess.run(a))
    print("b =", sess.run(b))
    print("a + b =", sess.run(x))
    print("a/b =", sess.run(y))

a = 5.0
b = 10.0
a + b = 15.0
a/b = 0.5

2.2 numpy转换tensor运算

将Numpy转为tensor

import numpy as np
a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)
with tf.Session() as sess:
     print(sess.run(ta))

2.3 placeholder

placeholder称为传入值或占位符。上述示例在计算图中引入了张量,以常量或变量的形式存储,Tensorflow中还提供了另外一种机制,即先定义占位符,等到真正执行的时候再用具体值去填充或更新占位符的值。
TensorFlow使用t.placeholder()创建占位符,开始先hold住变量,之后会从外界传入进来,把placeholder值填充进去,Session.run的feed_dict为参数填充值。

placeholder,指定一个位置,但是里面是什么值还不确定,里面需要写一个数据类型。
在进行迭代的时候,每次是数据格式是一样的,但是每次的操作后的值是在改变的,可以先固定一个数据类型和shape,再传数据。边执行边赋值。
(类似于挖了一个坑,在里面埋下一个大小固定的不同的萝卜)

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
    print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))

[array([ 14.], dtype=float32)]

2.4激励函数

在这里插入图片描述
激励函数相当于一个过滤器或激励器,它把特有的信息或特征激活,常见的激活函数包括sofiplus、sigmoid、relu、 sofimax、 elu、tanh等。

  • 对于隐藏层,我们可以使用relu、tanh、 softplus等非线性关系;
  • 对于分类问题,我们可以使用sigmoid (值越小越接近于0,值越大越接近于1 ) 、softmax函数,对每个类求概率,最后以最大的概率作为结果;
  • 对于回归问题,使用线性函数 ( linear function )来实验。

案例:

import tensorflow as tf

a = tf.constant([-1.0, 2.0])

# 激励函数
with tf.Session() as sess:
    b = tf.nn.relu(a)
    print(sess.run(b))
    
    c = tf.sigmoid(a)
    print(sess.run(c))

[0. 2.]
[0.26894143 0.880797 ]

3.实现线性回归算法

在数据中找到最好拟合数据的线

3.1 生成样本

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

# 随机生成1000个点,围绕在y=0.1x+0.3的直线周围
num_points = 1000
vectors_set = []
for i in range(num_points):
    x1 = np.random.normal(0.0, 0.55)
    y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
    vectors_set.append([x1, y1])

# 生成一些样本
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]

plt.scatter(x_data,y_data,c='r')
plt.show()

在这里插入图片描述

3.2 训练模型

# 生成1维的W矩阵,取值是[-1,1]之间的随机数
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='W')
# 生成1维的b矩阵,初始值是0
b = tf.Variable(tf.zeros([1]), name='b')
# 经过计算得出预估值y
y = W * x_data + b

# 以预估值y和实际值y_data之间的均方误差作为损失
loss = tf.reduce_mean(tf.square(y - y_data), name='loss')
# 采用梯度下降法来优化参数
optimizer = tf.train.GradientDescentOptimizer(0.5)
# 训练的过程就是最小化这个误差值
train = optimizer.minimize(loss, name='train')

sess = tf.Session()

init = tf.global_variables_initializer()
sess.run(init)

# 初始化的W和b是多少
print ("W =", sess.run(W), "b =", sess.run(b), "loss =", sess.run(loss))
# 执行20次训练
for step in range(20):
    sess.run(train)
    # 输出训练好的W和b
    print ("W =", sess.run(W), "b =", sess.run(b), "loss =", sess.run(loss))
#writer = tf.train.SummaryWriter("./tmp", sess.graph)

W = [ 0.96539688] b = [ 0.] loss = 0.297884
W = [ 0.71998411] b = [ 0.28193575] loss = 0.112606
W = [ 0.54009342] b = [ 0.28695393] loss = 0.0572231
W = [ 0.41235447] b = [ 0.29063231] loss = 0.0292957
W = [ 0.32164571] b = [ 0.2932443] loss = 0.0152131
W = [ 0.25723246] b = [ 0.29509908] loss = 0.00811188
W = [ 0.21149193] b = [ 0.29641619] loss = 0.00453103
W = [ 0.17901111] b = [ 0.29735151] loss = 0.00272536
W = [ 0.15594614] b = [ 0.29801565] loss = 0.00181483
W = [ 0.13956745] b = [ 0.29848731] loss = 0.0013557
W = [ 0.12793678] b = [ 0.29882219] loss = 0.00112418
W = [ 0.11967772] b = [ 0.29906002] loss = 0.00100743
W = [ 0.11381286] b = [ 0.29922891] loss = 0.000948558
W = [ 0.10964818] b = [ 0.29934883] loss = 0.000918872
W = [ 0.10669079] b = [ 0.29943398] loss = 0.000903903
W = [ 0.10459071] b = [ 0.29949448] loss = 0.000896354
W = [ 0.10309943] b = [ 0.29953739] loss = 0.000892548
W = [ 0.10204045] b = [ 0.29956791] loss = 0.000890629
W = [ 0.10128847] b = [ 0.29958954] loss = 0.000889661
W = [ 0.10075447] b = [ 0.29960492] loss = 0.000889173
W = [ 0.10037527] b = [ 0.29961586] loss = 0.000888927

plt.scatter(x_data,y_data,c='r')
plt.plot(x_data,sess.run(W)*x_data+sess.run(b))
plt.show()

在这里插入图片描述

4.Mnist 手写识别数据集

tensorflow自带的数据集

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

print ("大吉大利 今晚吃鸡")

大吉大利 今晚吃鸡

下载数据集

print ("下载中~别催了")
mnist = input_data.read_data_sets('data/', one_hot=True)
print
print (" 类型是 %s" % (type(mnist)))
print (" 训练数据有 %d" % (mnist.train.num_examples))
print (" 测试数据有 %d" % (mnist.test.num_examples))
trainimg   = mnist.train.images
trainlabel = mnist.train.labels
testimg    = mnist.test.images
testlabel  = mnist.test.labels
# 28 * 28 * 1
print (" 数据类型 is %s"    % (type(trainimg)))
print (" 标签类型 %s"  % (type(trainlabel)))
print (" 训练集的shape %s"   % (trainimg.shape,))
print (" 训练集的标签的shape %s" % (trainlabel.shape,))
print (" 测试集的shape' is %s"    % (testimg.shape,))
print (" 测试集的标签的shape %s"  % (testlabel.shape,))

该数据集的label的定义为一个onehot的编码格式,在0-9的10个类别下,只有在当前数据集下是1,别的位置都是0。
在这里插入图片描述
做分类任务的时候,最终的结果都是对不同类别的概率。取得概率最高的那个类别。

# 看看庐山真面目
nsample = 5
randidx = np.random.randint(trainimg.shape[0], size=nsample)

for i in randidx:
    curr_img   = np.reshape(trainimg[i, :], (28, 28)) # 28 by 28 matrix 
    curr_label = np.argmax(trainlabel[i, :] ) # Label
    plt.matshow(curr_img, cmap=plt.get_cmap('gray'))
    print ("" + str(i) + "th 训练数据 " 
           + "标签是 " + str(curr_label))
    plt.show()

Batch

n. 一批; (食物、药物等)一批生产的量; 批;
v. 分批处理;
[其他] 复数:batches

取batch数据,在数据集中每次取得批量的数据进行训练

# Batch数据
print ("Batch Learning? ")
batch_size = 100
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
print ("Batch数据 %s" % (type(batch_xs)))
print ("Batch标签 %s" % (type(batch_ys)))
print ("Batch数据的shape %s" % (batch_xs.shape,))
print ("Batch标签的shape %s" % (batch_ys.shape,))

5. Tensorflow-逻辑回归分类任务

导入数据

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

mnist = input_data.read_data_sets('data/', one_hot=True)

Extracting data/train-images-idx3-ubyte.gz
Extracting data/train-labels-idx1-ubyte.gz
Extracting data/t10k-images-idx3-ubyte.gz
Extracting data/t10k-labels-idx1-ubyte.gz

设置参数,设置类别个数,指定输入格式,指定迭代次数,指定每次迭代个数的batch个数

numClasses = 10
inputSize = 784  
trainingIterations = 50000
batchSize = 64
	

placeholder指定x和y的大小,None表示指定任意的数据格式

X = tf.placeholder(tf.float32, shape = [None, inputSize])
y = tf.placeholder(tf.float32, shape = [None, numClasses])

参数初始化,W1代表权重参数矩阵,为【784*10】的矩阵,B1位【10,】的矩阵
在这里插入图片描述

W1 = tf.Variable(tf.random_normal([inputSize, numClasses], stddev=0.1))
B1 = tf.Variable(tf.constant(0.1), [numClasses])

构造模型

构建逻辑回归的预测值y_pred

判断训练的准确率,用位置是否一样来判断预测对不对

y_pred = tf.nn.softmax(tf.matmul(X, W1) + B1)

loss = tf.reduce_mean(tf.square(y - y_pred))
opt = tf.train.GradientDescentOptimizer(learning_rate = .05).minimize(loss)

correct_prediction = tf.equal(tf.argmax(y_pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

迭代计算

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
for i in range(trainingIterations):
    batch = mnist.train.next_batch(batchSize)
    batchInput = batch[0]
    batchLabels = batch[1]
    _, trainingLoss = sess.run([opt, loss], feed_dict={X: batchInput, y: batchLabels})
    if i%1000 == 0:
        train_accuracy = accuracy.eval(session=sess, feed_dict={X: batchInput, y: batchLabels})
        print ("step %d, training accuracy %g"%(i, train_accuracy))

step 0, training accuracy 0.09375
step 1000, training accuracy 0.53125
step 2000, training accuracy 0.8125
step 3000, training accuracy 0.734375
step 4000, training accuracy 0.828125
step 5000, training accuracy 0.890625
step 6000, training accuracy 0.8125
step 7000, training accuracy 0.84375
step 8000, training accuracy 0.84375
step 9000, training accuracy 0.75
step 10000, training accuracy 0.75
step 11000, training accuracy 0.90625
step 12000, training accuracy 0.84375
step 13000, training accuracy 0.875
step 14000, training accuracy 0.921875
step 15000, training accuracy 0.859375
step 16000, training accuracy 0.84375
step 17000, training accuracy 0.90625
step 18000, training accuracy 0.90625
step 19000, training accuracy 0.8125
step 20000, training accuracy 0.921875
step 21000, training accuracy 0.890625
step 22000, training accuracy 0.875
step 23000, training accuracy 0.84375
step 24000, training accuracy 0.859375
step 25000, training accuracy 0.890625
step 26000, training accuracy 0.90625
step 27000, training accuracy 0.9375
step 28000, training accuracy 0.859375
step 29000, training accuracy 0.921875
step 30000, training accuracy 0.890625
step 31000, training accuracy 0.921875
step 32000, training accuracy 0.890625
step 33000, training accuracy 0.953125
step 34000, training accuracy 0.890625
step 35000, training accuracy 0.9375
step 36000, training accuracy 0.828125
step 37000, training accuracy 0.921875
step 38000, training accuracy 0.953125
step 39000, training accuracy 0.921875
step 40000, training accuracy 0.890625
step 41000, training accuracy 0.875
step 42000, training accuracy 0.8125
step 43000, training accuracy 0.953125
step 44000, training accuracy 0.953125
step 45000, training accuracy 0.875
step 46000, training accuracy 0.859375
step 47000, training accuracy 0.9375
step 48000, training accuracy 0.921875
step 49000, training accuracy 0.921875

测试结果

batch = mnist.test.next_batch(batchSize)
testAccuracy = sess.run(accuracy, feed_dict={X: batch[0], y: batch[1]})
print ("test accuracy %g"%(testAccuracy))

test accuracy 0.9375

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

驭风少年君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值