python_tensorflow_Django实现逻辑回归
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实现逻辑回归的更多相关文章
- 逻辑回归 Logistic Regression
逻辑回归(Logistic Regression)是广义线性回归的一种.逻辑回归是用来做分类任务的常用算法.分类任务的目标是找一个函数,把观测值匹配到相关的类和标签上.比如一个人有没有病,又因为噪声的 ...
- 用R做逻辑回归之汽车贷款违约模型
数据说明 本数据是一份汽车贷款违约数据 application_id 申请者ID account_number 账户号 bad_ind 是否违约 vehicle_year ...
- 逻辑回归(LR)总结复习
摘要: 1.算法概述 2.算法推导 3.算法特性及优缺点 4.注意事项 5.实现和具体例子 6.适用场合 内容: 1.算法概述 最基本的LR分类器适合于对两分类(类0,类1)目标进行分类:这个模型以样 ...
- scikit-learn 逻辑回归类库使用小结
之前在逻辑回归原理小结这篇文章中,对逻辑回归的原理做了小结.这里接着对scikit-learn中逻辑回归类库的我的使用经验做一个总结.重点讲述调参中要注意的事项. 1. 概述 在scikit-lear ...
- 逻辑回归LR
逻辑回归算法相信很多人都很熟悉,也算是我比较熟悉的算法之一了,毕业论文当时的项目就是用的这个算法.这个算法可能不想随机森林.SVM.神经网络.GBDT等分类算法那么复杂那么高深的样子,可是绝对不能小看 ...
- 逻辑回归(Logistic Regression)
转载请注明出自BYRans博客:http://www.cnblogs.com/BYRans/ 本文主要讲解分类问题中的逻辑回归.逻辑回归是一个二分类问题. 二分类问题 二分类问题是指预测的y值只有两个 ...
- 逻辑回归算法的原理及实现(LR)
Logistic回归虽然名字叫"回归" ,但却是一种分类学习方法.使用场景大概有两个:第一用来预测,第二寻找因变量的影响因素.逻辑回归(Logistic Regression, L ...
- 感知器、逻辑回归和SVM的求解
这篇文章将介绍感知器.逻辑回归的求解和SVM的部分求解,包含部分的证明.本文章涉及的一些基础知识,已经在<梯度下降.牛顿法和拉格朗日对偶性>中指出,而这里要解决的问题,来自<从感知器 ...
- stanford coursera 机器学习编程作业 exercise 3(逻辑回归实现多分类问题)
本作业使用逻辑回归(logistic regression)和神经网络(neural networks)识别手写的阿拉伯数字(0-9) 关于逻辑回归的一个编程练习,可参考:http://www.cnb ...
随机推荐
- linux中创建一个回收站
1. mkdir /tmp/trash_tmp 建立一个回收站目录 2. vi /bin/trash 编辑一个文件 mv $@ /tmp/trash_tmp :wq 保存退出 3. ...
- day 28 :进程相关,进程池,锁,队列,生产者消费者模式
---恢复内容开始--- 前情提要: 一:进程Process 1:模块介绍 from multiprocessing import Process from multiprocessing impo ...
- day 11课后作业
# -*- coding: utf-8 -*-# @Time : 2019/1/3 20:03# @Author : Endless-cloud# @Site : # @File : day 11 课 ...
- C语言数据结构之二叉树的实现
本篇博文是博主在学习C语言算法与数据结构的一些应用代码实例,给出了以二叉链表的形式实现二叉树的相关操作.如创建,遍历(先序,中序后序遍历),求树的深度,树的叶子节点数,左右兄弟,父节点. 代码清单如下 ...
- C#-类-string/Manth/Random/DateTime-及练习
类一.string类:.Length 字符串的长度 .Trim() 去掉开头以及结尾的空格.TrimStart() 去掉开头的空格.TrimEnd() 去掉结尾的空格 .ToLower() 全部转换为 ...
- 电信10兆指的是多少Mbps
一般电信10兆(10Mbps)指的是:下载速度最大在1.25MB/s 1Mbps(兆位/秒) = 0.125MB/S(兆字节/秒) 8Mbps(兆位/秒) = 1MB/ ...
- Windows下部署安装Docker
好长时间没用Docker,最近准备部署一下,做个记录,今天早上去官网下载,发现Docker开始区分Docker Community Edition(社区版)和Docker Enterprise Edi ...
- 生成allure测试报告之后,服务器端口无法访问查看生成的report,可能是这样引起的。
1. 检查防火墙 2. 如果机器有安装ADsafe,请关闭adsafe后重试
- 认识CSS中字体图标
前端之HTML,CSS(十一) 字体图标 使用文字做出小图标的效果并超越了小图标应用精灵图,使得图标变得灵活,减少了请求次数,优化了界面的性能.字体图标本身为矢量图. 字体图标的使用过程 1.UI设计 ...
- Neo4j使用简单例子(转)
Neo4j Versions Most of the examples on this page are written with Neo4j 2.0 in mind, so they skip th ...