主頁 > 後端開發 > 黑馬程式員3天玩轉Python深度學習tensorflow(第一天)

黑馬程式員3天玩轉Python深度學習tensorflow(第一天)

2021-04-27 17:36:50 後端開發

文章目錄

  • 一、深度學習的介紹
    • 1.1 深度學習與機器學習的區別
      • 1.1.1 特征提取方面
      • 1.1.2 資料量和計算性能要求
      • 1.1.3 演算法代表
    • 1.2 深度學習的應用場景
    • 1.3 深度學習框架介紹
      • 1.3.1 常見深度學習框架對比
      • 1.3.2 tensorflow的特點
      • 1.3.3 tensorflow的安裝
  • 二、tensorflow框架介紹
    • 2.1 TF資料流圖
      • 2.1.1 案例:tensorflow實作一個加法運算
    • 2.2 圖與TensorBoard
      • 2.2.1 什么是圖結構
      • 2.2.2 圖相關操作
      • 2.2.3 TensorBoard可視化學習
      • 2.2.4 OP
    • 2.3 會話
      • 2.3.1 會話創建
    • 2.4 張量
      • 2.4.1 張量(Tensor)
      • 2.4.2 創建張量的指令
      • 2.4.3 張量的變換
      • 2.4.4 張量的數學運算
    • 2.5 變數OP
      • 2.5.1 創建變數
      • 2.5.2 使用tf.variable_scope()修改變數的命名空間
    • 2.6 高級API
      • 2.6.1 其他基礎API
      • 2.6.2 高級API
    • 2.7 案例:實作線性回歸
      • 2.7.2 案例:實作線性回歸的訓練
      • 2.7.3 增加其他功能

學習目標:

  • 第一天:tensorflow框架實用
  • 第二天:資料讀取、神經網路基礎
  • 第三天:卷積神經網路、驗證碼識別

第一天:

  • 學習學習介紹
  • tensorflow框架的使用
    • 1)tensorflow的結構
    • 2)tensorflow的各個組件:圖、會話、張量、變數
    • 3)簡單的線性回歸案例----將TensorFlow用起來

一、深度學習的介紹

1.1 深度學習與機器學習的區別

學習目標:知道深度學習與機器學習的區別
區別:深度學習沒有特征提取
在這里插入圖片描述

1.1.1 特征提取方面

  • 機器學習的特征工程步驟是要靠手動完成的,而且需要大量領域專業知識
  • 深度學習通常由多個層組成,它們通常將更簡單的模型組合在一起,將資料從一層傳遞到另一層來構建更復雜的模型,通過訓練大量資料自動得到模型,不需要人工特征提取環節

深度學習演算法試圖從資料中學習高級功能,這是深度學習的一個非常獨特的部分,因此,減少了為每個問題開發新特征提取器的任務,適合用在難提取特征的影像、語音、自然語言處理領域

1.1.2 資料量和計算性能要求

機器學習需要的執行時間遠少于深度學習,深度學習引數往往很龐大,需要通過大量
資料的多次優化來訓練引數
在這里插入圖片描述

  • 第一,深度學習需要大量的訓練資料集
  • 第二,訓練深度神經網路需要大量的算力
    可能要花費數天、甚至數周的時間,才能使用數百萬張影像的資料集訓練出一個深度網路,所以深度學習通常需要強大的GPU服務器來進行計算

1.1.3 演算法代表

機器學習:樸素貝葉斯,決策樹
深度學習:神經網路

1.2 深度學習的應用場景

影像識別:物體識別、場景識別、車型識別、人臉檢測跟蹤、人臉關鍵點定位、人臉身份認證
自然語言處理技術:機器翻譯、文本識別、聊天對話
語音技術:語音識別

1.3 深度學習框架介紹

1.3.1 常見深度學習框架對比

在這里插入圖片描述
在這里插入圖片描述

1.3.2 tensorflow的特點

官網:https://www.tensorflow.org/

1.3.3 tensorflow的安裝

1 CPU版本
2 GPU版本:核芯數量多,更適合處理并行任務

pip install tensorflow==1.8 -i https://pypi.douban.com/simple

二、tensorflow框架介紹

2.1 TF資料流圖

學習目標:說明tensorflow的資料流圖結構

2.1.1 案例:tensorflow實作一個加法運算

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告


def tensorflow_demo():
    """
    tensorflow的基本結構
    :return:
    """
    # tensorflow實作加法運算
    a_t = tf.constant(2)
    b_t = tf.constant(3)
    c_t = a_t + b_t
    print("c_t:", c_t)

    # 開啟會話
    with tf.Session() as sess:
        c_t_value = sess.run(c_t)
        print("c_t_value:", c_t_value)

    return None


if __name__ == "__main__":
    tensorflow_demo()
c_t: Tensor("add:0", shape=(), dtype=int32)
c_t_value: 5

2 TensorFlow結構分析
TensorFlow程式通常被組織成一個構件圖階段和一個執行圖階段
在構建階段,資料與操作的執行步驟被描述為一個圖
在執行階段,使用會話執行構建好的圖中的操作

