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. Oauth2.0 整合springCloud的Zuul 解决关键BUG 报错信息:Principal must not be null

    不清楚Oauth2.0 的 可以查看我前几篇博文 2018.4.8 补充 我出现这个原因:是我在资源服务器使用了 如下图所示 Principal Oauth2.0 提供的获取用户信息的方法 使其找到相 ...

  2. Linux系统NAT模式下设置网络网关

    1.配置Vm网络编辑器 2.配置固定IP地址 命令:vi /etc/sysconfig/network-scripts/ifcfg-ens33 #下面内容直接复制进去,如果有重复的可以去除 TYPE= ...

  3. UVALive-7457-Discrete Logarithm Problem(取模运算)

    原题链接 额,一直在理解题意在纠结看不懂,后来才恍然大悟 题意:定义一种新运算 a × b = a * b mod p : 已知条件给定一个p 求 x 这里用到同余与模运算乘法公式:a * b % n ...

  4. You need to use a Theme.AppCompat theme (or descendant) with this activity问题

    You need to use a Theme.AppCompat theme (or descendant) with this activity问题 https://blog.csdn.net/j ...

  5. chainWebpack 和 htmlWebpackPlugin搭配使用

    const HtmlWebpackPlugin = require('html-webpack-plugin'); ... chainWebpack: config => { config .p ...

  6. springcloud(八)-Hystrix熔断器

    雪崩效应 在微服务架构中通常会有多个服务层调用,基础服务的故障可能会导致级联故障,进而造成整个系统不可用的情况,这种现象被称为服务雪崩效应.服务雪崩效应是一种因“服务提供者”的不可用导致“服务消费者” ...

  7. java的SSH的baseDao,巧用泛型

    BaseDao接口: import java.util.List; public interface BaseDao<T,PK> { public void add(T t); publi ...

  8. javac之向前引用

    可以参考JLS7:https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3 public class Test5 ...

  9. resotreIpAddress

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  10. poj 1222EXTENDED LIGHTS OUT

    高斯消元的题本质思想一样. 学习网址:http://www.cnblogs.com/rainydays/archive/2011/08/31/2160748.html #include <ios ...