C语言实现神经网络中的卷积

卷积神经网络

看过darknet的同学可能知道这个项目中的卷积是把图像转换成列,此时的卷积操作就是一维数组相乘,据称这样效率比较高。这篇博客主要用C语言实现传统的卷积,就是基于滑动窗口的卷积,这样可能更接近我们所学的卷积,容易大家理解。

#include
#define M 18        //图像尺寸 18 *18 * 3
#define N 3			//卷积核尺寸 3 * 3 * 3
#define K 3       //卷积核数量


int image[3][M][M] = { 0 };
int kernal[K][N][N][N] = { 0 };
int out[K][M - N + 1][M - N + 1] = { 0 };
int temp = 0;

//初始化卷积核
void init_kernals()
{
	for (int a = 0; a < K; ++a)
	{
		for (int b = 0; b < N; ++b)
		{
			for (int c = 0; c < N; ++c)
			{
				for (int d = 0; d < N; ++d)
				{
					kernal[a][b][c][d] = rand() % 3;
				}
			}

		}
	}
}

//随机产生图像数据
void generate_matrix()
{

	// 除pad 初始化矩阵
	for (int i = 0; i < 3; ++i)
	{
		for (int row = 1; row <= M - N + 1; ++row)
		{
			for (int col = 1; col <= M - N + 1; ++col)
			{
				image[i][row][col] = rand() % 10;
			}
		}
	}

}

void print_kernal()
{
	for (int a = 0; a < K; ++a)
	{
		for (int b = 0; b < N; ++b)
		{
			for (int c = 0; c < N; ++c)
			{
				for (int d = 0; d < N; ++d)
				{
					printf("%d ", kernal[a][b][c][d]);
				}
				printf("\n");
			}
			printf("\n");
		}
		printf("\n");
	}

}

void convolutional()
{
	int ch = 0;
	int row = 0;
	int col = 0;

	for (int k = 0; k < K; ++k)
	{
		for (int ax = 1; ax <= M - N + 1; ++ax)
		{
			for (int ay = 1; ay <= M - N + 1; ++ay)
			{
				for (int c = 0; c < 3; ++c)
				{
					temp += image[c][ax - 1][ay - 1] * kernal[k][c][0][0] + image[c][ax - 1][ay] * kernal[k][c][0][1] + image[c][ax - 1][ay + 1] * kernal[k][c][0][2] +
						image[c][ax][ay - 1] * kernal[k][c][1][0] + image[c][ax][ay] * kernal[k][c][1][1] + image[c][ax][ay + 1] * kernal[k][c][1][2] +
						image[c][ax + 1][ay - 1] * kernal[k][c][2][0] + image[c][ax + 1][ay] * kernal[k][c][2][1] + image[c][ax + 1][ay + 1] * kernal[k][c][2][2];
				}

				out[ch][row][col] = temp;
				temp = 0;
				col++;
				if (col == M - N + 1)
				{
					col = 0;
					row++;
					if (row == M - N + 1)
					{
						row = 0;
						ch++;
					}

				}

			}
		}
	}
	
}

void print_data()
{
	for (int i = 0; i < 3; ++i)
	{
		for (int row = 0; row < M; ++row)
		{
			for (int col = 0; col < M; ++col)
			{
				printf("%d ", image[i][row][col]);
			}
			printf("\n");
		}
		printf("\n");
	}
}

void print_out_data()
{
	for (int ch = 0; ch < K;++ch)
	{
		for (int row = 0; row < M - N + 1; ++row)
		{
			for (int col = 0; col < M - N + 1; ++col)
			{
				printf("%d ", out[ch][row][col]);
			}
			printf("\n");
		}
		printf("\n");
	}
	
}

int main()
{
	generate_matrix();
	init_kernals();
	print_data();
	
	print_kernal();
	convolutional();
	print_out_data();
}


你可能感兴趣的:(C语言,深度学习,机器视觉)