最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

tensorflow基本操作小白快速構(gòu)建線性回歸和分類模型

 更新時(shí)間:2021年08月30日 13:25:21   作者:劉潤(rùn)森!  
這篇文章主要介紹了tensorflow基本操作,快速構(gòu)建線性回歸和分類模型,圖文代碼示例非常詳細(xì),有需要的朋友可以借鑒參考下,希望可以對(duì)大家有所幫助

TF 目前發(fā)布2.5 版本,之前閱讀1.X官方文檔,最近查看2.X的文檔。

tensorflow是非常強(qiáng)的工具,生態(tài)龐大

tensorflow提供了Keras的分支

這里不再提供Keras相關(guān)順序模型教程。

關(guān)于環(huán)境:ubuntu的 GPU,需要cuda和nvcc

不會(huì)安裝:查看

完整的Ubuntu18.04深度學(xué)習(xí)GPU環(huán)境配置,英偉達(dá)顯卡驅(qū)動(dòng)安裝、cuda9.0安裝、cudnn的安裝、anaconda安裝

不安裝,用colab

測(cè)試GPU

>>> from tensorflow.python.client import device_lib
>>> device_lib.list_local_devices()

這是意思是掛了一個(gè)顯卡

具體查看官方文檔:https://www.tensorflow.org/install

服務(wù)器跑Jupyter

Define tensor constants.

import tensorflow as tf
# Create a Tensor.
hello = tf.constant("hello world")
hello
# Define tensor constants.
a = tf.constant(1)
b = tf.constant(6)
c = tf.constant(9)
# tensor變量的操作
# (+, *, ...)
add = tf.add(a, b)
sub = tf.subtract(a, b)
mul = tf.multiply(a, b)
div = tf.divide(a, b)
# 通過(guò)numpy返回?cái)?shù)值  和torch一樣
print("add =", add.numpy())
print("sub =", sub.numpy())
print("mul =", mul.numpy())
print("div =", div.numpy())
add = 7
sub = -5
mul = 6
div = 0.16666666666666666
mean = tf.reduce_mean([a, b, c])
sum_ = tf.reduce_sum([a, b, c])
# Access tensors value.
print("mean =", mean.numpy())
print("sum =", sum_ .numpy())
mean = 5
sum = 16
# Matrix multiplications.
matrix1 = tf.constant([[1., 2.], [3., 4.]])
matrix2 = tf.constant([[5., 6.], [7., 8.]])
product = tf.matmul(matrix1, matrix2)
product
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[19., 22.],
       [43., 50.]], dtype=float32)>
# Tensor to Numpy.
np_product = product.numpy()
print(type(np_product), np_product)
(numpy.ndarray,
 array([[19., 22.],
        [43., 50.]], dtype=float32))

Linear Regression

下面使用tensorflow快速構(gòu)建線性回歸模型,這里不使用kears的順序模型,而是采用torch的模型定義的寫法。

import numpy as np
import tensorflow as tf
# Parameters:
learning_rate = 0.01
training_steps = 1000
display_step = 50
# Training Data.
X = np.array([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])
Y = np.array([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3])
random = np.random
# 權(quán)重和偏差,隨機(jī)初始化。
W = tf.Variable(random.randn(), name="weight")
b = tf.Variable(random.randn(), name="bias")
# Linear regression (Wx + b).
def linear_regression(x):
    return W * x + b
# Mean square error.
def mean_square(y_pred, y_true):
    return tf.reduce_mean(tf.square(y_pred - y_true))
# 隨機(jī)梯度下降優(yōu)化器。
optimizer = tf.optimizers.SGD(learning_rate)
# 優(yōu)化過(guò)程。
def run_optimization():
    # 將計(jì)算包在GradientTape中,以便自動(dòng)區(qū)分。
    with tf.GradientTape() as g:
        pred = linear_regression(X)
        loss = mean_square(pred, Y)
    # 計(jì)算梯度。
    gradients = g.gradient(loss, [W, b])
        # 按照梯度更新W和b。
    optimizer.apply_gradients(zip(gradients, [W, b]))
#按給定的步數(shù)進(jìn)行訓(xùn)練。
for step in range(1, training_steps + 1):
    # 運(yùn)行優(yōu)化以更新W和b值。
    run_optimization()
        if step % display_step == 0:
        pred = linear_regression(X)
        loss = mean_square(pred, Y)
        print("Step: %i, loss: %f, W: %f, b: %f" % (step, loss, W.numpy(), b.numpy()))


