where is the failture

cyyuu-bot: <p>import os<br>
import torch<br>
import numpy as np<br>
import matplotlib.pyplot as plt<br>
from torch.utils import data<br>
from torchvision import transforms<br>
from numpy import array<br>
from  sklearn . preprocessing   import   LabelEncoder<br>
from  sklearn . preprocessing   import   OneHotEncoder<br>
import time<br>
import torch<br>
import torch.nn as nn<br>
from torch.utils.data import DataLoader<br>
import string<br>
batch_size=64</p>
<p>step=40<br>
path1=‘E:\31data\data’<br>
path=r’E:\31data\data’<br>
pathlist=os.listdir(path)<br>
print(np.load(os.path.join(path,pathlist[0])).shape)<br>
class Dataset(data.Dataset):<br>
def <strong>init</strong>(self,root_dir):<br>
self.root=root_dir<br>
self.root_dir=os.listdir(self.root)<br>
def <strong>getitem</strong>(self, item):<br>
sample1=[]<br>
path_status=os.path.join(self.root,self.root_dir[item])<br>
Data=np.load(path_status)<br>
for  index in range(0,Data.shape[0],9116):<br>
sample_single=Data[0+index:243+index]<br>
sample1.append(sample_single)<br>
path = r’E:\31data\data’<br>
samples = os.listdir(path)<br>
characters = string.printable  # 表示所有可打印的 ASCII 字符<br>
token_index = dict(zip(characters, range(1, len(characters) + 1)))  # 将所有可打印的 ASCII 字符和数字组成一个词典用于后面查询<br>
max_length = 243<br>
results = np.zeros((64, max_length, max(token_index.values()) - 69))<br>
for i, sample in enumerate(samples):<br>
for j, character in enumerate(sample):<br>
index = token_index.get(31)  # 得到字母所对应的数字索引<br>
results[i, j, index] = 1<br>
results=torch.tensor(results)<br>
Data_tensor=torch.tensor(sample1)<br>
return Data_tensor,results<br>
def <strong>len</strong>(self):<br>
return len(self.root_dir)<br>
Mydataset=Dataset(path)<br>
traindata=np.stack([Mydataset[i][0] for i in range(31)])<br>
traindata=np.reshape(traindata,(-1,243,58))<br>
print(traindata.shape)<br>
traindata=torch.tensor(traindata)<br>
traindata=traindata.permute(0,2,1)<br>
print(traindata.shape)<br>
labeldata=np.stack([Mydataset[i][1] for i in range(31)])<br>
labeldata=torch.tensor(labeldata)<br>
print(labeldata.shape)<br>
labeldata=np.reshape(labeldata,(-1,243,31))<br>
trainset=list(zip(traindata,labeldata))</p>
<p>class Model(torch.nn.Module):<br>
class Model(torch.nn.Module):<br>
def <strong>init</strong>(self):<br>
super(Model, self).<strong>init</strong>()<br>
self.conv = torch.nn.Sequential(  # output=(input+2*padding-kernel_size)/stride+1<br>
torch.nn.Conv1d(in_channels=58, out_channels=128, kernel_size=5, stride=3, padding=1),<br>
torch.nn.ReLU(),  # input(64,58,243)-(64,128,81)<br>
torch.nn.MaxPool1d(stride=2, kernel_size=2),  # (64,128,40)</p>
<pre><code>            torch.nn.Conv1d(in_channels=128, out_channels=64, kernel_size=5, stride=3, padding=1),  # (128,64,13)
            torch.nn.ReLU(),
            torch.nn.MaxPool1d(stride=2, kernel_size=2),  # (64,64,6)

            torch.nn.Conv1d(in_channels=64, out_channels=32, kernel_size=4, stride=2, padding=1),  # (64,32,3)
            torch.nn.ReLU(),
            torch.nn.MaxPool1d(stride=2, kernel_size=2),  # (64,32,1)
        )
        self.fc = torch.nn.Linear(32, 31)

    def forward(self, x):
        x = self.conv(x)
        x = x.view(x.size()[0], -1)
        x = self.fc(x)
        y_hat = torch.nn.functional.softmax(x, dim=1)
        return y_hat
