# Qiskit Aer: Pulse simulation of two qubits using a Duffing oscillator model

This notebook shows how to use the Qiskit Aer pulse simulator, which simulates experiments specified as pulse `Schedule` objects at the Hamiltonian level. The simulator solves the Schrodinger equation for a specified Hamiltonian model and pulse `Schedule` in the frame of the drift Hamiltonian.

In particular, in this tutorial we will:
- Construct a model of a two qubit superconducting system.
- Calibrate $\pi$ pulses on each qubit in the simulated system.
- Observe cross-resonance oscillations when driving qubit 1 with target qubit 0.

The Introduction outlines the concepts and flow of this notebook.

## 1. Introduction

The main sections proceed as follows.

### Section 3: Duffing oscillator model

To simulate a physical system, it is necessary to specify a model. In this notebook, we will model superconducting qubits as a collection of *Duffing oscillators*. The model is specified in terms of the following parameters:

-  Each Duffing oscillator is specified by a frequency $\nu$, anharmonicity $\alpha$, and drive strength $r$, which result in the Hamiltonian terms:
\begin{equation}
    2\pi\nu a^\dagger a + \pi \alpha a^\dagger a(a^\dagger a - 1) + 2 \pi r (a + a^\dagger) \times D(t),
\end{equation}
where $D(t)$ is the signal on the drive channel for the qubit, and $a^\dagger$ and $a$ are, respectively, the creation and annihilation operators for the qubit. Note that the drive strength $r$ sets the scaling of the control term, with $D(t)$ assumed to be a complex and unitless number satisfying $|D(t)| \leq 1$.
-  A coupling between a pair of oscillators $(l,k)$ is specified by the coupling strength $J$, resulting in an exchange coupling term:
\begin{equation}
    2 \pi J (a_l a_k^\dagger + a_l^\dagger a_k),
\end{equation}
where the subscript denotes which qubit the operators act on.
- Additionally, for numerical simulation, it is necessary to specify a cutoff dimension; the Duffing oscillator model is *infinite dimensional*, and computer simulation requires restriction of the operators to a finite dimensional subspace.

**In the code:** We will define a model of the above form for two coupled qubits using the helper function `duffing_system_model`.

### Section 4: $\pi$-pulse calibration using Ignis

Once the model is defined, we will calibrate $\pi$-pulses on each qubit. A $\pi$-pulse is defined as a pulse on the drive channel of a qubit that "flips" the qubit; i.e. that takes the ground state to the first excited state, and the first excited state to the ground state.

We will experimentally find a $\pi$-pulse for each qubit using the following procedure:
- A fixed pulse shape is set - in this case it will be a Gaussian pulse.
- A sequence of experiments is run, each consisting of a Gaussian pulse on the qubit, followed by a measurement, with each experiment in the sequence having a subsequently larger amplitude for the Gaussian pulse.
- The measurement data is fit, and the pulse amplitude that completely flips the qubit is found (i.e. the $\pi$-pulse amplitude).

**In the code:** Using Ignis we will construct `Schedule` objects for the above experiments, then fit the data to find the $\pi$-pulse amplitudes.

### Section 5: Cross-resonance oscillations

Once the $\pi$-pulses are calibrated, we will simulate the effects of cross-resonance driving on qubit $1$ with target qubit $0$. This means that we will drive qubit $1$ at the frequency of qubit $0$, with the goal of observing that the trajectory and oscillations of qubit $0$ *depends* on the state of qubit $1$. This phenomenon provides a basis for creating two-qubit *controlled* gates. Note: This section requires the calibration of the $\pi$-pulse in Section 4.

To observe cross-resonance driving, we will use experiments very similar to the $\pi$-pulse calibration case:
- Initially, qubit $1$ is either left in the ground state, or is driven to its first excited state using the $\pi$-pulse found in Section 4.
- A sequence of experiments is run, each consisting of a Gaussian pulse on qubit $1$ driven at the frequency of qubit $0$, followed by a measurement of both qubits, with each experiment of the sequence having a subsequently larger amplitude for the Gaussian pulse.

**In the code:** Functions for defining the experiments and visualizing the data are constructed, including a visualization of the trajectory of the target qubit on the Bloch sphere.

## 2. Imports

This notebook makes use of the following imports.

```python
import numpy as np
from scipy.optimize import curve_fit, root

# visualization tools
import matplotlib.pyplot as plt
from qiskit.visualization.bloch import Bloch
```

Import qiskit libraries for working with `pulse` and calibration:

```python
import qiskit.pulse as pulse
from qiskit.pulse.commands.parametric_pulses import Gaussian, GaussianSquare
from qiskit.compiler import assemble

from qiskit.ignis.characterization.calibrations import rabi_schedules, RabiFitter
```

Imports for qiskit pulse simulator:

```python
# The pulse simulator
from qiskit.providers.aer import PulseSimulator

# function for constructing duffing models
from qiskit.providers.aer.pulse import duffing_system_model
```

## 3. Duffing oscillator system model

An object representing a model for a collection of Duffing oscillators can be constructed using the `duffing_system_model` function. Here we construct a $2$ Duffing oscillator model with cutoff dimension $3$.