圖:這是TensorFlow將計算表示為指令之間的依賴關系的一種表示法
會話:TensorFlow跨一個或多個本地或遠程設備運行資料流圖的機制
張量:TensorFlow中的基本資料物件
節點:提供圖當中執行的操作

2.2 圖與TensorBoard

學習目標:

  • 說明圖的基本使用
  • 應用tf.Graph創建圖,tf.get_default_graph獲取默認圖
  • 知道開啟TensorBoard程序
  • 知道圖當中op的名字以及命名空間

2.2.1 什么是圖結構

圖包含了一組tf.Operation代表的計算單元物件和tf.Tensor代表的計算單元之間流動的資料

2.2.2 圖相關操作

1 默認圖
通常tensorflow會默認幫我們創建一張圖

查看默認圖的兩種方法:

  • 通過呼叫**tf.get_default_graph()**訪問,要將操作添加到默認圖形中,直接創建OP即可
  • op、sess都含有graph屬性,默認都在一張圖中
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告


def graph_demo():
    """
    圖的演示
    :return:
    """
    # tensorflow實作加法運算
    a_t = tf.constant(2)
    b_t = tf.constant(3)
    c_t = a_t + b_t
    print("c_t:", c_t)

    # 查看默認圖
    # 方法1:呼叫方法
    default_g = tf.get_default_graph()
    print("default_g:", default_g)

    # 方法2:查看屬性
    print("a_t的圖屬性:", a_t.graph)
    print("c_t的圖屬性:", c_t.graph)

    # 開啟會話
    with tf.Session() as sess:
        c_t_value = sess.run(c_t)
        print("c_t_value:", c_t_value)
        print("sess的圖屬性:", sess.graph)

    return None


if __name__ == "__main__":
    graph_demo()
c_t: Tensor("add:0", shape=(), dtype=int32)
default_g: <tensorflow.python.framework.ops.Graph object at 0x000002A49DEA72B0>
a_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000002A49DEA72B0>
c_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000002A49DEA72B0>
c_t_value: 5
sess的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000002A49DEA72B0>

2 創建圖

  • 可以通過**tf.Graph()**自定義創建圖
  • 如果要在這張圖中創建OP,典型用法是使用**tf.Graph.as_default()**背景關系管理器
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def graph_demo():
    """
    圖的演示
    :return:
    """
    # tensorflow實作加法運算
    a_t = tf.constant(2)
    b_t = tf.constant(3)
    c_t = a_t + b_t
    print("c_t:", c_t)

    # 查看默認圖
    # 方法1:呼叫方法
    default_g = tf.get_default_graph()
    print("default_g:", default_g)

    # 方法2:查看屬性
    print("a_t的圖屬性:", a_t.graph)
    print("c_t的圖屬性:", c_t.graph)

    # 開啟會話
    with tf.Session() as sess:
        c_t_value = sess.run(c_t)
        print("c_t_value:", c_t_value)
        print("sess的圖屬性:", sess.graph)
    print("--------------------------------")

    # 自定義圖
    new_g = tf.Graph()
    # 在自己的圖中定義資料和操作
    with new_g.as_default():
        a_new = tf.constant(20)
        b_new = tf.constant(30)
        c_new = a_new + b_new
        print("c_new:", c_new)
        print("a_new的圖屬性:", a_new.graph)
        print("c_new的圖屬性:", c_new.graph)

    # 開啟new_g的會話
    with tf.Session(graph=new_g) as new_sess:
        # 試圖運行自定義圖中的資料,操作
        c_new_value = new_sess.run(c_new)
        print("c_new_value:", c_new_value)
        print("new_sess的圖屬性:", new_sess.graph)

    return None


if __name__ == "__main__":
    graph_demo()
c_t: Tensor("add:0", shape=(), dtype=int32)
default_g: <tensorflow.python.framework.ops.Graph object at 0x00000152C1C87400>
a_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152C1C87400>
c_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152C1C87400>
c_t_value: 5
sess的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152C1C87400>
--------------------------------
c_new: Tensor("add:0", shape=(), dtype=int32)
a_new的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152E6FFD9B0>
c_new的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152E6FFD9B0>
c_new_value: 50
new_sess的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152E6FFD9B0>

2.2.3 TensorBoard可視化學習

tensorflow可用于訓練大規模深度神經網路所需的計算,使用該工具設計的計算往往復雜而深奧,為了更方便tensorflow程式的理解、除錯與優化,tensorflow提供了TensorBoard可視化工具

實作程式可視化程序:
1 資料序列化-events檔案
TensorBoard通過讀取TensorFlow的事件檔案來運行,需要將資料生成一個序列化的Summary protobuf物件

tf.summary.FileWriter(path, graph=sess.graph)

2 啟動TensorBoard

tensorboard --logdir=path

