{ "cells": [ { "cell_type": "code", "id": "initial_id", "metadata": { "collapsed": true, "ExecuteTime": { "end_time": "2025-06-16T08:22:25.477936Z", "start_time": "2025-06-16T08:22:25.474514Z" } }, "source": [ "import torch\n", "import torch.nn as nn" ], "outputs": [], "execution_count": 4 }, { "metadata": { "ExecuteTime": { "end_time": "2025-06-16T09:46:23.991077Z", "start_time": "2025-06-16T09:46:23.982065Z" } }, "cell_type": "code", "source": [ "input_feat = torch.tensor([[4, 1, 7, 5], [4, 4, 2, 5], [7, 7, 2, 4], [1, 0, 2, 4]], dtype=torch.float32).unsqueeze(0).unsqueeze(0)\n", "print(input_feat)\n", "print(input_feat.shape)" ], "id": "c2fef52f697ea63", "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor([[[[4., 1., 7., 5.],\n", " [4., 4., 2., 5.],\n", " [7., 7., 2., 4.],\n", " [1., 0., 2., 4.]]]])\n", "torch.Size([1, 1, 4, 4])\n" ] } ], "execution_count": 8 }, { "metadata": { "ExecuteTime": { "end_time": "2025-06-16T09:47:40.137555Z", "start_time": "2025-06-16T09:47:40.131166Z" } }, "cell_type": "code", "source": [ "conv2d = nn.Conv2d(1, 1, (2, 2), stride=1, padding='same', bias=False)\n", "# 卷积核要有四个维度:输出通道数,输入通道数,卷积核高度,卷积核宽度\n", "kernels = torch.tensor([[[[1, 0], [2, 1]]]], dtype=torch.float32)\n", "conv2d.weight = nn.Parameter(kernels, requires_grad=False) # 设置卷积核\n", "# 默认情况随机初始化参数\n", "print(conv2d.weight)\n", "print(conv2d.bias)" ], "id": "1903942bae26fde7", "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Parameter containing:\n", "tensor([[[[1., 0.],\n", " [2., 1.]]]])\n", "None\n" ] } ], "execution_count": 16 }, { "metadata": { "ExecuteTime": { "end_time": "2025-06-16T09:47:42.159880Z", "start_time": "2025-06-16T09:47:42.153928Z" } }, "cell_type": "code", "source": [ "output = conv2d(input_feat)\n", "output" ], "id": "8ebf518ec7c7bc70", "outputs": [ { "data": { "text/plain": [ "tensor([[[[16., 11., 16., 15.],\n", " [25., 20., 10., 13.],\n", " [ 9., 9., 10., 12.],\n", " [ 1., 0., 2., 4.]]]])" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "execution_count": 17 } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 5 }