```python
# cutoff dimension
dim_oscillators = 3

# frequencies for transmon drift terms, harmonic term and anharmonic term
# Number of oscillators in the model is determined from len(oscillator_freqs)
oscillator_freqs = [5.0e9, 5.2e9]
anharm_freqs = [-0.33e9, -0.33e9]

# drive strengths
drive_strengths = [0.02e9, 0.02e9]

# specify coupling as a dictionary (qubits 0 and 1 are coupled with a coefficient 0.002e9)
coupling_dict = {(0,1): 0.002e9}

# sample duration for pulse instructions
dt = 1e-9

# create the model
two_qubit_model = duffing_system_model(dim_oscillators=dim_oscillators,
                                       oscillator_freqs=oscillator_freqs,
                                       anharm_freqs=anharm_freqs,
                                       drive_strengths=drive_strengths,
                                       coupling_dict=coupling_dict,
                                       dt=dt)
```

The function `duffing_system_model` returns a `PulseSystemModel` object, which is a general object for storing model information required for simulation with the `PulseSimulator`.

## 4 Calibrating $\pi$ pulses on each qubit using Ignis

As described in the introduction, we now calibrate $\pi$ pulses on each qubit in `two_qubit_model`. The experiments in this calibration procedure are known as *Rabi experiments*, and the data we will observe are known as *Rabi oscillations*.

### 4.1 Constructing the schedules

We construct the schedules using the `rabi_schedules` function in Ignis. To do this, we need to supply an `InstructionScheduleMap` containing a measurement schedule.

```python
# list of qubits to be used throughout the notebook
qubits = [0, 1]

# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_amp = 0.025
meas_samples = 1200
meas_sigma = 4
meas_width = 1150
meas_pulse = GaussianSquare(duration=meas_samples, amp=meas_amp,
                            sigma=meas_sigma, width=meas_width)

acq_cmd = pulse.Acquire(duration=meas_samples)
acq_sched = acq_cmd(pulse.AcquireChannel(0), pulse.MemorySlot(0))
acq_sched += acq_cmd(pulse.AcquireChannel(1), pulse.MemorySlot(1))

measure_sched = meas_pulse(pulse.MeasureChannel(0)) | meas_pulse(pulse.MeasureChannel(1)) | acq_sched

inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', qubits, measure_sched)
```

    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:121: DeprecationWarning: Usage of Acquire without specifying a channel is deprecated. For example, Acquire(1200)(AcquireChannel(0)) should be replaced by Acquire(1200, AcquireChannel(0)).
      "Acquire(1200, AcquireChannel(0)).", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:218: DeprecationWarning: Calling Acquire with a channel is deprecated. Instantiate the acquire with a channel instead.
      "a channel instead.", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:218: DeprecationWarning: Calling Acquire with a channel is deprecated. Instantiate the acquire with a channel instead.
      "a channel instead.", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=1200, amp=(0.025+0j), sigma=4, width=1150), MeasureChannel(0))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=1200, amp=(0.025+0j), sigma=4, width=1150), MeasureChannel(1))`.
      DeprecationWarning)

Next, construct the Rabi schedules.

```python
# construct Rabi experiments
drive_amps = np.linspace(0, 0.9, 41)
drive_sigma = 16
drive_duration = 128
drive_channels = [pulse.DriveChannel(qubit) for qubit in qubits]

rabi_experiments, rabi_amps = rabi_schedules(amp_list=drive_amps,
                                             qubits=qubits,
                                             pulse_width=drive_duration,
                                             pulse_sigma=drive_sigma,
                                             drives=drive_channels,
                                             inst_map=inst_map,
                                             meas_map=[[0, 1]])
```

The `Schedule`s in `rabi_schedules` correspond to experiments to generate Rabi oscillations on both qubits in parallel. Each experiment consists of a Gaussian pulse on the qubits of a given magnitude, followed by measurement.

For example:

```python
rabi_experiments[10].draw()
```

### 4.2 Simulate the Rabi experiments

To simulate the Rabi experiments, assemble the `Schedule` list into a qobj. When assembling, pass the `PulseSimulator` as the backend.

Here, we want to use local oscillators with frequencies automatically computed from Duffing model Hamiltonian.

```python
# instantiate the pulse simulator
backend_sim = PulseSimulator()

# compute frequencies from the Hamiltonian
qubit_lo_freq = two_qubit_model.hamiltonian.get_qubit_lo_from_drift()

rabi_qobj = assemble(rabi_experiments,
                     backend=backend_sim,
                     qubit_lo_freq=qubit_lo_freq,
                     meas_level=1,
                     meas_return='avg',
                     shots=512)
```

Run the simulation using the simulator backend.

```python
# run the simulation
rabi_result = backend_sim.run(rabi_qobj, two_qubit_model).result()
```

### 4.3 Fit and plot the data

Next, we use `RabiFitter` in Ignis to fit the data, extract the $\pi$-pulse amplitude, and then plot the data.

```python
rabifit = RabiFitter(rabi_result, rabi_amps, qubits, fit_p0 = [0.5,0.5,0.6,1.5])

plt.figure(figsize=(15, 10))
q_offset = 0
for qubit in qubits:
    ax = plt.subplot(2, 2, qubit + 1)
    rabifit.plot(qubit, ax=ax)
    print('Pi Amp: %f'%rabifit.pi_amplitude(qubit))