例:

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def graph_demo():
    """
    圖的演示
    :return:
    """
    # tensorflow實作加法運算
    a_t = tf.constant(2)
    b_t = tf.constant(3)
    c_t = a_t + b_t
    print("c_t:", c_t)

    # 查看默認圖
    # 方法1:呼叫方法
    default_g = tf.get_default_graph()
    print("default_g:", default_g)

    # 方法2:查看屬性
    print("a_t的圖屬性:", a_t.graph)
    print("c_t的圖屬性:", c_t.graph)

    # 開啟會話
    with tf.Session() as sess:
        c_t_value = sess.run(c_t)
        print("c_t_value:", c_t_value)
        print("sess的圖屬性:", sess.graph)
        # 1)將圖寫入本地生成events檔案
        tf.summary.FileWriter("summary", graph=sess.graph)  # tmp檔案夾下
    print("--------------------------------")

    # 自定義圖
    new_g = tf.Graph()
    # 在自己的圖中定義資料和操作
    with new_g.as_default():
        a_new = tf.constant(20)
        b_new = tf.constant(30)
        c_new = a_new + b_new
        print("c_new:", c_new)
        print("a_new的圖屬性:", a_new.graph)
        print("c_new的圖屬性:", c_new.graph)

    # 開啟new_g的會話
    with tf.Session(graph=new_g) as new_sess:
        # 試圖運行自定義圖中的資料,操作
        c_new_value = new_sess.run(c_new)
        print("c_new_value:", c_new_value)
        print("new_sess的圖屬性:", new_sess.graph)

    return None

if __name__ == "__main__":
    graph_demo()

在這里插入圖片描述
之后,在終端輸入:
在這里插入圖片描述
得到鏈接,點擊網址鏈接
在這里插入圖片描述
在這里插入圖片描述
成功!

2.2.4 OP

即操作物件

1 常見OP
那些是OP
在這里插入圖片描述

操作函式操作物件
tf.constant(Tensor物件)輸入Tensor物件-Const輸出 Tensor物件
tf.add(Tensor物件1,Tensor物件2)輸入(Tensor物件1,Tensor物件2) ,add物件,輸出 Tensor物件3
  • 一個圖一個命名空間,互不干擾影響
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def graph_demo():
    """
    圖的演示
    :return:
    """
    # tensorflow實作加法運算
    a_t = tf.constant(2, name="a_t")
    b_t = tf.constant(3, name="b_t")
    c_t = tf.add(a_t, b_t, name="c_t")
    print("c_t:", c_t)

    # 查看默認圖
    # 方法1:呼叫方法
    default_g = tf.get_default_graph()
    print("default_g:", default_g)

    # 方法2:查看屬性
    print("a_t的圖屬性:", a_t.graph)
    print("c_t的圖屬性:", c_t.graph)

    # 開啟會話
    with tf.Session() as sess:
        c_t_value = sess.run(c_t)
        print("c_t_value:", c_t_value)
        print("sess的圖屬性:", sess.graph)
        # 1)將圖寫入本地生成events檔案
        tf.summary.FileWriter("logs", graph=sess.graph)  
    print("--------------------------------")

    # 自定義圖
    new_g = tf.Graph()
    # 在自己的圖中定義資料和操作
    with new_g.as_default():
        a_new = tf.constant(20, name="a_new")
        b_new = tf.constant(30, name="b_new")
        c_new = tf.add(a_new, b_new, name="c_new")
        print("c_new:", c_new)
        print("a_new的圖屬性:", a_new.graph)
        print("c_new的圖屬性:", c_new.graph)
        tf.summary.FileWriter("log2", graph=sess.graph)

    # 開啟new_g的會話
    with tf.Session(graph=new_g) as new_sess:
        # 試圖運行自定義圖中的資料,操作
        c_new_value = new_sess.run(c_new)
        print("c_new_value:", c_new_value)
        print("new_sess的圖屬性:", new_sess.graph)

    return None


if __name__ == "__main__":
    graph_demo()

在這里插入圖片描述

2.3 會話

學習目標:

  • 應用sess.rn或者eval運行圖程式并獲取張量值
  • 應用feed_dict機制實作運行時填充資料
  • 應用placeholder實作創建占位符

2.3.1 會話創建

  • tf.Session:用于完整的程式當中
  • tf.InteractiveSession:用于互動式背景關系中的TensorFlow,例如shell
    在這里插入圖片描述

背景關系管理器:

with tf.Session() as sess:
	sess.run(sth)
  • target:如果將此引數留空(默認設定),會話將僅使用本地計算機中的設備,可以指定grpc://網址,以便指定TensorFlow服務器的地址,這使得會話可以訪問該服務器控制的計算機上的所有設備
  • graph:默認情況下,新的tf.Session將系結到當前的默認圖
  • config:此引數允許您指定一個tf.ConfigProto以便控制會話的行為,例如,ConfigProto協議用于列印設備使用資訊
# 運行會話并列印設備資訊
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))

2 會話的run()
通過使用sess.run(0)來運行operation

run(fetches, feed_dict=None, options=None, run_metadata=None)
  • fetches:單一的operation,或者串列、元組(其他不屬于tensorflow的型別不行)
  • feed_dict:引數運行呼叫者覆寫圖中張量的值,運行時賦值,與tf.placeholder搭配使用,則會檢查值的形式是否與占位符兼容
# 創建圖
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a + b

# 創建會話
sess = tf.Session()

# 計算C的值
print(sess.run(c))
print(c.eval(session=sess))

3 feed操作

  • placeholder提供占位符,run時候通過feed_dict指定引數
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告


