Getting Started With TensorFlow

 

Tensors

tensorflow中核心数据单元是tensor张量。张量是一组任意维度的值。张量的rank是维度的数量。

  • 3 # a rank 0 tensor; a scalar with shape []
  • [1., 2., 3.] # a rank 1 tensor; a vector with shape [3]
  • [[1., 2., 3.], [4., 5., 6.]] # a rank 2 tensor; a matrix with shape [2, 3]
  • [[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3]

TensorFlow Core tutorial

Importing TensorFlow
import tensorflow as tf

import tensorflow as tf

The Computation Graph

tensorflow核心程序包括两部分:
1.构建计算图
2.运行计算图
计算图是由一系列tensorflow操作组成,这些操作就是图中的节点。构建一个简单的计算图,每个节点的输入是零个或多个张量,输出是生成的一个张量。节点的类型之一是常量。常量不需要输入,输出是内部存储值。

node1=tf.constant(3.0,dtype=tf.float32)  
node2=tf.constant(4.0)
print(node1,node2)

 

 Tensor("Const_4:0", shape=(), dtype=float32) Tensor("Const_5:0", shape=(), dtype=float32)
 

注:打印节点没有输出3.0和4.0,是因为目前它们只是节点,在实际评估节点时,需要使用session运行图,才能打印出3.0和4.0。session封装了tensorflow运行时的控制和状态。
创建一个Session对象,然后调用run方法,运行计算图来评估node1和node2。

sess=tf.Session()
print(sess.run([node1,node2]))

[3.0, 4.0]

更加复杂的计算,例如将两个常量节点相加

node3=tf.add(node1,node2)
print(node3)
print(sess.run(node3))

Tensor("Add_2:0", shape=(), dtype=float32)

7.0

tensorflow提供了计算图的可视化应用tensorBoard

avatar
除此之外图可以接受外部输入,即占位符,占位符是允许在之后再赋值。

a=tf.placeholder(tf.float32)
b=tf.placeholder(tf.float32)
adder_node=a+b 

类似函数,定义了两个输入参数a和b,以及它们之间的操作,可以通过多次输入评估这个图,通过使用feed_dict:

print(sess.run(adder_node,{a:3,b:4.5}))

 

7.5

 

 

再复杂一些

add_and_triple=adder_node*3
print(sess.run(add_and_triple,{a:3,b:4.5}))

 

22.5
 


机器学习中需要能够通过修改图,达到相同输入得到不同输出,变量就可以在图中加入可训练参数,变量由类型和初始值构成。

W=tf.Variable([.3],dtype=tf.float32)
b=tf.Variable([-.3],dtype=tf.float32)
x=tf.placeholder(tf.float32)
linear_model=W*x+b

常量实在调用tf.constant时被初始化,值不会再改变。而变量在调用tf.Variable是没有被初始化,需要调用具体操作:

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

 

 init是tensorflow子图的一个句柄,定义了初始化所有全局变量,直到调用sess.run,变量才被初始化。
print(sess.run(linear_model,{x:[1,2,3,4]}))

[ 0. 0.30000001 0.60000002 0.90000004]

 

为了评估模型好坏,需要损失函数。
损失函数用于衡量当前模型与提供的结果的差距。使用线性回归的标准损失函数模型。

y=tf.placeholder(tf.float32)
squared_deltas=tf.square(linear_model-y)
loss=tf.reduce_sum(squared_deltas)
print(sess.run(loss,{x:[1,2,3,4],y:[0,-1,-2,-3]}))

23.66

 通过修改W和b,来改进。
fixW=tf.assign(W,[-1.])
fixb=tf.assign(b,[1.])
sess.run([fixW,fixb])
print(sess.run(loss,{x:[1,2,3,4],y:[0,-1,-2,-3]}))

0.0

 

tf.train API

tensorflow提供optimizers慢慢地改变变量来使损失函数最小化。最简单的优化是梯度下降。

optimizer=tf.train.GradientDescentOptimizer(0.01)
train=optimizer.minimize(loss)
sess.run(init)
for i in range(1000):
    sess.run(train,{x:[1,2,3,4],y:[0,-1,-2,-3]})
print(sess.run([W,b]))

[array([-0.9999969], dtype=float32), array([ 0.99999082], dtype=float32)]

 
完整程序
import tensorflow as tf

# Model parameters
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W*x + b
y = tf.placeholder(tf.float32)

# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
    sess.run(train, {x: x_train, y: y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

 

W: [-0.9999969] b: [ 0.99999082] loss: 5.69997e-11
 

 

tf.estimator

tf.estimator是tensorflow的高级库,简化机器学习,主要包括:

  • 循环训练的运行
  • 循环评估的运行
  • 管理数据集
基本使用

可以看出更加简洁:

import tensorflow as tf
import numpy as np
#特征的声明列表
feature_columns=[tf.feature_column.numeric_column("x",shape=[1])]
#estimator是调用训练和评估的前端。有许多与定义类型例如线性回归,线性分类,神经网络分类和回归。
estimator=tf.estimator.LinearRegressor(feature_columns=feature_columns)
x_train = np.array([1., 2., 3., 4.])
y_train = np.array([0., -1., -2., -3.])
x_eval = np.array([2., 5., 8., 1.])
y_eval = np.array([-1.01, -4.1, -7, 0.])
input_fn=tf.estimator.inputs.numpy_input_fn({"x":x_train},y_train,batch_size=4,num_epochs=None,shuffle=True)
train_input_fn=tf.estimator.inputs.numpy_input_fn({"x":x_train},y_train,batch_size=4,num_epochs=1000,shuffle=False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn({"x": x_eval}, y_eval, batch_size=4, num_epochs=1000, shuffle=False)
#调用1000次训练
estimator.train(input_fn=input_fn,steps=1000)
#评估模型好坏
train_metrics=estimator.evaluate(input_fn=train_input_fn)
eval_metrics=estimator.evaluate(input_fn=eval_input_fn)
print("train metrics: %r"% train_metrics)
print("eval metrics: %r"% eval_metrics)

 

train metrics: {'average_loss': 2.5272706e-07, 'loss': 1.0109082e-06, 'global_step': 1000}
eval metrics: {'average_loss': 0.0025713388, 'loss': 0.010285355, 'global_step': 1000}

转载于:https://www.cnblogs.com/lucysun/p/8056627.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值