plt.show()
```

Plotted is the averaged IQ data for observing each qubit. Observe that here, each qubit oscillates between the 0 and 1 state. The amplitude at which a given qubit reaches the peak of the oscillation is the desired $\pi$-pulse amplitude.

## 5. Oscillations from cross-resonance drive

Next, we simulate the effects of a cross-resonance drive on qubit $1$ with target qubit $0$, observing that the trajectory and oscillations of qubit $0$ *depends* on the state of qubit $1$.

**Note:** This section depends on the $\pi$-pulse calibrations of Section 2.

### 5.1 Cross-resonance `ControlChannel` indices

Driving qubit $1$ at the frequency of qubit $0$ requires use of a pulse `ControlChannel`. The model generating function `duffing_system_model`, automatically sets up `ControlChannels` for performing cross-resonance drives between pairs of coupled qubits. The index of the `ControlChannel` for performing a particular cross-resonance drive is retrievable using the class method `control_channel_index` on the returned `PulseSystemModel`. For example, to get the `ControlChannel` index corresponding to a CR drive on qubit 1 with target 0, call the function `control_channel_index` with the tuple `(1,0)`:

```python
two_qubit_model.control_channel_index((1,0))
```

    1

Hence, to perform a cross-resonance drive on qubit $1$ with target qubit $0$, use `ControlChannel(1)`. This will be made use of when constructing `Schedule` objects in this section.

### 5.2 Functions to generate the experiment list, and analyze the output

First, we define a function `cr_drive_experiments`, which, given the drive and target indices, and the option to either start with the drive qubit in the ground or excited state, returns a list of experiments for observing the oscillations.

```python
# store the pi amplitudes from Section 2 in a list
pi_amps = [rabifit.pi_amplitude(0), rabifit.pi_amplitude(1)]

def cr_drive_experiments(drive_idx,
                         target_idx,
                         flip_drive_qubit = False,
                         cr_drive_amps=np.linspace(0, 0.9, 41),
                         cr_drive_samples=600,
                         cr_drive_sigma=4,
                         pi_drive_samples=128,
                         pi_drive_sigma=16):
    """Generate schedules corresponding to CR drive experiments.

    Args:
        drive_idx (int): label of driven qubit
        target_idx (int): label of target qubit
        flip_drive_qubit (bool): whether or not to start the driven qubit in the ground or excited state
        cr_drive_amps (array): list of drive amplitudes to use
        cr_drive_samples (int): number samples for each CR drive signal
        cr_drive_sigma (float): standard deviation of CR Gaussian pulse
        pi_drive_samples (int): number samples for pi pulse on drive
        pi_drive_sigma (float): standard deviation of Gaussian pi pulse on drive

    Returns:
        list[Schedule]: A list of Schedule objects for each experiment
    """

    # Construct measurement commands to be used for all schedules
    meas_amp = 0.025
    meas_samples = 1200
    meas_sigma = 4
    meas_width = 1150
    meas_pulse = GaussianSquare(duration=meas_samples, amp=meas_amp,
                               sigma=meas_sigma, width=meas_width)

    acq_cmd = pulse.Acquire(duration=meas_samples)
    acq_sched = acq_cmd(pulse.AcquireChannel(0), pulse.MemorySlot(0))
    acq_sched += acq_cmd(pulse.AcquireChannel(1), pulse.MemorySlot(1))

    # create measurement schedule
    measure_sched = meas_pulse(pulse.MeasureChannel(0)) | meas_pulse(pulse.MeasureChannel(1)) | acq_sched

    # Create schedule
    schedules = []
    for ii, cr_drive_amp in enumerate(cr_drive_amps):

        # pulse for flipping drive qubit if desired
        pi_pulse = Gaussian(duration=pi_drive_samples, amp=pi_amps[drive_idx], sigma=pi_drive_sigma)

        # cr drive pulse
        cr_width = cr_drive_samples - 2*cr_drive_sigma*4
        cr_rabi_pulse = GaussianSquare(duration=cr_drive_samples,
                                       amp=cr_drive_amp,
                                       sigma=cr_drive_sigma,
                                       width=cr_width)

        # add commands to schedule
        schedule = pulse.Schedule(name='cr_rabi_exp_amp_%s' % cr_drive_amp)

        # flip drive qubit if desired
        if flip_drive_qubit:
            schedule += pi_pulse(pulse.DriveChannel(drive_idx))

        # do cr drive
        # First, get the ControlChannel index for CR drive from drive to target
        cr_idx = two_qubit_model.control_channel_index((drive_idx, target_idx))
        schedule += cr_rabi_pulse(pulse.ControlChannel(cr_idx))  << schedule.duration

        schedule += measure_sched << schedule.duration

        schedules.append(schedule)
    return schedules
```

Next we create two functions for observing the data:
- `plot_cr_pop_data` - for plotting the oscillations between the ground state and the first excited state
- `plot_bloch_sphere` - for viewing the trajectory of the target qubit on the bloch sphere

```python
def plot_cr_pop_data(drive_idx,
                     target_idx,
                     sim_result,
                     cr_drive_amps=np.linspace(0, 0.9, 41)):
    """Plot the population of each qubit.

    Args:
        drive_idx (int): label of driven qubit
        target_idx (int): label of target qubit
        sim_result (Result): results of simulation
        cr_drive_amps (array): list of drive amplitudes to use for axis labels
    """

    amp_data_Q0 = []
    amp_data_Q1 = []

    for exp_idx in range(len(cr_drive_amps)):
        exp_mem = sim_result.get_memory(exp_idx)
        amp_data_Q0.append(np.abs(exp_mem[0]))
        amp_data_Q1.append(np.abs(exp_mem[1]))

    plt.plot(cr_drive_amps, amp_data_Q0, label='Q0')
    plt.plot(cr_drive_amps, amp_data_Q1, label='Q1')
    plt.legend()
    plt.xlabel('Pulse amplitude, a.u.', fontsize=20)
    plt.ylabel('Signal, a.u.', fontsize=20)
    plt.title('CR (Target Q{0}, driving on Q{1})'.format(target_idx, drive_idx), fontsize=20)
    plt.grid(True)