def session_demo():
    """
    會話的演示:列印設備資訊
    :return:
    """
    # tensorflow實作加法運算
    a_t = tf.constant(2, name="a_t")
    b_t = tf.constant(3, name="b_t")
    c_t = tf.add(a_t, b_t, name="c_t")
    print("a_t", a_t)
    print("b_t", b_t)
    print("c_t:", c_t)
    print("------------------------------")

    # 定義占位符
    a_ph = tf.placeholder(tf.float32)
    b_ph = tf.placeholder(tf.float32)
    c_ph = tf.add(a_ph, b_ph)
    print("a_ph:", a_ph)
    print("b_ph:", b_ph)
    print("c_ph:", c_ph)
    print("------------------------------")

    # 查看默認圖
    # 方法1:呼叫方法
    default_g = tf.get_default_graph()
    print("default_g:", default_g)
    # 方法2:查看屬性
    print("a_t的圖屬性:", a_t.graph)
    print("c_t的圖屬性:", c_t.graph)
    print("-------------------------------")

    # 開啟會話
    with tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                          log_device_placement=True)) as sess:
        # 運行placeholder
        c_ph_value = sess.run(c_ph, feed_dict={a_ph:3.9, b_ph:4.8})
        print('c_ph_value', c_ph_value)
        print("------------------------------")
        abc = sess.run([a_t, b_t, c_t])  # 傳入串列,回傳串列
        print("abc:", abc)
        print("c_t_value;", c_t.eval())
        print("sess的圖屬性:", sess.graph)
        #tf.summary.FileWriter("logs", graph=sess.graph)  # 1)將圖寫入本地生成events檔案


if __name__ == "__main__":
    session_demo()
a_t Tensor("a_t:0", shape=(), dtype=int32)
b_t Tensor("b_t:0", shape=(), dtype=int32)
c_t: Tensor("c_t:0", shape=(), dtype=int32)
------------------------------
a_ph: Tensor("Placeholder:0", dtype=float32)
b_ph: Tensor("Placeholder_1:0", dtype=float32)
c_ph: Tensor("Add:0", dtype=float32)
------------------------------
default_g: <tensorflow.python.framework.ops.Graph object at 0x000001618EF65748>
a_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000001618EF65748>
c_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000001618EF65748>
-------------------------------
Device mapping: no known devices.
Add: (Add): /job:localhost/replica:0/task:0/device:CPU:0
c_t: (Add): /job:localhost/replica:0/task:0/device:CPU:0
Placeholder_1: (Placeholder): /job:localhost/replica:0/task:0/device:CPU:0
Placeholder: (Placeholder): /job:localhost/replica:0/task:0/device:CPU:0
b_t: (Const): /job:localhost/replica:0/task:0/device:CPU:0
a_t: (Const): /job:localhost/replica:0/task:0/device:CPU:0
c_ph_value 8.700001
------------------------------
abc: [2, 3, 5]
c_t_value; 5
sess的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000001618EF65748>

2.4 張量

學習目標:

  • 知道常見的TensorFlow創建張量
  • 知道常見的張量數學運算操作
  • 說明numpy的陣列與張量相同性
  • 說明張量的兩種形狀改變特點
  • 應用set_shape和tf.reshape山西愛你張量形狀的修改
  • 應用tf.matmul實作張量的矩陣運算修改
  • 應用tf.cast實作張量的型別

2.4.1 張量(Tensor)

TensorFlow的張量就是一個N維陣列,型別為tf.Tensor,

張量:在計算機當中如何存盤?N維陣列
標量:一個數字----0階張量
向量:一維陣列-----1階張量
矩陣:二維陣列------2階張量

  • type:資料型別
  • shape:形狀(階)

1 張量的型別
在這里插入圖片描述
2 張量的階
在這里插入圖片描述
未指定型別時,默認型別:

  • 整型:tf.int32
  • 浮點型:tf.float32
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def tensor_demo():
    """
    張量的演示
    :return:
    """

    tensor1 = tf.constant(4.0)
    tensor2 = tf.constant([1,2,3,4])  # 未指定型別,默認型別
    linear_squares = tf.constant([[4],[9],[16],[25]],dtype=tf.int32)
    print("tensor1:", tensor1)
    print("tensor2:", tensor2)
    print("linear_square:", linear_squares)
    return None


if __name__ == "__main__":
    tensor_demo()
tensor1: Tensor("Const:0", shape=(), dtype=float32)
tensor2: Tensor("Const_1:0", shape=(4,), dtype=int32)
linear_square: Tensor("Const_2:0", shape=(4, 1), dtype=int32)

2.4.2 創建張量的指令

固定值張量
1 創建多個0

tf.zeros(shape, dtype=tf.float32, name=None)

2 創建多個1

tf.ones(shape, dtype=tf.float32, name=None)

3 創建常數張量

tf.constant(value, dtype=tf.float32, name='Const')

用.eval可以查看值
在這里插入圖片描述

2.4.3 張量的變換

