tensorflow基本操作小白快速构建线性回归和分类模型

目录
  • tensorflow是非常强的工具,生态庞大
    • tensorflow提供了Keras的分支
    • Define tensor constants.
    • Linear Regression
  • 分类模型
    • 本例使用MNIST手写数字
      • Model prediction: 7
      • Model prediction: 2
      • Model prediction: 1
      • Model prediction: 0
      • Model prediction: 4

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.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快速构建线性回归模型,这里不使用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 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)
# 预测前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快速构建线性回归和分类模型的资料请关注我们其它相关文章!

(0)

相关推荐

  • Tensorflow与RNN、双向LSTM等的踩坑记录及解决

    1.tensorflow(不定长)文本序列读取与解析 tensorflow读取csv时需要指定各列的数据类型. 但是对于RNN这种接受序列输入的模型来说,一条序列的长度是不固定.这时如果使用csv存储序列数据,应当首先将特征序列拼接成一列. 例如两条数据序列,第一项是标签,之后是特征序列 [0, 1.1, 1.2, 2.3] 转换成 [0, '1.1_1.2_2.3'] [1, 1.0, 2.5, 1.6, 3.2, 4.5] 转换成 [1, '1.0_2.5_1.6_3.2_4.5'] 这样每

  • TensorFlow中tf.batch_matmul()的用法

    TensorFlow中tf.batch_matmul()用法 如果有两个三阶张量,size分别为 a.shape = [100, 3, 4] b.shape = [100, 4, 5] c = tf.batch_matmul(a, b) 则c.shape = [100, 3, 5] //将每一对 3x4 的矩阵与 4x5 的矩阵分别相乘.batch_size不变 100为张量的batch_size.剩下的两个维度为数据的维度. 不过新版的tensorflow已经移除了上面的函数,使用时换为tf.

  • 教你使用TensorFlow2识别验证码

    验证码是根据随机字符生成一幅图片,然后在图片中加入干扰象素,用户必须手动填入,防止有人利用机器人自动批量注册.灌水.发垃圾广告等等 . 数据集来源:https://www.kaggle.com/fournierp/captcha-version-2-images 图片是5个字母的单词,可以包含数字.这些图像应用了噪声(模糊和一条线).它们是200 x 50 PNG.我们的任务是尝试制作光学字符识别算法的模型. 在数据集中存在的验证码png图片,对应的标签就是图片的名字. import os im

  • tensorflow中的数据类型dtype用法说明

    Tensorflow中,主要有以下几种数据类型(dtype),在旧版本中,不用加tf也能使用. 有符号整型 tf.int8:8位整数. tf.int16:16位整数. tf.int32:32位整数. tf.int64:64位整数. 无符号整型 tf.uint8:8位无符号整数. tf.uint16:16位无符号整数. 浮点型 tf.float16:16位浮点数. tf.float32:32位浮点数. tf.float64:64位浮点数. tf.double:等同于tf.float64. 字符串型

  • pytorch_pretrained_bert如何将tensorflow模型转化为pytorch模型

    pytorch_pretrained_bert将tensorflow模型转化为pytorch模型 BERT仓库里的模型是TensorFlow版本的,需要进行相应的转换才能在pytorch中使用 在Google BERT仓库里下载需要的模型,这里使用的是中文预训练模型(chinese_L-12_H-768_A_12) 下载chinese_L-12_H-768_A-12.zip后解压,里面有5个文件 chinese_L-12_H-768_A-12.zip后解压,里面有5个文件 bert_config

  • tensorflow基本操作小白快速构建线性回归和分类模型

    目录 tensorflow是非常强的工具,生态庞大 tensorflow提供了Keras的分支 Define tensor constants. Linear Regression 分类模型 本例使用MNIST手写数字 Model prediction: 7 Model prediction: 2 Model prediction: 1 Model prediction: 0 Model prediction: 4 TF 目前发布2.5 版本,之前阅读1.X官方文档,最近查看2.X的文档. te

  • 教你使用vue-cli快速构建的小说阅读器

    项目介绍 主要页面 1.首页home.vue分类展示书籍,幻灯片展示热门推荐 2.搜索search.vue,上拉加载更多 3.书籍详情book.vue加入书架.立即阅读,展示评论,同类书籍推荐 4.书籍内容read.vue,获取目录,存储翻阅的章节位置, 5.书架bookrack.vue,获取加入书架的书单 技术栈 vue.vue-cli.axios.vue-router.vuex.localStorege 入口页面app.vue 分成底部导航 跟 主视图容器 router-view 首页tab

  • 详解vue-cli快速构建项目以及引入bootstrap、jq

    vue-cli脚手架工具快速构建项目架构: ..首先默认了有已经安装了node... npm install -g vue-cli                   全局安装vue-cli vue init webpack cnm                  生成项目名为cnm的的项目模板,cnm自定义 npm install                                   到cnm文件夹中打开Git bash或者命令窗口初始化安装依赖 此时文件夹目录应该是这样 然后

  • 使用Spring Boot快速构建基于SQLite数据源的应用

    为了提供一个单包易部署的服务器应用,考虑使用Spring Boot,因为其集成了Apache Tomcat,易于运行,免去绝大部分了服务器配置的步骤. 项目初始化 首先从mvn archetype:generate中选择 com.github.mkspcd:simple-webapp(或其他webapp模版) 模版生成项目结构. 更多关于maven请移步Maven - Users Centre 在pom.xml中添加parent来获取Spring Boot所需的最小依赖. <project xm

  • ASP.NET MVC Admin主页快速构建

    前言 后台开发人员一般不喜欢调样式,搞半天样式出不来,还要考虑各种浏览器兼容,费心费力不讨好,还好互联网时代有大量的资源共享,避免我们从零开始,现在就来看怎么快速构建一个ASP.NETMVC后台管理admin主页的方法,先看一看最终的效果! 第一步:选择一个admin模板 互联网时代就是资源共享的时代,网上各种前端模板,这里主要是说明怎么把模板整合到我们的ASP.NETMVC项目中,至于模板大家可以自己去选择喜欢的,这里我们选择这个清爽版的AircraftAdmin,首先看看AircraftAd

  • 详解如何利用docker快速构建MySQL主从复制环境

    在学习MySQL的过程中,常常会测试各种参数的作用.这时候,就需要快速构建出MySQL实例,甚至主从. 考虑如下场景: 譬如我想测试mysqldump在指定--single-transaction参数的情况下,对于myisam表的影响. 本来想在现成的测试环境中进行,但测试环境中,有大量的数据,执行mysqldump进行全备,产生的SQL文件,很难基于表进行搜索. 这个时候,就特别渴望能有一套干净的实例进行测试. 此刻,快速构建能力就显得尤为必要,很多童鞋可能会问,通过脚本不就能实现么?为什么要

  • vue-cli如何快速构建vue项目

    vue-cli 是vue.js的脚手架,用于自动生成vue.js模板工程的. 1.安装vue-cli 使用npm全局安装vue-cli(前提是已经安装了nodejs,否则连npm都用不了) $ npm install -g vue-cli 2.创建自己的工作空间 $ vue init webpack vuetest 3.项目信息 命令输入后,会进入安装阶段,需要用户输入一些信息 Project name (vuetest) 项目名称,可以自己指定,也可直接回车,按照括号中默认名字(注意这里的名字

  • 利用React-router+Webpack快速构建react程序

    本文主要介绍的是使用React-router和Webpack如何快速构建一个react程序,下面话不多说,感兴趣的可以一起学习学习. 初始化项目 我们先创建个空文件夹,然后初始化 package.json ,填写一些基本信息. $ npm init 接下来我们开始安装依赖项,我的 package.json 的依赖项如下 "devDependencies": { "babel": "^5.5.6", "babel-core":

  • 详解vue-cli快速构建vue应用并实现webpack打包

    Vue是什么,是一套构建用户界面的渐进式框架(官网解释),什么叫渐进式框架呢,简单回答就是主张最少,这些概念只能自己去看,自己去理解,一千个读者一千个哈姆雷特,不过多的解释.Vue官方文档很全面的. Vue两大核心思想,组件化和数据驱动,组件化就是将一个整体合理拆分为一个一个小块(组件),组件可重复使用,数据驱动是前端的未来发展方向,释放了对DOM的操作,让DOM随着数据的变化自然而然的变化(尤神原话),不必过多的关注DOM,只需要将数据组织好即可. 一.什么是vue-cli vue-cli是由

  • 【spring-boot】快速构建spring-boot微框架的方法

    spring-boot是一个快速构建环境的一套框架,其设计理念是尽可能的减少xml的配置,用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 废话不多说,关于spring-boot是什么具体请百度. 官网:http://projects.spring.io/spring-boot 1. spring-boot是一个mavan项目,所以其使用的jar包全部是通过maven管理,当然,使用maven也是非常方便的. 首先上我的

随机推荐