def bloch_vectors(drive_idx, drive_energy_level, sim_result):
    """Plot the population of each qubit.

    Args:
        drive_idx (int): label of driven qubit
        drive_energy_level (int): energy level of drive qubit at start of CR drive
        sim_result (Result): results of simulation

    Returns:
        list: list of Bloch vectors corresponding to the final state of the target qubit
              for each experiment
    """

    # get the dimension used for simulation
    dim = int(np.sqrt(len(sim_result.get_statevector(0))))

    # get the relevant dressed state indices
    idx0 = 0
    idx1 = 0
    if drive_idx == 0:
        if drive_energy_level == 0:
            idx0, idx1 = 0, dim
        elif drive_energy_level == 1:
            idx0, idx1 = 1, dim + 1
    if drive_idx == 1:
        if drive_energy_level == 0:
            idx0, idx1 = 0, 1
        elif drive_energy_level == 1:
            idx0, idx1 = dim, dim + 1

    # construct Pauli operators for correct dressed manifold
    state0 = np.array([two_qubit_model.hamiltonian._estates[idx0]])
    state1 = np.array([two_qubit_model.hamiltonian._estates[idx1]])

    outer01 = np.transpose(state0)@state1
    outer10 = np.transpose(state1)@state0
    outer00 = np.transpose(state0)@state0
    outer11 = np.transpose(state1)@state1

    X = outer01 + outer10
    Y = -1j*outer01 + 1j*outer10
    Z = outer00 - outer11

    # function for computing a single bloch vector
    bloch_vec = lambda vec: np.real(np.array([np.conj(vec)@X@vec, np.conj(vec)@Y@vec, np.conj(vec)@Z@vec]))

    return [bloch_vec(sim_result.get_statevector(idx)) for idx in range(len(sim_result.results))]

def plot_bloch_sphere(bloch_vectors):
    """Given a list of Bloch vectors, plot them on the Bloch sphere

    Args:
        bloch_vectors (list): list of bloch vectors
    """
    sphere = Bloch()
    sphere.add_points(np.transpose(bloch_vectors))
    sphere.show()
```

### 5.3 Drive qubit 1 to observe CR oscillations on qubit 0

#### Qubit 1 in the ground state

First, we drive with both qubit 0 and qubit 1 in the ground state.

```python
# construct experiments
drive_idx = 1
target_idx = 0
flip_drive = False
experiments = cr_drive_experiments(drive_idx, target_idx, flip_drive)

# compute frequencies from the Hamiltonian
qubit_lo_freq = two_qubit_model.hamiltonian.get_qubit_lo_from_drift()

# assemble the qobj
cr_rabi_qobj = assemble(experiments,
                        backend=backend_sim,
                        qubit_lo_freq=qubit_lo_freq,
                        meas_level=1,
                        meas_return='avg',
                        shots=512)
```

    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:121: DeprecationWarning: Usage of Acquire without specifying a channel is deprecated. For example, Acquire(1200)(AcquireChannel(0)) should be replaced by Acquire(1200, AcquireChannel(0)).
      "Acquire(1200, AcquireChannel(0)).", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:218: DeprecationWarning: Calling Acquire with a channel is deprecated. Instantiate the acquire with a channel instead.
      "a channel instead.", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:218: DeprecationWarning: Calling Acquire with a channel is deprecated. Instantiate the acquire with a channel instead.
      "a channel instead.", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=1200, amp=(0.025+0j), sigma=4, width=1150), MeasureChannel(0))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=1200, amp=(0.025+0j), sigma=4, width=1150), MeasureChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=0j, sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.0225+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.045+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.0675+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.09+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.11249999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.135+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.1575+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.18+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.20249999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.22499999999999998+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.2475+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.27+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.2925+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.315+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.33749999999999997+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.36+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.3825+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.40499999999999997+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.4275+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.44999999999999996+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.4725+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.495+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.5175+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.54+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.5625+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.585+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.6074999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.63+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.6525+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.6749999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.6975+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.72+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.7424999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.765+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.7875+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.8099999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.8325+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.855+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.8775+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.9+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)

Run the simulation:

```python
sim_result = backend_sim.run(cr_rabi_qobj, two_qubit_model).result()

plot_cr_pop_data(drive_idx, target_idx, sim_result)
```

Observe that qubit 1 remains in the ground state, while excitations are driven in qubit 0.

We may also observe the trajectory of qubit 0 on the Bloch sphere:

```python
bloch_vecs = bloch_vectors(drive_idx, int(flip_drive), sim_result)
plot_bloch_sphere(bloch_vecs)
```

#### Qubit 1 in the first excited state

Next, we again perform a CR drive qubit 1 with qubit 0 as the target, but now we start each experiment by flipping qubit 1 into the first excited state.

```python
# construct experiments, now with flip_drive == True
drive_idx = 1
target_idx = 0
flip_drive = True
experiments = cr_drive_experiments(drive_idx, target_idx, flip_drive)

# compute frequencies from the Hamiltonian
qubit_lo_freq = two_qubit_model.hamiltonian.get_qubit_lo_from_drift()

# assemble the qobj
cr_rabi_qobj = assemble(experiments,
                        backend=backend_sim,
                        qubit_lo_freq=qubit_lo_freq,
                        meas_level=1,
                        meas_return='avg',
                        shots=512)
