<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 09:50:39 2020

@author: Vaishnavi
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataset = pd.read_csv('Social_Network_Ads.csv')

X = dataset.iloc[:, [2,3]].values
y = dataset.iloc[:, 4].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state=0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators=10, criterion="entropy")
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

from sklearn import metrics
cm = metrics.confusion_matrix(y_test, y_pred)
ac = metrics.accuracy_score(y_test, y_pred)
pr = metrics.precision_score(y_test, y_pred)


from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start=X_set[:, 0].min()-1, stop=X_set[:,0].max()+1, step=0.001), 
                     np.arange(start=X_set[:, 1].min()-1, stop=X_set[:,1].max()+1, step=0.001))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha=0.75, cmap = ListedColormap(("red", "blue")))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())

for i,j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set==j,0], X_set[y_set==j,1], c=ListedColormap(("black","white"))(i), label=j)
    
plt.title('Random Forest(Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()


<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Feb  7 21:21:08 2020

@author: Vaish
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

dataset = pd.read_csv("Position_Salaries.csv")

X = dataset.iloc[:,1:2].values
y = dataset.iloc[:, 2].values

#Linear Regression
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X,y)

#Polynomial Regression
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=4)
X_poly = poly_reg.fit_transform(X)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

#Visualizing Linear Model
plt.figure('Linear Regression', clear = True)
plt.scatter(X, y, color='red')
plt.plot(X, lin_reg.predict(X), color = 'blue')
plt.title("Truth or Bluff (Linear Regression)")
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()

#Visualizing Polynomial Regression Model
plt.figure('Polynomial Regression', clear = True)
plt.scatter(X, y, color = 'red')
plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color = 'blue')
plt.title("Truth or Bluff (Polynomial Regression)")
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()

#Visualizing Higher Resolution and Smooth Curve for Polynomial regression Model
plt.figure('For higher resolution and smooth curve', clear = True)
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y, color='red')
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color='blue')
plt.xlabel('Position Level')
plt.ylabel('Salary')

#Predicting a new result with Linear Regression
lin_reg.predict([[6.5]]) 

#Predicting a new result with Polynomial Regression
lin_reg_2.predict(poly_reg.fit_transform([[6.5]]))







<file_sep>dataset = read.csv('Salary_Data.csv')
library(caTools)
set.seed(123)
split = sample.split(dataset$Salary, SplitRatio = 2/3)
training_set = subset(dataset, split==TRUE)
test_set = subset(dataset, split==FALSE)
regressor = lm(formula = Salary~YearsExperience, data=training_set)
y_pred = predict(regressor, test_set)

#install.packages('ggplot2')
library(ggplot2)
ggplot() + 
  geom_point(aes(x=training_set$YearsExperience, y=training_set$Salary), colour='red')+
  geom_line(aes(x=training_set$YearsExperience, y=predict(regressor,newdata = training_set)), colour='blue') +
  ggtitle('Salary vs Experience(Test Set)') +
  xlab('Years of Experience') +
  ylab('Salary')
  <file_sep>import tweepy
import time

# NOTE: flush=True is just for running this script

CONSUMER_KEY = '####'
CONSUMER_SECRET = '####'
ACCESS_KEY = '####'
ACCESS_SECRET = '####'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

FILE_NAME = 'last_id.txt'

def retrive_last_id(file_name):
    f_read = open(file_name, 'r')
    last_id = int(f_read.read().strip())
    f_read.close()
    return last_id

def store_last_id(last_id, file_name):
    f_write = open(file_name, 'w')
    f_write.write(str(last_id))
    f_write.close()
    return

def reply_tweet():
    print('This is a bot for replying to Tweets!!!!')
    
    last_id = retrive_last_id(FILE_NAME)
    mentions = api.mentions_timeline(last_id, tweet_mode = 'extended')
    
    for mention in reversed(mentions):
        print(str(mention.id)+' '+mention.text, flush=True)
        last_id = mention.id
        store_last_id(last_id, FILE_NAME)
        
        if 'helloword' or 'hello' or 'hi' in mention.text.lower():
            print('Found Greetings... Replying back', flush=True)
            api.update_status('@'+mention.user.screen_name+' '+"Hello back to you!!!", mention.id)
        
        elif 'bye' or 'good bye' in mention.text.lower():
            print('Found Bye.... Replying back', flush=True)
            api.update_status('@'+mention.user.screen_name+' '+"Good Bye!!!", mention.id)
        
        else:
            print('Generic message.... Replying back', flush=True)
            api.update_status('@'+mention.user.screen_name+' '+"Will get back to you later", mention.id)

while True:
    reply_tweet()
    time.sleep(10)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri May  1 23:45:47 2020

@author: Vaish
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataset = pd.read_csv('Mall_Customers.csv')

