当前位置: 首页>>代码示例>>Python>>正文


Python ScalarEncoder.encode方法代码示例

本文整理汇总了Python中nupic.encoders.scalar.ScalarEncoder.encode方法的典型用法代码示例。如果您正苦于以下问题:Python ScalarEncoder.encode方法的具体用法?Python ScalarEncoder.encode怎么用?Python ScalarEncoder.encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在nupic.encoders.scalar.ScalarEncoder的用法示例。


在下文中一共展示了ScalarEncoder.encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: testBottomUpEncodingPeriodicEncoder

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
  def testBottomUpEncodingPeriodicEncoder(self):
      """Test bottom-up encoding for a Periodic encoder"""
      l = ScalarEncoder(n=14, w=3, minval=1, maxval=8, periodic=True, forced=True)
      self.assertEqual(l.getDescription(), [("[1:8]", 0)])
      l = ScalarEncoder(name='scalar', n=14, w=3, minval=1, maxval=8, periodic=True, forced=True)
      self.assertEqual(l.getDescription(), [("scalar", 0)])
      self.assertTrue((l.encode(3) == numpy.array([0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                                         dtype=defaultDtype)).all())
      self.assertTrue((l.encode(3.1) == l.encode(3)).all())
      self.assertTrue((l.encode(3.5) == numpy.array([0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
                                           dtype=defaultDtype)).all())
      self.assertTrue((l.encode(3.6) == l.encode(3.5)).all())
      self.assertTrue((l.encode(3.7) == l.encode(3.5)).all())
      self.assertTrue((l.encode(4) == numpy.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
                                         dtype=defaultDtype)).all())

      self.assertTrue((l.encode(1) == numpy.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                                         dtype=defaultDtype)).all())
      self.assertTrue((l.encode(1.5) == numpy.array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                           dtype=defaultDtype)).all())
      self.assertTrue((l.encode(7) == numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
                                         dtype=defaultDtype)).all())
      self.assertTrue((l.encode(7.5) == numpy.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
                                           dtype=defaultDtype)).all())

      self.assertEqual(l.resolution, 0.5)
      self.assertEqual(l.radius, 1.5)
开发者ID:AI-Cdrone,项目名称:nupic,代码行数:29,代码来源:scalar_test.py

示例2: testBottomUpEncodingPeriodicEncoder

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
  def testBottomUpEncodingPeriodicEncoder(self):
      """Test bottom-up encoding for a Periodic encoder"""
      l = ScalarEncoder(n=14, w=3, minval=1, maxval=8, periodic=True)
      assert l.getDescription() == [("[1:8]", 0)]
      l = ScalarEncoder(name='scalar', n=14, w=3, minval=1, maxval=8, periodic=True)
      assert l.getDescription() == [("scalar", 0)]
      assert (l.encode(3) == numpy.array([0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                                         dtype=defaultDtype)).all()
      assert (l.encode(3.1) == l.encode(3)).all()
      assert (l.encode(3.5) == numpy.array([0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
                                           dtype=defaultDtype)).all()
      assert (l.encode(3.6) == l.encode(3.5)).all()
      assert (l.encode(3.7) == l.encode(3.5)).all()
      assert (l.encode(4) == numpy.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
                                         dtype=defaultDtype)).all()

      assert (l.encode(1) == numpy.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                                         dtype=defaultDtype)).all()
      assert (l.encode(1.5) == numpy.array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                           dtype=defaultDtype)).all()
      assert (l.encode(7) == numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
                                         dtype=defaultDtype)).all()
      assert (l.encode(7.5) == numpy.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
                                           dtype=defaultDtype)).all()

      assert l.resolution == 0.5
      assert l.radius == 1.5
开发者ID:MaxDavila,项目名称:nupic,代码行数:29,代码来源:scalar_test.py

示例3: profileEnc

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
def profileEnc(maxValue, nRuns):
  minV=0
  maxV=nRuns
  # generate input data
  data=numpy.random.randint(minV, maxV+1, nRuns)
  # instantiate measured encoders
  encScalar = ScalarEncoder(w=21, minval=minV, maxval=maxV, resolution=1)
  encRDSE = RDSE(resolution=1)
  
  # profile!  
  for d in data:
    encScalar.encode(d)
    encRDSE.encode(d)

  print "Scalar n=",encScalar.n," RDSE n=",encRDSE.n
开发者ID:AaronZhangL,项目名称:nupic,代码行数:17,代码来源:enc_profile.py

