@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)的一维数组。

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):# 应用softmax函数将logit标准化为概率分布out = tf.nn.softmax(tf.matmul(x, W) + b)return out# 交叉熵损失函数
def cross_entropy(y_pred, y_true):# 将标签编码为一个one_hot向量y_true = tf.one_hot(y_true, depth=num_classes)# 剪裁预测值避免错误y_pred = tf.clip_by_value(y_pred, 1e-9, 1)# 计算交叉熵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))# 随机梯度下降优化器
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 brun_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)
# 预测前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教程】一、tensorflow基本操作、快速构建线性回归和分类模型相关推荐

  1. 【小白学习PyTorch教程】十六、在多标签分类任务上 微调BERT模型

    @Author:Runsen BERT模型在NLP各项任务中大杀四方,那么我们如何使用这一利器来为我们日常的NLP任务来服务呢?首先介绍使用BERT做文本多标签分类任务. 文本多标签分类是常见的NLP ...

  2. 【小白学习keras教程】九、keras 使用GPU和Callbacks模型保存

    @Author:Runsen GPU 在gpu上训练使训练神经网络比在cpu上运行快得多 Keras支持使用Tensorflow和Theano后端对gpu进行培训 文档: https://keras. ...

  3. 云计算学习路线教程大纲课堂笔记:构建企业级WIKI及工单系统

    云计算学习路线教程大纲课堂笔记:构建企业级WIKI及工单系统: -Author: bavdu -Email: bavduer@163.com -Github: https://github.com/b ...

  4. 【Insights直播】3D建模服务,快速构建高质量3D模型

    2021年7月15日,HMS Core 6.0面向全球开发者正式上线.华为在HMS Core 6.0中,为开发者开放了一个全新的服务--3D建模服务(3D Modeling Kit),为应用开发者提供 ...

  5. tensorflow从入门到精通100讲(七)-TensorFlow房价预估使用Keras快速构建模型

    前言 这篇文章承接上一篇tensorflow从入门到精通100讲(二)-IRIS数据集应用实战 https://wenyusuran.blog.csdn.net/article/details/107 ...

  6. 【小白学习PyTorch教程】八、使用图像数据增强手段,提升CIFAR-10 数据集精确度...

    「@Author:Runsen」 上次基于CIFAR-10 数据集,使用PyTorch构建图像分类模型的精确度是60%,对于如何提升精确度,方法就是常见的transforms图像数据增强手段. imp ...

  7. Caffe、TensorFlow、MXnet三个开源库对比+主流分类模型对比

    库名称 开发语言 支持接口 安装难度(ubuntu) 文档风格 示例 支持模型 上手难易 Caffe c++/cuda c++/python/matlab *** * *** CNN ** MXNet ...

  8. R 语言快速构建信用评分卡模型---scorecard包

    前言 R 语言快速构建机器学习,基于某大佬的scorecard包. # github主页 - R版: http://github.com/shichenxie/scorecard # 加载[data. ...

  9. TensorFlow和深度学习入门教程(TensorFlow and deep learning without a P

    前言 上月导师在组会上交我们用tensorflow写深度学习和卷积神经网络,并把其PPT的参考学习资料给了我们, 这是codelabs上的教程:<TensorFlow and deep lear ...

最新文章

  1. csgo怎么控制电脑玩家_图文详解电脑怎么发起远程控制
  2. Chapter 8(查找)
  3. HDU 1052 Tian Ji -- The Horse Racing
  4. 2022-01-01
  5. python实现新闻网站_如何用 100 行 Python 代码实现新闻爬虫?这样可算成功?
  6. IE浏览器样式表限制
  7. JavaScript 函数(方法)的封装技巧要领及其重要性
  8. macOS Monterey中最新的「通用控制」是什么?苹果设备如何使用通用控制功能!
  9. pythoncharm怎么保存代码_pycharm怎么保存代码
  10. 相见恨晚的英语学习方法!百万人读过!
  11. Snagit 2019 for Mac如何合并图像+安装方法详解
  12. VS离线安装NuGet包
  13. matlab学霸表白公式,一个理科学霸的表白:数学公式的超酷表白
  14. python如何模拟键盘输入_Python模拟键盘输入和鼠标操作
  15. 通过蒲公英让两台异地电脑组建局域网
  16. 关于tensorflow的报错NodeDef mentions attr ‘xxx‘ not in Op的解决方案和产生原因
  17. 从零到一搭建基础架构(2)-如何构建基础架构模块划分
  18. python学习:break用法详解
  19. 【前端项目问题】draw抽屉的实现(Vue3)
  20. linux服务器引导分区,Linux系统的引导过程和磁盘分区信息

热门文章

  1. echarts柱状图间距调整_Excel每天学个统计图(1)-折线柱状图
  2. zemax操作数_ZEMAX与像差理论:二级光谱的ZEMAX描述与详解
  3. C51 汇编 双层循环延时代码
  4. 风控策略和模型的区别_风控模型之产品赢利分析与策略优化
  5. SCARA四轴机器人丝杆花键_花键丝杆一体轴型SCARA机器人的制作方法
  6. Cracer渗透-下载安装软件
  7. ES6学习笔记(十六)async函数
  8. 简练软考知识点整理-规划风险应对
  9. 【剑指offer】21、调整数组顺序使奇数在偶数前面
  10. CodeForces509F Progress Monitoring