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 ...
随机推荐
- Python Socket 编程示例 Echo Server
简评:我们已经从「Python Socket 编程概览」了解了 socket API 的概述以及客户端和服务器的通信方式,接下来让我们创建第一个客户端和服务器,我们将从一个简单的实现开始,服务器将简单 ...
- 腾讯云服务器安装宝塔面板快速配置LNMP/LAMP网站系统
我们在选择购买腾讯云服务器之后,有部分用户肯定是用来建站用途的.毕竟云服务器的性能和功能比虚拟主机优秀很多.腾讯云服务器拥有香港.北京.广州.上海.美国等多个机房,可以安装Linux和Windows系 ...
- Apache Maven的入门使用之项目的基本构建(1)
前言 最近在研究java框架struts2的相关漏洞,然后就去看了官方给出的文档.在看文档的过程中发现使用到了Apache Maven这个项目管理工具,我在网上搜索了一下,大多数文章都写得不是很系统, ...
- 解决Visual C++ Redistributable for Visual Studio 2015的安装问题(摘录)
1. Visual C++ Redistributable for Visual Studio 2015系统要求:Windows 7情况下必须是Windows 7 with SP1.或者Windows ...
- 【文档】四、Mysql Binlog事件含义详解
下面对binlog中事件做个简单说明: UNKNOWN_EVENT 这个事件类型应该永远不会出现.它从不会写入binlog中.如果binlog中的事件没法被识别成其他已知事件,他被当做UNKNOWN_ ...
- ubuntu安装ntp时间服务器
1.安装ntp软件 sudo apt-get install ntp2.修改配置文件 sudo vim /etc/ntp.conf driftfile /var/lib/ntp/ntp.dr ...
- WPF的Label默认的padding不为0
1.如图: 要求让“Tools” 左对齐,代码中已设置:HorizontalContentAlignment="Left" <Label Foreground="W ...
- 快捷键 -- windows
win+数字 : 打开任务栏第n个图标 Win+D :快速显示桌面 Win+R :快速运行打开软件 例如 cmd services,msc Win+E:打开资源管理器 Win+L:快速锁定计算机 ...
- free 和 delete 把指针怎么了
使用free或delete之后,只是把指针所指的内容给释放掉,但是指针并没有被干掉,还是指向原来位置(并不是执行NULL),此时指针指向的内容为垃圾,被称为“野指针”. 举例说明几个重要容易迷糊的特征 ...
- java并发编程(6)显式锁
显式锁 一.Lock与ReentrantLock Lock提供了一种无条件的.可轮询的.定时的以及可中断的锁获取操作,所有的加锁和解锁方法都是显式的 ReentrantLock实现了Lock:并提供了 ...