示例4: ScalarBucketEncoder

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
class ScalarBucketEncoder(Encoder):

  def __init__(self):
    self.encoder = NupicScalarEncoder(w=1, minval=0, maxval=40000, n=22, forced=True)

  def encode(self, symbol):
    encoding = self.encoder.encode(symbol)
    return encoding
开发者ID:andrewmalta13,项目名称:nupic.research,代码行数:10,代码来源:run_lstm_suite.py

示例5: testScalarEncoder

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
  def testScalarEncoder(self):
    """Testing ScalarEncoder..."""

    # -------------------------------------------------------------------------
    # test missing values
    mv = ScalarEncoder(name="mv", n=14, w=3, minval=1, maxval=8,
                       periodic=False, forced=True)
    empty = mv.encode(SENTINEL_VALUE_FOR_MISSING_DATA)
    self.assertEqual(empty.sum(), 0)
开发者ID:leotam,项目名称:cupic,代码行数:11,代码来源:scalar_test.py

示例6: testScalarEncoder

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
  def testScalarEncoder(self):
      """Testing ScalarEncoder..."""

      # -------------------------------------------------------------------------
      # test missing values
      mv = ScalarEncoder(name='mv', n=14, w=3, minval=1, maxval=8, periodic=False, forced=True)
      empty = mv.encode(SENTINEL_VALUE_FOR_MISSING_DATA)
      print "\nEncoded missing data \'None\' as %s" % empty
      self.assertEqual(empty.sum(), 0)
开发者ID:AI-Cdrone,项目名称:nupic,代码行数:11,代码来源:scalar_test.py

示例7: testNonPeriodicBottomUp

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
  def testNonPeriodicBottomUp(self):
      """Test Non-periodic encoder bottom-up"""
      l = ScalarEncoder(name='scalar', n=14, w=5, minval=1, maxval=10, periodic=False, forced=True)
      print "\nTesting non-periodic encoder encoding, resolution of %f..." % \
                  l.resolution
      self.assertTrue((l.encode(1) == numpy.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                         dtype=defaultDtype)).all())
      self.assertTrue((l.encode(2) == numpy.array([0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                                         dtype=defaultDtype)).all())
      self.assertTrue((l.encode(10) == numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
                                          dtype=defaultDtype)).all())

      # Test that we get the same encoder when we construct it using resolution
      #  instead of n
      d = l.__dict__
      l = ScalarEncoder(name='scalar', resolution=1, w=5, minval=1, maxval=10,
                         periodic=False, forced=True)
      self.assertEqual(l.__dict__, d)

      # Test that we get the same encoder when we construct it using radius
      #  instead of n
      l = ScalarEncoder(name='scalar', radius=5, w=5, minval=1, maxval=10, periodic=False, forced=True)
      self.assertEqual(l.__dict__, d)



      # -------------------------------------------------------------------------
      # Test the input description generation and topDown decoding of a non-periodic
      #  encoder
      v = l.minval
      print "\nTesting non-periodic encoder decoding, resolution of %f..." % \
                  l.resolution
      while v < l.maxval:
        output = l.encode(v)
        decoded = l.decode(output)
        print "decoding", output, "(%f)=>" % v, l.decodedToStr(decoded)

        (fieldsDict, fieldNames) = decoded
        self.assertEqual(len(fieldsDict), 1)
        (ranges, desc) = fieldsDict.values()[0]
        self.assertEqual(len(ranges), 1)
        (rangeMin, rangeMax) = ranges[0]
        self.assertEqual(rangeMin, rangeMax)
        self.assertTrue(abs(rangeMin - v) < l.resolution)

        topDown = l.topDownCompute(output)[0]
        print "topdown =>", topDown
        self.assertTrue((topDown.encoding == output).all())
        self.assertTrue(abs(topDown.value - v) <= l.resolution)

        # Test bucket support
        bucketIndices = l.getBucketIndices(v)
        print "bucket index =>", bucketIndices[0]
        topDown = l.getBucketInfo(bucketIndices)[0]
        self.assertTrue(abs(topDown.value - v) <= l.resolution / 2)
        self.assertEqual(topDown.scalar, topDown.value)
        self.assertTrue((topDown.encoding == output).all())

        # Next value
        v += l.resolution / 4


      # Make sure we can fill in holes
      decoded = l.decode(numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1]))
      (fieldsDict, fieldNames) = decoded
      self.assertEqual(len(fieldsDict), 1)
      (ranges, desc) = fieldsDict.values()[0]
      self.assertTrue(len(ranges) == 1 and numpy.array_equal(ranges[0], [10, 10]))
      print "decodedToStr of", ranges, "=>", l.decodedToStr(decoded)

      decoded = l.decode(numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1]))
      (fieldsDict, fieldNames) = decoded
      self.assertEqual(len(fieldsDict), 1)
      (ranges, desc) = fieldsDict.values()[0]
      self.assertTrue(len(ranges) == 1 and numpy.array_equal(ranges[0], [10, 10]))
      print "decodedToStr of", ranges, "=>", l.decodedToStr(decoded)

      #Test min and max
      l = ScalarEncoder(name='scalar', n=14, w=3, minval=1, maxval=10, periodic=False, forced=True)
      decoded = l.topDownCompute(numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]))[0]
      self.assertEqual(decoded.value, 10)
      decoded = l.topDownCompute(numpy.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]))[0]
      self.assertEqual(decoded.value, 1)

      #Make sure only the last and first encoding encodes to max and min, and there is no value greater than max or min
      l = ScalarEncoder(name='scalar', n=140, w=3, minval=1, maxval=141, periodic=False, forced=True)
      for i in range(137):
        iterlist = [0 for _ in range(140)]
        for j in range(i, i+3):
          iterlist[j] =1
        npar = numpy.array(iterlist)
        decoded = l.topDownCompute(npar)[0]
        self.assertTrue(decoded.value <= 141)
        self.assertTrue(decoded.value >= 1)
        self.assertTrue(decoded.value < 141 or i==137)
        self.assertTrue(decoded.value > 1 or i == 0)


      # -------------------------------------------------------------------------
      # Test the input description generation and top-down compute on a small number
