Book Image

Python Machine Learning Cookbook

By : Prateek Joshi, Vahid Mirjalili
Book Image

Python Machine Learning Cookbook

By: Prateek Joshi, Vahid Mirjalili

Overview of this book

Machine learning is becoming increasingly pervasive in the modern data-driven world. It is used extensively across many fields such as search engines, robotics, self-driving cars, and more. With this book, you will learn how to perform various machine learning tasks in different environments. We’ll start by exploring a range of real-life scenarios where machine learning can be used, and look at various building blocks. Throughout the book, you’ll use a wide variety of machine learning algorithms to solve real-world problems and use Python to implement these algorithms. You’ll discover how to deal with various types of data and explore the differences between machine learning paradigms such as supervised and unsupervised learning. We also cover a range of regression techniques, classification algorithms, predictive modeling, data visualization techniques, recommendation engines, and more with the help of real-world examples.
Table of Contents (19 chapters)
Python Machine Learning Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Synthesizing music


Now that we know how to generate audio, let's use this principle to synthesize some music. You can check out this link, http://www.phy.mtu.edu/~suits/notefreqs.html. This link lists various notes, such as A, G, D, and so on, along with their corresponding frequencies. We will use this to generate some simple music.

How to do it…

  1. Create a new Python file, and import the following packages:

    import json
    import numpy as np
    from scipy.io.wavfile import write
    import matplotlib.pyplot as plt
  2. Define a function to synthesize a tone, based on input parameters:

    # Synthesize tone
    def synthesizer(freq, duration, amp=1.0, sampling_freq=44100):
  3. Build the time axis values:

        # Build the time axis
        t = np.linspace(0, duration, duration * sampling_freq)
  4. Construct the audio sample using the input arguments, such as amplitude and frequency:

        # Construct the audio signal
        audio = amp * np.sin(2 * np.pi * freq * t)
    
        return audio.astype(np.int16) 
  5. Let's define the main function. You have...