summary(net, input_size=(3, 32, 32))TypeError: ‘module‘ object is not callable

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchsummary as summary



class LeNet(nn.Module):
    def __init__(self, classes):
        super(LeNet, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16*5*5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, classes)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.max_pool2d(out, 2)
        out = F.relu(self.conv2(out))
        out = F.max_pool2d(out, 2)
        out = out.view(out.size(0), -1)
        out = F.relu(self.fc1(out))
        out = F.relu(self.fc2(out))
        out = self.fc3(out)
        return out

    def initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.xavier_normal_(m.weight.data)
                if m.bias is not None:
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight.data, 0, 0.1)
                m.bias.data.zero_()


def lenet():
    return LeNet(classes=2)


if __name__ == "__main__":
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    net = lenet().to(device)
    net.initialize_weights()
    print(net)
    summary(net, input_size=(3, 32, 32))

 解决办法:

if __name__ == "__main__":
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    net = lenet().to(device)
    net.initialize_weights()
    print(net)
    summary.summary(net, input_size=(3, 32, 32))

 

 究其原因参考:https://blog.youkuaiyun.com/The_Time_Runner/article/details/85224843?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-2.control

# 实现线性层算子 class Linear(): def __init__(self, input_size, output_size, name, weight_init=torch.randn, bias_init=torch.zeros): """ 输入: - input_size:输入数据维度 - output_size:输出数据维度 - name:算子名称 - weight_init:权重初始化方式,默认使用'paddle.standard_normal'进行标准正态分布初始化 - bias_init:偏置初始化方式,默认使用全0初始化 """ self.params = {} # 初始化权重 self.params['W'] = weight_init([input_size,output_size]) # 初始化偏置 self.params['b'] = bias_init([1,output_size]) self.inputs = None self.name = name def forward(self, inputs): """ 输入: - inputs:shape=[N,input_size], N是样本数量 输出: - outputs:预测值,shape=[N,output_size] """ self.inputs = inputs outputs = torch.matmul(self.inputs, self.params['W']) + self.params['b'] return outputs class Logistic(): def __init__(self): self.inputs = None self.outputs = None def forward(self, inputs): """ 输入: - inputs: shape=[N,D] 输出: - outputs:shape=[N,D] """ outputs = 1.0 / (1.0 + torch.exp(-inputs)) self.outputs = outputs return outputs # 实现一个两层前馈神经网络 class Model_MLP_L2(): def __init__(self, input_size, hidden_size, output_size): """ 输入: - input_size:输入维度 - hidden_size:隐藏层神经元数量 - output_size:输出维度 """ self.fc1 = Linear(input_size, hidden_size ,name="fc1") self.fc2 = Linear(hidden_size, output_size ,name="fc2") def __call__(self, X): return self.forward(X) def forward(self, X): """ 输入: - X:shape=[N,input_size], N是样本数量 输出: - a2:预测值,shape=[N,output_size] """ z1 = self.fc1(X) a1 = Logistic(z1) z2 = self.fc2(a1) a2 = Logistic(z2) return a2 # 实例化模型 model = Model_MLP_L2(input_size=5, hidden_size=10, output_size=1) # 随机生成1条长度为5的数据 X = torch.rand([1, 5]) result = model(X) print ("result: ", result)运行时出现以下错误TypeError Traceback (most recent call last) Cell In[76], line 5 3 # 随机生成1条长度为5的数据 4 X = torch.rand([1, 5]) ----> 5 result = model(X) 6 print ("result: ", result) Cell In[75], line 14, in Model_MLP_L2.__call__(self, X) 13 def __call__(self, X): ---> 14 return self.forward(X) Cell In[75], line 23, in Model_MLP_L2.forward(self, X) 16 def forward(self, X): 17 """ 18 输入: 19 - X:shape=[N,input_size], N是样本数量 20 输出: 21 - a2:预测值,shape=[N,output_size] 22 """ ---> 23 z1 = self.fc1(X) 24 a1 = Logistic(z1) 25 z2 = self.fc2(a1) TypeError: 'Linear' object is not callable应该如何修改代码
最新发布
08-09
import tensorflow as tf import matplotlib.pyplot as plt # 数据集加载函数,指明数据集的位置并统一处理为imgheight*imgwidth的大小,同时设置batch def data_load(data_dir, test_data_dir, img_height, img_width, batch_size): # 加载训练集 train_ds = tf.keras.preprocessing.image_dataset_from_directory( data_dir, label_mode=&#39;categorical&#39;, seed=123, image_size=(img_height, img_width), batch_size=batch_size) # 加载测试集 val_ds = tf.keras.preprocessing.image_dataset_from_directory( test_data_dir, label_mode=&#39;categorical&#39;, seed=123, image_size=(img_height, img_width), batch_size=batch_size) class_names = train_ds.class_names # 返回处理之后的训练集、验证集和类名 return train_ds, val_ds, class_names # 构建mobilenet模型 # 模型加载,指定图片处理的大小和是否进行迁移学习 def model_load(IMG_SHAPE=(224, 224, 3), class_num=12): # 微调的过程中不需要进行归一化的处理 # 加载预训练的mobilenet模型 base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights=&#39;imagenet&#39;) # 将模型的主干参数进行冻结 base_model.trainable = False model = tf.keras.models.Sequential([ # 进行归一化的处理 tf.keras.layers.experimental.preprocessing.Rescaling(1. / 127.5, offset=-1, input_shape=IMG_SHAPE), # 设置主干模型 base_model, # 对主干模型的输出进行全局平均池化 tf.keras.layers.GlobalAveragePooling2D(), # 通过全连接层映射到最后的分类数目上 tf.keras.layers.Dense(class_num, activation=&#39;softmax&#39;) ]) model.summary() # 模型训练的优化器为adam优化器,模型的损失函数为交叉熵损失函数 model.compile(optimizer=&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;]) return model # 展示训练过程的曲线 def show_loss_acc(history): # 从history中提取模型训练集和验证集准确率信息和误差信息 acc = history.history[&#39;accuracy&#39;] val_acc = history.history[&#39;val_accuracy&#39;] loss = history.history[&#39;loss&#39;] val_loss = history.history[&#39;val_loss&#39;] # 按照上下结构将图画输出 plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.plot(acc, label=&#39;Training Accuracy&#39;) plt.plot(val_acc, label=&#39;Validation Accuracy&#39;) plt.legend(loc=&#39;lower right&#39;) plt.ylabel(&#39;Accuracy&#39;) plt.ylim([min(plt.ylim()), 1]) plt.title(&#39;Training and Validation Accuracy&#39;) plt.subplot(2, 1, 2) plt.plot(loss, label=&#39;Training Loss&#39;) plt.plot(val_loss, label=&#39;Validation Loss&#39;) plt.legend(loc=&#39;upper right&#39;) plt.ylabel(&#39;Cross Entropy&#39;) plt.title(&#39;Training and Validation Loss&#39;) plt.xlabel(&#39;epoch&#39;) plt.savefig(&#39;results/results_mobilenet.png&#39;, dpi=100) def train(epochs): import time # 开始训练,记录开始时间 begin_time = time() # todo 加载数据集, 修改为你的数据集的路径 train_ds, val_ds, class_names = data_load("d:/Users/DELL/Desktop/hua hua/hua/split_data/train", "d:/Users/DELL/Desktop/hua hua/hua/split_data/val", 224, 224, 16) print(class_names) # 加载模 model = model_load(class_num=len(class_names)) # 指明训练的轮数epoch,开始训练 history = model.fit(train_ds, validation_data=val_ds, epochs=epochs) # todo 保存模型, 修改为你要保存的模型的名称 model.save("models/mobilenet_flowers.h5") # 记录结束时间 end_time = time() run_time = end_time - begin_time print(&#39;该循环程序运行时间:&#39;, run_time, "s") # 该循环程序运行时间: 1.4201874732 # 绘制模型训练过程图 show_loss_acc(history) if __name__ == &#39;__main__&#39;: train(epochs=10) Traceback (most recent call last): File "D:/Users/DELL/Desktop/hua hua/hua/flower_tf2.3-master/train_cnn.py", line 100, in <module> train(epochs=10) File "D:/Users/DELL/Desktop/hua hua/hua/flower_tf2.3-master/train_cnn.py", line 81, in train begin_time = time() TypeError: &#39;module&#39; object is not callable
05-30
将下列代码修改成tensorflow2.3.0兼容的模式:class BSplineLayer(Layer): """自定义B样条基函数层""" def __init__(self, num_basis, degree=3, **kwargs): super(BSplineLayer, self).__init__(**kwargs) self.num_basis = num_basis self.degree = degree def build(self, input_shape): # 初始化B样条节点和系数 self.knots = self.add_weight( name=&#39;knots&#39;, shape=(self.num_basis + self.degree + 1,), initializer=&#39;glorot_uniform&#39;, trainable=True) self.coeffs = self.add_weight( name=&#39;coeffs&#39;, shape=(self.num_basis,), initializer=&#39;glorot_uniform&#39;, trainable=True) super(BSplineLayer, self).build(input_shape) def call(self, inputs): # B样条基函数计算 t = tf.linspace(-1.0, 1.0, self.num_basis + self.degree + 1) basis = tf.map_fn( lambda x: tf.math.bessel_j0( # 使用Bessel函数近似样条基 tf.reduce_sum(self.coeffs * tf.math.exp(-(x - self.knots)**2)) ), inputs) return basis class KANBlock(Layer): """KAN模块实现""" def __init__(self, num_basis, **kwargs): super(KANBlock, self).__init__(**kwargs) self.bspline_layer = BSplineLayer(num_basis=num_basis) def build(self, input_shape): self.bias = self.add_weight( name=&#39;bias&#39;, shape=(input_shape[-1],), initializer=&#39;zeros&#39;, trainable=True) super(KANBlock, self).build(input_shape) def call(self, inputs): # 分路径处理每个输入特征 spline_outputs = [] for i in range(inputs.shape[-1]): feature = inputs[..., i:i+1] spline_outputs.append(self.bspline_layer(feature)) # 合并并添加偏置 combined = tf.concat(spline_outputs, axis=-1) return combined + self.bias
04-01
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值