TensorFlow学习笔记一

这篇博客介绍了在Ubuntu14.04环境下使用pip安装TensorFlow的步骤,接着展示了TensorFlow的基本用法,包括计算图的构建、变量的使用、Fetch和Feed的操作。通过示例代码解释了如何创建常量、矩阵运算、变量赋值以及如何从计算图中获取和填充值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ubuntu14.04(python2.7)下pip安装

更新源包

$ sudo apt-get update

安装pip

$ sudo apt-get install python-pip

安装TensorFlow(cpu版本)

$ pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl

python入门例程

#创建两个常量(向量) a,b

a=[1.,2.]

b=[3.,1.]

#求和

c=a+b

#打印结果

print("HelloWorld")

print(c)

a=1
b=2
c=a+b
print(c)


计算图

tensorflow通过计算图的形式来表述计算模型,每一个计算为计算图上的节点,节点之间的边描述了计算之间的依赖关系。主要分为两步:构建和启动。构建图:添加节点 启动图:创建会话并在会话中执行计算。

#coding=utf-8
import tensorflow as tf
#构建图
#创建起始节点,constant()
a=tf.constant([[3., 3.]])
b=tf.constant([[1.],[1.]])
#创建新节点 matmul()
c=tf.matmul(a,b)
#启动图
#创建会话
sess=tf.Session()
#运行会话
res=sess.run(c)
#打印结果
print(res)
sess.close()


note:注意当在py文件中使用#注释中文时,需要先指定字符编码位数(#coding=utf-8),否则会报错,因为ASCII不包含中文字符。
Session对象在使用完毕后要关闭释放资源,也可以使用Session块语句自动释放,但要注意python的语法规则,即缩进。
with tf.Session() as sess
    res=sess.run(c)
    print(res)

变量

tf.Variable(),相比于常量tf.constant,变量的值是可变的。
import tensorflow as tf
#创建变量state
state=tf.Variable(0,name='counter')
#创建常量one
one=tf.constant(1)
#创建加法
new_value=tf.add(state,one)
update=tf.assign(state,new_value)
#初始化构造器op
init_op = tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(state))
    for _ in range(3):
        print(sess.run(update))


Fetch(取回计算值)

为了获取在计算当中的值,可以在run()函数中传入变量,可以是单个计算的变量,也可以是多个计算的变量组。
#coding=utf-8
import tensorflow as tf
#定义三个常量
i1=tf.constant(4)
i2=tf.constant(2)
i3=tf.constant(3)
#构造节点 加法、乘法
val1=tf.add(i2,i3)
val2=tf.mul(i1,val1)
#启动图
with tf.Session() as sess:
    res=sess.run([val2,val1])
    print(res)

在run()中指定要返回的值的类型,这样res变量会按照指定的格式储存。如果不指定的话,run只会返回最后一次计算的结果。

Feed(填充计算值)

在定义变量时可以不赋值,而是在run()执行计算时赋值。
import tensorflow as tf
#声明三个变量
input1 = tf.placeholder(tf.types.float32)
input2 = tf.placeholder(tf.types.float32)
output = tf.mul(input1, input2)
with tf.Session() as sess:
    #在run()中填充变量值
    print sess.run([output], feed_dict={input1:[7.], input2:[2.]})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值