メインコンテンツへスキップ
見出し画像
Photo bykyoto_gonchan

C言語でニューラルネットワークを作る 【Lv.9】 Activation層を導入する

    前回の復習

    前回のLv.8ではLinear層を導入しました。

    Linear
    ├── weight
    ├── bias
    └── forward()

    Linear層の状態(weight、bias)を保持するLinear構造体を導入し、線形変換の計算をおこなう linear_forward() を追加しました。

    Lv.9のテーマ:Activation層の導入

    今回のLv.9ではActivation層を導入します。

    Activation
    └── forward()

    Activation構造体を導入します。

    typedef double (*ActivationFunc)(double);
    
    typedef struct
    {
        ActivationFunc forward;
    
    } Activation;

    さらに、そのメンバであるforwardに活性化関数を設定します。

    Activation act = {step};

    今回の変更により、活性化関数を簡単に交換できるようになります。

    // 2種類のActivationを生成
    Activation act1 = {step};
    Activation act2 = {sigmoid};
    
    // ステップ関数を使った推論
    double output1 = predict(&linear, &act1, &input);
    
    // シグモイド関数を使った推論
    double output2 = predict(&linear, &act2, &input);

    補足

    関数のアドレス:
    C言語のプログラムを実行すると、コンパイルされた関数の機械語命令がメモリのどこかに配置されます。よって関数には、そこに配置された場所を示すアドレスがあります。

    構造体のメンバに関数を設定する:
    C言語では、関数そのものを構造体のメンバにすることはできません。しかし、関数へのポインタ(関数ポインタ)をメンバにすることはできます。これにより、構造体から関数をメンバのように呼び出すことができます。

    コード

    Lv.9のコード全体を表示します。

    0090.c

    /* C言語でニューラルネットワークを作る Lv.9 Activation層を導入する */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    /* ===== Vector ===== */
    
    /* ベクトル */
    typedef struct
    {
        /* サイズ */
        int size;
    
        /* データ */
        double* data;
    
    } Vector;
    
    
    /* ベクトル生成 */
    Vector vector_create(int size)
    {
        Vector vector;
    
        vector.size = size;
        vector.data = calloc(size, sizeof(double));
    
        if (vector.data == NULL)
            fprintf(stderr, "Memory allocation failed in vector_create.\n");
    
        return vector;
    }
    
    
    /* ベクトルのメモリ解放 */
    void vector_destroy(Vector* pVector)
    {
        free(pVector->data);
        pVector->data = NULL;
    }
    
    /* ===== Matrix ===== */
    
    /* 行列 */
    typedef struct
    {
        /* 行数 */
        int rows;
    
        /* 列数 */
        int cols;
    
        /* データ */
        double* data;
    
    } Matrix;
    
    
    /* 行列生成 */
    Matrix matrix_create(int rows, int cols)
    {
        Matrix matrix;
    
        matrix.rows = rows;
        matrix.cols = cols;
    
        matrix.data = calloc(rows * cols, sizeof(double));
    
        if (matrix.data == NULL)
            fprintf(stderr, "Memory allocation failed in matrix_create.\n");
    
        return matrix;
    }
    
    
    /* 行列のメモリ解放 */
    void matrix_destroy(Matrix* pMatrix)
    {
        free(pMatrix->data);
        pMatrix->data = NULL;
    }
    
    
    /* 行列の要素取得 */
    double matrix_get(const Matrix* pMatrix, int r, int c)
    {
        return pMatrix->data[r * pMatrix->cols + c];
    }
    
    
    /* 行列の要素設定 */
    void matrix_set(Matrix* pMatrix, int r, int c, double value)
    {
        pMatrix->data[r * pMatrix->cols + c] = value;
    }
    
    
    /* 行列の要素に値を加える */
    void matrix_add(Matrix* pMatrix, int r, int c, double value)
    {
        pMatrix->data[r * pMatrix->cols + c] += value;
    }
    
    /* ===== Operation ===== */
    
    /* Matrix × Vector */
    void matrix_mul_vector(const Matrix* pMatrix, const Vector* x, Vector* y)
    {
        for(int r = 0; r < pMatrix->rows; r++)
        {
            double sum = 0;
            
            for(int c = 0; c < pMatrix->cols; c++)
                sum += matrix_get(pMatrix, r, c) * x->data[c];
            
            y->data[r] = sum;
        }
    }
    
    
    /* 行列の1行をベクトルとして取得 */
    Vector matrix_get_row(const Matrix* pMatrix, int row)
    {
        Vector v = vector_create(pMatrix->cols);
    
        for(int c = 0; c < pMatrix->cols; c++)
            v.data[c] = matrix_get(pMatrix, row, c);
    
        return v;
    }
    
    /* ===== Linear Layer ===== */
    
    /* Linear */
    typedef struct
    {
        /* 重み */
        Matrix weight;
        
        /* バイアス */
        Vector bias;
        
    } Linear;
    
    
    /* Linear生成 */
    Linear linear_create(int in, int out)
    {
        Linear linear;
        
        linear.weight = matrix_create(out, in);
        linear.bias = vector_create(out);
        
        return linear;
    }
    
    
    /* Linearのメモリ解放 */
    void linear_destroy(Linear* pLinear)
    {
        matrix_destroy(&pLinear->weight);
        vector_destroy(&pLinear->bias);
    }
    
    
    /* Linear Forward */
    void linear_forward(const Linear* pLinear, const Vector* pInput, Vector* pOutput)
    {
        /* y = Wx */
        matrix_mul_vector(&pLinear->weight, pInput, pOutput);
    
        /* バイアスを加える */
        for(int i = 0; i < pOutput->size; i++)
            pOutput->data[i] += pLinear->bias.data[i];
    }
    
    /* ===== 活性化関数 ===== */
    
    /* ステップ関数 */
    double step(double x)
    {
        if (x >= 0)
            return 1.0;
        else
            return 0.0;
    }
    
    /* ===== Activation Layer ===== */
    
    /* Activation Func */
    typedef double (*ActivationFunc)(double);
    
    
    /* Activation */
    typedef struct
    {
        ActivationFunc forward;
    
    } Activation;
    
    
    /* Activation Forward */
    void activation_forward(const Activation* pAct, Vector* pInput, Vector* pOutput)
    {
        for(int i = 0; i < pInput->size; i++)
            pOutput->data[i] = pAct->forward(pInput->data[i]);
    }
    
    /* ===== パーセプトロン ===== */
    
    /* 推論 */
    double predict(const Linear* pLinear, Activation* pAct, const Vector* x)
    {
        Vector y = vector_create(pLinear->weight.rows);
    
        /* y = W x + b*/
        linear_forward(pLinear, x, &y);
    
        /* 活性化関数を適用 */
        activation_forward(pAct, &y, &y);
    
        double result = y.data[0];
    
        /* Vectorを解放 */
        vector_destroy(&y);
    
        return result;
    }
    
    
    /* 学習 */
    void train(Linear* pLinear, Activation* pAct,
        const Matrix* x, const Vector* t, double lr, int epoch)
    {
        for(int e = 0; e < epoch; e++)
        {
            for(int i = 0; i < x->rows; i++)
            {
                /* Matrixのi行目をVectorとして取得 */
                Vector input = matrix_get_row(x, i);
    
                /* 推論 */
                double output = predict(pLinear, pAct, &input);
    
                /* 誤差 */
                double error = t->data[i] - output;
    
                /* 重み更新 */
                for(int j = 0; j < pLinear->weight.cols; j++)
                    matrix_add(&pLinear->weight, 0, j, lr * error * input.data[j]);
    
                /* バイアス更新 */
                pLinear->bias.data[0] += lr * error;
                
                /* Vectorを解放 */
                vector_destroy(&input);
            }
        }
    }
    
    
    /* 開始 */
    int main(void)
    {
        /* 学習データ(ANDゲート) */
        Matrix x = matrix_create(4, 2);
    
        double data[][2] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};
    
        for(int i = 0; i < 4; i++)
            for(int j = 0; j < 2; j++)
                matrix_set(&x, i, j, data[i][j]);
    
        /* 教師データ */
        Vector t = vector_create(4);
    
        t.data[0] = 0;
        t.data[1] = 0;
        t.data[2] = 0;
        t.data[3] = 1;
    
        /* 2入力1出力のLinear生成 */
        Linear linear = linear_create(2,1);
    
        /* Activation生成 */
        Activation act = {step};
    
        /* 学習率 */
        double lr = 0.1;
    
        /* 学習 */
        train(&linear, &act, &x, &t, lr, 100);
    
        printf("=== 学習結果 ===\n\n");
    
        for(int i = 0; i < x.rows; i++)
        {
            Vector input = matrix_get_row(&x, i);
            
            double output = predict(&linear, &act, &input);
    
            printf("%.0f %.0f -> %.3f\n", input.data[0], input.data[1], output);
    
            vector_destroy(&input);
        }
    
        /* メモリを解放 */
        linear_destroy(&linear);
        matrix_destroy(&x);
        vector_destroy(&t);
    
        return 0;
    }
    

    ダウンロード

    下記のリポジトリからダウンロードできます。

    実行結果

    > cc .\0090.c
    > .\a.out
    === 学習結果 ===
    
    0 0 -> 0.000
    0 1 -> 0.000
    1 0 -> 0.000
    1 1 -> 1.000

    変更点

    Lv.9の主要な変更点を挙げます。

    ①Activation構造体の追加

    /* Activation Func */
    typedef double (*ActivationFunc)(double);
    
    
    /* Activation */
    typedef struct
    {
        ActivationFunc forward;
    
    } Activation;

    2行目

    typedef double (*ActivationFunc)(double);

    は、double型の引数を1つ受け取り、double型の値を返す関数へのポインタ型を定義しています。型名のActivationFuncは必ず (* と ) で囲みます。

    以前の解説に登場したtypedefの使い方(下記)とは異なっていますが、これも別の使い方です。

    typedef struct PERSON Person;

    4行目以降

    typedef struct
    {
        ActivationFunc forward;
    
    } Activation;

    は、上で定義したActivationFunc型を使って、Activation構造体のメンバ forward に関数を指すポインタを代入できるようにしています。

    Activation act;
    act.forward = step; // step関数を指す関数ポインタをforwardに代入
    
    // まとめて書くと
    // Activation act = {step};

    なお

    typedef double (*ActivationFunc)(double);
    
    
    typedef struct
    {
        ActivationFunc forward;
    
    } Activation;

    の全体をまとめて次のように書くこともできます。

    typedef struct
    {
        double (*forward)(double);
    
    } Activation;

    ②activation_forward()の追加

    void activation_forward(const Activation* pAct, Vector* pInput, Vector* pOutput)
    {
        for(int i = 0; i < pInput->size; i++)
            pOutput->data[i] = pAct->forward(pInput->data[i]);
    }

    act.forward = step なので、4行目

    pOutput->data[i] = pAct->forward(pInput->data[i])

    は

    pOutput->data[i] = step(pInput->data[i])

    の意味になります。

    ③predict()の変更

    変更前(Lv.8)

    int predict(const Linear* pLinear, const Vector* x)
    {
        Vector y = vector_create(pLinear->weight.rows);
    
        /* y = W x + b*/
        linear_forward(pLinear, x, &y);
    
        /* 活性化関数を適用 */
        int result = step(y.data[0]);
    
        /* Vectorを解放 */
        vector_destroy(&y);
    
        return result;
    }

    変更後(Lv.9)

    double predict(const Linear* pLinear, Activation* pAct, const Vector* x)
    {
        Vector y = vector_create(pLinear->weight.rows);
    
        /* y = W x + b*/
        linear_forward(pLinear, x, &y);
    
        /* 活性化関数を適用 */
        activation_forward(pAct, &y, &y);
    
        double result = y.data[0];
    
        /* Vectorを解放 */
        vector_destroy(&y);
    
        return result;
    }

    活性化関数の適用を

    // Lv.8
    int result = step(y.data[0]);
    // Lv.9
    activation_forward(pAct, &y, &y);
    
    double result = y.data[0];

    と変更しました。活性化関数を変更したいときは main() を変更すればよく、predict() は変更不要になりました。 なお train() の変更は必要です。

    また predict() 内では、ニューラルネットワークの推論計算

    z=w1x1+w2x2+bz = w_1x_1+ w_2x_2 + b
    y=step(z)y = step(z)

    を、linear_forward と activation_forward を並べて実現できました。

    linear_forward(pLinear, x, &z);
    
    activation_forward(pAct, &z, &y);
    
    double result = y.data[0];

    ここが今回のハイライトです。

    なお実際のコードではメモリ節約のため、&z を &y として値を上書きしています。

    ④ステップ関数の変更

    ステップ関数の返り値を int から double へ変更しました。

    double step(double x)
    {
        if (x >= 0)
            return 1.0;
        else
            return 0.0;
    }

    int のままだと ActivationFunc の定義(doubleを引数に取り、doubleを返す)と異なるので、関数ポインタの代入に支障が出てしまいます。

    さまざまな活性化関数

    活性化関数の主要な例を、コード付きで以下に挙げます。

    ①ステップ関数

    現在のコードで使用している関数です。

    f(x)={1(x≧0)0(x<0)f(x)=\begin{cases} 1 & (x \geqq 0) \\ 0 & (x < 0) \end{cases}

    double step(double x)
    {
        if (x >= 0)
            return 1.0;
        else
            return 0.0;
    }

    x=0 で微分不可能、 x=0 以外では 微分=0 という性質があります。これが今後の展開においてネックとなります。

    ②シグモイド関数

    ステップ関数と同様に0~1の範囲の数値を取りますが、微分可能かつ、微分≠0という性質があります。今後の展開において重要な関数です。

    f(x)=11+e−xf(x)=\frac{1}{1+e^{-x}}

    #include <math.h>
    
    double sigmoid(double x)
    {
        return 1.0 / (1.0 + exp(-x));
    }

    今後の記事では、行けるところまでステップ関数のままで進めますが、どこかの時点でシグモイド関数にバトンタッチする予定です。

    ③ハイパボリックタンジェント

    f(x)=tanh(x)≡ex−e−xex+e−xf(x)=tanh(x)\equiv\frac{e^x-e^{-x}}{e^x+e^{-x}}

    #include <math.h>
    
    double tanh_activation(double x)
    {
        return tanh(x);
    }

    ④ReLU

    現在のニューラルネットワークにおいて、非常によく使われます。

    f(x)=max(0,x)f(x)=max(0,x)
    もしくは
    f(x)={x(x>0)0(x≦0)f(x)=\begin{cases} x & (x > 0) \\ 0 & (x \leqq 0) \end{cases}

    double relu(double x)
    {
        if (x > 0)
            return x;
        else
            return 0.0;
    }

    ⑤Leakey ReLU

    f(x)={x(x>0)αx(x≦0)f(x)=\begin{cases} x & (x > 0) \\ αx & (x \leqq 0) \end{cases}

    double leaky_relu(double x)
    {
        const double alpha = 0.01;
    
        if (x > 0)
            return x;
        else
            return alpha * x;
    }

    おわりに

    Lv.9のまとめ

    コードの変更点:
    Activation構造体を導入しました。
    activation_forward()を追加しました。

    キーワード:
    活性化関数、関数ポインタ、ステップ関数、シグモイド関数、ReLU

    今後の予定

    前回から計算の部品化を進めています。推論計算(predict)をLinear層のForward、Activation層のForwardの組み合わせとして再構成できました。

    次回からは学習計算(train)に着手します。Lv.10では損失関数を導入します。

    参考文献

    • 中山清喬(2024)『スッキリわかるC言語入門 第3版』インプレス.

    • 斎藤康毅(2016)『ゼロから作る Deep Learning ―Pythonで学ぶディープラーニングの理論と実装』オライリー・ジャパン.

    • OpenAI(2026).ChatGPT(GPT-5.5).回答生成日:2026年7~9月.https://chatgpt.com

     
     
    プログラミングに興味があります。VBScriptとVBAを10年ほど使ってきました。VBScriptの廃止が決定されたのを機に、他のプログラミング言語の勉強を模索中です。

    あなたへのおすすめ