1
0
Files
AI-learning/lab/6_MLP-pt.ipynb
2025-01-25 22:33:14 +08:00

124 lines
3.4 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-20T07:32:36.354335Z",
"start_time": "2025-01-20T07:32:35.224080Z"
}
},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn as nn"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# 设置使用gpu7 cuda\n",
"device = torch.device(\"cuda:7\" if torch.cuda.is_available() and torch.cuda.get_device_properties(0).total_memory >= 6*1024**3 else \"cpu\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-20T07:32:38.297401Z",
"start_time": "2025-01-20T07:32:38.261009Z"
}
},
"outputs": [],
"source": [
"# 设置使用mps mps设备当前未支持限制内存\n",
"device = torch.device(\"mps\" if torch.backends.mps.is_available() else \"cpu\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"ExecuteTime": {
"end_time": "2025-01-20T07:32:39.972353Z",
"start_time": "2025-01-20T07:32:39.958549Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"MultiLayerPerceptron(\n",
" (hidden_layer1): Linear(in_features=10, out_features=20, bias=True)\n",
" (hidden_layer2): Linear(in_features=20, out_features=10, bias=True)\n",
" (output_layer): Linear(in_features=10, out_features=2, bias=True)\n",
" (activation1): ReLU()\n",
" (activation2): Sigmoid()\n",
")\n"
]
}
],
"source": [
"# 定义一个简单的神经元层\n",
"class MultiLayerPerceptron(nn.Module):\n",
" def __init__(self, input_size, hidden_size1, hidden_size2, output_size):\n",
" super(MultiLayerPerceptron, self).__init__()\n",
" self.hidden_layer1 = nn.Linear(input_size, hidden_size1)\n",
" self.hidden_layer2 = nn.Linear(hidden_size1, hidden_size2)\n",
" self.output_layer = nn.Linear(hidden_size2, output_size)\n",
" \n",
" # 定义不同的激活函数\n",
" self.activation1 = nn.ReLU() # 第一个隐藏层使用 ReLU\n",
" self.activation2 = nn.Sigmoid() # 第二个隐藏层使用 Sigmoid\n",
"\n",
" def forward(self, x):\n",
" # 第一个隐藏层及其激活函数\n",
" x = self.hidden_layer1(x)\n",
" x = self.activation1(x)\n",
" \n",
" # 第二个隐藏层及其激活函数\n",
" x = self.hidden_layer2(x)\n",
" x = self.activation2(x)\n",
" \n",
" # 输出层\n",
" x = self.output_layer(x)\n",
" return x\n",
"\n",
"# 创建一个MLP实例\n",
"mlp = MultiLayerPerceptron(input_size=10, hidden_size1=20, hidden_size2=10, output_size=2)\n",
"\n",
"# 打印模型结构\n",
"print(mlp)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "ail",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.14"
}
},
"nbformat": 4,
"nbformat_minor": 2
}