tensorflow入门_TensorFlow法律和统计入门

tensorflow入门

by Daniel Deutsch

由Daniel Deutsch

TensorFlow法律和统计入门 (Get started with TensorFlow on law and statistics)

  • What this is about

    这是关于什么的

  • What we will use

    我们将使用什么

  • Get started

    开始吧

  • Shell commands for installing everything you need

    用于安装所需内容的Shell命令

  • Get data and draw a plot

    获取数据并绘制图

  • Import everything you need

    导入您需要的一切

  • Create and plot some numbers

    创建并绘制一些数字

  • Build a TensorFlow model

    建立一个TensorFlow模型

  • Prepare data

    准备数据

  • Set up variables and operations for TensorFlow

    为TensorFlow设置变量和操作

  • Start the calculations with a TensorFlow session

    从TensorFlow会话开始计算

  • Visualize the result and process

    可视化结果和过程

这是关于什么的 (What this is about)

As I am exploring TensorFlow, I wanted build a beginner example and document it. This is a very basic example that uses a gradient descent optimization to train parameters with TensorFlow. The key variables are evidence and convictions. It will illustrate:

在探索TensorFlow时,我想构建一个初学者示例并记录下来。 这是一个非常基本的示例,该示例使用梯度下降优化来使用TensorFlow训练参数。 关键变量是证据信念 。 它将说明:

  • how the number of convictions depend upon the number of pieces of evidence

    定罪的数量如何取决于证据的数量
  • how to predict the number of convictions using a regression model

    如何使用回归模型预测定罪人数

The Python file is in my repository on GitHub.

Python文件位于我在GitHub上的存储库中 。

See the article in better formatting on GitHub.

在GitHub上以更好的格式查看文章。

我们将使用什么 (What we will use)

1. TensorFlow(as tf) (1. TensorFlow (as tf))

Tensors

张量

  • tf.placeholders

    tf.placeholders
  • tf.Variables

    tf。变量

Helper function

辅助功能

  • tf.global_variables_initializer

    tf.global_variables_initializer

Math Operations

数学运算

  • tf.add

    tf.add
  • tf.multiply

    tf.multiply
  • tf.reduce_sum

    tf.reduce_sum
  • tf.pow

    tf.pow

Building a graph

建立图

  • tf.train.GradientDescentOptimizer

    tf.train.GradientDescentOptimizer

Session

届会

  • tf.Session

    会话

2.脾气暴躁(as np) (2. Numpy (as np))

  • np.random.seed

    np.random.seed
  • np.random.zeros

    np.random.zeros
  • np.random.randint

    np.random.randint
  • np.random.randn

    np.random.randn
  • np.random.asanyarray

    np.random.asanyarray

3. Matplotlib (3. Matplotlib)

4.数学 (4. Math)

入门 (Getting started)

Install TensorFlow with virtualenv. See the guide on the TF website.

使用virtualenv安装TensorFlow。 请参阅TF网站上的指南 。

用于安装所需内容的Shell命令 (Shell commands for installing everything you need)

sudo easy_install pip
pip3 install --upgrade virtualenv
virtualenv --system-site-packages <targetDirectory>
cd <targetDirectory>
source ./bin/activate
easy_install -U pip3
pip3 install tensorflow
pip3 install matplotlib

获取数据并绘制图 (Get data and draw a plot)

导入您需要的一切 (Import everything you need)

import tensorflow as tfimport numpy as npimport mathimport matplotlibmatplotlib.use('TkAgg')import matplotlib.pyplot as pltimport matplotlib.animation as animation

As you can see I am using the “TkAgg” backend from matplotlib. This allows me to debug with my vsCode and macOS setup without any further complicated installments.

如您所见,我正在使用matplotlib中的“ TkAgg”后端。 这使我可以使用vsCode和macOS设置进行调试,而无需进行任何其他复杂的安装。

创建并绘制一些数字 (Create and plot some numbers)

# Generate evidence numbers between 10 and 20# Generate a number of convictions from the evidence with a random noise addednp.random.seed(42)sampleSize = 200numEvid = np.random.randint(low=10, high=50, size=sampleSize)numConvict = numEvid * 10 + np.random.randint(low=200, high=400, size=sampleSize)
# Plot the data to get a feelingplt.title("Number of convictions based on evidence")plt.plot(numEvid, numConvict, "bx")plt.xlabel("Number of Evidence")plt.ylabel("Number of Convictions")plt.show(block=False)  # Use the keyword 'block' to override the blocking behavior