</code></pre>
<p>device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)</p>
<h1>
<a name="h-1" class="anchor" href="#h-1"></a>超参数</h1>
<p>batch_size = 64<br>
num_epochs = 10<br>
learning_rate = 5e-5<br>
device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)</p>
<h1>
<a name="h-2" class="anchor" href="#h-2"></a>获取数据集</h1>
<h1>
<a name="h-3" class="anchor" href="#h-3"></a>定义模型</h1>
<p>train_model = Model().to(device)<br>
criterion = nn.CrossEntropyLoss()<br>
optimizer = torch.optim.Adam(train_model.parameters(), lr=learning_rate)</p>
<h1>
<a name="train_size-intlentrainset-08-lentrain_dataset9372-4" class="anchor" href="#train_size-intlentrainset-08-lentrain_dataset9372-4"></a>train_size = int(len(trainset) * 0.8) <span class="hashtag">#len</span>(train_dataset)=9372</h1>
<h1>
<a name="printtrain_size-7497-5" class="anchor" href="#printtrain_size-7497-5"></a>print(train_size)  <span class="hashtag">#7497</span>
</h1>
<h1>
<a name="valid_size-intlentrainset-train_size-6" class="anchor" href="#valid_size-intlentrainset-train_size-6"></a>valid_size = int(len(trainset)) - train_size</h1>
<h1>
<a name="train_dataset-valid_dataset-torchutilsdatarandom_splittrainset-train_size-valid_size-7" class="anchor" href="#train_dataset-valid_dataset-torchutilsdatarandom_splittrainset-train_size-valid_size-7"></a>train_dataset, valid_dataset = torch.utils.data.random_split(trainset, [train_size, valid_size])</h1>
<p>train_loader = DataLoader(dataset=trainset, batch_size=batch_size, shuffle=True, drop_last=True)<br>
print(len(train_loader))</p>
<h1>
<a name="valid_loader-dataloaderdatasetvalid_dataset-batch_sizebatch_size-shuffletrue-drop_lasttrue-8" class="anchor" href="#valid_loader-dataloaderdatasetvalid_dataset-batch_sizebatch_size-shuffletrue-drop_lasttrue-8"></a>valid_loader = DataLoader(dataset=valid_dataset, batch_size=batch_size, shuffle=True, drop_last=True)</h1>
<h1>
<a name="def-test-9" class="anchor" href="#def-test-9"></a>def test():</h1>
<h1>
<a name="train_modelload_state_dicttorchloadecwrupytorch-cnn-cwru-masterdatarawdatanpy-10" class="anchor" href="#train_modelload_state_dicttorchloadecwrupytorch-cnn-cwru-masterdatarawdatanpy-10"></a>train_model.load_state_dict(torch.load(‘E:/cwru/pytorch-cnn-cwru-master/data/raw/data.npy’))</h1>
<h1>
<a name="torchsavenet-databest_modelpt-11" class="anchor" href="#torchsavenet-databest_modelpt-11"></a># torch.save(net, ‘data/best_model.pt’)</h1>
<h1>
<a name="train_modeleval-12" class="anchor" href="#train_modeleval-12"></a>train_model.eval()</h1>
<h1>
<a name="valid_acc-get_valid_acctrain_model-13" class="anchor" href="#valid_acc-get_valid_acctrain_model-13"></a>valid_acc = get_valid_acc(train_model)</h1>
<h1>
<a name="printvalid_acc-14" class="anchor" href="#printvalid_acc-14"></a>print(valid_acc)</h1>
<h1>
<a name="def-get_valid_accvalid_model-15" class="anchor" href="#def-get_valid_accvalid_model-15"></a>def get_valid_acc(valid_model):</h1>
<h1>
<a name="valid_modeleval-16" class="anchor" href="#valid_modeleval-16"></a>valid_model.eval()</h1>
<h1>
<a name="li-list-17" class="anchor" href="#li-list-17"></a>li = list()</h1>
<h1>
<a name="for-x_valid-y_valid-in-valid_loader-18" class="anchor" href="#for-x_valid-y_valid-in-valid_loader-18"></a>for x_valid, y_valid in valid_loader:</h1>
<h1>
<a name="x_valid-x_validtodevice-19" class="anchor" href="#x_valid-x_validtodevice-19"></a>x_valid = x_valid.to(device)</h1>
<h1>
<a name="y_valid-y_validtodevice-20" class="anchor" href="#y_valid-y_validtodevice-20"></a>y_valid = y_valid.to(device)</h1>
<h1>
<a name="y_hat-valid_modeltorchtensorx_valid-dtypetorchfloat64-21" class="anchor" href="#y_hat-valid_modeltorchtensorx_valid-dtypetorchfloat64-21"></a>y_hat = valid_model(torch.tensor(x_valid, dtype=torch.float64))</h1>
<h1>
<a name="y_hat-torchargmaxy_hat-1-22" class="anchor" href="#y_hat-torchargmaxy_hat-1-22"></a>y_hat = torch.argmax(y_hat, 1)</h1>
<h1>
<a name="y-torchargmaxy_valid-1-23" class="anchor" href="#y-torchargmaxy_valid-1-23"></a>y = torch.argmax(y_valid, 1)</h1>
<h1>
<a name="res-y_hat-y-24" class="anchor" href="#res-y_hat-y-24"></a>res = y_hat == y</h1>
<h1>
<a name="res2-resint-25" class="anchor" href="#res2-resint-25"></a>res2 = res.int()</h1>
<h1>
<a name="acc-res2sumitem-batch_size-26" class="anchor" href="#acc-res2sumitem-batch_size-26"></a>acc = res2.sum().item() / batch_size</h1>
<h1>
<a name="liappendacc-27" class="anchor" href="#liappendacc-27"></a>li.append(acc)</h1>
<h1>
<a name="valid_modeltrain-28" class="anchor" href="#valid_modeltrain-28"></a>valid_model.train()</h1>
<h1>
<a name="return-sumli-lenli-29" class="anchor" href="#return-sumli-lenli-29"></a>return sum(li) / len(li)</h1>
<p>def train():<br>
total_step = len(train_loader)         <span class="hashtag">#len</span>(train_loader)=58 len(valid_loader)=14<br>
acc_valid_old = 0<br>
a = time.time()<br>
for epoch in range(num_epochs):<br>
# li = list()<br>
for i, (trains, labels) in enumerate(train_loader):<br>
trains = trains.to(device)<br>
labels = labels.to(device,torch.float)<br>
# 预测和损失<br>
outputs = train_model(trains)<br>
print(outputs)<br>
loss = criterion(outputs, labels)<br>
print(loss)<br>
# 计算准确率<br>
# y_hat = torch.argmax(outputs, 1)<br>
# y = torch.argmax(labels, 1)<br>
# res = y_hat == y<br>
# res2 = res.int()<br>
# acc = res2.sum().item() / batch_size<br>
# li.append(acc)<br>
# 反向传播<br>
optimizer.zero_grad()<br>
loss.backward()<br>
optimizer.step()</p>
<pre><code>        if (i + 1) % 10 == 0:
            # acc_valid = get_valid_acc(train_model)
            print('Epoch: [{}/{}], Step: [{}/{}], Loss: {:.4f}  '
                  .format(epoch + 1, num_epochs, i + 1, total_step, loss.item() ))

            # if acc_valid &gt; acc_valid_old:
            #     torch.save(train_model.state_dict(), 'data/best.pt')
            #     acc_valid_old = acc_valid
    #     li = list()
    # b = time.time()
    # print(b - a)
    # a = time.time()
