<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by dylan wenzlau on Medium]]></title>
        <description><![CDATA[Stories by dylan wenzlau on Medium]]></description>
        <link>https://medium.com/@dylanwenzlau?source=rss-c652ab9d90e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vmkLVl3uFTmhpJ4jDEpW0g.jpeg</url>
            <title>Stories by dylan wenzlau on Medium</title>
            <link>https://medium.com/@dylanwenzlau?source=rss-c652ab9d90e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:52:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dylanwenzlau/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Longevity Cheat Sheet: 15 Ways to Live Longer]]></title>
            <link>https://medium.com/@dylanwenzlau/longevity-cheat-sheet-4228692a039b?source=rss-c652ab9d90e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4228692a039b</guid>
            <category><![CDATA[health]]></category>
            <category><![CDATA[fitness]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[longevity]]></category>
            <dc:creator><![CDATA[dylan wenzlau]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 18:51:50 GMT</pubDate>
            <atom:updated>2022-01-28T19:12:28.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imSTCOJDVbOdD50cMTFJqw.png" /></figure><p>First off, this guide is not just about lifespan. These tips can improve your energy, happiness, productivity, and much more than just how long you live.</p><p>This cheat sheet is designed to be short and jam-packed with science-based tips to improve your longevity. In contrast to fluffier online resources, we will focus exclusively on results of modern science. For each tip in our guide, we identify a reasonable longevity improvement that an average person might be able to attain, ranging from 7% to 66%.</p><p><strong>Disclaimer</strong>: The studies below are mostly correlations, not guaranteed causations, and are based on averages of many people. This means that your personal health may react differently than in the studies. Before taking action, you should talk to your doctor about your specific situation.</p><h3>#1: Do not smoke cigarettes</h3><p>The most boring and yet most effective recommendation on our list shouldn’t surprise anyone. <em>Don’t light toxic stuff on fire and then inhale it.</em> Never-smokers vs. lifelong smokers have a whopping <a href="https://www.nejm.org/doi/full/10.1056/NEJMsa1211128">66% reduction in mortality</a>, and quitting after a long time of smoking can also retain much of this benefit.</p><h3>#2: Take 8,000 to 12,000 steps per day</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*vJIRVkom9iskBAB7.jpeg" /></figure><p>There’s a reason fitness trackers target 10,000 steps per day: it’s the magic number that gets you most of the possible improvement. Increasing step count from 4,000 to 8,000 per day was associated with a staggering <a href="https://pubmed.ncbi.nlm.nih.gov/32207799/">51% reduction</a> in death from all causes (all-cause mortality). Additionally, the intensity of the steps, like running vs. walking, didn’t matter at all! So 25 minutes on the elliptical might save you time in obtaining your step goal, but each step will benefit your longevity the same as a normal walk.</p><h3>#3: Get sufficient sunlight</h3><p>This was higher up the list than we expected, but it turns out that totally hiding from the sun can really hurt you. A <a href="https://pubmed.ncbi.nlm.nih.gov/24697969/">study of 29,518 Swedish</a> women found a 2X decrease in mortality associated with the highest amount of sun exposure. Note however that we only gave this study a scientific rigor score of 1/3 because it was only women and took place in a northern (less sunny) country. Many other studies have found that adequate sunlight is important for longevity though, often related to Vitamin D and <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4935707/">melatonin</a>.</p><p>It’s obvious, but we’ll state it anyway: too much sun will kill you. Pretty quickly, in fact. So don’t take this as advice to sit in the sun all day or to get sunburnt.</p><h3>#4: Consider dry sauna a few times per week</h3><p>Our study showcasing sauna benefits is from Finland, as many sauna aficionados might have guessed. The study only includes men and they’re all from Finland, but it’s the best study we found and it shows a <a href="https://jamanetwork.com/journals/jamainternalmedicine/fullarticle/2130724">substantial 40% reduction</a> in all-cause mortality for those who used a sauna 4–7 times per week compared with once per week. Normally we’d compare with zero saunas per week, but apparently that is unheard of in the sauna capital of the world! Keep in mind this is for dry saunas at around 175˚F, so does not necessarily apply to cooler saunas, infrared saunas, or steam rooms. Although, we did find a study <a href="https://www.sciencedirect.com/science/article/pii/S073510970101467X">linking infrared sauna with coronary improvements</a>.</p><h3>#5: Brush and floss your teeth nightly</h3><p>In addition to not aggravating the people within smelling distance, brushing and flossing each independently help you live longer according to our chosen <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3124861/">study on dental behaviors</a>. Brushing and flossing every day compared to not every day was associated with a mighty 37% reduction in death during the study period. Yep, it wasn’t just something your parents bugged you about, it might actually kill you! A curious discovery in the article was that nightly brushing was most important, and was even better than morning and daytime combined. Flossing every day was best, but don’t worry if you’re lazy sometimes, there was still noticeable benefit in flossing “sometimes”, just not as much.</p><h3>#6: Minimize your stress levels</h3><p>Another commonly mentioned factor of faster aging, reduction of perceived stress landed on our list with <a href="https://pubmed.ncbi.nlm.nih.gov/27407085/">thorough scientific evidence</a>. There is an entire industry around stress reduction, but if you’re looking to improve you should first consider all the other health improvements on this list since many can reduce stress. Then, perhaps consider meditation or massage, which both have scientific evidence of stress reduction.</p><h3>#7: If you drink alcohol, stay below 7 standard drinks per week</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*t9Ua6DRbfcQocTc7.png" /></figure><p>A small amount of alcohol appears to give you slight protection from a few causes of death, notably myocardial infarction, but it’s still detrimental to overall longevity. For amounts below 100 grams (~7 drinks) per week, <a href="https://www.thelancet.com/journals/lancet/article/PIIS0140-6736(18)30134-X/fulltext">this study of 599,912 people</a> found negligible effects on mortality. But, as you can see in the chart, those negative effects increased steeply above 7 drinks per week. Cutting down from 3 drinks per day to 1 drink could reduce your risk of death by 31%!</p><p>Keep in mind that if you don’t currently drink, we wouldn’t recommend you start, since alcohol is known to be addictive and moderating your consumption might be difficult.</p><h3>#8: Consider intermittent fasting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*-wAImj0f7CpdNyo-.png" /></figure><p>Caloric restriction is one of the most effective and persistent methods of extending life across every species of life ever studied. Humans, however, have not been equally proven to live longer simply by reducing calories. There are some studies showing probable positive effects, such as the people who eat less in the Japanese islands of Okinawa, and across studies of fasting, which is a little different from calorie restriction. The <a href="https://www.ahajournals.org/doi/10.1161/circ.140.suppl_1.11123">best study we found</a> wasn’t as thorough as we’d hoped because it studied only 2,714 people and they were all recovering from a surgical procedure. But, it did show a very substantial reduction in mortality for those who routinely fasted for 5+ years compared with those who didn’t fast.</p><h3>#9: Don’t consume too much sugar</h3><p><a href="https://academic.oup.com/ajcn/article/109/2/411/5261249">This study</a> found that consuming only 10% of your daily calories as sugars compared with 20% or more offered a 23% reduction in mortality. The authors also found that it was more important to avoid sugar in beverages than it was in solid foods. Similar to minimizing sugar, <a href="https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0107968">avoiding high glycemic index foods</a> is also extremely helpful to your longevity. Basically, eat more of the stuff like nuts and vegetables that don’t give you an instant dump of energy.</p><h3>#10: Minimize processed meat</h3><p>Of all the meats you can eat, fish is one of the best for longevity while red meat and processed meat are among the worst. That’s a generalization of course — some fish are much healthier to eat than others (wild salmon is great), and the quality of red meats can vary significantly. The study we chose shows the <a href="https://academic.oup.com/ajcn/article/105/6/1462/4569801">biggest offender to be processed meat</a> by far, but also shows red meat is slightly harmful on average. So our official recommendation here is to avoid processed meat when you can, and either avoid red meat or be sure it’s high quality.</p><h3>#11: Avoid bad air quality</h3><p>Bad air can come from many sources including polluted cities, factories, forest fires, and high heat cooking. Basically, it’s not healthy to burn stuff and then breathe it in. A <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4748718/">massive study on U.S. cities</a> found that each 10 µg/m3 decrease in PM2.5, a common measure of air pollution, reduces your mortality by 17%. This amount of reduction or more could be achieved by moving from a polluted city or factory to the suburbs. You can easily find your neighborhood’s current PM2.5 measurement online. If you’re in one of the world’s most polluted cities, your potential benefit could be much higher than 17%! And if you don’t plan on moving, you can also use an air purifier in your home and office, and use a car with HEPA filters to help minimize your exposure.</p><h3>#12: Consider drinking 2–4 cups of coffee per day</h3><p>Before modern science began adjusting for confounding factors, researchers used to think that <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3439152/">coffee increased death rates</a>. In reality, coffee drinkers were just more likely to <em>also</em> smoke cigarettes. After adjusting for this, recent studies show a <a href="https://pubmed.ncbi.nlm.nih.gov/31055709/">non-trivial reduction in mortality</a> for moderate coffee drinking. Furthermore, the <a href="https://jamanetwork.com/journals/jamainternalmedicine/fullarticle/2686145">improvement appears to remain</a> even if you’re a slow metabolizer of caffeine, which is something you can test for with popular genetic test kits. Note that it’s <em>coffee</em> studied here, not caffeine. Decaffeinated coffee has shown similar results.</p><p>Remember, caffeine is a drug and is often addictive. It can be beneficial, but can also cause serious effects on your body, particularly at high amounts, so consult your doctor if you’re unsure.</p><h3>#13: Eat 5 servings of fruits and vegetables per day</h3><p>More servings of fruits and veggies were <a href="https://pubmed.ncbi.nlm.nih.gov/33641343/">associated with lower mortality</a>, plateauing around ~5 servings. Notably, this does not include starchy veggies like corn, peas, and potatoes, nor does it include fruit juices. Increasing from 2 to 5 servings per day is what showed the 13% benefit we’re highlighting.</p><h3>#14: Sleep 7–9 hours per night</h3><p>Many studies including this <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2864873/">meta study</a> show increased mortality if you sleep too little. One difficulty is they had to combine different definitions of “short sleep” ranging from 4 to 7 hours, but the overall result was that staying above ~7 hours reduced mortality. A curious result of their study was that long sleep was even worse than short sleep. Somewhere in the range 7–9 hours looked optimal for most studies, and although the studies were based on survey answers and couldn’t measure it, it’s common to recommend 7 hours of time <em>actually asleep</em> and not just laying in bed.</p><h3>#15: Consider Metformin</h3><p>Normally we wouldn’t include a drug targeting a specific disease in a longevity cheat sheet built for everyone, but Metformin is a notable exception. In studies meant to understand its effectiveness at improving diabetes, the researchers were surprised to find that <a href="https://pubmed.ncbi.nlm.nih.gov/28802803/">Metformin reduced death</a> from all causes for diabetics even beyond non-diabetics by 7%. This suggests that non-diabetics could benefit by even more than 7% by taking it. However, Metformin is a prescription drug in the U.S., so we only recommend considering it through talking with your doctor, or other legitimate pathways if you live outside the U.S.</p><h3>Bonus: Drinking more water doesn’t actually help (???)</h3><p>Strangely, <a href="https://pubmed.ncbi.nlm.nih.gov/24398890/">no correlation was found</a> between the amount of liquids consumed in a day and mortality. We all know that you’ll die within days if you stop drinking water, but perhaps the negative effects only appear with extreme dehydration, whereas all the study participants had full access to water.</p><h3>Epilogue</h3><p><a href="https://guavahealth.com/">Guava</a> can help you track many of the healthy habits in this list. We built Guava to provide the best way to understand and control everything related to your personal health and longevity, all in one place. Guava combines your lab tests, medications, fitness device metrics, lifestyle logs, and more, to make it easy to ensure your health is on track.</p><p><em>Originally published at </em><a href="https://guavahealth.com/article/longevity-cheat-sheet"><em>https://guavahealth.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4228692a039b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get Your Medical Records]]></title>
            <link>https://medium.com/@dylanwenzlau/how-to-get-your-medical-records-745b47b41df2?source=rss-c652ab9d90e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/745b47b41df2</guid>
            <category><![CDATA[medical-records]]></category>
            <category><![CDATA[health-tracking]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[hipaa]]></category>
            <dc:creator><![CDATA[dylan wenzlau]]></dc:creator>
            <pubDate>Thu, 07 Oct 2021 21:19:39 GMT</pubDate>
            <atom:updated>2021-10-07T21:26:28.850Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are medical records?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1UwZRqQ6J1VF4X2xtx28g.png" /></figure><p>Medical records are all the documentation and data that a healthcare provider keeps about your health. It includes your medications, surgeries, doctor visit summaries and notes, x-ray and MRI imaging, lab tests, and sometimes device data like heart rate or glucose levels. It usually does not contain your genetic information, unless you specifically gave it to your doctor or took a test through your clinic. Your record also includes logistical information like your full name, date of birth, social security number, home address, and other demographics.</p><h3>Why should I care about getting my records?</h3><p>Having your comprehensive medical record empowers you to understand your health better and play a proactive role in improving it.</p><ul><li>Take control of your health and do your own research on your history and test results. No one cares about your health as much as you.</li><li>Review results immediately rather than waiting until your next appointment</li><li>Avoid costly repeat x-rays, lab tests, and wrong or delayed diagnoses by having prior results on-hand for new doctors</li><li>Read your doctor’s actual notes about your visits</li><li>Save records before your provider deletes them. US states have various <a href="https://www.healthit.gov/sites/default/files/appa7-1.pdf">retention laws</a> ranging from 5–10 years, but after that they can permanently delete your patient records.</li></ul><h3>How can I get my records?</h3><h4>1) Make a list of your care providers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*GXwQy85aRTiBvbGxTS_DDQ.png" /></figure><p>Take some time and really think about all the healthcare and medical tests you’ve ever received starting at age 0. Even the healthiest people have often been to more providers than they think!</p><p>Some questions to help guide you:</p><ul><li>Where have you gotten any flu or vaccine shots?</li><li>What pharmacies have you filled prescriptions from?</li><li>What are all the health insurance companies you’ve used?</li><li>Which urgent care clinics have you been to?</li><li>Have you ever gotten x-rays, MRIs, CT scans, or other body scans?</li><li>Have you been to physical therapy or mental health therapists?</li><li>Have you been to hospitals or clinics in other states or countries or on vacation?</li><li>Which clinics did you go to as a kid or in college?</li><li>Are you on Medicare/Medicaid?</li></ul><h4>2) Log in to your patient portals</h4><p>Most health care providers, especially larger ones, have a “patient portal” which is a website or app where you can log in with a username and password. These portals generally give you online access to most of your health records and and let you send secure messages to your doctor and take other actions.</p><p>Some common patient portals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6Whh_A3Xa7OkI9Fx6f-Cg.png" /></figure><p>If you already have a login for a given provider, you can just log in and view your records, and BOOM you’re done! Almost. Many patient portals do not contain your radiology records like x-rays and MRIs. To get these, follow the steps below to manually request records.</p><p>If you don’t yet have a login for a provider, you can obtain one by checking their website for a “create account” or “patient portal” link. When you first visit a clinic they’ll often email you an activation code, but you can also request an account either on their website or by emailing or calling your doctor’s office. Sometimes you can simply click “create account” on your hospital’s website and input your name, date of birth, and social security number, and they will immediately activate your account if the info matches.</p><p>Does managing all those portals sound like a pain? <a href="https://guavahealth.com/">Guava</a> lets you instantly connect to as many providers as you want and easily view all your records in one place.</p><h4>3) Request records manually</h4><p>If you aren’t able to easily access a patient portal, or if you want your complete record including imaging, then you’ll have to submit a medical records request. You can sometimes request imaging records from your patient portal if you already have a login. Otherwise, your provider will usually display their contact information for records requests on their website, such as an email like myrecords@walgreens.com or a phone number. Sometimes they’ll have a release form you can fill out right away on their website. They will likely ask you to verify your identity to authorize the medical record release using info like your date of birth and social security number, since HIPAA law is strict about when a copy of your medical records may be released. You may also be asked to sign their authorization form, but keep in mind that if you prefer to sign it digitally because that’s faster and easier for you, US providers cannot force you to sign on paper due to the <a href="https://www.fdic.gov/resources/supervision-and-examinations/consumer-compliance-examination-manual/documents/10/x-3-1.pdf">ESIGN Act</a>.</p><p>Be sure to ask for your entire record including imaging, since otherwise you may only receive your written records. If you have any device measurements like continuous heart rate monitoring then you should also explicitly ask for this.</p><p>Keep in mind that all providers in the USA are <a href="https://www.hhs.gov/hipaa/for-professionals/privacy/guidance/access/index.html">legally required by HIPAA</a> and other federal and state laws to give you your own records. Some smaller medical practices still aren’t very familiar with these laws, so if your provider tries to deny you access or make you do anything unreasonable other than verify your identity, then you can politely inform them of their legal obligation.</p><p>Depending on your provider, you may receive records in one of many forms including secure email, fax, DVD, USB drive, or paper mail. If you want to store all those records digitally, you may want to buy a scanner or take pictures of each page and use a DVD reader for the bigger files.</p><p>Some advantages of storing records digitally:</p><ul><li>They don’t waste cabinet space</li><li>They don’t degrade over time like paper</li><li>You can instantly share them with anyone in the world, such as family members or doctors, for free</li></ul><p><a href="https://guavahealth.com/">Guava</a> can remove the hassle of emailing, faxing, and calling your providers for you, and also take care of scanning and importing records on your behalf.</p><h3>How can I store and organize my health records?</h3><p>You probably want all your records stored in one place, digitally and encrypted. One option is a generic cloud file service like Google Drive or Dropbox so that you can view your records from anywhere and they are backed up forever. If you prefer maximum privacy storage on your own hardware instead of a cloud service, then be sure to store your records on multiple devices such as USB drives or external hard drives to ensure you get the same redundancy as a robust cloud service. This way, your records aren’t gone forever if your laptop fries.</p><p>In addition to storing all your medical records securely in one place, you may want to organize them to better utilize your valuable health information. You can categorize your visit notes, group related lab results to track health risks, and track your numbers over time to see how your diet, medications, or lifestyle changes are affecting your health. Instead of using spreadsheets or manually charting your medical data, <a href="https://guavahealth.com/">Guava</a> can automatically organize your health data and help you understand it, so you can take better action toward improving your health.</p><p><em>Originally published at </em><a href="https://guavahealth.com/article/how-to-get-your-medical-records"><em>https://guavahealth.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=745b47b41df2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meme Text Generation with a Deep Convolutional Network in Keras & Tensorflow]]></title>
            <link>https://medium.com/data-science/meme-text-generation-with-a-deep-convolutional-network-in-keras-tensorflow-a57c6f218e85?source=rss-c652ab9d90e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a57c6f218e85</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[memes]]></category>
            <dc:creator><![CDATA[dylan wenzlau]]></dc:creator>
            <pubDate>Mon, 08 Apr 2019 21:12:11 GMT</pubDate>
            <atom:updated>2019-04-10T20:43:37.421Z</atom:updated>
            <content:encoded><![CDATA[<p>The goal of this post is to describe end-to-end how to build a deep conv net for text generation, but in greater <a href="https://i.imgflip.com/2fim0f.jpg">depth</a> than some of the existing articles I’ve read. This will be a practical guide and while I suggest many best practices, I am not an expert in deep learning theory nor have I read every single relevant research paper. I’ll cover takeaways about data cleaning, training, model design, and prediction algorithms.</p><h3>Step 1: Building training data</h3><p>The raw dataset we’ll draw from is ~100M public meme captions by users of the <a href="https://imgflip.com/memegenerator">Imgflip Meme Generator</a>. To speed up training and reduce complexity of the model, we only use the 48 most popular memes and exactly 20,000 captions per meme, totaling 960,000 captions as training data. However, since we are building a generational model there will be one training example for each <em>character</em> in the caption, totaling ~45,000,000 training examples. Character-level generation rather than word-level was chosen here because memes tend to use spelling and grammar… uh… creatively. Also, character-level deep learning is a superset of word-level deep learning and can therefore achieve higher accuracy if you have enough data and your model design is sufficient to learn all the complexity. If you try the finished model below, you’ll also see that char-level can be more fun!</p><p>Below is what the training data looks if the first meme caption is “make all the memes”. I’m omitting the code for reading from the database and performing initial cleaning because it’s very standard and could be done in multiple ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*1AVYhw27y0wBwnpi.jpg" /></figure><pre>training_data = [<br>    [&quot;000000061533  0  &quot;, &quot;m&quot;],<br>    [&quot;000000061533  0  m&quot;, &quot;a&quot;],<br>    [&quot;000000061533  0  ma&quot;, &quot;k&quot;],<br>    [&quot;000000061533  0  mak&quot;, &quot;e&quot;],<br>    [&quot;000000061533  0  make&quot;, &quot;|&quot;],<br>    [&quot;000000061533  1  make|&quot;, &quot;a&quot;],<br>    [&quot;000000061533  1  make|a&quot;, &quot;l&quot;],<br>    [&quot;000000061533  1  make|al&quot;, &quot;l&quot;],<br>    [&quot;000000061533  1  make|all&quot;, &quot; &quot;],<br>    [&quot;000000061533  1  make|all &quot;, &quot;t&quot;],<br>    [&quot;000000061533  1  make|all t&quot;, &quot;h&quot;],<br>    [&quot;000000061533  1  make|all th&quot;, &quot;e&quot;],<br>    [&quot;000000061533  1  make|all the&quot;, &quot; &quot;],<br>    [&quot;000000061533  1  make|all the &quot;, &quot;m&quot;],<br>    [&quot;000000061533  1  make|all the m&quot;, &quot;e&quot;],<br>    [&quot;000000061533  1  make|all the me&quot;, &quot;m&quot;],<br>    [&quot;000000061533  1  make|all the mem&quot;, &quot;e&quot;],<br>    [&quot;000000061533  1  make|all the meme&quot;, &quot;s&quot;],<br>    [&quot;000000061533  1  make|all the memes&quot;, &quot;|&quot;],<br>    <br>    ... 45 million more rows here ...<br>]<br># we&#39;ll need our feature text and labels as separate arrays later<br>texts = [row[0] for row in training_data]<br>labels = [row[1] for row in training_data]</pre><p>Like most things in machine learning, this is just a classification problem. We are classifying the text strings on the left into one of ~70 different buckets where the buckets are characters.</p><p>Let’s unpack the format.</p><ul><li>The first 12 characters are the meme template ID. This allows the model to differentiate between the 48 distinct memes we’re feeding it. The string is left padded with zeros so all IDs are the same length.</li><li>The 0 or 1 is the index of the current text box being predicted, generally 0 is the top box and 1 is the bottom box, although <a href="https://imgflip.com/memegenerator/Distracted-Boyfriend">many memes are more complex</a>. The two spaces are just extra spacing to ensure the model can tell the box index apart from the template ID and meme text. Note: it is critical that our convolution kernel width (seen later in this post) is no wider than the 4 spaces plus the index character, aka ≤ 5.</li><li>After that is the text of the meme so far, with | used as the end-of-text-box character.</li><li>Finally, the last character by itself (the 2nd array item) is the next character in the sequence.</li></ul><p>Several cleaning techniques were used on the data before training:</p><ul><li>Trim leading and trailing whitespace and replace repeated whitespace (\s+) with a single space character.</li><li>Apply a minimum string length of 10 characters so we don’t generate boring one-word or one-letter memes.</li><li>Apply a maximum string length of 82 characters so we don’t generate super long memes and because the model will train faster. 82 is arbitrary, it just made the overall training strings about 100 characters.</li><li>Convert everything to lowercase to reduce the number of characters the model must learn, and because many memes are just all caps anyway.</li><li>Skip meme captions with non-ascii characters to reduce the complexity the model has to learn. This means that both our feature text and labels will come from a set of only ~70 characters, depending on which ascii characters the training data happens to include.</li><li>Skip meme captions containing the pipe character | since it’s our special end-of-text-box character.</li><li>Run the text through a language detection library and skip meme captions that are unlikely to be English. Improves quality of the text we generate since the model only has to learn one language, and identical character sequences can have meanings in multiple languages.</li><li>Skip duplicate meme captions we’ve already added to the training set to reduce the chance the model simply memorizes entire meme captions.</li></ul><p>Our data is now ready to feed into a neural net!</p><h3>Step 2: Data Tensorization</h3><p>That may or may not be a word. Fun fact: apparently we in deep learning are heathens for calling multi-dimensional arrays tensors rather than the mathematical term “holors”, which is a generalized tensor not requiring particular transformation properties. But whatever, tensor sounds cooler than holor ;)</p><p>First, here is the python import code for everything we’ll do below:</p><pre><strong>from </strong>keras <strong>import </strong>Sequential<br><strong>from </strong>keras.preprocessing.sequence <strong>import </strong>pad_sequences<br><strong>from </strong>keras.callbacks <strong>import </strong>ModelCheckpoint<br><strong>from </strong>keras.layers <strong>import </strong>Dense, Dropout, GlobalMaxPooling1D, Conv1D, MaxPooling1D, Embedding<br><strong>from </strong>keras.layers.normalization <strong>import </strong>BatchNormalization<br><strong>import </strong>numpy <strong>as </strong>np<br><strong>import </strong>util  # util is a custom file I wrote, see github link below</pre><p>Neural nets operate on tensors of numbers (vectors/matrices/multi-dimensional arrays), so we need to restructure our text accordingly. Each of our training texts will be transformed into an array of integers (a rank 1 tensor) by replacing each character with its corresponding index from the array of ~70 unique characters found in the data. The order of the character array is arbitrary, but we choose to order it by character frequency so it stays roughly consistent when changing the amount of training data. Keras has a Tokenizer class which you can use for this (with char_level=True), but I wrote my own util functions because they were must faster than the Keras tokenizer.</p><pre># output: {&#39; &#39;: 1, &#39;0&#39;: 2, &#39;e&#39;: 3, ... }<br>char_to_int = util.map_char_to_int(texts)</pre><pre># output: [[2, 2, 27, 11, ...], ... ]<br>sequences = util.texts_to_sequences(texts, char_to_int)</pre><pre>labels = [char_to_int[char] for char in labels]</pre><p>These are the characters our data contains in order of frequency:</p><pre>0etoains|rhl1udmy2cg4p53wf6b897kv.&quot;!?j:x,*&quot;z-q/&amp;$)(#%+_@=&gt;;&lt;][~`^}{\</pre><p>Next we will pad our sequences of integers with leading zeros so they are all the same length, since the model‘s tensor math requires the shape of each training example to be identical. (<em>note: I could have used as low as 100 length here because our texts are only 100 characters, but I wanted all my pooling operations later on to be perfectly divisible by 2.</em>)</p><pre>SEQUENCE_LENGTH = 128<br>data = pad_sequences(sequences, maxlen=SEQUENCE_LENGTH)</pre><p>And finally we’ll shuffle our training data and split it into training and validation sets. Shuffling (randomizing the order) ensures that a particular subset of the data is not always the subset we use to validate accuracy. Splitting some data into a validation set allows us to gauge how well the model is performing on examples that we are not allowing it to use for training.</p><pre><em># randomize order of training data</em><br>indices = np.arange(data.shape[0])<br>np.random.shuffle(indices)<br>data = data[indices]<br>labels = labels[indices]</pre><pre><em># validation set can be much smaller if we use a lot of data<br></em>validation_ratio = 0.2 if<strong> </strong>data.shape[0] &lt; 1000000 else<strong> </strong>0.02<br>num_validation_samples = int(validation_ratio * data.shape[0])<br><br>x_train = data[:-num_validation_samples]<br>y_train = labels[:-num_validation_samples]<br>x_val = data[-num_validation_samples:]<br>y_val = labels[-num_validation_samples:]</pre><h3>Step 3: Model Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*eaU-biq79qgFjned.jpg" /></figure><p>I chose to use a convolutional net because convolutions are simple and fast to train. I did briefly test a two layer LSTM, but the accuracy per time spent training was worse than the conv net, and predictions with even that small LSTM took longer than the age of the universe (okay, maybe it just felt that long). Generative Adversarial Networks (GANs) are beautiful creatures with massive potential, but using them for text generation is still in early stages and my first attempt at it was lackluster. Maybe that will be my next post…</p><p>Okay, here’s the code used to construct our conv net model in Keras:</p><pre>EMBEDDING_DIM = 16</pre><pre>model = Sequential()</pre><pre>model.add(Embedding(len(char_to_int) + 1, EMBEDDING_DIM, input_length=SEQUENCE_LENGTH))<br>model.add(Conv1D(1024, 5, activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>model.add(BatchNormalization())<br>model.add(MaxPooling1D(2))<br>model.add(Dropout(0.25))<br>model.add(Conv1D(1024, 5, activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>model.add(BatchNormalization())<br>model.add(MaxPooling1D(2))<br>model.add(Dropout(0.25))<br>model.add(Conv1D(1024, 5, activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>model.add(BatchNormalization())<br>model.add(MaxPooling1D(2))<br>model.add(Dropout(0.25))<br>model.add(Conv1D(1024, 5, activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>model.add(BatchNormalization())<br>model.add(MaxPooling1D(2))<br>model.add(Dropout(0.25))<br>model.add(Conv1D(1024, 5, activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>model.add(BatchNormalization())<br>model.add(GlobalMaxPooling1D())<br>model.add(Dropout(0.25))<br>model.add(Dense(1024, activation=&#39;relu&#39;))<br>model.add(BatchNormalization())<br>model.add(Dropout(0.25))<br>model.add(Dense(len(labels_index), activation=&#39;softmax&#39;))<br><br>model.compile(loss=&#39;sparse_categorical_crossentropy&#39;, optimizer=&#39;rmsprop&#39;, metrics=[&#39;acc&#39;])</pre><p>Lots of things going on there. Here’s what all that code is doing:</p><p>First the model converts each input example from an array of 128 integers (each representing one text character) into a 128x16 matrix using a Keras Embedding. An embedding is a layer that learns an optimal way to convert each of our characters from being represented as an integer to instead being represented as an array of 16 floats like [0.02, ..., -0.91]. This allows the model to learn which characters are used similarly by embedding them near one another in 16-dimensional space, and ultimately increases the accuracy of the model’s predictions.</p><p>Next we add 5 convolutional layers each with a kernel size of 5, 1024 filters, and a ReLU activation. Conceptually, the first conv layer is learning how to construct words from characters, and later layers are learning to construct longer words and chains of words (n-grams), each more abstracted than the previous.</p><ul><li>padding=&#39;same&#39; is used to ensure the output dimensions of the layer are the same as the input dimensions, since otherwise a width 5 convolution would reduce the dimension of the layer by 2 for each side of the kernel.</li><li>1024 was chosen as the number of filters because it was a good tradeoff between training speed and model accuracy, determined by trial and error. For other datasets I would recommend starting with 128 filters and then increasing/decreasing it by a factor of two several times to see what happens. More filters generally means better model accuracy, but slower training, slower runtime predicting, and larger model size. However, if you have too little data or too many filters, your model may overfit and accuracy will plummet, in which case you should decrease the filters.</li><li>Kernel size of 5 was chosen after testing 2, 3, 5, and 7. Kernels of 2 and 3 did worse, and 7 was similar but slower due to needing to train 7/5 more parameters. In my research, other people have had success using kernel sizes from 3 to 7 in various combinations, but my takeaway is that a size 5 kernel usually performs decently on text data, and you can always experiment later on to squeeze out more accuracy for your particular dataset.</li><li>The ReLU activation was chosen because it is fast, simple, and very good for a huge variety of use cases. My takeaway from reading a few articles and research papers was that Leaky ReLU or other variations may give a slight improvement on some datasets, but it’s not guaranteed to be better, and it’s less likely to be noticeable on larger datasets.</li><li>Batch normalization is added after each conv layer so that the input parameters to the next layer are normalized based on the mean and variance for the given batch. This mechanism isn’t perfectly understood by deep learning engineers yet, but we know that normalizing input parameters improves training speed and becomes more important with deeper networks due to vanishing/exploding gradients. The <a href="https://arxiv.org/abs/1502.03167">original batch normalization paper</a> had impressive results.</li><li>A bit of dropout is added after each conv layer to help prevent the layer from simply memorizing the data and overfitting. Dropout(0.25) randomly kills 25% of the parameters (sets them to zero).</li><li>MaxPooling1D(2) is added between each conv layer to “squeeze” our sequence of 128 characters in half into sequences of 64, 32, 16, and 8 characters in the following layers. Conceptually, this allows the convolutional filters to learn more abstract patterns from the text in the deeper layers, since our width 5 kernel will span twice as many characters after the dimensionality is reduced by 2X by each max pooling operation.</li></ul><p>After all the conv layers we use a global max pooling layer, which is identical to the normal max pooling layers except that it automatically chooses how much to shrink the input size in order to match the size of our next layer. The final layers are just standard Dense (fully-connected) layers with 1024 neurons, and finally 70 neurons because our classifier needs to output the probability for each of our 70 different labels.</p><p>The model.compile step is pretty standard. The RMSprop optimizer is a decent all around optimizer and I didn’t experiment with changing it for this neural net. loss=sparse_categorical_crossentropy tells the model we want it to optimize for choosing the best category among a set of 2 or more categories (aka labels). The “sparse” part refers to the fact that our labels are integers between 0 and 70 rather than one-hot arrays each of length 70. Using one hot arrays for the labels takes WAY more memory, more time to process, and does not affect the model accuracy. Don’t use one hot labels!</p><p>Keras has a nice model.summary() function that lets us view our model:</p><pre>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #<br>=================================================================<br>embedding_1 (Embedding)      (None, 128, 16)           1136<br>_________________________________________________________________<br>conv1d_1 (Conv1D)            (None, 128, 1024)         82944<br>_________________________________________________________________<br>batch_normalization_1 (Batch (None, 128, 1024)         4096<br>_________________________________________________________________<br>max_pooling1d_1 (MaxPooling1 (None, 64, 1024)          0<br>_________________________________________________________________<br>dropout_1 (Dropout)          (None, 64, 1024)          0<br>_________________________________________________________________<br>conv1d_2 (Conv1D)            (None, 64, 1024)          5243904<br>_________________________________________________________________<br>batch_normalization_2 (Batch (None, 64, 1024)          4096<br>_________________________________________________________________<br>max_pooling1d_2 (MaxPooling1 (None, 32, 1024)          0<br>_________________________________________________________________<br>dropout_2 (Dropout)          (None, 32, 1024)          0<br>_________________________________________________________________<br>conv1d_3 (Conv1D)            (None, 32, 1024)          5243904<br>_________________________________________________________________<br>batch_normalization_3 (Batch (None, 32, 1024)          4096<br>_________________________________________________________________<br>max_pooling1d_3 (MaxPooling1 (None, 16, 1024)          0<br>_________________________________________________________________<br>dropout_3 (Dropout)          (None, 16, 1024)          0<br>_________________________________________________________________<br>conv1d_4 (Conv1D)            (None, 16, 1024)          5243904<br>_________________________________________________________________<br>batch_normalization_4 (Batch (None, 16, 1024)          4096<br>_________________________________________________________________<br>max_pooling1d_4 (MaxPooling1 (None, 8, 1024)           0<br>_________________________________________________________________<br>dropout_4 (Dropout)          (None, 8, 1024)           0<br>_________________________________________________________________<br>conv1d_5 (Conv1D)            (None, 8, 1024)           5243904<br>_________________________________________________________________<br>batch_normalization_5 (Batch (None, 8, 1024)           4096<br>_________________________________________________________________<br>global_max_pooling1d_1 (Glob (None, 1024)              0<br>_________________________________________________________________<br>dropout_5 (Dropout)          (None, 1024)              0<br>_________________________________________________________________<br>dense_1 (Dense)              (None, 1024)              1049600<br>_________________________________________________________________<br>batch_normalization_6 (Batch (None, 1024)              4096<br>_________________________________________________________________<br>dropout_6 (Dropout)          (None, 1024)              0<br>_________________________________________________________________<br>dense_2 (Dense)              (None, 70)                71750<br>=================================================================<br>Total params: 22,205,622<br>Trainable params: 22,193,334<br>Non-trainable params: 12,288<br>_________________________________________________________________</pre><p>The parameter counts are particularly useful if you’re not addicted to doing tensor shape multiplication in your head. When adjusting the hyperparameters we discussed above, it’s useful to keep an eye on the parameter count of the model, which roughly represents the model’s total amount of learning capacity.</p><h3>Step 4: Training</h3><p>Now we’re going to let the model train and use “checkpoints” to save the history and optimal model along the way so that we can check progress and make predictions using the latest model at any point during training.</p><pre><em># the path where you want to save all of this model&#39;s files<br></em>MODEL_PATH = &#39;/home/ubuntu/imgflip/models/conv_model&#39;<br><em># just make this large since you can stop training at any time<br></em>NUM_EPOCHS = 48<br><em># batch size below 256 will reduce training speed since<br></em># CPU (non-GPU) work must be done between each batch<br>BATCH_SIZE = 256</pre><pre><em># callback to save the model whenever validation loss improves<br></em>checkpointer = ModelCheckpoint(filepath=MODEL_PATH + &#39;/model.h5&#39;, verbose=1, save_best_only=True)</pre><pre><em># custom callback to save history and plots after each epoch<br></em>history_checkpointer = util.SaveHistoryCheckpoint(MODEL_PATH)</pre><pre><em># the main training function where all the magic happens!<br></em>history = model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=NUM_EPOCHS, batch_size=BATCH_SIZE, callbacks=[checkpointer, history_checkpointer])</pre><p>This is where you just sit and watch the magic number go up over a period of many hours…</p><pre>Train on 44274928 samples, validate on 903569 samples<br>Epoch 1/48<br>44274928/44274928 [==============================] - 16756s 378us/step - loss: 1.5516 - acc: 0.5443 - val_loss: 1.3723 - val_acc: 0.5891</pre><pre>Epoch 00001: val_loss improved from inf to 1.37226, saving model to /home/ubuntu/imgflip/models/gen_2019_04_04_03_28_00/model.h5<br>Epoch 2/48<br>44274928/44274928 [==============================] - 16767s 379us/step - loss: 1.4424 - acc: 0.5748 - val_loss: 1.3416 - val_acc: 0.5979</pre><pre>Epoch 00002: val_loss improved from 1.37226 to 1.34157, saving model to /home/ubuntu/imgflip/models/gen_2019_04_04_03_28_00/model.h5<br>Epoch 3/48<br>44274928/44274928 [==============================] - 16798s 379us/step - loss: 1.4192 - acc: 0.5815 - val_loss: 1.3239 - val_acc: 0.6036</pre><pre>Epoch 00003: val_loss improved from 1.34157 to 1.32394, saving model to /home/ubuntu/imgflip/models/gen_2019_04_04_03_28_00/model.h5<br>Epoch 4/48<br>44274928/44274928 [==============================] - 16798s 379us/step - loss: 1.4015 - acc: 0.5857 - val_loss: 1.3127 - val_acc: 0.6055</pre><pre>Epoch 00004: val_loss improved from 1.32394 to 1.31274, saving model to /home/ubuntu/imgflip/models/gen_2019_04_04_03_28_00/model.h5<br>Epoch 5/48<br> 1177344/44274928 [..............................] - ETA: 4:31:59 - loss: 1.3993 - acc: 0.5869</pre><p>Fast forward and here are some shiny plots of our loss and accuracy at each epoch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_oarar1lJMjUUlCz.jpg" /></figure><p>I’ve found that when training loss/accuracy is worse than validation loss/accuracy it’s a sign that the model is learning well and not overfitting.</p><p>As a side note if you’re using an AWS server for training, I found the optimal instance to be p3.2xlarge. This uses their fastest GPU as of April 2019 (Tesla V100), and the instance only has one GPU since our model cannot make use of multiple GPUs very efficiently. I did try using Keras’s multi_gpu_model but it requires making the batch size way larger to actually realize speed gains, which can mess with the model’s ability to converge, and it barely got 2X faster even when using 4 GPUs. The p3.8xlarge with 4 GPUs costs 4 times more, so for me it wasn’t worth it.</p><h3>Step 5: Predicting</h3><p>Okay so now we have a model that can output the probabilities for which character should come next in a meme caption, but how do we use that to actually create a full meme caption from scratch?</p><p>The basic premise is that we initialize a string with whichever meme we want to generate text for, and then we call model.predict once for each character until the model outputs the end-of-box-text character | as many times as there are text boxes in the meme. For the “X All The Y” meme seen above, the default number of text boxes is 2 and our initial text would be:</p><pre>&quot;000000061533  0  &quot;</pre><p>I tried a few different approaches for choosing the next character given the model’s output of 70 probabilities:</p><ol><li>Pick the character with highest score each time. This is ultra boring because it chooses the exact same text every time for a given meme, and it uses the same words over and over across memes. It spit out “when you find out your friends are the best party” for the X All The Y meme over and over. It liked to use the words “best” and “party” a lot in other memes too.</li><li>Give each character a probability of being chosen equal to the score the model gave it, but only if the score is above a certain threshold (≥ 10% of the highest score works well for this model). This means multiple characters can be chosen, but bias is given to higher scored characters. This method succeeded in adding variety, but longer phrases sometimes lacked cohesion. Here’s one from the Futurama Fry meme: “not sure if she said or just put out of my day”.</li><li>Give each character an equal probability of being chosen, but only if it’s score is high enough (≥ 10% of the highest score works well for this model). Also, use beam search to keep a running list of N texts at any given time, and use the product of all the character scores instead of just the last character’s score. This takes up to N times longer to compute, but seems to improve sentence cohesion in some cases.</li></ol><p>I’m currently using method #2 because it’s much faster than beam search and both methods give decent results. Below are some random examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Gucnk-HpkeJB6u6l.jpg" /></figure><p>You can play with the latest model yourself and generate from any of the 48 memes at <a href="https://imgflip.com/ai-meme">imgflip.com/ai-meme</a>.</p><p>The code for making runtime predictions using method #2 is below. The full implementation on Github is a generalized beam search algorithm so beam search can be enabled simply by increasing the beam width beyond 1.</p><pre># min score as percentage of the maximum score, not absolute<br>MIN_SCORE = 0.1<br>int_to_char = {v: k for k, v in char_to_int.items()}</pre><pre>def predict_meme_text(template_id, num_boxes, init_text = &#39;&#39;):<br>  template_id = str(template_id).zfill(12)<br>  final_text = &#39;&#39;<br>  for char_count in range(len(init_text), SEQUENCE_LENGTH):<br>    box_index = str(final_text.count(&#39;|&#39;))<br>    texts = [template_id + &#39;  &#39; + box_index + &#39;  &#39; + final_text]<br>    sequences = util.texts_to_sequences(texts, char_to_int)<br>    data = pad_sequences(sequences, maxlen=SEQUENCE_LENGTH)<br>    predictions_list = model.predict(data)<br>    predictions = []<br>    for j in range(0, len(predictions_list[0])):<br>      predictions.append({<br>        &#39;text&#39;: final_text + int_to_char[j],<br>        &#39;score&#39;: predictions_list[0][j]<br>      })<br>    predictions = sorted(predictions, key=lambda p: p[&#39;score&#39;], reverse=True)<br>    top_predictions = []<br>    top_score = predictions[0][&#39;score&#39;]<br>    rand_int = random.randint(int(MIN_SCORE * 1000), 1000)<br>    for prediction in predictions:<br>      # give each char a chance of being chosen based on its score<br>      if prediction[&#39;score&#39;] &gt;= rand_int / 1000 * top_score:<br>        top_predictions.append(prediction)<br>    random.shuffle(top_predictions)<br>    final_text = top_predictions[0][&#39;text&#39;]<br>    if char_count &gt;= SEQUENCE_LENGTH - 1 or final_text.count(&#39;|&#39;) == num_boxes - 1:<br>      return final_text</pre><p>You can view all the code including utility functions and a sample training data file on <a href="https://github.com/dylanwenzlau/ml-scripts/tree/master/meme_text_gen_convnet">github</a>.</p><h3>Step 6: ???</h3><h3>Step 7: Profit from AI-generated memes, obviously</h3><p>The end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a57c6f218e85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/meme-text-generation-with-a-deep-convolutional-network-in-keras-tensorflow-a57c6f218e85">Meme Text Generation with a Deep Convolutional Network in Keras &amp; Tensorflow</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[500X Faster Caching than Redis/Memcache/APC in PHP & HHVM]]></title>
            <link>https://medium.com/@dylanwenzlau/500x-faster-caching-than-redis-memcache-apc-in-php-hhvm-dcd26e8447ad?source=rss-c652ab9d90e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcd26e8447ad</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hhvm]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[dylan wenzlau]]></dc:creator>
            <pubDate>Wed, 15 Jun 2016 15:01:03 GMT</pubDate>
            <atom:updated>2018-05-14T07:30:54.556Z</atom:updated>
            <content:encoded><![CDATA[<p>Yes, you read that correctly. In this post, I’ll tell you how we’ve implemented “PHP file caching” in our application logic at Graphiq, resulting in crazy-fast cache reads.</p><p>The core of the technique is leveraging the PHP engine’s in-memory file caching (opcache) to cache application data in addition to code. HHVM has supported this technique for a few years, but PHP only recently started supporting it with the launch of PHP 7. The method still “works” in PHP &lt; 7, it just isn’t fast.</p><p>The reason this method is faster than Redis, Memcache, APC, and other PHP caching solutions is the fact that all those solutions must serialize and unserialize objects, generally using PHP’s serialize or json_encode functions. By storing PHP objects in file cache memory across requests, we can avoid serialization completely!</p><p>Here’s how we “set” a value in the cache:</p><pre><strong>function </strong>cache_set($key, $val) {<br>   $val = var_export($val, <strong>true</strong>);<br>   // HHVM fails at __set_state, so just use object cast for now<br>   $val = str_replace(&#39;stdClass::__set_state&#39;, &#39;(object)&#39;, $val);<br>   // Write to temp file first to ensure atomicity<br>   $tmp = &quot;/tmp/$key.&quot; . uniqid(&#39;&#39;, <strong>true</strong>) . &#39;.tmp&#39;;<br>   file_put_contents($tmp, &#39;&lt;?php $val = &#39; . $val . &#39;;&#39;, <em>LOCK_EX</em>);<br>   rename($tmp, &quot;/tmp/$key&quot;);<br>}</pre><p>And here’s how we “get” a value from the cache:</p><pre>function cache_get($key) {<br>    <a href="http://twitter.com/include">@include</a> &quot;/tmp/$key&quot;;<br>    return isset($val) ? $val : false;<br>}</pre><p>Now let’s store a value in both our PHP file cache and in APC to compare:</p><pre>$data = array_fill(0, 1000000, ‘hi’); // your application data here<br>cache_set(&#39;my_key&#39;, $data);<br>apc_store(&#39;my_key&#39;, $data);</pre><p>And see how they perform:</p><pre>// <em>note: make sure you run this on a separate request from cache_set to ensure PHP&#39;s opcache will actually cache the file</em></pre><pre>$t = microtime(true);<br>$data = cache_get(‘my_key’);<br>echo microtime(true) - $t;<br>// 0.00013017654418945</pre><pre>$t = microtime(true);<br>$data = apc_fetch(‘my_key’);<br>echo microtime(true) - $t;<br>// 0.061056137084961</pre><p>We were able to fetch a million-row array of strings in a tenth of a millisecond, ~500 times faster than APC. The 500X number is kind of arbitrary, because larger objects will have larger performance improvements, approaching infinity. To be clear, though, we <em>did</em> see speed improvements of two orders of magnitude in our real production object caching when we implemented this method.</p><p>Keep in mind that PHP file caching should primarily be used for arrays &amp; objects, not strings, since there is no performance benefit for strings. In fact, APC is a tad bit faster when dealing with short strings, due to the slight overhead of calling PHP’s include() function.</p><h4>Production Implementation</h4><p>We use a bit more code in our production application than what is illustrated above. In addition to adding expiration support and a cache_clear function, we also had to implement our own multi-server distributed clearing logic, which data stores like Redis and Memcache handle automatically. Cache keys must also be validated or encoded based on the filesystem to ensure valid filename characters.</p><p>Another production consideration is the PHP opcache configuration (or HHVM .ini configuration). Your opcache.memory_consumption setting needs to be larger than the size of all your code files plus all the data you plan to store in the cache. Your opcache.max_accelerated_files setting needs to be larger than your total number of code files plus the total number of keys you plan to cache. If those settings aren’t high enough, the cache will still work, but its performance may suffer.</p><p>At <a href="https://www.graphiq.com/">Graphiq</a>, we’re building a platform that processes and visualizes knowledge from thousands of distinct datasets and billions of entities. Operating at that scale and beyond forces constant innovation to keep our platform from getting bogged down. By caching our array/object data in PHP files, we’ve mitigated what once was a tricky bottleneck.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcd26e8447ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>