【小白学习tensorflow教程】一、tensorflow基本操作、快速构建线性回归和分类模型
@Author:Runsen
TF 目前發布2.5 版本,之前閱讀1.X官方文檔,最近查看2.X的文檔。tensorflow是非常強的工具,生態龐大。
tensorflow提供了Keras的分支,這里不再提供Keras相關順序模型教程。
關于環境:ubuntu的 GPU,需要cuda和nvcc
不會安裝:查看
- 完整的Ubuntu18.04深度學習GPU環境配置,英偉達顯卡驅動安裝、cuda9.0安裝、cudnn的安裝、anaconda安裝
不安裝,直接翻墻用colab
測試GPU
>>> from tensorflow.python.client import device_lib >>> device_lib.list_local_devices()這是意思是掛了一個顯卡
具體查看官方文檔:https://www.tensorflow.org/install
服務器跑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)# 通過numpy返回數值 和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.16666666666666666mean = 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快速構建線性回歸模型,這里不使用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# 權重和偏差,隨機初始化。 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))# 隨機梯度下降優化器。 optimizer = tf.optimizers.SGD(learning_rate)# 優化過程。 def run_optimization():# 將計算包在GradientTape中,以便自動區分。with tf.GradientTape() as g:pred = linear_regression(X)loss = mean_square(pred, Y)# 計算梯度。gradients = g.gradient(loss, [W, b])# 按照梯度更新W和b。optimizer.apply_gradients(zip(gradients, [W, b]))#按給定的步數進行訓練。 for step in range(1, training_steps + 1):# 運行優化以更新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手寫數字。數據集包含60000個訓練示例和10000個測試示例。這些數字已經過大小標準化,并在一個固定大小的圖像(28x28像素)中居中,值從0到255。
在本例中,每個圖像將轉換為float32,標準化為[0,1],并展平為784個特征(28×28)的一維數組。
Test Accuracy: 0.892300009727478
import matplotlib.pyplot as plt n_images = 5 test_images = x_test[:n_images] predictions = logistic_regression(test_images) # 預測前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
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的【小白学习tensorflow教程】一、tensorflow基本操作、快速构建线性回归和分类模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工资奖金和工资有什么区别 看看你的属
- 下一篇: 怎么查询银行卡开户行 可以通过手机银行查