I am creating random values for the evidence. The number of convictions depends on the amount (number) of evidence, with random noise. Of course those numbers are made up, but they are just used to prove a point.

我正在为证据创建随机值。 定罪的数量取决于证据的数量(数量)以及随机噪声。 当然,这些数字是虚构的,但是它们只是用来证明这一点。

建立一个TensorFlow模型 (Build a TensorFlow model)

To build a basic machine learning model, we need to prepare the data. Then we make predictions, measure the loss, and optimize by minimizing the loss.

要构建基本的机器学习模型,我们需要准备数据。 然后我们进行预测,测量损失,并通过最小化损失进行优化。

准备数据 (Prepare data)

# create a function for normalizing values# use 70% of the data for training (the remaining 30% shall be used for testing)def normalize(array):    return (array - array.mean()) / array.std()
numTrain = math.floor(sampleSize * 0.7)
# convert list to an array and normalize arraystrainEvid = np.asanyarray(numEvid[:numTrain])trainConvict = np.asanyarray(numConvict[:numTrain])trainEvidNorm = normalize(trainEvid)trainConvictdNorm = normalize(trainConvict)
testEvid = np.asanyarray(numEvid[numTrain:])testConvict = np.asanyarray(numConvict[numTrain:])testEvidNorm = normalize(testEvid)testConvictdNorm = normalize(testConvict)

We are splitting the data into training and testing portions. Afterwards, we normalize the values, as this is necessary for machine learning projects. (See also “feature scaling”.)

我们将数据分为训练和测试部分。 之后,我们将值标准化,因为这对于机器学习项目是必需的。 (另请参阅“ 功能缩放 ”。)

为TensorFlow设置变量和操作 (Set up variables and operations for TensorFlow)

# define placeholders  and variablestfEvid = tf.placeholder(tf.float32, name="Evid")tfConvict = tf.placeholder(tf.float32, name="Convict")tfEvidFactor = tf.Variable(np.random.randn(), name="EvidFactor")tfConvictOffset = tf.Variable(np.random.randn(), name="ConvictOffset")
# define the operation for predicting the conviction based on evidence by adding both values# define a loss function (mean squared error)tfPredict = tf.add(tf.multiply(tfEvidFactor, tfEvid), tfConvictOffset)tfCost = tf.reduce_sum(tf.pow(tfPredict - tfConvict, 2)) / (2 * numTrain)
# set a learning rate and a gradient descent optimizerlearningRate = 0.1gradDesc = tf.train.GradientDescentOptimizer(learningRate).minimize(tfCost)

The pragmatic differences between tf.placeholder and tf.Variable are:

tf.placeholdertf.Variable之间的实用差异是:

  • placeholders are allocated storage for data, and initial values are not required

    占位符被分配用于数据存储,并且不需要初始值
  • variables are used for parameters to learn, and initial values are required. The values can be derived from training.

    变量用于学习参数,并且需要初始值。 这些值可以从训练中得出。

I use the TensorFlow operators precisely as tf.add(…), because it is pretty clear what library is used for the calculation. This is instead of using the + operator.

我将TensorFlow运算符精确地用作tf.add(…) ,因为很清楚使用哪个库进行计算。 这不是使用+运算符。

从TensorFlow会话开始计算 (Start the calculations with a TensorFlow session)

# initialize variablesinit = tf.global_variables_initializer()
with tf.Session() as sess:    sess.run(init)
# set up iteration parameters    displayEvery = 2    numTrainingSteps = 50
# Calculate the number of lines to animation    # define variables for updating during animation    numPlotsAnim = math.floor(numTrainingSteps / displayEvery)    evidFactorAnim = np.zeros(numPlotsAnim)    convictOffsetAnim = np.zeros(numPlotsAnim)    plotIndex = 0
# iterate through the training data    for i in range(numTrainingSteps):
# ======== Start training by running the session and feeding the gradDesc        for (x, y) in zip(trainEvidNorm, trainConvictdNorm):            sess.run(gradDesc, feed_dict={tfEvid: x, tfConvict: y})
# Print status of learning        if (i + 1) % displayEvery == 0:            cost = sess.run(                tfCost, feed_dict={tfEvid: trainEvidNorm, tfConvict: trainConvictdNorm}            )            print(                "iteration #:",                "%04d" % (i + 1),                "cost=",                "{:.9f}".format(cost),                "evidFactor=",                sess.run(tfEvidFactor),                "convictOffset=",                sess.run(tfConvictOffset),            )
# store the result of each step in the animation variables            evidFactorAnim[plotIndex] = sess.run(tfEvidFactor)            convictOffsetAnim[plotIndex] = sess.run(tfConvictOffset)            plotIndex += 1
# log the optimized result    print("Optimized!")    trainingCost = sess.run(        tfCost, feed_dict={tfEvid: trainEvidNorm, tfConvict: trainConvictdNorm}    )    print(        "Trained cost=",        trainingCost,        "evidFactor=",        sess.run(tfEvidFactor),        "convictOffset=",        sess.run(tfConvictOffset),        "\n",    )

