<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Law - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Law - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 25 Jul 2026 22:29:22 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/law/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Get started with TensorFlow on law and statistics ]]>
                </title>
                <description>
                    <![CDATA[ By Daniel Deutsch What this is about What we will use Get started Shell commands for installing everything you need Get data and draw a plot Import everything you need Create and plot some numbers Build a TensorFlow model Prepare data Set up variabl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/tensorflow-starter-on-law-and-statistics-646072b93b5a/</link>
                <guid isPermaLink="false">66c3605e56e6b06442afd883</guid>
                
                    <category>
                        <![CDATA[ Law ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 06 Jul 2018 07:34:40 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*xqr3ulVKnBwueUVk" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Daniel Deutsch</p>
<ul>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#what-this-is-about">What this is about</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#what-we-will-use">What we will use</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#get-started">Get started</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#shell-commands-for-installing-everything-you-need">Shell commands for installing everything you need</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#get-data-and-draw-a-plot">Get data and draw a plot</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#import-everything-you-need">Import everything you need</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#create-and-plot-some-numbers">Create and plot some numbers</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#build-a-tensorflow-model">Build a TensorFlow model</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#prepare-data">Prepare data</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#set-up-variables-and-operations-for-tensorflow">Set up variables and operations for TensorFlow</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#start-the-calculations-with-a-tensorflow-session">Start the calculations with a TensorFlow session</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md#visualize-the-result-and-process">Visualize the result and process</a></li>
</ul>
<h3 id="heading-what-this-is-about">What this is about</h3>
<p>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 <strong>evidence</strong> and <strong>convictions</strong>. It will illustrate:</p>
<ul>
<li>how the number of convictions depend upon the number of pieces of evidence</li>
<li>how to predict the number of convictions using a regression model</li>
</ul>
<p>The Python file is in my <a target="_blank" href="https://github.com/Createdd/lawstatistics/blob/feature/ReferenceBranchForArticle/evidencePrediction.py">repository on GitHub</a>.</p>
<p><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/LawStatisticsExample.md">See the article in better formatting on GitHub.</a></p>
<h3 id="heading-what-we-will-use">What we will use</h3>
<h4 id="heading-1-tensorflow-as-tf">1. TensorFlow (as tf)</h4>
<p><a target="_blank" href="https://www.tensorflow.org/programmers_guide/tensors">Tensors</a></p>
<ul>
<li>tf.placeholders</li>
<li>tf.Variables</li>
</ul>
<p><a target="_blank" href="https://www.tensorflow.org/programmers_guide/variables#initializing_variables">Helper function</a></p>
<ul>
<li>tf.global_variables_initializer</li>
</ul>
<p><a target="_blank" href="https://www.tensorflow.org/api_guides/python/math_ops">Math Operations</a></p>
<ul>
<li>tf.add</li>
<li>tf.multiply</li>
<li>tf.reduce_sum</li>
<li>tf.pow</li>
</ul>
<p><a target="_blank" href="https://www.tensorflow.org/programmers_guide/graphs#building_a_tfgraph">Building a graph</a></p>
<ul>
<li>tf.train.GradientDescentOptimizer</li>
</ul>
<p><a target="_blank" href="https://www.tensorflow.org/programmers_guide/graphs#executing_a_graph_in_a_tfsession">Session</a></p>
<ul>
<li>tf.Session</li>
</ul>
<h4 id="heading-2-numpy-as-np">2. Numpy (as np)</h4>
<ul>
<li>np.random.seed</li>
<li>np.random.zeros</li>
<li>np.random.randint</li>
<li>np.random.randn</li>
<li>np.random.asanyarray</li>
</ul>
<h4 id="heading-3-matplotlib">3. Matplotlib</h4>
<h4 id="heading-4-math">4. Math</h4>
<h3 id="heading-getting-started">Getting started</h3>
<p>Install TensorFlow with virtualenv. See the <a target="_blank" href="https://www.tensorflow.org/install/install_mac">guide</a> on the TF website.</p>
<h4 id="heading-shell-commands-for-installing-everything-you-need">Shell commands for installing everything you need</h4>
<pre><code>sudo easy_install pip
</code></pre><pre><code>pip3 install --upgrade virtualenv
</code></pre><pre><code>virtualenv --system-site-packages &lt;targetDirectory&gt;
</code></pre><pre><code>cd &lt;targetDirectory&gt;
</code></pre><pre><code>source ./bin/activate
</code></pre><pre><code>easy_install -U pip3
</code></pre><pre><code>pip3 install tensorflow
</code></pre><pre><code>pip3 install matplotlib
</code></pre><h3 id="heading-get-data-and-draw-a-plot">Get data and draw a plot</h3>
<h4 id="heading-import-everything-you-need">Import everything you need</h4>
<pre><code><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tfimport numpy <span class="hljs-keyword">as</span> npimport mathimport matplotlibmatplotlib.use(<span class="hljs-string">'TkAgg'</span>)<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> pltimport matplotlib.animation <span class="hljs-keyword">as</span> animation
</code></pre><p>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.</p>
<h4 id="heading-create-and-plot-some-numbers">Create and plot some numbers</h4>
<pre><code># Generate evidence numbers between <span class="hljs-number">10</span> and <span class="hljs-number">20</span># Generate a number <span class="hljs-keyword">of</span> convictions <span class="hljs-keyword">from</span> the evidence <span class="hljs-keyword">with</span> a random noise addednp.random.seed(<span class="hljs-number">42</span>)sampleSize = <span class="hljs-number">200n</span>umEvid = np.random.randint(low=<span class="hljs-number">10</span>, high=<span class="hljs-number">50</span>, size=sampleSize)numConvict = numEvid * <span class="hljs-number">10</span> + np.random.randint(low=<span class="hljs-number">200</span>, high=<span class="hljs-number">400</span>, size=sampleSize)
</code></pre><pre><code># Plot the data to get a feelingplt.title(<span class="hljs-string">"Number of convictions based on evidence"</span>)plt.plot(numEvid, numConvict, <span class="hljs-string">"bx"</span>)plt.xlabel(<span class="hljs-string">"Number of Evidence"</span>)plt.ylabel(<span class="hljs-string">"Number of Convictions"</span>)plt.show(block=False)  # Use the keyword <span class="hljs-string">'block'</span> to override the blocking behavior
</code></pre><p>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.</p>
<h3 id="heading-build-a-tensorflow-model">Build a TensorFlow model</h3>
<p>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.</p>
<h4 id="heading-prepare-data">Prepare data</h4>
<pre><code># create a <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">for</span> <span class="hljs-title">normalizing</span> <span class="hljs-title">values</span># <span class="hljs-title">use</span> 70% <span class="hljs-title">of</span> <span class="hljs-title">the</span> <span class="hljs-title">data</span> <span class="hljs-title">for</span> <span class="hljs-title">training</span> (<span class="hljs-params">the remaining <span class="hljs-number">30</span>% shall be used for testing</span>)<span class="hljs-title">def</span> <span class="hljs-title">normalize</span>(<span class="hljs-params">array</span>):    <span class="hljs-title">return</span> (<span class="hljs-params">array - array.mean()</span>) / <span class="hljs-title">array</span>.<span class="hljs-title">std</span>(<span class="hljs-params"></span>)</span>
</code></pre><pre><code>numTrain = math.floor(sampleSize * <span class="hljs-number">0.7</span>)
</code></pre><pre><code># convert list to an array and normalize arraystrainEvid = np.asanyarray(numEvid[:numTrain])trainConvict = np.asanyarray(numConvict[:numTrain])trainEvidNorm = normalize(trainEvid)trainConvictdNorm = normalize(trainConvict)
</code></pre><pre><code>testEvid = np.asanyarray(numEvid[numTrain:])testConvict = np.asanyarray(numConvict[numTrain:])testEvidNorm = normalize(testEvid)testConvictdNorm = normalize(testConvict)
</code></pre><p>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 “<a target="_blank" href="https://en.wikipedia.org/wiki/Feature_scaling">feature scaling</a>”.)</p>
<h4 id="heading-set-up-variables-and-operations-for-tensorflow">Set up variables and operations for TensorFlow</h4>
<pre><code># define placeholders  and variablestfEvid = tf.placeholder(tf.float32, name=<span class="hljs-string">"Evid"</span>)tfConvict = tf.placeholder(tf.float32, name=<span class="hljs-string">"Convict"</span>)tfEvidFactor = tf.Variable(np.random.randn(), name=<span class="hljs-string">"EvidFactor"</span>)tfConvictOffset = tf.Variable(np.random.randn(), name=<span class="hljs-string">"ConvictOffset"</span>)
</code></pre><pre><code># define the operation <span class="hljs-keyword">for</span> predicting the conviction based on evidence by adding both values# define a loss <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">mean squared error</span>)<span class="hljs-title">tfPredict</span> = <span class="hljs-title">tf</span>.<span class="hljs-title">add</span>(<span class="hljs-params">tf.multiply(tfEvidFactor, tfEvid), tfConvictOffset</span>)<span class="hljs-title">tfCost</span> = <span class="hljs-title">tf</span>.<span class="hljs-title">reduce_sum</span>(<span class="hljs-params">tf.pow(tfPredict - tfConvict, <span class="hljs-number">2</span>)</span>) / (<span class="hljs-params"><span class="hljs-number">2</span> * numTrain</span>)</span>
</code></pre><pre><code># set a learning rate and a gradient descent optimizerlearningRate = <span class="hljs-number">0.1</span>gradDesc = tf.train.GradientDescentOptimizer(learningRate).minimize(tfCost)
</code></pre><p>The pragmatic differences between <code>tf.placeholder</code> and <code>tf.Variable</code> are:</p>
<ul>
<li>placeholders are allocated storage for data, and initial values are not required</li>
<li>variables are used for parameters to learn, and initial values are required. The values can be derived from training.</li>
</ul>
<p>I use the TensorFlow operators precisely as <code>tf.add(…)</code>, because it is pretty clear what library is used for the calculation. This is instead of using the <code>+</code> operator.</p>
<h4 id="heading-start-the-calculations-with-a-tensorflow-session">Start the calculations with a TensorFlow session</h4>
<pre><code># initialize variablesinit = tf.global_variables_initializer()
</code></pre><pre><code><span class="hljs-keyword">with</span> tf.Session() <span class="hljs-keyword">as</span> sess:    sess.run(init)
</code></pre><pre><code>    # set up iteration parameters    displayEvery = <span class="hljs-number">2</span>    numTrainingSteps = <span class="hljs-number">50</span>
</code></pre><pre><code>    # Calculate the number <span class="hljs-keyword">of</span> lines to animation    # define variables <span class="hljs-keyword">for</span> updating during animation    numPlotsAnim = math.floor(numTrainingSteps / displayEvery)    evidFactorAnim = np.zeros(numPlotsAnim)    convictOffsetAnim = np.zeros(numPlotsAnim)    plotIndex = <span class="hljs-number">0</span>
</code></pre><pre><code>    # iterate through the training data    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(numTrainingSteps):
</code></pre><pre><code>        # ======== Start training by running the session and feeding the gradDesc        <span class="hljs-keyword">for</span> (x, y) <span class="hljs-keyword">in</span> zip(trainEvidNorm, trainConvictdNorm):            sess.run(gradDesc, feed_dict={<span class="hljs-attr">tfEvid</span>: x, <span class="hljs-attr">tfConvict</span>: y})
</code></pre><pre><code>        # Print status <span class="hljs-keyword">of</span> learning        <span class="hljs-keyword">if</span> (i + <span class="hljs-number">1</span>) % displayEvery == <span class="hljs-number">0</span>:            cost = sess.run(                tfCost, feed_dict={<span class="hljs-attr">tfEvid</span>: trainEvidNorm, <span class="hljs-attr">tfConvict</span>: trainConvictdNorm}            )            print(                <span class="hljs-string">"iteration #:"</span>,                <span class="hljs-string">"%04d"</span> % (i + <span class="hljs-number">1</span>),                <span class="hljs-string">"cost="</span>,                <span class="hljs-string">"{:.9f}"</span>.format(cost),                <span class="hljs-string">"evidFactor="</span>,                sess.run(tfEvidFactor),                <span class="hljs-string">"convictOffset="</span>,                sess.run(tfConvictOffset),            )
</code></pre><pre><code>            # store the result <span class="hljs-keyword">of</span> each step <span class="hljs-keyword">in</span> the animation variables            evidFactorAnim[plotIndex] = sess.run(tfEvidFactor)            convictOffsetAnim[plotIndex] = sess.run(tfConvictOffset)            plotIndex += <span class="hljs-number">1</span>
</code></pre><pre><code>    # log the optimized result    print(<span class="hljs-string">"Optimized!"</span>)    trainingCost = sess.run(        tfCost, feed_dict={<span class="hljs-attr">tfEvid</span>: trainEvidNorm, <span class="hljs-attr">tfConvict</span>: trainConvictdNorm}    )    print(        <span class="hljs-string">"Trained cost="</span>,        trainingCost,        <span class="hljs-string">"evidFactor="</span>,        sess.run(tfEvidFactor),        <span class="hljs-string">"convictOffset="</span>,        sess.run(tfConvictOffset),        <span class="hljs-string">"\n"</span>,    )
</code></pre><p>Now we come to the actual training and the most interesting part.</p>
<p>The graph is now executed in a <code>[tf.Session](https://www.tensorflow.org/programmers_guide/graphs#executing_a_graph_in_a_tfsession)</code>. I am using "feeding" as it lets you inject data into any Tensor in a computation graph. You can see more on reading data <a target="_blank" href="https://www.tensorflow.org/api_guides/python/reading_data#Feeding">here</a>.</p>
<p><code>tf.Session()</code> is used to create a session that is automatically closed on exiting the context. The session also closes when an uncaught exception is raised.</p>
<p>The <code>tf.Session.run</code> method is the main mechanism for running a <code>tf.Operation</code> or evaluating a <code>tf.Tensor</code>. You can pass one or more <code>tf.Operation</code> or <code>tf.Tensor</code> objects to <code>tf.Session.run</code>, and TensorFlow will execute the operations that are needed to compute the result.</p>
<p>First, we are running the gradient descent training while feeding it the normalized training data. After that, we are calculating the the loss.</p>
<p>We are repeating this process until the improvements per step are very small. Keep in mind that the <code>tf.Variables</code> (the parameters) have been adapted throughout and now reflect an optimum.</p>
<h3 id="heading-visualize-the-result-and-process">Visualize the result and process</h3>
<pre><code># 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
</code></pre><pre><code>    # Plot the result graph    plt.figure()
</code></pre><pre><code>    plt.xlabel(<span class="hljs-string">"Number of Evidence"</span>)    plt.ylabel(<span class="hljs-string">"Number of Convictions"</span>)
</code></pre><pre><code>    plt.plot(trainEvid, trainConvict, <span class="hljs-string">"go"</span>, label=<span class="hljs-string">"Training data"</span>)    plt.plot(testEvid, testConvict, <span class="hljs-string">"mo"</span>, label=<span class="hljs-string">"Testing data"</span>)    plt.plot(xNorm, yNorm, label=<span class="hljs-string">"Learned Regression"</span>)    plt.legend(loc=<span class="hljs-string">"upper left"</span>)
</code></pre><pre><code>    plt.show()
</code></pre><pre><code>    # Plot an animated graph that shows the process <span class="hljs-keyword">of</span> optimization    fig, ax = plt.subplots()    line, = ax.plot(numEvid, numConvict)
</code></pre><pre><code>    plt.rcParams[<span class="hljs-string">"figure.figsize"</span>] = (<span class="hljs-number">10</span>, <span class="hljs-number">8</span>) # adding fixed size parameters to keep animation <span class="hljs-keyword">in</span> scale    plt.title(<span class="hljs-string">"Gradient Descent Fitting Regression Line"</span>)    plt.xlabel(<span class="hljs-string">"Number of Evidence"</span>)    plt.ylabel(<span class="hljs-string">"Number of Convictions"</span>)    plt.plot(trainEvid, trainConvict, <span class="hljs-string">"go"</span>, label=<span class="hljs-string">"Training data"</span>)    plt.plot(testEvid, testConvict, <span class="hljs-string">"mo"</span>, label=<span class="hljs-string">"Testing data"</span>)
</code></pre><pre><code>    # define an animation <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">that</span> <span class="hljs-title">changes</span> <span class="hljs-title">the</span> <span class="hljs-title">ydata</span>    <span class="hljs-title">def</span> <span class="hljs-title">animate</span>(<span class="hljs-params">i</span>):        <span class="hljs-title">line</span>.<span class="hljs-title">set_xdata</span>(<span class="hljs-params">xNorm</span>)        <span class="hljs-title">line</span>.<span class="hljs-title">set_ydata</span>(<span class="hljs-params">            (evidFactorAnim[i] * trainEvidNorm + convictOffsetAnim[i]) * trainConvictStd            + trainConvictMean        </span>)        <span class="hljs-title">return</span> (<span class="hljs-params">line,</span>)</span>
</code></pre><pre><code>    # Initialize the animation <span class="hljs-keyword">with</span> zeros <span class="hljs-keyword">for</span> y    def initAnim():        line.set_ydata(np.zeros(shape=numConvict.shape[<span class="hljs-number">0</span>]))        <span class="hljs-keyword">return</span> (line,)
</code></pre><pre><code>    # call the animation    ani = animation.FuncAnimation(        fig,        animate,        frames=np.arange(<span class="hljs-number">0</span>, plotIndex),        init_func=initAnim,        interval=<span class="hljs-number">200</span>,        blit=True,    )
</code></pre><pre><code>    plt.show()
</code></pre><p>To visualize the process, it is helpful to plot the result and maybe even the optimization process.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/w31dQ19xkDhfLzWpeqqUkvmXVtsNeK-JkWDg" alt="Image" width="800" height="342" loading="lazy"></p>
<p>Check out this <a target="_blank" href="https://www.pluralsight.com/courses/tensorflow-getting-started">Pluralsight course</a> which helped me a lot to get started. :)</p>
<p>Thanks for reading my article! Feel free to leave any feedback!</p>
<p>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.</p>
<p>Connect on:</p>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/in/createdd">LinkedIn</a></li>
<li><a target="_blank" href="https://github.com/Createdd">Github</a></li>
<li><a target="_blank" href="https://medium.com/@ddcreationstudi">Medium</a></li>
<li><a target="_blank" href="https://twitter.com/DDCreationStudi">Twitter</a></li>
<li><a target="_blank" href="https://steemit.com/@createdd">Steemit</a></li>
<li><a target="_blank" href="https://hashnode.com/@DDCreationStudio">Hashnode</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
