zoukankan      html  css  js  c++  java
  • Tensorflow-基础使用

    Tensorflow基本概念

    • 使用图(graphs)来表示计算任务
    • 在被称之为会话(Session)的上下文(context)中执行图
    • 使用tensor表示数据
    • 通过变量(Variable)维护状态
    • 使用feed和fetch可以为任意的操作赋值或者从其中获取数据

    Tensorflow是一个编程系统,使用图(graphs)来表示计算任务,图(graphs)中的节点称之为op
    (operation),一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。Tensor 看作是
    一个 n 维的数组或列表。图必须在会话(Session)里被启动。

    Tensorflow结构

     

     创建图,启动图

    #2-1 创建图,启动图
    #创建一个常量op
    m1=tf.constant([[3,3]])
    #创建一个常量op
    m2=tf.constant([[2],[3]])
    #创建一个矩阵乘法op
    product=tf.matmul(m1,m2)
    print(product)
    
    with tf.compat.v1.Session() as sess:
    
        # run(product)触发了图中的3个op
        result = sess.run(product)
        print(result)

    结果为:

     

     变量

    #2-2变量
    #创建一个变量初始化0
    state=tf.Variable(0,name='counter')
    #创建op,作用是使state加1
    new_value=tf.add(state,1)
    #赋值op
    update=tf.compat.v1.assign(state,new_value)
    
    with tf.compat.v1.Session() as sess:
        #变量初始化
        sess.run(tf.compat.v1.global_variables_initializer())
        print(sess.run(state))
        for _ in range(5):
            sess.run(update)
            print(sess.run(state))

    输出为:

     

     Fetch and Feed

    #2-3Fetch and Feed
    #Fetch
    input1=tf.constant(3.0)
    input2=tf.constant(2.0)
    input3=tf.constant(5.0)
    
    add=tf.add(input2,input3)
    mul=tf.multiply(input1,add)
    
    with tf.compat.v1.Session() as sess:
        result=sess.run([mul,add])
        print(result)
    
    #Feed
    #创建占位符
    input1=tf.compat.v1.placeholder(tf.float32)
    input2=tf.compat.v1.placeholder(tf.float32)
    output=tf.multiply(input1,input2)
    
    with tf.compat.v1.Session() as sess:
        #feed的数据以字典传入
        print(sess.run(output,feed_dict={input1:[7.],input2:[2.]}))

    输出为:

     

     线性模型

    import numpy as np
    
    #使用np生成100个随机点
    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
    
    #二次代价函数
    loss=tf.reduce_mean(tf.square(y_data-y))
    #定义一个梯度下降法来进行训练的优化器
    optimizer=tf.compat.v1.train.GradientDescentOptimizer(0.2)
    
    #最小化代价函数
    train=optimizer.minimize(loss)
    
    #对变量进行初始化
    init=tf.compat.v1.global_variables_initializer()
    
    with tf.compat.v1.Session() as sess:
        sess.run(init)
        for step in range(201):
            sess.run(train)
            if step%20==0:
                print(step,sess.run([k,b]))

    输出为:

     

  • 相关阅读:
    GeoServer与Spring MVC
    GeoServer二次开发1 hello Geoserver
    servlet的生命周期
    springboot打包出错,没有主清单
    空间数据库管理
    Gone with the wind
    谎言中的民众
    还是有些怀念这里啊
    MSN Protcol 学习笔记
    祝我的老师教师节快乐!
  • 原文地址:https://www.cnblogs.com/xiaofengzai/p/14328002.html
Copyright © 2011-2022 走看看