1. 程式人生 > >python,tensorflow線性迴歸Django網頁顯示Gif動態圖

python,tensorflow線性迴歸Django網頁顯示Gif動態圖

1.工程組成

2.urls.py

"""Django_machine_learning_linear_regression URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app01 import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('tu/', views.tu),

]

3.views.py

from django.shortcuts import render, HttpResponse
from app01 import linear_regression
import numpy as np
import tensorflow as tf
import os
# Create your views here.





def index(request):
    if request.method == 'POST':
        num_points = 1000
        vectors_set = []
        for i in range(num_points):
            x1 = np.random.normal(0.0, 0.55)
            y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
            vectors_set.append([x1, y1])

        x_data = [v[0] for v in vectors_set]
        y_data = [v[1] for v in vectors_set]

        result = linear_regression.linear_regression(x_data, y_data)

        return render(request, 'index.html', {'result': result, 'range':range(1,21)})

    else:
        return render(request, 'index.html')


def tu(request):
    num = request.GET.get('num')
    print(num)

    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    d = base_dir
    imagepath = os.path.join(d, "regression_res.gif")
    image_data = open(imagepath, "rb").read()
    return HttpResponse(image_data, content_type='gif')

4.index.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <form action="/index/" method="post">
        {% csrf_token %}
        <input type="submit" value="開始運算!">
    </form>
    {% if result.W != None %}


    <p>{{ result.W }} x + {{ result.b }}</p>

    <img src="/tu/?num={{ num }}" name="{{ num }}" title="圖{{ num }}" alt="" />

    {% endif %}

</body>
</html>

5.linear_regression.py

def create_gif(image_list, gif_name):
    import imageio
    frames = []
    for image_name in image_list:
        frames.append(imageio.imread(image_name))
    # Save them as frames into a gif
    imageio.mimsave(gif_name, frames, 'GIF', duration=0.1)

def linear_regression(x_data, y_data):
    import tensorflow as tf
    import matplotlib.pyplot as plt

    W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='W')
    b = tf.Variable(tf.zeros([1]), name='b')
    y = W*x_data + b

    loss = tf.reduce_mean(tf.square(y - y_data), name='loss')
    optimizer = tf.train.GradientDescentOptimizer(0.5)
    train = optimizer.minimize(loss, name='train')
    sess = tf.Session()
    init = tf.global_variables_initializer()
    sess.run(init)
    print('W=', sess.run(W), 'b=', sess.run(b), 'loss=', sess.run(loss))
    i = 0
    image_list = []
    for step in range(20):
        i = i+1
        sess.run(train)
        print('W=', sess.run(W), 'b=', sess.run(b), 'loss=', sess.run(loss))

        plt.xlim((-2, 2))
        plt.ylim((0.1, 0.5))
        plt.scatter(x_data, y_data, c='r')
        plt.plot(x_data, sess.run(W)*x_data + sess.run(b))
        plt.savefig("./static/"+str(i)+".png")
        plt.close()
        image_list.append("./static/"+str(i)+".png")

    create_gif(image_list, 'regression_res.gif')


    result = {'W': sess.run(W), 'b': sess.run(b), 'loss': sess.run(loss)}

    return result