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


Python CoordinateEncoder.encode方法代码示例

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


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

示例1: PositionPredictionModel

# 需要导入模块: from nupic.encoders.coordinate import CoordinateEncoder [as 别名]
# 或者: from nupic.encoders.coordinate.CoordinateEncoder import encode [as 别名]
class PositionPredictionModel(Model):

  def __init__(self, motorValues=range(-4, 4+1),
               sparsity=0.02, encoderResolution=1.0, tmParams=None):
    super(PositionPredictionModel, self).__init__(motorValues=motorValues)
    tmParams = tmParams or {}
    self.tm = MonitoredExtendedTemporalMemory(mmName="TM", **tmParams)
    self.n = self.tm.numberOfColumns()
    self.w = int(self.n * sparsity) + 1
    self.encoderResolution = encoderResolution
    self.sensorEncoder = CoordinateEncoder(w=self.w, n=self.n)
    self.motorEncoder = CoordinateEncoder(w=self.w, n=self.n)


  def update(self, sensorValue, motorValue, goalValue=None):
    scale = 100
    radius = int(self.encoderResolution * scale)
    sensorInput = (numpy.array([int(sensorValue * scale)]), radius)
    motorInput = (numpy.array([int(motorValue * scale)]), radius)
    sensorPattern = set(self.sensorEncoder.encode(sensorInput).nonzero()[0])
    motorPattern = set(self.motorEncoder.encode(motorInput).nonzero()[0])

    self.tm.compute(sensorPattern,
                    activeExternalCells=motorPattern,
                    formInternalConnections=True,
                    learn=True)
开发者ID:andrewmalta13,项目名称:nupic.research,代码行数:28,代码来源:model.py

示例2: PositionPredictionModel

# 需要导入模块: from nupic.encoders.coordinate import CoordinateEncoder [as 别名]
# 或者: from nupic.encoders.coordinate.CoordinateEncoder import encode [as 别名]
class PositionPredictionModel(Model):

  def __init__(self, motorValues=range(-4, 4+1),
               sparsity=0.02, encoderResolution=1.0, tmParams=None):
    super(PositionPredictionModel, self).__init__(motorValues=motorValues)

    tmParams = dict(DEFAULT_TM_PARAMS)
    tmParams.update(tmParams or {})
    self.tm = MonitoredApicalTiebreakPairMemory(mmName="TM", **tmParams)
    self.n = self.tm.numberOfColumns()
    self.w = int(self.n * sparsity) + 1
    self.encoderResolution = encoderResolution
    self.sensorEncoder = CoordinateEncoder(w=self.w, n=self.n)
    self.motorEncoder = CoordinateEncoder(w=self.w, n=self.n)
    self.prevMotorPattern = ()


  def update(self, sensorValue, motorValue, goalValue=None):
    scale = 100
    radius = int(self.encoderResolution * scale)
    sensorInput = (numpy.array([int(sensorValue * scale)]), radius)
    motorInput = (numpy.array([int(motorValue * scale)]), radius)
    sensorPattern = set(self.sensorEncoder.encode(sensorInput).nonzero()[0])
    motorPattern = set(self.motorEncoder.encode(motorInput).nonzero()[0])

    self.tm.compute(sensorPattern,
                    activeCellsExternalBasal=motorPattern,
                    reinforceCandidatesExternalBasal=self.prevMotorPattern,
                    growthCandidatesExternalBasal=self.prevMotorPattern,
                    learn=True)

    self.prevMotorPattern = motorPattern
开发者ID:dubing12,项目名称:htmresearch,代码行数:34,代码来源:model.py

示例3: testEncodeIntoArray

# 需要导入模块: from nupic.encoders.coordinate import CoordinateEncoder [as 别名]
# 或者: from nupic.encoders.coordinate.CoordinateEncoder import encode [as 别名]
  def testEncodeIntoArray(self):
    n = 33
    w = 3
    encoder = CoordinateEncoder(name="coordinate", n=n, w=w)

    coordinate = np.array([100, 200])
    radius = 5
    output1 = encode(encoder, coordinate, radius)

    self.assertEqual(np.sum(output1), w)

    # Test that we get the same output for the same input
    output2 = encode(encoder, coordinate, radius)
    self.assertTrue(np.array_equal(output2, output1))

    # Test that a float radius raises an assertion error
    with self.assertRaises(AssertionError):
      encoder.encode((coordinate, float(radius)))
开发者ID:Erichy94,项目名称:nupic,代码行数:20,代码来源:coordinate_test.py

示例4: PositionBehaviorModel

