初学pytorch,记录一下自己踩过的坑。
错误提示:
RuntimeError: Error(s) in loading state_dict for Sequential:
Missing key(s) in state_dict: "0.weight", "0.bias", "2.weight", "2.bias".
教程完整的代码
import torch
import torch.nn.functional as F
import numpy as np
######创建一个假数据######
n_data = torch.ones(100,2)
# 第一个数据集
x0 = torch.normal(2*n_data,1)
y0 = torch.zeros(100)
# 第二个数据集
x1 = torch.normal(-2*n_data,1)
y1 = torch.ones(100)
# 合并数据集 --> 合并 并改变格式
x = torch.cat((x0,x1),0).type(torch.FloatTensor) # 32位浮点数
y = torch.cat((y0,y1)).type(torch.LongTensor) # 64 位整型
######定义我们的神经网络#######
class Net(torch.nn.Module):
# n_feature 输入的神经元的数目 n_hidden 隐藏层中的神经元数目 n_output输入神经元的数目
def __init__(self,n_feature,n_hidden,n_output):
# 必要步骤 调用父类
super(Net,self).__init__()
self.hidden = torch.nn.Linear(n_feature,n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_output)
def forward(self,x):
x = F.relu(self.hidden(x))
x =self.predict(x)
return x