Repository navigation
Expand file tree
/
Copy pathocr.py
More file actions
76 lines (58 loc) · 2.15 KB
/
Copy pathocr.py
File metadata and controls
76 lines (58 loc) · 2.15 KB
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
import numpy as np
import neurolab as nl
# Define the input file
input_file = 'letter.data'
# Define the number of datapoints to
# be loaded from the input file
num_datapoints = 50
# String containing all the distinct characters
orig_labels = 'omandig'
# Compute the number of distinct characters
num_orig_labels = len(orig_labels)
# Define the training and testing parameters
num_train = int(0.9 * num_datapoints)
num_test = num_datapoints - num_train
# Define the dataset extraction parameters
start = 6
end = -1
# Creating the dataset
data = []
labels = []
with open(input_file, 'r') as f:
for line in f.readlines():
# Split the current line tabwise
list_vals = line.split('\t')
# Check if the label is in our ground truth
# labels. If not, we should skip it.
if list_vals[1] not in orig_labels:
continue
# Extract the current label and append it
# to the main list
label = np.zeros((num_orig_labels, 1))
label[orig_labels.index(list_vals[1])] = 1
labels.append(label)
# Extract the character vector and append it to the main list
cur_char = np.array([float(x) for x in list_vals[start:end]])
data.append(cur_char)
# Exit the loop once the required dataset has been created
if len(data) >= num_datapoints:
break
# Convert the data and labels to numpy arrays
data = np.asfarray(data)
labels = np.array(labels).reshape(num_datapoints, num_orig_labels)
# Extract the number of dimensions
num_dims = len(data[0])
# Create a feedforward neural network
nn = nl.net.newff([[0, 1] for _ in range(len(data[0]))],
[128, 16, num_orig_labels])
# Set the training algorithm to gradient descent
nn.trainf = nl.train.train_gd
# Train the network
error_progress = nn.train(data[:num_train,:], labels[:num_train,:],
epochs=10000, show=100, goal=0.01)
# Predict the output for test inputs
print('\nTesting on unknown data:')
predicted_test = nn.sim(data[num_train:, :])
for i in range(num_test):
print('\nOriginal:', orig_labels[np.argmax(labels[i])])
print('Predicted:', orig_labels[np.argmax(predicted_test[i])])