1 型別改變

  • tf.string_to_number(string_tensor, out_type=None, name=None)
  • tf.to_double(x, name=‘ToDouble’)
  • tf.to_float(x, name=‘ToFloat’)
  • tf.to_bfloat16(x, name=“ToBFloat16”)
  • tf.to_int32(x, name=‘Tolnt32’)
  • tf.to_int64(x, name=‘Tolnt64’)
  • tf.cast(x, dtype, name=None),通用型別轉換
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def tensor_demo():
    """
    張量的演示
    :return:
    """

    tensor1 = tf.constant(4.0)
    tensor2 = tf.constant([1,2,3,4])  # 未指定型別,默認型別
    linear_squares = tf.constant([[4],[9],[16],[25]],dtype=tf.int32)
    print("tensor1:", tensor1)
    print("tensor2:", tensor2)
    print("linear_square:", linear_squares)

    print("----------------")
    # 張量型別的修改:不會改變原始的Tensor
    l_cast = tf.cast(linear_squares, dtype=tf.float32)
    print("linear_square_after:", linear_squares)
    print('l_cast:', l_cast)

    return None


if __name__ == "__main__":
    tensor_demo()
tensor1: Tensor("Const:0", shape=(), dtype=float32)
tensor2: Tensor("Const_1:0", shape=(4,), dtype=int32)
linear_square: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
----------------
linear_square_after: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
l_cast: Tensor("Cast:0", shape=(4, 1), dtype=float32)

2 形狀改變
tensorflow的張量具有兩種形狀變換,動態形狀和靜態形狀

  • tf.reshape:改變動態形狀

  • tf.set_shape:改變靜態形狀

  • 靜態形狀:初始創建張量時的形狀

  • 動態形狀:

什么情況下可以改變靜態形狀:只有在形狀還沒有完全固定下來的情況下;轉換形狀的時候,只能一維到一維,二維到二維,而不能跨維度改變形狀

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def tensor_demo():
    """
    張量的演示
    :return:
    """

    tensor1 = tf.constant(4.0)
    tensor2 = tf.constant([1,2,3,4])  # 未指定型別,默認型別
    linear_squares = tf.constant([[4],[9],[16],[25]],dtype=tf.int32)
    print("tensor1:", tensor1)
    print("tensor2:", tensor2)
    print("linear_square:", linear_squares)

    print("----------------")
    # 張量型別的修改:不會改變原始的Tensor
    l_cast = tf.cast(linear_squares, dtype=tf.float32)
    print("linear_square_after:", linear_squares)
    print('l_cast:', l_cast)

    print('------------------')
    # 更新、改變靜態形狀
    # 定義占位符
    a_p = tf.placeholder(dtype=tf.float32, shape=[None, None])  # 形狀沒有完全固定下來的靜態形狀
    b_p = tf.placeholder(dtype=tf.float32, shape=[None, 10])
    c_p = tf.placeholder(dtype=tf.float32, shape=[3, 2])
    print("a_p:", a_p)
    print("b_p:", b_p)
    print("c_p:", c_p)

    print("-----------------------")
    # 更新形狀未確定的部分
    a_p.set_shape([2,3])
    b_p.set_shape([2,10])
    print("a_p:", a_p)
    print("b_p:", b_p)

    print('-------------')
    # 動態形狀修改
    a_p_reshape = tf.reshape(a_p, shape=[2, 3, 1])
    print("a_p:", a_p)
    print("a_p_reshape:", a_p_reshape)

    c_p_reshape = tf.reshape(c_p, shape=[2, 3, 1])  # 必須保持改變前后元素的數量一致
    print("c_p:", c_p)
    print("c_p_reshape:", c_p_reshape)

    return None


if __name__ == "__main__":
    tensor_demo()
tensor1: Tensor("Const:0", shape=(), dtype=float32)
tensor2: Tensor("Const_1:0", shape=(4,), dtype=int32)
linear_square: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
----------------
linear_square_after: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
l_cast: Tensor("Cast:0", shape=(4, 1), dtype=float32)
------------------
a_p: Tensor("Placeholder:0", shape=(?, ?), dtype=float32)
b_p: Tensor("Placeholder_1:0", shape=(?, 10), dtype=float32)
c_p: Tensor("Placeholder_2:0", shape=(3, 2), dtype=float32)
-----------------------
a_p: Tensor("Placeholder:0", shape=(2, 3), dtype=float32)
b_p: Tensor("Placeholder_1:0", shape=(2, 10), dtype=float32)
-------------
a_p: Tensor("Placeholder:0", shape=(2, 3), dtype=float32)
a_p_reshape: Tensor("Reshape:0", shape=(2, 3, 1), dtype=float32)
c_p: Tensor("Placeholder_2:0", shape=(3, 2), dtype=float32)
c_p_reshape: Tensor("Reshape_1:0", shape=(2, 3, 1), dtype=float32)

2.4.4 張量的數學運算

  • 算術運算子
  • 基本數學函式
  • 矩陣運算
  • reduce操作
  • 序列索引操作

2.5 變數OP

學習目標:

  • 說明變數op的特殊作用
  • 說明變數op的trainable引數的作用
  • 應用global_variables_initializer實作變數op的初始化

變數的特點:

  • 存盤持久化
  • 可修改值
  • 可指定被訓練

2.5.1 創建變數

