forked from fredgu2019/tensorflow-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmelt_dataset.py
79 lines (68 loc) · 1.97 KB
/
melt_dataset.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
#!/usr/bin/env python
#coding=gbk
# ==============================================================================
# \file melt_dataset.py
# \author chenghuige
# \date 2015-11-17 10:55:40.916390
# \Description
# ==============================================================================
import numpy as np
import os
def parse_first_line(line):
label_idx = 0
if line.startswith('_'):
label_idx = 1
return label_idx
def load_dense_data(dataset, has_header = False):
''' Loads the dataset
:type dataset: string
:param dataset: the path to the dataset
'''
print '... loading data:',dataset
dataset_x = []
dataset_y = []
lines = open(dataset).readlines()
if (lines[0].startswith('#')):
has_header = True
label_idx = parse_first_line(lines[has_header])
nrows = 0
for i in xrange(has_header, len(lines)):
if nrows % 10000 == 0:
print nrows
nrows += 1
line = lines[i]
l = line.rstrip().split()
dataset_y.append([float(l[label_idx])])
dataset_x.append([float(x) for x in l[label_idx + 1:]])
dataset_x = np.array(dataset_x)
dataset_y = np.array(dataset_y)
return dataset_x, dataset_y
def load_sparse_data(dataset):
print '... loading data:',dataset
dataset_x = []
dataset_y = []
lines = open(dataset).readlines()
label_idx = parse_first_line(lines[0])
num_features = int(lines[0].split()[label_idx + 1])
nrows = 0
for i in xrange(len(lines)):
if nrows % 10000 == 0:
print nrows
nrows += 1
line = lines[i]
l = line.rstrip().split()
dataset_y.append([float(l[label_idx])])
dataset_x.append(l[label_idx + 2:])
dataset_y = np.array(dataset_y)
return dataset_x, dataset_y, num_features
def sparse2dense(dataset_x, num_features):
print "start convert to dense"
dataset_x_ = []
for instance in dataset_x:
l = [float(0)] * num_features
for item in instance:
index, value = item.split(':')
l[int(index)] = float(value)
dataset_x_.append(l)
print "finish convert to dense"
return np.array(dataset_x_)