-
Notifications
You must be signed in to change notification settings - Fork 17
/
classification_perceptron.py
96 lines (83 loc) · 3.64 KB
/
classification_perceptron.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from common.kernel import get_kernel
from common.fetch_data import get_binary_features
import modshogun as sg
import numpy as np
import json
def entrance(request):
arguments = [
{
'argument_type': 'decimal',
'argument_name': 'rate',
'argument_label': 'learning rate',
'argument_default': '1'},
{
'argument_type': 'decimal',
'argument_name': 'bias',
'argument_label': 'bias',
'argument_default' : '0'},
{
'argument_type': 'button-group',
'argument_items': [{'button_name': 'classify',
'button_type': 'json_up_down_load'},
{'button_name': 'clear'}]
}]
properties = { 'title': 'Perceptron(binary)',
'template': {'type': 'coordinate-2dims',
'coordinate_system': {'horizontal_axis': {'position': 'bottom',
'label': 'x1',
'range': [0, 1]},
'vertical_axis': {'position': 'left',
'label': 'x2',
'range': [0, 1]}},
'heatmap': { 'contour': True },
'mouse_click_enabled': 'both'},
'panels': [
{
'panel_name': 'arguments',
'panel_label': 'Arguments',
'panel_property': arguments
},
{
'panel_name': 'toy_data',
'panel_label': 'Toy Data'}]}
return render_to_response("classification/binary.html",
properties,
context_instance = RequestContext(request))
def classify(request):
try:
features, labels = get_binary_features(request)
except ValueError as e:
return HttpResponse(json.dumps({"status": e.message}))
try:
rate = float(request.POST["rate"])
bias = float(request.POST['bias'])
z_value, z_label = classify_perceptron(sg.Perceptron, features, labels, rate, bias)
except Exception as e:
return HttpResponse(json.dumps({"status": e}))
return HttpResponse(json.dumps({ 'status': 'ok',
'domain': [np.min(z_value), np.max(z_value)],
'z': z_value.tolist() }))
def classify_perceptron(classifier, features, labels, learn=1, bias=0):
perceptron = classifier(features, labels)
perceptron.set_learn_rate(learn)
perceptron.set_max_iter(1000)
perceptron.set_bias(bias)
perceptron.train()
size = 100
x1 = np.linspace(0, 1, size)
y1 = np.linspace(0, 1, size)
x, y = np.meshgrid(x1, y1)
test = sg.RealFeatures(np.array((np.ravel(x), np.ravel(y))))
outl = perceptron.apply(test).get_labels()
outv = perceptron.apply(test).get_values()
# Normalize output
outv /= np.max(outv)
z_value = outv.reshape((size, size))
z_value = np.transpose(z_value)
z_label = outl.reshape((size, size))
z_label = np.transpose(z_label)
z_label = z_label + np.random.rand(*z_label.shape) * 0.01
return z_value, z_label