import matplotlib.pyplot as plt
plt.plot(X, Y, 'ro', label='Original data')
plt.plot(X, np.array(W * X + b), label='Fitted line')
plt.legend()
plt.show()

分類模型

本例使用MNIST手寫數(shù)字

數(shù)據(jù)集包含60000個(gè)訓(xùn)練示例和10000個(gè)測(cè)試示例。

這些數(shù)字已經(jīng)過(guò)大小標(biāo)準(zhǔn)化,并在一個(gè)固定大小的圖像(28x28像素)中居中,值從0到255。

在本例中,每個(gè)圖像將轉(zhuǎn)換為float32,標(biāo)準(zhǔn)化為[0,1],并展平為784個(gè)特征(28×28)的一維數(shù)組。

import numpy as np
import tensorflow as tf
#  MNIST data
num_classes = 10      # 0->9 digits
num_features = 784    # 28 * 28
# Parameters 
lr = 0.01
batch_size = 256
display_step = 100
training_steps = 1000
# Prepare MNIST data
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Convert to Float32
x_train, x_test = np.array(x_train, np.float32), np.array(x_test, np.float32)
# Flatten images into 1-D vector of 784 dimensions (28 * 28)
x_train, x_test = x_train.reshape([-1, num_features]), x_test.reshape([-1, num_features])
# [0, 255] to [0, 1]
x_train, x_test = x_train / 255, x_test / 255
# 打亂順序: tf.data API to shuffle and batch data
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = train_dataset.repeat().shuffle(5000).batch(batch_size=batch_size).prefetch(1)
# Weight of shape [784, 10] ~= [number_features, number_classes]
W = tf.Variable(tf.ones([num_features, num_classes]), name='weight')
# Bias of shape [10] ~= [number_classes]
b = tf.Variable(tf.zeros([num_classes]), name='bias')
# Logistic regression: W*x + b
def logistic_regression(x):
    # 應(yīng)用softmax函數(shù)將logit標(biāo)準(zhǔn)化為概率分布
    out = tf.nn.softmax(tf.matmul(x, W) + b)
       return out
# 交叉熵?fù)p失函數(shù)
def cross_entropy(y_pred, y_true):
    # 將標(biāo)簽編碼為一個(gè)one_hot向量
    y_true = tf.one_hot(y_true, depth=num_classes)
        # 剪裁預(yù)測(cè)值避免錯(cuò)誤
    y_pred = tf.clip_by_value(y_pred, 1e-9, 1)
        # 計(jì)算交叉熵
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_true * tf.math.log(y_pred), 1))    
    return cross_entropy
# Accuracy
def accuracy(y_pred, y_true):
    correct = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64))
    return tf.reduce_mean(tf.cast(correct, tf.float32))
# 隨機(jī)梯度下降優(yōu)化器
optimizer = tf.optimizers.SGD(lr)
# Optimization
def run_optimization(x, y):
    with tf.GradientTape() as g:
        pred = logistic_regression(x)
        loss = cross_entropy(y_pred=pred, y_true=y)
    gradients = g.gradient(loss, [W, b])   
    optimizer.apply_gradients(zip(gradients, [W, b]))
# Training
for step, (batch_x, batch_y) in enumerate(train_dataset.take(training_steps), 1):
    # Run the optimization to update W and b
    run_optimization(x=batch_x, y=batch_y)
       if step % display_step == 0:
        pred = logistic_regression(batch_x)
        loss = cross_entropy(y_pred=pred, y_true=batch_y)
        acc = accuracy(y_pred=pred, y_true=batch_y)
        print("Step: %i, loss: %f, accuracy: %f" % (step, loss, acc))

pred = logistic_regression(x_test)
print(f"Test Accuracy: {accuracy(pred, y_test)}")

Test Accuracy: 0.892300009727478

import matplotlib.pyplot as plt
n_images = 5
test_images = x_test[:n_images]
predictions = logistic_regression(test_images)
# 預(yù)測(cè)前5張
for i in range(n_images):
    plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
    plt.show()
    print("Model prediction: %i" % np.argmax(predictions.numpy()[i]))

Model prediction: 7

Model prediction: 2

Model prediction: 1

Model prediction: 0

Model prediction: 4