X = dataset.iloc[:, [3,4]].values

from sklearn.cluster import KMeans
wcss = []

for i in range(1,11):
    kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10)
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)
    
plt.plot(range(1,11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()

#Applying kmeans 
kmeans = KMeans(n_clusters=5, n_init=10, init='k-means++', max_iter=300, random_state=0)
y_means = kmeans.fit_predict(X)

#Visualising
plt.scatter(X[y_means==0,0], X[y_means==0, 1], s=100, c='red', label='Careful')
plt.scatter(X[y_means==1,0], X[y_means==1, 1], s=100, c='blue', label='Standard')
plt.scatter(X[y_means==2,0], X[y_means==2, 1], s=100, c='green', label='Target')
plt.scatter(X[y_means==3,0], X[y_means==3, 1], s=100, c='cyan', label='Careless')
plt.scatter(X[y_means==4,0], X[y_means==4, 1], s=100, c='purple', label='Sensible')
plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s=100, c='yellow', label='Centroids')
plt.title('Clusters of Clients')
plt.xlabel('Annual Income(k$)')
plt.ylabel('Spending Score(1-100)')
plt.legend()
plt.show()




<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 17:03:39 2020

@author: Vaish
"""

#Importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataset = pd.read_csv("Position_Salaries.csv")
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

from sklearn.ensemble import RandomForestRegressor
regressor = RandomForestRegressor(n_estimators = 300,random_state=0)

regressor.fit(X,y)

y_pred = regressor.predict([[6.5]])

#Visualizing the Randon Forest Regression
X_grid = np.arange(min(X), max(X), 0.01)
X_grid = X_grid.reshape(len(X_grid), 1)
plt.scatter(X, y, color='red')
plt.plot(X_grid, regressor.predict(X_grid), color="blue")
plt.title("Truth or Bluff(Random Forest Regressor)")
plt.xlabel('Position Label')
plt.ylabel('Salary')
plt.show()<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 09:07:37 2020

@author: Vaish
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,0].values
y = dataset.iloc[:,-1].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)


from sklearn.linear_model import LinearRegression
X_train = X_train.reshape(-1,1)
X_test = X_test.reshape(-1,1)
y_train = y_train.reshape(-1,1)

regressor = LinearRegression(copy_X=True, fit_intercept= True, n_jobs = 1)
regressor.fit(X_train, y_train)

y_pred = regressor.predict(X_test)



plt.scatter(X_test, y_test, color='red')
plt.plot(X_train, regressor.predict(X_train), color='blue')
plt.title('Salary vs Experience(Test Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()

plt.scatter(X_train, y_train, color='red')
plt.plot(X_train, regressor.predict(X_train), color='blue')
plt.title('Salary vs Experience(Train Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat May  9 08:12:30 2020

@author: Vaishnavi
"""

import numpy as np
import pandas as pd

data = pd.read_csv("Market_Basket_Optimisation.csv", header = None)

trans = []

for i in range(0,7501):
    trans.append([str(data.values[i,j]) for j in range(0,20)])

from apyori import apriori
rules = apriori(trans, min_support = 0.003, min_confidence = 0.2, min_lift = 3, min_length = 2)

results = list(rules)<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 16:32:47 2020

@author: Vaish
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
'''y = y.reshape(-1,1)'''

'''from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
sc_y = StandardScaler()
X = sc_X.fit_transform(X)
y = sc_y.fit_transform(y)'''

from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor()
regressor.fit(X,y)

'''
y_pred = sc_y.inverse_transform(regressor.predict(sc_X.transform(np.array([[6.5]]))))
'''

y_pred = regressor.predict([[6.5]])

#Plotting in Higher Resolution
X_grid = np.arange(min(X), max(X), 0.01)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y, color='red')
plt.plot(X_grid, regressor.predict(X_grid), color='blue')
plt.title('Truth or Bluff(Decision Tree Regressor)')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()


<file_sep>#Create environment
conda create -n py36 python=3.6
conda config --add channels conda-forge
conda install numpy
conda install scipy
conda install dlib

pip install --no-dependencies face_recognition

#import libraries
import os
import face_recognition

#make list of all the available images
images = os.listdir('images')
#load your image
image_to_be_matched = face_recognition.load_image_file('my_image.jpg')
#encode the loaded into feature vector
image_to_be_matched_encoded = face_recognition.face_encodings(image_to_be_matched)[0]
#iterate over each image
for image in images:
    #load the image
    current_image = face_recognition.load_image.file("images/"+image)
    #encode the loaded image into feature vector
    current_image_encoded = face_recognition.face_encodings(current_image)[0]
    #match your image with the image and check if it matches
    result = face_recognition.compare_face([image_to_be_matched_encoded], current_image_encoded)
    #check if it matches
    if result[0] == True:
        print("Matched " + image)
    else:
        print("Not Matched " + image)
