Skip to content

Instantly share code, notes, and snippets.

@binzume
Created October 16, 2013 10:10
Show Gist options
  • Save binzume/7005564 to your computer and use it in GitHub Desktop.
Save binzume/7005564 to your computer and use it in GitHub Desktop.
パーセプトロン
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
typedef double value_t;
template<int N>
class Vec {
value_t d[N];
public:
Vec() {}
Vec(const value_t a[N]) {
for (int i=0; i<N;i++) d[i] = a[i];
}
inline value_t operator*(const Vec<N> &a) const{
value_t prod = 0;
for (int i=0; i< N; i++) prod += d[i] * a[i];
return prod;
}
inline Vec<N> operator-(const Vec<N> &a) const{
Vec<N> r;
for (int i=0; i< N; i++) r[i] = d[i] - a[i];
return r;
}
inline Vec<N> operator*(const value_t &a) const{
Vec<N> r;
for (int i=0; i< N; i++) r[i] = d[i]*a;
return r;
}
inline Vec<N>& operator+=(const Vec<N> &a) {
for (int i=0; i< N; i++) d[i] += a[i];
return *this;
}
inline value_t& operator[](const int n) {
return d[n];
}
inline value_t operator[](const int n) const {
return d[n];
}
inline bool operator!=(const Vec<N> &a) const {
for (int i=0; i<N; i++) if (d[i] != a[i]) return true;
return false;
}
std::string to_s() {
std::stringstream ss;
ss << "[";
for (int i=0; i<N; i++) ss << d[i] << (i==N-1?"":",");
ss << "]";
return ss.str();
}
};
template<int IN, int OUT>
class Perceptron {
Vec<IN> weight[OUT];
double eta;
public:
Perceptron() : eta(0.5) {
for (int i=0; i<OUT; i++) {
for (int j=0; j<IN; j++) {
weight[i][j] = (double)(rand()%1024) / 1024;
}
}
}
Vec<OUT> predict(Vec<IN> input) {
Vec<OUT> out;
for (int i=0; i<OUT; i++) {
value_t net = weight[i] * input;
out[i] = net > 0 ? 1 : 0;
}
return out;
}
void learn(Vec<IN> input, Vec<OUT> teach) {
Vec<OUT> p = predict(input);
if (p != teach) {
for (int i=0; i<OUT; i++) {
weight[i] += input * eta * (teach-p)[i];
}
}
}
};
using namespace std;
int main() {
Perceptron<3,1> machine;
for (int i=0; i<50; i++) {
double in[] = {rand()%2, rand()%2, 1};
double out[] = { (int)in[0] & int(in[1]) };
machine.learn(in, out);
cout << Vec<3>(in).to_s() << " : " << Vec<1>(out).to_s() << endl;
}
for (int i=0; i<10; i++) {
double in[] = {rand()%2,rand()%2,1};
Vec<1> out = machine.predict(in);
cout << Vec<3>(in).to_s() << " => " << out.to_s() << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment