linsa11 commited on
Commit
fb22435
1 Parent(s): 7988aaa

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +21 -0
  3. configuration_MyResnet.py +26 -0
  4. model.safetensors +3 -0
  5. modeling_MyResnet.py +156 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MyResnetModelForImageClassification"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_MyResnet.MyResnetConfig",
7
+ "AutoModelForImageClassification": "modeling_MyResnet.MyResnetModelForImageClassification"
8
+ },
9
+ "in_channels": 3,
10
+ "model_type": "resnet",
11
+ "num_channels": 64,
12
+ "num_classes": 176,
13
+ "num_residuals": [
14
+ 2,
15
+ 2,
16
+ 2,
17
+ 2
18
+ ],
19
+ "torch_dtype": "float32",
20
+ "transformers_version": "4.45.2"
21
+ }
configuration_MyResnet.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ """
4
+ 编写自定义配置时需要记住的三个重要事项如下:
5
+ 必须继承自 PretrainedConfig,
6
+ PretrainedConfig 的 __init__ 方法必须接受任何 kwargs,
7
+ 这些 kwargs 需要传递给超类的 __init__ 方法。
8
+ """
9
+ class MyResnetConfig(PretrainedConfig):
10
+ model_type = "resnet"
11
+
12
+ def __init__(
13
+ self,
14
+ num_classes: int = 176, # 分类数
15
+ in_channels: int = 3, # 输入通道数
16
+ num_channels: int = 64, # 第一个卷积的输出通道数
17
+ num_residuals=None, # 每个残差块组合里残差块的数量
18
+ **kwargs,
19
+ ):
20
+ self.num_classes = num_classes
21
+ self.in_channels = in_channels
22
+ self.num_channels = num_channels
23
+ if num_residuals is None:
24
+ num_residuals = [2, 2, 2, 2]
25
+ self.num_residuals = num_residuals
26
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0f439c16a4605e7282c4bdfd481b9afdf1ff06ea6cd7ec471953e8ed243cf5d
3
+ size 45121784
modeling_MyResnet.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+ from transformers import PreTrainedModel
6
+ from .configuration_MyResnet import MyResnetConfig
7
+
8
+ # 设置CUDA异常阻塞,用于调试CUDA相关问题
9
+ os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
10
+
11
+ """
12
+ 定义自己的模型
13
+ """
14
+
15
+
16
+ # 定义残差块
17
+ class Residual(nn.Module):
18
+ def __init__(self, input_channels, num_channels,
19
+ use_1x1conv=False, strides=1):
20
+ super().__init__()
21
+ # 第一个3x3卷积层
22
+ self.conv1 = nn.Conv2d(input_channels, num_channels,
23
+ kernel_size=3, padding=1, stride=strides)
24
+ # 第二个3x3卷积层
25
+ self.conv2 = nn.Conv2d(num_channels, num_channels,
26
+ kernel_size=3, padding=1)
27
+ # 可选的1x1卷积层,用于调整输入的通道数
28
+ if use_1x1conv:
29
+ self.conv3 = nn.Conv2d(input_channels, num_channels,
30
+ kernel_size=1, stride=strides)
31
+ else:
32
+ self.conv3 = None
33
+ # 批量归一化层
34
+ self.bn1 = nn.BatchNorm2d(num_channels)
35
+ self.bn2 = nn.BatchNorm2d(num_channels)
36
+
37
+ def forward(self, X):
38
+ # 第一个卷积 -> 批量归一化 -> ReLU激活
39
+ Y = F.relu(self.bn1(self.conv1(X)))
40
+ # 第二个卷积 -> 批量归一化
41
+ Y = self.bn2(self.conv2(Y))
42
+ # 如果使用1x1卷积,调整输入的通道数
43
+ if self.conv3:
44
+ X = self.conv3(X)
45
+ # 将输入与输出相加
46
+ Y += X
47
+ return F.relu(Y) # 返回激活后的结果
48
+
49
+
50
+ # 组合多个残差块
51
+ def resnet_block(input_channels, num_channels, num_residuals,
52
+ first_block=False):
53
+ """
54
+ :param first_block: 是否为第一个块,用于确定是否需要1x1卷积
55
+ :param input_channels: 输入通道数
56
+ :param num_channels: 残差块的输出通道数
57
+ :param num_residuals: 残差块的数量
58
+ :return: 组合后的多个残差块
59
+ """
60
+ blk = []
61
+ for i in range(num_residuals):
62
+ # 第一个残差块需要降维
63
+ if i == 0 and not first_block:
64
+ blk.append(Residual(input_channels, num_channels,
65
+ use_1x1conv=True, strides=2))
66
+ else:
67
+ blk.append(Residual(num_channels, num_channels))
68
+ return blk
69
+
70
+
71
+ # 定义残差网络
72
+ def net(in_channels, num_channels, num_residuals, num_classes):
73
+ """
74
+ :param in_channels: 输入图像的通道数
75
+ :param num_channels: 第一个卷积层的输出通道数
76
+ :param num_residuals: 每个阶段的残差块数量
77
+ :param num_classes: 分类的数量
78
+ :return: 构建的残差网络模型
79
+ """
80
+ # 首先是一个7x7卷积层,接着是批量归一化、ReLU激活和3x3最大池化
81
+ b1 = nn.Sequential(nn.Conv2d(in_channels, num_channels, kernel_size=7, stride=2, padding=3),
82
+ nn.BatchNorm2d(64), nn.ReLU(),
83
+ nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
84
+
85
+ # 构建多个残差块
86
+ b2 = nn.Sequential(*resnet_block(64, num_channels, num_residuals[0], first_block=True))
87
+ b3 = nn.Sequential(*resnet_block(num_channels, num_channels * 2, num_residuals[1]))
88
+ b4 = nn.Sequential(*resnet_block(num_channels * 2, num_channels * 4, num_residuals[2]))
89
+ b5 = nn.Sequential(*resnet_block(num_channels * 4, num_channels * 8, num_residuals[3]))
90
+
91
+ # 全局平均池化后,连接一个全连接层进行分类
92
+ resnet = nn.Sequential(b1, b2, b3, b4, b5,
93
+ nn.AdaptiveAvgPool2d((1, 1)),
94
+ nn.Flatten(), nn.Linear(num_channels * 8, num_classes))
95
+ return resnet
96
+
97
+
98
+ """
99
+ 把模型封装成huggingface的模型,
100
+ 可以使用transformers库进行训练和推理
101
+ 这里定义了两个模型类:一个用于从一批图像中提取隐藏特征(类似于 BertModel),
102
+ 另一个适用于图像分类(类似于 BertForSequenceClassification)。
103
+ """
104
+
105
+
106
+ class MyResnetModel(PreTrainedModel):
107
+ config_class = MyResnetConfig # 指定配置类
108
+
109
+ def __init__(self, config):
110
+ super().__init__(config)
111
+ # 根据配置初始化模型
112
+ self.model = net(
113
+ in_channels=config.in_channels,
114
+ num_channels=config.num_channels,
115
+ num_residuals=config.num_residuals,
116
+ num_classes=config.num_classes
117
+ )
118
+
119
+ def forward(self, tensor, labels=None):
120
+ return self.model.forward_features(tensor) # 返回特征
121
+
122
+
123
+ class MyResnetModelForImageClassification(PreTrainedModel):
124
+ config_class = MyResnetConfig # 指定配置类
125
+
126
+ def __init__(self, config):
127
+ super().__init__(config)
128
+ # 根据配置初始化模型
129
+ self.model = net(
130
+ in_channels=config.in_channels,
131
+ num_channels=config.num_channels,
132
+ num_residuals=config.num_residuals,
133
+ num_classes=config.num_classes
134
+ )
135
+
136
+ """
137
+ 你可以让模型返回任何你想要的内容,
138
+ 但是像这样返回一个字典,并在传递标签时包含loss,可以使你的模型能够在 Trainer 类中直接使用。
139
+ 只要你计划使用自己的训练循环或其他库进行训练,也可以使用其他输出格式。
140
+ """
141
+
142
+ def forward(self, X, y):
143
+ # 前向传播,计算模型输出
144
+ # print(y)
145
+ y_hat = self.model(X)
146
+ if y is not None:
147
+ # 计算损失
148
+ loss = torch.nn.functional.cross_entropy(y_hat, y)
149
+ return {"loss": loss, "logits": y_hat} # 返回损失和输出
150
+ return {"logits": y_hat}
151
+
152
+ def forward_features(self, X):
153
+ # 返回特征
154
+ for layer in self.model:
155
+ X = layer(X)
156
+ print(layer.__class__.__name__, 'output shape:\t', X.shape)