```

    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:121: DeprecationWarning: Usage of Acquire without specifying a channel is deprecated. For example, Acquire(1200)(AcquireChannel(0)) should be replaced by Acquire(1200, AcquireChannel(0)).
      "Acquire(1200, AcquireChannel(0)).", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:218: DeprecationWarning: Calling Acquire with a channel is deprecated. Instantiate the acquire with a channel instead.
      "a channel instead.", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/instructions/acquire.py:218: DeprecationWarning: Calling Acquire with a channel is deprecated. Instantiate the acquire with a channel instead.
      "a channel instead.", DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=1200, amp=(0.025+0j), sigma=4, width=1150), MeasureChannel(0))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=1200, amp=(0.025+0j), sigma=4, width=1150), MeasureChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=0j, sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.0225+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.045+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.0675+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.09+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.11249999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.135+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.1575+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.18+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.20249999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.22499999999999998+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.2475+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.27+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.2925+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.315+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.33749999999999997+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.36+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.3825+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.40499999999999997+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.4275+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.44999999999999996+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.4725+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.495+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.5175+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.54+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.5625+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.585+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.6074999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.63+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.6525+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.6749999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.6975+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.72+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.7424999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.765+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.7875+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.8099999999999999+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.8325+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.855+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.8775+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `Gaussian` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(Gaussian(duration=128, amp=(0.31081040780699565+0j), sigma=16), DriveChannel(1))`.
      DeprecationWarning)
    /opt/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/pulse/pulse_lib/pulse.py:49: DeprecationWarning: Calling `GaussianSquare` with a channel is deprecated. Instantiate the new `Play` instruction directly with a pulse and a channel. In this case, please use: `Play(GaussianSquare(duration=600, amp=(0.9+0j), sigma=4, width=568), ControlChannel(1))`.
      DeprecationWarning)

```python
sim_result = backend_sim.run(cr_rabi_qobj, two_qubit_model).result()

plot_cr_pop_data(drive_idx, target_idx, sim_result)
```

Observe that now qubit 1 is in the excited state, while oscillations are again being driven on qubit 0, now at a different rate as before.

Again, observe the trajectory of qubit 0 on the Bloch sphere:

```python
bloch_vecs = bloch_vectors(drive_idx, int(flip_drive), sim_result)
plot_bloch_sphere(bloch_vecs)
```

Here we see that qubit 0 takes a *different* trajectory on the Bloch sphere when qubit 1 is in the excited state. This is what enables controlled operations between two qubits.

```python
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
```

Version Information

Qiskit Software	Version

Qiskit	0.19.6

Terra	0.14.2

Aer	0.5.2

Ignis	0.3.3

Aqua	0.7.3

IBM Q Provider	0.7.2

System information

Python	3.7.7 (default, May  6 2020, 04:59:01)
[Clang 4.0.1 (tags/RELEASE_401/final)]

OS	Darwin

CPUs	4

Memory (Gb)	16.0

Mon Jul 13 15:35:23 2020 EDT

This code is a part of Qiskit

© Copyright IBM 2017, 2020.

This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
 of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
Any modifications or derivative works of this code must retain this
copyright notice, and modified files need to carry a notice indicating
that they have been altered from the originals.

```python

```


Prepared by: Manjula Mishra

# Learning Goals

By the end of this class students will:

1. know what is logsitic regression.

2. know why logistic regression is still so poplular.

3. understand the usecases/applications of logistic regression.

4. be able to implement logistic regression in Python from scratch using SKLearn and Statsmodels.

5. know its limitations.

## Keywords

Supervised learning

Classification

Sigmoid function

Gradient Descent

Loss function/Cost function

# Sections:

This notebook is divided into 5 different sections which covers the main idea behind the logistic regression.

1. What is logistic regression?

2. Why is logistic regression still so poplular?

3. Applications of logistic regression

4. Implement logistic regression in Python from scratch

5. Limitations of logistic regression

## 1. What is logistic regression?

Logistic regression is a supervised learning method to model the relationship between a categorical outcome (dependent variable) and one or more independent variable. The independent variables or explanatory variables can be discrete and/or continuous.

The logistic function was invented in the 19TH century for the description of growth of human populations and the course of autocatalytic chemical reactions.

Logistic regression is not a typical linear regression model. It belongs to the family of GLMs. Some of the things to notice about the logistic regression:

1. Logistic regression does not assume a linear relationship between the dependent and independent variables. It's linear in parameters.

2. The dependent variable must be categorical.

3. the independent variables need not be normally distributed, nor linearly related, nor of equal variance within each group, and lastly, the categories (groups) must be mutually exclusive and exhaustive.

4. The logistic regression has the power to accommodate both categorical and continuous independent variables.

5. Although the power of the analysis is increased if the independent variables are normally distributed and do have a linear relationship with the dependent variable.

## 2. Why is logistic regression still so poplular?

* Logistic regression is easier to implement, interpret, and very efficient to train.

* It makes no assumptions about distributions of classes in feature space.

* It can easily extend to multiple classes(multinomial regression) and a natural probabilistic view of class predictions.

* It not only provides a measure of how appropriate a predictor(coefficient size)is, but also its direction of association (positive or negative).

* It is very fast at classifying unknown records.

* Good accuracy for many simple data sets and it performs well when the dataset is linearly separable.

* It can interpret model coefficients as indicators of feature importance.

* Logistic regression is less inclined to over-fitting but it can overfit in high dimensional datasets.One may consider Regularization (L1 and L2) techniques to avoid over-fitting in these scenarios.

