Sunday, December 17, 2017

Quantum Programming - Hello World

Hey There,

A sample "hello world" program for quantum programming.
   

operation Teleport(msg : Qubit, there : Qubit) : () {
        body {
            using (register = Qubit[1]) {
                // Ask for an auxillary qubit that we can use to prepare
                // for teleportation.
                let here = register[0];
           
                // Create some entanglement that we can use to send our message.
                H(here);
                CNOT(here, there);
           
                // Move our message into the entangled pair.
                CNOT(msg, here);
                H(msg);

                // Measure out the entanglement.
                if (M(msg) == One)  { Z(there); }
                if (M(here) == One) { X(there); }

                // Reset our "here" qubit before releasing it.
                Reset(here);
            }
        }
}

operation TeleportClassicalMessage(message : Bool) : Bool {
        body {
            mutable measurement = false;

            using (register = Qubit[2]) {
                // Ask for some qubits that we can use to teleport.
                let msg = register[0];
                let there = register[1];
               
                // Encode the message we want to send.
                if (message) { X(msg); }
           
                // Use the operation we defined above.
                Teleport(msg, there);

                // Check what message was sent.
                if (M(there) == One) { set measurement = true; }

                // Reset all of the qubits that we used before releasing
                // them.
                ResetAll(register);
            }

            return measurement;
        }
    }

Monday, October 23, 2017

Setting up AWS - VPC Instance, Subnet, Security Group

Welcome,

You came here because you want to automate your AWS VPC/VPN setup.
Please find the below code snippet for your reference, make sure you have puppet installed.

Below code should help you with:
1. Setting up VPS in AWS
2. Setting up VPN Gateway
3. Setting up Subnet
4. Setting up Security Group
5. Setting up Instance
6. Setting up load balancer

#Setting up VPC using Puppet:
ec2_vpc { 'name-of-vpc':
  ensure     => present,
  region     => 'us-east-1',
  cidr_block => '10.0.0.0/24',
  tags       => {
    tag_name => 'value',
  },
}


#setup VPN Gateway:

ec2_vpc_vpn_gateway { 'sample2-vgw':
  ensure => present,
  region => 'us-east-1',
  vpc    => 'sample2-vpc',
  type   => 'ipsec.1',
}


#setup customer gateway:

ec2_vpc_customer_gateway { 'sample2-cgw':
  ensure     => present,
  region     => 'us-east-1',
  ip_address => '177.255.196.143',
  bgp_asn    => 65000,
  type       => 'ipsec.1',
}


#Setup VPC VPN to connect:

ec2_vpc_vpn { 'sample2-vpn':
  ensure           => present,
  region           => 'us-east-1',
  vpn_gateway      => 'sample2-vgw',
  customer_gateway => 'sample2-cgw',
  type             => 'ipsec.1',
  routes           => ['0.0.0.0/0'],
  static_routes    => true,
}


#Setup a subnet:
ec2_vpc_subnet { 'name-of-subnet':
  ensure                  => present,
  region                  => 'us-east-1',
  cidr_block              => '10.0.0.0/24',
  availability_zone       => 'us-east-1a',
  map_public_ip_on_launch => true,
  vpc                     => 'name-of-vpc,
  tags                    => {
    tag_name => 'value',
  },
}

#Setup a security group:
ec2_securitygroup { 'name-of-security-group':
  ensure      => present,
  region      => 'us-east-1',
  vpc         => 'name-of-vpc',
  description => 'a description of the group',
  ingress     => [{
    protocol  => 'tcp',
    port      => 22,
    cidr      => '0.0.0.0/0',
  }],
  tags        => {
    tag_name  => 'value',
  },
}


#Setup an Instance:
ec2_instance { 'name-of-instance':
  ensure            => running,
  region            => 'us-east-1',
  availability_zone => 'us-east-1a',
  image_id          => 'ami-123456', # you need to select your own AMI
  instance_type     => 't2.micro',
  key_name          => 'name-of-existing-key',
  subnet            => 'name-of-subnet',
  security_groups   => ['name-of-security-group'],
  tags              => {
    tag_name => 'value',
  },
}

