{"cells":[{"metadata":{},"cell_type":"markdown","source":"![HPA](https://upload.wikimedia.org/wikipedia/commons/2/2c/HPA_logo.png)"},{"metadata":{},"cell_type":"markdown","source":" # Welcome to HPA. Part 1. \n \nHere we will get acquainted with the data and the topic of the competition,so that everything becomes  Clearly Explained!!!\n\n\n\n> Добро пожаловать в HPA. Часть 1. \n> Здесь мы познакомимся с данными и темой конкурса, чтобы все стало предельно ясно!!!\n"},{"metadata":{},"cell_type":"markdown","source":"\n"},{"metadata":{},"cell_type":"markdown","source":"The purpose of the competition: to classify different human cells by images. \nCells are the basic structural units of all living organisms. The bustling activity of the human cell is maintained as proteins perform specific tasks in designated compartments, called organelles.\n\n\nI want to give you quality study material where everything is well structured and explained. To do this, I need to receive feedback from you in the form of comments. And also, if you like it, support the notebook -  press the upvote button! =) Thanks!\n\n\n> Цель соревнования: классифицировать различные клетки человека по изображениям.\n> Клетки - это основные структурные единицы всех живых организмов. Активная активность человеческой клетки поддерживается, поскольку белки выполняют определенные задачи в определенных отсеках, называемых органеллами. \n\n> Я хочу давать вам качественный материал для изучения, где всё хорошо структруированно и объяснено. Для этого мне необходимо получать от вас фидбек в виде комментариев. А также, если это вам нравится - поддержите ноутбук и жмите кнопку \"за\" !=) Спасибо!"},{"metadata":{},"cell_type":"markdown","source":"# 1. Data\nLet us have a look at competiton data directory.\n> Давайте посмотрим на каталог данных соревнования."},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"\nimport os\nimport pandas as pd\nfrom glob import glob\nfrom tqdm.notebook import tqdm","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":false,"trusted":true},"cell_type":"code","source":"# directory\nprint('Competition Data/Files')\nROOT = '../input/hpa-single-cell-image-classification/'\nos.listdir(ROOT)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train\n\n\nМы имеем 2 тренировочных набора ('train' и 'train.csv'): \n>****train**** - здесь находится набор изображений с клетками человека. Для каждой клетки существует 4 изображения. Это связано с распознованием внутренностей клетки, ведь каждая органелла(компонент клетки) хорошо видна лишь в своём спектре. \n![](https://lh3.googleusercontent.com/PNfoiDzYAqHrzwBQQreV2Y1UB2XN9j62_ghb4y88gWMV86MS5gf_P9Gk7HzrlOjEMZySC0RhEKU6KorDnu4KS69sHIbGPabPQo1OZCHsMMkyAiEESyb2uufVxZ2x2wx8Q4sXrVzEkcEmCoZ73N2xV7IuMCwlW4VJ7mv6enOS2h76OVzioOXrCQGlUx37ItTT0ok3p4PfPKsnGPc_jb2ohTbLwIs_mZVkg6TxpbaqGRboNgsUTydCViEq3bZvlZqu4hUr_SY4ubbQXP8qfLN69tRtEhPxW4qaiUVv4s_wbtEQAypA30Hf10r9fhpbcR4Ybk8GZfE7jtaKRRwSLPiTtZRSADymASdG7D5gWXjjFqDKS5zIjrVi22FKXFRte6u9Mga_gNP5gq2N8o84VTnuPg_ph3VHozFs2FXRz66JUE1uI1hzxsZ0rxuI3ObWYgCR-aTiq89J_isZ1j-7vFtK8mLLyJrvW0q-l4SlZps3X7rFKv2fQC7LjFfTAaRa1z2o1RvwsSDpqAJl4F_WbPO0zanhUNwgi1eCJ-tD045C_CL4UN84G0v-GtWZPloLvud9dYTsG0Vg64MLqeBoB6RwzbaJah2q9V3O2hnAAnMODLVhTr5YE9xdj_O1DyBovvAmiyOxQc66fo4Es_og_xT4zisl-eIGgZoivBPCFFgvMsmsieE3g5-VauqE1PEg0w=w1366-h378-no?authuser=0)\n\n>****train.csv**** - содержит набор меток органелл к каждой клетке. Эти файлы выглядят вот так:"},{"metadata":{"_kg_hide-output":false,"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(os.path.join(ROOT, 'train.csv'))\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"\nWhat do these labels represent? \n\n| Label | Name | Description |\n|-|-|-|\n| 0. | Nucleoplasm | The nucleus is found in the center of cell and can be identified with the help of the signal in the blue nucleus channel. A staining of the nucleoplasm may include the whole nucleus or of the nucleus without the regions known as nucleoli (Class 2). |\n| 1. | Nuclear membrane | The nuclear membrane appears as a thin circle around the nucleus. It is not perfectly smooth and sometimes it is also possible to see the folds of the membrane as small circles or dots inside the nucleus. |\n| 2. | Nucleoli | Nucleoli can be seen as slightly elongated circular areas in the nucleoplasm, which usually display a much weaker staining in the blue DAPI channel. The number and size of nucleoli varies between cell types. |\n| 3. | Nucleoli fibrillar center | Nucleoli fibrillary center can appear as a spotty cluster or as a single bigger spot in the nucleolus, depending on the cell type. |\n| 4. | Nuclear speckles | Nuclear speckles can be seen as irregular and mottled spots inside the nucleoplasm. |\n| 5. | Nuclear bodies | Nuclear bodies are visible as distinct spots in the nucleoplasm. They vary in shape, size and numbers depending on the type of bodies as well as cell type, but are usually more rounded compared to nuclear speckles. |\n| 6. | Endoplasmic reticulum | The endoplasmic reticulum (ER) is recognized by a network-like staining in the cytosol, which is usually stronger close to the nucleus and weaker close to the edges of the cell. The ER can be identified with the help of the staining in the yellow ER channel. |\n| 7. | Golgi apparatus | The Golgi apparatus is a rather large organelle that is located next to the nucleus, close to the centrosome, from which the microtubules in the red channel originate. It has a folded ribbon-like appearance, but the shape and size can vary between cell types, and in response to cellular various processes. |\n| 8. | Intermediate filaments | Intermediate filaments often exhibit a slightly tangled structure with strands crossing every so often. They can appear similar to microtubules, but do not match well with the staining in the red microtubule channel. Intermediate filaments may extend through the whole cytosol, or be concentrated in an area close to the nucleus. |\n| 9. | Actin filaments | Actin filaments can be seen as long and rather straight bundles of filaments or as branched networks of thinner filaments. They are usually located close to the edges of the cells. |\n| 10. | Microtubules | Microtubules are seen as thin strands that stretch throughout the whole cell. It is almost always possible to detect the center from which they all originate (the centrosome). And yes, as you might have guessed, this overlaps the staining in the red channel. |\n| 11. | Mitotic spindle | The mitotic spindle can be seen as an intricate structure of microtubules radiating from each of the centrosomes at opposite ends of a dividing cell (mitosis). At this stage, the chromatin of the cell is condensed, as visible by intense DAPI staining. The size and exact shape of the mitotic spindle changes during mitotic progression, clearly reflecting the different stages of mitosis. |\n| 12. | Centrosome | This class includes centrosomes and centriolar satellites. They can be seen as a more or less distinct staining of a small area at the origin of the microtubules, close to the nucleus. When a cell is dividing, the two centrosomes move to opposite ends of the cell and form the poles of the mitotic spindle. |\n| 13. | Plasma membrane | This class includes plasma membrane and cell junctions. Both are at the outer edge of the cell. Plasma membrane sometimes appears as a more or less distinct edge around the cell, occasionally with characteristic protrusions or ruffles. In some cell lines, the staining can be uniform across the entire cell. Cell junctions can be observed at contact sites between neighboring cells. |\n| 14. | Mitochondria | Mitochondria are small rod-like units in the cytosol, which are often distributed in a thread-like pattern along microtubules. |\n| 15. | Aggresome | An aggresome can be seen as a dense cytoplasmic inclusion, which is usually found close to the nucleus, in a region where the microtubule network is disrupted. |\n| 16. | Cytosol | The cytosol extends from the plasma membrane to the nuclear membrane. It can appear smooth or granular, and the staining is often stronger close to the nucleus. |\n| 17. | Vesicles and punctate cytosolic patterns | This class includes small circular compartments in the cytosol: Vesicles, Peroxisomes (lipid metabolism), Endosomes (sorting compartments), Lysosomes (degradation of molecules or eating up dead molecules), Lipid droplets (fat storage), Cytoplasmic bodies (distinct granules in the cytosol). They are highly dynamic, varying in numbers and size in response to environmental and cellular cues. They can be round or more elongated. |\n| 18. | Negative | This class include negative stainings and unspecific patterns. This means that the cells have no green staining (negative), or have staining but no pattern can be deciphered from the staining (unspecific). |\n\n>\n>\n\n>Что означают эти ярлыки?\n\n> \n> | Этикетка | Имя | Описание | \n> |-|-|-|\n> |0.| Нуклеоплазма | Ядро находится в центре клетки и может быть идентифицировано с помощью сигнала в синем канале ядра. Окрашивание нуклеоплазмы может охватывать все ядро ​​или ядро ​​без участков, известных как ядрышки (класс 2). | \n> |1.| Ядерная мембрана | Ядерная мембрана выглядит как тонкий круг вокруг ядра. Он не идеально гладкий, и иногда можно также увидеть складки мембраны в виде маленьких кружков или точек внутри ядра. | \n> | 2. | Ядрышки | Ядрышки можно рассматривать как слегка удлиненные круглые области в нуклеоплазме, которые обычно имеют гораздо более слабое окрашивание в синем канале DAPI. Количество и размер ядрышек варьируется в зависимости от типа клеток. | \n> | 3. | Фибриллярный центр ядрышек | Фибриллярный центр ядрышек может выглядеть как пятнистый кластер или как единое более крупное пятно в ядрышке, в зависимости от типа клетки. | \n> | 4. | Ядерные спеклы | Ядерные спеклы можно рассматривать как неправильные и пестрые пятна внутри нуклеоплазмы. | \n> | 5. | Ядерные тела | Ядерные тела видны как отдельные пятна в нуклеоплазме. Они различаются по форме, размеру и количеству в зависимости от типа тел, а также от типа клеток, но обычно имеют более округлую форму по сравнению с ядерными крапинками. | \n> | 6. | Эндоплазматический ретикулум | Эндоплазматический ретикулум (ЭР) распознается по сетчатому окрашиванию в цитозоле, которое обычно сильнее вблизи ядра и слабее вблизи краев клетки. ER можно идентифицировать с помощью окрашивания желтого канала ER. | \n> | 7. | Аппарат Гольджи | Аппарат Гольджи представляет собой довольно крупную органеллу, которая находится рядом с ядром, недалеко от центросомы, от которой берут начало микротрубочки в красном канале. Он имеет вид свернутой ленты, но форма и размер могут варьироваться в зависимости от типа клеток и в ответ на различные клеточные процессы. | \n> | 8. | Промежуточные волокна | Промежуточные волокна часто демонстрируют слегка запутанная структура с частыми перекрещивающимися нитями. Они могут казаться похожими на микротрубочки, но не соответствуют окрашиванию красного канала микротрубочек. Промежуточные филаменты могут проходить через весь цитозоль или концентрироваться в области, близкой к ядру. | \n> | 9. | Актиновые нити | Актиновые филаменты можно увидеть как длинные и довольно прямые пучки филаментов или как разветвленные сети из более тонких филаментов. Обычно они располагаются близко к краям ячеек. | \n> | 10. | Микротрубочки | Микротрубочки представляют собой тонкие нити, тянущиеся по всей клетке. Почти всегда можно обнаружить центр, из которого все они происходят (центросома). И да, как вы могли догадаться, это перекрывает окрашивание в красном канале. |\n> | 11. | Митотическое веретено | Митотическое веретено можно рассматривать как сложную структуру микротрубочек, исходящих от каждой из центросом на противоположных концах делящейся клетки (митоз). На этом этапе хроматин клетки конденсируется, что видно по интенсивному окрашиванию DAPI. Размер и точная форма митотического веретена меняются во время митотической прогрессии, четко отражая различные стадии митоза. | \n> | 12. | Центросома | Этот класс включает центросомы и центриолярные сателлиты. Их можно увидеть как более или менее отчетливое окрашивание небольшого участка в начале микротрубочек, рядом с ядром. Когда клетка делится, две центросомы перемещаются к противоположным концам клетки и образуют полюса митотического веретена. | \n> | 13. | Плазменная мембрана | Этот класс включает плазматические мембраны и соединения клеток. Оба находятся на внешнем краю ячейки. Плазменная мембрана иногда выглядит как более или менее отчетливый край вокруг клетки, иногда с характерными выступами или складками. В некоторых клеточных линиях окрашивание может быть равномерным по всей клетке. Соединения клеток можно наблюдать в местах контакта между соседними клетками. | \n> | 14. | Митохондрии | Митохондрии маленькие палочковидные единиц цитозоля, которые часто распределены в виде нитей вдоль микротрубочек. |\n> | 15. | Агрессивный | Агресома может рассматриваться как плотное цитоплазматическое включение, которое обычно находится рядом с ядром, в области, где нарушена сеть микротрубочек. | \n> | 16. | Цитозоль | Цитозоль простирается от плазматической мембраны до ядерной мембраны. Он может казаться гладким или зернистым, а окраска часто более сильна вблизи ядра. |\n> | 17. | Пузырьки и точечные узоры цитозола | Этот класс включает небольшие кольцевые компартменты в цитозоле: везикулы, пероксисомы (липидный обмен), эндосомы (отсеки сортировки), лизосомы (разрушение молекул или поедание мертвых молекул), липидные капли (накопление жира), цитоплазматические тела (отдельные гранулы в цитозоль). Они очень динамичны, различаются по количеству и размеру в зависимости от внешних и клеточных сигналов. Они могут быть круглыми или более удлиненными. |\n> | 18. | Отрицательный | К этому классу относятся отрицательные окрашивания и неспецифические шаблоны. Это означает, что клетки не окрашены в зеленый цвет (отрицательно) или имеют окрашивание, но по окрашиванию нельзя определить рисунок (неспецифический). |\n\n* It looks like this.\n>На изображении это выглядит примерно так.\n\n![](https://naked-science.ru/wp-content/uploads/2017/05/field_image_screenshot-2017-05-15-10-45-26.png)"},{"metadata":{},"cell_type":"markdown","source":"# **Submission**\n"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"sample_sub = pd.read_csv(os.path.join(ROOT, 'sample_submission.csv'))\nsample_sub.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The file that we will have to send for verification: sample_submission.csv - contains ID, sizes and a string containing predictions(The PredicitionString column contains a string of label, confidence score for that classified label/organelle and mask information ecoded in RLE encoding and we are doing this for every cell present in the image. It may be possible that some of the cells in the image may not have the protein of interest.)\n\n\n\n> Файл, который мы должны будем отправить на проверку:\n> sample_submission.csv - содержит ID, размеры и строку, в которой записаны предсказания(Столбец PredicitionString содержит строку метки, оценку достоверности для этой классифицированной метки / органеллы и информацию о маске, в кодировке RLE, и мы делаем это для каждой клетки, присутствующей на изображении. Возможно, некоторые из клеток на изображении могут не содержать интересующий белок.)\n\n"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"print(f'We have {sample_sub.shape[0]} rows and {sample_sub.shape[1]} columns in our sample_sub.csv.')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"At the end, I suggest you relax and watch this video.\n> В конце предлогаю вам расслабиться и посмотреть это видео. \n"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"from IPython.display import HTML\n\nHTML('<center><iframe width=\"950\" height=\"450\" src=\"https://www.youtube.com/embed/P4gz6DrZOOI\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></center>')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Don't forget to vote=)** The next part will be an analysis.Thanks for watching.\n>Не забудьте проголосовать=) В следующей части будет анализ. Спасибо за просмотр. \n\n"}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}