## 3. Applications of logistic regression

The logistic regression has many applications in wide variety of fields. The types of problems it deals with are of the following nature:

Binary (Pass/Fail)

Multi (Cats, Dogs, Sheep)

Ordinal (Low, Medium, High)

Some of the usecases in different business settings are:

**Fraud detection**: Detection of credit card frauds or banking fraud is the objective of this use case.

**Email spam or ham**: Classifying the email as spam or ham and putting it in either Inbox or Spam folder is the objective of this use case.

**Sentiment Analysis**: Analyzing the sentiment using the review or tweets is the objective of this use case. Most of the brands and companies use this to increase customer experience.

**Image segmentation, recognition and classification**: The objective of all these use cases is to identify the object in the image and classify it.

**Object detection**: This use case is to detect objects and classify them not in the image but the video.
Handwriting recognition: Recognizing the letters written is the objective of this use case.

**Disease (diabetes, cancer etc.) prediction**: Predicting whether the patient has disease or not is the objective of this use case.

## Quiz

**1. True-False: Is Logistic regression a supervised machine learning algorithm?**

A. TRUE

B. FALSE

**2. True-False: Is Logistic regression mainly used for Regression?**

A. TRUE

B. FALSE

**3.Logistic regression assumes a:**

A. Linear relationship between continuous predictor variables and the outcome variable.

B. Linear relationship between continuous predictor variables and the logit of the outcome variable.

C. Linear relationship between continuous predictor variables.

D. Linear relationship between observations.

**4. True-False: Is it possible to apply a logistic regression algorithm on a 3-class Classification problem?**

A. TRUE

B. FALSE

**5. Logistic regression is used when you want to:**

A. Predict a dichotomous variable from continuous or dichotomous variables.

B. Predict a continuous variable from dichotomous variables.

C. Predict any categorical variable from several other categorical variables.

D. Predict a continuous variable from dichotomous or continuous variables.

**6. In binary logistic regression:**

A. The dependent variable is continuous.

B. The dependent variable is divided into two equal subcategories.

C. The dependent variable consists of two categories.

D. There is no dependent variable.

# 4. Implement logistic regression in Python from scratch

Here, we will be implementing a basic logsitic regression model to improve our understanding of how it works.

To acomplish that, we will be using a famous dataset called 'iris'. The description and the data can be found here: https://archive.ics.uci.edu/ml/datasets/iris. Basically, the dataset contains information (features) about three different types of flowers. We will be focusing on accuratly classifying the correct flowers.

We wil be taking the first two features into account and two non-linearly flowers are classified as one, so leaving them as binary class.

## Loading the data and importing the libraries

```python
# let's import the important libraries we will need
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
from sklearn import datasets
```

Although we will directly be loading a preprocessed iris data from sklearn, I wanted to you to know that the data can also be loaded like this to have a first look at the data

```python
url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"
```

```python
df = pd.read_csv(url)
df.head()
```

      sepal_length
      sepal_width
      petal_length
      petal_width
      species

      0
      5.1
      3.5
      1.4
      0.2
      setosa

      1
      4.9
      3.0
      1.4
      0.2
      setosa

      2
      4.7
      3.2
      1.3
      0.2
      setosa

      3
      4.6
      3.1
      1.5
      0.2
      setosa

      4
      5.0
      3.6
      1.4
      0.2
      setosa

Let's load the data from sklearn and encode the target variable 0 and 1

```python
from sklearn.datasets import load_iris
data = load_iris()

# Load digits dataset
iris = sklearn.datasets.load_iris()

# Create feature matrix
X = iris.data[:, :2]

# Create target vector
y = (iris.target != 0) * 1 # so that 2 converts into 1

y
# y1 = iris.target #this will have category 2 as well that's why we use the above method
# y1
```

    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

```python
print(iris.feature_names) #column names
```

    ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']

```python
print(iris.target_names) # target varieties
```

    ['setosa' 'versicolor' 'virginica']

We will plot the 0 and 1 classes to see how it looks

```python
plt.figure(figsize=(10, 6))
plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='b', label='0')
plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='r', label='1')
plt.legend();
```

## Algorithm

To iterate it once again, given a set of inputs X, our goal is to correctly identify the class (0 or 1).As we know, we will use a logistic regression model to predict the probability for each flower to know which catergory it belongs to.

### Hypothesis

Any function takes inputs and returns the coresponding outputs. Logistic regression uses a function that generates probabilities an gives outputs between 0 and 1 for all values of X. The function that we will to achieve that is called Sigmoid function.

```python
# Import matplotlib, numpy and math
import matplotlib.pyplot as plt
import numpy as np
import math

plt.figure(figsize=(10, 6))
x = np.linspace(-10, 10, 100)
z = 1/(1 + np.exp(-x))

plt.plot(x, z)
plt.xlabel("x")
plt.ylabel("Sigmoid(X)")

plt.show()
```

### The Sigmoid function:

\begin{equation}
\begin{array}{l}
h_{\theta}(x)=g\left(\theta^{T} x\right) \\
z=\theta^{T} x \\
g(z)=\frac{1}{1+e^{-z}}
\end{array}
\end{equation}

### Explanation

The binary dependent variable has the values of 0 and 1 and the predicted value (probability) must be bounded to fall within the same range. To define a relationship bounded by 0 and 1, the logistic regression uses the logistic curve to represent the relationship between the independent and dependent variable. At very low levels of the independent variable, the probability approaches 0, but never reaches 0. Likewise, if the independent variable increases, the predicted values increase up the curve and approach 1 but never equal to 1.