# 需要导入模块: from nupic.encoders.coordinate import CoordinateEncoder [as 别名]
# 或者: from nupic.encoders.coordinate.CoordinateEncoder import encode [as 别名]
class PositionBehaviorModel(Model):

  def __init__(self, motorValues=range(-4, 4+1),
               sparsity=0.02, encoderResolution=0.5, bmParams=None):
    super(PositionBehaviorModel, self).__init__(motorValues=motorValues)
    self.encoderResolution = encoderResolution
    bmParams = bmParams or {}

    numMotorColumns = len(self.motorValues)
    bmParams["numMotorColumns"] = numMotorColumns
    self.bm = BehaviorMemory(**bmParams)

    self.sensorN = self.bm.numSensorColumns
    self.sensorW = int(self.sensorN * sparsity) + 1

    self.sensorEncoder = CoordinateEncoder(w=self.sensorW, n=self.sensorN)


  def update(self, sensorValue, motorValue, goalValue=None):
    motorPattern = set([self.motorValues.index(motorValue)])

    scale = 100
    radius = int(self.encoderResolution * scale)
    sensorInput = (numpy.array([int(sensorValue * scale)]), radius)
    sensorPattern = set(self.sensorEncoder.encode(sensorInput).nonzero()[0])

    goalPattern = set()
    if goalValue is not None:
      goalInput = (numpy.array([int(goalValue * scale)]), radius)
      goalPattern = set(self.sensorEncoder.encode(goalInput).nonzero()[0])

    self.bm.compute(motorPattern, sensorPattern, goalPattern)

    if goalValue is not None:
      return self.decodeMotor()


  def decodeMotor(self):
    idx = self.bm.motor.argmax()
    return self.motorValues[idx]
开发者ID:andrewmalta13,项目名称:nupic.research,代码行数:42,代码来源:model.py

示例5: ContinuousLocationObjectMachine