Now we come to the actual training and the most interesting part.

现在我们来进行实际的培训和最有趣的部分。

The graph is now executed in a tf.Session. I am using "feeding" as it lets you inject data into any Tensor in a computation graph. You can see more on reading data here.

该图现在在tf.Session执行。 我正在使用“馈送”,因为它可以让您将数据注入计算图中的任何张量。 您可以在此处查看有关读取数据的更多信息。

tf.Session() is used to create a session that is automatically closed on exiting the context. The session also closes when an uncaught exception is raised.

tf.Session()用于创建一个会话,该会话在退出上下文时自动关闭。 当引发未捕获的异常时,会话也会关闭。

The tf.Session.run method is the main mechanism for running a tf.Operation or evaluating a tf.Tensor. You can pass one or more tf.Operation or tf.Tensor objects to tf.Session.run, and TensorFlow will execute the operations that are needed to compute the result.

tf.Session.run方法是运行tf.Operation或评估tf.Tensor的主要机制。 您可以将一个或多个tf.Operationtf.Tensor对象传递给tf.Session.run ,TensorFlow将执行计算结果所需的操作。

First, we are running the gradient descent training while feeding it the normalized training data. After that, we are calculating the the loss.

首先,我们在进行梯度下降训练的同时将其归一化训练数据。 之后,我们正在计算损失。

We are repeating this process until the improvements per step are very small. Keep in mind that the tf.Variables (the parameters) have been adapted throughout and now reflect an optimum.

我们将重复此过程,直到每个步骤的改进很小为止。 请记住,已经对tf.Variables (参数)进行了全面调整,现在反映了最优值。

可视化结果和过程 (Visualize the result and process)

# de-normalize variables to be plotable again    trainEvidMean = trainEvid.mean()    trainEvidStd = trainEvid.std()    trainConvictMean = trainConvict.mean()    trainConvictStd = trainConvict.std()    xNorm = trainEvidNorm * trainEvidStd + trainEvidMean    yNorm = (        sess.run(tfEvidFactor) * trainEvidNorm + sess.run(tfConvictOffset)    ) * trainConvictStd + trainConvictMean
# Plot the result graph    plt.figure()
plt.xlabel("Number of Evidence")    plt.ylabel("Number of Convictions")
plt.plot(trainEvid, trainConvict, "go", label="Training data")    plt.plot(testEvid, testConvict, "mo", label="Testing data")    plt.plot(xNorm, yNorm, label="Learned Regression")    plt.legend(loc="upper left")
plt.show()
# Plot an animated graph that shows the process of optimization    fig, ax = plt.subplots()    line, = ax.plot(numEvid, numConvict)
plt.rcParams["figure.figsize"] = (10, 8) # adding fixed size parameters to keep animation in scale    plt.title("Gradient Descent Fitting Regression Line")    plt.xlabel("Number of Evidence")    plt.ylabel("Number of Convictions")    plt.plot(trainEvid, trainConvict, "go", label="Training data")    plt.plot(testEvid, testConvict, "mo", label="Testing data")
# define an animation function that changes the ydata    def animate(i):        line.set_xdata(xNorm)        line.set_ydata(            (evidFactorAnim[i] * trainEvidNorm + convictOffsetAnim[i]) * trainConvictStd            + trainConvictMean        )        return (line,)
# Initialize the animation with zeros for y    def initAnim():        line.set_ydata(np.zeros(shape=numConvict.shape[0]))        return (line,)
# call the animation    ani = animation.FuncAnimation(        fig,        animate,        frames=np.arange(0, plotIndex),        init_func=initAnim,        interval=200,        blit=True,    )
plt.show()

To visualize the process, it is helpful to plot the result and maybe even the optimization process.

为了使过程可视化,对结果甚至优化过程进行绘图很有帮助。

