python,tensorflow线性回归Django网页显示Gif动态图

本文展示了一个使用Django框架实现线性回归的实例,包括urls配置、视图处理、线性回归算法实现及结果展示。通过POST请求触发计算,GET请求获取图像结果,详细介绍了如何在Web应用中集成机器学习算法。
摘要由CSDN通过智能技术生成

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

  

 

  

 

转载于:https://www.cnblogs.com/CK85/p/10249061.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值