以上就是tensorflow基本操作小白快速構(gòu)建線性回歸和分類模型的詳細(xì)內(nèi)容,更多關(guān)于tensorflow快速構(gòu)建線性回歸和分類模型的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python3.6利用pyinstall打包py為exe的操作實(shí)例

    python3.6利用pyinstall打包py為exe的操作實(shí)例

    今天小編就為大家分享一篇python3.6利用pyinstall打包py為exe的操作實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-10-10
  • Python match語(yǔ)句的具體使用

    Python match語(yǔ)句的具體使用

    match語(yǔ)句接受一個(gè)表達(dá)式,并將其值與作為一個(gè)或多個(gè)case塊給出的連續(xù)模式進(jìn)行比較,本文主要介紹了Python match語(yǔ)句的具體使用,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • 一行Python代碼制作動(dòng)態(tài)二維碼的實(shí)現(xiàn)

    一行Python代碼制作動(dòng)態(tài)二維碼的實(shí)現(xiàn)

    這篇文章主要介紹了一行Python代碼制作動(dòng)態(tài)二維碼的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • Jupyter notebook如何實(shí)現(xiàn)指定瀏覽器打開(kāi)

    Jupyter notebook如何實(shí)現(xiàn)指定瀏覽器打開(kāi)

    這篇文章主要介紹了Jupyter notebook如何實(shí)現(xiàn)指定瀏覽器打開(kāi),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • Python之關(guān)于類變量的兩種賦值區(qū)別詳解

    Python之關(guān)于類變量的兩種賦值區(qū)別詳解

    這篇文章主要介紹了Python之關(guān)于類變量的兩種賦值區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-03-03
  • python 五子棋如何獲得鼠標(biāo)點(diǎn)擊坐標(biāo)

    python 五子棋如何獲得鼠標(biāo)點(diǎn)擊坐標(biāo)

    這篇文章主要介紹了python 五子棋如何獲得鼠標(biāo)點(diǎn)擊坐標(biāo),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • kali最新國(guó)內(nèi)更新源sources

    kali最新國(guó)內(nèi)更新源sources

    這篇文章主要介紹了kali最新國(guó)內(nèi)更新源sources的相關(guān)資料,需要的朋友可以參考下
    2023-03-03
  • Python_查看sqlite3表結(jié)構(gòu),查詢語(yǔ)句的示例代碼

    Python_查看sqlite3表結(jié)構(gòu),查詢語(yǔ)句的示例代碼

    今天小編就為大家分享一篇Python_查看sqlite3表結(jié)構(gòu),查詢語(yǔ)句的示例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-07-07
  • Python?tkinter庫(kù)繪圖實(shí)例分享

    Python?tkinter庫(kù)繪圖實(shí)例分享

    這篇文章主要給大家分享了Python?tkinter庫(kù)繪圖實(shí)例,主要分享實(shí)例有小房子繪制、彩色氣泡動(dòng)畫繪制內(nèi)容,需要的小伙伴可以參考一下,希望對(duì)你的學(xué)習(xí)有所幫助
    2022-04-04
  • Python實(shí)現(xiàn)圖像和辦公文檔處理的方法和技巧

    Python實(shí)現(xiàn)圖像和辦公文檔處理的方法和技巧

    本文介紹了Python實(shí)現(xiàn)圖像和辦公文檔處理的方法和技巧,包括使用Pillow庫(kù)處理圖像、使用OpenCV庫(kù)進(jìn)行圖像識(shí)別和處理、使用PyPDF2庫(kù)處理PDF文檔、使用docx和xlwt庫(kù)處理Word和Excel文檔等,幫助讀者更好地掌握Python在圖像和辦公文檔處理方面的應(yīng)用
    2023-05-05

最新評(píng)論

辽阳县| 永嘉县| 石嘴山市| 江西省| 革吉县| 宜兰市| 久治县| 洛南县| 彭山县| 乐陵市| 信阳市| 嘉兴市| 共和县| 惠东县| 岱山县| 虎林市| 呼伦贝尔市| 柳州市| 阿城市| 牙克石市| 鄂伦春自治旗| 淳安县| 恭城| 龙陵县| 资源县| 涞源县| 游戏| 郎溪县| 威宁| 宣城市| 苍溪县| 望江县| 衡山县| 浪卡子县| 临江市| 桃江县| 丰宁| 青阳县| 宜都市| 宁强县| 牡丹江市|