├── 3D Lung Segmentation model ├── inference.py ├── mas_lung_002.nii ├── mask_lung_002.npy ├── new.py ├── readme.md ├── requirement.txt ├── resunet.py ├── rough.py └── utilties.py ├── AStarGUI.py ├── Basic Autopilot with Tensorflow ├── README.md ├── driving_data.py ├── model.py ├── run.py ├── run_dataset.py ├── save │ ├── checkpoint │ ├── model.ckpt │ └── model.ckpt.meta ├── steering_wheel_image.jpg └── train.py ├── CARTOONING-AN-IMAGE-USING-OPENCV-master ├── CARTOONING AN IMAGE USING OPENCV.ipynb └── Cartoon_BIRD.png ├── CONTRIBUTING.md ├── Dominent Color Extractor ├── Color_Extraction.ipynb ├── Image_Segmentation.ipynb └── images │ ├── photo1.jpg │ ├── photo2.jpg │ ├── photo3.jpg │ ├── photo4.jpg │ ├── photo5.jpg │ └── photo6.jpg ├── Ecommerce Customers-Linear Regression.ipynb ├── Face Recognition ├── archive │ ├── haarcascade_eye.xml │ ├── haarcascade_eye_tree_eyeglasses.xml │ ├── haarcascade_frontalcatface.xml │ ├── haarcascade_frontalcatface_extended.xml │ ├── haarcascade_frontalface_alt.xml │ ├── haarcascade_frontalface_alt2.xml │ ├── haarcascade_frontalface_alt_tree.xml │ ├── haarcascade_frontalface_default.xml │ ├── haarcascade_fullbody.xml │ ├── haarcascade_lefteye_2splits.xml │ ├── haarcascade_licence_plate_rus_16stages.xml │ ├── haarcascade_lowerbody.xml │ ├── haarcascade_profileface.xml │ ├── haarcascade_righteye_2splits.xml │ ├── haarcascade_russian_plate_number.xml │ ├── haarcascade_smile.xml │ └── haarcascade_upperbody.xml ├── face_classifier.ipynb └── face_recognizer.ipynb ├── Face-Recognition-cum-Attendance ├── Dataset │ ├── Bill Gates.jpg │ ├── Edward Snowden.jpg │ └── Elon Musk.jpg ├── LICENSE ├── README.md ├── attendance-project.py └── requirements.txt ├── Hand gesture detection with tensorflow ├── Readme.md ├── data.pickle ├── gesture.names ├── images │ ├── fist.png │ ├── rock.png │ ├── thumbs_down.png │ └── thumbs_up.png ├── main.py ├── mp_hand_gesture │ ├── keras_metadata.pb │ ├── saved_model.pb │ └── variables │ │ ├── variables.data-00000-of-00001 │ │ └── variables.index └── requirements.txt ├── Hangman ├── README.md ├── __pycache__ │ ├── hangman_art.cpython-310.pyc │ └── hangman_words.cpython-310.pyc ├── hangman_art.py ├── hangman_words.py └── main.py ├── Lung cancer detection using CNN and DCGAN ├── CancerNoduleImagesgeneration.ipynb ├── Densenet_To_Detetct_lung_cancer.ipynb ├── EfficientNet_For_LungCancerNoduleDetection.ipynb ├── InceptionNet_For_LungCancerNoduleDetection.ipynb ├── MobileNet_For_LungCancerNoduleDetection.ipynb ├── NonCancerousNoduleImageGeneration.ipynb ├── ShuffleNet_To_detect_lung_cancer.ipynb └── XceptionNet_For_LungCancerNoduleDetection.ipynb ├── ML-WebApp ├── .gitignore ├── README.md ├── requirements.txt └── src │ ├── AgesAndHeights.pkl │ ├── app.py │ ├── model.ipynb │ ├── model.joblib │ ├── output.svg │ ├── static │ ├── 001c359471524b2ea2a44ffb408ef9f0.svg │ ├── 5d0b4cd358a3403495f3f5a32ad45cd6.svg │ ├── base.svg │ ├── c9dd34492a344500a494b9368dadcf0f.svg │ └── predictions.svg │ └── templates │ └── index.html ├── MNIST number detector ├── images │ ├── MNIST-Matrix.png │ └── relu.jpeg ├── main.ipynb ├── readme.md └── requirements.txt ├── Minesweeper ├── LICENSE ├── __pycache__ │ ├── minesweeper.cpython-38.pyc │ └── minesweeper.cpython-39.pyc ├── assets │ ├── fonts │ │ └── OpenSans-Regular.ttf │ └── images │ │ ├── flag.png │ │ └── mine.png ├── minesweeper.py ├── requirements.txt └── runner.py ├── Plagiarism Checker ├── File 1.txt ├── File 2.txt ├── File 3.txt ├── Plagiarism Checker.ipynb └── README.md ├── Polynomial Regression ├── data_preprocessing_template.py └── polynomial_regression.py ├── README.md ├── Spotify Recommendation Analysis ├── File ├── Readme.md └── Spotify_Recommendation.ipynb ├── Tic-Tac-Toe ├── LICENSE ├── OpenSans-Regular.ttf ├── README.md ├── __pycache__ │ ├── tictactoe.cpython-38.pyc │ └── tictactoe.cpython-39.pyc ├── check.py ├── requirements.txt ├── runner.py └── tictactoe.py ├── Titanic_Dataset_Random_Forest.ipynb ├── Twitter Sentiment Analysis with RoBERTa ├── main.ipynb ├── readme.md ├── requirements.txt └── result.png ├── Twitter Sentiment Analysis with VADER ├── main.ipynb ├── readme.md ├── requirements.txt └── result.png ├── Web_Scrapper ├── LinkedIn_Scrapper.ipynb ├── Twitter scraper.ipynb └── linkedin_scraper-checkpoint.ipynb ├── decision tree classifier ├── Decision Tree Classifier (with sklearn).ipynb ├── Decision Tree Classifier (without sklearn).ipynb └── Tennis.csv ├── generalized KNN algorithm for all datasets classification ├── KNN_Algorithm.ipynb └── diabetes.csv ├── knights ├── README.md ├── __pycache__ │ ├── logic.cpython-38.pyc │ └── logic.cpython-39.pyc ├── logic.py └── puzzle.py ├── market-basket-analysis Apriori ├── Apriori.ipynb └── store_data.csv ├── requirements.txt └── snake ├── README.md ├── __pycache__ ├── food.cpython-310.pyc ├── scoreboard.cpython-310.pyc └── snake.cpython-310.pyc ├── food.py ├── scoreboard.py ├── snake.py └── snakegame.py /3D Lung Segmentation model/inference.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | # from lungmask import utils 4 | import utilties as utils 5 | import SimpleITK as sitk 6 | from resunet import UNet 7 | import warnings 8 | import sys 9 | from tqdm import tqdm 10 | import skimage 11 | import logging 12 | import nibabel as nib 13 | 14 | logging.basicConfig(stream=sys.stdout, level=logging.INFO) 15 | warnings.filterwarnings("ignore", category=UserWarning) 16 | 17 | 18 | def apply(image, model=None, force_cpu=False, batch_size=20, volume_postprocessing=True, noHU=False): 19 | if model is None: 20 | model = get_model('model.pth') 21 | 22 | numpy_mode = isinstance(image, np.ndarray) 23 | if numpy_mode: 24 | inimg_raw = image.copy() 25 | else: 26 | inimg_raw = sitk.GetArrayFromImage(image) 27 | directions = np.asarray(image.GetDirection()) 28 | if len(directions) == 9: 29 | inimg_raw = np.flip(inimg_raw, np.where(directions[[0,4,8]][::-1]<0)[0]) 30 | del image 31 | 32 | if force_cpu: 33 | device = torch.device('cpu') 34 | else: 35 | if torch.cuda.is_available(): 36 | device = torch.device('cuda') 37 | else: 38 | logging.info("No GPU support available, will use CPU. Note, that this is significantly slower!") 39 | batch_size = 1 40 | device = torch.device('cpu') 41 | model.to(device) 42 | 43 | 44 | if not noHU: 45 | tvolslices, xnew_box = utils.preprocess(inimg_raw, resolution=[256, 256]) 46 | tvolslices[tvolslices > 600] = 600 47 | tvolslices = np.divide((tvolslices + 1024), 1624) 48 | else: 49 | # support for non HU images. This is just a hack. The models were not trained with this in mind 50 | tvolslices = skimage.color.rgb2gray(inimg_raw) 51 | tvolslices = skimage.transform.resize(tvolslices, [256, 256]) 52 | tvolslices = np.asarray([tvolslices*x for x in np.linspace(0.3,2,20)]) 53 | tvolslices[tvolslices>1] = 1 54 | sanity = [(tvolslices[x]>0.6).sum()>25000 for x in range(len(tvolslices))] 55 | tvolslices = tvolslices[sanity] 56 | torch_ds_val = utils.LungLabelsDS_inf(tvolslices) 57 | dataloader_val = torch.utils.data.DataLoader(torch_ds_val, batch_size=batch_size, shuffle=False, pin_memory=False) 58 | 59 | timage_res = np.empty((np.append(0, tvolslices[0].shape)), dtype=np.uint8) 60 | 61 | with torch.no_grad(): 62 | for X in tqdm(dataloader_val): 63 | X = X.float().to(device) 64 | prediction = model(X) 65 | pls = torch.max(prediction, 1)[1].detach().cpu().numpy().astype(np.uint8) 66 | timage_res = np.vstack((timage_res, pls)) 67 | 68 | # postprocessing includes removal of small connected components, hole filling and mapping of small components to 69 | # neighbors 70 | if volume_postprocessing: 71 | outmask = utils.postrocessing(timage_res) 72 | else: 73 | outmask = timage_res 74 | 75 | if noHU: 76 | outmask = skimage.transform.resize(outmask[np.argmax((outmask==1).sum(axis=(1,2)))], inimg_raw.shape[:2], order=0, anti_aliasing=False, preserve_range=True)[None,:,:] 77 | else: 78 | outmask = np.asarray( 79 | [utils.reshape_mask(outmask[i], xnew_box[i], inimg_raw.shape[1:]) for i in range(outmask.shape[0])], 80 | dtype=np.uint8) 81 | 82 | if not numpy_mode: 83 | if len(directions) == 9: 84 | outmask = np.flip(outmask, np.where(directions[[0,4,8]][::-1]<0)[0]) 85 | 86 | return outmask.astype(np.uint8) 87 | 88 | 89 | def get_model(modelpath, n_classes=3): 90 | 91 | state_dict = torch.load(modelpath, map_location=torch.device('cpu')) 92 | 93 | model = UNet(n_classes=n_classes, padding=True, depth=5, up_mode='upsample', batch_norm=True, residual=False) 94 | 95 | model.load_state_dict(state_dict) 96 | model.eval() 97 | return model 98 | 99 | 100 | from glob import glob 101 | import os 102 | # data=glob(os.path.join('D:/Projects/AI Diagnostics/3D Lung Segmentation/imagesTs',"*")) 103 | 104 | # for d in data: 105 | # # print(d.split("\\")[-1]) 106 | # input_image = sitk.ReadImage(d) 107 | # se= apply(input_image) 108 | 109 | # ni_img = nib.Nifti1Image(se, affine=np.eye(4)) 110 | # nib.save(ni_img, ("outputs/"+d.split("\\")[-1])) 111 | 112 | input_image = sitk.ReadImage("outputs/3000566.nii.gz") 113 | se= apply(input_image) 114 | # print(se.shape) 115 | np.save("mask_lung_002.npy",se) 116 | 117 | 118 | ni_img = nib.Nifti1Image(se, affine=np.eye(4)) 119 | nib.save(ni_img, "mas_lung_002.nii") 120 | -------------------------------------------------------------------------------- /3D Lung Segmentation model/mas_lung_002.nii: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/3D Lung Segmentation model/mas_lung_002.nii -------------------------------------------------------------------------------- /3D Lung Segmentation model/mask_lung_002.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/3D Lung Segmentation model/mask_lung_002.npy -------------------------------------------------------------------------------- /3D Lung Segmentation model/new.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import SimpleITK as sitk 3 | image = sitk.ReadImage("D:/Projects/AI Diagnostics/3D Lung Segmentation V2/imagesTs/lung_002.nii.gz") 4 | directions = np.asarray(image.GetDirection()) 5 | 6 | print(image) -------------------------------------------------------------------------------- /3D Lung Segmentation model/readme.md: -------------------------------------------------------------------------------- 1 | # 3D Lung Segmentation Model 2 | This is a Python3 based project where i have implemented a resnet insipred model to create 3D lung mask from CT scans. 3 | 4 | To install the requirements use the following command: 5 | pip/pip3 install -r requirements.txt 6 | 7 | 8 | Details: 9 | Using different deep learning approaches, 10 | mean Dice similarity coefficients (DSCs) on test datasets varied not over 0.02. 11 | When trained on a diverse routine dataset (n = 36), a standard approach (U-net) yields a higher DSC (0.97 ± 0.05) 12 | compared to training on public datasets such as the Lung Tissue Research Consortium (0.94 ± 0.13, p = 0.024) or 13 | Anatomy 3 (0.92 ± 0.15, p = 0.001). 14 | 15 | Trained on routine data (n = 231) covering multiple diseases, 16 | U-net compared to reference methods yields a DSC of 0.98 ± 0.03 versus 0.94 ± 0.12 (p = 0.024). 17 | 18 | Contact (ahmedmulla1910@gmail.com) for pre trianed weights 19 | 20 | ## How to Contribute? 21 | 22 | - Take Existing Issues or create your own Issues! 23 | - Get Assigned with Issues 24 | - Fork the Repo, then Clone forked repo. 25 | - Create a Pull Request. 26 | - Add Screenshots/deployed link in your project repo README.md 27 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 28 | 29 | 30 | ## HELP US OUT BY STARRING THIS REPOSITORY -------------------------------------------------------------------------------- /3D Lung Segmentation model/requirement.txt: -------------------------------------------------------------------------------- 1 | certifi==2022.6.15 2 | charset-normalizer==2.1.1 3 | colorama==0.4.5 4 | fastremap==1.13.3 5 | fill-voids==2.0.2 6 | idna==3.3 7 | imageio==2.21.2 8 | networkx==2.8.6 9 | nibabel==4.0.2 10 | numpy==1.23.2 11 | packaging==21.3 12 | Pillow==9.2.0 13 | pydicom==2.3.0 14 | pyparsing==3.0.9 15 | PyWavelets==1.3.0 16 | requests==2.28.1 17 | scikit-image==0.19.3 18 | scipy==1.9.1 19 | SimpleITK==2.2.0 20 | tifffile==2022.8.12 21 | torch==1.12.1+cu113 22 | torchaudio==0.12.1+cu113 23 | torchvision==0.13.1+cu113 24 | tqdm==4.64.1 25 | typing_extensions==4.3.0 26 | urllib3==1.26.12 27 | -------------------------------------------------------------------------------- /3D Lung Segmentation model/resunet.py: -------------------------------------------------------------------------------- 1 | # Adapted from https://discuss.pytorch.org/t/unet-implementation/426 2 | 3 | import torch 4 | from torch import nn 5 | import torch.nn.functional as F 6 | 7 | 8 | class UNet(nn.Module): 9 | def __init__(self, in_channels=1, n_classes=2, depth=5, wf=6, padding=False, 10 | batch_norm=False, up_mode='upconv', residual=False): 11 | 12 | super(UNet, self).__init__() 13 | assert up_mode in ('upconv', 'upsample') 14 | self.padding = padding 15 | self.depth = depth 16 | prev_channels = in_channels 17 | self.down_path = nn.ModuleList() 18 | for i in range(depth): 19 | if i == 0 and residual: 20 | self.down_path.append(UNetConvBlock(prev_channels, 2 ** (wf + i), 21 | padding, batch_norm, residual, first=True)) 22 | else: 23 | self.down_path.append(UNetConvBlock(prev_channels, 2 ** (wf + i), 24 | padding, batch_norm, residual)) 25 | prev_channels = 2 ** (wf + i) 26 | 27 | self.up_path = nn.ModuleList() 28 | for i in reversed(range(depth - 1)): 29 | self.up_path.append(UNetUpBlock(prev_channels, 2 ** (wf + i), up_mode, 30 | padding, batch_norm, residual)) 31 | prev_channels = 2 ** (wf + i) 32 | 33 | self.last = nn.Conv2d(prev_channels, n_classes, kernel_size=1) 34 | self.softmax = nn.LogSoftmax(dim=1) 35 | 36 | def forward(self, x): 37 | blocks = [] 38 | for i, down in enumerate(self.down_path): 39 | x = down(x) 40 | if i != len(self.down_path) - 1: 41 | blocks.append(x) 42 | x = F.avg_pool2d(x, 2) 43 | 44 | for i, up in enumerate(self.up_path): 45 | x = up(x, blocks[-i - 1]) 46 | 47 | res = self.last(x) 48 | return self.softmax(res) 49 | 50 | 51 | class UNetConvBlock(nn.Module): 52 | def __init__(self, in_size, out_size, padding, batch_norm, residual=False, first=False): 53 | super(UNetConvBlock, self).__init__() 54 | self.residual = residual 55 | self.out_size = out_size 56 | self.in_size = in_size 57 | self.batch_norm = batch_norm 58 | self.first = first 59 | self.residual_input_conv = nn.Conv2d(self.in_size, self.out_size, kernel_size=1) 60 | self.residual_batchnorm = nn.BatchNorm2d(self.out_size) 61 | 62 | if residual: 63 | padding = 1 64 | block = [] 65 | 66 | if residual and not first: 67 | block.append(nn.ReLU()) 68 | if batch_norm: 69 | block.append(nn.BatchNorm2d(in_size)) 70 | 71 | block.append(nn.Conv2d(in_size, out_size, kernel_size=3, 72 | padding=int(padding))) 73 | block.append(nn.ReLU()) 74 | if batch_norm: 75 | block.append(nn.BatchNorm2d(out_size)) 76 | 77 | block.append(nn.Conv2d(out_size, out_size, kernel_size=3, 78 | padding=int(padding))) 79 | 80 | if not residual: 81 | block.append(nn.ReLU()) 82 | if batch_norm: 83 | block.append(nn.BatchNorm2d(out_size)) 84 | self.block = nn.Sequential(*block) 85 | 86 | def forward(self, x): 87 | out = self.block(x) 88 | if self.residual: 89 | if self.in_size != self.out_size: 90 | x = self.residual_input_conv(x) 91 | x = self.residual_batchnorm(x) 92 | out = out + x 93 | 94 | return out 95 | 96 | 97 | class UNetUpBlock(nn.Module): 98 | def __init__(self, in_size, out_size, up_mode, padding, batch_norm, residual=False): 99 | super(UNetUpBlock, self).__init__() 100 | self.residual = residual 101 | self.in_size = in_size 102 | self.out_size = out_size 103 | self.residual_input_conv = nn.Conv2d(self.in_size, self.out_size, kernel_size=1) 104 | self.residual_batchnorm = nn.BatchNorm2d(self.out_size) 105 | 106 | if up_mode == 'upconv': 107 | self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=2, 108 | stride=2) 109 | elif up_mode == 'upsample': 110 | self.up = nn.Sequential(nn.Upsample(mode='bilinear', scale_factor=2), 111 | nn.Conv2d(in_size, out_size, kernel_size=1)) 112 | 113 | self.conv_block = UNetConvBlock(in_size, out_size, padding, batch_norm) 114 | 115 | @staticmethod 116 | def center_crop(layer, target_size): 117 | _, _, layer_height, layer_width = layer.size() 118 | diff_y = (layer_height - target_size[0]) // 2 119 | diff_x = (layer_width - target_size[1]) // 2 120 | return layer[:, :, diff_y:(diff_y + target_size[0]), diff_x:(diff_x + target_size[1])] 121 | 122 | def forward(self, x, bridge): 123 | up = self.up(x) 124 | crop1 = self.center_crop(bridge, up.shape[2:]) 125 | out_orig = torch.cat([up, crop1], 1) 126 | out = self.conv_block(out_orig) 127 | if self.residual: 128 | if self.in_size != self.out_size: 129 | out_orig = self.residual_input_conv(out_orig) 130 | out_orig = self.residual_batchnorm(out_orig) 131 | out = out + out_orig 132 | 133 | return out 134 | -------------------------------------------------------------------------------- /3D Lung Segmentation model/rough.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import nibabel as nib 3 | 4 | se=np.load("mask_lung_002.npy") 5 | # ni_img = nib.Nifti1Image(se, affine=np.eye(4)) 6 | # nib.save(ni_img, "a1_lung_002.nii.gz") 7 | 8 | # se=se.reshape((512, 512,269)) 9 | ni_img = nib.Nifti1Image(se, affine=np.eye(4)) 10 | img = nib.load('timage_res_lung_002.nii.gz') 11 | head=img.header 12 | print(head) 13 | # head.write_to(ni_img) 14 | print(ni_img.header) 15 | # nib.save(ni_img, "a3_lung_002.nii.gz") -------------------------------------------------------------------------------- /3D Lung Segmentation model/utilties.py: -------------------------------------------------------------------------------- 1 | import scipy.ndimage as ndimage 2 | import skimage.measure 3 | import numpy as np 4 | from torch.utils.data import Dataset 5 | import os 6 | import sys 7 | import SimpleITK as sitk 8 | import pydicom as pyd 9 | import logging 10 | from tqdm import tqdm 11 | import fill_voids 12 | import skimage.morphology 13 | 14 | 15 | def preprocess(img, label=None, resolution=[192, 192]): 16 | imgmtx = np.copy(img) 17 | lblsmtx = np.copy(label) 18 | 19 | imgmtx[imgmtx < -1024] = -1024 20 | imgmtx[imgmtx > 600] = 600 21 | cip_xnew = [] 22 | cip_box = [] 23 | cip_mask = [] 24 | for i in range(imgmtx.shape[0]): 25 | if label is None: 26 | (im, m, box) = crop_and_resize(imgmtx[i, :, :], width=resolution[0], height=resolution[1]) 27 | else: 28 | (im, m, box) = crop_and_resize(imgmtx[i, :, :], mask=lblsmtx[i, :, :], width=resolution[0], 29 | height=resolution[1]) 30 | cip_mask.append(m) 31 | cip_xnew.append(im) 32 | cip_box.append(box) 33 | if label is None: 34 | return np.asarray(cip_xnew), cip_box 35 | else: 36 | return np.asarray(cip_xnew), cip_box, np.asarray(cip_mask) 37 | 38 | 39 | def simple_bodymask(img): 40 | maskthreshold = -500 41 | oshape = img.shape 42 | img = ndimage.zoom(img, 128/np.asarray(img.shape), order=0) 43 | bodymask = img > maskthreshold 44 | bodymask = ndimage.binary_closing(bodymask) 45 | bodymask = ndimage.binary_fill_holes(bodymask, structure=np.ones((3, 3))).astype(int) 46 | bodymask = ndimage.binary_erosion(bodymask, iterations=2) 47 | bodymask = skimage.measure.label(bodymask.astype(int), connectivity=1) 48 | regions = skimage.measure.regionprops(bodymask.astype(int)) 49 | if len(regions) > 0: 50 | max_region = np.argmax(list(map(lambda x: x.area, regions))) + 1 51 | bodymask = bodymask == max_region 52 | bodymask = ndimage.binary_dilation(bodymask, iterations=2) 53 | real_scaling = np.asarray(oshape)/128 54 | return ndimage.zoom(bodymask, real_scaling, order=0) 55 | 56 | 57 | def crop_and_resize(img, mask=None, width=192, height=192): 58 | bmask = simple_bodymask(img) 59 | # img[bmask==0] = -1024 # this line removes background outside of the lung. 60 | # However, it has been shown problematic with narrow circular field of views that touch the lung. 61 | # Possibly doing more harm than help 62 | reg = skimage.measure.regionprops(skimage.measure.label(bmask)) 63 | if len(reg) > 0: 64 | bbox = np.asarray(reg[0].bbox) 65 | else: 66 | bbox = (0, 0, bmask.shape[0], bmask.shape[1]) 67 | img = img[bbox[0]:bbox[2], bbox[1]:bbox[3]] 68 | img = ndimage.zoom(img, np.asarray([width, height]) / np.asarray(img.shape), order=1) 69 | if not mask is None: 70 | mask = mask[bbox[0]:bbox[2], bbox[1]:bbox[3]] 71 | mask = ndimage.zoom(mask, np.asarray([width, height]) / np.asarray(mask.shape), order=0) 72 | # mask = ndimage.binary_closing(mask,iterations=5) 73 | return img, mask, bbox 74 | 75 | 76 | ## For some reasons skimage.transform leads to edgy mask borders compared to ndimage.zoom 77 | # def reshape_mask(mask, tbox, origsize): 78 | # res = np.ones(origsize) * 0 79 | # resize = [tbox[2] - tbox[0], tbox[3] - tbox[1]] 80 | # imgres = skimage.transform.resize(mask, resize, order=0, mode='constant', cval=0, anti_aliasing=False, preserve_range=True) 81 | # res[tbox[0]:tbox[2], tbox[1]:tbox[3]] = imgres 82 | # return res 83 | 84 | 85 | def reshape_mask(mask, tbox, origsize): 86 | res = np.ones(origsize) * 0 87 | resize = [tbox[2] - tbox[0], tbox[3] - tbox[1]] 88 | imgres = ndimage.zoom(mask, resize / np.asarray(mask.shape), order=0) 89 | res[tbox[0]:tbox[2], tbox[1]:tbox[3]] = imgres 90 | return res 91 | 92 | 93 | class LungLabelsDS_inf(Dataset): 94 | def __init__(self, ds): 95 | self.dataset = ds 96 | 97 | def __len__(self): 98 | return len(self.dataset) 99 | 100 | def __getitem__(self, idx): 101 | return self.dataset[idx, None, :, :].astype(np.float) 102 | 103 | 104 | def read_dicoms(path, primary=True, original=True): 105 | allfnames = [] 106 | for dir, _, fnames in os.walk(path): 107 | [allfnames.append(os.path.join(dir, fname)) for fname in fnames] 108 | 109 | dcm_header_info = [] 110 | dcm_parameters = [] 111 | unique_set = [] # need this because too often there are duplicates of dicom files with different names 112 | i = 0 113 | for fname in tqdm(allfnames): 114 | filename_ = os.path.splitext(os.path.split(fname)[1]) 115 | i += 1 116 | if filename_[0] != 'DICOMDIR': 117 | try: 118 | dicom_header = pyd.dcmread(fname, defer_size=100, stop_before_pixels=True, force=True) 119 | if dicom_header is not None: 120 | if 'ImageType' in dicom_header: 121 | if primary: 122 | is_primary = all([x in dicom_header.ImageType for x in ['PRIMARY']]) 123 | else: 124 | is_primary = True 125 | 126 | if original: 127 | is_original = all([x in dicom_header.ImageType for x in ['ORIGINAL']]) 128 | else: 129 | is_original = True 130 | 131 | # if 'ConvolutionKernel' in dicom_header: 132 | # ck = dicom_header.ConvolutionKernel 133 | # else: 134 | # ck = 'unknown' 135 | if is_primary and is_original and 'LOCALIZER' not in dicom_header.ImageType: 136 | h_info_wo_name = [dicom_header.StudyInstanceUID, dicom_header.SeriesInstanceUID, 137 | dicom_header.ImagePositionPatient] 138 | h_info = [dicom_header.StudyInstanceUID, dicom_header.SeriesInstanceUID, fname, 139 | dicom_header.ImagePositionPatient] 140 | if h_info_wo_name not in unique_set: 141 | unique_set.append(h_info_wo_name) 142 | dcm_header_info.append(h_info) 143 | # kvp = None 144 | # if 'KVP' in dicom_header: 145 | # kvp = dicom_header.KVP 146 | # dcm_parameters.append([ck, kvp,dicom_header.SliceThickness]) 147 | except: 148 | logging.error("Unexpected error:", sys.exc_info()[0]) 149 | logging.warning("Doesn't seem to be DICOM, will be skipped: ", fname) 150 | 151 | conc = [x[1] for x in dcm_header_info] 152 | sidx = np.argsort(conc) 153 | conc = np.asarray(conc)[sidx] 154 | dcm_header_info = np.asarray(dcm_header_info, dtype=object)[sidx] 155 | # dcm_parameters = np.asarray(dcm_parameters)[sidx] 156 | vol_unique = np.unique(conc, return_index=1, return_inverse=1) # unique volumes 157 | n_vol = len(vol_unique[1]) 158 | logging.info('There are ' + str(n_vol) + ' volumes in the study') 159 | 160 | relevant_series = [] 161 | relevant_volumes = [] 162 | 163 | for i in range(len(vol_unique[1])): 164 | curr_vol = i 165 | info_idxs = np.where(vol_unique[2] == curr_vol)[0] 166 | vol_files = dcm_header_info[info_idxs, 2] 167 | positions = np.asarray([np.asarray(x[2]) for x in dcm_header_info[info_idxs, 3]]) 168 | slicesort_idx = np.argsort(positions) 169 | vol_files = vol_files[slicesort_idx] 170 | relevant_series.append(vol_files) 171 | reader = sitk.ImageSeriesReader() 172 | reader.SetFileNames(vol_files) 173 | vol = reader.Execute() 174 | relevant_volumes.append(vol) 175 | 176 | return relevant_volumes 177 | 178 | 179 | def get_input_image(path): 180 | if os.path.isfile(path): 181 | logging.info(f'Read input: {path}') 182 | input_image = sitk.ReadImage(path) 183 | else: 184 | logging.info(f'Looking for dicoms in {path}') 185 | dicom_vols = read_dicoms(path, original=False, primary=False) 186 | if len(dicom_vols) < 1: 187 | sys.exit('No dicoms found!') 188 | if len(dicom_vols) > 1: 189 | logging.warning("There are more than one volume in the path, will take the largest one") 190 | input_image = dicom_vols[np.argmax([np.prod(v.GetSize()) for v in dicom_vols], axis=0)] 191 | return input_image 192 | 193 | 194 | def postrocessing(label_image, spare=[]): 195 | '''some post-processing mapping small label patches to the neighbout whith which they share the 196 | largest border. All connected components smaller than min_area will be removed 197 | ''' 198 | 199 | # merge small components to neighbours 200 | regionmask = skimage.measure.label(label_image) 201 | origlabels = np.unique(label_image) 202 | origlabels_maxsub = np.zeros((max(origlabels) + 1,), dtype=np.uint32) # will hold the largest component for a label 203 | regions = skimage.measure.regionprops(regionmask, label_image) 204 | regions.sort(key=lambda x: x.area) 205 | regionlabels = [x.label for x in regions] 206 | 207 | # will hold mapping from regionlabels to original labels 208 | region_to_lobemap = np.zeros((len(regionlabels) + 1,), dtype=np.uint8) 209 | for r in regions: 210 | r_max_intensity = int(r.max_intensity) 211 | if r.area > origlabels_maxsub[r_max_intensity]: 212 | origlabels_maxsub[r_max_intensity] = r.area 213 | region_to_lobemap[r.label] = r_max_intensity 214 | 215 | for r in tqdm(regions): 216 | r_max_intensity = int(r.max_intensity) 217 | if (r.area < origlabels_maxsub[r_max_intensity] or r_max_intensity in spare) and r.area>2: # area>2 improves runtime because small areas 1 and 2 voxel will be ignored 218 | bb = bbox_3D(regionmask == r.label) 219 | sub = regionmask[bb[0]:bb[1], bb[2]:bb[3], bb[4]:bb[5]] 220 | dil = ndimage.binary_dilation(sub == r.label) 221 | neighbours, counts = np.unique(sub[dil], return_counts=True) 222 | mapto = r.label 223 | maxmap = 0 224 | myarea = 0 225 | for ix, n in enumerate(neighbours): 226 | if n != 0 and n != r.label and counts[ix] > maxmap and n != spare: 227 | maxmap = counts[ix] 228 | mapto = n 229 | myarea = r.area 230 | regionmask[regionmask == r.label] = mapto 231 | # print(str(region_to_lobemap[r.label]) + ' -> ' + str(region_to_lobemap[mapto])) # for debugging 232 | if regions[regionlabels.index(mapto)].area == origlabels_maxsub[ 233 | int(regions[regionlabels.index(mapto)].max_intensity)]: 234 | origlabels_maxsub[int(regions[regionlabels.index(mapto)].max_intensity)] += myarea 235 | regions[regionlabels.index(mapto)].__dict__['_cache']['area'] += myarea 236 | 237 | outmask_mapped = region_to_lobemap[regionmask] 238 | outmask_mapped[outmask_mapped==spare] = 0 239 | 240 | if outmask_mapped.shape[0] == 1: 241 | # holefiller = lambda x: ndimage.morphology.binary_fill_holes(x[0])[None, :, :] # This is bad for slices that show the liver 242 | holefiller = lambda x: skimage.morphology.area_closing(x[0].astype(int), area_threshold=64)[None, :, :] == 1 243 | else: 244 | holefiller = fill_voids.fill 245 | 246 | outmask = np.zeros(outmask_mapped.shape, dtype=np.uint8) 247 | for i in np.unique(outmask_mapped)[1:]: 248 | outmask[holefiller(keep_largest_connected_component(outmask_mapped == i))] = i 249 | 250 | return outmask 251 | 252 | 253 | def bbox_3D(labelmap, margin=2): 254 | shape = labelmap.shape 255 | r = np.any(labelmap, axis=(1, 2)) 256 | c = np.any(labelmap, axis=(0, 2)) 257 | z = np.any(labelmap, axis=(0, 1)) 258 | 259 | rmin, rmax = np.where(r)[0][[0, -1]] 260 | rmin -= margin if rmin >= margin else rmin 261 | rmax += margin if rmax <= shape[0] - margin else rmax 262 | cmin, cmax = np.where(c)[0][[0, -1]] 263 | cmin -= margin if cmin >= margin else cmin 264 | cmax += margin if cmax <= shape[1] - margin else cmax 265 | zmin, zmax = np.where(z)[0][[0, -1]] 266 | zmin -= margin if zmin >= margin else zmin 267 | zmax += margin if zmax <= shape[2] - margin else zmax 268 | 269 | if rmax-rmin == 0: 270 | rmax = rmin+1 271 | 272 | return np.asarray([rmin, rmax, cmin, cmax, zmin, zmax]) 273 | 274 | 275 | def keep_largest_connected_component(mask): 276 | mask = skimage.measure.label(mask) 277 | regions = skimage.measure.regionprops(mask) 278 | resizes = np.asarray([x.area for x in regions]) 279 | max_region = np.argsort(resizes)[-1] + 1 280 | mask = mask == max_region 281 | return mask 282 | -------------------------------------------------------------------------------- /AStarGUI.py: -------------------------------------------------------------------------------- 1 | # A * Pathfinding Algorithm 🌟 2 | 3 | # Implemented with pygame, this script will find the shortest distance between two nodes using A * Algorithm 🎮 4 | 5 | # Instructions / Keys Functionalities: 6 | # -Left Click to add start and end nodes 7 | # -Right Click to remove the nodes 8 | # -Space Bar to start finding the shortest distance 9 | # -'C' to clear and reset the grid 10 | 11 | # Requirements: 12 | # pip install pygame 13 | 14 | # By Susnata Goswami(https://github.com/proghead00) 15 | 16 | import pygame 17 | import math 18 | from queue import PriorityQueue 19 | 20 | WIDTH = 800 21 | WIN = pygame.display.set_mode((WIDTH, WIDTH)) # dimension to make it a square 22 | pygame.display.set_caption("A* Path Finding Algorithm") 23 | 24 | RED = (235, 77, 75) 25 | GREEN = (186, 220, 88) 26 | BLUE = (48, 51, 107) 27 | YELLOW = (249, 202, 36) 28 | WHITE = (255, 255, 255) 29 | BLACK = (53, 59, 72) 30 | PURPLE = (130, 88, 159) 31 | ORANGE = (225, 95, 65) 32 | GREY = (128, 128, 128) 33 | TURQUOISE = (10, 189, 227) 34 | 35 | 36 | class Spot: 37 | def __init__(self, row, col, width, total_rows): 38 | self.row = row 39 | self.col = col 40 | self.x = row * width 41 | self.y = col * width 42 | self.color = WHITE 43 | self.neighbors = [] 44 | self.width = width 45 | self.total_rows = total_rows 46 | 47 | def get_pos(self): 48 | return self.row, self.col 49 | 50 | def is_closed(self): 51 | return self.color == RED 52 | 53 | def is_open(self): 54 | return self.color == GREEN 55 | 56 | def is_barrier(self): 57 | return self.color == BLACK 58 | 59 | def is_start(self): 60 | return self.color == ORANGE 61 | 62 | def is_end(self): 63 | return self.color == TURQUOISE 64 | 65 | def reset(self): 66 | self.color = WHITE 67 | 68 | def make_start(self): 69 | self.color = ORANGE 70 | 71 | def make_closed(self): 72 | self.color = RED 73 | 74 | def make_open(self): 75 | self.color = GREEN 76 | 77 | def make_barrier(self): 78 | self.color = BLACK 79 | 80 | def make_end(self): 81 | self.color = TURQUOISE 82 | 83 | def make_path(self): 84 | self.color = PURPLE 85 | 86 | def draw(self, win): 87 | pygame.draw.rect( 88 | win, self.color, (self.x, self.y, self.width, self.width)) 89 | 90 | def update_neighbors(self, grid): 91 | self.neighbors = [] 92 | # DOWN 93 | if self.row < self.total_rows - 1 and not grid[self.row + 1][self.col].is_barrier(): 94 | self.neighbors.append(grid[self.row + 1][self.col]) 95 | 96 | if self.row > 0 and not grid[self.row - 1][self.col].is_barrier(): # UP 97 | self.neighbors.append(grid[self.row - 1][self.col]) 98 | 99 | # RIGHT 100 | if self.col < self.total_rows - 1 and not grid[self.row][self.col + 1].is_barrier(): 101 | self.neighbors.append(grid[self.row][self.col + 1]) 102 | 103 | if self.col > 0 and not grid[self.row][self.col - 1].is_barrier(): # LEFT 104 | self.neighbors.append(grid[self.row][self.col - 1]) 105 | 106 | def __lt__(self, other): 107 | return False 108 | 109 | 110 | def h(p1, p2): 111 | x1, y1 = p1 112 | x2, y2 = p2 113 | return abs(x1 - x2) + abs(y1 - y2) # finding absolute distance 114 | 115 | 116 | def reconstruct_path(came_from, current, draw): 117 | while current in came_from: 118 | current = came_from[current] 119 | current.make_path() 120 | draw() 121 | 122 | 123 | def algorithm(draw, grid, start, end): 124 | count = 0 125 | open_set = PriorityQueue() 126 | open_set.put((0, count, start)) 127 | came_from = {} 128 | # keeps track of current shortest distance from start node to this node 129 | g_score = {spot: float("inf") for row in grid for spot in row} 130 | g_score[start] = 0 131 | # keeps track of predicted distance from this node to end node 132 | f_score = {spot: float("inf") for row in grid for spot in row} 133 | f_score[start] = h(start.get_pos(), end.get_pos()) 134 | 135 | open_set_hash = {start} 136 | 137 | while not open_set.empty(): 138 | for event in pygame.event.get(): 139 | if event.type == pygame.QUIT: 140 | pygame.quit() 141 | 142 | current = open_set.get()[2] 143 | open_set_hash.remove(current) 144 | 145 | if current == end: 146 | reconstruct_path(came_from, end, draw) 147 | end.make_end() 148 | return True 149 | 150 | for neighbor in current.neighbors: 151 | temp_g_score = g_score[current] + 1 152 | 153 | if temp_g_score < g_score[neighbor]: 154 | came_from[neighbor] = current 155 | g_score[neighbor] = temp_g_score 156 | f_score[neighbor] = temp_g_score + \ 157 | h(neighbor.get_pos(), end.get_pos()) 158 | if neighbor not in open_set_hash: 159 | count += 1 160 | open_set.put((f_score[neighbor], count, neighbor)) 161 | open_set_hash.add(neighbor) 162 | neighbor.make_open() 163 | 164 | draw() 165 | 166 | if current != start: 167 | current.make_closed() 168 | 169 | return False 170 | 171 | 172 | def make_grid(rows, width): 173 | grid = [] 174 | gap = width // rows # integer division: gap b/w each of these rows 175 | for i in range(rows): 176 | grid.append([]) 177 | for j in range(rows): 178 | spot = Spot(i, j, gap, rows) 179 | grid[i].append(spot) 180 | 181 | return grid 182 | 183 | 184 | def draw_grid(win, rows, width): 185 | gap = width // rows 186 | for i in range(rows): 187 | pygame.draw.line(win, GREY, (0, i * gap), 188 | (width, i * gap)) # horizontal line 189 | for j in range(rows): 190 | pygame.draw.line(win, GREY, (j * gap, 0), 191 | (j * gap, width)) # vertical lines 192 | 193 | 194 | def draw(win, grid, rows, width): 195 | win.fill(WHITE) 196 | 197 | for row in grid: 198 | for spot in row: 199 | spot.draw(win) 200 | 201 | draw_grid(win, rows, width) 202 | pygame.display.update() 203 | 204 | # getting mouse postiion 205 | 206 | 207 | def get_clicked_pos(pos, rows, width): 208 | gap = width // rows 209 | y, x = pos 210 | 211 | row = y // gap 212 | col = x // gap 213 | 214 | return row, col 215 | 216 | 217 | def main(win, width): 218 | ROWS = 50 219 | grid = make_grid(ROWS, width) 220 | 221 | start = None 222 | end = None 223 | 224 | run = True 225 | while run: 226 | draw(win, grid, ROWS, width) 227 | for event in pygame.event.get(): 228 | if event.type == pygame.QUIT: 229 | run = False 230 | 231 | if pygame.mouse.get_pressed()[0]: # LEFT MOUSE BUTTON: 0 232 | pos = pygame.mouse.get_pos() 233 | # actual spot in 2D list where mouse is clicked 234 | row, col = get_clicked_pos(pos, ROWS, width) 235 | spot = grid[row][col] 236 | 237 | # if start and end aren't done 238 | if not start and spot != end: 239 | start = spot 240 | start.make_start() 241 | 242 | # to avoid overlapping of start and end node 243 | elif not end and spot != start: 244 | end = spot 245 | end.make_end() 246 | 247 | elif spot != end and spot != start: 248 | spot.make_barrier() 249 | 250 | elif pygame.mouse.get_pressed()[2]: # RIGHT MOUSE BUTTON: 2 251 | pos = pygame.mouse.get_pos() 252 | row, col = get_clicked_pos(pos, ROWS, width) 253 | spot = grid[row][col] 254 | spot.reset() 255 | if spot == start: 256 | start = None 257 | elif spot == end: 258 | end = None 259 | 260 | if event.type == pygame.KEYDOWN: 261 | if event.key == pygame.K_SPACE and start and end: 262 | for row in grid: 263 | for spot in row: 264 | spot.update_neighbors(grid) 265 | 266 | algorithm(lambda: draw(win, grid, ROWS, width), 267 | grid, start, end) 268 | 269 | if event.key == pygame.K_c: 270 | start = None 271 | end = None 272 | grid = make_grid(ROWS, width) 273 | 274 | pygame.quit() 275 | 276 | 277 | main(WIN, WIDTH) 278 | -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/README.md: -------------------------------------------------------------------------------- 1 | #Basic Autopilot with tensorflow 2 | 3 | This is a variation of Sully Chen's autopilot model with a few changed hyperparameters. This model is originally based on a project made by the NVIDIA team ( link below ) 4 | 5 | Nvidia link: https://arxiv.org/pdf/1604.07316.pdf 6 | 7 | The model uses CNN with a 3 layer approach to convert images to the predicted steering angle 8 | 9 | #WARNING : This is a very rudimentary model that should not be used to automate the car in any case. This is only to better understand how CNN's work and how a basic self driving may work. 10 | 11 | If you would like to use your own test data to train the model, you may do so by changing the data path in model.py 12 | 13 | Links to data sets used by me are : 14 | 15 | 1)https://drive.google.com/open?id=1PZWa6H0i1PCH9zuYcIh5Ouk_p-9Gh58B 16 | 17 | 2)https://drive.google.com/file/d/1Ue4XohCOV5YXy57S_5tDfCVqzLr101M7/view?usp=sharing 18 | -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/driving_data.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import random 3 | import numpy as np 4 | 5 | xs = [] 6 | ys = [] 7 | 8 | #points to the end of the last batch 9 | train_batch_pointer = 0 10 | val_batch_pointer = 0 11 | 12 | #read data.txt 13 | with open("driving_dataset/data.txt") as f: 14 | for line in f: 15 | xs.append("driving_dataset/" + line.split()[0]) 16 | #the paper by Nvidia uses the inverse of the turning radius, 17 | #but steering wheel angle is proportional to the inverse of turning radius 18 | #so the steering wheel angle in radians is used as the output 19 | ys.append(float(line.split()[1]) * 3.14159265 / 180) 20 | 21 | #get number of images 22 | num_images = len(xs) 23 | 24 | #shuffle list of images 25 | c = list(zip(xs, ys)) 26 | random.shuffle(c) 27 | xs, ys = zip(*c) 28 | 29 | train_xs = xs[:int(len(xs) * 0.8)] 30 | train_ys = ys[:int(len(xs) * 0.8)] 31 | 32 | val_xs = xs[-int(len(xs) * 0.2):] 33 | val_ys = ys[-int(len(xs) * 0.2):] 34 | 35 | num_train_images = len(train_xs) 36 | num_val_images = len(val_xs) 37 | 38 | def LoadTrainBatch(batch_size): 39 | global train_batch_pointer 40 | x_out = [] 41 | y_out = [] 42 | for i in range(0, batch_size): 43 | x_out.append(cv2.resize(cv2.imread(train_xs[(train_batch_pointer + i) % num_train_images])[-150:], (200, 66)) / 255.0) 44 | y_out.append([train_ys[(train_batch_pointer + i) % num_train_images]]) 45 | train_batch_pointer += batch_size 46 | return x_out, y_out 47 | 48 | def LoadValBatch(batch_size): 49 | global val_batch_pointer 50 | x_out = [] 51 | y_out = [] 52 | for i in range(0, batch_size): 53 | x_out.append(cv2.resize(cv2.imread(val_xs[(val_batch_pointer + i) % num_val_images])[-150:], (200, 66)) / 255.0) 54 | y_out.append([val_ys[(val_batch_pointer + i) % num_val_images]]) 55 | val_batch_pointer += batch_size 56 | return x_out, y_out 57 | -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/model.py: -------------------------------------------------------------------------------- 1 | import tensorflow.compat.v1 as tf 2 | tf.disable_v2_behavior() 3 | import scipy 4 | 5 | def weight_variable(shape): 6 | initial = tf.truncated_normal(shape, stddev=0.1) 7 | return tf.Variable(initial) 8 | 9 | def bias_variable(shape): 10 | initial = tf.constant(0.1, shape=shape) 11 | return tf.Variable(initial) 12 | 13 | def conv2d(x, W, stride): 14 | return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='VALID') 15 | 16 | x = tf.placeholder(tf.float32, shape=[None, 66, 200, 3]) 17 | y_ = tf.placeholder(tf.float32, shape=[None, 1]) 18 | 19 | x_image = x 20 | 21 | #first convolutional layer 22 | W_conv1 = weight_variable([5, 5, 3, 24]) 23 | b_conv1 = bias_variable([24]) 24 | 25 | h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1, 2) + b_conv1) 26 | 27 | #second convolutional layer 28 | W_conv2 = weight_variable([5, 5, 24, 36]) 29 | b_conv2 = bias_variable([36]) 30 | 31 | h_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2, 2) + b_conv2) 32 | 33 | #third convolutional layer 34 | W_conv3 = weight_variable([5, 5, 36, 48]) 35 | b_conv3 = bias_variable([48]) 36 | 37 | h_conv3 = tf.nn.relu(conv2d(h_conv2, W_conv3, 2) + b_conv3) 38 | 39 | #fourth convolutional layer 40 | W_conv4 = weight_variable([3, 3, 48, 64]) 41 | b_conv4 = bias_variable([64]) 42 | 43 | h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4, 1) + b_conv4) 44 | 45 | #fifth convolutional layer 46 | W_conv5 = weight_variable([3, 3, 64, 64]) 47 | b_conv5 = bias_variable([64]) 48 | 49 | h_conv5 = tf.nn.relu(conv2d(h_conv4, W_conv5, 1) + b_conv5) 50 | 51 | #FCL 1 52 | W_fc1 = weight_variable([1152, 1164]) 53 | b_fc1 = bias_variable([1164]) 54 | 55 | h_conv5_flat = tf.reshape(h_conv5, [-1, 1152]) 56 | h_fc1 = tf.nn.relu(tf.matmul(h_conv5_flat, W_fc1) + b_fc1) 57 | 58 | keep_prob = tf.placeholder(tf.float32) 59 | h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 60 | 61 | #FCL 2 62 | W_fc2 = weight_variable([1164, 100]) 63 | b_fc2 = bias_variable([100]) 64 | 65 | h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 66 | 67 | h_fc2_drop = tf.nn.dropout(h_fc2, keep_prob) 68 | 69 | #FCL 3 70 | W_fc3 = weight_variable([100, 50]) 71 | b_fc3 = bias_variable([50]) 72 | 73 | h_fc3 = tf.nn.relu(tf.matmul(h_fc2_drop, W_fc3) + b_fc3) 74 | 75 | h_fc3_drop = tf.nn.dropout(h_fc3, keep_prob) 76 | 77 | #FCL 3 78 | W_fc4 = weight_variable([50, 10]) 79 | b_fc4 = bias_variable([10]) 80 | 81 | h_fc4 = tf.nn.relu(tf.matmul(h_fc3_drop, W_fc4) + b_fc4) 82 | 83 | h_fc4_drop = tf.nn.dropout(h_fc4, keep_prob) 84 | 85 | #Output 86 | W_fc5 = weight_variable([10, 1]) 87 | b_fc5 = bias_variable([1]) 88 | 89 | y = tf.multiply(tf.atan(tf.matmul(h_fc4_drop, W_fc5) + b_fc5), 2) #scale the atan output 90 | -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/run.py: -------------------------------------------------------------------------------- 1 | import tensorflow.compat.v1 as tf 2 | tf.disable_v2_behavior() 3 | import model 4 | import cv2 5 | from subprocess import call 6 | import os 7 | 8 | #check if on windows OS 9 | windows = False 10 | if os.name == 'nt': 11 | windows = True 12 | 13 | sess = tf.InteractiveSession() 14 | saver = tf.train.Saver() 15 | saver.restore(sess, "save/model.ckpt") 16 | 17 | img = cv2.imread('steering_wheel_image.jpg',0) 18 | rows,cols = img.shape 19 | 20 | smoothed_angle = 0 21 | 22 | cap = cv2.VideoCapture(0) 23 | while(cv2.waitKey(10) != ord('q')): 24 | ret, frame = cap.read() 25 | image = cv2.resize(frame, (200, 66)) / 255.0 26 | degrees = model.y.eval(feed_dict={model.x: [image], model.keep_prob: 1.0})[0][0] * 180 / 3.14159265 27 | if not windows: 28 | call("clear") 29 | print("Predicted steering angle: " + str(degrees) + " degrees") 30 | cv2.imshow('frame', frame) 31 | #make smooth angle transitions by turning the steering wheel based on the difference of the current angle 32 | #and the predicted angle 33 | smoothed_angle += 0.2 * pow(abs((degrees - smoothed_angle)), 2.0 / 3.0) * (degrees - smoothed_angle) / abs(degrees - smoothed_angle) 34 | M = cv2.getRotationMatrix2D((cols/2,rows/2),-smoothed_angle,1) 35 | dst = cv2.warpAffine(img,M,(cols,rows)) 36 | cv2.imshow("steering wheel", dst) 37 | 38 | cap.release() 39 | cv2.destroyAllWindows() 40 | -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/run_dataset.py: -------------------------------------------------------------------------------- 1 | import tensorflow.compat.v1 as tf 2 | tf.disable_v2_behavior() 3 | import model 4 | import cv2 5 | from subprocess import call 6 | import os 7 | 8 | #check if on windows OS 9 | windows = False 10 | if os.name == 'nt': 11 | windows = True 12 | 13 | sess = tf.InteractiveSession() 14 | saver = tf.train.Saver() 15 | saver.restore(sess, "save/model.ckpt") 16 | 17 | img = cv2.imread('steering_wheel_image.jpg',0) 18 | rows,cols = img.shape 19 | 20 | smoothed_angle = 0 21 | 22 | i = 0 23 | while(cv2.waitKey(10) != ord('q')): 24 | full_image = cv2.imread("driving_dataset/" + str(i) + ".jpg") 25 | image = cv2.resize(full_image[-150:], (200, 66)) / 255.0 26 | degrees = model.y.eval(feed_dict={model.x: [image], model.keep_prob: 1.0})[0][0] * 180.0 / 3.14159265 27 | if not windows: 28 | call("clear") 29 | print("Predicted steering angle: " + str(degrees) + " degrees") 30 | cv2.imshow("frame", full_image) 31 | #make smooth angle transitions by turning the steering wheel based on the difference of the current angle 32 | #and the predicted angle 33 | smoothed_angle += 0.2 * pow(abs((degrees - smoothed_angle)), 2.0 / 3.0) * (degrees - smoothed_angle) / abs(degrees - smoothed_angle) 34 | M = cv2.getRotationMatrix2D((cols/2,rows/2),-smoothed_angle,1) 35 | dst = cv2.warpAffine(img,M,(cols,rows)) 36 | cv2.imshow("steering wheel", dst) 37 | i += 1 38 | 39 | cv2.destroyAllWindows() 40 | -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/save/checkpoint: -------------------------------------------------------------------------------- 1 | model_checkpoint_path: "model.ckpt" 2 | all_model_checkpoint_paths: "model.ckpt" 3 | -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/save/model.ckpt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Basic Autopilot with Tensorflow/save/model.ckpt -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/save/model.ckpt.meta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Basic Autopilot with Tensorflow/save/model.ckpt.meta -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/steering_wheel_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Basic Autopilot with Tensorflow/steering_wheel_image.jpg -------------------------------------------------------------------------------- /Basic Autopilot with Tensorflow/train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import tensorflow.compat.v1 as tf 3 | tf.disable_v2_behavior() 4 | from tensorflow.core.protobuf import saver_pb2 5 | import driving_data 6 | import model 7 | 8 | LOGDIR = './save' 9 | 10 | sess = tf.InteractiveSession() 11 | 12 | L2NormConst = 0.001 13 | 14 | train_vars = tf.trainable_variables() 15 | 16 | loss = tf.reduce_mean(tf.square(tf.subtract(model.y_, model.y))) + tf.add_n([tf.nn.l2_loss(v) for v in train_vars]) * L2NormConst 17 | train_step = tf.train.AdamOptimizer(1e-4).minimize(loss) 18 | sess.run(tf.global_variables_initializer()) 19 | 20 | # create a summary to monitor cost tensor 21 | tf.summary.scalar("loss", loss) 22 | # merge all summaries into a single op 23 | merged_summary_op = tf.summary.merge_all() 24 | 25 | saver = tf.train.Saver(write_version = saver_pb2.SaverDef.V2) 26 | 27 | # op to write logs to Tensorboard 28 | logs_path = './logs' 29 | summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph()) 30 | 31 | epochs = 30 32 | batch_size = 100 33 | 34 | # train over the dataset about 30 times 35 | for epoch in range(epochs): 36 | for i in range(int(driving_data.num_images/batch_size)): 37 | xs, ys = driving_data.LoadTrainBatch(batch_size) 38 | train_step.run(feed_dict={model.x: xs, model.y_: ys, model.keep_prob: 0.8}) 39 | if i % 10 == 0: 40 | xs, ys = driving_data.LoadValBatch(batch_size) 41 | loss_value = loss.eval(feed_dict={model.x:xs, model.y_: ys, model.keep_prob: 1.0}) 42 | print("Epoch: %d, Step: %d, Loss: %g" % (epoch, epoch * batch_size + i, loss_value)) 43 | 44 | # write logs at every iteration 45 | summary = merged_summary_op.eval(feed_dict={model.x:xs, model.y_: ys, model.keep_prob: 1.0}) 46 | summary_writer.add_summary(summary, epoch * driving_data.num_images/batch_size + i) 47 | 48 | if i % batch_size == 0: 49 | if not os.path.exists(LOGDIR): 50 | os.makedirs(LOGDIR) 51 | checkpoint_path = os.path.join(LOGDIR, "model.ckpt") 52 | filename = saver.save(sess, checkpoint_path) 53 | print("Model saved in file: %s" % filename) 54 | 55 | print("Run the command line:\n" \ 56 | "--> tensorboard --logdir=./logs " \ 57 | "\nThen open http://0.0.0.0:6006/ into your web browser") 58 | -------------------------------------------------------------------------------- /CARTOONING-AN-IMAGE-USING-OPENCV-master/Cartoon_BIRD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/CARTOONING-AN-IMAGE-USING-OPENCV-master/Cartoon_BIRD.png -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Steps to contribute 🤩 2 | 3 | **1.** Fork [this](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022) repository. 4 | 5 | **2.** Clone your forked copy of the project. 6 | 7 | ``` 8 | git clone --depth 1 https://github.com//Hacktober2022.git 9 | ``` 10 | 11 | **3.** Navigate to the project directory :file_folder: . 12 | 13 | ``` 14 | cd Hacktober2022 15 | 16 | ``` 17 | 18 | **4.** Add a reference(remote) to the original repository. 19 | 20 | ``` 21 | git remote add upstream https://github.com/Encode-PDEU/AI-ML_Encode_HF2022 22 | ``` 23 | 24 | **5.** Check the remotes for this repository. 25 | ``` 26 | git remote -v 27 | ``` 28 | 29 | **6.** Always take a pull from the upstream repository to your master branch to keep it at par with the main project(updated repository). 30 | 31 | ``` 32 | git pull upstream master 33 | ``` 34 | 35 | **7.** Create a new branch. 36 | 37 | ``` 38 | git checkout -b 39 | ``` 40 | 41 | **8.** Perfom your desired changes to the code base. 42 | **9.** Track your changes:heavy_check_mark: . 43 | 44 | ``` 45 | git add . 46 | ``` 47 | 48 | **10.** Commit your changes . 49 | 50 | ``` 51 | git commit -m "Relevant message" 52 | ``` 53 | 54 | **11.** Push the committed changes in your feature branch to your remote repo. 55 | ``` 56 | git push -u origin 57 | ``` 58 | 59 | **12.** To create a pull request, click on `Compare and pull requests`. Please ensure you compare your feature branch to the desired branch of the repo you are suppose to make a PR to. 60 | 61 | **13.** Add appropriate title and description to your pull request explaining your changes and efforts done. 62 | 63 | **14.** Click on `Create Pull Request`. 64 | 65 | **15** Voila! You have made a PR to the awesome-developer-portfolio project. Sit back patiently and relax while the your PR is reviewed. 66 | 67 | In case of any help, please free to contact me via mail @papnejaanmol@gmail.com 68 | 69 | -------------------------------------------------------------------------------- /Dominent Color Extractor/images/photo1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Dominent Color Extractor/images/photo1.jpg -------------------------------------------------------------------------------- /Dominent Color Extractor/images/photo2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Dominent Color Extractor/images/photo2.jpg -------------------------------------------------------------------------------- /Dominent Color Extractor/images/photo3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Dominent Color Extractor/images/photo3.jpg -------------------------------------------------------------------------------- /Dominent Color Extractor/images/photo4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Dominent Color Extractor/images/photo4.jpg -------------------------------------------------------------------------------- /Dominent Color Extractor/images/photo5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Dominent Color Extractor/images/photo5.jpg -------------------------------------------------------------------------------- /Dominent Color Extractor/images/photo6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Dominent Color Extractor/images/photo6.jpg -------------------------------------------------------------------------------- /Face Recognition/face_classifier.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "trying-uncle", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "import pandas as pd\n", 11 | "import numpy as np\n", 12 | "import matplotlib.pyplot as plt\n", 13 | "import seaborn as sns\n", 14 | "%matplotlib inline\n", 15 | "from sklearn import datasets\n", 16 | "from sklearn import model_selection\n", 17 | "import cv2" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 2, 23 | "id": "apart-cornell", 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "cap = cv2.VideoCapture(0)\n", 28 | "face_cascade = cv2.CascadeClassifier(\"archive/haarcascade_frontalface_alt.xml\")\n", 29 | "\n", 30 | "\n", 31 | "skip = 0\n", 32 | "face_data = []\n", 33 | "dataset_path = './data/'\n", 34 | "offset = 10\n", 35 | "\n" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 3, 41 | "id": "electoral-investor", 42 | "metadata": {}, 43 | "outputs": [ 44 | { 45 | "name": "stdout", 46 | "output_type": "stream", 47 | "text": [ 48 | "Enter the name of the person : Priyanshu\n", 49 | "1\n", 50 | "2\n", 51 | "3\n", 52 | "4\n", 53 | "5\n", 54 | "6\n", 55 | "7\n", 56 | "8\n", 57 | "9\n", 58 | "10\n", 59 | "11\n", 60 | "12\n", 61 | "13\n", 62 | "14\n", 63 | "15\n", 64 | "16\n", 65 | "17\n", 66 | "18\n", 67 | "19\n", 68 | "20\n", 69 | "21\n", 70 | "22\n", 71 | "23\n", 72 | "24\n", 73 | "25\n", 74 | "26\n", 75 | "27\n", 76 | "28\n", 77 | "29\n", 78 | "30\n", 79 | "31\n", 80 | "32\n", 81 | "33\n", 82 | "34\n", 83 | "35\n", 84 | "36\n", 85 | "37\n", 86 | "38\n", 87 | "39\n", 88 | "40\n", 89 | "41\n", 90 | "42\n", 91 | "43\n", 92 | "44\n", 93 | "45\n", 94 | "46\n", 95 | "47\n", 96 | "48\n", 97 | "49\n", 98 | "50\n", 99 | "51\n", 100 | "52\n", 101 | "53\n", 102 | "54\n", 103 | "55\n", 104 | "56\n", 105 | "57\n", 106 | "58\n", 107 | "59\n", 108 | "60\n", 109 | "61\n", 110 | "62\n", 111 | "63\n", 112 | "64\n", 113 | "65\n", 114 | "66\n", 115 | "67\n", 116 | "68\n", 117 | "69\n", 118 | "70\n", 119 | "71\n", 120 | "72\n", 121 | "73\n", 122 | "74\n", 123 | "75\n", 124 | "76\n", 125 | "77\n", 126 | "78\n", 127 | "79\n", 128 | "80\n", 129 | "81\n", 130 | "82\n", 131 | "83\n", 132 | "84\n", 133 | "85\n", 134 | "86\n", 135 | "87\n", 136 | "88\n", 137 | "89\n", 138 | "90\n", 139 | "91\n", 140 | "92\n", 141 | "93\n", 142 | "94\n", 143 | "95\n", 144 | "96\n", 145 | "97\n", 146 | "98\n", 147 | "99\n", 148 | "100\n", 149 | "101\n", 150 | "102\n", 151 | "103\n", 152 | "104\n", 153 | "105\n", 154 | "106\n", 155 | "107\n", 156 | "108\n", 157 | "109\n", 158 | "110\n", 159 | "111\n", 160 | "112\n", 161 | "113\n", 162 | "114\n", 163 | "115\n", 164 | "116\n", 165 | "117\n", 166 | "118\n", 167 | "119\n", 168 | "120\n", 169 | "121\n", 170 | "122\n", 171 | "123\n", 172 | "124\n", 173 | "125\n", 174 | "126\n", 175 | "127\n", 176 | "128\n", 177 | "129\n", 178 | "130\n", 179 | "131\n", 180 | "132\n", 181 | "133\n", 182 | "134\n", 183 | "135\n", 184 | "136\n", 185 | "137\n", 186 | "138\n", 187 | "139\n", 188 | "140\n", 189 | "141\n", 190 | "142\n", 191 | "143\n", 192 | "144\n", 193 | "145\n", 194 | "146\n", 195 | "147\n", 196 | "148\n", 197 | "149\n", 198 | "150\n", 199 | "151\n", 200 | "152\n", 201 | "153\n", 202 | "154\n", 203 | "155\n", 204 | "156\n", 205 | "157\n", 206 | "158\n", 207 | "159\n", 208 | "160\n", 209 | "161\n", 210 | "162\n", 211 | "163\n", 212 | "164\n", 213 | "165\n", 214 | "166\n", 215 | "167\n", 216 | "168\n", 217 | "169\n", 218 | "170\n", 219 | "171\n", 220 | "172\n", 221 | "173\n", 222 | "174\n", 223 | "175\n", 224 | "176\n", 225 | "177\n", 226 | "178\n", 227 | "179\n", 228 | "180\n", 229 | "181\n", 230 | "182\n", 231 | "183\n", 232 | "184\n", 233 | "185\n", 234 | "186\n", 235 | "187\n", 236 | "188\n", 237 | "189\n", 238 | "190\n", 239 | "191\n", 240 | "192\n", 241 | "193\n", 242 | "194\n", 243 | "195\n", 244 | "196\n", 245 | "197\n", 246 | "198\n", 247 | "199\n", 248 | "200\n", 249 | "201\n", 250 | "202\n", 251 | "203\n", 252 | "204\n", 253 | "(204, 100, 100, 3)\n", 254 | "(204, 30000)\n", 255 | "data successfully saved at ./data/Priyanshu.npy\n" 256 | ] 257 | } 258 | ], 259 | "source": [ 260 | "\n", 261 | "file_name = input(\"Enter the name of the person : \")\n", 262 | "\n", 263 | "while True:\n", 264 | " ret,frame = cap.read()\n", 265 | " \n", 266 | " if(ret == False):\n", 267 | " continue\n", 268 | " \n", 269 | " gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) \n", 270 | " \n", 271 | " \n", 272 | " faces = face_cascade.detectMultiScale(frame, 1.3, 5)\n", 273 | " \n", 274 | " faces = sorted(faces,key=lambda f: f[2]* f[3])\n", 275 | " \n", 276 | " \n", 277 | " for face in faces[-1:]:\n", 278 | " x, y, w, h = face \n", 279 | " cv2.rectangle(frame,(x, y),(x + w,y +h),(255,0,0),2)\n", 280 | " \n", 281 | " #extract main face\n", 282 | " face_section = frame[ y-offset: y+h+offset, x-offset:x+ w+ offset]\n", 283 | " face_section = cv2.resize(face_section,(100, 100))\n", 284 | " \n", 285 | " skip += 1\n", 286 | " \n", 287 | " if(skip % 10 == 0):\n", 288 | " face_data.append(face_section)\n", 289 | " print(len(face_data))\n", 290 | " \n", 291 | " \n", 292 | " cv2.imshow(\"Cropped\", face_section) \n", 293 | " cv2.imshow(\"VIDEO FRAME\", frame)\n", 294 | " \n", 295 | " keypressed = cv2.waitKey(1) & 0xFF\n", 296 | " if(keypressed == ord('q')):\n", 297 | " break\n", 298 | " \n", 299 | "\n", 300 | "face_data = np.array(face_data)\n", 301 | "print(face_data.shape)\n", 302 | "face_data = face_data.reshape((face_data.shape[0],-1))\n", 303 | "print(face_data.shape)\n", 304 | "\n", 305 | "\n", 306 | "np.save(dataset_path + file_name + '.npy',face_data)\n", 307 | "print(\"data successfully saved at \" + dataset_path+file_name+'.npy')\n", 308 | "\n" 309 | ] 310 | } 311 | ], 312 | "metadata": { 313 | "kernelspec": { 314 | "display_name": "Python 3", 315 | "language": "python", 316 | "name": "python3" 317 | }, 318 | "language_info": { 319 | "codemirror_mode": { 320 | "name": "ipython", 321 | "version": 3 322 | }, 323 | "file_extension": ".py", 324 | "mimetype": "text/x-python", 325 | "name": "python", 326 | "nbconvert_exporter": "python", 327 | "pygments_lexer": "ipython3", 328 | "version": "3.9.1" 329 | } 330 | }, 331 | "nbformat": 4, 332 | "nbformat_minor": 5 333 | } 334 | -------------------------------------------------------------------------------- /Face Recognition/face_recognizer.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "economic-discovery", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "import pandas as pd\n", 11 | "import numpy as np\n", 12 | "import matplotlib.pyplot as plt\n", 13 | "import seaborn as sns\n", 14 | "%matplotlib inline\n", 15 | "from sklearn import datasets\n", 16 | "from sklearn import model_selection\n", 17 | "import cv2\n", 18 | "import os" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 2, 24 | "id": "amino-garden", 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "cap = cv2.VideoCapture(0)\n", 29 | "\n", 30 | "\n", 31 | "face_cascade = cv2.CascadeClassifier(\"archive/haarcascade_frontalface_alt.xml\")\n", 32 | "\n", 33 | "skip = 0\n", 34 | "dataset_path = './data/'\n", 35 | "\n", 36 | "face_data = []\n", 37 | "labels = []\n", 38 | "\n", 39 | "class_id = 0\n", 40 | "names = {} " 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 3, 46 | "id": "functional-reproduction", 47 | "metadata": {}, 48 | "outputs": [ 49 | { 50 | "name": "stdout", 51 | "output_type": "stream", 52 | "text": [ 53 | "Loaded Priyanshu.npy\n", 54 | "(36, 30000)\n", 55 | "(36, 1)\n", 56 | "(36, 30001)\n" 57 | ] 58 | } 59 | ], 60 | "source": [ 61 | "for fx in os.listdir(dataset_path):\n", 62 | " if fx.endswith('.npy'):\n", 63 | "\n", 64 | " names[class_id] = fx[:-4]\n", 65 | " print(\"Loaded \"+ fx)\n", 66 | " data_item = np.load(dataset_path+fx)\n", 67 | " face_data.append(data_item)\n", 68 | "\n", 69 | "\n", 70 | " target = class_id*np.ones((data_item.shape[0],))\n", 71 | " class_id += 1\n", 72 | " labels.append(target)\n", 73 | "\n", 74 | "face_dataset = np.concatenate(face_data,axis=0)\n", 75 | "face_labels = np.concatenate(labels,axis=0).reshape((-1,1))\n", 76 | "\n", 77 | "print(face_dataset.shape)\n", 78 | "print(face_labels.shape)\n", 79 | "\n", 80 | "trainset = np.concatenate((face_dataset,face_labels),axis=1)\n", 81 | "print(trainset.shape)" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": 4, 87 | "id": "sexual-luxury", 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "def distance(x1, x2):\n", 92 | " return np.sqrt(np.sum((x1 - x2)**2))" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": 5, 98 | "id": "crucial-threat", 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "def knn(train, test, k=5):\n", 103 | " dist = []\n", 104 | " \n", 105 | " for i in range(train.shape[0]):\n", 106 | " \n", 107 | " ix = train[i, :-1]\n", 108 | " iy = train[i, -1]\n", 109 | " \n", 110 | " d = distance(test, ix)\n", 111 | " dist.append([d, iy])\n", 112 | " \n", 113 | " dk = sorted(dist, key=lambda x: x[0])[:k]\n", 114 | " \n", 115 | " labels = np.array(dk)[:, -1]\n", 116 | " \n", 117 | " \n", 118 | " output = np.unique(labels, return_counts=True)\n", 119 | " \n", 120 | " index = np.argmax(output[1])\n", 121 | " return output[0][index]" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": null, 127 | "id": "original-inflation", 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 6, 135 | "id": "young-finding", 136 | "metadata": {}, 137 | "outputs": [], 138 | "source": [ 139 | "while True:\n", 140 | " ret ,frame = cap.read()\n", 141 | " \n", 142 | " if ret == False:\n", 143 | " continue\n", 144 | "\n", 145 | " faces = face_cascade.detectMultiScale(frame,1.3,5)\n", 146 | " \n", 147 | " if(len(faces)==0):\n", 148 | " continue\n", 149 | "\n", 150 | " for face in faces:\n", 151 | " x,y,w,h = face\n", 152 | "\n", 153 | " offset = 10\n", 154 | " \n", 155 | " face_section = frame[ y-offset: y+h+offset, x - offset: x+ w+ offset]\n", 156 | " face_section = cv2.resize(face_section,(100,100))\n", 157 | "\n", 158 | "\n", 159 | " out = knn(trainset,face_section.flatten())\n", 160 | "\n", 161 | "\n", 162 | " pred_name = names[int(out)]\n", 163 | " cv2.putText(frame, pred_name, (x,y-10) , cv2.FONT_HERSHEY_SIMPLEX,1,(255, 0, 0),2, cv2.LINE_AA)\n", 164 | " cv2.rectangle(frame,(x,y),(x+ w,y+ h),(0, 255, 255),2)\n", 165 | "\n", 166 | " cv2.imshow(\"Faces\",frame)\n", 167 | "\n", 168 | " key = cv2.waitKey(1) & 0xFF\n", 169 | " if key==ord('q'):\n", 170 | " break\n", 171 | "\n", 172 | "cap.release()\n", 173 | "cv2.destroyAllWindows()" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "id": "acute-spice", 180 | "metadata": {}, 181 | "outputs": [], 182 | "source": [] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "id": "actual-reasoning", 188 | "metadata": {}, 189 | "outputs": [], 190 | "source": [] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": null, 195 | "id": "furnished-sierra", 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": null, 203 | "id": "about-contrast", 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "id": "split-analysis", 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "id": "cathedral-passion", 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "id": "instructional-viewer", 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "id": "threaded-consciousness", 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "id": "black-invalid", 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "execution_count": null, 251 | "id": "distributed-least", 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "id": "attractive-jaguar", 260 | "metadata": {}, 261 | "outputs": [], 262 | "source": [] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "id": "indian-turtle", 268 | "metadata": {}, 269 | "outputs": [], 270 | "source": [] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": null, 275 | "id": "incorrect-david", 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": null, 283 | "id": "absolute-occasions", 284 | "metadata": {}, 285 | "outputs": [], 286 | "source": [] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": null, 291 | "id": "occasional-playlist", 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": null, 299 | "id": "dirty-morrison", 300 | "metadata": {}, 301 | "outputs": [], 302 | "source": [] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": null, 307 | "id": "subsequent-amount", 308 | "metadata": {}, 309 | "outputs": [], 310 | "source": [] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": null, 315 | "id": "burning-safety", 316 | "metadata": {}, 317 | "outputs": [], 318 | "source": [] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": null, 323 | "id": "fatty-charlotte", 324 | "metadata": {}, 325 | "outputs": [], 326 | "source": [] 327 | }, 328 | { 329 | "cell_type": "code", 330 | "execution_count": null, 331 | "id": "whole-juvenile", 332 | "metadata": {}, 333 | "outputs": [], 334 | "source": [] 335 | }, 336 | { 337 | "cell_type": "code", 338 | "execution_count": null, 339 | "id": "broadband-cancer", 340 | "metadata": {}, 341 | "outputs": [], 342 | "source": [] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "id": "spectacular-gallery", 348 | "metadata": {}, 349 | "outputs": [], 350 | "source": [] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": null, 355 | "id": "convenient-balance", 356 | "metadata": {}, 357 | "outputs": [], 358 | "source": [] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": null, 363 | "id": "immediate-circle", 364 | "metadata": {}, 365 | "outputs": [], 366 | "source": [] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": null, 371 | "id": "fitted-colony", 372 | "metadata": {}, 373 | "outputs": [], 374 | "source": [] 375 | }, 376 | { 377 | "cell_type": "code", 378 | "execution_count": null, 379 | "id": "electric-holiday", 380 | "metadata": {}, 381 | "outputs": [], 382 | "source": [] 383 | }, 384 | { 385 | "cell_type": "code", 386 | "execution_count": null, 387 | "id": "outside-lawrence", 388 | "metadata": {}, 389 | "outputs": [], 390 | "source": [] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": null, 395 | "id": "administrative-wayne", 396 | "metadata": {}, 397 | "outputs": [], 398 | "source": [] 399 | }, 400 | { 401 | "cell_type": "code", 402 | "execution_count": null, 403 | "id": "forward-moderator", 404 | "metadata": {}, 405 | "outputs": [], 406 | "source": [] 407 | } 408 | ], 409 | "metadata": { 410 | "kernelspec": { 411 | "display_name": "Python 3", 412 | "language": "python", 413 | "name": "python3" 414 | }, 415 | "language_info": { 416 | "codemirror_mode": { 417 | "name": "ipython", 418 | "version": 3 419 | }, 420 | "file_extension": ".py", 421 | "mimetype": "text/x-python", 422 | "name": "python", 423 | "nbconvert_exporter": "python", 424 | "pygments_lexer": "ipython3", 425 | "version": "3.9.1" 426 | } 427 | }, 428 | "nbformat": 4, 429 | "nbformat_minor": 5 430 | } 431 | -------------------------------------------------------------------------------- /Face-Recognition-cum-Attendance/Dataset/Bill Gates.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Face-Recognition-cum-Attendance/Dataset/Bill Gates.jpg -------------------------------------------------------------------------------- /Face-Recognition-cum-Attendance/Dataset/Edward Snowden.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Face-Recognition-cum-Attendance/Dataset/Edward Snowden.jpg -------------------------------------------------------------------------------- /Face-Recognition-cum-Attendance/Dataset/Elon Musk.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Face-Recognition-cum-Attendance/Dataset/Elon Musk.jpg -------------------------------------------------------------------------------- /Face-Recognition-cum-Attendance/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Kunal Kumar Sahoo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Face-Recognition-cum-Attendance/README.md: -------------------------------------------------------------------------------- 1 | # Face-Recognition-cum-Attendance 2 | This is a Python3 based project where I have implemented the HOG method for Face detection and with the help of dlib library created an attendance system. 3 | 4 | To install the requirements use the foollowinng command: 5 | pip/pip3 install -r requirements.txt 6 | 7 | If any problems faced during installation of dlib library, refer to this page: 8 | https://gist.github.com/ageitgey/629d75c1baac34dfa5ca2a1928a7aeaf 9 | 10 | ## How to Contribute? 11 | 12 | - Take Existing Issues or create your own Issues! 13 | - Get Assigned with Issues 14 | - Fork the Repo, then Clone forked repo. 15 | - Create a Pull Request. 16 | - Add Screenshots/deployed link in your project repo README.md 17 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 18 | 19 | 20 | ## HELP US OUT BY STARRING THIS REPOSITORY -------------------------------------------------------------------------------- /Face-Recognition-cum-Attendance/attendance-project.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import face_recognition 4 | import os 5 | from datetime import datetime 6 | 7 | path = "Dataset" 8 | images = [] 9 | names = [] 10 | myList = os.listdir(path) 11 | # print(myList) 12 | 13 | for name in myList: 14 | currentImg = cv2.imread(f"{path}/{name}") 15 | images.append(currentImg) 16 | names.append(os.path.splitext(name)[0]) 17 | # print(names) 18 | 19 | 20 | def findEncodings(images): 21 | encodeList = [] 22 | for img in images: 23 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 24 | encode = face_recognition.face_encodings(img)[0] 25 | encodeList.append(encode) 26 | 27 | return encodeList 28 | 29 | 30 | def markAttendance(name): 31 | with open('attendance.csv', 'r+') as f: 32 | myDataList = f.readlines() 33 | # print(myDataList) 34 | nameList, timeList = [], [] 35 | for line in myDataList: 36 | entry = line.split(',') 37 | nameList.append(entry[0]) 38 | 39 | if name not in nameList: 40 | now = datetime.now() 41 | dtString = now.strftime("%H:%M:%S") 42 | f.writelines(f"\n{name}, {dtString}") 43 | 44 | 45 | if __name__ == "__main__": 46 | encodeListForKnownFaces = findEncodings(images) 47 | # print(len(encodeListForKnownFaces)) 48 | print("Encoding completed") 49 | 50 | cap = cv2.VideoCapture(2) 51 | while True: 52 | success, img = cap.read() 53 | imgSmall = cv2.resize(img, (0, 0), None, 0.25, 0.25) 54 | imgSmall = cv2.cvtColor(imgSmall, cv2.COLOR_BGR2RGB) 55 | 56 | facesInCurrentFrame = face_recognition.face_locations(imgSmall) 57 | encodesCurrentFrame = face_recognition.face_encodings(imgSmall, facesInCurrentFrame) 58 | 59 | for encodeFace, faceLocation in zip(encodesCurrentFrame, facesInCurrentFrame): 60 | matches = face_recognition.compare_faces(encodeListForKnownFaces, encodeFace) 61 | faceDistance = face_recognition.face_distance(encodeListForKnownFaces, encodeFace) 62 | # print(faceDistance) 63 | matchIndex = np.argmin(faceDistance) 64 | 65 | if matches[matchIndex]: 66 | name = names[matchIndex].upper() 67 | print(name) 68 | y1, x1, y2, x2 = faceLocation 69 | y1, x1, y2, x2 = y1*4, x1*4, y2*4, x2*4 70 | cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2) 71 | cv2.rectangle(img, (x1, y2-35), (x2, y2), (0, 255, 0), cv2.FILLED) 72 | cv2.putText(img, name, (x1+6, y2-6), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) 73 | markAttendance(name) 74 | 75 | else: 76 | print("Not identified") 77 | cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2) 78 | cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 0, 255), cv2.FILLED) 79 | cv2.putText(img, "Person is unknown", 80 | (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) 81 | 82 | cv2.imshow("Camera feed", img) 83 | if cv2.waitKey(1) & 0xFF == ord('q'): 84 | break 85 | 86 | 87 | # faceLocTest = face_recognition.face_locations(imgTest)[0] 88 | # encodeTest = face_recognition.face_encodings(imgTest)[0] 89 | # cv2.rectangle(imgTest, (faceLocTest[3], faceLocTest[0]), (faceLocTest[1], faceLocTest[2]), (0, 0, 255), 5) 90 | # 91 | # results = face_recognition.compare_faces([encodeElon], encodeTest) 92 | # faceDis = face_recognition.face_distance([encodeElon], encodeTest) 93 | # print(results, faceDis) 94 | # cv2.putText(imgTest, f"{results} {round(faceDis[0], 2)}", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) -------------------------------------------------------------------------------- /Face-Recognition-cum-Attendance/requirements.txt: -------------------------------------------------------------------------------- 1 | dlib~=19.22.99 2 | numpy~=1.20.3 3 | setuptools~=52.0.0 4 | opencv-python~=4.5.2.52 -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/Readme.md: -------------------------------------------------------------------------------- 1 | #Basic hand gesture detector with mediapipe and tensorflow 2 | 3 | This project is based on detecting a few simple hand gesture such as 'Stop','Rock and roll','Thumbs up','Thumbs down' and so on 4 | 5 | Unfortunately, as very few conv layers were used, the model is not quite accurate, but with the addition of 2-3 conv layers and some more training, the model can be expanded to applications such as ASL or even gestures for the device to act upon. 6 | 7 | This model was pre-trained and may be retrained using new user data 8 | 9 | ![Thumbs up](./images/thumbs_up.png "Thumbs up") 10 | 11 | ![Thumbs down](./images/thumbs_down.png "Thumbs down") 12 | 13 | ![rock](./images/rock.png "Rock") 14 | 15 | ![Fist](./images/fist.png "Fist") 16 | -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/data.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/data.pickle -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/gesture.names: -------------------------------------------------------------------------------- 1 | okay 2 | peace 3 | thumbs up 4 | thumbs down 5 | call me 6 | stop 7 | rock 8 | live long 9 | fist 10 | smile -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/images/fist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/images/fist.png -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/images/rock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/images/rock.png -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/images/thumbs_down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/images/thumbs_down.png -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/images/thumbs_up.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/images/thumbs_up.png -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/main.py: -------------------------------------------------------------------------------- 1 | # TechVidvan hand Gesture Recognizer 2 | 3 | # import necessary packages 4 | import cv2 5 | import numpy as np 6 | import mediapipe as mp 7 | import tensorflow as tf 8 | from tensorflow import keras 9 | from keras.models import load_model 10 | 11 | # initialize mediapipe 12 | mpHands = mp.solutions.hands 13 | hands = mpHands.Hands(max_num_hands=1, min_detection_confidence=0.7) 14 | mpDraw = mp.solutions.drawing_utils 15 | 16 | # Load the gesture recognizer model 17 | model = load_model('Hand gesture detection with tensorflow\mp_hand_gesture') 18 | 19 | # Load class names 20 | f = open('Hand gesture detection with tensorflow\gesture.names', 'r') 21 | classNames = f.read().split('\n') 22 | f.close() 23 | print(classNames) 24 | 25 | 26 | # Initialize the webcam 27 | cap = cv2.VideoCapture(0) 28 | 29 | while True: 30 | # Read each frame from the webcam 31 | _, frame = cap.read() 32 | 33 | x, y, c = frame.shape 34 | 35 | # Flip the frame vertically 36 | frame = cv2.flip(frame, 1) 37 | framergb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 38 | 39 | # Get hand landmark prediction 40 | result = hands.process(framergb) 41 | 42 | # print(result) 43 | 44 | className = '' 45 | 46 | # post process the result 47 | if result.multi_hand_landmarks: 48 | landmarks = [] 49 | for handslms in result.multi_hand_landmarks: 50 | for lm in handslms.landmark: 51 | # print(id, lm) 52 | lmx = int(lm.x * x) 53 | lmy = int(lm.y * y) 54 | 55 | landmarks.append([lmx, lmy]) 56 | 57 | # Drawing landmarks on frames 58 | mpDraw.draw_landmarks(frame, handslms, mpHands.HAND_CONNECTIONS) 59 | 60 | # Predict gesture 61 | prediction = model.predict([landmarks]) 62 | # print(prediction) 63 | classID = np.argmax(prediction) 64 | className = classNames[classID] 65 | 66 | # show the prediction on the frame 67 | cv2.putText(frame, className, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 68 | 1, (0, 0, 255), 2, cv2.LINE_AA) 69 | 70 | # Show the final output 71 | cv2.imshow("Output", frame) 72 | 73 | if cv2.waitKey(1) == ord('q'): 74 | break 75 | 76 | # release the webcam and destroy all active windows 77 | cap.release() 78 | 79 | cv2.destroyAllWindows() 80 | -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/mp_hand_gesture/keras_metadata.pb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/mp_hand_gesture/keras_metadata.pb -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/mp_hand_gesture/saved_model.pb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/mp_hand_gesture/saved_model.pb -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/mp_hand_gesture/variables/variables.data-00000-of-00001: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/mp_hand_gesture/variables/variables.data-00000-of-00001 -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/mp_hand_gesture/variables/variables.index: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hand gesture detection with tensorflow/mp_hand_gesture/variables/variables.index -------------------------------------------------------------------------------- /Hand gesture detection with tensorflow/requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python~=4.6.0.66 2 | numpy~=1.20.1 3 | tensorflow~=2.10 -------------------------------------------------------------------------------- /Hangman/README.md: -------------------------------------------------------------------------------- 1 | # Hangman 2 | 3 | ## How to Contribute? 4 | 5 | - Take Existing Issues or create your own Issues! 6 | - Get Assigned with Issues 7 | - Fork the Repo, then Clone forked repo. 8 | - Create a Pull Request. 9 | - Add Screenshots/deployed link in your project repo README.md 10 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 11 | 12 | 13 | ## HELP US OUT BY STARRING THIS REPOSITORY -------------------------------------------------------------------------------- /Hangman/__pycache__/hangman_art.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hangman/__pycache__/hangman_art.cpython-310.pyc -------------------------------------------------------------------------------- /Hangman/__pycache__/hangman_words.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Hangman/__pycache__/hangman_words.cpython-310.pyc -------------------------------------------------------------------------------- /Hangman/hangman_art.py: -------------------------------------------------------------------------------- 1 | stages = [''' 2 | +---+ 3 | | | 4 | O | 5 | /|\ | 6 | / \ | 7 | | 8 | ========= 9 | ''', ''' 10 | +---+ 11 | | | 12 | O | 13 | /|\ | 14 | / | 15 | | 16 | ========= 17 | ''', ''' 18 | +---+ 19 | | | 20 | O | 21 | /|\ | 22 | | 23 | | 24 | ========= 25 | ''', ''' 26 | +---+ 27 | | | 28 | O | 29 | /| | 30 | | 31 | | 32 | =========''', ''' 33 | +---+ 34 | | | 35 | O | 36 | | | 37 | | 38 | | 39 | ========= 40 | ''', ''' 41 | +---+ 42 | | | 43 | O | 44 | | 45 | | 46 | | 47 | ========= 48 | ''', ''' 49 | +---+ 50 | | | 51 | | 52 | | 53 | | 54 | | 55 | ========= 56 | '''] 57 | 58 | logo = ''' 59 | _ 60 | | | 61 | | |__ __ _ _ __ __ _ _ __ ___ __ _ _ __ 62 | | '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ 63 | | | | | (_| | | | | (_| | | | | | | (_| | | | | 64 | |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| 65 | __/ | 66 | |___/ ''' 67 | 68 | 69 | -------------------------------------------------------------------------------- /Hangman/hangman_words.py: -------------------------------------------------------------------------------- 1 | word_list = [ 2 | 'abruptly', 3 | 'absurd', 4 | 'abyss', 5 | 'affix', 6 | 'askew', 7 | 'avenue', 8 | 'awkward', 9 | 'axiom', 10 | 'azure', 11 | 'bagpipes', 12 | 'bandwagon', 13 | 'banjo', 14 | 'bayou', 15 | 'beekeeper', 16 | 'bikini', 17 | 'blitz', 18 | 'blizzard', 19 | 'boggle', 20 | 'bookworm', 21 | 'boxcar', 22 | 'boxful', 23 | 'buckaroo', 24 | 'buffalo', 25 | 'buffoon', 26 | 'buxom', 27 | 'buzzard', 28 | 'buzzing', 29 | 'buzzwords', 30 | 'caliph', 31 | 'cobweb', 32 | 'cockiness', 33 | 'croquet', 34 | 'crypt', 35 | 'curacao', 36 | 'cycle', 37 | 'daiquiri', 38 | 'dirndl', 39 | 'disavow', 40 | 'dizzying', 41 | 'duplex', 42 | 'dwarves', 43 | 'embezzle', 44 | 'equip', 45 | 'espionage', 46 | 'euouae', 47 | 'exodus', 48 | 'faking', 49 | 'fishhook', 50 | 'fixable', 51 | 'fjord', 52 | 'flapjack', 53 | 'flopping', 54 | 'fluffiness', 55 | 'flyby', 56 | 'foxglove', 57 | 'frazzled', 58 | 'frizzled', 59 | 'fuchsia', 60 | 'funny', 61 | 'gabby', 62 | 'galaxy', 63 | 'galvanize', 64 | 'gazebo', 65 | 'giaour', 66 | 'gizmo', 67 | 'glowworm', 68 | 'glyph', 69 | 'gnarly', 70 | 'gnostic', 71 | 'gossip', 72 | 'grogginess', 73 | 'haiku', 74 | 'haphazard', 75 | 'hyphen', 76 | 'iatrogenic', 77 | 'icebox', 78 | 'injury', 79 | 'ivory', 80 | 'ivy', 81 | 'jackpot', 82 | 'jaundice', 83 | 'jawbreaker', 84 | 'jaywalk', 85 | 'jazziest', 86 | 'jazzy', 87 | 'jelly', 88 | 'jigsaw', 89 | 'jinx', 90 | 'jiujitsu', 91 | 'jockey', 92 | 'jogging', 93 | 'joking', 94 | 'jovial', 95 | 'joyful', 96 | 'juicy', 97 | 'jukebox', 98 | 'jumbo', 99 | 'kayak', 100 | 'kazoo', 101 | 'keyhole', 102 | 'khaki', 103 | 'kilobyte', 104 | 'kiosk', 105 | 'kitsch', 106 | 'kiwifruit', 107 | 'klutz', 108 | 'knapsack', 109 | 'larynx', 110 | 'lengths', 111 | 'lucky', 112 | 'luxury', 113 | 'lymph', 114 | 'marquis', 115 | 'matrix', 116 | 'megahertz', 117 | 'microwave', 118 | 'mnemonic', 119 | 'mystify', 120 | 'naphtha', 121 | 'nightclub', 122 | 'nowadays', 123 | 'numbskull', 124 | 'nymph', 125 | 'onyx', 126 | 'ovary', 127 | 'oxidize', 128 | 'oxygen', 129 | 'pajama', 130 | 'peekaboo', 131 | 'phlegm', 132 | 'pixel', 133 | 'pizazz', 134 | 'pneumonia', 135 | 'polka', 136 | 'pshaw', 137 | 'psyche', 138 | 'puppy', 139 | 'puzzling', 140 | 'quartz', 141 | 'queue', 142 | 'quips', 143 | 'quixotic', 144 | 'quiz', 145 | 'quizzes', 146 | 'quorum', 147 | 'razzmatazz', 148 | 'rhubarb', 149 | 'rhythm', 150 | 'rickshaw', 151 | 'schnapps', 152 | 'scratch', 153 | 'shiv', 154 | 'snazzy', 155 | 'sphinx', 156 | 'spritz', 157 | 'squawk', 158 | 'staff', 159 | 'strength', 160 | 'strengths', 161 | 'stretch', 162 | 'stronghold', 163 | 'stymied', 164 | 'subway', 165 | 'swivel', 166 | 'syndrome', 167 | 'thriftless', 168 | 'thumbscrew', 169 | 'topaz', 170 | 'transcript', 171 | 'transgress', 172 | 'transplant', 173 | 'triphthong', 174 | 'twelfth', 175 | 'twelfths', 176 | 'unknown', 177 | 'unworthy', 178 | 'unzip', 179 | 'uptown', 180 | 'vaporize', 181 | 'vixen', 182 | 'vodka', 183 | 'voodoo', 184 | 'vortex', 185 | 'voyeurism', 186 | 'walkway', 187 | 'waltz', 188 | 'wave', 189 | 'wavy', 190 | 'waxy', 191 | 'wellspring', 192 | 'wheezy', 193 | 'whiskey', 194 | 'whizzing', 195 | 'whomever', 196 | 'wimpy', 197 | 'witchcraft', 198 | 'wizard', 199 | 'woozy', 200 | 'wristwatch', 201 | 'wyvern', 202 | 'xylophone', 203 | 'yachtsman', 204 | 'yippee', 205 | 'yoked', 206 | 'youthful', 207 | 'yummy', 208 | 'zephyr', 209 | 'zigzag', 210 | 'zigzagging', 211 | 'zilch', 212 | 'zipper', 213 | 'zodiac', 214 | 'zombie', 215 | ] -------------------------------------------------------------------------------- /Hangman/main.py: -------------------------------------------------------------------------------- 1 | import random 2 | from hangman_art import stages, logo 3 | from hangman_words import word_list 4 | 5 | 6 | print(logo) 7 | game_is_finished = False 8 | lives = len(stages) - 1 9 | 10 | chosen_word = random.choice(word_list) 11 | word_length = len(chosen_word) 12 | 13 | display = [] 14 | for _ in range(word_length): 15 | display += "_" 16 | 17 | while not game_is_finished: 18 | guess = input("Guess a letter: ").lower() 19 | 20 | #Use the clear() function imported from replit to clear the output between guesses. 21 | 22 | 23 | if guess in display: 24 | print(f"You've already guessed {guess}") 25 | 26 | for position in range(word_length): 27 | letter = chosen_word[position] 28 | if letter == guess: 29 | display[position] = letter 30 | print(f"{' '.join(display)}") 31 | 32 | if guess not in chosen_word: 33 | print(f"You guessed {guess}, that's not in the word. You lose a life.") 34 | lives -= 1 35 | if lives == 0: 36 | game_is_finished = True 37 | print("You lose.") 38 | 39 | if not "_" in display: 40 | game_is_finished = True 41 | print("You win.") 42 | 43 | print(stages[lives]) -------------------------------------------------------------------------------- /ML-WebApp/.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | -------------------------------------------------------------------------------- /ML-WebApp/README.md: -------------------------------------------------------------------------------- 1 | # ML-WebApp 2 | 3 | ## How to Contribute? 4 | 5 | - Take Existing Issues or create your own Issues! 6 | - Get Assigned with Issues 7 | - Fork the Repo, then Clone forked repo. 8 | - Create a Pull Request. 9 | - Add Screenshots/deployed link in your project repo README.md 10 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 11 | 12 | 13 | ## HELP US OUT BY STARRING THIS REPOSITORY -------------------------------------------------------------------------------- /ML-WebApp/requirements.txt: -------------------------------------------------------------------------------- 1 | argon2-cffi==21.3.0 2 | argon2-cffi-bindings==21.2.0 3 | asttokens==2.0.8 4 | attrs==22.1.0 5 | backcall==0.2.0 6 | beautifulsoup4==4.11.1 7 | bleach==5.0.1 8 | certifi==2022.9.24 9 | cffi==1.15.1 10 | charset-normalizer==2.1.1 11 | click==8.1.3 12 | contourpy==1.0.5 13 | cycler==0.11.0 14 | debugpy==1.6.3 15 | decorator==5.1.1 16 | defusedxml==0.7.1 17 | entrypoints==0.4 18 | executing==1.1.0 19 | fastjsonschema==2.16.2 20 | Flask==2.2.2 21 | fonttools==4.37.4 22 | idna==3.4 23 | ipykernel==6.16.0 24 | ipython==8.5.0 25 | ipython-genutils==0.2.0 26 | ipywidgets==8.0.2 27 | itsdangerous==2.1.2 28 | jedi==0.18.1 29 | Jinja2==3.1.2 30 | joblib==1.2.0 31 | jsonschema==4.16.0 32 | jupyter==1.0.0 33 | jupyter-console==6.4.4 34 | jupyter-core==4.11.1 35 | jupyter_client==7.3.5 36 | jupyterlab-pygments==0.2.2 37 | jupyterlab-widgets==3.0.3 38 | kaleido==0.2.1 39 | kiwisolver==1.4.4 40 | MarkupSafe==2.1.1 41 | matplotlib==3.6.0 42 | matplotlib-inline==0.1.6 43 | mistune==2.0.4 44 | nbclient==0.7.0 45 | nbconvert==7.2.1 46 | nbformat==5.6.1 47 | nest-asyncio==1.5.6 48 | notebook==6.4.12 49 | numpy==1.23.3 50 | packaging==21.3 51 | pandas==1.5.0 52 | pandocfilters==1.5.0 53 | parso==0.8.3 54 | pexpect==4.8.0 55 | pickleshare==0.7.5 56 | Pillow==9.2.0 57 | plotly==5.10.0 58 | prometheus-client==0.14.1 59 | prompt-toolkit==3.0.31 60 | psutil==5.9.2 61 | ptyprocess==0.7.0 62 | pure-eval==0.2.2 63 | pycparser==2.21 64 | Pygments==2.13.0 65 | pyparsing==3.0.9 66 | pyrsistent==0.18.1 67 | python-dateutil==2.8.2 68 | pytz==2022.4 69 | pyzmq==24.0.1 70 | qtconsole==5.3.2 71 | QtPy==2.2.1 72 | requests==2.28.1 73 | scikit-learn==1.1.2 74 | scipy==1.9.1 75 | Send2Trash==1.8.0 76 | six==1.16.0 77 | soupsieve==2.3.2.post1 78 | stack-data==0.5.1 79 | tenacity==8.1.0 80 | terminado==0.16.0 81 | threadpoolctl==3.1.0 82 | tinycss2==1.1.1 83 | tornado==6.2 84 | traitlets==5.4.0 85 | urllib3==1.26.12 86 | wcwidth==0.2.5 87 | webencodings==0.5.1 88 | Werkzeug==2.2.2 89 | widgetsnbextension==4.0.3 90 | -------------------------------------------------------------------------------- /ML-WebApp/src/AgesAndHeights.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/ML-WebApp/src/AgesAndHeights.pkl -------------------------------------------------------------------------------- /ML-WebApp/src/app.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from joblib import load 3 | import pandas as pd 4 | 5 | import plotly.express as px 6 | import plotly.graph_objects as go 7 | 8 | import uuid 9 | 10 | from flask import Flask, render_template, request 11 | app = Flask(__name__) 12 | 13 | @app.route('/', methods=['GET', 'POST']) 14 | def index(): 15 | request_type_str = request.method 16 | if request_type_str == 'GET': 17 | return render_template('index.html', href='static/base.svg') 18 | else: 19 | text = request.form['text'] 20 | random_str = uuid.uuid4().hex 21 | path = f'static/{random_str}.svg' 22 | make_picture('AgesAndHeights.pkl', load('model.joblib'), floats_string_to_np_arr(text), path) 23 | return render_template('index.html', href=path) 24 | 25 | def make_picture(training_data_filename, model, new_input_arr, output_file): 26 | # assert training_data_filename[-1:-5] == '.pkl' 27 | data = pd.read_pickle(training_data_filename) 28 | ages = data['Age'] 29 | data = data[ages > 0] 30 | ages = data['Age'] 31 | heights = data['Height'] 32 | 33 | x_new = np.array([range(19)]).reshape(19, 1) 34 | preds = model.predict(x_new) 35 | 36 | fig = px.scatter(x=ages, y=heights, title='Heights vs Age of people', labels={'x':'Age (years)', 'y':'Height (inches)'}) 37 | fig.add_trace(go.Scatter(x=x_new.reshape(x_new.shape[0]), y=preds, mode='lines', name='Model')) 38 | 39 | new_preds = model.predict(new_input_arr) 40 | fig.add_trace(go.Scatter(x=new_input_arr.reshape(len(new_input_arr)), y=new_preds, mode='markers', name='New Outputs', marker=dict(color='purple', size=20, line=dict(color='purple', width=2)))) 41 | fig.write_image(output_file, width=800, engine='kaleido') 42 | fig.show() 43 | 44 | def floats_string_to_np_arr(floats_str): 45 | def is_float(s): 46 | try: 47 | float(s) 48 | return True 49 | except: 50 | return False 51 | floats = [float(x) for x in floats_str.split(',') if is_float(x)] 52 | return np.array(floats).reshape(len(floats), 1) 53 | 54 | if __name__ == '__main__': 55 | app.run( 56 | host='127.0.0.1', 57 | port=2022, 58 | debug=False 59 | ) -------------------------------------------------------------------------------- /ML-WebApp/src/model.joblib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/ML-WebApp/src/model.joblib -------------------------------------------------------------------------------- /ML-WebApp/src/templates/index.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | 6 | 7 |
8 |
-------------------------------------------------------------------------------- /MNIST number detector/images/MNIST-Matrix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/MNIST number detector/images/MNIST-Matrix.png -------------------------------------------------------------------------------- /MNIST number detector/images/relu.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/MNIST number detector/images/relu.jpeg -------------------------------------------------------------------------------- /MNIST number detector/main.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "b82df592", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "import numpy as np\n", 11 | "from tensorflow import keras\n", 12 | "from tensorflow.keras import layers" 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": 2, 18 | "id": "7b16e89a", 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "num_classes = 10 # Output layer will be in the form of a number in [0,9]\n", 23 | "input_shape = (28, 28, 1) # Input image is in a 28 X 28 pixel format\n", 24 | "\n", 25 | "# Loading test/train data\n", 26 | "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "id": "241cc885", 32 | "metadata": {}, 33 | "source": [ 34 | "We are importing an image where each pixel is in grayscale.\n", 35 | "\n", 36 | "This is represented in a range of 0 to 255, 0 being Black and 255 being white\n", 37 | "\n", 38 | "For easier representation, we divide each element by 255 to scale down to [0,1]\n", 39 | "\n", 40 | "![Matrix visualised](./images/MNIST-Matrix.png \"28x28 Matrix with scaled down integers\")" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 3, 46 | "id": "e4ba69ed", 47 | "metadata": {}, 48 | "outputs": [ 49 | { 50 | "name": "stdout", 51 | "output_type": "stream", 52 | "text": [ 53 | "x_train shape: (60000, 28, 28, 1)\n", 54 | "60000 train samples\n", 55 | "10000 test samples\n" 56 | ] 57 | } 58 | ], 59 | "source": [ 60 | "# To ensure shape of matrix is 28 X 28\n", 61 | "x_train = np.expand_dims(x_train, -1)\n", 62 | "x_test = np.expand_dims(x_test, -1)\n", 63 | "\n", 64 | "print(\"x_train shape:\", x_train.shape)\n", 65 | "print(x_train.shape[0], \"train samples\")\n", 66 | "print(x_test.shape[0], \"test samples\")\n", 67 | "\n", 68 | "y_train = keras.utils.to_categorical(y_train, num_classes)\n", 69 | "y_test = keras.utils.to_categorical(y_test, num_classes)" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 4, 75 | "id": "9c81d894", 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "# Building the model\n", 80 | "model = keras.Sequential(\n", 81 | " [\n", 82 | " keras.Input(shape=input_shape), # setting input shape as 28 X 28 X 1 (2d input)\n", 83 | " layers.Conv2D(32, kernel_size=(3, 3), activation=\"relu\"),\n", 84 | " layers.MaxPooling2D(pool_size=(2, 2)),\n", 85 | " layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\"),\n", 86 | " layers.MaxPooling2D(pool_size=(2, 2)),\n", 87 | " layers.Flatten(),\n", 88 | " layers.Dropout(0.5),\n", 89 | " layers.Dense(num_classes, activation=\"softmax\"),\n", 90 | " ]\n", 91 | ")" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "id": "928ddaae", 97 | "metadata": {}, 98 | "source": [ 99 | "Explaining the previous cell\n", 100 | "\n", 101 | "First we define the input size to the model.\n", 102 | "\n", 103 | "Then we define the kernel size and the activation function to be used, while relu is most used, you may also use tanh\n", 104 | "\n", 105 | "![RelU vs TanH](./images/relu.jpeg \"RelU vs TanH\")\n", 106 | "\n", 107 | "Then we define the pooling size, in our case 2X2. this basically selects the max value in a 2x2 matrix\n", 108 | "\n", 109 | "Then we repeat the process, as we have chosen 2 conv layers, after which we flatten them.\n", 110 | "\n", 111 | "Then in order to reduce the risk of overfitting we set the dropout to 0.5 i.e. some neurons will be randomly turned on and off to add entropy\n", 112 | "\n", 113 | "After which we use softmax to give the output in the form of a probablity array" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 5, 119 | "id": "c9f13fd1", 120 | "metadata": {}, 121 | "outputs": [ 122 | { 123 | "name": "stdout", 124 | "output_type": "stream", 125 | "text": [ 126 | "Model: \"sequential\"\n", 127 | "_________________________________________________________________\n", 128 | " Layer (type) Output Shape Param # \n", 129 | "=================================================================\n", 130 | " conv2d (Conv2D) (None, 26, 26, 32) 320 \n", 131 | " \n", 132 | " max_pooling2d (MaxPooling2D (None, 13, 13, 32) 0 \n", 133 | " ) \n", 134 | " \n", 135 | " conv2d_1 (Conv2D) (None, 11, 11, 64) 18496 \n", 136 | " \n", 137 | " max_pooling2d_1 (MaxPooling (None, 5, 5, 64) 0 \n", 138 | " 2D) \n", 139 | " \n", 140 | " flatten (Flatten) (None, 1600) 0 \n", 141 | " \n", 142 | " dropout (Dropout) (None, 1600) 0 \n", 143 | " \n", 144 | " dense (Dense) (None, 10) 16010 \n", 145 | " \n", 146 | "=================================================================\n", 147 | "Total params: 34,826\n", 148 | "Trainable params: 34,826\n", 149 | "Non-trainable params: 0\n", 150 | "_________________________________________________________________\n" 151 | ] 152 | } 153 | ], 154 | "source": [ 155 | "# Gives a summary of the designed model\n", 156 | "model.summary()" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 6, 162 | "id": "f7fb602f", 163 | "metadata": {}, 164 | "outputs": [ 165 | { 166 | "name": "stdout", 167 | "output_type": "stream", 168 | "text": [ 169 | "Epoch 1/15\n", 170 | "422/422 [==============================] - 12s 27ms/step - loss: 1.1590 - accuracy: 0.8529 - val_loss: 0.0803 - val_accuracy: 0.9767\n", 171 | "Epoch 2/15\n", 172 | "422/422 [==============================] - 11s 27ms/step - loss: 0.1766 - accuracy: 0.9473 - val_loss: 0.0553 - val_accuracy: 0.9843\n", 173 | "Epoch 3/15\n", 174 | "422/422 [==============================] - 12s 27ms/step - loss: 0.1255 - accuracy: 0.9618 - val_loss: 0.0516 - val_accuracy: 0.9857\n", 175 | "Epoch 4/15\n", 176 | "422/422 [==============================] - 12s 28ms/step - loss: 0.1062 - accuracy: 0.9675 - val_loss: 0.0440 - val_accuracy: 0.9867\n", 177 | "Epoch 5/15\n", 178 | "422/422 [==============================] - 12s 27ms/step - loss: 0.0920 - accuracy: 0.9717 - val_loss: 0.0449 - val_accuracy: 0.9868\n", 179 | "Epoch 6/15\n", 180 | "422/422 [==============================] - 11s 27ms/step - loss: 0.0861 - accuracy: 0.9739 - val_loss: 0.0441 - val_accuracy: 0.9882\n", 181 | "Epoch 7/15\n", 182 | "422/422 [==============================] - 11s 26ms/step - loss: 0.0762 - accuracy: 0.9764 - val_loss: 0.0373 - val_accuracy: 0.9895\n", 183 | "Epoch 8/15\n", 184 | "422/422 [==============================] - 12s 28ms/step - loss: 0.0713 - accuracy: 0.9782 - val_loss: 0.0336 - val_accuracy: 0.9913\n", 185 | "Epoch 9/15\n", 186 | "422/422 [==============================] - 13s 30ms/step - loss: 0.0669 - accuracy: 0.9791 - val_loss: 0.0361 - val_accuracy: 0.9908\n", 187 | "Epoch 10/15\n", 188 | "422/422 [==============================] - 12s 27ms/step - loss: 0.0669 - accuracy: 0.9789 - val_loss: 0.0364 - val_accuracy: 0.9903\n", 189 | "Epoch 11/15\n", 190 | "422/422 [==============================] - 11s 26ms/step - loss: 0.0623 - accuracy: 0.9803 - val_loss: 0.0372 - val_accuracy: 0.9915\n", 191 | "Epoch 12/15\n", 192 | "422/422 [==============================] - 12s 27ms/step - loss: 0.0557 - accuracy: 0.9825 - val_loss: 0.0356 - val_accuracy: 0.9895\n", 193 | "Epoch 13/15\n", 194 | "422/422 [==============================] - 12s 27ms/step - loss: 0.0577 - accuracy: 0.9813 - val_loss: 0.0409 - val_accuracy: 0.9893\n", 195 | "Epoch 14/15\n", 196 | "422/422 [==============================] - 11s 26ms/step - loss: 0.0570 - accuracy: 0.9826 - val_loss: 0.0396 - val_accuracy: 0.9897\n", 197 | "Epoch 15/15\n", 198 | "422/422 [==============================] - 11s 26ms/step - loss: 0.0549 - accuracy: 0.9828 - val_loss: 0.0360 - val_accuracy: 0.9917\n" 199 | ] 200 | }, 201 | { 202 | "data": { 203 | "text/plain": [ 204 | "" 205 | ] 206 | }, 207 | "execution_count": 6, 208 | "metadata": {}, 209 | "output_type": "execute_result" 210 | } 211 | ], 212 | "source": [ 213 | "# Now we train the model\n", 214 | "\n", 215 | "batch_size = 128\n", 216 | "epochs = 15\n", 217 | "\n", 218 | "model.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n", 219 | "\n", 220 | "model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": 8, 226 | "id": "7ece05f2", 227 | "metadata": {}, 228 | "outputs": [ 229 | { 230 | "name": "stdout", 231 | "output_type": "stream", 232 | "text": [ 233 | "Test loss: 0.034038905054330826\n", 234 | "Test accuracy: 0.9901000261306763\n" 235 | ] 236 | } 237 | ], 238 | "source": [ 239 | "# Testing with test data\n", 240 | "score = model.evaluate(x_test, y_test, verbose=0)\n", 241 | "print(\"Test loss:\", score[0])\n", 242 | "print(\"Test accuracy:\", score[1])\n" 243 | ] 244 | } 245 | ], 246 | "metadata": { 247 | "kernelspec": { 248 | "display_name": "Python 3.8.8 ('base')", 249 | "language": "python", 250 | "name": "python3" 251 | }, 252 | "language_info": { 253 | "codemirror_mode": { 254 | "name": "ipython", 255 | "version": 3 256 | }, 257 | "file_extension": ".py", 258 | "mimetype": "text/x-python", 259 | "name": "python", 260 | "nbconvert_exporter": "python", 261 | "pygments_lexer": "ipython3", 262 | "version": "3.8.8" 263 | }, 264 | "vscode": { 265 | "interpreter": { 266 | "hash": "a8aa08b4109e02faef70797796bfd5fb313790bd5a534ff08957d24923938621" 267 | } 268 | } 269 | }, 270 | "nbformat": 4, 271 | "nbformat_minor": 5 272 | } 273 | -------------------------------------------------------------------------------- /MNIST number detector/readme.md: -------------------------------------------------------------------------------- 1 | # MNIST number detector 2 | 3 | This is a very simple form of OCR where I am using the MNIST dataset to train and test a simple digit recogniser 4 | 5 | It functions on CNN with 2 convolution layers using RelU as the main activation function 6 | 7 | ## How to Contribute? 8 | 9 | - Take Existing Issues or create your own Issues! 10 | - Get Assigned with Issues 11 | - Fork the Repo, then Clone forked repo. 12 | - Create a Pull Request. 13 | - Add Screenshots/deployed link in your project repo README.md 14 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 15 | 16 | 17 | ## HELP US OUT BY STARRING THIS REPOSITORY -------------------------------------------------------------------------------- /MNIST number detector/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy~=1.20.3 2 | tensorflow~=2.10 -------------------------------------------------------------------------------- /Minesweeper/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 HarshBardolia01 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Minesweeper/__pycache__/minesweeper.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Minesweeper/__pycache__/minesweeper.cpython-38.pyc -------------------------------------------------------------------------------- /Minesweeper/__pycache__/minesweeper.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Minesweeper/__pycache__/minesweeper.cpython-39.pyc -------------------------------------------------------------------------------- /Minesweeper/assets/fonts/OpenSans-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Minesweeper/assets/fonts/OpenSans-Regular.ttf -------------------------------------------------------------------------------- /Minesweeper/assets/images/flag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Minesweeper/assets/images/flag.png -------------------------------------------------------------------------------- /Minesweeper/assets/images/mine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Minesweeper/assets/images/mine.png -------------------------------------------------------------------------------- /Minesweeper/minesweeper.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import random 3 | import copy 4 | 5 | class Minesweeper(): 6 | """ 7 | Minesweeper game representation 8 | """ 9 | 10 | def __init__(self, height=8, width=8, mines=8): 11 | 12 | # Set initial width, height, and number of mines 13 | self.height = height 14 | self.width = width 15 | self.mines = set() 16 | 17 | # Initialize an empty field with no mines 18 | self.board = [] 19 | for i in range(self.height): 20 | row = [] 21 | for j in range(self.width): 22 | row.append(False) 23 | self.board.append(row) 24 | 25 | # Add mines randomly 26 | while len(self.mines) != mines: 27 | i = random.randrange(height) 28 | j = random.randrange(width) 29 | if not self.board[i][j]: 30 | self.mines.add((i, j)) 31 | self.board[i][j] = True 32 | 33 | # At first, player has found no mines 34 | self.mines_found = set() 35 | 36 | def print(self): 37 | """ 38 | Prints a text-based representation 39 | of where mines are located. 40 | """ 41 | for i in range(self.height): 42 | print("--" * self.width + "-") 43 | for j in range(self.width): 44 | if self.board[i][j]: 45 | print("|X", end="") 46 | else: 47 | print("| ", end="") 48 | print("|") 49 | print("--" * self.width + "-") 50 | 51 | def is_mine(self, cell): 52 | i, j = cell 53 | return self.board[i][j] 54 | 55 | def nearby_mines(self, cell): 56 | """ 57 | Returns the number of mines that are 58 | within one row and column of a given cell, 59 | not including the cell itself. 60 | """ 61 | 62 | # Keep count of nearby mines 63 | count = 0 64 | 65 | # Loop over all cells within one row and column 66 | for i in range(cell[0] - 1, cell[0] + 2): 67 | for j in range(cell[1] - 1, cell[1] + 2): 68 | 69 | # Ignore the cell itself 70 | if (i, j) == cell: 71 | continue 72 | 73 | # Update count if cell in bounds and is mine 74 | if 0 <= i < self.height and 0 <= j < self.width: 75 | if self.board[i][j]: 76 | count += 1 77 | 78 | return count 79 | 80 | def won(self): 81 | """ 82 | Checks if all mines have been flagged. 83 | """ 84 | return self.mines_found == self.mines 85 | 86 | 87 | class Sentence(): 88 | """ 89 | Logical statement about a Minesweeper game 90 | A sentence consists of a set of board cells, 91 | and a count of the number of those cells which are mines. 92 | """ 93 | 94 | def __init__(self, cells, count): 95 | self.cells = set(cells) 96 | self.count = count 97 | 98 | def __eq__(self, other): 99 | return self.cells == other.cells and self.count == other.count 100 | 101 | def __str__(self): 102 | return f"{self.cells} = {self.count}" 103 | 104 | def known_mines(self): 105 | """ 106 | Returns the set of all cells in self.cells known to be mines. 107 | """ 108 | 109 | # if the count of mines is equal to number of neighbouring cells 110 | if len(self.cells) == self.count: 111 | return self.cells 112 | 113 | # raise NotImplementedError 114 | 115 | def known_safes(self): 116 | """ 117 | Returns the set of all cells in self.cells known to be safe. 118 | """ 119 | 120 | # if the count is 0, i.e. there are no mines 121 | if self.count == 0: 122 | return self.cells 123 | 124 | # raise NotImplementedError 125 | 126 | def mark_mine(self, cell): 127 | """ 128 | Updates internal knowledge representation given the fact that 129 | a cell is known to be a mine. 130 | """ 131 | 132 | # if we know that a cell is mine then removinig it from the set and decreasing count by 1 133 | if cell in self.cells: 134 | self.cells.remove(cell) 135 | self.count -= 1 136 | 137 | # raise NotImplementedError 138 | 139 | def mark_safe(self, cell): 140 | """ 141 | Updates internal knowledge representation given the fact that 142 | a cell is known to be safe. 143 | """ 144 | 145 | # if we know that a cell is safe, just removing it from the set 146 | if cell in self.cells: 147 | self.cells.remove(cell) 148 | 149 | # raise NotImplementedError 150 | 151 | 152 | class MinesweeperAI(): 153 | """ 154 | Minesweeper game player 155 | """ 156 | 157 | def __init__(self, height=8, width=8): 158 | 159 | # Set initial height and width 160 | self.height = height 161 | self.width = width 162 | 163 | # Keep track of which cells have been clicked on 164 | self.moves_made = set() 165 | 166 | # Keep track of cells known to be safe or mines 167 | self.mines = set() 168 | self.safes = set() 169 | 170 | # List of sentences about the game known to be true 171 | self.knowledge = [] 172 | 173 | def mark_mine(self, cell): 174 | """ 175 | to mark that cell as a mine as well. 176 | Marks a cell as a mine, and updates all knowledge 177 | """ 178 | self.mines.add(cell) 179 | for sentence in self.knowledge: 180 | sentence.mark_mine(cell) 181 | 182 | def mark_safe(self, cell): 183 | """ 184 | Marks a cell as safe, and updates all knowledge 185 | to mark that cell as safe as well. 186 | """ 187 | self.safes.add(cell) 188 | for sentence in self.knowledge: 189 | sentence.mark_safe(cell) 190 | 191 | def add_knowledge(self, cell, count): 192 | """ 193 | Called when the Minesweeper board tells us, for a given 194 | safe cell, how many neighboring cells have mines in them. 195 | 196 | This function should: 197 | 1) mark the cell as a move that has been made 198 | 2) mark the cell as safe 199 | 3) add a new sentence to the AI's knowledge base 200 | based on the value of `cell` and `count` 201 | 4) mark any additional cells as safe or as mines 202 | if it can be concluded based on the AI's knowledge base 203 | 5) add any new sentences to the AI's knowledge base 204 | if they can be inferred from existing knowledge 205 | """ 206 | 207 | # 1. marking the cell as a move that has been made 208 | self.moves_made.add(cell) 209 | 210 | # the x and y coordinates of the cell 211 | i = cell[0] 212 | j = cell[1] 213 | 214 | neighbors = list() 215 | 216 | # iterating over the neighbors 217 | for row in range(i - 1, i + 2): 218 | for col in range(j - 1, j + 2): 219 | 220 | if (row, col) == cell: 221 | continue 222 | 223 | if row > self.height - 1 or row < 0 or col > self.width - 1 or col < 0: 224 | continue 225 | else: 226 | if (row, col) not in self.moves_made: 227 | neighbors.append((row, col)) 228 | 229 | # 3. adding a new sentance to the knowlege base 230 | self.knowledge.append(Sentence(neighbors, count)) 231 | 232 | # 2. marking the cell as safe 233 | self.mark_safe(cell) 234 | 235 | base = copy.deepcopy(self.knowledge) 236 | 237 | # 4. 238 | for sentence in self.knowledge: 239 | # adding a cell to mines based on the knowlege 240 | if len(sentence.cells) == sentence.count: 241 | cells = copy.deepcopy(sentence.cells) 242 | for cell in cells: 243 | self.mark_mine(cell) 244 | del sentence 245 | # adding a cell to safes based on the knowledge 246 | else: 247 | if sentence.count == 0: 248 | cells = copy.deepcopy(sentence.cells) 249 | for cell in cells: 250 | self.mark_safe(cell) 251 | del sentence 252 | 253 | # 5. adding new sentences to knowledege base inferred from the existing ones 254 | for sentence in base: 255 | if sentence.count == 0: 256 | continue 257 | 258 | # cells and counts of sentence 1 259 | cells1 = sentence.cells 260 | count1 = sentence.count 261 | 262 | for sentence2 in base: 263 | # cells and counts of sentence 2 264 | cells2 = sentence2.cells 265 | count2 = sentence2.count 266 | 267 | if sentence == sentence2 or sentence2.count == 0: 268 | continue 269 | 270 | # if cells in sentence 2 is subest of cells in sentence 1 271 | elif cells2.issubset(cells1): 272 | new_count = count1 - count2 273 | new_cells = list(copy.deepcopy(cells1)) 274 | 275 | # removing cells of sentence 2 from new cells list 276 | for cell in cells2: 277 | new_cells.remove(cell) 278 | 279 | # removing the made moves from the new cells list 280 | for cell in self.moves_made: 281 | if cell in new_cells: 282 | new_cells.remove(cell) 283 | 284 | for sentence in base: 285 | if set(new_cells).issubset(sentence.cells): 286 | continue 287 | 288 | # adding new sentence to the knowledege base 289 | self.knowledge.append(Sentence(new_cells, new_count)) 290 | 291 | else: 292 | continue 293 | 294 | # raise NotImplementedError 295 | 296 | def make_safe_move(self): 297 | """ 298 | Returns a safe cell to choose on the Minesweeper board. 299 | The move must be known to be safe, and not already a move 300 | that has been made. 301 | 302 | This function may use the knowledge in self.mines, self.safes 303 | and self.moves_made, but should not modify any of those values. 304 | """ 305 | 306 | # printing number of unused safe cells and detected mines 307 | print(f"{len(self.safes - self.moves_made)} known unused safes.") 308 | print(f"{len(self.mines)} detected mines:\n{list(self.mines)}") 309 | 310 | # if safe cells exists 311 | if len(self.safes) != 0: 312 | for cell in self.safes: 313 | # the cell that is not mine and moved earlier is returned 314 | if (cell not in self.moves_made) and (cell not in self.mines): 315 | return cell 316 | else: 317 | return None 318 | 319 | # raise NotImplementedError 320 | 321 | def make_random_move(self): 322 | """ 323 | Returns a move to make on the Minesweeper board. 324 | Should choose randomly among cells that: 325 | 1) have not already been chosen, and 326 | 2) are not known to be mines 327 | """ 328 | 329 | # moves is the list of available moves 330 | moves = [] 331 | for i in range(0, self.height): 332 | for j in range(0, self.width): 333 | if (i, j) not in self.moves_made: 334 | if (i, j) not in self.mines: 335 | # return (i, j) 336 | moves.append((i, j)) 337 | 338 | # if no moves are remaining then game is over 339 | if len(moves) == 0: 340 | print("GAME FINISHED!") 341 | 342 | # else choosing a random move from the list 343 | else: 344 | random_move = random.choice(moves) 345 | self.moves_made.add(random_move) 346 | print(f"Move made {random_move}") 347 | return random_move 348 | 349 | # raise NotImplementedError 350 | -------------------------------------------------------------------------------- /Minesweeper/requirements.txt: -------------------------------------------------------------------------------- 1 | pygame 2 | -------------------------------------------------------------------------------- /Minesweeper/runner.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | import time 4 | 5 | from minesweeper import Minesweeper, MinesweeperAI 6 | 7 | HEIGHT = 8 8 | WIDTH = 8 9 | MINES = 8 10 | 11 | # Colors 12 | BLACK = (0, 0, 0) 13 | GRAY = (180, 180, 180) 14 | WHITE = (255, 255, 255) 15 | 16 | # Create game 17 | pygame.init() 18 | size = width, height = 600, 400 19 | screen = pygame.display.set_mode(size) 20 | 21 | # Fonts 22 | OPEN_SANS = "assets/fonts/OpenSans-Regular.ttf" 23 | smallFont = pygame.font.Font(OPEN_SANS, 20) 24 | mediumFont = pygame.font.Font(OPEN_SANS, 28) 25 | largeFont = pygame.font.Font(OPEN_SANS, 40) 26 | 27 | # Compute board size 28 | BOARD_PADDING = 20 29 | board_width = ((2 / 3) * width) - (BOARD_PADDING * 2) 30 | board_height = height - (BOARD_PADDING * 2) 31 | cell_size = int(min(board_width / WIDTH, board_height / HEIGHT)) 32 | board_origin = (BOARD_PADDING, BOARD_PADDING) 33 | 34 | # Add images 35 | flag = pygame.image.load("assets/images/flag.png") 36 | flag = pygame.transform.scale(flag, (cell_size, cell_size)) 37 | mine = pygame.image.load("assets/images/mine.png") 38 | mine = pygame.transform.scale(mine, (cell_size, cell_size)) 39 | 40 | # Create game and AI agent 41 | game = Minesweeper(height=HEIGHT, width=WIDTH, mines=MINES) 42 | ai = MinesweeperAI(height=HEIGHT, width=WIDTH) 43 | 44 | # Keep track of revealed cells, flagged cells, and if a mine was hit 45 | revealed = set() 46 | flags = set() 47 | lost = False 48 | 49 | # Show instructions initially 50 | instructions = True 51 | 52 | while True: 53 | 54 | # Check if game quit 55 | for event in pygame.event.get(): 56 | if event.type == pygame.QUIT: 57 | sys.exit() 58 | 59 | screen.fill(BLACK) 60 | 61 | # Show game instructions 62 | if instructions: 63 | 64 | # Title 65 | title = largeFont.render("Play Minesweeper", True, WHITE) 66 | titleRect = title.get_rect() 67 | titleRect.center = ((width / 2), 50) 68 | screen.blit(title, titleRect) 69 | 70 | # Rules 71 | rules = [ 72 | "Click a cell to reveal it.", 73 | "Right-click a cell to mark it as a mine.", 74 | "Mark all mines successfully to win!" 75 | ] 76 | for i, rule in enumerate(rules): 77 | line = smallFont.render(rule, True, WHITE) 78 | lineRect = line.get_rect() 79 | lineRect.center = ((width / 2), 150 + 30 * i) 80 | screen.blit(line, lineRect) 81 | 82 | # Play game button 83 | buttonRect = pygame.Rect((width / 4), (3 / 4) * height, width / 2, 50) 84 | buttonText = mediumFont.render("Play Game", True, BLACK) 85 | buttonTextRect = buttonText.get_rect() 86 | buttonTextRect.center = buttonRect.center 87 | pygame.draw.rect(screen, WHITE, buttonRect) 88 | screen.blit(buttonText, buttonTextRect) 89 | 90 | # Check if play button clicked 91 | click, _, _ = pygame.mouse.get_pressed() 92 | if click == 1: 93 | mouse = pygame.mouse.get_pos() 94 | if buttonRect.collidepoint(mouse): 95 | instructions = False 96 | time.sleep(0.3) 97 | 98 | pygame.display.flip() 99 | continue 100 | 101 | # Draw board 102 | cells = [] 103 | for i in range(HEIGHT): 104 | row = [] 105 | for j in range(WIDTH): 106 | 107 | # Draw rectangle for cell 108 | rect = pygame.Rect( 109 | board_origin[0] + j * cell_size, 110 | board_origin[1] + i * cell_size, 111 | cell_size, cell_size 112 | ) 113 | pygame.draw.rect(screen, GRAY, rect) 114 | pygame.draw.rect(screen, WHITE, rect, 3) 115 | 116 | # Add a mine, flag, or number if needed 117 | if game.is_mine((i, j)) and lost: 118 | screen.blit(mine, rect) 119 | elif (i, j) in flags: 120 | screen.blit(flag, rect) 121 | elif (i, j) in revealed: 122 | neighbors = smallFont.render( 123 | str(game.nearby_mines((i, j))), 124 | True, BLACK 125 | ) 126 | neighborsTextRect = neighbors.get_rect() 127 | neighborsTextRect.center = rect.center 128 | screen.blit(neighbors, neighborsTextRect) 129 | 130 | row.append(rect) 131 | cells.append(row) 132 | 133 | # AI Move button 134 | aiButton = pygame.Rect( 135 | (2 / 3) * width + BOARD_PADDING, (1 / 3) * height - 50, 136 | (width / 3) - BOARD_PADDING * 2, 50 137 | ) 138 | buttonText = mediumFont.render("AI Move", True, BLACK) 139 | buttonRect = buttonText.get_rect() 140 | buttonRect.center = aiButton.center 141 | pygame.draw.rect(screen, WHITE, aiButton) 142 | screen.blit(buttonText, buttonRect) 143 | 144 | # Reset button 145 | resetButton = pygame.Rect( 146 | (2 / 3) * width + BOARD_PADDING, (1 / 3) * height + 20, 147 | (width / 3) - BOARD_PADDING * 2, 50 148 | ) 149 | buttonText = mediumFont.render("Reset", True, BLACK) 150 | buttonRect = buttonText.get_rect() 151 | buttonRect.center = resetButton.center 152 | pygame.draw.rect(screen, WHITE, resetButton) 153 | screen.blit(buttonText, buttonRect) 154 | 155 | # Display text 156 | text = "Lost" if lost else "Won" if game.mines == flags else "" 157 | text = mediumFont.render(text, True, WHITE) 158 | textRect = text.get_rect() 159 | textRect.center = ((5 / 6) * width, (2 / 3) * height) 160 | screen.blit(text, textRect) 161 | 162 | move = None 163 | 164 | left, _, right = pygame.mouse.get_pressed() 165 | 166 | # Check for a right-click to toggle flagging 167 | if right == 1 and not lost: 168 | mouse = pygame.mouse.get_pos() 169 | for i in range(HEIGHT): 170 | for j in range(WIDTH): 171 | if cells[i][j].collidepoint(mouse) and (i, j) not in revealed: 172 | if (i, j) in flags: 173 | flags.remove((i, j)) 174 | else: 175 | flags.add((i, j)) 176 | time.sleep(0.2) 177 | 178 | elif left == 1: 179 | mouse = pygame.mouse.get_pos() 180 | 181 | # If AI button clicked, make an AI move 182 | if aiButton.collidepoint(mouse) and not lost: 183 | move = ai.make_safe_move() 184 | if move is None: 185 | move = ai.make_random_move() 186 | if move is None: 187 | flags = ai.mines.copy() 188 | print("No moves left to make.") 189 | else: 190 | print("No known safe moves, AI making random move.") 191 | else: 192 | print("AI making safe move.") 193 | time.sleep(0.2) 194 | # print(move) 195 | 196 | # Reset game state 197 | elif resetButton.collidepoint(mouse): 198 | game = Minesweeper(height=HEIGHT, width=WIDTH, mines=MINES) 199 | ai = MinesweeperAI(height=HEIGHT, width=WIDTH) 200 | revealed = set() 201 | flags = set() 202 | lost = False 203 | continue 204 | 205 | # User-made move 206 | elif not lost: 207 | for i in range(HEIGHT): 208 | for j in range(WIDTH): 209 | if (cells[i][j].collidepoint(mouse) 210 | and (i, j) not in flags 211 | and (i, j) not in revealed): 212 | move = (i, j) 213 | 214 | # Make move and update AI knowledge 215 | if move: 216 | if game.is_mine(move): 217 | lost = True 218 | else: 219 | nearby = game.nearby_mines(move) 220 | revealed.add(move) 221 | ai.add_knowledge(move, nearby) 222 | 223 | pygame.display.flip() 224 | -------------------------------------------------------------------------------- /Plagiarism Checker/File 1.txt: -------------------------------------------------------------------------------- 1 | Hacktoberfest, a month-long celebration of open-source software that encourages participation in giving back to the open-source community, is sponsored by DigitalOcean. Developers take part by finishing pull requests, going to events, and contributing money to open source projects. -------------------------------------------------------------------------------- /Plagiarism Checker/File 2.txt: -------------------------------------------------------------------------------- 1 | DigitalOcean sponsors Hacktoberfest, a month-long festival honouring open-source software that promotes involvement in giving back to the open-source community. Developers participate through completing pull requests, attending events, and making financial contributions to open source projects. -------------------------------------------------------------------------------- /Plagiarism Checker/File 3.txt: -------------------------------------------------------------------------------- 1 | Hacktoberfest is a month-long celebration of open-source software by DigitalOcean that encourages participation in giving back to the open-source community. Developers get involved by completing pull requests, participating in events, and donating to open source projects. -------------------------------------------------------------------------------- /Plagiarism Checker/Plagiarism Checker.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "ExecuteTime": { 8 | "end_time": "2021-10-05T13:06:11.749110Z", 9 | "start_time": "2021-10-05T13:06:09.467318Z" 10 | } 11 | }, 12 | "outputs": [ 13 | { 14 | "name": "stdout", 15 | "output_type": "stream", 16 | "text": [ 17 | "Similarity data:\n", 18 | " ('File 1.txt', 'File 3.txt', 0.7652495556569432)\n", 19 | "Similarity data:\n", 20 | " ('File 1.txt', 'File 2.txt', 0.5429392493791333)\n", 21 | "Similarity data:\n", 22 | " ('File 2.txt', 'File 3.txt', 0.5858083067194831)\n" 23 | ] 24 | } 25 | ], 26 | "source": [ 27 | "# Import necessary modules!\n", 28 | "import os\n", 29 | "from sklearn.feature_extraction.text import TfidfVectorizer\n", 30 | "from sklearn.metrics.pairwise import cosine_similarity\n", 31 | "\n", 32 | "student_files = [doc for doc in os.listdir() if doc.endswith('.txt')]\n", 33 | "student_notes = [open(_file, encoding='utf-8').read()\n", 34 | " for _file in student_files]\n", 35 | "\n", 36 | "\n", 37 | "def vectorize(Text): return TfidfVectorizer().fit_transform(Text).toarray()\n", 38 | "def similarity(doc1, doc2): return cosine_similarity([doc1, doc2])\n", 39 | "\n", 40 | "\n", 41 | "vectors = vectorize(student_notes)\n", 42 | "s_vectors = list(zip(student_files, vectors))\n", 43 | "plagiarism_results = set()\n", 44 | "\n", 45 | "\n", 46 | "def check_plagiarism():\n", 47 | " global s_vectors\n", 48 | " for student_a, text_vector_a in s_vectors:\n", 49 | " new_vectors = s_vectors.copy()\n", 50 | " current_index = new_vectors.index((student_a, text_vector_a))\n", 51 | " del new_vectors[current_index]\n", 52 | " for student_b, text_vector_b in new_vectors:\n", 53 | " sim_score = similarity(text_vector_a, text_vector_b)[0][1]\n", 54 | " student_pair = sorted((student_a, student_b))\n", 55 | " score = (student_pair[0], student_pair[1], sim_score)\n", 56 | " plagiarism_results.add(score)\n", 57 | " return plagiarism_results\n", 58 | "\n", 59 | "\n", 60 | "for data in check_plagiarism():\n", 61 | " print(\"Similarity data:\\n\", data) " 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [] 70 | } 71 | ], 72 | "metadata": { 73 | "hide_input": false, 74 | "kernelspec": { 75 | "display_name": "Python 3 (ipykernel)", 76 | "language": "python", 77 | "name": "python3" 78 | }, 79 | "language_info": { 80 | "codemirror_mode": { 81 | "name": "ipython", 82 | "version": 3 83 | }, 84 | "file_extension": ".py", 85 | "mimetype": "text/x-python", 86 | "name": "python", 87 | "nbconvert_exporter": "python", 88 | "pygments_lexer": "ipython3", 89 | "version": "3.9.12" 90 | }, 91 | "toc": { 92 | "base_numbering": 1, 93 | "nav_menu": {}, 94 | "number_sections": true, 95 | "sideBar": true, 96 | "skip_h1_title": false, 97 | "title_cell": "Table of Contents", 98 | "title_sidebar": "Contents", 99 | "toc_cell": false, 100 | "toc_position": {}, 101 | "toc_section_display": true, 102 | "toc_window_display": false 103 | }, 104 | "varInspector": { 105 | "cols": { 106 | "lenName": 16, 107 | "lenType": 16, 108 | "lenVar": 40 109 | }, 110 | "kernels_config": { 111 | "python": { 112 | "delete_cmd_postfix": "", 113 | "delete_cmd_prefix": "del ", 114 | "library": "var_list.py", 115 | "varRefreshCmd": "print(var_dic_list())" 116 | }, 117 | "r": { 118 | "delete_cmd_postfix": ") ", 119 | "delete_cmd_prefix": "rm(", 120 | "library": "var_list.r", 121 | "varRefreshCmd": "cat(var_dic_list()) " 122 | } 123 | }, 124 | "types_to_exclude": [ 125 | "module", 126 | "function", 127 | "builtin_function_or_method", 128 | "instance", 129 | "_Feature" 130 | ], 131 | "window_display": false 132 | }, 133 | "vscode": { 134 | "interpreter": { 135 | "hash": "f4a5aaf0e81527b6176594c7af59856b967260c0ff5f33fbbb76cd469280c61e" 136 | } 137 | } 138 | }, 139 | "nbformat": 4, 140 | "nbformat_minor": 4 141 | } 142 | -------------------------------------------------------------------------------- /Plagiarism Checker/README.md: -------------------------------------------------------------------------------- 1 | # Plagiarism Checker 2 | 3 | ## How to Contribute? 4 | 5 | - Take Existing Issues or create your own Issues! 6 | - Get Assigned with Issues 7 | - Fork the Repo, then Clone forked repo. 8 | - Create a Pull Request. 9 | - Add Screenshots/deployed link in your project repo README.md 10 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 11 | 12 | 13 | ## HELP US OUT BY STARRING THIS REPOSITORY -------------------------------------------------------------------------------- /Polynomial Regression/data_preprocessing_template.py: -------------------------------------------------------------------------------- 1 | # Data Preprocessing Template 2 | 3 | # Importing the libraries 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | import pandas as pd 7 | 8 | # Importing the dataset 9 | dataset = pd.read_csv('Data.csv') 10 | X = dataset.iloc[:, :-1].values 11 | y = dataset.iloc[:, 3].values 12 | 13 | # Splitting the dataset into the Training set and Test set 14 | from sklearn.model_selection import train_test_split 15 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) 16 | 17 | # Feature Scaling 18 | """from sklearn.preprocessing import StandardScaler 19 | sc_X = StandardScaler() 20 | X_train = sc_X.fit_transform(X_train) 21 | X_test = sc_X.transform(X_test) 22 | sc_y = StandardScaler() 23 | y_train = sc_y.fit_transform(y_train.reshape(-1,1))""" -------------------------------------------------------------------------------- /Polynomial Regression/polynomial_regression.py: -------------------------------------------------------------------------------- 1 | # Polynomial Regression 2 | 3 | # Importing the libraries 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | import pandas as pd 7 | 8 | # Importing the dataset 9 | dataset = pd.read_csv('Position_Salaries.csv') 10 | X = dataset.iloc[:, 1:2].values 11 | y = dataset.iloc[:, 2].values 12 | 13 | # Splitting the dataset into the Training set and Test set 14 | """from sklearn.model_selection import train_test_split 15 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)""" 16 | 17 | # Feature Scaling 18 | """from sklearn.preprocessing import StandardScaler 19 | sc_X = StandardScaler() 20 | X_train = sc_X.fit_transform(X_train) 21 | X_test = sc_X.transform(X_test)""" 22 | 23 | # Fitting Linear Regression to the dataset 24 | from sklearn.linear_model import LinearRegression 25 | lin_reg = LinearRegression() 26 | lin_reg.fit(X, y) 27 | 28 | # Fitting Polynomial Regression to the dataset 29 | from sklearn.preprocessing import PolynomialFeatures 30 | poly_reg = PolynomialFeatures(degree = 4) 31 | X_poly = poly_reg.fit_transform(X) 32 | poly_reg.fit(X_poly, y) 33 | lin_reg_2 = LinearRegression() 34 | lin_reg_2.fit(X_poly, y) 35 | 36 | # Visualising the Linear Regression results 37 | plt.scatter(X, y, color = 'red') 38 | plt.plot(X, lin_reg.predict(X), color = 'blue') 39 | plt.title('Truth or Bluff (Linear Regression)') 40 | plt.xlabel('Position level') 41 | plt.ylabel('Salary') 42 | plt.show() 43 | 44 | # Visualising the Polynomial Regression results 45 | plt.scatter(X, y, color = 'red') 46 | plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color = 'blue') 47 | plt.title('Truth or Bluff (Polynomial Regression)') 48 | plt.xlabel('Position level') 49 | plt.ylabel('Salary') 50 | plt.show() 51 | 52 | # Visualising the Polynomial Regression results (for higher resolution and smoother curve) 53 | X_grid = np.arange(min(X), max(X), 0.1) 54 | X_grid = X_grid.reshape((len(X_grid), 1)) 55 | plt.scatter(X, y, color = 'red') 56 | plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue') 57 | plt.title('Truth or Bluff (Polynomial Regression)') 58 | plt.xlabel('Position level') 59 | plt.ylabel('Salary') 60 | plt.show() 61 | 62 | # Predicting a new result with Linear Regression 63 | lin_reg.predict([[6.5]]) 64 | 65 | # Predicting a new result with Polynomial Regression 66 | lin_reg_2.predict(poly_reg.fit_transform([[6.5]])) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # HACKTOBERFEST 2022 3 | 4 | Encode AI-Ml & python is an open source project which contains different projects of AI, ML and Python Mini projects etc. which makes your it easier for the students to learn and explore different projects in the field of AI-ML or Python. You can submit your projects or raise/claim issues on existing projects 5 | 6 | 7 | ## Introduction 8 | 9 | This Repo is an open source collection of projects of AI-ML & python etc for uplifting Creative thinking over Binge watching tutorials. 10 | 11 | 12 | ## How to Contribute? 13 | 14 | - Take Existing Issues or create your own Issues! 15 | - Get Assigned with Issues 16 | - Fork the Repo, then Clone forked repo. 17 | - Create a Pull Request. 18 | - Add Screenshots/deployed link in your project repo README.md 19 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 20 | 21 | 22 | ## HELP US OUT BY STARRING THIS REPOSITORY 23 | -------------------------------------------------------------------------------- /Spotify Recommendation Analysis/File: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Spotify Recommendation Analysis/Readme.md: -------------------------------------------------------------------------------- 1 | # Spotify Recommendation Analysis 2 | 3 | In this project I have done an analysis for spotify recommendation using basic python libraries. 4 | 5 | ## How to Contribute? 6 | 7 | - Take Existing Issues or create your own Issues! 8 | - Get Assigned with Issues 9 | - Fork the Repo, then Clone forked repo. 10 | - Create a Pull Request. 11 | - Add Screenshots/deployed link in your project repo README.md 12 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 13 | 14 | 15 | ## HELP US OUT BY STARRING THIS REPOSITORY 16 | -------------------------------------------------------------------------------- /Tic-Tac-Toe/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 HarshBardolia01 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Tic-Tac-Toe/OpenSans-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Tic-Tac-Toe/OpenSans-Regular.ttf -------------------------------------------------------------------------------- /Tic-Tac-Toe/README.md: -------------------------------------------------------------------------------- 1 | # Tic-Tac-Toe 2 | 3 | This project was a part of CS50's introduction to AI with python. 4 | 5 | ## How to Contribute? 6 | 7 | - Take Existing Issues or create your own Issues! 8 | - Get Assigned with Issues 9 | - Fork the Repo, then Clone forked repo. 10 | - Create a Pull Request. 11 | - Add Screenshots/deployed link in your project repo README.md 12 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 13 | 14 | 15 | ## HELP US OUT BY STARRING THIS REPOSITORY -------------------------------------------------------------------------------- /Tic-Tac-Toe/__pycache__/tictactoe.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Tic-Tac-Toe/__pycache__/tictactoe.cpython-38.pyc -------------------------------------------------------------------------------- /Tic-Tac-Toe/__pycache__/tictactoe.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Tic-Tac-Toe/__pycache__/tictactoe.cpython-39.pyc -------------------------------------------------------------------------------- /Tic-Tac-Toe/check.py: -------------------------------------------------------------------------------- 1 | import tictactoe as ttt 2 | board = ttt.initial_state() 3 | 4 | turn = ttt.player(board) 5 | print(turn) -------------------------------------------------------------------------------- /Tic-Tac-Toe/requirements.txt: -------------------------------------------------------------------------------- 1 | pygame 2 | -------------------------------------------------------------------------------- /Tic-Tac-Toe/runner.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | import time 4 | 5 | import tictactoe as ttt 6 | 7 | pygame.init() 8 | size = width, height = 600, 400 9 | 10 | # Colors 11 | black = (0, 0, 0) 12 | white = (255, 255, 255) 13 | 14 | screen = pygame.display.set_mode(size) 15 | 16 | mediumFont = pygame.font.Font("OpenSans-Regular.ttf", 28) 17 | largeFont = pygame.font.Font("OpenSans-Regular.ttf", 40) 18 | moveFont = pygame.font.Font("OpenSans-Regular.ttf", 60) 19 | 20 | user = None 21 | board = ttt.initial_state() 22 | ai_turn = False 23 | 24 | while True: 25 | 26 | for event in pygame.event.get(): 27 | if event.type == pygame.QUIT: 28 | sys.exit() 29 | 30 | screen.fill(black) 31 | 32 | # Let user choose a player. 33 | if user is None: 34 | 35 | # Draw title 36 | title = largeFont.render("Play Tic-Tac-Toe", True, white) 37 | titleRect = title.get_rect() 38 | titleRect.center = ((width / 2), 50) 39 | screen.blit(title, titleRect) 40 | 41 | # Draw buttons 42 | playXButton = pygame.Rect((width / 8), (height / 2), width / 4, 50) 43 | playX = mediumFont.render("Play as X", True, black) 44 | playXRect = playX.get_rect() 45 | playXRect.center = playXButton.center 46 | pygame.draw.rect(screen, white, playXButton) 47 | screen.blit(playX, playXRect) 48 | 49 | playOButton = pygame.Rect(5 * (width / 8), (height / 2), width / 4, 50) 50 | playO = mediumFont.render("Play as O", True, black) 51 | playORect = playO.get_rect() 52 | playORect.center = playOButton.center 53 | pygame.draw.rect(screen, white, playOButton) 54 | screen.blit(playO, playORect) 55 | 56 | # Check if button is clicked 57 | click, _, _ = pygame.mouse.get_pressed() 58 | if click == 1: 59 | mouse = pygame.mouse.get_pos() 60 | if playXButton.collidepoint(mouse): 61 | time.sleep(0.2) 62 | user = ttt.X 63 | elif playOButton.collidepoint(mouse): 64 | time.sleep(0.2) 65 | user = ttt.O 66 | 67 | else: 68 | 69 | # Draw game board 70 | tile_size = 80 71 | tile_origin = (width / 2 - (1.5 * tile_size), 72 | height / 2 - (1.5 * tile_size)) 73 | tiles = [] 74 | for i in range(3): 75 | row = [] 76 | for j in range(3): 77 | rect = pygame.Rect( 78 | tile_origin[0] + j * tile_size, 79 | tile_origin[1] + i * tile_size, 80 | tile_size, tile_size 81 | ) 82 | pygame.draw.rect(screen, white, rect, 3) 83 | 84 | if board[i][j] != ttt.EMPTY: 85 | move = moveFont.render(board[i][j], True, white) 86 | moveRect = move.get_rect() 87 | moveRect.center = rect.center 88 | screen.blit(move, moveRect) 89 | row.append(rect) 90 | tiles.append(row) 91 | 92 | game_over = ttt.terminal(board) 93 | player = ttt.player(board) 94 | 95 | # Show title 96 | if game_over: 97 | winner = ttt.winner(board) 98 | if winner is None: 99 | title = f"Game Over: Tie." 100 | else: 101 | title = f"Game Over: {winner} wins." 102 | elif user == player: 103 | title = f"Play as {user}" 104 | else: 105 | title = f"Computer thinking..." 106 | title = largeFont.render(title, True, white) 107 | titleRect = title.get_rect() 108 | titleRect.center = ((width / 2), 30) 109 | screen.blit(title, titleRect) 110 | 111 | # Check for AI move 112 | if user != player and not game_over: 113 | if ai_turn: 114 | time.sleep(0.5) 115 | move = ttt.minimax(board) 116 | board = ttt.result(board, move) 117 | ai_turn = False 118 | else: 119 | ai_turn = True 120 | 121 | # Check for a user move 122 | click, _, _ = pygame.mouse.get_pressed() 123 | if click == 1 and user == player and not game_over: 124 | mouse = pygame.mouse.get_pos() 125 | for i in range(3): 126 | for j in range(3): 127 | if (board[i][j] == ttt.EMPTY and tiles[i][j].collidepoint(mouse)): 128 | board = ttt.result(board, (i, j)) 129 | 130 | if game_over: 131 | againButton = pygame.Rect(width / 3, height - 65, width / 3, 50) 132 | again = mediumFont.render("Play Again", True, black) 133 | againRect = again.get_rect() 134 | againRect.center = againButton.center 135 | pygame.draw.rect(screen, white, againButton) 136 | screen.blit(again, againRect) 137 | click, _, _ = pygame.mouse.get_pressed() 138 | if click == 1: 139 | mouse = pygame.mouse.get_pos() 140 | if againButton.collidepoint(mouse): 141 | time.sleep(0.2) 142 | user = None 143 | board = ttt.initial_state() 144 | ai_turn = False 145 | 146 | pygame.display.flip() -------------------------------------------------------------------------------- /Tic-Tac-Toe/tictactoe.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tic Tac Toe Player 3 | """ 4 | 5 | import math, copy 6 | 7 | X = "X" 8 | O = "O" 9 | EMPTY = None 10 | 11 | 12 | def initial_state(): 13 | """ 14 | Returns starting state of the board. 15 | """ 16 | return [[EMPTY, EMPTY, EMPTY], 17 | [EMPTY, EMPTY, EMPTY], 18 | [EMPTY, EMPTY, EMPTY]] 19 | 20 | 21 | def player(board): 22 | """ 23 | Returns player who has the next turn on a board. 24 | """ 25 | 26 | # if count of X on board is equal to count of O on board, then its X's turn, else its O's turn. 27 | X_count = 0 28 | O_count = 0 29 | for i in range(3): 30 | for j in range(3): 31 | if board[i][j] == X: 32 | X_count += 1 33 | if board[i][j] == O: 34 | O_count += 1 35 | 36 | if X_count == O_count: 37 | return X 38 | else: 39 | return O 40 | 41 | # raise NotImplementedError 42 | 43 | 44 | def actions(board): 45 | """ 46 | Returns set of all possible actions (i, j) available on the board. 47 | """ 48 | 49 | action = set() 50 | for i in range(3): 51 | for j in range(3): 52 | if board[i][j] == EMPTY: 53 | action.add((i,j)) 54 | 55 | return action 56 | 57 | # raise NotImplementedError 58 | 59 | 60 | def result(board, action): 61 | """ 62 | Returns the board that results from making move (i, j) on the board. 63 | """ 64 | 65 | # action here is a set of i, j 66 | i, j = action 67 | 68 | # if action is valid then we will return a board state after impling the action, else will raise an error 69 | if i <= 2 and j <= 2 and board[i][j] == EMPTY: 70 | new_board = copy.deepcopy(board) 71 | new_board[i][j] = player(board) 72 | return new_board 73 | 74 | else: 75 | raise Exception("Action is Invalid") 76 | 77 | # raise NotImplementedError 78 | 79 | 80 | def is_over(board): 81 | # for horizontals and vertical 82 | for i in range(3): 83 | if board[i][0] == board[i][1] == board[i][2]: 84 | if board[i][0] == X or board[i][0] == O: 85 | return True 86 | 87 | if board[0][i] == board[1][i] == board[2][i]: 88 | if board[0][i] == X or board[0][i] == O: 89 | return True 90 | 91 | # for diagonals 92 | if board[0][0] == board[1][1] == board[2][2]: 93 | if board[1][1] == X or board[1][1] == O: 94 | return True 95 | 96 | if board[0][2] == board[1][1] == board[2][0]: 97 | if board[1][1] == X or board[1][1] == O: 98 | return True 99 | 100 | return False 101 | 102 | def winner(board): 103 | """ 104 | Returns the winner of the game, if there is one. 105 | """ 106 | # if someone won and it shows next move (hypothetical) to be of X, that implies O wins and vice versa 107 | if is_over(board): 108 | if player(board) == X: 109 | return O 110 | else: 111 | return X 112 | 113 | # raise NotImplementedError 114 | 115 | 116 | def terminal(board): 117 | """ 118 | Returns True if game is over, False otherwise. 119 | """ 120 | 121 | # if someone one the game, it's a terminal board 122 | if is_over(board): 123 | return True 124 | 125 | # if no one wins, and there are empty space that implies more moves to be played 126 | # therfore it is not terminal board 127 | # if no cell is empty and no one won, i.e. it's tie then also it's terminal board 128 | else: 129 | for i in range(3): 130 | for j in range(3): 131 | if board[i][j] == EMPTY: 132 | return False 133 | return True 134 | 135 | # raise NotImplementedError 136 | 137 | 138 | def utility(board): 139 | """ 140 | Returns 1 if X has won the game, -1 if O has won, 0 otherwise. 141 | """ 142 | 143 | # if someone has won the game, utility will be 1 or -1 according to who won 144 | # X wins --> utility = 1 145 | # O wins --> utility = -1 146 | if is_over(board): 147 | if winner(board) == X: 148 | return 1 149 | elif winner(board) == O: 150 | return -1 151 | 152 | # if no one won and its a terminal board i.e. it is a tie, then utility will be 0 153 | if is_over(board) == False and terminal(board) == True: 154 | return 0 155 | 156 | # raise NotImplementedError 157 | 158 | 159 | def minimax(board): 160 | """ 161 | Returns the optimal action for the current player on the board. 162 | """ 163 | 164 | # if it is already a terminal board, nothing will be returned 165 | if terminal(board): 166 | return None 167 | 168 | else: 169 | # if next move (of AI) is from X, then max_value function is called, and it returns the optimized move 170 | if player(board) == X: 171 | value, move = max_value(board) 172 | return move 173 | 174 | # if next move (of AI) is from O, then min_value function is called, and it returns the optimized move 175 | else: 176 | value, move = min_value(board) 177 | return move 178 | 179 | # raise NotImplementedError 180 | 181 | def max_value(board): 182 | # if it is already a terminal board, it returns the utility of the board 183 | if terminal(board): 184 | return utility(board), None 185 | 186 | # for getting max value, setting value to -200 187 | v = -200 188 | move = None 189 | 190 | # iteration to all possible actions 191 | for action in actions(board): 192 | 193 | # getting the most optimized utility and move after opponents move 194 | a, b = min_value(result(board, action)) 195 | 196 | # if value is less then utility, change value to that and move to the action through which this is got 197 | if a > v: 198 | v = a 199 | move = action 200 | 201 | # if the value gets to 1 return the move 202 | if v == 1: 203 | return v, move 204 | 205 | return v, move 206 | 207 | def min_value(board): 208 | # if it is already a terminal board, it returns the utility of the board 209 | if terminal(board): 210 | return utility(board), None 211 | 212 | # for getting min value, setting value to 200 213 | v = 200 214 | move = None 215 | 216 | # iteration to all possible actions 217 | for action in actions(board): 218 | 219 | # getting the most optimized utility and move after opponents move 220 | a, b = max_value(result(board, action)) 221 | 222 | # if value is greater then utility, change value to that and move to the action through which this is got 223 | if a < v: 224 | v = a 225 | move = action 226 | 227 | # if the value gets to -1 return the move 228 | if v == -1: 229 | return v, move 230 | 231 | return v, move -------------------------------------------------------------------------------- /Twitter Sentiment Analysis with RoBERTa/readme.md: -------------------------------------------------------------------------------- 1 | #Twitter Sentiment Analysis with RoBERTa 2 | 3 | What I have done in this project is essentially use the twitter API to request the last 20 tweets of a random user in my case CardinalSama (one of my friends, I took his permission) and run the RoBERTa model to determine the sentiment of the tweets. 4 | 5 | Unlike the VADER model however, this model is relatively more successful in categorising the tweets correctly. However certain tweets having sarcasm or satire don't work as well. 6 | 7 | ![Result](./result.png "Positive,Negative and neutral result plots") 8 | -------------------------------------------------------------------------------- /Twitter Sentiment Analysis with RoBERTa/requirements.txt: -------------------------------------------------------------------------------- 1 | pandas~=1.2.4 2 | numpy~=1.20.1 3 | matplotlib~=3.3.4 4 | seaborn~=0.11.1 5 | tweepy~=4.1.0 6 | requests~=2.28.1 7 | nltk~=3.6.1 8 | tqdm~=2.59.0 9 | transformers~=4.2.3 10 | scipy~=1.6.2 11 | torch~=1.12.1 -------------------------------------------------------------------------------- /Twitter Sentiment Analysis with RoBERTa/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Twitter Sentiment Analysis with RoBERTa/result.png -------------------------------------------------------------------------------- /Twitter Sentiment Analysis with VADER/readme.md: -------------------------------------------------------------------------------- 1 | #Twitter Sentiment Analysis with VADER 2 | 3 | What I have done in this project is essentially use the twitter API to request the last 20 tweets of a random user in my case CardinalSama (one of my friends, I took his permission) and run the VADER model to determine the sentiment of the tweets. 4 | 5 | However as you will can see in the graphic, this is very rudimentary and is classing most of his posts as neutral where they are clearly positive or negative. 6 | 7 | ![Result](./result.png "Positive,Negative and neutral result plots") 8 | 9 | This is where VADER falls short, while being a relatively simple model, and reliablein shorter reviews / ratings system, it ultimately falls short while dealing with larger, more complex sentences. 10 | 11 | For such cases models such as RoBERTa are much better 12 | -------------------------------------------------------------------------------- /Twitter Sentiment Analysis with VADER/requirements.txt: -------------------------------------------------------------------------------- 1 | pandas~=1.2.4 2 | numpy~=1.20.1 3 | matplotlib~=3.3.4 4 | seaborn~=0.11.1 5 | tweepy~=4.1.0 6 | requests~=2.28.1 7 | nltk~=3.6.1 8 | tqdm~=2.59.0 9 | -------------------------------------------------------------------------------- /Twitter Sentiment Analysis with VADER/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/Twitter Sentiment Analysis with VADER/result.png -------------------------------------------------------------------------------- /Web_Scrapper/LinkedIn_Scrapper.ipynb: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Web_Scrapper/Twitter scraper.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 10, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "Enter Twitter HashTag to search for\n", 13 | "Accolite Digital\n", 14 | "Enter Date since The Tweets are required in yyyy-mm--dd\n", 15 | "2022-09-01\n", 16 | "\n", 17 | "Tweet 1:\n", 18 | "Username:codefor30days\n", 19 | "Description:I will retweet your tweet if it has #codefor30days or #100daysofcode in it. \n", 20 | "Original Twitter account: @_rishuverma\n", 21 | "GitHub: https://t.co/v5iUDzHRd9\n", 22 | "Location:\n", 23 | "Following Count:5002\n", 24 | "Follower Count:1800\n", 25 | "Total Tweets:194944\n", 26 | "Retweet Count:3\n", 27 | "Tweet Text:Day 13 of #100DaysOfCode \n", 28 | "Gave a mocktest on Accolite Digital platform\n", 29 | "Went through Computer networks and Operating systems notes for the placement test\n", 30 | "Hashtags Used:['100DaysOfCode']\n", 31 | "\n", 32 | "Tweet 2:\n", 33 | "Username:TeddyBearIsABot\n", 34 | "Description:Hi im a 🤖. I’ll 🔁 your #100daysofcode process! ily! you can block me if you don’t want me to! 🥺wish you all the best with your learning journey!!🦾🥳\n", 35 | "Location:Python🤖\n", 36 | "Following Count:1\n", 37 | "Follower Count:152\n", 38 | "Total Tweets:46023\n", 39 | "Retweet Count:3\n", 40 | "Tweet Text:Day 13 of #100DaysOfCode \n", 41 | "Gave a mocktest on Accolite Digital platform\n", 42 | "Went through Computer networks and Operating systems notes for the placement test\n", 43 | "Hashtags Used:['100DaysOfCode']\n", 44 | "\n", 45 | "Tweet 3:\n", 46 | "Username:BotKoshur\n", 47 | "Description:I RT #100DaysOfCode currently .\n", 48 | "Made with #nodejs and #twit.\n", 49 | "created by @__junaidshah\n", 50 | "\n", 51 | "Support me by Buying me a coffee(https://t.co/2OgKj8iqga)\n", 52 | "Location:\n", 53 | "Following Count:1\n", 54 | "Follower Count:656\n", 55 | "Total Tweets:67436\n", 56 | "Retweet Count:3\n", 57 | "Tweet Text:Day 13 of #100DaysOfCode \n", 58 | "Gave a mocktest on Accolite Digital platform\n", 59 | "Went through Computer networks and Operating systems notes for the placement test\n", 60 | "Hashtags Used:['100DaysOfCode']\n", 61 | "\n", 62 | "Tweet 4:\n", 63 | "Username:AKotamsetty\n", 64 | "Description:\n", 65 | "Location:\n", 66 | "Following Count:14\n", 67 | "Follower Count:17\n", 68 | "Total Tweets:19\n", 69 | "Retweet Count:3\n", 70 | "Tweet Text:Day 13 of #100DaysOfCode \n", 71 | "Gave a mocktest on Accolite Digital platform\n", 72 | "Went through Computer networks and Operating systems notes for the placement test\n", 73 | "Hashtags Used:['100DaysOfCode']\n", 74 | "\n", 75 | "Tweet 5:\n", 76 | "Username:zobjobsUS\n", 77 | "Description:Thousands of the Latest Working From Home Jobs updated every hour & Free job postings from the fastest growing jobs platform\n", 78 | "#remotework #workfromhome\n", 79 | "Location:United States US\n", 80 | "Following Count:3\n", 81 | "Follower Count:2122\n", 82 | "Total Tweets:122443\n", 83 | "Retweet Count:0\n", 84 | "Tweet Text:Remote- Project Manager - (SAP, Supply chain management & Cloud Migration)\n", 85 | "at Accolite Digital\n", 86 | "About us Accolite Di...\n", 87 | "#Management #remoteworking #accolitedigital\n", 88 | "https://t.co/QCXNbHkGnB\n", 89 | "Hashtags Used:['Management', 'remoteworking', 'accolitedigital']\n", 90 | "Scraping has completed!\n" 91 | ] 92 | } 93 | ], 94 | "source": [ 95 | "# Python Script to Extract tweets of a\n", 96 | "# particular Hashtag using Tweepy and Pandas\n", 97 | "\n", 98 | "# import modules\n", 99 | "import pandas as pd\n", 100 | "import tweepy\n", 101 | "\n", 102 | "# function to display data of each tweet\n", 103 | "def printtweetdata(n, ith_tweet):\n", 104 | "\t\tprint()\n", 105 | "\t\tprint(f\"Tweet {n}:\")\n", 106 | "\t\tprint(f\"Username:{ith_tweet[0]}\")\n", 107 | "\t\tprint(f\"Description:{ith_tweet[1]}\")\n", 108 | "\t\tprint(f\"Location:{ith_tweet[2]}\")\n", 109 | "\t\tprint(f\"Following Count:{ith_tweet[3]}\")\n", 110 | "\t\tprint(f\"Follower Count:{ith_tweet[4]}\")\n", 111 | "\t\tprint(f\"Total Tweets:{ith_tweet[5]}\")\n", 112 | "\t\tprint(f\"Retweet Count:{ith_tweet[6]}\")\n", 113 | "\t\tprint(f\"Tweet Text:{ith_tweet[7]}\")\n", 114 | "\t\tprint(f\"Hashtags Used:{ith_tweet[8]}\")\n", 115 | "\n", 116 | "\n", 117 | "# function to perform data extraction\n", 118 | "def scrape(words, date_since, numtweet):\n", 119 | "\n", 120 | "\t\t# Creating DataFrame using pandas\n", 121 | "\t\tdb = pd.DataFrame(columns=['username',\n", 122 | "\t\t\t\t\t\t\t\t'description',\n", 123 | "\t\t\t\t\t\t\t\t'location',\n", 124 | "\t\t\t\t\t\t\t\t'following',\n", 125 | "\t\t\t\t\t\t\t\t'followers',\n", 126 | "\t\t\t\t\t\t\t\t'totaltweets',\n", 127 | "\t\t\t\t\t\t\t\t'retweetcount',\n", 128 | "\t\t\t\t\t\t\t\t'text',\n", 129 | "\t\t\t\t\t\t\t\t'hashtags'])\n", 130 | "\n", 131 | "\t\t# We are using .Cursor() to search\n", 132 | "\t\t# through twitter for the required tweets.\n", 133 | "\t\t# The number of tweets can be\n", 134 | "\t\t# restricted using .items(number of tweets)\n", 135 | "\t\ttweets = tweepy.Cursor(api.search_tweets,\n", 136 | "\t\t\t\t\t\t\twords, lang=\"en\",\n", 137 | "\t\t\t\t\t\t\tsince_id=date_since,\n", 138 | "\t\t\t\t\t\t\ttweet_mode='extended').items(numtweet)\n", 139 | "\n", 140 | "\n", 141 | "\t\t# .Cursor() returns an iterable object. Each item in\n", 142 | "\t\t# the iterator has various attributes\n", 143 | "\t\t# that you can access to\n", 144 | "\t\t# get information about each tweet\n", 145 | "\t\tlist_tweets = [tweet for tweet in tweets]\n", 146 | "\n", 147 | "\t\t# Counter to maintain Tweet Count\n", 148 | "\t\ti = 1\n", 149 | "\n", 150 | "\t\t# we will iterate over each tweet in the\n", 151 | "\t\t# list for extracting information about each tweet\n", 152 | "\t\tfor tweet in list_tweets:\n", 153 | "\t\t\t\tusername = tweet.user.screen_name\n", 154 | "\t\t\t\tdescription = tweet.user.description\n", 155 | "\t\t\t\tlocation = tweet.user.location\n", 156 | "\t\t\t\tfollowing = tweet.user.friends_count\n", 157 | "\t\t\t\tfollowers = tweet.user.followers_count\n", 158 | "\t\t\t\ttotaltweets = tweet.user.statuses_count\n", 159 | "\t\t\t\tretweetcount = tweet.retweet_count\n", 160 | "\t\t\t\thashtags = tweet.entities['hashtags']\n", 161 | "\n", 162 | "\t\t\t\t# Retweets can be distinguished by\n", 163 | "\t\t\t\t# a retweeted_status attribute,\n", 164 | "\t\t\t\t# in case it is an invalid reference,\n", 165 | "\t\t\t\t# except block will be executed\n", 166 | "\t\t\t\ttry:\n", 167 | "\t\t\t\t\t\ttext = tweet.retweeted_status.full_text\n", 168 | "\t\t\t\texcept AttributeError:\n", 169 | "\t\t\t\t\t\ttext = tweet.full_text\n", 170 | "\t\t\t\thashtext = list()\n", 171 | "\t\t\t\tfor j in range(0, len(hashtags)):\n", 172 | "\t\t\t\t\t\thashtext.append(hashtags[j]['text'])\n", 173 | "\n", 174 | "\t\t\t\t# Here we are appending all the\n", 175 | "\t\t\t\t# extracted information in the DataFrame\n", 176 | "\t\t\t\tith_tweet = [username, description,\n", 177 | "\t\t\t\t\t\t\tlocation, following,\n", 178 | "\t\t\t\t\t\t\tfollowers, totaltweets,\n", 179 | "\t\t\t\t\t\t\tretweetcount, text, hashtext]\n", 180 | "\t\t\t\tdb.loc[len(db)] = ith_tweet\n", 181 | "\n", 182 | "\t\t\t\t# Function call to print tweet data on screen\n", 183 | "\t\t\t\tprinttweetdata(i, ith_tweet)\n", 184 | "\t\t\t\ti = i+1\n", 185 | "\t\tfilename = 'scraped_tweets.csv'\n", 186 | "\n", 187 | "\t\t# we will save our database as a CSV file.\n", 188 | "\t\tdb.to_csv(filename)\n", 189 | "\n", 190 | "if __name__ == '__main__':\n", 191 | "\n", 192 | "\t\t# Enter your own credentials obtained\n", 193 | "\t\t# from your developer account\n", 194 | "\t\tconsumer_key = \"3Rf9lK5tMJsOMdOkyXN0rDziY\"\n", 195 | "\t\tconsumer_secret = \"EToTwjI1Ue6eO8MmtVTX97wMRnPSjiXA1bsEs3xksBTSI5AOpX\"\n", 196 | "\t\taccess_key = \"1261243073754918913-bD5fEJR1F3Z6lOEidKSIvCfBbBW3nf\"\n", 197 | "\t\taccess_secret = \"WvcTfpP75btc4z8ezX55a0EmyXfJMeCT4U59nVnpDHx9Y\"\n", 198 | "\n", 199 | "\n", 200 | "\t\tauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n", 201 | "\t\tauth.set_access_token(access_key, access_secret)\n", 202 | "\t\tapi = tweepy.API(auth)\n", 203 | "\n", 204 | "\t\t# Enter Hashtag and initial date\n", 205 | "\t\tprint(\"Enter Twitter HashTag to search for\")\n", 206 | "\t\twords = input()\n", 207 | "\t\tprint(\"Enter Date since The Tweets are required in yyyy-mm--dd\")\n", 208 | "\t\tdate_since = input()\n", 209 | "\n", 210 | "\t\t# number of tweets you want to extract in one run\n", 211 | "\t\tnumtweet = 10\n", 212 | "\t\tscrape(words, date_since, numtweet)\n", 213 | "\t\tprint('Scraping has completed!')\n" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "metadata": {}, 220 | "outputs": [], 221 | "source": [] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [] 229 | } 230 | ], 231 | "metadata": { 232 | "kernelspec": { 233 | "display_name": "Python 3", 234 | "language": "python", 235 | "name": "python3" 236 | }, 237 | "language_info": { 238 | "codemirror_mode": { 239 | "name": "ipython", 240 | "version": 3 241 | }, 242 | "file_extension": ".py", 243 | "mimetype": "text/x-python", 244 | "name": "python", 245 | "nbconvert_exporter": "python", 246 | "pygments_lexer": "ipython3", 247 | "version": "3.8.3" 248 | } 249 | }, 250 | "nbformat": 4, 251 | "nbformat_minor": 5 252 | } 253 | -------------------------------------------------------------------------------- /decision tree classifier/Decision Tree Classifier (without sklearn).ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Importing Dataset" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import pandas as pd\n", 17 | "import math\n", 18 | "import os\n", 19 | "import numpy as np" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "## Loading Dataset " 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 2, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "data = pd.read_csv(\"Tennis.csv\")\n", 36 | "# print(data)\n", 37 | "features = [feat for feat in data]\n", 38 | "# features.remove(\"ID\")\n", 39 | "features.remove(\"playtennis\")" 40 | ] 41 | }, 42 | { 43 | "cell_type": "markdown", 44 | "metadata": {}, 45 | "source": [ 46 | "## Creating Decision Tree using ID3 Algorithm" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 3, 52 | "metadata": {}, 53 | "outputs": [ 54 | { 55 | "name": "stdout", 56 | "output_type": "stream", 57 | "text": [ 58 | "outlook\n", 59 | "\tovercast -> ['yes']\n", 60 | "\n", 61 | "\train\n", 62 | "\t\twind\n", 63 | "\t\t\tstrong -> ['no']\n", 64 | "\n", 65 | "\t\t\tweak -> ['yes']\n", 66 | "\n", 67 | "\tsunny\n", 68 | "\t\thumidity\n", 69 | "\t\t\thigh -> ['no']\n", 70 | "\n", 71 | "\t\t\tnormal -> ['yes']\n", 72 | "\n" 73 | ] 74 | } 75 | ], 76 | "source": [ 77 | "class Node:\n", 78 | " def __init__(self):\n", 79 | " self.children = []\n", 80 | " self.value = \"\"\n", 81 | " self.isLeaf = False\n", 82 | " self.pred = \"\"\n", 83 | " \n", 84 | "def entropy(examples):\n", 85 | " pos = 0.0\n", 86 | " neg = 0.0\n", 87 | " for _, row in examples.iterrows():\n", 88 | " if row[\"playtennis\"] == \"yes\":\n", 89 | " pos += 1\n", 90 | " else:\n", 91 | " neg += 1\n", 92 | " if pos == 0.0 or neg == 0.0:\n", 93 | " return 0.0\n", 94 | " else:\n", 95 | " p = pos / (pos + neg)\n", 96 | " n = neg / (pos + neg)\n", 97 | " return -(p * math.log(p, 2) + n * math.log(n, 2))\n", 98 | "\n", 99 | "def info_gain(examples, attr):\n", 100 | " uniq = np.unique(examples[attr])\n", 101 | " gain = entropy(examples)\n", 102 | " for u in uniq:\n", 103 | " subdata = examples[examples[attr] == u]\n", 104 | " sub_e = entropy(subdata)\n", 105 | " gain -= (float(len(subdata)) / float(len(examples))) * sub_e\n", 106 | " return gain\n", 107 | "\n", 108 | "def ID3(examples, attrs):\n", 109 | " root = Node()\n", 110 | " max_gain = 0.0\n", 111 | " max_feat = \"\"\n", 112 | " for feature in attrs:\n", 113 | " gain = info_gain(examples, feature)\n", 114 | " if gain == 0.0:\n", 115 | " return None\n", 116 | " if gain > max_gain:\n", 117 | " max_gain = gain\n", 118 | " max_feat = feature\n", 119 | " root.value = max_feat\n", 120 | " \n", 121 | " if max_feat not in features:\n", 122 | " return\n", 123 | " uniq = np.unique(examples[max_feat])\n", 124 | " for u in uniq:\n", 125 | " subdata = examples[examples[max_feat] == u]\n", 126 | " if entropy(subdata) == 0:\n", 127 | " newNode = Node()\n", 128 | " newNode.isLeaf = True\n", 129 | " newNode.value = u\n", 130 | " newNode.pred = np.unique(subdata[\"playtennis\"])\n", 131 | " root.children.append(newNode)\n", 132 | " else:\n", 133 | " dummyNode = Node()\n", 134 | " dummyNode.value = u\n", 135 | " new_attrs = attrs.copy()\n", 136 | " new_attrs.remove(max_feat)\n", 137 | " child = ID3(subdata, new_attrs)\n", 138 | " dummyNode.children.append(child)\n", 139 | " root.children.append(dummyNode)\n", 140 | " return root\n", 141 | "\n", 142 | "def printTree(root: Node, depth=0):\n", 143 | " for i in range(depth):\n", 144 | " print(\"\\t\", end=\"\")\n", 145 | " if root is not None:\n", 146 | " print(root.value, end=\"\")\n", 147 | " if root is not None and root.isLeaf:\n", 148 | " print(\" -> \", root.pred)\n", 149 | " print()\n", 150 | " if root is not None:\n", 151 | " for child in root.children:\n", 152 | " printTree(child, depth + 1)\n", 153 | "\n", 154 | "root = ID3(data, features)\n", 155 | "printTree(root)" 156 | ] 157 | } 158 | ], 159 | "metadata": { 160 | "kernelspec": { 161 | "display_name": "Python 3", 162 | "language": "python", 163 | "name": "python3" 164 | }, 165 | "language_info": { 166 | "codemirror_mode": { 167 | "name": "ipython", 168 | "version": 3 169 | }, 170 | "file_extension": ".py", 171 | "mimetype": "text/x-python", 172 | "name": "python", 173 | "nbconvert_exporter": "python", 174 | "pygments_lexer": "ipython3", 175 | "version": "3.8.5" 176 | } 177 | }, 178 | "nbformat": 4, 179 | "nbformat_minor": 5 180 | } 181 | -------------------------------------------------------------------------------- /decision tree classifier/Tennis.csv: -------------------------------------------------------------------------------- 1 | outlook,temperature,humidity,wind,playtennis 2 | sunny,hot,high,weak,no 3 | sunny,hot,high,strong,no 4 | overcast,hot,high,weak,yes 5 | rain,mild,high,weak,yes 6 | rain,cool,normal,weak,yes 7 | rain,cool,normal,strong,no 8 | overcast,cool,normal,strong,yes 9 | sunny,mild,high,weak,no 10 | sunny,cool,normal,weak,yes 11 | rain,mild,normal,weak,yes 12 | sunny,mild,normal,strong,yes 13 | overcast,mild,high,strong,yes 14 | overcast,hot,normal,weak,yes 15 | rain,mild,high,strong,no 16 | -------------------------------------------------------------------------------- /knights/README.md: -------------------------------------------------------------------------------- 1 | ## Understanding 2 | 3 | `Logic.py` defines several classes for different types of logical connectives. These classes can be composed within each other, so an expression like `And(Not(A), Or(B, C))` represents the logical sentence stating that symbol `A` is not true, and that symbol `B` or symbol `C` is true (where “or” here refers to inclusive, not exclusive, or). 4 | 5 | `logic.py` also contains a function `model_check`. `model_check` takes a knowledge base and a query. The knowledge base is a single logical sentence: if multiple logical sentences are known, they can be joined together in an `And` expression. `model_check` recursively considers all possible models, and returns `True` if the knowledge base entails the query, and returns `False` otherwise. 6 | 7 | Now, take a look at `puzzle.py`. At the top, we’ve defined six propositional symbols. `AKnight`, for example, represents the sentence that “A is a knight,” while `AKnave` represents the sentence that “A is a knave.” We’ve similarly defined propositional symbols for characters B and C as well. 8 | 9 | What follows are four different knowledge bases, `knowledge0`, `knowledge1`, `knowledge2`, and `knowledge3`, which will contain the knowledge needed to deduce the solutions to the upcoming Puzzles 0, 1, 2, and 3, respectively. Notice that, for now, each of these knowledge bases is empty. That’s where you come in! 10 | 11 | The `main` function of this `puzzle.py` loops over all puzzles, and uses model checking to compute, given the knowledge for that puzzle, whether each character is a knight or a knave, printing out any conclusions that the model checking algorithm is able to make. 12 | 13 | 14 | 15 | ## Specifications 16 | 17 | Add knowledge to knowledge bases `knowledge0`, `knowledge1`, `knowledge2`, and `knowledge3` to solve the following puzzles. 18 | 19 | - Puzzle 0 is the puzzle from the Background. It contains a single character, A. 20 | - A says “I am both a knight and a knave.” 21 | - Puzzle 1 has two characters: A and B. 22 | - A says “We are both knaves.” 23 | - B says nothing. 24 | - Puzzle 2 has two characters: A and B. 25 | - A says “We are the same kind.” 26 | - B says “We are of different kinds.” 27 | - Puzzle 3 has three characters: A, B, and C. 28 | - A says either “I am a knight.” or “I am a knave.”, but you don’t know which. 29 | - B says “A said ‘I am a knave.’” 30 | - B then says “C is a knave.” 31 | - C says “A is a knight.” 32 | 33 | In each of the above puzzles, each character is either a knight or a knave. Every sentence spoken by a knight is true, and every sentence spoken by a knave is false. 34 | 35 | you can run `python puzzle.py` to see the solution to the puzzle. -------------------------------------------------------------------------------- /knights/__pycache__/logic.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/knights/__pycache__/logic.cpython-38.pyc -------------------------------------------------------------------------------- /knights/__pycache__/logic.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/knights/__pycache__/logic.cpython-39.pyc -------------------------------------------------------------------------------- /knights/logic.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | 4 | class Sentence(): 5 | 6 | def evaluate(self, model): 7 | """Evaluates the logical sentence.""" 8 | raise Exception("nothing to evaluate") 9 | 10 | def formula(self): 11 | """Returns string formula representing logical sentence.""" 12 | return "" 13 | 14 | def symbols(self): 15 | """Returns a set of all symbols in the logical sentence.""" 16 | return set() 17 | 18 | @classmethod 19 | def validate(cls, sentence): 20 | if not isinstance(sentence, Sentence): 21 | raise TypeError("must be a logical sentence") 22 | 23 | @classmethod 24 | def parenthesize(cls, s): 25 | """Parenthesizes an expression if not already parenthesized.""" 26 | def balanced(s): 27 | """Checks if a string has balanced parentheses.""" 28 | count = 0 29 | for c in s: 30 | if c == "(": 31 | count += 1 32 | elif c == ")": 33 | if count <= 0: 34 | return False 35 | count -= 1 36 | return count == 0 37 | if not len(s) or s.isalpha() or ( 38 | s[0] == "(" and s[-1] == ")" and balanced(s[1:-1]) 39 | ): 40 | return s 41 | else: 42 | return f"({s})" 43 | 44 | 45 | class Symbol(Sentence): 46 | 47 | def __init__(self, name): 48 | self.name = name 49 | 50 | def __eq__(self, other): 51 | return isinstance(other, Symbol) and self.name == other.name 52 | 53 | def __hash__(self): 54 | return hash(("symbol", self.name)) 55 | 56 | def __repr__(self): 57 | return self.name 58 | 59 | def evaluate(self, model): 60 | try: 61 | return bool(model[self.name]) 62 | except KeyError: 63 | raise Exception(f"variable {self.name} not in model") 64 | 65 | def formula(self): 66 | return self.name 67 | 68 | def symbols(self): 69 | return {self.name} 70 | 71 | 72 | class Not(Sentence): 73 | def __init__(self, operand): 74 | Sentence.validate(operand) 75 | self.operand = operand 76 | 77 | def __eq__(self, other): 78 | return isinstance(other, Not) and self.operand == other.operand 79 | 80 | def __hash__(self): 81 | return hash(("not", hash(self.operand))) 82 | 83 | def __repr__(self): 84 | return f"Not({self.operand})" 85 | 86 | def evaluate(self, model): 87 | return not self.operand.evaluate(model) 88 | 89 | def formula(self): 90 | return "¬" + Sentence.parenthesize(self.operand.formula()) 91 | 92 | def symbols(self): 93 | return self.operand.symbols() 94 | 95 | 96 | class And(Sentence): 97 | def __init__(self, *conjuncts): 98 | for conjunct in conjuncts: 99 | Sentence.validate(conjunct) 100 | self.conjuncts = list(conjuncts) 101 | 102 | def __eq__(self, other): 103 | return isinstance(other, And) and self.conjuncts == other.conjuncts 104 | 105 | def __hash__(self): 106 | return hash( 107 | ("and", tuple(hash(conjunct) for conjunct in self.conjuncts)) 108 | ) 109 | 110 | def __repr__(self): 111 | conjunctions = ", ".join( 112 | [str(conjunct) for conjunct in self.conjuncts] 113 | ) 114 | return f"And({conjunctions})" 115 | 116 | def add(self, conjunct): 117 | Sentence.validate(conjunct) 118 | self.conjuncts.append(conjunct) 119 | 120 | def evaluate(self, model): 121 | return all(conjunct.evaluate(model) for conjunct in self.conjuncts) 122 | 123 | def formula(self): 124 | if len(self.conjuncts) == 1: 125 | return self.conjuncts[0].formula() 126 | return " ∧ ".join([Sentence.parenthesize(conjunct.formula()) 127 | for conjunct in self.conjuncts]) 128 | 129 | def symbols(self): 130 | return set.union(*[conjunct.symbols() for conjunct in self.conjuncts]) 131 | 132 | 133 | class Or(Sentence): 134 | def __init__(self, *disjuncts): 135 | for disjunct in disjuncts: 136 | Sentence.validate(disjunct) 137 | self.disjuncts = list(disjuncts) 138 | 139 | def __eq__(self, other): 140 | return isinstance(other, Or) and self.disjuncts == other.disjuncts 141 | 142 | def __hash__(self): 143 | return hash( 144 | ("or", tuple(hash(disjunct) for disjunct in self.disjuncts)) 145 | ) 146 | 147 | def __repr__(self): 148 | disjuncts = ", ".join([str(disjunct) for disjunct in self.disjuncts]) 149 | return f"Or({disjuncts})" 150 | 151 | def evaluate(self, model): 152 | return any(disjunct.evaluate(model) for disjunct in self.disjuncts) 153 | 154 | def formula(self): 155 | if len(self.disjuncts) == 1: 156 | return self.disjuncts[0].formula() 157 | return " ∨ ".join([Sentence.parenthesize(disjunct.formula()) 158 | for disjunct in self.disjuncts]) 159 | 160 | def symbols(self): 161 | return set.union(*[disjunct.symbols() for disjunct in self.disjuncts]) 162 | 163 | 164 | class Implication(Sentence): 165 | def __init__(self, antecedent, consequent): 166 | Sentence.validate(antecedent) 167 | Sentence.validate(consequent) 168 | self.antecedent = antecedent 169 | self.consequent = consequent 170 | 171 | def __eq__(self, other): 172 | return (isinstance(other, Implication) 173 | and self.antecedent == other.antecedent 174 | and self.consequent == other.consequent) 175 | 176 | def __hash__(self): 177 | return hash(("implies", hash(self.antecedent), hash(self.consequent))) 178 | 179 | def __repr__(self): 180 | return f"Implication({self.antecedent}, {self.consequent})" 181 | 182 | def evaluate(self, model): 183 | return ((not self.antecedent.evaluate(model)) 184 | or self.consequent.evaluate(model)) 185 | 186 | def formula(self): 187 | antecedent = Sentence.parenthesize(self.antecedent.formula()) 188 | consequent = Sentence.parenthesize(self.consequent.formula()) 189 | return f"{antecedent} => {consequent}" 190 | 191 | def symbols(self): 192 | return set.union(self.antecedent.symbols(), self.consequent.symbols()) 193 | 194 | 195 | class Biconditional(Sentence): 196 | def __init__(self, left, right): 197 | Sentence.validate(left) 198 | Sentence.validate(right) 199 | self.left = left 200 | self.right = right 201 | 202 | def __eq__(self, other): 203 | return (isinstance(other, Biconditional) 204 | and self.left == other.left 205 | and self.right == other.right) 206 | 207 | def __hash__(self): 208 | return hash(("biconditional", hash(self.left), hash(self.right))) 209 | 210 | def __repr__(self): 211 | return f"Biconditional({self.left}, {self.right})" 212 | 213 | def evaluate(self, model): 214 | return ((self.left.evaluate(model) 215 | and self.right.evaluate(model)) 216 | or (not self.left.evaluate(model) 217 | and not self.right.evaluate(model))) 218 | 219 | def formula(self): 220 | left = Sentence.parenthesize(str(self.left)) 221 | right = Sentence.parenthesize(str(self.right)) 222 | return f"{left} <=> {right}" 223 | 224 | def symbols(self): 225 | return set.union(self.left.symbols(), self.right.symbols()) 226 | 227 | 228 | def model_check(knowledge, query): 229 | """Checks if knowledge base entails query.""" 230 | 231 | def check_all(knowledge, query, symbols, model): 232 | """Checks if knowledge base entails query, given a particular model.""" 233 | 234 | # If model has an assignment for each symbol 235 | if not symbols: 236 | 237 | # If knowledge base is true in model, then query must also be true 238 | if knowledge.evaluate(model): 239 | return query.evaluate(model) 240 | return True 241 | else: 242 | 243 | # Choose one of the remaining unused symbols 244 | remaining = symbols.copy() 245 | p = remaining.pop() 246 | 247 | # Create a model where the symbol is true 248 | model_true = model.copy() 249 | model_true[p] = True 250 | 251 | # Create a model where the symbol is false 252 | model_false = model.copy() 253 | model_false[p] = False 254 | 255 | # Ensure entailment holds in both models 256 | return (check_all(knowledge, query, remaining, model_true) and 257 | check_all(knowledge, query, remaining, model_false)) 258 | 259 | # Get all symbols in both knowledge and query 260 | symbols = set.union(knowledge.symbols(), query.symbols()) 261 | 262 | # Check that knowledge entails query 263 | return check_all(knowledge, query, symbols, dict()) 264 | -------------------------------------------------------------------------------- /knights/puzzle.py: -------------------------------------------------------------------------------- 1 | from logic import * 2 | 3 | AKnight = Symbol("A is a Knight") 4 | AKnave = Symbol("A is a Knave") 5 | 6 | BKnight = Symbol("B is a Knight") 7 | BKnave = Symbol("B is a Knave") 8 | 9 | CKnight = Symbol("C is a Knight") 10 | CKnave = Symbol("C is a Knave") 11 | 12 | # Puzzle 0 13 | # A says "I am both a knight and a knave." 14 | knowledge0 = And( 15 | # TODO 16 | 17 | # A can only be one of Knave or Knight and not both 18 | And( Or(AKnight, AKnave), 19 | Not( And(AKnight, AKnave)) 20 | ), 21 | 22 | # If A is Knight, then according to what it says it needs to be both Knave and Knight 23 | Implication(AKnight, And(AKnight, AKnave)) 24 | ) 25 | 26 | # Puzzle 1 27 | # A says "We are both knaves." 28 | # B says nothing. 29 | knowledge1 = And( 30 | # TODO 31 | 32 | # A can only be one of Knave or Knight and not both 33 | And( Or(AKnight, AKnave), 34 | Not( And(AKnight, AKnave)) 35 | ), 36 | 37 | # B can only be one of Knave or Knight and not both 38 | And( Or(BKnight, BKnave), 39 | Not( And(BKnight, BKnave)) 40 | ), 41 | 42 | # If A is Knight, i.e. what it says is true, therefore both A and B are Knaves (although this is a contradiction) 43 | Implication(AKnight, And(AKnave, BKnave)), 44 | 45 | # If A is Knave, i.e. what it says is false, therfore both aren't Knaves and that implies B is Knight 46 | Implication(AKnave, BKnight) 47 | ) 48 | 49 | # Puzzle 2 50 | # A says "We are the same kind." 51 | # B says "We are of different kinds." 52 | knowledge2 = And( 53 | # TODO 54 | 55 | # A can only be one of Knave or Knight and not both 56 | And( Or(AKnight, AKnave), 57 | Not( And(AKnight, AKnave)) 58 | ), 59 | 60 | # B can only be one of Knave or Knight and not both 61 | And( Or(BKnight, BKnave), 62 | Not( And(BKnight, BKnave)) 63 | ), 64 | 65 | # According to A's statment if A is Knight, B has to be Knight; and if A is Knave, B has to be still Knight 66 | # Therefore whatever A is, i.e. Knave or Knight, that implies B to be Knight. 67 | Implication( Or(AKnave, AKnight), BKnight), 68 | 69 | # According to B's statment if B is Knight, A has to be Knave; and if B is Knave, A has to be still Knave 70 | # Therefore whatever B is, i.e. Knave or Knight, that implies A to be Knave. 71 | Implication( Or(BKnight, BKnave), AKnave) 72 | ) 73 | 74 | # Puzzle 3 75 | # A says either "I am a knight." or "I am a knave.", but you don't know which. 76 | # B says "A said 'I am a knave'." 77 | # B says "C is a knave." 78 | # C says "A is a knight." 79 | knowledge3 = And( 80 | # TODO 81 | 82 | # A can only be one of Knave or Knight and not both 83 | And( Or(AKnight, AKnave), 84 | Not( And(AKnight, AKnave)) 85 | ), 86 | 87 | # B can only be one of Knave or Knight and not both 88 | And( Or(BKnight, BKnave), 89 | Not( And(BKnight, BKnave)) 90 | ), 91 | 92 | # C can only be one of Knave or Knight and not both 93 | And( Or(CKnight, CKnave), 94 | Not( And(CKnight, CKnave)) 95 | ), 96 | 97 | # If C is Knight, then A will be Knight 98 | Implication(CKnight, AKnight), 99 | 100 | # If B is Knave, according to what it says about C, C will be Knight 101 | Implication(BKnave, CKnight), 102 | 103 | # If A is Knight, It will say "I am a knight.", and if A is Knave it will say the same i.e. "I am a knight." 104 | # As in any case of A, A will never say "I am a knave.", this implies B is Knave 105 | Implication( Or(AKnight, AKnave), BKnave) 106 | ) 107 | 108 | 109 | def main(): 110 | symbols = [AKnight, AKnave, BKnight, BKnave, CKnight, CKnave] 111 | puzzles = [ 112 | ("Puzzle 0", knowledge0), 113 | ("Puzzle 1", knowledge1), 114 | ("Puzzle 2", knowledge2), 115 | ("Puzzle 3", knowledge3) 116 | ] 117 | for puzzle, knowledge in puzzles: 118 | print(puzzle) 119 | if len(knowledge.conjuncts) == 0: 120 | print(" Not yet implemented.") 121 | else: 122 | for symbol in symbols: 123 | if model_check(knowledge, symbol): 124 | print(f" {symbol}") 125 | 126 | 127 | if __name__ == "__main__": 128 | main() 129 | -------------------------------------------------------------------------------- /market-basket-analysis Apriori/Apriori.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "2b2761cd", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "# Importing Libraries\n", 11 | "\n", 12 | "import numpy as np\n", 13 | "import pandas as pd\n", 14 | "import matplotlib.pyplot as plt\n", 15 | "from apyori import apriori" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 2, 21 | "id": "adb8366e", 22 | "metadata": {}, 23 | "outputs": [ 24 | { 25 | "data": { 26 | "text/html": [ 27 | "
\n", 28 | "\n", 41 | "\n", 42 | " \n", 43 | " \n", 44 | " \n", 45 | " \n", 46 | " \n", 47 | " \n", 48 | " \n", 49 | " \n", 50 | " \n", 51 | " \n", 52 | " \n", 53 | " \n", 54 | " \n", 55 | " \n", 56 | " \n", 57 | " \n", 58 | " \n", 59 | " \n", 60 | " \n", 61 | " \n", 62 | " \n", 63 | " \n", 64 | " \n", 65 | " \n", 66 | " \n", 67 | " \n", 68 | " \n", 69 | " \n", 70 | " \n", 71 | " \n", 72 | " \n", 73 | " \n", 74 | " \n", 75 | " \n", 76 | " \n", 77 | " \n", 78 | " \n", 79 | " \n", 80 | " \n", 81 | " \n", 82 | " \n", 83 | " \n", 84 | " \n", 85 | " \n", 86 | " \n", 87 | " \n", 88 | " \n", 89 | " \n", 90 | " \n", 91 | " \n", 92 | " \n", 93 | " \n", 94 | " \n", 95 | " \n", 96 | " \n", 97 | " \n", 98 | " \n", 99 | " \n", 100 | " \n", 101 | " \n", 102 | " \n", 103 | " \n", 104 | " \n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | " \n", 113 | " \n", 114 | " \n", 115 | " \n", 116 | " \n", 117 | " \n", 118 | " \n", 119 | " \n", 120 | " \n", 121 | " \n", 122 | " \n", 123 | " \n", 124 | " \n", 125 | " \n", 126 | " \n", 127 | " \n", 128 | " \n", 129 | " \n", 130 | " \n", 131 | " \n", 132 | " \n", 133 | " \n", 134 | " \n", 135 | " \n", 136 | " \n", 137 | " \n", 138 | " \n", 139 | " \n", 140 | " \n", 141 | " \n", 142 | " \n", 143 | " \n", 144 | " \n", 145 | " \n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " \n", 151 | " \n", 152 | " \n", 153 | " \n", 154 | " \n", 155 | " \n", 156 | " \n", 157 | " \n", 158 | " \n", 159 | " \n", 160 | " \n", 161 | " \n", 162 | " \n", 163 | " \n", 164 | " \n", 165 | " \n", 166 | " \n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | " \n", 179 | " \n", 180 | " \n", 181 | " \n", 182 | " \n", 183 | " \n", 184 | "
012345678910111213141516171819
0shrimpalmondsavocadovegetables mixgreen grapeswhole weat flouryamscottage cheeseenergy drinktomato juicelow fat yogurtgreen teahoneysaladmineral watersalmonantioxydant juicefrozen smoothiespinacholive oil
1burgersmeatballseggsNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
2chutneyNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
3turkeyavocadoNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
4mineral watermilkenergy barwhole wheat ricegreen teaNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
\n", 185 | "
" 186 | ], 187 | "text/plain": [ 188 | " 0 1 2 3 4 \\\n", 189 | "0 shrimp almonds avocado vegetables mix green grapes \n", 190 | "1 burgers meatballs eggs NaN NaN \n", 191 | "2 chutney NaN NaN NaN NaN \n", 192 | "3 turkey avocado NaN NaN NaN \n", 193 | "4 mineral water milk energy bar whole wheat rice green tea \n", 194 | "\n", 195 | " 5 6 7 8 9 \\\n", 196 | "0 whole weat flour yams cottage cheese energy drink tomato juice \n", 197 | "1 NaN NaN NaN NaN NaN \n", 198 | "2 NaN NaN NaN NaN NaN \n", 199 | "3 NaN NaN NaN NaN NaN \n", 200 | "4 NaN NaN NaN NaN NaN \n", 201 | "\n", 202 | " 10 11 12 13 14 15 \\\n", 203 | "0 low fat yogurt green tea honey salad mineral water salmon \n", 204 | "1 NaN NaN NaN NaN NaN NaN \n", 205 | "2 NaN NaN NaN NaN NaN NaN \n", 206 | "3 NaN NaN NaN NaN NaN NaN \n", 207 | "4 NaN NaN NaN NaN NaN NaN \n", 208 | "\n", 209 | " 16 17 18 19 \n", 210 | "0 antioxydant juice frozen smoothie spinach olive oil \n", 211 | "1 NaN NaN NaN NaN \n", 212 | "2 NaN NaN NaN NaN \n", 213 | "3 NaN NaN NaN NaN \n", 214 | "4 NaN NaN NaN NaN " 215 | ] 216 | }, 217 | "metadata": {}, 218 | "output_type": "display_data" 219 | }, 220 | { 221 | "name": "stdout", 222 | "output_type": "stream", 223 | "text": [ 224 | "(7501, 20)\n" 225 | ] 226 | } 227 | ], 228 | "source": [ 229 | "# Loading Dataset\n", 230 | "\n", 231 | "data = pd.read_csv(\"store_data.csv\" , header = None)\n", 232 | "display(data.head())\n", 233 | "print(data.shape)" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": 3, 239 | "id": "e1d22059", 240 | "metadata": {}, 241 | "outputs": [ 242 | { 243 | "name": "stdout", 244 | "output_type": "stream", 245 | "text": [ 246 | "\n" 247 | ] 248 | } 249 | ], 250 | "source": [ 251 | "# Data Preprocessing\n", 252 | "\n", 253 | "rec = []\n", 254 | "for i in range(1, 7501):\n", 255 | " rec.append([str(data.values[i, j]) for j in range(0, 20)])\n", 256 | "\n", 257 | "print(type(rec))" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": 4, 263 | "id": "840bf2e4", 264 | "metadata": {}, 265 | "outputs": [], 266 | "source": [ 267 | "# Implementation of Algorithm\n", 268 | "\n", 269 | "association_rules = apriori(rec, min_support=0.0042, min_confidence=0.2, min_lift=3, min_length=2)\n", 270 | "association_results = list(association_rules)" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": 5, 276 | "id": "bca9f08b", 277 | "metadata": {}, 278 | "outputs": [ 279 | { 280 | "name": "stdout", 281 | "output_type": "stream", 282 | "text": [ 283 | "frozenset({'light cream', 'chicken'})\n", 284 | "frozenset({'escalope', 'mushroom cream sauce'})\n", 285 | "frozenset({'escalope', 'pasta'})\n", 286 | "frozenset({'ground beef', 'herb & pepper'})\n", 287 | "frozenset({'ground beef', 'tomato sauce'})\n", 288 | "frozenset({'whole wheat pasta', 'olive oil'})\n", 289 | "frozenset({'pasta', 'shrimp'})\n", 290 | "frozenset({'light cream', 'nan', 'chicken'})\n", 291 | "frozenset({'frozen vegetables', 'chocolate', 'shrimp'})\n", 292 | "frozenset({'cooking oil', 'spaghetti', 'ground beef'})\n", 293 | "frozenset({'escalope', 'mushroom cream sauce', 'nan'})\n", 294 | "frozenset({'escalope', 'pasta', 'nan'})\n", 295 | "frozenset({'ground beef', 'spaghetti', 'frozen vegetables'})\n", 296 | "frozenset({'olive oil', 'milk', 'frozen vegetables'})\n", 297 | "frozenset({'frozen vegetables', 'mineral water', 'shrimp'})\n", 298 | "frozenset({'olive oil', 'spaghetti', 'frozen vegetables'})\n", 299 | "frozenset({'spaghetti', 'frozen vegetables', 'shrimp'})\n", 300 | "frozenset({'spaghetti', 'tomatoes', 'frozen vegetables'})\n", 301 | "frozenset({'grated cheese', 'spaghetti', 'ground beef'})\n", 302 | "frozenset({'ground beef', 'herb & pepper', 'mineral water'})\n", 303 | "frozenset({'ground beef', 'herb & pepper', 'nan'})\n", 304 | "frozenset({'ground beef', 'herb & pepper', 'spaghetti'})\n", 305 | "frozenset({'ground beef', 'milk', 'olive oil'})\n", 306 | "frozenset({'ground beef', 'tomato sauce', 'nan'})\n", 307 | "frozenset({'ground beef', 'spaghetti', 'shrimp'})\n", 308 | "frozenset({'milk', 'spaghetti', 'olive oil'})\n", 309 | "frozenset({'olive oil', 'soup', 'mineral water'})\n", 310 | "frozenset({'whole wheat pasta', 'olive oil', 'nan'})\n", 311 | "frozenset({'pasta', 'nan', 'shrimp'})\n", 312 | "frozenset({'spaghetti', 'pancakes', 'olive oil'})\n", 313 | "frozenset({'spaghetti', 'tomatoes', 'olive oil'})\n", 314 | "frozenset({'nan', 'frozen vegetables', 'chocolate', 'shrimp'})\n", 315 | "frozenset({'cooking oil', 'spaghetti', 'ground beef', 'nan'})\n", 316 | "frozenset({'ground beef', 'spaghetti', 'frozen vegetables', 'mineral water'})\n", 317 | "frozenset({'ground beef', 'spaghetti', 'frozen vegetables', 'nan'})\n", 318 | "frozenset({'milk', 'spaghetti', 'frozen vegetables', 'mineral water'})\n", 319 | "frozenset({'olive oil', 'milk', 'frozen vegetables', 'nan'})\n", 320 | "frozenset({'nan', 'frozen vegetables', 'mineral water', 'shrimp'})\n", 321 | "frozenset({'olive oil', 'spaghetti', 'frozen vegetables', 'nan'})\n", 322 | "frozenset({'spaghetti', 'frozen vegetables', 'nan', 'shrimp'})\n", 323 | "frozenset({'spaghetti', 'tomatoes', 'frozen vegetables', 'nan'})\n", 324 | "frozenset({'grated cheese', 'spaghetti', 'ground beef', 'nan'})\n", 325 | "frozenset({'ground beef', 'herb & pepper', 'mineral water', 'nan'})\n", 326 | "frozenset({'ground beef', 'herb & pepper', 'spaghetti', 'nan'})\n", 327 | "frozenset({'ground beef', 'milk', 'spaghetti', 'mineral water'})\n", 328 | "frozenset({'ground beef', 'milk', 'olive oil', 'nan'})\n", 329 | "frozenset({'ground beef', 'spaghetti', 'shrimp', 'nan'})\n", 330 | "frozenset({'milk', 'spaghetti', 'olive oil', 'nan'})\n", 331 | "frozenset({'olive oil', 'soup', 'mineral water', 'nan'})\n", 332 | "frozenset({'spaghetti', 'pancakes', 'olive oil', 'nan'})\n", 333 | "frozenset({'spaghetti', 'tomatoes', 'olive oil', 'nan'})\n", 334 | "frozenset({'frozen vegetables', 'ground beef', 'nan', 'spaghetti', 'mineral water'})\n", 335 | "frozenset({'milk', 'frozen vegetables', 'nan', 'spaghetti', 'mineral water'})\n", 336 | "frozenset({'milk', 'ground beef', 'nan', 'spaghetti', 'mineral water'})\n" 337 | ] 338 | } 339 | ], 340 | "source": [ 341 | "# Total rules derived\n", 342 | "\n", 343 | "for i in range(0, len(association_results)):\n", 344 | " print(association_results[i][0])" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": 6, 350 | "id": "c7f350f7", 351 | "metadata": {}, 352 | "outputs": [ 353 | { 354 | "name": "stdout", 355 | "output_type": "stream", 356 | "text": [ 357 | "Rule: light cream > chicken\n", 358 | "Support: 0.004533333333333334\n", 359 | "Confidence: 0.2905982905982906\n", 360 | "Lift: 4.843304843304844\n", 361 | "/nRule: escalope > mushroom cream sauce\n", 362 | "Support: 0.005733333333333333\n", 363 | "Confidence: 0.30069930069930073\n", 364 | "Lift: 3.7903273197390845\n", 365 | "/nRule: escalope > pasta\n", 366 | "Support: 0.005866666666666667\n", 367 | "Confidence: 0.37288135593220345\n", 368 | "Lift: 4.700185158809287\n", 369 | "/nRule: ground beef > herb & pepper\n", 370 | "Support: 0.016\n", 371 | "Confidence: 0.3234501347708895\n", 372 | "Lift: 3.2915549671393096\n", 373 | "/nRule: ground beef > tomato sauce\n", 374 | "Support: 0.005333333333333333\n", 375 | "Confidence: 0.37735849056603776\n", 376 | "Lift: 3.840147461662528\n", 377 | "/nRule: whole wheat pasta > olive oil\n", 378 | "Support: 0.008\n", 379 | "Confidence: 0.2714932126696833\n", 380 | "Lift: 4.130221288078346\n", 381 | "/nRule: pasta > shrimp\n", 382 | "Support: 0.005066666666666666\n", 383 | "Confidence: 0.3220338983050848\n", 384 | "Lift: 4.514493901473151\n", 385 | "/nRule: light cream > nan\n", 386 | "Support: 0.004533333333333334\n", 387 | "Confidence: 0.2905982905982906\n", 388 | "Lift: 4.843304843304844\n", 389 | "/nRule: frozen vegetables > chocolate\n", 390 | "Support: 0.005333333333333333\n", 391 | "Confidence: 0.23255813953488372\n", 392 | "Lift: 3.260160834601174\n", 393 | "/nRule: cooking oil > spaghetti\n", 394 | "Support: 0.0048\n", 395 | "Confidence: 0.5714285714285714\n", 396 | "Lift: 3.281557646029315\n", 397 | "/nRule: escalope > mushroom cream sauce\n", 398 | "Support: 0.005733333333333333\n", 399 | "Confidence: 0.30069930069930073\n", 400 | "Lift: 3.7903273197390845\n", 401 | "/nRule: escalope > pasta\n", 402 | "Support: 0.005866666666666667\n", 403 | "Confidence: 0.37288135593220345\n", 404 | "Lift: 4.700185158809287\n", 405 | "/nRule: ground beef > spaghetti\n", 406 | "Support: 0.008666666666666666\n", 407 | "Confidence: 0.3110047846889952\n", 408 | "Lift: 3.164906221394116\n", 409 | "/nRule: olive oil > milk\n", 410 | "Support: 0.0048\n", 411 | "Confidence: 0.20338983050847456\n", 412 | "Lift: 3.094165778526489\n", 413 | "/nRule: frozen vegetables > mineral water\n", 414 | "Support: 0.0072\n", 415 | "Confidence: 0.3068181818181818\n", 416 | "Lift: 3.2183725365543547\n", 417 | "/nRule: olive oil > spaghetti\n", 418 | "Support: 0.005733333333333333\n", 419 | "Confidence: 0.20574162679425836\n", 420 | "Lift: 3.1299436124887174\n", 421 | "/nRule: spaghetti > frozen vegetables\n", 422 | "Support: 0.006\n", 423 | "Confidence: 0.21531100478468898\n", 424 | "Lift: 3.0183785717479763\n", 425 | "/nRule: spaghetti > tomatoes\n", 426 | "Support: 0.006666666666666667\n", 427 | "Confidence: 0.23923444976076555\n", 428 | "Lift: 3.497579674864993\n", 429 | "/nRule: grated cheese > spaghetti\n", 430 | "Support: 0.005333333333333333\n", 431 | "Confidence: 0.3225806451612903\n", 432 | "Lift: 3.282706701098612\n", 433 | "/nRule: ground beef > herb & pepper\n", 434 | "Support: 0.006666666666666667\n", 435 | "Confidence: 0.390625\n", 436 | "Lift: 3.975152645861601\n", 437 | "/nRule: ground beef > herb & pepper\n", 438 | "Support: 0.016\n", 439 | "Confidence: 0.3234501347708895\n", 440 | "Lift: 3.2915549671393096\n", 441 | "/nRule: ground beef > herb & pepper\n", 442 | "Support: 0.0064\n", 443 | "Confidence: 0.3934426229508197\n", 444 | "Lift: 4.003825878061259\n", 445 | "/nRule: ground beef > milk\n", 446 | "Support: 0.004933333333333333\n", 447 | "Confidence: 0.22424242424242424\n", 448 | "Lift: 3.411395906324912\n", 449 | "/nRule: ground beef > tomato sauce\n", 450 | "Support: 0.005333333333333333\n", 451 | "Confidence: 0.37735849056603776\n", 452 | "Lift: 3.840147461662528\n", 453 | "/nRule: ground beef > spaghetti\n", 454 | "Support: 0.006\n", 455 | "Confidence: 0.5232558139534884\n", 456 | "Lift: 3.004914704939635\n", 457 | "/nRule: milk > spaghetti\n", 458 | "Support: 0.0072\n", 459 | "Confidence: 0.20300751879699247\n", 460 | "Lift: 3.0883496774390333\n", 461 | "/nRule: olive oil > soup\n", 462 | "Support: 0.0052\n", 463 | "Confidence: 0.2254335260115607\n", 464 | "Lift: 3.4295161157945335\n", 465 | "/nRule: whole wheat pasta > olive oil\n", 466 | "Support: 0.008\n", 467 | "Confidence: 0.2714932126696833\n", 468 | "Lift: 4.130221288078346\n", 469 | "/nRule: pasta > nan\n", 470 | "Support: 0.005066666666666666\n", 471 | "Confidence: 0.3220338983050848\n", 472 | "Lift: 4.514493901473151\n", 473 | "/nRule: spaghetti > pancakes\n", 474 | "Support: 0.005066666666666666\n", 475 | "Confidence: 0.20105820105820105\n", 476 | "Lift: 3.0586947422647217\n", 477 | "/nRule: spaghetti > tomatoes\n", 478 | "Support: 0.0044\n", 479 | "Confidence: 0.6111111111111112\n", 480 | "Lift: 3.50944359367024\n", 481 | "/nRule: nan > frozen vegetables\n", 482 | "Support: 0.005333333333333333\n", 483 | "Confidence: 0.23255813953488372\n", 484 | "Lift: 3.260160834601174\n", 485 | "/nRule: cooking oil > spaghetti\n", 486 | "Support: 0.0048\n", 487 | "Confidence: 0.5714285714285714\n", 488 | "Lift: 3.281557646029315\n", 489 | "/nRule: ground beef > spaghetti\n", 490 | "Support: 0.0044\n", 491 | "Confidence: 0.25984251968503935\n", 492 | "Lift: 4.350042182227221\n", 493 | "/nRule: ground beef > spaghetti\n", 494 | "Support: 0.008666666666666666\n", 495 | "Confidence: 0.3110047846889952\n", 496 | "Lift: 3.164906221394116\n", 497 | "/nRule: milk > spaghetti\n", 498 | "Support: 0.004533333333333334\n", 499 | "Confidence: 0.28813559322033905\n", 500 | "Lift: 3.0224013274860737\n", 501 | "/nRule: olive oil > milk\n", 502 | "Support: 0.0048\n", 503 | "Confidence: 0.20338983050847456\n", 504 | "Lift: 3.094165778526489\n", 505 | "/nRule: nan > frozen vegetables\n", 506 | "Support: 0.0072\n", 507 | "Confidence: 0.3068181818181818\n", 508 | "Lift: 3.2183725365543547\n", 509 | "/nRule: olive oil > spaghetti\n", 510 | "Support: 0.005733333333333333\n", 511 | "Confidence: 0.20574162679425836\n", 512 | "Lift: 3.1299436124887174\n", 513 | "/nRule: spaghetti > frozen vegetables\n", 514 | "Support: 0.006\n", 515 | "Confidence: 0.21531100478468898\n", 516 | "Lift: 3.0183785717479763\n", 517 | "/nRule: spaghetti > tomatoes\n", 518 | "Support: 0.006666666666666667\n", 519 | "Confidence: 0.23923444976076555\n", 520 | "Lift: 3.497579674864993\n", 521 | "/nRule: grated cheese > spaghetti\n", 522 | "Support: 0.005333333333333333\n", 523 | "Confidence: 0.3225806451612903\n", 524 | "Lift: 3.282706701098612\n", 525 | "/nRule: ground beef > herb & pepper\n", 526 | "Support: 0.006666666666666667\n", 527 | "Confidence: 0.390625\n", 528 | "Lift: 3.975152645861601\n", 529 | "/nRule: ground beef > herb & pepper\n", 530 | "Support: 0.0064\n", 531 | "Confidence: 0.3934426229508197\n", 532 | "Lift: 4.003825878061259\n", 533 | "/nRule: ground beef > milk\n", 534 | "Support: 0.0044\n", 535 | "Confidence: 0.2\n", 536 | "Lift: 3.348214285714286\n", 537 | "/nRule: ground beef > milk\n", 538 | "Support: 0.004933333333333333\n", 539 | "Confidence: 0.22424242424242424\n", 540 | "Lift: 3.411395906324912\n", 541 | "/nRule: ground beef > spaghetti\n", 542 | "Support: 0.006\n", 543 | "Confidence: 0.5232558139534884\n", 544 | "Lift: 3.004914704939635\n", 545 | "/nRule: milk > spaghetti\n", 546 | "Support: 0.0072\n", 547 | "Confidence: 0.20300751879699247\n", 548 | "Lift: 3.0883496774390333\n", 549 | "/nRule: olive oil > soup\n", 550 | "Support: 0.0052\n", 551 | "Confidence: 0.2254335260115607\n", 552 | "Lift: 3.4295161157945335\n", 553 | "/nRule: spaghetti > pancakes\n", 554 | "Support: 0.005066666666666666\n", 555 | "Confidence: 0.20105820105820105\n", 556 | "Lift: 3.0586947422647217\n", 557 | "/nRule: spaghetti > tomatoes\n", 558 | "Support: 0.0044\n", 559 | "Confidence: 0.6111111111111112\n", 560 | "Lift: 3.50944359367024\n", 561 | "/nRule: frozen vegetables > ground beef\n", 562 | "Support: 0.0044\n", 563 | "Confidence: 0.25984251968503935\n", 564 | "Lift: 4.350042182227221\n", 565 | "/nRule: milk > frozen vegetables\n", 566 | "Support: 0.004533333333333334\n", 567 | "Confidence: 0.28813559322033905\n", 568 | "Lift: 3.0224013274860737\n", 569 | "/nRule: milk > ground beef\n", 570 | "Support: 0.0044\n", 571 | "Confidence: 0.2\n", 572 | "Lift: 3.348214285714286\n", 573 | "/n" 574 | ] 575 | } 576 | ], 577 | "source": [ 578 | "# Visualization of rules generated\n", 579 | "\n", 580 | "for item in association_results:\n", 581 | " pair = item[0]\n", 582 | " items = [x for x in pair]\n", 583 | " print(\"Rule: \" + items[0] + \" > \" + items[1])\n", 584 | "\n", 585 | " print(\"Support: \" + str(item[1]))\n", 586 | "\n", 587 | " print(\"Confidence: \" + str(item[2][0][2]))\n", 588 | " print(\"Lift: \" + str(item[2][0][3]))\n", 589 | " print(end=\"/n\")" 590 | ] 591 | } 592 | ], 593 | "metadata": { 594 | "kernelspec": { 595 | "display_name": "Python 3", 596 | "language": "python", 597 | "name": "python3" 598 | }, 599 | "language_info": { 600 | "codemirror_mode": { 601 | "name": "ipython", 602 | "version": 3 603 | }, 604 | "file_extension": ".py", 605 | "mimetype": "text/x-python", 606 | "name": "python", 607 | "nbconvert_exporter": "python", 608 | "pygments_lexer": "ipython3", 609 | "version": "3.10.2" 610 | }, 611 | "vscode": { 612 | "interpreter": { 613 | "hash": "a9cff5a362bc38ef45d817ae74b1af54d6a076e3d773891282bce078b815ba34" 614 | } 615 | } 616 | }, 617 | "nbformat": 4, 618 | "nbformat_minor": 5 619 | } 620 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pygame -------------------------------------------------------------------------------- /snake/README.md: -------------------------------------------------------------------------------- 1 | # Snake Game 2 | 3 | ## How to Contribute? 4 | 5 | - Take Existing Issues or create your own Issues! 6 | - Get Assigned with Issues 7 | - Fork the Repo, then Clone forked repo. 8 | - Create a Pull Request. 9 | - Add Screenshots/deployed link in your project repo README.md 10 | - [Contribution.md](https://github.com/Encode-PDEU/AI-ML_Encode_HF2022/blob/main/CONTRIBUTING.md) 11 | 12 | 13 | ## HELP US OUT BY STARRING THIS REPOSITORY -------------------------------------------------------------------------------- /snake/__pycache__/food.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/snake/__pycache__/food.cpython-310.pyc -------------------------------------------------------------------------------- /snake/__pycache__/scoreboard.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/snake/__pycache__/scoreboard.cpython-310.pyc -------------------------------------------------------------------------------- /snake/__pycache__/snake.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Encode-PDEU/AI-ML-Python_Encode_HF2022/43f78eba3e52c28197e3fd152f108996e2c4fdfa/snake/__pycache__/snake.cpython-310.pyc -------------------------------------------------------------------------------- /snake/food.py: -------------------------------------------------------------------------------- 1 | from random import random 2 | from turtle import Turtle 3 | import random 4 | class Food(Turtle): 5 | def __init__(self): 6 | super().__init__() 7 | self.shape("circle") 8 | self.penup() 9 | self.shapesize(stretch_len=0.5,stretch_wid=0.5) 10 | self.color("blue") 11 | self.speed("fastest") 12 | self.refresh() 13 | 14 | def refresh(self): 15 | random_x = random.randint(-270,270) 16 | random_y = random.randint(-270,250) 17 | self.goto(random_x,random_y) 18 | 19 | 20 | -------------------------------------------------------------------------------- /snake/scoreboard.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle, color 2 | 3 | class Scoreboard(Turtle): 4 | def __init__(self): 5 | super().__init__() 6 | self.current_score = 0 7 | self.goto(0,270) 8 | self.color("white") 9 | self.write(f"Score: {self.current_score}", align="center", font=("Arial",22,"normal")) 10 | self.hideturtle() 11 | 12 | def game_over(self): 13 | self.goto(0,0) 14 | self.write("GAME OVER", align="center", font=("Arial",22,"normal")) 15 | def increase_score(self): 16 | self.current_score += 1 17 | self.clear() 18 | self.write(f"Score: {self.current_score}", align="center", font=("Arial",22,"normal")) -------------------------------------------------------------------------------- /snake/snake.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle,Screen 2 | 3 | screen = Screen() 4 | Y = [(0,0),(-20,0),(-40,0)] 5 | UP = 90 6 | DOWN = 270 7 | RIGHT = 0 8 | LEFT = 180 9 | 10 | class Snake: 11 | 12 | def __init__(self): 13 | self.snakes = [] 14 | self.create_snake() 15 | self.head = self.snakes[0] 16 | 17 | def add_tail(self, position): 18 | snake = Turtle(shape="square") 19 | snake.penup() 20 | snake.color("white") 21 | snake.goto(position) 22 | self.snakes.append(snake) 23 | 24 | def create_snake(self): 25 | for i in range(3): 26 | self.add_tail(Y[i]) 27 | 28 | def entend(self): 29 | pos = self.snakes[-1].position() 30 | self.add_tail(pos) 31 | 32 | def up(self): 33 | if self.head.heading() != DOWN: 34 | self.head.setheading(UP) 35 | 36 | def down(self): 37 | if self.head.heading() != UP: 38 | self.head.setheading(DOWN) 39 | 40 | def right(self): 41 | if self.head.heading() != LEFT: 42 | self.head.setheading(RIGHT) 43 | 44 | def left(self): 45 | if self.head.heading() != RIGHT: 46 | self.head.setheading(LEFT) 47 | 48 | def moveforward(self): 49 | for snake in range(len(self.snakes)-1, 0, -1): 50 | x = self.snakes[snake - 1].xcor() 51 | y = self.snakes[snake - 1].ycor() 52 | self.snakes[snake].goto(x,y) 53 | self.head.forward(20) 54 | 55 | def listen(self): 56 | screen.listen() 57 | screen.onkey(self.up,"Up") 58 | screen.onkey(self.down,"Down") 59 | screen.onkey(self.right,"Right") 60 | screen.onkey(self.left,"Left") 61 | 62 | def mov(self): 63 | self.moveforward() 64 | self.listen() 65 | 66 | def collison(self): 67 | 68 | return False -------------------------------------------------------------------------------- /snake/snakegame.py: -------------------------------------------------------------------------------- 1 | import time 2 | from turtle import Screen 3 | from scoreboard import Scoreboard 4 | from snake import Snake 5 | from food import Food 6 | from scoreboard import Scoreboard 7 | 8 | screen = Screen() 9 | screen.setup(width = 600, height = 600) 10 | screen.bgcolor("black") 11 | screen.title("Snake game") 12 | screen.tracer(0) 13 | 14 | snake = Snake() 15 | food = Food() 16 | score = Scoreboard() 17 | 18 | screen.update() 19 | is_on = True 20 | 21 | while is_on: 22 | screen.update() 23 | time.sleep(0.1) 24 | snake.mov() 25 | 26 | if snake.head.distance(food) < 15: 27 | food.refresh() 28 | snake.entend() 29 | score.increase_score() 30 | 31 | if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 260 or snake.head.ycor() < -280: 32 | is_on = False 33 | score.game_over() 34 | 35 | for seg in snake.snakes[1:]: 36 | # if seg == snake.head: 37 | # pass 38 | if snake.head.distance(seg) < 10: 39 | is_on = False 40 | score.game_over() 41 | screen.exitonclick() --------------------------------------------------------------------------------