# 需要导入模块: from nupic.encoders.coordinate import CoordinateEncoder [as 别名]
# 或者: from nupic.encoders.coordinate.CoordinateEncoder import encode [as 别名]
class ContinuousLocationObjectMachine(ObjectMachineBase):
  """
  This implementation of the object machine uses continuous locations instead
  of discrete random ones. They are created using a CoordinateEncoder.

  The "objects" should be PhysicalObjects as defined in physical_object_base
  and physical_objects. Subclass the base implementation for specific needs.
  """

  def __init__(self,
               numInputBits=41,
               sensorInputSize=2048,
               externalInputSize=2048,
               numCorticalColumns=1,
               numFeatures=400,
               dimension=3,
               seed=42):
    """
    At creation, the SimpleObjectMachine creates a pool of locations and
    features SDR's.

    Parameters:
    ----------------------------
    @param   numInputBits (int)
             Number of ON bits in the input. Note: it should be uneven as the
             encoder only accepts uneven number of bits.

    @param   sensorInputSize (int)
             Total number of bits in the sensory input

    @param   externalInputSize (int)
             Total number of bits the external (location) input

    @param   numCorticalColumns (int)
             Number of cortical columns used in the experiment

    @param   dimension (int)
             Dimension of the locations. Will typically be 3.

    @param   numFeatures (int)
             Number of feature SDRs to generate per cortical column. There is
             typically no need to not use the default value, unless the user
             knows he will use more than 400 patterns.

    @param   seed (int)
             Seed to be used in the machine

    """
    super(ContinuousLocationObjectMachine, self).__init__(numInputBits,
                                                          sensorInputSize,
                                                          externalInputSize,
                                                          numCorticalColumns,
                                                          seed)

    # location and features pool
    self.numFeatures = numFeatures
    self._generateFeatures()

    self.dimension = dimension
    self.locationEncoder = CoordinateEncoder(
      w=numInputBits,
      n=externalInputSize,
      name="locationEncoder"
    )


  def provideObjectsToLearn(self, learningConfig, plot=False):
    """
    Returns the objects in a canonical format to be sent to an experiment.

    The input, learningConfig, should have the following format. It is a
    mapping from object to a list of features to sample locations from, and
    the number of points to sample from each feature. Note that these objects
    should be first added with .addObjects().
    These features can be either hard-coded with their key or accessed
    with .getFeatures.

    An other possibility is to directly specify locations. The machine will
    use the object to find the corresponding feature (an empty feature will
    be sent if the location is not on the object's surface).

    learningConfig = {
      # hard-coded keys and number of points
      "cube": [("face", 5), ("edge", 5), ("vertex", 3)],

      # programmatically-accessed keys and number of points
      "cylinder": [(feature, 5) for feature in cylinder.getFeatures()],

      # specific locations
      "sphere": [(10, 5, 3), (12, 45, 32), (12, 5, 46)],
    }

    The returned format is a a dictionary where the keys are object names, and
    values are lists of sensations, each sensation being a mapping from
    cortical column index to a pair of SDR's (one location and one feature).

    Parameters:
    ----------------------------
    @param   learningConfig (dict)
             Configuration for learning, as described above.
#.........这里部分代码省略.........
开发者ID:dubing12,项目名称:htmresearch,代码行数:103,代码来源:continuous_location_object_machine.py

示例6: Agent

# 需要导入模块: from nupic.encoders.coordinate import CoordinateEncoder [as 别名]
# 或者: from nupic.encoders.coordinate.CoordinateEncoder import encode [as 别名]
class Agent(object):

  def __init__(self):
    self.encoder = CoordinateEncoder(n=1024,
                                w=21)
    self.motorEncoder = ScalarEncoder(21, -1, 1,
                                 n=1024)
    self.tm = MonitoredExtendedTemporalMemory(
      columnDimensions=[2048],
      cellsPerColumn=1,
      initialPermanence=0.5,
      connectedPermanence=0.6,
      permanenceIncrement=0.1,
      permanenceDecrement=0.02,
      minThreshold=35,
      activationThreshold=35,
      maxNewSynapseCount=40)
    self.plotter = Plotter(self.tm, showOverlaps=False, showOverlapsValues=False)

    self.lastState = None
    self.lastAction = None


  def sync(self, outputData):
    if not ("location" in outputData and
            "steer" in outputData):
      print "Warning: Missing data:", outputData
      return

    reset = outputData.get("reset") or False

    if reset:
      print "Reset."
      self.tm.reset()

    location = outputData["location"]
    steer = outputData["steer"]

    x = int(location["x"] * SCALE)
    z = int(location["z"] * SCALE)
    coordinate = numpy.array([x, z])
    encoding = self.encoder.encode((coordinate, RADIUS))

    motorEncoding = self.motorEncoder.encode(steer)

    sensorPattern = set(encoding.nonzero()[0])
    motorPattern = set(motorEncoding.nonzero()[0])

    self.tm.compute(sensorPattern,
                    activeExternalCells=motorPattern,
                    formInternalConnections=True)

    print self.tm.mmPrettyPrintMetrics(self.tm.mmGetDefaultMetrics())

    self.plotter.update(encoding, reset)

    if reset:
      self.plotter.render()

    self.lastState = encoding
    self.lastAction = steer
开发者ID:andrewmalta13,项目名称:nupic.research,代码行数:63,代码来源:run_sm.py

示例7: CoordinateSensorRegion

# 需要导入模块: from nupic.encoders.coordinate import CoordinateEncoder [as 别名]
# 或者: from nupic.encoders.coordinate.CoordinateEncoder import encode [as 别名]
class CoordinateSensorRegion(PyRegion):
  """
  CoordinateSensorRegion is a simple sensor for sending coordinate data into
  networks using NuPIC's CoordinateEncoder.

  It accepts data using the command "addDataToQueue" or through the function
  addDataToQueue() which can be called directly from Python. Data is queued up
  in a FIFO and each call to compute pops the top element.

  Each data record consists of the coordinate in an N-dimensional integer
  coordinate space, a 0/1 reset flag, and an integer sequence ID.
  """

  def __init__(self,
               activeBits=21,
               outputWidth=1000,
               radius=2,
               verbosity=0):
    self.verbosity = verbosity
    self.activeBits = activeBits
    self.outputWidth = outputWidth
    self.radius = radius
    self.queue = deque()
    self.encoder = CoordinateEncoder(n=self.outputWidth, w=self.activeBits,
                                     verbosity=self.verbosity)

  @classmethod
  def getSpec(cls):
    """Return base spec for this region. See base class method for more info."""
    spec = {
      "description": CoordinateSensorRegion.__doc__,
      "singleNodeOnly": True,
      "inputs": {},  # input data is added to queue via "addDataToQueue" command
      "outputs": {
        "dataOut": {
          "description": "Encoded coordinate SDR.",
          "dataType": "Real32",
          "count": 0,
          "regionLevel": True,
          "isDefaultOutput": True,
        },
        "resetOut": {
          "description": "0/1 reset flag output.",
          "dataType": "UInt32",
          "count": 1,
          "regionLevel": True,
          "isDefaultOutput": False,
        },
        "sequenceIdOut": {
          "description": "Sequence ID",
          "dataType": "UInt32",
          "count": 1,
          "regionLevel": True,
          "isDefaultOutput": False,
        },
      },
      "parameters": {
        "activeBits": {
          "description": "The number of bits that are set to encode a single "
                         "coordinate value",
          "dataType": "uint",
          "accessMode": "ReadWrite",
          "count": 1,
          "defaultValue": 21
        },
        "outputWidth": {
          "description": "Size of output vector",
          "dataType": "UInt32",
          "accessMode": "ReadWrite",
          "count": 1,
          "defaultValue": 1000
        },
        "radius": {
          "description": "Radius around 'coordinate'",
          "dataType": "UInt32",
          "accessMode": "ReadWrite",
          "count": 1,
          "defaultValue": 2
        },
        "verbosity": {
          "description": "Verbosity level",
          "dataType": "UInt32",
          "accessMode": "ReadWrite",
          "count": 1
        },
      },
      "commands": {
        "addDataToQueue": {
          "description": CoordinateSensorRegion.addDataToQueue.__doc__,
        },
        "addResetToQueue": {
          "description": CoordinateSensorRegion.addResetToQueue.__doc__,
        }
      },
    }

    return spec

  def compute(self, inputs, outputs):
    """
#.........这里部分代码省略.........
开发者ID:dubing12,项目名称:htmresearch,代码行数:103,代码来源:CoordinateSensorRegion.py


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