tf.Variable(initia_value=None, trainable=True, collections=None, name=None)
  • initial_value:初始化的值
  • trainable:是否被訓練
  • collections:新變數將添加到列出的圖的集合中collections,默認為[GraphKeys.GLOBAL_VARIABLES],如果trainable是True變數也被添加到圖形集合GraphKeys.TRAINABLE_VARIABLES

變數需要顯示初始化,才能運行值

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def variable_demo():
    """
    變數的演示
    :return:
    """
    # 創建變數
    a = tf.Variable(initial_value=50)
    b = tf.Variable(initial_value=40)
    c = tf.add(a, b)
    print("a:", a)
    print("b", b)
    print("c", c)
    print('----------------------')

    # 初始化變數
    init = tf.global_variables_initializer()

    # 開啟會話
    with tf.Session() as sess:
        # 運行初始化
        sess.run(init)
        a_value, b_value, c_value = sess.run([a,b,c])
        print("a_value:", a_value)
        print("b_value", b_value)
        print("c_value", c_value)

    return None


if __name__ == "__main__":
    variable_demo()
a: <tf.Variable 'Variable:0' shape=() dtype=int32_ref>
b <tf.Variable 'Variable_1:0' shape=() dtype=int32_ref>
c Tensor("Add:0", shape=(), dtype=int32)
----------------------
a_value: 50
b_value 40
c_value 90

2.5.2 使用tf.variable_scope()修改變數的命名空間

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def variable_demo():
    """
    變數的演示
    :return:
    """
    # 創建變數
    with tf.variable_scope("my_scope"):
        a = tf.Variable(initial_value=50)
        b = tf.Variable(initial_value=40)
    with tf.variable_scope("your_scope"):
        c = tf.add(a, b)
    print("a:", a)
    print("b", b)
    print("c", c)
    print('----------------------')

    # 初始化變數
    init = tf.global_variables_initializer()

    # 開啟會話
    with tf.Session() as sess:
        # 運行初始化
        sess.run(init)
        a_value, b_value, c_value = sess.run([a,b,c])
        print("a_value:", a_value)
        print("b_value", b_value)
        print("c_value", c_value)

    return None


if __name__ == "__main__":
    variable_demo()
a: <tf.Variable 'my_scope/Variable:0' shape=() dtype=int32_ref>
b <tf.Variable 'my_scope/Variable_1:0' shape=() dtype=int32_ref>
c Tensor("your_scope/Add:0", shape=(), dtype=int32)
----------------------
a_value: 50
b_value 40
c_value 90

2.6 高級API

2.6.1 其他基礎API

1 tf.app
這個模塊相當于為TensorFlow進行的腳本提供一個main函式入口,可以定義腳本運行的flags

2 tf.image
TensorFlow的影像處理操作,主要是一些顏色變換、變形和影像的編碼和解碼

3 tf.gfile
這個模塊提供了一組檔案操作函式

4 tf.summary
用來生成TensorBoard可用的統計日志,目前Summary主要提供了4種型別:
audio、image、histogram、scalar

5 tf.python_io
用來讀寫TFRecords檔案

6 tf.train
這個模塊提供了一些訓練器,與tf.nn結合起來,實作一些網路的優化計算

7 tf.nn
這個模塊提供了一些構建神經網路的底層函式,TensorFlow構建網路的核心模塊,其中包含了添加各種層的函式,比如添加卷積層、池化層等,

2.6.2 高級API

1 tf.keras
Kears本來是一個獨立的深度學習庫,tensorflow將其學習過來,增加這部分模塊在于快速構建模型

2 tf.layers
高級API,以便高級的概念層來定義一個模型,類似tf.kears

3 tf.contrib
tf.contrib.layers提供夠將計算圖中的網路層、正則化、摘要操作,是構建計算圖的高級操作,但是tf.contrib包含不穩定和實驗代碼,有可能以后API會改變

4 tf.estimator
一個estimator相當于model + training + evaluate 的合體,在模塊中,已經實作了幾種簡單的分類器和回歸其,包括:Baseline,learning 和 DNN,這里的DNN的網路,只是全連接網路,沒有提供卷積之類的

2.7 案例:實作線性回歸

學習目標:

  • 應用op的name引數實作op的名字修改
  • 應用variable_scope實作圖程式作用域的添加
  • 應用scalar或histogram實作張良志的跟蹤顯示
  • 應用merge_all實作張量值的合并
  • 應用add_summary實作張量值的寫入檔案
  • 應用tf.train.saver實作TensorFlow的模型保存以及加載
  • 應用tf.app.flags實作命令列引數添加和使用
  • 應用reduce_mean、square實作均方誤差計算
  • 應用tf.train.GradientDescentOptimizer實作有梯度下降優化器創建
  • 應用minimize函式優化損失
  • 知道梯度爆炸以及常見解決技巧

2.7.2 案例:實作線性回歸的訓練

1)構建模型
2)構建損失函式:均方誤差
3)優化損失:梯度下降

準備真實資料:
x:特征值,形狀:(100,1)
y_true:目標值 (100,1)
y_true = 0.8x + 0.7 ,100個樣本
假設滿足: y =kx + b

流程分析:

1001*11=1001)
y_predict = x * weight(1,1)  + bias(1,1)

