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. 简单列举几种常用 FTP

    简单说下几种FTP FTP:文件传输协议(File Transfer Protocol,FTP) SFTP:OPENSSH 提供的隧道级文件传送(file transfer) FTPS:支持传输层安全 ...

  2. Ionic2 自学须知的基本知识点

    http://www.cnblogs.com/zsl123/p/5991336.html Ionic(ionicframework)一款接近原生的HTML5移动App开发框架. IONIC 是目前最有 ...

  3. iOS --UIScrollView的学习(一)

    1.为什么使用UIScrollView 因为移动设备的屏幕大小是极其有限的,因此直接展示在用户眼前的内容也相当有限,当展示的内容较多,超出一个屏幕时,用户可通过滚动手势来查看屏幕以外的内容普通的UIV ...

  4. git 命令摘录

    回滚 n 个 commit (增加了revert commit) git revert -n commit_id 回滚到指定的commit_id(不增加commit,回滚的commit_id被删除) ...

  5. mac安装gdb调试(转载)

    转载自:http://blog.plotcup.com/a/129 最近一直用go写一个项目,本想在mac上用gdb调试一下,但xcode4.6带的gdb版 本还是太低了,不支持go,只好自己安装一个 ...

  6. maven web不能创建src/main/java等文件等问题

    我们在创建maven web项目的时候,默认只有src/main/resources这个source folder,我们按照maven结构添加src/main/java和src/test/java等s ...

  7. 【HADR】搭建实战

    Summary: 简单的HADR,只用一台虚拟机,两个实例间搭建.工作量不大,一般5分钟左右能够完成. 步骤: 1.设定归档模式 2.使用备份建立standby数据库 3.设定hadr相关的参数 4. ...

  8. Javascript之in操作符的用法

    in操作符是js里面常用的一个操作符,下面是其几个常用的功能: 1.配合for语句循环遍历/迭代数组中的元素 2.配合for语句循环遍历/迭代集合中的属性 3.判断对象是否是数组的元素 4.判断对象是 ...

  9. 网站变灰css

    html{ filter: grayscale(100%); -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-fi ...

  10. 【es6】let和const

    let 1.不存在变量提升      es5中var和function都存在变量提升,但let声明的变量不存在.     在代码块内,使用let命令声明变量之前,该变量都是不可用的.这在语法上,称为“ ...