Skip to content

Instantly share code, notes, and snippets.

@KatagiriSo
Created October 24, 2017 04:34
Show Gist options
  • Save KatagiriSo/0e0cde966f316985015f8f6b90222f87 to your computer and use it in GitHub Desktop.
Save KatagiriSo/0e0cde966f316985015f8f6b90222f87 to your computer and use it in GitHub Desktop.
Perceptron cpp
//
// perceptron2.cpp
// RDPerceptronSwift
//
// Created by KatagiriSo on 2017/10/24.
// Copyright © 2017年 RodhosSoft. All rights reserved.
//
#include "perceptron2.hpp"
#include <iostream>
#include <vector>
#include <algorithm>
namespace Percepron2 {
float prod(std::vector<float> &v1, std::vector<float> &v2);
template <typename T1, typename T2>
std::vector<std::pair<T1, T2>> zip(std::vector<T1> &v1, std::vector<T1> &v2);
float prod(std::vector<float> &v1, std::vector<float> &v2) {
auto pairs = zip<float, float>(v1, v2);
float ret = 0.0;
for (auto pair : pairs) {
ret += pair.first * pair.second;
}
return ret;
}
/// ステップ関数
float step(float x) {
return x>0 ? 1:0;
}
float forward(std::vector<float> &w, std::vector<float> &x) {
float u = prod(w,x);
return step(u);
}
/// e 学習率 x 入力 t 正解
void train(std::vector<float> &w, std::vector<float> &x, float t, float e) {
float z = forward(w, x);
for (int j=0;j<w.size();j++) {
w[j] += (t-z) * x[j] * e;
}
}
void learning(std::vector<float> &w, std::vector<std::vector<float>> &x, std::vector<float> t, float e) {
for (int i=0;i<x.size();i++) {
train(w, x[i], t[i], e);
}
}
void testcpp() {
// std::vector<float> v1 = {1.0,2.0};
// std::vector<float> v2 = {1.0,4.0};
// auto ret = prod(v1, v2);
// std::cout << ret << std::endl;
std::vector<std::vector<float>> x = {{1,0,0},{1,0,1},{1,1,1},{0,0,1}};
std::vector<float> t = {0,0,1,0};
std::vector<float> w = {0,0,0};
float e = 0.1;
int epoch = 10;
for (int i=0;i<epoch;i++) {
learning(w, x, t, e);
}
for (int i=0;i<x.size();i++) {
float ans = forward(w, x[i]);
std::cout << "ans" << ans << "---" << t[i] << std::endl;
}
}
template <typename T1, typename T2>
std::vector<std::pair<T1, T2>> zip(std::vector<T1> &v1, std::vector<T1> &v2) {
std::vector<std::pair<T1, T2>> pairlist = {};
for (int i=0;i<v1.size();i++) {
std::pair<T1, T2> pair = std::pair<T1, T2>(v1[i], v2[i]);
pairlist.push_back(pair);
}
return pairlist;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment