# Reza Amini Gougeh > Reza Amini Gougeh builds AI products in Montréal. Health AI, RAG pipelines, voice AI, and deep learning in production. Founded a startup and sold it. I'm Reza Amini Gougeh. I take AI ideas and turn them into things people actually use: a voice assistant a patient can talk to, a pipeline that catches Parkinson's in a recording, a search engine that cites its sources instead of making them up. This file is a machine-readable summary of https://magnumical.ca/, generated from the same content the site renders. ## Facts - **Who**: Reza Amini Gougeh, an AI and machine learning engineer. - **What I build**: Retrieval pipelines that cite their sources, voice assistants people talk to, and deep learning models that run in production rather than in a notebook. - **Based in**: Montréal, Québec, Canada. I have also worked in Ottawa and in Markham, Ontario, and several roles have been remote. - **Shipped**: A virtual companion for patients at Élisabeth Bruyère Hospital, Parkinson's detection models in production at Amplifier Health, federated learning decision support for the DREAM BIG consortium of 10+ institutions, and a full-stack AI product with voice and a citation engine that I built alone and then sold. - **Worked at**: Juztina LLC, Amplifier Health, CIUSSS West-Central Montreal at the Jewish General Hospital and the Lady Davis Institute, Huawei Technologies, and UQO with Élisabeth Bruyère Hospital. - **Studied**: MSc in telecommunication at INRS, University of Quebec, on motor imagery brain-computer interfaces and virtual reality. BSc in biomedical engineering at the University of Tabriz. - **Research**: Peer-reviewed papers on virtual reality, multisensory experience, brain-computer interfaces, and IoT health sensing, in Sensors, Frontiers, QoMEX, and IEEE MetroXRAINE. - **Languages**: English, Persian, Azerbaijani, and French. I write on this site in English and Persian. - **Writing**: 36 posts going back to 2018, 25 in English and 11 in Persian, on model architectures, hackathons, and the things I got wrong. - **Find me**: GitHub as magnumical, LinkedIn as rezaag, plus Google Scholar and ResearchGate. ## Pages - [Home](https://magnumical.ca/): who Reza Amini Gougeh is, the work, the projects, the papers. - [About](https://magnumical.ca/about): the longer version, with the degrees and the history. - [Projects](https://magnumical.ca/projects): things built, research and side builds alike. - [Writing](https://magnumical.ca/blog): every post, English and Persian. - [Topics](https://magnumical.ca/topics): the subjects the writing keeps returning to. - [RSS feed](https://magnumical.ca/feed.xml): the posts as a feed. ## Experience - **Founder, Building something new in legal tech** (Feb 2026 – Present, Montréal / Remote): Early-stage work on an AI product for legal teams. Too soon to say much publicly. Same pattern as last time: build the thing, put it in front of people, keep what works. - **AI Lead, Juztina LLC** (Dec 2025 – Present, Remote): Built the AI pipelines and data infrastructure behind the platform, and tuned LLM performance in production. The AI features cut churn by 10% and lifted feature adoption by 25%. Deployed on Azure and AWS EC2. - **Founder & Applied AI Engineer, Stealth AI Startup** (Oct 2025 – Feb 2026, Montréal / Remote): Shipped a full-stack AI product on my own: web platform, voice AI, audio features, plus RAG pipelines and a citation engine over a large document corpus. Made every technical call, then sold the company and the technology behind it. - **AI Engineer, Amplifier Health** (Feb 2025 – Oct 2025, Remote): Built the data pipelines and AI infrastructure, and put deep learning models into production for medical use, including Parkinson's detection. Ran the stack on GCP Cloud Run and AWS EC2. - **Lead Machine Learning Engineer, CIUSSS West-Central Montreal / Jewish General Hospital** (2024 – 2025, Montréal, QC): Led the AI work for precision medicine in the mental health department at the Lady Davis Institute. Took models from research question to something clinicians could actually use. - **HCI Research Engineer, Huawei Technologies** (2023 – 2024, Markham, ON): Built AI and IoT features for phones, homes, and cars, and cut system latency by 20%. Prototyped ideas, demoed them, and contributed to patents. - **Full-Stack Developer & AI Specialist, UQO / Élisabeth Bruyère Hospital** (Feb 2023 – Apr 2023, Ottawa, ON): Built a virtual companion for patients in Unity, running on the ChatGPT API. Improved speech recognition and text-to-speech, and engagement went up 55%. - **Machine Learning Engineer, CIUSSS West-Central Montreal / Jewish General Hospital** (2021 – 2023, Montréal, QC): Worked on DREAM BIG, a consortium of 10+ institutions studying how genes, prenatal adversity, and early childhood environment shape children's wellbeing. Built federated-learning decision support systems and hardened the models to keep sensitive data safe. ## Education - **MSc, Telecommunication**, INRS, University of Quebec (2021 – 2022). Thesis: Enhancing motor imagery-based brain-computer interface efficacy using multisensory virtual reality training. - **BSc, Biomedical Engineering**, University of Tabriz (2016 – 2020). Where the signal processing and medical side of my work started. ## Awards - Outstanding Team Award, Huawei Canadian Research Centre - MEITA, McGill University - Graduate Excellence Fellowship, McGill University - International Student Tuition Exemption, University of Quebec - 1st place, Popular Vote, and Best SSVEP Game, BCI Game Jam ## Skills - **Machine learning**: Python, PyTorch, TensorFlow, scikit-learn, pandas, NumPy, SHAP, LIME - **LLMs and RAG**: RAG design, LangChain, LangGraph, LangSmith, OpenAI, Gemini, Claude, Retell.ai voice AI - **Data and storage**: PostgreSQL, Supabase, Milvus, Qdrant, pgvector - **Shipping and ops**: Docker, Kubernetes, GCP, AWS, Azure, CI, MLflow, DVC, Weights & Biases - **Product surface**: FastAPI, Flask, Django, Streamlit, Stripe, Unity ## Projects Some were research, some were weekend builds, some turned into products. All of them ran. - **Quick Talk** (2023, GPT-4, RAG, Monitoring): A conversational companion built on GPT-4 with retrieval so it answers from real documents. Wired up to Grafana so I could watch it behave in production. - **Keira** (2023, Voice AI, Health, Encryption): An AI companion for dementia patients at Bruyère, with ElevenLabs voice and end-to-end encryption. Built for people who need patience more than speed. - **[ImmerseGuard](https://magnumical.ca/blog/immerseguard-bridging-immersion-and-environmental-awareness)** (2024, VR, Safety, HCI): VR is great until you walk into a wall. This one keeps you inside the experience while still telling you what's happening in the room. - **[SmartBib](https://magnumical.ca/p/extract-relevant-papers)** (2024, NLP, Research tools, Python): Point it at a BibTeX file with thousands of papers and it hands back the ones that actually matter to your topic. Built while writing a literature review. - **[McGillian GreenQuest](https://magnumical.ca/p/greenquest)** (2024, LLM, Assistant, Sustainability): An assistant that answers real questions about sustainability on the McGill campus: what to recycle, how to save energy, how to get around. - **[Fill blanks](https://magnumical.ca/p/fillblanks)** (2024, LLM, Automation, Forms): Give it a template with gaps and it asks you the questions needed to fill them. Form filling without the form. - **[Chit Chat Charm](https://magnumical.ca/blog/chit-chat-charm)** (2023, NLP, Voice, Avatars): An AI conversation you can see and hear, not just read. Text, voice, and a face, put together into one experience. - **[MuSAE Games](https://magnumical.ca/blog/bci-game-jam-2021-musae-games)** (2021, BCI, EEG, Games): A multiplayer game for disabled kids, controlled entirely by brain signals using SSVEP. Won the BCI Game Jam overall, plus the popular vote and best SSVEP game. - **[COVID-19 chest X-ray classifier](https://magnumical.ca/blog/an-online-automatic-corona-diagnose-system-based-on-chest-x-ray-images)** (2020, Deep learning, Medical imaging, Robustness): An online tool that reads a chest X-ray and flags likely COVID cases. Built early in the pandemic, then tested against adversarial attacks to see how fragile it really was. ## Publications A systematic review, a multisensory study, an instrumented headset, and the sound-detection work behind ImmerseGuard. - [Systematic Review of IoT-Based Solutions for User Tracking: Towards Smarter Lifestyle, Wellness and Health Management](https://doi.org/10.3390/s24185939). Sensors, 2024. - [Optimizing Auditory Immersion Safety on Edge Devices: An On-Device Sound Event Detection System](https://doi.org/10.21437/odyssey.2024-32). Odyssey, 2024. - [Multisensory Immersive Experiences: A Pilot Study on Subjective and Instrumental Human Influential Factors Assessment](https://doi.org/10.1109/qomex55416.2022.9900907). QoMEX, 2022. - [Towards instrumental quality assessment of multisensory immersive experiences using a biosensor-equipped head-mounted display](https://doi.org/10.1007/s41233-023-00062-7). Quality and User Experience, 2023. ## Profiles If you're building something in AI and want another pair of hands on it, or you just want to talk about a problem, reach out on LinkedIn or GitHub. I answer. - [GitHub](https://github.com/magnumical) - [LinkedIn](https://www.linkedin.com/in/rezaag) - [Google Scholar](https://scholar.google.com/citations?user=XDYSTfkAAAAJ&hl=en) - [ResearchGate](https://www.researchgate.net/profile/Reza-Amini-Gougeh) ## Posts (36, full text, newest first) ### Using HuggingFace without sharing your code! URL: https://magnumical.ca/blog/using-huggingface-without-sharing-your-code Published: 2024-07-16 (updated 2024-07-16) Language: English In short: you can run a Python project on HuggingFace Spaces while the source stays in a private GitHub repo. Here is the three-step setup, with the code that does the cloning. Ever wanted to breathe life into one of your Python projects? HuggingFace Spaces is a great place to showcase and share a machine learning model. But what if you want to keep the code private? Here is how. - Push the code somewhere private Upload the project to a private GitHub repository so it is not publicly readable. - Clone it at runtime Give the Space your credentials as environment variables and pull the repo when the app starts. - Deploy the wrapper to Spaces Only the thin launcher lives on HuggingFace. The real code arrives at runtime. Step 1: Put the code in a private GitHub repo Upload your project to a private GitHub repository. That keeps the code out of public view. Store your GitHub Personal Access Token (PAT) and any other credentials securely. Step 2: Set up the environment and clone the repo Next, set up your environment to use those credentials. Here is one way to do it in Python. from git import Repo import os # Retrieve the environment variables GITHUB_PAT = os.getenv('GITHUB_PAT') GIT_id = os.getenv('GIT_id') GIT_repo = os.getenv('GIT_repo') if GITHUB_PAT: print("GITHUB_PAT set") # Ensure the cloned_repo directory does not already exist if not os.path.exists('cloned_repo'): # Clone the repository using the Personal Access Token for authentication Repo.clone_from(f'https://{GIT_id}:{GITHUB_PAT}@github.com/{GIT_id}/{GIT_repo}.git', './cloned_repo') # Import the main module from the cloned repository import cloned_repo.main as main from cloned_repo.main import * What the script does: - Reads your GitHub PAT, repository ID and repository name from environment variables. - Checks that GITHUB_PAT is set. - Makes sure the cloned_repo directory does not already exist, to avoid conflicts. - Clones the private repository, authenticating with the PAT. - Imports the main module from the clone. Careful The PAT goes in the clone URL. Keep it in an environment variable, never in the file you upload to the Space. Step 3: Upload to HuggingFace Now push this launcher to HuggingFace Spaces. You get to run your models and share their outputs without exposing the source. All the features of Spaces, none of the code on display. --- ### ImmerseGuard: Bridging Immersion and Environmental Awareness URL: https://magnumical.ca/blog/immerseguard-bridging-immersion-and-environmental-awareness Published: 2024-05-08 (updated 2024-07-03) Language: English In short: ImmerseGuard is a phone app that listens through your noise-cancelling headphones and tells you when something important is happening around you. It runs on the device, with no internet connection needed. The problem with good noise cancelling Noise cancelling has got very good. That is great for music and for immersive content, and it is a problem for everything else. Once the room is gone, so are the sounds you actually needed to hear. The system in outline. Users switch on ANC in all sorts of places: walking down the street, doing something at home, or inside a VR headset for full immersion. ImmerseGuard analyses the headphone audio in real time and, when it detects a sound event, alerts the user with a text or voice notification. What we built ImmerseGuard puts an on-device sound event detection system alongside active noise cancelling (ANC). It is compressed enough to run on a phone, and it gives you real-time alerts for the sounds that matter without pulling you out of what you are listening to. How it works The core is YAMNet, which is known for doing sound event detection efficiently on edge devices. We pair it with a shallower model trained by transfer learning. Together they pick out emergency vehicle sirens, general vehicle noise, room and household sounds, human speech, pets and device alarms. To make it fit a resource-limited platform we quantized the model. That gets inference times down to something usable in real time and lets the whole thing run locally, with no internet connection. What happened when people used it The user experience studies came back positive. People found it practical for staying aware of their surroundings while immersed in digital content, and they liked that it just sat on their phone. No heavy files or models to download. What is next The studies had limits and we know it. The next round is about making ImmerseGuard work across a wider range of devices and real environments. From user feedback, we also want more specific sound classes and notifications people can tune themselves. Balancing immersive content against staying connected to the room is the whole point. On-device machine learning and model compression are what make it possible. You can read the full paper on ResearchGate . --- ### Chit Chat Charm ^__^ URL: https://magnumical.ca/blog/chit-chat-charm Published: 2023-10-27 (updated 2023-10-28) Language: English In short: Chit Chat Charm is an AI conversation app with a face and a voice, not just a text box. There is a playable demo, a set of backer rewards, and a plan for how it pays for itself. Talking to an AI usually means typing into a box and reading text back. Chit Chat Charm adds the visual and the audio: a character you pick, a voice that sounds like a voice, and an appearance you can change. Watch the demo video on YouTube What it does - Interactive AI conversations. The AI is built to hold a conversation, not just answer a question. - Choose your companion. Martin or Rose. Each one gives you a different chat. - Natural voices. Replies come back spoken, in the most natural voices we could get, so the conversation actually flows. - Change how they look. Casual tees or formal suits. Skin colour, race, eye colour and body shape are all adjustable. Play the demo Chit Chat Charm AI on itch.io Rewards Back the project and pick a tier. Reward 1: Supporter's Shoutout, CA$0 - A heartfelt thank you from the Chit Chat Charm AI team. - Access to play the base game demo. - Note: the final product will run in browsers, on phones and on desktop. The demo is the minimum viable product and shows where the app is going. Reward 2: Chatterbox Explorer, CA$25 - Digital thank you card. - One month of unlimited access to the final product. Note: the base game stays free forever, with at least two characters to talk to. Avatar and background customisation is the paid part. - Pick from a range of characters, each with its own behaviour and look, and customise the voices. Reward 3: Social Butterfly, CA$50 - Everything in Chatterbox Explorer. - Three months of unlimited access. - An in-game badge marking you as an early supporter. Reward 4: Conversation Connoisseur, CA$75 - Everything in Social Butterfly. - Six months of unlimited access. - Access to select presets for each character, such as psychologist, doctor and chef avatars. Reward 5: Chat Maestro, CA$100 - Everything in Conversation Connoisseur. - Nine months of unlimited access. - A say in character designs and features for future updates. - One exclusive character customisation, held back from the public for three months. - A "Chat Maestro" badge in the game. How it makes money The base game stays open to everyone. That is the point. But a project this size needs to pay for itself, so the money comes from customisation. If you want to change how your avatar looks or behaves, that costs. If you just want to talk, it does not. Other things we are looking at: - Premium content packs. Special scenarios, conversations or events you can buy. - Affiliate partnerships. Working with brands to place products or services in the game, as long as they fit the experience. Ads and promoted content inside the chat are possible too. - Subscriptions. Early access to new features, an ad-free experience, and other extras. Free access on one side, paid personalisation on the other. That is the balance we are trying to hit. Want something specific? An AI consultant for your business, an advisor for a classroom, a virtual psychologist that listens. We can build the app around what your organisation needs. Write to chitchat@magnumical.ca . --- ### What is the Google Project Management Professional Certificate program? URL: https://magnumical.ca/blog/what-is-the-google-project-management-professional-certificate-program Published: 2023-04-22 (updated 2023-04-22) Language: English In short: I finished the Google Project Management Professional Certificate. Here is what the program actually covers and why I took it. What the program covers The certificate walks through the whole project management process: initiation, planning, execution, monitoring and control, and closing a project out. It is a mix of online lectures, interactive exercises and real case studies, and it covers the standard methodologies and tools. The part I did not expect to get as much airtime was the soft skills. Communication, stakeholder management, working with a team. Those turn out to be most of the job. Why I took it I am moving into this field on the industry side. I have a background in science and engineering, plus project coordination and years in a research lab, so the pieces were already there. The program gave me the vocabulary and the structure to put around them. Download the certificate (PDF) --- ### Attending to Scientist2Entrepreneur (S2E) Program! Finding my way into the world of startups! URL: https://magnumical.ca/blog/attending-to-scientist2entrepreneur-s2e-program-finding-my-way-into-the-world-of-startups Published: 2023-01-27 (updated 2023-01-27) Language: English In short: I spent a few months hunting for gaps where health, VR and machine learning meet, then joined the Scientist2Entrepreneur program to learn how to turn an idea into a product. For the last couple of months I have been reading the literature and gathering information on the gaps at the meeting point of health, VR and ML. I came up with several ideas. A good idea does not guarantee a good result, though, so I also contacted a lot of places and met people who showed me how to bake an idea into an actual product, B2B or B2C. That is how I found the Scientist2Entrepreneur (S2E) program. S2E runs for eight weeks. You look at entrepreneurship as an alternative career path: what your technology could be applied to, and how to build a network in the ecosystem. S2E went national in January 2022. Before that it ran at the provincial level through Concordia University in Quebec, under the name Quebec Scientific Entrepreneurship Program. --- ### TeTrA: Jump to speech controlled VR env URL: https://magnumical.ca/blog/tetra-jump-to-speech-controlled-vr-env Published: 2022-03-19 (updated 2022-10-31) Language: English Topics: bci, machine learning, brain, VR, arspeech controlled game, NLP, natural language, processing, Speech In short: I built a Windows test game you control entirely by talking to it. Say "show me some clouds" and clouds appear. It understands eight commands. One of my dreams has been games you control with your brain, your voice and your body. Kinect covered body movement. I have built BCI games too, you can see them in earlier posts. What I had not seen was a speech-controlled VR game, so I gave myself a shot at building one. What follows is a Windows, non-VR version of my test game. The code and my other projects live on my GitHub . What it understands Right now it will listen to anything you say, but it only acts on these: - Show me dreamy night - Show me day - Show me some clouds, or add clouds - Add extra clouds - Add some flowers - Add more flowers - Show me some trees - Exit, or quit. Hahahaha. --- ### The Oranges: A multi-sensory Experience URL: https://magnumical.ca/blog/oranges Published: 2022-02-27 (updated 2022-12-08) Language: English Topics: virtual reality, experience, multisensory, multimodal, AI, meta, in-game questionnaire In short: a multi-sensory VR study with smell and touch feedback, where participants answer the questionnaire inside the headset instead of taking it off. Over the past few weeks I have been designing and collecting data to look at quality of experience in a multi-sensory environment with olfactory and haptic feedback. Results will be published soon. Questionnaires without taking the headset off The best thing I got to build into this one was in-game questionnaires, using the VRQuestionnaireToolkit repository. It meant I could evaluate users qualitatively after every condition without asking them to remove the iHMD, which in our setup is a VR headset plus EEG and EOG. --- ### BCIGameJam'21! MuSAE Games :) A Winner! URL: https://magnumical.ca/blog/bci-game-jam-2021-musae-games Published: 2022-02-13 (updated 2022-11-26) Language: English In short: Marilia, Olivier and I built a brain-controlled co-op game for the 2021 BCI Game Jam. It won Overall Winner, the popular vote from other devs, and Best SSVEP Game. 1st Overall Winner at BCI Game Jam 2021 3 awards, including Best SSVEP Game 3 people on the team We took part in this year's online jam to build a game you play with your brain. Our entry won Overall Winner (1st place), Popular Vote (Other Devs) and Best SSVEP Game . INRS wrote up the story: developing brain games to help children with physical disabilities Watch the demo video on YouTube You can download the game from my GitHub . How the game works It is a collaborative SSVEP game where players collect diamonds in an ancient Aztec mine. To move, you click on the flickering blocks. Each diamond gives you a different power. Diamond Description Red Increase hit points Yellow Make the avatar fly Blue Increase movement range Watch out for the ancient gods walking the map. Players have to dodge the monsters to keep their health. The monster is a real threat to you. To win, your team collects every diamond on the map. The effect of each diamond shows up visually, so you can see what you picked up. If any player on your team loses all their HP, the whole team starts over. Tip Map size, number of players, monsters, diamonds and the rest are all configurable in the source code. Key features - Plays from one player up to multiplayer . - Cooperative theme . - Fully adjustable: number of diamonds, blocks, monsters, player speed and more, so it is re-playable . - A random map every time you press Start, so it stays fresh . - Easy to pick up. All you need is a mouse. - Shiny graphics and a soundtrack that keeps you going. - Fun animations : jumping, monsters and the rest. Screenshots --- ### Coping with life after immigration :) URL: https://magnumical.ca/blog/coping-with-life-after-migration Published: 2021-09-02 (updated 2022-02-27) Language: English Topics: tinder, migration, socialize, mcgill, student, canada, apply, university, how to be successful, guidline migration, immigration In short: five months into moving to Montreal as an international student, here is what migration actually felt like, why I picked this city and this lab, and what helped with the loneliness. It has been almost five months since I moved to Montreal as an international student. I want to share the interesting parts of migration, what the society here is like, and some suggestions for dealing with your emotions afterwards. Migration is a big deal in anyone's life. If you were born in a middle eastern country, it is one of your options for getting an acceptable quality of life, which is the platform everything else gets built on. People should try hard anywhere in the world to get what they want. I just think it is easier to grow in a developed country like Canada. Here are the questions I want to answer: - Why migrate? Why cross two continents and an ocean to study in Canada? - Why Montreal? Why MuSAE Lab? - How did I deal with distance, homesickness, emotions and living alone? Had I lived alone before? - Do I need to socialize with new people here, or should I stick with the Iranian community? What can I do to meet people? Beautiful scene of my room :) Why migrate? Why cross two continents and an ocean to study in Canada? People answer "why" questions differently. I migrated because I was hitting a dead end, in education and in most other parts of life. I think you migrate to get something more , something you could not get where you were. In my case I could not see personal, educational or business growth in Iran. I chose Canada over Europe and south Asian countries because it offers things they do not. Quebec in particular has excellent innovation centres, pioneering universities, and researchers whose collaboration will make me better at what I do. The ties between academic institutes and industry are what make Canada unique for me. Our institute, INRS , is research-intensive, equipped with modern facilities in my field, and well connected to industry. Beyond the academic side, Canada is known for being multicultural, which you have heard everywhere, and which means being surrounded by people with very different backgrounds and ideas. Was it worth it so far? Yes, of course. I have productive, knowledgeable, helpful people around me now. I have been getting closer to my goal every day since I landed in Montreal, thanks to lovely colleagues and a great supervisor :) Delightful lab meeting in summer! Why Montreal? Why MuSAE Lab? Because this city and this province are different. Good or bad? Both. People here listen to you. Nobody mocks the way you speak English or French. Everyone is chill and nobody is in a hurry. Old port of Montreal My field is interdisciplinary: neuroscience, biomedical and telecommunications. Montreal has a lot of frontier labs and faculties in it. One of the big names in my area is Prof. Falk at INRS-EMT, who directs MuSAE Lab. The lab works on multi-modal signal enhancement and processing, and we tackle the theory and the practice. Working with a group like that is a dream for anyone who wants to learn more. How did I deal with distance, homesickness and living alone? I have not felt homesick yet :) but of course I wanted my family beside me. Do they want to tear down what they built in Iran and start over in Canada? No. And the reason I am at peace with migrating is that I had not built anything back there yet, so cutting the connections was easy for me. Much easier than it would be for my father or mother. Thanks to technology I can talk to my family regularly, so conversation is easy. But is talking all we need? No. As a normal human you need support, a hug, physical connection. That is the hard part, and how hard depends on your character. It hurt a lot at first. Then I accepted that I am alone, and I started respecting myself for it. Every time I felt sad, I reminded myself why I am here. because I love reading while lying down on grass :) Should I socialize with new people, or stick with the Iranian community? You need to be around people. We evolved for thousands of years living in groups, so it is in your nature :) But sticking only to people from your own country causes problems. As an immigrant you may cut the cultural ties to your country, and you are not connected to Canadian culture either. You are in transition. So yes, get in touch with people from here. At the very least, you develop alongside the cultural changes happening in Canadian society. How do you meet people? I think the best route is groups: hiking, biking, reading, whatever you like. Do Tinder and the other dating apps help? Yeah, if you are good looking :)))) And note that there is only a 0.5% chance of finding a successful person on Tinder . Invest in better ways. Go to student association events, socialize, make friends :) --- ### New Preprint: How Adversarial attacks affect Deep Neural Networks Detecting COVID-19? URL: https://magnumical.ca/blog/new-preprint-how-adversarial-attacks-affect-deep-neural-networks-detecting-covid-19 Published: 2021-08-03 Language: English Topics: papers, machine learning, Deep learning, Covid-19, adversarial attack, machine learning, vulnerability, drawback of ml, drawback AI, artificial intellegence, state of art covid, biomedical engineering, kaggle, COVID-19 Xray dataset, xray, practical ML In short: I took five networks that classify COVID-19 chest X-rays and attacked them four different ways. Average accuracy fell from 96.7% to as low as 25.5%. After building an online COVID-19 diagnosing system , I got interested in where machine learning in healthcare breaks. One of the biggest problems is how fragile these models are. So I wrote a preprint about it. What I tested Five networks: ResNet-18, ResNet-50, Wide ResNet-16-8 (WRN-16-8), VGG-19, and Inception v3. Four attacks: Fast Gradient Sign Method (FGSM), Projected Gradient Descent (PGD), Carlini and Wagner (C&W), and Spatial Transformations Attack (ST). What happened 96.7% average accuracy on clean test images 25.5% average accuracy under PGD, the worst case 5 networks put through 4 attacks each Attack Average accuracy None (clean images) 96.7% FGSM 41.1% PGD 25.5% C&W 50.1% ST 56.3% Careful A low false-negative rate on clean data tells you nothing about how a medical image classifier behaves on a perturbed input. The same model can go from 96.7% to 25.5% without the image looking any different to a person. ResNet-50 and WRN-16-8 held up better than the rest. That makes them the sensible place to spend effort on defenses. Abstract Considering the global crisis of Coronavirus infection (COVID-19), the essence of utilizing novel approaches to achieve quick and accurate diagnosing methods is required. Deep Neural Networks (DNN) showed outstanding capabilities in classifying various data types, including medical images, in order to build a practical automatic diagnosing system. Therefore, DNNs can help the healthcare system to reduce patients waiting time. However, despite acceptable accuracy and low false-negative rate of DNNs in medical image classification, they have shown vulnerabilities in terms of adversarial attacks. Such input can lead the model to misclassification. This paper investigated the effect of these attacks on five commonly used neural networks, including ResNet-18, ResNet-50, Wide ResNet-16-8 (WRN-16-8), VGG-19, and Inception v3. Four adversarial attacks, including Fast Gradient Sign Method (FGSM), Projected Gradient Descent (PGD), Carlini and Wagner (C&W), and Spatial Transformations Attack (ST), were used to complete this investigation. Average accuracy on test images was 96.7% and decreased to 41.1%, 25.5%, 50.1%, and 56.3% in FGSM, PGD, C&W, and ST, respectively. Results are indicating that ResNet-50 and WRN-16-8 were generally less affected by attacks. Therefore using defense methods in these two models can enhance their performance encountering adversarial perturbations. Full report: dx.doi.org/10.21203/rs.3.rs-763355/v1 --- ### My Experience in Hospital! URL: https://magnumical.ca/blog/my-experience-in-hospital Published: 2021-05-03 (updated 2025-07-21) Language: English Topics: Covid-19, corona, sars-cov-2, کرونا In short: in April 2020 I went into Imam Khomeini Hospital in Ardabil to build a machine learning system that diagnoses COVID-19 from scans. I ended up admitting patients and scheduling the imaging ward too. The idea of building machine learning for health is being pushed hard by colleagues all over the world, because a tool like this can make diagnosis quick and accurate. The system got a good reception. The news was picked up by the Ministry of Science, Research and Technology website . Beyond the reception counter. You can work six hours straight without drinking, eating, or fresh air. What the job actually was On top of the model, I stayed at the hospital and helped in the imaging section. I admitted new patients to the ward and put the bracelets on their wrists. I did the time scheduling for each patient around the radiologist's availability. That was alongside my other work: improving the data pipelines on the hospital network, and building the AI model to speed up COVID-19 diagnosis. Doctors and nurses are the main part of the army fighting COVID-19. So is everyone else in the building, from the device suppliers to the janitors. They work hard, indoors, in masks and disposable gloves, all day. The tools around the wards Walking the wards I kept running into genuinely clever devices. I want to point at the things biomedical engineers build to make a medical procedure easier. Handy tools of hospitals Defibrillator, oxygen capsule, nebulizer, ECG. Those are the ones you see everywhere. With a respiratory disease you have to add ventilators to the list. --- ### WordUp! Pro Version Experience! URL: https://magnumical.ca/blog/wordupp Published: 2020-11-17 (updated 2022-02-13) Language: English Topics: learn, english, ielts, ازمون ایلتس, تافل, vocab, vocabulary, لعات انگلیسی In short: I have been using WordUp to learn vocabulary for more than six months, and I bought the Pro version. Here is what it does and why it stuck. This is for anyone who has trouble remembering words. The app is WordUp , built by two people, Peyman and Somayeh. There is a short video of it on Vimeo if you want to see it moving. How does it work? On your first login it shows you words and you answer "I know" or "I don't know". From that it estimates your vocabulary and your level. The app has 25,000 words, 1,000 per level, so 25 levels. You go into a level, mark the words you don't know, and it teaches you those. The review page holds the words you don't know. Tap learn. How do you actually learn a word? Through quotations, movies, news and songs. The word CANNY sits in level 15. You start with the meanings. It gives you more than the meaning. For some words you also get phrasal verbs, idioms and related forms. Those three screens are the examples for one word. It covers the word from every side, so the meaning sticks. What else is in there? Movies, games and categories. Is Pro worth it? I have been on it for over six months and the experience is good. Pro gives you more songs, movies and quotes, and no ads. The Explore section lets you learn vocabulary by category, which is a convenient way to focus on the topics you care about. Tip Give it a week. After that you will be opening it daily without thinking about it. Get it on the App Store or on Google Play . --- ### VR based Rehabilitation platform for Dementia URL: https://magnumical.ca/blog/vr-based-rehabilitation-platform-for-dementia Published: 2020-08-24 (updated 2021-05-14) Language: English Topics: dementia, virtual reality, rehabiliation, bme In short: I built a VR environment for people living with dementia and put the first build on GitHub so anyone can take it further. This first version has no VR controllers, so you can walk around with the keyboard and mouse. That makes it easy to try before you commit a headset to it. The project lives here: VR_Dementia_Rehabilitation on GitHub . There is also a walkthrough video on YouTube . --- ### Graph Neural Networks- Architectures review! URL: https://magnumical.ca/blog/graph-neural-networks-architectures-review Published: 2020-07-06 Language: English Topics: Fields of research, graph signal processin, grap, graph, نظریه گراف In short: a walk through the graph neural networks I found most useful. GCN, DeepWalk and GraphSAGE, starting from the three matrices you need before any of it makes sense. If a problem can be drawn as a graph, a graph neural network is often the accurate and efficient way to answer it. I start with the simple models and work up to the newer ones. ChebNet gets its own post. The ball-and-stick model is the simplest use of graphs in chemistry. The vocabulary you need first I am mostly following Kipf and Welling on semi-supervised classification with GCNs [1]. I plotted the example graph with GraphOnline . G = (v, e) That is, a graph G is made of v nodes and e edges. Five nodes (vertices) and five edges (links). Edges can carry a value. Three matrices do most of the work: The adjacency matrix is node x node. It says which nodes are connected. The degree matrix is a node x node diagonal matrix. It counts the edges landing on each node. The Laplacian matrix is just D minus A. Those three are the key to graph-based processing. You can define others. The feature matrix holds the features of each node. If the nodes are people, the features might be age, height and weight. So it has n rows and f columns, where f is the number of features. Graph Convolutional Network (GCN) Think of the graph you just drew as layer one. What is layer two? You apply some math to the matrices, and the math runs on the node features. So you have a function F , adjacency A , and features X . Define H l for the values at each layer. In math: F can be anything. I use ReLU. You also need a matrix W to carry the layer-specific trainable weights. In a GCN, each node ends up as the aggregation of its neighbours. This is where semi-supervised learning comes in. In a graph you often do not have a label for every node, so you use the labelled ones to predict the rest. In fully supervised learning you have all the labels. Here you do not, hence semi-supervised. Careful Aggregation is biased by degree. In the example graph node 2 has three edges and node 4 has one. More neighbours, more value, for no good reason. You have to normalize symmetrically using the degree matrix. I is the identity matrix, which is what lets you normalize A . D hat is the diagonal degree matrix of A hat. That gives the final equation: DeepWalk My reference here is "DeepWalk: Online Learning of Social Representations" by Perozzi et al., who demonstrate it on Zachary's Karate network [2]. This one learns unsupervised , so there may be no feature matrix at all. The algorithm starts from random features and develops them each iteration. The problem they were solving: cluster the members of a karate club. Karate club clustered in four. They separated labels from features to prevent cascading errors . You learn from a subset of the data, and RandomWalk plus SkipGram get you the rest of the way. In RandomWalk , at each node you pick a walk size and a walk length. GraphSAGE GraphSAGE is the practical one. With the earlier networks, growing the graph means retraining the model. GraphSAGE makes that easy [3]. - Sample the neighbourhood Pick which neighbours of a node you are going to look at. - Aggregate Combine the feature information coming from those neighbours. - Predict Produce the graph context and the label. Earlier nets - Learn a vector per node - Extending the graph means training again GraphSAGE - Learns a set of aggregation functions over a node's neighbourhood - Handles nodes it has not seen Time to define embedding , which is not a strange thing at all. It is a calculation on node features. Picture a graph of three nodes in a triangle. To get the new value for node 0, you feed its neighbours' values into a function. Averaging, for example. First assign random values to each node. Here are the random numbers I gave the example graph: Take node 2. Capture its neighbours and apply the function. Nodes 0, 3 and 4 are the input, so 0.8, 0.6 and 0.7 go in and the output is the new value of node 2. Careful Notice node 2 itself never went into the function. That is a disaster. When you implement this, add a self loop to every node so its own value is included. Repeat for every node and you have layer one. Do it again for layer two. Which function should you use? Anything, even a small neural network. Mostly people average: Or take the maximum, which picks 0.8 in this example. That is the pool aggregator. And note this was one-hop embedding. In two-hop you pull in the neighbours of the neighbours as well. Next In the next posts I will cover the networks used in graph signal processing (GSP). References - arxiv.org/abs/1609.02907 - arxiv.org/abs/1403.6652 - snap.stanford.edu/graphsage --- ### A GUI for DIY Syringe pump URL: https://magnumical.ca/blog/a-gui-for-diy-syringe-pump Published: 2020-06-28 Language: English Topics: medical Equipment, پمپ سرنگ, مهندسی پزشکی, syringe pump, biomedical engineering In short: my final-semester group set out to build a syringe pump out of an Arduino. COVID-19 split the team up, so I published my part: the Python GUI that drives it. We tried to build a syringe pump in the last semester of our undergraduate program. The "Medical devices" course had covered the general equipment of hospital units, and we wanted to make one with the tools we already had. Three of us formed a group. Then the COVID-19 crisis hit and the group broke up, so I decided to upload my part of the job. Careful I stripped the port-controlling code out of the version below, so it runs without throwing an error when no Arduino is attached. You will need to put the serial handling back to drive real hardware. What the GUI asks you - Mode Two states: inject, or withdraw the volume inside the syringe. - Volume Type the amount and pick the unit, mL or uL. - Speed Four options: ml/min, ml/hr, uL/min, uL/hr. - Syringe type Metal, glass or plastic. So I pick 1000 mL to inject, at 20 ml/min, with a metal syringe. Those numbers go to the Arduino, which drives the servo motors that move the syringe. The GUI is Python 3 and the code is on GitHub . from tkinter import * import tkinter.messagebox from tkinter import filedialog def gett(): if selected.get()==0: str1='Injection ' else: str1='Withdraw ' str2=str1+"of "+ E1.get() if volumeindex.get()==0: str3=" mL " else: str3=" uL " str4=str2 + str3 str5=str4+"with "+ E2.get() if speed.get()==0: str6=" ml/min" elif speed.get()==1: str6=" ml/hr" elif speed.get()==2: str6=" uL/min" else: str6=" uL/hr" str7=str5+str6+ " speed" if typeGlass.get()==0: str8=" metal" elif typeGlass.get()==1: str8=" glass" else: str8=" plastic" str9= str7+" in" + str8+" syring" tkinter.messagebox.showinfo("Conditions!", str9) win = Tk() win.configure(bg="#007EA0") win.title("Syring Pump GUI") win.geometry('400x420') L1 = Label(win, text="Mode:", fg="black") L1.grid(column=0, row=0) selected = IntVar() rad1 = Radiobutton(win,text='Injection', value=0, variable=selected,bg="#0080FF", fg="black") rad1.grid(column=1, row=0) rad2 = Radiobutton(win,text='Withdraw', value=1, variable=selected,bg="#0080FF", fg="black") rad2.grid(column=2, row=0,padx=10, pady=20) volume = IntVar() L2 = Label(win, text="Enter Volume:", fg="black") L2.grid(column=0, row=1) E1 = Entry(win, textvariable=volume) E1.grid(column=2, row=1) volumeindex = IntVar() rad3 = Radiobutton(win,text='ml', value=0, variable=volumeindex,bg="#0080FF", fg="black") rad3.grid(column=1, row=2) rad4 = Radiobutton(win,text='uL', value=1, variable=volumeindex,bg="#0080FF", fg="black") rad4.grid(column=2, row=2,padx=10, pady=20) L4 = Label(win, text="Enter speed:", fg="black") L4.grid(column=0, row=3) E2 = Entry(win) E2.grid(column=2, row=3) speed = IntVar() rad5 = Radiobutton(win,text='ml/min', value=0, variable=speed,bg="#0080FF", fg="black") rad5.grid(column=1, row=4) rad6 = Radiobutton(win,text='ml/hr', value=1, variable=speed,bg="#0080FF", fg="black") rad6.grid(column=2, row=4) rad7 = Radiobutton(win,text='ul/min', value=2, variable=speed,bg="#0080FF", fg="black") rad7.grid(column=1, row=5) rad8 = Radiobutton(win,text='ul/hr', value=3, variable=speed,bg="#0080FF", fg="black") rad8.grid(column=2, row=5,padx=1, pady=20) L6 = Label(win, text="Syring structure:", fg="black") L6.grid(column=0, row=6) typeGlass = IntVar() rad9 = Radiobutton(win,text='metal', value=0, variable=typeGlass,bg="#0080FF", fg="black") rad9.grid(column=1, row=6) rad10 = Radiobutton(win,text='glass', value=1, variable=typeGlass,bg="#0080FF", fg="black") rad10.grid(column=2, row=6) rad11 = Radiobutton(win,text='plastic', value=2, variable=typeGlass,bg="#0080FF", fg="black") rad11.grid(column=3, row=6) b1 = Button(win, text = 'Start', command=gett) b1.grid(column=1, row=7,padx=10, pady=20) L9 = Label(win, text="Developed by Reza Amini", fg="black") L9.grid(column=1, row=8) L10 = Label(win, text="imreza.ir", fg="black") L10.grid(column=1, row=9) win.mainloop() --- ### An Online Automatic Corona Diagnose System Based on Chest X-ray Images URL: https://magnumical.ca/blog/an-online-automatic-corona-diagnose-system-based-on-chest-x-ray-images Published: 2020-05-30 (updated 2020-05-30) Language: English Topics: biomedical engineering, Fields of research, machine learning, image processing, DSP, biomedical engineering, biomedical, medical corona, Covid-19, sars-cov-2, Medical, corona, مهندسی پزشکی, کرونا In short: I trained four networks on chest X-rays to detect COVID-19, picked the best one, and put it online. VGG16 won with 98.92% accuracy and it now runs behind an API on Google Cloud. 98.92% VGG16 accuracy, the best of the four 4 architectures compared on the same data 1,400 X-ray images, split 80:20 into 1,120 train and 280 test Why X-ray and not CT SARS-CoV-2 spread across the world fast [1]. It infects the lungs and causes pneumonia in most patients. RT-PCR is reliable [2], but it takes time and some kits are not accurate enough. The common symptoms are fever and cough, plus shortness of breath, headache and fatigue [3]. Imaging helps. CT and X-ray are both used, but CT is not available in most small cities and it costs more. So this study is about X-ray, and about closing the gap between taking the image and getting the answer. The goal was an online system that reports lung engagement with the disease, patient status, and therapeutic guidelines, and takes some pressure off radiologists. Other groups had gone at this too. Apostolopoulos and Mpesiana [4] compared five CNNs across normal, pneumonia and COVID-19 lungs, and found MobileNet v2 effective. Hemdan et al. [5] built COVIDX-Net, where VGG19 and DenseNet came out on top. Narin et al. [6] tested ResNet50, InceptionV3 and Inception-ResNetV2, and ResNet50 gave 98% accuracy. How the system was built Figure 1. Complete flow diagram of study - Build the dataset 400 confirmed positive COVID-19 subjects, from the public collection by Cohen et al. [8] plus images from hospitals in Ardabil province, Iran. 1,000 healthy lung X-rays came from the RSNA pneumonia detection challenge [12]. - Fine-tune four networks VGG16, VGG19, InceptionV3 and ResNet50, each with a fully connected layer added on top of the pre-trained model. - Evaluate on the same terms Same epochs, same data, 80:20 split. Inputs at 244x244, except InceptionV3 at 299x299. - Deploy the winner The best model goes onto Google Cloud Platform behind a Python API. Images and results move as JSON. The models VGG16 and VGG19 come from Simonyan and Zisserman [9]. They stack convolutional layers on top of each other. VGG16 has 138.4 million parameters, VGG19 has 143.7 million. Training networks that size on a small COVID-19 dataset is not efficient, so fine-tuning is what makes them usable here. ResNet50 came from He et al. [10] in 2015, with 25.6 million parameters and 152 layers, eight times deeper than the VGG networks. Inception-V3 came from Szegedy et al. [11] the same year, around 23 million parameters, and hit 5.6% top-5 error for single frame evaluation on the ILSVRC 2012 challenge. The API The backbone sits on Google Cloud Platform, which gives serverless compute, so the model is cheap to create and run. Front-end and back-end talk in JSON. Input images are not stored, which avoids a storage problem and a privacy one. When an encoded image arrives, the Python core decodes it, preprocesses it, and analyses it. Three things come back to the website: lung engagement with the disease, patient status, and therapeutic guidelines. The first one is the real output. The other two follow from it. Tip Putting the model behind an endpoint instead of shipping it means every user is on the latest version the moment it is retrained. That was the point of doing it online. Results Everything ran in Python 3.7 on a laptop with an Intel Core i7-9750H, an Nvidia GTX 1650 2GB, and 24GB of RAM. Accuracy, sensitivity (recall) and specificity all come out of the confusion matrix: true positive, true negative, false negative, false positive. VGG16 came out ahead, with the highest sensitivity and specificity as well as the highest accuracy. VGG19 was almost identical. The other two were not usable. Network Accuracy (%) Sensivity (%) Specifity (%) VGG16 98.92 96.25 100 VGG19 98.90 97.50 99.50 InceptionV3 71.79 1.25 100 ResNet50 28.27 100 0.00 Table 1. Final results of networks Careful Look at the two failures in the confusion matrix, not just the accuracy column. InceptionV3 caught 1 positive out of 80. ResNet50 caught all 80 positives by calling every single image positive. Both are useless, and one of them still reports 71.79% accuracy. Network True Positive False Negative False Positive True Negative VGG16 77 3 0 200 VGG19 78 2 1 199 InceptionV3 1 79 0 200 ResNet50 80 0 200 0 Table 2. Confusion matrix of CNN models Here are the training histories. Each plot has training accuracy, validation accuracy, training loss and validation loss. Figure 2. VGG19 training history plot Figure 3. VGG16 training history plot Figure 4. ResNet50 training history plot Figure 5. InceptionV3 training history plot The ROC curve is below. The closer the curve hugs the true-positive border and then the top border of the ROC space, the more accurate the test. Figure 6. The receiver operating characteristic curve of networks Precision and F1-score are two more ways to judge the networks: Table 3. Precision and F1-score of CNN models Conclusion Combining image processing and machine learning gives you convolutional networks that already do real work, in self-driving cars and elsewhere. Medicine is the obvious next place. The SARS-CoV-2 outbreak made the gap visible: as hospitals filled up and demand for CT and X-ray rose, the time to a confirmed diagnosis became the thing that mattered. This study evaluated four CNNs, took the best one, and deployed it on GCP as an online diagnosing system. VGG16 outperformed the rest. The platform is free and gets updated regularly. Acknowledgments Thanks to everyone working in hospitals and caring for patients. This work would not have been possible without help from Ardabil University of Medical Sciences and Ardabil Science and Technology Park, Ardabil, Iran. References - Cohen, J., & Normile, D. (2020). New SARS-like virus in China triggers alarm, Science, vol. 367, no. 6475, pp. 234-235, 2020. - Fang, Y., Zhang, H., Xie, J., Lin, M., Ying, L., Pang, P., & Ji, W. (2020). Sensitivity of chest CT for COVID-19: comparison to RT-PCR. Radiology, 200432. - Wang, W., Tang, J., & Wei, F. (2020). Updated understanding of the outbreak of 2019 novel coronavirus (2019-nCoV) in Wuhan, China. Journal of medical virology, 92(4), 441-447. - Apostolopoulos, I. D., & Mpesiana, T. A. (2020). Covid-19: automatic detection from x-ray images utilizing transfer learning with convolutional neural networks. Physical and Engineering Sciences in Medicine, 1. - Hemdan, E. E. D., Shouman, M. A., & Karar, M. E. (2020). Covidx-net: A framework of deep learning classifiers to diagnose covid-19 in x-ray images. arXiv preprint arXiv:2003.11055 - Narin, A., Kaya, C., & Pamuk, Z. (2020). Automatic detection of coronavirus disease (covid-19) using x-ray images and deep convolutional neural networks. arXiv preprint arXiv:2003.10849 - Online COVID-19 Diagnose System. - Cohen, J. P., Morrison, P., & Dao, L. (2020). COVID-19 image data collection. arXiv preprint arXiv:2003.11597. - Simonyan, K., & Zisserman, A. (2014). Very deep convolutional networks for large-scale image recognition. arXiv preprint arXiv:1409.1556 - He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 770-778) - Szegedy, C., Vanhoucke, V., Ioffe, S., Shlens, J., & Wojna, Z. (2016). Rethinking the inception architecture for computer vision. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 2818-2826) - Stein, A., (2018) Pneumonia Dataset Annotation Methods. RSNA Pneumonia Detection Challenge Discussion. kaggle.com/c/rsna-pneumonia-detection-challenge/discussion/64723 --- ### Online COVID-19 detector based on CXR URL: https://magnumical.ca/blog/online-covid-19-detector-based-on-cxr Published: 2020-04-17 (updated 2020-04-17) Language: English Topics: biomedical engineering, تشخیص آنلاین کرونا, covid=19, cororna, تشخیص گر آنلاین, پایتون, PaaS, سرویس هوش مصنوعی آنلاین, کلود پایتون In short: the online COVID-19 detector is live. Upload a chest X-ray, get back lung engagement, patient status and therapeutic guidelines. I wrote up how it was built, which four networks I compared and what each one scored, in the full write-up of the system . --- ### Biological Signal Processing: ML Approach- E01: Breast Cancer Detection URL: https://magnumical.ca/blog/biological-signal-processing-ml-approach-e01-breast-cancer-detection Published: 2020-03-09 (updated 2020-03-09) Language: English Topics: Machine Learning In Biomedical Engineering, biological, signal, eeg, ecg, bci, brain computer interface, data analyzing, cancer, breast, سرطان سینه, تشخیص, یادگیری ماشین, پردازش سیگنال حیاتی, پردازش سیگنال, مهندسی پزشکی, پایاننامه In short: episode one of a tutorial series on analysing biological signals with Python and MATLAB. Here we load the Breast Cancer Wisconsin dataset and train an SVM to tell malignant from benign. This series is about biomedical signals like EEG and ECG and the datasets around them. I picked breast cancer data to start because the code is easy, which makes it a good opening. دوره آموزشی تحلیل سیگنال های حیاتی با پایتون و متلب مناسب برای داده های مرتبط با سیستم سلامت. توی این دوره قراره که داده های مربوط به سرطان سینه رو مورد تحلیل قرار میدیم. دلیل انتخاب این دیتاست بخاطر اینه که برنامه نویسیش آسونه و برای شروع دوره مناسبه. 699 patient records in the dataset 10 features, plus the class attribute 80:20 train / test split The packages Four libraries do the work here: - NumPy for the computation - Pandas to handle the dataset - Matplotlib for plotting - Sklearn for the machine learning import numpy as np import pandas as pd from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn import svm Why numpy as np , pandas as pd , matplotlib.pyplot as plt ? It is not required. It is just the convention programmers use worldwide, and following it makes your code readable to everyone else. The last few imports pull in the specific functions and methods we need from Sklearn. More on those as we use them. Getting the data I used the Breast Cancer Wisconsin (Diagnostic) dataset. Go to the Data Folder and download breast-cancer-wisconsin.data and breast-cancer-wisconsin.names . The .names file describes the data. The dataset owners put that there to help you analyse it, and the thing to look for first is always the features : what they are and how many. This one has 10, plus the class attribute. Class tells you whether the patient has malignant cancer (class = 4) or benign (class = 2). The file also says there are 699 instances. So when we import, we should get 699 rows and 11 columns. Why 11? The first one is the ID . Tip This dataset arrives with its features already extracted. With raw data, like raw EEG, finding the features is a step you do before any learning happens. We will get to that in a later episode. لینکهای مربوط به دیتاست در پاراگراف بالا موجود میباشند در فایل دوم، اطلاعات مربوط به دیتاست قرار دارد در این فایل آمده است که داده ها شامل 10 ویژگی هستند که آخرین ستون ویژگی به اینکه فرد دارای سرطان خوش‌خیم یا بد‌خیم است اختصاص دارد اگر داده ها خام بودند، قبل از هرکاری باید ویژگی هایشان را درمیاوردیم که در پروژه های بعدی خواهیم داشت names=['id','clump_thickness','uniform_cell_size','uniform_cell_shape', 'marginal_adhesion','signle_epithelial_size','bra_nuclei', 'bland_chromatin','normal_nucleoli','mitoses','class'] df=pd.read_csv('breast-cancer-wisconsin.data',names=names) The names variable holds the 11 column labels. pd.read_csv reads .data files without complaint, and passing names to it labels the columns straight away. ( pd is Pandas, remember.) After running that: This is how our data looks like Looking at it To check the size: print(df.axes) print (df.shape) df.axes gives the number of rows and the column names. df.shape gives rows and columns. To reach a single row: print(df.loc[0]) print(df.describe()) df.loc[0] through df.loc[698] print everything in that row. df.describe() gives you statistics like mean and standard deviation per column. To see the distributions, use hist() : df.hist(figsize=(20,20)) plt.show() As the .names file said, every value in the table sits between 0 and 10. A scatter matrix is the other useful view: scatter_matrix(df,figsize=(20,20)) plt.show() Training the classifier Now we need train and test sets. You reach a column by name with df['class'] , and class is the output we want, our Y . The inputs are the other 10 columns, so we drop class and feed what is left in as X . X=np.array(df.drop(['class'],1)) y=np.array(df['class']) Then split it: 80% of the data for training, 20% for testing. That is what test_size=0.2 means. X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.2) And build the SVM classifier: mclf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train) print(clf.score(X_test, y_test)) --- ### COVID-19 Detection with ML and CXR | تشخیص کرونا توسط یادگیری ماشین و CXR URL: https://magnumical.ca/blog/covid-19-detection-with-ml-and-cxr-cxr Published: 2020-03-02 (updated 2020-03-16) Language: English Topics: کرونا, تشخیص بیماری, سرفه خشک, کووید, کووید19, Covid-19, covid, crona, corona, epidemi, china, brain computer interface, ML in medical, machine learning, python In short: when Iran ran short of COVID-19 test kits, I built a demo that looks at a chest X-ray and tells a normal lung from an abnormal one. Full Keras code below. زمانیکه شروع به ساخت این برنامه کردم بحران تعداد کیت داشتیم. با توجه به علائم کیفی مانند تب و سرفه و غیره نمیتوان بطور قطع گفت که فرد مبتلا به این بیماریست یا خیر. بنابر مقاله های جدید منتشر شده در دو هفته اخیر متوجه شدم که اسکن ریه میتونه خیلی واضح توی روند تشخیص کمک کنه. با مطالعه مقالات و پیدا کردن دیتابیسشون تونستم یه شمای کلی از مساله پیدا کنم. متاسفانه تنها مشکل این نرم افزار کم بودن داده های آموزش هست که خوب میشه اگر بیمارستان ها بتونند داده هاشون رو به اشتراک بزارن. علاوه بر عکس های ایکس ری، نیاز به داده های بیشتر مثل سچوریشن اکسیژن خون، میزان دمای بدن، جنسیت و فاکتور های دیگر رو میشه بعنوان ورودی به سیستم داد تا تخمین دقیق تری داشته باشیم. When I started on this, we had a shortage of detection kits for the patients showing symptoms. Symptoms alone, fever and cough and the rest, do not tell you whether someone has it. After reading the papers coming out at the time, I built a demo app to distinguish normal lungs from abnormal ones. Careful The real limit here is training data. There is not enough of it. This gets a lot better the moment hospitals are able to share what they have. X-rays are not the only signal worth feeding in. Blood oxygen saturation, body temperature, sex and other factors would all sharpen the estimate. output | خروجی The code import os import numpy as np import pandas as pd import random import cv2 import matplotlib.pyplot as plt import keras.backend as K from keras.models import Model, Sequential from keras.layers import Input, Dense, Flatten, Dropout, BatchNormalization from keras.layers import Conv2D, SeparableConv2D, MaxPool2D, LeakyReLU, Activation from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping import tensorflow as tf seed = 200 np.random.seed(seed) tf.random.set_seed(seed) input_path = 'chest_xray/DATA/' fig, img = plt.subplots(2, 3, figsize=(15, 15)) img = img.ravel() plt.tight_layout() for i, _set in enumerate(['train', 'val', 'test']): set_path = input_path+_set img[i].imshow(plt.imread(set_path+'/NORMAL/'+os.listdir(set_path+'/NORMAL')[0]), cmap='gray') img[i].set_title('Normal'.format(_set)) img[i+3].imshow(plt.imread(set_path+'/COVID/'+os.listdir(set_path+'/COVID')[0]), cmap='gray') img[i+3].set_title('nCoVid-19'.format(_set)) for _set in ['train', 'val', 'test']: n_normal = len(os.listdir(input_path + _set + '/NORMAL')) n_infect = len(os.listdir(input_path + _set + '/COVID')) print('normal images: {}, nCoVid-19 images: {}'.format(_set, n_normal, n_infect)) def process_data(img_dims, batch_size): train_datagen = ImageDataGenerator(rescale=1./255, zoom_range=0.3, vertical_flip=True) test_val_datagen = ImageDataGenerator(rescale=1./255) train_gen = train_datagen.flow_from_directory( directory=input_path+'train', target_size=(img_dims, img_dims), batch_size=batch_size, class_mode='binary', shuffle=True) test_gen = test_val_datagen.flow_from_directory( directory=input_path+'test', target_size=(img_dims, img_dims), batch_size=batch_size, class_mode='binary', shuffle=True) test_data = [] test_labels = [] for cond in ['/NORMAL/', '/COVID/']: for img in (os.listdir(input_path + 'test' + cond)): img = plt.imread(input_path+'test'+cond+img) img = cv2.resize(img, (img_dims, img_dims)) img = np.dstack([img, img, img]) img = img.astype('float32') / 255 if cond=='/NORMAL/': label = 0 elif cond=='/COVID/': label = 1 test_data.append(img) test_labels.append(label) test_data = np.array(test_data) test_labels = np.array(test_labels) return train_gen, test_gen, test_data, test_labels img_dims = 150 epochs = 10 batch_size = 32 train_gen, test_gen, test_data, test_labels = process_data(img_dims, batch_size) inputs = Input(shape=(img_dims, img_dims, 3)) x = Conv2D(filters=16, kernel_size=(3, 3), activation='relu', padding='same')(inputs) x = Conv2D(filters=16, kernel_size=(3, 3), activation='relu', padding='same')(x) x = MaxPool2D(pool_size=(2, 2))(x) x = SeparableConv2D(filters=32, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=32, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = SeparableConv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = SeparableConv2D(filters=128, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=128, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = Dropout(rate=0.2)(x) x = SeparableConv2D(filters=256, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=256, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = Dropout(rate=0.2)(x) x = SeparableConv2D(filters=512, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=512, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = Dropout(rate=0.2)(x) output = Dense(units=1, activation='sigmoid')(x) model = Model(inputs=inputs, outputs=output) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) checkpoint = ModelCheckpoint(filepath='best_weights.hdf5', save_best_only=True, save_weights_only=True) lr_reduce = ReduceLROnPlateau(monitor='val_loss', factor=0.3, patience=2, verbose=2, mode='max') early_stop = EarlyStopping(monitor='val_loss', min_delta=0.1, patience=1, mode='min') hist = model.fit_generator(train_gen, steps_per_epoch=train_gen.samples // batch_size,epochs=epochs, validation_data=test_gen,validation_steps=test_gen.samples // batch_size,callbacks=[checkpoint, lr_reduce]) Where the images came from - pubs.rsna.org/2019-nCoV - itnonline.com: CT provides best diagnosis for novel coronavirus - r/COVID19: chest CT images of COVID-19 lung involvement - radiopaedia.org: COVID-19 pneumonia case Update 1: someone built a better version A group in China took the same idea further, using CT images instead: A deep learning algorithm using CT images to screen for Corona Virus Disease (COVID-19). Shuai Wang, Bo Kang, Jinlu Ma, Xianjun Zeng, Mingming Xiao, Jia Guo, Mengjiao Cai, Jingyi Yang, Yaodong Li, Xiangfei Meng, Bo Xu. doi: 10.1101/2020.02.14.20023028 Update 2: the dataset The dataset archive that used to be attached to this post is no longer hosted here. You can rebuild it from the image sources listed above. Update 3: fixing the errors people hit If the code above throws errors for you, use this version instead. It adds the flatten and dense layers before the output. import os import numpy as np import pandas as pd import random import cv2 import matplotlib.pyplot as plt import keras.backend as K from keras.models import Model, Sequential from keras.layers import Input, Dense, Flatten, Dropout, BatchNormalization from keras.layers import Conv2D, SeparableConv2D, MaxPool2D, LeakyReLU, Activation from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping import tensorflow as tf seed = 200 np.random.seed(seed) tf.random.set_seed(seed) input_path = 'chest_xray/DATA/' fig, img = plt.subplots(2, 3, figsize=(15, 15)) img = img.ravel() plt.tight_layout() for i, _set in enumerate(['train', 'val', 'test']): set_path = input_path+_set img[i].imshow(plt.imread(set_path+'/NORMAL/'+os.listdir(set_path+'/NORMAL')[0]), cmap='gray') img[i].set_title('Normal'.format(_set)) img[i+3].imshow(plt.imread(set_path+'/COVID/'+os.listdir(set_path+'/COVID')[0]), cmap='gray') img[i+3].set_title('nCoVid-19'.format(_set)) for _set in ['train', 'val', 'test']: n_normal = len(os.listdir(input_path + _set + '/NORMAL')) n_infect = len(os.listdir(input_path + _set + '/COVID')) print('normal images: {}, nCoVid-19 images: {}'.format(_set, n_normal, n_infect)) def process_data(img_dims, batch_size): train_datagen = ImageDataGenerator(rescale=1./255, zoom_range=0.3, vertical_flip=True) test_val_datagen = ImageDataGenerator(rescale=1./255) train_gen = train_datagen.flow_from_directory( directory=input_path+'train', target_size=(img_dims, img_dims), batch_size=batch_size, class_mode='binary', shuffle=True) test_gen = test_val_datagen.flow_from_directory( directory=input_path+'test', target_size=(img_dims, img_dims), batch_size=batch_size, class_mode='binary', shuffle=True) test_data = [] test_labels = [] for cond in ['/NORMAL/', '/COVID/']: for img in (os.listdir(input_path + 'test' + cond)): img = plt.imread(input_path+'test'+cond+img) img = cv2.resize(img, (img_dims, img_dims)) img = np.dstack([img, img, img]) img = img.astype('float32') / 255 if cond=='/NORMAL/': label = 0 elif cond=='/COVID/': label = 1 test_data.append(img) test_labels.append(label) test_data = np.array(test_data) test_labels = np.array(test_labels) return train_gen, test_gen, test_data, test_labels img_dims = 150 epochs = 10 batch_size = 32 train_gen, test_gen, test_data, test_labels = process_data(img_dims, batch_size) inputs = Input(shape=(img_dims, img_dims, 3)) x = Conv2D(filters=16, kernel_size=(3, 3), activation='relu', padding='same')(inputs) x = Conv2D(filters=16, kernel_size=(3, 3), activation='relu', padding='same')(x) x = MaxPool2D(pool_size=(2, 2))(x) x = SeparableConv2D(filters=32, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=32, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = SeparableConv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = SeparableConv2D(filters=128, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=128, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = Dropout(rate=0.2)(x) x = SeparableConv2D(filters=256, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=256, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = Dropout(rate=0.2)(x) x = SeparableConv2D(filters=512, kernel_size=(3, 3), activation='relu', padding='same')(x) x = SeparableConv2D(filters=512, kernel_size=(3, 3), activation='relu', padding='same')(x) x = BatchNormalization()(x) x = MaxPool2D(pool_size=(2, 2))(x) x = Dropout(rate=0.2)(x) x = Flatten()(x) x = Dense(units=512, activation='relu')(x) x = Dropout(rate=0.7)(x) x = Dense(units=128, activation='relu')(x) x = Dropout(rate=0.5)(x) x = Dense(units=64, activation='relu')(x) x = Dropout(rate=0.3)(x) x = Dense(units=32, activation='relu')(x) x = Dropout(rate=0.1)(x) output = Dense(units=1, activation='sigmoid')(x) model = Model(inputs=inputs, outputs=output) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) checkpoint = ModelCheckpoint(filepath='best_weights.hdf5', save_best_only=True, save_weights_only=True) lr_reduce = ReduceLROnPlateau(monitor='val_loss', factor=0.3, patience=2, verbose=2, mode='max') early_stop = EarlyStopping(monitor='val_loss', min_delta=0.1, patience=1, mode='min') hist = model.fit_generator(train_gen, steps_per_epoch=train_gen.samples // batch_size,epochs=epochs, validation_data=test_gen,validation_steps=test_gen.samples // batch_size,callbacks=[checkpoint, lr_reduce]) --- ### New Publication: Medical Image Enhancement and Deblurring URL: https://magnumical.ca/blog/new-publication-medical-image-enhancement-and-deblurring Published: 2019-12-13 (updated 2020-10-02) Language: English Topics: signal processing, papers, Fields of research, Medical, Image Enhancement, Deblurring, PACS, shock filter, رفع تاری تصویر, تاری تصویر, تصویر پزشکی, پکس, مهندسی پزشکی In short: a paper on deblurring medical images, published at the NUSYS'19 conference . It combines anisotropic diffusion, shock filters and a coarse-to-fine blur kernel estimate to pull a sharp image back out of a blurred one. Abstract One of the most common image artifacts is blurring. Blind methods have been developed to restore a clear image from blurred input. In this paper, we introduce a new method which optimizes previous works and adapted with medical images. Optimized non-linear anisotropic diffusion was used to reduce noise by choosing constants correctly. After de-noising, edge sharpening is done using shock filters. A novel enhanced method called Coherence-Enhancing shock filters helped us to have strong sharpened edges. To obtain a blur kernel, we used the coarse-to-fine method. In the last step, we used spatial prior before restoring the unblurred image. Experiments with images show that combining these methods may outperform previous image restoration techniques in order to obtain reliable accuracy. Keywords: medical images, blind deconvolution, deblurring. The blur model A blurred image is the convolution of the sharp image with a blur kernel, plus noise. The noise term is small but it matters a lot once you start inverting the convolution. Read the paper on SpringerLink . It appears in LNEE'19 and on the IEEE website. --- ### New Publication: An Automatic Driver Assistant based on Intention Detecting Using EEG Signal URL: https://magnumical.ca/blog/new-publication-an-automatic-driver-assistant-based-on-intention-detecting-using-eeg-signal Published: 2019-12-13 (updated 2020-10-02) Language: English Topics: signal processing, MATLAB projects, papers, Fields of research, publication, ISI, مقاله ISI, مقاله کنفرانس, conferance, An Automatic Driver Assistant based on Intention Detecting Using EEG Signal, eeg, openbci In short: a driver assistant that reads motor intention straight off the scalp. Sixteen channels of OpenBCI, common spatial patterns for features, an SVM to sort them into left, right and brake. Published at the NUSYS'19 conference . 94.6% average classification accuracy 500ms earlier command prediction 16 OpenBCI channels recorded Abstract Each year, vehicle safety is increasing. Recently brain signals were used to assist drivers. Attempting to do movement produces electrical signals in specific regions of the brain. We developed a system based on motor intention to assist drivers and prevent car accidents. The main objective of this work is improving reaction time to external hazards. The motor intention was recorded by 16 channels of a portable device called Open-BCI. Extracting features was done by common spatial patterns which is a well-known method in motor imagery based brain computer interface (BCI) systems. By using enhanced common spatial pattern (CSP) called strong uncorrelated transform complex common spatial pattern (SUTCCSP), features of preprocessed data were extracted. Regarding the nonlinear nature of electroencephalogram (EEG), support vector machine (SVM) with kernel trick classifier was used to classify features into 3 classes: left, right and brake. Due to using developed SVM, commands can be predicted 500ms earlier with the system accuracy of 94.6% on average. Keywords: intentional EEG, driving assistant. At the University of Tabriz we were working to take this from a lab setup toward something you could actually put in a car. Read the paper on SpringerLink . It appears in LNEE 2019 and on the IEEE website. --- ### Open-BCI: First touch URL: https://magnumical.ca/blog/open-bci-first-touch Published: 2019-09-08 Language: English Topics: University, signal processing, تصورحرکتی, مغز, پایتون, pthob, pythob, open-bci, واسط مغز و رایانه, بی سی ای, bci, motory, motor imagery In short: our OpenBCI kit arrived and we put it on a head the same week. Here is how it actually feels to use: good hardware, open software, dry electrodes that beat gel for setup time, and more noise than you would like. OpenBCI specializes in creating low-cost, high-quality biosensing hardware for brain computer interfacing. Our arduino compatible biosensing boards provide high resolution imaging and recording of EMG, ECG, and EEG signals. Our devices have been used by researchers, makers, and hobbyists in over 60+ countries as brain computer interfaces to power machines and map brain activity. OpenBCI headsets, boards, sensors and electrodes allow anyone interested in biosensing and neurofeedback to purchase high quality equipment at affordable prices. What we liked The hardware and the software are built for each other, so the first recording took minutes rather than a day. Better still, you can modify all of it yourself. The headset prints in three sizes, so the design is yours to change. The dry electrodes are the other win. They are much quicker to work with than gel electrodes and the impedance is acceptable for what we need. What bit us We started with the large headset and it was far too big. We could not seat Cz, F1 and F3 properly, which is exactly where we needed clean contact. Watch the noise Signals come in noisy more often than the demos suggest. Budget time for filtering before you trust anything you plot. Worth it Compared with something like MindWave, OpenBCI wins for us because it is open and easy to use, and you get the raw signal without paying extra for it. Next step: print the small headset sizes on our own 3D printer. --- ### Neural Networks- Review URL: https://magnumical.ca/blog/neural-networks-review Published: 2018-09-22 Language: English Topics: University, Artificial intelligence, machine learning, Deep learning, Fields of research, biomedical engineering, biomedical, network neural, deep learning, پایتون, برنامه نویسی, دیپ لرنینگ, مهندسی, مهندسی پزشکی In short: notes I took while reviewing the basics of neural networks. Mostly quotes worth keeping, plus the three kinds of learning and where each one shows up. A lot is happening in AI right now. Neural networks are one part of it, and that is the part I want to talk about here. Quotes worth keeping Artificial Intelligence is the New Electricity Andrew Ng Geoffrey Hinton made neural networks easier to understand for people. Three kinds of learning - Supervised learning - Unsupervised learning - Reinforcement learning Recommendation systems are supervised learning. AlphaGo is reinforcement learning. Where it lands AI can help produce medicine. It can also diagnose skin cancer. --- ### Genomic signal processing- An introduction URL: https://magnumical.ca/blog/genomic-signal-processing-an-introduction Published: 2018-09-17 (updated 2018-09-17) Language: English Topics: papers In short: after a biophysics class I went looking for work on programming biomolecules and found Dimitris Anastassiou's paper on genomic signal processing. These are the parts I kept. The paper is here: Genomic signal processing on IEEE Xplore . Genomes are already digital Genomic information is digital in a very real sense; it is represented in the form of sequences of which each element can be one out of a finite number of entities. Such sequences, like DNA and proteins, have been mathematically represented by character strings, in which each character is a letter of an alphabet. In the case of DNA, the alphabet is size 4 and consists of the letters A, T, C and G; in the case of proteins, the size of the corresponding alphabet is 20. Genomic signal processing, Dimitris Anastassiou Why signal processing has not taken over yet The main reason that the field of signal processing does not yet have significant impact in the field is because it deals with numerical sequences rather than character strings. However, if we properly map a character string into one or more numerical sequences, then digital signal processing (DSP) provides a set of novel and useful tools for solving highly relevant problems. Genomic signal processing, Dimitris Anastassiou What proteins do Protein molecules tend to fold into complex three-dimensional (3-D) structures forming weak bonds between their own atoms, and they are responsible for carrying out nearly all of the essential functions in the living cell by properly binding to other molecules with a number of chemical bonds connecting neighboring atoms. Genomic signal processing, Dimitris Anastassiou Start and stop codons A particular triplet, ATG, serves as the START codon and it also codes for the M amino acid (methionine); thus, methionine appears as the first amino acid of proteins, but it may also appear in other locations. We also see that there are three STOP codons (TAA, TAG, TGA) indicating termination of amino acid chain synthesis, and the last amino acid is the one generated by the codon preceding the STOP codon. Mapping letters to numbers In a DNA sequence of length N, assume that we assign the numbers a, t, c, g to the characters A, T, C, G, respectively. A proper choice of the numbers a, t, c and g can provide potentially useful properties to the numerical sequence x[n]. For example, if we choose complex conjugate pairs t = a* and g = c*, then the complementary DNA strand is represented by ~x[n] = x*[−n + N −1], n = 0, 1, …, N −1 That last one is the trick the whole field hangs on. Pick the mapping well and the complementary strand falls out as a time reversal and conjugation, which is something a DSP toolbox already knows how to do. --- ### Wearable ECG- Implementation URL: https://magnumical.ca/blog/wearable-ecg-implementation Published: 2018-09-17 (updated 2022-11-29) Language: English Topics: University, MATLAB projects, Arduino projects, signal processing, biomedical engineering, ساخت ای سی جی, مهندسی گزشکی, fda, device, wearable ecg, ad8232, DIY, biomedical, ekg, ecg, مهندسی پزشکی, نوار قلب In short: I built a working ECG recorder out of an AD8232 module, an Arduino, three electrodes and a breadboard. Here are the parts, the wiring, where the electrodes go, and how to get the trace on a screen. The heart has a vital role in our life, so being aware of its activity matters. This project was about getting the AD8232 up and running to record an electrocardiograph. What you need AD8232. An integrated front end for signal conditioning of cardiac biopotentials. It holds a specialized instrumentation amplifier, an operational amplifier, and a right-leg drive amplifier. Arduino. Open source hardware: single-board microcontrollers and kits for building digital devices that sense and control things in the physical world. Electrodes. The bridge between the body and the input stage. Breadboard. Junctions. Electrode wires. Good cable means less noise picked up on the way in. Putting it together Read the AD8232 datasheet first. Once you know what each pin is for, the module is easy to use well. This is the build after wiring everything up. Placing the electrodes Electrode placement changes the trace Put the LL electrode on the right side and you may see an extra shape after the QRS complex. Seeing the signal I wired up an LED and a speaker that fire on each heartbeat, which makes it obvious when the rig is working before you plot anything. For the trace itself, the Arduino IDE's serial plotter is enough to start. MATLAB, Processing and PLX-DAQ all work too. --- ### BCIپردازش تصورحرکتی + راه اندازی آردوینو URL: https://magnumical.ca/blog/bci Published: 2018-09-12 (updated 2018-09-12) Language: Persian Topics: داتنشگاه تبریز, eeg, motor imagery, brain, csp, biomedical, تصورحرکتی, مغز, پردازش سیگنال, ای ای جی, مهندسی, پزشکی, bci خلاصه: کد متلب برای پردازش سیگنال مغزی (EEG) از داده‌های مسابقه BCI، با فیلترهای فضایی (CSP)، و اتصال متلب به آردوینو. امیدوارم تابستون خوبی رو پشت‌سر گذاشته‌ باشید. در ادامه متلب کد های پردازش سیگنال مغزی(EEG) - از داده های مسابقه BCI - رو میزارم. بعد از پردازش، من متلب رو به آردوینو متصل کردم تا بتونیم بعد از پردازش، به عملکرد مورد نظر دست پیدا کنیم. توی این مثال، با تصور چپ یا راست، لامپ سفید یا سبز روشن میشه. در این پروژه، از فیلتر های فضایی یا CSP استفاده شده. بزودی طی یک ویدیو کاملا به توضیح نوشتن این کد میپردازم. - ثبت داده داده‌های تصور حرکتی از مسابقه BCI. - استخراج ویژگی فیلترهای فضایی یا همان CSP. - اتصال به آردوینو با تصور چپ یا راست، لامپ سفید یا سبز روشن می‌شود. فایل دانلود این پست دیگر در دسترس نیست. کدهای دیگر من در گیت‌هاب هست. --- ### متلب و سیگنالها و سیستم ها URL: https://magnumical.ca/blog/post-2374 Published: 2018-07-01 (updated 2018-07-01) Language: Persian Topics: University, MATLAB projects, signal processing, کد متلب, شسورس کد متلب, spurce code, filter, matlab, freqs, matlab learning, توابع متلب, signals and system, متلب, دانشگاه تبریز, آموزش, سیگنال سیستم, فیلتر, اموزش متلب, برنامه نویسی خلاصه: کدهای متلب درس سیگنال‌ها و سیستم‌ها، در شش سری: رسم و پخش صدای سیگنال، کار با دیتاست‌های خود متلب، ذخیره و لود داده، ضرایب سری فوریه، پاسخ فرکانسی تابع تبدیل، و محاسبه خروجی سیستم. سیگنال ها و سیستم ها درس مهمیه و خیلی هم پایه ای و کاربردی. بخاطر همین استاد گراوانچی زاده همراه با تدرس فوق العاده، جنبه های عملی رو در متلب نیز باهامون کار میکردن. که توی ادامه متلب کد هاشون رو گذاشتم. سری اول: پلات کردن و شنیدن صدای سیگنال‌ها x=0:0.01:1 y=cos(2*pi*(x/0.1)) figure(1) plot (x,y) sound(1000*y,8000) سری دوم: کار با دیتاهای تعریف‌شده داخل متلب clc;clear all load clown whos figure(1) colormap('gray') imagesc(X) figure(2) colormap('hot') imagesc(X) figure(3) colormap('pink') imagesc(X) figure(5) colormap('bone') imagesc(X) سری سوم: ذخیره‌سازی و لود اطلاعات clc;clear all x = 0:3:360 y = sin(x*pi/180) xy = [x' y'] save sine.mat xy clear all load sine whos clc;clear all load train whos sound(y) plot(y) سری چهارم: رسم فاز و اندازه ضرایب سری فوریه clear all;clc;close all k=-10:10 %============= a=1/7 * exp(-j*4*pi*k/7).*sin(5*pi*k/7)./sin(pi*k/7) %============= mag=abs(a) angle=phase(a) subplot(1,2,1) xlabel('k') ylabel('|ak|') stem(k,mag) %============= subplot(1,2,2) stem(k,angle); xlabel('k') ylabel(' target_length: interval = split_interval(interval) if not interval: print ("Function returned False! (spliting the interval)") return False interval_length = get_length(interval) t.add_row([interval[0], interval[1],interval_length]) print ("Bisection Method\n\n|_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_--| \n\n Result: [%f : %f]" % (interval[0], interval[1])) print (t) def fun(x): return pow(x,2)- 2 interval = [0, 2] length = decimal.Decimal('0.00000000001') t = PrettyTable(['a', 'b','interval size']) run_bisection(interval, length) k=input(":") Newton import time import numpy as np from prettytable import PrettyTable tab = PrettyTable(['m=(f(x+h) - f(x))/h', 'b=f(x)-m','-b/m']) def rootNR(f, start_x): step = 1e-10 x = start_x eps = 1e-15 while True: m = (f(x+step) - f(x))/step b = f(x)-m*x x_0 = -b/m tab.add_row([m, b,x_0]) if (np.abs(x-x_0) <= eps): break else: x = x_0 return x, np.abs(x-x_0) if __name__ == "__main__": t = time.time() def funct(x): return (x*x)-2 root, err = rootNR(funct, 1) print 'Root:', root print 'Elapsed time: %s ms' % ((time.time() - t)*1000) print 'Error:', err print tab k=input("enterkey to close ") Fixed Point import math def fixedpoint( f, x, tol, maxiter ): x1 = x + 8.0 * tol x0 = x + 4.0 * tol a= 2 * tol / ( f( x - tol ) - f( x + tol ) ) k = 0 while k <= maxiter and abs( x - x0 ) >= tol: x2, x1, x0 = ( x1, x0, x ) x = x + a * f( x ) print ("%2d %18.11e %18.11e") % ( k, x, abs( x - x0 ) ) k = k + 1 if k > maxiter: print ("Error: exceeded %d iterations") % maxiter rate = math.log( abs((x - x0) / (x0 - x1)) ) / \ math.log( abs((x0 - x1) / (x1 - x2)) ) return ( x, rate ) #------------------------------------------------------------------------------ if __name__ == "__main__": maxiter = 100 tol = 1e-10 def f(x): return x*x-2 def df(x): return x-2 a, b = ( 0.0, 2.0 ) first_guess = 1 dfr=0 print ("\n-------- Fixed-Point Method -------------------------\n") x, rate = fixedpoint( f, first_guess, tol, maxiter ) print ("root = "), x print ("Estimated Convergence Rate = %5.2f") % rate k=input(":") Lagrange Polynomial import numpy as np import matplotlib.pyplot as plt import sys def main(): if len(sys.argv) == 1 or "-h" in sys.argv or "--help" in sys.argv: print ("python lagrange.py .. ") print ("Example:") print ("python lagrange.py 0.1 2.4 4.5 3.2") exit() points = [] for i in xrange(len(sys.argv)): if i != 0: points.append((int(sys.argv[i].split(".")[0]),int(sys.argv[i].split(".")[1]))) #points =[(0,0),(25,30),(50,10), (57,0)] P = lagrange(points) nr = 2 print (" + str(points[nr][0]) + ", " + str(points[nr][1]) +") P(" + str(points[nr][0]) +")= " +str(P(points[nr][0])) plot(P, points) def plot(f, points): x = range(-10, 100) y = map(f, x) print y plt.plot( x, y, linewidth=2.0) x_list = [] y_list = [] for x_p, y_p in points: x_list.append(x_p) y_list.append(y_p) print x_list print y_list plt.plot(x_list, y_list, 'ro') plt.show() def lagrange(points): def P(x): total = 0 n = len(points) for i in xrange(n): xi, yi = points[i] def g(i, n): tot_mul = 1 for j in xrange(n): if i == j: continue xj, yj = points[j] tot_mul *= (x - xj) / float(xi - xj) return tot_mul total += yi * g(i, n) return total return P if __name__ == "__main__": main() Trapezoidal Integral import time def trapezoidal(f, a, b, n): h = float(b - a) / n s = 0.0 s += f(a)/2.0 for i in range(1, n): s += f(a + i*h) s += f(b)/2.0 return s * h a=input("Enter a:" ) a1=eval(a) b=input("Enter b:" ) b1=eval(b) n=input("Enter n: ") n1=eval(n) t = time.time() trap=trapezoidal(lambda x:x*x, a1,b1, n1) #mitunid tabe ro ba'd az ":" avaz konid masalan lambda x: 3*x print(trap) print ("Elapsed time in ms:") print( (time.time() - t)*1000 ) Simpson Integral import time def simpson(f, a, b, n): h=(b-a)/n k=0.0 x=a + h for i in range(1,n//2 + 1): k += 4*f(x) x += 2*h x = a + 2*h for i in range(1,n//2): k += 2*f(x) x += 2*h return (h/3)*(f(a)+f(b)+k) t = time.time() def function(x): return x*x l =simpson(function, 3.0, 6.0, 100) print (l) print ("Elapsed time in ms:") print( (time.time() - t)*1000 ) --- ### اپ آشنایی با رشته مهندسی پزشکی دانشگاه تبریز URL: https://magnumical.ca/blog/post-78 Published: 2018-05-29 (updated 2020-07-11) Language: Persian Topics: پروژه های اندروید, University, kvl htchv hknv, ddn, نرم افزار اندروید, اندروید, b4a, basicforandroid, آشنایی, دانشگاه تبریز, Tabriz University برای ورودی های 96 اپی رو طراحی کردم تا بیشتر با فضای دانشگاه و استاد های گروه مهندسی پزشکی آشنا بشن. کد و فایل‌های این اپ روی گیت‌هاب هست. --- ### ماهنامه بیوتک| شهریور 1396 |سرطان و میدان های الکتریکی URL: https://magnumical.ca/blog/1396 Published: 2018-05-28 Language: Persian Topics: University, papers, biomedical engineering, بیوتک, مجله, مهندسی, زشکی, سرطان, درمان, article, jornal, university, magazine, scitech, science این ماه مجله بیوتک هم منتشر شد که یکی از مقالاتش بعنوان «سرطان و میدان‌های الکتریکی» رو من نوشتم. اولین مقاله‌م بود. این مقاله در مورد آشنایی با یکی از روش های افزایش طول عمر مبتلایان به نوع خاصی از سرطان در قسمت سر هست. میتونید شماره شهریور ۱۳۹۶ ماهنامه بیوتک رو از این لینک دانلود کنید. --- ### اضافه کردن EEGLab به متلب و کار با آن URL: https://magnumical.ca/blog/eeglab Published: 2018-05-28 (updated 2018-05-28) Language: Persian Topics: signal processing, MATLAB projects, متلب, توباکس, دانلود, اموزش, eeglab, سیگنال مغزی, علوم اعصاب شناختی, cognitive, matlab, tool box خلاصه: نصب تولباکس EEGLab روی متلب در سه قدم، و بعد باز کردن دیتاست و رسم آن از منوی plot. تولباکس EEGLab یکی از بهترین تولباکس ها برای پردازش سیگنال های مغزیه. - دانلود و آنزیپ ابتدا اون رو دانلود کنید و در یک مسیر مشخص آنزیپ کنید. - معرفی مسیر به متلب در قسمت Home روی گزینه Set path کلیک کنید. با استفاده از add folder، تولباکس را به متلب معرفی کنید. - اجرا برای باز کردن EEGLab کافیست عبارت eeglab را در Command Window بنویسید. سپس دیتاست را به تولباکس بدهید. حال از قسمت plot میتونیم اطلاعاتی که داریم رو در شکل های گوناگون ببینیم و شروع به تفسیر اونها کنیم. --- ### معرفی و دانلود دیتابیس ECG و EEG URL: https://magnumical.ca/blog/ecg-eeg Published: 2018-05-28 (updated 2018-05-28) Language: Persian Topics: signal processing, MATLAB projects, پردازش سیگنال, مهندسی پزشکی, آموزش matlab, دیتاست, دیتابیس, تجسم حرکتی, motor imagery, ignal, process, signal process, database, dataset, matlab, .mat, دانلود, eeg, ecg, پردازش سیگنال مغزی, الکتروانسفالوگرام, الکتروکاردیوگرام, کاردیوگراف, نورولوژیشت, داده چند وبسایت برای دانلود دیتابیس‌های ECG و EEG: - physionet.org شامل انواع و اقسام دیتا ها از ECG و EEG و EHG تا دیتا های مربوط به تصویر و بانک اطلاعات تصویری. - www.brainsignals.de این وبسایت هم شامل داده هایی با تنوع زیادیه. - www.tcts.fpms.ac.be/~devuyst/Databases/DatabaseSpindles این وبسایت دیتا های یک تحقیق بنام DREAMS Project رو داره و خیلی خیلی مفیده. - www.sccn.ucsd.edu/~arno/fam2data/publicly_available_EEG_data.html این وبسایت هم شامل تعداد زیادی دادس. --- ### تمرینات درس برنامه نویسی! URL: https://magnumical.ca/blog/post-21 Published: 2018-05-28 (updated 2018-05-28) Language: Persian Topics: C and C++ projects خلاصه: چند سوال مهم برنامه‌نویسی C که توی کلاس حل تمرین حل کردیم. اول ده خط اشتباه که باید تصحیح شوند، بعد سیزده تمرین از محاسبه BMI تا تشخیص عدد اول و کار با رشته‌ها. چنتا سوال مهم برنامه نویسی C رو که توی کلاس حل تمرین حل کردیم رو قرار دادم. سوالات خوبی بودند و حلشون خیلی میتونه کمک بکنه. ۱. جملات زیر را تصحیح کنید - scanf( "d" ,value ); - printf( "The product of %d and %d is %d"n , x, y ); - firstNumber + secondNumber = sumOfNumbers - if ( number => largest ) largest == number; - */ Program to determine the largest of three integers /* - Scanf( "%d" , anInteger ); - printf( "Remainder of %d divided by %d isn" , x, y, x % y ); - if ( x = y ); printf( %d is equal to %dn" , x, y ); - print( "The sum is %dn," x + y ); - Printf( "The value you entered is: %dn , &value ); بقیه تمرین‌ها - برنامه ای بنویسید که سه مقدار بگیرد و جمع، میانگین، تفاضل و کوچکترین و بیشترین عدد را نشان دهد. - برنامه ای بنویسید که یک عدد چند رقمی را بگیرد و هر رقم را در یک سطر نشان دهد. - در شرکتی سالانه 150 خودکار و 50 بسته کاغذ a4 مصرف میشود. در پایان سال، این شرکت می خواهد بداند که در سال آینده چقدر باید براي این بخش از تجهیزات اداري هزینه کند. برنامه اي بنویسید که قیمت این اقلام را در امسال از ورودي خوانده، با خواندن نرخ تورم در سال آینده، هزینه شرکت را در این بخش حساب کند و به خروجی ببرد. تورم به صورت درصد وارد می شود که برنامه باید آن را به یک مقدار اعشاري تبدیل کند. مثلا اگر تورم را به صورت 5,6 از ورودي بخواند باید آن را به صورت 0,056 به کار ببرد. - برنامه ای بنویسید که قد و وزن را بگیرد و BMI را حساب کند. - برنامه ای بنویسید که حرف اول نام و نام خانوادگی را بگیرد و به شکل دلخواه تنظیم کند. - برنامه ای بنویسید که شکل مقابل را نمایش دهد: ##### $$$$$ &&&&& - برنامه ای بنویسید که عدد صحیحی را گرفته و آنرا با کاراکتر * نشان دهد. مثال x=5 : * ** *** **** ***** - برنامه ای بنویسید که عدد صحیحی را گرفته و آنرا با کاراکتر * نشان دهد (دو تا دوتا کم شود). مثال x=3 : *** * - برنامه ای بنویسید که عدد صحیحی را گرفته و مشخص کند آن عدد اول است یا خیر. - برنامه ای بنویسید که عددی را گرفته و فاکتوریل آنرا حساب کند. - برنامه ای بنویسید که رشته ای را از کاربر بگیرد و حروف تکراری پشت سر هم را از آن حذف کند. - برنامه ای بنویسید که رشته ای را از کاربر بگیرد و بررسی کند که آیا از دو طرف یکسان است یا خیر. مثال: reer از دو طرف یکسان است ولی reza از دو طرف یکسان نیست. - برنامه ای بنویسید که رشته ای را از کاربر بخواند و جمع اعداد داخل رشته را حساب کند.