Vector.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. try:
  2. import cPickle as pickle
  3. except ImportError:
  4. import pickle
  5. import sample
  6. import typing
  7. from typing import List
  8. class FeatureVector:
  9. def __init__(self):
  10. self.features = []
  11. self.activefeatures = []
  12. # list of key, value tuples represnting values for features.
  13. self.sampleInfo = {}
  14. self.classification = None
  15. # set which features are active using a binary list
  16. # ex: For 2nd, 4th and 5th features to be active, pass [0,1,0,1,1]
  17. def setFeatures(self, binlist):
  18. activefeatures = []
  19. if len(binlist) != len(self.features):
  20. print("Feature choice list must equal length of feature list")
  21. for b in range(len(binlist)):
  22. if binlist[b] == 1:
  23. activefeatures.append(self.features[b])
  24. self.activefeatures = activefeatures
  25. def __repr__(self):
  26. return str(self.features)
  27. # use to make a sample into a vector
  28. def SampleToFeatureVector(s: sample):
  29. print(s.__activities)
  30. v = FeatureVector()
  31. for a in s.__activities.keys():
  32. for d in s.__activities[a].keys():
  33. # a + d looks like: high.total_packets
  34. v.sampleInfo.update({a + "." + d: s.__activities[a][d]})
  35. v.features.extend(a["high"].values())
  36. v.features.extend(a["mid"].values())
  37. v.features.extend(a["low"].values())
  38. v.sampleInfo.update(("total_time", s.total_time))
  39. v.sampleInfo.update(("average_iat", s.average_iat))
  40. v.sampleInfo.update(("dead_time", s.dead_time))
  41. v.features.append(s.total_time)
  42. v.features.append(s.average_iat)
  43. v.features.append(s.dead_time)
  44. return v
  45. def writePickledData(filename):
  46. v = FeatureVector()
  47. v.features = [1, 2, 3, 4]
  48. v.activefeatures = [1, 2, 3, 4]
  49. vs = [v,v]
  50. with open(filename, 'wb') as file:
  51. pickle.dump(vs, file)
  52. def readPickledData(filename):
  53. with open(filename, 'rb') as file:
  54. x = pickle.load(file)
  55. # print(x)
  56. return x
  57. def main():
  58. fv = FeatureVector()
  59. # writePickledData("test.bin")
  60. # readPickledData("test.txt")
  61. s = sample.Sample([{"delta": 0, "time": '09/19/18 13:55:26', }], open("./results.txt"))
  62. s.dead_time = 30
  63. s.average_iat = 3
  64. s.total_time = 30
  65. fv = SampleToFeatureVector(s)
  66. if __name__ == '__main__':
  67. main()