Check out this Pluralsight course which helped me a lot to get started. :)

查看此Pluralsight课程 ,该课程对我有很多帮助。 :)

Thanks for reading my article! Feel free to leave any feedback!

感谢您阅读我的文章! 随时留下任何反馈!

Daniel is a LL.M. student in business law, working as a software engineer and organizer of tech related events in Vienna. His current personal learning efforts focus on machine learning.

丹尼尔(Daniel)是法学硕士。 商业法专业的学生,​​在维也纳担任软件工程师和技术相关活动的组织者。 他目前的个人学习重点是机器学习。

Connect on:

连接:

  • LinkedIn

    领英

  • Github

    Github

  • Medium

  • Twitter

    推特

  • Steemit

    Steemit

  • Hashnode

    哈希节点

翻译自: https://www.freecodecamp.org/news/tensorflow-starter-on-law-and-statistics-646072b93b5a/

tensorflow入门

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393725.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

centos7 nginx+php5.6+mysql安装与配置

安装与配置 php 56的安装 php的配置写在 php.ini&#xff0c;可在phpinfo()中查看 //查找已安装 yum list installed | grep php // php卸载 yum -y remove php56* yum remove httpd* php* 可用的资源&#xff1a;centos 安装php56nginx nginx php-fpm nginx安装 sudo rpm -Uv…

leetcode337. 打家劫舍 III(dfs)

在上次打劫完一条街道之后和一圈房屋后&#xff0c;小偷又发现了一个新的可行窃的地区。这个地区只有一个入口&#xff0c;我们称之为“根”。 除了“根”之外&#xff0c;每栋房子有且只有一个“父“房子与之相连。一番侦察之后&#xff0c;聪明的小偷意识到“这个地方的所有房…

c语言面试题东软,2012东软笔试题

1、下列变量定义错误的是&#xff24;int a;double b4.5;boolean btrue;float f9.8; (9.8f)2、65%32的值是 D 3%53219103、对于一个三位的正整数 n&#xff0c;取出它的十位数字k(k为整型)的表达式是k n / 10 % 10k ( n - n / 100 * 100 )k n % 10k n / 104、下列语句序列执…

matlab肌电信号平滑滤波_MATLAB图像处理:43:用高斯平滑滤波器处理图像

本示例说明了如何使用imgaussfilt来对图像应用不同的高斯平滑滤波器。高斯平滑滤波器通常用于降低噪声。将图像读入工作区。I imread(cameraman.tif);使用各向同性的高斯平滑核增加标准偏差来过滤图像。高斯滤波器通常是各向同性的&#xff0c;也就是说&#xff0c;它们在两个…

Github 简明教程 - 添加远程库

现在的情景是&#xff0c;你已经在本地创建了一个Git仓库后&#xff0c;又想在GitHub创建一个Git仓库&#xff0c;并且让这两个仓库进行远程同步&#xff0c;这样&#xff0c;GitHub上的仓库既可以作为备份&#xff0c;又可以让其他人通过该仓库来协作&#xff0c;真是一举多得…

githooks_使用Githooks改善团队的开发工作流程

githooksby Daniel Deutsch由Daniel Deutsch 使用Githooks改善团队的开发工作流程 (Improve your team’s development workflow with Githooks) Every product that is developed by more than one programmer needs to have some guidelines to harmonize the workflow.由多…

分享AI有道干货 | 126 篇 AI 原创文章精选(ML、DL、资源、教程)

一年多来&#xff0c;公众号【AI有道】已经发布了 140 的原创文章了。内容涉及林轩田机器学习课程笔记、吴恩达 deeplearning.ai 课程笔记、机器学习、深度学习、笔试面试题、资源教程等等。值得一提的是每篇文章都是我用心整理的&#xff0c;编者一贯坚持使用通俗形象的语言给…

c语言qt生成dll与加载dll,Qt制作界面的DLL以及调用

1、将界面做成dll修改pro文件DEFINES WIDGETDLL_LIBRARYTEMPLATE lib修改头文件#if defined(WIDGETDLL_LIBRARY)# define WIDGETDLLSHARED_EXPORT Q_DECL_EXPORT#else# define WIDGETDLLSHARED_EXPORT Q_DECL_IMPORT#endifclass WIDGETDLLSHARED_EXPORT WidgetDll:public QWi…

leetcode1338. 数组大小减半(贪心算法)