#.........这里部分代码省略.........
开发者ID:AI-Cdrone,项目名称:nupic,代码行数:103,代码来源:scalar_test.py

示例8: ScalarEncoderTest

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
class ScalarEncoderTest(unittest.TestCase):
  """Unit tests for ScalarEncoder class"""

  def setUp(self):
    # use of forced is not recommended, but used here for readability, see
    # scalar.py
    self._l = ScalarEncoder(name="scalar", n=14, w=3, minval=1, maxval=8,
                            periodic=True, forced=True)

  def testScalarEncoder(self):
    """Testing ScalarEncoder..."""

    # -------------------------------------------------------------------------
    # test missing values
    mv = ScalarEncoder(name="mv", n=14, w=3, minval=1, maxval=8,
                       periodic=False, forced=True)
    empty = mv.encode(SENTINEL_VALUE_FOR_MISSING_DATA)
    self.assertEqual(empty.sum(), 0)


  def testNaNs(self):
    """test NaNs"""
    mv = ScalarEncoder(name="mv", n=14, w=3, minval=1, maxval=8,
                       periodic=False, forced=True)
    empty = mv.encode(float("nan"))
    self.assertEqual(empty.sum(), 0)


  def testBottomUpEncodingPeriodicEncoder(self):
    """Test bottom-up encoding for a Periodic encoder"""
    l = ScalarEncoder(n=14, w=3, minval=1, maxval=8, periodic=True,
                      forced=True)
    self.assertEqual(l.getDescription(), [("[1:8]", 0)])
    l = ScalarEncoder(name="scalar", n=14, w=3, minval=1, maxval=8,
                      periodic=True, forced=True)
    self.assertEqual(l.getDescription(), [("scalar", 0)])
    self.assertTrue(numpy.array_equal(
      l.encode(3),
      numpy.array([0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                  dtype=defaultDtype)))
    self.assertTrue(numpy.array_equal(l.encode(3.1), l.encode(3)))
    self.assertTrue(numpy.array_equal(
      l.encode(3.5),
      numpy.array([0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
                  dtype=defaultDtype)))
    self.assertTrue(numpy.array_equal(l.encode(3.6), l.encode(3.5)))
    self.assertTrue(numpy.array_equal(l.encode(3.7), l.encode(3.5)))
    self.assertTrue(numpy.array_equal(
      l.encode(4),
      numpy.array([0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
                   dtype=defaultDtype)))

    self.assertTrue(numpy.array_equal(
      l.encode(1),
      numpy.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                  dtype=defaultDtype)))
    self.assertTrue(numpy.array_equal(
      l.encode(1.5),
      numpy.array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  dtype=defaultDtype)))
    self.assertTrue(numpy.array_equal(
      l.encode(7),
      numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
                  dtype=defaultDtype)))
    self.assertTrue(numpy.array_equal(
      l.encode(7.5),
      numpy.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
                  dtype=defaultDtype)))

    self.assertEqual(l.resolution, 0.5)
    self.assertEqual(l.radius, 1.5)


  def testCreateResolution(self):
    """Test that we get the same encoder when we construct it using resolution
    instead of n
    """
    l = self._l
    d = l.__dict__
    l = ScalarEncoder(name="scalar", resolution=0.5, w=3, minval=1, maxval=8,
                      periodic=True, forced=True)
    self.assertEqual(l.__dict__, d)

    # Test that we get the same encoder when we construct it using radius
    #  instead of n
    l = ScalarEncoder(name="scalar", radius=1.5, w=3, minval=1, maxval=8,
                      periodic=True, forced=True)
    self.assertEqual(l.__dict__, d)



  def testDecodeAndResolution(self):
    """Test the input description generation, top-down compute, and bucket
    support on a periodic encoder
    """
    l = self._l
    v = l.minval
    while v < l.maxval:
      output = l.encode(v)
      decoded = l.decode(output)