1)構建模型
y_predict = tf.matmul(x, weights) + bias
2)構造損失函式
error = tf.reduce_mean(tf.square(y_predict - y_true))
3)優化損失:梯度下降優化器
optimizer = tf.train.GrandientDescentOptimizer(learning_rate=0.01).minimize(error)

運算:

  • 矩陣運算:tf.matmu(x,w)
  • 平方:tf.square(error)
  • 均方:tf.reduce_mean(error)
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def linear_regression():
    """
    實作線性回歸
    :return:
    """
    # 1)準備資料
    X = tf.random_normal(shape=[100, 1])  # 形狀:100行1列
    y_true = tf.matmul(X, [[0.8]]) + 0.7  # y_true = 0.8x + 0.7

    # 2)構造模型
    # 定義模型引數,用變數
    weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
    bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
    y_predict = tf.matmul(X, weights) + bias

    # 3)構造損失函式
    error = tf.reduce_mean(tf.square(y_predict - y_true))

    # 4)優化損失
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)

    # 顯式地初始化變數
    init = tf.global_variables_initializer()

    # 開啟會話
    with tf.Session() as sess:
        # 初始化變數
        sess.run(init)

        # 查看初始化模型引數之后的值
        print("訓練前模型引數為:權重%f,偏置%f,損失為%f" %
              (weights.eval(), bias.eval(), error.eval()))

        # 開始訓練
        for i in range(200):
            sess.run(optimizer)
            print("第%d訓練后模型引數為:權重%f,偏置%f,損失為%f" %
              (i+1, weights.eval(), bias.eval(), error.eval()))

    return None


if __name__ == "__main__":
    linear_regression()
...195訓練后模型引數為:權重0.784588,偏置0.704202,損失為0.000298196訓練后模型引數為:權重0.784881,偏置0.704130,損失為0.000259197訓練后模型引數為:權重0.785245,偏置0.704024,損失為0.000256198訓練后模型引數為:權重0.785542,偏置0.703911,損失為0.000219199訓練后模型引數為:權重0.785778,偏置0.703855,損失為0.000218200訓練后模型引數為:權重0.786084,偏置0.703762,損失為0.000211

5 學習率的設定、步數的設定與梯度爆炸

  • 學習率越大,訓練

2.7.3 增加其他功能

  • 變數TensorBoard顯示
  • 增加命名空間
  • 模型保存于加載
  • 命令列引數設定

1 增加變數顯示
目的:在TensorBoard當中觀察模型的引數、損失值等變數值的變化
在這里插入圖片描述
1)創建事件檔案
2)收集變數
3)合并變數
4)每次迭代運行合并變數
5)每次迭代將summary事件寫入事件檔案

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def linear_regression():
    """
    實作線性回歸
    :return:
    """
    # 1)準備資料
    X = tf.random_normal(shape=[100, 1])  # 形狀:100行1列
    y_true = tf.matmul(X, [[0.8]]) + 0.7  # y_true = 0.8x + 0.7

    # 2)構造模型
    # 定義模型引數,用變數
    weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
    bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
    y_predict = tf.matmul(X, weights) + bias

    # 3)構造損失函式
    error = tf.reduce_mean(tf.square(y_predict - y_true))

    # 4)優化損失
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)

    # 2)收集變數
    tf.summary.scalar("error", error)
    tf.summary.histogram("weights", weights)
    tf.summary.histogram("bias", bias)

    # 3)合并變數
    merged = tf.summary.merge_all()

    # 顯式地初始化變數
    init = tf.global_variables_initializer()

    # 開啟會話
    with tf.Session() as sess:
        # 初始化變數
        sess.run(init)

        # 1)創建事件檔案
        file_writer = tf.summary.FileWriter('logs', graph=sess.graph)

        # 查看初始化模型引數之后的值
        print("訓練前模型引數為:權重%f,偏置%f,損失為%f" %
              (weights.eval(), bias.eval(), error.eval()))

        # 開始訓練
        for i in range(100):
            sess.run(optimizer)
            print("第%d訓練后模型引數為:權重%f,偏置%f,損失為%f" %
              (i+1, weights.eval(), bias.eval(), error.eval()))

            # 運行合并變數操作
            summary = sess.run(merged)
            # 每次迭代后的變數寫入事件
            file_writer.add_summary(summary, i)

    return None


if __name__ == "__main__":
    linear_regression()

在這里插入圖片描述

