1.工程概要

2.data文件以及input_data文件准备

链接:https://pan.baidu.com/s/1EBNyNurBXWeJVyhNeVnmnA
提取码:4nnl
3.logisstic_mnist.py

def logistic_regression():

    import tensorflow as tf
import matplotlib.pyplot as plt
from app01 import input_data
import numpy as np
from PIL import Image print('Download and Extract MNIST dataset')
mnist = input_data.read_data_sets('app01/data/', one_hot=True)
print("type of 'mnist' is %s" % (type(mnist)))
print("number of train data is %d" % (mnist.train.num_examples))
print("number of test data is %d" % (mnist.test.num_examples)) trainimg = mnist.train.images for img in trainimg:
for i in range(0, 748):
if img[i] < 0.6:
img[i] = 0
else:
img[i] = 1 trainlabel = mnist.train.labels testimg = mnist.test.images for img in testimg:
for i in range(0, 748):
if img[i] < 0.6:
img[i] = 0
else:
img[i] = 1 testlabel = mnist.test.labels print("type of the 'trainimg' is %s" % (type(trainimg)))
print("type of the 'trainlabel' is %s" % (type(trainlabel)))
print("type of the 'testimg' is %s" % (type(testimg)))
print("type of the 'testlabel' is %s" % (type(testlabel)))
print("shape of the 'trainimg' is %s" % (trainimg.shape,))
print("shape of the 'trainlabel' is %s" % (trainlabel.shape,))
print("shape of the 'testimg' is %s" % (testimg.shape,))
print("shape of the 'testlabel' is %s" % (testlabel.shape,)) print('how dose the training data look like?') nsample = 5
randidx = np.random.randint(trainimg.shape[0], size=nsample) for i in randidx:
curr_img = np.reshape(trainimg[i, :], (28, 28))
curr_label = np.argmax(trainlabel[i, :])
plt.matshow(curr_img, cmap=plt.get_cmap('gray'))
plt.title(""+str(i)+"th Training Data"+"Label is"+str(curr_label))
print(""+str(i)+"th Training Data"+"Label is"+str(curr_label))
plt.show() print('Batch Learning?')
batch_size = 100
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
print("type of 'batch_xs' is %s" % (type(batch_xs)))
print("type of 'batch_ys' is %s" % (type(batch_ys)))
print("shape of 'batch_xs' is %s" % (batch_xs.shape, ))
print("shape of 'batch_ys' is %s" % (batch_ys.shape, )) # print(trainlabel[0]) x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float', [None, 10])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10])) actv = tf.nn.softmax(tf.matmul(x, W) + b)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv), reduction_indices=1))
learning_rate = 0.01 optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) pred = tf.equal(tf.argmax(actv, 1), tf.argmax(y, 1))
accr = tf.reduce_mean(tf.cast(pred, 'float'))
init = tf.global_variables_initializer()
sess = tf.InteractiveSession() training_epochs = 50
batch_size = 100
display_step = 5
sess = tf.Session()
sess.run(init) for epoch in range(training_epochs):
avg_cost = 0.
num_batch = int(mnist.train.num_examples/batch_size)
for i in range(num_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
feeds = {x: batch_xs, y: batch_ys}
sess.run(optm, feed_dict=feeds) avg_cost += sess.run(cost, feed_dict=feeds)/num_batch
if epoch % display_step == 0:
feeds_train = {x: batch_xs, y: batch_ys}
feeds_test = {x: mnist.test.images, y: mnist.test.labels}
train_acc = sess.run(accr, feed_dict=feeds_train)
test_acc = sess.run(accr, feed_dict=feeds_test)
print("Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f" % (epoch, training_epochs, avg_cost, train_acc, test_acc)) W_out = W.eval(session=sess)
b_out = b.eval(session=sess)
res_dict = {'W': W_out, 'b': b_out} print('DONE')
return res_dict

4.views.py

from django.shortcuts import render
from app01 import logistic_mnist as lomni
from app01 import save_and_load_dict as save_load
# Create your views here. def index(request):
if request.method == 'GET':
return render(request, 'logistic_regression.html', {'range': range(0, 28)})
if request.method == 'POST':
choice = request.GET.get('n')
print('choice:', choice)
if choice == '1':
res_dict = lomni.logistic_regression()
save_load.save_obj(res_dict, 'res_dict')
return render(request, 'logistic_regression.html', {'resdict': res_dict})
if choice == '2':
import numpy as np
my_test = []
for row in range(0, 28):
for line in range(0, 28):
if request.POST.get('('+str(row)+','+str(line)+')') == None:
my_test.append(0)
else:
my_test.append(1)
my_test = np.array(my_test)
print('my_test:', my_test)
res_dict = save_load.load_obj('res_dict')
W = np.array(res_dict['W'])
b = np.array(res_dict['b'])
# print(W, b)
pred = np.argmax(np.matmul(my_test, W)+b) return render(request, 'logistic_regression.html', {'resdict': res_dict, 'pred':pred}) if choice == '3':
import numpy as np from PIL import Image
img = Image.open('app01/image/sharped5.png')
img_array = np.array(img)
img_array = np.zeros(784).reshape(28, 28)
print(img_array + 0)
return render(request, 'logistic_regression.html', {'img_array': img_array+0, 'range': range(0, 28)})

5.urls.py

"""logistic_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),
]

6.logistic_regression.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style> </style>
</head>
<body>
<form action="/index/?n=1" method="post">
{% csrf_token %}
<input type="submit" value="逻辑回归训练">
</form> {% if resdict != none %}
<div>
<p>训练结果:</p>
<p>W:{{ resdict.W }}</p>
<p>b:{{ resdict.b }}</p>
</div>
{% endif %} <form action="/index/?n=2" method="post">
{% csrf_token %}
<table border="1">
<thead></thead>
<tbody >
{% for row in range %}
<tr>
{% for line in range %}
<td>
<input type="checkbox" name="({{ row }},{{ line }})" class="paint">
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table> <input type="submit" value="进行手写识别">
</form>
{% if pred != none %}
<div>
<p>
检测结果是{{ pred }}
</p>
</div>
{% endif %} <form action="/index/?n=3" method="post">
{% csrf_token %}
<input type="submit" value="开始检测目标文件夹中的手写字体!">
<p>{{ img }}</p> </form> </body>
</html>

7.save_and_load_dict.py

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style> </style>
</head>
<body>
<form action="/index/?n=1" method="post">
{% csrf_token %}
<input type="submit" value="逻辑回归训练">
</form> {% if resdict != none %}
<div>
<p>训练结果:</p>
<p>W:{{ resdict.W }}</p>
<p>b:{{ resdict.b }}</p>
</div>
{% endif %} <form action="/index/?n=2" method="post">
{% csrf_token %}
<table border="1">
<thead></thead>
<tbody >
{% for row in range %}
<tr>
{% for line in range %}
<td>
<input type="checkbox" name="({{ row }},{{ line }})" class="paint">
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table> <input type="submit" value="进行手写识别">
</form>
{% if pred != none %}
<div>
<p>
检测结果是{{ pred }}
</p>
</div>
{% endif %} <form action="/index/?n=3" method="post">
{% csrf_token %}
<input type="submit" value="开始检测目标文件夹中的手写字体!">
<p>{{ img }}</p> </form> </body>
</html>

8.graying.py

import sys
print(sys.argv[0]) import os
path_curr = os.path.abspath('.')
path_up = os.path.abspath('..')
print(path_up) threshold = 140 table = []
for a in range(256): if a > threshold:
table.append(1) else:
table.append(0) from PIL import Image
for i in range(0, 10):
img = Image.open('image/'+str(i)+'.png') Img = img.convert('L') Img.save('image/grey'+str(i)+'.png') photo = Img.point(table, '1') photo.save('image/sharped'+str(i)+'.png')

  

python_tensorflow_Django实现逻辑回归的更多相关文章

  1. 逻辑回归 Logistic Regression

    逻辑回归(Logistic Regression)是广义线性回归的一种.逻辑回归是用来做分类任务的常用算法.分类任务的目标是找一个函数,把观测值匹配到相关的类和标签上.比如一个人有没有病,又因为噪声的 ...

  2. 用R做逻辑回归之汽车贷款违约模型

    数据说明 本数据是一份汽车贷款违约数据 application_id    申请者ID account_number 账户号 bad_ind            是否违约 vehicle_year  ...

  3. 逻辑回归(LR)总结复习

    摘要: 1.算法概述 2.算法推导 3.算法特性及优缺点 4.注意事项 5.实现和具体例子 6.适用场合 内容: 1.算法概述 最基本的LR分类器适合于对两分类(类0,类1)目标进行分类:这个模型以样 ...

  4. scikit-learn 逻辑回归类库使用小结

    之前在逻辑回归原理小结这篇文章中,对逻辑回归的原理做了小结.这里接着对scikit-learn中逻辑回归类库的我的使用经验做一个总结.重点讲述调参中要注意的事项. 1. 概述 在scikit-lear ...

  5. 逻辑回归LR

    逻辑回归算法相信很多人都很熟悉,也算是我比较熟悉的算法之一了,毕业论文当时的项目就是用的这个算法.这个算法可能不想随机森林.SVM.神经网络.GBDT等分类算法那么复杂那么高深的样子,可是绝对不能小看 ...

  6. 逻辑回归(Logistic Regression)

    转载请注明出自BYRans博客:http://www.cnblogs.com/BYRans/ 本文主要讲解分类问题中的逻辑回归.逻辑回归是一个二分类问题. 二分类问题 二分类问题是指预测的y值只有两个 ...

  7. 逻辑回归算法的原理及实现(LR)

    Logistic回归虽然名字叫"回归" ,但却是一种分类学习方法.使用场景大概有两个:第一用来预测,第二寻找因变量的影响因素.逻辑回归(Logistic Regression, L ...

  8. 感知器、逻辑回归和SVM的求解

    这篇文章将介绍感知器.逻辑回归的求解和SVM的部分求解,包含部分的证明.本文章涉及的一些基础知识,已经在<梯度下降.牛顿法和拉格朗日对偶性>中指出,而这里要解决的问题,来自<从感知器 ...

  9. stanford coursera 机器学习编程作业 exercise 3(逻辑回归实现多分类问题)

    本作业使用逻辑回归(logistic regression)和神经网络(neural networks)识别手写的阿拉伯数字(0-9) 关于逻辑回归的一个编程练习,可参考:http://www.cnb ...

随机推荐

  1. 微信小程序ofo小黄车+thinkphp5.0打造全栈应用

    原文地址:https://www.imooc.com/article/20310 ofo至今还没有微信小程序(很费解),每次用ofo都得去支付宝,很不方便,我用微信用的比较多,无意间在简书上面看到某人 ...

  2. RN47 中通过 JS 调用 Native 方法

    每一个模块.方法都有一个 ID,通过 ID 来调用. m_registry->callNativeMethod(call.moduleId, call.methodId, std::move(c ...

  3. 总结day23 ---- 网络编程,以及计算机基础概念

    计算机网络的发展及基础网络概念 问题:网络到底是什么?计算机之间是如何通信的? 早期 : 联机 以太网 : 局域网与交换机 广播 主机之间“一对所有”的通讯模式,网络对其中每一台主机发出的信号都进行无 ...

  4. java中的jdk配置详解:

    1.配值系统变量"JAVA_HOME" 变量名JAVA_HOME: 指向:JDK(java开发工具包)的安装路径 目的:使用JDK安装目录时,可以直接通过”%JAVA_HOME%“ ...

  5. javaweb Servlet接收Android请求,并返回json数据

    1.实现功能 (1)接收http请求 (2)获取Android客户端发送的参数对应的内容 (3)hibernate查询数据库 (4)返回json数据 2.java代码 import EntityCla ...

  6. (转)2017年Linux运维人员必会开源运维工具体系

    标签:操作系统 中间件 千里马 Linux 技能 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://oldboy.blog.51ct ...

  7. 【系统】Ubuntu和win7双系统更改系统引导菜单

    1. 下载EasyBCD 2. 编辑菜单选项以及重写MBR

  8. Javac的命令(注解相关)

    1.-Akey[=value] Options to pass to annotation processors. These are not interpreted by javac directl ...

  9. AbstractQueuedSynchronizer,ReentraLock部分代码分析

    /* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * ...

  10. ibatis内置类型

    别名 java类型 事务管理器类型   JDBC com.ibatis.sqlmap.engine.transaction.jdbc.JdbcTransactionConfig JTA com.iba ...