#.........这里部分代码省略.........
开发者ID:leotam,项目名称:cupic,代码行数:103,代码来源:scalar_test.py

示例9: testGetBucketInfoIntResolution

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
 def testGetBucketInfoIntResolution(self):
   """Ensures that passing resolution as an int doesn't truncate values."""
   encoder = ScalarEncoder(w=3, resolution=1, minval=1, maxval=8,
                           periodic=True, forced=True)
   self.assertEqual(4.5,
                    encoder.topDownCompute(encoder.encode(4.5))[0].scalar)
开发者ID:leotam,项目名称:cupic,代码行数:8,代码来源:scalar_test.py

示例10: testEncodeInvalidInputType

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
 def testEncodeInvalidInputType(self):
   encoder = ScalarEncoder(name="enc", n=14, w=3, minval=1, maxval=8,
                           periodic=False, forced=True)
   with self.assertRaises(TypeError):
     encoder.encode("String")
开发者ID:leotam,项目名称:cupic,代码行数:7,代码来源:scalar_test.py

示例11: testNonPeriodicBottomUp

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
  def testNonPeriodicBottomUp(self):
    """Test Non-periodic encoder bottom-up"""
    l = ScalarEncoder(name="scalar", n=14, w=5, minval=1, maxval=10,
                      periodic=False, forced=True)
    self.assertTrue(numpy.array_equal(
      l.encode(1),
      numpy.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  dtype=defaultDtype)))
    self.assertTrue(numpy.array_equal(
      l.encode(2),
      numpy.array([0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                  dtype=defaultDtype)))
    self.assertTrue(numpy.array_equal(
      l.encode(10),
      numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
                  dtype=defaultDtype)))

    # Test that we get the same encoder when we construct it using resolution
    #  instead of n
    d = l.__dict__
    l = ScalarEncoder(name="scalar", resolution=1, w=5, minval=1, maxval=10,
                       periodic=False, forced=True)
    self.assertEqual(l.__dict__, d)

    # Test that we get the same encoder when we construct it using radius
    #  instead of n
    l = ScalarEncoder(name="scalar", radius=5, w=5, minval=1, maxval=10,
                      periodic=False, forced=True)
    self.assertEqual(l.__dict__, d)

    # -------------------------------------------------------------------------
    # Test the input description generation and topDown decoding of a
    # non-periodic encoder
    v = l.minval
    while v < l.maxval:
      output = l.encode(v)
      decoded = l.decode(output)

      (fieldsDict, _) = decoded
      self.assertEqual(len(fieldsDict), 1)
      (ranges, _) = fieldsDict.values()[0]
      self.assertEqual(len(ranges), 1)
      (rangeMin, rangeMax) = ranges[0]
      self.assertEqual(rangeMin, rangeMax)
      self.assertLess(abs(rangeMin - v), l.resolution)

      topDown = l.topDownCompute(output)[0]
      self.assertTrue(numpy.array_equal(topDown.encoding, output))
      self.assertLessEqual(abs(topDown.value - v), l.resolution)

      # Test bucket support
      bucketIndices = l.getBucketIndices(v)
      topDown = l.getBucketInfo(bucketIndices)[0]
      self.assertLessEqual(abs(topDown.value - v), l.resolution / 2)
      self.assertEqual(topDown.scalar, topDown.value)
      self.assertTrue(numpy.array_equal(topDown.encoding, output))

      # Next value
      v += l.resolution / 4


    # Make sure we can fill in holes
    decoded = l.decode(numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1]))
    (fieldsDict, _) = decoded
    self.assertEqual(len(fieldsDict), 1)
    (ranges, _) = fieldsDict.values()[0]
    self.assertEqual(len(ranges), 1)
    self.assertTrue(numpy.array_equal(ranges[0], [10, 10]))

    decoded = l.decode(numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1]))
    (fieldsDict, _) = decoded
    self.assertEqual(len(fieldsDict), 1)
    (ranges, _) = fieldsDict.values()[0]
    self.assertEqual(len(ranges), 1)
    self.assertTrue(numpy.array_equal(ranges[0], [10, 10]))

    #Test min and max
    l = ScalarEncoder(name="scalar", n=14, w=3, minval=1, maxval=10,
                      periodic=False, forced=True)
    decoded = l.topDownCompute(
      numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]))[0]
    self.assertEqual(decoded.value, 10)
    decoded = l.topDownCompute(
      numpy.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]))[0]
    self.assertEqual(decoded.value, 1)

    #Make sure only the last and first encoding encodes to max and min, and
    #there is no value greater than max or min
    l = ScalarEncoder(name="scalar", n=140, w=3, minval=1, maxval=141,
                      periodic=False, forced=True)
    for i in range(137):
      iterlist = [0 for _ in range(140)]
      for j in range(i, i+3):
        iterlist[j] =1
      npar = numpy.array(iterlist)
      decoded = l.topDownCompute(npar)[0]
      self.assertLessEqual(decoded.value, 141)
      self.assertGreaterEqual(decoded.value, 1)
      self.assertTrue(decoded.value < 141 or i==137)
      self.assertTrue(decoded.value > 1 or i == 0)
