i couldn't undestand what this lines of code do?












-1















This part of class i did not understand what does do in this code:



for file in os.listdir(path):
if(os.path.isfile(os.path.join(path,file)) and select in file):
temp = scipy.io.loadmat(os.path.join(path,file))
temp = {k:v for k, v in temp.items() if k[0] != '_'}
for i in range(len(temp[patch_type+"_patches"])):
self.tensors.append(temp[patch_type+"_patches"][i])
self.labels.append(temp[patch_type+"_labels"][0][i])

self.tensors = np.array(self.tensors)
self.labels = np.array(self.labels)


especially this line :



temp = {k:v for k, v in temp.items() if k[0] != '_'}


the whole class is as follow :



class Datasets(Dataset):
def __init__(self,path,train,transform=None):
if(train):
select ="Training"
patch_type = "train"
else:
select = "Testing"
patch_type = "testing"

self.tensors =
self.labels =
self.transform = transform


for file in os.listdir(path):
if(os.path.isfile(os.path.join(path,file)) and select in file):

temp = scipy.io.loadmat(os.path.join(path,file))
temp = {k:v for k, v in temp.items() if k[0] != '_'}
for i in range(len(temp[patch_type+"_patches"])):
self.tensors.append(temp[patch_type+"_patches"][i])
self.labels.append(temp[patch_type+"_labels"][0][i])

self.tensors = np.array(self.tensors)
self.labels = np.array(self.labels)

def __len__(self):
try:
if len(self.tensors) != len(self.labels):
raise Exception("Lengths of the tensor and labels list are not the same")
except Exception as e:
print(e.args[0])
return len(self.tensors)

def __getitem__(self,idx):
sample = (self.tensors[idx],self.labels[idx])
# print(self.labels)
sample = (torch.from_numpy(self.tensors[idx]),torch.from_numpy(np.array(self.labels[idx])).long())
return sample
#tuple containing the image patch and its corresponding label









share|improve this question

























  • where did you get this code? can you give me a link? also which line? or is it the part that its checking to see if a file exists?

    – user169808
    Nov 21 '18 at 12:52











  • At first glance, it appears to be cloning a dictionary minus the underscore prefixed keys.

    – Jared Smith
    Nov 21 '18 at 12:52











  • i couldnt find the repository from github but here is the whole class :

    – Daniel
    Nov 21 '18 at 13:47
















-1















This part of class i did not understand what does do in this code:



for file in os.listdir(path):
if(os.path.isfile(os.path.join(path,file)) and select in file):
temp = scipy.io.loadmat(os.path.join(path,file))
temp = {k:v for k, v in temp.items() if k[0] != '_'}
for i in range(len(temp[patch_type+"_patches"])):
self.tensors.append(temp[patch_type+"_patches"][i])
self.labels.append(temp[patch_type+"_labels"][0][i])

self.tensors = np.array(self.tensors)
self.labels = np.array(self.labels)


especially this line :



temp = {k:v for k, v in temp.items() if k[0] != '_'}


the whole class is as follow :



class Datasets(Dataset):
def __init__(self,path,train,transform=None):
if(train):
select ="Training"
patch_type = "train"
else:
select = "Testing"
patch_type = "testing"

self.tensors =
self.labels =
self.transform = transform


for file in os.listdir(path):
if(os.path.isfile(os.path.join(path,file)) and select in file):

temp = scipy.io.loadmat(os.path.join(path,file))
temp = {k:v for k, v in temp.items() if k[0] != '_'}
for i in range(len(temp[patch_type+"_patches"])):
self.tensors.append(temp[patch_type+"_patches"][i])
self.labels.append(temp[patch_type+"_labels"][0][i])

self.tensors = np.array(self.tensors)
self.labels = np.array(self.labels)

def __len__(self):
try:
if len(self.tensors) != len(self.labels):
raise Exception("Lengths of the tensor and labels list are not the same")
except Exception as e:
print(e.args[0])
return len(self.tensors)

def __getitem__(self,idx):
sample = (self.tensors[idx],self.labels[idx])
# print(self.labels)
sample = (torch.from_numpy(self.tensors[idx]),torch.from_numpy(np.array(self.labels[idx])).long())
return sample
#tuple containing the image patch and its corresponding label









share|improve this question

























  • where did you get this code? can you give me a link? also which line? or is it the part that its checking to see if a file exists?

    – user169808
    Nov 21 '18 at 12:52











  • At first glance, it appears to be cloning a dictionary minus the underscore prefixed keys.

    – Jared Smith
    Nov 21 '18 at 12:52











  • i couldnt find the repository from github but here is the whole class :

    – Daniel
    Nov 21 '18 at 13:47














-1












-1








-1








This part of class i did not understand what does do in this code:



for file in os.listdir(path):
if(os.path.isfile(os.path.join(path,file)) and select in file):
temp = scipy.io.loadmat(os.path.join(path,file))
temp = {k:v for k, v in temp.items() if k[0] != '_'}
for i in range(len(temp[patch_type+"_patches"])):
self.tensors.append(temp[patch_type+"_patches"][i])
self.labels.append(temp[patch_type+"_labels"][0][i])

self.tensors = np.array(self.tensors)
self.labels = np.array(self.labels)


especially this line :



temp = {k:v for k, v in temp.items() if k[0] != '_'}


the whole class is as follow :



class Datasets(Dataset):
def __init__(self,path,train,transform=None):
if(train):
select ="Training"
patch_type = "train"
else:
select = "Testing"
patch_type = "testing"

self.tensors =
self.labels =
self.transform = transform


for file in os.listdir(path):
if(os.path.isfile(os.path.join(path,file)) and select in file):

temp = scipy.io.loadmat(os.path.join(path,file))
temp = {k:v for k, v in temp.items() if k[0] != '_'}
for i in range(len(temp[patch_type+"_patches"])):
self.tensors.append(temp[patch_type+"_patches"][i])
self.labels.append(temp[patch_type+"_labels"][0][i])

self.tensors = np.array(self.tensors)
self.labels = np.array(self.labels)

def __len__(self):
try:
if len(self.tensors) != len(self.labels):
raise Exception("Lengths of the tensor and labels list are not the same")
except Exception as e:
print(e.args[0])
return len(self.tensors)

def __getitem__(self,idx):
sample = (self.tensors[idx],self.labels[idx])
# print(self.labels)
sample = (torch.from_numpy(self.tensors[idx]),torch.from_numpy(np.array(self.labels[idx])).long())
return sample
#tuple containing the image patch and its corresponding label









share|improve this question
















This part of class i did not understand what does do in this code:



for file in os.listdir(path):
if(os.path.isfile(os.path.join(path,file)) and select in file):
temp = scipy.io.loadmat(os.path.join(path,file))
temp = {k:v for k, v in temp.items() if k[0] != '_'}
for i in range(len(temp[patch_type+"_patches"])):
self.tensors.append(temp[patch_type+"_patches"][i])
self.labels.append(temp[patch_type+"_labels"][0][i])

self.tensors = np.array(self.tensors)
self.labels = np.array(self.labels)


especially this line :



temp = {k:v for k, v in temp.items() if k[0] != '_'}


the whole class is as follow :



class Datasets(Dataset):
def __init__(self,path,train,transform=None):
if(train):
select ="Training"
patch_type = "train"
else:
select = "Testing"
patch_type = "testing"

self.tensors =
self.labels =
self.transform = transform


for file in os.listdir(path):
if(os.path.isfile(os.path.join(path,file)) and select in file):

temp = scipy.io.loadmat(os.path.join(path,file))
temp = {k:v for k, v in temp.items() if k[0] != '_'}
for i in range(len(temp[patch_type+"_patches"])):
self.tensors.append(temp[patch_type+"_patches"][i])
self.labels.append(temp[patch_type+"_labels"][0][i])

self.tensors = np.array(self.tensors)
self.labels = np.array(self.labels)

def __len__(self):
try:
if len(self.tensors) != len(self.labels):
raise Exception("Lengths of the tensor and labels list are not the same")
except Exception as e:
print(e.args[0])
return len(self.tensors)

def __getitem__(self,idx):
sample = (self.tensors[idx],self.labels[idx])
# print(self.labels)
sample = (torch.from_numpy(self.tensors[idx]),torch.from_numpy(np.array(self.labels[idx])).long())
return sample
#tuple containing the image patch and its corresponding label






python scipy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 13:52







Daniel

















asked Nov 21 '18 at 12:48









DanielDaniel

41




41













  • where did you get this code? can you give me a link? also which line? or is it the part that its checking to see if a file exists?

    – user169808
    Nov 21 '18 at 12:52











  • At first glance, it appears to be cloning a dictionary minus the underscore prefixed keys.

    – Jared Smith
    Nov 21 '18 at 12:52











  • i couldnt find the repository from github but here is the whole class :

    – Daniel
    Nov 21 '18 at 13:47



















  • where did you get this code? can you give me a link? also which line? or is it the part that its checking to see if a file exists?

    – user169808
    Nov 21 '18 at 12:52











  • At first glance, it appears to be cloning a dictionary minus the underscore prefixed keys.

    – Jared Smith
    Nov 21 '18 at 12:52











  • i couldnt find the repository from github but here is the whole class :

    – Daniel
    Nov 21 '18 at 13:47

















where did you get this code? can you give me a link? also which line? or is it the part that its checking to see if a file exists?

– user169808
Nov 21 '18 at 12:52





