DAY35 模型可视化与推理

python 复制代码
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as np


iris=load_iris()
X=iris.data
y=iris.target

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)

print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)

from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler()
X_train=scaler.fit_transform(X_train)
X_test=scaler.transform(X_test)

X_train=torch.FloatTensor(X_train)
y_train=torch.LongTensor(y_train)
X_test=torch.FloatTensor(X_test)
y_test=torch.LongTensor(y_test)


import torch
import torch.nn as nn
import torch.optim

class MLP(nn.Module):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fc1=nn.Linear(4,10)
        self.relu=nn.ReLU()
        self.fc2=nn.Linear(10,3)

    def forward(self,x):
        out=self.fc1(x)
        out=self.relu(out)
        out=self.fc2(out)
        return out
    
model=MLP()


criterion=nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

num_epochs=20000
losses=[]
for epoch in range(num_epochs):
    outputs=model.forward(X_train)
    loss=criterion(outputs,y_train)# 预测损失

    # 反向传播和优化
    optimizer.zero_grad()
    loss.backward() # 反向传播计算梯度 
    optimizer.step() 

    losses.append(loss.item())

    if(epoch+1)%100==0:
        print(f'Epoch[{epoch+1}/{num_epochs}],Loss:{loss.item():.4f}')


import matplotlib.pyplot as plt
plt.plot(range(num_epochs),losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training Loss over Epochs')
plt.show()


python 复制代码
print(model)
python 复制代码
for name,param in model.named_parameters():
    print(f"Parameter name:{name},Shape:{param.shape}")
python 复制代码
import numpy as np
weight_data={}
for name,param in model.named_parameters():
    if 'weight' in name:
        weight_data[name]=param.detach().cpu().numpy()

fig,axes=plt.subplots(1,len(weight_data),figsize=(15,5))
fig.suptitle('Weight Distribution of Layers')

for i,(name,weights) in enumerate(weight_data.items()):
    weights_flat=weights.flatten()

    axes[i].hist(weights_flat,bins=50,alpha=0.7)
    axes[i].set_title(name)
    axes[i].set_xlabel('Weight Value')
    axes[i].set_ylabel('Frequency')
    axes[i].grid(True,linestyle='--',alpha=0.7)

plt.tight_layout()
plt.subplots_adjust(top=0.85)
plt.show()

print("\n===权重信息")
for name,weight in weight_data.items():
    mean=np.mean(weights)
    std=np.std(weights)
    min_val=np.min(weights)
    max_val=np.max(weights)
    print(f"{name}")
    print(f"均值:{mean:.6f}")
    print(f"标准差:{std:.6f}")
    print(f"最小值:{min_val:.6f}")
    print(f"最大值:{max_val:.6f}")
    print("-"*30)


python 复制代码
from torchsummary import summary
summary(model,input_size=(4,))
相关推荐
tlwlmy几秒前
python excel图片批量拼接导出
前端·python·excel
R-sz几秒前
坐标转换踩坑实录:UTM → WGS84 → GCJ02 前端后端一致实现
开发语言·前端·python
2301_816651221 分钟前
Python游戏中的碰撞检测实现
jvm·数据库·python
cm6543202 分钟前
Python Lambda(匿名函数):简洁之道
jvm·数据库·python
小陈工3 分钟前
ModelEngine智能体开发实战:知识库自动生成与多Agent协作
大数据·网络·数据库·人工智能·python·django·异步
小陈工5 分钟前
2026年3月23日技术资讯洞察:AI Agent失控,Claude Code引领AI编程新趋势
开发语言·数据库·人工智能·后端·python·性能优化·ai编程
蓝天星空10 分钟前
java、python、C# 编程语言的区别,不同开发语言平台对比有什么优势和缺点
java·开发语言·python
程序员三藏1 小时前
Selenium无法定位元素的几种解决方案
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
前端小趴菜~时倾1 小时前
自我提升-python爬虫学习:day04
爬虫·python·学习
小罗和阿泽1 小时前
接口测试系列 接口自动化测试 pytest框架(三)
开发语言·python·pytest