zoukankan      html  css  js  c++  java
  • TensorFlow入门极简教程(一)

    一、 TensorFlow 模型   

    TensorFlow的命名来源于本身的运行原理。tensor(张量)表示的是N维数组,Flow(流)意味着基于数据流图的计算。

        Tensorflow是张量从图像的一端流动到另一端的计算(编程模型)。

    二、 模型的运行机制
        TensorFlow的运行机制属于“定义”与“运行”相分离的。从操作来看分两层:模型构建和模型运行

        模型构建所需概念如下:

    三、 实例

       1. session的作用,以及使用例子

    # -*- coding: utf-8 -*-
    # !/usr/bin/env python
    # @Time    : 2019/5/15 11:32
    # @Author  : xhh
    # @Desc    :  session的演示
    # @File    : tensor_tf4.py
    # @Software: PyCharm
     
    import tensorflow as tf
     
    hello = tf.constant('hello, tensorflow')  # 定义一个常量
    sess = tf.Session()  # 建立一个session
    print(sess.run(hello))  # 通过sess中的run函数来运行结果
    sess.close()  # 关闭session

    2. with session的使用
    with session是我们以后会经常用的,他沿用了python中的with用法,当程序结束之后会自动关闭session,二不需要在手动的close

    例:使用with session方法建立session,并在session中计算两个变量(3和4)的相加与相乘值

    import tensorflow as tf
     
    a = tf.constant(3)  # 定义常量3
    b = tf.constant(4)  # 定义常量4
    with tf.Session() as sess:   # 建立session
        print("相加: %i"%sess.run(a+b))
        print("相乘: %i"%sess.run(a*b))
    

    4. 保存/载入线性回归模型

    import tensorflow as tf
    import numpy as np
    import matplotlib.pyplot as plt
     
    plotdata = {"batchsize":[], "loss":[]}
     
    def moving_average(a, w=10):
        if len(a)<w:
            return a[:]
        return [val if idx < w else sum(a[(idx-w):idx])/w for idx, val in enumerate(a)]
     
    #  模拟数据
    train_X = np.linspace(-1, 1, 100)
    train_Y = 2*train_X + np.random.randn(*train_X.shape)*0.3  # 加入了噪声
     
    # 图形展示
    plt.plot(train_X,train_Y,'ro',label="original data") # label数据标签
    plt.legend()
    plt.show()
     
    tf.reset_default_graph()  # 重置会话
     
    # 创建模型
    # 占位符
    X = tf.placeholder("float")
    Y = tf.placeholder("float")
    # 模型参数
    W = tf.Variable(tf.random_normal([1]), name="weight")
    b = tf.Variable(tf.zeros([1]), name="bias")
     
    # 前向结构
    z = tf.multiply(X, W) +b
     
    # 反向优化
    cost = tf.reduce_mean(tf.square(Y-z))
    learning_rate = 0.01
    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
     
    # 初始化变量
    init = tf.global_variables_initializer()
    # 参数设置
    training_epochs = 20
    display_step = 2
    saver = tf.train.Saver() # 模型生成,并保存
    savedir = "log/"
     
    # 启动session
    with tf.Session() as sess:
        sess.run(init)
     
        for epoch in range(training_epochs):
            for (x, y) in zip(train_X,train_Y):
                sess.run(optimizer, feed_dict={X:x, Y:y})
     
            # 显示训练中的详细信息
            if epoch % display_step == 0:
                loss = sess.run(cost, feed_dict={X:train_X, Y:train_Y})
                print("Epoch:",epoch+1,"cost=", loss,"W=",sess.run(W),"b=",sess.run(b))
                if not (loss=="NA"):
                    plotdata["batchsize"].append(epoch)
                    plotdata["loss"].append(loss)
     
            print("finished!")
            saver.save(sess, savedir+"linermodel.cpkt")
            print("cost=",sess.run(cost, feed_dict={X:train_X, Y:train_Y}),"W=", sess.run(W),"b=",sess.run(b))
     
            # 图形显示
            plt.plot(train_X, train_Y, 'ro', label='Original data')
            plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
            plt.legend()
            plt.show()
     
            plotdata["avgloss"] = moving_average(plotdata["loss"])
            plt.figure(1)
            plt.subplot(211)
            plt.plot(plotdata["batchsize"], plotdata["avgloss"], 'b--')
            plt.xlabel('Minibatch number')
            plt.ylabel('Loss')
            plt.title('Minibatch run vs. Training loss')
            plt.show()
  • 相关阅读:
    最短路之浇水
    agc031_d A Sequence of Permutations
    loj 3236 [POI2019 R1] Układ scalony
    CodeForces 1237H Balanced Reversals
    CodeForces 1320F Blocks and Sensors
    CodeForces 1340D Nastya and Time Machine
    agc037_f Counting of Subarrays
    nikkei2019_2_qual_e Non-triangular Triplets
    CodeForces 603E Pastoral Oddities
    Vue router / ElementUI,Ant Design Vue 重复点击导航路由报错解决方法
  • 原文地址:https://www.cnblogs.com/xiatian21/p/14941241.html
Copyright © 2011-2022 走看看