#Setup Load Balancer:
elb_loadbalancer { 'name-of-load-balancer':
  ensure                  => present,
  region                  => 'us-east-1',
  availability_zones      => ['us-east-1a', 'us-east-1b'],
  instances               => ['name-of-instance', 'another-instance'],
  security_groups         => ['name-of-security-group'],
  listeners               => [
    {
      protocol              => 'HTTP',
      load_balancer_port    => 80,
      instance_protocol     => 'HTTP',
      instance_port         => 80,
    },{
      protocol              => 'HTTPS',
      load_balancer_port    => 443,
      instance_protocol     => 'HTTPS',
      instance_port         => 8080,
      ssl_certificate_id    => 'arn:aws:iam::123456789000:server-certificate/yourcert.com',
      policies              =>  [
        {
          'policy_type'       => 'SSLNegotiationPolicyType',
          'policy_attributes' => {
            'Protocol-TLSv1.1' => false,
            'Protocol-TLSv1.2' => true,
          }
        }
      ]
    }
  ],
  health_check            => {
    'healthy_threshold'   => '10',
    'interval'            => '30',
    'target'              => 'HTTP:80/health_check',
    'timeout'             => '5',
    'unhealthy_threshold' => '2'
  },
  tags                    => {
    tag_name              => 'value',
  },
}


Let me know if you have any questions around. Thanks!

Friday, August 4, 2017

K-Mean Clustering vs Hierarchal Clustering [Machine Learning]

Straight Forward:

K Mean Clustering:


  1. In K-Mean clustering we tel machine about how much cluster we want to have.
  2. We start with defining with random cluster center and find new cluster center, continuing this same process we'll reach to a stage where our "new cluster centre" and "current cluster centre" will be same. This mean our algorithm is optimise and it is the cluster centre.  


Hierarchal Clustering:


  1. In this clustering algorithm of Machine learning we feed data to machine and let machine decide how many cluster it want to group that data.
  2. We start with considering very data point as cluster centre and take mean of all nearby data points (depending upon radius you have selected). This process will continue until we optimise our algorithm (using mean shift algorithm) and at the point where we found our convergence is out cluster center.  

Tuesday, July 25, 2017

Algorithm KNN = ScikitLearn vs Actual

By Scikit Learn:

import numpy as np
from sklearn import preprocessing, cross_validation, neighbors
import pandas as pd

df = pd.read_csv('breast-cancer-wisconsin.data.txt')
df.replace('?',-99999, inplace=True)
df.drop(['id'], 1, inplace=True)

X = np.array(df.drop(['class'], 1))
y = np.array(df['class'])

X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)

clf = neighbors.KNeighborsClassifier()
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)

print(accuracy)


Build your own model:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import warnings
from collections import Counter
#dont forget this
import pandas as pd
import random
style.use('fivethirtyeight')

def k_nearest_neighbors(data, predict, k=3):
    if len(data) >= k:
        warnings.warn('K is set to a value less than total voting groups!')
    distances = []
    for group in data:
        for features in data[group]:
            euclidean_distance = np.linalg.norm(np.array(features)-np.array(predict))
            distances.append([euclidean_distance,group])
    votes = [i[1] for i in sorted(distances)[:k]]
    vote_result = Counter(votes).most_common(1)[0][0]
    return vote_result

df = pd.read_csv('breast-cancer-wisconsin.data.txt')
df.replace('?',-99999, inplace=True)
df.drop(['id'], 1, inplace=True)
full_data = df.astype(float).values.tolist()

random.shuffle(full_data)

test_size = 0.2
train_set = {2:[], 4:[]}
test_set = {2:[], 4:[]}
train_data = full_data[:-int(test_size*len(full_data))]
test_data = full_data[-int(test_size*len(full_data)):]

for i in train_data:
    train_set[i[-1]].append(i[:-1])

for i in test_data:
    test_set[i[-1]].append(i[:-1])

correct = 0
total = 0

for group in test_set:
    for data in test_set[group]:
        vote = k_nearest_neighbors(train_set, data, k=5)
        if group == vote:
            correct += 1
        total += 1
print('Accuracy:', correct/total)

Point to be know before you consider:
1. Whats your data volume (should not be in TB)
2. What should be value of "K" (depending upon your requirement, having high K value doesn't mean you will get better accuracy, in-fact opposite is what I observed)
3. Can you multithread your algorithm ? (Scikit KNN algorithm is already multithreaded (n_jobs = -1))
4. Difference between Accuracy and Confidence
5. Do you need to define Radius ?