<file_sep>dataset = read.csv('Data.csv')

dataset$Age = ifelse(is.na(dataset$Age), ave(dataset$Age, FUN = function(x) mean(x,na.rm = TRUE)),dataset$Age)

dataset$Salary = ifelse(is.na(dataset$Salary), ave(dataset$Salary, FUN = function(x) mean(x,na.rm = TRUE)), dataset$Salary)

dataset$Country = factor(dataset$Country, levels = c('France','Spain','Germany'), labels = c(1,2,3))
dataset$Purchased = factor(dataset$Purchased, levels = c('Yes', 'No'), labels = c(1,0))

install.packages('caTools')
library(caTools)
set.seed(123)
split = sample.split(dataset$Purchased, SplitRatio = 0.8)
training_set = subset(dataset, split == TRUE)
test_set = subset(dataset, split == FALSE)

training_set[,2:3] = scale(training_set[,2:3])
test_set[,2:3] = scale(test_set[,2:3])<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 05:38:10 2020

@author: Vaishnavi
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataset = pd.read_csv('Social_Network_Ads.csv')

X = dataset.iloc[:, [2,3]].values
y = dataset.iloc[:, 4].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state=0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion="entropy", random_state=0)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)

from sklearn import metrics
cm = metrics.confusion_matrix(y_test, y_pred)
ac = metrics.accuracy_score(y_test, y_pred)
pr = metrics.precision_score(y_test, y_pred)

from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start=X_set[:, 0].min()-1, stop=X_set[:,0].max()+1, step=0.001), 
                     np.arange(start=X_set[:, 1].min()-1, stop=X_set[:,1].max()+1, step=0.001))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha=0.75, cmap = ListedColormap(("orange", "pink")))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())

for i,j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set==j,0], X_set[y_set==j,1], c=ListedColormap(("yellow","white"))(i), label=j)
    
plt.title('Classifier(Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start=X_set[:, 0].min()-1, stop=X_set[:,0].max()+1, step=0.001), 
                     np.arange(start=X_set[:, 1].min()-1, stop=X_set[:,1].max()+1, step=0.001))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha=0.75, cmap = ListedColormap(("orange", "pink")))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())

for i,j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set==j,0], X_set[y_set==j,1], c=ListedColormap(("yellow","white"))(i), label=j)
    
plt.title('Classifier(Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()


<file_sep>#Data Preprocessing

import numpy as np;
import matplotlib.pyplot as plt;
import pandas as pd;

dataset = pd.read_csv('Data.csv');
X = dataset.iloc[:,:-1].values;
X
y = dataset.iloc[:,-1].values;
y
a = np.arange(1,10,3);
a
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values=np.nan, strategy = 'mean', axis=0)
imputer = imputer.fit(X[:,1:3])
X[:, 1:3] = imputer.transform(X[:,1:3])

from sklearn.preprocessing import LabelEncoder
labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)

from sklearn.preprocessing import OneHotEncoder
onehotencoder_X = OneHotEncoder(categorical_features = [0])
X = onehotencoder_X.fit_transform(X).toarray()

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 0)

from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Feb  6 11:39:30 2020

@author: Vaish
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:, 4].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:,3] = labelencoder_X.fit_transform(X[:,3])
onehotencoder = OneHotEncoder(categorical_features = [3])
X = onehotencoder.fit_transform(X).toarray()
X = X[:,1:]

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)



import statsmodels.api as sm

X = np.append(arr= np.ones((50,1)), values= X, axis=1)

def backwardElimination(x, SL):
  numVars = len(x[0])
  temp = np.zeros((50,6)).astype(int)
  for i in range(0, numVars):
    regressor_OLS = sm.OLS(y,x).fit()
    maxVar = max(regressor_OLS.pvalues).astype(float)
    adjR_before = regressor_OLS.rsquared_adj.astype(float)
    if maxVar>SL:
      for j in range(0, numVars-i):
        if(regressor_OLS.pvalues[j]==maxVar):
          temp[:,j] = x[:,j]
          x = np.delete(x,j,1)
          temp_regressor = sm.OLS(y,x).fit()
          adjR_after = temp_regressor.rsquared_adj.astype(float)
          if(adjR_before>=adjR_after):
            x_rollback = np.hstack((x, temp[:, [0,j]]))
            x_rollback = np.delete(x_rollback, j,1)
            print(regressor_OLS.summary())
            return x_rollback
          else:
            continue
    regressor_OLS.summary()
    return x
SL = 0.05
X_opt = X[:, [0,1,2,3,4,5]]
X_Modeled = backwardElimination(X_opt, SL)
          
          
          
          
          
          
          
    
    
    
    
    
    
    
    
    
    