The logistic transformation ensures that estimated values do not fall outside the range of 0 and 1. This is achieved in two steps, firstly the probability is re-stated as odds which is defined as the ratio of the probability of the event occurring to the probability of it not occurring. For example, if a horse has a probability of 0.8 of winning a race, the odds of it winning are 0.8/(1 − 0.8) = 4:1. To constrain the predicted values to within 0 and 1, the odds value can be converted back into a probability; thus,

$$
\text { Probability (event) }=\frac{\text { odds(event) }}{1+\text { odds(event) }}
$$

It can therefore be shown that the corresponding probability is 4/(1 + 4) = 0.8. Also, to keep the odds values form going below 0, which is the lower limit (there is no upper limit), the logit value which is calculated by taking the logarithm of the odds, must be computed. Odds less than 1 have a negative logit value, odds ratio greater than 1.0 have positive logit values and the odds ratio of 1.0 (corresponding to a probability of 0.5) have a logit value of 0.

Let's create a function in Python:

```python
# sigmoin function
def sigmoid(z):
    return 1 / (1 + np.exp(-z))

theta = np.zeros(X.shape[1])
z = np.dot(X, theta)
h = sigmoid(z)
```

### Loss Function

Functions (rememeber linear regression) have weights also called parameters what we are represnting by theta in our case. The goal is to find the best value for them that can make most accurate predcitions.

We start by picking random values. Now we need a way to measure how well the algorithm performs using the random weights that we chose. We compute this by the following loss funtion:

$$
\begin{array}{l}
h=g(X \theta) \\
J(\theta)=\frac{1}{m} \cdot\left(-y^{T} \log (h)-(1-y)^{T} \log (1-h)\right)
\end{array}
$$

```python
# Let' code our loss fucntion

def loss(h, y):
    return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()
```

### Gradient Descent

Now that we have our loss function, our goal is to minimize it by increasing/decreasing teh weights i.e. fititng them. One obvious questions is how do we know which weights should be increased or decreased or how big what parameters should be bigger or smaller?

To achieve this, we calculate the partial derivatives of the loss function with respect to each weight. It will tell us how loss changes if we modify the parameters.

$$
\frac{\delta J(\theta)}{\delta \theta_{j}}=\frac{1}{m} X^{T}(g(X \theta)-y)
$$

```python
gradient = np.dot(X.T, (h - y)) / y.shape[0]
```

To update the weights, we subtract to them the derivative times the learning rate. And we do taht several times until we reach the optimal solution.

```python
lr = 0.01
theta -= lr * gradient
```

### predcitions

To make the predcitions, let's set our threshold (which can change depending on the business prbolem) to 0.5. If the predicted probability is >= 0.5 then it's considered class 1 vs < 0.5 belong to 0.

```python
def predict_probs(X, theta):
    return sigmoid(np.dot(X, theta))

def predict(X, theta, threshold=0.5):
    return predict_probs(X, theta) >= threshold
```

# Putting the code together

Now that we have already learned Logistic regression step by step, it makes sense to put it all together in one single code block. It is important for reproducibility reasons.

Here, we are creating a class because all the other functions belong to the same class. It's a neater way to consolidate your code.

```python
 # create a class
class LogisticRegression:
    def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False):
        self.lr = lr
        self.num_iter = num_iter
        self.fit_intercept = fit_intercept
        self.verbose = verbose

    # add intercept or the bias term
    def __add_intercept(self, X):
        intercept = np.ones((X.shape[0], 1))
        return np.concatenate((intercept, X), axis=1)

    # the sigmoid function that predcits output in terms of probabilites
    def __sigmoid(self, z):
        return 1 / (1 + np.exp(-z))

    #the loss function
    def __loss(self, h, y):
        return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()

    # fitting the model
    def fit(self, X, y):
        if self.fit_intercept:
            X = self.__add_intercept(X)

        # weights initialization
        self.theta = np.zeros(X.shape[1])

        for i in range(self.num_iter):
            z = np.dot(X, self.theta)
            h = self.__sigmoid(z)
            gradient = np.dot(X.T, (h - y)) / y.size
            self.theta -= self.lr * gradient

            z = np.dot(X, self.theta)
            h = self.__sigmoid(z)
            loss = self.__loss(h, y)

            if(self.verbose ==True and i % 10000 == 0):
                print(f'loss: {loss} \t')

    # predciting the probablities for instances
    def predict_prob(self, X):
        if self.fit_intercept:
            X = self.__add_intercept(X)

        return self.__sigmoid(np.dot(X, self.theta))

    # output the predcited probablities
    def predict(self, X):
        return self.predict_prob(X).round()
```

### Evaluation

```python
model = LogisticRegression(lr=0.1, num_iter=300000)
%time model.fit(X, y)
```

    CPU times: user 10.6 s, sys: 31.2 ms, total: 10.6 s
    Wall time: 10.6 s

```python
preds = model.predict(X)

# accuracy
(preds == y).mean()
1.0
```

    1.0

### Resulting Weights

```python
model.theta
```

    array([-25.89066442,  12.523156  , -13.40150447])

```python
plt.figure(figsize=(10, 6))
plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='b', label='0')
plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='r', label='1')
plt.legend()
x1_min, x1_max = X[:,0].min(), X[:,0].max(),
x2_min, x2_max = X[:,1].min(), X[:,1].max(),
xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
grid = np.c_[xx1.ravel(), xx2.ravel()]
probs = model.predict_prob(grid).reshape(xx1.shape)
plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors='black');
```

