Tensorflow 初步

来源:互联网 发布:淘宝女装店铺改卖男装 编辑:程序博客网 时间:2024/06/06 03:49

Tensorflow 一直零散的学习,立个博客作为笔记:

Tensorflow是一个编程系统,使用图(graphs)来表示计算任务,图(graphs)中的节点称之为op(operation),一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。Tensor 看作是一个 n 维的数组或列表。图必须在会话(Session)里被启动。
TensorFlow用张量这种数据结构来表示所有的数据。用一阶张量来表示向量,如:v = [1.2, 2.3, 3.5] ,如二阶张量表示矩阵,如:m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],可以看成是方括号嵌套的层数。

定义会话,运行会话的样例

import tensorflow as tf#定义一个常量的opm1 = tf.constant([[3,2]])    # 定义一行两列#定义一个常量的opm2 = tf.constant([[2],[3]])  # 定义两行一列#定义一个矩阵运算的opproduct = tf.matmul(m1, m2)#定义一个会话,启动默认图sess = tf.Session()#触发三个opresult = sess.run(product)print resultsess.close()#方式二with tf.Session()  as sess:    result = sess.run(product)    print result

变量的使用

shift+tab 可以快速查找函数作用

x = tf.Variable([1, 2]);a = tf.constant([3,3]);sub = tf.subtract(x,a)     #元素相减init = tf.global_variables_initializer();  #注意初始化变量with tf.Session() as sess:    sess.run(init)    result = sess.run(sub)print result

使用for 复制变量

x = tf.Variable(0);new_x = tf.add(x,1);updata  =tf.assign(x, new_x)   赋值opinit = tf.global_variables_initializer(); #初始化为0with tf.Session() as sess:    sess.run(init)    print sess.run(x)    for _ in range(5):        result = sess.run(updata)        print result

Fetch 和 Feed用法

fetch 可以同时运行多个op

#fetchinput1 = tf.constant(1.2)input2 = tf.constant(2.2)input3 = tf.constant(3.2)add = tf.add(input1, input2)mul = tf.multiply(add, input3)with tf.Session() as sess:    print sess.run([mul, add])

feed 使用字典的形式将数据传入

#feedinput1  = tf.placeholder(tf.float32)input2  = tf.placeholder(tf.float32)out = tf.multiply(input1,input2)with tf.Session() as sess:    result =  sess.run( out, feed_dict= {input1:[7.], input2:[5.]} )    print result

梯度下降法 实现直线的拟合

import tensorflow as tfimport numpy as np#生成随机点x_data = np.random.rand(100)     #产生随机点y_data = x_data * 0.1 +0.2#构造一个线性模型b = tf.Variable(0.)k = tf.Variable(0.)y = k*x_data + b# 定义lossloss = tf.reduce_mean(tf.square(y_data-y))#定义优化方法optimizar = tf.train.GradientDescentOptimizer(0.2)#最小化losstrain = optimizar.minimize(loss)#变量初始化init = tf.global_variables_initializer()with tf.Session() as sess:    sess.run(init)    for step in range(201):        sess.run(train)        if step%20 == 0:            print sess.run([k, b])[0.055063572, 0.10062776][0.10450891, 0.19752166][0.1027341, 0.19849722][0.10165788, 0.19908877][0.10100529, 0.19944745][0.10060959, 0.19966495][0.10036964, 0.19979683][0.10022413, 0.1998768][0.1001359, 0.1999253][0.10008241, 0.1999547][0.10004997, 0.19997254]
原创粉丝点击