where did you get this code? can you give me a link? also which line? or is it the part that its checking to see if a file exists?

– user169808
Nov 21 '18 at 12:52













At first glance, it appears to be cloning a dictionary minus the underscore prefixed keys.

– Jared Smith
Nov 21 '18 at 12:52





At first glance, it appears to be cloning a dictionary minus the underscore prefixed keys.

– Jared Smith
Nov 21 '18 at 12:52













i couldnt find the repository from github but here is the whole class :

– Daniel
Nov 21 '18 at 13:47





i couldnt find the repository from github but here is the whole class :

– Daniel
Nov 21 '18 at 13:47












2 Answers
2






active

oldest

votes


















2














It's a dict comprehension; in this particular case, it creates a new dict from an existing dict temp, but only for items for which the key k does not start with an underscore. That check is performed by the if ... part.



It is equivalent to



new = {}
for k, v in temp.items():
if key[0] != '_':
new[k] = value
temp = new


or, slightly different:



new = {}
for key, value in temp.items():
if not key.startswith('_'):
new[key] = value
temp = new


You can see that it looks a bit nicer as a single line, since it avoids a temporary dict (new; under the hood, it still creates a nameless temporary dict though).






share|improve this answer































    0














    It is filtering out the underscore-prefixed variables from the loaded MATLAB file. From the scipy documentation the function scipy.io.loadmat returns a dictionary containing the variable names from the loaded file as keys and the matricies as values. The line of code you reference is a dictionary comprehension that clones the dictionary minus the variables that fail the conditional check.



    Update



    What happens here is roughly this:




    1. Load a MATLAB file (file in your code) as a hashmap (dictionary) where the keys are the variable names from the file and the values are the matricies, assign to temp.

    2. Iterate through those key/value pairs and drop the underscore-prefixed ones and reassign the results of that iteration to temp.

    3. Profit






    share|improve this answer


























    • if i got you, the filename which starts with '_' is gonna be ignored to be assigned to temp ?

      – Daniel
      Nov 21 '18 at 13:31











    • @Daniel no it has nothing to do with the filename which is denoted by the variable file in the code you posted. I'll update my answer.

      – Jared Smith
      Nov 21 '18 at 13:40











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412389%2fi-couldnt-undestand-what-this-lines-of-code-do%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    It's a dict comprehension; in this particular case, it creates a new dict from an existing dict temp, but only for items for which the key k does not start with an underscore. That check is performed by the if ... part.



    It is equivalent to



    new = {}
    for k, v in temp.items():
    if key[0] != '_':
    new[k] = value
    temp = new


    or, slightly different:



    new = {}
    for key, value in temp.items():
    if not key.startswith('_'):
    new[key] = value
    temp = new


    You can see that it looks a bit nicer as a single line, since it avoids a temporary dict (new; under the hood, it still creates a nameless temporary dict though).






    share|improve this answer




























      2














      It's a dict comprehension; in this particular case, it creates a new dict from an existing dict temp, but only for items for which the key k does not start with an underscore. That check is performed by the if ... part.



      It is equivalent to



      new = {}
      for k, v in temp.items():
      if key[0] != '_':
      new[k] = value
      temp = new


      or, slightly different:



      new = {}
      for key, value in temp.items():
      if not key.startswith('_'):
      new[key] = value
      temp = new


      You can see that it looks a bit nicer as a single line, since it avoids a temporary dict (new; under the hood, it still creates a nameless temporary dict though).






      share|improve this answer


























        2












        2








        2







        It's a dict comprehension; in this particular case, it creates a new dict from an existing dict temp, but only for items for which the key k does not start with an underscore. That check is performed by the if ... part.



        It is equivalent to



        new = {}
        for k, v in temp.items():
        if key[0] != '_':
        new[k] = value
        temp = new


        or, slightly different:



        new = {}
        for key, value in temp.items():
        if not key.startswith('_'):
        new[key] = value
        temp = new


        You can see that it looks a bit nicer as a single line, since it avoids a temporary dict (new; under the hood, it still creates a nameless temporary dict though).






        share|improve this answer













        It's a dict comprehension; in this particular case, it creates a new dict from an existing dict temp, but only for items for which the key k does not start with an underscore. That check is performed by the if ... part.



        It is equivalent to



        new = {}
        for k, v in temp.items():
        if key[0] != '_':
        new[k] = value
        temp = new


        or, slightly different:



        new = {}
        for key, value in temp.items():
        if not key.startswith('_'):
        new[key] = value
        temp = new


        You can see that it looks a bit nicer as a single line, since it avoids a temporary dict (new; under the hood, it still creates a nameless temporary dict though).







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 12:56









        97699539769953

        1,5471316




        1,5471316

























            0














            It is filtering out the underscore-prefixed variables from the loaded MATLAB file. From the scipy documentation the function scipy.io.loadmat returns a dictionary containing the variable names from the loaded file as keys and the matricies as values. The line of code you reference is a dictionary comprehension that clones the dictionary minus the variables that fail the conditional check.



            Update



            What happens here is roughly this:




            1. Load a MATLAB file (file in your code) as a hashmap (dictionary) where the keys are the variable names from the file and the values are the matricies, assign to temp.

            2. Iterate through those key/value pairs and drop the underscore-prefixed ones and reassign the results of that iteration to temp.

            3. Profit






            share|improve this answer


























            • if i got you, the filename which starts with '_' is gonna be ignored to be assigned to temp ?

              – Daniel
              Nov 21 '18 at 13:31











            • @Daniel no it has nothing to do with the filename which is denoted by the variable file in the code you posted. I'll update my answer.

              – Jared Smith
              Nov 21 '18 at 13:40
















            0














            It is filtering out the underscore-prefixed variables from the loaded MATLAB file. From the scipy documentation the function scipy.io.loadmat returns a dictionary containing the variable names from the loaded file as keys and the matricies as values. The line of code you reference is a dictionary comprehension that clones the dictionary minus the variables that fail the conditional check.



            Update



            What happens here is roughly this:




            1. Load a MATLAB file (file in your code) as a hashmap (dictionary) where the keys are the variable names from the file and the values are the matricies, assign to temp.

            2. Iterate through those key/value pairs and drop the underscore-prefixed ones and reassign the results of that iteration to temp.

            3. Profit






            share|improve this answer


























            • if i got you, the filename which starts with '_' is gonna be ignored to be assigned to temp ?

              – Daniel
              Nov 21 '18 at 13:31











            • @Daniel no it has nothing to do with the filename which is denoted by the variable file in the code you posted. I'll update my answer.

              – Jared Smith
              Nov 21 '18 at 13:40














            0












            0








            0







            It is filtering out the underscore-prefixed variables from the loaded MATLAB file. From the scipy documentation the function scipy.io.loadmat returns a dictionary containing the variable names from the loaded file as keys and the matricies as values. The line of code you reference is a dictionary comprehension that clones the dictionary minus the variables that fail the conditional check.



            Update



            What happens here is roughly this:




            1. Load a MATLAB file (file in your code) as a hashmap (dictionary) where the keys are the variable names from the file and the values are the matricies, assign to temp.

            2. Iterate through those key/value pairs and drop the underscore-prefixed ones and reassign the results of that iteration to temp.

            3. Profit






            share|improve this answer















            It is filtering out the underscore-prefixed variables from the loaded MATLAB file. From the scipy documentation the function scipy.io.loadmat returns a dictionary containing the variable names from the loaded file as keys and the matricies as values. The line of code you reference is a dictionary comprehension that clones the dictionary minus the variables that fail the conditional check.



            Update



            What happens here is roughly this:




            1. Load a MATLAB file (file in your code) as a hashmap (dictionary) where the keys are the variable names from the file and the values are the matricies, assign to temp.

            2. Iterate through those key/value pairs and drop the underscore-prefixed ones and reassign the results of that iteration to temp.

            3. Profit







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 21 '18 at 13:42

























            answered Nov 21 '18 at 12:55









            Jared SmithJared Smith

            9,84432044




            9,84432044













            • if i got you, the filename which starts with '_' is gonna be ignored to be assigned to temp ?

              – Daniel
              Nov 21 '18 at 13:31











            • @Daniel no it has nothing to do with the filename which is denoted by the variable file in the code you posted. I'll update my answer.

              – Jared Smith
              Nov 21 '18 at 13:40



















            • if i got you, the filename which starts with '_' is gonna be ignored to be assigned to temp ?

              – Daniel
              Nov 21 '18 at 13:31











            • @Daniel no it has nothing to do with the filename which is denoted by the variable file in the code you posted. I'll update my answer.

              – Jared Smith
              Nov 21 '18 at 13:40

















            if i got you, the filename which starts with '_' is gonna be ignored to be assigned to temp ?

            – Daniel
            Nov 21 '18 at 13:31





            if i got you, the filename which starts with '_' is gonna be ignored to be assigned to temp ?

            – Daniel
            Nov 21 '18 at 13:31













            @Daniel no it has nothing to do with the filename which is denoted by the variable file in the code you posted. I'll update my answer.

            – Jared Smith
            Nov 21 '18 at 13:40





            @Daniel no it has nothing to do with the filename which is denoted by the variable file in the code you posted. I'll update my answer.

            – Jared Smith
            Nov 21 '18 at 13:40


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412389%2fi-couldnt-undestand-what-this-lines-of-code-do%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

            ComboBox Display Member on multiple fields

            Is it possible to collect Nectar points via Trainline?