2 增加命名空間
使得代碼結構更加資訊,TensorBoard圖結構更加清楚

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def linear_regression():
    """
    實作線性回歸
    :return:
    """
    with tf.variable_scope("prepare_data"):
        # 1)準備資料
        X = tf.random_normal(shape=[100, 1], name='feature')  # 形狀:100行1列
        y_true = tf.matmul(X, [[0.8]]) + 0.7  # y_true = 0.8x + 0.7
    with tf.variable_scope("create_model"):
        # 2)構造模型
        # 定義模型引數,用變數
        weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]), name="Weights")
        bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]), name="Bias")
        y_predict = tf.matmul(X, weights) + bias
    with tf.variable_scope("loss_function"):
        # 3)構造損失函式
        error = tf.reduce_mean(tf.square(y_predict - y_true))
    with tf.variable_scope("optimizer"):
        # 4)優化損失
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)

    # 2)收集變數
    tf.summary.scalar("error", error)
    tf.summary.histogram("weights", weights)
    tf.summary.histogram("bias", bias)

    # 3)合并變數
    merged = tf.summary.merge_all()

    # 顯式地初始化變數
    init = tf.global_variables_initializer()

    # 開啟會話
    with tf.Session() as sess:
        # 初始化變數
        sess.run(init)

        # 1)創建事件檔案
        file_writer = tf.summary.FileWriter('logs', graph=sess.graph)

        # 查看初始化模型引數之后的值
        print("訓練前模型引數為:權重%f,偏置%f,損失為%f" %
              (weights.eval(), bias.eval(), error.eval()))

        # 開始訓練
        for i in range(100):
            sess.run(optimizer)
            print("第%d訓練后模型引數為:權重%f,偏置%f,損失為%f" %
              (i+1, weights.eval(), bias.eval(), error.eval()))

            # 運行合并變數操作
            summary = sess.run(merged)
            # 每次迭代后的變數寫入事件
            file_writer.add_summary(summary, i)

    return None


if __name__ == "__main__":
    linear_regression()

在這里插入圖片描述

3 模型的保存與加載
在這里插入圖片描述
步驟:
1)實體化Saver
2)保存:saver.save(sess, path)
3)加載:saver.restore(sess, path)

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def linear_regression():
    """
    實作線性回歸
    :return:
    """
    with tf.variable_scope("prepare_data"):
        # 1)準備資料
        X = tf.random_normal(shape=[100, 1], name='feature')  # 形狀:100行1列
        y_true = tf.matmul(X, [[0.8]]) + 0.7  # y_true = 0.8x + 0.7
    with tf.variable_scope("create_model"):
        # 2)構造模型
        # 定義模型引數,用變數
        weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]), name="Weights")
        bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]), name="Bias")
        y_predict = tf.matmul(X, weights) + bias
    with tf.variable_scope("loss_function"):
        # 3)構造損失函式
        error = tf.reduce_mean(tf.square(y_predict - y_true))
    with tf.variable_scope("optimizer"):
        # 4)優化損失
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(error)

    # 2)收集變數
    tf.summary.scalar("error", error)
    tf.summary.histogram("weights", weights)
    tf.summary.histogram("bias", bias)

    # 3)合并變數
    merged = tf.summary.merge_all()

    # 創建Saver物件
    saver = tf.train.Saver()

    # 顯式地初始化變數
    init = tf.global_variables_initializer()

    # 開啟會話
    with tf.Session() as sess:
        # 初始化變數
        sess.run(init)

        # 1)創建事件檔案
        file_writer = tf.summary.FileWriter('logs', graph=sess.graph)

        # 查看初始化模型引數之后的值
        print("訓練前模型引數為:權重%f,偏置%f,損失為%f" %
              (weights.eval(), bias.eval(), error.eval()))

        # # 開始訓練
        # for i in range(100):
        #     sess.run(optimizer)
        #     print("第%d訓練后模型引數為:權重%f,偏置%f,損失為%f" %
        #       (i+1, weights.eval(), bias.eval(), error.eval()))
        #
        #     # 運行合并變數操作
        #     summary = sess.run(merged)
        #     # 每次迭代后的變數寫入事件
        #     file_writer.add_summary(summary, i)
        #
        #     # 保存模型
        #     if i % 10 == 0:
        #         saver.save(sess, "model/my_Linear.ckpt")
        # 加載模型
        if os.path.exists("model/checkpoint"):
            saver.restore(sess, "model/my_Linear.ckpt")
        print("訓練后模型引數為:權重%f,偏置%f,損失為%f" %
              (weights.eval(), bias.eval(), error.eval()))
    return None


if __name__ == "__main__":
    linear_regression()
訓練前模型引數為:權重-0.726173,偏置-1.391275,損失為6.139051
訓練后模型引數為:權重0.800000,偏置0.700000,損失為0.000000

4 命令列引數設定
在這里插入圖片描述

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

# 1)定義命令列引數
tf.app.flags.DEFINE_integer("max_step", 100, "訓練模型的步數")
tf.app.flags.DEFINE_string("model_dir", "Unknown", "模型保存的路徑+模型的名字")
# 2)簡化變數名
FLAGS = tf.app.flags.FLAGS

def command_demo():
    """
    命令列引數演示
    :return:
    """
    print("max_step:", FLAGS.max_step)
    print("model_dir:", FLAGS.model_dir)

    return None

if __name__ == "__main__":
    command_demo()

在這里插入圖片描述
在這里插入圖片描述

在這里插入圖片描述
在這里插入圖片描述

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 去警告

def main(argv):
    print(argv)
    print("code start")
    return None

if __name__ == "__main__":
    tf.app.run()   # 自動運行main函式
    #command_demo()
['D:/programming_software/pycharm/PycharmProjects/deep_learning/day01_deeplearning.py']
code start

總結
在這里插入圖片描述

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/280705.html

標籤:python

上一篇:爬蟲百戰穿山甲(6)-- 學會爬蟲,終于拿到了我心心念念的那首歌

下一篇:IDEA必備插件提高企業開發效率(強烈推薦)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more