Beispiel #1
0
func (self *nnServer) apiLearn(w http.ResponseWriter, r *http.Request) {
	if !self.requireMethods(w, r, []string{"POST"}) {
		return
	}

	session, err := self.getSession(w, r)
	if err != nil {
		return
	}

	var req ApiLearnRequest
	decoder := json.NewDecoder(r.Body)
	err = decoder.Decode(&req)
	if err != nil {
		self.errorResponse(w, http.StatusBadRequest, "request could not been decoded: "+err.Error())
	}

	conf := &perceptron.PerceptronConf{
		Inputs:       req.Inputs,
		LearningRate: req.LearningRate,
		Threshold:    req.Threshold,
		Iterations:   req.Iterations,
	}

	net := perceptron.BuildPerceptronNet(conf)

	netUuid, err := uuid.NewV4()
	if err != nil {
		self.log.Error(err.Error())
	}
	netId := netUuid.String()
	self.nets[netId] = net
	session.Values["netId"] = netId
	err = session.Save(r, w)
	if err != nil {
		self.log.Error(err.Error())
	}

	weights, errors, err := net.Train(req.TrainData)
	if err != nil {
		self.log.Error(err.Error())
		return
	}

	data := self.makeData()
	data["weights"] = net.W
	data["iterations"] = weights
	data["iterations_errors"] = errors
	resp := ApiResponse{
		Status: "ok",
		Data:   data,
	}
	self.apiOkResponse(w, &resp)
}
Beispiel #2
0
func perceptron_test() {
	trainSet := []util.TrainExample{
		util.TrainExample{Input: []float64{1, 1, 1,
			0, 0, 0,
			0, 0, 0}, Output: []float64{0}},
		util.TrainExample{Input: []float64{0, 0, 0,
			1, 1, 1,
			0, 0, 0}, Output: []float64{0}},
		//		util.TrainExample{Input:[]float64{0, 0, 0,
		//			                              0, 0, 0,
		//			                              1, 1, 1}, Output:[]float64{0}},

		util.TrainExample{Input: []float64{1, 0, 0,
			1, 0, 0,
			1, 0, 0}, Output: []float64{1}},
		util.TrainExample{Input: []float64{0, 1, 0,
			0, 1, 0,
			0, 1, 0}, Output: []float64{1}},
		util.TrainExample{Input: []float64{0, 0, 1,
			0, 0, 1,
			0, 0, 1}, Output: []float64{1}},
	}

	conf := &perceptron.PerceptronConf{
		Inputs:       9,
		LearningRate: 1,
		Iterations:   1000,
		Threshold:    20,
	}
	net := perceptron.BuildPerceptronNet(conf)
	weights, errors, _ := net.Train(trainSet)
	fmt.Println(weights)
	fmt.Println(errors)

	for t := range trainSet {
		prediction, _ := net.Predict(trainSet[t].Input)
		fmt.Println(trainSet[t].Input, "=>", prediction)
	}
}