#.........这里部分代码省略.........
开发者ID:leotam,项目名称:cupic,代码行数:103,代码来源:scalar_test.py

示例12: OneDDepthEncoder

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
class OneDDepthEncoder(Encoder):
  """
  Given an array of numbers, each representing distance to the closest object,
  returns an SDR representation of that depth data.

  At each given position, computes the closest distance within radius 3, and
  encodes that distance with a scalar encoder. The concatenation of all these
  scalar encodings is the final encoding.
  """

  def __init__(self,
               positions=range(36),
               radius=3,
               wrapAround=False,
               nPerPosition=57,
               wPerPosition=3,
               minVal=0,
               maxVal=1,
               name=None,
               verbosity=0):
    """
    See `nupic.encoders.base.Encoder` for more information.

    @param positions    (list) Positions at which to encode distance
    @param radius       (int)  Radius of positions over which to consider to get closest distance for encoding
    @param wrapAround   (bool) Whether radius should wrap around the sides of the input array
    @param nPerPosition (int)  Number of bits available for scalar encoder when encoding each position
    @param wPerPosition (int)  Number of bits active for scalar encoder when encoding each position
    @param minVal       (int)  Minimum distance that can be encoded
    @param maxVal       (int)  Maximum distance that can be encoded
    """
    self.positions = positions
    self.radius = radius
    self.wrapAround = wrapAround
    self.scalarEncoder = ScalarEncoder(wPerPosition, minVal, maxVal,
                                       n=nPerPosition,
                                       forced=True)
    self.verbosity = verbosity
    self.encoders = None

    self.n = len(self.positions) * nPerPosition
    self.w = len(self.positions) * wPerPosition

    if name is None:
      name = "[%s:%s]" % (self.n, self.w)
    self.name = name


  def getWidth(self):
    """See `nupic.encoders.base.Encoder` for more information."""
    return self.n


  def getDescription(self):
    """See `nupic.encoders.base.Encoder` for more information."""
    return [('data', 0)]


  def getScalars(self, inputData):
    """See `nupic.encoders.base.Encoder` for more information."""
    return numpy.array([0]*len(inputData))


  def encodeIntoArray(self, inputData, output):
    """
    See `nupic.encoders.base.Encoder` for more information.

    @param inputData (tuple) Contains depth data (numpy.array)
    @param output (numpy.array) Stores encoded SDR in this numpy array
    """
    output[:] = 0

    for i, position in enumerate(self.positions):
      indices = range(position-self.radius, position+self.radius+1)
      mode = 'wrap' if self.wrapAround else 'clip'
      values = inputData.take(indices, mode=mode)
      start = i * self.scalarEncoder.getWidth()
      end = (i + 1) * self.scalarEncoder.getWidth()
      output[start:end] = self.scalarEncoder.encode(max(values))


  def dump(self):
    print "OneDDepthEncoder:"
    print "  w:   %d" % self.w
    print "  n:   %d" % self.n


  @classmethod
  def read(cls, proto):
    encoder = object.__new__(cls)
    encoder.w = proto.w
    encoder.n = proto.n
    encoder.radius = proto.radius
    encoder.verbosity = proto.verbosity
    encoder.name = proto.name
    return encoder


  def write(self, proto):
    proto.w = self.w