</code></pre>
<p>if <strong>name</strong> == ‘<strong>main</strong>’:<br>
train()<br>
# test()</p>
<p>Traceback (most recent call last):<br>
File “D:\pythonProject\fast.py”, line 101, in <br>
optimizer = torch.optim.Adam(train_model.parameters(), lr=learning_rate)<br>
File “D:\anaconda\envs\pytorch\lib\site-packages\torch\optim\adam.py”, line 137, in <strong>init</strong><br>
super(Adam, self).<strong>init</strong>(params, defaults)<br>
File “D:\anaconda\envs\pytorch\lib\site-packages\torch\optim\optimizer.py”, line 61, in <strong>init</strong><br>
raise ValueError(“optimizer got an empty parameter list”)<br>
ValueError: optimizer got an empty parameter list</p>

ptrblck: <p>I cannot reproduce the issue using this minimal code snippet taken from your post:</p>
<pre><code class="lang-python">class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv = torch.nn.Sequential(
            torch.nn.Conv1d(in_channels=58, out_channels=128, kernel_size=5, stride=3, padding=1),
            torch.nn.ReLU(),
            torch.nn.MaxPool1d(stride=2, kernel_size=2),
            torch.nn.Conv1d(in_channels=128, out_channels=64, kernel_size=5, stride=3, padding=1),
            torch.nn.ReLU(),
            torch.nn.MaxPool1d(stride=2, kernel_size=2),
            torch.nn.Conv1d(in_channels=64, out_channels=32, kernel_size=4, stride=2, padding=1), 
            torch.nn.ReLU(),
            torch.nn.MaxPool1d(stride=2, kernel_size=2), 
                )
        self.fc = torch.nn.Linear(32, 31)

    def forward(self, x):
        x = self.conv(x)
        x = x.view(x.size()[0], -1)
        x = self.fc(x)
        y_hat = torch.nn.functional.softmax(x, dim=1)
        return y_hat

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

train_model = Model().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(train_model.parameters(), lr=1.)
</code></pre>
<p>so I don’t know what might be causing the issue.</p>
<p>You can post code snippets by wrapping them into three backticks ```, which makes debugging easier.<br>
Feel free to update the code to a minimal and executable code snippet which would reproduce the issue, so that I could debug it further.</p>