## Logistic Regression Using SKLearn

## Import the relevant library

```python
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
```

```python
model = LogisticRegression(C=1e20)
```

```python
from sklearn.datasets import load_iris
data = load_iris()
iris = sklearn.datasets.load_iris()
X = iris.data[:, :2]
y = (iris.target != 0) * 1

```

```python
model.fit(X, y)
```

    LogisticRegression(C=1e+20)

```python
model.score(X,y)
```

    1.0

```python
preds = model.predict(X)
# (preds == y).mean()
```

    1.0

```python
print(f'Train Accuracy: {accuracy_score(y, preds)}')

```

    Train Accuracy: 1.0

```python
model.intercept_, model.coef_
```

    (array([-276.67727715]), array([[ 134.80324426, -147.37951668]]))

# Logistic Regression using Statsmodel

```python
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
```

```python
# This is like using np.ones to add a vector of ones
X = sm.add_constant(X)

#obust standard errors essentially correct heteroskedasticity in our data
#cov_type = "HC3" is to compute robust standard error
model = sm.Logit(y, X).fit()
predictions = model.predict(X)

print_model = model.summary()
print(print_model)
```

    Warning: Maximum number of iterations has been exceeded.
             Current function value: 0.000000
             Iterations: 35
                               Logit Regression Results
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                  150
    Model:                          Logit   Df Residuals:                      147
    Method:                           MLE   Df Model:                            2
    Date:                Fri, 23 Oct 2020   Pseudo R-squ.:                   1.000
    Time:                        13:27:10   Log-Likelihood:            -7.5605e-08
    converged:                      False   LL-Null:                       -95.477
    Covariance Type:            nonrobust   LLR p-value:                 3.426e-42
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const       -436.7700   5.43e+05     -0.001      0.999   -1.06e+06    1.06e+06
    x1           166.7834   2.13e+05      0.001      0.999   -4.17e+05    4.17e+05
    x2          -143.5493   1.89e+05     -0.001      0.999   -3.71e+05    3.71e+05
    ==============================================================================

    Complete Separation: The results show that there iscomplete separation.
    In this case the Maximum Likelihood Estimator does not exist and the parameters
    are not identified.

    /Users/manjulamishra/Library/Python/3.7/lib/python/site-packages/statsmodels/base/model.py:568: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
      "Check mle_retvals", ConvergenceWarning)

# Your Turn

1. Load the data from this url

2. Take three numerical features to predict whether a passanger survived or not by implementing Logistic regression in sklearn and Statsmodel.

3. Choose X and y.

4. Run the model and make predictions.

5. Explain your results

6. Give at least two examples of real world problems where you can use logistic regression.

### part 1: Load the data

```python
#Train and test datasets

url_train = "https://raw.githubusercontent.com/agconti/kaggle-titanic/master/data/train.csv"
url_test = "https://raw.githubusercontent.com/agconti/kaggle-titanic/master/data/test.csv"
```

```python
# Be mindful of missing values, you might want to drop them
```

```python
# check the first few rows of the dataframes
```

### part 2: Take three numerical feature

```python
# choose three numerical variables to train the model
```

### part 3. Choose X and y

```python
# X matrix and y
```

### part 4.  Run the model and make predictions

```python
# run the model
```

```python
# make the predictions
```

### part 5. Interpret your results

```python
# How would you interpret the coefficents?

```

```python
# which feature are negatively related to Y?
```

```python
# which feature are positively related to Y?
```

### 6. Give at least two examples of real world problems where you can use logistic regression.

```python
# write down the examples where you would use logistic regression to solve the problem.
```

## 5. Limitations of logistic regression

* Overfitting: If the number of observations is lesser than the number of features, Logistic Regression should not be used, otherwise, it may lead to overfitting.

* The major limitation of Logistic Regression is the assumption of linearity between the dependent variable and the independent variables.

* It can only be used to predict discrete functions. Hence, the dependent variable of Logistic Regression is bound to the discrete number set.

* Non-linear problems can’t be solved with logistic regression because it has a linear decision surface. Linearly separable data is rarely found in real-world scenarios.

* Logistic Regression requires average or no multicollinearity between independent variables.

* It is tough to obtain complex relationships using logistic regression. More powerful and compact algorithms such as Neural Networks can easily outperform this algorithm.

* In Linear Regression independent and dependent variables are related linearly. But Logistic Regression needs that independent variables are linearly related to the log odds (log(p/(1-p)).

# Some questions to think about!

* What is overfiting? How can we solve this problem?

* What does intercept/constant term represent?

* How would you interpret coefficients?

* What if the classes are imbalanced ( the bianry classes are not equally reprenseted)?

* What acurancy metric we we use in classification problems?

* How can we use logstic regression for multiclass problems?

## References

https://en.wikipedia.org/wiki/Sigmoid_function

https://www.scirp.org/journal/paperinformation.aspx?paperid=95655

https://ml-cheatsheet.readthedocs.io/en/latest/logistic_regression.htm

https://www.quora.com/What-are-applications-of-linear-and-logistic-regression

https://papers.tinbergen.nl/02119.pdf

https://online.stat.psu.edu/stat504/node/149/.

http://www.stat.cmu.edu/~ryantibs/advmethods/notes/glm.pdf

https://www.geeksforgeeks.org/advantages-and-disadvantages-of-logistic-regression/

############################################ The End ########################################################