给你一个整数数组 arr。你可以从中选出一个整数集合&#xff0c;并删除这些整数在数组中的每次出现。 返回 至少 能删除数组中的一半整数的整数集合的最小大小。 示例 1&#xff1a; 输入&#xff1a;arr [3,3,3,3,5,5,5,2,2,7] 输出&#xff1a;2 解释&#xff1a;选择 {3…

20162329 张旭升 2017 - 2018 《程序设计与数据结构》第五周总结

20162329 2017-2018-1 《程序设计与数据结构》第五周学习总结 教材学习内容总结 1.学习目标 了解集合的概念了解并使用抽象数据类型初步了解使用Java泛型学习栈这种数据结构用数组、链表实现栈2.学习内容 集合的概念&#xff1a; 集合是手机并组织其他对象的对象&#xff0c;他…

centos 安装trace_前期的准备工作-MacOS Mojave 10.14.3 下安装CentOS 7及Bochs 002

MacOS Mojave 10.14.3 下使用虚拟机安装CentOS 7 以及 Bochs 2.6.9CentOS 7.6.1810 系统下 安装Bochs 2.6.91 下载CentOS 7.6.1810网址为https://www.centos.org/遇到的问题安装后无法使用使用网络&#xff0c;最简单的解决方法就是增加一个新的网络适配器&#xff0c;使用Nat共…

js中的extend的用法及其JS中substring与substr的区别

1. JS中substring与substr的区别 之前在项目中用到substring方法&#xff0c;因为C#中也有字符串的截取方法Substring方法&#xff0c;当时也没有多想就误以为这两种方法的使用时一样的。这样就直接按照在C#中使用Substring的方式&#xff0c;直接在js中用了substring&#…

事件处理程序

转载于:https://www.cnblogs.com/ypx666/p/10869448.html

fis3 配置文件

1 代码: fis.match(*.less, {// fis-parser-less 插件进行解析parser: fis.plugin(less),// .less 文件后缀构建后被改成 .css 文件rExt: .css });// 配置配置文件&#xff0c;注意&#xff0c;清空所有的配置&#xff0c;只留下以下代码即可。 fis.match(*.{png,js,css}, {rel…

核心指导网络由任务编码器_如何在现实世界中与实际用户一起指导您的编码和编码生涯...

核心指导网络由任务编码器by Bob Berry由Bob Berry 如何在现实世界中与实际用户一起指导您的编码和编码生涯 (How to guide your coding and your coding career with real users, in the real world) Experience drives everything. It’s the basis of our reality. It’s a…

脉冲时间宽度c语言,基于AT89C52脉冲宽度测量仪的设计与实现

赵翠玉摘要&#xff1a;本文基于AT89C52的脉冲宽度测量仪的设计。该仪器测量结果采用了软件数字滤波&#xff0c;消除了测量中抖动问题&#xff0c;测量精度高、稳定性好&#xff0c;具有一定的实用性。关键词&#xff1a;AT89C52;测量仪;脉冲宽度中图分类号&#xff1a;TM935.…

leetcode1433. 检查一个字符串是否可以打破另一个字符串(贪心算法)

给你两个字符串 s1 和 s2 &#xff0c;它们长度相等&#xff0c;请你检查是否存在一个 s1 的排列可以打破 s2 的一个排列&#xff0c;或者是否存在一个 s2 的排列可以打破 s1 的一个排列。 字符串 x 可以打破字符串 y &#xff08;两者长度都为 n &#xff09;需满足对于所有 …

cordova 人脸识别_html5与EmguCV前后端实现——人脸识别篇(一)

上个月因为出差的关系&#xff0c;断更了很久&#xff0c;为了补偿大家长久的等待&#xff0c;送上一个新的系列&#xff0c;之前几个系列也会抽空继续更新。大概半年多前吧&#xff0c;因为工作需要&#xff0c;我开始研究图像识别技术。OpenCV在这方面已经有了很多技术积累&a…

[转载] mysql 索引中的USING BTREE 的意义

索引是在存储引擎中实现的&#xff0c;因此每种存储引擎的索引都不一定完全相同&#xff0c;并且每种存储引擎也不一定支持所有索引类型。 根据存储引擎定义每个表的最大索引数和最大索引长度。所有存储引擎支持每个表至少16个索引&#xff0c;总索引长度至少为256字节。 大多数…

git-命令

git config --global user.email “邮箱” git config --global user.name ”用户名” git init           初始化 忽略指定文件 echo "temp/" >> .gitignore echo "private_key" >> .gitginore 状态 git status 添加 git add …