#.........这里部分代码省略.........
开发者ID:akhilaananthram,项目名称:nupic.research,代码行数:103,代码来源:one_d_depth.py

示例13: SoundEncoder

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
class SoundEncoder(Encoder):
  """
  This is an implementation of a sound encoder. A sound wave is converted into
  the maximum frequency detected according to FFT, and this frequency is
  encoded into an SDR using a ScalarEncoder.
  """


  def __init__(self, n, w, rate, chunk, minval=20, maxval=20000, name=None):
    """
    @param n int the length of the encoded SDR
    @param w int the number of 1s in the encoded SDR
    @param rate int the number of sound samples per second
    @param chunk int the number of samples in an input
    @param minval float the lowest possible frequency detected
    @param maxval float the highest possible frequency detected
    @param name string the name of the encoder
    """
    self.n = n
    self.w = w
    self.rate = rate
    self.chunk  = chunk
    self.minval = minval
    self.maxval = maxval
    self.name = name
    self._scalarEncoder = ScalarEncoder(name="scalar_"+str(name), n=n, w=w,
                                        minval=minval, maxval=maxval)


  def _detectFrequency(self, inputArr):
    """Use FFT to find maximum frequency present in the input."""
    fftData=abs(np.fft.rfft(inputArr))**2
    maxFreqIdx = np.argmax(fftData)

    if maxFreqIdx < len(fftData)-1:
      # Quadratic interpolation
      y0, y1, y2 = np.log(fftData[maxFreqIdx-1:maxFreqIdx+2:])
      x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
      return (maxFreqIdx+x1)*(self.rate/self.chunk)

    # Maximum idx is last in list, so cannot do quadratic interpolation
    return (maxFreqIdx+x1)*(self.rate/self.chunk)


  def encodeIntoArray(self, inputArr, output):
    if not isinstance(inputArr, (list, np.ndarray)):
      raise TypeError(
          "Expected a list or numpy array but got input of type %s" % type(inputArr))

    if inputArr == SENTINEL_VALUE_FOR_MISSING_DATA:
      output[0:self.n] = 0
    else:
      frequency = self._detectFrequency(inputArr)
      # Fail fast if frequency is outside allowed range.
      if (frequency < self.minval) or (frequency > self.maxval):
        raise ValueError(
             "Frequency value %f is outside allowed range (%f, %f)" % (
                  frequency, self.minval, self.maxval))

      output[0:self.n] = self._scalarEncoder.encode(frequency)


  def getWidth(self):
    return self.n
开发者ID:Starcounter-Jack,项目名称:nupic.research,代码行数:66,代码来源:sound_encoder.py

示例14: testNaNs

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
 def testNaNs(self):
     """test NaNs"""
     mv = ScalarEncoder(name='mv', n=14, w=3, minval=1, maxval=8, periodic=False, forced=True)
     empty = mv.encode(float("nan"))
     print "\nEncoded missing data \'None\' as %s" % empty
     self.assertEqual(empty.sum(), 0)
开发者ID:AI-Cdrone,项目名称:nupic,代码行数:8,代码来源:scalar_test.py

示例15: testNaNs

# 需要导入模块: from nupic.encoders.scalar import ScalarEncoder [as 别名]
# 或者: from nupic.encoders.scalar.ScalarEncoder import encode [as 别名]
 def testNaNs(self):
   """test NaNs"""
   mv = ScalarEncoder(name="mv", n=14, w=3, minval=1, maxval=8,
                      periodic=False, forced=True)
   empty = mv.encode(float("nan"))
   self.assertEqual(empty.sum(), 0)
开发者ID:leotam,项目名称:cupic,代码行数:8,代码来源:scalar_test.py


注:本文中的nupic.encoders.scalar.ScalarEncoder.encode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。