hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
sequence
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
sequence
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
sequence
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
sequence
cell_types
sequence
cell_type_groups
sequence
d071c8289a019b9c6a6880090573ca9c0b618dbe
131,607
ipynb
Jupyter Notebook
4_channels/3 _channels.ipynb
Pavel-Konarik/detectron2
90bb33bc4554c014af53952e96c2602a7d7fc0d0
[ "Apache-2.0" ]
null
null
null
4_channels/3 _channels.ipynb
Pavel-Konarik/detectron2
90bb33bc4554c014af53952e96c2602a7d7fc0d0
[ "Apache-2.0" ]
null
null
null
4_channels/3 _channels.ipynb
Pavel-Konarik/detectron2
90bb33bc4554c014af53952e96c2602a7d7fc0d0
[ "Apache-2.0" ]
null
null
null
160.105839
23,896
0.818042
[ [ [ "# check pytorch installation: \nimport torch, torchvision\nprint(torch.__version__, torch.cuda.is_available())\nassert torch.__version__.startswith(\"1.9\") # please manually install torch 1.9 if Colab changes its default version\n\nimport detectron2\nfrom detectron2.utils.logger import setup_logger\nsetup_logger()\n\n# import some common libraries\nimport numpy as np\nimport os, json, cv2, random\nfrom PIL import Image\nfrom IPython.display import display \nfrom typing import Tuple\n\n# import some common detectron2 utilities\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.data import MetadataCatalog, DatasetCatalog\nfrom detectron2.data.dataset_mapper import DatasetMapper\n\nfrom detectron2.data import detection_utils as utils\nfrom detectron2.engine import DefaultTrainer\nfrom detectron2.data import build_detection_test_loader, build_detection_train_loader\nimport copy\nimport json\nfrom detectron2.data import transforms as T", "1.9.0+cu111 True\n" ], [ "def get_circles_dataset():\n with open(\"circles.json\") as json_file:\n data = json.load(json_file)\n return data\n \nDatasetCatalog.register(\"circles_train\", get_circles_dataset)\nMetadataCatalog.get(\"circles_train\").set(thing_classes=[\"circle\"])\ncircles_metadata = MetadataCatalog.get(\"circles_train\")", "_____no_output_____" ], [ "dataset_dicts = get_circles_dataset()\nfor d in random.sample(dataset_dicts, 2):\n img = cv2.imread(d[\"file_name\"])\n visualizer = Visualizer(img[:, :, ::-1], metadata=circles_metadata, scale=0.5)\n out = visualizer.draw_dataset_dict(d)\n display(Image.fromarray(out.get_image()))", "_____no_output_____" ], [ "class FourChannelMapper(DatasetMapper):\n def __call__(self, dataset_dict):\n \"\"\"\n This method is basically a carbon copy of DatasetMapper::__call__,\n but each image gets expanded by one empty channel\n \"\"\"\n dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below\n \n image = utils.read_image(dataset_dict[\"file_name\"], format=self.image_format)\n \n #########################################\n # MY CODE\n # Simply add a 4th empty channel\n # image = np.dstack((image, np.zeros_like(image[:,:,0])))\n # END OF MY CODE\n \n \n utils.check_image_size(dataset_dict, image)\n \n # USER: Remove if you don't do semantic/panoptic segmentation.\n if \"sem_seg_file_name\" in dataset_dict:\n sem_seg_gt = utils.read_image(dataset_dict.pop(\"sem_seg_file_name\"), \"L\").squeeze(2)\n else:\n sem_seg_gt = None\n\n aug_input = T.AugInput(image, sem_seg=sem_seg_gt)\n transforms = self.augmentations(aug_input)\n image, sem_seg_gt = aug_input.image, aug_input.sem_seg\n\n image_shape = image.shape[:2] # h, w\n # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory,\n # but not efficient on large generic data structures due to the use of pickle & mp.Queue.\n # Therefore it's important to use torch.Tensor.\n dataset_dict[\"image\"] = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))\n if sem_seg_gt is not None:\n dataset_dict[\"sem_seg\"] = torch.as_tensor(sem_seg_gt.astype(\"long\"))\n\n \n\n if not self.is_train:\n # USER: Modify this if you want to keep them for some reason.\n dataset_dict.pop(\"annotations\", None)\n dataset_dict.pop(\"sem_seg_file_name\", None)\n return dataset_dict\n\n if \"annotations\" in dataset_dict:\n # USER: Modify this if you want to keep them for some reason.\n for anno in dataset_dict[\"annotations\"]:\n if not self.use_instance_mask:\n anno.pop(\"segmentation\", None)\n if not self.use_keypoint:\n anno.pop(\"keypoints\", None)\n\n # USER: Implement additional transformations if you have other types of data\n annos = [\n utils.transform_instance_annotations(\n obj, transforms, image_shape, keypoint_hflip_indices=self.keypoint_hflip_indices\n )\n for obj in dataset_dict.pop(\"annotations\")\n if obj.get(\"iscrowd\", 0) == 0\n ]\n instances = utils.annotations_to_instances(\n annos, image_shape, mask_format=self.instance_mask_format\n )\n\n # After transforms such as cropping are applied, the bounding box may no longer\n # tightly bound the object. As an example, imagine a triangle object\n # [(0,0), (2,0), (0,2)] cropped by a box [(1,0),(2,2)] (XYXY format). The tight\n # bounding box of the cropped triangle should be [(1,0),(2,1)], which is not equal to\n # the intersection of original bounding box and the cropping box.\n if self.recompute_boxes:\n instances.gt_boxes = instances.gt_masks.get_bounding_boxes()\n dataset_dict[\"instances\"] = utils.filter_empty_instances(instances)\n return dataset_dict\n\n \nclass Trainer(DefaultTrainer):\n @classmethod\n def build_train_loader(cls, cfg):\n return build_detection_train_loader(cfg, mapper=FourChannelMapper(cfg, True))\n \n @classmethod\n def build_test_loader(cls, cfg, dataset_name):\n return build_detection_test_loader(cfg, dataset_name, mapper=FourChannelMapper(cfg, False))\n", "_____no_output_____" ], [ "cfg = get_cfg()\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\"))\ncfg.DATASETS.TRAIN = (\"circles_train\",)\ncfg.DATASETS.TEST = ()\n\n#cfg.INPUT.FORMAT = \"BGR\"\ncfg.INPUT.FORMAT = \"RGB\"\n\ncfg.MODEL.PIXEL_MEAN = [103.530, 116.280, 123.675]\n#cfg.MODEL.PIXEL_MEAN = [103.530, 116.280, 123.675, 103.530]\ncfg.MODEL.PIXEL_STD = [1.0, 1.0, 1.0]\n#cfg.MODEL.PIXEL_STD = [1.0, 1.0, 1.0, 1.0]\n\ncfg.DATALOADER.NUM_WORKERS = 2\n#cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\") # Let training initialize from model zoo\ncfg.SOLVER.IMS_PER_BATCH = 1\ncfg.SOLVER.BASE_LR = 0.00025 # pick a good LR\ncfg.SOLVER.MAX_ITER = 300 # 300 iterations seems good enough for this toy dataset; you will need to train longer for a practical dataset\ncfg.SOLVER.STEPS = [] # do not decay learning rate\ncfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 128 # faster, and good enough for this toy dataset (default: 512)\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 1 # only has one class (ballon). (see https://detectron2.readthedocs.io/tutorials/datasets.html#update-the-config-for-new-datasets)\n# NOTE: this config means the number of classes, but a few popular unofficial tutorials incorrect uses num_classes+1 here.\n\nos.makedirs(cfg.OUTPUT_DIR, exist_ok=True)\ntrainer = Trainer(cfg) \ntrainer.resume_or_load(resume=False)\ntrainer.train()", "\u001b[32m[08/04 18:07:44 d2.engine.defaults]: \u001b[0mModel:\nGeneralizedRCNN(\n (backbone): FPN(\n (fpn_lateral2): Conv2d(256, 256, kernel_size=(1, 1), stride=(1, 1))\n (fpn_output2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (fpn_lateral3): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1))\n (fpn_output3): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (fpn_lateral4): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1))\n (fpn_output4): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (fpn_lateral5): Conv2d(2048, 256, kernel_size=(1, 1), stride=(1, 1))\n (fpn_output5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (top_block): LastLevelMaxPool()\n (bottom_up): ResNet(\n (stem): BasicStem(\n (conv1): Conv2d(\n 3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False\n (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)\n )\n )\n (res2): Sequential(\n (0): BottleneckBlock(\n (shortcut): Conv2d(\n 64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv1): Conv2d(\n 64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)\n )\n (conv2): Conv2d(\n 64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)\n )\n (conv3): Conv2d(\n 64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n )\n (1): BottleneckBlock(\n (conv1): Conv2d(\n 256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)\n )\n (conv2): Conv2d(\n 64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)\n )\n (conv3): Conv2d(\n 64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n )\n (2): BottleneckBlock(\n (conv1): Conv2d(\n 256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)\n )\n (conv2): Conv2d(\n 64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=64, eps=1e-05)\n )\n (conv3): Conv2d(\n 64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n )\n )\n (res3): Sequential(\n (0): BottleneckBlock(\n (shortcut): Conv2d(\n 256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n (conv1): Conv2d(\n 256, 128, kernel_size=(1, 1), stride=(2, 2), bias=False\n (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)\n )\n (conv2): Conv2d(\n 128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)\n )\n (conv3): Conv2d(\n 128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n )\n (1): BottleneckBlock(\n (conv1): Conv2d(\n 512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)\n )\n (conv2): Conv2d(\n 128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)\n )\n (conv3): Conv2d(\n 128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n )\n (2): BottleneckBlock(\n (conv1): Conv2d(\n 512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)\n )\n (conv2): Conv2d(\n 128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)\n )\n (conv3): Conv2d(\n 128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n )\n (3): BottleneckBlock(\n (conv1): Conv2d(\n 512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)\n )\n (conv2): Conv2d(\n 128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=128, eps=1e-05)\n )\n (conv3): Conv2d(\n 128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n )\n )\n (res4): Sequential(\n (0): BottleneckBlock(\n (shortcut): Conv2d(\n 512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False\n (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)\n )\n (conv1): Conv2d(\n 512, 256, kernel_size=(1, 1), stride=(2, 2), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv2): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv3): Conv2d(\n 256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)\n )\n )\n (1): BottleneckBlock(\n (conv1): Conv2d(\n 1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv2): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv3): Conv2d(\n 256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)\n )\n )\n (2): BottleneckBlock(\n (conv1): Conv2d(\n 1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv2): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv3): Conv2d(\n 256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)\n )\n )\n (3): BottleneckBlock(\n (conv1): Conv2d(\n 1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv2): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv3): Conv2d(\n 256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)\n )\n )\n (4): BottleneckBlock(\n (conv1): Conv2d(\n 1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv2): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv3): Conv2d(\n 256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)\n )\n )\n (5): BottleneckBlock(\n (conv1): Conv2d(\n 1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv2): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=256, eps=1e-05)\n )\n (conv3): Conv2d(\n 256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=1024, eps=1e-05)\n )\n )\n )\n (res5): Sequential(\n (0): BottleneckBlock(\n (shortcut): Conv2d(\n 1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False\n (norm): FrozenBatchNorm2d(num_features=2048, eps=1e-05)\n )\n (conv1): Conv2d(\n 1024, 512, kernel_size=(1, 1), stride=(2, 2), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n (conv2): Conv2d(\n 512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n (conv3): Conv2d(\n 512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=2048, eps=1e-05)\n )\n )\n (1): BottleneckBlock(\n (conv1): Conv2d(\n 2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n (conv2): Conv2d(\n 512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n (conv3): Conv2d(\n 512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=2048, eps=1e-05)\n )\n )\n (2): BottleneckBlock(\n (conv1): Conv2d(\n 2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n (conv2): Conv2d(\n 512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=512, eps=1e-05)\n )\n (conv3): Conv2d(\n 512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False\n (norm): FrozenBatchNorm2d(num_features=2048, eps=1e-05)\n )\n )\n )\n )\n )\n (proposal_generator): RPN(\n (rpn_head): StandardRPNHead(\n (conv): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)\n (activation): ReLU()\n )\n (objectness_logits): Conv2d(256, 3, kernel_size=(1, 1), stride=(1, 1))\n (anchor_deltas): Conv2d(256, 12, kernel_size=(1, 1), stride=(1, 1))\n )\n (anchor_generator): DefaultAnchorGenerator(\n (cell_anchors): BufferList()\n )\n )\n (roi_heads): StandardROIHeads(\n (box_pooler): ROIPooler(\n (level_poolers): ModuleList(\n (0): ROIAlign(output_size=(7, 7), spatial_scale=0.25, sampling_ratio=0, aligned=True)\n (1): ROIAlign(output_size=(7, 7), spatial_scale=0.125, sampling_ratio=0, aligned=True)\n (2): ROIAlign(output_size=(7, 7), spatial_scale=0.0625, sampling_ratio=0, aligned=True)\n (3): ROIAlign(output_size=(7, 7), spatial_scale=0.03125, sampling_ratio=0, aligned=True)\n )\n )\n (box_head): FastRCNNConvFCHead(\n (flatten): Flatten(start_dim=1, end_dim=-1)\n (fc1): Linear(in_features=12544, out_features=1024, bias=True)\n (fc_relu1): ReLU()\n (fc2): Linear(in_features=1024, out_features=1024, bias=True)\n (fc_relu2): ReLU()\n )\n (box_predictor): FastRCNNOutputLayers(\n (cls_score): Linear(in_features=1024, out_features=2, bias=True)\n (bbox_pred): Linear(in_features=1024, out_features=4, bias=True)\n )\n (mask_pooler): ROIPooler(\n (level_poolers): ModuleList(\n (0): ROIAlign(output_size=(14, 14), spatial_scale=0.25, sampling_ratio=0, aligned=True)\n (1): ROIAlign(output_size=(14, 14), spatial_scale=0.125, sampling_ratio=0, aligned=True)\n (2): ROIAlign(output_size=(14, 14), spatial_scale=0.0625, sampling_ratio=0, aligned=True)\n (3): ROIAlign(output_size=(14, 14), spatial_scale=0.03125, sampling_ratio=0, aligned=True)\n )\n )\n (mask_head): MaskRCNNConvUpsampleHead(\n (mask_fcn1): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)\n (activation): ReLU()\n )\n (mask_fcn2): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)\n (activation): ReLU()\n )\n (mask_fcn3): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)\n (activation): ReLU()\n )\n (mask_fcn4): Conv2d(\n 256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)\n (activation): ReLU()\n )\n (deconv): ConvTranspose2d(256, 256, kernel_size=(2, 2), stride=(2, 2))\n (deconv_relu): ReLU()\n (predictor): Conv2d(256, 1, kernel_size=(1, 1), stride=(1, 1))\n )\n )\n)\n\u001b[32m[08/04 18:07:44 d2.data.dataset_mapper]: \u001b[0m[DatasetMapper] Augmentations used in training: [ResizeShortestEdge(short_edge_length=(640, 672, 704, 736, 768, 800), max_size=1333, sample_style='choice'), RandomFlip()]\n\u001b[32m[08/04 18:07:44 d2.data.build]: \u001b[0mRemoved 0 images with no usable annotations. 2 images left.\n\u001b[32m[08/04 18:07:44 d2.data.build]: \u001b[0mDistribution of instances among all 1 categories:\n\u001b[36m| category | #instances |\n|:----------:|:-------------|\n| circle | 2 |\n| | |\u001b[0m\n\u001b[32m[08/04 18:07:44 d2.data.build]: \u001b[0mUsing training sampler TrainingSampler\n\u001b[32m[08/04 18:07:44 d2.data.common]: \u001b[0mSerializing 2 elements to byte tensors and concatenating them all ...\n\u001b[32m[08/04 18:07:44 d2.data.common]: \u001b[0mSerialized dataset takes 0.00 MiB\n\u001b[32m[08/04 18:07:44 d2.checkpoint.c2_model_loading]: \u001b[0mRenaming Caffe2 weights ......\n\u001b[32m[08/04 18:07:44 d2.checkpoint.c2_model_loading]: \u001b[0mFollowing weights matched with submodule backbone.bottom_up:\n| Names in Model | Names in Checkpoint | Shapes |\n|:------------------|:-------------------------|:------------------------------------------------|\n| res2.0.conv1.* | res2_0_branch2a_{bn_*,w} | (64,) (64,) (64,) (64,) (64,64,1,1) |\n| res2.0.conv2.* | res2_0_branch2b_{bn_*,w} | (64,) (64,) (64,) (64,) (64,64,3,3) |\n| res2.0.conv3.* | res2_0_branch2c_{bn_*,w} | (256,) (256,) (256,) (256,) (256,64,1,1) |\n| res2.0.shortcut.* | res2_0_branch1_{bn_*,w} | (256,) (256,) (256,) (256,) (256,64,1,1) |\n| res2.1.conv1.* | res2_1_branch2a_{bn_*,w} | (64,) (64,) (64,) (64,) (64,256,1,1) |\n| res2.1.conv2.* | res2_1_branch2b_{bn_*,w} | (64,) (64,) (64,) (64,) (64,64,3,3) |\n| res2.1.conv3.* | res2_1_branch2c_{bn_*,w} | (256,) (256,) (256,) (256,) (256,64,1,1) |\n| res2.2.conv1.* | res2_2_branch2a_{bn_*,w} | (64,) (64,) (64,) (64,) (64,256,1,1) |\n| res2.2.conv2.* | res2_2_branch2b_{bn_*,w} | (64,) (64,) (64,) (64,) (64,64,3,3) |\n| res2.2.conv3.* | res2_2_branch2c_{bn_*,w} | (256,) (256,) (256,) (256,) (256,64,1,1) |\n| res3.0.conv1.* | res3_0_branch2a_{bn_*,w} | (128,) (128,) (128,) (128,) (128,256,1,1) |\n| res3.0.conv2.* | res3_0_branch2b_{bn_*,w} | (128,) (128,) (128,) (128,) (128,128,3,3) |\n| res3.0.conv3.* | res3_0_branch2c_{bn_*,w} | (512,) (512,) (512,) (512,) (512,128,1,1) |\n| res3.0.shortcut.* | res3_0_branch1_{bn_*,w} | (512,) (512,) (512,) (512,) (512,256,1,1) |\n| res3.1.conv1.* | res3_1_branch2a_{bn_*,w} | (128,) (128,) (128,) (128,) (128,512,1,1) |\n| res3.1.conv2.* | res3_1_branch2b_{bn_*,w} | (128,) (128,) (128,) (128,) (128,128,3,3) |\n| res3.1.conv3.* | res3_1_branch2c_{bn_*,w} | (512,) (512,) (512,) (512,) (512,128,1,1) |\n| res3.2.conv1.* | res3_2_branch2a_{bn_*,w} | (128,) (128,) (128,) (128,) (128,512,1,1) |\n| res3.2.conv2.* | res3_2_branch2b_{bn_*,w} | (128,) (128,) (128,) (128,) (128,128,3,3) |\n| res3.2.conv3.* | res3_2_branch2c_{bn_*,w} | (512,) (512,) (512,) (512,) (512,128,1,1) |\n| res3.3.conv1.* | res3_3_branch2a_{bn_*,w} | (128,) (128,) (128,) (128,) (128,512,1,1) |\n| res3.3.conv2.* | res3_3_branch2b_{bn_*,w} | (128,) (128,) (128,) (128,) (128,128,3,3) |\n| res3.3.conv3.* | res3_3_branch2c_{bn_*,w} | (512,) (512,) (512,) (512,) (512,128,1,1) |\n| res4.0.conv1.* | res4_0_branch2a_{bn_*,w} | (256,) (256,) (256,) (256,) (256,512,1,1) |\n| res4.0.conv2.* | res4_0_branch2b_{bn_*,w} | (256,) (256,) (256,) (256,) (256,256,3,3) |\n| res4.0.conv3.* | res4_0_branch2c_{bn_*,w} | (1024,) (1024,) (1024,) (1024,) (1024,256,1,1) |\n| res4.0.shortcut.* | res4_0_branch1_{bn_*,w} | (1024,) (1024,) (1024,) (1024,) (1024,512,1,1) |\n| res4.1.conv1.* | res4_1_branch2a_{bn_*,w} | (256,) (256,) (256,) (256,) (256,1024,1,1) |\n| res4.1.conv2.* | res4_1_branch2b_{bn_*,w} | (256,) (256,) (256,) (256,) (256,256,3,3) |\n| res4.1.conv3.* | res4_1_branch2c_{bn_*,w} | (1024,) (1024,) (1024,) (1024,) (1024,256,1,1) |\n| res4.2.conv1.* | res4_2_branch2a_{bn_*,w} | (256,) (256,) (256,) (256,) (256,1024,1,1) |\n| res4.2.conv2.* | res4_2_branch2b_{bn_*,w} | (256,) (256,) (256,) (256,) (256,256,3,3) |\n| res4.2.conv3.* | res4_2_branch2c_{bn_*,w} | (1024,) (1024,) (1024,) (1024,) (1024,256,1,1) |\n| res4.3.conv1.* | res4_3_branch2a_{bn_*,w} | (256,) (256,) (256,) (256,) (256,1024,1,1) |\n| res4.3.conv2.* | res4_3_branch2b_{bn_*,w} | (256,) (256,) (256,) (256,) (256,256,3,3) |\n| res4.3.conv3.* | res4_3_branch2c_{bn_*,w} | (1024,) (1024,) (1024,) (1024,) (1024,256,1,1) |\n| res4.4.conv1.* | res4_4_branch2a_{bn_*,w} | (256,) (256,) (256,) (256,) (256,1024,1,1) |\n| res4.4.conv2.* | res4_4_branch2b_{bn_*,w} | (256,) (256,) (256,) (256,) (256,256,3,3) |\n| res4.4.conv3.* | res4_4_branch2c_{bn_*,w} | (1024,) (1024,) (1024,) (1024,) (1024,256,1,1) |\n| res4.5.conv1.* | res4_5_branch2a_{bn_*,w} | (256,) (256,) (256,) (256,) (256,1024,1,1) |\n| res4.5.conv2.* | res4_5_branch2b_{bn_*,w} | (256,) (256,) (256,) (256,) (256,256,3,3) |\n| res4.5.conv3.* | res4_5_branch2c_{bn_*,w} | (1024,) (1024,) (1024,) (1024,) (1024,256,1,1) |\n| res5.0.conv1.* | res5_0_branch2a_{bn_*,w} | (512,) (512,) (512,) (512,) (512,1024,1,1) |\n| res5.0.conv2.* | res5_0_branch2b_{bn_*,w} | (512,) (512,) (512,) (512,) (512,512,3,3) |\n| res5.0.conv3.* | res5_0_branch2c_{bn_*,w} | (2048,) (2048,) (2048,) (2048,) (2048,512,1,1) |\n| res5.0.shortcut.* | res5_0_branch1_{bn_*,w} | (2048,) (2048,) (2048,) (2048,) (2048,1024,1,1) |\n| res5.1.conv1.* | res5_1_branch2a_{bn_*,w} | (512,) (512,) (512,) (512,) (512,2048,1,1) |\n| res5.1.conv2.* | res5_1_branch2b_{bn_*,w} | (512,) (512,) (512,) (512,) (512,512,3,3) |\n| res5.1.conv3.* | res5_1_branch2c_{bn_*,w} | (2048,) (2048,) (2048,) (2048,) (2048,512,1,1) |\n| res5.2.conv1.* | res5_2_branch2a_{bn_*,w} | (512,) (512,) (512,) (512,) (512,2048,1,1) |\n| res5.2.conv2.* | res5_2_branch2b_{bn_*,w} | (512,) (512,) (512,) (512,) (512,512,3,3) |\n| res5.2.conv3.* | res5_2_branch2c_{bn_*,w} | (2048,) (2048,) (2048,) (2048,) (2048,512,1,1) |\n| stem.conv1.norm.* | res_conv1_bn_* | (64,) (64,) (64,) (64,) |\n| stem.conv1.weight | conv1_w | (64, 3, 7, 7) |\n" ], [ "# Inference should use the config with parameters that are used in training\n# cfg now already contains everything we've set previously. We changed it a little bit for inference:\ncfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, \"model_final.pth\") # path to the model we just trained\ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.4 # set a custom testing threshold\npredictor = DefaultPredictor(cfg)", "_____no_output_____" ], [ "from detectron2.utils.visualizer import ColorMode\ndataset_dict = get_circles_dataset()\nfor d in random.sample(dataset_dicts, 2): \n img = utils.read_image(d[\"file_name\"], format=cfg.INPUT.FORMAT)\n #stacked = np.dstack((img, np.zeros_like(img[:,:,0])))\n stacked = img\n\n display(Image.fromarray(img))\n outputs = predictor(stacked)\n v = Visualizer(img,\n metadata=circles_metadata, \n scale=1.0, \n )\n out = v.draw_instance_predictions(outputs[\"instances\"].to(\"cpu\"))\n display(Image.fromarray(out.get_image()))", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d071e37ef703cac47827c5fb6ccf2bde0a181103
283,439
ipynb
Jupyter Notebook
code/05-alpha-diversity/alpha_diversity_90bp_100bp_150bp.ipynb
justinshaffer/emp
3cf0fc8dd13ec7a128d5be2c33e4c7a31f9447cf
[ "BSD-3-Clause" ]
1
2018-12-27T07:53:37.000Z
2018-12-27T07:53:37.000Z
code/05-alpha-diversity/alpha_diversity_90bp_100bp_150bp.ipynb
justinshaffer/emp
3cf0fc8dd13ec7a128d5be2c33e4c7a31f9447cf
[ "BSD-3-Clause" ]
null
null
null
code/05-alpha-diversity/alpha_diversity_90bp_100bp_150bp.ipynb
justinshaffer/emp
3cf0fc8dd13ec7a128d5be2c33e4c7a31f9447cf
[ "BSD-3-Clause" ]
null
null
null
932.365132
166,980
0.943804
[ [ [ "**author**: [email protected]<br>\n**date**: 7 Oct 2017<br>\n**language**: Python 3.5<br>\n**license**: BSD3<br>\n\n## alpha_diversity_90bp_100bp_150bp.ipynb", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom empcolors import get_empo_cat_color\n%matplotlib inline", "_____no_output_____" ] ], [ [ "*** Choose 2k or qc-filtered subset (one or the other) ***", "_____no_output_____" ] ], [ [ "path_map = '../../data/mapping-files/emp_qiime_mapping_subset_2k.tsv' # already has 90bp alpha-div data\nversion = '2k'", "_____no_output_____" ], [ "path_map = '../../data/mapping-files/emp_qiime_mapping_qc_filtered.tsv' # already has 90bp alpha-div data\nversion = 'qc'", "_____no_output_____" ] ], [ [ "*** Merged mapping file and alpha-div ***", "_____no_output_____" ] ], [ [ "path_adiv100 = '../../data/alpha-div/emp.100.min25.deblur.withtax.onlytree_5000.txt'\npath_adiv150 = '../../data/alpha-div/emp.150.min25.deblur.withtax.onlytree_5000.txt'", "_____no_output_____" ], [ "df_map = pd.read_csv(path_map, sep='\\t', index_col=0)\ndf_adiv100 = pd.read_csv(path_adiv100, sep='\\t', index_col=0)\ndf_adiv150 = pd.read_csv(path_adiv150, sep='\\t', index_col=0)\n\ndf_adiv100.columns = ['adiv_chao1_100bp', 'adiv_observed_otus_100bp', 'adiv_faith_pd_100bp', 'adiv_shannon_100bp']\ndf_adiv150.columns = ['adiv_chao1_150bp', 'adiv_observed_otus_150bp', 'adiv_faith_pd_150bp', 'adiv_shannon_150bp']", "_____no_output_____" ], [ "df_merged = pd.concat([df_adiv100, df_adiv150, df_map], axis=1, join='outer')", "_____no_output_____" ] ], [ [ "*** Removing all samples without 150bp alpha-div results ***", "_____no_output_____" ] ], [ [ "df1 = df_merged[['empo_3', 'adiv_observed_otus', 'adiv_observed_otus_100bp', 'adiv_observed_otus_150bp']]\ndf1.columns = ['empo_3', 'observed_tag_sequences_90bp', 'observed_tag_sequences_100bp', 'observed_tag_sequences_150bp']\ndf1.dropna(axis=0, inplace=True)", "/Users/luke.thompson/.local/lib/python3.5/site-packages/ipykernel/__main__.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n app.launch_new_instance()\n" ], [ "g = sns.PairGrid(df1, hue='empo_3', palette=get_empo_cat_color(returndict=True))\ng = g.map(plt.scatter, alpha=0.5)\nfor i in [0, 1, 2]:\n for j in [0, 1, 2]:\n g.axes[i][j].set_xscale('log')\n g.axes[i][j].set_yscale('log')\n g.axes[i][j].set_xlim([1e0, 1e4])\n g.axes[i][j].set_ylim([1e0, 1e4])\n \ng.savefig('adiv_%s_scatter.pdf' % version)", "_____no_output_____" ], [ "sns.lmplot(x='observed_tag_sequences_90bp', y='observed_tag_sequences_150bp', col='empo_3', hue=\"empo_3\", data=df1,\n col_wrap=4, palette=get_empo_cat_color(returndict=True), size=3, markers='o',\n scatter_kws={\"s\": 20, \"alpha\": 1}, fit_reg=True)\nplt.xlim([0, 3000])\nplt.ylim([0, 3000])\nplt.savefig('adiv_%s_lmplot.pdf' % version)", "_____no_output_____" ], [ "df1melt = pd.melt(df1, id_vars='empo_3')\nempo_list = list(set(df1melt.empo_3))\nempo_list = [x for x in empo_list if type(x) is str]\nempo_list.sort()\nempo_colors = [get_empo_cat_color(returndict=True)[x] for x in empo_list]\n\nfor var in ['observed_tag_sequences_90bp', 'observed_tag_sequences_100bp', 'observed_tag_sequences_150bp']:\n list_of = [0] * len(empo_list)\n df1melt2 = df1melt[df1melt['variable'] == var].drop('variable', axis=1)\n for empo in np.arange(len(empo_list)):\n list_of[empo] = list(df1melt2.pivot(columns='empo_3')['value'][empo_list[empo]].dropna())\n\n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(2.5,2.5)) \n plt.hist(list_of, color=empo_colors, \n bins=np.logspace(np.log10(1e0),np.log10(1e4), 20),\n stacked=True)\n plt.xscale('log')\n\n fig.savefig('adiv_%s_hist_%s.pdf' % (version, var))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d071ea9989feb789b1b3ba569b36db15f307938c
5,646
ipynb
Jupyter Notebook
jobsearch_web_scraping/job_search_colab.ipynb
Ricardo-BarMa/web-scraping
2c9701a1bea983b67cb9f99d472830a0291691c3
[ "MIT" ]
null
null
null
jobsearch_web_scraping/job_search_colab.ipynb
Ricardo-BarMa/web-scraping
2c9701a1bea983b67cb9f99d472830a0291691c3
[ "MIT" ]
null
null
null
jobsearch_web_scraping/job_search_colab.ipynb
Ricardo-BarMa/web-scraping
2c9701a1bea983b67cb9f99d472830a0291691c3
[ "MIT" ]
null
null
null
36.192308
93
0.647892
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d071f167d932969d67fb62ac9c4d26ed4702b7a1
18,684
ipynb
Jupyter Notebook
explore/tags_filter.ipynb
cpc-azimuths/azimuth-rain
60ae6c338f24523a9168ccbed28b18b6f68538cc
[ "BSD-3-Clause" ]
null
null
null
explore/tags_filter.ipynb
cpc-azimuths/azimuth-rain
60ae6c338f24523a9168ccbed28b18b6f68538cc
[ "BSD-3-Clause" ]
null
null
null
explore/tags_filter.ipynb
cpc-azimuths/azimuth-rain
60ae6c338f24523a9168ccbed28b18b6f68538cc
[ "BSD-3-Clause" ]
null
null
null
56.44713
1,995
0.634875
[ [ [ "# Value Investing Indicators from SEC Filings\n\n### Data Source: https://www.sec.gov/dera/data/financial-statement-data-sets.html\n\n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport os\nimport shutil\nimport glob\nimport sys\nimport warnings\nimport functools\nfrom functools import reduce\nimport os \n\npd.set_option('display.max_columns', 999)\n\nwarnings.simplefilter(\"ignore\")\n\nos.chdir(\"..\")\n\ndir_root = os.getcwd()\n", "_____no_output_____" ], [ "dir_raw = dir_root + u\"/sec_filings/Raw\"\n\ncik_lookup = pd.read_csv(dir_root + u\"/sec_filings/cik_ticker.csv\", usecols=['CIK', 'Ticker'], sep=\"|\")\n", "_____no_output_____" ], [ "# num_tags = [\"PreferredStockValue\", \"AssetsCurrent\", \"Liabilities\", \"EarningsPerShareBasic\", \"CommonStockSharesOutstanding\", \"LiabilitiesCurrent\", \"EarningsPerShareBasic\", \"SharePrice\", \"StockholdersEquity\", \"PreferredStockValue\", \"CommonStockSharesOutstanding\", \"NetIncomeLoss\", \"GrossProfit\", \"SalesRevenueNet\",\"StockRepurchasedAndRetiredDuringPeriodShares\"]\n\nfiles_num = sorted(glob.glob(dir_raw + u'/*_num.txt'))\n\nfiles_sub = sorted(glob.glob(dir_raw + u'/*_sub.txt'))\n\nfiles_pre = sorted(glob.glob(dir_raw + u'/*_pre.txt'))\n\nsec_df = pd.DataFrame([])\n\nfor num, sub, pre in zip(files_num, files_sub, files_pre):\n df_num = pd.read_csv(num, sep='\\t', dtype=str, encoding = \"ISO-8859-1\")\n df_sub = pd.read_csv(sub, sep='\\t', dtype=str, encoding = \"ISO-8859-1\")\n df_pre = pd.read_csv(pre, sep='\\t', dtype=str, encoding = \"ISO-8859-1\")\n # df_num = df_num[df_num['tag'].isin(num_tags)]\n df_pre = df_pre.merge(df_num, on=['adsh', 'tag', 'version'], sort=True)\n sec_merge = df_sub.merge(df_pre, on='adsh', how=\"inner\", sort=True)\n sec_merge = sec_merge[sec_merge['form'] == \"10-Q\"]\n sec_merge = sec_merge[sec_merge['stmt'] == \"BS\"]\n sec_df = sec_df.append(sec_merge)\n", "_____no_output_____" ], [ "sec_curated = sec_df.sort_values(by='ddate').drop_duplicates(subset=['adsh', 'tag', 'version'], keep='last')\n\nsec_curated = sec_curated[['adsh', 'ddate','version','filed', 'form', 'fp', 'fy', 'fye', 'instance', 'period', 'tag', 'uom', 'value']]\n\nsec_curated.to_csv(dir_root + r'/test.csv', index=False)", "_____no_output_____" ], [ "sec_curated = sec_curated.drop_duplicates(subset=['instance'])\nsec_curated[sec_curated['tag'] == 'Share'].dropna()\n", "_____no_output_____" ], [ "drop_cols = ['adsh', 'ddate','version','filed', 'form', 'fp', 'fy', 'fye', 'period', 'tag', 'uom']\n\nPreferredStockValue = sec_curated[sec_curated[\"tag\"] == \"PreferredStockValue\"].rename(columns={\"value\": \"PreferredStockValue\"}).drop(columns=drop_cols)\n\nAssetsCurrent = sec_curated[sec_curated[\"tag\"] == \"AssetsCurrent\"].rename(columns={'value': 'AssetsCurrent'}).drop(columns=drop_cols)\n\nLiabilities = sec_curated[sec_curated[\"tag\"] == \"Liabilities\"].rename(columns={'value': 'Liabilities'}).drop(columns=drop_cols)\n\nEarningsPerShareBasic = sec_curated[sec_curated[\"tag\"] == \"EarningsPerShareBasic\"].rename(columns={'value': 'EarningsPerShareBasic'}).drop(columns=drop_cols)\n\nCommonStockSharesOutstanding = sec_curated[sec_curated[\"tag\"] == \"CommonStockSharesOutstanding\"].rename(columns={'value': 'CommonStockSharesOutstanding'}).drop(columns=drop_cols)\n\nLiabilitiesCurrent = sec_curated[sec_curated[\"tag\"] == \"LiabilitiesCurrent\"].rename(columns={'value': 'LiabilitiesCurrent'}).drop(columns=drop_cols)\n\nEarningsPerShareBasic = sec_curated[sec_curated[\"tag\"] == \"EarningsPerShareBasic\"].rename(columns={'value': 'EarningsPerShareBasic'}).drop(columns=drop_cols)\n\nSharePrice = sec_curated[sec_curated[\"tag\"] == \"SharePrice\"].rename(columns={'value': 'SharePrice'}).drop(columns=drop_cols)\n\nStockholdersEquity = sec_curated[sec_curated[\"tag\"] == \"StockholdersEquity\"].rename(columns={'value': 'StockholdersEquity'}).drop(columns=drop_cols)\n\nPreferredStockValue = sec_curated[sec_curated[\"tag\"] == \"PreferredStockValue\"].rename(columns={'value': 'PreferredStockValue'}).drop(columns=drop_cols)\n\nCommonStockSharesOutstanding = sec_curated[sec_curated[\"tag\"] == \"CommonStockSharesOutstanding\"].rename(columns={'value': 'CommonStockSharesOutstanding'}).drop(columns=drop_cols)\n\nNetIncomeLoss = sec_curated[sec_curated[\"tag\"] == \"NetIncomeLoss\"].rename(columns={'value': 'NetIncomeLoss'}).drop(columns=drop_cols)\n\nGrossProfit = sec_curated[sec_curated[\"tag\"] == \"GrossProfit\"].rename(columns={'value': 'GrossProfit'}).drop(columns=drop_cols)\n\nSalesRevenueNet = sec_curated[sec_curated[\"tag\"] == \"SalesRevenueNet\"].rename(columns={'value': 'SalesRevenueNet'}).drop(columns=drop_cols)\n\nStockRepurchased = sec_curated[sec_curated[\"tag\"] == \"StockRepurchasedAndRetiredDuringPeriodShares\"].rename(columns={'value': 'StockRepurchased'}).drop(columns=drop_cols)\n", "_____no_output_____" ], [ "cols = ['adsh', 'ddate','version','filed', 'form', 'fp', 'fy', 'fye', 'instance', 'period', 'tag', 'uom']\n\nsec_final = sec_curated[cols]\n\ndfs = [sec_curated, PreferredStockValue, AssetsCurrent, Liabilities, EarningsPerShareBasic, \nCommonStockSharesOutstanding, LiabilitiesCurrent, EarningsPerShareBasic, \nSharePrice, StockholdersEquity, PreferredStockValue, CommonStockSharesOutstanding, \nNetIncomeLoss, GrossProfit, SalesRevenueNet,StockRepurchased]\n\ndf_final = reduce(lambda left,right: pd.merge(sec_curated,right,on='instance'), dfs)", "_____no_output_____" ], [ "dfs_final = [df.set_index('instance') for df in dfs]\nx = pd.concat(dfs_final, axis=1)\n\nx['SharePriceBasic'].dropna()\n", "_____no_output_____" ] ], [ [ "# Benjamin Graham \n\n## Formulas:\n\n* NCAVPS = CurrentAssets - (Total Liabilities + Preferred Stock) ÷ Shares Outstanding\n * Less than 1.10 \n\n* Debt to Assets = Current Assets / Current Liabilities\n * Greater than 1.50\n\n* Price / Earnings per Share ratio \n * Less than 9.0\n\n* PRICE TO BOOK VALUE = (P/BV) \n * Where BV = (Total Shareholder Equity−Preferred Stock)/ Total Outstanding Shares\n * Less than 1.20. P/E ratios\n\n## References:\n\nBenjamin Graham rules: https://cabotwealth.com/daily/value-investing/benjamin-grahams-value-stock-criteria/ \n\nBenjamin Graham rules Modified: https://www.netnethunter.com/16-benjamin-graham-rules/ \n\n", "_____no_output_____" ] ], [ [ "\nsec_df['NCAVPS'] = sec_df['AssetsCurrent'] - (sec_df['Liabilities'] + sec_df[\n'PreferredStockValue']) / sec_df['CommonStockSharesOutstanding']\n\nsec_df['DebtToAssets'] = sec_df['AssetsCurrent'] / sec_df['LiabilitiesCurrent']\n\nsec_df['PE'] = sec_df['SharePrice'] / sec_df['EarningsPerShareBasic'] \n\nsec_df['PBV'] = sec_df['SharePrice'] / ((sec_df['StockholdersEquity'] - sec_df['PreferredStockValue']) / sec_df['CommonStockSharesOutstanding'])\n", "_____no_output_____" ] ], [ [ "# Warren Buffet Rules \n\n## Formulas\n\n* Debt/Equity= Total Liabilities / Total Shareholders’ Equity \n * Less than 1 and ROE is greater than 10%\n\n* Return on Earnings = (Net Income / Stock Holders Equity)\n * Is Positive\n\n* Gross Profit Margin = Gross Profit / Revenue \n * Greater than 40% \n​\n* Quarter over Quarter EPS \n * Greater than 10\n\n* Stock Buybacks\n * Greater than last period\n\n## References: \nhttps://www.oldschoolvalue.com/tutorial/this-is-how-buffett-interprets-financial-statements/", "_____no_output_____" ] ], [ [ "\nsec_df['DebtEquity'] = sec_df['Liabilities'] / sec_df['StockholdersEquity']\n\nsec_df['ReturnEarnings'] = sec_df['NetIncomeLoss'] / sec_df['StockholdersEquity']\n\nsec_df[\"GrossProfitMargin\"] = sec_df['GrossProfit'] / sec_df['SalesRevenueNet']\n\nsec_df[\"EPS\"] = sec_df[\"EarningsPerShareBasic\"]\n\nsec_df[\"StockBuybacks\"] = sec_df[\"StockRepurchasedAndRetiredDuringPeriodShares\"]", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d071fa1112412164f1191d49e5972d270918f2e2
108,813
ipynb
Jupyter Notebook
notebooks/modeling.ipynb
brunocvs7/bot_detection_twitter_profile_features
44a88b0774bdab33da78f7679e109ccd8c34f4df
[ "MIT" ]
1
2021-11-03T02:22:57.000Z
2021-11-03T02:22:57.000Z
notebooks/modeling.ipynb
brunocvs7/bot_detection_twitter_profile_features
44a88b0774bdab33da78f7679e109ccd8c34f4df
[ "MIT" ]
null
null
null
notebooks/modeling.ipynb
brunocvs7/bot_detection_twitter_profile_features
44a88b0774bdab33da78f7679e109ccd8c34f4df
[ "MIT" ]
1
2021-11-01T00:49:07.000Z
2021-11-01T00:49:07.000Z
148.246594
37,414
0.856249
[ [ [ "# Modeling\n@Author: Bruno Vieira\n\nGoals: Create a classification model able to identify a BOT account on twitter, using only profile-based features.", "_____no_output_____" ] ], [ [ "# Libs\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.metrics import classification_report, precision_score, recall_score, roc_auc_score, average_precision_score, f1_score\nfrom sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, MinMaxScaler, StandardScaler, FunctionTransformer\nfrom sklearn.inspection import permutation_importance\nfrom sklearn.model_selection import cross_validate, StratifiedKFold, train_test_split\nimport cloudpickle\nfrom sklearn.model_selection import learning_curve\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nimport utils.dev.model as mdl\nimport importlib\nimport warnings\nwarnings.filterwarnings('ignore')\npd.set_option('display.max_columns', 100)", "_____no_output_____" ], [ "# Paths and Filenames\nDATA_INPUT_PATH = 'data/interim'\nDATA_INPUT_TRAIN_NAME = 'train_selected_features.csv'\nDATA_INPUT_TEST_NAME = 'test.csv'\nMODEL_OUTPUT_PATH = 'models'\nMODEL_NAME = 'model_bot_classifier_v0.pkl'", "_____no_output_____" ], [ "df_twitter_train = pd.read_csv(os.path.join('..',DATA_INPUT_PATH, DATA_INPUT_TRAIN_NAME))\ndf_twitter_test = pd.read_csv(os.path.join('..',DATA_INPUT_PATH, DATA_INPUT_TEST_NAME))", "_____no_output_____" ], [ "df_twitter_train.replace({False:'FALSE', True:'TRUE'}, inplace=True)\ndf_twitter_test.replace({False:'FALSE', True:'TRUE'}, inplace=True)", "_____no_output_____" ] ], [ [ "# 1) Training", "_____no_output_____" ] ], [ [ "X_train = df_twitter_train.drop('label', axis=1)\ny_train = df_twitter_train['label']\ncat_columns = df_twitter_train.select_dtypes(include=['bool', 'object']).columns.tolist()\nnum_columns = df_twitter_train.select_dtypes(include=['int32','int64','float32', 'float64']).columns.tolist()\nnum_columns.remove('label')", "_____no_output_____" ], [ "\nskf = StratifiedKFold(n_splits=10)\ncat_preprocessor = Pipeline(steps=[('imputer', SimpleImputer(strategy='most_frequent')), \n ('encoder', OneHotEncoder(handle_unknown='ignore'))])\nnum_preprocessor = Pipeline(steps=[('imputer', SimpleImputer(strategy='constant', fill_value=0)), \n ('scaler', StandardScaler())])\n\npipe_transformer = ColumnTransformer(transformers=[('num_pipe_preprocessor', num_preprocessor, num_columns),\n ('cat_pipe_preprocessor', cat_preprocessor, cat_columns)])\npipe_model = Pipeline(steps=[('pre_processor', pipe_transformer), \n ('model', SVC(random_state=23, kernel='rbf', gamma='scale', C=1, probability=True))])", "_____no_output_____" ], [ "cross_validation_results = cross_validate(pipe_model, X=X_train, y=y_train, scoring=['average_precision', 'roc_auc', 'precision', 'recall'], cv=skf, n_jobs=-1, verbose=0, return_train_score=True)", "_____no_output_____" ], [ "pipe_model.fit(X_train, y_train)", "_____no_output_____" ] ], [ [ "# 2) Evaluation", "_____no_output_____" ], [ "## 2.1) Cross Validation", "_____no_output_____" ] ], [ [ "cross_validation_results = pd.DataFrame(cross_validation_results)", "_____no_output_____" ], [ "cross_validation_results", "_____no_output_____" ], [ "1.96*cross_validation_results['train_average_precision'].std()", "_____no_output_____" ], [ "print(f\"Avg Train Avg Precision:{np.round(cross_validation_results['train_average_precision'].mean(), 2)} +/- {np.round(1.96*cross_validation_results['train_average_precision'].std(), 2)}\")\nprint(f\"Avg Test Avg Precision:{np.round(cross_validation_results['test_average_precision'].mean(), 2)} +/- {np.round(1.96*cross_validation_results['test_average_precision'].std(), 2)}\")", "Avg Train Avg Precision:0.72 +/- 0.01\nAvg Test Avg Precision:0.72 +/- 0.1\n" ], [ "print(f\"ROC - AUC Train:{np.round(cross_validation_results['train_roc_auc'].mean(), 2)} +/- {np.round(1.96*cross_validation_results['train_roc_auc'].std(), 2)}\")\nprint(f\"ROC - AUC Test:{np.round(cross_validation_results['test_roc_auc'].mean(), 2)} +/- {np.round(1.96*cross_validation_results['test_roc_auc'].std(), 2)}\")", "ROC - AUC Train:0.69 +/- 0.01\nROC - AUC Test:0.68 +/- 0.11\n" ] ], [ [ "## 2.2) Test Set", "_____no_output_____" ] ], [ [ "def build_features(df):\n list_columns_colors = df.filter(regex='color').columns.tolist()\n df = df.replace({'false':'FALSE', 'true':'TRUE', False:'FALSE', True:'TRUE'})\n df['name'] = df['name'].apply(lambda x: len(x) if x is not np.nan else 0)\n df['profile_location'] = df['profile_location'].apply(lambda x: 'TRUE' if x is not np.nan else 'FALSE')\n df['rate_friends_followers'] = df['friends_count']/df['followers_count']\n df['rate_friends_followers'] = df['rate_friends_followers'].map({np.inf:0, np.nan:0})\n df['unique_colors'] = df[list_columns_colors].stack().groupby(level=0).nunique()\n return df", "_____no_output_____" ], [ "df_twitter_test = build_features(df_twitter_test)", "_____no_output_____" ], [ "columns_to_predict = df_twitter_train.columns.tolist()\ndf_twitter_test = df_twitter_test.loc[:,columns_to_predict]", "_____no_output_____" ], [ "X_test = df_twitter_test.drop('label', axis=1)\ny_test = df_twitter_test['label']\n", "_____no_output_____" ] ], [ [ "## 2.3) Metrics", "_____no_output_____" ] ], [ [ "y_train_predict = pipe_model.predict_proba(X_train)\ny_test_predict = pipe_model.predict_proba(X_test)", "_____no_output_____" ], [ "df_metrics_train = mdl.eval_thresh(y_real = y_train, y_proba = y_train_predict[:,1])\ndf_metrics_test = mdl.eval_thresh(y_real = y_test, y_proba = y_test_predict[:,1])\n", "_____no_output_____" ], [ "importlib.reload(mdl)", "_____no_output_____" ], [ "mdl.plot_metrics(df_metrics_train)", "_____no_output_____" ], [ "mdl.plot_metrics(df_metrics_test)", "_____no_output_____" ] ], [ [ "## 2.4) Learning Curve", "_____no_output_____" ] ], [ [ "train_sizes, train_scores, validation_scores = learning_curve(estimator = pipe_model,\n X = X_train,\n y = y_train,\n cv = 5,\n train_sizes=np.linspace(0.1, 1, 10),\n scoring = 'neg_log_loss')", "_____no_output_____" ], [ "train_scores_mean = train_scores.mean(axis=1)\nvalidation_scores_mean = validation_scores.mean(axis=1)\nplt.style.use('seaborn')\nplt.plot(train_sizes, train_scores_mean, label = 'Training error')\nplt.plot(train_sizes, validation_scores_mean, label = 'Validation error')\nplt.ylabel('Average Precision Score', fontsize = 14)\nplt.xlabel('Training set size', fontsize = 14)\nplt.title('Learning curves', fontsize = 18, y = 1.03)\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "## 2.5) Ordering", "_____no_output_____" ], [ "## 2.6) Callibration", "_____no_output_____" ], [ "# 3) Saving the Model", "_____no_output_____" ] ], [ [ "with open(os.path.join('..', MODEL_OUTPUT_PATH, MODEL_NAME), 'wb') as f:\n cloudpickle.dump(pipe_model, f)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ] ]
d071fa42f382035bd78b8caf0b6df8b4a5e0c404
62,334
ipynb
Jupyter Notebook
Online-Courses/gans/Vanilla GAN PyTorch.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
1
2019-05-10T09:16:23.000Z
2019-05-10T09:16:23.000Z
Online-Courses/gans/Vanilla GAN PyTorch.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
null
null
null
Online-Courses/gans/Vanilla GAN PyTorch.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
1
2019-05-10T09:17:28.000Z
2019-05-10T09:17:28.000Z
155.059701
50,988
0.872461
[ [ [ "from IPython import display\n\nfrom utils import Logger\n\nimport torch\nfrom torch import nn\nfrom torch.optim import Adam\nfrom torch.autograd import Variable\n\nfrom torchvision import transforms, datasets", "/Users/diego/.pyenv/versions/miniconda-latest/lib/python2.7/site-packages/subprocess32.py:472: RuntimeWarning: The _posixsubprocess module is not being used. Child process reliability may suffer if your program uses threads.\n \"program uses threads.\", RuntimeWarning)\n" ], [ "DATA_FOLDER = './torch_data/VGAN/MNIST'", "_____no_output_____" ] ], [ [ "## Load Data", "_____no_output_____" ] ], [ [ "def mnist_data():\n compose = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((.5, .5, .5), (.5, .5, .5))\n ])\n out_dir = '{}/dataset'.format(DATA_FOLDER)\n return datasets.MNIST(root=out_dir, train=True, transform=compose, download=True)", "_____no_output_____" ], [ "data = mnist_data()\nbatch_size = 100\ndata_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True)\nnum_batches = len(data_loader)", "_____no_output_____" ] ], [ [ "## Networks", "_____no_output_____" ] ], [ [ "class DiscriminativeNet(torch.nn.Module):\n \"\"\"\n A two hidden-layer discriminative neural network\n \"\"\"\n def __init__(self):\n super(DiscriminativeNet, self).__init__()\n n_features = 784\n n_out = 1\n \n self.hidden0 = nn.Sequential( \n nn.Linear(n_features, 1024),\n nn.LeakyReLU(0.2),\n nn.Dropout(0.3)\n )\n self.hidden1 = nn.Sequential(\n nn.Linear(1024, 512),\n nn.LeakyReLU(0.2),\n nn.Dropout(0.3)\n )\n self.hidden2 = nn.Sequential(\n nn.Linear(512, 256),\n nn.LeakyReLU(0.2),\n nn.Dropout(0.3)\n )\n self.out = nn.Sequential(\n torch.nn.Linear(256, n_out),\n torch.nn.Sigmoid()\n )\n\n def forward(self, x):\n x = self.hidden0(x)\n x = self.hidden1(x)\n x = self.hidden2(x)\n x = self.out(x)\n return x\n \ndef images_to_vectors(images):\n return images.view(images.size(0), 784)\n\ndef vectors_to_images(vectors):\n return vectors.view(vectors.size(0), 1, 28, 28)", "_____no_output_____" ], [ "class GenerativeNet(torch.nn.Module):\n \"\"\"\n A three hidden-layer generative neural network\n \"\"\"\n def __init__(self):\n super(GenerativeNet, self).__init__()\n n_features = 100\n n_out = 784\n \n self.hidden0 = nn.Sequential(\n nn.Linear(n_features, 256),\n nn.LeakyReLU(0.2)\n )\n self.hidden1 = nn.Sequential( \n nn.Linear(256, 512),\n nn.LeakyReLU(0.2)\n )\n self.hidden2 = nn.Sequential(\n nn.Linear(512, 1024),\n nn.LeakyReLU(0.2)\n )\n \n self.out = nn.Sequential(\n nn.Linear(1024, n_out),\n nn.Tanh()\n )\n\n def forward(self, x):\n x = self.hidden0(x)\n x = self.hidden1(x)\n x = self.hidden2(x)\n x = self.out(x)\n return x\n \n# Noise\ndef noise(size):\n n = Variable(torch.randn(size, 100))\n if torch.cuda.is_available(): return n.cuda \n return n", "_____no_output_____" ], [ "discriminator = DiscriminativeNet()\ngenerator = GenerativeNet()\nif torch.cuda.is_available():\n discriminator.cuda()\n generator.cuda()", "_____no_output_____" ] ], [ [ "## Optimization", "_____no_output_____" ] ], [ [ "# Optimizers\nd_optimizer = Adam(discriminator.parameters(), lr=0.0002)\ng_optimizer = Adam(generator.parameters(), lr=0.0002)\n\n# Loss function\nloss = nn.BCELoss()\n\n# Number of steps to apply to the discriminator\nd_steps = 1 # In Goodfellow et. al 2014 this variable is assigned to 1\n# Number of epochs\nnum_epochs = 200", "_____no_output_____" ] ], [ [ "## Training", "_____no_output_____" ] ], [ [ "def real_data_target(size):\n '''\n Tensor containing ones, with shape = size\n '''\n data = Variable(torch.ones(size, 1))\n if torch.cuda.is_available(): return data.cuda()\n return data\n\ndef fake_data_target(size):\n '''\n Tensor containing zeros, with shape = size\n '''\n data = Variable(torch.zeros(size, 1))\n if torch.cuda.is_available(): return data.cuda()\n return data", "_____no_output_____" ], [ "def train_discriminator(optimizer, real_data, fake_data):\n # Reset gradients\n optimizer.zero_grad()\n \n # 1.1 Train on Real Data\n prediction_real = discriminator(real_data)\n # Calculate error and backpropagate\n error_real = loss(prediction_real, real_data_target(real_data.size(0)))\n error_real.backward()\n\n # 1.2 Train on Fake Data\n prediction_fake = discriminator(fake_data)\n # Calculate error and backpropagate\n error_fake = loss(prediction_fake, fake_data_target(real_data.size(0)))\n error_fake.backward()\n \n # 1.3 Update weights with gradients\n optimizer.step()\n \n # Return error\n return error_real + error_fake, prediction_real, prediction_fake\n\ndef train_generator(optimizer, fake_data):\n # 2. Train Generator\n # Reset gradients\n optimizer.zero_grad()\n # Sample noise and generate fake data\n prediction = discriminator(fake_data)\n # Calculate error and backpropagate\n error = loss(prediction, real_data_target(prediction.size(0)))\n error.backward()\n # Update weights with gradients\n optimizer.step()\n # Return error\n return error", "_____no_output_____" ] ], [ [ "### Generate Samples for Testing", "_____no_output_____" ] ], [ [ "num_test_samples = 16\ntest_noise = noise(num_test_samples)", "_____no_output_____" ] ], [ [ "### Start training", "_____no_output_____" ] ], [ [ "logger = Logger(model_name='VGAN', data_name='MNIST')\n\nfor epoch in range(num_epochs):\n for n_batch, (real_batch,_) in enumerate(data_loader):\n\n # 1. Train Discriminator\n real_data = Variable(images_to_vectors(real_batch))\n if torch.cuda.is_available(): real_data = real_data.cuda()\n # Generate fake data\n fake_data = generator(noise(real_data.size(0))).detach()\n # Train D\n d_error, d_pred_real, d_pred_fake = train_discriminator(d_optimizer,\n real_data, fake_data)\n\n # 2. Train Generator\n # Generate fake data\n fake_data = generator(noise(real_batch.size(0)))\n # Train G\n g_error = train_generator(g_optimizer, fake_data)\n # Log error\n logger.log(d_error, g_error, epoch, n_batch, num_batches)\n\n # Display Progress\n if (n_batch) % 100 == 0:\n display.clear_output(True)\n # Display Images\n test_images = vectors_to_images(generator(test_noise)).data.cpu()\n logger.log_images(test_images, num_test_samples, epoch, n_batch, num_batches);\n # Display status Logs\n logger.display_status(\n epoch, num_epochs, n_batch, num_batches,\n d_error, g_error, d_pred_real, d_pred_fake\n )\n # Model Checkpoints\n logger.save_models(generator, discriminator, epoch)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d07211e30aa4361bcd64996e48c354969af630ee
29,345
ipynb
Jupyter Notebook
notebooks/demos/correlation_matrix.ipynb
prof-groff/evns-462
072b3d7b2e145bd9423e35a18b1b5cbcf4d11914
[ "MIT" ]
null
null
null
notebooks/demos/correlation_matrix.ipynb
prof-groff/evns-462
072b3d7b2e145bd9423e35a18b1b5cbcf4d11914
[ "MIT" ]
null
null
null
notebooks/demos/correlation_matrix.ipynb
prof-groff/evns-462
072b3d7b2e145bd9423e35a18b1b5cbcf4d11914
[ "MIT" ]
1
2020-03-12T15:14:05.000Z
2020-03-12T15:14:05.000Z
60.010225
16,420
0.710274
[ [ [ "## Correlation Matrix\nThis notebook shows how to calculate a correlation matrix to explore if there are correlations any pair of columns in a datafram. The correlation coefficient can be Pearson's, Kendall's, or Spearmans.", "_____no_output_____" ] ], [ [ "# import some modules\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport seaborn as sns", "_____no_output_____" ], [ "# read in some data\ndata = pd.read_csv('corr.csv')\nprint(data.shape)\ndata.head(6)", "(30, 4)\n" ], [ "# you can find the correlation coefficients between columns on a data frame using the .corr method\ndata.corr(method='pearson')", "_____no_output_____" ], [ "# alternatively, you can find the correlation coeff and the pvalue between individual columns using stats.pearsonr\nstats.pearsonr(data.x1,data.x2)", "_____no_output_____" ], [ "# let's define a function that returns two dataframes, one with correlation coefficients and the other with p-values\ndef calc_corr_matrix(data, dims):\n cmatrix = pd.DataFrame()\n pmatrix = pd.DataFrame()\n for row in dims:\n for col in dims:\n corrcoef ,pvalue = stats.pearsonr(data[row],data[col])\n cmatrix.loc[row,col] = corrcoef\n pmatrix.loc[row,col] = pvalue\n for each in dims:\n cmatrix.loc[each,each] = np.nan\n pmatrix.loc[each,each] = np.nan\n return cmatrix, pmatrix", "_____no_output_____" ], [ "# use the funtion\ncmatrix, pmatrix = calc_corr_matrix(data,data.keys().values)", "_____no_output_____" ], [ "# look at results\ncmatrix", "_____no_output_____" ], [ "pmatrix", "_____no_output_____" ], [ "# plot a heatmap to show correlation coefficients\nplt.figure(figsize=(8,5))\nax = sns.heatmap(cmatrix, center = 0, cmap='coolwarm', annot = True, vmin=-1, vmax=1)\nax.tick_params(axis='both', labelsize=12)\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d072168e2025fd64a9b746c925f0cdfab30acfbb
10,867
ipynb
Jupyter Notebook
Thursday/Activities/06-Stu_TrainingGrounds/Unsolved/TrainingGrounds.ipynb
Jens794/jack101
cb137eb4c6ad29552bb933f8889526ac6bda7ab6
[ "ADSL" ]
null
null
null
Thursday/Activities/06-Stu_TrainingGrounds/Unsolved/TrainingGrounds.ipynb
Jens794/jack101
cb137eb4c6ad29552bb933f8889526ac6bda7ab6
[ "ADSL" ]
null
null
null
Thursday/Activities/06-Stu_TrainingGrounds/Unsolved/TrainingGrounds.ipynb
Jens794/jack101
cb137eb4c6ad29552bb933f8889526ac6bda7ab6
[ "ADSL" ]
null
null
null
89.07377
3,711
0.677464
[ [ [ "# Import Dependencies\nimport pandas as pd\nimport random", "_____no_output_____" ], [ "# A gigantic DataFrame of individuals' names, their trainers, their weight, and their days as gym members\ntraining_data = pd.DataFrame({\n \"Name\":[\"Gino Walker\",\"Hiedi Wasser\",\"Kerrie Wetzel\",\"Elizabeth Sackett\",\"Jack Mitten\",\"Madalene Wayman\",\"Jamee Horvath\",\"Arlena Reddin\",\"Tula Levan\",\"Teisha Dreier\",\"Leslie Carrier\",\"Arlette Hartson\",\"Romana Merkle\",\"Heath Viviani\",\"Andres Zimmer\",\"Allyson Osman\",\"Yadira Caggiano\",\"Jeanmarie Friedrichs\",\"Leann Ussery\",\"Bee Mom\",\"Pandora Charland\",\"Karena Wooten\",\"Elizabet Albanese\",\"Augusta Borjas\",\"Erma Yadon\",\"Belia Lenser\",\"Karmen Sancho\",\"Edison Mannion\",\"Sonja Hornsby\",\"Morgan Frei\",\"Florencio Murphy\",\"Christoper Hertel\",\"Thalia Stepney\",\"Tarah Argento\",\"Nicol Canfield\",\"Pok Moretti\",\"Barbera Stallings\",\"Muoi Kelso\",\"Cicely Ritz\",\"Sid Demelo\",\"Eura Langan\",\"Vanita An\",\"Frieda Fuhr\",\"Ernest Fitzhenry\",\"Ashlyn Tash\",\"Melodi Mclendon\",\"Rochell Leblanc\",\"Jacqui Reasons\",\"Freeda Mccroy\",\"Vanna Runk\",\"Florinda Milot\",\"Cierra Lecompte\",\"Nancey Kysar\",\"Latasha Dalton\",\"Charlyn Rinaldi\",\"Erline Averett\",\"Mariko Hillary\",\"Rosalyn Trigg\",\"Sherwood Brauer\",\"Hortencia Olesen\",\"Delana Kohut\",\"Geoffrey Mcdade\",\"Iona Delancey\",\"Donnie Read\",\"Cesar Bhatia\",\"Evia Slate\",\"Kaye Hugo\",\"Denise Vento\",\"Lang Kittle\",\"Sherry Whittenberg\",\"Jodi Bracero\",\"Tamera Linneman\",\"Katheryn Koelling\",\"Tonia Shorty\",\"Misha Baxley\",\"Lisbeth Goering\",\"Merle Ladwig\",\"Tammie Omar\",\"Jesusa Avilla\",\"Alda Zabala\",\"Junita Dogan\",\"Jessia Anglin\",\"Peggie Scranton\",\"Dania Clodfelter\",\"Janis Mccarthy\",\"Edmund Galusha\",\"Tonisha Posey\",\"Arvilla Medley\",\"Briana Barbour\",\"Delfina Kiger\",\"Nia Lenig\",\"Ricarda Bulow\",\"Odell Carson\",\"Nydia Clonts\",\"Andree Resendez\",\"Daniela Puma\",\"Sherill Paavola\",\"Gilbert Bloomquist\",\"Shanon Mach\",\"Justin Bangert\",\"Arden Hokanson\",\"Evelyne Bridge\",\"Hee Simek\",\"Ward Deangelis\",\"Jodie Childs\",\"Janis Boehme\",\"Beaulah Glowacki\",\"Denver Stoneham\",\"Tarra Vinton\",\"Deborah Hummell\",\"Ulysses Neil\",\"Kathryn Marques\",\"Rosanna Dake\",\"Gavin Wheat\",\"Tameka Stoke\",\"Janella Clear\",\"Kaye Ciriaco\",\"Suk Bloxham\",\"Gracia Whaley\",\"Philomena Hemingway\",\"Claudette Vaillancourt\",\"Olevia Piche\",\"Trey Chiles\",\"Idalia Scardina\",\"Jenine Tremble\",\"Herbert Krider\",\"Alycia Schrock\",\"Miss Weibel\",\"Pearlene Neidert\",\"Kina Callender\",\"Charlotte Skelley\",\"Theodora Harrigan\",\"Sydney Shreffler\",\"Annamae Trinidad\",\"Tobi Mumme\",\"Rosia Elliot\",\"Debbra Putt\",\"Rena Delosantos\",\"Genna Grennan\",\"Nieves Huf\",\"Berry Lugo\",\"Ayana Verdugo\",\"Joaquin Mazzei\",\"Doris Harmon\",\"Patience Poss\",\"Magaret Zabel\",\"Marylynn Hinojos\",\"Earlene Marcantel\",\"Yuki Evensen\",\"Rema Gay\",\"Delana Haak\",\"Patricia Fetters\",\"Vinnie Elrod\",\"Octavia Bellew\",\"Burma Revard\",\"Lakenya Kato\",\"Vinita Buchner\",\"Sierra Margulies\",\"Shae Funderburg\",\"Jenae Groleau\",\"Louetta Howie\",\"Astrid Duffer\",\"Caron Altizer\",\"Kymberly Amavisca\",\"Mohammad Diedrich\",\"Thora Wrinkle\",\"Bethel Wiemann\",\"Patria Millet\",\"Eldridge Burbach\",\"Alyson Eddie\",\"Zula Hanna\",\"Devin Goodwin\",\"Felipa Kirkwood\",\"Kurtis Kempf\",\"Kasey Lenart\",\"Deena Blankenship\",\"Kandra Wargo\",\"Sherrie Cieslak\",\"Ron Atha\",\"Reggie Barreiro\",\"Daria Saulter\",\"Tandra Eastman\",\"Donnell Lucious\",\"Talisha Rosner\",\"Emiko Bergh\",\"Terresa Launius\",\"Margy Hoobler\",\"Marylou Stelling\",\"Lavonne Justice\",\"Kala Langstaff\",\"China Truett\",\"Louanne Dussault\",\"Thomasena Samaniego\",\"Charlesetta Tarbell\",\"Fatimah Lade\",\"Malisa Cantero\",\"Florencia Litten\",\"Francina Fraise\",\"Patsy London\",\"Deloris Mclaughlin\"],\n \"Trainer\":['Bettyann Savory','Mariah Barberio','Gordon Perrine','Pa Dargan','Blanch Victoria','Aldo Byler','Aldo Byler','Williams Camire','Junie Ritenour','Gordon Perrine','Bettyann Savory','Mariah Barberio','Aldo Byler','Barton Stecklein','Bettyann Savory','Barton Stecklein','Gordon Perrine','Pa Dargan','Aldo Byler','Brittani Brin','Bettyann Savory','Phyliss Houk','Bettyann Savory','Junie Ritenour','Aldo Byler','Calvin North','Brittani Brin','Junie Ritenour','Blanch Victoria','Brittani Brin','Bettyann Savory','Blanch Victoria','Mariah Barberio','Bettyann Savory','Blanch Victoria','Brittani Brin','Junie Ritenour','Pa Dargan','Gordon Perrine','Phyliss Houk','Pa Dargan','Mariah Barberio','Phyliss Houk','Phyliss Houk','Calvin North','Williams Camire','Brittani Brin','Gordon Perrine','Bettyann Savory','Bettyann Savory','Pa Dargan','Phyliss Houk','Barton Stecklein','Blanch Victoria','Coleman Dunmire','Phyliss Houk','Blanch Victoria','Pa Dargan','Harland Coolidge','Calvin North','Bettyann Savory','Phyliss Houk','Bettyann Savory','Harland Coolidge','Gordon Perrine','Junie Ritenour','Harland Coolidge','Blanch Victoria','Mariah Barberio','Coleman Dunmire','Aldo Byler','Bettyann Savory','Gordon Perrine','Bettyann Savory','Barton Stecklein','Harland Coolidge','Aldo Byler','Aldo Byler','Pa Dargan','Junie Ritenour','Brittani Brin','Junie Ritenour','Gordon Perrine','Mariah Barberio','Mariah Barberio','Mariah Barberio','Bettyann Savory','Brittani Brin','Aldo Byler','Phyliss Houk','Blanch Victoria','Pa Dargan','Phyliss Houk','Brittani Brin','Barton Stecklein','Coleman Dunmire','Bettyann Savory','Bettyann Savory','Gordon Perrine','Blanch Victoria','Junie Ritenour','Phyliss Houk','Coleman Dunmire','Williams Camire','Harland Coolidge','Williams Camire','Aldo Byler','Harland Coolidge','Gordon Perrine','Brittani Brin','Coleman Dunmire','Calvin North','Phyliss Houk','Brittani Brin','Aldo Byler','Bettyann Savory','Brittani Brin','Gordon Perrine','Calvin North','Harland Coolidge','Coleman Dunmire','Harland Coolidge','Aldo Byler','Junie Ritenour','Blanch Victoria','Harland Coolidge','Blanch Victoria','Junie Ritenour','Harland Coolidge','Junie Ritenour','Gordon Perrine','Brittani Brin','Coleman Dunmire','Williams Camire','Junie Ritenour','Brittani Brin','Calvin North','Barton Stecklein','Barton Stecklein','Mariah Barberio','Coleman Dunmire','Bettyann Savory','Mariah Barberio','Pa Dargan','Barton Stecklein','Coleman Dunmire','Brittani Brin','Barton Stecklein','Pa Dargan','Barton Stecklein','Junie Ritenour','Bettyann Savory','Williams Camire','Pa Dargan','Calvin North','Williams Camire','Coleman Dunmire','Aldo Byler','Barton Stecklein','Coleman Dunmire','Blanch Victoria','Mariah Barberio','Mariah Barberio','Harland Coolidge','Barton Stecklein','Phyliss Houk','Pa Dargan','Bettyann Savory','Barton Stecklein','Harland Coolidge','Junie Ritenour','Pa Dargan','Mariah Barberio','Blanch Victoria','Williams Camire','Phyliss Houk','Phyliss Houk','Coleman Dunmire','Mariah Barberio','Gordon Perrine','Coleman Dunmire','Brittani Brin','Pa Dargan','Coleman Dunmire','Brittani Brin','Blanch Victoria','Coleman Dunmire','Gordon Perrine','Coleman Dunmire','Aldo Byler','Aldo Byler','Mariah Barberio','Williams Camire','Phyliss Houk','Aldo Byler','Williams Camire','Aldo Byler','Williams Camire','Coleman Dunmire','Phyliss Houk'],\n \"Weight\":[128,180,193,177,237,166,224,208,177,241,114,161,162,151,220,142,193,193,124,130,132,141,190,239,213,131,172,127,184,157,215,122,181,240,218,205,239,217,234,158,180,131,194,171,177,110,117,114,217,123,248,189,198,127,182,121,224,111,151,170,188,150,137,231,222,186,139,175,178,246,150,154,129,216,144,198,228,183,173,129,157,199,186,232,172,157,246,239,214,161,132,208,187,224,164,177,175,224,219,235,112,241,243,179,208,196,131,207,182,233,191,162,173,197,190,182,231,196,196,143,250,174,138,135,164,204,235,192,114,179,215,127,185,213,250,213,153,217,176,190,119,167,118,208,113,206,200,236,159,218,168,159,156,183,121,203,215,209,179,219,174,220,129,188,217,250,166,157,112,236,182,144,189,243,238,147,165,115,160,134,245,174,238,157,150,184,174,134,134,248,199,165,117,119,162,112,170,224,247,217],\n \"Membership(Days)\":[52,70,148,124,186,157,127,155,37,185,158,129,93,69,124,13,76,153,164,161,48,121,167,69,39,163,7,34,176,169,108,162,195,86,155,77,197,200,80,142,179,67,58,145,188,147,125,15,13,173,125,4,61,29,132,110,62,137,197,135,162,174,32,151,149,65,18,42,63,62,104,200,189,40,38,199,1,12,8,2,195,30,7,72,130,144,2,34,200,143,43,196,22,115,171,54,143,59,14,52,109,115,187,185,26,19,178,18,120,169,45,52,130,69,168,178,96,22,78,152,39,51,118,130,60,156,108,69,103,158,165,142,86,91,117,77,57,169,86,188,97,111,22,83,81,177,163,35,12,164,21,181,171,138,22,107,58,51,38,128,19,193,157,13,104,89,13,10,26,190,179,101,7,159,100,49,120,109,56,199,51,108,47,171,69,162,74,119,148,88,32,159,65,146,140,171,88,18,59,13]\n})\ntraining_data.head(10)", "_____no_output_____" ], [ "# Collecting a summary of all numeric data", "_____no_output_____" ], [ "# Finding the names of the trainers", "_____no_output_____" ], [ "# Finding how many students each trainer has", "_____no_output_____" ], [ "# Finding the average weight of all students", "_____no_output_____" ], [ "# Finding the combined weight of all students", "_____no_output_____" ], [ "# Converting the membership days into weeks and then adding a column to the DataFrame", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d072252586c4d20f1cb3e9176e86c8111513b790
142,884
ipynb
Jupyter Notebook
P1.ipynb
Abhishek-Balaji/CarND-LaneLines-P1
fe32a42ede2397394172e8f0e7c69db958ad8764
[ "MIT" ]
null
null
null
P1.ipynb
Abhishek-Balaji/CarND-LaneLines-P1
fe32a42ede2397394172e8f0e7c69db958ad8764
[ "MIT" ]
null
null
null
P1.ipynb
Abhishek-Balaji/CarND-LaneLines-P1
fe32a42ede2397394172e8f0e7c69db958ad8764
[ "MIT" ]
null
null
null
200.679775
116,828
0.896909
[ [ [ "# Self-Driving Car Engineer Nanodegree\n\n\n## Project: **Finding Lane Lines on the Road** \n***\nIn this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n\nOnce you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n\nIn addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n\n---\nLet's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n\n**Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n\n---", "_____no_output_____" ], [ "**The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.**\n\n---\n\n<figure>\n <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n </figcaption>\n</figure>\n <p></p> \n<figure>\n <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n </figcaption>\n</figure>", "_____no_output_____" ], [ "**Run the cell below to import some packages. If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.** ", "_____no_output_____" ], [ "## Import Packages", "_____no_output_____" ] ], [ [ "#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Read in an Image", "_____no_output_____" ] ], [ [ "#reading in an image\nimage = mpimg.imread('test_images/solidWhiteRight.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(image), 'with dimensions:', image.shape)\nplt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')", "This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)\n" ] ], [ [ "## Ideas for Lane Detection Pipeline", "_____no_output_____" ], [ "**Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**\n\n`cv2.inRange()` for color selection \n`cv2.fillPoly()` for regions selection \n`cv2.line()` to draw lines on an image given endpoints \n`cv2.addWeighted()` to coadd / overlay two images \n`cv2.cvtColor()` to grayscale or change color \n`cv2.imwrite()` to output images to file \n`cv2.bitwise_and()` to apply a mask to an image\n\n**Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**", "_____no_output_____" ], [ "## Helper Functions", "_____no_output_____" ], [ "Below are some helper functions to help get you started. They should look familiar from the lesson!", "_____no_output_____" ] ], [ [ "import math\n\ndef grayscale(img):\n \"\"\"Applies the Grayscale transform\n This will return an image with only one color channel\n but NOTE: to see the returned image as grayscale\n (assuming your grayscaled image is called 'gray')\n you should call plt.imshow(gray, cmap='gray')\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Or use BGR2GRAY if you read an image with cv2.imread()\n # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \ndef canny(img, low_threshold, high_threshold):\n \"\"\"Applies the Canny transform\"\"\"\n return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=15):\n \"\"\"\n NOTE: this is the function you might want to use as a starting point once you want to \n average/extrapolate the line segments you detect to map out the full\n extent of the lane (going from the result shown in raw-lines-example.mp4\n to that shown in P1_example.mp4). \n \n Think about things like separating line segments by their \n slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n line vs. the right line. Then, you can average the position of each of \n the lines and extrapolate to the top and bottom of the lane.\n \n This function draws `lines` with `color` and `thickness`. \n Lines are drawn on the image inplace (mutates the image).\n If you want to make the lines semi-transparent, think about combining\n this function with the weighted_img() function below\n \"\"\"\n \n # initialize the accumulators\n imshape = img.shape\n left_slopes = []\n left_x = 0\n left_y = 0\n right_slopes = []\n right_x = 0\n right_y = 0\n \n # loop over the lines\n for line in lines:\n for x1,y1,x2,y2 in line:\n slope = (y2 - y1)/(x2 - x1)\n if slope < -.5 and slope > -1: #left\n left_slopes.append(slope)\n left_x += x1 + x2\n left_y += y1 + y2\n elif slope > .5 and slope < .8: #right\n right_slopes.append(slope)\n right_x += x1 + x2\n right_y += y1 + y2\n \n left_slope = sum(left_slopes) / len(left_slopes) \n avg_left_x = int(left_x / (2 * len(left_slopes)))\n avg_left_y = int(left_y / (2 * len(left_slopes)))\n y_left_1 = imshape[0]\n x_left_1 = int((y_left_1 - avg_left_y) / left_slope + avg_left_x) \n x_left_2 = int((y_left_2 - avg_left_y) / left_slope + avg_left_x)\n \n right_slope = sum(right_slopes) / len(right_slopes)\n avg_right_x = int(right_x / (2 * len(right_slopes)))\n avg_right_y = int(right_y / (2 * len(right_slopes)))\n y_right_1 = imshape[0]\n x_right_1 = int((y_right_1 - avg_right_y) / right_slope + avg_right_x)\n y_right_2 = int((34/54) * imshape[0])\n x_right_2 = int((y_right_2 - avg_right_y) / right_slope + avg_right_x)\n \n cv2.line(img, (x_left_1, y_left_1), (x_left_2, y_left_2), color, thickness)\n cv2.line(img, (x_right_1, y_right_1), (x_right_2, y_right_2), color, thickness)\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\"\n `img` should be the output of a Canny transform.\n \n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n draw_lines(line_img, lines)\n return line_img\n\n# Python 3 has support for cool math symbols.\n\ndef weighted_img(img, initial_img, α=0.8, β=1., γ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n \n `initial_img` should be the image before any processing.\n \n The result image is computed as follows:\n \n initial_img * α + img * β + γ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, γ)", "_____no_output_____" ] ], [ [ "## Test Images\n\nBuild your pipeline to work on the images in the directory \"test_images\" \n**You should make sure your pipeline works well on these images before you try the videos.**", "_____no_output_____" ] ], [ [ "import os\nos.listdir(\"test_images/\")", "_____no_output_____" ] ], [ [ "## Build a Lane Finding Pipeline\n\n", "_____no_output_____" ], [ "Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n\nTry tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.", "_____no_output_____" ] ], [ [ "def draw(image):\n gray=grayscale(image)\n blur=gaussian_blur(gray,5)\n edge=canny(blur,50,150)\n imshape=image.shape\n vertices = np.array([[(0, imshape[0]),((43/96) * imshape[1], (33/54) * imshape[0]), ((54/96) * imshape[1], (33/54) * imshape[0]), (imshape[1],imshape[0])]], dtype=np.int32)\n masked_edges = region_of_interest(edge, vertices)\n rho = 1\n theta = np.pi/180\n threshold = 5\n min_line_length = 3\n max_line_gap = 1\n lines = hough_lines(masked_edges, 1, math.pi/180, 5, 3, 1)\n lines_overlayed = weighted_img(lines, image)\n return lines_overlayed", "_____no_output_____" ], [ "for i in os.listdir(\"test_images/\"):\n image = mpimg.imread('test_images/'+i)\n out=draw(image)\n plt.imsave(i[:-4]+\"out.jpg\",out)", "_____no_output_____" ] ], [ [ "## Test on Videos\n\nYou know what's cooler than drawing lanes over images? Drawing lanes over video!\n\nWe can test our solution on two provided videos:\n\n`solidWhiteRight.mp4`\n\n`solidYellowLeft.mp4`\n\n**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n\n**If you get an error that looks like this:**\n```\nNeedDownloadError: Need ffmpeg exe. \nYou can download it by calling: \nimageio.plugins.ffmpeg.download()\n```\n**Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**", "_____no_output_____" ] ], [ [ "# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML", "_____no_output_____" ], [ "def process_image(image):\n # NOTE: The output you return should be a color image (3 channel) for processing video below\n # TODO: put your pipeline here,\n # you should return the final output (image where lines are drawn on lanes)\n result=draw(image)\n return result", "_____no_output_____" ] ], [ [ "Let's try the one with the solid white lane on the right first ...", "_____no_output_____" ] ], [ [ "white_output = 'test_videos_output/solidWhiteRight.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n%time white_clip.write_videofile(white_output, audio=False)", "t: 1%|▏ | 3/221 [00:00<00:09, 22.45it/s, now=None]" ] ], [ [ "Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.", "_____no_output_____" ] ], [ [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))", "_____no_output_____" ] ], [ [ "## Improve the draw_lines() function\n\n**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n\n**Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**", "_____no_output_____" ], [ "Now for the one with the solid yellow lane on the left. This one's more tricky!", "_____no_output_____" ] ], [ [ "yellow_output = 'test_videos_output/solidYellowLeft.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\nyellow_clip = clip2.fl_image(process_image)\n%time yellow_clip.write_videofile(yellow_output, audio=False)", "t: 1%| | 6/681 [00:00<00:12, 54.59it/s, now=None]" ], [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))", "_____no_output_____" ] ], [ [ "## Writeup and Submission\n\nIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.\n", "_____no_output_____" ], [ "## Optional Challenge\n\nTry your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!", "_____no_output_____" ] ], [ [ "challenge_output = 'test_videos_output/challenge.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)\nclip3 = VideoFileClip('test_videos/challenge.mp4')\nchallenge_clip = clip3.fl_image(process_image)\n%time challenge_clip.write_videofile(challenge_output, audio=False)", "_____no_output_____" ], [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(challenge_output))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
d0722e3a43cb19cdbcd4cbbcb8d1dea3ddea83e8
958,889
ipynb
Jupyter Notebook
examples/bias/Bias.ipynb
dabrze/similarity_forest
3d0f0f304b0106a6b2d86e6e84562ef2cb5ee81d
[ "BSD-3-Clause" ]
2
2020-01-24T12:37:14.000Z
2021-04-14T10:47:20.000Z
examples/bias/Bias.ipynb
dabrze/similarity_forest
3d0f0f304b0106a6b2d86e6e84562ef2cb5ee81d
[ "BSD-3-Clause" ]
null
null
null
examples/bias/Bias.ipynb
dabrze/similarity_forest
3d0f0f304b0106a6b2d86e6e84562ef2cb5ee81d
[ "BSD-3-Clause" ]
1
2022-03-03T09:38:28.000Z
2022-03-03T09:38:28.000Z
1,141.534524
177,096
0.951543
[ [ [ "from simforest import SimilarityForestClassifier, SimilarityForestRegressor\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.datasets import load_svmlight_file\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import f1_score\nfrom scipy.stats import pearsonr\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom bias import create_numerical_feature_classification, create_categorical_feature_classification\nfrom bias import create_numerical_feature_regression, create_categorical_feature_regression\nfrom bias import get_permutation_importances, bias_experiment, plot_bias\n\nsns.set_style('whitegrid')\n\nSEED = 42\n\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "# Read the data", "_____no_output_____" ] ], [ [ "X, y = load_svmlight_file('data/heart')\nX = X.toarray().astype(np.float32)\ny[y==-1] = 0\n\nfeatures = [f'f{i+1}' for i in range(X.shape[1])]\ndf = pd.DataFrame(X, columns=features)\ndf.head()", "_____no_output_____" ] ], [ [ "# Add new numerical feature\n\nCreate synthetic column, strongly correlated with target.\nEach value is calculated according to the formula:\n v = y * a + random(-b, b)\n So its scaled target value with some noise.\n\nThen a fraction of values is permuted, to reduce the correlation.\n\nIn this case, a=10, b=5, fraction=0.05", "_____no_output_____" ] ], [ [ "if 'new_feature' in df.columns:\n df.pop('new_feature')\n\nnew_feature, corr = create_numerical_feature_classification(y, fraction=0.05, seed=SEED, verbose=True)\ndf = pd.concat([pd.Series(new_feature, name='new_feature'), df], axis=1)\n\nplt.scatter(new_feature, y, alpha=0.3)\nplt.xlabel('Feature value')\nplt.ylabel('Target')\nplt.title('Synthetic numerical feature');", "Initial new feature - target point biserial correlation, without shuffling: 0.878, p: 0.0\nNew feature - target point biserial correlation, after shuffling: 0.849, p: 0.0\n" ] ], [ [ "# Random Forest feature importance\n\nRandom Forest offers a simple way to measure feature importance. A certain feature is considered to be important if it reduced node impurity often, during fitting the trees.\n\nWe can see that adding a feature strongly correlated with target improved the model's performance, compared to results we obtained without this feature. What is more, this new feature was really important for the predictions. The plot shows that it is far more important than the original features.", "_____no_output_____" ] ], [ [ "X_train, X_test, y_train, y_test = train_test_split(\n df, y, test_size=0.3, random_state=SEED)\n\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\nrf = RandomForestClassifier(random_state=SEED)\nrf.fit(X_train, y_train)\nrf_pred = rf.predict(X_test)\nprint(f'Random Forest f1 score: {round(f1_score(y_test, rf_pred), 3)}')\n\ndf_rf_importances = pd.DataFrame(rf.feature_importances_, index=df.columns.values, columns=['importance'])\ndf_rf_importances = df_rf_importances.sort_values(by='importance', ascending=False)\ndf_rf_importances.plot()\nplt.title('Biased Random Forest feature importance');", "Random Forest f1 score: 0.985\n" ] ], [ [ "# Permutation feature importance\n\nThe impurity-based feature importance of Random Forests suffers from being computed on statistics derived from the training dataset: the importances can be high even for features that are not predictive of the target variable, as long as the model has the capacity to use them to overfit.\n\nFuthermore, Random Forest feature importance is biased towards high-cardinality numerical feautures.\n\nIn this experiment, we will use permutation feature importance to asses how Random Forest and Similarity Forest\ndepend on syntetic feauture. This method is more reliable, and enables to measure feature importance for Similarity Forest, that doesn't enable us to measure impurity-based feature importance.\n\nSource: https://scikit-learn.org/stable/auto_examples/inspection/plot_permutation_importance.html", "_____no_output_____" ] ], [ [ "sf = SimilarityForestClassifier(n_estimators=100, random_state=SEED).fit(X_train, y_train)\n\nperm_importance_results = get_permutation_importances(rf, sf, \n X_train, y_train, X_test, y_test, \n corr, df.columns.values, plot=True)", "_____no_output_____" ], [ "fraction_range = [0.0, 0.02, 0.05, 0.08, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 1.0]\n\n\ncorrelations, rf_scores, sf_scores, permutation_importances = bias_experiment(df, y, \n 'classification', 'numerical', \n fraction_range, SEED)\nplot_bias(fraction_range, correlations, \n rf_scores, sf_scores, \n permutation_importances, 'heart')", "19it [31:09, 98.37s/it] \n" ] ], [ [ "# New categorical feature", "_____no_output_____" ] ], [ [ "if 'new_feature' in df.columns:\n df.pop('new_feature')\n\nnew_feature, corr = create_categorical_feature_classification(y, fraction=0.05, seed=SEED, verbose=True)\ndf = pd.concat([pd.Series(new_feature, name='new_feature'), df], axis=1)\n\ndf_category = pd.concat([pd.Series(new_feature, name='new_feature'), pd.Series(y, name='y')], axis=1)\nfig = plt.figure(figsize=(8, 6))\nsns.countplot(data=df_category, x='new_feature', hue='y')\nplt.xlabel('Feature value, grouped by class')\nplt.ylabel('Count')\nplt.title('Synthetic categorical feature', fontsize=16);", "Initial new feature - target point Phi coefficient, without shuffling: 1.0\nNew feature - target point Phi coefficient, after shuffling: 0.805\n" ], [ "X_train, X_test, y_train, y_test = train_test_split(\n df, y, test_size=0.3, random_state=SEED)\n\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\nrf = RandomForestClassifier(random_state=SEED).fit(X_train, y_train)\nsf = SimilarityForestClassifier(n_estimators=100, random_state=SEED).fit(X_train, y_train)\n\nperm_importance_results = get_permutation_importances(rf, sf, \n X_train, y_train, X_test, y_test, \n corr, df.columns.values, plot=True)", "_____no_output_____" ], [ "correlations, rf_scores, sf_scores, permutation_importances = bias_experiment(df, y, \n 'classification', 'categorical', \n fraction_range, SEED)\nplot_bias(fraction_range, correlations, \n rf_scores, sf_scores, \n permutation_importances, 'heart')", "19it [26:26, 83.49s/it]\n" ] ], [ [ "# Regression, numerical feature", "_____no_output_____" ] ], [ [ "X, y = load_svmlight_file('data/mpg')\nX = X.toarray().astype(np.float32)\n\nfeatures = [f'f{i+1}' for i in range(X.shape[1])]\ndf = pd.DataFrame(X, columns=features)\ndf.head()", "_____no_output_____" ], [ "if 'new_feature' in df.columns:\n df.pop('new_feature')\n\nnew_feature, corr = create_numerical_feature_regression(y, fraction=0.2, seed=SEED, verbose=True)\ndf = pd.concat([pd.Series(new_feature, name='new_feature'), df], axis=1)\n\nplt.scatter(new_feature, y, alpha=0.3)\nplt.xlabel('Feature value')\nplt.ylabel('Target')\nplt.title('Synthetic numerical feature');", "Initial new feature - target Spearman correlation, without shuffling: 0.998, p: 0.0\nNew feature - target Spearman correlation, after shuffling: 0.803, p: 0.0\n" ], [ "X_train, X_test, y_train, y_test = train_test_split(\n df, y, test_size=0.3, random_state=SEED)\n\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\nrf = RandomForestRegressor(random_state=SEED).fit(X_train, y_train)\nsf = SimilarityForestRegressor(n_estimators=100, random_state=SEED).fit(X_train, y_train)\n\nperm_importance_results = get_permutation_importances(rf, sf, \n X_train, y_train, X_test, y_test, \n corr, df.columns.values, plot=True)", "_____no_output_____" ], [ "correlations, rf_scores, sf_scores, permutation_importances = bias_experiment(df, y, \n 'regression', 'numerical', \n fraction_range, SEED)\nplot_bias(fraction_range, correlations, \n rf_scores, sf_scores, \n permutation_importances, 'mpg')", "19it [42:41, 134.82s/it]\n" ] ], [ [ "# Regression, categorical feature", "_____no_output_____" ] ], [ [ "if 'new_feature' in df.columns:\n df.pop('new_feature')\n\nnew_feature, corr = create_categorical_feature_regression(y, fraction=0.15, seed=SEED, verbose=True)\ndf = pd.concat([pd.Series(new_feature, name='new_feature'), df], axis=1)\n\nplt.scatter(new_feature, y, alpha=0.3)\nplt.xlabel('Feature value')\nplt.ylabel('Target')\nplt.title('Synthetic categorical feature');", "Initial new feature - target point biserial correlation, without shuffling: 0.965, p: 0.0\nNew feature - target point biserial correlation, after shuffling: 0.797, p: 0.0\n" ], [ "X_train, X_test, y_train, y_test = train_test_split(\n df, y, test_size=0.3, random_state=SEED)\n\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\nrf = RandomForestRegressor(random_state=SEED).fit(X_train, y_train)\nsf = SimilarityForestRegressor(n_estimators=100, random_state=SEED).fit(X_train, y_train)\n\nperm_importance_results = get_permutation_importances(rf, sf, \n X_train, y_train, X_test, y_test, \n corr, df.columns.values, plot=True)", "_____no_output_____" ], [ "correlations, rf_scores, sf_scores, permutation_importances = bias_experiment(df, y, \n 'regression', 'categorical', \n fraction_range, SEED)\nplot_bias(fraction_range, correlations, \n rf_scores, sf_scores, \n permutation_importances, 'mpg')", "19it [46:58, 148.33s/it]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d0723477326f1f72ab34c1d9cf9c64a15f176740
30,394
ipynb
Jupyter Notebook
doc/python/Heatmap.ipynb
ssadedin/beakerx
34479b07d2dfdf1404692692f483faf0251632c3
[ "Apache-2.0" ]
1,491
2017-03-30T03:05:05.000Z
2022-03-27T04:26:02.000Z
doc/python/Heatmap.ipynb
ssadedin/beakerx
34479b07d2dfdf1404692692f483faf0251632c3
[ "Apache-2.0" ]
3,268
2015-01-01T00:10:26.000Z
2017-05-05T18:59:41.000Z
doc/python/Heatmap.ipynb
ssadedin/beakerx
34479b07d2dfdf1404692692f483faf0251632c3
[ "Apache-2.0" ]
287
2017-04-03T01:30:06.000Z
2022-03-17T06:09:15.000Z
249.131148
21,070
0.725373
[ [ [ "# Heap Maps\n\nA heat map is a two-dimensional representation of data in which values are represented by colors. A simple heat map provides an immediate visual summary of information.", "_____no_output_____" ] ], [ [ "from beakerx import *\n\ndata = [[533.08714795974, 484.92105712087596, 451.63070008303896, 894.4451947886148, 335.44965728686225, 640.9424094527392, 776.2709495045433, 621.8819257981404, 793.2905673902735, 328.97078791524234, 139.26962328268513, 800.9314566259062, 629.0795214099808, 418.90954534196544, 513.8036215424278, 742.9834968485734, 542.9393528649774, 671.4256827205828, 507.1129322933082, 258.8238039352692, 581.0354187924672, 190.1830169180297, 480.461111816312, 621.621218137835, 650.6023460248642, 635.7577683708486, 605.5201537254429, 364.55368485516846, 554.807212844458, 526.1823154945637], [224.1432052432479, 343.26660237811336, 228.29828973027486, 550.3809606942758, 340.16890889700994, 214.05332637480836, 461.3159325548031, 471.2546571575069, 503.071081294441, 757.4281483575993, 493.82140462579406, 579.4302306011925, 459.76905409338497, 580.1282535427403, 378.8722877921564, 442.8806517248869, 573.9346962907078, 449.0587543606964, 383.50503527041144, 378.90761994599256, 755.1883447435789, 581.6815170672886, 426.56807864689773, 602.6727518023347, 555.6481983927658, 571.1201152862207, 372.24744704437876, 424.73180136220844, 739.9173564499195, 462.3257604373609], [561.8684320610753, 604.2859791599086, 518.3421287392559, 524.6887104615442, 364.41920277904774, 433.37737233751386, 565.0508404421712, 533.6030951907703, 306.68809206630397, 738.7229466356732, 766.9678519097575, 699.8457506281374, 437.0340850742263, 802.4400914789037, 417.38754410115075, 907.5825538527938, 521.4281410545287, 318.6109350534576, 435.8275858900637, 463.82924688853524, 533.4069709666686, 404.50516534982546, 332.6966202103611, 560.0346672408426, 436.9691072984075, 631.3453929454839, 585.1581992195356, 522.3209865675237, 497.57041075817443, 525.8867246757814], [363.4020792898871, 457.31257834906256, 333.21325206873564, 508.0466632081777, 457.1905718373847, 611.2168422907173, 515.2088862309242, 674.5569500790505, 748.0512665828364, 889.7281605626981, 363.6454276219251, 647.0396659692233, 574.150119779024, 721.1853645071792, 309.5388283799724, 450.51745569875845, 339.1271937333267, 630.6976744426033, 630.1571298446103, 615.0700456998867, 780.7843408745639, 205.13803869051543, 784.5916902014255, 498.10545868387925, 553.936345186856, 207.59216580556847, 488.12270849418735, 422.6667046886397, 292.1061953879919, 565.1595338825396], [528.5186504364794, 642.5542319036714, 563.8776991112292, 537.0271437681837, 430.4056097950834, 384.50193545472877, 693.3404035076994, 573.0278734604005, 261.2443087970927, 563.412635691231, 258.13860041989085, 550.150017102056, 477.70582135030617, 509.4311099345934, 661.3308013433317, 523.1175760654914, 370.29659041946326, 557.8704186019502, 353.66591951113645, 510.5389425077261, 469.11212447314324, 626.2863927887214, 318.5642686423241, 141.13900677851177, 486.00711121264453, 542.0075639686526, 448.7161764573215, 376.65492084577164, 166.56246586635706, 718.6147921685923], [435.403218786657, 470.74259129379413, 615.3542648093958, 483.61792559031693, 607.9455289424717, 454.9949861614464, 869.45041758392, 750.3595195751914, 754.7958625343501, 508.38715645396553, 368.2779213892305, 662.23752125613, 350.46366230046397, 619.8010888063362, 497.9560438683688, 420.64163974607766, 487.16698403905633, 273.3352931767504, 354.02637708217384, 457.9408818614016, 496.2986534025747, 364.84710143814976, 458.29907844925157, 634.073520178434, 558.7161089429649, 603.6634230782621, 514.1019407724017, 539.6741842214251, 585.0639516732675, 488.3003071211236], [334.0264519516021, 459.5702037859653, 543.8547654459309, 471.6623772418301, 500.98627686914386, 740.3857774449933, 487.4853744264201, 664.5373560191691, 573.764159193263, 471.32565842016527, 448.8845519093864, 729.3173859836543, 453.34766656988694, 428.4975196541853, 575.1404740691066, 190.18782164376034, 243.90403003048107, 430.03959300145215, 429.08666492876233, 508.89662188951297, 669.6400651031191, 516.2894766192492, 441.39320293407405, 653.1948574772491, 529.6831617222962, 176.0833629734244, 568.7136007686755, 461.66494617366294, 443.39303344518356, 840.642834252332], [347.676690455591, 475.0701395711058, 383.94468812449156, 456.7512619303556, 547.1719187673109, 224.69458657065758, 458.98685335259506, 599.8561007491281, 231.02565460233575, 610.5318803183029, 763.3423474509603, 548.8104762105211, 445.95788564834953, 844.6566709331175, 591.2236009653337, 586.0438760821825, 399.6820689195621, 395.17360423878256, 535.9853351258233, 332.27242110850426, 801.7584039310705, 190.6337233666032, 805.700536966829, 799.6824375238089, 346.29917202656327, 611.7423892505719, 705.8824305058062, 535.9691379719488, 488.1708623023391, 604.3772264289142], [687.7108994865216, 483.44749361779685, 661.8182197739575, 591.5452701990528, 151.60961549943875, 524.1475889465452, 745.1142999852398, 665.6103992924466, 701.3015233859578, 648.9854638583182, 403.08097902196505, 384.97216329583586, 442.52161997463816, 590.5026536093199, 219.04366558018955, 899.2103705796073, 562.4908789323547, 666.088957218587, 496.97593850278065, 777.9572405840922, 531.7316118485633, 500.7782009017233, 646.4095967934252, 633.5713368259554, 608.1857007168994, 585.4020395597571, 490.06193749044934, 463.884131549627, 632.7981360348942, 634.8055942938928], [482.5550451528366, 691.7011356960619, 496.2851035642388, 529.4040886765091, 444.3593296445004, 198.06208336708823, 365.6472909266031, 391.3885069938369, 859.494451604626, 275.19483951927816, 568.4478784631463, 203.74971298680123, 676.2053582803082, 527.9859302404323, 714.4565600799949, 288.9012675397431, 629.6056652113498, 326.2525932990075, 519.5740740263301, 696.8119752318905, 347.1796230415255, 388.6576994098651, 357.54758351840974, 873.5528483422207, 507.0189947052724, 508.1981784529926, 536.9527958233257, 871.2838601964829, 361.93416709279154, 496.5981745168124]]\ndata2 = [[103,104,104,105,105,106,106,106,107,107,106,106,105,105,104,104,104,104,105,107,107,106,105,105,107,108,109,110,110,110,110,110,110,109,109,109,109,109,109,108,107,107,107,107,106,106,105,104,104,104,104,104,104,104,103,103,103,103,102,102,101,101,100,100,100,100,100,99,98,97,97,96,96,96,96,96,96,96,95,95,95,94,94,94,94,94,94], [104,104,105,105,106,106,107,107,107,107,107,107,107,106,106,106,106,106,106,108,108,108,106,106,108,109,110,110,112,112,113,112,111,110,110,110,110,109,109,109,108,107,107,107,107,106,106,105,104,104,104,104,104,104,104,103,103,103,103,102,102,101,101,100,100,100,100,99,99,98,97,97,96,96,96,96,96,96,96,95,95,95,94,94,94,94,94], [104,105,105,106,106,107,107,108,108,108,108,108,108,108,108,108,108,108,108,108,110,110,110,110,110,110,110,111,113,115,116,115,113,112,110,110,110,110,110,110,109,108,108,108,108,107,106,105,105,105,105,105,105,104,104,104,104,103,103,103,102,102,102,101,100,100,100,99,99,98,97,97,96,96,96,96,96,96,96,96,95,95,94,94,94,94,94], [105,105,106,106,107,107,108,108,109,109,109,109,109,110,110,110,110,110,110,110,111,112,115,115,115,115,115,116,116,117,119,118,117,116,114,113,112,110,110,110,110,110,110,109,109,108,107,106,106,106,106,106,105,105,105,104,104,104,103,103,103,102,102,102,101,100,100,99,99,98,97,97,96,96,96,96,96,96,96,96,95,95,94,94,94,94,94], [105,106,106,107,107,108,108,109,109,110,110,110,110,111,110,110,110,110,111,114,115,116,121,121,121,121,121,122,123,124,124,123,121,119,118,117,115,114,112,111,110,110,110,110,110,110,109,109,108,109,107,107,106,106,105,105,104,104,104,104,103,103,102,102,102,101,100,100,99,99,98,97,96,96,96,96,96,96,96,96,95,95,94,94,94,94,94], [106,106,107,107,107,108,109,109,110,110,111,111,112,113,112,111,111,112,115,118,118,119,126,128,128,127,128,128,129,130,129,128,127,125,122,120,118,117,115,114,112,110,110,110,110,110,111,110,110,110,109,109,108,107,106,105,105,105,104,104,104,103,103,102,102,102,101,100,99,99,98,97,96,96,96,96,96,96,96,96,95,95,94,94,94,94,94], [106,107,107,108,108,108,109,110,110,111,112,113,114,115,114,115,116,116,119,123,125,130,133,134,134,134,134,135,135,136,135,134,132,130,128,124,121,119,118,116,114,112,111,111,111,112,112,111,110,110,110,109,108,108,107,108,107,106,105,104,104,104,103,103,103,102,101,100,99,99,98,97,96,96,96,96,96,96,96,96,95,95,95,94,94,94,94], [107,107,108,108,109,109,110,110,112,113,114,115,116,117,117,120,120,121,123,129,134,136,138,139,139,139,140,142,142,141,141,140,137,134,131,127,124,122,120,118,117,115,113,114,113,114,114,113,112,111,110,110,109,108,107,106,105,105,105,104,104,104,103,103,103,101,100,100,99,99,98,97,96,96,96,96,96,96,96,96,96,95,95,94,94,94,94], [107,108,108,109,109,110,111,112,114,115,116,117,118,119,121,125,125,127,131,136,140,141,142,144,144,145,148,149,148,147,146,144,140,138,136,130,127,125,123,121,119,118,117,117,116,116,116,115,114,113,113,111,110,109,108,107,106,105,105,103,103,102,102,102,103,101,100,100,100,99,98,98,97,96,96,96,96,96,96,96,96,95,95,95,94,94,94], [107,108,109,109,110,110,110,113,115,117,118,119,120,123,126,129,131,134,139,142,144,145,147,148,150,152,154,154,153,154,151,149,146,143,140,136,130,128,126,124,122,121,120,119,118,117,117,117,116,116,115,113,112,110,109,108,107,106,106,105,104,103,102,101,101,100,100,100,100,99,99,98,97,96,96,96,96,96,96,96,96,95,95,95,94,94,94], [107,108,109,109,110,110,110,112,115,117,119,122,125,127,130,133,137,141,143,145,148,149,152,155,157,159,160,160,161,162,159,156,153,149,146,142,139,134,130,128,126,125,122,120,120,120,119,119,119,118,117,115,113,111,110,110,109,108,107,106,106,105,104,104,103,102,100,100,100,99,99,98,97,96,96,96,96,96,96,96,96,95,95,95,95,94,94], [108,108,109,109,110,110,110,112,115,118,121,125,128,131,134,138,141,145,147,149,152,157,160,161,163,166,169,170,170,171,168,162,158,155,152,148,144,140,136,132,129,127,124,122,121,120,120,120,120,120,119,117,115,113,110,110,110,110,109,108,108,107,107,106,105,104,102,100,100,100,99,98,97,96,96,96,96,96,96,96,96,96,95,95,95,94,94], [108,109,109,110,110,111,112,114,117,120,124,128,131,135,138,142,145,149,152,155,158,163,166,167,170,173,175,175,175,173,171,169,164,160,156,153,149,144,140,136,131,129,126,124,123,123,122,121,120,120,120,119,117,115,111,110,110,110,110,110,109,109,110,109,108,106,103,101,100,100,100,98,97,96,96,96,96,96,96,96,96,96,95,95,95,95,94], [108,109,110,110,110,113,114,116,119,122,126,131,134,138,141,145,149,152,156,160,164,169,171,174,177,175,178,179,177,175,174,172,168,163,160,157,151,147,143,138,133,130,128,125,125,124,123,122,121,121,120,120,118,116,115,111,110,110,110,110,113,114,113,112,110,107,105,102,100,100,100,98,97,96,96,96,96,96,96,96,96,96,96,95,95,95,94], [108,109,110,110,112,115,116,118,122,125,129,133,137,140,144,149,152,157,161,165,169,173,176,179,179,180,180,180,178,178,176,175,171,165,163,160,153,148,143,139,135,132,129,128,127,125,124,124,123,123,122,122,120,118,117,118,115,117,118,118,119,117,116,115,112,109,107,105,100,100,100,100,97,96,96,96,96,96,96,96,96,96,96,95,95,95,95], [108,109,110,111,114,116,118,122,127,130,133,136,140,144,148,153,157,161,165,169,173,177,180,180,180,180,181,180,180,180,179,178,173,168,165,161,156,149,143,139,136,133,130,129,128,126,126,125,125,125,125,124,122,121,120,120,120,120,121,122,123,122,120,117,114,111,108,106,105,100,100,100,100,96,96,96,96,96,96,96,96,96,96,96,95,95,95], [107,108,110,113,115,118,121,126,131,134,137,140,143,148,152,157,162,165,169,173,177,181,181,181,180,181,181,181,180,180,180,178,176,170,167,163,158,152,145,140,137,134,132,130,129,127,127,126,127,128,128,126,125,125,125,123,126,128,129,130,130,125,124,119,116,114,112,110,107,106,105,100,100,100,96,96,96,96,96,96,96,96,96,96,96,95,95], [107,109,111,116,119,122,125,130,135,137,140,144,148,152,156,161,165,168,172,177,181,184,181,181,181,180,180,180,180,180,180,178,178,173,168,163,158,152,146,141,138,136,134,132,130,129,128,128,130,130,130,129,128,129,129,130,132,133,133,134,134,132,128,122,119,116,114,112,108,106,105,105,100,100,100,97,97,97,97,97,97,97,96,96,96,96,95], [108,110,112,117,122,126,129,135,139,141,144,149,153,156,160,165,168,171,177,181,184,185,182,180,180,179,178,178,180,179,179,178,176,173,168,163,157,152,148,143,139,137,135,133,131,130,130,131,132,132,132,131,132,132,133,134,136,137,137,137,136,134,131,124,121,118,116,114,111,109,107,106,105,100,100,100,97,97,97,97,97,97,97,96,96,96,96], [108,110,114,120,126,129,134,139,142,144,146,152,158,161,164,168,171,175,181,184,186,186,183,179,178,178,177,175,178,177,177,176,175,173,168,162,156,153,149,145,142,140,138,136,133,132,132,132,134,134,134,134,135,136,137,138,140,140,140,140,139,137,133,127,123,120,118,115,112,108,108,106,106,105,100,100,100,98,98,98,98,98,98,97,96,96,96], [108,110,116,122,128,133,137,141,143,146,149,154,161,165,168,172,175,180,184,188,189,187,182,178,176,176,175,173,174,173,175,174,173,171,168,161,157,154,150,148,145,143,141,138,135,135,134,135,135,136,136,137,138,139,140,140,140,140,140,140,140,139,135,130,126,123,120,117,114,111,109,108,107,106,105,100,100,100,99,99,98,98,98,98,97,97,96], [110,112,118,124,130,135,139,142,145,148,151,157,163,169,172,176,179,183,187,190,190,186,180,177,175,173,170,169,169,170,171,172,170,170,167,163,160,157,154,152,149,147,144,140,137,137,136,137,138,138,139,140,141,140,140,140,140,140,140,140,140,138,134,131,128,124,121,118,115,112,110,109,108,107,106,105,100,100,100,99,99,99,98,98,98,97,97], [110,114,120,126,131,136,140,143,146,149,154,159,166,171,177,180,182,186,190,190,190,185,179,174,171,168,166,163,164,163,166,169,170,170,168,164,162,161,158,155,153,150,147,143,139,139,139,139,140,141,141,142,142,141,140,140,140,140,140,140,140,137,134,131,128,125,122,119,116,114,112,110,109,109,108,107,105,100,100,100,99,99,99,98,98,97,97], [110,115,121,127,132,136,140,144,148,151,157,162,169,174,178,181,186,188,190,191,190,184,177,172,168,165,162,159,158,158,159,161,166,167,169,166,164,163,161,159,156,153,149,146,142,142,141,142,143,143,143,143,144,142,141,140,140,140,140,140,140,138,134,131,128,125,123,120,117,116,114,112,110,109,108,107,106,105,102,101,100,99,99,99,98,98,97], [110,116,121,127,132,136,140,144,148,154,160,166,171,176,180,184,189,190,191,191,191,183,176,170,166,163,159,156,154,155,155,158,161,165,170,167,166,165,163,161,158,155,152,150,146,145,145,145,146,146,144,145,145,144,142,141,140,140,140,140,138,136,134,131,128,125,123,121,119,117,115,113,112,111,111,110,108,106,105,102,100,100,99,99,99,98,98], [110,114,119,126,131,135,140,144,149,158,164,168,172,176,183,184,189,190,191,191,190,183,174,169,165,161,158,154,150,151,152,155,159,164,168,168,168,167,165,163,160,158,155,153,150,148,148,148,148,148,147,146,146,145,143,142,141,140,139,138,136,134,132,131,128,126,124,122,120,118,116,114,113,113,112,111,108,107,106,105,104,102,100,99,99,99,99], [110,113,119,125,131,136,141,145,150,158,164,168,172,177,183,187,189,191,192,191,190,183,174,168,164,160,157,153,150,149,150,154,158,162,166,170,170,168,166,164,162,160,158,155,152,151,151,151,151,151,149,148,147,146,145,143,142,140,139,137,135,134,132,131,129,127,125,123,121,119,117,116,114,114,113,112,110,108,107,105,103,100,100,100,100,99,99], [110,112,118,124,130,136,142,146,151,157,163,168,174,178,183,187,189,190,191,192,189,182,174,168,164,160,157,153,149,148,149,153,157,161,167,170,170,170,168,166,165,163,159,156,154,153,155,155,155,155,152,150,149,147,145,143,141,140,139,138,136,134,133,131,130,128,126,124,122,120,119,117,116,115,114,113,111,110,107,106,105,105,102,101,100,100,100], [110,111,116,122,129,137,142,146,151,158,164,168,172,179,183,186,189,190,192,193,188,182,174,168,164,161,157,154,151,149,151,154,158,161,167,170,170,170,170,169,168,166,160,157,156,156,157,158,159,159,156,153,150,148,146,144,141,140,140,138,136,135,134,133,131,129,127,125,123,122,120,118,117,116,115,114,112,111,110,108,107,106,105,104,102,100,100], [108,110,115,121,131,137,142,147,152,159,163,167,170,177,182,184,187,189,192,194,189,183,174,169,165,161,158,156,154,153,154,157,160,164,167,171,172,174,174,173,171,168,161,159,158,158,159,161,161,160,158,155,151,149,147,144,142,141,140,138,137,136,135,134,132,130,128,126,125,123,121,119,118,117,116,115,113,112,112,111,110,109,108,107,105,101,100], [108,110,114,120,128,134,140,146,152,158,162,166,169,175,180,183,186,189,193,195,190,184,176,171,167,163,160,158,157,156,157,159,163,166,170,174,176,178,178,176,172,167,164,161,161,160,161,163,163,163,160,157,153,150,148,146,144,142,141,140,139,138,136,135,134,133,129,127,126,124,122,121,119,118,117,116,114,113,112,111,110,110,109,109,107,104,100], [107,110,115,119,123,129,135,141,146,156,161,165,168,173,179,182,186,189,193,194,191,184,179,175,170,166,162,161,160,160,161,162,165,169,172,176,178,179,179,176,172,168,165,163,163,163,163,165,166,164,161,158,155,152,150,147,146,144,143,142,141,139,139,138,137,135,131,128,127,125,124,122,121,119,118,116,115,113,112,111,111,110,110,109,109,105,100], [107,110,114,117,121,126,130,135,142,151,159,163,167,171,177,182,185,189,192,193,191,187,183,179,174,169,167,166,164,164,165,166,169,171,174,178,179,180,180,178,173,169,166,165,165,166,165,168,169,166,163,159,157,154,152,149,148,147,146,145,143,142,141,140,139,138,133,130,128,127,125,124,122,120,118,117,115,112,111,111,111,111,110,109,108,106,100], [107,109,113,118,122,126,129,134,139,150,156,160,165,170,175,181,184,188,191,192,192,189,185,181,177,173,171,169,168,167,169,170,172,174,176,178,179,180,180,179,175,170,168,166,166,168,168,170,170,168,164,160,158,155,152,151,150,149,149,148,147,145,144,143,142,141,136,133,130,129,127,125,123,120,119,118,115,112,111,111,111,110,109,109,109,105,100], [105,107,111,117,121,124,127,131,137,148,154,159,164,168,174,181,184,187,190,191,191,190,187,184,180,178,175,174,172,171,173,173,173,176,178,179,180,180,180,179,175,170,168,166,168,169,170,170,170,170,166,161,158,156,154,153,151,150,150,150,150,148,147,146,145,143,139,135,133,131,129,126,124,121,120,118,114,111,111,111,110,110,109,107,106,104,100], [104,106,110,114,118,121,125,129,135,142,150,157,162,167,173,180,183,186,188,190,190,190,189,184,183,181,180,179,179,176,177,176,176,177,178,179,180,180,179,177,173,169,167,166,167,169,170,170,170,170,167,161,159,157,155,153,151,150,150,150,150,150,150,149,147,145,141,138,135,133,130,127,125,123,121,118,113,111,110,110,109,109,107,106,105,103,100], [104,106,108,111,115,119,123,128,134,141,148,154,161,166,172,179,182,184,186,189,190,190,190,187,185,183,180,180,180,179,179,177,176,177,178,178,178,177,176,174,171,168,166,164,166,168,170,170,170,170,168,162,159,157,155,153,151,150,150,150,150,150,150,150,150,148,144,140,137,134,132,129,127,125,122,117,111,110,107,107,106,105,104,103,102,101,100], [103,105,107,110,114,118,122,127,132,140,146,153,159,165,171,176,180,183,185,186,189,190,188,187,184,182,180,180,180,179,178,176,176,176,176,174,174,173,172,170,168,167,165,163,164,165,169,170,170,170,166,162,159,157,155,153,151,150,150,150,150,150,150,150,150,150,146,142,139,136,133,131,128,125,122,117,110,108,106,105,104,103,103,101,101,101,101], [102,103,106,108,112,116,121,125,130,138,145,151,157,163,170,174,178,181,181,184,186,186,187,186,184,181,180,180,180,179,178,174,173,173,171,170,170,169,168,167,166,164,163,162,161,164,167,169,170,168,164,160,158,157,155,153,151,150,150,150,150,150,150,150,150,150,147,144,141,138,135,133,128,125,122,116,109,107,104,104,103,102,101,101,101,101,101], [101,102,105,107,110,115,120,124,129,136,143,149,155,162,168,170,174,176,178,179,181,182,184,184,183,181,180,180,179,177,174,172,170,168,166,165,164,164,164,164,162,160,159,159,158,160,162,164,166,166,163,159,157,156,155,153,151,150,150,150,150,150,150,150,150,150,149,146,143,140,137,133,129,124,119,112,108,105,103,103,102,101,101,101,101,100,100], [101,102,104,106,109,113,118,122,127,133,141,149,155,161,165,168,170,172,175,176,177,179,181,181,181,180,180,179,177,174,171,167,165,163,161,160,160,160,160,160,157,155,155,154,154,155,157,159,161,161,161,159,156,154,154,153,151,150,150,150,150,150,150,150,150,150,149,147,144,141,137,133,129,123,116,110,107,104,102,102,101,101,101,100,100,100,100], [102,103,104,106,108,112,116,120,125,129,137,146,154,161,163,165,166,169,172,173,174,175,177,178,178,178,178,177,174,171,168,164,160,158,157,157,156,156,156,155,152,151,150,150,151,151,152,154,156,157,157,156,155,153,152,152,151,150,150,150,150,150,150,150,150,150,150,147,144,141,138,133,127,120,113,109,106,103,101,101,101,100,100,100,100,100,100], [103,104,105,106,108,110,114,118,123,127,133,143,150,156,160,160,161,162,167,170,171,172,173,175,175,174,174,173,171,168,164,160,156,155,154,153,153,152,152,150,149,148,148,148,148,148,149,149,150,152,152,152,152,151,150,150,150,150,150,150,150,150,150,150,150,150,149,147,144,141,138,132,125,118,111,108,105,103,102,101,101,101,100,100,100,100,100], [104,105,106,107,108,110,113,117,120,125,129,138,145,151,156,156,157,158,160,164,166,168,170,171,172,171,171,169,166,163,160,156,153,151,150,150,149,149,149,148,146,146,146,146,146,146,146,147,148,148,149,149,149,148,148,148,148,149,149,150,150,150,150,150,150,150,148,146,143,141,136,129,123,117,110,108,105,104,103,102,102,101,101,100,100,100,100], [103,104,105,106,107,109,111,115,118,122,127,133,140,143,150,152,153,155,157,159,162,164,167,168,168,168,167,166,163,160,157,153,150,148,148,147,147,147,145,145,144,143,143,143,144,144,144,144,145,145,145,145,146,146,146,146,146,147,147,148,149,150,150,150,150,149,147,145,143,141,134,127,123,117,111,108,105,105,104,104,103,103,102,101,100,100,100], [102,103,104,105,106,107,109,113,116,120,125,129,133,137,143,147,149,151,152,154,158,161,164,165,164,164,163,163,160,157,154,151,149,147,145,145,144,143,141,140,141,141,141,141,141,142,142,142,142,142,142,142,143,143,143,144,144,145,146,146,146,147,148,148,148,148,145,143,142,140,134,128,123,117,112,108,106,105,105,104,104,103,102,101,100,100,99], [102,103,104,105,105,106,108,110,113,118,123,127,129,132,137,141,142,142,145,150,154,157,161,161,160,160,160,159,157,154,151,148,146,145,143,142,142,139,137,136,137,137,138,138,139,139,139,139,139,139,139,139,140,140,141,142,142,143,144,144,144,145,145,145,145,145,144,142,140,139,136,129,124,119,113,109,106,106,105,104,103,102,101,101,100,99,99], [102,103,104,104,105,106,107,108,111,116,121,124,126,128,131,134,135,137,139,143,147,152,156,157,157,157,156,155,153,151,148,146,143,142,141,140,138,135,133,132,132,133,133,133,134,135,135,135,135,136,136,137,137,138,138,139,140,141,141,142,142,143,142,142,141,141,140,139,137,134,133,129,125,121,114,110,107,106,106,104,103,102,101,100,99,99,99], [102,103,104,104,105,105,106,108,110,113,118,121,124,126,128,130,132,134,136,139,143,147,150,154,154,154,153,151,149,148,146,143,141,139,137,136,132,130,128,128,128,129,129,130,130,131,132,132,132,133,134,134,135,135,136,137,138,139,139,140,140,140,139,139,138,137,137,135,132,130,129,127,124,120,116,112,109,106,105,103,102,101,101,100,99,99,99], [101,102,103,104,104,105,106,107,108,110,114,119,121,124,126,128,129,132,134,137,140,143,147,149,151,151,151,149,147,145,143,141,138,136,134,131,128,126,124,125,125,126,126,127,128,128,129,129,130,130,131,131,132,132,133,134,135,135,136,136,137,137,136,136,135,134,133,131,129,128,127,126,123,119,115,111,109,107,105,104,103,102,101,100,100,100,99], [101,102,103,103,104,104,105,106,108,110,112,116,119,121,124,125,127,130,132,135,137,140,143,147,149,149,149,147,145,143,141,139,136,133,131,128,125,122,121,122,122,122,123,125,125,126,127,127,127,128,128,128,129,129,130,131,131,132,132,133,133,133,132,132,131,131,130,129,128,126,125,124,121,117,111,109,108,106,105,104,103,102,101,101,100,100,100], [100,101,102,103,103,104,105,106,107,108,110,114,117,119,121,123,126,128,130,133,136,139,141,144,146,147,146,145,143,141,138,136,133,130,127,124,121,120,120,120,120,120,121,122,123,124,124,125,125,126,126,125,126,126,126,125,126,127,128,128,129,129,128,128,128,128,128,128,126,125,123,122,119,114,109,108,107,106,105,104,103,103,102,102,101,100,100], [100,101,102,103,104,105,106,107,108,109,110,112,115,117,120,122,125,127,130,132,135,137,139,142,144,144,144,142,140,138,136,132,129,126,123,120,120,119,119,118,119,119,120,120,120,121,122,122,123,123,123,123,122,123,122,122,121,122,122,122,123,123,123,124,125,125,126,126,125,124,122,120,116,113,109,107,106,105,104,104,103,102,102,101,101,100,100], [100,101,102,103,104,105,106,107,108,109,110,112,114,117,119,122,124,127,129,131,134,136,138,140,142,142,142,140,138,136,133,129,125,122,120,119,118,118,117,116,117,117,118,119,119,120,120,120,121,121,121,122,121,120,120,120,119,119,120,120,120,120,120,120,123,123,124,124,124,123,121,119,114,112,108,106,106,104,104,103,102,102,101,101,100,100,99], [101,102,103,104,105,106,107,108,109,110,111,113,114,116,119,121,124,126,128,130,133,135,137,138,140,140,139,137,135,133,131,127,122,120,118,118,117,117,116,115,116,116,117,118,118,118,119,119,120,120,121,121,120,119,119,118,117,117,118,119,118,118,118,119,120,122,123,123,123,122,120,117,113,110,108,106,105,104,103,103,102,101,101,100,100,99,99], [101,102,103,104,105,106,107,108,109,110,111,111,113,115,118,121,123,125,127,129,131,133,135,137,138,138,137,134,132,130,127,122,120,118,116,116,116,116,115,113,114,115,116,117,117,118,118,119,119,119,120,120,119,118,117,117,116,116,117,117,117,118,119,119,119,120,121,121,121,121,119,116,113,110,107,105,105,103,103,103,102,101,100,100,99,99,99], [101,102,103,104,105,106,107,108,109,110,111,112,114,116,117,120,122,124,126,129,130,132,133,135,136,136,134,132,129,126,122,120,118,116,114,114,114,114,114,113,113,114,115,116,116,117,117,117,118,118,119,119,118,117,116,116,115,115,116,116,116,117,117,118,118,119,120,120,120,120,119,116,113,109,106,104,104,103,102,102,101,101,100,99,99,99,98], [101,102,103,104,105,106,107,108,109,110,111,113,115,117,117,118,121,123,126,128,130,130,131,132,133,134,131,129,125,122,120,118,116,114,113,112,112,113,112,112,111,112,113,113,114,115,116,116,117,117,118,118,116,116,115,115,115,114,114,115,116,116,117,117,118,118,119,119,120,120,117,115,112,108,106,104,103,102,102,102,101,100,99,99,99,98,98], [101,102,103,104,105,105,106,107,108,109,110,111,113,115,117,118,120,122,125,126,127,128,129,130,131,131,128,125,121,120,118,116,114,113,113,111,111,111,111,110,109,110,111,112,113,113,114,115,115,116,117,117,116,115,114,114,113,113,114,114,115,115,116,116,117,118,118,119,119,118,116,114,112,108,105,103,103,102,101,101,100,100,99,99,98,98,97], [100,101,102,103,104,105,106,107,108,109,110,110,111,113,115,118,120,121,122,124,125,125,126,127,128,127,124,121,120,118,116,114,113,112,112,110,109,109,108,108,108,109,110,111,112,112,113,114,114,115,116,116,115,114,113,112,112,113,113,114,114,115,115,116,116,117,117,118,118,117,115,113,111,107,105,103,102,101,101,100,100,100,99,99,98,98,97], [100,101,102,103,104,105,105,106,107,108,109,110,110,111,114,116,118,120,120,121,122,122,123,124,123,123,120,118,117,115,114,115,113,111,110,109,108,108,107,107,107,108,109,110,111,111,112,113,113,114,115,115,114,113,112,111,111,112,112,112,113,114,114,115,115,116,116,117,117,116,114,112,109,106,104,102,101,100,100,99,99,99,99,98,98,97,97]]\ndata3 = [[16,29, 12, 14, 16, 5, 9, 43, 25, 49, 57, 61, 37, 66, 79, 55, 51, 55, 17, 29, 9, 4, 9, 12, 9], [22,6, 2, 12, 23, 9, 2, 4, 11, 28, 49, 51, 47, 38, 65, 69, 59, 65, 59, 22, 11, 12, 9, 9, 13], [2, 5, 8, 44, 9, 22, 2, 5, 12, 34, 43, 54, 44, 49, 48, 54, 59, 69, 51, 21, 16, 9, 5, 4, 7], [3, 9, 9, 34, 9, 9, 2, 4, 13, 26, 58, 61, 59, 53, 54, 64, 55, 52, 53, 18, 3, 9, 12, 2, 8], [4, 2, 9, 8, 2, 23, 2, 4, 14, 31, 48, 46, 59, 66, 54, 56, 67, 54, 23, 14, 6, 8, 7, 9, 8], [5, 2, 23, 2, 9, 9, 9, 4, 8, 8, 6, 14, 12, 9, 14, 9, 21, 22, 34, 12, 9, 23, 9, 11, 13], [6, 7, 23, 23, 9, 4, 7, 4, 23, 11, 32, 2, 2, 5, 34, 9, 4, 12, 15, 19, 45, 9, 19, 9, 4]]\n", "_____no_output_____" ], [ "HeatMap(data = data)\n", "_____no_output_____" ], [ "HeatMap(title= \"Heatmap Second Example\",\n xLabel= \"X Label\",\n yLabel= \"Y Label\",\n data = data,\n legendPosition = LegendPosition.TOP)", "_____no_output_____" ], [ "HeatMap(title = \"Green Yellow White\",\n data = data2,\n showLegend = False,\n color = GradientColor.GREEN_YELLOW_WHITE)\n", "_____no_output_____" ], [ "colors = [Color.black, Color.yellow, Color.red]\nHeatMap(title= \"Custom Gradient Example\",\n data= data3,\n color= GradientColor(colors))", "_____no_output_____" ], [ "HeatMap(initWidth= 900,\n initHeight= 300,\n title= \"Custom size, no tooltips\",\n data= data3,\n useToolTip= False,\n showLegend= False,\n color= GradientColor.WHITE_BLUE)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d0723912e5fb3fd6e97e1ef18b7445df77ddff01
10,216
ipynb
Jupyter Notebook
Course2Part4Lesson4.ipynb
MBadriNarayanan/TensorFlow
8bfa86f4b1167b8f44cbd1080edf392445303a7e
[ "MIT" ]
null
null
null
Course2Part4Lesson4.ipynb
MBadriNarayanan/TensorFlow
8bfa86f4b1167b8f44cbd1080edf392445303a7e
[ "MIT" ]
null
null
null
Course2Part4Lesson4.ipynb
MBadriNarayanan/TensorFlow
8bfa86f4b1167b8f44cbd1080edf392445303a7e
[ "MIT" ]
1
2021-06-15T06:45:53.000Z
2021-06-15T06:45:53.000Z
35.349481
376
0.523297
[ [ [ "##### Copyright 2019 The TensorFlow Authors.", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ], [ "!wget --no-check-certificate \\\n https://storage.googleapis.com/laurencemoroney-blog.appspot.com/horse-or-human.zip \\\n -O /tmp/horse-or-human.zip\n\n!wget --no-check-certificate \\\n https://storage.googleapis.com/laurencemoroney-blog.appspot.com/validation-horse-or-human.zip \\\n -O /tmp/validation-horse-or-human.zip\n \nimport os\nimport zipfile\n\nlocal_zip = '/tmp/horse-or-human.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp/horse-or-human')\nlocal_zip = '/tmp/validation-horse-or-human.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp/validation-horse-or-human')\nzip_ref.close()\n# Directory with our training horse pictures\ntrain_horse_dir = os.path.join('/tmp/horse-or-human/horses')\n\n# Directory with our training human pictures\ntrain_human_dir = os.path.join('/tmp/horse-or-human/humans')\n\n# Directory with our training horse pictures\nvalidation_horse_dir = os.path.join('/tmp/validation-horse-or-human/horses')\n\n# Directory with our training human pictures\nvalidation_human_dir = os.path.join('/tmp/validation-horse-or-human/humans')", "_____no_output_____" ] ], [ [ "## Building a Small Model from Scratch\n\nBut before we continue, let's start defining the model:\n\nStep 1 will be to import tensorflow.", "_____no_output_____" ] ], [ [ "import tensorflow as tf", "_____no_output_____" ] ], [ [ "We then add convolutional layers as in the previous example, and flatten the final result to feed into the densely connected layers.", "_____no_output_____" ], [ "Finally we add the densely connected layers. \n\nNote that because we are facing a two-class classification problem, i.e. a *binary classification problem*, we will end our network with a [*sigmoid* activation](https://wikipedia.org/wiki/Sigmoid_function), so that the output of our network will be a single scalar between 0 and 1, encoding the probability that the current image is class 1 (as opposed to class 0).", "_____no_output_____" ] ], [ [ "model = tf.keras.models.Sequential([\n # Note the input shape is the desired size of the image 300x300 with 3 bytes color\n # This is the first convolution\n tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),\n tf.keras.layers.MaxPooling2D(2, 2),\n # The second convolution\n tf.keras.layers.Conv2D(32, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n # The third convolution\n tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n # The fourth convolution\n tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n # The fifth convolution\n tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n # Flatten the results to feed into a DNN\n tf.keras.layers.Flatten(),\n # 512 neuron hidden layer\n tf.keras.layers.Dense(512, activation='relu'),\n # Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('horses') and 1 for the other ('humans')\n tf.keras.layers.Dense(1, activation='sigmoid')\n])", "_____no_output_____" ], [ "from tensorflow.keras.optimizers import RMSprop\n\nmodel.compile(loss='binary_crossentropy',\n optimizer=RMSprop(lr=1e-4),\n metrics=['accuracy'])", "_____no_output_____" ], [ "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# All images will be rescaled by 1./255\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\nvalidation_datagen = ImageDataGenerator(rescale=1/255)\n\n# Flow training images in batches of 128 using train_datagen generator\ntrain_generator = train_datagen.flow_from_directory(\n '/tmp/horse-or-human/', # This is the source directory for training images\n target_size=(300, 300), # All images will be resized to 150x150\n batch_size=128,\n # Since we use binary_crossentropy loss, we need binary labels\n class_mode='binary')\n\n# Flow training images in batches of 128 using train_datagen generator\nvalidation_generator = validation_datagen.flow_from_directory(\n '/tmp/validation-horse-or-human/', # This is the source directory for training images\n target_size=(300, 300), # All images will be resized to 150x150\n batch_size=32,\n # Since we use binary_crossentropy loss, we need binary labels\n class_mode='binary')", "_____no_output_____" ], [ "history = model.fit(\n train_generator,\n steps_per_epoch=8, \n epochs=100,\n verbose=1,\n validation_data = validation_generator,\n validation_steps=8)", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\n\nplt.figure()\n\nplt.plot(epochs, loss, 'r', label='Training Loss')\nplt.plot(epochs, val_loss, 'b', label='Validation Loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d0724a8fbf77657fac9f899fdf917b20fab7caca
205,665
ipynb
Jupyter Notebook
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
b6838e4a1e757104b02347078a4e27c2b97960e2
[ "MIT" ]
1
2019-02-27T03:43:34.000Z
2019-02-27T03:43:34.000Z
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
b6838e4a1e757104b02347078a4e27c2b97960e2
[ "MIT" ]
null
null
null
Adversarial Examples.ipynb
wgharbieh/Adversarial-Examples
b6838e4a1e757104b02347078a4e27c2b97960e2
[ "MIT" ]
null
null
null
225.509868
15,738
0.899798
[ [ [ "# Adversarial Examples", "_____no_output_____" ], [ "Let's start out by importing all the required libraries", "_____no_output_____" ] ], [ [ "import os\nimport sys", "_____no_output_____" ], [ "sys.path.append(os.path.join(os.getcwd(), \"venv\"))", "_____no_output_____" ], [ "import numpy as np\n\nimport torch\nimport torchvision.transforms as transforms\n\nfrom matplotlib import pyplot as plt\n\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import MNIST", "_____no_output_____" ] ], [ [ "## MNIST ", "_____no_output_____" ], [ "Pytorch expects `Dataset` objects as input. Luckily, for MNIST (and few other datasets such as CIFAR and SVHN), torchvision has a ready made function to convert the dataset to a pytorch `Dataset` object. Keep in mind that these functions return `PIL` images so you will have to apply a transformation on them. ", "_____no_output_____" ] ], [ [ "path = os.path.join(os.getcwd(), \"MNIST\")\ntransform = transforms.Compose([transforms.ToTensor()])\ntrain_mnist = MNIST(path, train=True, transform=transform)\ntest_mnist = MNIST(path, train=False, transform=transform)", "_____no_output_____" ] ], [ [ "### Visualize Dataset", "_____no_output_____" ], [ "Set `batch_size` to 1 to visualize the dataset.", "_____no_output_____" ] ], [ [ "batch_size = 1\ntrain_set = DataLoader(train_mnist, batch_size=batch_size, shuffle=True)\ntest_set = DataLoader(test_mnist, batch_size=batch_size, shuffle=True)", "_____no_output_____" ], [ "num_images = 2\n\nfor i, (image, label) in enumerate(train_set):\n if i == num_images:\n break\n #Pytorch returns batch_size x num_channels x 28 x 28\n plt.imshow(image[0][0])\n plt.show()\n print(\"label: \" + str(label))", "_____no_output_____" ] ], [ [ "### Train a Model", "_____no_output_____" ], [ "Set `batch_size` to start training a model on the dataset.", "_____no_output_____" ] ], [ [ "batch_size = 64\ntrain_set = DataLoader(train_mnist, batch_size=batch_size, shuffle=True)", "_____no_output_____" ] ], [ [ "Define a `SimpleCNN` model to train on MNIST", "_____no_output_____" ] ], [ [ "def identity():\n return lambda x: x\n\n\nclass CustomConv2D(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size,\n activation, stride):\n super().__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size-2)\n self.activation = activation\n\n def forward(self, x):\n h = self.conv(x)\n return self.activation(h)\n\n \nclass SimpleCNN(nn.Module):\n def __init__(self, in_channels=1, out_base=2, kernel_size=3, activation=identity(),\n stride=2, num_classes=10):\n super().__init__()\n\n self.conv1 = CustomConv2D(in_channels, out_base, kernel_size, activation, stride)\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.conv2 = CustomConv2D(out_base, out_base, kernel_size, activation, stride)\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.linear = nn.Linear(4 * out_base, num_classes, bias=True)\n\n self.log_softmax = nn.LogSoftmax(dim=-1)\n\n def forward(self, x):\n h = self.conv1(x)\n h = self.pool1(h)\n h = self.conv2(h)\n h = self.pool2(h)\n h = h.view([x.size(0), -1])\n return self.log_softmax(self.linear(h))\n", "_____no_output_____" ] ], [ [ "Create 4 model variations:\n\n identity_model: SimpleCNN model with identity activation functions\n relu_model: SimpleCNN model with relu activation functions\n sig_model: SimpleCNN model with sigmoid activation functions\n tanh_model: SimpleCNN model with tanh activation functions", "_____no_output_____" ] ], [ [ "identity_model = SimpleCNN()\nrelu_model = SimpleCNN(activation=nn.ReLU())\nsig_model = SimpleCNN(activation=nn.Sigmoid())\ntanh_model = SimpleCNN(activation=nn.Tanh())", "_____no_output_____" ] ], [ [ "Create a function to train the model", "_____no_output_____" ] ], [ [ "def train_model(model, train_set, num_epochs):\n optimizer = torch.optim.Adam(lr=0.001, params=model.parameters())\n for epoch in range(num_epochs):\n epoch_accuracy, epoch_loss = 0, 0\n train_set_size = 0\n for images, labels in train_set:\n batch_size = images.size(0)\n images_var, labels_var = Variable(images), Variable(labels)\n \n log_probs = model(images_var)\n _, preds = torch.max(log_probs, dim=-1)\n \n loss = nn.NLLLoss()(log_probs, labels_var)\n epoch_loss += loss.data.numpy()[0] * batch_size\n \n accuracy = preds.eq(labels_var).float().mean().data.numpy()[0] * 100.0\n epoch_accuracy += accuracy * batch_size\n train_set_size += batch_size\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n epoch_accuracy = epoch_accuracy / train_set_size\n epoch_loss = epoch_loss / train_set_size\n print(\"epoch {}: loss= {:.3}, accuracy= {:.4}\".format(epoch + 1, epoch_loss, epoch_accuracy))\n \n return model\n ", "_____no_output_____" ], [ "trained_model = train_model(relu_model, train_set, 10)", "epoch 1: loss= 1.86, accuracy= 35.7\nepoch 2: loss= 1.49, accuracy= 49.69\nepoch 3: loss= 1.44, accuracy= 51.29\nepoch 4: loss= 1.4, accuracy= 52.41\nepoch 5: loss= 1.37, accuracy= 53.35\nepoch 6: loss= 1.34, accuracy= 54.23\nepoch 7: loss= 1.32, accuracy= 54.97\nepoch 8: loss= 1.3, accuracy= 55.83\nepoch 9: loss= 1.29, accuracy= 56.24\nepoch 10: loss= 1.28, accuracy= 56.8\n" ] ], [ [ "## Generating Adversarial Examples", "_____no_output_____" ], [ "Now that we have a trained model, we can generate adversarial examples.", "_____no_output_____" ], [ "### Gradient Ascent ", "_____no_output_____" ], [ "Use Gradient Ascent to generate a targeted adversarial example.", "_____no_output_____" ] ], [ [ "def np_val(torch_var):\n return torch_var.data.numpy()[0]\n\n\nclass AttackNet(nn.Module):\n def __init__(self, model, image_size):\n super().__init__()\n self.model = model\n self.params = nn.Parameter(torch.zeros(image_size), requires_grad=True)\n\n def forward(self, image):\n # clamp parameters here? or in backward?\n x = image + self.params\n x = torch.clamp(x, 0, 1)\n log_probs = self.model(x)\n return log_probs\n\n\nclass GradientAscent(object):\n def __init__(self, model, confidence=0):\n super().__init__()\n self.model = model\n self.num_steps = 10000\n self.confidence = confidence\n\n def attack(self, image, label, target=None):\n image_var = Variable(image)\n attack_net = AttackNet(self.model, image.shape)\n optimizer = torch.optim.Adam(lr=0.01, params=[attack_net.params])\n target = Variable(torch.from_numpy(np.array([target], dtype=np.int64))\n ) if target is not None else None\n log_probs = attack_net(image_var)\n confidence, predictions = torch.max(torch.exp(log_probs), dim=-1)\n if label.numpy()[0] != np_val(predictions):\n print(\"model prediction does not match label\")\n return None, (None, None), (None, None)\n else:\n for step in range(self.num_steps):\n stop_training = self.perturb(image_var, attack_net, target, optimizer)\n if stop_training:\n print(\"Adversarial attack succeeded after {} steps!\".format(\n step + 1))\n break\n if stop_training is False:\n print(\"Adversarial attack failed\")\n\n log_probs = attack_net(image_var)\n adv_confidence, adv_predictions = torch.max(torch.exp(log_probs), dim=-1)\n return attack_net.params, (confidence, predictions), (adv_confidence,\n adv_predictions)\n\n def perturb(self, image, attack_net, target, optimizer):\n log_probs = attack_net(image)\n confidence, predictions = torch.max(torch.exp(log_probs), dim=-1)\n\n if (np_val(predictions) == np_val(target) and\n np_val(confidence) >= self.confidence):\n return True\n\n loss = nn.NLLLoss()(log_probs, target)\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n return False", "_____no_output_____" ] ], [ [ "Define a `GradientAscent` object", "_____no_output_____" ] ], [ [ "gradient_ascent = GradientAscent(trained_model)", "_____no_output_____" ] ], [ [ "Define a function to help plot the results", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\ndef plot_results(image, perturbation, orig_pred, orig_con, adv_pred, adv_con):\n plot_image = image.numpy()[0][0]\n plot_perturbation = perturbation.data.numpy()[0][0]\n \n fig_size = plt.rcParams[\"figure.figsize\"]\n fig_size[0] = 10\n fig_size[1] = 5\n plt.rcParams[\"figure.figsize\"] = fig_size\n \n ax = plt.subplot(131)\n ax.set_title(\"Original: \" + str(np_val(orig_pred)) + \" @ \" +\n str(np.round(np_val(orig_con) * 100, decimals=1)) + \"%\")\n plt.imshow(plot_image)\n plt.subplot(132)\n plt.imshow(plot_perturbation)\n ax = plt.subplot(133)\n plt.imshow(plot_image + plot_perturbation)\n ax.set_title(\"Adversarial: \" + str(np_val(adv_pred)) + \" @ \" +\n str(np.round(np_val(adv_con) * 100, decimals=1)) + \"%\")\n plt.show()", "_____no_output_____" ] ], [ [ "Let's generate some adversarial examples!", "_____no_output_____" ] ], [ [ "num_images = 2\n\nfor i, (test_image, test_label) in enumerate(test_set):\n if i == num_images:\n break\n target_classes = list(range(10))\n target_classes.remove(test_label.numpy()[0])\n target = np.random.choice(target_classes)\n perturbation, (orig_con, orig_pred), (\n adv_con, adv_pred) = gradient_ascent.attack(test_image, test_label, target)\n if perturbation is not None:\n plot_results(test_image, perturbation, orig_pred, orig_con, adv_pred, adv_con)", "Adversarial attack succeeded after 3 steps!\n" ] ], [ [ "### Fast Gradient", "_____no_output_____" ], [ "Now let's use the Fast Gradient Sign Method to generate untargeted adversarial examples.", "_____no_output_____" ] ], [ [ "class FastGradient(object):\n def __init__(self, model, confidence=0, alpha=0.1):\n super().__init__()\n self.model = model\n self.confidence = confidence\n self.alpha = alpha\n\n def attack(self, image, label):\n image_var = Variable(image, requires_grad=True)\n target = Variable(torch.from_numpy(np.array([label], dtype=np.int64))\n ) if label is not None else None\n log_probs = self.model(image_var)\n confidence, predictions = torch.max(torch.exp(log_probs), dim=-1)\n if label.numpy()[0] != np_val(predictions):\n print(\"model prediction does not match label\")\n return None, (None, None), (None, None)\n else:\n loss = nn.NLLLoss()(log_probs, target)\n loss.backward()\n \n x_grad = torch.sign(image_var.grad.data)\n adv_image = torch.clamp(image_var.data + self.alpha * x_grad, 0, 1)\n delta = adv_image - image_var.data\n\n adv_log_probs = self.model(Variable(adv_image))\n adv_confidence, adv_predictions = torch.max(torch.exp(adv_log_probs),\n dim=-1)\n if (np_val(adv_predictions) != np_val(predictions) and\n np_val(adv_confidence) >= self.confidence):\n print(\"Adversarial attack succeeded!\")\n else:\n print(\"Adversarial attack failed\")\n \n return Variable(delta), (confidence, predictions), (adv_confidence,\n adv_predictions)", "_____no_output_____" ] ], [ [ "Define a `FastGradient` object", "_____no_output_____" ] ], [ [ "fast_gradient = FastGradient(trained_model)", "_____no_output_____" ] ], [ [ "Let's generate some adversarial examples!", "_____no_output_____" ] ], [ [ "num_images = 20\n\nfor i, (test_image, test_label) in enumerate(test_set):\n if i == num_images:\n break\n perturbation, (orig_con, orig_pred), (\n adv_con, adv_pred) = fast_gradient.attack(test_image, test_label)\n if perturbation is not None:\n plot_results(test_image, perturbation, orig_pred, orig_con, adv_pred, adv_con)", "Adversarial attack failed\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d07253d348b82da5e717d16533adc7089f50a440
8,421
ipynb
Jupyter Notebook
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
ec3fe6fa95eb2bab5d4dd99a996dd95e428162e8
[ "MIT" ]
null
null
null
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
ec3fe6fa95eb2bab5d4dd99a996dd95e428162e8
[ "MIT" ]
null
null
null
day_1/Actividad_02.ipynb
Fhrozen/2021_clubes_ciencia_speech
ec3fe6fa95eb2bab5d4dd99a996dd95e428162e8
[ "MIT" ]
null
null
null
26.818471
195
0.483316
[ [ [ "# Introduccion a la Inteligencia Artificial", "_____no_output_____" ], [ "Veremos dos ejercicios con para entender el concepto de inteligencia artificial", "_____no_output_____" ], [ "## Objeto Rebotador", "_____no_output_____" ], [ "En el siguiente ejercicio, realizaremos un objeto que al chocar con una de las paredes, este cambie de direccion y siga con su camino", "_____no_output_____" ] ], [ [ "!pip3 install ColabTurtle", "_____no_output_____" ] ], [ [ "Llamamos las librerias", "_____no_output_____" ] ], [ [ "import ColabTurtle.Turtle as robot\nimport random", "_____no_output_____" ] ], [ [ "Ahora el codigo principal. \nDe momento el robot rebota y vuelve en la misma dirección.\nLo que tienes que hacer es poner un inicio aleatorio y modificar el `if` dentro del lazo `while` de manera que este cambie en un solo eje.", "_____no_output_____" ] ], [ [ "robot.initializeTurtle(initial_speed=1) \npad = 15\nmax_w = robot.window_width() - pad\nmax_h = robot.window_height() - pad\n\nrobot.shape(\"circle\")\nrobot.color(\"green\")\nrobot.penup()\nrobot.goto(0 + pad, 200)\n\nrobot.dx = 10 # Velociad en x\nrobot.dy = 10 # Velociad en y\n\nreflections = 0\n\n# El numero de reflexiones puede ser modificado para que se ejecute por la eternidad. usando while True.\n# Pero, debido al limitado tiempo, este es limitado a solo 3 reflexiones.\n\nwhile reflections < 3: \n robot.speed(random.randrange(1, 10))\n new_y = robot.gety() + robot.dy\n new_x = robot.getx() + robot.dx\n if (new_y < pad) or \\\n (new_y > max_h) or \\\n (new_x < pad) or \\\n (new_x > max_w):\n robot.dy *= -1\n robot.dx *= -1\n reflections += 1\n robot.goto(new_x, new_y)", "_____no_output_____" ] ], [ [ "## ChatBot", "_____no_output_____" ], [ "Para el siguiente ejercicio, utilizaremos un ChatBot con definido por reglas. (Ejemplo tomado de: https://www.analyticsvidhya.com/blog/2021/07/build-a-simple-chatbot-using-python-and-nltk/)", "_____no_output_____" ] ], [ [ "!pip install nltk", "_____no_output_____" ], [ "import nltk\nfrom nltk.chat.util import Chat, reflections", "_____no_output_____" ] ], [ [ "**Chat**: es la clase que contiene toda lo logica para processar el texto que el chatbot recibe y encontrar informacion util.\n**reflections**: es un diccionario que contiene entradas basica y sus correspondientes salidas.", "_____no_output_____" ] ], [ [ "print(reflections)", "_____no_output_____" ] ], [ [ "Comenzemos contruyendo las reglas. Las siguientes lineas generan un conjunto de reglas simples.", "_____no_output_____" ] ], [ [ "pairs = [\n [\n r\"my name is (.*)\",\n [\"Hello %1, How are you today ?\",]\n ],\n [\n r\"hi|hey|hello\",\n [\"Hello\", \"Hey there\",]\n ], \n [\n r\"what is your name ?\",\n [\"I am a bot created by Analytics Vidhya. you can call me crazy!\",]\n ],\n [\n r\"how are you ?\",\n [\"I'm doing goodnHow about You ?\",]\n ],\n [\n r\"sorry (.*)\",\n [\"Its alright\",\"Its OK, never mind\",]\n ],\n [\n r\"I am fine\",\n [\"Great to hear that, How can I help you?\",]\n ],\n [\n r\"i'm (.*) doing good\",\n [\"Nice to hear that\",\"How can I help you?:)\",]\n ],\n [\n r\"(.*) age?\",\n [\"I'm a computer program dudenSeriously you are asking me this?\",]\n ],\n [\n r\"what (.*) want ?\",\n [\"Make me an offer I can't refuse\",]\n ],\n [\n r\"(.*) created ?\",\n [\"Raghav created me using Python's NLTK library \",\"top secret ;)\",]\n ],\n [\n r\"(.*) (location|city) ?\",\n ['Indore, Madhya Pradesh',]\n ],\n [\n r\"how is weather in (.*)?\",\n [\"Weather in %1 is awesome like always\",\"Too hot man here in %1\",\"Too cold man here in %1\",\"Never even heard about %1\"]\n ],\n [\n r\"i work in (.*)?\",\n [\"%1 is an Amazing company, I have heard about it. But they are in huge loss these days.\",]\n ],\n [\n r\"(.*)raining in (.*)\",\n [\"No rain since last week here in %2\",\"Damn its raining too much here in %2\"]\n ],\n [\n r\"how (.*) health(.*)\",\n [\"I'm a computer program, so I'm always healthy \",]\n ],\n [\n r\"(.*) (sports|game) ?\",\n [\"I'm a very big fan of Football\",]\n ],\n [\n r\"who (.*) sportsperson ?\",\n [\"Messy\",\"Ronaldo\",\"Roony\"]\n ],\n [\n r\"who (.*) (moviestar|actor)?\",\n [\"Brad Pitt\"]\n ],\n [\n r\"i am looking for online guides and courses to learn data science, can you suggest?\",\n [\"Crazy_Tech has many great articles with each step explanation along with code, you can explore\"]\n ],\n [\n r\"quit\",\n [\"BBye take care. See you soon :) \",\"It was nice talking to you. See you soon :)\"]\n ],\n]", "_____no_output_____" ] ], [ [ "Después de definir las reglas, definimos la función para ejecutar el proceso de chat.", "_____no_output_____" ] ], [ [ "def chat(this_creator='Nelson Yalta'):\n print(f\"Hola!!! Yo soy un chatbot creado por {this_creator}, y estoy listo para sus servicios. Recuede que hablo inglés.\")\n chat = Chat(pairs, reflections)\n chat.converse()\n\nchat()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d07263ddc66f1f1f47f6aca18258a191b23ec39e
6,417
ipynb
Jupyter Notebook
V3/v3_exercises_material/solutions/4_Pi-Estimation/Pi_Solution.ipynb
fred1234/BDLC_FS22
9db012026bfa1b8672bb4c62558b3beac4baff98
[ "MIT" ]
1
2022-02-24T12:47:23.000Z
2022-02-24T12:47:23.000Z
V3/v3_exercises_material/solutions/4_Pi-Estimation/Pi_Solution.ipynb
fred1234/BDLC_FS22
9db012026bfa1b8672bb4c62558b3beac4baff98
[ "MIT" ]
null
null
null
V3/v3_exercises_material/solutions/4_Pi-Estimation/Pi_Solution.ipynb
fred1234/BDLC_FS22
9db012026bfa1b8672bb4c62558b3beac4baff98
[ "MIT" ]
null
null
null
28.775785
283
0.525012
[ [ [ "# Pi Estimation Using Monte Carlo", "_____no_output_____" ], [ "In this exercise, we will use MapReduce and a Monte-Carlo-Simulation to estimate $\\Pi$.\n\nIf we are looking at this image from this [blog](https://towardsdatascience.com/how-to-make-pi-part-1-d0b41a03111f), we see a unit circle in a unit square:\n\n![Circle_Box](https://miro.medium.com/max/700/1*y-GFdC5OM0ZtYfbfkjjB2w.png)", "_____no_output_____" ], [ "The area:\n\n- for the circle is $A_{circle} = \\Pi*r^2 = \\Pi * 1*1 = \\Pi$\n- for the square is $A_{square} = d^2 = (2*r)^2 = 4$\n\nThe ratio of the two areas are therefore $\\frac{A_{circle}}{A_{square}} = \\frac{\\Pi}{4}$", "_____no_output_____" ], [ "The Monte-Carlo-Simulation draws multiple points on the square, uniformly at random. For every point, we count if it lies within the circle or not.\n\nAnd so we get the approximation:\n\n$\\frac{\\Pi}{4} \\approx \\frac{\\text{points_in_circle}}{\\text{total_points}}$\n\nor\n\n$\\Pi \\approx 4* \\frac{\\text{points_in_circle}}{\\text{total_points}}$\n\n", "_____no_output_____" ], [ "If we have a point $x_1,y_1$ and we want to figure out if it lies in a circle with radius $1$ we can use the following formula:\n\n$\\text{is_in_circle}(x_1,y_1) = \n\\begin{cases}\n 1,& \\text{if } (x_1)^2 + (y_1)^2 \\leq 1\\\\\n 0, & \\text{otherwise}\n\\end{cases}$", "_____no_output_____" ], [ "## Implementation\nWrite a MapReduce algorithm for estimating $\\Pi$", "_____no_output_____" ] ], [ [ "%%writefile pi.py\n\n#!/usr/bin/python3\nfrom mrjob.job import MRJob\n\nfrom random import uniform\n\nclass MyJob(MRJob):\n\n def mapper(self, _, line):\n \n for x in range(100):\n x = uniform(-1,1)\n y = uniform(-1,1)\n \n in_circle = x*x + y*y <=1\n yield None, in_circle\n\n def reducer(self, key, values):\n values = list(values)\n yield \"Pi\", 4 * sum(values) / len(values)\n yield \"number of values\", len(values)\n # for v in values:\n # yield key, v\n\nif __name__ == '__main__':\n MyJob.run()", "_____no_output_____" ] ], [ [ "## Another Approach\nComputing the mean in the mapper", "_____no_output_____" ] ], [ [ "%%writefile pi.py\n\n#!/usr/bin/python3\nfrom mrjob.job import MRJob\n\nfrom random import uniform\n\nclass MyJob(MRJob):\n\n def mapper(self, _, line): \n num_samples = 100\n in_circles_list = []\n \n for x in range(num_samples):\n x = uniform(-1,1)\n y = uniform(-1,1)\n \n in_circle = x*x + y*y <=1\n in_circles_list.append(in_circle)\n \n yield None, [num_samples, sum(in_circles_list)/num_samples]\n\n def reducer(self, key, numSamples_sum_pairs):\n \n total_samples = 0\n weighted_numerator_sum = 0\n for (num_samples, current_sum) in numSamples_sum_pairs:\n total_samples += num_samples\n weighted_numerator_sum += num_samples*current_sum\n \n \n yield \"Pi\", 4 * weighted_numerator_sum / total_samples\n yield \"weighted_numerator_sum\", weighted_numerator_sum\n yield \"total_samples\", total_samples\n\nif __name__ == '__main__':\n MyJob.run()", "_____no_output_____" ] ], [ [ "### Running the Job\n\n\nUnfortunately, the library does not work without an input file. I guess this comes from the fact that the hadoop streaming library also does not support this feature, see [stack overflow](https://stackoverflow.com/questions/22821005/hadoop-streaming-job-with-no-input-file).\n\nWe fake the number of mappers with different input files. Not the most elegant solution :/\n", "_____no_output_____" ] ], [ [ "!python pi.py /data/dataset/text/small.txt", "_____no_output_____" ], [ "!python pi.py /data/dataset/text/holmes.txt", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d072643d5dc6092509f9cf9190cd5f5b95401bca
24,747
ipynb
Jupyter Notebook
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
5dd86703c29f01e1de6f864b047f6b47159a9cf3
[ "Apache-2.0" ]
4
2021-04-01T12:53:41.000Z
2021-09-24T08:55:42.000Z
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
5dd86703c29f01e1de6f864b047f6b47159a9cf3
[ "Apache-2.0" ]
null
null
null
train_captioning_model.ipynb
sidphbot/visual-to-audio-aid-for-visually-impaired
5dd86703c29f01e1de6f864b047f6b47159a9cf3
[ "Apache-2.0" ]
1
2020-07-18T11:38:55.000Z
2020-07-18T11:38:55.000Z
24,747
24,747
0.662828
[ [ [ "import tensorflow as tf\n\n# You'll generate plots of attention in order to see which parts of an image\n# our model focuses on during captioning\nimport matplotlib.pyplot as plt\n\n# Scikit-learn includes many helpful utilities\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\nimport re\nimport numpy as np\nimport os\nimport time\nimport json\nfrom glob import glob\nfrom PIL import Image\nimport pickle", "_____no_output_____" ], [ "# mount drive\nfrom google.colab import drive\ndrive.mount('/gdrive')", "_____no_output_____" ], [ "#set up pickle and checkpoints folder\n\n!ls /gdrive\ncheckpoint_path = \"/gdrive/My Drive/checkpoints/train\"\n\nif not os.path.exists(checkpoint_path):\n os.mkdir(\"/gdrive/My Drive/checkpoints\")\n os.mkdir(\"/gdrive/My Drive/checkpoints/train\")\nif not os.path.exists(\"/gdrive/My Drive/pickles\"):\n os.mkdir(\"/gdrive/My Drive/pickles\")\n ", "_____no_output_____" ] ], [ [ "## Download and prepare the MS-COCO dataset\n\nYou will use the [MS-COCO dataset](http://cocodataset.org/#home) to train our model. The dataset contains over 82,000 images, each of which has at least 5 different caption annotations. The code below downloads and extracts the dataset automatically.\n\n**Caution: large download ahead**. You'll use the training set, which is a 13GB file.", "_____no_output_____" ] ], [ [ "# Download caption annotation files\nannotation_folder = '/annotations/'\nif not os.path.exists(os.path.abspath('.') + annotation_folder):\n annotation_zip = tf.keras.utils.get_file('captions.zip',\n cache_subdir=os.path.abspath('.'),\n origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip',\n extract = True)\n annotation_file = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json'\n os.remove(annotation_zip)\n\n# Download image files\nimage_folder = '/train2014/'\nif not os.path.exists(os.path.abspath('.') + image_folder):\n image_zip = tf.keras.utils.get_file('train2014.zip',\n cache_subdir=os.path.abspath('.'),\n origin = 'http://images.cocodataset.org/zips/train2014.zip',\n extract = True)\n PATH = os.path.dirname(image_zip) + image_folder\n os.remove(image_zip)\nelse:\n PATH = os.path.abspath('.') + image_folder", "_____no_output_____" ], [ "#Limiting size of dataset to 50000\n\n# Read the json file\nwith open(annotation_file, 'r') as f:\n annotations = json.load(f)\n\n# Store captions and image names in vectors\nall_captions = []\nall_img_name_vector = []\n\nfor annot in annotations['annotations']:\n caption = '<start> ' + annot['caption'] + ' <end>'\n image_id = annot['image_id']\n full_coco_image_path = PATH + 'COCO_train2014_' + '%012d.jpg' % (image_id)\n\n all_img_name_vector.append(full_coco_image_path)\n all_captions.append(caption)\n\n# Shuffle captions and image_names together\n# Set a random state\ntrain_captions, img_name_vector = shuffle(all_captions,\n all_img_name_vector,\n random_state=1)\n\n# Select the first 30000 captions from the shuffled set\nnum_examples = 50000\ntrain_captions = train_captions[:num_examples]\nimg_name_vector = img_name_vector[:num_examples]", "_____no_output_____" ], [ "len(train_captions), len(all_captions)", "_____no_output_____" ] ], [ [ "## Preprocess the images using InceptionV3\nNext, you will use InceptionV3 (which is pretrained on Imagenet) to classify each image. You will extract features from the last convolutional layer.\n\nFirst, you will convert the images into InceptionV3's expected format by:\n* Resizing the image to 299px by 299px\n* [Preprocess the images](https://cloud.google.com/tpu/docs/inception-v3-advanced#preprocessing_stage) using the [preprocess_input](https://www.tensorflow.org/api_docs/python/tf/keras/applications/inception_v3/preprocess_input) method to normalize the image so that it contains pixels in the range of -1 to 1, which matches the format of the images used to train InceptionV3.", "_____no_output_____" ] ], [ [ "def load_image(image_path):\n img = tf.io.read_file(image_path)\n img = tf.image.decode_jpeg(img, channels=3)\n img = tf.image.resize(img, (299, 299))\n img = tf.keras.applications.inception_v3.preprocess_input(img)\n return img, image_path", "_____no_output_____" ] ], [ [ "## Initialize InceptionV3 and load the pretrained Imagenet weights\n\nNow you'll create a tf.keras model where the output layer is the last convolutional layer in the InceptionV3 architecture. The shape of the output of this layer is ```8x8x2048```. You use the last convolutional layer because you are using attention in this example. You don't perform this initialization during training because it could become a bottleneck.\n\n* You forward each image through the network and store the resulting vector in a dictionary (image_name --> feature_vector).\n* After all the images are passed through the network, you pickle the dictionary and save it to disk.\n", "_____no_output_____" ] ], [ [ "image_model = tf.keras.applications.InceptionV3(include_top=False,\n weights='imagenet')\nnew_input = image_model.input\nhidden_layer = image_model.layers[-1].output\n\nimage_features_extract_model = tf.keras.Model(new_input, hidden_layer)", "_____no_output_____" ] ], [ [ "## Caching the features extracted from InceptionV3\n\nYou will pre-process each image with InceptionV3 and cache the output to disk. Caching the output in RAM would be faster but also memory intensive, requiring 8 \\* 8 \\* 2048 floats per image. At the time of writing, this exceeds the memory limitations of Colab (currently 12GB of memory).\n\nPerformance could be improved with a more sophisticated caching strategy (for example, by sharding the images to reduce random access disk I/O), but that would require more code.\n\nThe caching will take about 10 minutes to run in Colab with a GPU. If you'd like to see a progress bar, you can: \n\n1. install [tqdm](https://github.com/tqdm/tqdm):\n\n `!pip install tqdm`\n\n2. Import tqdm:\n\n `from tqdm import tqdm`\n\n3. Change the following line:\n\n `for img, path in image_dataset:`\n\n to:\n\n `for img, path in tqdm(image_dataset):`\n", "_____no_output_____" ] ], [ [ "# Get unique images\nencode_train = sorted(set(img_name_vector))\n\n# Feel free to change batch_size according to your system configuration\nimage_dataset = tf.data.Dataset.from_tensor_slices(encode_train)\nimage_dataset = image_dataset.map(\n load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE).batch(16)\n\nfor img, path in image_dataset:\n batch_features = image_features_extract_model(img)\n batch_features = tf.reshape(batch_features,\n (batch_features.shape[0], -1, batch_features.shape[3]))\n\n for bf, p in zip(batch_features, path):\n path_of_feature = p.numpy().decode(\"utf-8\")\n np.save(path_of_feature, bf.numpy())", "_____no_output_____" ] ], [ [ "## Preprocess and tokenize the captions\n\n* First, you'll tokenize the captions (for example, by splitting on spaces). This gives us a vocabulary of all of the unique words in the data (for example, \"surfing\", \"football\", and so on).\n* Next, you'll limit the vocabulary size to the top 5,000 words (to save memory). You'll replace all other words with the token \"UNK\" (unknown).\n* You then create word-to-index and index-to-word mappings.\n* Finally, you pad all sequences to be the same length as the longest one.", "_____no_output_____" ] ], [ [ "# Find the maximum length of any caption in our dataset\ndef calc_max_length(tensor):\n return max(len(t) for t in tensor)", "_____no_output_____" ], [ "# Choose the top 5000 words from the vocabulary\ntop_k = 5000\ntokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k,\n oov_token=\"<unk>\",\n filters='!\"#$%&()*+.,-/:;=?@[\\]^_`{|}~ ')\ntokenizer.fit_on_texts(train_captions)\ntrain_seqs = tokenizer.texts_to_sequences(train_captions)", "_____no_output_____" ], [ "tokenizer.word_index['<pad>'] = 0\ntokenizer.index_word[0] = '<pad>'\npickle.dump( tokenizer, open( \"tokeniser.pkl\", \"wb\" ) )\n!cp tokeniser.pkl \"/gdrive/My Drive/pickles/tokeniser.pkl\"", "_____no_output_____" ], [ "# Create the tokenized vectors\ntrain_seqs = tokenizer.texts_to_sequences(train_captions)", "_____no_output_____" ], [ "# Pad each vector to the max_length of the captions\n# If you do not provide a max_length value, pad_sequences calculates it automatically\ncap_vector = tf.keras.preprocessing.sequence.pad_sequences(train_seqs, padding='post')", "_____no_output_____" ], [ "# Calculates the max_length, which is used to store the attention weights\nmax_length = calc_max_length(train_seqs)\nprint(max_length)\n#pickle.dump( max_length, open( \"/gdrive/My Drive/max_length.p\", \"wb\" ) )\npickle.dump( max_length, open( \"max_length.pkl\", \"wb\" ) )\n!cp max_length.pkl \"/gdrive/My Drive/pickles/max_length.pkl\"\n#assert(False)", "_____no_output_____" ] ], [ [ "## Split the data into training and testing", "_____no_output_____" ] ], [ [ "# Create training and validation sets using an 80-20 split\nimg_name_train, img_name_val, cap_train, cap_val = train_test_split(img_name_vector,\n cap_vector,\n test_size=0.2,\n random_state=0)", "_____no_output_____" ], [ "len(img_name_train), len(cap_train), len(img_name_val), len(cap_val)", "_____no_output_____" ] ], [ [ "## Create a tf.data dataset for training\n", "_____no_output_____" ] ], [ [ "# Feel free to change these parameters according to your system's configuration\n\nBATCH_SIZE = 64\nBUFFER_SIZE = 1000\nembedding_dim = 256\nunits = 512\nvocab_size = top_k + 1\nnum_steps = len(img_name_train) // BATCH_SIZE\n# Shape of the vector extracted from InceptionV3 is (64, 2048)\n# These two variables represent that vector shape\nfeatures_shape = 2048\nattention_features_shape = 64", "_____no_output_____" ], [ "# Load the numpy files\ndef map_func(img_name, cap):\n img_tensor = np.load(img_name.decode('utf-8')+'.npy')\n return img_tensor, cap", "_____no_output_____" ], [ "dataset = tf.data.Dataset.from_tensor_slices((img_name_train, cap_train))\n\n# Use map to load the numpy files in parallel\ndataset = dataset.map(lambda item1, item2: tf.numpy_function(\n map_func, [item1, item2], [tf.float32, tf.int32]),\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n# Shuffle and batch\ndataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)\ndataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)", "_____no_output_____" ] ], [ [ "## Model\n\nFun fact: the decoder below is identical to the one in the example for [Neural Machine Translation with Attention](../sequences/nmt_with_attention.ipynb).\n\nThe model architecture is inspired by the [Show, Attend and Tell](https://arxiv.org/pdf/1502.03044.pdf) paper.\n\n* In this example, you extract the features from the lower convolutional layer of InceptionV3 giving us a vector of shape (8, 8, 2048).\n* You squash that to a shape of (64, 2048).\n* This vector is then passed through the CNN Encoder (which consists of a single Fully connected layer).\n* The RNN (here GRU) attends over the image to predict the next word.", "_____no_output_____" ] ], [ [ "class BahdanauAttention(tf.keras.Model):\n def __init__(self, units):\n super(BahdanauAttention, self).__init__()\n self.W1 = tf.keras.layers.Dense(units)\n self.W2 = tf.keras.layers.Dense(units)\n self.V = tf.keras.layers.Dense(1)\n\n def call(self, features, hidden):\n # features(CNN_encoder output) shape == (batch_size, 64, embedding_dim)\n\n # hidden shape == (batch_size, hidden_size)\n # hidden_with_time_axis shape == (batch_size, 1, hidden_size)\n hidden_with_time_axis = tf.expand_dims(hidden, 1)\n\n # score shape == (batch_size, 64, hidden_size)\n score = tf.nn.tanh(self.W1(features) + self.W2(hidden_with_time_axis))\n\n # attention_weights shape == (batch_size, 64, 1)\n # you get 1 at the last axis because you are applying score to self.V\n attention_weights = tf.nn.softmax(self.V(score), axis=1)\n\n # context_vector shape after sum == (batch_size, hidden_size)\n context_vector = attention_weights * features\n context_vector = tf.reduce_sum(context_vector, axis=1)\n\n return context_vector, attention_weights", "_____no_output_____" ], [ "class CNN_Encoder(tf.keras.Model):\n # Since you have already extracted the features and dumped it using pickle\n # This encoder passes those features through a Fully connected layer\n def __init__(self, embedding_dim):\n super(CNN_Encoder, self).__init__()\n # shape after fc == (batch_size, 64, embedding_dim)\n self.fc = tf.keras.layers.Dense(embedding_dim)\n\n def call(self, x):\n x = self.fc(x)\n x = tf.nn.relu(x)\n return x", "_____no_output_____" ], [ "class RNN_Decoder(tf.keras.Model):\n def __init__(self, embedding_dim, units, vocab_size):\n super(RNN_Decoder, self).__init__()\n self.units = units\n\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(self.units,\n return_sequences=True,\n return_state=True,\n recurrent_initializer='glorot_uniform')\n \n #self.bi = tf.keras.layers.LSTM(self.units,\n # return_sequences=True,\n # return_state=True,\n # recurrent_initializer='glorot_uniform')\n #self.fc0 = tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(self.units, activation='sigmoid'))\n self.fc1 = tf.keras.layers.Dense(self.units)\n self.fc2 = tf.keras.layers.Dense(vocab_size)\n\n self.attention = BahdanauAttention(self.units)\n\n def call(self, x, features, hidden):\n # defining attention as a separate model\n context_vector, attention_weights = self.attention(features, hidden)\n\n # x shape after passing through embedding == (batch_size, 1, embedding_dim)\n x = self.embedding(x)\n\n # x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)\n x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)\n\n # passing the concatenated vector to the GRU\n output, state = self.gru(x)\n\n #x = self.fc0(output)\n\n # shape == (batch_size, max_length, hidden_size)\n x = self.fc1(output)\n\n # x shape == (batch_size * max_length, hidden_size)\n x = tf.reshape(x, (-1, x.shape[2]))\n\n # output shape == (batch_size * max_length, vocab)\n x = self.fc2(x)\n\n return x, state, attention_weights\n\n def reset_state(self, batch_size):\n return tf.zeros((batch_size, self.units))", "_____no_output_____" ], [ "encoder = CNN_Encoder(embedding_dim)\ndecoder = RNN_Decoder(embedding_dim, units, vocab_size)", "_____no_output_____" ], [ "optimizer = tf.keras.optimizers.Adam()\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True, reduction='none')\n\ndef loss_function(real, pred):\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n\n return tf.reduce_mean(loss_)", "_____no_output_____" ] ], [ [ "## Checkpoint", "_____no_output_____" ] ], [ [ "checkpoint_path = \"/gdrive/My Drive/checkpoints/train\"\nif not os.path.exists(checkpoint_path):\n os.mkdir(checkpoint_path)\nckpt = tf.train.Checkpoint(encoder=encoder,\n decoder=decoder,\n optimizer = optimizer)\nckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)", "_____no_output_____" ], [ "start_epoch = 0\nif ckpt_manager.latest_checkpoint:\n start_epoch = int(ckpt_manager.latest_checkpoint.split('-')[-1])\n # restoring the latest checkpoint in checkpoint_path\n ckpt.restore(ckpt_manager.latest_checkpoint)", "_____no_output_____" ] ], [ [ "## Training\n\n* You extract the features stored in the respective `.npy` files and then pass those features through the encoder.\n* The encoder output, hidden state(initialized to 0) and the decoder input (which is the start token) is passed to the decoder.\n* The decoder returns the predictions and the decoder hidden state.\n* The decoder hidden state is then passed back into the model and the predictions are used to calculate the loss.\n* Use teacher forcing to decide the next input to the decoder.\n* Teacher forcing is the technique where the target word is passed as the next input to the decoder.\n* The final step is to calculate the gradients and apply it to the optimizer and backpropagate.\n", "_____no_output_____" ] ], [ [ "# adding this in a separate cell because if you run the training cell\n# many times, the loss_plot array will be reset\nloss_plot = []", "_____no_output_____" ], [ "@tf.function\ndef train_step(img_tensor, target):\n loss = 0\n\n # initializing the hidden state for each batch\n # because the captions are not related from image to image\n hidden = decoder.reset_state(batch_size=target.shape[0])\n\n dec_input = tf.expand_dims([tokenizer.word_index['<start>']] * target.shape[0], 1)\n\n with tf.GradientTape() as tape:\n features = encoder(img_tensor)\n\n for i in range(1, target.shape[1]):\n # passing the features through the decoder\n predictions, hidden, _ = decoder(dec_input, features, hidden)\n\n loss += loss_function(target[:, i], predictions)\n\n # using teacher forcing\n dec_input = tf.expand_dims(target[:, i], 1)\n\n total_loss = (loss / int(target.shape[1]))\n\n trainable_variables = encoder.trainable_variables + decoder.trainable_variables\n\n gradients = tape.gradient(loss, trainable_variables)\n\n optimizer.apply_gradients(zip(gradients, trainable_variables))\n\n return loss, total_loss", "_____no_output_____" ], [ "EPOCHS = 40\n\nfor epoch in range(start_epoch, EPOCHS):\n start = time.time()\n total_loss = 0\n\n for (batch, (img_tensor, target)) in enumerate(dataset):\n batch_loss, t_loss = train_step(img_tensor, target)\n total_loss += t_loss\n\n if batch % 100 == 0:\n print ('Epoch {} Batch {} Loss {:.4f}'.format(\n epoch + 1, batch, batch_loss.numpy() / int(target.shape[1])))\n # storing the epoch end loss value to plot later\n loss_plot.append(total_loss / num_steps)\n\n if epoch % 5 == 0:\n ckpt_manager.save()\n\n print ('Epoch {} Loss {:.6f}'.format(epoch + 1,\n total_loss/num_steps))\n print ('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))", "_____no_output_____" ], [ "plt.plot(loss_plot)\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Loss Plot')\nplt.show()\npickle.dump( loss_plot, open( \"/gdrive/My Drive/loss_plot_save.p\", \"wb\" ) )", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d0726568c6358e10b3f04fa6b4d371afc06e6552
6,131
ipynb
Jupyter Notebook
Object Tracking and Localization/Representing State and Motion/Matrix Multiplication/Matrix_Multiplication.ipynb
brand909/Computer-Vision
18e5bda880e40f0a355d1df8520770df5bb1ed6b
[ "MIT" ]
null
null
null
Object Tracking and Localization/Representing State and Motion/Matrix Multiplication/Matrix_Multiplication.ipynb
brand909/Computer-Vision
18e5bda880e40f0a355d1df8520770df5bb1ed6b
[ "MIT" ]
4
2021-03-19T02:34:33.000Z
2022-03-11T23:56:20.000Z
Object Tracking and Localization/Representing State and Motion/Matrix Multiplication/Matrix_Multiplication.ipynb
brand909/Computer-Vision
18e5bda880e40f0a355d1df8520770df5bb1ed6b
[ "MIT" ]
null
null
null
25.978814
244
0.530419
[ [ [ "# Predict state\n\nHere is the current implementation of the `predict_state` function. It takes in a state (a Python list), and then separates those into position and velocity to calculate a new, predicted state. It uses a constant velocity motion model.\n\n**In this exercise, we'll be improving this function, and using matrix multiplication to efficiently calculate the predicted state!**", "_____no_output_____" ] ], [ [ "# The current predict state function\n# Predicts the next state based on a motion model\ndef predict_state(state, dt):\n # Assumes a valid state had been passed in\n x = state[0]\n velocity = state[1]\n \n # Assumes a constant velocity model\n new_x = x + velocity*dt\n \n # Create and return the new, predicted state\n predicted_state = [new_x, velocity]\n return predicted_state\n", "_____no_output_____" ] ], [ [ "## Matrix operations\n\nYou've been given a matrix class that can create new matrices and performs one operation: multiplication. In our directory this is called `matrix.py`.\n\nSimilar to the Car class, we can use this to initialize matrix objects.", "_____no_output_____" ] ], [ [ "# import the matrix file\nimport matrix\n\n# Initialize a state vector\ninitial_position = 0 # meters\nvelocity = 50 # m/s\n\n# Notice the syntax for creating a state column vector ([ [x], [v] ])\n# Commas separate these items into rows and brackets into columns\ninitial_state = matrix.Matrix([ [initial_position], \n [velocity] ])", "_____no_output_____" ] ], [ [ "### Transformation matrix\n\nNext, define the state transformation matrix and print it out!", "_____no_output_____" ] ], [ [ "# Define the state transformation matrix\ndt = 1\ntx_matrix = matrix.Matrix([ [1, dt], \n [0, 1] ])\n\nprint(tx_matrix)", "[[1 1 ]\n[0 1 ]\n]\n" ] ], [ [ "### TODO: Modify the predict state function to use matrix multiplication\n\nNow that you know how to create matrices, modify the `predict_state` function to work with them!\n\nNote: you can multiply a matrix A by a matrix B by writing `A*B` and it will return a new matrix.\n", "_____no_output_____" ] ], [ [ "# The current predict state function\ndef predict_state_mtx(state, dt):\n ## TODO: Assume that the state passed in is a Matrix object\n ## Using a constant velocity model and a transformation matrix\n ## Create and return the new, predicted state!\n tx_matrix = matrix.Matrix([ [1, dt], \n [0, 1] ]) \n predicted_state = tx_matrix * state\n \n return predicted_state", "_____no_output_____" ] ], [ [ "### Test cell\n\nHere is an initial state vector and dt to test your function with!", "_____no_output_____" ] ], [ [ "# initial state variables\ninitial_position = 10 # meters\nvelocity = 30 # m/s\n\n# Initial state vector\ninitial_state = matrix.Matrix([ [initial_position], \n [velocity] ])\n\n\nprint('The initial state is: ' + str(initial_state))\n\n\n# after 2 seconds make a prediction using the new function\nstate_est1 = predict_state_mtx(initial_state, 2)\n\nprint('State after 2 seconds is: ' + str(state_est1))", "The initial state is: [[10 ]\n[30 ]\n]\nState after 2 seconds is: [[70.0 ]\n[30.0 ]\n]\n" ], [ "# Make more predictions!\n\n# after 3 more\nstate_est2 = predict_state_mtx(state_est1, 3)\n\nprint('State after 3 more seconds is: ' + str(state_est2))\n\n# after 3 more\nstate_est3 = predict_state_mtx(state_est2, 3)\n\nprint('Final state after 3 more seconds is: ' + str(state_est3))", "State after 3 more seconds is: [[160.0 ]\n[30.0 ]\n]\nFinal state after 3 more seconds is: [[250.0 ]\n[30.0 ]\n]\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d072829215f29960ca4b3bfc963122163f2ecea9
23,495
ipynb
Jupyter Notebook
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
c315e7cf75822088e974e15b43c96fab86746733
[ "Apache-2.0" ]
null
null
null
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
c315e7cf75822088e974e15b43c96fab86746733
[ "Apache-2.0" ]
null
null
null
docs/tutorials/tfx/penguin_simple.ipynb
suryaavala/tfx
c315e7cf75822088e974e15b43c96fab86746733
[ "Apache-2.0" ]
null
null
null
36.257716
218
0.549606
[ [ [ "##### Copyright 2021 The TensorFlow Authors.", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ] ], [ [ "# Simple TFX Pipeline Tutorial using Penguin dataset\n\n***A Short tutorial to run a simple TFX pipeline.***", "_____no_output_____" ], [ "Note: We recommend running this tutorial in a Colab notebook, with no setup required! Just click \"Run in Google Colab\".\n\n<div class=\"devsite-table-wrapper\"><table class=\"tfo-notebook-buttons\" align=\"left\">\n<td><a target=\"_blank\" href=\"https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple\">\n<img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\"/>View on TensorFlow.org</a></td>\n<td><a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tfx/blob/master/docs/tutorials/tfx/penguin_simple.ipynb\">\n<img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\">Run in Google Colab</a></td>\n<td><a target=\"_blank\" href=\"https://github.com/tensorflow/tfx/tree/master/docs/tutorials/tfx/penguin_simple.ipynb\">\n<img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\">View source on GitHub</a></td>\n<td><a href=\"https://storage.googleapis.com/tensorflow_docs/tfx/docs/tutorials/tfx/penguin_simple.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a></td>\n</table></div>", "_____no_output_____" ], [ "In this notebook-based tutorial, we will create and run a TFX pipeline\nfor a simple classification model.\nThe pipeline will consist of three essential TFX components: ExampleGen,\nTrainer and Pusher. The pipeline includes the most minimal ML workflow like\nimporting data, training a model and exporting the trained model.\n\nPlease see\n[Understanding TFX Pipelines](https://www.tensorflow.org/tfx/guide/understanding_tfx_pipelines)\nto learn more about various concepts in TFX.", "_____no_output_____" ], [ "## Set Up\nWe first need to install the TFX Python package and download\nthe dataset which we will use for our model.\n\n### Upgrade Pip\n\nTo avoid upgrading Pip in a system when running locally,\ncheck to make sure that we are running in Colab.\nLocal systems can of course be upgraded separately.", "_____no_output_____" ] ], [ [ "try:\n import colab\n !pip install --upgrade pip\nexcept:\n pass", "_____no_output_____" ] ], [ [ "### Install TFX\n", "_____no_output_____" ] ], [ [ "!pip install -U tfx", "_____no_output_____" ] ], [ [ "### Did you restart the runtime?\n\nIf you are using Google Colab, the first time that you run\nthe cell above, you must restart the runtime by clicking\nabove \"RESTART RUNTIME\" button or using \"Runtime > Restart\nruntime ...\" menu. This is because of the way that Colab\nloads packages.", "_____no_output_____" ], [ "Check the TensorFlow and TFX versions.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nprint('TensorFlow version: {}'.format(tf.__version__))\nfrom tfx import v1 as tfx\nprint('TFX version: {}'.format(tfx.__version__))", "_____no_output_____" ] ], [ [ "### Set up variables\n\nThere are some variables used to define a pipeline. You can customize these\nvariables as you want. By default all output from the pipeline will be\ngenerated under the current directory.", "_____no_output_____" ] ], [ [ "import os\n\nPIPELINE_NAME = \"penguin-simple\"\n\n# Output directory to store artifacts generated from the pipeline.\nPIPELINE_ROOT = os.path.join('pipelines', PIPELINE_NAME)\n# Path to a SQLite DB file to use as an MLMD storage.\nMETADATA_PATH = os.path.join('metadata', PIPELINE_NAME, 'metadata.db')\n# Output directory where created models from the pipeline will be exported.\nSERVING_MODEL_DIR = os.path.join('serving_model', PIPELINE_NAME)\n\nfrom absl import logging\nlogging.set_verbosity(logging.INFO) # Set default logging level.", "_____no_output_____" ] ], [ [ "### Prepare example data\nWe will download the example dataset for use in our TFX pipeline. The dataset we\nare using is\n[Palmer Penguins dataset](https://allisonhorst.github.io/palmerpenguins/articles/intro.html)\nwhich is also used in other\n[TFX examples](https://github.com/tensorflow/tfx/tree/master/tfx/examples/penguin).\n\nThere are four numeric features in this dataset:\n\n- culmen_length_mm\n- culmen_depth_mm\n- flipper_length_mm\n- body_mass_g\n\nAll features were already normalized to have range [0,1]. We will build a\nclassification model which predicts the `species` of penguins.", "_____no_output_____" ], [ "Because TFX ExampleGen reads inputs from a directory, we need to create a\ndirectory and copy dataset to it.", "_____no_output_____" ] ], [ [ "import urllib.request\nimport tempfile\n\nDATA_ROOT = tempfile.mkdtemp(prefix='tfx-data') # Create a temporary directory.\n_data_url = 'https://raw.githubusercontent.com/tensorflow/tfx/master/tfx/examples/penguin/data/penguins_processed.csv'\n_data_filepath = os.path.join(DATA_ROOT, \"data.csv\")\nurllib.request.urlretrieve(_data_url, _data_filepath)", "_____no_output_____" ] ], [ [ "Take a quick look at the CSV file.", "_____no_output_____" ] ], [ [ "!head {_data_filepath}", "_____no_output_____" ] ], [ [ "You should be able to see five values. `species` is one of 0, 1 or 2, and all\nother features should have values between 0 and 1.", "_____no_output_____" ], [ "## Create a pipeline\n\nTFX pipelines are defined using Python APIs. We will define a pipeline which\nconsists of following three components.\n- CsvExampleGen: Reads in data files and convert them to TFX internal format\nfor further processing. There are multiple\n[ExampleGen](https://www.tensorflow.org/tfx/guide/examplegen)s for various\nformats. In this tutorial, we will use CsvExampleGen which takes CSV file input.\n- Trainer: Trains an ML model.\n[Trainer component](https://www.tensorflow.org/tfx/guide/trainer) requires a\nmodel definition code from users. You can use TensorFlow APIs to specify how to\ntrain a model and save it in a _saved_model_ format.\n- Pusher: Copies the trained model outside of the TFX pipeline.\n[Pusher component](https://www.tensorflow.org/tfx/guide/pusher) can be thought\nof an deployment process of the trained ML model.\n\nBefore actually define the pipeline, we need to write a model code for the\nTrainer component first.", "_____no_output_____" ], [ "### Write model training code\n\nWe will create a simple DNN model for classification using TensorFlow Keras\nAPI. This model training code will be saved to a separate file.\n\nIn this tutorial we will use\n[Generic Trainer](https://www.tensorflow.org/tfx/guide/trainer#generic_trainer)\nof TFX which support Keras-based models. You need to write a Python file\ncontaining `run_fn` function, which is the entrypoint for the `Trainer`\ncomponent.", "_____no_output_____" ] ], [ [ "_trainer_module_file = 'penguin_trainer.py'", "_____no_output_____" ], [ "%%writefile {_trainer_module_file}\n\nfrom typing import List\nfrom absl import logging\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow_transform.tf_metadata import schema_utils\n\nfrom tfx import v1 as tfx\nfrom tfx_bsl.public import tfxio\nfrom tensorflow_metadata.proto.v0 import schema_pb2\n\n_FEATURE_KEYS = [\n 'culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm', 'body_mass_g'\n]\n_LABEL_KEY = 'species'\n\n_TRAIN_BATCH_SIZE = 20\n_EVAL_BATCH_SIZE = 10\n\n# Since we're not generating or creating a schema, we will instead create\n# a feature spec. Since there are a fairly small number of features this is\n# manageable for this dataset.\n_FEATURE_SPEC = {\n **{\n feature: tf.io.FixedLenFeature(shape=[1], dtype=tf.float32)\n for feature in _FEATURE_KEYS\n },\n _LABEL_KEY: tf.io.FixedLenFeature(shape=[1], dtype=tf.int64)\n}\n\n\ndef _input_fn(file_pattern: List[str],\n data_accessor: tfx.components.DataAccessor,\n schema: schema_pb2.Schema,\n batch_size: int = 200) -> tf.data.Dataset:\n \"\"\"Generates features and label for training.\n\n Args:\n file_pattern: List of paths or patterns of input tfrecord files.\n data_accessor: DataAccessor for converting input to RecordBatch.\n schema: schema of the input data.\n batch_size: representing the number of consecutive elements of returned\n dataset to combine in a single batch\n\n Returns:\n A dataset that contains (features, indices) tuple where features is a\n dictionary of Tensors, and indices is a single Tensor of label indices.\n \"\"\"\n return data_accessor.tf_dataset_factory(\n file_pattern,\n tfxio.TensorFlowDatasetOptions(\n batch_size=batch_size, label_key=_LABEL_KEY),\n schema=schema).repeat()\n\n\ndef _build_keras_model() -> tf.keras.Model:\n \"\"\"Creates a DNN Keras model for classifying penguin data.\n\n Returns:\n A Keras Model.\n \"\"\"\n # The model below is built with Functional API, please refer to\n # https://www.tensorflow.org/guide/keras/overview for all API options.\n inputs = [keras.layers.Input(shape=(1,), name=f) for f in _FEATURE_KEYS]\n d = keras.layers.concatenate(inputs)\n for _ in range(2):\n d = keras.layers.Dense(8, activation='relu')(d)\n outputs = keras.layers.Dense(3)(d)\n\n model = keras.Model(inputs=inputs, outputs=outputs)\n model.compile(\n optimizer=keras.optimizers.Adam(1e-2),\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n\n model.summary(print_fn=logging.info)\n return model\n\n\n# TFX Trainer will call this function.\ndef run_fn(fn_args: tfx.components.FnArgs):\n \"\"\"Train the model based on given args.\n\n Args:\n fn_args: Holds args used to train the model as name/value pairs.\n \"\"\"\n\n # This schema is usually either an output of SchemaGen or a manually-curated\n # version provided by pipeline author. A schema can also derived from TFT\n # graph if a Transform component is used. In the case when either is missing,\n # `schema_from_feature_spec` could be used to generate schema from very simple\n # feature_spec, but the schema returned would be very primitive.\n schema = schema_utils.schema_from_feature_spec(_FEATURE_SPEC)\n\n train_dataset = _input_fn(\n fn_args.train_files,\n fn_args.data_accessor,\n schema,\n batch_size=_TRAIN_BATCH_SIZE)\n eval_dataset = _input_fn(\n fn_args.eval_files,\n fn_args.data_accessor,\n schema,\n batch_size=_EVAL_BATCH_SIZE)\n\n model = _build_keras_model()\n model.fit(\n train_dataset,\n steps_per_epoch=fn_args.train_steps,\n validation_data=eval_dataset,\n validation_steps=fn_args.eval_steps)\n\n # The result of the training should be saved in `fn_args.serving_model_dir`\n # directory.\n model.save(fn_args.serving_model_dir, save_format='tf')", "_____no_output_____" ] ], [ [ "Now you have completed all preparation steps to build a TFX pipeline.", "_____no_output_____" ], [ "### Write a pipeline definition\n\nWe define a function to create a TFX pipeline. A `Pipeline` object\nrepresents a TFX pipeline which can be run using one of pipeline\norchestration systems that TFX supports.\n", "_____no_output_____" ] ], [ [ "def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str,\n module_file: str, serving_model_dir: str,\n metadata_path: str) -> tfx.dsl.Pipeline:\n \"\"\"Creates a three component penguin pipeline with TFX.\"\"\"\n # Brings data into the pipeline.\n example_gen = tfx.components.CsvExampleGen(input_base=data_root)\n\n # Uses user-provided Python function that trains a model.\n trainer = tfx.components.Trainer(\n module_file=module_file,\n examples=example_gen.outputs['examples'],\n train_args=tfx.proto.TrainArgs(num_steps=100),\n eval_args=tfx.proto.EvalArgs(num_steps=5))\n\n # Pushes the model to a filesystem destination.\n pusher = tfx.components.Pusher(\n model=trainer.outputs['model'],\n push_destination=tfx.proto.PushDestination(\n filesystem=tfx.proto.PushDestination.Filesystem(\n base_directory=serving_model_dir)))\n\n # Following three components will be included in the pipeline.\n components = [\n example_gen,\n trainer,\n pusher,\n ]\n\n return tfx.dsl.Pipeline(\n pipeline_name=pipeline_name,\n pipeline_root=pipeline_root,\n metadata_connection_config=tfx.orchestration.metadata\n .sqlite_metadata_connection_config(metadata_path),\n components=components)", "_____no_output_____" ] ], [ [ "## Run the pipeline\n\nTFX supports multiple orchestrators to run pipelines.\nIn this tutorial we will use `LocalDagRunner` which is included in the TFX\nPython package and runs pipelines on local environment.\nWe often call TFX pipelines \"DAGs\" which stands for directed acyclic graph.\n\n`LocalDagRunner` provides fast iterations for developemnt and debugging.\nTFX also supports other orchestrators including Kubeflow Pipelines and Apache\nAirflow which are suitable for production use cases.\n\nSee\n[TFX on Cloud AI Platform Pipelines](https://www.tensorflow.org/tfx/tutorials/tfx/cloud-ai-platform-pipelines)\nor\n[TFX Airflow Tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/airflow_workshop)\nto learn more about other orchestration systems.", "_____no_output_____" ], [ "Now we create a `LocalDagRunner` and pass a `Pipeline` object created from the\nfunction we already defined.\n\nThe pipeline runs directly and you can see logs for the progress of the pipeline including ML model training.", "_____no_output_____" ] ], [ [ "tfx.orchestration.LocalDagRunner().run(\n _create_pipeline(\n pipeline_name=PIPELINE_NAME,\n pipeline_root=PIPELINE_ROOT,\n data_root=DATA_ROOT,\n module_file=_trainer_module_file,\n serving_model_dir=SERVING_MODEL_DIR,\n metadata_path=METADATA_PATH))", "_____no_output_____" ] ], [ [ "You should see \"INFO:absl:Component Pusher is finished.\" at the end of the\nlogs if the pipeline finished successfully. Because `Pusher` component is the\nlast component of the pipeline.\n\nThe pusher component pushes the trained model to the `SERVING_MODEL_DIR` which\nis the `serving_model/penguin-simple` directory if you did not change the\nvariables in the previous steps. You can see the result from the file browser\nin the left-side panel in Colab, or using the following command:", "_____no_output_____" ] ], [ [ "# List files in created model directory.\n!find {SERVING_MODEL_DIR}", "_____no_output_____" ] ], [ [ "## Next steps\n\nYou can find more resources on https://www.tensorflow.org/tfx/tutorials.\n\nPlease see\n[Understanding TFX Pipelines](https://www.tensorflow.org/tfx/guide/understanding_tfx_pipelines)\nto learn more about various concepts in TFX.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d07282bb7f73671aa9143faf583a17cb76e78ca1
6,107
ipynb
Jupyter Notebook
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
f60128a74b9958633e97970b98ab61a4f8069913
[ "Apache-2.0" ]
null
null
null
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
f60128a74b9958633e97970b98ab61a4f8069913
[ "Apache-2.0" ]
null
null
null
docs/using-a-different-corpus.ipynb
wuhaifengdhu/zh_segment
f60128a74b9958633e97970b98ab61a4f8069913
[ "Apache-2.0" ]
null
null
null
23.132576
297
0.548551
[ [ [ "# Using a Different Corpus\n\nzh_segment makes it easy to use a different corpus for word segmentation.\n\nIf you simply want to \"teach\" the algorithm a single phrase it doesn't know then read [this StackOverflow answer](http://stackoverflow.com/questions/20695825/english-word-segmentation-in-nlp).\n\nNow, let's get a new corpus. For this example, we'll use the text from Jane Austen's *Pride and Prejudice*.", "_____no_output_____" ] ], [ [ "import requests\n\nresponse = requests.get('https://www.gutenberg.org/ebooks/1342.txt.utf-8')\n\ntext = response.text\n\nprint len(text)", "717573\n" ] ], [ [ "Great. We've got a new corpus for `zh_segment`. Now let's look at what parts of the API we need to change. There's one function and two dictionaries: `zh_segment.clean`, `zh_segment.bigram_counts` and `zh_segment.unigram_counts`. We'll work on these in reverse.", "_____no_output_____" ] ], [ [ "import zh_segment", "_____no_output_____" ], [ "print type(zh_segment.unigram_counts), type(zh_segment.bigram_counts)", "<type 'dict'> <type 'dict'>\n" ], [ "print zh_segment.unigram_counts.items()[:3]\nprint zh_segment.bigram_counts.items()[:3]", "[('biennials', 37548.0), ('verplank', 48349.0), ('tsukino', 19771.0)]\n[('personal effects', 151369.0), ('basic training', 294085.0), ('it absolutely', 130505.0)]\n" ] ], [ [ "Ok, so `zh_segment.unigram_counts` is just a dictionary mapping unigrams to their counts. Let's write a method to tokenize our text.", "_____no_output_____" ] ], [ [ "import re\n\ndef tokenize(text):\n pattern = re.compile('[a-zA-Z]+')\n return (match.group(0) for match in pattern.finditer(text))\n\nprint list(tokenize(\"Wait, what did you say?\"))", "['Wait', 'what', 'did', 'you', 'say']\n" ] ], [ [ "Now we'll build our dictionaries.", "_____no_output_____" ] ], [ [ "from collections import Counter\n\nzh_segment.unigram_counts = Counter(tokenize(text))\n\ndef pairs(iterable):\n iterator = iter(iterable)\n values = [next(iterator)]\n for value in iterator:\n values.append(value)\n yield ' '.join(values)\n del values[0]\n\nzh_segment.bigram_counts = Counter(pairs(tokenize(text)))", "_____no_output_____" ] ], [ [ "That's it.\n\nNow, by default, `zh_segment.segment` lowercases all input and removes punctuation. In our corpus we have capitals so we'll also have to change the `clean` function. Our heaviest hammer is to simply replace it with the identity function. This will do no sanitation of the input to `segment`.", "_____no_output_____" ] ], [ [ "def identity(value):\n return value\n\nzh_segment.clean = identity", "_____no_output_____" ], [ "zh_segment.segment('wantofawife')", "_____no_output_____" ] ], [ [ "If you find this behaves poorly then you may need to change the `zh_segment.TOTAL` variable to reflect the total of all unigrams. In our case that's simply: ", "_____no_output_____" ] ], [ [ "zh_segment.TOTAL = float(sum(zh_segment.unigram_counts.values()))", "_____no_output_____" ] ], [ [ "zh_segment doesn't require any fancy machine learning training algorithms. Simply update the unigram and bigram count dictionaries and you're ready to go.", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0728cc935b79db0a4a0bdd00259ece86f49a23d
26,857
ipynb
Jupyter Notebook
notebooks/Untitled.ipynb
alancmathew/anime-recommendation-engine
43ef08d761eb787f49fad28076d926d0af13fba0
[ "MIT" ]
null
null
null
notebooks/Untitled.ipynb
alancmathew/anime-recommendation-engine
43ef08d761eb787f49fad28076d926d0af13fba0
[ "MIT" ]
null
null
null
notebooks/Untitled.ipynb
alancmathew/anime-recommendation-engine
43ef08d761eb787f49fad28076d926d0af13fba0
[ "MIT" ]
null
null
null
36.993113
613
0.320959
[ [ [ "import numpy as np\nimport pandas as pd\nimport scipy as sp", "_____no_output_____" ], [ "df = pd.read_pickle('../data/watch_list_clean.pkl.xz')[['title', 'username', 'rating']]", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df = df.pivot(index='username', columns='title', values='rating')", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df = df.fillna(0)", "_____no_output_____" ], [ "sparse = sp.sparse.csr_matrix(df.values, dtype=np.float32)", "_____no_output_____" ], [ "def similarity_calculator(data):\n return pd.DataFrame(cosine_similarity(sparse, data), index=df.index, columns=data.index).astype(np.float16)\n\nnum_workers = 15\nchunksize = int(validate_X.shape[0]/num_workers)+1\nchunks = chunker(validate_X.fillna(0), chunksize)\nwith Pool(num_workers) as p:\n similarity_matrix = pd.concat(p.map(similarity_calculator, chunks), axis=1)\n \ndel chunks\n\nsimilarity_matrix.to_pickle('/mnt/int_drive_0/Data/anime-recommendation-engine/similarity_matrix.pkl')", "_____no_output_____" ], [ "similarity_matrix = pd.read_pickle('/mnt/int_drive_0/Data/anime-recommendation-engine/similarity_matrix.pkl')\ndef n_similar_users(column, n=1000):\n return pd.Series(column.sort_values(ascending=False).head(n).index, name=column.name)\n\ndef similar_users_ordered(column):\n return pd.Series(column.sort_values(ascending=False).index, name=column.name)\n\nwith Pool(15) as p:\n similar_users_ordered = pd.concat(p.map(similar_users_ordered, (tup[1] for tup in similarity_matrix.items())), axis=1)\n\nsimilar_users_ordered.to_pickle('/mnt/int_drive_0/Data/anime-recommendation-engine/similar_users_ordered.pkl')", "_____no_output_____" ], [ "df = df.replace(0, np.NaN)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d072ac17177e68fb09e16358dcbd40409c103b0f
15,343
ipynb
Jupyter Notebook
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
142330ab6427254109af3b86102a30a13144ba0c
[ "MIT" ]
null
null
null
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
142330ab6427254109af3b86102a30a13144ba0c
[ "MIT" ]
null
null
null
example-usage/Jupyter Notebook/output data inspection/checking container dwell times.ipynb
1grasse/conflowgen
142330ab6427254109af3b86102a30a13144ba0c
[ "MIT" ]
null
null
null
29.792233
130
0.576875
[ [ [ "# Checking Container Dwell Times\n\nThis works with the CSV export of ConFlowGen.", "_____no_output_____" ], [ "Import libraries", "_____no_output_____" ] ], [ [ "import os\nimport pathlib\nimport ipywidgets as widgets\nimport pandas as pd\nfrom IPython.display import Markdown\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec", "_____no_output_____" ] ], [ [ "Select input data", "_____no_output_____" ] ], [ [ "folder_of_this_jupyter_notebook = pathlib.Path.cwd()\nexport_folder = os.path.join(\n folder_of_this_jupyter_notebook,\n os.pardir,\n os.pardir,\n os.pardir,\n \"conflowgen\",\n \"data\",\n \"exports\"\n)\nfolders = [\n folder\n for folder in os.listdir(export_folder)\n if os.path.isdir(\n os.path.join(\n export_folder,\n folder\n )\n )\n]\n\ndropdown_field = widgets.Dropdown(\n options=list(reversed(folders)), # always show the newest first\n description='',\n layout={'width': 'max-content'}\n)\ndropdown_label = widgets.Label(value=\"Select the exported output: \")\ndisplay(widgets.HBox([dropdown_label, dropdown_field]))", "_____no_output_____" ], [ "path_to_selected_exported_content = os.path.join(\n export_folder,\n dropdown_field.value\n)\n\nprint(\"Working with directory \" + path_to_selected_exported_content)", "_____no_output_____" ] ], [ [ "## Load containers", "_____no_output_____" ] ], [ [ "path_to_containers = os.path.join(\n path_to_selected_exported_content,\n \"containers.csv\"\n)\nprint(f\"Opening {path_to_containers}\")\ndf_containers = pd.read_csv(path_to_containers, index_col=\"id\", dtype={\n \"delivered_by_truck\": \"Int64\",\n \"picked_up_by_truck\": \"Int64\",\n \"delivered_by_large_scheduled_vehicle\": \"Int64\",\n \"picked_up_by_large_scheduled_vehicle\": \"Int64\"\n})\n\ndf_containers", "_____no_output_____" ] ], [ [ "Check number of large scheduled vehicles (deep sea vessels, feeders, barges, and trains).", "_____no_output_____" ] ], [ [ "df_containers.groupby(by=\"delivered_by_large_scheduled_vehicle\").count()", "_____no_output_____" ] ], [ [ "## Load scheduled vehicles\n\nLoad the vehicles to enrich the information regarding the arrival and departure of the containers.", "_____no_output_____" ] ], [ [ "path_to_deep_sea_vessels = os.path.join(\n path_to_selected_exported_content,\n \"deep_sea_vessels.csv\"\n)\n\npath_to_feeders = os.path.join(\n path_to_selected_exported_content,\n \"feeders.csv\"\n)\n\npath_to_barges = os.path.join(\n path_to_selected_exported_content,\n \"barges.csv\"\n)\n\npath_to_trains = os.path.join(\n path_to_selected_exported_content,\n \"trains.csv\"\n)\n\nscheduled_vehicle_file_paths = {\n \"deep_sea_vessels\": path_to_deep_sea_vessels,\n \"feeders\": path_to_feeders,\n \"barges\": path_to_barges,\n \"trains\": path_to_trains\n}\n\nfor name, path in scheduled_vehicle_file_paths.items():\n print(\"Check file exists for vehicle \" + name + \".\")\n assert os.path.isfile(path)\n\nprint(\"All files exist.\")", "_____no_output_____" ], [ "for name, path in list(scheduled_vehicle_file_paths.items()):\n print(\"Check file size for vehicle \" + name)\n size_in_bytes = os.path.getsize(path)\n if size_in_bytes <= 4:\n print(\" This file is empty, ignoring it in the analysis from now on\")\n del scheduled_vehicle_file_paths[name]", "_____no_output_____" ], [ "scheduled_vehicle_dfs = {\n name: pd.read_csv(path, index_col=0, parse_dates=[\"scheduled_arrival\"])\n for name, path in scheduled_vehicle_file_paths.items()\n}\n\nfor name, df in scheduled_vehicle_dfs.items():\n display(Markdown(\"#### \" + name))\n scheduled_vehicle_dfs[name][\"vehicle_type\"] = name\n display(scheduled_vehicle_dfs[name].sort_values(by=\"scheduled_arrival\"))", "_____no_output_____" ], [ "df_large_scheduled_vehicle = pd.concat(\n scheduled_vehicle_dfs.values()\n)\ndf_large_scheduled_vehicle.sort_index(inplace=True)\ndf_large_scheduled_vehicle.info()\ndf_large_scheduled_vehicle", "_____no_output_____" ] ], [ [ "Plot arrival pattern.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(15, 3))\n\nx, y, z = [], [], []\ny_axis = []\n\ny_scaling_factor = 2\n\nfor i, (name, df) in enumerate(scheduled_vehicle_dfs.items()):\n y_axis.append((i/y_scaling_factor, name))\n if len(df) == 0:\n continue\n arrivals_and_capacity = df[[\"scheduled_arrival\", \"moved_capacity\"]]\n for _, row in arrivals_and_capacity.iterrows():\n event = row[\"scheduled_arrival\"]\n moved_capacity = row[\"moved_capacity\"]\n x.append(event)\n y.append(i / y_scaling_factor)\n z.append(moved_capacity / 20)\n\nplt.xticks(rotation=45)\nplt.yticks(*list(zip(*y_axis)))\nplt.scatter(x, y, s=z, color='gray')\nplt.ylim([-0.5, 1.5])\nplt.show()", "_____no_output_____" ] ], [ [ "Transform data to check how many containers are delivered and picked up by which vehicle.", "_____no_output_____" ] ], [ [ "vehicle_to_teu_to_deliver = {}\nvehicle_to_teu_to_pickup = {}\n\nfor i, container in df_containers.iterrows():\n teu = container[\"length\"] / 20\n assert 1 <= teu <= 2.5\n\n if container[\"delivered_by\"] != \"truck\":\n vehicle = container[\"delivered_by_large_scheduled_vehicle\"]\n if vehicle not in vehicle_to_teu_to_deliver.keys():\n vehicle_to_teu_to_deliver[vehicle] = 0\n vehicle_to_teu_to_deliver[vehicle] += teu\n\n if container[\"picked_up_by\"] != \"truck\":\n vehicle = container[\"picked_up_by_large_scheduled_vehicle\"]\n if vehicle not in vehicle_to_teu_to_pickup.keys():\n vehicle_to_teu_to_pickup[vehicle] = 0\n vehicle_to_teu_to_pickup[vehicle] += teu\n\nvehicle_to_teu_to_deliver, vehicle_to_teu_to_pickup", "_____no_output_____" ] ], [ [ "Add transformed data to vehicles.", "_____no_output_____" ] ], [ [ "s_delivery = pd.Series(vehicle_to_teu_to_deliver)\ns_pickup = pd.Series(vehicle_to_teu_to_pickup)\ndf_large_scheduled_vehicle[\"capacity_delivery\"] = s_delivery\ndf_large_scheduled_vehicle[\"capacity_pickup\"] = s_pickup\ndf_large_scheduled_vehicle", "_____no_output_____" ], [ "for large_scheduled_vehicle_id in df_large_scheduled_vehicle.index:\n delivered_teu = vehicle_to_teu_to_deliver.get(large_scheduled_vehicle_id, 0)\n picked_up_teu = vehicle_to_teu_to_pickup.get(large_scheduled_vehicle_id, 0)\n capacity_in_teu = df_large_scheduled_vehicle.loc[large_scheduled_vehicle_id, \"capacity_in_teu\"]\n assert delivered_teu <= capacity_in_teu, f\"{delivered_teu} is more than {capacity_in_teu} for vehicle \"\\\n f\"with id {large_scheduled_vehicle_id}\"\n assert picked_up_teu <= capacity_in_teu, f\"{picked_up_teu} is more than {capacity_in_teu} for vehicle \"\\\n f\"with id {large_scheduled_vehicle_id}\"", "_____no_output_____" ] ], [ [ "## Load trucks", "_____no_output_____" ] ], [ [ "path_to_trucks = os.path.join(\n path_to_selected_exported_content,\n \"trucks.csv\"\n)\nassert os.path.isfile(path_to_trucks)", "_____no_output_____" ], [ "df_truck = pd.read_csv(\n path_to_trucks, index_col=0,\n parse_dates=[\n # Pickup\n \"planned_container_pickup_time_prior_berthing\",\n \"realized_container_pickup_time\",\n\n # Delivery\n \"planned_container_delivery_time_at_window_start\",\n \"realized_container_delivery_time\"\n ])\ndf_truck", "_____no_output_____" ], [ "assert len(df_truck[df_truck[\"picks_up_container\"] & pd.isna(df_truck[\"realized_container_pickup_time\"])]) == 0, \\\n \"If a truck picks up a container, it should always have a realized container pickup time\"\n\nassert len(df_truck[df_truck[\"delivers_container\"] & pd.isna(df_truck[\"realized_container_delivery_time\"])]) == 0, \\\n \"If a truck deliver a container, it should always have a realized container delivery time\"\n\nassert len(df_truck[~(df_truck[\"delivers_container\"] | df_truck[\"picks_up_container\"])]) == 0, \\\n \"There is no truck that neither delivers or picks up a container\"", "_____no_output_____" ] ], [ [ "This is the probability of the truck to show up at any given hour of the week (by index).", "_____no_output_____" ] ], [ [ "delivered_and_picked_up_by_large_vessels_df = df_containers.loc[\n ~pd.isna(df_containers[\"picked_up_by_large_scheduled_vehicle\"])\n].join(\n df_large_scheduled_vehicle, on=\"picked_up_by_large_scheduled_vehicle\", rsuffix=\"_picked_up\"\n).loc[\n ~pd.isna(df_containers[\"delivered_by_large_scheduled_vehicle\"])\n].join(\n df_large_scheduled_vehicle, on=\"delivered_by_large_scheduled_vehicle\", rsuffix=\"_delivered_by\"\n)\n\ndelivered_and_picked_up_by_large_vessels_df", "_____no_output_____" ], [ "dwell_time = (\n delivered_and_picked_up_by_large_vessels_df[\"scheduled_arrival\"]\n - delivered_and_picked_up_by_large_vessels_df[\"scheduled_arrival_delivered_by\"]\n)\ndwell_time.describe()", "_____no_output_____" ], [ "dwell_time.astype(\"timedelta64[h]\").plot.hist(bins=30, color=\"gray\")\nplt.xlabel(\"Hours between delivery and onward transportation (except trucks)\")\nplt.ylabel(\"Number container\")\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d072ce8f96fb3cf84222d7786b57b2a6fa34cf90
126,520
ipynb
Jupyter Notebook
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
13d0579addd133eb4e4285b0857750f908fc0380
[ "MIT" ]
1
2020-04-04T02:29:01.000Z
2020-04-04T02:29:01.000Z
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
13d0579addd133eb4e4285b0857750f908fc0380
[ "MIT" ]
null
null
null
Formula One World Championship Analysis.ipynb
mbadamve/Machine-Learning-projects
13d0579addd133eb4e4285b0857750f908fc0380
[ "MIT" ]
null
null
null
50.446571
665
0.617057
[ [ [ "# 2019 Formula One World Championship\n\n\n<div style=\"text-align: justify\">\n \n A Formula One season consists of a series of races, known as Grands Prix (French for ''grand prizes' or 'great prizes''), which take place worldwide on purpose-built circuits and on public roads. The results of each race are evaluated using a points system to determine two annual World Championships: one for drivers, the other for constructors. Drivers must hold valid Super Licences, the highest class of racing licence issued by the FIA. The races must run on tracks graded \"1\" (formerly \"A\"), the highest grade-rating issued by the FIA.Most events occur in rural locations on purpose-built tracks, but several events take place on city streets.\nThere are a number of F1 races coming up:\n\nSingapore GP: Date: Sun, Sep 22, 8:10 AM\n\nRussian GP: Date: Sun, Sep 29, 7:10 AM\n\nJapanese GP: Date: Sun, Oct 13, 1:10 AM\n\nMexican GP Date: Sun, Oct 13, 1:10 AM\n\nThe Singaporean Grand Prix this weekend and the Russian Grand Prix the weekend after, as you can see here.\n\nThe 2019 driver standings are given here. Given these standings:\n\n</div>\n", "_____no_output_____" ], [ "# Lets Answer few fun questions?\n", "_____no_output_____" ] ], [ [ "#A Probability Distribution; an {outcome: probability} mapping.\n# Make probabilities sum to 1.0; assert no negative probabilities\n\nclass ProbDist(dict):\n \"\"\"A Probability Distribution; an {outcome: probability} mapping.\"\"\"\n def __init__(self, mapping=(), **kwargs):\n self.update(mapping, **kwargs)\n \n total = sum(self.values()) \n for outcome in self:\n self[outcome] = self[outcome] / total\n assert self[outcome] >= 0", "_____no_output_____" ], [ "def p(event, space): \n \"\"\"The probability of an event, given a sample space of outcomes. \n event: a collection of outcomes, or a predicate that is true of outcomes in the event. \n space: a set of outcomes or a probability distribution of {outcome: frequency} pairs.\"\"\"\n \n # if event is a predicate it, \"unroll\" it as a collection \n if is_predicate(event):\n event = such_that(event, space)\n \n # if space is not an equiprobably collection (a simple set), \n # but a probability distribution instead (a dictionary set),\n # then add (union) the probabilities for all favorable outcomes\n if isinstance(space, ProbDist):\n return sum(space[o] for o in space if o in event)\n \n # simplest case: what we played with in our previous lesson\n else:\n return Fraction(len(event & space), len(space))\n\nis_predicate = callable\n\n# Here we either return a simple collection in the case of equiprobable outcomes, or a dictionary collection in the\n# case of non-equiprobably outcomes\ndef such_that(predicate, space): \n \"\"\"The outcomes in the sample pace for which the predicate is true.\n If space is a set, return a subset {outcome,...} with outcomes where predicate(element) is true;\n if space is a ProbDist, return a ProbDist {outcome: frequency,...} with outcomes where predicate(element) is true.\"\"\"\n if isinstance(space, ProbDist):\n return ProbDist({o:space[o] for o in space if predicate(o)})\n else:\n return {o for o in space if predicate(o)}", "_____no_output_____" ] ], [ [ "# Question Set 1\n\nwhat is the Probability Distribution for each F1 driver to win the Singaporean Grand Prix? \n\nWhat is the Probability Distribution for each F1 driver to win both the Singaporean and Russian Grand Prix?\n\nWhat is the probability for Mercedes to win both races?\n\nWhat is the probability for Mercedes to win at least one race?\n\nNote that Mercedes, and each other racing team, has two drivers per race.\n\n", "_____no_output_____" ], [ "\n# Solution ", "_____no_output_____" ], [ "1. what is the Probability Distribution for each F1 driver to win the Singaporean Grand Prix?", "_____no_output_____" ] ], [ [ "SGP = ProbDist(LH=284,VB=221,CL=182,MV=185,SV=169,PG=65,CS=58,AA=34,DR=34,DK=33,NH=31,LN=25,KR=31,SP=27,LS=19,KM=18,RG=8,AG=3,RK=1,\n GR=0)\nprint (\"The probability of each driver winnning Singaporean Grand Prix \")\nSGP #Driver standing divided by / total of all driver standings, SGP returns total probability as 1", "The probability of each driver winnning Singaporean Grand Prix \n" ] ], [ [ " 2. What is the Probability Distribution for each F1 driver to win both the Singaporean and Russian Grand Prix?", "_____no_output_____" ] ], [ [ "SGP = ProbDist(\n LH=284,VB=221,CL=182,MV=185,SV=169,PG=65,CS=58,AA=34,DR=34,DK=33,NH=31,LN=25,KR=31,SP=27,LS=19,KM=18,\n RG=8,AG=3,RK=1,GR=0) # data taken on saturday before race starts for Singapore \n\nRGP = ProbDist(\n LH=296,VB=231,CL=200,MV=200,SV=194,PG=69,CS=58,AA=42,DR=34,DK=33,NH=33,LN=31,KR=31,SP=27,LS=19,KM=18,\n RG=8,AG=4,RK=1,GR=0) # data taken on saturday before race starts for Russia", "_____no_output_____" ], [ "#perfoms joint probabilities on SGP and RGP probability distributions\ndef joint(A, B, sep=''):\n \"\"\"The joint distribution of two independent probability distributions. \n Result is all entries of the form {a+sep+b: P(a)*P(b)}\"\"\"\n return ProbDist({a + sep + b: A[a] * B[b]\n for a in A\n for b in B})\n\nbothSGPRGP= joint(SGP, RGP, ' ')\nprint (\"The probability of each driver winnning Singaporean Grand Prix and Russian Grand Prix\")\nbothSGPRGP", "The probability of each driver winnning Singaporean Grand Prix and Russian Grand Prix\n" ] ], [ [ "3. What is the probability for Mercedes to win both races?", "_____no_output_____" ] ], [ [ "def mercedes_T(outcome): return outcome == \"VB\" or outcome == \"LH\"\nmercedesWinningSGPRace = p(mercedes_T, SGP)\n#calculate probability of mercedes winning Singapore Frand Pix", "_____no_output_____" ], [ "def mercedes_T(outcome): return outcome == \"VB\" or outcome == \"LH\"\nmercedesWinningRGPRace = p(mercedes_T, RGP)\n#calculate probability of mercedes winning Russia Grand Pix", "_____no_output_____" ], [ "print (\"The probability of mercedes winnning both the races \")\nmercedesWinningBothRaces = mercedesWinningRGPRace * mercedesWinningSGPRace\nmercedesWinningBothRaces\n#probability of two events occurring together as independent events (P1 * P2)= P", "The probability of mercedes winnning both the races \n" ] ], [ [ "4. What is the probability for Mercedes to win at least one race?", "_____no_output_____" ] ], [ [ "def p(event, space): \n \"\"\"The probability of an event, given a sample space of outcomes. \n event: a collection of outcomes, or a predicate that is true of outcomes in the event. \n space: a set of outcomes or a probability distribution of {outcome: frequency} pairs.\"\"\"\n \n # if event is a predicate it, \"unroll\" it as a collection \n if is_predicate(event):\n event = such_that(event, space)\n \n # if space is not an equiprobably collection (a simple set), \n # but a probability distribution instead (a dictionary set),\n # then add (union) the probabilities for all favorable outcomes\n if isinstance(space, ProbDist):\n return sum(space[o] for o in space if o in event)\n \n # simplest case: what we played with in our previous lesson\n else:\n return Fraction(len(event & space), len(space))\n\nis_predicate = callable\n\n# Here we either return a simple collection in the case of equiprobable outcomes, or a dictionary collection in the\n# case of non-equiprobably outcomes\ndef such_that(predicate, space): \n \"\"\"The outcomes in the sample pace for which the predicate is true.\n If space is a set, return a subset {outcome,...} with outcomes where predicate(element) is true;\n if space is a ProbDist, return a ProbDist {outcome: frequency,...} with outcomes where predicate(element) is true.\"\"\"\n if isinstance(space, ProbDist):\n return ProbDist({o:space[o] for o in space if predicate(o)})\n else:\n return {o for o in space if predicate(o)}", "_____no_output_____" ], [ "mercedesWinningAtleastOneRace = mercedesWinningBothRaces + (mercedesWinningRGPRace * (1 - mercedesWinningSGPRace))+mercedesWinningSGPRace * (1 - mercedesWinningRGPRace)\nprint (\"The probability of mercedes winnning at least one of the races \")\nmercedesWinningAtleastOneRace\n#probability of an event occurring at least once, it will be the complement of the probability of the event never occurring.", "The probability of mercedes winnning at least one of the races \n" ] ], [ [ "# Question Set 2\n If Mercedes wins the first race, what is the probability that Mercedes wins the next one? \nIf Mercedes wins at least one of these two races, what is the probability Mercedes wins both races? \nHow about Ferrari, Red Bull, and Renault?\n\n", "_____no_output_____" ], [ "# Solution ", "_____no_output_____" ], [ "If Mercedes wins the first race, what is the probability that Mercedes wins the next one? If Mercedes wins at least one of these two races, what is the probability Mercedes wins both races? How about Ferrari, Red Bull, and Renault?", "_____no_output_____" ] ], [ [ "SGP = ProbDist(\n LH=284,VB=221,CL=182,MV=185,SV=169,PG=65,CS=58,AA=34,DR=34,DK=33,NH=31,LN=25,KR=31,SP=27,LS=19,KM=18,\n RG=8,AG=3,RK=1,GR=0)\n\nRGP = ProbDist(\n LH=296,VB=231,CL=200,MV=200,SV=194,PG=69,CS=58,AA=42,DR=34,DK=33,NH=33,LN=31,KR=31,SP=27,LS=19,KM=18,\n RG=8,AG=4,RK=1,GR=0)\nWeather = ProbDist(RA=1, SU=1, SN=1, CL=1, FO=1)", "_____no_output_____" ], [ "def Mercedes_Win_First(outcome): return outcome.startswith('LH') or outcome.startswith('VB') #choose prob of first set", "_____no_output_____" ], [ "def Mercedes_Win_Second(outcome): return outcome.endswith('LH') or outcome.endswith('VB')\np(Mercedes_Win_Second, such_that(Mercedes_Win_First,bothSGPRGP)) #given first race is won, the second will be won", "_____no_output_____" ], [ "def Mercedes_WinBoth(outcome): return 'LH LH' in outcome or 'LH VB' in outcome or 'VB LH' in outcome or 'VB VB' in outcome\ndef Mercedes_Win(outcome): return 'LH' in outcome or 'VB' in outcome\np(Mercedes_WinBoth, such_that(Mercedes_Win,bothSGPRGP)) # (LH,LH VB,VB LH,VB VB,LH) 4 groups to pickup provided first race is won for the both event", "_____no_output_____" ] ], [ [ "If Ferrari wins the first race, what is the probability that Ferrari wins the next one? ", "_____no_output_____" ] ], [ [ "def Ferrari_WinBoth(outcome): return 'CL CL' in outcome or 'CL SV' in outcome or 'SV SV' in outcome or 'SV CL' in outcome\ndef Ferrari_Win(outcome): return 'CL' in outcome or 'SV' in outcome\np(Ferrari_WinBoth, such_that(Ferrari_Win,bothSGPRGP))", "_____no_output_____" ] ], [ [ "If RedBull wins the first race, what is the probability that RedBull wins the next one", "_____no_output_____" ] ], [ [ "def RedBull_WinBoth(outcome): return 'MV MV' in outcome or 'MV AA' in outcome or 'AA AA' in outcome or 'AA MV' in outcome\ndef RedBull_Win(outcome): return 'MV' in outcome or 'AA' in outcome\np(RedBull_WinBoth, such_that(RedBull_Win,bothSGPRGP))", "_____no_output_____" ] ], [ [ "If Renault wins the first race, what is the probability that Renault wins the next one?", "_____no_output_____" ] ], [ [ "def Renault_WinBoth(outcome): return 'DR DR' in outcome or 'DR NH' in outcome or 'NH NH' in outcome or 'NH DR' in outcome\ndef Renault_Win(outcome): return 'DR' in outcome or 'NH' in outcome\np(Renault_WinBoth, such_that(Renault_Win,bothSGPRGP))", "_____no_output_____" ] ], [ [ "# Question Set 3\n\nMercedes wins one of these two races on a rainy day. \nWhat is the probability Mercedes wins both races, assuming races can be held on either rainy, sunny, cloudy, snowy or foggy days? \nAssume that rain, sun, clouds, snow, and fog are the only possible weather conditions on race tracks.", "_____no_output_____" ], [ "# Solution ", "_____no_output_____" ], [ "Mercedes wins one of these two races on a rainy day. What is the probability Mercedes wins both races, assuming races can be held on either rainy, sunny, cloudy, snowy or foggy days? Assume that rain, sun, clouds, snow, and fog are the only possible weather conditions on race tracks.", "_____no_output_____" ] ], [ [ "#create Probability Distribution for given Weather Condtions wher p(weather) will be 0.20\nGivenFiveWeatherConditons = ProbDist(\nRainyDay=1,\nSunnyDay=1,\nCloudyDay=1,\nSnowyDay=1,\nFoggyDay=1\n)\nGivenFiveWeatherConditons", "_____no_output_____" ], [ "#perfoms joint probabilities on SGP & weather and RGP & weather probability distributions Respectively\ndef joint(A, B, A1, B1, sep=''):\n \"\"\"The joint distribution of two independent probability distributions. \n Result is all entries of the form {a+sep+b: P(a)*P(b)}\"\"\"\n return ProbDist({a + sep + a1 + sep + b + sep + b1: A[a] * B[b] *A1[a1] * B1[b1]\n for a in A\n for b in B\n for a1 in A1\n for b1 in B1})\n\nbothSGPRGPWeather= joint(SGP, RGP, GivenFiveWeatherConditons,GivenFiveWeatherConditons, ' ')\nbothSGPRGPWeather", "_____no_output_____" ], [ "def Mercedes_Wins_Race_On_Any_Rainy(outcome): return ('LH R' in outcome or 'VB R' in outcome)\nsuch_that(Mercedes_Wins_Race_On_Any_Rainy, bothSGPRGPWeather)\n", "_____no_output_____" ], [ "def Mercedes_Wins_Race_On_Both_Rain(outcome): return ('LH' in outcome and 'VB' in outcome) or (outcome.count('LH')==2 ) or (outcome.count('VB')==2 )\np(Mercedes_Wins_Race_On_Both_Rain, such_that(Mercedes_Wins_Race_On_Any_Rainy, bothSGPRGPWeather))", "_____no_output_____" ] ], [ [ "End!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
d072d9b17a3a4ec06d0e5fc8cf332d73a68eac7d
18,316
ipynb
Jupyter Notebook
notebooks/ANN.ipynb
HausReport/ClubRaiders
88bd64d2512302ca2b391b48979b6e88b092eb92
[ "BSD-3-Clause" ]
null
null
null
notebooks/ANN.ipynb
HausReport/ClubRaiders
88bd64d2512302ca2b391b48979b6e88b092eb92
[ "BSD-3-Clause" ]
2
2020-05-28T13:30:08.000Z
2020-06-02T14:12:04.000Z
notebooks/ANN.ipynb
HausReport/ClubRaiders
88bd64d2512302ca2b391b48979b6e88b092eb92
[ "BSD-3-Clause" ]
null
null
null
36.632
224
0.301703
[ [ [ "<a href=\"https://colab.research.google.com/github/HausReport/ClubRaiders/blob/master/ANN.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "import pandas as pd\nfrom typing import List\nfrom datetime import datetime\nfrom random import randint\nfrom dateutil.relativedelta import *\n", "_____no_output_____" ], [ " factionName: List[str] = []\n systemName: List[str] = []\n population: List[int] = []\n influence: List[float] = []\n updated: List[datetime] = []", "_____no_output_____" ], [ "factionName: List[str] = []\nsystemName: List[str] = []\npopulation: List[int] = []\ninfluence: List[float] = []\nupdated: List[datetime] = []\n \nrandStrs = ['foo', 'bar', 'guh']\n\ndef randStr() -> str:\n global randStrs\n return randStrs[randint(0, len(randStrs))]\n\ndef seqStr(i: int) -> str:\n global randStrs\n return randStrs[i % len(randStrs)]\n\nstart_date = datetime.strptime(\"2020-06-01\", \"%Y-%m-%d\")\n\n\nfor fac in ['foo','bar','guh']:\n upd = start_date\n for sys in ['sol','celeano']:\n for i in range(0,5):\n factionName.append( fac)\n systemName.append( sys)\n population.append(10000)\n influence.append(.33)\n\n day = randint(2,4)\n upd = upd + relativedelta(hours=day*8)\n updated.append(upd)\n\n\ndata = { 'systemName' : systemName,\n 'factionName' : factionName,\n 'population' : population,\n 'influence' : influence,\n 'updated' : updated\n }\ndf = pd.DataFrame(data = data)\n", "_____no_output_____" ], [ "# prepare data\n\ndf['updated'] = df.updated.dt.round(\"D\") \ndf = df.sort_values(by=['systemName', 'factionName','updated'])\n\n# this drops out all data that doesn't have at least 2 days in a row\nsystems = df['systemName'].unique().tolist()\nholder = pd.DataFrame()\n\nfor sys in systems:\n print(sys)\n sysSlice = df[ df['systemName'] ==sys]\n facs = sysSlice['factionName'].unique().tolist()\n for fac in facs:\n print(\"\\t\"+ fac)\n facSlice = sysSlice[ sysSlice['factionName'] == fac].reset_index()\n facSlice['diff1'] = facSlice.updated.diff(periods=1).dt.days.abs()\n facSlice['diff2'] = facSlice.updated.diff(periods=-1).dt.days.abs()\n facSlice = facSlice.fillna(999.0) \n facSlice['diffz'] = facSlice[['diff1','diff2']].min(axis=1)\n facSlice = facSlice[ facSlice['diffz'] <=1.0]\n facSlice = facSlice.drop(['diff1','diff2','diffz'], axis=1)\n holder = holder.append(facSlice.copy(), ignore_index=True)\n\n\nholder", "celeano\n\tbar\n\tfoo\n\tguh\nsol\n\tbar\n\tfoo\n\tguh\n" ], [ "def minAbs(x1: float, x2: float) -> float:\n return min ( abs(x1), abs(x2))", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
d0730b4d515e68abf15e499b007203b3baef7083
9,839
ipynb
Jupyter Notebook
Copy_of_Workshop2Final.ipynb
feliz10/papus
f4539d5819cee8a610b4abf2d92662de37072c58
[ "MIT" ]
null
null
null
Copy_of_Workshop2Final.ipynb
feliz10/papus
f4539d5819cee8a610b4abf2d92662de37072c58
[ "MIT" ]
null
null
null
Copy_of_Workshop2Final.ipynb
feliz10/papus
f4539d5819cee8a610b4abf2d92662de37072c58
[ "MIT" ]
null
null
null
21.38913
234
0.42423
[ [ [ "<a href=\"https://colab.research.google.com/github/feliz10/papus/blob/master/Copy_of_Workshop2Final.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# WELCOME BACK TO SACNAS' PYTHON WORKSHOP \nhosted by Luis and Emily\n", "_____no_output_____" ], [ "### Introduction:\nSign in and grab food! \n### Import the necessary libraries/packages:\nThere are tools you can download into your code to implement. Think of these like your toolbox, to create plots, analyze data, and endless possibilities \n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\n\n# visualization libraries\nimport matplotlib.pyplot as plt\n\n", "_____no_output_____" ] ], [ [ "### Import data and assign it to a variable called tips", "_____no_output_____" ] ], [ [ "url = 'https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/07_Visualization/Tips/tips.csv'\n", "_____no_output_____" ] ], [ [ "# .describe()\nGenerate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset’s distribution, excluding NaN values.\n\n", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "# For loops \na for-loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly. ", "_____no_output_____" ] ], [ [ "x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", "_____no_output_____" ] ], [ [ "# Working with our dataset\n\nRecap on worksheet. ", "_____no_output_____" ], [ "### What day are people more likely to tip?\n", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "\n", "_____no_output_____" ] ], [ [ "### How can we automate a print statement using a For loop?", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "### How do we store these values? ", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "### Lists, Arrays , Dictionaries \n", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "### Plotting a bar graph\n\nparameters are what you need inside the paranthesis for the function you are calling to work. \n\nplt.bar(x coordinate, height)", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "### Who tips more? Smokers or non smokers?", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "\n\n\n\n### Who tips more? Women or Men\n", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "### Plot the total_bill column using a histogram", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "### Create a scatter plot presenting the relationship between total_bill and tip\n\n---\n\n", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "### Create one plot with the relationship of size and tip.", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0730d791052f0e282dfc4bfc7cb3e1b934f2df2
276,151
ipynb
Jupyter Notebook
Model/99_kaggle_credit_card_analysis_and_prediction.ipynb
skawns0724/KOSA-Big-Data_Vision
af123dfe0a82a82795bb6732285c390be86e83b7
[ "MIT" ]
1
2021-09-24T20:55:35.000Z
2021-09-24T20:55:35.000Z
Model/99_kaggle_credit_card_analysis_and_prediction.ipynb
skawns0724/KOSA-Big-Data_Vision
af123dfe0a82a82795bb6732285c390be86e83b7
[ "MIT" ]
null
null
null
Model/99_kaggle_credit_card_analysis_and_prediction.ipynb
skawns0724/KOSA-Big-Data_Vision
af123dfe0a82a82795bb6732285c390be86e83b7
[ "MIT" ]
7
2021-09-13T02:13:30.000Z
2021-09-23T01:26:38.000Z
117.56109
17,081
0.829097
[ [ [ "<a href=\"https://colab.research.google.com/github/JSJeong-me/KOSA-Big-Data_Vision/blob/main/Model/99_kaggle_credit_card_analysis_and_prediction.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Importing Packages", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nimport os\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.metrics import confusion_matrix,ConfusionMatrixDisplay,classification_report,plot_roc_curve,accuracy_score\npd.set_option('display.max_columns',25)\nwarnings.filterwarnings('ignore')", "/usr/local/lib/python3.7/dist-packages/sklearn/externals/six.py:31: FutureWarning: The module is deprecated in version 0.21 and will be removed in version 0.23 since we've dropped support for Python 2.7. Please rely on the official version of six (https://pypi.org/project/six/).\n \"(https://pypi.org/project/six/).\", FutureWarning)\n/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.neighbors.base module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.neighbors. Anything that cannot be imported from sklearn.neighbors is now part of the private API.\n warnings.warn(message, FutureWarning)\n" ], [ "# Importing Dataset\ndata = pd.read_csv(r'./credit_cards_dataset.csv')\ndata.head(10)", "_____no_output_____" ], [ "data.info()\n#info shows that there is no null values and all the features are numeric", "_____no_output_____" ], [ "data.describe(include='all') # Descriptive analysis", "_____no_output_____" ], [ "data.rename(columns={'PAY_0':'PAY_1','default.payment.next.month':'def_pay'},inplace=True) \n#rename few columns", "_____no_output_____" ] ], [ [ "# Exploratory Data Analysis", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,6))\ndata.groupby('def_pay')['AGE'].hist(legend=True)\nplt.show()\n#here we can see that, between age 20 to 45 most of the people will fall into..", "_____no_output_____" ], [ "sns.distplot(data['AGE'])\nplt.title('Age Distribution')", "_____no_output_____" ], [ "sns.boxplot('def_pay','LIMIT_BAL',data=data)", "_____no_output_____" ], [ "data[data['LIMIT_BAL']>700000].sort_values(ascending=False,by='LIMIT_BAL')", "_____no_output_____" ], [ "data[data['LIMIT_BAL']>700000].value_counts().sum()", "_____no_output_____" ], [ "plt.figure(figsize=(16,5))\nplt.subplot(121)\nsns.boxplot(x='SEX', y= 'AGE',data = data)\nsns.stripplot(x='SEX', y= 'AGE',data = data,linewidth = 0.9)\nplt.title ('Sex vs AGE')\n\nplt.subplot(122)\nax = sns.countplot(x='EDUCATION',data = data, order= data['EDUCATION'].value_counts().index)\nplt.title ('EDUCATION')\nlabels = data['EDUCATION'].value_counts()\nfor i, v in enumerate(labels):\n ax.text(i,v+100,v, horizontalalignment='center')\nplt.show()", "_____no_output_____" ], [ "plt.figure(figsize=(20,5))\nplt.subplot(121)\nsns.boxplot(x='def_pay', y= 'AGE',data = data)\nsns.stripplot(x='def_pay', y= 'AGE',data = data,linewidth = 0.9)\nplt.title ('Age vs def_pay')\n\nax2=plt.subplot(1,2,2)\npay_edu = data.groupby('EDUCATION')['def_pay'].value_counts(normalize=True).unstack()\npay_edu = pay_edu.sort_values(ascending=False,by=1)\npay_edu.plot(kind='bar',stacked= True,color=[\"#3f3e6fd1\", \"#85c6a9\"], ax = ax2)\nplt.legend(loc=(1.04,0))\nplt.title('Education vs def_pay')\nplt.show()", "_____no_output_____" ], [ "# function for Multivariate analysis\n# This method is used to show point estimates and confidence intervals using scatter plot graphs\ndef plotfig(df1,col11,col22,deft1):\n plt.figure(figsize=(16,6))\n\n plt.subplot(121)\n sns.pointplot(df1[col11], df1[deft1],hue = df1[col22])\n\n plt.subplot(122)\n sns.countplot(df1[col11], hue = df1[col22])\n plt.show() \n\n\ndef varplot(df2, col1, col2, deft, bin=3, unique=10):\n df=df2.copy()\n if len(df[col1].unique())>unique:\n df[col1+'cut']= pd.qcut(df[col1],bin)\n if len(df[col2].unique())>unique:\n df[col2+'cut']= pd.qcut(df[col2],bin)\n return plotfig(df,col1+'cut',col2+'cut',deft)\n else:\n df[col2+'cut']= df[col2]\n return plotfig(df,col1+'cut',col2+'cut',deft)\n else:\n return plotfig(df,col1,col2,deft)", "_____no_output_____" ], [ "varplot(data,'AGE','SEX','def_pay',3)", "_____no_output_____" ], [ "varplot(data,'LIMIT_BAL','AGE','def_pay',3)", "_____no_output_____" ], [ "# Univariate Analysis\ndf = data.drop('ID',1)\nnuniq = df.nunique()\ndf = data[[col for col in df if nuniq[col]>1 and nuniq[col]<50]]\nrow, cols = df.shape\ncolnames = list(df)\ngraph_perrow = 5\ngraph_row = (cols+graph_perrow-1)/ graph_perrow\nmax_graph = 20\nplt.figure(figsize=(graph_perrow*12,graph_row*8))\nfor i in range(min(cols,max_graph)):\n plt.subplot(graph_row,graph_perrow,i+1)\n coldf = df.iloc[:,i]\n if (not np.issubdtype(type(coldf),np.number)):\n sns.countplot(colnames[i],data= df, order= df[colnames[i]].value_counts().index)\n else:\n coldf.hist()\n plt.title(colnames[i])\nplt.show()", "_____no_output_____" ], [ "cont_var = df.select_dtypes(exclude='object').columns\nnrow = (len(cont_var)+5-1)/5\nplt.figure(figsize=(12*5,6*2))\nfor i,j in enumerate(cont_var):\n plt.subplot(nrow,5,i+1)\n sns.distplot(data[j])\nplt.show()", "_____no_output_____" ], [ "# from the above,we can see that we have maximum clients from 20-30 age group followed by 31-40. \n# Hence with increasing age group the number of clients that will default the payment next month is decreasing. \n# Hence we can see that Age is important feature to predict the default payment for next month.", "_____no_output_____" ], [ "plt.subplots(figsize=(26,20))\ncorr = data.corr()\nsns.heatmap(corr,annot=True)\nplt.show()", "_____no_output_____" ], [ "from statsmodels.stats.outliers_influence import variance_inflation_factor\ndf= data.drop(['def_pay','ID'],1)\nvif = pd.DataFrame()\nvif['Features']= df.columns\nvif['vif']= [variance_inflation_factor(df.values,i) for i in range(df.shape[1])]\nvif", "_____no_output_____" ], [ "# From this heatmap and VIF we can see that there are some multicolinearity(values >10) in the data which we can handle\n# simply doing feature engineering of some columns \n\nbill_tot = pd.DataFrame(data['BILL_AMT1']+data['BILL_AMT2']+data['BILL_AMT3']+data['BILL_AMT4']+data['BILL_AMT5']+data['BILL_AMT6'],columns=['bill_tot'])\npay_tot =pd.DataFrame(data['PAY_1']+data['PAY_2']+data['PAY_3']+data['PAY_4']+data['PAY_5']+data['PAY_6'],columns=['pay_tot'])\npay_amt_tot = pd.DataFrame(data['PAY_AMT1']+data['PAY_AMT2']+data['PAY_AMT3']+data['PAY_AMT4']+data['PAY_AMT5']+data['PAY_AMT6'],columns=['pay_amt_tot'])\nframes=[bill_tot,pay_tot,pay_amt_tot,data['def_pay']]\ntot = pd.concat(frames,axis=1)\n", "_____no_output_____" ], [ "plt.figure(figsize=(20,4))\nplt.subplot(131)\nsns.boxplot(x='def_pay',y='pay_tot',data = tot)\nsns.stripplot(x='def_pay',y='pay_tot',data = tot,linewidth=1)\n\nplt.subplot(132)\nsns.boxplot(x='def_pay', y='bill_tot',data=tot)\nsns.stripplot(x='def_pay', y='bill_tot',data=tot,linewidth=1)\n\nplt.subplot(133)\nsns.boxplot(x='def_pay', y='pay_amt_tot',data=tot)\nsns.stripplot(x='def_pay', y='pay_amt_tot',data=tot,linewidth=1)\nplt.show()", "_____no_output_____" ], [ "sns.pairplot(tot[['bill_tot','pay_amt_tot','pay_tot','def_pay']],hue='def_pay')\nplt.show()", "_____no_output_____" ], [ "sns.violinplot(x=tot['def_pay'], y= tot['bill_tot'])", "_____no_output_____" ], [ "tot.drop('def_pay',1,inplace=True)", "_____no_output_____" ], [ "data1 = pd.concat([data,tot],1)", "_____no_output_____" ], [ "data1.groupby('def_pay')['EDUCATION'].hist(legend=True)\nplt.show()", "_____no_output_____" ], [ "data1.groupby('def_pay')['AGE'].hist()\nplt.figure(figsize=(12,6))", "_____no_output_____" ], [ "# we know that the Bill_AMT is the most correlated column so using that we create a data\ndf= pd.concat([bill_tot,df],1)\ndf1 = df.drop(['BILL_AMT1','BILL_AMT2','BILL_AMT3','BILL_AMT4','BILL_AMT5','BILL_AMT6'],1)", "_____no_output_____" ], [ "vif = pd.DataFrame()\nvif['Features']= df1.columns\nvif['vif']= [variance_inflation_factor(df1.values,i) for i in range(df1.shape[1])]\nvif", "_____no_output_____" ], [ "# above we can see that now our data doesnt have multicollinearty(no values >10)", "_____no_output_____" ], [ "data2 = df1.copy()", "_____no_output_____" ], [ "# using the above plot we can create age bins\nage = [20,27,32,37,42,48,58,64,80]\nlab = [8,7,6,5,4,3,2,1]\ndata2['AGE'] = pd.cut(data2['AGE'],bins= age,labels=lab)", "_____no_output_____" ], [ "data2 = pd.concat([data2,data['def_pay']],1)\ndata2", "_____no_output_____" ], [ "data2.groupby('def_pay')['AGE'].hist()\nplt.figure(figsize=(12,6))", "_____no_output_____" ], [ "sns.countplot(data2['AGE'])", "_____no_output_____" ], [ "data2.groupby('def_pay')['LIMIT_BAL'].hist(legend=True)\nplt.show()", "_____no_output_____" ], [ "data2.columns", "_____no_output_____" ] ], [ [ "# Model Creation\n#### We know that we have a dataset where we have imbalance in the target variable\n#### you get a pretty high accuracy just by predicting the majority class, but you fail to capture the minority class\n#### which is most often the point of creating the model in the first place.\n#### Hence we try to create more model to get the best results", "_____no_output_____" ] ], [ [ "x= data2.drop(['def_pay'],1)\ny = data2['def_pay']\nx_train,x_test, y_train, y_test = train_test_split(x,y,test_size=0.30, random_state=1)\nsc = StandardScaler()\nx_train = sc.fit_transform(x_train)\nx_test = sc.transform(x_test)", "_____no_output_____" ], [ "# Accuracy is not the best metric to use when evaluating imbalanced datasets as it can be misleading.\n# hence we are using Classification Report and Confusion Matrix\n# function for accuracy and confusion matrix\ndef res(y_test_valid,y_train_valid):\n cm_log = confusion_matrix(y_test,y_test_valid)\n ConfusionMatrixDisplay(cm_log).plot()\n print(classification_report(y_test,y_test_valid))\n print('train_accuracy:',accuracy_score(y_train,y_train_valid))\n print('test_accuracy:',accuracy_score(y_test,y_test_valid))", "_____no_output_____" ] ], [ [ "# Logistic model", "_____no_output_____" ] ], [ [ "log_model= LogisticRegression()\nlog_model.fit(x_train,y_train)\ny_pred_log = log_model.predict(x_test)\ny_pred_train = log_model.predict(x_train)\nres(y_pred_log,y_pred_train)", " precision recall f1-score support\n\n 0 0.81 0.98 0.89 4663\n 1 0.72 0.22 0.34 1337\n\n accuracy 0.81 6000\n macro avg 0.77 0.60 0.61 6000\nweighted avg 0.79 0.81 0.76 6000\n\ntrain_accuracy: 0.8107916666666667\ntest_accuracy: 0.8071666666666667\n" ], [ "plot_roc_curve(log_model,x_test,y_test)\nplt.show()", "_____no_output_____" ], [ "# log model using Threshold\nthreshold = 0.36\ny_log_prob = log_model.predict_proba(x_test)\ny_train_log_prob = log_model.predict_proba(x_train)\ny_log_prob=y_log_prob[:,1]\ny_train_log_prob= y_train_log_prob[:,1]\ny_pred_log_prob = np.where(y_log_prob>threshold,1,0)\ny_pred_log_prob_train = np.where(y_train_log_prob>threshold,1,0)\nres(y_pred_log_prob,y_pred_log_prob_train)", " precision recall f1-score support\n\n 0 0.85 0.93 0.89 4663\n 1 0.64 0.41 0.50 1337\n\n accuracy 0.82 6000\n macro avg 0.74 0.67 0.69 6000\nweighted avg 0.80 0.82 0.80 6000\n\ntrain_accuracy: 0.8137083333333334\ntest_accuracy: 0.8158333333333333\n" ] ], [ [ "# using Decision Tree model", "_____no_output_____" ] ], [ [ "dec_model = DecisionTreeClassifier()\ndec_model.fit(x_train,y_train)\ny_pred_dec = dec_model.predict(x_test)\ny_pred_dec_train = dec_model.predict(x_train)\nres(y_pred_dec,y_pred_dec_train)", " precision recall f1-score support\n\n 0 0.82 0.81 0.81 4663\n 1 0.37 0.40 0.38 1337\n\n accuracy 0.71 6000\n macro avg 0.60 0.60 0.60 6000\nweighted avg 0.72 0.71 0.72 6000\n\ntrain_accuracy: 0.9977083333333333\ntest_accuracy: 0.7146666666666667\n" ] ], [ [ "### Hyper parameter tuning for DecisionTree", "_____no_output_____" ] ], [ [ "parameters = {'max_depth':[1,2,3,4,5,6],'min_samples_split':[3,4,5,6,7],'min_samples_leaf':[1,2,3,4,5,6]}\ntree = GridSearchCV(dec_model, parameters,cv=10)\ntree.fit(x_train,y_train)\ntree.best_params_", "_____no_output_____" ], [ "# We know that Decision tree will have high variance due to which the model overfit hence we can reduce this by \"Pruning\"\n# By using the best parameter from GridSearchCV best parameters\ndec_model1 = DecisionTreeClassifier(max_depth=4,min_samples_split=10,min_samples_leaf=1)\ndec_model1.fit(x_train,y_train)\ny_pred_dec1 = dec_model1.predict(x_test)\ny_pred_dec_train1 = dec_model1.predict(x_train)\nres(y_pred_dec1,y_pred_dec_train1)", " precision recall f1-score support\n\n 0 0.84 0.95 0.89 4663\n 1 0.68 0.35 0.46 1337\n\n accuracy 0.82 6000\n macro avg 0.76 0.65 0.68 6000\nweighted avg 0.80 0.82 0.79 6000\n\ntrain_accuracy: 0.824375\ntest_accuracy: 0.8183333333333334\n" ] ], [ [ "# Random Forest Model", "_____no_output_____" ] ], [ [ "rf_model = RandomForestClassifier(n_estimators=200, criterion='entropy', max_features='log2', max_depth=15, random_state=42)\nrf_model.fit(x_train,y_train)\ny_pred_rf = rf_model.predict(x_test)\ny_pred_rf_train = rf_model.predict(x_train)\n#res(y_pred_rf,y_pred_rf_train)", "_____no_output_____" ], [ "from sklearn.metrics import confusion_matrix\nimport itertools", "_____no_output_____" ], [ "def plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n \n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")", "_____no_output_____" ], [ "cnf_matrix = confusion_matrix(y_test, y_pred_rf)\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=['Non_Default','Default'], normalize=False,\n title='Non Normalized confusion matrix')", "Confusion matrix, without normalization\n[[6647 353]\n [1282 718]]\n" ], [ "from sklearn.metrics import recall_score", "_____no_output_____" ], [ "print(\"Recall score:\"+ str(recall_score(y_test, y_pred_rf)))", "Recall score:0.359\n" ] ], [ [ "### Again hyper parameter tuning for Random Forest", "_____no_output_____" ] ], [ [ "parameters = {'n_estimators':[60,70,80],'max_depth':[1,2,3,4,5,6],'min_samples_split':[3,4,5,6,7],\n 'min_samples_leaf':[1,2,3,4,5,6]}\nclf = GridSearchCV(rf_model, parameters,cv=10)\nclf.fit(x_train,y_train)\nclf.best_params_\n# {'max_depth': 5,\n# 'min_samples_leaf': 4,\n# 'min_samples_split': 3,\n# 'n_estimators': 70}", "_____no_output_____" ], [ "# Decision trees frequently perform well on imbalanced data. so using RandomForest uses bagging of n_trees will be a better idea.\nrf_model = RandomForestClassifier(n_estimators=80, max_depth=6, min_samples_leaf=2, min_samples_split=5)\nrf_model.fit(x_train,y_train)\ny_pred_rf = rf_model.predict(x_test)\ny_pred_rf_train = rf_model.predict(x_train)\n#res(y_pred_rf,y_pred_rf_train)\n\ncnf_matrix = confusion_matrix(y_test, y_pred_rf)\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=['Non_Default','Default'], normalize=False,\n title='Non Normalized confusion matrix')", "Confusion matrix, without normalization\n[[6679 321]\n [1306 694]]\n" ], [ "print(\"Recall score:\"+ str(recall_score(y_test, y_pred_rf)))", "Recall score:0.347\n" ] ], [ [ "# KNN model", "_____no_output_____" ] ], [ [ "# finding the K value\nerror = []\n\nfor i in range(1,21,2):\n knn = KNeighborsClassifier(n_neighbors=i)\n knn.fit(x_train,y_train)\n preds = knn.predict(x_test)\n error.append(np.mean(preds!=y_test))\n\nplt.plot(range(1,21,2), error, linestyle = 'dashed', marker ='o', mfc= 'red')", "_____no_output_____" ], [ "# By using the elbow graph we can see that the k=5 will perform better in the first place so impute k = 5\nknn_model = KNeighborsClassifier(n_neighbors=5)\nknn_model.fit(x_train,y_train)\ny_pred_knn = knn_model.predict(x_test)\ny_pred_knn_train = knn_model.predict(x_train)\n\nres(y_pred_knn,y_pred_knn_train)", " precision recall f1-score support\n\n 0 0.83 0.92 0.87 4663\n 1 0.55 0.34 0.42 1337\n\n accuracy 0.79 6000\n macro avg 0.69 0.63 0.65 6000\nweighted avg 0.77 0.79 0.77 6000\n\ntrain_accuracy: 0.84325\ntest_accuracy: 0.792\n" ] ], [ [ "# SVM Model", "_____no_output_____" ] ], [ [ "# use penalized learning algorithms that increase the cost of classification mistakes on the minority class.\nsvm_model = SVC(class_weight='balanced', probability=True)\nsvm_model.fit(x_train,y_train)\ny_pred_svm = svm_model.predict(x_test)\ny_pred_svm_train = svm_model.predict(x_train)\nres(y_pred_svm,y_pred_svm_train)", " precision recall f1-score support\n\n 0 0.87 0.84 0.85 4663\n 1 0.49 0.56 0.52 1337\n\n accuracy 0.77 6000\n macro avg 0.68 0.70 0.69 6000\nweighted avg 0.79 0.77 0.78 6000\n\ntrain_accuracy: 0.7889583333333333\ntest_accuracy: 0.7745\n" ], [ "# we can see in SVM that our recall of target variable is 0.56 which is the best we ever predicted.", "_____no_output_____" ] ], [ [ "# Naive Bayes", "_____no_output_____" ] ], [ [ "nb_model = GaussianNB()\nnb_model.fit(x_train,y_train)\ny_pred_nb = nb_model.predict(x_test)\ny_pred_nb_train = nb_model.predict(x_train)\nres(y_pred_nb,y_pred_nb_train)", " precision recall f1-score support\n\n 0 0.88 0.78 0.83 4663\n 1 0.45 0.61 0.52 1337\n\n accuracy 0.74 6000\n macro avg 0.66 0.70 0.67 6000\nweighted avg 0.78 0.74 0.76 6000\n\ntrain_accuracy: 0.743375\ntest_accuracy: 0.7448333333333333\n" ], [ "# But here Naive bayes out performs every other model though over accuracy is acceptable, checkout the recall ", "_____no_output_____" ] ], [ [ "# Boosting model XGB Classifier", "_____no_output_____" ] ], [ [ "from xgboost import XGBClassifier\n\nxgb_model = XGBClassifier()\nxgb_model.fit(x_train, y_train)\nxgb_y_predict = xgb_model.predict(x_test)\nxgb_y_predict_train = xgb_model.predict(x_train)\nres(xgb_y_predict,xgb_y_predict_train)", "[00:09:23] WARNING: ../src/learner.cc:1095: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.\n precision recall f1-score support\n\n 0 0.84 0.94 0.89 4663\n 1 0.64 0.35 0.46 1337\n\n accuracy 0.81 6000\n macro avg 0.74 0.65 0.67 6000\nweighted avg 0.79 0.81 0.79 6000\n\ntrain_accuracy: 0.874125\ntest_accuracy: 0.8125\n" ], [ "# Even Boosting technique gives low recall for our target variable", "_____no_output_____" ], [ "# So from the above model we can conclude that the data imbalance is playing a major part \n# Hence we try to fix that by doing ReSample techniques", "_____no_output_____" ] ], [ [ "# Random under-sampling\n### Let’s apply some of these resampling techniques, using the Python library imbalanced-learn.", "_____no_output_____" ] ], [ [ "from collections import Counter\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.over_sampling import RandomOverSampler\nfrom imblearn.under_sampling import TomekLinks", "_____no_output_____" ], [ "x= data2.drop(['def_pay'],1)\ny = data2['def_pay']\n\nrus = RandomUnderSampler(random_state=1)\nx_rus, y_rus = rus.fit_resample(x,y)\n\nprint('original dataset shape:', Counter(y))\nprint('Resample dataset shape', Counter(y_rus))", "original dataset shape: Counter({0: 23364, 1: 6636})\nResample dataset shape Counter({0: 6636, 1: 6636})\n" ], [ "x_train,x_test, y_train, y_test = train_test_split(x_rus,y_rus,test_size=0.20, random_state=1)\nx_train = sc.fit_transform(x_train)\nx_test = sc.transform(x_test)", "_____no_output_____" ], [ "# again we try to predict using Random Forest\nrf_model_rus = RandomForestClassifier(n_estimators=70, max_depth=5, min_samples_leaf=4, min_samples_split=3,random_state=1)\nrf_model_rus.fit(x_train,y_train)\ny_pred_rf_rus = rf_model_rus.predict(x_test)\ny_pred_rf_rus_train = rf_model_rus.predict(x_train)\nres(y_pred_rf_rus,y_pred_rf_rus_train)", " precision recall f1-score support\n\n 0 0.70 0.84 0.76 1364\n 1 0.78 0.62 0.69 1291\n\n accuracy 0.73 2655\n macro avg 0.74 0.73 0.72 2655\nweighted avg 0.74 0.73 0.73 2655\n\ntrain_accuracy: 0.719318074785721\ntest_accuracy: 0.7295668549905838\n" ] ], [ [ "# Random over-sampling", "_____no_output_____" ] ], [ [ "x= data2.drop(['def_pay'],1)\ny = data2['def_pay']\n\nros = RandomOverSampler(random_state=42)\nx_ros, y_ros = ros.fit_resample(x, y)\n\nprint('Original dataset shape', Counter(y))\nprint('Resample dataset shape', Counter(y_ros))", "Original dataset shape Counter({0: 23364, 1: 6636})\nResample dataset shape Counter({1: 23364, 0: 23364})\n" ], [ "x_train,x_test, y_train, y_test = train_test_split(x_ros,y_ros,test_size=0.20, random_state=1)\nx_train = sc.fit_transform(x_train)\nx_test = sc.transform(x_test)", "_____no_output_____" ], [ "rf_model_ros = RandomForestClassifier(n_estimators=70, max_depth=5, min_samples_leaf=4, min_samples_split=3,random_state=1)\nrf_model_ros.fit(x_train,y_train)\ny_pred_rf_ros = rf_model_ros.predict(x_test)\ny_pred_rf_ros_train = rf_model_ros.predict(x_train)\nres(y_pred_rf_ros,y_pred_rf_ros_train)", " precision recall f1-score support\n\n 0 0.67 0.82 0.74 4607\n 1 0.77 0.62 0.69 4739\n\n accuracy 0.71 9346\n macro avg 0.72 0.72 0.71 9346\nweighted avg 0.72 0.71 0.71 9346\n\ntrain_accuracy: 0.7182066235086405\ntest_accuracy: 0.7138882944575219\n" ] ], [ [ "# Under-sampling: Tomek links", "_____no_output_____" ] ], [ [ "x= data2.drop(['def_pay'],1)\ny = data2['def_pay']\n\ntl = TomekLinks(sampling_strategy='majority')\nx_tl, y_tl = tl.fit_resample(x,y)\n\nprint('Original dataset shape', Counter(y))\nprint('Resample dataset shape', Counter(y_tl))", "Original dataset shape Counter({0: 23364, 1: 6636})\nResample dataset shape Counter({0: 21479, 1: 6636})\n" ], [ "x_train,x_test, y_train, y_test = train_test_split(x_tl,y_tl,test_size=0.20, random_state=1)\nx_train = sc.fit_transform(x_train)\nx_test = sc.transform(x_test)", "_____no_output_____" ], [ "rf_model_tl = RandomForestClassifier(n_estimators=70, max_depth=5, min_samples_leaf=4, min_samples_split=3,random_state=1)\nrf_model_tl.fit(x_train,y_train)\ny_pred_rf_tl = rf_model_tl.predict(x_test)\ny_pred_rf_tl_train = rf_model_tl.predict(x_train)\nres(y_pred_rf_tl,y_pred_rf_tl_train)", " precision recall f1-score support\n\n 0 0.83 0.95 0.89 4286\n 1 0.71 0.38 0.49 1337\n\n accuracy 0.81 5623\n macro avg 0.77 0.66 0.69 5623\nweighted avg 0.80 0.81 0.79 5623\n\ntrain_accuracy: 0.8188689311755291\ntest_accuracy: 0.8143339854170372\n" ] ], [ [ "# Synthetic Minority Oversampling Technique (SMOTE)", "_____no_output_____" ] ], [ [ "from imblearn.over_sampling import SMOTE\nsmote = SMOTE()\n\nx_smote, y_smote = smote.fit_resample(x, y)\n\nprint('Original dataset shape', Counter(y))\nprint('Resample dataset shape', Counter(y_smote))", "Original dataset shape Counter({0: 23364, 1: 6636})\nResample dataset shape Counter({1: 23364, 0: 23364})\n" ], [ "x_train,x_test, y_train, y_test = train_test_split(x_smote,y_smote,test_size=0.20, random_state=1)\nx_train = sc.fit_transform(x_train)\nx_test = sc.transform(x_test)", "_____no_output_____" ], [ "x_train = pd.DataFrame(x_train).fillna(0)\nx_test = pd.DataFrame(x_test).fillna(0)", "_____no_output_____" ], [ "rf_model_smote = RandomForestClassifier(n_estimators=70, max_depth=5, min_samples_leaf=4, min_samples_split=3,random_state=1)\nrf_model_smote.fit(x_train,y_train)\ny_pred_rf_smote = rf_model_smote.predict(x_test)\ny_pred_rf_smote_train = rf_model_smote.predict(x_train)\nres(y_pred_rf_smote,y_pred_rf_smote_train)", " precision recall f1-score support\n\n 0 0.80 0.87 0.84 4607\n 1 0.87 0.79 0.83 4739\n\n accuracy 0.83 9346\n macro avg 0.83 0.83 0.83 9346\nweighted avg 0.83 0.83 0.83 9346\n\ntrain_accuracy: 0.8365256005564176\ntest_accuracy: 0.831371709822384\n" ] ], [ [ "### Finally using SMOTE we can see our accuracy as well as recall and precision ratio are give equal ratio\n### Though all the above models performs well, based on the accuracy but in a imbalance dataset like this,\n#### we actually prefer to change the performance metrics \n### We can get better result when we do SVM and Naive bayes with our original data\n### Even we dont have any variance in the model nor to much of bias\n### But when we do over or Under sample the date the other metrics like sensity and specificity was better\n### Hence we can conclue that if we use resample technique we will get better result", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
d0731b3df9dce4a83047971a5395bb66fe6b82d5
62,209
ipynb
Jupyter Notebook
python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb
rtp-aws/devpost_aws_disaster_recovery
2ccfff2d8b85614f3043f09d98c9981dedf43c05
[ "MIT" ]
1
2022-01-13T23:36:05.000Z
2022-01-13T23:36:05.000Z
python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb
rtp-aws/devpost_aws_disaster_recovery
2ccfff2d8b85614f3043f09d98c9981dedf43c05
[ "MIT" ]
9
2022-01-13T19:34:34.000Z
2022-01-14T19:41:18.000Z
python/d2l-en/mxnet/chapter_recurrent-modern/seq2seq.ipynb
rtp-aws/devpost_aws_disaster_recovery
2ccfff2d8b85614f3043f09d98c9981dedf43c05
[ "MIT" ]
null
null
null
38.471861
203
0.528396
[ [ [ "# Sequence to Sequence Learning\n:label:`sec_seq2seq`\n\nAs we have seen in :numref:`sec_machine_translation`,\nin machine translation\nboth the input and output are a variable-length sequence.\nTo address this type of problem,\nwe have designed a general encoder-decoder architecture\nin :numref:`sec_encoder-decoder`.\nIn this section,\nwe will\nuse two RNNs to design\nthe encoder and the decoder of\nthis architecture\nand apply it to *sequence to sequence* learning\nfor machine translation\n:cite:`Sutskever.Vinyals.Le.2014,Cho.Van-Merrienboer.Gulcehre.ea.2014`.\n\nFollowing the design principle\nof the encoder-decoder architecture,\nthe RNN encoder can\ntake a variable-length sequence as the input and transforms it into a fixed-shape hidden state.\nIn other words,\ninformation of the input (source) sequence\nis *encoded* in the hidden state of the RNN encoder.\nTo generate the output sequence token by token,\na separate RNN decoder\ncan predict the next token based on\nwhat tokens have been seen (such as in language modeling) or generated,\ntogether with the encoded information of the input sequence.\n:numref:`fig_seq2seq` illustrates\nhow to use two RNNs\nfor sequence to sequence learning\nin machine translation.\n\n\n![Sequence to sequence learning with an RNN encoder and an RNN decoder.](../img/seq2seq.svg)\n:label:`fig_seq2seq`\n\nIn :numref:`fig_seq2seq`,\nthe special \"&lt;eos&gt;\" token\nmarks the end of the sequence.\nThe model can stop making predictions\nonce this token is generated.\nAt the initial time step of the RNN decoder,\nthere are two special design decisions.\nFirst, the special beginning-of-sequence \"&lt;bos&gt;\" token is an input.\nSecond,\nthe final hidden state of the RNN encoder is used\nto initiate the hidden state of the decoder.\nIn designs such as :cite:`Sutskever.Vinyals.Le.2014`,\nthis is exactly\nhow the encoded input sequence information\nis fed into the decoder for generating the output (target) sequence.\nIn some other designs such as :cite:`Cho.Van-Merrienboer.Gulcehre.ea.2014`,\nthe final hidden state of the encoder\nis also fed into the decoder as\npart of the inputs\nat every time step as shown in :numref:`fig_seq2seq`.\nSimilar to the training of language models in\n:numref:`sec_language_model`,\nwe can allow the labels to be the original output sequence,\nshifted by one token:\n\"&lt;bos&gt;\", \"Ils\", \"regardent\", \".\" $\\rightarrow$\n\"Ils\", \"regardent\", \".\", \"&lt;eos&gt;\".\n\n\nIn the following,\nwe will explain the design of :numref:`fig_seq2seq`\nin greater detail.\nWe will train this model for machine translation\non the English-French dataset as introduced in\n:numref:`sec_machine_translation`.\n", "_____no_output_____" ] ], [ [ "import collections\nimport math\nfrom mxnet import autograd, gluon, init, np, npx\nfrom mxnet.gluon import nn, rnn\nfrom d2l import mxnet as d2l\n\nnpx.set_np()", "_____no_output_____" ] ], [ [ "## Encoder\n\nTechnically speaking,\nthe encoder transforms an input sequence of variable length into a fixed-shape *context variable* $\\mathbf{c}$, and encodes the input sequence information in this context variable.\nAs depicted in :numref:`fig_seq2seq`,\nwe can use an RNN to design the encoder.\n\nLet us consider a sequence example (batch size: 1).\nSuppose that\nthe input sequence is $x_1, \\ldots, x_T$, such that $x_t$ is the $t^{\\mathrm{th}}$ token in the input text sequence.\nAt time step $t$, the RNN transforms\nthe input feature vector $\\mathbf{x}_t$ for $x_t$\nand the hidden state $\\mathbf{h} _{t-1}$ from the previous time step\ninto the current hidden state $\\mathbf{h}_t$.\nWe can use a function $f$ to express the transformation of the RNN's recurrent layer:\n\n$$\\mathbf{h}_t = f(\\mathbf{x}_t, \\mathbf{h}_{t-1}). $$\n\nIn general,\nthe encoder transforms the hidden states at\nall the time steps\ninto the context variable through a customized function $q$:\n\n$$\\mathbf{c} = q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T).$$\n\nFor example, when choosing $q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T) = \\mathbf{h}_T$ such as in :numref:`fig_seq2seq`,\nthe context variable is just the hidden state $\\mathbf{h}_T$\nof the input sequence at the final time step.\n\nSo far we have used a unidirectional RNN\nto design the encoder,\nwhere\na hidden state only depends on\nthe input subsequence at and before the time step of the hidden state.\nWe can also construct encoders using bidirectional RNNs. In this case, a hidden state depends on\nthe subsequence before and after the time step (including the input at the current time step), which encodes the information of the entire sequence.\n\n\nNow let us [**implement the RNN encoder**].\nNote that we use an *embedding layer*\nto obtain the feature vector for each token in the input sequence.\nThe weight\nof an embedding layer\nis a matrix\nwhose number of rows equals to the size of the input vocabulary (`vocab_size`)\nand number of columns equals to the feature vector's dimension (`embed_size`).\nFor any input token index $i$,\nthe embedding layer\nfetches the $i^{\\mathrm{th}}$ row (starting from 0) of the weight matrix\nto return its feature vector.\nBesides,\nhere we choose a multilayer GRU to\nimplement the encoder.\n", "_____no_output_____" ] ], [ [ "#@save\nclass Seq2SeqEncoder(d2l.Encoder):\n \"\"\"The RNN encoder for sequence to sequence learning.\"\"\"\n def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n dropout=0, **kwargs):\n super(Seq2SeqEncoder, self).__init__(**kwargs)\n # Embedding layer\n self.embedding = nn.Embedding(vocab_size, embed_size)\n self.rnn = rnn.GRU(num_hiddens, num_layers, dropout=dropout)\n\n def forward(self, X, *args):\n # The output `X` shape: (`batch_size`, `num_steps`, `embed_size`)\n X = self.embedding(X)\n # In RNN models, the first axis corresponds to time steps\n X = X.swapaxes(0, 1)\n state = self.rnn.begin_state(batch_size=X.shape[1], ctx=X.ctx)\n output, state = self.rnn(X, state)\n # `output` shape: (`num_steps`, `batch_size`, `num_hiddens`)\n # `state[0]` shape: (`num_layers`, `batch_size`, `num_hiddens`)\n return output, state", "_____no_output_____" ] ], [ [ "The returned variables of recurrent layers\nhave been explained in :numref:`sec_rnn-concise`.\nLet us still use a concrete example\nto [**illustrate the above encoder implementation.**]\nBelow\nwe instantiate a two-layer GRU encoder\nwhose number of hidden units is 16.\nGiven\na minibatch of sequence inputs `X`\n(batch size: 4, number of time steps: 7),\nthe hidden states of the last layer\nat all the time steps\n(`output` return by the encoder's recurrent layers)\nare a tensor\nof shape\n(number of time steps, batch size, number of hidden units).\n", "_____no_output_____" ] ], [ [ "encoder = Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,\n num_layers=2)\nencoder.initialize()\nX = np.zeros((4, 7))\noutput, state = encoder(X)\noutput.shape", "_____no_output_____" ] ], [ [ "Since a GRU is employed here,\nthe shape of the multilayer hidden states\nat the final time step\nis\n(number of hidden layers, batch size, number of hidden units).\nIf an LSTM is used,\nmemory cell information will also be contained in `state`.\n", "_____no_output_____" ] ], [ [ "len(state), state[0].shape", "_____no_output_____" ] ], [ [ "## [**Decoder**]\n:label:`sec_seq2seq_decoder`\n\nAs we just mentioned,\nthe context variable $\\mathbf{c}$ of the encoder's output encodes the entire input sequence $x_1, \\ldots, x_T$. Given the output sequence $y_1, y_2, \\ldots, y_{T'}$ from the training dataset,\nfor each time step $t'$\n(the symbol differs from the time step $t$ of input sequences or encoders),\nthe probability of the decoder output $y_{t'}$\nis conditional\non the previous output subsequence\n$y_1, \\ldots, y_{t'-1}$ and\nthe context variable $\\mathbf{c}$, i.e., $P(y_{t'} \\mid y_1, \\ldots, y_{t'-1}, \\mathbf{c})$.\n\nTo model this conditional probability on sequences,\nwe can use another RNN as the decoder.\nAt any time step $t^\\prime$ on the output sequence,\nthe RNN takes the output $y_{t^\\prime-1}$ from the previous time step\nand the context variable $\\mathbf{c}$ as its input,\nthen transforms\nthem and\nthe previous hidden state $\\mathbf{s}_{t^\\prime-1}$\ninto the\nhidden state $\\mathbf{s}_{t^\\prime}$ at the current time step.\nAs a result, we can use a function $g$ to express the transformation of the decoder's hidden layer:\n\n$$\\mathbf{s}_{t^\\prime} = g(y_{t^\\prime-1}, \\mathbf{c}, \\mathbf{s}_{t^\\prime-1}).$$\n:eqlabel:`eq_seq2seq_s_t`\n\nAfter obtaining the hidden state of the decoder,\nwe can use an output layer and the softmax operation to compute the conditional probability distribution\n$P(y_{t^\\prime} \\mid y_1, \\ldots, y_{t^\\prime-1}, \\mathbf{c})$ for the output at time step $t^\\prime$.\n\nFollowing :numref:`fig_seq2seq`,\nwhen implementing the decoder as follows,\nwe directly use the hidden state at the final time step\nof the encoder\nto initialize the hidden state of the decoder.\nThis requires that the RNN encoder and the RNN decoder have the same number of layers and hidden units.\nTo further incorporate the encoded input sequence information,\nthe context variable is concatenated\nwith the decoder input at all the time steps.\nTo predict the probability distribution of the output token,\na fully-connected layer is used to transform\nthe hidden state at the final layer of the RNN decoder.\n", "_____no_output_____" ] ], [ [ "class Seq2SeqDecoder(d2l.Decoder):\n \"\"\"The RNN decoder for sequence to sequence learning.\"\"\"\n def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n dropout=0, **kwargs):\n super(Seq2SeqDecoder, self).__init__(**kwargs)\n self.embedding = nn.Embedding(vocab_size, embed_size)\n self.rnn = rnn.GRU(num_hiddens, num_layers, dropout=dropout)\n self.dense = nn.Dense(vocab_size, flatten=False)\n\n def init_state(self, enc_outputs, *args):\n return enc_outputs[1]\n\n def forward(self, X, state):\n # The output `X` shape: (`num_steps`, `batch_size`, `embed_size`)\n X = self.embedding(X).swapaxes(0, 1)\n # `context` shape: (`batch_size`, `num_hiddens`)\n context = state[0][-1]\n # Broadcast `context` so it has the same `num_steps` as `X`\n context = np.broadcast_to(context, (\n X.shape[0], context.shape[0], context.shape[1]))\n X_and_context = np.concatenate((X, context), 2)\n output, state = self.rnn(X_and_context, state)\n output = self.dense(output).swapaxes(0, 1)\n # `output` shape: (`batch_size`, `num_steps`, `vocab_size`)\n # `state[0]` shape: (`num_layers`, `batch_size`, `num_hiddens`)\n return output, state", "_____no_output_____" ] ], [ [ "To [**illustrate the implemented decoder**],\nbelow we instantiate it with the same hyperparameters from the aforementioned encoder.\nAs we can see, the output shape of the decoder becomes (batch size, number of time steps, vocabulary size),\nwhere the last dimension of the tensor stores the predicted token distribution.\n", "_____no_output_____" ] ], [ [ "decoder = Seq2SeqDecoder(vocab_size=10, embed_size=8, num_hiddens=16,\n num_layers=2)\ndecoder.initialize()\nstate = decoder.init_state(encoder(X))\noutput, state = decoder(X, state)\noutput.shape, len(state), state[0].shape", "_____no_output_____" ] ], [ [ "To summarize,\nthe layers in the above RNN encoder-decoder model are illustrated in :numref:`fig_seq2seq_details`.\n\n![Layers in an RNN encoder-decoder model.](../img/seq2seq-details.svg)\n:label:`fig_seq2seq_details`\n\n## Loss Function\n\nAt each time step, the decoder\npredicts a probability distribution for the output tokens.\nSimilar to language modeling,\nwe can apply softmax to obtain the distribution\nand calculate the cross-entropy loss for optimization.\nRecall :numref:`sec_machine_translation`\nthat the special padding tokens\nare appended to the end of sequences\nso sequences of varying lengths\ncan be efficiently loaded\nin minibatches of the same shape.\nHowever,\nprediction of padding tokens\nshould be excluded from loss calculations.\n\nTo this end,\nwe can use the following\n`sequence_mask` function\nto [**mask irrelevant entries with zero values**]\nso later\nmultiplication of any irrelevant prediction\nwith zero equals to zero.\nFor example,\nif the valid length of two sequences\nexcluding padding tokens\nare one and two, respectively,\nthe remaining entries after\nthe first one\nand the first two entries are cleared to zeros.\n", "_____no_output_____" ] ], [ [ "X = np.array([[1, 2, 3], [4, 5, 6]])\nnpx.sequence_mask(X, np.array([1, 2]), True, axis=1)", "_____no_output_____" ] ], [ [ "(**We can also mask all the entries across the last\nfew axes.**)\nIf you like, you may even specify\nto replace such entries with a non-zero value.\n", "_____no_output_____" ] ], [ [ "X = np.ones((2, 3, 4))\nnpx.sequence_mask(X, np.array([1, 2]), True, value=-1, axis=1)", "_____no_output_____" ] ], [ [ "Now we can [**extend the softmax cross-entropy loss\nto allow the masking of irrelevant predictions.**]\nInitially,\nmasks for all the predicted tokens are set to one.\nOnce the valid length is given,\nthe mask corresponding to any padding token\nwill be cleared to zero.\nIn the end,\nthe loss for all the tokens\nwill be multipled by the mask to filter out\nirrelevant predictions of padding tokens in the loss.\n", "_____no_output_____" ] ], [ [ "#@save\nclass MaskedSoftmaxCELoss(gluon.loss.SoftmaxCELoss):\n \"\"\"The softmax cross-entropy loss with masks.\"\"\"\n # `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)\n # `label` shape: (`batch_size`, `num_steps`)\n # `valid_len` shape: (`batch_size`,)\n def forward(self, pred, label, valid_len):\n # `weights` shape: (`batch_size`, `num_steps`, 1)\n weights = np.expand_dims(np.ones_like(label), axis=-1)\n weights = npx.sequence_mask(weights, valid_len, True, axis=1)\n return super(MaskedSoftmaxCELoss, self).forward(pred, label, weights)", "_____no_output_____" ] ], [ [ "For [**a sanity check**], we can create three identical sequences.\nThen we can\nspecify that the valid lengths of these sequences\nare 4, 2, and 0, respectively.\nAs a result,\nthe loss of the first sequence\nshould be twice as large as that of the second sequence,\nwhile the third sequence should have a zero loss.\n", "_____no_output_____" ] ], [ [ "loss = MaskedSoftmaxCELoss()\nloss(np.ones((3, 4, 10)), np.ones((3, 4)), np.array([4, 2, 0]))", "_____no_output_____" ] ], [ [ "## [**Training**]\n:label:`sec_seq2seq_training`\n\nIn the following training loop,\nwe concatenate the special beginning-of-sequence token\nand the original output sequence excluding the final token as\nthe input to the decoder, as shown in :numref:`fig_seq2seq`.\nThis is called *teacher forcing* because\nthe original output sequence (token labels) is fed into the decoder.\nAlternatively,\nwe could also feed the *predicted* token\nfrom the previous time step\nas the current input to the decoder.\n", "_____no_output_____" ] ], [ [ "#@save\ndef train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):\n \"\"\"Train a model for sequence to sequence.\"\"\"\n net.initialize(init.Xavier(), force_reinit=True, ctx=device)\n trainer = gluon.Trainer(net.collect_params(), 'adam',\n {'learning_rate': lr})\n loss = MaskedSoftmaxCELoss()\n animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n xlim=[10, num_epochs])\n for epoch in range(num_epochs):\n timer = d2l.Timer()\n metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens\n for batch in data_iter:\n X, X_valid_len, Y, Y_valid_len = [\n x.as_in_ctx(device) for x in batch]\n bos = np.array(\n [tgt_vocab['<bos>']] * Y.shape[0], ctx=device).reshape(-1, 1)\n dec_input = np.concatenate([bos, Y[:, :-1]], 1) # Teacher forcing\n with autograd.record():\n Y_hat, _ = net(X, dec_input, X_valid_len)\n l = loss(Y_hat, Y, Y_valid_len)\n l.backward()\n d2l.grad_clipping(net, 1)\n num_tokens = Y_valid_len.sum()\n trainer.step(num_tokens)\n metric.add(l.sum(), num_tokens)\n if (epoch + 1) % 10 == 0:\n animator.add(epoch + 1, (metric[0] / metric[1],))\n print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '\n f'tokens/sec on {str(device)}')", "_____no_output_____" ] ], [ [ "Now we can [**create and train an RNN encoder-decoder model**]\nfor sequence to sequence learning on the machine translation dataset.\n", "_____no_output_____" ] ], [ [ "embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1\nbatch_size, num_steps = 64, 10\nlr, num_epochs, device = 0.005, 300, d2l.try_gpu()\n\ntrain_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)\nencoder = Seq2SeqEncoder(\n len(src_vocab), embed_size, num_hiddens, num_layers, dropout)\ndecoder = Seq2SeqDecoder(\n len(tgt_vocab), embed_size, num_hiddens, num_layers, dropout)\nnet = d2l.EncoderDecoder(encoder, decoder)\ntrain_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)", "loss 0.023, 5661.3 tokens/sec on gpu(0)\n" ] ], [ [ "## [**Prediction**]\n\nTo predict the output sequence\ntoken by token,\nat each decoder time step\nthe predicted token from the previous\ntime step is fed into the decoder as an input.\nSimilar to training,\nat the initial time step\nthe beginning-of-sequence (\"&lt;bos&gt;\") token\nis fed into the decoder.\nThis prediction process\nis illustrated in :numref:`fig_seq2seq_predict`.\nWhen the end-of-sequence (\"&lt;eos&gt;\") token is predicted,\nthe prediction of the output sequence is complete.\n\n\n![Predicting the output sequence token by token using an RNN encoder-decoder.](../img/seq2seq-predict.svg)\n:label:`fig_seq2seq_predict`\n\nWe will introduce different\nstrategies for sequence generation in\n:numref:`sec_beam-search`.\n", "_____no_output_____" ] ], [ [ "#@save\ndef predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,\n device, save_attention_weights=False):\n \"\"\"Predict for sequence to sequence.\"\"\"\n src_tokens = src_vocab[src_sentence.lower().split(' ')] + [\n src_vocab['<eos>']]\n enc_valid_len = np.array([len(src_tokens)], ctx=device)\n src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])\n # Add the batch axis\n enc_X = np.expand_dims(np.array(src_tokens, ctx=device), axis=0)\n enc_outputs = net.encoder(enc_X, enc_valid_len)\n dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)\n # Add the batch axis\n dec_X = np.expand_dims(np.array([tgt_vocab['<bos>']], ctx=device), axis=0)\n output_seq, attention_weight_seq = [], []\n for _ in range(num_steps):\n Y, dec_state = net.decoder(dec_X, dec_state)\n # We use the token with the highest prediction likelihood as the input\n # of the decoder at the next time step\n dec_X = Y.argmax(axis=2)\n pred = dec_X.squeeze(axis=0).astype('int32').item()\n # Save attention weights (to be covered later)\n if save_attention_weights:\n attention_weight_seq.append(net.decoder.attention_weights)\n # Once the end-of-sequence token is predicted, the generation of the\n # output sequence is complete\n if pred == tgt_vocab['<eos>']:\n break\n output_seq.append(pred)\n return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq", "_____no_output_____" ] ], [ [ "## Evaluation of Predicted Sequences\n\nWe can evaluate a predicted sequence\nby comparing it with the\nlabel sequence (the ground-truth).\nBLEU (Bilingual Evaluation Understudy),\nthough originally proposed for evaluating\nmachine translation results :cite:`Papineni.Roukos.Ward.ea.2002`,\nhas been extensively used in measuring\nthe quality of output sequences for different applications.\nIn principle, for any $n$-grams in the predicted sequence,\nBLEU evaluates whether this $n$-grams appears\nin the label sequence.\n\nDenote by $p_n$\nthe precision of $n$-grams,\nwhich is\nthe ratio of\nthe number of matched $n$-grams in\nthe predicted and label sequences\nto\nthe number of $n$-grams in the predicted sequence.\nTo explain,\ngiven a label sequence $A$, $B$, $C$, $D$, $E$, $F$,\nand a predicted sequence $A$, $B$, $B$, $C$, $D$,\nwe have $p_1 = 4/5$, $p_2 = 3/4$, $p_3 = 1/3$, and $p_4 = 0$.\nBesides,\nlet $\\mathrm{len}_{\\text{label}}$ and $\\mathrm{len}_{\\text{pred}}$\nbe\nthe numbers of tokens in the label sequence and the predicted sequence, respectively.\nThen, BLEU is defined as\n\n$$ \\exp\\left(\\min\\left(0, 1 - \\frac{\\mathrm{len}_{\\text{label}}}{\\mathrm{len}_{\\text{pred}}}\\right)\\right) \\prod_{n=1}^k p_n^{1/2^n},$$\n:eqlabel:`eq_bleu`\n\nwhere $k$ is the longest $n$-grams for matching.\n\nBased on the definition of BLEU in :eqref:`eq_bleu`,\nwhenever the predicted sequence is the same as the label sequence, BLEU is 1.\nMoreover,\nsince matching longer $n$-grams is more difficult,\nBLEU assigns a greater weight\nto a longer $n$-gram precision.\nSpecifically, when $p_n$ is fixed,\n$p_n^{1/2^n}$ increases as $n$ grows (the original paper uses $p_n^{1/n}$).\nFurthermore,\nsince\npredicting shorter sequences\ntends to obtain a higher $p_n$ value,\nthe coefficient before the multiplication term in :eqref:`eq_bleu`\npenalizes shorter predicted sequences.\nFor example, when $k=2$,\ngiven the label sequence $A$, $B$, $C$, $D$, $E$, $F$ and the predicted sequence $A$, $B$,\nalthough $p_1 = p_2 = 1$, the penalty factor $\\exp(1-6/2) \\approx 0.14$ lowers the BLEU.\n\nWe [**implement the BLEU measure**] as follows.\n", "_____no_output_____" ] ], [ [ "def bleu(pred_seq, label_seq, k): #@save\n \"\"\"Compute the BLEU.\"\"\"\n pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')\n len_pred, len_label = len(pred_tokens), len(label_tokens)\n score = math.exp(min(0, 1 - len_label / len_pred))\n for n in range(1, k + 1):\n num_matches, label_subs = 0, collections.defaultdict(int)\n for i in range(len_label - n + 1):\n label_subs[' '.join(label_tokens[i: i + n])] += 1\n for i in range(len_pred - n + 1):\n if label_subs[' '.join(pred_tokens[i: i + n])] > 0:\n num_matches += 1\n label_subs[' '.join(pred_tokens[i: i + n])] -= 1\n score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))\n return score", "_____no_output_____" ] ], [ [ "In the end,\nwe use the trained RNN encoder-decoder\nto [**translate a few English sentences into French**]\nand compute the BLEU of the results.\n", "_____no_output_____" ] ], [ [ "engs = ['go .', \"i lost .\", 'he\\'s calm .', 'i\\'m home .']\nfras = ['va !', 'j\\'ai perdu .', 'il est calme .', 'je suis chez moi .']\nfor eng, fra in zip(engs, fras):\n translation, attention_weight_seq = predict_seq2seq(\n net, eng, src_vocab, tgt_vocab, num_steps, device)\n print(f'{eng} => {translation}, bleu {bleu(translation, fra, k=2):.3f}')", "go . => va !, bleu 1.000\ni lost . => j'ai perdu ., bleu 1.000\nhe's calm . => il est malade ., bleu 0.658\ni'm home . => je suis fainéante ?, bleu 0.418\n" ] ], [ [ "## Summary\n\n* Following the design of the encoder-decoder architecture, we can use two RNNs to design a model for sequence to sequence learning.\n* When implementing the encoder and the decoder, we can use multilayer RNNs.\n* We can use masks to filter out irrelevant computations, such as when calculating the loss.\n* In encoder-decoder training, the teacher forcing approach feeds original output sequences (in contrast to predictions) into the decoder.\n* BLEU is a popular measure for evaluating output sequences by matching $n$-grams between the predicted sequence and the label sequence.\n\n\n## Exercises\n\n1. Can you adjust the hyperparameters to improve the translation results?\n1. Rerun the experiment without using masks in the loss calculation. What results do you observe? Why?\n1. If the encoder and the decoder differ in the number of layers or the number of hidden units, how can we initialize the hidden state of the decoder?\n1. In training, replace teacher forcing with feeding the prediction at the previous time step into the decoder. How does this influence the performance?\n1. Rerun the experiment by replacing GRU with LSTM.\n1. Are there any other ways to design the output layer of the decoder?\n", "_____no_output_____" ], [ "[Discussions](https://discuss.d2l.ai/t/345)\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d0732360595964ead8da1d09f5905099366ac090
742,981
ipynb
Jupyter Notebook
Day 4/Seaborn In Action.ipynb
Abuton/10-Academy-5days-Challenge
97188d5d0122265a8216ec35ef8ffb67db1f3e39
[ "Apache-2.0" ]
1
2021-01-23T11:36:19.000Z
2021-01-23T11:36:19.000Z
Day 4/Seaborn In Action.ipynb
Abuton/10-Academy-5days-Challenge
97188d5d0122265a8216ec35ef8ffb67db1f3e39
[ "Apache-2.0" ]
null
null
null
Day 4/Seaborn In Action.ipynb
Abuton/10-Academy-5days-Challenge
97188d5d0122265a8216ec35ef8ffb67db1f3e39
[ "Apache-2.0" ]
null
null
null
586.409629
175,312
0.937102
[ [ [ "# Seaborn In Action\n\nSeaborn is a data visualization library that is based on **Matplotlib**. It is tightly integrated with Pandas library and provides a high level interface for making attractive and informative statistical graphics in Python.\n\nThis Notebook introduces the basic and essential functions in the seaborn library. Lets go ahead and import the relevant libraries for this tutorials", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set()", "_____no_output_____" ], [ "?sns.relplot", "_____no_output_____" ] ], [ [ "## Loading the Data and Inspection", "_____no_output_____" ] ], [ [ "cs = pd.read_csv('data/c_scores.csv')\ncs", "_____no_output_____" ], [ "cs.sample(5)", "_____no_output_____" ], [ "cs.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1000 entries, 0 to 999\nData columns (total 21 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 checking_status 979 non-null object \n 1 duration 1000 non-null int64 \n 2 credit_history 999 non-null object \n 3 purpose 1000 non-null object \n 4 credit_amount 1000 non-null int64 \n 5 savings_status 967 non-null object \n 6 employment 968 non-null object \n 7 installment_commitment 1000 non-null int64 \n 8 personal_status 997 non-null object \n 9 other_parties 998 non-null object \n 10 residence_since 1000 non-null int64 \n 11 property_magnitude 999 non-null object \n 12 age 1000 non-null int64 \n 13 other_payment_plans 996 non-null object \n 14 housing 998 non-null object \n 15 existing_credits 999 non-null float64\n 16 job 999 non-null object \n 17 num_dependents 1000 non-null int64 \n 18 own_telephone 1000 non-null object \n 19 foreign_worker 999 non-null object \n 20 class 999 non-null object \ndtypes: float64(1), int64(6), object(14)\nmemory usage: 164.2+ KB\n" ] ], [ [ "## Scatter Plots", "_____no_output_____" ], [ "We shall plot the **age** and **credit_amount** columns using the **jointplot** function.", "_____no_output_____" ] ], [ [ "sns.jointplot(x='age', y='credit_amount', data=cs)", "_____no_output_____" ] ], [ [ "Let's plot the **age** and **credit_amount** again but this time let's break that with **job**. For this, we shall used the **relplot()**. This functions provides access to several axes-level functions that show the relationship between two variables which can also come with semantic mappings. It also come with the **kind** parameter which can be used to specify whether you want a **lineplot** or **scatterplot**. The default is **scatterplot**.", "_____no_output_____" ], [ "The visualization below shows the relation between credit amount given to people and their ages. In addition, I am comparing it over the kind of job. Seaborn uses coloring to show which of the points represent what kind of job. The **height** and the **aspect** parameter is used to adjust the height and width of the FacetGrid. The **hue** parameter helps to group variables that will produce element with different colors. **data** parameter represents the dataset of interest.", "_____no_output_____" ] ], [ [ "sns.relplot(x=\"age\", y=\"credit_amount\", height= 8, aspect=1, hue=\"job\", data=cs)", "_____no_output_____" ] ], [ [ "We can also plot the above visualization where we compare what it looks like over two or more categorical elements. For example, in the below visualization, we shall compare the above visualization over **class** using the **col** parameter in the **relplot()** function.", "_____no_output_____" ] ], [ [ "sns.relplot(x=\"age\", y=\"credit_amount\", height= 8, aspect=1, hue=\"job\", col='class',data=cs)", "_____no_output_____" ] ], [ [ "## Boxplots", "_____no_output_____" ], [ "A boxplot is used to show the distribution of numerical variables and facilitates comparisons across multiple categorical variables.\n\nWe would like to visualize the distribution of **age** of the customers with respect to **class**.", "_____no_output_____" ] ], [ [ "sns.boxplot(x='class', y='age', data=cs)", "_____no_output_____" ] ], [ [ "Let's visualize the distribution of **credit_amount** with respect to **purpose** using **class** as the **hue**", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(figsize=(18,7))\nsns.boxplot(x='purpose', y='credit_amount', hue='class', ax = ax, data=cs)", "_____no_output_____" ] ], [ [ "## Histogram", "_____no_output_____" ], [ "A histrogram represents the distribution of data by forming bins along the range of the data and drawing lines to represents the number of observations that fall within each bin.\n\nLet's plot the histogram of **credit_amount**. ", "_____no_output_____" ] ], [ [ "sns.distplot(cs['credit_amount'])", "_____no_output_____" ] ], [ [ "Let's plot the histogram of the **age**", "_____no_output_____" ] ], [ [ "sns.distplot(cs['age'])", "_____no_output_____" ] ], [ [ "Let's get the histogram of the **credit_amount** of the customers, this time across the **class** dimension as a faceted histogram.", "_____no_output_____" ] ], [ [ "facet = sns.FacetGrid(cs, height=6, col='class')\nfacet = facet.map(sns.distplot, 'credit_amount', color='r')", "_____no_output_____" ] ], [ [ "It will however be a fantastic idea to compare the distribution of **class_amount** across **class** overlaid on the same plot.", "_____no_output_____" ] ], [ [ "facet = sns.FacetGrid(cs, height=6, hue='class')\nfacet = facet.map(sns.distplot, 'credit_amount')", "_____no_output_____" ] ], [ [ "## Line Plots", "_____no_output_____" ], [ "To make meaningful line plots, we are going to generate a dataframe to be used to help us understand line plots.\n\nWe will randomly generate some dates from (1970) to (1970+36) over 12 months period. We will then go ahead and select the first 36 rows for the **duration** and **age** columns to form our new dataframe.", "_____no_output_____" ] ], [ [ "new_series = pd.DataFrame({'time': pd.date_range('1970-12-31', periods=36, freq='12M'),\n 'duration': cs['duration'].iloc[0:36],\n 'age': cs['age'].iloc[0:36]})\n\nnew_series.head()", "_____no_output_____" ] ], [ [ "Next, we are going to move the **duration** and the **age** columns to rows so that we can plot both on the graph. We are going to do that using the the pandas **melt()** method.\n\nThe **melt()** method allows us to unpivot a dataframe from a wide to a long format, optionally leaving the identifiers set. It takes in the dataframe you want to unpivot, the **id_vars**, identifier variable (could be single column or list of columns), the **var_name**, variable name (for the variable that are going to be unpivoted), and the **value_name**, the name of the value column.", "_____no_output_____" ] ], [ [ "series = pd.melt(new_series, id_vars=['time'],\n var_name='Variables',\n value_name='values')\n\nseries.sample(10)", "_____no_output_____" ], [ "lp = sns.lineplot(x='time', y='values', hue='Variables', data=series)\n\n#Position the legend out the graph\nlp.legend(bbox_to_anchor=(1.02, 1),\n loc=2, \n borderaxespad=0.0);\nlp.set(title='Line plot of Duration and Age', xlabel='Year', ylabel='Values')", "_____no_output_____" ] ], [ [ "## Regression Plot", "_____no_output_____" ], [ "In the regression plotting, we are going to use the **lmplot()**. This function combines the the **regplot()** and FacetGrid. It is intended as a convenient interface to fit regression models across subsets of datasets.\n\nWe will use the famous iris flower dataset for the regression plot. It is available in the seaborn module.", "_____no_output_____" ] ], [ [ "iris = sns.load_dataset('iris')", "_____no_output_____" ], [ "iris.sample(8)", "_____no_output_____" ] ], [ [ "Let's plot the **sepal_length** vs the **sepal_withth** only", "_____no_output_____" ] ], [ [ "g = sns.lmplot(x='petal_length', y='petal_width', order=1, data=iris)\ng.set_axis_labels(\"Petal Length(mm)\", \"Petal Width(mm)\" )", "_____no_output_____" ] ], [ [ "Using the species, lets break the regression line with respect to the species and fit a first order regression to each species' respective data point.", "_____no_output_____" ] ], [ [ "g = sns.lmplot(x='petal_length', y='petal_width', hue='species',height=8, order=1, data=iris)\ng.set_axis_labels(\"Petal Length(mm)\", \"Petal Width(mm)\" )", "_____no_output_____" ] ], [ [ "Now, let's use the **species** as the **col**, column parameter", "_____no_output_____" ] ], [ [ "g = sns.lmplot(x='petal_length', y='petal_width', col='species',height=10, order=1, data=iris)\ng.set_axis_labels(\"Petal Length(mm)\", \"Petal Width(mm)\" )", "_____no_output_____" ] ], [ [ "### References\n\n1. https://seaborn.pydata.org/index.html\n2. https://www.featureranking.com/tutorials/python-tutorials/seaborn/", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d0732a5ad91ae46981c387f8df362ae1a9645a79
16,981
ipynb
Jupyter Notebook
workshop_sections/mnist_series/mnist_estimator.ipynb
nghiatd16/tensorflow-workshop
4cdc2cc84dc15dcb8c4d1c0a51221b552f50bc8e
[ "Apache-2.0" ]
null
null
null
workshop_sections/mnist_series/mnist_estimator.ipynb
nghiatd16/tensorflow-workshop
4cdc2cc84dc15dcb8c4d1c0a51221b552f50bc8e
[ "Apache-2.0" ]
null
null
null
workshop_sections/mnist_series/mnist_estimator.ipynb
nghiatd16/tensorflow-workshop
4cdc2cc84dc15dcb8c4d1c0a51221b552f50bc8e
[ "Apache-2.0" ]
1
2020-01-20T08:29:10.000Z
2020-01-20T08:29:10.000Z
32.344762
352
0.564396
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d0733209a2771a03e36008aaf8bbf79d4c3ccfeb
2,005
ipynb
Jupyter Notebook
#4 - Automated text rating/4.0 - Introduction.ipynb
Jorbet0805/AlexGascon-playing-with-keras
c3f99c50b8467757071b879884dff69fe8d06b23
[ "Apache-2.0" ]
10
2018-03-05T07:15:02.000Z
2021-08-15T13:50:49.000Z
#4 - Automated text rating/4.0 - Introduction.ipynb
Jorbet0805/AlexGascon-playing-with-keras
c3f99c50b8467757071b879884dff69fe8d06b23
[ "Apache-2.0" ]
null
null
null
#4 - Automated text rating/4.0 - Introduction.ipynb
Jorbet0805/AlexGascon-playing-with-keras
c3f99c50b8467757071b879884dff69fe8d06b23
[ "Apache-2.0" ]
2
2020-04-14T16:10:42.000Z
2020-09-01T03:21:49.000Z
48.902439
487
0.705237
[ [ [ "## 4.0 - Automated text rating: introduction\n\nNow that we've almost solved the problems of our next character prediction system, the next steps will lean towards tuning its parameters until we found the ones that make it the closest to an optimal generation. \n\nHowever, there are a lot of possible configurations to try, and we'll need to use each one of them several times to have a better understanding of its actual performance; obtaining only one result for each configuration may result in us choosing one which outputs a good result by chance, instead of choosing the best one. Therefore, it's quite clear that we need several outputs per configuration, and that its average optimality will be the optimality of the system.\n\nThe problem is that this will undoubtedly produce a huge amount of different texts, and probably most of them look incredibly similar. Then, how can we choose which one of them is the best one? \n\nWe need to change the process we've been following. Instead of determining the best system by subjectively choosing the one whose text looks more realistic, we're going to establish a rating system that we'll use to assign a numeric score to each text according to its correctness. This numeric score will let us have a measurable way to determinate which configuration results in the best performance, and to discover if some changes affect or not the correctness of the result.\n", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
d0733590b49374e4d117dde7ba9ac9a5a7cb5dbe
8,914
ipynb
Jupyter Notebook
mlcourse/Percentiles.ipynb
chauhanr/DLTFpT
31e806ce489448728d0b439ae557cf2ffb4f8c25
[ "MIT" ]
null
null
null
mlcourse/Percentiles.ipynb
chauhanr/DLTFpT
31e806ce489448728d0b439ae557cf2ffb4f8c25
[ "MIT" ]
null
null
null
mlcourse/Percentiles.ipynb
chauhanr/DLTFpT
31e806ce489448728d0b439ae557cf2ffb4f8c25
[ "MIT" ]
null
null
null
62.335664
6,452
0.834193
[ [ [ "# Percentiles", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nvals = np.random.normal(0, 0.25, 10000)\n\nplt.hist(vals, 50)\nplt.show()", "_____no_output_____" ], [ "np.percentile(vals, 50)", "_____no_output_____" ], [ "np.percentile(vals, 99)", "_____no_output_____" ], [ "np.percentile(vals, 10)", "_____no_output_____" ] ], [ [ "## Activity", "_____no_output_____" ], [ "Experiment with different parameters when creating the test data. What effect does it have on the percentiles?", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
d0734143ce9f785c20722f9eda08ba826cbbce11
55,043
ipynb
Jupyter Notebook
cluster_tfidf_v2.ipynb
shebak11/emotionalPhenome
8e46e1cc7966714e7b14847dba0825edf292b7c7
[ "MIT" ]
1
2019-02-22T14:10:17.000Z
2019-02-22T14:10:17.000Z
submitted_code/cluster_tfidf_v2.ipynb
shebak11/emotionalPhenome
8e46e1cc7966714e7b14847dba0825edf292b7c7
[ "MIT" ]
null
null
null
submitted_code/cluster_tfidf_v2.ipynb
shebak11/emotionalPhenome
8e46e1cc7966714e7b14847dba0825edf292b7c7
[ "MIT" ]
null
null
null
65.998801
837
0.662046
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d0735965a81f7cfb76322f2434eca205a3345063
2,753
ipynb
Jupyter Notebook
content/lessons/02/Watch-Me-Code/WMC2-String-Formatting.ipynb
MahopacHS/spring-2020-oubinam0717
5b35579e658e34cbb07c3477a9fce13ce01830af
[ "MIT" ]
1
2020-01-17T13:22:31.000Z
2020-01-17T13:22:31.000Z
content/lessons/02/Watch-Me-Code/WMC2-String-Formatting.ipynb
MahopacHS/spring-2020-oubinam0717
5b35579e658e34cbb07c3477a9fce13ce01830af
[ "MIT" ]
null
null
null
content/lessons/02/Watch-Me-Code/WMC2-String-Formatting.ipynb
MahopacHS/spring-2020-oubinam0717
5b35579e658e34cbb07c3477a9fce13ce01830af
[ "MIT" ]
2
2019-02-12T18:23:11.000Z
2019-03-02T19:40:54.000Z
17.20625
58
0.450781
[ [ [ "# Watch Me Code 2: String Formatting", "_____no_output_____" ] ], [ [ "name = \"Mike\"\nage = 45\nsalary = 15.75\n", "_____no_output_____" ], [ "# string formatting\nprint(\"Hello there %s. How are you? \" % (name))", "Hello there Mike. How are you? \n" ], [ "# formatting redux\nprint(\"%s makes %f per hour.\" % (name, salary))", "Mike makes 15.750000 per hour.\n" ], [ "# let's use spacing\nprint(\"%s makes %.2f per hour.\" % (name, salary))", "Mike makes 15.75 per hour.\n" ], [ "# right alignment \nprint(\"-\" * 10) # print 10 dashes\nprint(\"%10d\" %(age))", "----------\n 45\n" ], [ "# left alignment\nprint(\"-\" * 10)\nprint(\"%-10d\" % (age))", "----------\n45 \n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d0735b2e996c08d93b20a227f4988f63c655368d
979,870
ipynb
Jupyter Notebook
notebooks/Imaging/Selective_Fourier_Transform.ipynb
gduscher/pyTEMlib
111c0e20caa06bd32c41137fc912ce4f2599c5d5
[ "MIT" ]
3
2019-06-17T05:13:33.000Z
2020-10-27T22:47:53.000Z
notebooks/Imaging/Selective_Fourier_Transform.ipynb
gduscher/pyTEMlib
111c0e20caa06bd32c41137fc912ce4f2599c5d5
[ "MIT" ]
null
null
null
notebooks/Imaging/Selective_Fourier_Transform.ipynb
gduscher/pyTEMlib
111c0e20caa06bd32c41137fc912ce4f2599c5d5
[ "MIT" ]
null
null
null
177.899419
344,367
0.844569
[ [ [ "<font size = \"5\"> **[Image Tools](2_Image_Tools.ipynb)** </font>\n\n<hr style=\"height:2px;border-top:4px solid #FF8200\" />\n\n\n# Selective Fourier Transform\n\n\npart of \n\n<font size = \"4\"> **pyTEMlib**, a **pycroscopy** library </font>\n\n\nNotebook by \n\nGerd Duscher\n\nMaterials Science & Engineering<br>\nJoint Institute of Advanced Materials<br>\nThe University of Tennessee, Knoxville\n\n\nAn introduction into Fourier Filtering of images.\n\n\n## Install pyTEMlib\n\nIf you have not done so in the [Introduction Notebook](_.ipynb), please test and install [pyTEMlib](https://github.com/gduscher/pyTEMlib) and other important packages with the code cell below.\n", "_____no_output_____" ] ], [ [ "import sys\nfrom pkg_resources import get_distribution, DistributionNotFound\n\ndef test_package(package_name):\n \"\"\"Test if package exists and returns version or -1\"\"\"\n try:\n version = (get_distribution(package_name).version)\n except (DistributionNotFound, ImportError) as err:\n version = '-1'\n return version\n\n# Colab setup ------------------\nif 'google.colab' in sys.modules:\n !pip install git+https://github.com/pycroscopy/pyTEMlib/ -q\n\n# pyTEMlib setup ------------------\nelse:\n if test_package('sidpy') < '0.0.7':\n print('installing sidpy')\n !{sys.executable} -m pip install --upgrade sidpy -q \n if test_package('pyNSID') < '0.0.3':\n print('installing pyNSID')\n !{sys.executable} -m pip install --upgrade pyNSID -q \n if test_package('pyTEMlib') < '0.2022.10.1':\n print('installing pyTEMlib')\n !{sys.executable} -m pip install --upgrade pyTEMlib -q\n# ------------------------------\nprint('done')", "_____no_output_____" ] ], [ [ "## Loading of necessary libraries\n\nPlease note, that we only need to load the pyTEMlib library, which is based on sidpy Datsets. \n\n", "_____no_output_____" ] ], [ [ "%pylab notebook\nfrom matplotlib.widgets import RectangleSelector\nsys.path.insert(0,'../../')\nimport pyTEMlib\nimport pyTEMlib.file_tools as ft\nimport pyTEMlib.image_tools as it\n\nprint('pyTEMlib version: ', pyTEMlib.__version__)\nnote_book_version = '2021.10.25'\nnote_book_name='pyTEMib/notebooks/Imaging/Adaptive_Fourier_Filter'", "Populating the interactive namespace from numpy and matplotlib\npyTEMlib version: 0.2021.10.2\n" ] ], [ [ "## Open File\n\nThese datasets are stored in the pyNSID data format (extension: hf5) automatically. \n\nAll results can be stored in that file. \n\nFirst we select the file", "_____no_output_____" ] ], [ [ "file_widget = ft.FileWidget()", "_____no_output_____" ] ], [ [ "Now, we open and plot them\n\nSelect with the moue an area; rectangle will apear!", "_____no_output_____" ] ], [ [ "try:\n dataset.h5_dataset.file.close()\nexcept:\n pass\ndataset= ft.open_file(file_widget.file_name)\nprint(file_widget.file_name)\nif dataset.data_type.name != 'IMAGE':\n print('We really would need an image here')\ndataset.plot()\nselector = RectangleSelector(dataset.view.axis, None,interactive=True , drawtype='box')", "/mnt/c/Users/gdusc/Documents/2021-09-01-20210913T151245Z-001/2021-09-01/Nion Swift Library 20210901/Nion Swift Data 13/2021/09/01/20210901-095127/2-HAADF-3.hf5\n" ], [ "def get_selection(dataset, extents):\n if (np.array(extents) <2).all():\n return dataset\n xmin, xmax, ymin, ymax = selector.extents/(dataset.x[1]-dataset.x[0])\n return dataset.like_data(dataset[int(xmin):int(xmax), int(ymin):int(ymax)])\n\nselection = it.get_selection(dataset, selector.extents)\nselection.plot()", "_____no_output_____" ] ], [ [ "## Power Spectrum of Image", "_____no_output_____" ] ], [ [ "power_spectrum = it.power_spectrum(selection, smoothing=1)\n\npower_spectrum.view_metadata()\nprint('source: ', power_spectrum.source)\npower_spectrum.plot()\n\n", "fft :\n\tsmoothing : 1\n\tminimum_intensity : 0.04261075359154022\n\tmaximum_intensity : 1.5140884612372518\nsource: /Measurement_000/Channel_000/2_HAADF/2_HAADF_new\n" ] ], [ [ "## Spot Detection in Fourier Transform", "_____no_output_____" ] ], [ [ "# ------Input----------\nspot_threshold=0.1\n# ---------------------\n\nspots = it.diffractogram_spots(power_spectrum, spot_threshold=spot_threshold)\nspots = spots[np.linalg.norm(spots[:,:2],axis=1)<8,:]\nspots = spots[np.linalg.norm(spots[:,:2],axis=1)>0.5,:]\npower_spectrum.plot()\n\nplt.gca().scatter(spots[:,0],spots[:,1], color='red', alpha=0.4);", "Found 7 reflections\n" ], [ "#print(spots[:,:2])\n#print(np.round(np.linalg.norm(spots[:,:2], axis=1),2))\n#print(np.round(np.degrees(np.arctan2(spots[:,0], spots[:,1])+np.pi)%180,2))\nangles=np.arctan2(spots[:,0], spots[:,1])\nradius= np.linalg.norm(spots[:,:2], axis=1)\nargs = angles>0\nradii = radius[angles>0]\nangles = angles[angles>0]\nprint(radii, np.degrees(angles))\n#print(np.degrees(angles[1]-angles[0]), np.degrees(angles[2]-angles[0]))\n#print(1/radii)", "[3.92020337 4.14388489 4.59259423] [ 20.63129574 90. 143.02034046]\n" ], [ "new_angles = np.round(np.degrees(angles+np.pi-angles[0]+0.0000001)%180,2)\nprint(new_angles)\nprint(np.degrees(angles[1]-angles[0]), np.degrees(angles[2]-angles[0]))", "-53.02034045871323 -122.38904471827684\n" ], [ "\nangles=np.arctan2(spots[:,0], spots[:,1])\nradius= np.linalg.norm(spots[:,:2], axis=1)\nargs = angles>0\nradii = radius[angles>0]\nangles = angles[angles>0]\nprint(radii, np.degrees(angles))", "[4.59 4.14 3.92 4.59 4.14 3.92]\n[143.02 90. 20.63 143.02 90. 20.63]\n[4.59259423 4.14388489 3.92020337] [143.02034046 90. 20.63129574]\n" ], [ "# clockwise from up\nangles =(-np.degrees(np.arctan2(spots[:,0], spots[:,1]))+180) % 360\nspots = spots[np.argsort(angles)]\nangles =(-np.degrees(np.arctan2(spots[:,0], spots[:,1]))+180) % 360\nplane_distances = 1/np.linalg.norm(spots[:,:2],axis=1)\nrolled_angles= np.roll(angles,1) %360\nrolled_angles[0] -= 360\nrelative_angles = angles - rolled_angles \nprint(np.round(plane_distances,3))\nprint(np.round(relative_angles,1))", "[0.218 0.241 0.255 0.218 0.241 0.255]\n[57.6 53. 69.4 57.6 53. 69.4]\n" ], [ "import pyTEMlib.kinematic_scattering as ks\n\n#Initialize the dictionary of the input\ntags_simulation = {}\n### Define Crystal\ntags_simulation = ft.read_poscar('./POSCAR.mp-2418_PdSe2')\n\n### Define experimental parameters:\ntags_simulation['acceleration_voltage_V'] = 200.0 *1000.0 #V\ntags_simulation['new_figure'] = False\ntags_simulation['plot FOV'] = 30\ntags_simulation['convergence_angle_mrad'] = 0\ntags_simulation['zone_hkl'] = np.array([0,0,1]) # incident neares zone axis: defines Laue Zones!!!!\ntags_simulation['mistilt'] = np.array([0,0,0]) # mistilt in degrees\ntags_simulation['Sg_max'] = .2 # 1/nm maximum allowed excitation error ; This parameter is related to the thickness\ntags_simulation['hkl_max'] = 6 # Highest evaluated Miller indices\n\n######################################\n# Diffraction Simulation of Crystal #\n######################################\nimport itertools\nhkl_list = [list([0, 0, 0])]\nspot_dict = {}\nfor hkl in itertools.product(range(6), repeat=3):\n if list(hkl) not in hkl_list:\n #print(hkl, hkl_list)\n\n tags_simulation['zone_hkl'] = hkl\n \n ks.kinematic_scattering(tags_simulation, verbose = False)\n if list(tags_simulation['nearest_zone_axes']['0']['hkl']) not in hkl_list:\n print('- ', tags_simulation['nearest_zone_axes']['0']['hkl'])\n \n \n spots = tags_simulation['allowed']['g'][np.linalg.norm(tags_simulation['allowed']['g'][:,:2], axis=1)<4.7,:2]\n angles=np.arctan2(spots[:,0], spots[:,1])\n radius= np.linalg.norm(spots[:,:2], axis=1)\n args = angles>0\n radii = radius[angles>0]\n angles = angles[angles>0]\n spot_dict[hkl] = {\"radii\": radii, \"angles\": angles}\n print(radii, np.degrees(angles%np.pi))\n hkl_list.append(list(hkl))", "Using kinematic_scattering library version 0.6 by G.Duscher\nSymmetry functions of spglib enabled\ndone\n- [0. 0. 1.]\n[3.36393279 3.83960126 3.45159773 3.83960126] [ 0. 115.98001194 90. 64.01998806]\ndone\ndone\ndone\ndone\ndone\n- [0. 1. 0.]\n[2.32962818 4.65925635 2.89923251 2.89923251 4.16421593 3.45159773\n 4.16421593] [ 0. 0. 36.5312114 143.4687886 55.98293415\n 90. 124.01706585]\ndone\n- [0. 1. 1.]\n[3.35132468 3.35132468 4.49071512 3.45159773 4.49071512] [149.00520452 30.99479548 129.77098412 90. 50.22901588]\ndone\n- [0. 1. 2.]\n[4.09105808 4.44017319 2.67629796 2.67629796 4.44017319 4.0121959\n 3.45159773 4.0121959 ] [ 0. 157.1277171 139.84590274 40.15409726 22.8722829\n 120.6523608 90. 59.3476392 ]\ndone\n- [0. 1. 3.]\n[3.45159773] [90.]\ndone\n- [0. 1. 4.]\n[3.55958758 3.95588744 3.95588744 3.45159773] [ 0. 154.13444838 25.86555162 90. ]\ndone\n- [0. 1. 5.]\n[3.55504407 3.9517996 3.45159773] [ 0. 154.10570979 90. ]\ndone\ndone\n- [0. 2. 1.]\n[3.45159773] [90.]\ndone\ndone\n- [0. 2. 3.]\n[3.45159773] [90.]\ndone\ndone\n- [0. 2. 5.]\n[2.67135911 2.67135911 4.00890318 3.45159773 4.00890318] [139.75647203 40.24352797 120.57285924 90. 59.42714076]\ndone\ndone\n- [0. 3. 1.]\n[3.45159773] [90.]\ndone\n- [0. 3. 2.]\n[4.24436536 4.24436536 3.45159773] [156.00798003 23.99201997 90. ]\ndone\ndone\n- [0. 3. 4.]\n[3.45159773] [90.]\ndone\n- [0. 3. 5.]\n[3.45159773] [90.]\ndone\ndone\n- [0. 4. 1.]\n[3.45159773] [90.]\ndone\ndone\n- [0. 4. 3.]\n[4.24318041 4.24318041 3.45159773] [156.00085864 23.99914136 90. ]\ndone\ndone\n- [0. 4. 5.]\n[3.45159773] [90.]\ndone\ndone\n- [0. 5. 1.]\n[3.45159773] [90.]\ndone\n- [0. 5. 2.]\n[3.45159773] [90.]\ndone\n- [0. 5. 3.]\n[4.23950748 3.45159773] [24.0212429 90. ]\ndone\n- [0. 5. 4.]\n[4.23900215 3.45159773] [155.975713 90. ]\ndone\n" ], [ "spot_dict", "_____no_output_____" ], [ "for hkl, refl in spot_dict.items():\n if len(refl['radii'])>4:\n print(hkl, 1/refl['radii'])", "(0, 1, 0) [0.42925305 0.21462653 0.34491887 0.34491887 0.24014125 0.2897209\n 0.24014125]\n(0, 1, 1) [0.29838947 0.29838947 0.22268168 0.2897209 0.22268168]\n(0, 1, 2) [0.24443554 0.22521644 0.37365047 0.37365047 0.22521644 0.24924007\n 0.2897209 0.24924007]\n(0, 2, 5) [0.37434128 0.37434128 0.24944479 0.2897209 0.24944479]\n(1, 0, 0) [0.24438842 0.28090735 0.2972711 0.21462653 0.42925305 0.24438842\n 0.28090735]\n(1, 0, 1) [0.2972711 0.22527197 0.29856219 0.3452512 0.29856219 0.22527197]\n(1, 0, 2) [0.2972711 0.25283763 0.37382609 0.37382609 0.25283763 0.22284852\n 0.24037262 0.22284852]\n(1, 1, 0) [0.21462653 0.42925305 0.23560622 0.29839823 0.37370861 0.37370861\n 0.29839823 0.23560622]\n(1, 1, 2) [0.24442305 0.25277107 0.29851821 0.24934585 0.2403143 ]\n(1, 2, 0) [0.21462653 0.42925305 0.22269858 0.24927592 0.26049888 0.24927592\n 0.22269858]\n(2, 0, 5) [0.2972711 0.25289088 0.37399827 0.37399827 0.25289088]\n(2, 1, 0) [0.21462653 0.42925305 0.22521415 0.25281914 0.25281914 0.22521415]\n" ] ], [ [ "## Log the result", "_____no_output_____" ] ], [ [ "# results_channel = ft.log_results(dataset.h5_dataset.parent.parent, filtered_dataset)\n", "_____no_output_____" ] ], [ [ "A tree-like plot of the file", "_____no_output_____" ] ], [ [ "ft.h5_tree(dataset.h5_dataset.file)", "_____no_output_____" ] ], [ [ "## Close File\nlet's close the file but keep the filename", "_____no_output_____" ] ], [ [ "dataset.h5_dataset.file.close()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d07360064b20a616dced35b24f04f2b67ad154f9
6,475
ipynb
Jupyter Notebook
notebooks/Oads_Mo2C_catalysts_PreprocessGraphStructure.ipynb
MolecularMaterials/MPNN-Mo2C
c0ea4cb793901b7ae86fdfc91e108f3912d7a750
[ "MIT" ]
null
null
null
notebooks/Oads_Mo2C_catalysts_PreprocessGraphStructure.ipynb
MolecularMaterials/MPNN-Mo2C
c0ea4cb793901b7ae86fdfc91e108f3912d7a750
[ "MIT" ]
null
null
null
notebooks/Oads_Mo2C_catalysts_PreprocessGraphStructure.ipynb
MolecularMaterials/MPNN-Mo2C
c0ea4cb793901b7ae86fdfc91e108f3912d7a750
[ "MIT" ]
null
null
null
37.427746
151
0.505792
[ [ [ "import time\nimport networkx as nx\nfrom nfp.preprocessing import features_graph\nimport numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "dataIni = pd.read_csv('Oads_Mo2C_catalysts_graphml.csv')\ndataIni['graphFileName'] = dataIni['graphFileName'].str.slice_replace(0,0,repl='Oads_Mo2C_graphml/')\nprint(dataIni.graphFileName)", "0 Oads_Mo2C_graphml/Mo2C_101_1_O_0_19_1.graphml\n1 Oads_Mo2C_graphml/Mo2C_110_4_O_0_19_2.graphml\n2 Oads_Mo2C_graphml/Mo2C_011_8_O_0_31_5.graphml\n3 Oads_Mo2C_graphml/Mo2C_101_5_O_0_23_6.graphml\n4 Oads_Mo2C_graphml/Mo2C_110_2_O_0_18_7.graphml\n ... \n20172 Oads_Mo2C_graphml/Mo2C_100_4_Au_1_O_0_6_26624....\n20173 Oads_Mo2C_graphml/Mo2C_100_0_Ru_1_O_0_8_26626....\n20174 Oads_Mo2C_graphml/Mo2C_110_2_Ir_0_O_0_6_26627....\n20175 Oads_Mo2C_graphml/Mo2C_110_1_Ru_0_O_0_3_26631....\n20176 Oads_Mo2C_graphml/Mo2C_101_7_Os_0_O_0_5_26632....\nName: graphFileName, Length: 20177, dtype: object\n" ], [ "# Prepare graph information for faster preprocessing\ndef construct_graph_data(graphDF,numOfShell=2):\n \"\"\" \n Returns\n dict with entries\n 'n_atom' : number of atoms in the molecule\n 'n_bond' : number of bonds in the molecule \n 'connectivity' : (n_bond, 2) array of source atom, target atom pairs.\n \"\"\"\n dataList = []\n for index,row in graphDF.iterrows():\n graph = row.graphFileName\n s1 = graph.split(\"/\")[-1]\n shortName = s1.split(\".\")[0]\n G = nx.read_graphml(graph)\n if numOfShell==2:\n nodes = (\n node\n for node, data\n in G.nodes(data=True)\n if data.get(\"type\") != \"thirdCoordinationShell\"\n )\n G = G.subgraph(nodes)\n\n elif numOfShell==1:\n nodes = (\n node\n for node, data\n in G.nodes(data=True)\n if data.get(\"type\") != \"thirdCoordinationShell\" and data.get(\"type\") != 'secondCoordinationShell'\n )\n G = G.subgraph(nodes)\n\n n_atom = G.number_of_nodes()\n n_bond = 2 * G.number_of_edges()\n\n # If its an isolated atom, add a self-link\n if n_bond == 0:\n n_bond = 1\n\n connectivity = np.zeros((n_bond, 2), dtype='int')\n nodeList = []\n edgeList = []\n revList = []\n atomFeatList = []\n bondFeatList = []\n bond_index = 0\n for n,node in enumerate(G.nodes):\n # Atom Classes\n start_index = list(G.nodes).index(node)\n nodeList.append(node)\n atomFeat = features_graph.atom_features_ver1(G.nodes[node])\n atomFeatList.append(atomFeat)\n for m,edge in enumerate(G.edges):\n if node in edge:\n # Is the bond pointing at the target atom \n rev = list(G.nodes).index(list(G.edges)[m][0]) != start_index\n bondFeat = features_graph.bond_features_v1(G.edges[edge],flipped=rev)\n bondFeatList.append(bondFeat)\n edgeList.append(edge)\n revList.append(rev)\n # Connectivity\n if not rev: # Original direction\n connectivity[bond_index, 0] = list(G.nodes).index(list(G.edges)[m][0])\n connectivity[bond_index, 1] = list(G.nodes).index(list(G.edges)[m][1])\n else: # Reversed\n connectivity[bond_index, 0] = list(G.nodes).index(list(G.edges)[m][1])\n connectivity[bond_index, 1] = list(G.nodes).index(list(G.edges)[m][0])\n bond_index += 1 \n connectivity = connectivity.tolist()\n dataList.append([shortName,n_atom, n_bond, nodeList, edgeList, atomFeatList, bondFeatList, revList, connectivity])\n return dataList", "_____no_output_____" ], [ "start_time = time.time()\nstructList = construct_graph_data(dataIni,numOfShell=2)\ndfGS = pd.DataFrame(structList,columns=['graphName','nAtoms','nBonds','nodes','edges','atomFeatures','bondFeatures','revBool','connectivity'])\nprint('Finished in (s):',time.time()-start_time)\n#dfGS.to_csv('graph_structure_2ndNN_ini.csv.gz', index=None, compression='gzip')", "Finished in (s): 58491.90770316124\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
d073717f2b36f3c9c99d2463adef04b2272bcbd7
958,112
ipynb
Jupyter Notebook
eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb
FangmingXie/scf_enhancer_paper
d7d80215daa4979afd45eaeb30ea31ec8deae864
[ "MIT" ]
null
null
null
eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb
FangmingXie/scf_enhancer_paper
d7d80215daa4979afd45eaeb30ea31ec8deae864
[ "MIT" ]
null
null
null
eran/.ipynb_checkpoints/Regress_June25_mc-checkpoint.ipynb
FangmingXie/scf_enhancer_paper
d7d80215daa4979afd45eaeb30ea31ec8deae864
[ "MIT" ]
1
2021-11-15T19:03:03.000Z
2021-11-15T19:03:03.000Z
357.104734
145,516
0.921818
[ [ [ "# Stage 1: Correlation for individual enhancers", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport time, re, datetime\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom scipy.stats import zscore\nimport random\n\nfrom multiprocessing import Pool,cpu_count\nnum_processors = cpu_count()\n\nprint('Starting analysis; %d processors; %s' % (num_processors, datetime.datetime.today()))\nt00 =time.time()\n\n# np.random.seed(0)\nimport sys\nsys.path.insert(0, '/cndd/fangming/CEMBA/snmcseq_dev')\nfrom __init__jupyterlab import *\nimport snmcseq_utils", "Starting analysis; 40 processors; 2020-06-27 13:16:21.271673\n" ], [ "today=datetime.datetime.today().strftime('%d-%m-%Y')\nuse_kmers = False\ncorr_type = 'Pearson' # corr_type = 'Spearman'\nfeatures_use = 'mCG+ATAC'\n\nanalysis_prefix = 'eran_model_{}'.format(features_use)\n\noutput_fig = '/cndd2/fangming/projects/scf_enhancers/results/figures/{}_{{}}_{}.pdf'.format(analysis_prefix, today)\noutput = '/cndd2/fangming/projects/scf_enhancers/results/{}_{{}}_{}'.format(analysis_prefix, today)", "_____no_output_____" ], [ "# fn_load_prefix = 'RegressData/Regress_data_6143genes_19cells_'\n# fn_load_prefix = 'RegressData/Regress_data_6174genes_20cells_'\nfn_load_prefix = 'RegressData/Regress_data_9811genes_24cells_'\n\n# Load datasets\nsave_vars = ['genes2enhu', 'rnau', 'df_mlevelu', 'df_atacu', 'genes']\n# save_vars = ['rnau','genes']\nfor var in save_vars:\n fn = fn_load_prefix+var+'.pkl'\n cmd = '%s=pd.read_pickle(\"%s\")' % (var, fn)\n exec(cmd)\n print('Loaded %s from %s' % (var, fn))\n\nif use_kmers:\n with np.load(fn_load_prefix+'kmer_countsu.npz', allow_pickle=True) as x:\n kmer_countsu=x['kmer_countsu']\n kmer_countsu = kmer_countsu/kmer_countsu.shape[1]/100\n \n # Testing:\n kmer_countsu = kmer_countsu[:,:2]\n \n print('Kmers shape: ', kmer_countsu.shape)\n Nk=kmer_countsu.shape[1]\n print('Loaded kmers')\nelse:\n Nk=0\n \n# Cell type names\ndf_cellnames = pd.read_csv(\n '/cndd/Public_Datasets/CEMBA/BICCN_minibrain_data/data_freeze/supp_info/clusters_final/cluster_annotation_scf_round2.tsv',\n sep='\\t', index_col='cluster')", "Loaded genes2enhu from RegressData/Regress_data_9811genes_24cells_genes2enhu.pkl\nLoaded rnau from RegressData/Regress_data_9811genes_24cells_rnau.pkl\nLoaded df_mlevelu from RegressData/Regress_data_9811genes_24cells_df_mlevelu.pkl\nLoaded df_atacu from RegressData/Regress_data_9811genes_24cells_df_atacu.pkl\nLoaded genes from RegressData/Regress_data_9811genes_24cells_genes.pkl\n" ], [ "genes2enhu = genes2enhu.iloc[[i in genes.index for i in genes2enhu['ensid']],:]\ngenes2enhu.shape, genes2enhu.index.unique().shape\n\ncelltypes = df_mlevelu.columns\nassert np.all(celltypes == df_atacu.columns)", "_____no_output_____" ], [ "if (features_use=='mCG'):\n x = df_mlevelu.loc[genes2enhu['enh_pos'],:].to_numpy()\nelif (features_use=='ATAC'):\n x = df_atacu.loc[genes2enhu['enh_pos'],:].to_numpy()\nelif (features_use=='mCG_ATAC'):\n x1 = df_mlevelu.loc[genes2enhu['enh_pos'],:].to_numpy()\n x2 = df_atacu.loc[genes2enhu['enh_pos'],:].to_numpy()\n x = f_mcg(x1) * f_atac(x2)\nelif (features_use=='mCG+ATAC'):\n x1 = df_mlevelu.loc[genes2enhu['enh_pos'],:].to_numpy()\n x2 = df_atacu.loc[genes2enhu['enh_pos'],:].to_numpy()\nelse:\n x = []\n \ny = rnau.loc[genes2enhu['ensid'],:].to_numpy()", "_____no_output_____" ], [ "print(\n rnau.shape, # rna by celltype\n df_mlevelu.shape, # enh by cell type\n df_atacu.shape, # enh by cell type\n \n genes.shape, # gene annotation\n genes2enhu.shape, # gene-enh pair \n \n x1.shape, # enh_mcg by cell type (mcg_enh for each enh-gene pair) how ?\n x2.shape, # enh_atac by cell type (mcg_enh for each enh-gene pair) how ?\n y.shape, # rna by cell type (rna for each enh-gene pair)\n )", "(9811, 24) (242461, 24) (242461, 24) (51809, 6) (468604, 13) (468604, 24) (468604, 24) (468604, 24)\n" ], [ "def my_cc(x,y,ensid,doshuff=False,jshuff=0,corr_type='Pearson',use_abs=True, doshuffgene=False,verbose=False):\n \"\"\"Calculate corr for each row of x and y\n x, y: enh_mcg/gene_rna (pair) vs celltype\n ensid: matched gene ensid for each row\n \n x, y contains no nan; but constant rows of x and y produces nan with zscoring\n \"\"\"\n t0=time.time()\n seed = int(time.time()*1e7 + jshuff) % 100\n np.random.seed(seed)\n \n ngenes, ncells = y.shape\n print('Computing correlations for %d gene-enhancer pairs; jshuff=%d; ' % (ngenes, jshuff))\n if doshuff:\n y = y[:,np.random.permutation(ncells)] # permute cells\n if doshuffgene:\n y = y[np.random.permutation(ngenes),:] # permute genes (pairs)\n\n if (corr_type=='Spearman'):\n y = np.argsort(y,axis=1)\n x = np.argsort(x,axis=1)\n xz = zscore(x, axis=1, nan_policy='propagate', ddof=0)\n yz = zscore(y, axis=1, nan_policy='propagate', ddof=0)\n xy_cc = np.nan_to_num(np.nanmean(xz*yz, axis=1)) # turn np.nan into zero\n\n xy_cc_df = pd.DataFrame(data=xy_cc, columns=['cc'])\n xy_cc_df['enh_num'] = np.arange(ngenes)\n xy_cc_df['ensid'] = ensid.values\n xy_cc_df['cc_abs'] = np.abs(xy_cc_df['cc'])\n if use_abs: # max abs_corr for each gene\n xy_cc_df = xy_cc_df.sort_values(['ensid','cc_abs'],\n ascending=[True,False]).drop_duplicates(['ensid'])\n else: # max corr for each gene \n xy_cc_df = xy_cc_df.sort_values(['ensid','cc'],\n ascending=[True,False]).drop_duplicates(['ensid'])\n best_cc = xy_cc_df['cc'] # corr (not abs)\n best_enh = xy_cc_df['enh_num'] # enh\n best_ensid = xy_cc_df['ensid'] # gene\n if verbose:\n print('t=%3.3f' % (time.time()-t0))\n \n return best_cc,best_enh,best_ensid,xy_cc\n\ndef my_cc_shuffgene(x, y, ensid, rnau, \n doshuff=False, jshuff=0,\n corr_type='Pearson', use_abs=True, \n doshuffgene=False,\n ):\n \"\"\"\n \"\"\"\n seed = int(time.time()*1e7 + jshuff) % 100\n \n rnau_shuff = rnau.copy()\n rnau_shuff.index = rnau.index.values[\n np.random.RandomState(seed=seed).permutation(len(rnau))\n ]\n y_shuff = rnau_shuff.loc[ensid,:].to_numpy()\n \n return my_cc(x, y_shuff, ensid, \n doshuff, jshuff,\n corr_type, use_abs, \n doshuffgene,\n )", "_____no_output_____" ], [ "def corr_pipe(x, y, genes2enhu, rnau, corr_type,):\n \"\"\"\n \"\"\"\n # observed\n best_cc, best_enh, best_ensid, all_cc = my_cc(x,y,genes2enhu['ensid'],False,0,corr_type,True,False)\n print(best_cc.shape, best_enh.shape, best_ensid.shape, all_cc.shape)\n\n # shuffled\n nshuff = np.min((num_processors*16,128))\n np.random.seed(0)\n with Pool(processes = num_processors) as p:\n best_cc_shuff_list = p.starmap(my_cc_shuffgene, \n [(x,y,genes2enhu['ensid'],rnau,False,jshuff,corr_type,True,False) for jshuff in range(nshuff)])\n\n # significance\n alpha = 0.01;\n best_cc_shuff = np.hstack([b[0].values[:,np.newaxis] for b in best_cc_shuff_list]) # gene (best corr) by num_shuff\n best_cc_shuff_max = np.percentile(np.abs(best_cc_shuff), 100*(1-alpha), axis=1) # get 99% (robust max) across shuffles \n best_cc_shuff_mean = np.abs(best_cc_shuff).mean(axis=1) # get mean across shuffles for each gene\n sig = np.abs(best_cc).squeeze()>best_cc_shuff_max # corr greater than 99% of the shuffled\n fdr = (alpha*len(sig))/np.sum(sig) # fdr - alpha\n \n print(np.sum(sig), len(sig), alpha, fdr)\n \n return best_cc, best_enh, best_ensid, all_cc, best_cc_shuff, best_cc_shuff_max, best_cc_shuff_mean, sig, fdr \n", "_____no_output_____" ], [ "import warnings\nwarnings.filterwarnings('ignore') \n\n(best_cc_1, best_enh_1, best_ensid_1, all_cc_1, \n best_cc_shuff_1, best_cc_shuff_max_1, best_cc_shuff_mean_1, sig_1, fdr_1,\n) = corr_pipe(x1, y, genes2enhu, rnau, corr_type,)\n\n(best_cc_2, best_enh_2, best_ensid_2, all_cc_2, \n best_cc_shuff_2, best_cc_shuff_max_2, best_cc_shuff_mean_2, sig_2, fdr_2,\n) = corr_pipe(x2, y, genes2enhu, rnau, corr_type,)", "Computing correlations for 468604 gene-enhancer pairs; jshuff=0; \n(9811,) (9811,) (9811,) (468604,)\nComputing correlations for 468604 gene-enhancer pairs; jshuff=0; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=1; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=2; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=3; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=4; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=5; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=6; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=8; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=7; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=9; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=10; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=11; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=12; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=13; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=14; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=15; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=16; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=17; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=18; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=19; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=20; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=21; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=22; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=23; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=24; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=25; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=26; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=27; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=28; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=29; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=30; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=31; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=32; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=33; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=34; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=35; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=36; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=37; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=38; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=39; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=40; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=41; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=42; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=43; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=44; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=45; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=46; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=47; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=48; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=49; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=50; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=51; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=52; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=53; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=54; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=55; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=56; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=57; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=58; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=59; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=60; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=61; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=62; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=63; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=64; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=65; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=66; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=67; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=68; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=69; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=70; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=71; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=72; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=73; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=74; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=75; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=76; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=77; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=78; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=79; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=80; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=81; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=82; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=83; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=84; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=85; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=86; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=87; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=88; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=89; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=90; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=91; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=92; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=93; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=94; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=95; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=96; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=97; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=98; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=99; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=100; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=101; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=102; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=103; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=104; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=105; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=106; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=107; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=108; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=109; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=110; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=111; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=112; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=113; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=114; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=115; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=116; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=117; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=118; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=119; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=120; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=121; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=122; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=123; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=124; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=125; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=126; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=127; \n1058 9811 0.01 0.0927315689981\nComputing correlations for 468604 gene-enhancer pairs; jshuff=0; \n(9811,) (9811,) (9811,) (468604,)\nComputing correlations for 468604 gene-enhancer pairs; jshuff=0; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=1; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=2; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=3; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=4; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=5; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=6; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=7; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=8; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=9; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=10; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=11; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=12; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=13; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=15; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=14; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=16; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=18; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=17; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=19; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=20; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=21; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=22; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=23; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=24; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=25; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=27; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=26; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=28; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=29; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=30; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=31; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=33; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=32; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=34; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=35; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=36; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=37; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=38; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=39; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=40; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=41; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=42; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=43; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=44; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=45; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=46; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=47; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=48; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=49; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=50; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=51; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=52; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=53; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=54; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=55; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=56; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=57; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=58; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=59; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=60; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=61; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=62; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=63; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=64; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=65; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=66; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=67; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=68; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=69; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=70; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=71; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=72; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=73; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=74; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=75; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=76; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=77; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=78; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=79; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=80; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=81; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=82; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=83; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=84; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=85; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=86; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=87; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=88; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=89; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=90; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=91; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=92; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=93; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=94; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=95; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=96; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=97; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=98; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=99; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=100; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=101; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=102; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=103; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=104; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=105; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=106; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=107; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=108; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=109; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=110; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=111; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=112; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=113; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=114; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=115; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=116; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=117; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=118; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=119; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=120; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=121; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=122; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=123; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=124; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=125; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=126; \nComputing correlations for 468604 gene-enhancer pairs; jshuff=127; \n358 9811 0.01 0.27405027933\n" ], [ "def plot_dists(best_cc, best_enh, best_ensid, all_cc, \n best_cc_shuff, best_cc_shuff_max, best_cc_shuff_mean, \n sig, fdr, alpha,\n feature):\n ngenes = best_cc.shape[0]\n\n fig, axs = plt.subplots(3,1,figsize=(5,10))\n ax = axs[0]\n ax.scatter(best_cc, best_cc_shuff_mean,\n s=2,c=sig,\n cmap=ListedColormap([\"gray\",'red']), \n rasterized=True,\n )\n ax.plot([-1,0,1],[1,0,1],'k--')\n ax.set_xlabel('Max %s correlation' % corr_type)\n ax.set_ylabel('Max %s correlation\\n(Mean of shuffles)' % corr_type)\n ax.set_title('%s\\n%d/%d=%3.1f%%\\nsig. genes (p<%3.2g, FDR=%3.1f%%)' % (\n feature, \n sig.sum(),ngenes,\n 100*sig.sum()/ngenes,\n alpha, fdr*100), )\n\n ax = axs[1]\n bins = np.arange(-2,2,0.1)\n hist_config = {\n 'histtype': 'bar', \n 'edgecolor': 'none',\n 'alpha': 0.5, \n 'density': False, \n }\n _vec = best_cc.squeeze()/best_cc_shuff_mean.squeeze()\n cond_pos_sig = np.logical_and(sig, best_cc > 0)\n cond_neg_sig = np.logical_and(sig, best_cc <= 0)\n\n ax.hist(_vec, bins=bins,\n color='gray', label='All genes', \n **hist_config,\n )\n ax.hist(_vec[sig], bins=bins,\n color='red', label='Significant', \n **hist_config,\n )\n ax.axvline(-1, linestyle='--', color='k')\n ax.axvline(1, linestyle='--', color='k')\n\n ax.set_xlabel(corr_type+' correlation/(Mean abs. corr. of shuffles)')\n ax.set_ylabel('Number of genes')\n num_sig, num_pos_sig, num_neg_sig = (sig.sum(), \n cond_pos_sig.sum(),\n cond_neg_sig.sum(),\n )\n ax.set_title(\"Num. pos={} ({:.1f}%)\\nNum. neg={} ({:.1f}%)\".format(\n num_pos_sig, num_pos_sig/num_sig*100, \n num_neg_sig, num_neg_sig/num_sig*100,\n ))\n\n ax.legend(bbox_to_anchor=(1,1))\n\n ax = axs[2]\n bins = bins=np.arange(0,1,0.02)\n hist_config = {\n 'histtype': 'bar', \n 'edgecolor': 'none',\n 'alpha': 0.5, \n 'density': True, \n }\n ax.hist(np.abs(all_cc), bins=bins,\n color='C1',\n label='All enh-gene pairs',\n **hist_config,\n )\n ax.hist(best_cc_shuff.reshape(-1,1), bins=bins,\n color='gray',\n label='Best (all shuffles)',\n **hist_config,\n )\n ax.hist(best_cc_shuff_max, bins=bins,\n color='C2',\n label='Best (max. shuffle)',\n **hist_config,\n )\n ax.hist(best_cc_shuff_mean, bins=bins,\n color='C0',\n label='Best (mean shuffle)',\n **hist_config,\n )\n ax.hist(best_cc.squeeze(), bins=bins,\n color='C3',\n label='Best (data)',\n **hist_config,\n )\n ax.legend(bbox_to_anchor=(1,1))\n ax.set_xlabel(corr_type+' correlation')\n ax.set_ylabel('Density of genes')\n\n fig.subplots_adjust(hspace=0.9)\n fn_plot = output.format(\"genes_corr_\"+feature+'_'+corr_type)\n snmcseq_utils.savefig(fig, fn_plot)\n print('Saved %s' % fn_plot)\n", "_____no_output_____" ], [ "alpha = 0.01\n\nfeature = 'mCG'\nplot_dists(best_cc_1, best_enh_1, best_ensid_1, all_cc_1, \n best_cc_shuff_1, best_cc_shuff_max_1, best_cc_shuff_mean_1, sig_1, fdr_1, alpha, \n feature)\n\nfeature = 'ATAC'\nplot_dists(best_cc_2, best_enh_2, best_ensid_2, all_cc_2, \n best_cc_shuff_2, best_cc_shuff_max_2, best_cc_shuff_mean_2, sig_2, fdr_2, alpha,\n feature)", "Saved /cndd2/fangming/projects/scf_enhancers/results/eran_model_mCG+ATAC_genes_corr_mCG_Pearson_27-06-2020\nSaved /cndd2/fangming/projects/scf_enhancers/results/eran_model_mCG+ATAC_genes_corr_ATAC_Pearson_27-06-2020\n" ], [ "# np.savez(\n# output.format('GenesCorr_%s_%s.npz' % (features_use, today)), \n# best_cc=best_cc,best_enh=best_enh,best_ensid=best_ensid,\n# sig=sig, best_cc_shuff=best_cc_shuff)\n# print('Saved data; t=%3.3f; %s' % (time.time()-t00, datetime.datetime.today()))", "_____no_output_____" ], [ "# check randomness\n\n# plt.scatter(np.arange(best_cc_shuff.shape[1]), best_cc_shuff[0])\n# plt.scatter(np.arange(best_cc_shuff.shape[1]), best_cc_shuff[1])\n# plt.scatter(np.arange(best_cc_shuff.shape[1]), best_cc_shuff[2])\n# plt.title(\"num_processors = {}\".format(num_processors))\n# plt.xlabel('n shuffle')\n# plt.ylabel('corr for a gene-enh pair')", "_____no_output_____" ], [ "genes2enhu.head()", "_____no_output_____" ], [ "genes2enhu['cc'] = all_cc\n\nbest_ensid_inv = pd.Series(best_ensid.index.values, index=best_ensid)\ni = best_ensid_inv.loc[genes2enhu.index].values\ngenes2enhu['best_cc'] = genes2enhu.iloc[i,:]['cc']\n\ni = pd.Series(np.arange(best_ensid.shape[0]), index=best_ensid)\ngenes2enhu['best_cc_shuff_max'] = best_cc_shuff_max[i.loc[genes2enhu.index]]\nisig = sig[best_ensid_inv.loc[genes2enhu.index]].values\ngenes2enhu['sig'] = (genes2enhu['cc'].abs() >= genes2enhu['best_cc_shuff_max'].abs()) \ngenes2enhu['nonsig'] = (genes2enhu['cc'].abs() < genes2enhu['best_cc_shuff_max'].abs())", "_____no_output_____" ], [ "# How many enhancers are \n# best_cc_shuff_max\nnsig = genes2enhu.groupby(level=0).sum()[['sig','nonsig']]\nnsig['best_cc'] = best_cc.values\nplt.semilogy(nsig['best_cc'], nsig['sig'], '.',\n markersize=5);", "_____no_output_____" ], [ "# top significant genes\nnsig['gene_name'] = genes2enhu.loc[nsig.index,:]['gene_name'].drop_duplicates()\nnsig.sort_values('sig').iloc[-10:,:]", "_____no_output_____" ], [ "def my_cdfplot(ax, x, label=''):\n ax.semilogx(np.sort(np.abs(x)), np.linspace(0,1,len(x)), \n label='%s (%d)\\nd=%3.1f±%3.1f kb' %\n (label, len(x), x.mean()/1000, x.std()/1000/np.sqrt(len(x))))\n return\n\n\nfig, axs = plt.subplots(1, 2, figsize=(8,5))\nax = axs[0]\nhist_config = {\n 'histtype': 'bar', \n 'edgecolor': 'none',\n 'alpha': 1, \n 'density': False, \n}\nax.hist(nsig['sig'].values, bins=np.arange(100),\n **hist_config\n )\nax.set_xlabel('Number of significant enhancers')\nax.set_ylabel('Number of genes')\nax.set_yscale('log')\n\nax = axs[1]\nmy_cdfplot(ax, nsig['sig'].values,)\nax.set_xlabel('Number of significant enhancers')\nax.set_ylabel('Cumulative fraction of genes')\nfig.tight_layout()\n\nsnmcseq_utils.savefig(fig, \n output_fig.format('GenesCorr_NumSigEnh_%s_%s_%s.pdf' % (features_use, today, corr_type))\n )\n", "_____no_output_____" ] ], [ [ "# Stage 1.5: Compare ATAC and mC ", "_____no_output_____" ] ], [ [ "print(all_cc_1.shape, best_cc_1.shape, sig_1.shape, best_cc_1[sig_1].shape, best_ensid_1.shape, best_enh_1.shape)\n\n# best_cc_1[sig_1]\nall_cc_2[best_enh_1[sig_1].index.values].shape", "(468604,) (9811,) (9811,) (1058,) (9811,) (9811,)\n" ], [ "fig, ax = plt.subplots()\n\nax.scatter(all_cc_1, all_cc_2, \n color='lightgray', s=1, alpha=0.3, \n rasterized=True,)\nax.scatter(\n all_cc_1[best_enh_1.index.values], # same as best_cc_1[sig_1]\n all_cc_2[best_enh_1.index.values],\n color='lightblue', label='best mCG', \n s=1, alpha=0.5, \n rasterized=True,)\nax.scatter(\n all_cc_1[best_enh_2.index.values], # same as best_cc_1[sig_1]\n all_cc_2[best_enh_2.index.values],\n color='wheat', label='best ATAC',\n s=1, alpha=0.5, \n rasterized=True,)\n\nax.scatter(\n all_cc_1[best_enh_1[sig_1].index.values], # same as best_cc_1[sig_1]\n all_cc_2[best_enh_1[sig_1].index.values],\n color='C0', label='sig. mCG',\n s=1, alpha=0.5, \n rasterized=True,)\nax.scatter(\n all_cc_1[best_enh_2[sig_2].index.values], # same as best_cc_1[sig_1]\n all_cc_2[best_enh_2[sig_2].index.values],\n color='C1', label='sig. ATAC',\n s=1, alpha=0.5, \n rasterized=True,)\n\nax.legend(bbox_to_anchor=(1,1))\n\nax.set_xlabel('mCG-RNA {} corr'.format(corr_type))\nax.set_ylabel('ATAC-RNA {} corr'.format(corr_type))\n\nsnmcseq_utils.savefig(fig, \n output_fig.format('mCG_ATAC_agreement_%s_%s_%s.pdf' % (features_use, today, corr_type))\n )\nplt.show()", "_____no_output_____" ], [ "fig, ax = plt.subplots()\nax.scatter(\n all_cc_1[best_enh_1.index.values], # same as best_cc_1[sig_1]\n all_cc_2[best_enh_1.index.values],\n color='lightgray', label='best', \n s=1, alpha=0.3, \n rasterized=True,)\nax.scatter(\n all_cc_1[best_enh_2.index.values], # same as best_cc_1[sig_1]\n all_cc_2[best_enh_2.index.values],\n color='lightgray', label='best', \n s=1, alpha=0.5, \n rasterized=True,)\n\nax.scatter(\n all_cc_1[best_enh_1[sig_1].index.values], # same as best_cc_1[sig_1]\n all_cc_2[best_enh_1[sig_1].index.values],\n color='C0', label='sig. mCG',\n s=1, alpha=0.5, \n rasterized=True,)\nax.scatter(\n all_cc_1[best_enh_2[sig_2].index.values], # same as best_cc_1[sig_1]\n all_cc_2[best_enh_2[sig_2].index.values],\n color='C1', label='sig. ATAC',\n s=1, alpha=0.5, \n rasterized=True,)\n\n\nax.legend(bbox_to_anchor=(1,1))\n\nax.set_xlabel('mCG-RNA {} corr'.format(corr_type))\nax.set_ylabel('ATAC-RNA {} corr'.format(corr_type))\n\nsnmcseq_utils.savefig(fig, \n output_fig.format('mCG_ATAC_agreement2_%s_%s_%s.pdf' % (features_use, today, corr_type))\n )\nplt.show()", "_____no_output_____" ], [ "\nfrom matplotlib_venn import venn2\n\nfig, ax = plt.subplots()\nvenn2([set(best_ensid_1[sig_1].values), set(best_ensid_2[sig_2].values)], \n set_labels=('sig. mCG', 'sig. ATAC'), \n set_colors=('C0', 'C1'),\n ax=ax\n )\nax.set_title('Overlap of sig. genes')\nsnmcseq_utils.savefig(fig, \n output_fig.format('mCG_ATAC_agreement3_%s_%s_%s.pdf' % (features_use, today, corr_type))\n )\nplt.show()", "_____no_output_____" ], [ "fig, ax = plt.subplots()\nvenn2([set(sig_1[sig_1].index.values), set(sig_2[sig_2].index.values)], \n set_labels=('sig. mCG', 'sig. ATAC'), \n set_colors=('C0', 'C1'),\n ax=ax\n )\nax.set_title('Overlap of sig. gene-enhancer pairs')\nsnmcseq_utils.savefig(fig, \n output_fig.format('mCG_ATAC_agreement4_%s_%s_%s.pdf' % (features_use, today, corr_type))\n )\nplt.show()", "_____no_output_____" ] ], [ [ "# Stage 2: Regression modeling across sig. genes ", "_____no_output_____" ] ], [ [ "# Are there any duplicate enhancers?\n\n_x = genes2enhu.iloc[(best_enh_1[sig_1].values),:]\nnenh_sig = len(_x)\nnenh_sig_unique = len(_x['enh_pos'].unique())\nnenh_sig_genes_unique = len(_x['ensid'].unique())\nprint(nenh_sig, nenh_sig_unique, nenh_sig_genes_unique)", "1058 1041 1058\n" ], [ "# best_enh_1[sig_1]", "_____no_output_____" ], [ "# get sig. mC enhancer-gene pairs (1 for each gene) only\nmc_u = df_mlevelu.loc[genes2enhu['enh_pos'],:].to_numpy()[best_enh_1[sig_1],:]\natac_u = df_atacu.loc[genes2enhu['enh_pos'],:].to_numpy()[best_enh_1[sig_1],:]\nrna_u = rnau.loc[genes2enhu['ensid'],:].to_numpy()[best_enh_1[sig_1],:].copy()\n\ngenes2enhu_u = genes2enhu.iloc[best_enh_1[sig_1],:].copy()\ngenes2enhu_u = genes2enhu_u.drop('ensid',axis=1).reset_index()", "_____no_output_____" ], [ "# genes2enhu.iloc[(best_enh_1[sig_1].values),:]['enh_pos'].shape", "_____no_output_____" ], [ "# cc_mc_rna = np.array([np.corrcoef(x1,y1)[0,1] for (x1,y1) in zip(mc_u,rna_u)])\n# cc_atac_rna = np.array([np.corrcoef(x1,y1)[0,1] for (x1,y1) in zip(atac_u,rna_u)])", "_____no_output_____" ], [ "# genes2enhu_u.loc[:,'cc_mc_rna'] = cc_mc_rna\n# genes2enhu_u.loc[:,'cc_atac_rna'] = cc_atac_rna\n# genes2enhu_u.sort_values('cc_mc_rna')\n# # genes2enhu_u['cc_atac_rna'] = cc_atac_rna", "_____no_output_____" ], [ "# fig, ax = plt.subplots()\n# sig_pos = (genes2enhu_u['cc_mc_rna']<0) & (genes2enhu_u['cc_atac_rna']>0)\n# sig_neg = (genes2enhu_u['cc_mc_rna']>0) & (genes2enhu_u['cc_atac_rna']<-0)\n\n# ax.plot(cc_mc_rna, cc_atac_rna, '.', color='gray', label='%d significnat pairs' % np.sum(sig))\n# ax.plot(cc_mc_rna[sig_pos], cc_atac_rna[sig_pos], 'r.', label='%d corr pairs' % np.sum(sig_pos))\n# ax.plot(cc_mc_rna[sig_neg], cc_atac_rna[sig_neg], 'g.', label='%d anti-corr pairs' % np.sum(sig_neg))\n# ax.set_xlabel('Correlation mCG vs. RNA')\n# ax.set_ylabel('Correlation ATAC vs. RNA')\n# ax.legend(bbox_to_anchor=(1,1))\n\n# print('We found %d significant enhancer-gene links, covering %d unique enhancers and %d unique genes' %\n# (nenh_sig, nenh_sig_unique, nenh_sig_genes_unique))\n# print('%d of these have the expected correlation (negative for mCG, positive for ATAC)' %\n# (np.sum(sig_pos)))\n# print('%d of these have the opposite correlation (positive for mCG, negative for ATAC)' %\n# (np.sum(sig_neg)))\n# snmcseq_utils.savefig(fig, output_fig.format(\n# 'EnhancerRegression_SigEnhancers_scatter_mCG_ATAC_corr_%dGenes_%dCelltypes_%s' % \n# (genes2enhu.ensid.unique().shape[0], len(celltypes), today)\n# ))", "_____no_output_____" ], [ "# fig, ax = plt.subplots(figsize=(7,4))\n# my_cdfplot(ax, genes2enhu['dtss'], label='All pairs')\n# my_cdfplot(ax, genes2enhu_u['dtss'], label='Best pair for each gene')\n# my_cdfplot(ax, genes2enhu_u['dtss'][sig_pos], label='Positive corr')\n# my_cdfplot(ax, genes2enhu_u['dtss'][sig_neg], label='Negative corr')\n\n# ax.legend(bbox_to_anchor=(1, 0.8))\n# ax.set_xlim([1e3,3e5])\n# ax.set_xlabel('Distance of enhancer from TSS')\n# ax.set_ylabel('Cumulative fraction')\n# ax.set_yticks(ticks=[0,.25,.5,.75,1]);\n# snmcseq_utils.savefig(fig, output_fig.format(\n# 'EnhancerRegression_SigEnhancers_dTSS_cdf_%dGenes_%dCelltypes_%s' % \n# (genes2enhu.ensid.unique().shape[0], len(celltypes), today)\n# ))", "_____no_output_____" ], [ "# Ordinary linear regression with CV\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.metrics import r2_score, make_scorer\nfrom sklearn.preprocessing import PolynomialFeatures\n\nX = np.concatenate((mc_u,atac_u),axis=1).copy()\ny = np.log10(rna_u+1).copy()\n\nX = zscore(X, axis=0)\ny = zscore(y, axis=0)\ny = y - np.mean(y,axis=1,keepdims=True)\n\n# X = X[sig_pos,:]\n# y = y[sig_pos,:]\n\n\nmdl = LinearRegression(fit_intercept=True, normalize=True)\nngenes,ncells = y.shape\nprint('%d genes, %d celltypes' % (ngenes,ncells))\n\nintxn_order = 3\n\nmy_r2 = make_scorer(r2_score)\nres_cv = {}\ncv = 5\nfor i,yi in enumerate(y.T):\n # Regression using only mCG and ATAC from the same cell type\n Xu = X[:,[i,i+ncells]]\n Xu = np.concatenate((X[:,[i,i+ncells]],\n# np.mean(X[:,:ncells],axis=1,keepdims=True),\n# np.mean(X[:,ncells:],axis=1,keepdims=True),\n ),axis=1)\n# Xu = PolynomialFeatures(degree=3, include_bias=False).fit_transform(Xu)\n\n res_cvi = cross_validate(mdl,Xu,yi,cv=cv,\n scoring=my_r2,\n return_train_score=True,\n verbose=0)\n if i==0:\n print('Simple model: %d parameters' % Xu.shape[1])\n dof_simple=Xu.shape[1]\n for m in res_cvi:\n if (m in res_cv):\n res_cv[m] = np.vstack((res_cv[m], res_cvi[m]))\n else:\n res_cv[m]=res_cvi[m]\n \n # Regression using mCG and ATAC from the same cell type, as well as the mean across all cell types\n\n# res_cvi = cross_validate(mdl,X,yi,cv=cv,\n# scoring=my_r2,\n# return_train_score=True,\n# verbose=0)\n Xu = np.concatenate((X[:,[i,i+ncells]],\n np.mean(X[:,:ncells],axis=1,keepdims=True),\n np.mean(X[:,ncells:],axis=1,keepdims=True),\n ),axis=1)\n Xu = PolynomialFeatures(degree=intxn_order, include_bias=False).fit_transform(Xu)\n\n res_cvi = cross_validate(mdl, Xu, yi,\n cv=cv,\n scoring=my_r2,\n return_train_score=True,\n verbose=0)\n if i==0:\n print('Complex model: %d parameters' % Xu.shape[1])\n dof_complex=Xu.shape[1]\n\n for m1 in res_cvi:\n m = m1+'_all'\n if (m in res_cv):\n res_cv[m] = np.vstack((res_cv[m], res_cvi[m1]))\n else:\n res_cv[m]=res_cvi[m1]\n", "1058 genes, 24 celltypes\nSimple model: 2 parameters\nComplex model: 34 parameters\n" ], [ "cellnames = df_cellnames.loc[celltypes]['annot']\n\n# Show the OLS results\ndef myplot(ax, x, label='', fmt=''):\n x[x<0] = 0\n# xu = np.sqrt(x)\n xu = x\n ax.errorbar(cellnames, xu.mean(axis=1), xu.std(axis=1)/np.sqrt(cv),\n label=label, fmt=fmt)\n return \n \nfig, ax = plt.subplots(figsize=(8,6))\nmyplot(ax, res_cv['train_score'], \n fmt='rs-', label='Train simple model:\\nRNA~mCG+ATAC\\n(%d params)' % dof_simple)\nmyplot(ax, res_cv['test_score'], \n fmt='ro-', label='Test')\nmyplot(ax, res_cv['train_score_all'],\n fmt='bs--', label='Train complex model:\\nRNA~mCG+ATAC+mean(mCG)+mean(ATAC)+%dth order intxn\\n(%d params)' % \n (intxn_order, dof_complex))\nmyplot(ax, res_cv['test_score_all'],\n fmt='bo--', label='Test')\n\nax.legend(bbox_to_anchor=(1, 1))\nax.set_xlabel('Cell type')\nax.set_ylabel('Score (R^2)')\nax.xaxis.set_tick_params(rotation=90)\nax.grid(axis='y')\nax.set_title('%d genes, separate model for each of %d celltypes' % y.shape)\nsnmcseq_utils.savefig(fig, output_fig.format(\n 'EnhancerRegression_SigEnhancers_OLS_%dGenes_%dCelltypes_%s' % \n (genes2enhu.ensid.unique().shape[0], len(celltypes), today)\n ))", "_____no_output_____" ], [ "# # Multi-task LASSO regression with CV\n# from sklearn.linear_model import MultiTaskLassoCV\n\n# t0=time.time()\n# mdl = MultiTaskLassoCV(fit_intercept=True, normalize=True, cv=cv, \n# selection='random',\n# random_state=0)\n\n# X = np.concatenate((mc_u,atac_u),axis=1).copy()\n# y = np.log10(rna_u+1).copy()\n\n# X = zscore(X[sig_pos,:], axis=0)\n# y = zscore(np.log10(y[sig_pos,:]+1), axis=0)\n\n# reg = mdl.fit(X,y)\n# print('Done fitting LASSO, t=%3.3f s' % (time.time()-t0))", "_____no_output_____" ], [ "# plt.errorbar(reg.alphas_, reg.mse_path_.mean(axis=1), reg.mse_path_.std(axis=1))\n# plt.vlines(reg.alpha_, plt.ylim()[0], plt.ylim()[1], 'k')\n# plt.xscale('log')", "_____no_output_____" ], [ "# Single task LASSO with CV, interaction terms\nfrom sklearn.linear_model import LassoCV\n\nXu_all = []\nfor i,yi in enumerate(y.T):\n Xu = np.concatenate((X[:,[i,i+ncells]],\n np.mean(X[:,:ncells],axis=1,keepdims=True),\n np.mean(X[:,ncells:],axis=1,keepdims=True),\n ),axis=1)\n Xu_all.append(Xu.T)\n\nXu_all = np.dstack(Xu_all).reshape(4,-1).T\nXu_fit = PolynomialFeatures(degree=intxn_order, include_bias=False)\n\nXu_all = Xu_fit.fit_transform(Xu_all)\nfeature_names = Xu_fit.get_feature_names(input_features=['mC','A','mCm','Am'])", "_____no_output_____" ], [ "print(Xu_all.shape, y.shape)\nyu = y.ravel()\nprint(Xu_all.shape, yu.shape)\n\nt0=time.time()\nmdl = LassoCV(fit_intercept=True, normalize=True, cv=cv, \n selection='random',\n random_state=0,\n n_jobs=8)\nreg = mdl.fit(Xu_all,yu)\nprint('Done fitting LASSO, t=%3.3f s' % (time.time()-t0))", "(25392, 34) (1058, 24)\n(25392, 34) (25392,)\nDone fitting LASSO, t=1.090 s\n" ], [ "plt.errorbar(reg.alphas_, reg.mse_path_.mean(axis=1), reg.mse_path_.std(axis=1))\nplt.vlines(reg.alpha_, plt.ylim()[0], plt.ylim()[1], 'k')\nplt.xscale('log')\nplt.xlabel('LASSO Regularization (lambda)')\nplt.ylabel('MSE')", "_____no_output_____" ], [ "yhat = reg.predict(Xu_all).reshape(y.shape)\ncc = [np.corrcoef(y1,y1hat)[0,1] for (y1,y1hat) in zip(y.T,yhat.T)]\n\nfig, ax = plt.subplots(figsize=(10,5))\nax.plot(cellnames, np.power(cc, 2), 'o-', color='C1', label='LASSO fit, single model for all cell types')\n# myplot(ax, res_cv['test_score_all'], label='Test (RNA~mCG+ATAC+mean(mCG)+mean(ATAC)+Intxn)', fmt='o--')\n\nmyplot(ax, res_cv['train_score'], \n fmt='rs-', label='Train simple model:\\nRNA~mCG+ATAC\\n(%d params)' % dof_simple)\nmyplot(ax, res_cv['test_score'], \n fmt='ro-', label='Test')\nmyplot(ax, res_cv['train_score_all'],\n fmt='bs--', label='Train complex model:\\nRNA~mCG+ATAC+mean(mCG)+mean(ATAC)+%dth order intxn\\n(%d params)' % \n (intxn_order, dof_complex))\nmyplot(ax, res_cv['test_score_all'],\n fmt='bo--', label='Test')\n\n\nax.legend(bbox_to_anchor=(1, 0.8))\n\nax.set_xlabel('Cell type')\nax.set_ylabel('Score (R^2)')\nax.xaxis.set_tick_params(rotation=90)\nax.grid(axis='y')\nax.set_ylim([0,0.8])\nax.set_title('Model for %d genes across %d celltypes' % y.shape)\n\nsnmcseq_utils.savefig(fig, output_fig.format(\n 'EnhancerRegression_SigEnhancers_CompareLASSO_%dGenes_%dCelltypes_%s' % \n (genes2enhu.ensid.unique().shape[0], len(celltypes), today)\n ))\n", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize=(10,5))\nshow = np.abs(reg.coef_)>0.01\nshow = np.argsort(np.abs(reg.coef_))[-30:][::-1]\nax.bar(np.array(feature_names)[show], reg.coef_[show])\nax.xaxis.set_tick_params(rotation=90)\nax.set_ylabel('Regression coefficient')\nax.grid(axis='y')\nsnmcseq_utils.savefig(fig, output_fig.format(\n 'EnhancerRegression_SigEnhancers_LASSO_CorrCoef_%dGenes_%dCelltypes_%s' % \n (genes2enhu.ensid.unique().shape[0], len(celltypes), today)\n ))", "_____no_output_____" ] ], [ [ "# Apply the nonlinear model to all enhancer", "_____no_output_____" ] ], [ [ "mc_u = df_mlevelu.loc[genes2enhu['enh_pos'],:].to_numpy()\n\natac_u = df_atacu.loc[genes2enhu['enh_pos'],:].to_numpy()\ngenes2enhu_u = genes2enhu.copy()\ngenes2enhu_u = genes2enhu_u.drop('ensid',axis=1).reset_index()\n\nrna_u = rnau.loc[genes2enhu['ensid'],:].to_numpy()\n\nrna_u.shape, mc_u.shape, atac_u.shape", "_____no_output_____" ], [ "X = np.concatenate((mc_u,atac_u),axis=1).copy()\ny = np.log10(rna_u+1).copy()\n\nX = zscore(X, axis=0)\ny = zscore(y, axis=0)\ny = y - np.mean(y,axis=1,keepdims=True)\n\nX.shape, y.shape", "_____no_output_____" ], [ "Xu_all = []\nfor i,yi in enumerate(y.T):\n Xu = np.concatenate((X[:,[i,i+ncells]],\n np.mean(X[:,:ncells],axis=1,keepdims=True),\n np.mean(X[:,ncells:],axis=1,keepdims=True),\n ),axis=1)\n Xu_all.append(Xu.T)\n\nXu_all = np.dstack(Xu_all).reshape(4,-1).T\nXu_fit = PolynomialFeatures(degree=intxn_order, include_bias=False).fit(Xu_all)\nfeature_names = Xu_fit.get_feature_names(input_features=['mC','A','mCm','Am'])\nXu_all = PolynomialFeatures(degree=intxn_order, include_bias=False).fit_transform(Xu_all)\nXu_all.shape, y.shape", "_____no_output_____" ], [ "yhat = reg.predict(Xu_all).reshape(y.shape)", "_____no_output_____" ], [ "x = df_mlevelu.loc[genes2enhu['enh_pos'],:].to_numpy()\nbest_cc,best_enh,best_ensid,all_cc = my_cc(-x,y,genes2enhu['ensid'],False,0,corr_type)", "Computing correlations for 468604 gene-enhancer pairs; jshuff=0; \n" ], [ "(~np.isfinite(best_cc2)).sum()", "_____no_output_____" ], [ "best_cc2,best_enh2,best_ensid2,all_cc2 = my_cc(yhat,y,genes2enhu['ensid'],False,0,corr_type)", "_____no_output_____" ], [ "plt.figure(figsize=(10,10))\nplt.plot(np.abs(all_cc[best_enh]), np.abs(all_cc2[best_enh]), '.', markersize=1, rasterized=True)\nplt.plot(np.abs(all_cc[best_enh2]), np.abs(all_cc2[best_enh2]), '.', markersize=1, rasterized=True)\nplt.plot([0,1],[0,1],'k')", "_____no_output_____" ], [ "np.abs(best_cc2)/(np.abs(best_cc)+1e-6)\nbest_cc2.shape, best_cc.shape", "_____no_output_____" ], [ "plt.hist(np.abs(best_cc2).values/np.abs(best_cc).values, bins=np.arange(0.7,1.3,0.01));\nprint(np.abs(best_cc2).values/np.abs(best_cc).values.mean())", "_____no_output_____" ], [ "# For each gene, find all enhancers with significant cc\ndf = pd.DataFrame(data=all_cc, columns=['cc'], index=genes2enhu[['ensid','enh_pos']])\ndf['ensid'] = genes2enhu['ensid'].values\ndf['enh_pos'] = genes2enhu['enh_pos'].values\ndf['cc2'] = all_cc2", "_____no_output_____" ], [ "df['good_pairs'] = df['cc']>0.6\ndf['good_pairs2'] = df['cc2']>0.6\n\nnpairs_df=df.groupby('ensid')[['good_pairs','good_pairs2']].sum()", "_____no_output_____" ], [ "plt.loglog(npairs_df['good_pairs']+1,npairs_df['good_pairs2']+1,'.')\nplt.plot([1,1e3],[1,1e3],'k')", "_____no_output_____" ], [ "np.mean((npairs_df['good_pairs2']+1)/(npairs_df['good_pairs']+1))", "_____no_output_____" ] ], [ [ "# Average over all the enhancers linked to a single gene", "_____no_output_____" ] ], [ [ "def myz(x):\n z = zscore(x, axis=1, nan_policy='omit', ddof=0)\n return z\ndef make_df(z):\n z_df = pd.DataFrame(data=z, columns=df_mlevelu.columns, index=rnau.index)\n return z_df\n\nmultiEnh = {}\nmultiEnh['rna'] = myz(rnau.values);\nmultiEnh['rna_hat_1Enh'] = myz(yhat[best_enh2,:])\nmultiEnh['rna_hat_AllEnh'] = myz(yhat[best_enh2,:])\nmultiEnh['rna_hat_AllSigEnh'] = np.zeros(yhat[best_enh2,:].shape)+np.nan;\nt0=time.time()\nfor i,c in enumerate(celltypes):\n df = pd.DataFrame(data=yhat[:,i], columns=['yhat'])\n df['ensid'] = genes2enhu.loc[:,'ensid'].values\n multiEnh['rna_hat_AllEnh'][:,i] = df.groupby('ensid')['yhat'].mean()\n df = df.loc[genes2enhu.sig.values,:]\n multiEnh['rna_hat_AllSigEnh'][sig,i] = df.groupby('ensid')['yhat'].mean()\n \nmultiEnh['rna'] = make_df(multiEnh['rna']);\nmultiEnh['rna_hat_1Enh'] = make_df(multiEnh['rna_hat_1Enh']);\nmultiEnh['rna_hat_AllEnh'] = make_df(multiEnh['rna_hat_AllEnh'])\nmultiEnh['rna_hat_AllSigEnh'] = make_df(multiEnh['rna_hat_AllSigEnh'])\nprint(time.time()-t0)", "_____no_output_____" ], [ "cc_1Enh = np.diag(np.corrcoef(multiEnh['rna'].values, multiEnh['rna_hat_1Enh'].values, rowvar=False)[:ncells,ncells:])\ncc_AllEnh = np.diag(np.corrcoef(multiEnh['rna'].values, multiEnh['rna_hat_AllEnh'].values, rowvar=False)[:ncells,ncells:])\ncc_AllSigEnh = np.diag(np.corrcoef(multiEnh['rna'].values[sig,:], multiEnh['rna_hat_AllSigEnh'].values[sig,:], rowvar=False)[:ncells,ncells:])\n\nplt.plot(cellnames, cc_1Enh, label='1 enhancer')\nplt.plot(cellnames, cc_AllEnh, label='All enhancers')\nplt.plot(cellnames, cc_AllSigEnh, label='Significant enhancers')\nplt.legend(bbox_to_anchor=(1,1))\nplt.xticks(rotation=90);\nplt.ylabel('Correlation across genes')", "_____no_output_____" ], [ "def cc_gene(x,y):\n c = np.nan_to_num([np.corrcoef(x1,y1)[0,1] for (x1,y1) in zip(x,y)])\n return c\n\ncc_1Enh = cc_gene(multiEnh['rna'].values, multiEnh['rna_hat_1Enh'].values)\ncc_AllEnh = cc_gene(multiEnh['rna'].values, multiEnh['rna_hat_AllEnh'].values)\ncc_AllSigEnh = cc_gene(multiEnh['rna'].values, multiEnh['rna_hat_AllSigEnh'].values)\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(2,2,1)\nax.plot(np.abs(cc_1Enh), np.abs(cc_AllEnh), '.', markersize=1, rasterized=True)\nax.set_xlabel('Corr with 1 best enhancer')\nax.set_ylabel('Corr with avg. prediction\\nbased on all enhancers')\n\nax = fig.add_subplot(2,2,2)\nax.plot(np.abs(cc_1Enh), np.abs(cc_AllSigEnh), '.', markersize=1, rasterized=True)\nax.set_xlabel('Corr with 1 best enhancer')\nax.set_ylabel('Corr with avg. prediction\\nbased on sig. enhancers')\n\nax = fig.add_subplot(2,1,2)\nbins = np.arange(-1,1,1/100)\nhist_config = {\n 'histtype': 'bar', \n 'edgecolor': 'none',\n 'alpha': 0.5, \n 'density': False, \n}\nax.hist(np.abs(cc_AllEnh)-np.abs(cc_1Enh), bins=bins, \n label='All enhancers-Best enhancer', \n **hist_config,\n )\nax.hist(np.abs(cc_AllSigEnh)-np.abs(cc_1Enh), bins=bins, \n label='Sig enhancers-Best enhancer', \n **hist_config,\n )\nax.legend(bbox_to_anchor=(1,1))\nax.set_xlabel('Difference in correlation')\nax.set_ylabel('Number of genes')\n\nfig.subplots_adjust(wspace=0.5, hspace=0.3)\nsnmcseq_utils.savefig(fig, output_fig.format(\n 'EnhancerRegression_Correlation_1Enh_vs_AllEnh_%dGenes_%dCelltypes_%s' % \n (genes2enhu.ensid.unique().shape[0], len(celltypes), today))\n )\n", "_____no_output_____" ] ], [ [ "# Nonlinear model fitting", "_____no_output_____" ] ], [ [ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(device)", "cpu\n" ], [ "X = np.concatenate((mc_u,atac_u),axis=1).copy()\ny = np.log10(rna_u+1).copy()\nngenes,ncells = y.shape\n\nX.shape, y.shape", "_____no_output_____" ], [ "# Define a class for the NN architecture\nNgenes, Nc = y.shape\nNx = X.shape[1]\nN1 = 128\nN2 = 32\nN3 = 0\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n \n self.fc1 = nn.Linear(Nx, N1);\n self.fc2 = nn.Linear(N1, N2);\n# self.fc3 = nn.Linear(N2, N3);\n self.fc4 = nn.Linear(N2, Nc);\n \n def forward(self, x):\n\n x = F.relu(self.fc1(x)) # Out: N x N1\n x = F.relu(self.fc2(x)) # Out: N x N2\n# x = F.relu(self.fc3(x)) # Out: N x N3\n x = self.fc4(x) # Out: N x C\n \n return x", "_____no_output_____" ], [ "# Initialize\ndef myinit():\n global net, optimizer, criterion, scheduler, loss_test, loss_train, test, train, ensids\n net = Net()\n net.to(device)\n\n# # Initialize the kmer weights to 0 and turn off learning\n# net.fc1_kmers.requires_grad_(False)\n# net.fc1_kmers.weight.fill_(0)\n# net.fc1_kmers.bias.fill_(0)\n \n criterion = nn.MSELoss(reduction='sum')\n optimizer = optim.Adam(net.parameters(), lr=lr)\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.25)\n \n loss_test=np.array([])\n loss_train = np.array([])\n\n # Train/Test split\n test = (np.random.rand(Ngenes,1)<0.2)\n train = [not i for i in test]\n\n test = np.random.permutation(np.nonzero(test)[0]).squeeze()\n train = np.random.permutation(np.nonzero(train)[0]).squeeze()\n ensids = rnau.index.values\n return\n\ndef train_epoch(epoch):\n nsamp = 0\n running_loss = 0.0\n running_time = 0.0\n net.train()\n t0train = time.time()\n for i in range(0, len(train), batch_size):\n tstart = time.time()\n indices = train[i:i+batch_size]\n\n # Input should be of size: (batch, channels, samples)\n batch_X = torch.tensor(X[indices,:],dtype=torch.float)\n batch_y = torch.tensor(y[indices,:],dtype=torch.float)\n\n # Send training data to CUDA\n if device is not \"cpu\":\n batch_X = batch_X.to(device)\n batch_y = batch_y.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(batch_X)\n loss = criterion(outputs, batch_y)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n running_time += time.time()-tstart\n nsamp += len(indices)\n if (time.time()-t0train)>5:\n print('Epoch %d, i=%d/%d, LR=%3.5g, loss=%3.8f, t=%3.3f, %3.5f s/sample' % (epoch, i, len(train), \n optimizer.state_dict()['param_groups'][0]['lr'],\n running_loss/nsamp, running_time, running_time/nsamp))\n t0train=time.time()\n\n return running_loss/nsamp\n\ndef test_epoch(epoch):\n \n net.eval()\n running_loss_test = 0.0\n nsamp = 0\n yyhat = {'y':[], 'yhat':[]}\n for i in range(0, len(test), batch_size):\n indices = test[i:i+batch_size]\n\n # Input should be of size: (batch, channels, samples)\n batch_X = torch.tensor(X[indices,:],dtype=torch.float)\n batch_y = torch.tensor(y[indices,:],dtype=torch.float)\n\n # Send training data to CUDA\n if device is not \"cpu\":\n batch_X = batch_X.to(device)\n batch_y = batch_y.to(device)\n\n # forward + backward + optimize\n outputs = net(batch_X)\n loss = criterion(outputs, batch_y)\n running_loss_test += loss.item()\n nsamp += len(indices)\n\n yyhat['yhat'].append(outputs.detach().cpu().numpy())\n yyhat['y'].append(batch_y.detach().cpu().numpy())\n\n return running_loss_test/nsamp\n", "_____no_output_____" ], [ "lr = 0.0002\nmyinit()\ntrain.shape, test.shape", "_____no_output_____" ], [ "import glob\nfrom IPython import display\n\ndef test_net(indices):\n net.eval()\n yyhat = {'y':[], 'yhat':[]}\n for i in range(0, len(indices), batch_size):\n i = indices[i:i+batch_size]\n\n # Input should be of size: (batch, channels, samples)\n batch_X = torch.tensor(X[indices,:],dtype=torch.float)\n batch_y = torch.tensor(y[indices,:],dtype=torch.float)\n\n # Send training data to CUDA\n if device is not \"cpu\":\n batch_X = batch_X.to(device)\n\n outputs = net(batch_X)\n \n yyhat['yhat'].append(outputs.detach().cpu().numpy())\n yyhat['y'].append(batch_y.numpy())\n yyhat['yhat'] = np.concatenate(yyhat['yhat'],axis=0)\n yyhat['y'] = np.concatenate(yyhat['y'],axis=0)\n \n cc = np.zeros((Nc,1))\n for i in range(yyhat['y'].shape[1]):\n cc[i,0] = np.corrcoef(yyhat['y'][:,i], yyhat['yhat'][:,i])[0,1] \n\n return yyhat, cc\n\ndef make_plot1(save=False):\n plt.figure(figsize=(15,4))\n plt.clf()\n plt.subplot(1,3,1)\n plt.semilogx(loss_train[2:],'o-',label='Train')\n plt.plot(loss_test[2:],'o-',label='Test')\n plt.legend()\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.title(fn_save)\n\n plt.subplot(1,3,2)\n plt.plot(yyhat_test['y'].T, yyhat_test['yhat'].T,'.');\n plt.plot([0,3],[0,3],'k--')\n plt.xlabel('True RNA expression')\n plt.ylabel('Estimated RNA expression')\n\n plt.subplot(1,3,3)\n plt.plot(np.arange(Nc), cc)\n plt.ylabel('R^2?')\n plt.xlabel('Cell type')\n plt.legend(['Train','Test'])\n if save:\n fn_plot = output_fig.format(fn_save.replace('.torch','')+'_corrcoef').replace('pdf', 'png')\n plt.savefig(fn_plot)\n print('Saved plot: '+fn_plot)\n plt.tight_layout()\n plt.show();\n\ndef make_plot2(save=False):\n plt.figure(figsize=(20,20))\n for i in range(Nc):\n plt.subplot(5,6,i+1)\n plt.plot([0,2],[0,2],'k--')\n plt.plot(yyhat_train['y'][:,i], yyhat_train['yhat'][:,i],'.');\n plt.plot(yyhat_test['y'][:,i], yyhat_test['yhat'][:,i],'.');\n # cc = np.corrcoef(yyhat['y'][:,i], yyhat['yhat'][:,i])[0,1]\n plt.title('r=%3.3f train/%3.3f test' % (cc[i,0], cc[i,1]))\n if save:\n fn_plot = output_fig.format(fn_save.replace('.torch','')+'_scatter').replace('pdf', 'png')\n plt.savefig(fn_plot)\n print('Saved plot: '+fn_plot)\n plt.tight_layout()\n plt.show();\n \n ", "_____no_output_____" ], [ "num_epochs1 = 1000\n\nfn_id = len(glob.glob('./RegressEnh*.pt'))+1 # Generate a unique ID for this run\nfn_save = 'RegressEnh%0.4d_%s_N_%d_%d_%d.%s.pt' % (fn_id, ('UseKmers' if use_kmers else 'NoKmers'), N1,N2,N3,today)\n \n\nt0 = time.time()\nbatch_size = 16\nfor epoch in range(num_epochs1): # loop over the dataset multiple times\n# while epoch<num_epochs1:\n new_loss_train = train_epoch(epoch);\n loss_train = np.append(loss_train, new_loss_train)\n \n new_loss_test = test_epoch(epoch);\n loss_test = np.append(loss_test,new_loss_test)\n scheduler.step(new_loss_test)\n\n print('**** Phase1 epoch %d, LR=%3.5g, loss_train=%3.8f, loss_test=%3.8f, time = %3.5f s/epoch' % (\n len(loss_train), \n optimizer.param_groups[0]['lr'],\n loss_train[-1], \n loss_test[-1], \n (time.time()-t0))\n )\n\n if (time.time()-t0)>60 or (epoch==num_epochs1-1): \n if (epoch>0): \n cc = np.zeros((Nc,2))\n yyhat_train, cc[:,[0]] = test_net(random.sample(train.tolist(), 500))\n yyhat_test, cc[:,[1]] = test_net(random.sample(test.tolist(), 500))\n\n display.clear_output(wait=True)\n display.display(plt.gcf())\n make_plot1(save=True)\n# make_plot2(save=True) \n display.display(plt.gcf())\n t0=time.time()\n torch.save({\n 'epoch': epoch,\n 'model_state_dict': net.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss_train': loss_train,\n 'loss_test': loss_test,\n }, fn_save)\n print('Saved data: %s' % fn_save)\n", "_____no_output_____" ], [ "output_fig", "_____no_output_____" ], [ "# test.max()\n# plt.hist2d(df['log_rna'], mdl.predict(), bins=(50,50), cmap=plt.cm.Reds);\n# plt.scatter(df['log_rna'], mdl.predict(),s=1)", "_____no_output_____" ], [ "plt.hist(np.log(rnau.loc[genes2enhu['ensid'][best_enh],:].iloc[:,3]+1), bins=100);", "_____no_output_____" ] ], [ [ "### Fangming follow-ups ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
d0738544f3d2cf0d79eea211df19d00cfc4b237c
65,937
ipynb
Jupyter Notebook
examples/multiple_choice-tf.ipynb
HAMZA310/notebooks
6204dcb906c6bc6d98168064b6aa27d15885f2fb
[ "Apache-2.0" ]
765
2020-06-15T14:09:03.000Z
2022-03-31T19:37:11.000Z
examples/multiple_choice-tf.ipynb
HAMZA310/notebooks
6204dcb906c6bc6d98168064b6aa27d15885f2fb
[ "Apache-2.0" ]
105
2020-07-24T11:01:46.000Z
2022-03-29T16:15:04.000Z
examples/multiple_choice-tf.ipynb
HAMZA310/notebooks
6204dcb906c6bc6d98168064b6aa27d15885f2fb
[ "Apache-2.0" ]
433
2020-06-15T19:31:21.000Z
2022-03-31T10:08:58.000Z
40.752163
599
0.613161
[ [ [ "If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Right now this requires the current master branch of both. Uncomment the following cell and run it.", "_____no_output_____" ] ], [ [ "#! pip install git+https://github.com/huggingface/transformers.git\n#! pip install git+https://github.com/huggingface/datasets.git", "_____no_output_____" ] ], [ [ "If you're opening this notebook locally, make sure your environment has an install from the last version of those libraries.\n\nTo be able to share your model with the community, there are a few more steps to follow.\n\nFirst you have to store your authentication token from the Hugging Face website (sign up [here](https://huggingface.co/join) if you haven't already!) then uncomment the following cell and input your username and password (this only works on Colab, in a regular notebook, you need to do this in a terminal):", "_____no_output_____" ] ], [ [ "from huggingface_hub import notebook_login\n\nnotebook_login()", "Login successful\nYour token has been saved to /home/matt/.huggingface/token\n" ] ], [ [ "Then you need to install Git-LFS and setup Git if you haven't already. Uncomment the following instructions and adapt with your name and email:", "_____no_output_____" ] ], [ [ "# !apt install git-lfs\n# !git config --global user.email \"[email protected]\"\n# !git config --global user.name \"Your Name\"", "_____no_output_____" ] ], [ [ "Make sure your version of Transformers is at least 4.8.1 since the functionality was introduced in that version:", "_____no_output_____" ] ], [ [ "import transformers\n\nprint(transformers.__version__)", "4.12.0.dev0\n" ] ], [ [ "If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Uncomment the following cell and run it.", "_____no_output_____" ], [ "# Fine-tuning a model on a multiple choice task", "_____no_output_____" ], [ "In this notebook, we will see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model to a multiple choice task, which is the task of selecting the most plausible inputs in a given selection. The dataset used here is [SWAG](https://www.aclweb.org/anthology/D18-1009/) but you can adapt the pre-processing to any other multiple choice dataset you like, or your own data. SWAG is a dataset about commonsense reasoning, where each example describes a situation then proposes four options that could go after it. \n\nThis notebook is built to run with any model checkpoint from the [Model Hub](https://huggingface.co/models) as long as that model has a version with a mutiple choice head. Depending on you model and the GPU you are using, you might need to adjust the batch size to avoid out-of-memory errors. Set those two parameters, then the rest of the notebook should run smoothly:", "_____no_output_____" ] ], [ [ "model_checkpoint = \"bert-base-uncased\"\nbatch_size = 16", "_____no_output_____" ] ], [ [ "## Loading the dataset", "_____no_output_____" ], [ "We will use the [🤗 Datasets](https://github.com/huggingface/datasets) library to download the data. This can be easily done with the functions `load_dataset`. ", "_____no_output_____" ] ], [ [ "from datasets import load_dataset, load_metric", "_____no_output_____" ] ], [ [ "`load_dataset` will cache the dataset to avoid downloading it again the next time you run this cell.", "_____no_output_____" ] ], [ [ "datasets = load_dataset(\"swag\", \"regular\")", "Reusing dataset swag (/home/matt/.cache/huggingface/datasets/swag/regular/0.0.0/9640de08cdba6a1469ed3834fcab4b8ad8e38caf5d1ba5e7436d8b1fd067ad4c)\n" ] ], [ [ "The `dataset` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasetdict), which contains one key for the training, validation and test set (with more keys for the mismatched validation and test set in the special case of `mnli`).", "_____no_output_____" ] ], [ [ "datasets", "_____no_output_____" ] ], [ [ "To access an actual element, you need to select a split first, then give an index:", "_____no_output_____" ] ], [ [ "datasets[\"train\"][0]", "_____no_output_____" ] ], [ [ "To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset.", "_____no_output_____" ] ], [ [ "from datasets import ClassLabel\nimport random\nimport pandas as pd\nfrom IPython.display import display, HTML\n\n\ndef show_random_elements(dataset, num_examples=10):\n assert num_examples <= len(\n dataset\n ), \"Can't pick more elements than there are in the dataset.\"\n picks = []\n for _ in range(num_examples):\n pick = random.randint(0, len(dataset) - 1)\n while pick in picks:\n pick = random.randint(0, len(dataset) - 1)\n picks.append(pick)\n\n df = pd.DataFrame(dataset[picks])\n for column, typ in dataset.features.items():\n if isinstance(typ, ClassLabel):\n df[column] = df[column].transform(lambda i: typ.names[i])\n display(HTML(df.to_html()))", "_____no_output_____" ], [ "show_random_elements(datasets[\"train\"])", "_____no_output_____" ] ], [ [ "Each example in the dataset has a context composed of a first sentence (in the field `sent1`) and an introduction to the second sentence (in the field `sent2`). Then four possible endings are given (in the fields `ending0`, `ending1`, `ending2` and `ending3`) and the model must pick the right one (indicated in the field `label`). The following function lets us visualize a give example a bit better:", "_____no_output_____" ] ], [ [ "def show_one(example):\n print(f\"Context: {example['sent1']}\")\n print(f\" A - {example['sent2']} {example['ending0']}\")\n print(f\" B - {example['sent2']} {example['ending1']}\")\n print(f\" C - {example['sent2']} {example['ending2']}\")\n print(f\" D - {example['sent2']} {example['ending3']}\")\n print(f\"\\nGround truth: option {['A', 'B', 'C', 'D'][example['label']]}\")", "_____no_output_____" ], [ "show_one(datasets[\"train\"][0])", "Context: Members of the procession walk down the street holding small horn brass instruments.\n A - A drum line passes by walking down the street playing their instruments.\n B - A drum line has heard approaching them.\n C - A drum line arrives and they're outside dancing and asleep.\n D - A drum line turns the lead singer watches the performance.\n\nGround truth: option A\n" ], [ "show_one(datasets[\"train\"][15])", "Context: Now it's someone's turn to rain blades on his opponent.\n A - Someone pats his shoulder and spins wildly.\n B - Someone lunges forward through the window.\n C - Someone falls to the ground.\n D - Someone rolls up his fast run from the water and tosses in the sky.\n\nGround truth: option C\n" ] ], [ [ "## Preprocessing the data", "_____no_output_____" ], [ "Before we can feed those texts to our model, we need to preprocess them. This is done by a 🤗 Transformers `Tokenizer` which will (as the name indicates) tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary) and put it in a format the model expects, as well as generate the other inputs that model requires.\n\nTo do all of this, we instantiate our tokenizer with the `AutoTokenizer.from_pretrained` method, which will ensure:\n\n- we get a tokenizer that corresponds to the model architecture we want to use,\n- we download the vocabulary used when pretraining this specific checkpoint.\n\nThat vocabulary will be cached, so it's not downloaded again the next time we run the cell.", "_____no_output_____" ] ], [ [ "from transformers import AutoTokenizer\n\ntokenizer = AutoTokenizer.from_pretrained(model_checkpoint)", "_____no_output_____" ] ], [ [ "You can directly call this tokenizer on one sentence or a pair of sentences:", "_____no_output_____" ] ], [ [ "tokenizer(\"Hello, this one sentence!\", \"And this sentence goes with it.\")", "_____no_output_____" ] ], [ [ "Depending on the model you selected, you will see different keys in the dictionary returned by the cell above. They don't matter much for what we're doing here (just know they are required by the model we will instantiate later), you can learn more about them in [this tutorial](https://huggingface.co/transformers/preprocessing.html) if you're interested.\n\nTo preprocess our dataset, we will thus need the names of the columns containing the sentence(s). The following dictionary keeps track of the correspondence task to column names:", "_____no_output_____" ], [ "We can them write the function that will preprocess our samples. The tricky part is to put all the possible pairs of sentences in two big lists before passing them to the tokenizer, then un-flatten the result so that each example has four input ids, attentions masks, etc.\n\nWhen calling the `tokenizer`, we use the argument `truncation=True`. This will ensure that an input longer that what the model selected can handle will be truncated to the maximum length accepted by the model.", "_____no_output_____" ] ], [ [ "ending_names = [\"ending0\", \"ending1\", \"ending2\", \"ending3\"]\n\n\ndef preprocess_function(examples):\n # Repeat each first sentence four times to go with the four possibilities of second sentences.\n first_sentences = [[context] * 4 for context in examples[\"sent1\"]]\n # Grab all second sentences possible for each context.\n question_headers = examples[\"sent2\"]\n second_sentences = [\n [f\"{header} {examples[end][i]}\" for end in ending_names]\n for i, header in enumerate(question_headers)\n ]\n\n # Flatten everything\n first_sentences = sum(first_sentences, [])\n second_sentences = sum(second_sentences, [])\n\n # Tokenize\n tokenized_examples = tokenizer(first_sentences, second_sentences, truncation=True)\n # Un-flatten\n return {\n k: [v[i : i + 4] for i in range(0, len(v), 4)]\n for k, v in tokenized_examples.items()\n }", "_____no_output_____" ] ], [ [ "This function works with one or several examples. In the case of several examples, the tokenizer will return a list of lists of lists for each key: a list of all examples (here 5), then a list of all choices (4) and a list of input IDs (length varying here since we did not apply any padding):", "_____no_output_____" ] ], [ [ "examples = datasets[\"train\"][:5]\nfeatures = preprocess_function(examples)\nprint(\n len(features[\"input_ids\"]),\n len(features[\"input_ids\"][0]),\n [len(x) for x in features[\"input_ids\"][0]],\n)", "5 4 [30, 25, 30, 28]\n" ] ], [ [ "To check we didn't do anything group when grouping all possibilites then unflattening, let's have a look at the decoded inputs for a given example:", "_____no_output_____" ] ], [ [ "idx = 3\n[tokenizer.decode(features[\"input_ids\"][idx][i]) for i in range(4)]", "_____no_output_____" ] ], [ [ "We can compare it to the ground truth:", "_____no_output_____" ] ], [ [ "show_one(datasets[\"train\"][3])", "Context: A drum line passes by walking down the street playing their instruments.\n A - Members of the procession are playing ping pong and celebrating one left each in quick.\n B - Members of the procession wait slowly towards the cadets.\n C - Members of the procession makes a square call and ends by jumping down into snowy streets where fans begin to take their positions.\n D - Members of the procession play and go back and forth hitting the drums while the audience claps for them.\n\nGround truth: option D\n" ] ], [ [ "This seems alright, so we can apply this function on all the examples in our dataset, we just use the `map` method of our `dataset` object we created earlier. This will apply the function on all the elements of all the splits in `dataset`, so our training, validation and testing data will be preprocessed in one single command.", "_____no_output_____" ] ], [ [ "encoded_datasets = datasets.map(preprocess_function, batched=True)", "Loading cached processed dataset at /home/matt/.cache/huggingface/datasets/swag/regular/0.0.0/9640de08cdba6a1469ed3834fcab4b8ad8e38caf5d1ba5e7436d8b1fd067ad4c/cache-ce78ab0ead9f175e.arrow\nLoading cached processed dataset at /home/matt/.cache/huggingface/datasets/swag/regular/0.0.0/9640de08cdba6a1469ed3834fcab4b8ad8e38caf5d1ba5e7436d8b1fd067ad4c/cache-0d9c087b50e2d5ce.arrow\nLoading cached processed dataset at /home/matt/.cache/huggingface/datasets/swag/regular/0.0.0/9640de08cdba6a1469ed3834fcab4b8ad8e38caf5d1ba5e7436d8b1fd067ad4c/cache-741a913dcfe8f6c0.arrow\n" ] ], [ [ "Even better, the results are automatically cached by the 🤗 Datasets library to avoid spending time on this step the next time you run your notebook. The 🤗 Datasets library is normally smart enough to detect when the function you pass to map has changed (and thus requires to not use the cache data). For instance, it will properly detect if you change the task in the first cell and rerun the notebook. 🤗 Datasets warns you when it uses cached files, you can pass `load_from_cache_file=False` in the call to `map` to not use the cached files and force the preprocessing to be applied again.\n\nNote that we passed `batched=True` to encode the texts by batches together. This is to leverage the full benefit of the fast tokenizer we loaded earlier, which will use multi-threading to treat the texts in a batch concurrently.", "_____no_output_____" ], [ "## Fine-tuning the model", "_____no_output_____" ], [ "Now that our data is ready, we can download the pretrained model and fine-tune it. Since all our task is about mutliple choice, we use the `AutoModelForMultipleChoice` class. Like with the tokenizer, the `from_pretrained` method will download and cache the model for us.", "_____no_output_____" ] ], [ [ "from transformers import TFAutoModelForMultipleChoice\n\nmodel = TFAutoModelForMultipleChoice.from_pretrained(model_checkpoint)", "All model checkpoint layers were used when initializing TFBertForMultipleChoice.\n\nSome layers of TFBertForMultipleChoice were not initialized from the model checkpoint at bert-base-uncased and are newly initialized: ['classifier']\nYou should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n" ] ], [ [ "The warning is telling us we are throwing away some weights (the `vocab_transform` and `vocab_layer_norm` layers) and randomly initializing some other (the `pre_classifier` and `classifier` layers). This is absolutely normal in this case, because we are removing the head used to pretrain the model on a masked language modeling objective and replacing it with a new head for which we don't have pretrained weights, so the library warns us we should fine-tune this model before using it for inference, which is exactly what we are going to do.", "_____no_output_____" ], [ "Next, we set some names and hyperparameters for the model. The first two variables are used so we can push the model to the [Hub](https://huggingface.co/models) at the end of training. Remove the two of them if you didn't follow the installation steps at the top of the notebook, otherwise you can change the value of `push_to_hub_model_id` to something you would prefer.", "_____no_output_____" ] ], [ [ "model_name = model_checkpoint.split(\"/\")[-1]\npush_to_hub_model_id = f\"{model_name}-finetuned-swag\"\n\nlearning_rate = 5e-5\nbatch_size = batch_size\nnum_train_epochs = 2\nweight_decay = 0.01", "_____no_output_____" ] ], [ [ "Next we need to tell our `Dataset` how to form batches from the pre-processed inputs. We haven't done any padding yet because we will pad each batch to the maximum length inside the batch (instead of doing so with the maximum length of the whole dataset). This will be the job of the *data collator*. A data collator takes a list of examples and converts them to a batch (by, in our case, applying padding). Since there is no data collator in the library that works on our specific problem, we will write one, adapted from the `DataCollatorWithPadding`:", "_____no_output_____" ] ], [ [ "from dataclasses import dataclass\nfrom transformers.tokenization_utils_base import (\n PreTrainedTokenizerBase,\n PaddingStrategy,\n)\nfrom typing import Optional, Union\nimport tensorflow as tf\n\n\n@dataclass\nclass DataCollatorForMultipleChoice:\n \"\"\"\n Data collator that will dynamically pad the inputs for multiple choice received.\n \"\"\"\n\n tokenizer: PreTrainedTokenizerBase\n padding: Union[bool, str, PaddingStrategy] = True\n max_length: Optional[int] = None\n pad_to_multiple_of: Optional[int] = None\n\n def __call__(self, features):\n label_name = \"label\" if \"label\" in features[0].keys() else \"labels\"\n labels = [feature.pop(label_name) for feature in features]\n batch_size = len(features)\n num_choices = len(features[0][\"input_ids\"])\n flattened_features = [\n [{k: v[i] for k, v in feature.items()} for i in range(num_choices)]\n for feature in features\n ]\n flattened_features = sum(flattened_features, [])\n\n batch = self.tokenizer.pad(\n flattened_features,\n padding=self.padding,\n max_length=self.max_length,\n pad_to_multiple_of=self.pad_to_multiple_of,\n return_tensors=\"tf\",\n )\n\n # Un-flatten\n batch = {\n k: tf.reshape(v, (batch_size, num_choices, -1)) for k, v in batch.items()\n }\n # Add back labels\n batch[\"labels\"] = tf.convert_to_tensor(labels, dtype=tf.int64)\n return batch", "_____no_output_____" ] ], [ [ "When called on a list of examples, it will flatten all the inputs/attentions masks etc. in big lists that it will pass to the `tokenizer.pad` method. This will return a dictionary with big tensors (of shape `(batch_size * 4) x seq_length`) that we then unflatten.\n\nWe can check this data collator works on a list of features, we just have to make sure to remove all features that are not inputs accepted by our model (something the `Trainer` will do automatically for us after):", "_____no_output_____" ] ], [ [ "accepted_keys = [\"input_ids\", \"attention_mask\", \"label\"]\nfeatures = [\n {k: v for k, v in encoded_datasets[\"train\"][i].items() if k in accepted_keys}\n for i in range(10)\n]\nbatch = DataCollatorForMultipleChoice(tokenizer)(features)", "_____no_output_____" ], [ "encoded_datasets[\"train\"].features[\"attention_mask\"].feature.feature", "_____no_output_____" ] ], [ [ "Again, all those flatten/un-flatten are sources of potential errors so let's make another sanity check on our inputs:", "_____no_output_____" ] ], [ [ "[tokenizer.decode(batch[\"input_ids\"][8][i].numpy().tolist()) for i in range(4)]", "_____no_output_____" ], [ "show_one(datasets[\"train\"][8])", "Context: Someone walks over to the radio.\n A - Someone hands her another phone.\n B - Someone takes the drink, then holds it.\n C - Someone looks off then looks at someone.\n D - Someone stares blearily down at the floor.\n\nGround truth: option D\n" ] ], [ [ "All good! Now we can use this collator as a collation function for our dataset. The best way to do this is with the `to_tf_dataset()` method. This converts our dataset to a `tf.data.Dataset` that Keras can take as input. It also applies our collation function to each batch.", "_____no_output_____" ] ], [ [ "data_collator = DataCollatorForMultipleChoice(tokenizer)\ntrain_set = encoded_datasets[\"train\"].to_tf_dataset(\n columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n shuffle=True,\n batch_size=batch_size,\n collate_fn=data_collator,\n)\nvalidation_set = encoded_datasets[\"validation\"].to_tf_dataset(\n columns=[\"attention_mask\", \"input_ids\", \"labels\"],\n shuffle=False,\n batch_size=batch_size,\n collate_fn=data_collator,\n)", "_____no_output_____" ] ], [ [ "Now we can create our model. First, we specify an optimizer. Using the `create_optimizer` function we can get a nice `AdamW` optimizer with weight decay and a learning rate decay schedule set up for free - but to compute that schedule, it needs to know how long training will take.", "_____no_output_____" ] ], [ [ "from transformers import create_optimizer\n\ntotal_train_steps = (len(encoded_datasets[\"train\"]) // batch_size) * num_train_epochs\n\noptimizer, schedule = create_optimizer(\n init_lr=learning_rate, num_warmup_steps=0, num_train_steps=total_train_steps\n)", "_____no_output_____" ] ], [ [ "All Transformers models have a `loss` output head, so we can simply leave the loss argument to `compile()` blank to train on it.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\n\nmodel.compile(optimizer=optimizer)", "No loss specified in compile() - the model's internal loss computation will be used as the loss. Don't panic - this is a common way to train TensorFlow models in Transformers! Please ensure your labels are passed as the 'labels' key of the input dict so that they are accessible to the model during the forward pass. To disable this behaviour, please pass a loss argument, or explicitly pass loss=None if you do not want your model to compute a loss.\n" ] ], [ [ "Now we can train our model. We can also add a callback to sync up our model with the Hub - this allows us to resume training from other machines and even test the model's inference quality midway through training! Make sure to change the `username` if you do. If you don't want to do this, simply remove the callbacks argument in the call to `fit()`.", "_____no_output_____" ] ], [ [ "from transformers.keras_callbacks import PushToHubCallback\n\nusername = \"Rocketknight1\"\n\ncallback = PushToHubCallback(\n output_dir=\"./mc_model_save\",\n tokenizer=tokenizer,\n hub_model_id=f\"{username}/{push_to_hub_model_id}\",\n)\n\nmodel.fit(\n train_set,\n validation_data=validation_set,\n epochs=num_train_epochs,\n callbacks=[callback],\n)", "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\nTo disable this warning, you can either:\n\t- Avoid using `tokenizers` before the fork if possible\n\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\nhuggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\nTo disable this warning, you can either:\n\t- Avoid using `tokenizers` before the fork if possible\n\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n" ] ], [ [ "One downside of using the internal loss, however, is that we can't use Keras metrics with it. So let's compute accuracy after the fact, to see how our model is performing. First, we need to get our model's predicted answers on the validation set.", "_____no_output_____" ] ], [ [ "predictions = model.predict(validation_set)[\"logits\"]\nlabels = encoded_datasets[\"validation\"][\"label\"]", "_____no_output_____" ] ], [ [ "And now we can compute our accuracy with Numpy.", "_____no_output_____" ] ], [ [ "import numpy as np\n\npreds = np.argmax(predictions, axis=1)\nprint({\"accuracy\": (preds == labels).astype(np.float32).mean().item()})", "{'accuracy': 0.7951614260673523}\n" ] ], [ [ "If you used the callback above, you can now share this model with all your friends, family, favorite pets: they can all load it with the identifier `\"your-username/the-name-you-picked\"` so for instance:\n\n```python\nfrom transformers import AutoModelForMultipleChoice\n\nmodel = AutoModelForMultipleChoice.from_pretrained(\"your-username/my-awesome-model\")\n```", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d07399e1f0e6eb948466da0f1a5fba165ddcf846
107,024
ipynb
Jupyter Notebook
docs/source/tutorials/2.02-recover-a-planet.ipynb
ceb8/lightkurve
0f06e654ebdbb799977a09c5d1aa22c2b15e52a0
[ "MIT" ]
null
null
null
docs/source/tutorials/2.02-recover-a-planet.ipynb
ceb8/lightkurve
0f06e654ebdbb799977a09c5d1aa22c2b15e52a0
[ "MIT" ]
null
null
null
docs/source/tutorials/2.02-recover-a-planet.ipynb
ceb8/lightkurve
0f06e654ebdbb799977a09c5d1aa22c2b15e52a0
[ "MIT" ]
null
null
null
352.052632
28,412
0.937874
[ [ [ "# How to recover a known planet in Kepler data", "_____no_output_____" ], [ "This tutorial demonstrates the basic steps required to recover a transiting planet candidate in the Kepler data.\n\nWe will show how you can recover the signal of [Kepler-10b](https://en.wikipedia.org/wiki/Kepler-10b), the first rocky planet that was discovered by Kepler! Kepler-10 is a Sun-like (G-type) star approximately 600 light years away in the constellation of Cygnus. In this tutorial, we will download the pixel data of Kepler-10, extract a lightcurve, and recover the planet.", "_____no_output_____" ], [ "Kepler pixel data is distributed in \"Target Pixel Files\". You can read more about them in our tutorial [here](http://lightkurve.keplerscience.org/tutorials/target-pixel-files.html). The `lightkurve` package provides a `KeplerTargetPixelFile` class, which enables you to load and interact with data in this format.\n\nThe class can take a path (local or url), or you can load data straight from the [MAST archive](https://archive.stsci.edu/kepler/), which holds all of the Kepler and K2 data archive. We'll download the Kepler-10 light curve using the `from_archive` function, as shown below. *(Note: we're adding the keyword `quarter=3` to download only the data from the third Kepler quarter. There were 17 quarters during the Kepler mission.)*", "_____no_output_____" ] ], [ [ "from lightkurve import KeplerTargetPixelFile\ntpf = KeplerTargetPixelFile.from_archive(\"Kepler-10\", quarter=3)", "Downloading URL https://mast.stsci.edu/api/v0/download/file?uri=mast:Kepler/url/missions/kepler/target_pixel_files/0119/011904151/kplr011904151-2009350155506_lpd-targ.fits.gz to ./mastDownload/Kepler/kplr011904151_lc_Q111111110111011101/kplr011904151-2009350155506_lpd-targ.fits.gz ... [Done]\n" ] ], [ [ "Let's use the `plot` method and pass along an aperture mask and a few plotting arguments.", "_____no_output_____" ] ], [ [ "tpf.plot(scale='log');", "_____no_output_____" ] ], [ [ "The target pixel file contains one bright star with approximately 50,000 counts.", "_____no_output_____" ], [ "Now, we will use the ``to_lightcurve`` method to create a simple aperture photometry lightcurve using the\nmask defined by the pipeline which is stored in `tpf.pipeline_mask`.", "_____no_output_____" ] ], [ [ "lc = tpf.to_lightcurve(aperture_mask=tpf.pipeline_mask)", "_____no_output_____" ] ], [ [ "Let's take a look at the output lightcurve.", "_____no_output_____" ] ], [ [ "lc.plot();", "_____no_output_____" ] ], [ [ "Now let's use the `flatten` method, which applies a Savitzky-Golay filter, to remove long-term variability that we are not interested in. We'll use the `return_trend` keyword so that it returns both the corrected `KeplerLightCurve` object and a new `KeplerLightCurve` object called 'trend'. This contains only the long term variability.", "_____no_output_____" ] ], [ [ "flat, trend = lc.flatten(window_length=301, return_trend=True)", "_____no_output_____" ] ], [ [ "Let's plot the trend estimated by the Savitzky-Golay filter:", "_____no_output_____" ] ], [ [ "ax = lc.plot() #plot() returns a matplotlib axis \ntrend.plot(ax, color='red'); #which we can pass to the next plot() to use the same plotting window", "_____no_output_____" ] ], [ [ "and the flat lightcurve:", "_____no_output_____" ] ], [ [ "flat.plot();", "_____no_output_____" ] ], [ [ "Now, let's run a period search function using the Box-Least Squares algorithm (http://adsabs.harvard.edu/abs/2002A%26A...391..369K). We will shortly have a built in BLS implementation, but until then you can download and install it separately from lightkurve using", "_____no_output_____" ], [ "`pip install git+https://github.com/mirca/transit-periodogram.git`", "_____no_output_____" ] ], [ [ "from transit_periodogram import transit_periodogram\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "periods = np.arange(0.3, 1.5, 0.0001)\ndurations = np.arange(0.005, 0.15, 0.001)\npower, _, _, _, _, _, _ = transit_periodogram(time=flat.time, \n flux=flat.flux,\n flux_err=flat.flux_err,\n periods=periods, \n durations=durations)\nbest_fit = periods[np.argmax(power)]", "_____no_output_____" ], [ "print('Best Fit Period: {} days'.format(best_fit))", "Best Fit Period: 0.8375999999999408 days\n" ], [ "flat.fold(best_fit).plot(alpha=0.4);", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ] ]
d073a2641b37b55c5466f9e50d0f88a0bdd7654b
6,028
ipynb
Jupyter Notebook
01_elements/01_exercises.ipynb
ramsaut/intro-to-python
73432b906048f7027c27c631a35e13bf8c5c7798
[ "MIT" ]
614
2018-10-22T12:08:56.000Z
2022-03-28T08:43:03.000Z
01_elements/01_exercises.ipynb
webartifex/ipp
73432b906048f7027c27c631a35e13bf8c5c7798
[ "MIT" ]
50
2019-10-25T09:41:49.000Z
2021-12-03T07:58:34.000Z
01_elements/01_exercises.ipynb
webartifex/ipp
73432b906048f7027c27c631a35e13bf8c5c7798
[ "MIT" ]
76
2019-03-04T13:57:40.000Z
2022-03-23T17:23:20.000Z
34.843931
559
0.604015
[ [ [ "**Note**: Click on \"*Kernel*\" > \"*Restart Kernel and Run All*\" in [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) *after* finishing the exercises to ensure that your solution runs top to bottom *without* any errors. If you cannot run this file on your machine, you may want to open it [in the cloud <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_mb.png\">](https://mybinder.org/v2/gh/webartifex/intro-to-python/develop?urlpath=lab/tree/01_elements/01_exercises.ipynb).", "_____no_output_____" ], [ "# Chapter 1: Elements of a Program (Coding Exercises)", "_____no_output_____" ], [ "The exercises below assume that you have read the [first part <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_nb.png\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/01_elements/00_content.ipynb) of Chapter 1.\n\nThe `...`'s in the code cells indicate where you need to fill in code snippets. The number of `...`'s within a code cell give you a rough idea of how many lines of code are needed to solve the task. You should not need to create any additional code cells for your final solution. However, you may want to use temporary code cells to try out some ideas.", "_____no_output_____" ], [ "## Printing Output", "_____no_output_____" ], [ "**Q1**: *Concatenate* `greeting` and `audience` below with the `+` operator and print out the resulting message `\"Hello World\"` with only *one* call of the built-in [print() <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_py.png\">](https://docs.python.org/3/library/functions.html#print) function!\n\nHint: You may have to \"add\" a space character in between `greeting` and `audience`.", "_____no_output_____" ] ], [ [ "greeting = \"Hello\"\naudience = \"World\"", "_____no_output_____" ], [ "print(...)", "_____no_output_____" ] ], [ [ "**Q2**: How is your answer to **Q1** an example of the concept of **operator overloading**?", "_____no_output_____" ], [ " < your answer >", "_____no_output_____" ], [ "**Q3**: Read the documentation on the built-in [print() <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_py.png\">](https://docs.python.org/3/library/functions.html#print) function! How can you print the above message *without* concatenating `greeting` and `audience` first in *one* call of [print() <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_py.png\">](https://docs.python.org/3/library/functions.html#print)?\n\nHint: The `*objects` in the documentation implies that we can put several *expressions* (i.e., variables) separated by commas within the same call of the [print() <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_py.png\">](https://docs.python.org/3/library/functions.html#print) function.", "_____no_output_____" ] ], [ [ "print(...)", "_____no_output_____" ] ], [ [ "**Q4**: What does the `sep=\" \"` mean in the documentation on the built-in [print() <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_py.png\">](https://docs.python.org/3/library/functions.html#print) function? Adjust and use it to print out the three names referenced by `first`, `second`, and `third` on *one* line separated by *commas* with only *one* call of the [print() <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_py.png\">](https://docs.python.org/3/library/functions.html#print) function!", "_____no_output_____" ] ], [ [ "first = \"Anthony\"\nsecond = \"Berta\"\nthird = \"Christian\"", "_____no_output_____" ], [ "print(...)", "_____no_output_____" ] ], [ [ "**Q5**: Lastly, what does the `end=\"\\n\"` mean in the documentation? Adjust and use it within the `for`-loop to print the numbers `1` through `10` on *one* line with only *one* call of the [print() <img height=\"12\" style=\"display: inline-block\" src=\"../static/link/to_py.png\">](https://docs.python.org/3/library/functions.html#print) function!", "_____no_output_____" ] ], [ [ "for number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:\n print(...)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d073b0cb0c333fbde7d9967970bff882285ca9c3
5,461
ipynb
Jupyter Notebook
nbs/test_files/run_flow_showstep.ipynb
outerbounds/nbdoc
b642d0f684c28594e601898ab6cbd12af3b9d7c1
[ "Apache-2.0" ]
15
2022-02-15T09:38:07.000Z
2022-03-26T09:12:02.000Z
nbs/test_files/run_flow_showstep.ipynb
outerbounds/nbdoc
b642d0f684c28594e601898ab6cbd12af3b9d7c1
[ "Apache-2.0" ]
10
2022-03-16T23:20:54.000Z
2022-03-30T14:58:15.000Z
nbs/test_files/run_flow_showstep.ipynb
outerbounds/nbdoc
b642d0f684c28594e601898ab6cbd12af3b9d7c1
[ "Apache-2.0" ]
null
null
null
65.011905
311
0.688152
[ [ [ "#cell_meta:show_steps=start,train\n!python myflow.py run", "\u001b[35m\u001b[1mMetaflow 2.5.0.post6+git62f5e52\u001b[0m\u001b[35m\u001b[22m executing \u001b[0m\u001b[31m\u001b[1mMyFlow\u001b[0m\u001b[35m\u001b[22m\u001b[0m\u001b[35m\u001b[22m for \u001b[0m\u001b[31m\u001b[1muser:hamel\u001b[0m\u001b[35m\u001b[22m\u001b[K\u001b[0m\u001b[35m\u001b[22m\u001b[0m\n\u001b[35m\u001b[22mValidating your flow...\u001b[K\u001b[0m\u001b[35m\u001b[22m\u001b[0m\n\u001b[32m\u001b[1m The graph looks good!\u001b[K\u001b[0m\u001b[32m\u001b[1m\u001b[0m\n\u001b[35m\u001b[22mRunning pylint...\u001b[K\u001b[0m\u001b[35m\u001b[22m\u001b[0m\n\u001b[32m\u001b[1m Pylint is happy!\u001b[K\u001b[0m\u001b[32m\u001b[1m\u001b[0m\n\u001b[35m2022-02-15 14:01:14.804 \u001b[0m\u001b[1mWorkflow starting (run-id 1644962474801237):\u001b[0m\n\u001b[35m2022-02-15 14:01:14.810 \u001b[0m\u001b[32m[1644962474801237/start/1 (pid 46758)] \u001b[0m\u001b[1mTask is starting.\u001b[0m\n\u001b[35m2022-02-15 14:01:15.433 \u001b[0m\u001b[32m[1644962474801237/start/1 (pid 46758)] \u001b[0m\u001b[22mthis is the start\u001b[0m\n\u001b[35m2022-02-15 14:01:15.500 \u001b[0m\u001b[32m[1644962474801237/start/1 (pid 46758)] \u001b[0m\u001b[1mTask finished successfully.\u001b[0m\n\u001b[35m2022-02-15 14:01:15.507 \u001b[0m\u001b[32m[1644962474801237/train/2 (pid 46763)] \u001b[0m\u001b[1mTask is starting.\u001b[0m\n\u001b[35m2022-02-15 14:01:16.123 \u001b[0m\u001b[32m[1644962474801237/train/2 (pid 46763)] \u001b[0m\u001b[22mthe train step\u001b[0m\n\u001b[35m2022-02-15 14:01:16.188 \u001b[0m\u001b[32m[1644962474801237/train/2 (pid 46763)] \u001b[0m\u001b[1mTask finished successfully.\u001b[0m\n\u001b[35m2022-02-15 14:01:16.195 \u001b[0m\u001b[32m[1644962474801237/end/3 (pid 46768)] \u001b[0m\u001b[1mTask is starting.\u001b[0m\n\u001b[35m2022-02-15 14:01:16.822 \u001b[0m\u001b[32m[1644962474801237/end/3 (pid 46768)] \u001b[0m\u001b[22mthis is the end\u001b[0m\n\u001b[35m2022-02-15 14:01:16.887 \u001b[0m\u001b[32m[1644962474801237/end/3 (pid 46768)] \u001b[0m\u001b[1mTask finished successfully.\u001b[0m\n\u001b[35m2022-02-15 14:01:16.887 \u001b[0m\u001b[1mDone!\u001b[0m\n\u001b[0m" ], [ "#cell_meta:show_steps=train\n!python myflow.py run", "\u001b[35m\u001b[1mMetaflow 2.5.0.post6+git62f5e52\u001b[0m\u001b[35m\u001b[22m executing \u001b[0m\u001b[31m\u001b[1mMyFlow\u001b[0m\u001b[35m\u001b[22m\u001b[0m\u001b[35m\u001b[22m for \u001b[0m\u001b[31m\u001b[1muser:hamel\u001b[0m\u001b[35m\u001b[22m\u001b[K\u001b[0m\u001b[35m\u001b[22m\u001b[0m\n\u001b[35m\u001b[22mValidating your flow...\u001b[K\u001b[0m\u001b[35m\u001b[22m\u001b[0m\n\u001b[32m\u001b[1m The graph looks good!\u001b[K\u001b[0m\u001b[32m\u001b[1m\u001b[0m\n\u001b[35m\u001b[22mRunning pylint...\u001b[K\u001b[0m\u001b[35m\u001b[22m\u001b[0m\n\u001b[32m\u001b[1m Pylint is happy!\u001b[K\u001b[0m\u001b[32m\u001b[1m\u001b[0m\n\u001b[35m2022-02-15 14:01:18.213 \u001b[0m\u001b[1mWorkflow starting (run-id 1644962478210532):\u001b[0m\n\u001b[35m2022-02-15 14:01:18.219 \u001b[0m\u001b[32m[1644962478210532/start/1 (pid 46778)] \u001b[0m\u001b[1mTask is starting.\u001b[0m\n\u001b[35m2022-02-15 14:01:18.849 \u001b[0m\u001b[32m[1644962478210532/start/1 (pid 46778)] \u001b[0m\u001b[22mthis is the start\u001b[0m\n\u001b[35m2022-02-15 14:01:18.917 \u001b[0m\u001b[32m[1644962478210532/start/1 (pid 46778)] \u001b[0m\u001b[1mTask finished successfully.\u001b[0m\n\u001b[35m2022-02-15 14:01:18.924 \u001b[0m\u001b[32m[1644962478210532/train/2 (pid 46783)] \u001b[0m\u001b[1mTask is starting.\u001b[0m\n\u001b[35m2022-02-15 14:01:19.566 \u001b[0m\u001b[32m[1644962478210532/train/2 (pid 46783)] \u001b[0m\u001b[22mthe train step\u001b[0m\n\u001b[35m2022-02-15 14:01:19.632 \u001b[0m\u001b[32m[1644962478210532/train/2 (pid 46783)] \u001b[0m\u001b[1mTask finished successfully.\u001b[0m\n\u001b[35m2022-02-15 14:01:19.639 \u001b[0m\u001b[32m[1644962478210532/end/3 (pid 46788)] \u001b[0m\u001b[1mTask is starting.\u001b[0m\n\u001b[35m2022-02-15 14:01:20.254 \u001b[0m\u001b[32m[1644962478210532/end/3 (pid 46788)] \u001b[0m\u001b[22mthis is the end\u001b[0m\n\u001b[35m2022-02-15 14:01:20.321 \u001b[0m\u001b[32m[1644962478210532/end/3 (pid 46788)] \u001b[0m\u001b[1mTask finished successfully.\u001b[0m\n\u001b[35m2022-02-15 14:01:20.322 \u001b[0m\u001b[1mDone!\u001b[0m\n\u001b[0m" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
d073b2f523801004f622c565a2836b38b495d7a6
29,048
ipynb
Jupyter Notebook
ML/3_ML.ipynb
astridwalle/python_jupyter_basics
27bbd1591fed3ad9b1def6b9eb31efe8fbef1f3a
[ "MIT" ]
8
2021-02-03T11:47:38.000Z
2021-02-22T23:21:27.000Z
ML/3_ML.ipynb
astridwalle/python_jupyter_basics
27bbd1591fed3ad9b1def6b9eb31efe8fbef1f3a
[ "MIT" ]
null
null
null
ML/3_ML.ipynb
astridwalle/python_jupyter_basics
27bbd1591fed3ad9b1def6b9eb31efe8fbef1f3a
[ "MIT" ]
1
2021-02-22T03:29:57.000Z
2021-02-22T03:29:57.000Z
31.746448
436
0.623313
[ [ [ "# Introduction to Machine Learning", "_____no_output_____" ], [ "(The examples in this notebook were inspired by my work for EmergentAlliance, the Scikit-Learn documentation and Jason Brownlee's \"Machine Learning Mastery with Python\")", "_____no_output_____" ], [ "In this short intro course we will focus on predictive modeling. That means that we want to use the models to make predictions, e.g. a system's future behaviour or a system's response to specific inputs, aka classification and regression.", "_____no_output_____" ], [ "So from all the various types of machine learning categories we will look at **supervised learning**. So we will train a model based on labelled training data. For example when training an image recognition model for recognizing cats vs dogs you need to label a lot of pictures for training purpose upfront.\n![](Bereiche-des-Machine-Learnings.png)", "_____no_output_____" ], [ "The other categories cover **unsupervised learning**, e.g. clustering and **Reinforcement learning**, e.g. Deepmind's AlphaGo.", "_____no_output_____" ], [ "![Alt Text](deepmind_parkour.0.gif.mp4)", "_____no_output_____" ], [ "## Datasets:\nWe will look at two different datasets:\n1. Iris Flower Dataset\n2. Boston Housing Prices\n\nThese datasets are so called toy datasets, well known machine learning examples, and already included in the Python machine learning library scikitlearn https://scikit-learn.org/stable/datasets/toy_dataset.html. The Iris Flower dataset is an example for a classification problem, whereas the Boston Housing Price dataset is a regression example.", "_____no_output_____" ], [ "## What does a ML project always look like?\n* Idea --> Problem Definition / Hypothesis formulation\n* Analyze and Visualize your data\n - Understand your data (dimensions, data types, class distributions (bias!), data summary, correllations, skewness)\n - Visualize your data (box and whisker / violine / distribution / scatter matrix)\n* Data Preprocessing including data cleansing, data wrangling, data compilation, normalization, standardization\n* Apply algorithms and make predictions\n* Improve, validate and present results", "_____no_output_____" ], [ "## Let's get started\nLoad some libraries", "_____no_output_____" ] ], [ [ "import pandas as pd # data analysis\nimport numpy as np # math operations on arrays and vectors\nimport matplotlib.pyplot as plt # plotting\n# display plots directly in the notebook\n%matplotlib inline \nimport sklearn # the library we use for all ML related functions, algorithms", "_____no_output_____" ] ], [ [ "## Example 1: Iris flower dataset\nhttps://scikit-learn.org/stable/datasets/toy_dataset.html#iris-dataset\n4 numeric, predictive attributes (sepal length in cm, sepal width in cm, petal length in cm, petal width in cm) and the class (Iris-Setosa, Iris-Versicolour, Iris-Virginica)\n\n**Hypothesis:** One can predict the class of Iris Flower based on their attributes.\n\nHere this is just one sentence, but formulating this hypothesis is a non-trivial, iterative task, which is the basis for data and feature selection and extremely important for the overall success!\n\n### 1. Load the data", "_____no_output_____" ] ], [ [ "# check here again with autocompletion --> then you can see all availbale datasets\n# https://scikit-learn.org/stable/datasets/toy_dataset.html\nfrom sklearn.datasets import load_iris", "_____no_output_____" ], [ "(data, target) =load_iris(return_X_y=True, as_frame=True)", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "target", "_____no_output_____" ] ], [ [ "We will combine this now into one dataframe and check the classes", "_____no_output_____" ] ], [ [ "data[\"class\"]=target", "_____no_output_____" ], [ "data", "_____no_output_____" ] ], [ [ "### 2. Understand your data", "_____no_output_____" ] ], [ [ "data.describe()", "_____no_output_____" ] ], [ [ "This is a classification problem, so we will check the class distribution. This is important to avoid bias due to over- oder underrepresentation of classes. Well known example of this problem are predictive maintenance (very less errors compared to normal runs, Amazon's hiring AI https://www.reuters.com/article/us-amazon-com-jobs-automation-insight-idUSKCN1MK08G)", "_____no_output_____" ] ], [ [ "class_counts = data.groupby('class').size()\nclass_counts", "_____no_output_____" ] ], [ [ "Now let's check for correlations\nCorrelation means the relationship between two variables and how they may or may not change together.\nThere are different methods available (--> check with ?data.corr)", "_____no_output_____" ] ], [ [ "correlations = data.corr(method='pearson')", "_____no_output_____" ], [ "correlations", "_____no_output_____" ] ], [ [ "Let's do a heatmap plot for the correlation matrix (pandas built-in)", "_____no_output_____" ] ], [ [ "correlations.style.background_gradient(cmap='coolwarm').set_precision(2)", "_____no_output_____" ] ], [ [ "Now we will also check the skewness of the distributions, assuming a normal Gaussian distribution. \nThe skew results show a positive (right) or negative (left) skew. Values closer to zero show less skew.", "_____no_output_____" ] ], [ [ "skew=data.skew()\nskew", "_____no_output_____" ] ], [ [ "## 2. Visualize your data\n- Histogram\n- Paiplot\n- Density", "_____no_output_____" ] ], [ [ "data.hist()", "_____no_output_____" ], [ "data.plot(kind=\"density\", subplots=True, layout=(3,2),sharex=False)", "_____no_output_____" ] ], [ [ "Another nice plot is the box and whisker plot, visualizing the quartiles of a distribution", "_____no_output_____" ] ], [ [ "data.plot(kind=\"box\", subplots=True, layout=(3,2),sharex=False)", "_____no_output_____" ] ], [ [ "Another option are the seaborn violine plots, which give a more intuitive feeling about the distribution of values", "_____no_output_____" ] ], [ [ "import seaborn as sns\nsns.violinplot(data=data,x=\"class\", y=\"sepal length (cm)\")", "_____no_output_____" ] ], [ [ "And last but not least a scatterplot matrix, similar to the pairplot we did already in the last session. This should also give insights about correllations.", "_____no_output_____" ] ], [ [ "sns.pairplot(data)", "_____no_output_____" ] ], [ [ "## 3. Data Preprocessing\nFor this dataset, there are already some steps we don't need to take, like:\nConglomeration of multiple datasources to one table, including the adaption of formats and granularities. Also we don't need to take care for missing values or NaN's. But among preprocessing there are as well\n- Rescaling\n- Normalization\n\nThe goal of these transformtions is bringing the data into a format, which is most beneficial for the later applied algorithms. So for example optimization algorithms for multivariate optimizations perform better, when all attributes / parameters have the same scale. And other methods assume that input variables have a Gaussian distribution, so it is better to transform the input parameters to meet these requirements.", "_____no_output_____" ], [ "At first we look at **rescaling**. This is done to rescale all attributes (parameters) into the same range, most of the times this is the range [0,1].\n\nFor applying these preprocessing steps at first we need to transform the dataframe into an array and split the arry in input and output values, here the descriptive parameters and the class.", "_____no_output_____" ] ], [ [ "# transform into array\narray = data.values\narray", "_____no_output_____" ], [ "# separate array into input and output components\nX = array[:,0:4]\nY = array[:,4]", "_____no_output_____" ], [ "# Now we apply the MinMaxScaler with a range of [0,1], so that afterwards all columns have a min of 0 and a max of 1.\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler(feature_range=(0, 1))\nrescaledX = scaler.fit_transform(X)\nrescaledX", "_____no_output_____" ] ], [ [ "Now we will apply Normalization by using the Standard Scaler, which means that each column (each attribute / parameter) will be transformed, such that afterwards each attribute has a standard distribution with mean = 0 and std. dev. = 1.\nGiven the distribution of the data, each value in the dataset will have the mean value subtracted, and then divided by the standard deviation of the whole dataset (or feature in the multivariate case)", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler().fit(X)\nrescaledX = scaler.transform(X)\nrescaledX", "_____no_output_____" ] ], [ [ "## 4. Feature Selection (Parameter Sensitivity)\nNow we come to an extremely interesting part, which is about finding out which parameters do really have an impact onto my outputs. This is the first time we can validate our assumptions. So we will get a qualitative and a quantitative answer to the question which parameters are important. This is also important as having irrelevant features in your data can decrease the accuracy of many models and increases the training time.", "_____no_output_____" ] ], [ [ "# Feature Extraction with Univariate Statistical Tests (Chi-squared for classification)\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\n# feature extraction\ntest = SelectKBest(score_func=chi2, k=3)\nfit = test.fit(X, Y)\n# summarize scores\nprint(fit.scores_)\nfeatures = fit.transform(X)\n# summarize selected features\nprint(features[0:5,:])", "_____no_output_____" ] ], [ [ "Here we can see the scores of the features. The higher the score, the more impact they have. As we have selected to take 3 attributes into account, we can see the values of the three selected features (sepal length (cm), sepal width (cm), petal length (cm), petal width (cm)). This result also makes sense, when remembering the correlation heatmap...", "_____no_output_____" ], [ "Another very interesting transformation, which fulfills the same job as feature extraction in terms of data reduction is the PCA. Here the complete dataset is transformed into a reduced dataset (you set the number of resulting principal components). A Singular Value Decomposition of the data is performed to project it to a lower dimensional space. ", "_____no_output_____" ] ], [ [ "from sklearn.decomposition import PCA\npca = PCA(n_components=3)\nfit = pca.fit(X)\n# summarize components\nprint(\"Explained Variance: %s\" % fit.explained_variance_ratio_)\nprint(fit.components_)", "_____no_output_____" ] ], [ [ "Of course there are even more possibilities, especially when you consider that the application of ML algorithms itself will give the feature importance. So there are multiple built-in methods available in sklearn.", "_____no_output_____" ], [ "## 5. Apply ML algorithms\n- The first step is to split our data into **training and testing data**. We need to have a separate testing dataset, which was not used for training purpose to validate the performance and accuracy of our trained model.\n- **Which algorithm to take?** There is no simple answer to that. Based on your problem (classification vs regression), there are different clases of algorithms, but you cannot know beforehand whoch algorithm will perform best on your data. So it is alwyas a good idea to try different algorithms and check the performance.\n- How to evaluate the performance? There are different metrics available to check the **performance of a ML model**", "_____no_output_____" ] ], [ [ "# specifying the size of the testing data set\n# seed: reproducable random split --> especially important when comparing different algorithms with each other.\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\ntest_size = 0.33\nseed = 7 # we set a seed to get a reproducable split - especially important when you want to compare diff. algorithms with each other\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_size,\nrandom_state=seed)\nmodel = LogisticRegression(solver='liblinear') \nmodel.fit(X_train, Y_train)\nresult = model.score(X_test, Y_test) \nprint(\"Accuracy: %.3f%%\" % (result*100.0))", "_____no_output_____" ], [ "# Let's compare the accuracy, when we use the same data for training and testing\nmodel = LogisticRegression(solver='liblinear') \nmodel.fit(X, Y)\nresult = model.score(X, Y) \nprint(\"Accuracy: %.3f%%\" % (result*100.0))", "_____no_output_____" ], [ "# get importance\nmodel = LogisticRegression(solver='liblinear') \nmodel.fit(X_train, Y_train)\nimportance = model.coef_[0]\n# summarize feature importance\nfor i,v in enumerate(importance):\n print('Feature: %0d, Score: %.5f' % (i,v))\n# print(\"Feature: \"+str(i)+\", Score: \"+str(v))\n# plot feature importance\nplt.bar([x for x in range(len(importance))], importance)", "_____no_output_____" ], [ "# decision tree for feature importance on a regression problem\nfrom sklearn.datasets import make_regression\nfrom sklearn.tree import DecisionTreeRegressor\nmodel = DecisionTreeRegressor()\n# fit the model\nmodel.fit(X_train, Y_train)\n# get importance\nimportance = model.feature_importances_\n# summarize feature importance\nfor i,v in enumerate(importance):\n\tprint('Feature: %0d, Score: %.5f' % (i,v))\n# plot feature importance\nplt.bar([x for x in range(len(importance))], importance)", "_____no_output_____" ] ], [ [ "### Test-Train-Splits\nPerforming just one test-train-split and checking the performance or feature importance might be not good enough, as the result could be very good or very bad by coincidence due to this specific split. So the easiest solution is to repeat this process several times and check the averaged accuracy or use some of the ready-to-use built-in tools in scikit-learn, like KFold, cross-val-score, LeaveOneOut, ShuffleSplit.", "_____no_output_____" ], [ "### Which ML model to use?\nHere is just a tiny overview of some mosdels one can use for classification and regression problems. For more models, which are just built-in in sciki-learn, please refer to https://scikit-learn.org/stable/index.html and https://machinelearningmastery.com\n\n- Logistic / Linear Regression\n- k-nearest neighbour\n- Classification and Regression Trees\n- Support Vector Machines\n- Neural Networks\n\nIn the following we will just use logistic regression (https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression) for our classification example and linear regression (https://scikit-learn.org/stable/modules/linear_model.html#generalized-linear-regression) for our regression example.\n", "_____no_output_____" ], [ "### ML model evaluation\nFor evaluating the model performance, there are different metrics available, depending on your type of problem (classification vs regression)\n\nFor classification, there are for example:\n- Classification accuracy\n- Logistic Loss\n- Confusion Matrix\n- ...\n\nFor regression, there are for example:\n- Mean Absolute Error\n- Mean Squared Error (R)MSE\n- R^2 \n\n\nSo the accuracy alone does by far not tell you the whole story, you need to check other metrics as well!\n\nThe confusion matrix is a handy presentation of the accuracy of a model with two or more classes. The table presents predictions on the x-axis and true outcomes on the y-axis. --> false negative, false positive\nhttps://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix\n\n#Lets have a look at our classification problem:\nkfold = KFold(n_splits=10, random_state=7, shuffle=True)\nmodel = LogisticRegression(solver='liblinear')\n\n# Classification accuracy:\nscoring = 'accuracy'\nresults = cross_val_score(model, X, Y, cv=kfold, scoring=scoring) \nprint(\"Accuracy: %.3f (%.3f)\" % (results.mean(), results.std()))\n\n# Logistic Loss\nscoring = 'neg_log_loss'\nresults = cross_val_score(model, X, Y, cv=kfold, scoring=scoring) \nprint(\"Logloss: %.3f (%.3f)\" % (results.mean(), results.std()))\n\n# Confusion Matrix\nmodel.fit(X_train, Y_train)\npredicted = model.predict(X_test)\nmatrix = confusion_matrix(Y_test, predicted)\nprint(matrix)", "_____no_output_____" ] ], [ [ "## Regression Example: Boston Housing Example", "_____no_output_____" ] ], [ [ "import sklearn\nfrom sklearn.datasets import load_boston ", "_____no_output_____" ], [ "data =load_boston(return_X_y=False)", "_____no_output_____" ], [ "print(data.DESCR)", "_____no_output_____" ], [ "df=pd.DataFrame(data.data)", "_____no_output_____" ], [ "df.columns=data.feature_names", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df[\"MEDV\"]=data.target", "_____no_output_____" ], [ "df", "_____no_output_____" ] ], [ [ "Now we start again with our procedure:\n* Hypothesis\n* Understand and visualize the data \n* Preprocessing\n* Feature Selection\n* Apply Model\n* Evaluate Results\n\nOur **Hypothesis** here is, that we can actually predict the price of a house based on attributes of the geographic area, population and the property.", "_____no_output_____" ] ], [ [ "df.describe()", "_____no_output_____" ], [ "sns.pairplot(df[[\"DIS\",\"RM\",\"CRIM\",\"LSTAT\",\"MEDV\"]])", "_____no_output_____" ], [ "from sklearn.linear_model import LinearRegression\n\n# Now we do the \n# preprocessing\n# feature selection\n# training-test-split\n# ML model application\n# evaluation\narray = df.values\nX = array[:,0:13]\nY = array[:,13]\n\n# preprocessing\nscaler = StandardScaler().fit(X)\nrescaledX = scaler.transform(X)\n\n# feature selection\ntest = SelectKBest(k=6)\nfit = test.fit(rescaledX, Y)\nfeatures = fit.transform(X)\n\n# train-test-split\nX_train, X_test, Y_train, Y_test = train_test_split(features, Y, test_size=0.3,\nrandom_state=5)\n\n# build model\nkfold = KFold(n_splits=10, random_state=7, shuffle=True)\nmodel = LinearRegression()\nmodel.fit(X_train,Y_train)\nacc = model.score(X_test, Y_test) \n\n# evaluate model\nmodel = LinearRegression()\nscoring = 'neg_mean_squared_error'\nresults = cross_val_score(model, X, Y, cv=kfold, scoring=scoring) \n\nprint(\"Accuracy: %.3f%%\" % (acc*100.0))\nprint(\"MSE: %.3f (%.3f)\" % (results.mean(), results.std()))\n\n\n# And now:\n# Make predictions\n# make predictions\n# model.predict(new_data)", "_____no_output_____" ] ], [ [ "### What comes next?\n---> Hyperparameter optimization.\nFor advanced ML algorithms you have to provide options and settings by yourself. These of course also have an impact onto your model performance and accuracy. Here you can perform so-called grid searches to find the optimal settings for your dataset.\n\n**GridSearchCV**", "_____no_output_____" ], [ "## What does a typical project look like:\n* Data engineering - **A LOT**\n* Applying actual ML algorithms - 5% of the time. \n(If you have your dataset ready to apply algorithms you have already done like 100% of the work. Of course afterwards you still need to validate and present your results)", "_____no_output_____" ], [ "![](HealthRiskIndex.png)", "_____no_output_____" ], [ "### Example: Emergent Alliance - Health Risk Index for Europe\nhttps://emergentalliance.org\nWhat we wanted to do: Predict the risk of getting infected, when travelling to a specific region.\n\nWe actually spent weeks formulating and reformulatin our hypothesis to (re-)consider influencing attributes, trying to distinguish between causes and effects.\n\nIn the end we spent most of the time with data engineering for:\nPopulation density, intensive care units, mobility, case numbers, sentiment, acceptance of governemnt orders.\nThe biggest amount of time was spent on checking data sources, getting the data, reading data dictionaries and understanding the data, creating automatic downloads and data pipelines, data preprocessig, bringing the preprocessed data into a database. We had to fight lots of issues with data quality and data granularity (time and geographic) for different countries.\n\nAlso afterwards the visual and textual processing and presentation took quite some time (writing blogs, building dashboards, cleaning up databases, ...)", "_____no_output_____" ], [ "## Image Recognition\nIt is actually quite easy to build a simple classification model (cats vs dogs), so when you are interested in applying something like this maybe to your experimental data (bubble column pictures or postprocessing contour plots), here are some links to get started:\nhttps://medium.com/@nina95dan/simple-image-classification-with-resnet-50-334366e7311a\nhttps://medium.com/abraia/getting-started-with-image-recognition-and-convolutional-neural-networks-in-5-minutes-28c1dfdd401", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d073c09f8df43a18549881ddb62ba2da01279183
596,970
ipynb
Jupyter Notebook
pandas/01-pandas_introduction.ipynb
jai-singhal/data_science
e0d9a1e3bfd3a6d2feb88fa549e86c9628bd8b2a
[ "MIT" ]
null
null
null
pandas/01-pandas_introduction.ipynb
jai-singhal/data_science
e0d9a1e3bfd3a6d2feb88fa549e86c9628bd8b2a
[ "MIT" ]
null
null
null
pandas/01-pandas_introduction.ipynb
jai-singhal/data_science
e0d9a1e3bfd3a6d2feb88fa549e86c9628bd8b2a
[ "MIT" ]
null
null
null
103.76673
152,100
0.813359
[ [ [ "<!--<img width=700px; src=\"../img/logoUPSayPlusCDS_990.png\"> -->\n\n<p style=\"margin-top: 3em; margin-bottom: 2em;\"><b><big><big><big><big>Introduction to Pandas</big></big></big></big></b></p>", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\npd.options.display.max_rows = 8", "_____no_output_____" ] ], [ [ "# 1. Let's start with a showcase\n\n#### Case 1: titanic survival data", "_____no_output_____" ] ], [ [ "df = pd.read_csv(\"data/titanic.csv\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "Starting from reading this dataset, to answering questions about this data in a few lines of code:", "_____no_output_____" ], [ "**What is the age distribution of the passengers?**", "_____no_output_____" ] ], [ [ "df['Age'].hist()", "_____no_output_____" ] ], [ [ "**How does the survival rate of the passengers differ between sexes?**", "_____no_output_____" ] ], [ [ "df.groupby('Sex')[['Survived']].aggregate(lambda x: x.sum() / len(x))", "_____no_output_____" ] ], [ [ "**Or how does it differ between the different classes?**", "_____no_output_____" ] ], [ [ "df.groupby('Pclass')['Survived'].aggregate(lambda x: x.sum() / len(x)).plot(kind='bar')", "_____no_output_____" ] ], [ [ "All the needed functionality for the above examples will be explained throughout this tutorial.", "_____no_output_____" ], [ "#### Case 2: air quality measurement timeseries", "_____no_output_____" ], [ "AirBase (The European Air quality dataBase): hourly measurements of all air quality monitoring stations from Europe\n\nStarting from these hourly data for different stations:", "_____no_output_____" ] ], [ [ "data = pd.read_csv('data/20000101_20161231-NO2.csv', sep=';', skiprows=[1], na_values=['n/d'], index_col=0, parse_dates=True)", "_____no_output_____" ], [ "data.head()", "_____no_output_____" ] ], [ [ "to answering questions about this data in a few lines of code:\n\n**Does the air pollution show a decreasing trend over the years?**", "_____no_output_____" ] ], [ [ "data['1999':].resample('M').mean().plot(ylim=[0,120])", "_____no_output_____" ], [ "data['1999':].resample('A').mean().plot(ylim=[0,100])", "_____no_output_____" ] ], [ [ "**What is the difference in diurnal profile between weekdays and weekend?**", "_____no_output_____" ] ], [ [ "data['weekday'] = data.index.weekday\ndata['weekend'] = data['weekday'].isin([5, 6])\ndata_weekend = data.groupby(['weekend', data.index.hour])['BASCH'].mean().unstack(level=0)\ndata_weekend.plot()", "_____no_output_____" ] ], [ [ "We will come back to these example, and build them up step by step.", "_____no_output_____" ], [ "# 2. Pandas: data analysis in python\n\nFor data-intensive work in Python the [Pandas](http://pandas.pydata.org) library has become essential.\n\nWhat is `pandas`?\n\n* Pandas can be thought of as *NumPy arrays with labels* for rows and columns, and better support for heterogeneous data types, but it's also much, much more than that.\n* Pandas can also be thought of as `R`'s `data.frame` in Python.\n* Powerful for working with missing data, working with time series data, for reading and writing your data, for reshaping, grouping, merging your data, ...\n\nIt's documentation: http://pandas.pydata.org/pandas-docs/stable/\n\n\n** When do you need pandas? **\n\nWhen working with **tabular or structured data** (like R dataframe, SQL table, Excel spreadsheet, ...):\n\n- Import data\n- Clean up messy data\n- Explore data, gain insight into data\n- Process and prepare your data for analysis\n- Analyse your data (together with scikit-learn, statsmodels, ...)\n\n<div class=\"alert alert-warning\">\n<b>ATTENTION!</b>: <br><br>\n\nPandas is great for working with heterogeneous and tabular 1D/2D data, but not all types of data fit in such structures!\n<ul>\n<li>When working with array data (e.g. images, numerical algorithms): just stick with numpy</li>\n<li>When working with multidimensional labeled data (e.g. climate data): have a look at [xarray](http://xarray.pydata.org/en/stable/)</li>\n</ul>\n</div>", "_____no_output_____" ], [ "# 2. The pandas data structures: `DataFrame` and `Series`\n\nA `DataFrame` is a **tablular data structure** (multi-dimensional object to hold labeled data) comprised of rows and columns, akin to a spreadsheet, database table, or R's data.frame object. You can think of it as multiple Series object which share the same index.\n\n\n<img align=\"left\" width=50% src=\"img/schema-dataframe.svg\">", "_____no_output_____" ] ], [ [ "df", "_____no_output_____" ] ], [ [ "### Attributes of the DataFrame\n\nA DataFrame has besides a `index` attribute, also a `columns` attribute:", "_____no_output_____" ] ], [ [ "df.index", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ] ], [ [ "To check the data types of the different columns:", "_____no_output_____" ] ], [ [ "df.dtypes", "_____no_output_____" ] ], [ [ "An overview of that information can be given with the `info()` method:", "_____no_output_____" ] ], [ [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 891 entries, 0 to 890\nData columns (total 12 columns):\nPassengerId 891 non-null int64\nSurvived 891 non-null int64\nPclass 891 non-null int64\nName 891 non-null object\nSex 891 non-null object\nAge 714 non-null float64\nSibSp 891 non-null int64\nParch 891 non-null int64\nTicket 891 non-null object\nFare 891 non-null float64\nCabin 204 non-null object\nEmbarked 889 non-null object\ndtypes: float64(2), int64(5), object(5)\nmemory usage: 66.2+ KB\n" ] ], [ [ "Also a DataFrame has a `values` attribute, but attention: when you have heterogeneous data, all values will be upcasted:", "_____no_output_____" ] ], [ [ "df.values", "_____no_output_____" ] ], [ [ "Apart from importing your data from an external source (text file, excel, database, ..), one of the most common ways of creating a dataframe is from a dictionary of arrays or lists.\n\nNote that in the IPython notebook, the dataframe will display in a rich HTML view:", "_____no_output_____" ] ], [ [ "data = {'country': ['Belgium', 'France', 'Germany', 'Netherlands', 'United Kingdom'],\n 'population': [11.3, 64.3, 81.3, 16.9, 64.9],\n 'area': [30510, 671308, 357050, 41526, 244820],\n 'capital': ['Brussels', 'Paris', 'Berlin', 'Amsterdam', 'London']}\ndf_countries = pd.DataFrame(data)\ndf_countries", "_____no_output_____" ] ], [ [ "### One-dimensional data: `Series` (a column of a DataFrame)\n\nA Series is a basic holder for **one-dimensional labeled data**.", "_____no_output_____" ] ], [ [ "df['Age']", "_____no_output_____" ], [ "age = df['Age']", "_____no_output_____" ] ], [ [ "### Attributes of a Series: `index` and `values`\n\nThe Series has also an `index` and `values` attribute, but no `columns`", "_____no_output_____" ] ], [ [ "age.index", "_____no_output_____" ] ], [ [ "You can access the underlying numpy array representation with the `.values` attribute:", "_____no_output_____" ] ], [ [ "age.values[:10]", "_____no_output_____" ] ], [ [ "We can access series values via the index, just like for NumPy arrays:", "_____no_output_____" ] ], [ [ "age[0]", "_____no_output_____" ] ], [ [ "Unlike the NumPy array, though, this index can be something other than integers:", "_____no_output_____" ] ], [ [ "df = df.set_index('Name')\ndf", "_____no_output_____" ], [ "age = df['Age']\nage", "_____no_output_____" ], [ "age['Dooley, Mr. Patrick']", "_____no_output_____" ] ], [ [ "but with the power of numpy arrays. Many things you can do with numpy arrays, can also be applied on DataFrames / Series.\n\nEg element-wise operations:", "_____no_output_____" ] ], [ [ "age * 1000", "_____no_output_____" ] ], [ [ "A range of methods:", "_____no_output_____" ] ], [ [ "age.mean()", "_____no_output_____" ] ], [ [ "Fancy indexing, like indexing with a list or boolean indexing:", "_____no_output_____" ] ], [ [ "age[age > 70]", "_____no_output_____" ] ], [ [ "But also a lot of pandas specific methods, e.g.", "_____no_output_____" ] ], [ [ "df['Embarked'].value_counts()", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>What is the maximum Fare that was paid? And the median?</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "df[\"Fare\"].max()", "_____no_output_____" ], [ "df[\"Fare\"].median()", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>Calculate the average survival ratio for all passengers (note: the 'Survived' column indicates whether someone survived (1) or not (0)).</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "survived_0 = df[df[\"Survived\"] == 0][\"Survived\"].count()\nsurvived_1 = df[df[\"Survived\"] == 1][\"Survived\"].count()\ntotal = df[\"Survived\"].count()\nsurvived_0_ratio = survived_0/total\nsurvived_1_ratio = survived_1/total\nprint(survived_0_ratio)\nprint(survived_1_ratio)\n\n# Method 2\nprint(df[\"Survived\"].mean())", "0.6161616161616161\n0.3838383838383838\n0.3838383838383838\n" ] ], [ [ "# 3. Data import and export", "_____no_output_____" ], [ "A wide range of input/output formats are natively supported by pandas:\n\n* CSV, text\n* SQL database\n* Excel\n* HDF5\n* json\n* html\n* pickle\n* sas, stata\n* (parquet)\n* ...", "_____no_output_____" ] ], [ [ "#pd.read", "_____no_output_____" ], [ "#df.to", "_____no_output_____" ] ], [ [ "Very powerful csv reader:", "_____no_output_____" ] ], [ [ "pd.read_csv?", "_____no_output_____" ] ], [ [ "Luckily, if we have a well formed csv file, we don't need many of those arguments:", "_____no_output_____" ] ], [ [ "df = pd.read_csv(\"data/titanic.csv\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>: Read the `data/20000101_20161231-NO2.csv` file into a DataFrame `no2`\n<br><br>\nSome aspects about the file:\n <ul>\n <li>Which separator is used in the file?</li>\n <li>The second row includes unit information and should be skipped (check `skiprows` keyword)</li>\n <li>For missing values, it uses the `'n/d'` notation (check `na_values` keyword)</li>\n <li>We want to parse the 'timestamp' column as datetimes (check the `parse_dates` keyword)</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "no2 = pd.read_csv(\"./data/20000101_20161231-NO2.csv\", sep=\";\", skiprows=[1],\n index_col =[0], na_values=[\"n/d\"], parse_dates=True )\nno2", "_____no_output_____" ] ], [ [ "# 4. Exploration", "_____no_output_____" ], [ "Some useful methods:\n\n`head` and `tail`", "_____no_output_____" ] ], [ [ "no2.head(3)", "_____no_output_____" ], [ "no2.tail()", "_____no_output_____" ] ], [ [ "`info()`", "_____no_output_____" ] ], [ [ "no2.info()", "<class 'pandas.core.frame.DataFrame'>\nDatetimeIndex: 149039 entries, 2000-01-01 01:00:00 to 2016-12-31 23:00:00\nData columns (total 4 columns):\nBASCH 139949 non-null float64\nBONAP 136493 non-null float64\nPA18 142259 non-null float64\nVERS 143813 non-null float64\ndtypes: float64(4)\nmemory usage: 5.7 MB\n" ] ], [ [ "Getting some basic summary statistics about the data with `describe`:", "_____no_output_____" ] ], [ [ "no2.describe()", "_____no_output_____" ] ], [ [ "Quickly visualizing the data", "_____no_output_____" ] ], [ [ "no2.plot(kind='box', ylim=[0,250])", "_____no_output_____" ], [ "no2['BASCH'].plot(kind='hist', bins=50)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>: \n\n <ul>\n <li>Plot the age distribution of the titanic passengers</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "df[\"Age\"].hist()", "_____no_output_____" ] ], [ [ "The default plot (when not specifying `kind`) is a line plot of all columns:", "_____no_output_____" ] ], [ [ "no2.plot(figsize=(12,6))", "_____no_output_____" ] ], [ [ "This does not say too much ..", "_____no_output_____" ], [ "We can select part of the data (eg the latest 500 data points):", "_____no_output_____" ] ], [ [ "no2[-500:].plot(figsize=(12,6))", "_____no_output_____" ] ], [ [ "Or we can use some more advanced time series features -> see further in this notebook!", "_____no_output_____" ], [ "# 5. Selecting and filtering data", "_____no_output_____" ], [ "<div class=\"alert alert-warning\">\n<b>ATTENTION!</b>: <br><br>\n\nOne of pandas' basic features is the labeling of rows and columns, but this makes indexing also a bit more complex compared to numpy. <br><br> We now have to distuinguish between:\n\n <ul>\n <li>selection by **label**</li>\n <li>selection by **position**</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "df = pd.read_csv(\"data/titanic.csv\")", "_____no_output_____" ] ], [ [ "### `df[]` provides some convenience shortcuts ", "_____no_output_____" ], [ "For a DataFrame, basic indexing selects the columns.\n\nSelecting a single column:", "_____no_output_____" ] ], [ [ "df['Age']", "_____no_output_____" ] ], [ [ "or multiple columns:", "_____no_output_____" ] ], [ [ "df[['Age', 'Fare']]", "_____no_output_____" ] ], [ [ "But, slicing accesses the rows:", "_____no_output_____" ] ], [ [ "df[10:15]", "_____no_output_____" ] ], [ [ "### Systematic indexing with `loc` and `iloc`\n\nWhen using `[]` like above, you can only select from one axis at once (rows or columns, not both). For more advanced indexing, you have some extra attributes:\n \n* `loc`: selection by label\n* `iloc`: selection by position", "_____no_output_____" ] ], [ [ "df = df.set_index('Name')", "_____no_output_____" ], [ "df.loc['Bonnell, Miss. Elizabeth', 'Fare']", "_____no_output_____" ], [ "df.loc['Bonnell, Miss. Elizabeth':'Andersson, Mr. Anders Johan', :]", "_____no_output_____" ] ], [ [ "Selecting by position with `iloc` works similar as indexing numpy arrays:", "_____no_output_____" ] ], [ [ "df.iloc[0:2,1:3]", "_____no_output_____" ] ], [ [ "The different indexing methods can also be used to assign data:", "_____no_output_____" ] ], [ [ "df.loc['Braund, Mr. Owen Harris', 'Survived'] = 100", "_____no_output_____" ], [ "df", "_____no_output_____" ] ], [ [ "### Boolean indexing (filtering)", "_____no_output_____" ], [ "Often, you want to select rows based on a certain condition. This can be done with 'boolean indexing' (like a where clause in SQL) and comparable to numpy. \n\nThe indexer (or boolean mask) should be 1-dimensional and the same length as the thing being indexed.", "_____no_output_____" ] ], [ [ "df['Fare'] > 50", "_____no_output_____" ], [ "df[df['Fare'] > 50]", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>Based on the titanic data set, select all rows for male passengers and calculate the mean age of those passengers. Do the same for the female passengers</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "df = pd.read_csv(\"data/titanic.csv\")", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction63.py\nmale_mean_age = df[df[\"Sex\"] == \"male\"][\"Age\"].mean()\nfemale_mean_age = df[df[\"Sex\"] == \"female\"][\"Age\"].mean()\nprint(male_mean_age)\nprint(female_mean_age)\nprint(male_mean_age == female_mean_age)", "30.72664459161148\n27.915708812260537\nFalse\n" ], [ "# by loc\nmale_mean_age = df.loc[df[\"Sex\"] == \"male\", \"Age\"].mean()\nfemale_mean_age = df.loc[df[\"Sex\"] == \"female\", \"Age\"].mean()\nprint(male_mean_age)\nprint(female_mean_age)\nprint(male_mean_age == female_mean_age)", "30.72664459161148\n27.915708812260537\nFalse\n" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>Based on the titanic data set, how many passengers older than 70 were on the Titanic?</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "len(df[df[\"Age\"] >= 70])", "_____no_output_____" ] ], [ [ "# 6. The group-by operation", "_____no_output_____" ], [ "### Some 'theory': the groupby operation (split-apply-combine)", "_____no_output_____" ] ], [ [ "df = pd.DataFrame({'key':['A','B','C','A','B','C','A','B','C'],\n 'data': [0, 5, 10, 5, 10, 15, 10, 15, 20]})\ndf", "_____no_output_____" ] ], [ [ "### Recap: aggregating functions", "_____no_output_____" ], [ "When analyzing data, you often calculate summary statistics (aggregations like the mean, max, ...). As we have seen before, we can easily calculate such a statistic for a Series or column using one of the many available methods. For example:", "_____no_output_____" ] ], [ [ "df['data'].sum()", "_____no_output_____" ] ], [ [ "However, in many cases your data has certain groups in it, and in that case, you may want to calculate this statistic for each of the groups.\n\nFor example, in the above dataframe `df`, there is a column 'key' which has three possible values: 'A', 'B' and 'C'. When we want to calculate the sum for each of those groups, we could do the following:", "_____no_output_____" ] ], [ [ "for key in ['A', 'B', 'C']:\n print(key, df[df['key'] == key]['data'].sum())", "_____no_output_____" ] ], [ [ "This becomes very verbose when having multiple groups. You could make the above a bit easier by looping over the different values, but still, it is not very convenient to work with.\n\nWhat we did above, applying a function on different groups, is a \"groupby operation\", and pandas provides some convenient functionality for this.", "_____no_output_____" ], [ "### Groupby: applying functions per group", "_____no_output_____" ], [ "The \"group by\" concept: we want to **apply the same function on subsets of your dataframe, based on some key to split the dataframe in subsets**\n\nThis operation is also referred to as the \"split-apply-combine\" operation, involving the following steps:\n\n* **Splitting** the data into groups based on some criteria\n* **Applying** a function to each group independently\n* **Combining** the results into a data structure\n\n<img src=\"img/splitApplyCombine.png\">\n\nSimilar to SQL `GROUP BY`", "_____no_output_____" ], [ "Instead of doing the manual filtering as above\n\n\n df[df['key'] == \"A\"].sum()\n df[df['key'] == \"B\"].sum()\n ...\n\npandas provides the `groupby` method to do exactly this:", "_____no_output_____" ] ], [ [ "df.groupby('key').sum()", "_____no_output_____" ], [ "df.groupby('key').aggregate(np.sum) # 'sum'", "_____no_output_____" ] ], [ [ "And many more methods are available. ", "_____no_output_____" ] ], [ [ "df.groupby('key')['data'].sum()", "_____no_output_____" ] ], [ [ "### Application of the groupby concept on the titanic data", "_____no_output_____" ], [ "We go back to the titanic passengers survival data:", "_____no_output_____" ] ], [ [ "df = pd.read_csv(\"data/titanic.csv\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>Calculate the average age for each sex again, but now using groupby.</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction76.py\ndf.groupby(\"Sex\")[\"Age\"].mean()", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>Calculate the average survival ratio for all passengers.</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "# df.groupby(\"Survived\")[\"Survived\"].count()\ndf[\"Survived\"].mean()\n# %load snippets/01-pandas_introduction77.py", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>Calculate this survival ratio for all passengers younger that 25 (remember: filtering/boolean indexing).</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction78.py\ndf[df[\"Age\"] <= 25][\"Survived\"].mean()", "_____no_output_____" ], [ "df25 = df[df['Age'] <= 25]\ndf25['Survived'].sum() / len(df25['Survived'])", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>What is the difference in the survival ratio between the sexes?</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction79.py\ndf.groupby(\"Sex\")[\"Survived\"].mean()", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>Or how does it differ between the different classes? Make a bar plot visualizing the survival ratio for the 3 classes.</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction80.py\ndf.groupby(\"Pclass\")[\"Survived\"].mean().plot(kind = \"bar\")", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>:\n\n <ul>\n <li>Make a bar plot to visualize the average Fare payed by people depending on their age. The age column is devided is separate classes using the `pd.cut` function as provided below.</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "df['AgeClass'] = pd.cut(df['Age'], bins=np.arange(0,90,10))", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction82.py\ndf.groupby(\"AgeClass\")[\"Fare\"].mean().plot(kind=\"bar\")", "_____no_output_____" ] ], [ [ "# 7. Working with time series data", "_____no_output_____" ] ], [ [ "no2 = pd.read_csv('data/20000101_20161231-NO2.csv', sep=';', skiprows=[1], na_values=['n/d'], index_col=0, parse_dates=True)", "_____no_output_____" ] ], [ [ "When we ensure the DataFrame has a `DatetimeIndex`, time-series related functionality becomes available:", "_____no_output_____" ] ], [ [ "no2.index", "_____no_output_____" ] ], [ [ "Indexing a time series works with strings:", "_____no_output_____" ] ], [ [ "no2[\"2010-01-01 09:00\": \"2010-01-01 12:00\"]", "_____no_output_____" ] ], [ [ "A nice feature is \"partial string\" indexing, so you don't need to provide the full datetime string.", "_____no_output_____" ], [ "E.g. all data of January up to March 2012:", "_____no_output_____" ] ], [ [ "no2['2012-01':'2012-03']", "_____no_output_____" ] ], [ [ "Time and date components can be accessed from the index:", "_____no_output_____" ] ], [ [ "no2.index.hour", "_____no_output_____" ], [ "no2.index.year", "_____no_output_____" ] ], [ [ "## Converting your time series with `resample`", "_____no_output_____" ], [ "A very powerfull method is **`resample`: converting the frequency of the time series** (e.g. from hourly to daily data).\n\nRemember the air quality data:", "_____no_output_____" ] ], [ [ "no2.plot()", "_____no_output_____" ] ], [ [ "The time series has a frequency of 1 hour. I want to change this to daily:", "_____no_output_____" ] ], [ [ "no2.head()", "_____no_output_____" ], [ "no2.resample('D').mean().head()", "_____no_output_____" ] ], [ [ "Above I take the mean, but as with `groupby` I can also specify other methods:", "_____no_output_____" ] ], [ [ "no2.resample('D').max().head()", "_____no_output_____" ] ], [ [ "The string to specify the new time frequency: http://pandas.pydata.org/pandas-docs/dev/timeseries.html#offset-aliases \nThese strings can also be combined with numbers, eg `'10D'`.", "_____no_output_____" ], [ "Further exploring the data:", "_____no_output_____" ] ], [ [ "no2.resample('M').mean().plot() # 'A'", "_____no_output_____" ], [ "# no2['2012'].resample('D').plot()", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction95.py", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>: The evolution of the yearly averages with, and the overall mean of all stations\n\n <ul>\n <li>Use `resample` and `plot` to plot the yearly averages for the different stations.</li>\n <li>The overall mean of all stations can be calculated by taking the mean of the different columns (`.mean(axis=1)`).</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction96.py", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>: how does the *typical monthly profile* look like for the different stations?\n\n <ul>\n <li>Add a 'month' column to the dataframe.</li>\n <li>Group by the month to obtain the typical monthly averages over the different years.</li>\n</ul>\n</div>", "_____no_output_____" ], [ "First, we add a column to the dataframe that indicates the month (integer value of 1 to 12):", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction97.py", "_____no_output_____" ] ], [ [ "Now, we can calculate the mean of each month over the different years:", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction98.py", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction99.py", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>: The typical diurnal profile for the different stations\n\n <ul>\n <li>Similar as for the month, you can now group by the hour of the day.</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction100.py", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>: What is the difference in the typical diurnal profile between week and weekend days for the 'BASCH' station.\n\n <ul>\n <li>Add a column 'weekday' defining the different days in the week.</li>\n <li>Add a column 'weekend' defining if a days is in the weekend (i.e. days 5 and 6) or not (True/False).</li>\n <li>You can groupby on multiple items at the same time. In this case you would need to group by both weekend/weekday and hour of the day.</li>\n</ul>\n</div>", "_____no_output_____" ], [ "Add a column indicating the weekday:", "_____no_output_____" ] ], [ [ "no2.index.weekday?", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction102.py", "_____no_output_____" ] ], [ [ "Add a column indicating week/weekend", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction103.py", "_____no_output_____" ] ], [ [ "Now we can groupby the hour of the day and the weekend (or use `pivot_table`):", "_____no_output_____" ] ], [ [ "# %load snippets/01-pandas_introduction104.py", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction105.py", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction106.py", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction107.py", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-success\">\n\n<b>EXERCISE</b>: What are the number of exceedances of hourly values above the European limit 200 µg/m3 ?\n\nCount the number of exceedances of hourly values above the European limit 200 µg/m3 for each year and station after 2005. Make a barplot of the counts. Add an horizontal line indicating the maximum number of exceedances (which is 18) allowed per year?\n<br><br>\n\nHints:\n\n <ul>\n <li>Create a new DataFrame, called `exceedances`, (with boolean values) indicating if the threshold is exceeded or not</li>\n <li>Remember that the sum of True values can be used to count elements. Do this using groupby for each year.</li>\n <li>Adding a horizontal line can be done with the matplotlib function `ax.axhline`.</li>\n</ul>\n</div>", "_____no_output_____" ] ], [ [ "# re-reading the data to have a clean version\nno2 = pd.read_csv('data/20000101_20161231-NO2.csv', sep=';', skiprows=[1], na_values=['n/d'], index_col=0, parse_dates=True)", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction109.py", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction110.py", "_____no_output_____" ], [ "# %load snippets/01-pandas_introduction111.py", "_____no_output_____" ] ], [ [ "# 9. What I didn't talk about", "_____no_output_____" ], [ "- Concatenating data: `pd.concat`\n- Merging and joining data: `pd.merge`\n- Reshaping data: `pivot_table`, `melt`, `stack`, `unstack`\n- Working with missing data: `isnull`, `dropna`, `interpolate`, ...\n- ...", "_____no_output_____" ], [ "\n## Further reading\n\n* Pandas documentation: http://pandas.pydata.org/pandas-docs/stable/\n\n* Books\n\n * \"Python for Data Analysis\" by Wes McKinney\n * \"Python Data Science Handbook\" by Jake VanderPlas\n\n* Tutorials (many good online tutorials!)\n\n * https://github.com/jorisvandenbossche/pandas-tutorial\n * https://github.com/brandon-rhodes/pycon-pandas-tutorial\n\n* Tom Augspurger's blog\n\n * https://tomaugspurger.github.io/modern-1.html", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
d073c9710df1228e0556771a109109d81b037a24
638
ipynb
Jupyter Notebook
notebooks/example.ipynb
lambdaofgod/jupyter-scala-bt
b003cfeeaa6ad4484dea166a4dd08bc8bc718f97
[ "Apache-2.0" ]
null
null
null
notebooks/example.ipynb
lambdaofgod/jupyter-scala-bt
b003cfeeaa6ad4484dea166a4dd08bc8bc718f97
[ "Apache-2.0" ]
null
null
null
notebooks/example.ipynb
lambdaofgod/jupyter-scala-bt
b003cfeeaa6ad4484dea166a4dd08bc8bc718f97
[ "Apache-2.0" ]
null
null
null
17.722222
38
0.551724
[ [ [ "import $file.scripts.importer\n\nimporter.loadProjectDependencies", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
d073ccb346ccce151432d193b997d517919e4488
73,705
ipynb
Jupyter Notebook
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
a366b8aece6892da32d7f419ad295fb201dc7f8a
[ "MIT" ]
null
null
null
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
a366b8aece6892da32d7f419ad295fb201dc7f8a
[ "MIT" ]
null
null
null
CIFAR_10/Other_numpy/my_cifar_transferlearning-Copy1.ipynb
kaelgabriel/Neural_Networks_Pytorch
a366b8aece6892da32d7f419ad295fb201dc7f8a
[ "MIT" ]
1
2018-08-22T15:43:37.000Z
2018-08-22T15:43:37.000Z
40.013572
7,728
0.617353
[ [ [ "print('Meu nome é: Gabriel Moraes Barros ')\nprint('Meu RA é: 192801')", "Meu nome é: Gabriel Moraes Barros \nMeu RA é: 192801\n" ], [ "%matplotlib inline\nimport matplotlib.pyplot as plot\nfrom IPython import display\n\nimport sys\nimport numpy as np\nimport numpy.random as nr\n\nimport keras\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n\nfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom keras.models import Sequential\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.layers import Conv2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.optimizers import (SGD, \n RMSprop, \n Adam, \n Adadelta, \n Adagrad)\n\nprint('Keras ', keras.__version__)", "Using TensorFlow backend.\n" ], [ "import os\nos.makedirs('../models', exist_ok=True)\nnr.seed(20170603)", "_____no_output_____" ], [ "!ls ../utils", "my_keras_utilities.py __pycache__\r\n" ], [ "sys.path.append('../utils')\nfrom my_keras_utilities import (get_available_gpus, \n load_model_and_history, \n save_model_and_history, \n TrainingPlotter, train_network)\n", "_____no_output_____" ] ], [ [ "### Testa se um modulo foi importado", "_____no_output_____" ] ], [ [ "'my_keras_utilities' in sys.modules\n\n", "_____no_output_____" ] ], [ [ "try:\n train_network(model_week05, model_name, train_generator, validation_generator, **fit_params);\nexcept AttributeError:\n print('nope')", "_____no_output_____" ] ], [ [ "import keras.backend as K\nK.set_image_data_format('channels_first')\nK.set_floatx('float32')\nprint('Backend: {}'.format(K.backend()))\nprint('Data format: {}'.format(K.image_data_format()))\n!nvidia-smib", "Backend: tensorflow\nData format: channels_first\n/bin/sh: 1: nvidia-smib: not found\r\n" ], [ "!ls ../Task\\ 5", "ls: cannot access '../Task 5': No such file or directory\r\n" ] ], [ [ "## Função auxiliar", "_____no_output_____" ] ], [ [ "class MyCb(TrainingPlotter):\n \n def on_epoch_end(self, epoch, logs={}):\n super().on_epoch_end(epoch, logs)\n\n\ndef train_network(model, model_name, train_generator, validation_generator, \n train_steps=10, valid_steps=10, opt='rmsprop', nepochs=50, \n patience=50, reset=False, ploss=1.0):\n\n do_plot = (ploss > 0.0)\n \n model_fn = model_name + '.model'\n if reset and os.path.isfile(model_fn):\n os.unlink(model_name + '.model')\n \n if not os.path.isfile(model_fn):\n # initialize the optimizer and model\n print(\"[INFO] compiling model...\")\n model.compile(loss=\"binary_crossentropy\", optimizer=opt, metrics=[\"accuracy\"]) \n\n # History, checkpoint, earlystop, plot losses:\n cb = [ModelCheckpoint(model_file, monitor='val_acc', verbose=0, save_best_only=True, mode='auto', period=1),\n MyCb(n=1, filepath=model_name, patience=patience, plot_losses=do_plot), \n ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=7, verbose=0, mode='auto', epsilon=0.00001, cooldown=0, min_lr=0)\n ]\n \n else:\n print(\"[INFO] loading model...\")\n model, cb = load_model_and_history(model_name)\n cb.patience = patience\n\n past_epochs = cb[1].get_nepochs()\n tr_epochs = nepochs - past_epochs\n \n if do_plot:\n vv = 0\n fig = plot.figure(figsize=(15,6))\n plot.ylim(0.0, ploss)\n plot.xlim(0, nepochs)\n plot.grid(True)\n else:\n vv = 2\n\n print(\"[INFO] training for {} epochs ...\".format(tr_epochs))\n try:\n model.fit_generator(train_generator, steps_per_epoch=train_steps,\n validation_data=validation_generator, validation_steps=valid_steps,\n epochs=nepochs, verbose=vv, callbacks=[cb[1]])\n except KeyboardInterrupt:\n pass\n\n model, histo = load_model_and_history(model_name)\n return model, cb\n\n\ndef test_network(model_name, validation_generator, nb_validation_samples):\n model, histo = load_model_and_history(model_name)\n print('Model from epoch {}'.format(histo.best_epoch))\n print(\"[INFO] evaluating in the test data set ...\")\n loss, accuracy = model.evaluate_generator(validation_generator, nb_validation_samples)\n print(\"\\n[INFO] accuracy on the test data set: {:.2f}% [{:.5f}]\".format(accuracy * 100, loss))\n", "_____no_output_____" ] ], [ [ "## Subindo o dataset", "_____no_output_____" ] ], [ [ "#auternar o comentário, se estiver no client ou no remote\ndata = np.load('/etc/jupyterhub/ia368z_2s2017/datasets/cifar10-redux.npz')\n#data = np.load('../Task 5/cifar10-redux.npz')", "_____no_output_____" ], [ "X_train = data['X_train']\ny_train = data['y_train']\nX_test = data['X_test']\ny_test = data['y_test']", "_____no_output_____" ], [ "X_train.dtype, y_train.dtype, X_test.dtype, y_test.dtype", "_____no_output_____" ] ], [ [ "### Separando o conjunto de treinamento em validação e treinamento, numa proporção 80/20 %\n", "_____no_output_____" ] ], [ [ "p=np.random.permutation(len(X_train))\npercent_factor=0.85\nnew_train_x = X_train[p]\nnew_train_y = y_train[p]\n\n\nnew_X_train = new_train_x[0:(np.floor(len(new_train_x)*percent_factor))]\nnew_y_train = new_train_y[0:(np.floor(len(new_train_y)*percent_factor))]\nnew_X_val = new_train_x[(np.ceil(len(new_train_x)*percent_factor)):]\nnew_y_val = new_train_y[(np.ceil(len(new_train_y)*percent_factor)):]\n", "/home/adessowiki/anaconda3/lib/python3.6/site-packages/ipykernel/__main__.py:7: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future\n/home/adessowiki/anaconda3/lib/python3.6/site-packages/ipykernel/__main__.py:8: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future\n/home/adessowiki/anaconda3/lib/python3.6/site-packages/ipykernel/__main__.py:9: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future\n/home/adessowiki/anaconda3/lib/python3.6/site-packages/ipykernel/__main__.py:10: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future\n" ], [ "print('X_train.shape',new_X_train.shape)\nprint('y_train.shape',new_y_train.shape)\nprint('X_val.shape',new_X_val.shape)\nprint('y_val.shape',new_y_val.shape)\nprint('y_test shape ',y_test.shape)\nprint('X_test.shape:',X_test.shape)\n", "X_train.shape (1700, 3, 32, 32)\ny_train.shape (1700,)\nX_val.shape (300, 3, 32, 32)\ny_val.shape (300,)\ny_test shape (500,)\nX_test.shape: (500, 3, 32, 32)\n" ], [ "print('Número de diferentes classes',len(np.unique(y_test)))\n", "Número de diferentes classes 3\n" ] ], [ [ "Normalizando os dados", "_____no_output_____" ] ], [ [ "a=0\nprint(np.mean(X_train))", "113.781868652\n" ] ], [ [ "#Guaranteeing that it only runs once\nif (a==0):\n X_test = X_test.astype('float32')\n new_X_train = new_X_train.astype('float32')\n new_X_val = new_X_val.astype('float32')\n \n new_X_val /= 255.\n new_X_train /= 255.\n X_test /= 255.\n \n a=1\nprint(np.mean(new_X_train))\nprint(np.mean(new_X_val))\nprint(np.mean(X_test))", "_____no_output_____" ] ], [ [ "from keras.utils import np_utils\n\n## Transforma o vetor de labels para o formato de one-hot encoding.\nn_classes = 3\ny_train_oh = np_utils.to_categorical(new_y_train-3, n_classes)\ny_val_oh = np_utils.to_categorical(new_y_val-3, n_classes)\ny_test_oh = np_utils.to_categorical(y_test-3, n_classes)", "_____no_output_____" ], [ "print(y_train_oh.shape)\nprint(y_val_oh.shape)\nprint(y_test_oh.shape)\n", "(1700, 3)\n(300, 3)\n(500, 3)\n" ] ], [ [ "## Fazendo o data augmentation", "_____no_output_____" ] ], [ [ "print(X_train.shape)\nprint(X_test.shape)", "(2000, 3, 32, 32)\n(500, 3, 32, 32)\n" ], [ "print('new x train shape', new_X_train.shape)\nprint('y train oh shape', y_train_oh.shape)\n\nprint('new x val shape', new_X_val.shape)\nprint('y val oh shape', y_val_oh.shape)\n\n", "new x train shape (1700, 3, 32, 32)\ny train oh shape (1700, 3)\nnew x val shape (300, 3, 32, 32)\ny val oh shape (300, 3)\n" ], [ "from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nnb_train_samples = new_train_x.shape[0]\nnb_val_samples = new_X_val.shape[0]\nprint('nb val samples',nb_val_samples)\nnb_test_samples = X_test.shape[0]\n\n# dimensions of our images.\nimg_width, img_height = 32, 32\nbatch_size=100", "nb val samples 300\n" ], [ "# this is the augmentation configuration we will use for training\naug_datagen = ImageDataGenerator(\n rescale=1./255, # sempre faz o rescale\n shear_range=0.2, # sorteio entre 0 e 0.2 distribuição uniforme\n zoom_range=0.2, # sorteio entre 0 e 0.2\n horizontal_flip=True) # sorteio 50%\n\nnon_aug_datagen = ImageDataGenerator( rescale=1./255)", "_____no_output_____" ], [ "train_generator = aug_datagen.flow(\n x = new_X_train, y = y_train_oh, # as amostras de treinamento\n batch_size=batch_size,shuffle=False # batch size do SGD\n )\n\nvalidation_generator = non_aug_datagen.flow(\n x = new_X_val, y = y_val_oh, # as amostras de validação\n batch_size=batch_size, shuffle = False)", "_____no_output_____" ], [ "test_generator = non_aug_datagen.flow(\n x = X_test, y = y_test_oh, # as amostras de validação\n batch_size=batch_size, shuffle = False)", "_____no_output_____" ] ], [ [ "#Conjunto de treinaemnto\nsamples_train = train_datagen.flow(new_X_train)\nn_samples_train = nb_train_samples/batch_size\n\n#Conjunto de teste\nsamples_test = train_datagen.flow(X_test)\nn_samples_test = nb_test_samples/batch_size\n#Conjunto de validacao\n\nsamples_val = train_datagen.flow(new_X_val)\nn_samples_val = nb_val_samples/batch_size", "_____no_output_____" ] ], [ [ "n_classes = len(np.unique(y_test))\nprint(n_classes)", "3\n" ] ], [ [ "## Treinamento", "_____no_output_____" ], [ "# Transfer_Learning\n", "_____no_output_____" ], [ "## Subindo a VGG-16", "_____no_output_____" ] ], [ [ "print(y_train_oh.shape)", "(1700, 3)\n" ], [ "from keras.applications.vgg16 import VGG16\nmodelvgg = VGG16(include_top=False, weights='imagenet',classes=y_train_oh.shape[1])\n", "/home/adessowiki/anaconda3/lib/python3.6/site-packages/keras/applications/vgg16.py:181: UserWarning: You are using the TensorFlow backend, yet you are using the Theano image data format convention (`image_data_format=\"channels_first\"`). For best performance, set `image_data_format=\"channels_last\"` in your Keras config at ~/.keras/keras.json.\n warnings.warn('You are using the TensorFlow backend, yet you '\n" ], [ "train_feature = modelvgg.predict_generator(generator=train_generator, steps=int(np.round(train_generator.n / batch_size)))\nprint(train_feature.shape, train_feature.dtype)\nvalidation_features = modelvgg.predict_generator(generator = validation_generator, steps=int(np.round(validation_generator.n / batch_size)))\nprint(validation_features.shape, validation_features.dtype)", "(1700, 512, 1, 1) float32\n(300, 512, 1, 1) float32\n" ], [ "train_feature.shape", "_____no_output_____" ] ], [ [ "topmodel.summary()", "_____no_output_____" ], [ "modelvgg.summary()", "_____no_output_____" ] ], [ [ "train_feature.shape[1:]\ntrain_feat = train_feature.reshape(1700,512)\nprint(train_feat.shape)", "(1700, 512)\n" ], [ "modelvgg.output", "_____no_output_____" ], [ "def model_build():\n img_rows, img_cols = 32, 32 # Dimensões das imagens\n #imagens com 3 canais e 32x32\n input_shape = (3, img_rows, img_cols)\n\n # Definindo a rede\n model = Sequential()\n #primeira conv\n model.add(Conv2D(32, (3, 3),\n input_shape=input_shape))\n model.add(Activation('relu'))\n \n #segunda conv\n model.add(Conv2D(32,(3,3)))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Dropout(0.25))\n\n # Aqui os features deixam de ser imagens\n model.add(Flatten())\n model.add(Dense(128))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(n_classes))\n model.add(Activation('softmax'))\n return model\nmodel_week05 = model_build()", "_____no_output_____" ], [ "model_week05.load_weights('../my_cifar_dataplus_model_weights.h5')\nprint(\"done\")", "done\n" ], [ "model_week05.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_1 (Conv2D) (None, 32, 30, 30) 896 \n_________________________________________________________________\nactivation_1 (Activation) (None, 32, 30, 30) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 32, 28, 28) 9248 \n_________________________________________________________________\nactivation_2 (Activation) (None, 32, 28, 28) 0 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 32, 14, 14) 0 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 32, 14, 14) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 6272) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 128) 802944 \n_________________________________________________________________\nactivation_3 (Activation) (None, 128) 0 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 128) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 3) 387 \n_________________________________________________________________\nactivation_4 (Activation) (None, 3) 0 \n=================================================================\nTotal params: 813,475\nTrainable params: 813,475\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "print(model_week05.layers)\nprint(len(model_week05.layers))\nweights10 = model_week05.layers[10].get_weights()\nprint(weights10[0].shape,weights10[1].shape)\nweights7 = model_week05.layers[7].get_weights()\nprint(weights7[0].shape,weights7[1].shape)\n", "[<keras.layers.convolutional.Conv2D object at 0x7f2475f62048>, <keras.layers.core.Activation object at 0x7f246f82e390>, <keras.layers.convolutional.Conv2D object at 0x7f246f82e7f0>, <keras.layers.core.Activation object at 0x7f246c636fd0>, <keras.layers.pooling.MaxPooling2D object at 0x7f2475f61fd0>, <keras.layers.core.Dropout object at 0x7f246c5f5e80>, <keras.layers.core.Flatten object at 0x7f2475f62b70>, <keras.layers.core.Dense object at 0x7f24b0f24a20>, <keras.layers.core.Activation object at 0x7f246c696630>, <keras.layers.core.Dropout object at 0x7f246c696cc0>, <keras.layers.core.Dense object at 0x7f246c696b00>, <keras.layers.core.Activation object at 0x7f24702d7cc0>]\n12\n(128, 3) (3,)\n(6272, 128) (128,)\n" ], [ "w2, b2 = weights10\nw1, b1 = weights7\n", "_____no_output_____" ], [ "topmodel = Sequential()\ntopmodel.add(layer=keras.layers.Flatten(input_shape=(1,1,512)))\n# topmodel.add(layer=keras.layers.Dense(units=256, activation='relu', name='d256'))\n\ntopmodel.add(layer=keras.layers.Dense(units=128, name='d256',))\ntopmodel.add(Activation('relu'))\ntopmodel.add(layer=keras.layers.Dropout(rate=.5))\ntopmodel.add(layer=keras.layers.Dense(units=3, name='d3'))\ntopmodel.add(Activation('softmax'))\n# topmodel.compile(optimizer=keras.optimizers.SGD(lr=.05, momentum=.9, nesterov=True),\ntopmodel.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])", "_____no_output_____" ], [ "topmodel.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nflatten_2 (Flatten) (None, 512) 0 \n_________________________________________________________________\nd256 (Dense) (None, 128) 65664 \n_________________________________________________________________\nactivation_5 (Activation) (None, 128) 0 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 128) 0 \n_________________________________________________________________\nd3 (Dense) (None, 3) 387 \n_________________________________________________________________\nactivation_6 (Activation) (None, 3) 0 \n=================================================================\nTotal params: 66,051\nTrainable params: 66,051\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "print(topmodel.layers)\nprint(len(topmodel.layers))", "[<keras.layers.core.Flatten object at 0x7f2470139198>, <keras.layers.core.Dense object at 0x7f2470139208>, <keras.layers.core.Activation object at 0x7f247021f828>, <keras.layers.core.Dropout object at 0x7f2470139ba8>, <keras.layers.core.Dense object at 0x7f24701392e8>, <keras.layers.core.Activation object at 0x7f24701396a0>]\n6\n" ], [ "topmodel.layers[20].set_weights([w1, b1])\ntopmodel.layers[5].set_weights([wei])", "_____no_output_____" ], [ "!ls ../", "cifar_redux_augmented_vgg.history utils week05\r\ncifar_redux_augmented_vgg.model week02 week06\r\nmodels\t\t\t\t week03\r\nmy_cifar_dataplus_model_weights.h5 week04\r\n" ] ], [ [ "w1, b1, w2, b2 = load_model('../my_cifar_dataplus_model_weights.h5').get_weights() ", "_____no_output_____" ], [ "w1, b1, w2, b2 = load_model('../my_cifar_dataplus_model_weights').get_weights()m m mmm", "_____no_output_____" ] ], [ [ "model2.load_weights('../my_cifar_dataplus_model_weights.h5')\n", "_____no_output_____" ] ], [ [ "\n # Aqui os features deixam de ser imagens\n model.add(Flatten())\n model.add(Dense(128))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(n_classes))\n model.add(Activation('softmax'))", "_____no_output_____" ], [ "topmodel = Sequential()\n# topmodel.add(layer=keras.layers.Flatten(input_shape=feat_train.shape[1:]))\n# topmodel.add(layer=keras.layers.Dense(units=256, activation='relu', name='d256'))\ntopmodel.add(layer=keras.layers.Dense(units=256, activation='relu', name='d256', input_shape=(1,1,512)))\ntopmodel.add(layer=keras.layers.Dropout(rate=.5))\ntopmodel.add(layer=keras.layers.Dense(units=3, activation='softmax', name='d3'))\n\n# topmodel.compile(optimizer=keras.optimizers.SGD(lr=.05, momentum=.9, nesterov=True),\ntopmodel.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])", "_____no_output_____" ], [ "#train_features = modelvgg.predict(new_X_train)\ntrain_features = modelvgg.predict(new_X_train)\n\nprint('train_features shape and type',train_features.shape,train_features.dtype)\nvalidation_features = modelvgg.predict(new_X_val)\nprint('validation_features shape and type',validation_features.shape,train_features.dtype)\ntest_features = modelvgg.predict(X_test)\nprint('test_features shape and type',test_features.shape,train_features.dtype)", "_____no_output_____" ] ], [ [ "modelvgg.layers.pop(18)\nmodelvgg.layers.pop(17)\nmodelvgg.layers.pop(16)\nmodelvgg.layers.pop(15)", "_____no_output_____" ], [ "#modelvgg.summary()", "_____no_output_____" ], [ "train_features = modelvgg.predict(new_X_train)\nprint('train_features shape and type',train_features.shape,train_features.dtype)\nvalidation_features = modelvgg.predict(new_X_val)\nprint('validation_features shape and type',validation_features.shape,train_features.dtype)\ntest_features = modelvgg.predict(X_test)\nprint('test_features shape and type',test_features.shape,train_features.dtype)", "_____no_output_____" ], [ "train_features.shape[1:]", "_____no_output_____" ], [ "model_name = '../cifar_redux_augmented_vgg'\n\nmodelVGG = Sequential()\nmodelVGG.add(Flatten(input_shape= train_features.shape[1:])) \nmodelVGG.add(Dense(120))\nmodelVGG.add(Activation('relu'))\nmodelVGG.add(Dropout(0.5))\nmodelVGG.add(Dense(3))\nmodelVGG.add(Activation('softmax'))", "_____no_output_____" ], [ "modelVGG.summary()", "_____no_output_____" ] ], [ [ "## Treinando class MyCb(TrainingPlotter):\n ", "_____no_output_____" ] ], [ [ "class MyCb(TrainingPlotter):\n \n def on_epoch_end(self, epoch, logs={}):\n super().on_epoch_end(epoch, logs)\n\n\ndef train_network(model, model_name, Xtra, ytra, Xval, yval, \n opt='rmsprop', batch_size=100, nepochs=50, patience=50, reset=False, ploss=1.0):\n\n do_plot = (ploss > 0.0)\n \n model_fn = model_name + '.model'\n if reset and os.path.isfile(model_fn):\n os.unlink(model_name + '.model')\n \n if not os.path.isfile(model_fn):\n # initialize the optimizer and model\n print(\"[INFO] compiling model...\")\n model.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"]) \n\n # History, checkpoint, earlystop, plot losses:\n cb = MyCb(n=1, filepath=model_name, patience=patience, plot_losses=do_plot)\n \n else:\n print(\"[INFO] loading model...\")\n model, cb = load_model_and_history(model_name)\n cb.patience = patience\n\n past_epochs = cb.get_nepochs()\n tr_epochs = nepochs - past_epochs\n \n if do_plot:\n vv = 0\n fig = plot.figure(figsize=(15,6))\n plot.ylim(0.0, ploss)\n plot.xlim(0, nepochs)\n plot.grid(True)\n else:\n vv = 2\n\n print(\"[INFO] training for {} epochs ...\".format(tr_epochs))\n try:\n model.fit(Xtra, ytra, batch_size=batch_size, epochs=tr_epochs, verbose=vv, \n validation_data=(Xval,yval), callbacks=[cb])\n except KeyboardInterrupt:\n pass\n\n model, histo = load_model_and_history(model_name)\n return model, cb\n\n\ndef test_network(model_name, Xtest, ytest, batch_size=40):\n model, histo = load_model_and_history(model_name)\n print('Model from epoch {}'.format(histo.best_epoch))\n print(\"[INFO] evaluating in the test data set ...\")\n loss, accuracy = model.evaluate(Xtest, ytest, batch_size=batch_size, verbose=1)\n print(\"\\n[INFO] accuracy on the test data set: {:.2f}% [{:.5f}]\".format(accuracy * 100, loss))", "_____no_output_____" ], [ "print('train_features.shape',train_features.shape)\nprint('validation_features.shape',validation_features.shape)\nprint('test_features.shape',test_features.shape)\n\n", "_____no_output_____" ], [ "fit_params = {\n 'opt': 'adam', # SGD(lr=0.01, momentum=0.9, nesterov=True), \n 'nepochs': 100, \n 'patience': 30,\n 'ploss': 1.5,\n 'reset': True,\n}\n\ntrain_network(modelVGG, model_name, train_features, y_train_oh, validation_features, y_val_oh, **fit_params);", "_____no_output_____" ], [ "test_network(model_name, test_features,y_test_oh,X_test.shape[0])", "_____no_output_____" ], [ "from keras.applications.vgg16 import VGG16\n\nprint(\"[INFO] creating model...\")\n#vgg = VGG16(include_top=False, weights='imagenet', input_shape=(img_height, img_width, 3))\nvgg = VGG16(include_top=False, weights='imagenet')\nvgg.summary()", "_____no_output_____" ] ], [ [ "## Construção da rede neural", "_____no_output_____" ] ], [ [ "print(train_features.shape)\nprint(new_X_train.shape)", "_____no_output_____" ], [ "img_height, img_width = new_X_train.shape[2],new_X_train.shape[3]\nprint(img_height,img_width)", "32 32\n" ], [ "!ls ..", "cifar_redux_augmented_vgg.history models week02 week04 week06\r\ncifar_redux_augmented_vgg.model utils week03 week05\r\n" ], [ "from keras.models import Model\nfrom keras.models import load_model\n\nmodel_name = '../cifar10_vgg_finetune' # modelo da rede atual\ntop_model_name = '../cifar_redux_augmented_vgg'\nnb_classes=3", "_____no_output_____" ], [ "def build_net(top_model_name):\n from keras.applications.vgg16 import VGG16\n \n print(\"[INFO] creating model...\")\n #vgg = VGG16(include_top=False, weights='imagenet', input_shape=(img_height, img_width, 3))\n #vgg = VGG16(include_top=False, weights='imagenet', input_shape=(3,img_height, img_width))\n vgg = VGG16(include_top=False, weights='imagenet', classes=nb_classes, pooling='max')\n \n print(vgg.output)\n # build a classifier model and put on top of the convolutional model\n #x = Flatten()(vgg.output)\n x = Dense(120, activation='relu', name='dense1')(vgg.output)\n x = Dropout(0.5)(x)\n x = Dense(3, activation='relu', name='d1')(x)\n x = Dropout(0.5)(x)\n x = Dense(1, activation='sigmoid', name='d2')(x)\n \n #x = Dense(40, activation='relu', name='dense1')(vgg.output)\n # x = Dropout(0.5)(x)\n #x = Dense(120, activation='relu', name='dense2')(x)\n #x = Dropout(0.2)(x)\n #x = Dense(nb_classes, activation='softmax', name='dense3')(x)\n\n #model = Model(inputs=vgg.input, outputs=x\n \n \n model = Model(inputs=vgg.input, outputs=x)\n print(model.layers)\n print(len(model.layers)) # print('Model layers:')\n # for i, layer in enumerate(model.layers):\n # print(' {:2d} {:15s} {}'.format(i, layer.name, layer))\n \n # modelo da rede densa treinada no notebook anterior\n top_model_name = top_model_name\n # Carrego os pesos treinados anteriormente\n #w1, b1, w2, b2 = load_model(top_model_name).get_weights() \n w1, b1, w2, b2 = modelVGG.get_weights() \n print(w1.shape,b1.shape,w2.shape,b2.shape)\n # Coloco nas camadas densas finais da rede\n model.layers[20].set_weights([w1, b1])\n model.layers[22].set_weights([w2, b2])\n \n # Torno não-treináveis as primeiras 15 camadas\n # da rede (os pesos não serão alterados)\n for layer in model.layers[:15]:\n layer.trainable = False\n \n return model\n\nmodel = build_net(top_model_name)", "[INFO] creating model...\n" ], [ "#model.summary()", "_____no_output_____" ], [ "model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nbatch_size = 40", "_____no_output_____" ], [ "print(new_X_train.shape, y_train_oh.shape,new_X_val.shape, y_val_oh.shape)", "(1700, 3, 32, 32) (1700, 3) (300, 3, 32, 32) (300, 3)\n" ] ], [ [ "(1600, 32, 32, 3) (1600, 3) (400, 32, 32, 3) (400, 3)\n", "_____no_output_____" ] ], [ [ "h = model.fit(new_X_train.reshape(1700,3,32,32), y_train_oh,\n validation_data=(new_X_val.reshape(300,3,32,32), y_val_oh),\n batch_size=batch_size,\n epochs=100,\n )", "_____no_output_____" ], [ "h = model.fit(X_train[train_i], y_train_oh[train_i],\n validation_data=(X_train[val_i], y_train_oh[val_i]),\n batch_size=batch_size,\n epochs=400,\n callbacks=[early_stopping, checkpointer, reduce_lr], verbose=1)", "_____no_output_____" ], [ "\nmodel_name = '../cifar10_vgg_finetune'\nfit_params = {\n 'opt': 'adam', # SGD(lr=0.01, momentum=0.9, nesterov=True), \n 'nepochs': 100, \n 'patience': 30,\n 'ploss': 1.5,\n 'reset': True,\n}\n\ntrain_network(model, model_name, train_features, y_train_oh, validation_features, y_val_oh, **fit_params);", "[INFO] compiling model...\n[INFO] training for 100 epochs ...\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d073ce9387ec02124bb2f4d73c5858c76ec6f782
238,284
ipynb
Jupyter Notebook
notebooks/data_vs_sampling_distributions.ipynb
e-alizadeh/medium
b84a9d6caf3805a1b67ac41d4fbcca56af17731f
[ "MIT" ]
17
2020-11-04T17:27:14.000Z
2021-12-22T06:09:17.000Z
notebooks/data_vs_sampling_distributions.ipynb
e-alizadeh/medium
b84a9d6caf3805a1b67ac41d4fbcca56af17731f
[ "MIT" ]
1
2021-04-25T20:58:27.000Z
2021-04-25T20:58:27.000Z
notebooks/data_vs_sampling_distributions.ipynb
e-alizadeh/medium
b84a9d6caf3805a1b67ac41d4fbcca56af17731f
[ "MIT" ]
16
2020-11-13T08:55:46.000Z
2022-03-28T06:02:01.000Z
651.04918
91,180
0.945204
[ [ [ "# Data Distribution vs. Sampling Distribution: What You Need to Know", "_____no_output_____" ], [ "This notebook is accompanying the article [Data Distribution vs. Sampling Distribution: What You Need to Know](https://www.ealizadeh.com/blog/statistics-data-vs-sampling-distribution/).\n\nSubscribe to **[my mailing list](https://www.ealizadeh.com/subscribe/)** to receive my posts on statistics, machine learning, and interesting Python libraries and tips & tricks.\n\nYou can also follow me on **[Medium](https://medium.com/@ealizadeh)**, **[LinkedIn](https://www.linkedin.com/in/alizadehesmaeil/)**, and **[Twitter]( https://twitter.com/es_alizadeh)**.\n\nCopyright © 2021 [Esmaeil Alizadeh](https://ealizadeh.com)", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(\"https://www.ealizadeh.com/wp-content/uploads/2021/01/data_dist_sampling_dist_featured_image.png\", width=1200)", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "It is important to distinguish between the data distribution (aka population distribution) and the sampling distribution. The distinction is critical when working with the central limit theorem or other concepts like the standard deviation and standard error.\n\nIn this post we will go over the above concepts and as well as bootstrapping to estimate the sampling distribution. In particular, we will cover the following:\n- Data distribution (aka population distribution)\n- Sampling distribution\n- Central limit theorem (CLT)\n- Standard error and its relation with the standard deviation\n- Bootstrapping\n\n---\n\n## Data Distribution\n\nMuch of the statistics deals with inferring from samples drawn from a larger population. Hence, we need to distinguish between the analysis done the original data as opposed to analyzing its samples. First, let's go over the definition of the data distribution:\n\n💡 **Data distribution:** *The frequency distribution of individual data points in the original dataset.*\n\n### Generate Data\nLet's first generate random skewed data that will result in a non-normal (non-Gaussian) data distribution. The reason behind generating non-normal data is to better illustrate the relation between data distribution and the sampling distribution.\n\nSo, let's import the Python plotting packages and generate right-skewed data. ", "_____no_output_____" ] ], [ [ "# Plotting packages and initial setup\nimport seaborn as sns\nsns.set_theme(palette=\"pastel\")\nsns.set_style(\"white\")\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.rcParams[\"figure.dpi\"] = 150\nsavefig_options = dict(format=\"png\", dpi=150, bbox_inches=\"tight\")", "_____no_output_____" ], [ "from scipy.stats import skewnorm\nfrom sklearn.preprocessing import MinMaxScaler\n\nnum_data_points = 10000\nmax_value = 100\nskewness = 15 # Positive values are right-skewed\n\nskewed_random_data = skewnorm.rvs(a=skewness, loc=max_value, size=num_data_points, random_state=1) \nskewed_data_scaled = MinMaxScaler().fit_transform(skewed_random_data.reshape(-1, 1))", "_____no_output_____" ] ], [ [ "Plotting the data distribution", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(figsize=(10, 6))\nax.set_title(\"Data Distribution\", fontsize=24, fontweight=\"bold\")\n\nsns.histplot(skewed_data_scaled, bins=30, stat=\"density\", kde=True, legend=False, ax=ax)\n\n# fig.savefig(\"original_skewed_data_distribution.png\", **savefig_options)", "_____no_output_____" ] ], [ [ "## Sampling Distribution\nIn the sampling distribution, you draw samples from the dataset and compute a statistic like the mean. It's very important to differentiate between the data distribution and the sampling distribution as most confusion comes from the operation done on either the original dataset or its (re)samples. \n\n💡 **Sampling distribution:** *The frequency distribution of a sample statistic (aka metric) over many samples drawn from the dataset[katex]^{[1]}[/katex]. Or to put it simply, the distribution of sample statistics is called the sampling distribution.*\n\nThe algorithm to obtain the sampling distribution is as follows: \n1. Draw a sample from the dataset.\n2. Compute a statistic/metric of the drawn sample in Step 1 and save it.\n3. Repeat Steps 1 and 2 many times.\n4. Plot the distribution (histogram) of the computed statistic.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport random\n\nsample_size = 50\nsample_means = []\n\nrandom.seed(1) # Setting the seed for reproducibility of the result\nfor _ in range(2000):\n sample = random.sample(skewed_data_scaled.tolist(), sample_size) \n sample_means.append(np.mean(sample))\n \nprint(\n f\"Mean: {np.mean(sample_means).round(5)}\"\n)", "Mean: 0.23269\n" ], [ "fig, ax = plt.subplots(figsize=(10, 6))\nax.set_title(\"Sampling Distribution\", fontsize=24, fontweight=\"bold\")\n\nsns.histplot(sample_means, bins=30, stat=\"density\", kde=True, legend=False)\n\n# fig.savefig(\"sampling_distribution.png\", **savefig_options)", "_____no_output_____" ] ], [ [ "Above sampling distribution is basically the histogram of the mean of each drawn sample (in above, we draw samples of 50 elements over 2000 iterations). The mean of the above sampling distribution is around 0.23, as can be noted from computing the mean of all samples means.\n\n⚠️ *Do not confuse the sampling distribution with the sample distribution. The sampling distribution considers the distribution of sample statistics (e.g. mean), whereas the sample distribution is basically the distribution of the sample taken from the population.*", "_____no_output_____" ], [ "## Central Limit Theorem (CLT)\n💡 **Central Limit Theorem:** *As the sample size gets larger, the sampling distribution tends to be more like a normal distribution (bell-curve shape).*\n\n*In CLT, we analyze the sampling distribution and not a data distribution, an important distinction to be made.* CLT is popular in hypothesis testing and confidence interval analysis, and it's important to be aware of this concept, even though with the use of bootstrap in data science, this theorem is less talked about or considered in the practice of data science$^{[1]}$. More on bootstrapping is provided later in the post.\n\n## Standard Error (SE)\nThe [standard error](https://en.wikipedia.org/wiki/Standard_error) is a metric to describe *the variability of a statistic in the sampling distribution*. We can compute the standard error as follows: \n$$ \\text{Standard Error} = SE = \\frac{s}{\\sqrt{n}} $$\nwhere $s$ denotes the standard deviation of the sample values and $n$ denotes the sample size. It can be seen from the formula that *as the sample size increases, the SE decreases*. \n\nWe can estimate the standard error using the following approach$^{[1]}$:\n\n1. Draw a new sample from a dataset.\n2. Compute a statistic/metric (e.g., mean) of the drawn sample in Step 1 and save it.\n3. Repeat Steps 1 and 2 several times.\n4. An estimate of the standard error is obtained by computing the standard deviation of the previous steps' statistics.\n\nWhile the above approach can be used to estimate the standard error, we can use bootstrapping instead, which is preferable. I will go over that in the next section.\n\n⚠️ *Do not confuse the standard error with the standard deviation. The standard deviation captures the variability of the individual data points (how spread the data is), unlike the standard error that captures a sample statistic's variability.*\n\n## Bootstrapping\nBootstrapping is an easy way of estimating the sampling distribution by randomly drawing samples from the population (with replacement) and computing each resample's statistic. Bootstrapping does not depend on the CLT or other assumptions on the distribution, and it is the standard way of estimating SE$^{[1]}$.\n\nLuckily, we can use [`bootstrap()`](https://rasbt.github.io/mlxtend/user_guide/evaluate/bootstrap/) functionality from the [MLxtend library](https://rasbt.github.io/mlxtend/) (You can read [my post](https://www.ealizadeh.com/blog/mlxtend-library-for-data-science/) on MLxtend library covering other interesting functionalities). This function also provides the flexibility to pass a custom sample statistic.", "_____no_output_____" ] ], [ [ "from mlxtend.evaluate import bootstrap\n\navg, std_err, ci_bounds = bootstrap(\n skewed_data_scaled, \n num_rounds=1000, \n func=np.mean, # A function to compute a sample statistic can be passed here\n ci=0.95, \n seed=123 # Setting the seed for reproducibility of the result\n)\n\nprint(\n f\"Mean: {avg.round(5)} \\n\"\n f\"Standard Error: +/- {std_err.round(5)} \\n\"\n f\"CI95: [{ci_bounds[0].round(5)}, {ci_bounds[1].round(5)}]\"\n)", "Mean: 0.23293 \nStandard Error: +/- 0.00144 \nCI95: [0.23023, 0.23601]\n" ] ], [ [ "## Conclusion\nThe main takeaway is to differentiate between whatever computation you do on the original dataset or the sampling of the dataset. Plotting a histogram of the data will result in data distribution, whereas plotting a sample statistic computed over samples of data will result in a sampling distribution. On a similar note, the standard deviation tells us how the data is spread, whereas the standard error tells us how a sample statistic is spread out. \n\nAnother takeaway is that even if the original data distribution is non-normal, the sampling distribution is normal (central limit theorem). \n\nThanks for reading!", "_____no_output_____" ], [ "___If you liked this post, you can [join my mailing list here](https://www.ealizadeh.com/subscribe/) to receive more posts about Data Science, Machine Learning, Statistics, and interesting Python libraries and tips & tricks. You can also follow me on my [website](https://ealizadeh.com/), [Medium](https://medium.com/@ealizadeh), [LinkedIn](https://www.linkedin.com/in/alizadehesmaeil/), or [Twitter](https://twitter.com/es_alizadeh).___", "_____no_output_____" ], [ "# References\n[1] P. Bruce & A. Bruce (2017), Practical Statistics for Data Scientists, First Edition, O’Reilly\n\n# Useful Links\n[MLxtend: A Python Library with Interesting Tools for Data Science Tasks](https://www.ealizadeh.com/blog/mlxtend-library-for-data-science/)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
d073e16579dd7e7ad8da8a0d03505d64f15d80a1
28,466
ipynb
Jupyter Notebook
notebooks/3-. Check combination 2 layers classifier with test set [utterance level][180t].ipynb
cinai/classification_ibl
a86b1176ab0c4d4cf3fae10804637471b8b1d4ed
[ "MIT" ]
null
null
null
notebooks/3-. Check combination 2 layers classifier with test set [utterance level][180t].ipynb
cinai/classification_ibl
a86b1176ab0c4d4cf3fae10804637471b8b1d4ed
[ "MIT" ]
null
null
null
notebooks/3-. Check combination 2 layers classifier with test set [utterance level][180t].ipynb
cinai/classification_ibl
a86b1176ab0c4d4cf3fae10804637471b8b1d4ed
[ "MIT" ]
1
2020-07-12T08:58:57.000Z
2020-07-12T08:58:57.000Z
30.059134
279
0.409611
[ [ [ "## Test \"best of two\" classifier \n\nThis notebook test a classifier that operates in two layers:\n- First we use a SVM classifier to label utterances with high degree of certainty.\n- Afterwards we use heuristics to complete the labeling", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport random\nimport pickle\nimport matplotlib.pyplot as plt\n\nroot_path = os.path.dirname(os.path.abspath(os.getcwd()))\nsys.path.append(root_path)\n\nfrom sklearn.svm import SVC\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom src import phase_classification as pc\n\ndata_path = os.path.join(root_path,'data')\ntables_path = os.path.join(data_path,'tables')\nresults_path = os.path.join(root_path,'results')\noutput_path =os.path.join(results_path,'tables')", "_____no_output_____" ], [ "import importlib\nimportlib.reload(pc)", "_____no_output_____" ], [ "WITH_STEMMING = True\n#REMOVE_STOPWORDS = True\nSEED = 10\nNUM_TOPICS = 60\nrandom.seed(SEED)\nt = 0\nCLASS_W = False", "_____no_output_____" ], [ "test_i = '[test1]'\nfile_name = test_i+'IBL_topic_distribution_by_utterance_before_after_{}_{}.xlsx'.format(WITH_STEMMING,NUM_TOPICS)\ndf_data = pd.read_excel(os.path.join(tables_path,'test','before_after',file_name))", "_____no_output_____" ], [ "the_keys = list(set(df_data['phase']))\ntotal_samples = 0\nclass_samples = {}\nfor key in the_keys:\n n = list(df_data.phase.values).count(key)\n #print(\"key {}, total {}\".format(key,n))\n total_samples += n\n class_samples[key] = n\nprint(total_samples)\nfor key in the_keys:\n print(\"key {}, samples: {}, prop: {}\".format(key,class_samples[key],round(class_samples[key]*1.0/total_samples,2)))", "181\nkey 1, samples: 55, prop: 0.3\nkey 2, samples: 27, prop: 0.15\nkey 3, samples: 46, prop: 0.25\nkey 4, samples: 7, prop: 0.04\nkey 5, samples: 46, prop: 0.25\n" ], [ "filter_rows = list(range(180))+[187,188]\nrow_label = 180", "_____no_output_____" ], [ "df_data.head(2)", "_____no_output_____" ], [ "dfs_all,_ = pc.split_df_discussions(df_data,.0,SEED)\nX_all,y_all_1 = pc.get_joined_data_from_df(dfs_all,filter_rows,row_label)", "_____no_output_____" ], [ "CLASS_W", "_____no_output_____" ], [ "name_classifier = 'classifier_svm_linear_combination_svc_ba_cw_{}.pickle'.format(CLASS_W)\nwith open(os.path.join(data_path,name_classifier),'rb') as f:\n svc = pickle.load(f)\n coeff = pickle.load(f)\n t = pickle.load(f)\n#t = 0.59\noutput_first_layer_1 = pc.first_layer_classifier(X_all,t,svc)\ncomparison = list(zip(output_first_layer_1,y_all_1))", "_____no_output_____" ], [ "df_data['first_layer'] = output_first_layer_1", "_____no_output_____" ], [ "second_layer_1 = pc.second_layer_combination_test(X_all,coeff,svc)", "_____no_output_____" ], [ "second_layer_1.count(-1)", "_____no_output_____" ], [ "df_data['second_layer'] = second_layer_1\ndf_data.to_excel(os.path.join(output_path,'[second_layer]'+file_name))", "_____no_output_____" ], [ "labels = [\"Phase {}\".format(i) for i in range(1,6)]\ndf = pd.DataFrame(confusion_matrix(y_all_1, second_layer_1),columns=[\"Predicted {}\".format(i) for i in labels])\ndf.index = labels\nprint(classification_report(y_all_1, second_layer_1))\ndf", " precision recall f1-score support\n\n 1 0.28 0.25 0.27 55\n 2 0.64 0.26 0.37 27\n 3 0.53 0.35 0.42 46\n 4 0.00 0.00 0.00 7\n 5 0.31 0.61 0.41 46\n\n micro avg 0.36 0.36 0.36 181\n macro avg 0.35 0.29 0.29 181\nweighted avg 0.39 0.36 0.35 181\n\n" ], [ "print('Accuracy of SVM classifier on training set: {:.2f}'\n .format(svc.score(X_all, y_all_1)))", "Accuracy of SVM classifier on training set: 0.30\n" ] ], [ [ "### Test 2", "_____no_output_____" ] ], [ [ "test_i = '[test2]'\nfile_name = test_i+'IBL_topic_distribution_by_utterance_before_after_{}_{}.xlsx'.format(WITH_STEMMING,NUM_TOPICS)\ndf_data = pd.read_excel(os.path.join(tables_path,'test','before_after',file_name))\nthe_keys = list(set(df_data['phase']))\ntotal_samples = 0\nclass_samples = {}\nfor key in the_keys:\n n = list(df_data.phase.values).count(key)\n #print(\"key {}, total {}\".format(key,n))\n total_samples += n\n class_samples[key] = n\nprint(total_samples)\nfor key in the_keys:\n print(\"key {}, samples: {}, prop: {}\".format(key,class_samples[key],round(class_samples[key]*1.0/total_samples,2)))", "100\nkey 1, samples: 17, prop: 0.17\nkey 2, samples: 6, prop: 0.06\nkey 3, samples: 24, prop: 0.24\nkey 4, samples: 1, prop: 0.01\nkey 5, samples: 52, prop: 0.52\n" ], [ "dfs_all,_ = pc.split_df_discussions(df_data,.0,SEED)\nX_all,y_all_2 = pc.get_joined_data_from_df(dfs_all,filter_rows,row_label)\noutput_first_layer_2 = pc.first_layer_classifier(X_all,t,name_classifier)\ncomparison = list(zip(output_first_layer_2,y_all_2))\ndf_data['first_layer'] = output_first_layer_2\nsecond_layer_2 = pc.second_layer_combination_test(X_all,coeff,svc)\ndf_data['second_layer'] = second_layer_2\ndf_data.to_excel(os.path.join(output_path,'[second_layer]'+file_name))", "_____no_output_____" ], [ "second_layer_2.count(-1)", "_____no_output_____" ], [ "labels = [\"Phase {}\".format(i) for i in range(1,6)]\ndf = pd.DataFrame(confusion_matrix(y_all_2, second_layer_2),columns=[\"Predicted {}\".format(i) for i in labels])\ndf.index = labels\nprint(classification_report(y_all_2, second_layer_2))\ndf", " precision recall f1-score support\n\n 1 0.48 0.82 0.61 17\n 2 0.67 0.33 0.44 6\n 3 0.73 0.67 0.70 24\n 4 0.00 0.00 0.00 1\n 5 0.74 0.65 0.69 52\n\n micro avg 0.66 0.66 0.66 100\n macro avg 0.52 0.50 0.49 100\nweighted avg 0.68 0.66 0.66 100\n\n" ], [ "print('Accuracy of SVM classifier on training set: {:.2f}'\n .format(svc.score(X_all, y_all_2)))", "Accuracy of SVM classifier on training set: 0.63\n" ], [ "y_all = y_all_1+y_all_2\npred = second_layer_1 + second_layer_2", "_____no_output_____" ], [ "df = pd.DataFrame(confusion_matrix(y_all, pred),columns=[\"Predicted {}\".format(i) for i in labels])\ndf.index = labels\nprint(classification_report(y_all, pred))\ndf", " precision recall f1-score support\n\n 1 0.35 0.39 0.37 72\n 2 0.64 0.27 0.38 33\n 3 0.62 0.46 0.52 70\n 4 0.00 0.00 0.00 8\n 5 0.46 0.63 0.53 98\n\n micro avg 0.47 0.47 0.47 281\n macro avg 0.41 0.35 0.36 281\nweighted avg 0.48 0.47 0.46 281\n\n" ], [ "print(\"Accuracy {0:.3f}\".format(np.sum(confusion_matrix(y_all, pred).diagonal())/len(y_all)))\nbs = [pc.unit_vector(x) for x in y_all]\ny_pred = [pc.unit_vector(x) for x in pred]\nnp.sqrt(np.sum([np.square(y_pred[i]-bs[i]) for i in range(len(y_all))])/(len(y_all)*2))", "Accuracy 0.466\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d073e8eb4deeebaf917623dc65be1c58f8271f04
8,092
ipynb
Jupyter Notebook
digits_knn.ipynb
sasiegel/mnist-classification
86df49b6bdf126a7f3ea09f0e22828ad768c11e6
[ "MIT" ]
null
null
null
digits_knn.ipynb
sasiegel/mnist-classification
86df49b6bdf126a7f3ea09f0e22828ad768c11e6
[ "MIT" ]
null
null
null
digits_knn.ipynb
sasiegel/mnist-classification
86df49b6bdf126a7f3ea09f0e22828ad768c11e6
[ "MIT" ]
null
null
null
48.166667
3,072
0.741967
[ [ [ "import torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport numpy as np", "_____no_output_____" ] ], [ [ "# Classifying Digits with K-Nearest-Neighbors (KNN)", "_____no_output_____" ], [ "This is a very simple implementation of classifying images using the k-nearest-neighbors algorithm. The accuracy is pretty good for how simple the algorithm is. The parameters can be tinkered with but at the time of writing I am using k = 5, training data size = 10000, testing data size = 1000. Let's set these parameters, read in the data, then view one of the images and the label associated with it. Afterwards I'll explain the algorithm. ", "_____no_output_____" ] ], [ [ "k = 5\nbatch_size_train = 10000\nbatch_size_test = 1000", "_____no_output_____" ], [ "train_mnist = torchvision.datasets.MNIST('C:/projects/summer2020/vision/digits/', train=True, download=True,\n transform=torchvision.transforms.ToTensor())\ntrain_loader = torch.utils.data.DataLoader(train_mnist, batch_size=batch_size_train, shuffle=True)\n\ntest_mnist = torchvision.datasets.MNIST('C:/projects/summer2020/vision/digits/', train=False, download=True,\n transform=torchvision.transforms.ToTensor())\ntest_loader = torch.utils.data.DataLoader(test_mnist,batch_size=batch_size_test, shuffle=True)", "_____no_output_____" ], [ "train_set = enumerate(train_loader)\n_, (train_imgs, train_targets) = next(train_set)\ntest_set = enumerate(test_loader)\n_, (test_imgs, test_targets) = next(test_set)", "_____no_output_____" ], [ "plt.imshow(train_imgs[0][0], cmap='gray', interpolation='none')\nplt.title(\"Ground Truth: {}\".format(train_targets[0]))\nplt.xticks([])\nplt.yticks([])", "_____no_output_____" ] ], [ [ "The k-nearest-neighbors algorithm is not very efficient and my implementation is even less efficient. I was aiming for simplicity over efficiency. We loop through each test image and find the distance to every training image. Distance is measured as Euclidean (p=2). We take the k nearest images and record the ground truth digit corresponding with the image. The predicted label is based on the majority of labels from k nearest images. The majority I chose to use is the median. It is very basic in that it is the central value/label. The effectiveness of this method of majority depends on our value of k. We compare the prediction with the ground truth of the test set which produces our prediction accuracy.", "_____no_output_____" ] ], [ [ "n_test = test_imgs.shape[0]\nn_train = train_imgs.shape[0]\npred_test_targets = torch.zeros_like(test_targets)\nfor i in range(n_test):\n test_img = test_imgs[i]\n distances = [torch.dist(test_img, train_imgs[j], p=2) for j in range(n_train)]\n nearest_indices = np.array(distances).argsort()[:5]\n pred_test_targets[i] = train_targets[nearest_indices].median()", "_____no_output_____" ], [ "accuracy = np.divide(sum(pred_test_targets == test_targets), len(test_targets))\nprint('Prediction accuracy: {}'.format(accuracy))", "Prediction accuracy: 0.959\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d07406b9225908827322d47367e096fb7c952115
51,105
ipynb
Jupyter Notebook
08_optimize/distributed-training/tensorflow/data_parallel/bert/tensorflow2_smdataparallel_bert_demo.ipynb
MarcusFra/workshop
83f16d41f5e10f9c23242066f77a14bb61ac78d7
[ "Apache-2.0" ]
2,327
2020-03-01T09:47:34.000Z
2021-11-25T12:38:42.000Z
08_optimize/distributed-training/tensorflow/data_parallel/bert/tensorflow2_smdataparallel_bert_demo.ipynb
MarcusFra/workshop
83f16d41f5e10f9c23242066f77a14bb61ac78d7
[ "Apache-2.0" ]
209
2020-03-01T17:14:12.000Z
2021-11-08T20:35:42.000Z
08_optimize/distributed-training/tensorflow/data_parallel/bert/tensorflow2_smdataparallel_bert_demo.ipynb
MarcusFra/workshop
83f16d41f5e10f9c23242066f77a14bb61ac78d7
[ "Apache-2.0" ]
686
2020-03-03T17:24:51.000Z
2021-11-25T23:39:12.000Z
59.77193
6,157
0.645045
[ [ [ "# Distributed data parallel BERT training with TensorFlow2 and SMDataParallel\n\nHSMDataParallel is a new capability in Amazon SageMaker to train deep learning models faster and cheaper. SMDataParallel is a distributed data parallel training framework for TensorFlow, PyTorch, and MXNet.\n\nThis notebook example shows how to use SMDataParallel with TensorFlow(version 2.3.1) on [Amazon SageMaker](https://aws.amazon.com/sagemaker/) to train a BERT model using [Amazon FSx for Lustre file-system](https://aws.amazon.com/fsx/lustre/) as data source.\n\nThe outline of steps is as follows:\n\n1. Stage dataset in [Amazon S3](https://aws.amazon.com/s3/). Original dataset for BERT pretraining consists of text passages from BooksCorpus (800M words) (Zhu et al. 2015) and English Wikipedia (2,500M words). Please follow original guidelines by NVidia to prepare training data in hdf5 format - \nhttps://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/BERT/README.md#getting-the-data\n2. Create Amazon FSx Lustre file-system and import data into the file-system from S3\n3. Build Docker training image and push it to [Amazon ECR](https://aws.amazon.com/ecr/)\n4. Configure data input channels for SageMaker\n5. Configure hyper-prarameters\n6. Define training metrics\n7. Define training job, set distribution strategy to SMDataParallel and start training\n\n**NOTE:** With large traning dataset, we recommend using (Amazon FSx)[https://aws.amazon.com/fsx/] as the input filesystem for the SageMaker training job. FSx file input to SageMaker significantly cuts down training start up time on SageMaker because it avoids downloading the training data each time you start the training job (as done with S3 input for SageMaker training job) and provides good data read throughput.\n\n\n**NOTE:** This example requires SageMaker Python SDK v2.X.", "_____no_output_____" ], [ "## Amazon SageMaker Initialization\n\nInitialize the notebook instance. Get the aws region, sagemaker execution role.\n\nThe IAM role arn used to give training and hosting access to your data. See the [Amazon SageMaker Roles](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) for how to create these. Note, if more than one role is required for notebook instances, training, and/or hosting, please replace the sagemaker.get_execution_role() with the appropriate full IAM role arn string(s). As described above, since we will be using FSx, please make sure to attach `FSx Access` permission to this IAM role.", "_____no_output_____" ] ], [ [ "%%time\n! python3 -m pip install --upgrade sagemaker", "Requirement already up-to-date: sagemaker in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (2.19.0)\nRequirement already satisfied, skipping upgrade: boto3>=1.16.32 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (1.16.33)\nRequirement already satisfied, skipping upgrade: google-pasta in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (0.2.0)\nRequirement already satisfied, skipping upgrade: protobuf>=3.1 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (3.8.0)\nRequirement already satisfied, skipping upgrade: packaging>=20.0 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (20.1)\nRequirement already satisfied, skipping upgrade: importlib-metadata>=1.4.0 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (1.5.0)\nRequirement already satisfied, skipping upgrade: protobuf3-to-dict>=0.1.5 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (0.1.5)\nRequirement already satisfied, skipping upgrade: attrs in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (19.3.0)\nRequirement already satisfied, skipping upgrade: numpy>=1.9.0 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (1.18.1)\nRequirement already satisfied, skipping upgrade: smdebug-rulesconfig>=1.0.0 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from sagemaker) (1.0.0)\nRequirement already satisfied, skipping upgrade: botocore<1.20.0,>=1.19.33 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from boto3>=1.16.32->sagemaker) (1.19.33)\nRequirement already satisfied, skipping upgrade: s3transfer<0.4.0,>=0.3.0 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from boto3>=1.16.32->sagemaker) (0.3.3)\nRequirement already satisfied, skipping upgrade: jmespath<1.0.0,>=0.7.1 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from boto3>=1.16.32->sagemaker) (0.10.0)\nRequirement already satisfied, skipping upgrade: six in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from google-pasta->sagemaker) (1.14.0)\nRequirement already satisfied, skipping upgrade: setuptools in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from protobuf>=3.1->sagemaker) (45.2.0.post20200210)\nRequirement already satisfied, skipping upgrade: pyparsing>=2.0.2 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from packaging>=20.0->sagemaker) (2.4.6)\nRequirement already satisfied, skipping upgrade: zipp>=0.5 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from importlib-metadata>=1.4.0->sagemaker) (2.2.0)\nRequirement already satisfied, skipping upgrade: urllib3<1.27,>=1.25.4; python_version != \"3.4\" in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from botocore<1.20.0,>=1.19.33->boto3>=1.16.32->sagemaker) (1.25.10)\nRequirement already satisfied, skipping upgrade: python-dateutil<3.0.0,>=2.1 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from botocore<1.20.0,>=1.19.33->boto3>=1.16.32->sagemaker) (2.8.1)\n\u001b[33mWARNING: You are using pip version 20.0.2; however, version 20.3.1 is available.\nYou should consider upgrading via the '/home/ec2-user/anaconda3/envs/tensorflow_p36/bin/python3 -m pip install --upgrade pip' command.\u001b[0m\nSageMaker Execution Role:arn:aws:iam::835319576252:role/service-role/AmazonSageMaker-ExecutionRole-20191006T135881\nAWS account:835319576252\nAWS region:us-east-1\nCPU times: user 122 ms, sys: 12.2 ms, total: 134 ms\nWall time: 1.87 s\n" ], [ "import sagemaker\nfrom sagemaker import get_execution_role\nfrom sagemaker.estimator import Estimator\nimport boto3\n\nsagemaker_session = sagemaker.Session()\nbucket = sagemaker_session.default_bucket()\n\nrole = get_execution_role() # provide a pre-existing role ARN as an alternative to creating a new role\nprint(f'SageMaker Execution Role:{role}')\n\nclient = boto3.client('sts')\naccount = client.get_caller_identity()['Account']\nprint(f'AWS account:{account}')\n\nsession = boto3.session.Session()\nregion = session.region_name\nprint(f'AWS region:{region}')", "SageMaker Execution Role:arn:aws:iam::835319576252:role/service-role/AmazonSageMaker-ExecutionRole-20191006T135881\nAWS account:835319576252\nAWS region:us-east-1\n" ] ], [ [ "## Prepare SageMaker Training Images\n\n1. SageMaker by default use the latest [Amazon Deep Learning Container Images (DLC)](https://github.com/aws/deep-learning-containers/blob/master/available_images.md) TensorFlow training image. In this step, we use it as a base image and install additional dependencies required for training BERT model.\n2. In the Github repository https://github.com/HerringForks/DeepLearningExamples.git we have made TensorFlow2-SMDataParallel BERT training script available for your use. This repository will be cloned in the training image for running the model training.\n\n### Build and Push Docker Image to ECR\n\nRun the below command build the docker image and push it to ECR.", "_____no_output_____" ] ], [ [ "image = \"tf2-smdataparallel-bert-sagemaker\" # Example: tf2-smdataparallel-bert-sagemaker\ntag = \"latest\" # Example: latest ", "_____no_output_____" ], [ "!pygmentize ./Dockerfile", "\u001b[34mARG\u001b[39;49;00m region\r\n\r\n\u001b[34mFROM\u001b[39;49;00m \u001b[33m763104351884.dkr.ecr.us-west-2.amazonaws.com/tensorflow-training:2.3.1-gpu-py37-cu110-ubuntu18.04\u001b[39;49;00m\r\n\r\n\u001b[34mRUN\u001b[39;49;00m \tpip --no-cache-dir --no-cache install \u001b[33m\\\u001b[39;49;00m\r\n scikit-learn==\u001b[34m0\u001b[39;49;00m.23.1 \u001b[33m\\\u001b[39;49;00m\r\n \u001b[31mwandb\u001b[39;49;00m==\u001b[34m0\u001b[39;49;00m.9.1 \u001b[33m\\\u001b[39;49;00m\r\n tensorflow-addons \u001b[33m\\\u001b[39;49;00m\r\n \u001b[31mcolorama\u001b[39;49;00m==\u001b[34m0\u001b[39;49;00m.4.3 \u001b[33m\\\u001b[39;49;00m\r\n pandas \u001b[33m\\\u001b[39;49;00m\r\n apache_beam \u001b[33m\\\u001b[39;49;00m\r\n \u001b[31mpyarrow\u001b[39;49;00m==\u001b[34m0\u001b[39;49;00m.16 \u001b[33m\\\u001b[39;49;00m\r\n git+https://github.com/HerringForks/transformers.git@master \u001b[33m\\\u001b[39;49;00m\r\n git+https://github.com/huggingface/nlp.git@703b761\r\n \r\n" ], [ "!pygmentize ./build_and_push.sh", "\u001b[37m#!/usr/bin/env bash\u001b[39;49;00m\r\n\u001b[37m# This script shows how to build the Docker image and push it to ECR to be ready for use\u001b[39;49;00m\r\n\u001b[37m# by SageMaker.\u001b[39;49;00m\r\n\u001b[37m# The argument to this script is the image name. This will be used as the image on the local\u001b[39;49;00m\r\n\u001b[37m# machine and combined with the account and region to form the repository name for ECR.\u001b[39;49;00m\r\n\u001b[37m# set region\u001b[39;49;00m\r\n\r\n\u001b[31mDIR\u001b[39;49;00m=\u001b[33m\"\u001b[39;49;00m\u001b[34m$(\u001b[39;49;00m \u001b[36mcd\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[34m$(\u001b[39;49;00m dirname \u001b[33m\"\u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31mBASH_SOURCE\u001b[39;49;00m[0]\u001b[33m}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34m)\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m && \u001b[36mpwd\u001b[39;49;00m \u001b[34m)\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\r\n\r\n\u001b[34mif\u001b[39;49;00m [ \u001b[33m\"\u001b[39;49;00m\u001b[31m$#\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m -eq \u001b[34m3\u001b[39;49;00m ]; \u001b[34mthen\u001b[39;49;00m\r\n \u001b[31mregion\u001b[39;49;00m=\u001b[31m$1\u001b[39;49;00m\r\n \u001b[31mimage\u001b[39;49;00m=\u001b[31m$2\u001b[39;49;00m\r\n \u001b[31mtag\u001b[39;49;00m=\u001b[31m$3\u001b[39;49;00m\r\n\u001b[34melse\u001b[39;49;00m\r\n \u001b[36mecho\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33musage: \u001b[39;49;00m\u001b[31m$0\u001b[39;49;00m\u001b[33m <aws-region> \u001b[39;49;00m\u001b[31m$1\u001b[39;49;00m\u001b[33m <image-repo> \u001b[39;49;00m\u001b[31m$2\u001b[39;49;00m\u001b[33m <image-tag>\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\r\n \u001b[36mexit\u001b[39;49;00m \u001b[34m1\u001b[39;49;00m\r\n\u001b[34mfi\u001b[39;49;00m\r\n\r\n\u001b[37m# Get the account number associated with the current IAM credentials\u001b[39;49;00m\r\n\u001b[31maccount\u001b[39;49;00m=\u001b[34m$(\u001b[39;49;00maws sts get-caller-identity --query Account --output text\u001b[34m)\u001b[39;49;00m\r\n\r\n\u001b[34mif\u001b[39;49;00m [ \u001b[31m$?\u001b[39;49;00m -ne \u001b[34m0\u001b[39;49;00m ]\r\n\u001b[34mthen\u001b[39;49;00m\r\n \u001b[36mexit\u001b[39;49;00m \u001b[34m255\u001b[39;49;00m\r\n\u001b[34mfi\u001b[39;49;00m\r\n\r\n\r\n\u001b[31mfullname\u001b[39;49;00m=\u001b[33m\"\u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31maccount\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\u001b[33m.dkr.ecr.\u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31mregion\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\u001b[33m.amazonaws.com/\u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31mimage\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\u001b[33m:\u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31mtag\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\r\n\r\n\u001b[37m# If the repository doesn't exist in ECR, create it.\u001b[39;49;00m\r\naws ecr describe-repositories --region \u001b[33m${\u001b[39;49;00m\u001b[31mregion\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m --repository-names \u001b[33m\"\u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31mimage\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m > /dev/null \u001b[34m2\u001b[39;49;00m>&\u001b[34m1\u001b[39;49;00m\r\n\u001b[34mif\u001b[39;49;00m [ \u001b[31m$?\u001b[39;49;00m -ne \u001b[34m0\u001b[39;49;00m ]; \u001b[34mthen\u001b[39;49;00m\r\n \u001b[36mecho\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcreating ECR repository : \u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31mfullname\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\u001b[33m \u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\r\n aws ecr create-repository --region \u001b[33m${\u001b[39;49;00m\u001b[31mregion\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m --repository-name \u001b[33m\"\u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31mimage\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m > /dev/null\r\n\u001b[34mfi\u001b[39;49;00m\r\n\r\n\u001b[34m$(\u001b[39;49;00maws ecr get-login --no-include-email --region us-west-2 --registry-ids \u001b[34m763104351884\u001b[39;49;00m\u001b[34m)\u001b[39;49;00m\r\ndocker build \u001b[33m${\u001b[39;49;00m\u001b[31mDIR\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m/ -t \u001b[33m${\u001b[39;49;00m\u001b[31mimage\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m -f \u001b[33m${\u001b[39;49;00m\u001b[31mDIR\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m/Dockerfile --build-arg \u001b[31mregion\u001b[39;49;00m=\u001b[33m${\u001b[39;49;00m\u001b[31mregion\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\r\ndocker tag \u001b[33m${\u001b[39;49;00m\u001b[31mimage\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m \u001b[33m${\u001b[39;49;00m\u001b[31mfullname\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\r\n\r\n\u001b[37m# Get the login command from ECR and execute it directly\u001b[39;49;00m\r\n\u001b[34m$(\u001b[39;49;00maws ecr get-login --region \u001b[33m${\u001b[39;49;00m\u001b[31mregion\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m --no-include-email\u001b[34m)\u001b[39;49;00m\r\ndocker push \u001b[33m${\u001b[39;49;00m\u001b[31mfullname\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\r\n\u001b[34mif\u001b[39;49;00m [ \u001b[31m$?\u001b[39;49;00m -eq \u001b[34m0\u001b[39;49;00m ]; \u001b[34mthen\u001b[39;49;00m\r\n\t\u001b[36mecho\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mAmazon ECR URI: \u001b[39;49;00m\u001b[33m${\u001b[39;49;00m\u001b[31mfullname\u001b[39;49;00m\u001b[33m}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\r\n\u001b[34melse\u001b[39;49;00m\r\n\t\u001b[36mecho\u001b[39;49;00m \u001b[33m\"Error: Image build and push failed\"\u001b[39;49;00m\r\n\t\u001b[36mexit\u001b[39;49;00m \u001b[34m1\u001b[39;49;00m\r\n\u001b[34mfi\u001b[39;49;00m\r\n" ], [ "%%time\n! chmod +x build_and_push.sh; bash build_and_push.sh {region} {image} {tag}", "WARNING! Using --password via the CLI is insecure. Use --password-stdin.\nWARNING! Your password will be stored unencrypted in /home/ec2-user/.docker/config.json.\nConfigure a credential helper to remove this warning. See\nhttps://docs.docker.com/engine/reference/commandline/login/#credentials-store\n\nLogin Succeeded\nSending build context to Docker daemon 12.35MB\nStep 1/3 : ARG region\nStep 2/3 : FROM 763104351884.dkr.ecr.us-west-2.amazonaws.com/tensorflow-training:2.3.1-gpu-py37-cu110-ubuntu18.04\n ---> 73f448953d3a\nStep 3/3 : RUN \tpip --no-cache-dir --no-cache install scikit-learn==0.23.1 wandb==0.9.1 tensorflow-addons colorama==0.4.3 pandas apache_beam pyarrow==0.16 git+https://github.com/HerringForks/transformers.git@master git+https://github.com/huggingface/nlp.git@703b761\n ---> Using cache\n ---> 24901ecc9de0\nSuccessfully built 24901ecc9de0\nSuccessfully tagged tf2-smdataparallel-bert-sagemaker:latest\nWARNING! Using --password via the CLI is insecure. Use --password-stdin.\nWARNING! Your password will be stored unencrypted in /home/ec2-user/.docker/config.json.\nConfigure a credential helper to remove this warning. See\nhttps://docs.docker.com/engine/reference/commandline/login/#credentials-store\n\nLogin Succeeded\nThe push refers to repository [835319576252.dkr.ecr.us-east-1.amazonaws.com/tf2-smdataparallel-bert-sagemaker]\n\n\u001b[1Bc96185e7: Preparing \n\u001b[1Bda29752b: Preparing \n\u001b[1Baf7081a0: Preparing \n\u001b[1B8f790f4a: Preparing \n\u001b[1Ba172edf1: Preparing \n\u001b[1B75917cc2: Preparing \n\u001b[1B445f2bde: Preparing \n\u001b[1B7f80b0c1: Preparing \n\u001b[1B90dd5fd5: Preparing \n\u001b[1B98b178d8: Preparing \n\u001b[1B7efd8228: Preparing \n\u001b[1Bdb20b91f: Preparing \n\u001b[1Bb9afb958: Preparing \n\u001b[1B7406ed5a: Preparing \n\u001b[1Bde285e41: Preparing \n\u001b[1B581d23ab: Preparing \n\u001b[1B8072e44c: Preparing \n\u001b[1Bca2d4d4f: Preparing \n\u001b[1Bf8c1572c: Preparing \n\u001b[14B45f2bde: Waiting g \n\u001b[13B0dd5fd5: Waiting g \n\u001b[1Bc9c88d14: Preparing \n\u001b[14B8b178d8: Waiting g \n\u001b[1B38a9aef5: Preparing \n\u001b[8Bca2d4d4f: Waiting g \n\u001b[11B81d23ab: Waiting g \n\u001b[11B072e44c: Waiting g \n\u001b[14Be285e41: Waiting g \n\u001b[16B406ed5a: Waiting g \n\u001b[10Bef50ffc: Waiting g \n\u001b[10B9c88d14: Waiting g \n\u001b[9B38a9aef5: Waiting g \n\u001b[1B34ed948a: Preparing \n\u001b[6B1cf2580d: Waiting g \n\u001b[6B604caecc: Waiting g \n\u001b[10B1d66695: Waiting g \n\u001b[1B93ac9526: Preparing \n\u001b[11B44c8522: Waiting g \n\u001b[34B5917cc2: Waiting g \n\u001b[1B824934b3: Preparing \n\u001b[1B9d46081a: Preparing \n\u001b[12B7c45380: Waiting g \n\u001b[12Be7b68e0: Waiting g \n\u001b[1B67539a0c: Preparing \n\u001b[13B4ed948a: Waiting g \n\u001b[1Ba984e1d1: Preparing \n\u001b[14Ba36ae91: Waiting g \n\u001b[1Bf94c75c1: Preparing \n\u001b[1Bb14f6ff1: Preparing \n\u001b[1B5f19e930: Preparing \n\u001b[1B26f8b991: Preparing \n\u001b[18Be003d68: Waiting g \n\u001b[1B4dce1444: Preparing \n\u001b[19B85beea2: Waiting g \n\u001b[1Be116c0c0: Preparing \n\u001b[1B4df0ad6c: Preparing \n\u001b[15Be1c7223: Waiting g \n\u001b[1B02706667: Layer already exists \u001b[53A\u001b[2K\u001b[48A\u001b[2K\u001b[47A\u001b[2K\u001b[39A\u001b[2K\u001b[35A\u001b[2K\u001b[31A\u001b[2K\u001b[27A\u001b[2K\u001b[22A\u001b[2K\u001b[16A\u001b[2K\u001b[12A\u001b[2K\u001b[9A\u001b[2K\u001b[4A\u001b[2Klatest: digest: sha256:a0e36b294f1909845a48d8e14725b922a137669bcb13c19e2f1029381f3c216d size: 12499\nAmazon ECR URI: 835319576252.dkr.ecr.us-east-1.amazonaws.com/tf2-smdataparallel-bert-sagemaker:latest\nCPU times: user 88.4 ms, sys: 18.1 ms, total: 106 ms\nWall time: 8.34 s\n" ] ], [ [ "## Preparing FSx Input for SageMaker\n\n1. Download and prepare your training dataset on S3.\n2. Follow the steps listed here to create a FSx linked with your S3 bucket with training data - https://docs.aws.amazon.com/fsx/latest/LustreGuide/create-fs-linked-data-repo.html. Make sure to add an endpoint to your VPC allowing S3 access.\n3. Follow the steps listed here to configure your SageMaker training job to use FSx https://aws.amazon.com/blogs/machine-learning/speed-up-training-on-amazon-sagemaker-using-amazon-efs-or-amazon-fsx-for-lustre-file-systems/\n\n### Important Caveats\n\n1. You need use the same `subnet` and `vpc` and `security group` used with FSx when launching the SageMaker notebook instance. The same configurations will be used by your SageMaker training job.\n2. Make sure you set appropriate inbound/output rules in the `security group`. Specically, opening up these ports is necessary for SageMaker to access the FSx filesystem in the training job. https://docs.aws.amazon.com/fsx/latest/LustreGuide/limit-access-security-groups.html\n3. Make sure `SageMaker IAM Role` used to launch this SageMaker training job has access to `AmazonFSx`.", "_____no_output_____" ], [ "## SageMaker TensorFlow Estimator function options\n\nIn the following code block, you can update the estimator function to use a different instance type, instance count, and distrubtion strategy. You're also passing in the training script you reviewed in the previous cell.\n\n**Instance types**\n\nSMDataParallel supports model training on SageMaker with the following instance types only:\n1. ml.p3.16xlarge\n1. ml.p3dn.24xlarge [Recommended]\n1. ml.p4d.24xlarge [Recommended]\n\n**Instance count**\n\nTo get the best performance and the most out of SMDataParallel, you should use at least 2 instances, but you can also use 1 for testing this example.\n\n**Distribution strategy**\n\nNote that to use DDP mode, you update the the `distribution` strategy, and set it to use `smdistributed dataparallel`.\n\n### Training script\n\nIn the Github repository https://github.com/HerringForks/deep-learning-models.git we have made reference TensorFlow-SMDataParallel BERT training script available for your use. Clone the repository.", "_____no_output_____" ] ], [ [ "# Clone herring forks repository for reference implementation BERT with TensorFlow2-SMDataParallel\n!rm -rf deep-learning-models\n!git clone --recursive https://github.com/HerringForks/deep-learning-models.git", "Cloning into 'deep-learning-models'...\nremote: Enumerating objects: 42, done.\u001b[K\nremote: Counting objects: 100% (42/42), done.\u001b[K\nremote: Compressing objects: 100% (34/34), done.\u001b[K\nremote: Total 1764 (delta 20), reused 18 (delta 8), pack-reused 1722\u001b[K\nReceiving objects: 100% (1764/1764), 4.76 MiB | 59.42 MiB/s, done.\nResolving deltas: 100% (834/834), done.\n" ], [ "import boto3\nimport sagemaker\nsm = boto3.client('sagemaker')", "_____no_output_____" ], [ "notebook_instance_name = sm.list_notebook_instances()['NotebookInstances'][3]['NotebookInstanceName']\nprint(notebook_instance_name)\n\nif notebook_instance_name != 'dsoaws':\n print('****** ERROR: MUST FIND THE CORRECT NOTEBOOK ******')\n exit() ", "dsoaws\n" ], [ "notebook_instance = sm.describe_notebook_instance(NotebookInstanceName=notebook_instance_name)\nnotebook_instance", "_____no_output_____" ], [ "security_group_id = notebook_instance['SecurityGroups'][0]\nprint(security_group_id)", "sg-5383e807\n" ], [ "subnet_id = notebook_instance['SubnetId']\nprint(subnet_id)", "subnet-0b8d836c\n" ], [ "from sagemaker.tensorflow import TensorFlow", "_____no_output_____" ], [ "print(account)\nprint(region)\nprint(image)\nprint(tag)", "835319576252\nus-east-1\ntf2-smdataparallel-bert-sagemaker\nlatest\n" ], [ "instance_type = \"ml.p3dn.24xlarge\" # Other supported instance type: ml.p3.16xlarge, ml.p4d.24xlarge\ninstance_count = 2 # You can use 2, 4, 8 etc.\ndocker_image = f\"{account}.dkr.ecr.{region}.amazonaws.com/{image}:{tag}\" # YOUR_ECR_IMAGE_BUILT_WITH_ABOVE_DOCKER_FILE\nusername = 'AWS'\nsubnets = [subnet_id] # Should be same as Subnet used for FSx. Example: subnet-0f9XXXX\nsecurity_group_ids = [security_group_id] # Should be same as Security group used for FSx. sg-03ZZZZZZ\njob_name = 'smdataparallel-bert-tf2-fsx-2p3dn' # This job name is used as prefix to the sagemaker training job. Makes it easy for your look for your training job in SageMaker Training job console.\n\n", "_____no_output_____" ], [ "# TODO: Copy data to FSx/S3", "_____no_output_____" ], [ "!pip install datasets", "Collecting datasets\n Downloading datasets-1.1.3-py3-none-any.whl (153 kB)\n\u001b[K |████████████████████████████████| 153 kB 10.7 MB/s eta 0:00:01\n\u001b[?25hCollecting pyarrow>=0.17.1\n Downloading pyarrow-2.0.0-cp36-cp36m-manylinux2014_x86_64.whl (17.7 MB)\n\u001b[K |████████████████████████████████| 17.7 MB 29.0 MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: tqdm<4.50.0,>=4.27 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from datasets) (4.42.1)\nCollecting dill\n Downloading dill-0.3.3-py2.py3-none-any.whl (81 kB)\n\u001b[K |████████████████████████████████| 81 kB 22.9 MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: requests>=2.19.0 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from datasets) (2.22.0)\nRequirement already satisfied: pandas in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from datasets) (1.0.1)\nCollecting dataclasses; python_version < \"3.7\"\n Downloading dataclasses-0.8-py3-none-any.whl (19 kB)\nCollecting xxhash\n Downloading xxhash-2.0.0-cp36-cp36m-manylinux2010_x86_64.whl (242 kB)\n\u001b[K |████████████████████████████████| 242 kB 112.7 MB/s eta 0:00:01\n\u001b[?25hCollecting multiprocess\n Downloading multiprocess-0.70.11.1-py36-none-any.whl (101 kB)\n\u001b[K |████████████████████████████████| 101 kB 22.0 MB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: numpy>=1.17 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from datasets) (1.18.1)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from requests>=2.19.0->datasets) (3.0.4)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from requests>=2.19.0->datasets) (1.25.10)\nRequirement already satisfied: certifi>=2017.4.17 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from requests>=2.19.0->datasets) (2020.6.20)\nRequirement already satisfied: idna<2.9,>=2.5 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from requests>=2.19.0->datasets) (2.8)\nRequirement already satisfied: pytz>=2017.2 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from pandas->datasets) (2019.3)\nRequirement already satisfied: python-dateutil>=2.6.1 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from pandas->datasets) (2.8.1)\nRequirement already satisfied: six>=1.5 in /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (from python-dateutil>=2.6.1->pandas->datasets) (1.14.0)\nInstalling collected packages: pyarrow, dill, dataclasses, xxhash, multiprocess, datasets\nSuccessfully installed dataclasses-0.8 datasets-1.1.3 dill-0.3.3 multiprocess-0.70.11.1 pyarrow-2.0.0 xxhash-2.0.0\n\u001b[33mWARNING: You are using pip version 20.0.2; however, version 20.3.1 is available.\nYou should consider upgrading via the '/home/ec2-user/anaconda3/envs/tensorflow_p36/bin/python -m pip install --upgrade pip' command.\u001b[0m\n" ], [ "# For loading datasets\nfrom datasets import list_datasets, load_dataset\n\n# To see all available dataset names\nprint(list_datasets()) \n\n# To load a dataset\nwiki = load_dataset(\"wikipedia\", \"20200501.en\", split='train')", "WARNING:tensorflow:From /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow_core/__init__.py:1473: The name tf.estimator.inputs is deprecated. Please use tf.compat.v1.estimator.inputs instead.\n\n['aeslc', 'afrikaans_ner_corpus', 'ag_news', 'ai2_arc', 'ajgt_twitter_ar', 'allegro_reviews', 'allocine', 'amazon_reviews_multi', 'amazon_us_reviews', 'ambig_qa', 'amttl', 'anli', 'aqua_rat', 'arcd', 'arsentd_lev', 'art', 'arxiv_dataset', 'aslg_pc12', 'asnq', 'asset', 'autshumato', 'bible_para', 'big_patent', 'billsum', 'biomrc', 'blended_skill_talk', 'blimp', 'blog_authorship_corpus', 'bookcorpus', 'bookcorpusopen', 'boolq', 'break_data', 'bsd_ja_en', 'c3', 'c4', 'cail2018', 'capes', 'cawac', 'cdsc', 'cdt', 'cfq', 'chr_en', 'circa', 'civil_comments', 'clinc_oos', 'clue', 'cmrc2018', 'cnn_dailymail', 'coached_conv_pref', 'coarse_discourse', 'codah', 'code_search_net', 'com_qa', 'common_gen', 'commonsense_qa', 'compguesswhat', 'conceptnet5', 'conll2000', 'conll2002', 'conll2003', 'conv_ai', 'coqa', 'cornell_movie_dialog', 'cos_e', 'cosmos_qa', 'covid_qa_castorini', 'covid_qa_deepset', 'craigslist_bargains', 'crd3', 'crime_and_punish', 'crows_pairs', 'cs_restaurants', 'csv', 'curiosity_dialogs', 'daily_dialog', 'dane', 'danish_political_comments', 'dart', 'dbpedia_14', 'dbrd', 'deal_or_no_dialog', 'definite_pronoun_resolution', 'dengue_filipino', 'dialog_re', 'disaster_response_messages', 'discofuse', 'docred', 'doqa', 'dream', 'drop', 'dyk', 'e2e_nlg', 'e2e_nlg_cleaned', 'ecb', 'eitb_parcc', 'eli5', 'emea', 'emo', 'emotion', 'empathetic_dialogues', 'enriched_web_nlg', 'eraser_multi_rc', 'esnli', 'eth_py150_open', 'euronews', 'event2Mind', 'evidence_infer_treatment', 'exams', 'fake_news_filipino', 'farsi_news', 'fever', 'finer', 'flores', 'flue', 'fquad', 'gap', 'generated_reviews_enth', 'german_legal_entity_recognition', 'germaner', 'germeval_14', 'gigaword', 'glucose', 'glue', 'go_emotions', 'google_wellformed_query', 'grail_qa', 'great_code', 'guardian_authorship', 'gutenberg_time', 'hans', 'hansards', 'hard', 'hate_speech_filipino', 'hausa_voa_ner', 'hausa_voa_topics', 'health_fact', 'hebrew_sentiment', 'hellaswag', 'hkcancor', 'hotpot_qa', 'hybrid_qa', 'hyperpartisan_news_detection', 'id_nergrit_ner', 'imdb', 'imdb_urdu_reviews', 'indic_glue', 'inquisitive_qg', 'isixhosa_ner_corpus', 'isizulu_ner_corpus', 'iwslt2017', 'jeopardy', 'jfleg', 'jnlpba', 'json', 'kannada_news', 'kelm', 'kilt_tasks', 'kilt_wikipedia', 'kor_hate', 'kor_ner', 'kor_nli', 'kor_nlu', 'kor_qpair', 'labr', 'lambada', 'large_spanish_corpus', 'lc_quad', 'lener_br', 'librispeech_lm', 'limit', 'lince', 'linnaeus', 'lm1b', 'lst20', 'math_dataset', 'math_qa', 'matinf', 'mc_taco', 'med_hop', 'medal', 'medical_questions_pairs', 'metooma', 'metrec', 'mkb', 'mkqa', 'mlqa', 'mlsum', 'mocha', 'movie_rationales', 'mrqa', 'ms_marco', 'ms_terms', 'msr_genomics_kbcomp', 'msr_text_compression', 'msr_zhen_translation_parity', 'msra_ner', 'multi_news', 'multi_nli', 'multi_nli_mismatch', 'multi_para_crawl', 'multi_woz_v22', 'multi_x_science_sum', 'mwsc', 'myanmar_news', 'natural_questions', 'ncbi_disease', 'nchlt', 'ncslgr', 'neural_code_search', 'news_commentary', 'newsgroup', 'newsph', 'newsph_nli', 'newsroom', 'nkjp-ner', 'nli_tr', 'norwegian_ner', 'nsmc', 'numer_sense', 'numeric_fused_head', 'oclar', 'offenseval2020_tr', 'onestop_english', 'open_subtitles', 'openbookqa', 'openwebtext', 'opinosis', 'opus100', 'opus_dogc', 'opus_elhuyar', 'opus_euconst', 'opus_finlex', 'opus_fiskmo', 'opus_infopankki', 'opus_memat', 'opus_montenegrinsubs', 'opus_openoffice', 'opus_sardware', 'opus_xhosanavy', 'orange_sum', 'pandas', 'para_crawl', 'paws', 'paws-x', 'pec', 'peoples_daily_ner', 'pg19', 'php', 'piaf', 'pib', 'piqa', 'poem_sentiment', 'polemo2', 'polyglot_ner', 'prachathai67k', 'pragmeval', 'proto_qa', 'psc', 'pubmed_qa', 'py_ast', 'qa4mre', 'qa_zre', 'qangaroo', 'qanta', 'qasc', 'qed', 'qed_amara', 'quac', 'quail', 'quarel', 'quartz', 'quora', 'quoref', 'race', 're_dial', 'recipe_nlg', 'reclor', 'reddit', 'reddit_tifu', 'reuters21578', 'roman_urdu', 'ropes', 'rotten_tomatoes', 'sanskrit_classic', 'scan', 'scb_mt_enth_2020', 'schema_guided_dstc8', 'scicite', 'scielo', 'scientific_papers', 'scifact', 'sciq', 'scitail', 'scitldr', 'search_qa', 'sem_eval_2010_task_8', 'sem_eval_2014_task_1', 'sent_comp', 'sentiment140', 'sepedi_ner', 'sesotho_ner_corpus', 'setimes', 'setswana_ner_corpus', 'sharc', 'sharc_modified', 'simple_questions_v2', 'siswati_ner_corpus', 'smartdata', 'sms_spam', 'snli', 'social_bias_frames', 'social_i_qa', 'sogou_news', 'species_800', 'spider', 'squad', 'squad_es', 'squad_it', 'squad_kor_v1', 'squad_v1_pt', 'squad_v2', 'squadshifts', 'stsb_mt_sv', 'style_change_detection', 'super_glue', 'swag', 'swahili_news', 'swedish_ner_corpus', 'swedish_reviews', 'tab_fact', 'tamilmixsentiment', 'tanzil', 'tashkeela', 'taskmaster1', 'taskmaster2', 'taskmaster3', 'tatoeba', 'ted_hrlr', 'ted_multi', 'telugu_books', 'telugu_news', 'tep_en_fa_para', 'text', 'thainer', 'thaiqa_squad', 'thaisum', 'tilde_model', 'tiny_shakespeare', 'tlc', 'totto', 'trec', 'trivia_qa', 'tsac', 'tunizi', 'tuple_ie', 'turkish_ner', 'turku_ner_corpus', 'tweet_qa', 'tweets_ar_en_parallel', 'tydiqa', 'ubuntu_dialogs_corpus', 'udhr', 'um005', 'un_multi', 'un_pc', 'universal_dependencies', 'urdu_fake_news', 'urdu_sentiment_corpus', 'web_nlg', 'web_of_science', 'web_questions', 'weibo_ner', 'wiki40b', 'wiki_auto', 'wiki_bio', 'wiki_dpr', 'wiki_hop', 'wiki_qa', 'wiki_qa_ar', 'wiki_snippets', 'wiki_split', 'wikiann', 'wikicorpus', 'wikihow', 'wikipedia', 'wikisql', 'wikitext', 'wikitext_tl39', 'winograd_wsc', 'winogrande', 'wiqa', 'wisesight1000', 'wisesight_sentiment', 'wmt14', 'wmt15', 'wmt16', 'wmt17', 'wmt18', 'wmt19', 'wmt_t2t', 'wnut_17', 'wongnai_reviews', 'woz_dialogue', 'x_stance', 'xcopa', 'xglue', 'xnli', 'xor_tydi_qa', 'xquad', 'xquad_r', 'xsum', 'xtreme', 'yahoo_answers_qa', 'yahoo_answers_topics', 'yelp_polarity', 'yelp_review_full', 'yoruba_bbc_topics', 'yoruba_gv_ner', 'zest', 'Fraser/news-category-dataset', 'Fraser/python-lines', 'cdminix/mgb1', 'german-nlp-group/german_common_crawl', 'joelito/ler', 'joelito/sem_eval_2010_task_8', 'k-halid/ar', 'lhoestq/squad', 'mulcyber/europarl-mono', 'piEsposito/br-quad-2.0', 'piEsposito/br_quad_20', 'piEsposito/squad_20_ptbr', 'sshleifer/pseudo_bart_xsum']\n" ], [ "file_system_id = '<FSX_ID>' # FSx file system ID with your training dataset. Example: 'fs-0bYYYYYY'", "_____no_output_____" ], [ "SM_DATA_ROOT = '/opt/ml/input/data/train'\n\nhyperparameters={\n \"train_dir\": '/'.join([SM_DATA_ROOT, 'tfrecords/train/max_seq_len_128_max_predictions_per_seq_20_masked_lm_prob_15']),\n \"val_dir\": '/'.join([SM_DATA_ROOT, 'tfrecords/validation/max_seq_len_128_max_predictions_per_seq_20_masked_lm_prob_15']), \n \"log_dir\": '/'.join([SM_DATA_ROOT, 'checkpoints/bert/logs']), \n \"checkpoint_dir\": '/'.join([SM_DATA_ROOT, 'checkpoints/bert']), \n \"load_from\": \"scratch\", \n \"model_type\": \"bert\", \n \"model_size\": \"large\", \n \"per_gpu_batch_size\": 64, \n \"max_seq_length\": 128,\n \"max_predictions_per_seq\": 20, \n \"optimizer\": \"lamb\", \n \"learning_rate\": 0.005, \n \"end_learning_rate\": 0.0003, \n \"hidden_dropout_prob\": 0.1, \n \"attention_probs_dropout_prob\": 0.1,\n \"gradient_accumulation_steps\": 1,\n \"learning_rate_decay_power\": 0.5, \n \"warmup_steps\": 2812, \n \"total_steps\": 2000, \n \"log_frequency\": 10,\n \"run_name\" : job_name,\n \"squad_frequency\": 0\n }", "_____no_output_____" ], [ "estimator = TensorFlow(entry_point='albert/run_pretraining.py',\n role=role,\n image_uri=docker_image,\n source_dir='deep-learning-models/models/nlp',\n framework_version='2.3.1',\n py_version='py3',\n instance_count=instance_count,\n instance_type=instance_type,\n sagemaker_session=sagemaker_session,\n subnets=subnets,\n hyperparameters=hyperparameters,\n security_group_ids=security_group_ids,\n debugger_hook_config=False,\n # Training using SMDataParallel Distributed Training Framework\n distribution={'smdistributed':{\n 'dataparallel':{\n 'enabled': True\n }\n }\n }\n )", "_____no_output_____" ] ], [ [ "# Configure FSx Input for the SageMaker Training Job", "_____no_output_____" ] ], [ [ "from sagemaker.inputs import FileSystemInput\n\n#YOUR_MOUNT_PATH_FOR_TRAINING_DATA # NOTE: '/fsx/' will be the root mount path. Example: '/fsx/albert''''\nfile_system_directory_path='/fsx/' \nfile_system_access_mode='rw'\nfile_system_type='FSxLustre'\n\ntrain_fs = FileSystemInput(file_system_id=file_system_id,\n file_system_type=file_system_type,\n directory_path=file_system_directory_path,\n file_system_access_mode=file_system_access_mode)\ndata_channels = {'train': train_fs}", "_____no_output_____" ], [ "# Submit SageMaker training job\nestimator.fit(inputs=data_channels, job_name=job_name)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d0740f2fb93344e9b3b98b8529e3670ac14356ed
43,664
ipynb
Jupyter Notebook
Project-2_Continuous-Control/Continuous-Control/Continuous_Control.ipynb
Mohammedabdalqader/DRL
cf7abbcff8cb8c928983d5d5c9f3d1adc4f34bf4
[ "MIT" ]
null
null
null
Project-2_Continuous-Control/Continuous-Control/Continuous_Control.ipynb
Mohammedabdalqader/DRL
cf7abbcff8cb8c928983d5d5c9f3d1adc4f34bf4
[ "MIT" ]
4
2020-11-13T18:53:36.000Z
2022-02-10T01:48:19.000Z
Project-2_Continuous-Control/Continuous-Control/Continuous_Control.ipynb
Mohammedabdalqader/DRL
cf7abbcff8cb8c928983d5d5c9f3d1adc4f34bf4
[ "MIT" ]
null
null
null
101.308585
27,500
0.817722
[ [ [ "# Continuous Control\n\n---\n\n\nIn this notebook I will implement the distributed disttributional deep determenstic policy gradients (D4PG) algorithm.\n\n#### different algorithm can also be used to solve this problem such as :\n '''\n 1 - Deep determenstic policy gradients (DDPG)\n 2 - Proximal policy optimization (PPO)\n 3 - Asynchronous Advantage Actor-Critic (A3C)\n 4 - Trust Region Policy Optimization (TRPO)\n\n \n and many more \n '''", "_____no_output_____" ], [ "# 1. Start the Environment\n", "_____no_output_____" ], [ "The environments corresponding to both versions of the environment are already saved in the work dirictory and can be accessed at the file paths provided below. \n\nPlease select one of the two options below for loading the environment.\n\nNote: This implementation applies to the second option, where the environment consists of 20 agents.", "_____no_output_____" ] ], [ [ "import random\nimport time\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom collections import deque\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nfrom unityagents import UnityEnvironment\nfrom d4pg_agent import Agent\n\n\n# select this option to load version 1 (with a single agent) of the environment\n#env = UnityEnvironment(file_name='Reacher_v1_Windows_x86_64/Reacher.exe')\n\n# select this option to load version 2 (with 20 agents) of the environment\nenv = UnityEnvironment(file_name='Reacher_v2_Windows_x86_64/Reacher.exe')", "INFO:unityagents:\n'Academy' started successfully!\nUnity Academy name: Academy\n Number of Brains: 1\n Number of External Brains : 1\n Lesson number : 0\n Reset Parameters :\n\t\tgoal_speed -> 1.0\n\t\tgoal_size -> 5.0\nUnity brain name: ReacherBrain\n Number of Visual Observations (per agent): 0\n Vector Observation space type: continuous\n Vector Observation space size (per agent): 33\n Number of stacked Vector Observation: 1\n Vector Action space type: continuous\n Vector Action space size (per agent): 4\n Vector Action descriptions: , , , \n" ] ], [ [ "Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python.", "_____no_output_____" ] ], [ [ "# get the default brain\nbrain_name = env.brain_names[0]\nbrain = env.brains[brain_name]", "_____no_output_____" ] ], [ [ "# 2. Examine the State and Action Spaces\n\nRun the code cell below to print some information about the environment.", "_____no_output_____" ] ], [ [ "# reset the environment\nenv_info = env.reset(train_mode=True)[brain_name]\n\n# number of agents\nnum_agents = len(env_info.agents)\nprint('Number of agents:', num_agents)\n\n# size of each action\naction_size = brain.vector_action_space_size\nprint('Size of each action:', action_size)\n\n# examine the state space \nstates = env_info.vector_observations\nstate_size = states.shape[1]\nprint('There are {} agents. Each observes a state with length: {}'.format(states.shape[0], state_size))\nprint('The state for the first agent looks like:', states[0])", "Number of agents: 20\nSize of each action: 4\nThere are 20 agents. Each observes a state with length: 33\nThe state for the first agent looks like: [ 0.00000000e+00 -4.00000000e+00 0.00000000e+00 1.00000000e+00\n -0.00000000e+00 -0.00000000e+00 -4.37113883e-08 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 -1.00000000e+01 0.00000000e+00\n 1.00000000e+00 -0.00000000e+00 -0.00000000e+00 -4.37113883e-08\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 5.75471878e+00 -1.00000000e+00\n 5.55726624e+00 0.00000000e+00 1.00000000e+00 0.00000000e+00\n -1.68164849e-01]\n" ] ], [ [ "# 3. Take Random Actions in the Environment\n\nIn the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment.\n\nNote that **in this coding environment, you will not be able to watch the agents while they are training**, and you should set `train_mode=True` to restart the environment.", "_____no_output_____" ] ], [ [ "for i in range(10):\n env_info = env.reset(train_mode=True)[brain_name] # reset the environment \n states = env_info.vector_observations # get the current state (for each agent)\n scores = np.zeros(num_agents) # initialize the score (for each agent)\n while True:\n actions = np.random.randn(num_agents, action_size) # select an action (for each agent)\n actions = np.clip(actions, -1, 1) # all actions between -1 and 1\n env_info = env.step(actions)[brain_name] # send all actions to tne environment\n next_states = env_info.vector_observations # get next state (for each agent)\n rewards = env_info.rewards # get reward (for each agent)\n dones = env_info.local_done # see if episode finished\n scores += env_info.rewards # update the score (for each agent)\n states = next_states # roll over states to next time step\n if np.any(dones): # exit loop if episode finished\n break\n print('Total score (averaged over agents) this episode: {}'.format(np.mean(scores)))", "_____no_output_____" ] ], [ [ "# 4. Implementation\n\nNow i will implement the D4PG Algorithm", "_____no_output_____" ] ], [ [ "agent = Agent(state_size=state_size, action_size=action_size,num_agents=num_agents, seed=7)", "_____no_output_____" ], [ "# Training the agent over a number of episodes until we reach the desired average reward, which is > 30\n\ndef d4pg(n_episodes=2000):\n \n scores = []\n scores_deque = deque(maxlen=100)\n rolling_average_score = []\n \n for i_episode in range(1, n_episodes+1):\n env_info = env.reset(train_mode=True)[brain_name] # reset the environment \n state = env_info.vector_observations # get the current state (for each agent)\n agent.reset()\n score = np.zeros(num_agents)\n \n for timestep in range(1000):\n action = agent.act(state)\n \n env_info = env.step(action)[brain_name] # send all actions to the environment\n next_state = env_info.vector_observations # get next state (for each agent)\n reward = env_info.rewards # get reward (for each agent)\n done = env_info.local_done # to see if episode finished\n \n score += reward\n agent.step(state, action, reward, next_state, done)\n state = next_state\n if np.any(done): # see if any episode finished\n break \n \n score = np.mean(score)\n scores_deque.append(score)\n scores.append(score)\n rolling_average_score.append(np.mean(scores_deque))\n \n \n print('\\rEpisode {}\\tAverage Score: {:.2f}\\tScore: {:.2f}'.format(i_episode, np.mean(scores_deque), score), end=\"\")\n \n if i_episode % 10 == 0: \n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n \n \n if 30 < current_score and 99 < len(scores_deque):\n print('Target average reward achieved!')\n torch.save(agent.actor_local.state_dict(), 'checkpoint_actor_local.pth') # save local actor\n torch.save(agent.critic_local.state_dict(), 'checkpoint_critic_local.pth') # save local critic\n break\n return scores, rolling_average_score", "_____no_output_____" ], [ "scores, rolling_average_score = ddpg()", "Episode 10\tAverage Score: 0.43\tScore: 0.50\nEpisode 20\tAverage Score: 0.57\tScore: 1.02\nEpisode 30\tAverage Score: 0.61\tScore: 0.58\nEpisode 40\tAverage Score: 0.83\tScore: 2.19\nEpisode 50\tAverage Score: 1.27\tScore: 4.12\nEpisode 60\tAverage Score: 1.86\tScore: 6.01\nEpisode 70\tAverage Score: 2.30\tScore: 3.91\nEpisode 80\tAverage Score: 2.61\tScore: 5.30\nEpisode 90\tAverage Score: 3.08\tScore: 7.62\nEpisode 100\tAverage Score: 3.65\tScore: 8.68\nEpisode 110\tAverage Score: 4.61\tScore: 9.194\nEpisode 120\tAverage Score: 5.22\tScore: 8.40\nEpisode 130\tAverage Score: 6.35\tScore: 14.87\nEpisode 140\tAverage Score: 7.72\tScore: 16.97\nEpisode 150\tAverage Score: 9.28\tScore: 20.73\nEpisode 160\tAverage Score: 11.44\tScore: 30.03\nEpisode 170\tAverage Score: 13.98\tScore: 29.39\nEpisode 180\tAverage Score: 16.18\tScore: 26.39\nEpisode 190\tAverage Score: 18.13\tScore: 28.11\nEpisode 200\tAverage Score: 20.15\tScore: 32.36\nEpisode 210\tAverage Score: 21.94\tScore: 23.75\nEpisode 220\tAverage Score: 24.26\tScore: 26.56\nEpisode 230\tAverage Score: 25.82\tScore: 26.39\nEpisode 240\tAverage Score: 27.24\tScore: 30.41\nEpisode 250\tAverage Score: 28.48\tScore: 31.83\nEpisode 260\tAverage Score: 28.90\tScore: 29.76\nEpisode 270\tAverage Score: 28.94\tScore: 31.92\nEpisode 280\tAverage Score: 29.45\tScore: 33.50\nEpisode 290\tAverage Score: 29.90\tScore: 30.02\nEpisode 294\tAverage Score: 30.03\tScore: 31.29Target average reward achieved!\n" ], [ "fig = plt.figure()\nax = fig.add_subplot(111)\nplt.plot(np.arange(1, len(scores)+1), scores)\nplt.plot(np.arange(1, len(rolling_average_score)+1), rolling_average_score)\nplt.ylabel('Score')\nplt.xlabel('Episode #')\nplt.show()", "_____no_output_____" ], [ "# Here you can test the performance of the agents \n\n# load the actor critic models\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nagent.actor_local.load_state_dict(torch.load(\"checkpoints/checkpoint_actor_local.pth\", map_location=device))\nagent.critic_local.load_state_dict(torch.load(\"checkpoints/checkpoint_critic_local.pth\", map_location=device))\n\nfor i in range(10):\n env_info = env.reset(train_mode=True)[brain_name] # reset the environment \n states = env_info.vector_observations # get the current state (for each agent)\n scores = np.zeros(num_agents) # initialize the score (for each agent)\n while True:\n actions = agent.act(states)\n env_info = env.step(actions)[brain_name] # send all actions to tne environment\n next_states = env_info.vector_observations # get next state (for each agent)\n rewards = env_info.rewards # get reward (for each agent)\n dones = env_info.local_done # see if episode finished\n scores += env_info.rewards # update the score (for each agent)\n states = next_states # roll over states to next time step\n if np.any(dones): # exit loop if episode finished\n break\n print('Total score (averaged over agents) this episode: {}'.format(np.mean(scores)))", "_____no_output_____" ], [ "# close the enviroment\nenv.close()", "_____no_output_____" ] ], [ [ "### As you can see, the average reward is reached after 294 episodes and there are several approaches to improve the results and train the agents much faster:\n\n1- Prioritized experience replay\n\n2- Modification of the hyperparameters which play a crucial role\n\n3- Use of another algorithm such as A3C.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
d07412f54cfd3119b181a004c4fd59b583d1ac7d
21,815
ipynb
Jupyter Notebook
dati_2013/04/Linear.ipynb
shishitao/boffi_dynamics
365f16d047fb2dbfc21a2874790f8bef563e0947
[ "MIT" ]
null
null
null
dati_2013/04/Linear.ipynb
shishitao/boffi_dynamics
365f16d047fb2dbfc21a2874790f8bef563e0947
[ "MIT" ]
null
null
null
dati_2013/04/Linear.ipynb
shishitao/boffi_dynamics
365f16d047fb2dbfc21a2874790f8bef563e0947
[ "MIT" ]
2
2019-06-23T12:32:39.000Z
2021-08-15T18:33:55.000Z
283.311688
20,088
0.906807
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d0741929bc3685248fec5c91b1415dccd27876cf
16,549
ipynb
Jupyter Notebook
doc/notebooks/transport_correlation_conversion.ipynb
romarro/CoolProp-1
c06d2df794d75766b769f5271b98ca3fc36b7f93
[ "MIT" ]
520
2015-01-14T16:49:41.000Z
2022-03-29T07:48:50.000Z
doc/notebooks/transport_correlation_conversion.ipynb
romarro/CoolProp-1
c06d2df794d75766b769f5271b98ca3fc36b7f93
[ "MIT" ]
1,647
2015-01-01T07:42:45.000Z
2022-03-31T23:48:56.000Z
doc/notebooks/transport_correlation_conversion.ipynb
romarro/CoolProp-1
c06d2df794d75766b769f5271b98ca3fc36b7f93
[ "MIT" ]
320
2015-01-02T17:24:27.000Z
2022-03-19T07:01:00.000Z
25.265649
230
0.464076
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d074209f531bebce811559463489771ddd4238e0
828,850
ipynb
Jupyter Notebook
archive/newer_notebooks_wip_drafts/drafts/new_egg_webscraper_app_NOTFINAL_review_too_much.ipynb
jhustles/new_egg_webscraper
551f20418a5dd393099269e12b91d3f74c58f1da
[ "MIT" ]
3
2020-04-30T07:01:41.000Z
2020-11-09T02:12:34.000Z
archive/newer_notebooks_wip_drafts/drafts/new_egg_webscraper_app_NOTFINAL_review_too_much.ipynb
jhustles/new_egg_webscraper
551f20418a5dd393099269e12b91d3f74c58f1da
[ "MIT" ]
null
null
null
archive/newer_notebooks_wip_drafts/drafts/new_egg_webscraper_app_NOTFINAL_review_too_much.ipynb
jhustles/new_egg_webscraper
551f20418a5dd393099269e12b91d3f74c58f1da
[ "MIT" ]
null
null
null
61.826794
12,262
0.570721
[ [ [ "# NewEgg.Com WebScraping Program For Laptops - Beta v1.0\n\n### - April 2020\n\n---", "_____no_output_____" ] ], [ [ "# Import dependencies.\n\nimport os\nimport re\nimport time\nimport glob\nimport random\nimport datetime\nimport requests\nimport pandas as pd\n\nfrom re import search\nfrom splinter import Browser\nfrom playsound import playsound\nfrom bs4 import BeautifulSoup as soup", "_____no_output_____" ] ], [ [ "## Functions & Classes Setup\n---", "_____no_output_____" ] ], [ [ "# Build a function to return date throughout the program.\n\ndef return_dt():\n \n global current_date\n \n current_date = str(datetime.datetime.now()).replace(':','.').replace(' ','_')[:-7]\n \n return current_date", "_____no_output_____" ], [ "\"\"\"\nNewEgg WebScraper function that scrapes data, saves it into a csv file, and creates Laptop objects.\n\n\"\"\"\n\ndef newegg_page_scraper(containers, turn_page):\n \n page_nums = []\n \n general_category = []\n \n product_categories = []\n \n images = []\n \n product_brands = []\n \n product_models = []\n \n product_links = []\n \n item_numbers = []\n \n promotions = []\n \n prices = []\n \n shipping_terms = []\n \n # Put this to avoid error that was being generated\n global gen_category\n \n \"\"\" \n Loop through all the containers on the HTML, and scrap the following content into the following lists\n \n \"\"\"\n for con in containers:\n \n try:\n page_counter = turn_page\n page_nums.append(int(turn_page))\n \n gen_category = target_page_soup.find_all('div', class_=\"nav-x-body-top-bar fix\")[0].text.split('\\n')[5]\n general_category.append(gen_category)\n \n prod_category = target_page_soup.find_all('h1', class_=\"page-title-text\")[0].text\n product_categories.append(prod_category)\n \n image = con.a.img[\"src\"]\n images.append(image)\n\n prd_title = con.find_all('a', class_=\"item-title\")[0].text\n product_models.append(prd_title)\n\n product_link = con.find_all('a', class_=\"item-title\")[0]['href']\n product_links.append(product_link)\n \n shipping = con.find_all('li', class_='price-ship')[0].text.strip().split()[0]\n \n if shipping != \"Free\":\n shipping = shipping.replace('$', '')\n shipping_terms.append(shipping)\n \n else:\n shipping = 0.00\n shipping_terms.append(shipping)\n\n brand_name = con.find_all('a', class_=\"item-brand\")[0].img[\"title\"]\n product_brands.append(brand_name)\n\n\n except (IndexError, ValueError) as e:\n \n # If there are no item_brand container, take the Brand from product details.\n product_brands.append(con.find_all('a', class_=\"item-title\")[0].text.split()[0])\n\n try:\n current_promo = con.find_all(\"p\", class_=\"item-promo\")[0].text\n promotions.append(current_promo)\n \n except:\n promotions.append('null')\n\n try:\n price = con.find_all('li', class_=\"price-current\")[0].text.split()[0].replace('$','').replace(',', '')\n prices.append(price)\n \n except:\n price = 'null / out of stock'\n prices.append(price)\n\n \n try:\n item_num = con.find_all('a', class_=\"item-title\")[0]['href'].split('p/')[1].split('?')[0]\n item_numbers.append(item_num)\n \n except (IndexError) as e:\n item_num = con.find_all('a', class_=\"item-title\")[0]['href'].split('p/')[1]\n item_numbers.append(item_num) \n \n # Convert all of the lists into a dataframe\n \n df = pd.DataFrame({\n 'item_number': item_numbers,\n 'general_category': general_category,\n 'product_category': product_categories,\n 'brand': product_brands,\n 'model_specifications': product_models,\n 'price': prices,\n 'current_promotions': promotions,\n 'shipping': shipping_terms,\n 'page_number': page_nums,\n 'product_links': product_links,\n 'image_link': images\n })\n \n # Rearrange the dataframe columns into the following order.\n df = df[['item_number', 'general_category','product_category', 'page_number' ,'brand','model_specifications' ,'current_promotions' ,'price' ,'shipping' ,'product_links','image_link']]\n \n # Convert the dataframe into a dictionary.\n global scraped_dict\n scraped_dict = df.to_dict('records')\n \n # Grab the subcategory \"Laptop/Notebooks\" and eliminate any special characters that may cause errors.\n global pdt_category\n pdt_category = df['product_category'].unique()[0]\n \n # Eliminate special characters in a string if it exists.\n pdt_category = ''.join(e for e in pdt_category if e.isalnum())\n \n \"\"\" Count the number of items scraped by getting the length of a all the models for sale.\n This parameter is always available for each item-container in the HTML\n \"\"\"\n\n global items_scraped\n items_scraped = len(df['model_specifications'])\n\n \"\"\"\n Save the results into a csv file using Pandas\n \"\"\"\n \n df.to_csv(f'./processing/{current_date}_{pdt_category}_{items_scraped}_scraped_page{turn_page}.csv')\n \n # Return these variables as they will be used.\n return scraped_dict, items_scraped, pdt_category\n \n", "_____no_output_____" ], [ "# Function to return the total results pages.\n\ndef results_pages(target_page_soup):\n \n # Use BeautifulSoup to extract the total results page number\n results_pages = target_page_soup.find_all('span', class_=\"list-tool-pagination-text\")[0].text.strip()\n \n # Find and extract total pages + and add 1 to ensure proper length of total pages.\n global total_results_pages\n \n total_results_pages = int(re.split(\"/\", results_pages)[1])\n \n return total_results_pages", "_____no_output_____" ], [ "\"\"\"\nBuild a function to concatenate all pages that were scraped and saved in the processing folder.\nSave the final output (1 csv file) all the results\n \n\"\"\"\n\ndef concatenate(total_results_pages):\n \n path = f'./processing\\\\'\n \n scraped_pages = glob.glob(path + \"/*.csv\")\n \n concatenate_pages = []\n \n counter = 0\n \n for page in scraped_pages:\n \n df = pd.read_csv(page, index_col=0, header=0)\n \n concatenate_pages.append(df)\n\n compiled_data = pd.concat(concatenate_pages, axis=0, ignore_index=True)\n \n total_items_scraped = len(compiled_data['brand'])\n \n concatenated_output = compiled_data.to_csv(f\"./finished_outputs/{current_date}_{total_items_scraped}_scraped_{total_results_pages}_pages_.csv\")\n \n return", "_____no_output_____" ], [ "\"\"\"\nBuilt a function to clear out the entire processing files folder to avoid clutter.\nOr the user can keep the processing files (page by page) for their own analysis.\n\n\"\"\"\ndef clean_processing_fldr():\n \n path = f'./processing\\\\'\n \n scraped_pages = glob.glob(path + \"/*.csv\")\n \n if len(scraped_pages) < 1:\n \n print(\"There are no files in the folder to clear. \\n\")\n \n else:\n \n print(f\"Clearing out a total of {len(scraped_pages)} scraped pages in the processing folder... \\n\")\n \n clear_processing_files = []\n \n for page in scraped_pages:\n \n os.remove(page)\n \n print('Clearing of \"Processing\" folder complete. \\n')\n \n return", "_____no_output_____" ], [ "def random_a_tag_mouse_over3():\n \n x = random.randint(6, 10)\n \n def rdm_slp_5_9(x):\n\n time.sleep(x)\n\n print(f\"Mimic Humans - Sleeping for {x} seconds. \")\n\n return x \n\n working_try_atags = []\n\n finally_atags = []\n\n working_atags = []\n\n not_working_atags = []\n\n try_counter = 0\n\n finally_counter = 0\n \n time.sleep(1)\n \n # Mouse over to header of the page \"Laptops\"\n browser.find_by_tag(\"h1\").mouse_over()\n \n number_of_a_tags = len(browser.find_by_tag(\"a\"))\n \n # My observation has taught me that most of the actual laptop clickable links on the grid are in the <a> range 2000 to 2100.\n if number_of_a_tags > 1900:\n \n print(f\"Found {number_of_a_tags} <a> tags when parsing html... \")\n \n random_90_percent_plug = (random.randint(90, 94)/100.00)\n \n start_a_tag = int(round((number_of_a_tags * random_90_percent_plug)))\n \n end_a_tag = int(round((number_of_a_tags * .96)))\n \n else:\n # After proving you're human, clickable <a>'s reduced 300, so adjusting mouse_over for that scenario\n\n print(f\"Found {number_of_a_tags} <a> tags when parsing html... \")\n \n random_40_percent_plug = (random.randint(40, 44)/100.00)\n \n start_a_tag = int(round((number_of_a_tags * random_40_percent_plug)))\n \n end_a_tag = int(round((number_of_a_tags * .46)))\n\n step = random.randint(13, 23)\n\n for i in range(start_a_tag, end_a_tag, step):\n\n try: # try this as normal part of the program - SHORT\n\n rdm_slp_5_9(x)\n\n browser.find_by_tag(\"a\")[i+2].mouse_over()\n\n time.sleep(3)\n\n except: # Execute this when there is an exception\n\n print(\"EXCEPTION raised during mouse over. Going to break loop and proceed with moving to the next page. \\n\")\n\n break\n\n else: # execute this only if no exceptions are raised\n\n working_try_atags.append(i+2)\n\n working_atags.append(i+2)\n\n try_counter += 1\n\n print(f\"<a> number = {i+2} | Current Attempts (Try Count): {try_counter} \\n\")\n\n return", "_____no_output_____" ], [ "def g_recaptcha_check():\n \n if browser.is_element_present_by_id('g-recaptcha') == True:\n \n for sound in range(0, 2):\n \n playsound('./sounds/user_alert.wav')\n \n print(\"recaptcha - Check Alert! \\n\")\n \n continue_scrape = input(\"Newegg system suspects you are a bot. \\n Complete the recaptcha test to prove you're not a bot. After, enter in any key and press ENTER to continue the scrape. \\n\")\n \n print(\"Continuing with scrape... \\n\")\n \n return\n", "_____no_output_____" ], [ "def are_you_human_backend(target_page_soup):\n \n if target_page_soup.find_all(\"title\")[0].text == 'Are you a human?':\n \n playsound('./sounds/user_alert.wav')\n\n continue_scrape = input(\"Newegg notices you're a robot on the backend when requesting. REFRESH THE PAGE and you may have to perform a test to prove you're human. After you refresh, enter in any key, and press ENTER to continue the webscrape. \\n\")\n\n print(\"Now will automatically will refresh the page 2 times, and target new URL. \\n\")\n \n print(\"Refreshing three times in 12 seconds. Please wait... \\n\")\n \n for i in range(0, 2):\n \n browser.reload()\n \n time.sleep(2)\n \n browser.back()\n \n time.sleep(4)\n \n browser.forward()\n \n time.sleep(3)\n \n print(\"Targeting new url... \")\n \n # After user passes test, target the new url, and return updated target_page_soup\n target_url = browser.url\n\n response_target = requests.get(target_url)\n\n target_page_soup = soup(response_target.text, 'html.parser')\n \n print(\"#\"* 60)\n print(target_page_soup)\n print(\"#\"* 60)\n \n #target_page_soup\n \n break_pedal = input(\"Does the soup say 'are you human?' in the text?' Enter 'y' or 'n'. \")\n \n if break_pedal == 'y':\n \n # recursion\n are_you_human_backend(target_page_soup)\n \n else:\n \n #print(\"#\"* 60)\n \n target_url = browser.url\n\n response_target = requests.get(target_url)\n\n target_page_soup = soup(response_target.text, 'html.parser')\n \n return target_page_soup\n \n else:\n \n print(\"Passed the 'Are you human?' check when requesting and parsing the html. Continuing with scrape ... \\n\")\n \n # Otherwise, return the target_page_soup that was passed in.\n return target_page_soup", "_____no_output_____" ], [ "def random_xpath_top_bottom():\n \n x = random.randint(3, 8)\n \n def rdm_slp_5_9(x):\n\n time.sleep(x)\n\n print(f\"Slept for {x} seconds. \\n\")\n\n return x\n\n # Check if there are working links on the screen, otherwise alert the user.\n \n if (browser.is_element_present_by_tag('h1')) == True:\n \n print(\"(Check 1 - Random Xpath Top Bottom) Header is present and hoverable on page. \\n\")\n \n else:\n \n print(\"(Check 1 - ERROR - Random Xpath Top Bottom) Header is NOT present on page. \\n\")\n \n for s in range(0, 1):\n \n playsound('./sounds/user_alert.wav')\n \n red_light = input(\"Program could not detect a clickable links to hover over, and click. Please use your mouse to refresh the page, and enter 'y' to continue the scrape. \\n\")\n \n if (browser.is_element_present_by_tag(\"a\")) == True:\n \n print(\"(Check 2- Random Xpath Top Bottom) <a> tags are present on page. Will begin mouse-over thru the page, and click a link. \\n\")\n \n else:\n # If there isn't, pause the program. Have user click somewhere on the screen.\n \n for s in range(0, 1):\n \n playsound('./sounds/user_alert.wav')\n \n red_light = input(\"Program could not detect a clickable links to hover over, and click. Please use your mouse to refresh the page, and enter 'y' to continue the scrape. \\n\")\n \n # There are clickable links, then 'flip the coin' to choose top or bottom button\n coin_toss_top_bottom = random.randint(0,1)\n \n next_page_button_results = []\n \n # If the coin toss is even, mouse_over and click the top page link.\n if (coin_toss_top_bottom == 0):\n \n print('Heads - Clicking \"Next Page\" Top Button. \\n')\n \n x = random.randint(3, 8)\n \n print(f\"Mimic human behavior by randomly sleeping for {x}. \\n\")\n \n rdm_slp_5_9(x)\n \n browser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[1]/div[2]/div/div[2]/button').mouse_over()\n \n time.sleep(1)\n \n browser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[1]/div[2]/div/div[2]/button').click()\n \n next_page_button_results.append(coin_toss_top_bottom)\n \n print('Heads - SUCCESSFUL \"Next Page\" Top Button. \\n')\n \n return\n \n else:\n \n next_page_button_results.append(coin_toss_top_bottom)\n \n# try: # after you add item to cart and go back back - this is the bottom next page link\n# /html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[3]/div[8]/div/div/div[11]/button\n# /html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[3]/div[6]/div/div/div[11]/button\n# /html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[3]/div[6]/div/div/div[11]/button\n# /html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[3]/div[6]/div/div/div[11]/button\n# /html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[3]/div[6]/div/div/div[11]/button\n try:\n print('Tails - Clicking \"Next Page\" Xpath Bottom Button. \\n')\n \n x = random.randint(3, 8)\n \n print(f\"Mimic human behavior by randomly sleeping for {x}. \\n\")\n \n rdm_slp_5_9(x)\n \n browser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button').mouse_over()\n time.sleep(4)\n browser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button').click()\n \n print('Tails - 1st Bottom Xpath - SUCCESSFUL \"Next Page\" Bottom Button. \\n')\n \n except:\n print(\"EXCEPTION - 1st Bottom Xpath Failed. Sleep for 1 second then will try with 2nd Xpath bottom link. \\n\")\n \n try:\n time.sleep(4)\n browser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[3]/div/div/div[11]/button').mouse_over()\n time.sleep(4)\n browser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[3]/div/div/div[11]/button').click()\n \n print('(Exception Attempt) Tails - 2nd Bottom Xpath - SUCCESSFUL \"Next Page\" Bottom Button. \\n')\n \n except:\n print(\"EXCEPTION - 2nd Bottom Xpath Failed. Trying with 3rd Xpath bottom link. \\n\")\n \n try:\n time.sleep(4)\n browser.find_by_xpath('/html/body/div[5]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button').mouse_over()\n time.sleep(4)\n browser.find_by_xpath('/html/body/div[5]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button').click()\n \n print('(Exception Attempt) Tails - 3rd Bottom Xpath - SUCCESSFUL \"Next Page\" Bottom Button. \\n')\n \n except:\n print(\"3rd Bottom Link - Didn't work - INSPECT AND GRAB THE XPATH... \\n\")\n break_pedeal = input(\"Pause. Enter anything to continue... \")\n\n return\n ", "_____no_output_____" ], [ "\"\"\"\nThis class takes in the dictionary from the webscraper function, and will be used in a list comprehension\n\nto produce class \"objects\"\n\n\"\"\"\nclass Laptops:\n \n counter = 0\n \n def __init__(self, **entries):\n \n self.__dict__.update(entries)\n Laptops.counter += 1\n \n def count(self):\n print(f\"Total Laptops scraped: {Laptops.counter}\")\n\n\"\"\"\nOriginally modeled out parent/child inheritance object structure.\n\nAfter careful research, I found it much easier to export the Pandas Dataframe of the results to a dictionary,\n\nand then into a class object, which I will elaborate more down below.\n\n\"\"\"\n# class Product_catalog:\n \n# all_prod_count = 0\n \n# def __init__(self, general_category): # computer systems\n# self.general_category = general_category\n \n# Product_catalog.all_prod_count += 1\n \n# def count_prod(self):\n# return int(self.all_prod_count)\n# #return '{}'.format(self.general_category)\n\n# Sub_category was later changed to Laptops due to the scope of this project.\n# class Sub_category(Product_catalog): # laptops/notebooks, gaming\n \n# sub_category_ct = 0\n \n# def __init__(self, general_category, sub_categ, item_num, brand, price, img_link, prod_link, model_specifications, current_promotions):\n# super().__init__(general_category)\n# Sub_category.sub_category_ct += 1\n \n# self.sub_categ = sub_categ\n# self.item_num = item_num\n# self.brand = brand\n# self.price = price\n# self.img_link = img_link\n# self.prod_link = prod_link\n# self.model_specifications = model_specifications\n# self.current_promotions = current_promotions", "_____no_output_____" ] ], [ [ "## Main Program Logic\n---", "_____no_output_____" ] ], [ [ "\"\"\" Welcome to the program message!\n\"\"\"\nprint(\"=== NewEgg.Com Laptop WebScraper Beta v1.0 ===\")\n\nprint(\"==\"*30)\n\nprint('Scope: This project is a beta and is only built to scrape the laptop section of NewEgg.com due to limited time. \\n')\n\nprint(\"Instructions: \\n\")\n\nreturn_dt()\n\nprint(f'Current Date And Time: {current_date} \\n')\n\nprint(\"(1) Go to www.newegg.com, go to the laptop section, select your requirements (e.g. brand, screensize, and specifications - SSD size, processor brand and etc...) \")\n\nprint(\"(2) Copy and paste the url from your exact search when prompted \")\n\nprint('(3) After the webscraping is successful, you will have an option to concatenate all of the pages you scraped together into one csv file')\n\nprint('(4) Lastly, you will have an option to clear out the processing folder (data scraped by each page)')\n\nprint('(5) If you have any issues or errors, \"PRESS CTRL + C\" to quit the program in the terminal ')\n\nprint('(6) You may run the program in the background as the program will make an alert noise to flag when Newegg suspects there is a bot, and will pause the scrape until you finish proving you are human. ')\n\nprint('(7) Disclaimer: Newegg may ban you for a 24 - 48 hours for webscraping their data, then you may resume. \\n Also, please consider executing during the day, with tons of web traffic to their site in your respective area. \\n')\n\nprint('Happy Scraping!')\n\n# Set up Splinter requirements.\nexecutable_path = {'executable_path': './chromedriver.exe'}\n\n# Add an item to the cart first, then go to the user URL and scrape.\n\n# Ask user to input in the laptop query link they would like to scrape.\nurl = input(\"Please copy and paste your laptop query that you want to webscrape, and press enter: \\n\")\n\nbrowser = Browser('chrome', **executable_path, headless=False, incognito=True)\n\n########################\n# Throw a headfake first.\n\nlaptops_home_url = 'https://www.newegg.com/'\n\nbrowser.visit(laptops_home_url)\n\n# Load Time.\ntime.sleep(4)\n#current_url = browser.url\n\nbrowser.find_by_xpath('/html/body/header/div[1]/div[3]/div[1]/form/div/div[1]/input').mouse_over()\ntime.sleep(1)\nbrowser.find_by_xpath('/html/body/header/div[1]/div[3]/div[1]/form/div/div[1]/input').click()\ntime.sleep(1)\n\n# Type in laptops\nintial_search = browser.find_by_xpath('/html/body/header/div[1]/div[3]/div[1]/form/div/div[1]/input').type('Lenovo Laptops intel', slowly=True)\nfor k in intial_search:\n time.sleep(0.5)\n pass\n\ntime.sleep(3)\n# Click the search button\nbrowser.find_by_xpath('/html/body/header/div[1]/div[3]/div[1]/form/div/div[3]/button').click()\n\nprint(\"Sleeping for 5 seconds. \\n\")\ntime.sleep(5)\n\n# try to click on the first workable link \nfor i in range(2,4):\n\n try:\n browser.find_by_xpath(f'/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[3]/div[{i}]/div[1]/div[1]/a').mouse_over()\n time.sleep(1)\n browser.find_by_xpath(f'/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[3]/div[{i}]/div[1]/div[1]/a').click()\n \n except:\n print(f\"i {i} - Exception occurred. Trying next link. \")\n\ntime.sleep(5)\n \nbrowser.back()\n\ntime.sleep(4)\n\ng_recaptcha_check()\n\n#####################\nprint(\"Sleeping for 5 seconds. \\n\")\n\ntime.sleep(3)\n\n# Go to the user intended url\nbrowser.visit(url)\n\ntime.sleep(3)\n\ng_recaptcha_check()\n\ncurrent_url = browser.url\n\n# Allocating loading time.\ntime.sleep(4)\n\n#current_url = browser.url\n \nresponse = requests.get(current_url)\n\nprint(f\"{response} \\n\")\n\ntarget_page_soup = soup(response.text, 'html.parser')\n\nare_you_human_backend(target_page_soup)\n\n# Run the results_pages function to gather the total pages to be scraped.\nresults_pages(target_page_soup)\n\n\"\"\"\nThis is the loop that performs the page by page scraping of data / results\nof the user's query.\n\"\"\"\n# List set up for where class Laptop objects will be stored.\n\nprint(\"Beginning webscraping and activity log below... \")\nprint(\"=\"*60)\n\nproduct_catalog = []\n\n# \"Stop\" in range below is \"total_results_pages+1\" because we started at 1.\nfor turn_page in range(1, total_results_pages+1):\n \n \"\"\"\n If \"reCAPTCHA\" pops up, pause the program using an input. This allows the user to continue\n to scrape after they're done completing the quiz by inputting any value.\n \"\"\"\n # Allocating loading time.\n time.sleep(4)\n \n g_recaptcha_check()\n\n print(f\"Beginning mouse over activity... \\n\")\n \n # Set up \"containers\" to be passed into main scraping function. \n \n if turn_page == 1:\n \n containers = target_page_soup.find_all(\"div\", class_=\"item-container\")\n \n else:\n \n target_url = browser.url\n\n # Use Request.get() - throw the boomerang at the target, retrieve the info, & return back to requestor\n response_target = requests.get(target_url)\n \n \n # Use BeautifulSoup to read grab all the HTML using the lxml parser\n target_page_soup = soup(response_target.text, 'html.parser')\n \n \n # Pass in target_page_soup to scan on the background (usually 10 pages in) if the html has text \"Are you human?\"\n # If yes, the browser will refresh twice, and return a new target_page_soup that should have the scrapable items we want\n are_you_human_backend(target_page_soup)\n\n \n containers = target_page_soup.find_all(\"div\", class_=\"item-container\")\n \n print(f\"Scraping Current Page: {turn_page} \\n\")\n \n # Execute webscraper function. Output is a csv file in the processing folder and dictionary.\n \n newegg_page_scraper(containers, turn_page)\n \n print(\"Creating laptop objects for this page... \\n\")\n \n \n # Create instances of class objects of the laptops/notebooks using a list comprehension.\n objects = [Laptops(**prod_obj) for prod_obj in scraped_dict]\n \n \n print(f\"Finished creating Laptop objects for page {turn_page} ... \\n\")\n \n # Append all of the objects to the main product_catalog list (List of List of Objects).\n \n print(f\"Adding {len(objects)} to laptop catalog... \\n\")\n \n product_catalog.append(objects)\n \n random_a_tag_mouse_over3()\n \n if turn_page == total_results_pages:\n \n print(f\"Completed scraping {turn_page} / {total_results_pages} pages. \\n \")\n \n # Exit the broswer once complete webscraping.\n \n browser.quit()\n \n else:\n \n try:\n \n y = random.randint(3, 5)\n \n print(f\"Current Page: {turn_page}) | SLEEPING FOR {y} SECONDS THEN will click next page. \\n\")\n \n time.sleep(y)\n \n random_xpath_top_bottom()\n\n except:\n z = random.randint(3, 5)\n \n print(f\" (EXCEPTION) Current Page: {turn_page}) | SLEEPING FOR {z} SECONDS - Will click next page, if applicable. \\n\")\n \n time.sleep(z)\n \n random_xpath_top_bottom()\n \n time.sleep(1)\n \n print(\"\")\n print(\"=\"*60)\n print(\"\")\n\n\n# Prompt the user if they would like to concatenate all of the pages into one csv file\nconcat_y_n = input(f'All {total_results_pages} pages have been saved in the \"processing\" folder (1 page = csv files). Would you like for us concatenate all the files into one? Enter \"y\", if so. Otherwise, enter anykey to exit the program. \\n')\n\nif concat_y_n == 'y':\n \n concatenate(total_results_pages)\n \n print(f'WebScraping Complete! All {total_results_pages} have been scraped and saved as {current_date}_{pdt_category}_scraped_{total_results_pages}_pages_.csv in the \"finished_outputs\" folder \\n')\n\n\n# Prompt the user to if they would like to clear out processing folder function here - as delete everything to prevent clutter\nclear_processing_y_n = input(f'The \"processing\" folder has {total_results_pages} csv files of each page that was scraped. Would you like to clear the files? Enter \"y\", if so. Otherwise, enter anykey to exit the program. \\n')\n\nif clear_processing_y_n == 'y':\n \n clean_processing_fldr()\n\nprint('Thank you checking out my project, and hope you found this useful! \\n')", "=== NewEgg.Com Laptop WebScraper Beta v1.0 ===\n============================================================\nScope: This project is a beta and is only built to scrape the laptop section of NewEgg.com due to limited time. \n\nInstructions: \n\nCurrent Date And Time: 2020-04-26_16.41.03 \n\n(1) Go to www.newegg.com, go to the laptop section, select your requirements (e.g. brand, screensize, and specifications - SSD size, processor brand and etc...) \n(2) Copy and paste the url from your exact search when prompted \n(3) After the webscraping is successful, you will have an option to concatenate all of the pages you scraped together into one csv file\n(4) Lastly, you will have an option to clear out the processing folder (data scraped by each page)\n(5) If you have any issues or errors, \"PRESS CTRL + C\" to quit the program in the terminal \n(6) You may run the program in the background as the program will make an alert noise to flag when Newegg suspects there is a bot, and will pause the scrape until you finish proving you are human. \n(7) Disclaimer: Newegg may ban you for a 24 - 48 hours for webscraping their data, then you may resume. \n Also, please consider executing during the day, with tons of web traffic to their site in your respective area. \n\nHappy Scraping!\nPlease copy and paste your laptop query that you want to webscrape, and press enter: \nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601346405%20600004341%20600004343%20601183480%20601307583%20601286800%204814%20601296065%20601296059%20601296066%20601286795%20600440394&LeftPriceRange=1000%201500\nSleeping for 5 seconds. \n\ni 2 - Exception occurred. Trying next link. \ni 3 - Exception occurred. Trying next link. \nSleeping for 5 seconds. \n\n<Response [200]> \n\nPassed the 'Are you human?' check when requesting and parsing the html. Continuing with scrape ... \n\nBeginning webscraping and activity log below... \n============================================================\nBeginning mouse over activity... \n\nScraping Current Page: 1 \n\nCreating laptop objects for this page... \n\nFinished creating Laptop objects for page 1 ... \n\nAdding 36 to laptop catalog... \n\nFound 2192 <a> tags when parsing html... \nMimic Humans - Sleeping for 6 seconds. \nEXCEPTION raised during mouse over. Going to break loop and proceed with moving to the next page. \n\nCurrent Page: 1) | SLEEPING FOR 4 SECONDS THEN will click next page. \n\n(Check 1 - Random Xpath Top Bottom) Header is present and hoverable on page. \n\n(Check 2- Random Xpath Top Bottom) <a> tags are present on page. Will begin mouse-over thru the page, and click a link. \n\nHeads - Clicking \"Next Page\" Top Button. \n\nMimic human behavior by randomly sleeping for 4. \n\nSlept for 4 seconds. \n\nHeads - SUCCESSFUL \"Next Page\" Top Button. \n\n\n============================================================\n\nrecaptcha - Check Alert! \n\nNewegg system suspects you are a bot. \n Complete the recaptcha test to prove you're not a bot. After, enter in any key and press ENTER to continue the scrape. \ny\nContinuing with scrape... \n\nBeginning mouse over activity... \n\nPassed the 'Are you human?' check when requesting and parsing the html. Continuing with scrape ... \n\nScraping Current Page: 2 \n\nCreating laptop objects for this page... \n\nFinished creating Laptop objects for page 2 ... \n\nAdding 36 to laptop catalog... \n\nFound 2171 <a> tags when parsing html... \nMimic Humans - Sleeping for 6 seconds. \n<a> number = 2021 | Current Attempts (Try Count): 1 \n\nMimic Humans - Sleeping for 6 seconds. \n<a> number = 2044 | Current Attempts (Try Count): 2 \n\nMimic Humans - Sleeping for 6 seconds. \n<a> number = 2067 | Current Attempts (Try Count): 3 \n\nCurrent Page: 2) | SLEEPING FOR 3 SECONDS THEN will click next page. \n\n(Check 1 - Random Xpath Top Bottom) Header is present and hoverable on page. \n\n(Check 2- Random Xpath Top Bottom) <a> tags are present on page. Will begin mouse-over thru the page, and click a link. \n\nHeads - Clicking \"Next Page\" Top Button. \n\nMimic human behavior by randomly sleeping for 4. \n\nSlept for 4 seconds. \n\nHeads - SUCCESSFUL \"Next Page\" Top Button. \n\n\n============================================================\n\nBeginning mouse over activity... \n\nNewegg notices you're a robot on the backend when requesting. REFRESH THE PAGE and you may have to perform a test to prove you're human. After you refresh, enter in any key, and press ENTER to continue the webscrape. \ny\nNow will automatically will refresh the page 2 times, and target new URL. \n\nRefreshing three times in 12 seconds. Please wait... \n\nTargeting new url... \n############################################################\n\n<!DOCTYPE html>\n\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>Are you a human?</title>\n<meta content=\"IE=EDGE\" http-equiv=\"X-UA-Compatible\"/><meta charset=\"utf-8\"/>\n<link href=\"//c1.neweggimages.com/WebResource/Themes/2005/Nest/Newegg.ico\" rel=\"shortcut icon\" type=\"image/x-icon\"/>\n<link href=\"https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,700,700italic|Open+Sans+Condensed:300,300italic,700\" rel=\"stylesheet\" type=\"text/css\"/>\n<style type=\"text/css\">\np{font-size:16px;color:#4d4d4d;padding:0;margin:0 0 5px}a img,a:hover img,a:visited img{border:0}.button-primary,.button-primary:focus,.button-primary:link,.button-primary:visited{font-family:'Open Sans Condensed','Arial Narrow','Helvetica Narrow',arial,helvetica,sans-serif;letter-spacing:1px;font-size:14px;font-weight:700;font-stretch:condensed;text-align:center;text-decoration:none;cursor:pointer;border-radius:4px;border:2px solid #E68626;display:inline-block;padding:9px 15px;margin:15px 0 0;outline:0;color:#552F00;background-color:#FFC010;background:linear-gradient(to bottom,#FFC010,#F9A21B);text-transform:uppercase}h1,h2{padding:0}.button-primary:active,.button-primary:hover{color:#552F00;background-color:#F9A21B;background:linear-gradient(to bottom,#F9A21B,#FFC010);border-color:#E68626}h1{margin:0;font-size:100px;line-height:120px;font-weight:700;color:#33425a}h2{color:#cc4e00;font-size:29px;margin:10px 0 20px}\n.lds-ripple{display:inline-block;position:relative;width:64px;height:64px}.lds-ripple div{position:absolute;border:4px solid #cc4e00;opacity:1;border-radius:50%;animation:lds-ripple 1s cubic-bezier(0,.2,.8,1) infinite}.lds-ripple div:nth-child(2){animation-delay:-.5s}@keyframes lds-ripple{0%{top:28px;left:28px;width:0;height:0;opacity:1}100%{top:-1px;left:-1px;width:58px;height:58px;opacity:0}}\n</style>\n<script type=\"text/javascript\">\ntry{!function(e, t, n, r, i, o, a) {e.NAO = i,e[i] = e[i] || function() {\n(e[i].q = e[i].q || []).push(arguments)},e[i].l = 1 * new Date,o = t.createElement(n),a = t.getElementsByTagName(n)[0],o.async = 1,o.src = \"//www.newegg.com/gfplib.js\",a.parentNode.insertBefore(o, a)}(window, document, \"script\", 0, \"_na\")}catch(e){\n}\n</script>\n<script src=\"//c1.neweggimages.com/WebResource/Scripts/USA/TP_jQueryPlugin/jquery-1.10.2.min.js?purge=1\" type=\"text/javascript\"></script>\n<script src=\"https://www.google.com/recaptcha/api.js?render=6LdAn3UUAAAAAKt8pKdAdZf83OwfA2QhtacSvywE\"></script>\n<script type=\"text/javascript\">\nvar win = jQuery(this);\nif (win.width() < 900) {\n window.resizeTo(900, win.height());\n}\nvar why = '0';\nfunction getReferer() {\n var reg = new RegExp(\"(^|&)referer=([^&]*)(&|$)\");\n var r = window.location.search.substr(1).match(reg);\n var referer = window.location.origin;\n if (r) {\n referer = unescape(r[2]);\n }\n if (referer.indexOf('?') > 0) {\n referer += '&';\n } else {\n referer += '?';\n }\n referer += 'recaptcha=pass';\n\n return referer;\n}\nvar postEventData = function (refer) {\n var items = location.hostname.split('.');\n items.shift();\n var topDomain = items.join('.');\n var reg = /^https?\\:\\/\\/\\w+\\.([^\\/\\s]+)/;\n var match = refer.match(reg);\n if(match){\n if(match[1] !== topDomain) {\n refer = location.origin;\n }\n }\n else {\n refer = location.origin+'/'+refer.replace(/^\\//,'');\n }\n jQuery.ajax({\n type: \"POST\",\n url: \"https://pf.newegg.com/r3\",\n data: JSON.stringify({c: document.cookie }),\n dataType: \"json\",\n contentType: \"application/json\",\n timeout:2000,\n success: function () {\n window.location.href = refer;\n }\n }).fail(function () {\n window.location.href = refer;\n });\n};\ngrecaptcha.ready(function() {\n grecaptcha.execute('6LdAn3UUAAAAAKt8pKdAdZf83OwfA2QhtacSvywE', {action: 'recaptcha'})\n .then(function(token) {\n jQuery.post(window.location.href, { t: token,t2:'s1', cookieEnabled: !!navigator.cookieEnabled, why: why }, function (data, status) {\n if (data === 'success') {\n var refer = getReferer();\n postEventData(refer);\n var noprotocl = refer.replace(\"http://\", \"\").replace(\"https://\", \"\");\n var questionMarkLocation = noprotocl.indexOf(\"?\");\n var label = questionMarkLocation > 0 ? noprotocl.slice(0, questionMarkLocation) : noprotocl;\n ga('send', 'event', 'Captcha', 'Click', label);\n \n } else {\n window.location.href = window.location.origin + window.location.pathname + '?' + 'itn=true&' + (location.search || '?').substring(1);\n }\n });\n });\n});\nsetTimeout(function(){\n window.location.href = window.location.origin + window.location.pathname + '?' + 'itn=true&' + (location.search || '?').substring(1);\n}, 8000);\n(function (i, s, o, g, r, a, m) {\n i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {\n (i[r].q = i[r].q || []).push(arguments)\n }, i[r].l = 1 * new Date(); a = s.createElement(o),\n m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)\n})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');\nga('create', 'UA-1147542-13', 'auto');\nga('send', 'pageview');\n</script>\n</head>\n<body style=\"font-family: 'Open Sans', Helvetica, Arial, sans-serif; line-height: 1.36;\">\n<div style=\"max-width: 1000px;min-width: 760px;overflow: hidden;margin:100px auto;\">\n<div style=\"float: left;padding: 50px 10px 40px 10px; width: 250px; box-sizing: border-box;\">\n<a href=\"https://www.newegg.com/\" style=\"border: none;\">\n<img alt=\"\" src=\"//c1.neweggimages.com/WebResource/Themes/2005/Nest/logo_424x210.png\" width=\"216\"/>\n</a>\n</div>\n<div style=\"border-left: 1px solid #ccc; padding: 30px 10px 70px 40px; margin-left: 250px;\">\n<h1>Human?</h1>\n<h2>Are you a human?</h2>\n<p style=\"margin-bottom: 10px;\">We apologize for the confusion, but we can't quite tell if you're a person or a script.</p>\n<p style=\"margin-bottom: 10px;\">Please don't take this personally. Bots and scripts can be very much lifelike these days!</p>\n<p style=\"margin-bottom: 40px;\">To help us better protect your account security, please check the reCAPTCHA box below.</p>\n<div class=\"lds-ripple\"><div></div><div></div></div>\n<p>detecting...</p>\n<script>var cookiesEnable=\"cookie\" in document&&(document.cookie.length>0||(document.cookie=\"test\").indexOf.call(document.cookie,\"test\")>-1);cookiesEnable||document.write('<p id=\"cookie\" style=\"margin-top: 40px;\">We use cookies to provide functionalities and bring better user experience to you. Please allow cookies for Newegg site.</p>');</script>\n<p style=\"margin-top: 40px;\">If you're interested in accessing Newegg API service, please <a href=\"#\" onclick=\"javascript:newegg_inhouse_feedback2 &amp;&amp; newegg_inhouse_feedback2.show();\" style=\"cursor: pointer;text-decoration: underline; color: #000;\" title=\"Request Access to Newegg API\">submit a request</a>.</p>\n<p style=\"margin-top: 40px;\">We would love to hear your opinion. <a href=\"#\" id=\"newegg_footer_feedback\" onclick=\"javascript:newegg_inhouse_feedback &amp;&amp; newegg_inhouse_feedback.show();\" style=\"cursor: pointer;text-decoration: underline; color: #000;\" title=\"feedback\">Let us know your feedback</a>.</p>\n</div>\n<script type=\"text/javascript\">\n var newegg_inhouse_feedback=null,newegg_inhouse_feedback2=null;!function(){var e=document.location.protocol;if(\"http:\"==e||\"https:\"==e){var n=document.createElement(\"script\");n.type=\"text/javascript\",n.async=!0,n.src=\"//promotions.newegg.com/Newegg/Survey/newegg-feedback.min.js\";var g=document.getElementsByTagName(\"head\")[0].childNodes[0];g.parentNode.insertBefore(n,g),n.onload=function(){null==newegg_inhouse_feedback&&(newegg_inhouse_feedback=new neweggFeedback.NeweggSurvey({cardType:\"Id\",key:\"027BC6DB\"})),null==newegg_inhouse_feedback2&&(newegg_inhouse_feedback2=new neweggFeedback.NeweggSurvey({cardType:\"Id\",key:\"D762FCF1\"}))}}}();\n\tvar Web={StateManager:{Cookies:{get:function(e){for(var t=document.cookie.split(\";\"),n=0;n<t.length;n++){var o=t[n].split(\"=\");if(e==decodeURIComponent(o[0].trim()))return unescape(o[1])}return null},Name:{UTMA:\"__utma\",NVTC:\"NVTC\",NID:\"NV_NID\",SPT:\"NV_SPT\"}}}};\n\t</script>\n</div>\n</body>\n</html>\n\n############################################################\n" ], [ "/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[1]/div[2]/div/div[2]/button", "_____no_output_____" ], [ "/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button", "_____no_output_____" ], [ "/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button", "_____no_output_____" ], [ "/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button", "_____no_output_____" ], [ "# 20 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601286795%20601346405%20600004341%20600004343&recaptcha=pass&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "## 22 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601286795%20601346405%20600004341%20600004343%20600440394%20601183480%20601307583&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 35\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601286795%20601346405%20600004341%20600004343%20601183480%20601307583%20601286800%204814&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 25 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601286795%20601346405%20600004341%20600004343%20601183480%20601307583%20601286800%204814%20601296065%20601296059%20601296066&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 15 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601346405%20600004341%20600004343%20601183480%20601307583%20601286800%204814%20601296065%20601296059%20601296066&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 26 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601346405%20600004341%20600004343%20601183480%20601307583%20601286800%204814%20601296065%20601296059%20601296066%20601286795%20600440394&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 28 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601346405%20600004341%20600004343%20601183480%20601307583%20601286800%204814%20601296065%20601296059%20601296066%20601286795%20600440394%20600337010%20601107729%20601331008&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 48 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20600004343%20601183480%20601307583%204814%20601296065%20601296059%20601296066%20601286795%20600440394%20600004344&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 29\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20600004343%20601183480%20601307583%204814%20601296066%20601286795%20600440394%20600004344%20601286800&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 33 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20600004343%20601183480%20601307583%204814%20601296066%20601286795%20600440394%20600004344%20601286800%20600337010&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 26 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601183480%20601307583%204814%20601296066%20601286795%20600440394%20600004344%20601286800%20600337010%20601107729%20601331008&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 11 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601183480%204814%20601296066%20600440394%20600004344%20601286800%20600337010%20601107729%20601331008&LeftPriceRange=1000%201500", "_____no_output_____" ], [ "# 22 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%20601183480%204814%20601296066%20600440394%20600004344%20601286800%20600337010%20601107729%20601331008%204023%204022%204084", "_____no_output_____" ], [ "# 33 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%204814%20601296066%20600004344%204023%204022%204084", "_____no_output_____" ], [ "# 33 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600136700%20600165638%204814%20601296066%204023%204022%2050001186%2050010418%2050010772", "_____no_output_____" ], [ "# 24 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600165638%204814%20601296066%204023%204022%2050001186%2050010418%2050010772", "_____no_output_____" ], [ "# 15 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600165638%204814%20601296066%204022%2050001186%2050010418%2050010772", "_____no_output_____" ], [ "# 17 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600165638%204814%20601296066%204022%2050001186%2050010418%2050010772%2050001315%2050001312", "_____no_output_____" ], [ "# 18 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600165638%204814%20601296066%204022%2050001186%2050010418%2050010772%2050001315%2050001312%2050001146", "_____no_output_____" ], [ "# 19 pages\n\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600165638%204814%20601296066%204022%2050001186%2050010418%2050010772%2050001315%2050001312%2050001146%2050001759%2050001149", "_____no_output_____" ], [ "# 25 pages\nhttps://www.newegg.com/p/pl?N=100006740%20600004804%20600165638%204814%20601296066%204022%2050001186%2050010418%2050010772%2050001315%2050001312%2050001146%2050001759%2050001149%2050001077%20600136700", "_____no_output_____" ], [ "/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button\n/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[1]/div[2]/div/div[2]/button", "_____no_output_____" ], [ "/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[1]/div[2]/div/div[2]/button", "_____no_output_____" ], [ "/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[3]/div/div/div[11]/button\nbrowser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[3]/div/div/div[11]/button').click()", "_____no_output_____" ], [ "browser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[3]/div/div/div[11]/button').click()", "_____no_output_____" ], [ "/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[1]/div[2]/div/div[2]/button", "_____no_output_____" ], [ "browser.find_by_xpath('/html/body/div[4]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[1]/div[2]/div/div[2]/button').click()", "_____no_output_____" ], [ "target_page_soup.find_all(\"div\", class_=\"item-container\")", "_____no_output_____" ], [ "browser.find_by_xpath('/html/body/div[5]/section/div/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div[4]/div/div/div[11]/button').click()", "_____no_output_____" ], [ "# 32 pages\n# https://www.newegg.com/p/pl?N=100006740%20601346405%20601307583%20601107729%20600337010%20601313977%20601274231%20601331008%20600440394%20601183480%20600136700", "_____no_output_____" ], [ "# 29 pages\n\n# https://www.newegg.com/p/pl?N=100006740%20601346405%20601307583%20601107729%20600337010%20601313977%20601274231%20601331008%20600136700", "_____no_output_____" ], [ "# 18 pages\n\n# https://www.newegg.com/p/pl?N=100006740%20601346405%20601307583%20601107729%20601313977%20601274231%20601331008%20600136700", "_____no_output_____" ], [ "# 30 pages\n\n#https://www.newegg.com/p/pl?N=100006740%20601346405%20601307583%20601107729%20601274231%20601331008%20600136700%20601346404%20600337010", "_____no_output_____" ], [ "# 28 pages\n# https://www.newegg.com/p/pl?N=100006740%20601346405%20601307583%20601107729%20601274231%20601331008%20600136700%20600337010", "_____no_output_____" ], [ "# 21 Pages\n\n# https://www.newegg.com/p/pl?N=100006740%20601307583%20601107729%20601274231%20601331008%20600136700%20600337010", "_____no_output_____" ], [ "# 13 pages\n\n# https://www.newegg.com/p/pl?N=100006740%20601307583%20601107729%20601274231%20601331008%20600136700", "_____no_output_____" ], [ "# 23 pages\n\n# https://www.newegg.com/p/pl?N=100006740%20601307583%20601107729%20601274231%20600136700%20601313977%20600337010%20600440394", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d07424090b5f3303d7650566a07f7505bcefd2eb
8,405
ipynb
Jupyter Notebook
src/ml_code/democlassi.ipynb
AlkaSaliss/dataviz-portfolio
58aa10ab4b5fbdeaafd91707d2fc6023882b1abc
[ "MIT" ]
null
null
null
src/ml_code/democlassi.ipynb
AlkaSaliss/dataviz-portfolio
58aa10ab4b5fbdeaafd91707d2fc6023882b1abc
[ "MIT" ]
2
2022-02-13T19:57:22.000Z
2022-02-19T06:20:07.000Z
src/ml_code/democlassi.ipynb
AlkaSaliss/dataviz-portfolio
58aa10ab4b5fbdeaafd91707d2fc6023882b1abc
[ "MIT" ]
null
null
null
27.112903
145
0.505889
[ [ [ "from IPython.display import display, HTML\n\ndisplay(HTML(data=\"\"\"\n<style>\n div#notebook-container { width: 99%; }\n div#menubar-container { width: 99%; }\n div#maintoolbar-container { width: 99%; }\n</style>\n\"\"\"))", "_____no_output_____" ], [ "import os\nimport torch \nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n%matplotlib inline", "_____no_output_____" ], [ "from democlassi import initialize_model, PretrainedMT, preprocess_fer, preprocess_utk", "_____no_output_____" ], [ "# create model objects\nresnet_fer, _ = initialize_model(\"resnet\", False, 7, \"fer2013\", False)\nresnet_rag = PretrainedMT(\"resnet\", False, False)", "_____no_output_____" ], [ "# load models weights\nfer_weight = torch.load(\"./ml_outputs/democlassi/FER_resnet_model_109_val_accuracy_0.6227361.pth\", map_location=torch.device(\"cpu\"))\nrag_weight = torch.load(\"./ml_outputs/democlassi/RAG_resnet_model_21_val_loss_4.275671.pth\", map_location=torch.device(\"cpu\"))", "_____no_output_____" ], [ "resnet_fer.load_state_dict(fer_weight)", "_____no_output_____" ], [ "resnet_rag.load_state_dict(rag_weight)", "_____no_output_____" ], [ "print(f\"Number of parameters for FER model : {sum(p.numel() for p in resnet_fer.parameters()):_}\")\nprint(f\"Number of parameters for RAG model : {sum(p.numel() for p in resnet_rag.parameters()):_}\")", "Number of parameters for FER model : 23_522_375\nNumber of parameters for RAG model : 23_771_336\n" ], [ "class FERModel(nn.Module):\n def __init__(self, model):\n super(FERModel, self).__init__()\n self.model = model\n self.eval()\n \n def forward(self, x):\n with torch.no_grad():\n# x = preprocess_fer(x)\n x = torch.argmax(self.model(x))\n return x\n\n\nclass RAGModel(nn.Module):\n def __init__(self, model):\n super(RAGModel, self).__init__()\n self.model = model\n self.eval()\n \n def forward(self, x):\n with torch.no_grad():\n# x = preprocess_utk(x)\n age, gender_pred, race_pred = self.model(x)\n gender, race = torch.argmax(gender_pred), torch.argmax(race_pred)\n return age[0][0], gender, race", "_____no_output_____" ], [ "tmp_im = Image.open(\"./ml_outputs/democlassi/little-girl-tampon.jpg\")", "_____no_output_____" ], [ "tmp_im", "_____no_output_____" ], [ "fer_model = FERModel(resnet_fer)\n# im = torch.tensor(np.array(tmp_im))\n# print(fer_model(im))", "_____no_output_____" ], [ "rag_model = RAGModel(resnet_rag)\n# print(rag_model(im))", "_____no_output_____" ], [ "torch.onnx.export(fer_model, # model being run\n torch.randn((1, 3, 48, 48)), # model input (or a tuple for multiple inputs)\n \"../../public/static/ml_models/fer.onnx\", # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=9, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n input_names = ['input'], # the model's input names\n output_names = ['output'], # the model's output names\n dynamic_axes={'input' : {0 : 'sH', 1: \"W\"}, # variable lenght axes\n })", "_____no_output_____" ], [ "torch.onnx.export(rag_model, # model being run\n torch.randn((1, 3, 128, 128)), # model input (or a tuple for multiple inputs)\n \"../../public/static/ml_models/rag.onnx\", # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=9, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n input_names = ['input'], # the model's input names\n output_names = ['age', \"gender\", \"race\"], # the model's output names\n dynamic_axes={'input' : {0 : 'H', 1: \"W\"}, # variable lenght axes\n })", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0743508e887b4b74a6a356081a5a80db1e7ccaf
113,075
ipynb
Jupyter Notebook
examples/table/visualize-saliency-table.ipynb
corochann/chainer-saliency
9fa638796b4463a8180c7b03b78c8cabb902a9a6
[ "MIT" ]
13
2018-12-14T00:48:35.000Z
2021-11-17T21:51:47.000Z
examples/table/visualize-saliency-table.ipynb
corochann/chainer-saliency
9fa638796b4463a8180c7b03b78c8cabb902a9a6
[ "MIT" ]
2
2019-06-28T08:41:59.000Z
2020-09-28T22:00:56.000Z
examples/table/visualize-saliency-table.ipynb
corochann/chainer-saliency
9fa638796b4463a8180c7b03b78c8cabb902a9a6
[ "MIT" ]
3
2019-04-09T10:08:55.000Z
2019-10-25T00:36:17.000Z
145.715206
11,824
0.839257
[ [ [ "%load_ext autoreload\n%autoreload 2\n\nimport sklearn\nfrom sklearn import datasets", "_____no_output_____" ], [ "iris = datasets.load_iris()", "_____no_output_____" ], [ "iris", "_____no_output_____" ], [ "iris.feature_names", "_____no_output_____" ], [ "print(iris.data.shape, iris.data.dtype)", "(150, 4) float64\n" ], [ "iris.target", "_____no_output_____" ], [ "iris.target_names", "_____no_output_____" ], [ "import numpy as np\nfrom chainer_chemistry.datasets.numpy_tuple_dataset import NumpyTupleDataset\n\n# All dataset is to train for simplicity\ndataset = NumpyTupleDataset(iris.data.astype(np.float32), iris.target.astype(np.int32))\ntrain = dataset", "C:\\Users\\nakago\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n" ], [ "from chainer.functions import relu, dropout\n\nfrom chainer_chemistry.models.mlp import MLP\nfrom chainer_chemistry.models.prediction.classifier import Classifier\n\n\nfrom chainer.functions import dropout\ndef activation_relu_dropout(h):\n return dropout(relu(h), ratio=0.5)\n\n\nout_dim = len(iris.target_names)\npredictor = MLP(out_dim=out_dim, hidden_dim=48, n_layers=2, activation=activation_relu_dropout)\nclassifier = Classifier(predictor)", "_____no_output_____" ], [ "from chainer import iterators\nfrom chainer import optimizers\nfrom chainer import training\nfrom chainer.training import extensions as E\n\n\ndef fit(model, dataset, batchsize=16, epoch=10, out='results/tmp', device=-1):\n train_iter = iterators.SerialIterator(train, batchsize)\n optimizer = optimizers.Adam()\n optimizer.setup(model)\n\n updater = training.StandardUpdater(\n train_iter, optimizer, device=device)\n trainer = training.Trainer(updater, (epoch, 'epoch'), out=out)\n\n #trainer.extend(E.Evaluator(val_iter, classifier,\n # device=device, converter=concat_mols))\n trainer.extend(E.LogReport(), trigger=(10, 'epoch'))\n\n trainer.extend(E.PrintReport([\n 'epoch', 'main/loss', 'main/accuracy', 'validation/main/loss',\n 'validation/main/accuracy', 'elapsed_time']))\n trainer.run()", "_____no_output_____" ], [ "fit(classifier, train, batchsize=16, epoch=100)", "epoch main/loss main/accuracy validation/main/loss validation/main/accuracy elapsed_time\n10 0.829222 0.625 0.284298 \n20 0.808287 0.5625 0.610615 \n30 0.435911 0.8125 1.16335 \n40 0.360421 0.9375 1.68585 \n50 0.339677 0.9375 2.32392 \n60 0.405774 0.8125 3.05227 \n70 0.271674 0.9375 3.63845 \n80 0.334459 0.875 4.29602 \n90 0.294407 0.875 5.09873 \n100 0.164008 1 5.70911 \n" ] ], [ [ "## Saliency visualization", "_____no_output_____" ] ], [ [ "from chainer_chemistry.saliency.calculator.gradient_calculator import GradientCalculator\nfrom chainer_chemistry.saliency.calculator.integrated_gradients_calculator import IntegratedGradientsCalculator\nfrom chainer_chemistry.link_hooks.variable_monitor_link_hook import VariableMonitorLinkHook\n\n\n# 1. instantiation\ngradient_calculator = GradientCalculator(classifier)\n#gradient_calculator = IntegratedGradientsCalculator(classifier, steps=3,\n\n", "_____no_output_____" ], [ "from chainer_chemistry.saliency.calculator.calculator_utils import GaussianNoiseSampler\n\n# --- VanillaGrad ---\nM = 30\n# 2. compute\nsaliency_samples_vanilla = gradient_calculator.compute(\n train, M=1,)\nsaliency_samples_smooth = gradient_calculator.compute(\n train, M=M, noise_sampler=GaussianNoiseSampler())\nsaliency_samples_bayes = gradient_calculator.compute(\n train, M=M, train=True)", "100%|████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 62.66it/s]\n100%|██████████████████████████████████████████████████████████████████████████████████| 30/30 [00:00<00:00, 64.69it/s]\n100%|██████████████████████████████████████████████████████████████████████████████████| 30/30 [00:00<00:00, 58.75it/s]\n" ], [ "# 3. aggregate\nmethod = 'square'\nsaliency_vanilla = gradient_calculator.aggregate(\n saliency_samples_vanilla, ch_axis=None, method=method)\nsaliency_smooth = gradient_calculator.aggregate(\n saliency_samples_smooth, ch_axis=None, method=method)\nsaliency_bayes = gradient_calculator.aggregate(\n saliency_samples_bayes, ch_axis=None, method=method)", "_____no_output_____" ], [ "from chainer_chemistry.saliency.visualizer.table_visualizer import TableVisualizer\nfrom chainer_chemistry.saliency.visualizer.visualizer_utils import normalize_scaler\n\n\nvisualizer = TableVisualizer()", "_____no_output_____" ], [ "# Visualize saliency of `i`-th data\ni = 0\nvisualizer.visualize(saliency_vanilla[i], feature_names=iris.feature_names,\n scaler=normalize_scaler)", "_____no_output_____" ] ], [ [ "visualize saliency of all data --> this can be considered as \"feature importance\"", "_____no_output_____" ] ], [ [ "saliency_mean = np.mean(saliency_vanilla, axis=0)\nvisualizer.visualize(saliency_mean, feature_names=iris.feature_names, num_visualize=-1,\n scaler=normalize_scaler)\nvisualizer.visualize(saliency_mean, feature_names=iris.feature_names, num_visualize=-1,\n scaler=normalize_scaler, save_filepath='results/iris_vanilla_{}.png'.format(method))", "_____no_output_____" ], [ "saliency_mean = np.mean(saliency_smooth, axis=0)\nvisualizer.visualize(saliency_mean, feature_names=iris.feature_names, num_visualize=-1,\n scaler=normalize_scaler)\nvisualizer.visualize(saliency_mean, feature_names=iris.feature_names, num_visualize=-1,\n scaler=normalize_scaler, save_filepath='results/iris_smooth_{}.png'.format(method))", "_____no_output_____" ], [ "saliency_mean = np.mean(saliency_bayes, axis=0)\nvisualizer.visualize(saliency_mean, feature_names=iris.feature_names, num_visualize=-1,\n scaler=normalize_scaler)\nvisualizer.visualize(saliency_mean, feature_names=iris.feature_names, num_visualize=-1,\n scaler=normalize_scaler, save_filepath='results/iris_bayes_{}.png'.format(method))", "_____no_output_____" ] ], [ [ "## sklearn random forest feature importance\n\nRef:\n - https://qiita.com/TomokIshii/items/290adc16e2ca5032ca07\n - https://stackoverflow.com/questions/44101458/random-forest-feature-importance-chart-using-python", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.ensemble import RandomForestClassifier\n\niris = load_iris()\nX = iris.data\ny = iris.target\n\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=0)\n\nclf_rf = RandomForestClassifier()\nclf_rf.fit(X_train, y_train)\ny_pred = clf_rf.predict(X_test)\n\naccu = accuracy_score(y_test, y_pred)\nprint('accuracy = {:>.4f}'.format(accu))\n\n# Feature Importance\nfti = clf_rf.feature_importances_ \n\nprint('Feature Importances:')\nfor i, feat in enumerate(iris['feature_names']):\n print('\\t{0:20s} : {1:>.6f}'.format(feat, fti[i]))", "C:\\Users\\nakago\\Anaconda3\\lib\\site-packages\\sklearn\\ensemble\\forest.py:246: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.\n \"10 in version 0.20 to 100 in 0.22.\", FutureWarning)\n" ], [ "import matplotlib.pyplot as plt\n\nfeatures = iris['feature_names']\nimportances = clf_rf.feature_importances_\nindices = np.argsort(importances)\n\nplt.title('Random forest feature importance')\nplt.barh(range(len(indices)), importances[indices], color='b', align='center')\nplt.yticks(range(len(indices)), [features[i] for i in indices])\nplt.xlabel('Relative Importance')\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d07442c8b4b67c55fced095b1078604e0e1e5350
60,648
ipynb
Jupyter Notebook
P2S10.ipynb
aks1981/ML
174e2c1a4368ead5fce823d20206dc652e59c4aa
[ "Apache-2.0" ]
null
null
null
P2S10.ipynb
aks1981/ML
174e2c1a4368ead5fce823d20206dc652e59c4aa
[ "Apache-2.0" ]
null
null
null
P2S10.ipynb
aks1981/ML
174e2c1a4368ead5fce823d20206dc652e59c4aa
[ "Apache-2.0" ]
null
null
null
46.724191
214
0.52348
[ [ [ "<a href=\"https://colab.research.google.com/github/aks1981/ML/blob/master/P2S10.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Twin-Delayed DDPG\n\nComplete credit goes to this [awesome Deep Reinforcement Learning 2.0 Course on Udemy](https://www.udemy.com/course/deep-reinforcement-learning/) for the code.", "_____no_output_____" ], [ "## Installing the packages", "_____no_output_____" ] ], [ [ "!pip install pybullet", "Requirement already satisfied: pybullet in /usr/local/lib/python3.6/dist-packages (2.7.1)\n" ] ], [ [ "## Importing the libraries", "_____no_output_____" ] ], [ [ "import os\nimport time\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pybullet_envs\nimport gym\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom gym import wrappers\nfrom torch.autograd import Variable\nfrom collections import deque", "_____no_output_____" ] ], [ [ "## Step 1: We initialize the Experience Replay memory", "_____no_output_____" ] ], [ [ "class ReplayBuffer(object):\n\n def __init__(self, max_size=1e6):\n self.storage = []\n self.max_size = max_size\n self.ptr = 0\n\n def add(self, transition):\n if len(self.storage) == self.max_size:\n self.storage[int(self.ptr)] = transition\n self.ptr = (self.ptr + 1) % self.max_size\n else:\n self.storage.append(transition)\n\n def sample(self, batch_size):\n ind = np.random.randint(0, len(self.storage), size=batch_size)\n batch_states, batch_next_states, batch_actions, batch_rewards, batch_dones = [], [], [], [], []\n for i in ind: \n state, next_state, action, reward, done = self.storage[i]\n batch_states.append(np.array(state, copy=False))\n batch_next_states.append(np.array(next_state, copy=False))\n batch_actions.append(np.array(action, copy=False))\n batch_rewards.append(np.array(reward, copy=False))\n batch_dones.append(np.array(done, copy=False))\n return np.array(batch_states), np.array(batch_next_states), np.array(batch_actions), np.array(batch_rewards).reshape(-1, 1), np.array(batch_dones).reshape(-1, 1)", "_____no_output_____" ] ], [ [ "## Step 2: We build one neural network for the Actor model and one neural network for the Actor target", "_____no_output_____" ] ], [ [ "class Actor(nn.Module):\n \n def __init__(self, state_dim, action_dim, max_action):\n super(Actor, self).__init__()\n self.layer_1 = nn.Linear(state_dim, 400)\n self.layer_2 = nn.Linear(400, 300)\n self.layer_3 = nn.Linear(300, action_dim)\n self.max_action = max_action\n\n def forward(self, x):\n x = F.relu(self.layer_1(x))\n x = F.relu(self.layer_2(x))\n x = self.max_action * torch.tanh(self.layer_3(x))\n return x", "_____no_output_____" ] ], [ [ "## Step 3: We build two neural networks for the two Critic models and two neural networks for the two Critic targets", "_____no_output_____" ] ], [ [ "class Critic(nn.Module):\n \n def __init__(self, state_dim, action_dim):\n super(Critic, self).__init__()\n # Defining the first Critic neural network\n self.layer_1 = nn.Linear(state_dim + action_dim, 400)\n self.layer_2 = nn.Linear(400, 300)\n self.layer_3 = nn.Linear(300, 1)\n # Defining the second Critic neural network\n self.layer_4 = nn.Linear(state_dim + action_dim, 400)\n self.layer_5 = nn.Linear(400, 300)\n self.layer_6 = nn.Linear(300, 1)\n\n def forward(self, x, u):\n xu = torch.cat([x, u], 1)\n # Forward-Propagation on the first Critic Neural Network\n x1 = F.relu(self.layer_1(xu))\n x1 = F.relu(self.layer_2(x1))\n x1 = self.layer_3(x1)\n # Forward-Propagation on the second Critic Neural Network\n x2 = F.relu(self.layer_4(xu))\n x2 = F.relu(self.layer_5(x2))\n x2 = self.layer_6(x2)\n return x1, x2\n\n def Q1(self, x, u):\n xu = torch.cat([x, u], 1)\n x1 = F.relu(self.layer_1(xu))\n x1 = F.relu(self.layer_2(x1))\n x1 = self.layer_3(x1)\n return x1", "_____no_output_____" ] ], [ [ "## Steps 4 to 15: Training Process", "_____no_output_____" ] ], [ [ "# Selecting the device (CPU or GPU)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Building the whole Training Process into a class\n\nclass TD3(object):\n \n def __init__(self, state_dim, action_dim, max_action):\n self.actor = Actor(state_dim, action_dim, max_action).to(device)\n self.actor_target = Actor(state_dim, action_dim, max_action).to(device)\n self.actor_target.load_state_dict(self.actor.state_dict())\n self.actor_optimizer = torch.optim.Adam(self.actor.parameters())\n self.critic = Critic(state_dim, action_dim).to(device)\n self.critic_target = Critic(state_dim, action_dim).to(device)\n self.critic_target.load_state_dict(self.critic.state_dict())\n self.critic_optimizer = torch.optim.Adam(self.critic.parameters())\n self.max_action = max_action\n\n def select_action(self, state):\n state = torch.Tensor(state.reshape(1, -1)).to(device)\n return self.actor(state).cpu().data.numpy().flatten()\n\n def train(self, replay_buffer, iterations, batch_size=100, discount=0.99, tau=0.005, policy_noise=0.2, noise_clip=0.5, policy_freq=2):\n \n for it in range(iterations):\n \n # Step 4: We sample a batch of transitions (s, s’, a, r) from the memory\n batch_states, batch_next_states, batch_actions, batch_rewards, batch_dones = replay_buffer.sample(batch_size)\n state = torch.Tensor(batch_states).to(device)\n next_state = torch.Tensor(batch_next_states).to(device)\n action = torch.Tensor(batch_actions).to(device)\n reward = torch.Tensor(batch_rewards).to(device)\n done = torch.Tensor(batch_dones).to(device)\n \n # Step 5: From the next state s’, the Actor target plays the next action a’\n next_action = self.actor_target(next_state)\n \n # Step 6: We add Gaussian noise to this next action a’ and we clamp it in a range of values supported by the environment\n noise = torch.Tensor(batch_actions).data.normal_(0, policy_noise).to(device)\n noise = noise.clamp(-noise_clip, noise_clip)\n next_action = (next_action + noise).clamp(-self.max_action, self.max_action)\n \n # Step 7: The two Critic targets take each the couple (s’, a’) as input and return two Q-values Qt1(s’,a’) and Qt2(s’,a’) as outputs\n target_Q1, target_Q2 = self.critic_target(next_state, next_action)\n \n # Step 8: We keep the minimum of these two Q-values: min(Qt1, Qt2)\n target_Q = torch.min(target_Q1, target_Q2)\n \n # Step 9: We get the final target of the two Critic models, which is: Qt = r + γ * min(Qt1, Qt2), where γ is the discount factor\n target_Q = reward + ((1 - done) * discount * target_Q).detach()\n \n # Step 10: The two Critic models take each the couple (s, a) as input and return two Q-values Q1(s,a) and Q2(s,a) as outputs\n current_Q1, current_Q2 = self.critic(state, action)\n \n # Step 11: We compute the loss coming from the two Critic models: Critic Loss = MSE_Loss(Q1(s,a), Qt) + MSE_Loss(Q2(s,a), Qt)\n critic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q)\n \n # Step 12: We backpropagate this Critic loss and update the parameters of the two Critic models with a SGD optimizer\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n self.critic_optimizer.step()\n \n # Step 13: Once every two iterations, we update our Actor model by performing gradient ascent on the output of the first Critic model\n if it % policy_freq == 0:\n actor_loss = -self.critic.Q1(state, self.actor(state)).mean()\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n \n # Step 14: Still once every two iterations, we update the weights of the Actor target by polyak averaging\n for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n \n # Step 15: Still once every two iterations, we update the weights of the Critic target by polyak averaging\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n \n # Making a save method to save a trained model\n def save(self, filename, directory):\n torch.save(self.actor.state_dict(), '%s/%s_actor.pth' % (directory, filename))\n torch.save(self.critic.state_dict(), '%s/%s_critic.pth' % (directory, filename))\n \n # Making a load method to load a pre-trained model\n def load(self, filename, directory):\n self.actor.load_state_dict(torch.load('%s/%s_actor.pth' % (directory, filename)))\n self.critic.load_state_dict(torch.load('%s/%s_critic.pth' % (directory, filename)))", "_____no_output_____" ] ], [ [ "## We make a function that evaluates the policy by calculating its average reward over 10 episodes", "_____no_output_____" ] ], [ [ "def evaluate_policy(policy, eval_episodes=10):\n avg_reward = 0.\n for _ in range(eval_episodes):\n obs = env.reset()\n done = False\n while not done:\n action = policy.select_action(np.array(obs))\n obs, reward, done, _ = env.step(action)\n avg_reward += reward\n avg_reward /= eval_episodes\n print (\"---------------------------------------\")\n print (\"Average Reward over the Evaluation Step: %f\" % (avg_reward))\n print (\"---------------------------------------\")\n return avg_reward", "_____no_output_____" ] ], [ [ "## We set the parameters", "_____no_output_____" ] ], [ [ "env_name = \"AntBulletEnv-v0\" # Name of a environment (set it to any Continous environment you want)\nseed = 0 # Random seed number\nstart_timesteps = 1e4 # Number of iterations/timesteps before which the model randomly chooses an action, and after which it starts to use the policy network\neval_freq = 5e3 # How often the evaluation step is performed (after how many timesteps)\nmax_timesteps = 5e5 # Total number of iterations/timesteps\nsave_models = True # Boolean checker whether or not to save the pre-trained model\nexpl_noise = 0.1 # Exploration noise - STD value of exploration Gaussian noise\nbatch_size = 100 # Size of the batch\ndiscount = 0.99 # Discount factor gamma, used in the calculation of the total discounted reward\ntau = 0.005 # Target network update rate\npolicy_noise = 0.2 # STD of Gaussian noise added to the actions for the exploration purposes\nnoise_clip = 0.5 # Maximum value of the Gaussian noise added to the actions (policy)\npolicy_freq = 2 # Number of iterations to wait before the policy network (Actor model) is updated", "_____no_output_____" ] ], [ [ "## We create a file name for the two saved models: the Actor and Critic models", "_____no_output_____" ] ], [ [ "file_name = \"%s_%s_%s\" % (\"TD3\", env_name, str(seed))\nprint (\"---------------------------------------\")\nprint (\"Settings: %s\" % (file_name))\nprint (\"---------------------------------------\")", "---------------------------------------\nSettings: TD3_AntBulletEnv-v0_0\n---------------------------------------\n" ] ], [ [ "## We create a folder inside which will be saved the trained models", "_____no_output_____" ] ], [ [ "if not os.path.exists(\"./results\"):\n os.makedirs(\"./results\")\nif save_models and not os.path.exists(\"./pytorch_models\"):\n os.makedirs(\"./pytorch_models\")", "_____no_output_____" ] ], [ [ "## We create the PyBullet environment", "_____no_output_____" ] ], [ [ "env = gym.make(env_name)", "/usr/local/lib/python3.6/dist-packages/gym/logger.py:30: UserWarning: \u001b[33mWARN: Box bound precision lowered by casting to float32\u001b[0m\n warnings.warn(colorize('%s: %s'%('WARN', msg % args), 'yellow'))\n" ] ], [ [ "## We set seeds and we get the necessary information on the states and actions in the chosen environment", "_____no_output_____" ] ], [ [ "env.seed(seed)\ntorch.manual_seed(seed)\nnp.random.seed(seed)\nstate_dim = env.observation_space.shape[0]\naction_dim = env.action_space.shape[0]\nmax_action = float(env.action_space.high[0])", "_____no_output_____" ] ], [ [ "## We create the policy network (the Actor model)", "_____no_output_____" ] ], [ [ "policy = TD3(state_dim, action_dim, max_action)", "_____no_output_____" ] ], [ [ "[link text](https://)## We create the Experience Replay memory", "_____no_output_____" ] ], [ [ "replay_buffer = ReplayBuffer()", "_____no_output_____" ] ], [ [ "## We define a list where all the evaluation results over 10 episodes are stored", "_____no_output_____" ] ], [ [ "evaluations = [evaluate_policy(policy)]", "---------------------------------------\nAverage Reward over the Evaluation Step: 9.804960\n---------------------------------------\n" ] ], [ [ "## We create a new folder directory in which the final results (videos of the agent) will be populated", "_____no_output_____" ] ], [ [ "def mkdir(base, name):\n path = os.path.join(base, name)\n if not os.path.exists(path):\n os.makedirs(path)\n return path\nwork_dir = mkdir('exp', 'brs')\nmonitor_dir = mkdir(work_dir, 'monitor')\nmax_episode_steps = env._max_episode_steps\nsave_env_vid = False\nif save_env_vid:\n env = wrappers.Monitor(env, monitor_dir, force = True)\n env.reset()", "_____no_output_____" ] ], [ [ "## We initialize the variables", "_____no_output_____" ] ], [ [ "total_timesteps = 0\ntimesteps_since_eval = 0\nepisode_num = 0\ndone = True\nt0 = time.time()", "_____no_output_____" ] ], [ [ "## Training", "_____no_output_____" ] ], [ [ "max_timesteps = 500000\n# We start the main loop over 500,000 timesteps\nwhile total_timesteps < max_timesteps:\n \n # If the episode is done\n if done:\n\n # If we are not at the very beginning, we start the training process of the model\n if total_timesteps != 0:\n print(\"Total Timesteps: {} Episode Num: {} Reward: {}\".format(total_timesteps, episode_num, episode_reward))\n policy.train(replay_buffer, episode_timesteps, batch_size, discount, tau, policy_noise, noise_clip, policy_freq)\n\n # We evaluate the episode and we save the policy\n if timesteps_since_eval >= eval_freq:\n timesteps_since_eval %= eval_freq\n evaluations.append(evaluate_policy(policy))\n policy.save(file_name, directory=\"./pytorch_models\")\n np.save(\"./results/%s\" % (file_name), evaluations)\n \n # When the training step is done, we reset the state of the environment\n obs = env.reset()\n \n # Set the Done to False\n done = False\n \n # Set rewards and episode timesteps to zero\n episode_reward = 0\n episode_timesteps = 0\n episode_num += 1\n \n # Before 10000 timesteps, we play random actions\n if total_timesteps < start_timesteps:\n action = env.action_space.sample()\n else: # After 10000 timesteps, we switch to the model\n action = policy.select_action(np.array(obs))\n # If the explore_noise parameter is not 0, we add noise to the action and we clip it\n if expl_noise != 0:\n action = (action + np.random.normal(0, expl_noise, size=env.action_space.shape[0])).clip(env.action_space.low, env.action_space.high)\n \n # The agent performs the action in the environment, then reaches the next state and receives the reward\n new_obs, reward, done, _ = env.step(action)\n \n # We check if the episode is done\n done_bool = 0 if episode_timesteps + 1 == env._max_episode_steps else float(done)\n \n # We increase the total reward\n episode_reward += reward\n \n # We store the new transition into the Experience Replay memory (ReplayBuffer)\n replay_buffer.add((obs, new_obs, action, reward, done_bool))\n\n # We update the state, the episode timestep, the total timesteps, and the timesteps since the evaluation of the policy\n obs = new_obs\n episode_timesteps += 1\n total_timesteps += 1\n timesteps_since_eval += 1\n\n# We add the last policy evaluation to our list of evaluations and we save our model\nevaluations.append(evaluate_policy(policy))\nif save_models: policy.save(\"%s\" % (file_name), directory=\"./pytorch_models\")\nnp.save(\"./results/%s\" % (file_name), evaluations)", "Total Timesteps: 1000 Episode Num: 1 Reward: 512.6232988347093\nTotal Timesteps: 2000 Episode Num: 2 Reward: 493.70176430884203\nTotal Timesteps: 3000 Episode Num: 3 Reward: 492.40008391554187\nTotal Timesteps: 4000 Episode Num: 4 Reward: 476.3080060617612\nTotal Timesteps: 5000 Episode Num: 5 Reward: 494.0312655821267\n---------------------------------------\nAverage Reward over the Evaluation Step: 154.195280\n---------------------------------------\nTotal Timesteps: 5133 Episode Num: 6 Reward: 62.03055212295001\nTotal Timesteps: 6133 Episode Num: 7 Reward: 514.9270628334779\nTotal Timesteps: 6485 Episode Num: 8 Reward: 167.59288140345458\nTotal Timesteps: 7485 Episode Num: 9 Reward: 236.29198633567387\nTotal Timesteps: 8485 Episode Num: 10 Reward: 509.53382938773007\nTotal Timesteps: 8602 Episode Num: 11 Reward: 50.5568507268108\nTotal Timesteps: 9602 Episode Num: 12 Reward: 520.9793005272942\nTotal Timesteps: 10602 Episode Num: 13 Reward: 497.8470933409838\n---------------------------------------\nAverage Reward over the Evaluation Step: 128.452366\n---------------------------------------\nTotal Timesteps: 11602 Episode Num: 14 Reward: 75.12851600337565\nTotal Timesteps: 12602 Episode Num: 15 Reward: 185.85454988972566\nTotal Timesteps: 13602 Episode Num: 16 Reward: 255.98572779187978\nTotal Timesteps: 14602 Episode Num: 17 Reward: 130.0382692472513\nTotal Timesteps: 15602 Episode Num: 18 Reward: 115.21073238051312\n---------------------------------------\nAverage Reward over the Evaluation Step: 229.912339\n---------------------------------------\nTotal Timesteps: 16602 Episode Num: 19 Reward: 286.9407247295469\nTotal Timesteps: 17602 Episode Num: 20 Reward: 227.17287004160997\nTotal Timesteps: 18602 Episode Num: 21 Reward: 80.32986466490651\nTotal Timesteps: 19602 Episode Num: 22 Reward: 283.3712042492783\nTotal Timesteps: 20602 Episode Num: 23 Reward: 127.41396182269945\n---------------------------------------\nAverage Reward over the Evaluation Step: 218.761478\n---------------------------------------\nTotal Timesteps: 21602 Episode Num: 24 Reward: 278.36781644990464\nTotal Timesteps: 22602 Episode Num: 25 Reward: 309.2025085988498\nTotal Timesteps: 23602 Episode Num: 26 Reward: 306.87063698855405\nTotal Timesteps: 24602 Episode Num: 27 Reward: 412.03125738607673\nTotal Timesteps: 25602 Episode Num: 28 Reward: 198.6635895184017\n---------------------------------------\nAverage Reward over the Evaluation Step: 350.084413\n---------------------------------------\nTotal Timesteps: 26602 Episode Num: 29 Reward: 322.19013162263946\nTotal Timesteps: 27602 Episode Num: 30 Reward: 204.21178137830844\nTotal Timesteps: 28602 Episode Num: 31 Reward: 103.61375401208718\nTotal Timesteps: 29602 Episode Num: 32 Reward: 292.5332001401748\nTotal Timesteps: 29631 Episode Num: 33 Reward: 6.9196293063098695\nTotal Timesteps: 29660 Episode Num: 34 Reward: 8.769085282658294\nTotal Timesteps: 29737 Episode Num: 35 Reward: 28.08327579198238\nTotal Timesteps: 29774 Episode Num: 36 Reward: 7.967136280319689\nTotal Timesteps: 30390 Episode Num: 37 Reward: 312.0899631284384\n---------------------------------------\nAverage Reward over the Evaluation Step: 202.433665\n---------------------------------------\nTotal Timesteps: 31390 Episode Num: 38 Reward: 164.12255778235527\nTotal Timesteps: 31447 Episode Num: 39 Reward: 5.823704818050642\nTotal Timesteps: 31548 Episode Num: 40 Reward: 14.783543810558175\nTotal Timesteps: 31695 Episode Num: 41 Reward: 50.982756144854214\nTotal Timesteps: 32695 Episode Num: 42 Reward: 459.96194083486074\nTotal Timesteps: 33695 Episode Num: 43 Reward: 437.38196663630356\nTotal Timesteps: 34398 Episode Num: 44 Reward: 300.1568646720385\nTotal Timesteps: 35398 Episode Num: 45 Reward: 210.21459800639192\n---------------------------------------\nAverage Reward over the Evaluation Step: 326.801282\n---------------------------------------\nTotal Timesteps: 36398 Episode Num: 46 Reward: 316.66459383449904\nTotal Timesteps: 37398 Episode Num: 47 Reward: 339.16414336388686\nTotal Timesteps: 38398 Episode Num: 48 Reward: 106.89385488193517\nTotal Timesteps: 39398 Episode Num: 49 Reward: 379.6430817247807\nTotal Timesteps: 40398 Episode Num: 50 Reward: 334.8962617321453\n---------------------------------------\nAverage Reward over the Evaluation Step: 117.635710\n---------------------------------------\nTotal Timesteps: 41272 Episode Num: 51 Reward: 111.15273857740404\nTotal Timesteps: 41302 Episode Num: 52 Reward: 12.68026840063823\nTotal Timesteps: 41634 Episode Num: 53 Reward: 83.37937865997512\nTotal Timesteps: 41667 Episode Num: 54 Reward: 15.29215813636454\nTotal Timesteps: 41708 Episode Num: 55 Reward: 22.910606202918174\nTotal Timesteps: 42708 Episode Num: 56 Reward: 300.95375435808313\nTotal Timesteps: 43708 Episode Num: 57 Reward: 307.7032024847098\nTotal Timesteps: 44064 Episode Num: 58 Reward: 39.01389233571982\nTotal Timesteps: 44140 Episode Num: 59 Reward: 11.810420664766298\nTotal Timesteps: 45140 Episode Num: 60 Reward: 195.05080454058643\n---------------------------------------\nAverage Reward over the Evaluation Step: 232.565050\n---------------------------------------\nTotal Timesteps: 46140 Episode Num: 61 Reward: 235.29411016742816\nTotal Timesteps: 47140 Episode Num: 62 Reward: 315.8326540369658\nTotal Timesteps: 48140 Episode Num: 63 Reward: 425.615676205701\nTotal Timesteps: 49140 Episode Num: 64 Reward: 628.341676038075\nTotal Timesteps: 50140 Episode Num: 65 Reward: 417.72993234590905\n---------------------------------------\nAverage Reward over the Evaluation Step: 483.382864\n---------------------------------------\nTotal Timesteps: 51140 Episode Num: 66 Reward: 270.6667814230197\nTotal Timesteps: 52140 Episode Num: 67 Reward: 358.8033832631072\nTotal Timesteps: 53140 Episode Num: 68 Reward: 516.792398534641\nTotal Timesteps: 54140 Episode Num: 69 Reward: 403.2419608632971\nTotal Timesteps: 55140 Episode Num: 70 Reward: 440.99007770491835\n---------------------------------------\nAverage Reward over the Evaluation Step: 394.578688\n---------------------------------------\nTotal Timesteps: 55242 Episode Num: 71 Reward: 39.70154329117188\nTotal Timesteps: 56242 Episode Num: 72 Reward: 374.1900584893031\nTotal Timesteps: 57242 Episode Num: 73 Reward: 307.6071611539539\nTotal Timesteps: 58242 Episode Num: 74 Reward: 311.1345148830395\nTotal Timesteps: 59242 Episode Num: 75 Reward: 127.5429629120776\nTotal Timesteps: 60242 Episode Num: 76 Reward: 367.0588217185416\n---------------------------------------\nAverage Reward over the Evaluation Step: 108.518749\n---------------------------------------\nTotal Timesteps: 60419 Episode Num: 77 Reward: 1.2919983145482905\nTotal Timesteps: 61419 Episode Num: 78 Reward: 414.1641433832518\nTotal Timesteps: 62419 Episode Num: 79 Reward: 369.97711832414734\nTotal Timesteps: 63419 Episode Num: 80 Reward: 313.3218709906793\nTotal Timesteps: 64419 Episode Num: 81 Reward: 305.6061976643445\nTotal Timesteps: 65419 Episode Num: 82 Reward: 351.9500421236098\n---------------------------------------\nAverage Reward over the Evaluation Step: 462.640597\n---------------------------------------\nTotal Timesteps: 66419 Episode Num: 83 Reward: 483.3780508358247\nTotal Timesteps: 67419 Episode Num: 84 Reward: 307.4506990402266\nTotal Timesteps: 68419 Episode Num: 85 Reward: 682.4619278143392\nTotal Timesteps: 69419 Episode Num: 86 Reward: 374.5233031917104\nTotal Timesteps: 70419 Episode Num: 87 Reward: 492.08397064197857\n---------------------------------------\nAverage Reward over the Evaluation Step: 374.841564\n---------------------------------------\nTotal Timesteps: 71419 Episode Num: 88 Reward: 442.93137085887406\nTotal Timesteps: 72419 Episode Num: 89 Reward: 586.8272792098666\nTotal Timesteps: 73419 Episode Num: 90 Reward: 358.33666422091284\nTotal Timesteps: 74419 Episode Num: 91 Reward: 621.0003030741502\nTotal Timesteps: 75419 Episode Num: 92 Reward: 674.2112092758323\n---------------------------------------\nAverage Reward over the Evaluation Step: 555.177452\n---------------------------------------\nTotal Timesteps: 76419 Episode Num: 93 Reward: 627.5050249241532\nTotal Timesteps: 77419 Episode Num: 94 Reward: 838.4823478856684\nTotal Timesteps: 78419 Episode Num: 95 Reward: 541.1595708152734\nTotal Timesteps: 79419 Episode Num: 96 Reward: 553.6311493618038\nTotal Timesteps: 80419 Episode Num: 97 Reward: 641.6735821734253\n---------------------------------------\nAverage Reward over the Evaluation Step: 504.145333\n---------------------------------------\nTotal Timesteps: 81419 Episode Num: 98 Reward: 522.8365489351993\nTotal Timesteps: 82419 Episode Num: 99 Reward: 477.0298818993572\nTotal Timesteps: 83419 Episode Num: 100 Reward: 791.6863211157099\nTotal Timesteps: 84419 Episode Num: 101 Reward: 573.3475449740887\nTotal Timesteps: 85419 Episode Num: 102 Reward: 648.3139759060236\n---------------------------------------\nAverage Reward over the Evaluation Step: 582.012942\n---------------------------------------\nTotal Timesteps: 86419 Episode Num: 103 Reward: 467.233995134909\nTotal Timesteps: 87419 Episode Num: 104 Reward: 532.355075793272\nTotal Timesteps: 88419 Episode Num: 105 Reward: 448.2984699517601\nTotal Timesteps: 89419 Episode Num: 106 Reward: 733.0891408655976\nTotal Timesteps: 90419 Episode Num: 107 Reward: 520.7315198264828\n---------------------------------------\nAverage Reward over the Evaluation Step: 572.394565\n---------------------------------------\nTotal Timesteps: 91419 Episode Num: 108 Reward: 247.1330145679398\nTotal Timesteps: 92419 Episode Num: 109 Reward: 539.4933900200043\nTotal Timesteps: 93419 Episode Num: 110 Reward: 482.3074099367543\nTotal Timesteps: 94419 Episode Num: 111 Reward: 608.9362342547292\nTotal Timesteps: 95419 Episode Num: 112 Reward: 533.214044848681\n---------------------------------------\nAverage Reward over the Evaluation Step: 432.162784\n---------------------------------------\nTotal Timesteps: 96419 Episode Num: 113 Reward: 626.7356321953255\nTotal Timesteps: 97419 Episode Num: 114 Reward: 165.0771181649909\nTotal Timesteps: 98419 Episode Num: 115 Reward: 246.41934316667087\nTotal Timesteps: 99419 Episode Num: 116 Reward: 687.2147335807146\nTotal Timesteps: 99552 Episode Num: 117 Reward: 106.12056982992601\nTotal Timesteps: 100552 Episode Num: 118 Reward: 584.3008095812155\n---------------------------------------\nAverage Reward over the Evaluation Step: 279.468899\n---------------------------------------\nTotal Timesteps: 101552 Episode Num: 119 Reward: 251.2864884588421\nTotal Timesteps: 102552 Episode Num: 120 Reward: 474.39117038965736\nTotal Timesteps: 103552 Episode Num: 121 Reward: 359.31576138266746\nTotal Timesteps: 104552 Episode Num: 122 Reward: 314.56947871004485\nTotal Timesteps: 105552 Episode Num: 123 Reward: 591.1184137822272\n---------------------------------------\nAverage Reward over the Evaluation Step: 307.921247\n---------------------------------------\nTotal Timesteps: 106552 Episode Num: 124 Reward: 557.791907911734\nTotal Timesteps: 107552 Episode Num: 125 Reward: 563.0735414812734\nTotal Timesteps: 108552 Episode Num: 126 Reward: 590.9480336821701\nTotal Timesteps: 109552 Episode Num: 127 Reward: 486.69656816088326\nTotal Timesteps: 110552 Episode Num: 128 Reward: 468.3500699716701\n---------------------------------------\nAverage Reward over the Evaluation Step: 429.304043\n---------------------------------------\nTotal Timesteps: 111552 Episode Num: 129 Reward: 411.6801388847237\nTotal Timesteps: 112552 Episode Num: 130 Reward: 411.70937509706556\nTotal Timesteps: 113552 Episode Num: 131 Reward: 372.00569251127206\nTotal Timesteps: 114552 Episode Num: 132 Reward: 666.1430800691087\nTotal Timesteps: 115552 Episode Num: 133 Reward: 460.9904416173104\n---------------------------------------\nAverage Reward over the Evaluation Step: 523.570190\n---------------------------------------\nTotal Timesteps: 116552 Episode Num: 134 Reward: 352.1573019072249\nTotal Timesteps: 117552 Episode Num: 135 Reward: 488.9605787803935\nTotal Timesteps: 118552 Episode Num: 136 Reward: 296.84492677040714\nTotal Timesteps: 119552 Episode Num: 137 Reward: 434.0537955059363\nTotal Timesteps: 120552 Episode Num: 138 Reward: 379.08378272070706\n---------------------------------------\nAverage Reward over the Evaluation Step: 657.452964\n---------------------------------------\nTotal Timesteps: 121552 Episode Num: 139 Reward: 371.07870015375863\nTotal Timesteps: 122552 Episode Num: 140 Reward: 664.9377383113746\nTotal Timesteps: 123552 Episode Num: 141 Reward: 308.3757851862608\nTotal Timesteps: 124552 Episode Num: 142 Reward: 600.4104389421784\nTotal Timesteps: 125552 Episode Num: 143 Reward: 439.525359030352\n---------------------------------------\nAverage Reward over the Evaluation Step: 512.187949\n---------------------------------------\nTotal Timesteps: 126552 Episode Num: 144 Reward: 342.8940278454713\nTotal Timesteps: 127552 Episode Num: 145 Reward: 580.1339780093208\nTotal Timesteps: 128552 Episode Num: 146 Reward: 378.0806987666161\nTotal Timesteps: 129552 Episode Num: 147 Reward: 594.8097622539781\nTotal Timesteps: 130552 Episode Num: 148 Reward: 311.5215678900163\n---------------------------------------\nAverage Reward over the Evaluation Step: 529.079285\n---------------------------------------\nTotal Timesteps: 131552 Episode Num: 149 Reward: 675.7493771261866\nTotal Timesteps: 132552 Episode Num: 150 Reward: 524.108399768893\nTotal Timesteps: 133552 Episode Num: 151 Reward: 592.0693750792075\nTotal Timesteps: 134552 Episode Num: 152 Reward: 292.74064823213683\nTotal Timesteps: 135552 Episode Num: 153 Reward: 330.2225634953474\n---------------------------------------\nAverage Reward over the Evaluation Step: 532.268559\n---------------------------------------\nTotal Timesteps: 136552 Episode Num: 154 Reward: 436.40275488198887\nTotal Timesteps: 137552 Episode Num: 155 Reward: 539.7247665876872\nTotal Timesteps: 138552 Episode Num: 156 Reward: 469.81523890069843\nTotal Timesteps: 139552 Episode Num: 157 Reward: 601.9912032541115\nTotal Timesteps: 140552 Episode Num: 158 Reward: 425.4515105314638\n---------------------------------------\nAverage Reward over the Evaluation Step: 314.491185\n---------------------------------------\nTotal Timesteps: 141468 Episode Num: 159 Reward: 425.93157392282257\nTotal Timesteps: 142468 Episode Num: 160 Reward: 427.26013116609346\nTotal Timesteps: 142833 Episode Num: 161 Reward: 183.91652865733244\nTotal Timesteps: 142947 Episode Num: 162 Reward: 50.069775269034324\nTotal Timesteps: 143947 Episode Num: 163 Reward: 646.364585534303\nTotal Timesteps: 144947 Episode Num: 164 Reward: 477.41824037888335\nTotal Timesteps: 145947 Episode Num: 165 Reward: 552.3042803396013\n---------------------------------------\nAverage Reward over the Evaluation Step: 531.458138\n---------------------------------------\nTotal Timesteps: 146947 Episode Num: 166 Reward: 585.5431257819682\nTotal Timesteps: 147947 Episode Num: 167 Reward: 324.94786041445747\nTotal Timesteps: 148947 Episode Num: 168 Reward: 546.6546656982192\nTotal Timesteps: 149947 Episode Num: 169 Reward: 592.4284350006956\nTotal Timesteps: 150947 Episode Num: 170 Reward: 412.1744292730023\n---------------------------------------\nAverage Reward over the Evaluation Step: 536.302828\n---------------------------------------\nTotal Timesteps: 151947 Episode Num: 171 Reward: 533.0888396635238\nTotal Timesteps: 152947 Episode Num: 172 Reward: 527.3217282008873\nTotal Timesteps: 153947 Episode Num: 173 Reward: 280.43220642595793\nTotal Timesteps: 154947 Episode Num: 174 Reward: 193.33424720378716\nTotal Timesteps: 155947 Episode Num: 175 Reward: 325.8002629464136\n---------------------------------------\nAverage Reward over the Evaluation Step: 338.946457\n---------------------------------------\nTotal Timesteps: 156947 Episode Num: 176 Reward: 290.7160933823586\nTotal Timesteps: 157947 Episode Num: 177 Reward: 379.10298330586903\nTotal Timesteps: 158947 Episode Num: 178 Reward: 292.6396511093699\nTotal Timesteps: 159947 Episode Num: 179 Reward: 461.62048504640205\nTotal Timesteps: 160947 Episode Num: 180 Reward: 422.45777610848126\n---------------------------------------\nAverage Reward over the Evaluation Step: 511.189483\n---------------------------------------\nTotal Timesteps: 161947 Episode Num: 181 Reward: 439.4691276679888\nTotal Timesteps: 162947 Episode Num: 182 Reward: 648.9593381207025\nTotal Timesteps: 163947 Episode Num: 183 Reward: 620.6338059293364\nTotal Timesteps: 164947 Episode Num: 184 Reward: 453.458217124958\nTotal Timesteps: 165947 Episode Num: 185 Reward: 414.36031279219804\n---------------------------------------\nAverage Reward over the Evaluation Step: 440.335195\n---------------------------------------\nTotal Timesteps: 166947 Episode Num: 186 Reward: 522.2063175282304\nTotal Timesteps: 167947 Episode Num: 187 Reward: 259.9825712171355\nTotal Timesteps: 168947 Episode Num: 188 Reward: 520.8221978165838\nTotal Timesteps: 169382 Episode Num: 189 Reward: 185.83971584414329\nTotal Timesteps: 170382 Episode Num: 190 Reward: 674.3617387582459\n---------------------------------------\nAverage Reward over the Evaluation Step: 705.455231\n---------------------------------------\nTotal Timesteps: 171382 Episode Num: 191 Reward: 564.1567976163952\nTotal Timesteps: 172382 Episode Num: 192 Reward: 740.9578833141447\nTotal Timesteps: 173382 Episode Num: 193 Reward: 340.24270992484423\n" ] ], [ [ "## Inference", "_____no_output_____" ] ], [ [ "class Actor(nn.Module):\n \n def __init__(self, state_dim, action_dim, max_action):\n super(Actor, self).__init__()\n self.layer_1 = nn.Linear(state_dim, 400)\n self.layer_2 = nn.Linear(400, 300)\n self.layer_3 = nn.Linear(300, action_dim)\n self.max_action = max_action\n\n def forward(self, x):\n x = F.relu(self.layer_1(x))\n x = F.relu(self.layer_2(x))\n x = self.max_action * torch.tanh(self.layer_3(x)) \n return x\n\nclass Critic(nn.Module):\n \n def __init__(self, state_dim, action_dim):\n super(Critic, self).__init__()\n # Defining the first Critic neural network\n self.layer_1 = nn.Linear(state_dim + action_dim, 400)\n self.layer_2 = nn.Linear(400, 300)\n self.layer_3 = nn.Linear(300, 1)\n # Defining the second Critic neural network\n self.layer_4 = nn.Linear(state_dim + action_dim, 400)\n self.layer_5 = nn.Linear(400, 300)\n self.layer_6 = nn.Linear(300, 1)\n\n def forward(self, x, u):\n xu = torch.cat([x, u], 1)\n # Forward-Propagation on the first Critic Neural Network\n x1 = F.relu(self.layer_1(xu))\n x1 = F.relu(self.layer_2(x1))\n x1 = self.layer_3(x1)\n # Forward-Propagation on the second Critic Neural Network\n x2 = F.relu(self.layer_4(xu))\n x2 = F.relu(self.layer_5(x2))\n x2 = self.layer_6(x2)\n return x1, x2\n\n def Q1(self, x, u):\n xu = torch.cat([x, u], 1)\n x1 = F.relu(self.layer_1(xu))\n x1 = F.relu(self.layer_2(x1))\n x1 = self.layer_3(x1)\n return x1\n\n# Selecting the device (CPU or GPU)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Building the whole Training Process into a class\n\nclass TD3(object):\n \n def __init__(self, state_dim, action_dim, max_action):\n self.actor = Actor(state_dim, action_dim, max_action).to(device)\n self.actor_target = Actor(state_dim, action_dim, max_action).to(device)\n self.actor_target.load_state_dict(self.actor.state_dict())\n self.actor_optimizer = torch.optim.Adam(self.actor.parameters())\n self.critic = Critic(state_dim, action_dim).to(device)\n self.critic_target = Critic(state_dim, action_dim).to(device)\n self.critic_target.load_state_dict(self.critic.state_dict())\n self.critic_optimizer = torch.optim.Adam(self.critic.parameters())\n self.max_action = max_action\n\n def select_action(self, state):\n state = torch.Tensor(state.reshape(1, -1)).to(device)\n return self.actor(state).cpu().data.numpy().flatten()\n\n def train(self, replay_buffer, iterations, batch_size=100, discount=0.99, tau=0.005, policy_noise=0.2, noise_clip=0.5, policy_freq=2):\n \n for it in range(iterations):\n \n # Step 4: We sample a batch of transitions (s, s’, a, r) from the memory\n batch_states, batch_next_states, batch_actions, batch_rewards, batch_dones = replay_buffer.sample(batch_size)\n state = torch.Tensor(batch_states).to(device)\n next_state = torch.Tensor(batch_next_states).to(device)\n action = torch.Tensor(batch_actions).to(device)\n reward = torch.Tensor(batch_rewards).to(device)\n done = torch.Tensor(batch_dones).to(device)\n \n # Step 5: From the next state s’, the Actor target plays the next action a’\n next_action = self.actor_target(next_state)\n \n # Step 6: We add Gaussian noise to this next action a’ and we clamp it in a range of values supported by the environment\n noise = torch.Tensor(batch_actions).data.normal_(0, policy_noise).to(device)\n noise = noise.clamp(-noise_clip, noise_clip)\n next_action = (next_action + noise).clamp(-self.max_action, self.max_action)\n \n # Step 7: The two Critic targets take each the couple (s’, a’) as input and return two Q-values Qt1(s’,a’) and Qt2(s’,a’) as outputs\n target_Q1, target_Q2 = self.critic_target(next_state, next_action)\n \n # Step 8: We keep the minimum of these two Q-values: min(Qt1, Qt2)\n target_Q = torch.min(target_Q1, target_Q2)\n \n # Step 9: We get the final target of the two Critic models, which is: Qt = r + γ * min(Qt1, Qt2), where γ is the discount factor\n target_Q = reward + ((1 - done) * discount * target_Q).detach()\n \n # Step 10: The two Critic models take each the couple (s, a) as input and return two Q-values Q1(s,a) and Q2(s,a) as outputs\n current_Q1, current_Q2 = self.critic(state, action)\n \n # Step 11: We compute the loss coming from the two Critic models: Critic Loss = MSE_Loss(Q1(s,a), Qt) + MSE_Loss(Q2(s,a), Qt)\n critic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q)\n \n # Step 12: We backpropagate this Critic loss and update the parameters of the two Critic models with a SGD optimizer\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n self.critic_optimizer.step()\n \n # Step 13: Once every two iterations, we update our Actor model by performing gradient ascent on the output of the first Critic model\n if it % policy_freq == 0:\n actor_loss = -self.critic.Q1(state, self.actor(state)).mean()\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n \n # Step 14: Still once every two iterations, we update the weights of the Actor target by polyak averaging\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n \n # Step 15: Still once every two iterations, we update the weights of the Critic target by polyak averaging\n for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\n target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)\n \n # Making a save method to save a trained model\n def save(self, filename, directory):\n torch.save(self.actor.state_dict(), '%s/%s_actor.pth' % (directory, filename))\n torch.save(self.critic.state_dict(), '%s/%s_critic.pth' % (directory, filename))\n \n # Making a load method to load a pre-trained model\n def load(self, filename, directory):\n self.actor.load_state_dict(torch.load('%s/%s_actor.pth' % (directory, filename)))\n self.critic.load_state_dict(torch.load('%s/%s_critic.pth' % (directory, filename)))\n\ndef evaluate_policy(policy, eval_episodes=10):\n avg_reward = 0.\n for _ in range(eval_episodes):\n obs = env.reset()\n done = False\n while not done:\n action = policy.select_action(np.array(obs))\n obs, reward, done, _ = env.step(action)\n avg_reward += reward\n avg_reward /= eval_episodes\n print (\"---------------------------------------\")\n print (\"Average Reward over the Evaluation Step: %f\" % (avg_reward))\n print (\"---------------------------------------\")\n return avg_reward\n\nenv_name = \"AntBulletEnv-v0\"\nseed = 0\n\nfile_name = \"%s_%s_%s\" % (\"TD3\", env_name, str(seed))\nprint (\"---------------------------------------\")\nprint (\"Settings: %s\" % (file_name))\nprint (\"---------------------------------------\")\n\neval_episodes = 10\nsave_env_vid = True\nenv = gym.make(env_name)\nmax_episode_steps = env._max_episode_steps\nif save_env_vid:\n env = wrappers.Monitor(env, monitor_dir, force = True)\n env.reset()\nenv.seed(seed)\ntorch.manual_seed(seed)\nnp.random.seed(seed)\nstate_dim = env.observation_space.shape[0]\naction_dim = env.action_space.shape[0]\nmax_action = float(env.action_space.high[0])\npolicy = TD3(state_dim, action_dim, max_action)\npolicy.load(file_name, './pytorch_models/')\n_ = evaluate_policy(policy, eval_episodes=eval_episodes)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d0744b8038ea9bb9f24eae93bb67d615152649ea
18,209
ipynb
Jupyter Notebook
udacity/data-scientist-nanodegree/sparkify/.ipynb_checkpoints/web_pred-checkpoint.ipynb
thomasrobertz/mooc
cb87365bfcbe8ccf972f36d70a251c73b3c15a7b
[ "MIT" ]
null
null
null
udacity/data-scientist-nanodegree/sparkify/.ipynb_checkpoints/web_pred-checkpoint.ipynb
thomasrobertz/mooc
cb87365bfcbe8ccf972f36d70a251c73b3c15a7b
[ "MIT" ]
13
2021-12-14T20:59:34.000Z
2022-03-02T11:09:34.000Z
udacity/data-scientist-nanodegree/sparkify/.ipynb_checkpoints/web_pred-checkpoint.ipynb
thomasrobertz/mooc
cb87365bfcbe8ccf972f36d70a251c73b3c15a7b
[ "MIT" ]
1
2020-08-20T12:53:43.000Z
2020-08-20T12:53:43.000Z
48.557333
1,653
0.514581
[ [ [ "# Web predictions\n\nThe purpose of this notebook is to experiment with making predictions from \"raw\" accumulated user values, that\ncould for instance be user input from a web form.", "_____no_output_____" ] ], [ [ "import findspark\nfindspark.init()\nfindspark.find()\n\nimport pyspark\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SparkSession\nconf = pyspark.SparkConf().setAppName('sparkify-capstone-web').setMaster('local')\nsc = pyspark.SparkContext(conf=conf)\nspark = SparkSession(sc)\n\nfrom pyspark.ml.classification import GBTClassifier\nfrom pyspark.ml.classification import GBTClassificationModel\nfrom pyspark.ml.feature import VectorAssembler", "_____no_output_____" ], [ "transformedPath = \"out/transformed.parquet\"\npredictionsPath = \"out/predictions.parquet\"\ndf_transformed = spark.read.parquet(transformedPath)\ndf_predictions = spark.read.parquet(predictionsPath)\nmodel = GBTClassificationModel.load(\"out/model\")", "_____no_output_____" ], [ "zeros = df_predictions.filter(df_predictions[\"prediction\"] == 0)\nones = df_predictions.filter(df_predictions[\"prediction\"] == 1)\nzerosCount = zeros.count()\nonesCount = ones.count()\nprint(\"Ones: {}, Zeros: {}\".format(onesCount, zerosCount))\nprint(onesCount / zerosCount * 100)", "Ones: 93, Zeros: 355\n26.197183098591548\n" ], [ "usersPredictedToChurn = df_predictions.filter(df_predictions[\"prediction\"] == 1).take(5)", "_____no_output_____" ], [ "for row in usersPredictedToChurn:\n print(int(row[\"userId\"]))", "85\n296\n100003\n200021\n100042\n" ], [ "df_transformed.show()", "+------+-----+-----------+------------+-------------+---------------+------------+-------------+-----------------+---------------+\n|userId|churn|level_index|gender_index|thumbs_up_sum|thumbs_down_sum|nextsong_sum|downgrade_sum| length_sum|sessionId_count|\n+------+-----+-----------+------------+-------------+---------------+------------+-------------+-----------------+---------------+\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 1.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 1.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 1.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 1.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n| 93| 0| 0.0| 0.0| 90| 12| 1628| 16|412840.6919200001| 16|\n+------+-----+-----------+------------+-------------+---------------+------------+-------------+-----------------+---------------+\nonly showing top 20 rows\n\n" ], [ "df_predictions.show()", "+----------+--------+\n|prediction| userId|\n+----------+--------+\n| 0.0| 148.0|\n| 0.0|200049.0|\n| 0.0|300040.0|\n| 1.0| 85.0|\n| 0.0| 137.0|\n| 0.0| 251.0|\n| 0.0|200031.0|\n| 0.0|300044.0|\n| 0.0| 65.0|\n| 0.0|200001.0|\n| 0.0| 53.0|\n| 0.0| 255.0|\n| 0.0| 133.0|\n| 1.0| 296.0|\n| 1.0|100003.0|\n| 1.0|200021.0|\n| 0.0| 78.0|\n| 0.0|100007.0|\n| 1.0|100042.0|\n| 0.0|100035.0|\n+----------+--------+\nonly showing top 20 rows\n\n" ], [ "# 1 300044\n# 0 251\n\n# Select the prediction of a user as value\npred = df_predictions[df_predictions[\"userId\"] == 78].select(\"prediction\").collect()[0][0]", "_____no_output_____" ], [ "pred", "_____no_output_____" ], [ "# From a query that could be entered in a web form, create a prediction\n\n# Query from web\nquery = \"1.0,0.0,10,4,307,0,76200,10\"\n\n# Split to values\nvalues = query.split(\",\")\n\n# Prepare dictionary for feature dataframe from web form values\nfeatures_dict = [{\n \"level_index\": float(values[0]),\n \"gender_index\": float(values[1]), \n \"thumbs_up_sum\": int(values[2]),\n \"thumbs_down_sum\": int(values[3]),\n \"nextsong_sum\": int(values[4]),\n \"downgrade_sum\": int(values[5]),\n \"length_sum\": float(values[6]),\n \"sessionId_count\": int(values[7]),\n }]\n\n# Create a user row to use in VectorAssembler\ndf_user_row = spark.createDataFrame(features_dict)\n\n# Create feature dataframe with VectorAssembler\ndf_features = VectorAssembler(inputCols = \\\n [\"level_index\", \"gender_index\", \"thumbs_up_sum\", \"thumbs_down_sum\", \\\n \"nextsong_sum\", \"downgrade_sum\", \"length_sum\", \"sessionId_count\"], \\\n outputCol = \"features\").transform(df_user_row)\n\n# Select features\ndf_features = df_features.select(\"features\")\n\n# Predict on model\nprediction = model.transform(df_features)", "C:\\dev\\runtimes\\spark-2.4.6-bin-hadoop2.7\\python\\pyspark\\sql\\session.py:346: UserWarning: inferring schema from dict is deprecated,please use pyspark.sql.Row instead\n warnings.warn(\"inferring schema from dict is deprecated,\"\n" ], [ "# Show result\nprediction.show()", "+--------------------+--------------------+--------------------+----------+\n| features| rawPrediction| probability|prediction|\n+--------------------+--------------------+--------------------+----------+\n|[1.0,0.0,10.0,4.0...|[1.73699945213100...|[0.96993883589948...| 0.0|\n+--------------------+--------------------+--------------------+----------+\n\n" ], [ "prediction.select(\"prediction\").collect()[0][0]", "_____no_output_____" ], [ "# Output the notebook to an html file\nfrom subprocess import call\ncall(['python', '-m', 'nbconvert', 'web_pred.ipynb'])", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d074546689fcd8b8ef97ec0a032cffaebed42120
139,198
ipynb
Jupyter Notebook
courses/modsim2018/matheuspiquini/Lecture11.ipynb
MatheusKP/bmc
5c9c426eeb49b2b686d2da9e5ac092e695428345
[ "MIT" ]
null
null
null
courses/modsim2018/matheuspiquini/Lecture11.ipynb
MatheusKP/bmc
5c9c426eeb49b2b686d2da9e5ac092e695428345
[ "MIT" ]
null
null
null
courses/modsim2018/matheuspiquini/Lecture11.ipynb
MatheusKP/bmc
5c9c426eeb49b2b686d2da9e5ac092e695428345
[ "MIT" ]
null
null
null
71.788551
31,997
0.693911
[ [ [ "# Lecture 9 - Motor Control\n### Introduction to modeling and simulation of human movement\nhttps://github.com/BMClab/bmc/blob/master/courses/ModSim2018.md", "_____no_output_____" ], [ "* In class:", "_____no_output_____" ] ], [ [ "import numpy as np\n#import pandas as pd\n#import pylab as pl\nimport matplotlib.pyplot as plt\nimport math\n\n%matplotlib notebook", "_____no_output_____" ] ], [ [ "### Muscle properties", "_____no_output_____" ] ], [ [ "Lslack = .223\nUmax = .04\nLce_o = .093 #optmal l\nwidth = .63\nFmax = 3000\na = .25\nb = .25*10", "_____no_output_____" ] ], [ [ "### Initial conditions", "_____no_output_____" ] ], [ [ "LceNorm = .087/Lce_o\nt0 = 0\ntf = 2.99\nh = 1e-3\nu = 1\na = 0", "_____no_output_____" ], [ "t = np.arange(t0,tf,h)\nF = np.empty(t.shape)\nFkpe = np.empty(t.shape)\nFiberLength = np.empty(t.shape)\nTendonLength = np.empty(t.shape)\nU = np.arange(t0,1,h)", "_____no_output_____" ], [ "## Funcoes", "_____no_output_____" ], [ "def computeTendonForce(LseeNorm, Lce_o, Lslack):\n '''\n Compute Tendon Length\n \n Input:\n \n LseeNorm - Normalized Tendon Length\n \n Lsalck - slack length of the tendon (non normalized)\n \n Lce_o - Optimal length of the fiber\n \n Output:\n \n FTendonNorm - Force on the tendon normalized\n '''\n \n Umax = 0.04\n if LseeNorm<(Lslack/Lce_o): \n FTendonNorm = 0\n else: \n FTendonNorm = ((LseeNorm-Lslack/Lce_o)/(Umax*Lslack/Lce_o))**2\n \n return FTendonNorm", "_____no_output_____" ], [ "def computeParallelElementForce (LceNorm):\n Umax = 1\n if LceNorm<1:\n FkpeNorm = 0\n else: \n FkpeNorm = ((LceNorm-1)/(Umax))**2\n #lce_o/Lce_o = 1 (normalizado)\n \n return FkpeNorm", "_____no_output_____" ], [ "def computeForceLengthCurve(LceNorm):\n width = 0.63\n FLNorm = max([0, (1-((LceNorm-1)/width)**2)])\n return FLNorm", "_____no_output_____" ], [ "def computeActivation(a, u, h):\n act = 0.015\n deact = 0.05\n \n if u>a:\n T = act*(0.4+(1.5*a))\n else:\n T = deact/(0.5+(1.5*a))\n \n a += h*((u-a)/T)\n \n return a", "_____no_output_____" ], [ "def computeContractileElementDerivative(FLNorm, FCENorm, a):\n #calculate CE velocity from Hill's equation\n a1 = .25\n b = .25*10\n \n Fmlen = 1.8\n Vmax = 8\n \n \n if FCENorm > a*FLNorm:\n B = ((2+2/a1)*(FLNorm*Fmlen-FCENorm))/(Fmlen-1)\n \n LceNormdot = (0.75+0.75*a)*Vmax*((FCENorm-FLNorm)/B)\n \n else:\n B = FLNorm + (FCENorm/a1)\n \n LceNormdot = (0.75+0.75*a)*Vmax*((FCENorm-FLNorm)/B)\n \n return LceNormdot\n ", "_____no_output_____" ], [ "def computeContractileElementForce(FTendonNorm, FkpeNorm):\n FCENorm = FTendonNorm - FkpeNorm\n \n return FCENorm", "_____no_output_____" ], [ "def ComputeTendonLength(Lm, Lce_o, LceNorm):\n LseeNorm = Lm/Lce_o - LceNorm\n return LseeNorm", "_____no_output_____" ] ], [ [ "## Simulation - Parallel", "_____no_output_____" ] ], [ [ "for i in range (len(t)):\n #ramp\n if t[i]<=1:\n Lm = 0.31\n elif t[i]>1 and t[i]<2:\n Lm = .31 - .04*(t[i]-1)\n #print(Lm)\n \n #####################################################################\n LseeNorm = (Lm/Lce_o) - LceNorm\n \n FTendonNorm = computeTendonForce(LseeNorm, Lce_o, Lslack)\n \n FkpeNorm = computeParallelElementForce(LceNorm)\n \n FLNorm = computeForceLengthCurve(LceNorm)\n \n FCENorm = computeContractileElementForce(FTendonNorm, FkpeNorm)\n \n LceNormdot = computeContractileElementDerivative(FLNorm,FCENorm, a)\n \n a = computeActivation(a, u, h)\n\n LceNorm += h*LceNormdot\n #####################################################################\n \n F[i] = FTendonNorm*Fmax\n FiberLength[i] = LceNorm*Lce_o\n TendonLength[i] = LseeNorm*Lce_o\n ", "_____no_output_____" ] ], [ [ "## Plot ", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(1, 1, figsize=(6,6), sharex=True)\n\nax.plot(t,F,c='red')\nplt.grid()\nplt.xlabel('time (s)')\nplt.ylabel('Force [N]')\n\n\n#ax.legend()", "_____no_output_____" ], [ "fig, ax = plt.subplots(1, 1, figsize=(6,6), sharex=True)\n\nax.plot(t,FiberLength, label = 'fibra')\nax.plot(t, TendonLength, label = 'tendao')\nax.plot(t,FiberLength + TendonLength, label = 'fibra + tendao')\nplt.grid()\nplt.legend(loc = 'best')\nplt.xlabel('time (s)')\nplt.ylabel('Length [m]')\nplt.tight_layout()\n\n#ax.legend()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d0746439b02db43d942afdd3c5fd8b9f4aa4b6ef
11,775
ipynb
Jupyter Notebook
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
55cca13e004a2844bef1f6afd09338852c61e1f1
[ "BSD-3-Clause" ]
1
2020-08-27T18:06:10.000Z
2020-08-27T18:06:10.000Z
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
55cca13e004a2844bef1f6afd09338852c61e1f1
[ "BSD-3-Clause" ]
null
null
null
docs/source/emat.examples/GBNRTC/gbnrtc_fresh_boxes.ipynb
tlumip/tmip-emat
55cca13e004a2844bef1f6afd09338852c61e1f1
[ "BSD-3-Clause" ]
1
2020-08-06T07:36:21.000Z
2020-08-06T07:36:21.000Z
24.328512
135
0.470658
[ [ [ "import emat", "_____no_output_____" ] ], [ [ "Load a scope from a yaml file.", "_____no_output_____" ] ], [ [ "with open('gbnrtc_scope.yaml') as yf:\n for _ in range(100):\n print(yf.readline(), end=\"\")", "---\n# EMAT Scope Definition\n# \n\nscope:\n name: GBNRTC\n desc: EMAT Prototype using TransCAD\n\ninputs:\n\n ## UNCERTAINTIES ##\n\n Land Use - CBD Focus:\n ptype: exogenous uncertainty\n desc: Change in overall land use with greatest effect in CBD\n default: 1.0\n min: 0.82\n max: 1.37\n dist:\n name: pert\n rel_peak: 0.33\n gamma: 4\n corr: []\n\n Freeway Capacity:\n ptype: exogenous uncertainty\n desc: Change in freeway capacity due to Vehicle Technology\n default: 1.0\n min: 1.0\n max: 2.0\n dist:\n name: triangle\n rel_peak: 0.5\n corr: []\n \n Auto IVTT Sensitivity:\n ptype: exogenous uncertainty\n desc: Change in sensitivity to Auto travel time due to Vehicle Technology\n default: 1.0\n min: 0.75\n max: 1.0\n dist:\n name: triangle\n rel_peak: 0.5\n corr: []\n \n Shared Mobility:\n ptype: exogenous uncertainty\n desc: Change in vehicle availability to represent ubiquity of shared mobility\n default: 0\n min: 0\n max: 1.0\n dist:\n name: pert\n rel_peak: 0.5\n gamma: 4\n corr: []\n \n ## LEVERS ## \n \n Kensington Decommissioning:\n ptype: policy lever\n dtype: bool\n desc: Change Kensington facility type from divided highway to arterial\n default: 0\n min: 0 \n max: 1\n dist: binary\n corr: []\n \n LRT Extension:\n ptype: policy lever\n dtype: bool\n desc: Amherst LRT extended to UB campus\n default: 0\n min: 0 \n max: 1\n dist: binary\n corr: []\n\n\n# Performance Measures -------------------------------------------------------\n#\n\noutputs:\n\n Region-wide VMT:\n metamodeltype: log\n kind: minimize\n Interstate + Expressway + Ramp/Connector VMT:\n metamodeltype: log\n kind: minimize\n Major and Minor Arterials VMT:\n metamodeltype: log\n kind: minimize\n Total Auto VMT:\n metamodeltype: log\n kind: minimize\n Total Truck VMT:\n metamodeltype: log\n" ], [ "scope = emat.Scope('gbnrtc_scope.yaml')", "_____no_output_____" ], [ "scope", "_____no_output_____" ] ], [ [ "Create a brand new set of `Boxes`.", "_____no_output_____" ] ], [ [ "boxes = emat.Boxes(scope=scope)", "_____no_output_____" ] ], [ [ "Define a new top-level box (i.e. a box with no parents to inherit from).", "_____no_output_____" ] ], [ [ "box_1 = emat.Box(name='High Population Growth', scope=scope)", "_____no_output_____" ] ], [ [ "Add a lower bound for population growth, to ensure the include values are all \"high\".", "_____no_output_____" ] ], [ [ "box_1.set_lower_bound('Land Use - CBD Focus', 1.0)", "_____no_output_____" ] ], [ [ "Add some things as \"relevant features\" that we are interested in analyzing,\neven though we do not set bounds on them (yet).", "_____no_output_____" ] ], [ [ "box_1.relevant_features.add('Total LRT Boardings')\nbox_1.relevant_features.add('Downtown to Airport Travel Time')\nbox_1.relevant_features.add('Peak Transit Share')\nbox_1.relevant_features.add('AM Trip Time (minutes)')\nbox_1.relevant_features.add('AM Trip Length (miles)')\nbox_1.relevant_features.add('Region-wide VMT')\nbox_1.relevant_features.add('Total Transit Boardings')\nbox_1.relevant_features.add('Corridor Kensington Daily VMT')", "_____no_output_____" ], [ "box_1", "_____no_output_____" ] ], [ [ "Define a new lower level box, which will inherit from the top level box we just created.", "_____no_output_____" ] ], [ [ "box_2 = emat.Box(name='Automated Vehicles', scope=scope, parent='High Population Growth')", "_____no_output_____" ] ], [ [ "Set some thresholds on this lower level box.", "_____no_output_____" ] ], [ [ "box_2.set_lower_bound('Freeway Capacity', 1.25)\nbox_2.set_upper_bound('Auto IVTT Sensitivity', 0.9)", "_____no_output_____" ], [ "box_2", "_____no_output_____" ], [ "box_2.parent_box_name", "_____no_output_____" ] ], [ [ "So far, the individual boxes we created are just loose boxes. To connect them, we need to add them to the master `Boxes` object.", "_____no_output_____" ] ], [ [ "boxes.add(box_1)\nboxes.add(box_2)", "_____no_output_____" ] ], [ [ "We can check on what named boxes are in a `Boxes` object with the `plain_names` method,\nwhich just gives the names, or the `fancy_names` method, which adds some icons\nto help indicate the hierarchy.", "_____no_output_____" ] ], [ [ "boxes.plain_names()", "_____no_output_____" ], [ "boxes.fancy_names()", "_____no_output_____" ] ], [ [ "Now that the boxes are linked together in a `Boxes` object, we can use the `get_chain` method to aggregate\nthe attributes of any box along with all parents in the chain.", "_____no_output_____" ] ], [ [ "boxes.get_chain('Automated Vehicles')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d074667f00ccf2eb70594c2cac53afd6394e973e
249,868
ipynb
Jupyter Notebook
src/time_series_modelling.ipynb
jsleslie/Ohare_taxi_demand
6007918bffb1e8b56198de4d942760e7f1007808
[ "MIT" ]
1
2020-04-14T19:38:36.000Z
2020-04-14T19:38:36.000Z
src/time_series_modelling.ipynb
jsleslie/Ohare_taxi_demand
6007918bffb1e8b56198de4d942760e7f1007808
[ "MIT" ]
17
2020-03-02T01:59:22.000Z
2021-10-18T23:00:12.000Z
src/time_series_modelling.ipynb
jsleslie/Ohare_taxi_demand
6007918bffb1e8b56198de4d942760e7f1007808
[ "MIT" ]
1
2020-02-24T05:48:25.000Z
2020-02-24T05:48:25.000Z
147.154299
187,576
0.818868
[ [ [ "# Time Series analysis of O'hare taxi rides data", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.model_selection import TimeSeriesSplit, cross_validate, GridSearchCV\npd.set_option('display.max_rows', 6)\nplt.style.use('ggplot')\nplt.rcParams.update({'font.size': 16,\n 'axes.labelweight': 'bold',\n 'figure.figsize': (8,6)})\nfrom mealprep.mealprep import find_missing_ingredients\n# pd.set_option('display.max_colwidth', None)\npd.set_option('display.max_rows', None)\nimport pickle", "_____no_output_____" ], [ "ORD_df = pd.read_csv('../data/ORD_train.csv').drop(columns=['Unnamed: 0', 'Unnamed: 0.1'])", "_____no_output_____" ], [ "ORD_df", "_____no_output_____" ] ], [ [ "## Tom's functions", "_____no_output_____" ] ], [ [ "# Custom functions\ndef lag_df(df, lag, cols):\n return df.assign(**{f\"{col}-{n}\": df[col].shift(n) for n in range(1, lag + 1) for col in cols})\n\n\ndef ts_predict(input_data, model, n=20, responses=1):\n predictions = []\n n_features = input_data.size\n for _ in range(n):\n\n predictions = np.append(predictions,\n model.predict(input_data.reshape(1, -1))) # make prediction\n input_data = np.append(predictions[-responses:],\n input_data[:n_features-responses]) # new input data\n return predictions.reshape((-1, responses))\n\n\ndef plot_ts(ax, df_train, df_test, predictions, xlim, response_cols):\n col_cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']\n for i, col in enumerate(response_cols):\n ax.plot(df_train[col], '-', c=col_cycle[i], label = f'Train {col}')\n ax.plot(df_test[col], '--', c=col_cycle[i], label = f'Validation {col}')\n ax.plot(np.arange(df_train.index[-1] + 1,\n df_train.index[-1] + 1 + len(predictions)),\n predictions[:,i], c=col_cycle[-i-2], label = f'Prediction {col}')\n ax.set_xlim(0, xlim+1)\n ax.set_title(f\"Train Shape = {len(df_train)}, Validation Shape = {len(df_test)}\",\n fontsize=16)\n ax.set_ylabel(df_train.columns[0])\n\n \ndef plot_forecast(ax, df_train, predictions, xlim, response_cols):\n col_cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']\n for i, col in enumerate(response_cols):\n ax.plot(df_train[col], '-', c=col_cycle[i], label = f'Train {col}')\n ax.plot(np.arange(df_train.index[-1] + 1,\n df_train.index[-1] + 1 + len(predictions)),\n predictions[:,i], '-', c=col_cycle[-i-2], label = f'Prediction {col}')\n ax.set_xlim(0, xlim+len(predictions))\n ax.set_title(f\"{len(predictions)}-step forecast\",\n fontsize=16)\n ax.set_ylabel(response_cols)\n \ndef create_rolling_features(df, columns, windows=[6, 12]):\n for window in windows:\n df[\"rolling_mean_\" + str(window)] = df[columns].rolling(window=window).mean()\n df[\"rolling_std_\" + str(window)] = df[columns].rolling(window=window).std()\n df[\"rolling_var_\" + str(window)] = df[columns].rolling(window=window).var()\n df[\"rolling_min_\" + str(window)] = df[columns].rolling(window=window).min()\n df[\"rolling_max_\" + str(window)] = df[columns].rolling(window=window).max()\n df[\"rolling_min_max_ratio_\" + str(window)] = df[\"rolling_min_\" + str(window)] / df[\"rolling_max_\" + str(window)]\n df[\"rolling_min_max_diff_\" + str(window)] = df[\"rolling_max_\" + str(window)] - df[\"rolling_min_\" + str(window)]\n\n df = df.replace([np.inf, -np.inf], np.nan) \n df.fillna(0, inplace=True)\n return df", "_____no_output_____" ], [ "\nlag = 3\nORD_train_lag = lag_df(ORD_df, lag=lag, cols=['seats']).dropna()", "_____no_output_____" ], [ "ORD_train_lag", "_____no_output_____" ], [ "find_missing_ingredients(ORD_train_lag)", "_____no_output_____" ], [ "lag = 3 # you can vary the number of lagged features in the model\nn_splits = 5 # you can vary the number of train/validation splits\nresponse_col = ['rides']\n# df_lag = lag_df(df, lag, response_col).dropna()\ntscv = TimeSeriesSplit(n_splits=n_splits) # define the splitter\nmodel = RandomForestRegressor() # define the model\n\ncv = cross_validate(model,\n X = ORD_train_lag.drop(columns=response_col),\n y = ORD_train_lag[response_col[0]],\n scoring =('r2', 'neg_mean_squared_error'),\n cv=tscv,\n return_train_score=True)\n\n\n\n\n# pd.DataFrame({'split': range(n_splits),\n# 'train_r2': cv['train_score'],\n# 'train_negrmse': cv['train_']\n# 'validation_r2': cv['test_score']}).set_index('split')", "_____no_output_____" ], [ "pd.DataFrame(cv)", "_____no_output_____" ], [ "fig, ax = plt.subplots(n_splits, 1, figsize=(8,4*n_splits))\nfor i, (train_index, test_index) in enumerate(tscv.split(ORD_train_lag)):\n df_train, df_test = ORD_train_lag.iloc[train_index], ORD_train_lag.iloc[test_index]\n model = RandomForestRegressor().fit(df_train.drop(columns=response_col),\n df_train[response_col[0]]) # train model\n # Prediction loop\n predictions = model.predict(df_test.drop(columns=response_col))[:,None]\n\n # Plot\n plot_ts(ax[i], df_train, df_test, predictions, xlim=ORD_train_lag.index[-1], response_cols=response_col)\nax[0].legend(facecolor='w')\nax[i].set_xlabel('time')\nfig.tight_layout()", "_____no_output_____" ], [ "lag = 3 # you can vary the number of lagged features in the model\nn_splits = 3 # you can vary the number of train/validation splits\nresponse_col = ['rides']\n# df_lag = lag_df(df, lag, response_col).dropna()\ntscv = TimeSeriesSplit(n_splits=n_splits) # define the splitter\nmodel = RandomForestRegressor() # define the model\nparam_grid = {'n_estimators': [50, 100, 150, 200],\n 'max_depth': [10,25,50,100, None]}\n\nX = ORD_train_lag.drop(columns=response_col)\ny = ORD_train_lag[response_col[0]]\n\n\ngcv = GridSearchCV(model,\n param_grid = param_grid,\n# X = ORD_train_lag.drop(columns=response_col),\n# y = ORD_train_lag[response_col[0]],\n scoring ='neg_mean_squared_error',\n cv=tscv,\n return_train_score=True)\n\n\ngcv.fit(X,y)\n\n# pd.DataFrame({'split': range(n_splits),\n# 'train_r2': cv['train_score'],\n# 'train_negrmse': cv['train_']\n# 'validation_r2': cv['test_score']}).set_index('split')", "_____no_output_____" ], [ "gcv.score(X,y)", "_____no_output_____" ], [ "filename = 'grid_search_model_1.sav'\npickle.dump(gcv, open(filename, 'wb'))", "_____no_output_____" ], [ "A = list(ORD_train_lag.columns)\nA.remove('rides')", "_____no_output_____" ], [ "pd.DataFrame({'columns' : A, 'importance' : gcv.best_estimator_.feature_importances_}).sort_values('importance', ascending=False)", "_____no_output_____" ], [ "gcv.best_params_", "_____no_output_____" ], [ "pd.DataFrame(gcv.cv_results_)", "_____no_output_____" ], [ "gcv.estimator.best_", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d07479138a6fe33267adc062aa2ec86cf01c1101
20,779
ipynb
Jupyter Notebook
Labs/Lab 4/Lesson04-numpy.ipynb
cvlpieas/CIS428-ICV
2e801bafebe381af9d050c329d72afefb296df36
[ "MIT" ]
2
2020-10-03T16:57:32.000Z
2020-10-11T06:06:39.000Z
Lessons/Lesson04-numpy.ipynb
cvlpieas/ADLCVP
2cd454c1f009c6bc8bb08f76a055e8867724b7ce
[ "MIT" ]
null
null
null
Lessons/Lesson04-numpy.ipynb
cvlpieas/ADLCVP
2cd454c1f009c6bc8bb08f76a055e8867724b7ce
[ "MIT" ]
3
2021-05-10T10:10:42.000Z
2021-06-17T04:54:13.000Z
17.609322
176
0.407671
[ [ [ "# Lesson 04: Numpy", "_____no_output_____" ], [ "- Used for working with tensors\n- Provides vectors, matrices, and tensors\n- Provides mathematical functions that operate on vectors, matrices, and tensors\n- Implemented in Fortran and C in the backend", "_____no_output_____" ] ], [ [ "import numpy as np", "_____no_output_____" ] ], [ [ "## Making Arrays", "_____no_output_____" ] ], [ [ "arr = np.array([1, 2, 3])", "_____no_output_____" ], [ "print(arr, type(arr), arr.shape, arr.dtype, arr.ndim)", "[1 2 3] <class 'numpy.ndarray'> (3,) int64 1\n" ], [ "matrix = np.array(\n [[1, 2, 3],\n [4, 5, 6.2]]\n)", "_____no_output_____" ], [ "print(matrix, type(matrix), matrix.shape, matrix.dtype, matrix.ndim)", "[[1. 2. 3. ]\n [4. 5. 6.2]] <class 'numpy.ndarray'> (2, 3) float64 2\n" ], [ "a = np.zeros((10, 2))\nprint(a)", "[[0. 0.]\n [0. 0.]\n [0. 0.]\n [0. 0.]\n [0. 0.]\n [0. 0.]\n [0. 0.]\n [0. 0.]\n [0. 0.]\n [0. 0.]]\n" ], [ "a = np.ones((4, 5))\nprint(a)", "[[1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]]\n" ], [ "a = np.full((2, 3, 5), 6)\nprint(a)", "[[[6 6 6 6 6]\n [6 6 6 6 6]\n [6 6 6 6 6]]\n\n [[6 6 6 6 6]\n [6 6 6 6 6]\n [6 6 6 6 6]]]\n" ], [ "a = np.eye(4)\nprint(a)", "[[1. 0. 0. 0.]\n [0. 1. 0. 0.]\n [0. 0. 1. 0.]\n [0. 0. 0. 1.]]\n" ], [ "a = np.random.random((5, 5))\nprint(a)", "[[0.94118745 0.22994581 0.75183424 0.3433619 0.53614551]\n [0.4701853 0.68700713 0.3685086 0.19023418 0.17094098]\n [0.96813951 0.00628098 0.02295652 0.9007116 0.03263926]\n [0.56018717 0.13823581 0.71362452 0.57653406 0.9263221 ]\n [0.22776242 0.92652569 0.04206205 0.13036483 0.10911229]]\n" ] ], [ [ "## Indexing", "_____no_output_____" ] ], [ [ "arr = np.array([\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15]\n])\nprint(arr)", "[[ 1 2 3 4 5]\n [ 6 7 8 9 10]\n [11 12 13 14 15]]\n" ] ], [ [ "The indexing format is: [rows , columns]\n\nYou can then slice the individual dimension as follows: [start : end , start : end]", "_____no_output_____" ] ], [ [ "print(arr[1:, 2:4])", "[[ 8 9]\n [13 14]]\n" ], [ "a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\nprint(a[ [0, 1, 2, 3], [1, 0, 2, 0] ])\n\nprint(a[0, 1], a[1, 0], a[2, 2], a[3, 0])\nprint(np.array([a[0, 1], a[1, 0], a[2, 2], a[3, 0]]))", "[ 2 4 9 10]\n2 4 9 10\n[ 2 4 9 10]\n" ], [ "b = np.array([1, 0, 2, 0])\n\nprint(a[np.arange(4), b])", "[ 2 4 9 10]\n" ], [ "a[np.arange(4), b] += 7\n\nprint(a)", "[[ 1 9 3]\n [11 5 6]\n [ 7 8 16]\n [17 11 12]]\n" ], [ "a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n\nbool_a = (a > 5)\n\nprint(bool_a)", "[[False False False]\n [False False True]\n [ True True True]\n [ True True True]]\n" ], [ "print(a[bool_a])", "[ 6 7 8 9 10 11 12]\n" ], [ "print(a[a>7])", "[ 8 9 10 11 12]\n" ] ], [ [ "## Data Types", "_____no_output_____" ] ], [ [ "b = np.array([1, 2, 3], dtype=np.float64)\nprint(b.dtype)", "float64\n" ] ], [ [ "https://numpy.org/doc/stable/reference/arrays.dtypes.html", "_____no_output_____" ], [ "## Operations", "_____no_output_____" ] ], [ [ "x = np.array([\n [1, 2],\n [3, 4]\n])\ny = np.array([\n [5, 6],\n [7, 8]\n])", "_____no_output_____" ], [ "print(x, x.shape)\nprint(y, y.shape)", "[[1 2]\n [3 4]] (2, 2)\n[[5 6]\n [7 8]] (2, 2)\n" ], [ "print(x + y)\nprint(np.add(x, y))", "[[ 6 8]\n [10 12]]\n[[ 6 8]\n [10 12]]\n" ], [ "print(x - y)\nprint(np.subtract(x, y))", "[[-4 -4]\n [-4 -4]]\n[[-4 -4]\n [-4 -4]]\n" ], [ "print(x * y)\nprint(np.multiply(x, y))", "[[ 5 12]\n [21 32]]\n[[ 5 12]\n [21 32]]\n" ], [ "print(x / y)\nprint(np.divide(x, y))", "[[0.2 0.33333333]\n [0.42857143 0.5 ]]\n[[0.2 0.33333333]\n [0.42857143 0.5 ]]\n" ] ], [ [ "### Matrix Multiplication", "_____no_output_____" ] ], [ [ "w = np.array([2, 4])\nv = np.array([4, 6])", "_____no_output_____" ], [ "print(x)\nprint(y)\nprint(w)\nprint(v)", "[[1 2]\n [3 4]]\n[[5 6]\n [7 8]]\n[2 4]\n[4 6]\n" ] ], [ [ "#### Vector-vector multiplication", "_____no_output_____" ] ], [ [ "print(v.dot(w))\nprint(np.dot(v, w))", "32\n32\n" ] ], [ [ "#### Matrix-vector multiplication", "_____no_output_____" ] ], [ [ "print(x.dot(w))", "[10 22]\n" ] ], [ [ "#### Matrix multiplication", "_____no_output_____" ] ], [ [ "print(x.dot(y))\nprint(np.dot(x, y))", "[[19 22]\n [43 50]]\n[[19 22]\n [43 50]]\n" ] ], [ [ "### Transpose", "_____no_output_____" ] ], [ [ "print(x)\n\nprint(x.T)", "[[1 2]\n [3 4]]\n[[1 3]\n [2 4]]\n" ] ], [ [ "http://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html", "_____no_output_____" ], [ "### Other Operations", "_____no_output_____" ] ], [ [ "print(x)\n\nprint(np.sum(x))\nprint(np.sum(x, axis=0))\nprint(np.sum(x, axis=1))", "[[1 2]\n [3 4]]\n10\n[4 6]\n[3 7]\n" ] ], [ [ "More array operations are listed here:\n\nhttp://docs.scipy.org/doc/numpy/reference/routines.math.html", "_____no_output_____" ], [ "## Broadcasting", "_____no_output_____" ], [ "Broadcasting allows Numpy to work with arrays of different shapes. Operations which would have required loops can now be done without them hence speeding up your program.", "_____no_output_____" ] ], [ [ "x = np.array([\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n [10, 11, 12],\n [13, 14, 15],\n [16, 17, 18],\n])\nprint(x, x.shape)", "[[ 1 2 3]\n [ 4 5 6]\n [ 7 8 9]\n [10 11 12]\n [13 14 15]\n [16 17 18]] (6, 3)\n" ], [ "y = np.array([1, 2, 3])\nprint(y, y.shape)", "[1 2 3] (3,)\n" ] ], [ [ "### Loop Approach", "_____no_output_____" ] ], [ [ "z = np.empty_like(x)\nprint(z, z.shape)", "[[ 93990358130640 0 140093575578096]\n [140093577442672 140093574520368 140093576112880]\n [140093577127280 140093577057072 140093575577648]\n [140093577543088 140093571607216 140093576757360]\n [140093575402288 140093576757424 140093577021872]\n [140093575091648 140093575610944 140093575612672]] (6, 3)\n" ], [ "for i in range(x.shape[0]):\n z[i, :] = x[i, :] + y\n\nprint(z)", "[[ 2 4 6]\n [ 5 7 9]\n [ 8 10 12]\n [11 13 15]\n [14 16 18]\n [17 19 21]]\n" ] ], [ [ "### Tile Approach", "_____no_output_____" ] ], [ [ "yy = np.tile(y, (6, 1))\nprint(yy, yy.shape)", "[[1 2 3]\n [1 2 3]\n [1 2 3]\n [1 2 3]\n [1 2 3]\n [1 2 3]] (6, 3)\n" ], [ "print(x + y)", "[[ 2 4 6]\n [ 5 7 9]\n [ 8 10 12]\n [11 13 15]\n [14 16 18]\n [17 19 21]]\n" ] ], [ [ "### Broadcasting Approach", "_____no_output_____" ] ], [ [ "print(x, x.shape)\nprint(y, y.shape)", "[[ 1 2 3]\n [ 4 5 6]\n [ 7 8 9]\n [10 11 12]\n [13 14 15]\n [16 17 18]] (6, 3)\n[1 2 3] (3,)\n" ], [ "print(x + y)", "[[ 2 4 6]\n [ 5 7 9]\n [ 8 10 12]\n [11 13 15]\n [14 16 18]\n [17 19 21]]\n" ] ], [ [ "- https://numpy.org/doc/stable/user/basics.broadcasting.html\n- http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc\n- http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs", "_____no_output_____" ], [ "## Reshape", "_____no_output_____" ] ], [ [ "x = np.array([\n [1, 2, 3],\n [4, 5, 6]\n])\n\ny = np.array([2, 2])\n\nprint(x, x.shape)\nprint(y, y.shape)", "[[1 2 3]\n [4 5 6]] (2, 3)\n[2 2] (2,)\n" ] ], [ [ "### Transpose Approach", "_____no_output_____" ] ], [ [ "xT = x.T\nprint(xT)", "[[1 4]\n [2 5]\n [3 6]]\n" ], [ "xTw = xT + y\nprint(xTw)", "[[3 6]\n [4 7]\n [5 8]]\n" ], [ "x = xTw.T\nprint(x)", "[[3 4 5]\n [6 7 8]]\n" ] ], [ [ "Transpose approach in one line", "_____no_output_____" ] ], [ [ "print( (x.T + y).T )", "[[3 4 5]\n [6 7 8]]\n" ] ], [ [ "### Reshape Approach", "_____no_output_____" ] ], [ [ "print(y, y.shape, y.ndim)\ny = np.reshape(y, (2, 1))\nprint(y, y.shape, y.ndim)", "[2 2] (2,) 1\n[[2]\n [2]] (2, 1) 2\n" ], [ "print(x + y)", "[[3 4 5]\n [6 7 8]]\n" ] ], [ [ "# Resources\n\n- http://docs.scipy.org/doc/numpy/reference/\n- https://numpy.org/doc/stable/user/absolute_beginners.html\n- https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_solutions.md", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d074814f6ab920fd3640418252f4d15271efa364
2,089
ipynb
Jupyter Notebook
samples/chromosome/Inspect_chromosome_model.ipynb
Andrew-M-Cox/Mask_RCNN
9e0249de1c5087ab267fe48e1f9ce698b4d7b4c4
[ "MIT" ]
null
null
null
samples/chromosome/Inspect_chromosome_model.ipynb
Andrew-M-Cox/Mask_RCNN
9e0249de1c5087ab267fe48e1f9ce698b4d7b4c4
[ "MIT" ]
null
null
null
samples/chromosome/Inspect_chromosome_model.ipynb
Andrew-M-Cox/Mask_RCNN
9e0249de1c5087ab267fe48e1f9ce698b4d7b4c4
[ "MIT" ]
null
null
null
22.223404
116
0.494974
[ [ [ "%load_ext tensorboard", "_____no_output_____" ], [ "import tensorflow as tf\nimport datetime", "_____no_output_____" ], [ "%tensorboard --logdir /Users/andrew/Dissertation/Mask_RCNN/logs/chromosome20200930T1005/", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
d07485f5c5cadb256bb41fe6c7a984957d2de7c7
4,437
ipynb
Jupyter Notebook
examples/local_jobs.ipynb
gretelai/gretel-python-client
6c868bb01b67601de2fafb9a95edbc6d60a7a7d9
[ "Apache-2.0" ]
23
2020-06-11T13:47:17.000Z
2022-03-03T03:13:24.000Z
examples/local_jobs.ipynb
gretelai/gretel-python-client
6c868bb01b67601de2fafb9a95edbc6d60a7a7d9
[ "Apache-2.0" ]
16
2020-06-23T18:25:47.000Z
2021-07-30T23:05:00.000Z
examples/local_jobs.ipynb
gretelai/gretel-python-client
6c868bb01b67601de2fafb9a95edbc6d60a7a7d9
[ "Apache-2.0" ]
4
2021-03-22T17:24:57.000Z
2021-07-27T08:28:25.000Z
35.496
124
0.41785
[ [ [ "import json\n\nimport yaml\nfrom smart_open import open\nimport pandas as pd\n\nfrom gretel_client import create_project, submit_docker_local\n\ndata_source = \"https://gretel-public-website.s3.us-west-2.amazonaws.com/datasets/USAdultIncome5k.csv\"\n\n# Policy to search for \"sensitive PII\" as defined by\n# https://www.experian.com/blogs/ask-experian/what-is-personally-identifiable-information/\nconfig = \"\"\"\nschema_version: 1.0\nmodels:\n - classify:\n data_source: \"_\"\n labels:\n - person_name\n - credit_card_number\n - phone_number\n - us_social_security_number\n - email_address\n\"\"\"\n", "_____no_output_____" ], [ "project = create_project()", "_____no_output_____" ], [ "# the following cell will create the classification model and \n# run a sample of the data set through the model. this sample\n# can be used to ensure the model is functioning correctly\n# before continuing.\nclassify = project.create_model_obj(\n model_config=yaml.safe_load(config),\n data_source=data_source\n)\n\nrun = submit_docker_local(classify, output_dir=\"tmp/\")", "_____no_output_____" ], [ "# review the sampled classification report\nreport = json.loads(open(\"tmp/report_json.json.gz\").read())\npd.DataFrame(report[\"metadata\"][\"fields\"])", "_____no_output_____" ], [ "# next let's classify the remaining records using the model\n# that was just created.\nclassify_records = classify.create_record_handler_obj(data_source=data_source)\n\nrun = submit_docker_local(\n classify_records,\n model_path=\"tmp/model.tar.gz\",\n output_dir=\"tmp/\"\n)", "_____no_output_____" ], [ "report = json.loads(open(\"tmp/report_json.json.gz\").read())\npd.DataFrame(report[\"metadata\"][\"fields\"])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
d074c6bb0b574d54de1729550f28f12d771d0db7
184,394
ipynb
Jupyter Notebook
notebook/Analise_Dados_Cheque.ipynb
victorblois/py_basico
1804c4909315a283d552be066107e40400c5a829
[ "MIT" ]
1
2020-05-11T22:22:54.000Z
2020-05-11T22:22:54.000Z
notebook/Analise_Dados_Cheque.ipynb
victorblois/py_basico
1804c4909315a283d552be066107e40400c5a829
[ "MIT" ]
null
null
null
notebook/Analise_Dados_Cheque.ipynb
victorblois/py_basico
1804c4909315a283d552be066107e40400c5a829
[ "MIT" ]
null
null
null
204.882222
20,724
0.899758
[ [ [ "import os\nimport pandas as pd", "_____no_output_____" ], [ "import os.path\ndef path_base(base_name):\n current_dir = os.path.abspath(os.path.join(os.getcwd()))\n print(current_dir)\n data_dir = current_dir.replace('notebook','data')\n print(data_dir)\n data_base = data_dir + '\\\\' + base_name\n print(data_base)\n return data_base", "_____no_output_____" ], [ "stats = pd.read_csv(path_base('db_analise_dados_cheque.csv'),converters={\"cheque\":float})", "C:\\MyGit\\py_basico\\notebook\nC:\\MyGit\\py_basico\\data\nC:\\MyGit\\py_basico\\data\\db_analise_dados_cheque.csv\n" ], [ "stats.head(4)", "_____no_output_____" ], [ "stats.tail(4)", "_____no_output_____" ], [ "stats.columns", "_____no_output_____" ], [ "stats.describe().transpose()", "_____no_output_____" ], [ "stats.cheque.describe()", "_____no_output_____" ], [ "stats.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 200 entries, 0 to 199\nData columns (total 6 columns):\ncheque 200 non-null float64\ntempo_no_cheque 200 non-null int64\nrelacionamento 200 non-null int64\nscore_serasa 200 non-null int64\nfatura_cartao 200 non-null float64\nultimo_default 200 non-null int64\ndtypes: float64(2), int64(4)\nmemory usage: 9.5 KB\n" ], [ "import matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nplt.rcParams['figure.figsize'] = 8,4\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "vis_cheque = sns.distplot(stats.cheque)", "_____no_output_____" ], [ "vis_cheque_1 = sns.boxplot(stats.cheque)\nstats.cheque.describe()", "_____no_output_____" ], [ "vis_tempo_no_cheque = sns.distplot(stats.tempo_no_cheque)", "_____no_output_____" ], [ "vis_tempo_no_cheque_1 = sns.boxplot(stats.tempo_no_cheque)\nstats.tempo_no_cheque.describe()", "_____no_output_____" ], [ "vis33 = sns.distplot(stats.relacionamento)", "_____no_output_____" ], [ "vis3 = sns.boxplot(stats.relacionamento)\nstats.relacionamento.describe()", "_____no_output_____" ], [ "vis_score_serasa = sns.distplot(stats.score_serasa)", "_____no_output_____" ], [ "vis_score_serasa_1 = sns.boxplot(stats.score_serasa)\nstats.score_serasa.describe()", "_____no_output_____" ], [ "vis_fatura_cartao = sns.distplot(stats.fatura_cartao)", "_____no_output_____" ], [ "vis_fatura_cartao_1 = sns.boxplot(stats.fatura_cartao)\nstats.fatura_cartao.describe()", "_____no_output_____" ], [ "vis_ultimo_default = sns.distplot(stats.fatura_cartao)", "_____no_output_____" ], [ "vis_ultimo_default_1 = sns.boxplot(stats.ultimo_default)\nstats.fatura_cartao.describe()", "_____no_output_____" ], [ "vis_cheque_vs_relacionamento = sns.boxplot(data = stats, x='relacionamento', y='cheque')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d074cc25d5639536bc6e6f8e204d157d22f7727c
12,899
ipynb
Jupyter Notebook
nanowrimoPosts.ipynb
wcmckee/wcmckee
19315a37b592b7bcebb5f2720c965aea58f928ce
[ "MIT" ]
null
null
null
nanowrimoPosts.ipynb
wcmckee/wcmckee
19315a37b592b7bcebb5f2720c965aea58f928ce
[ "MIT" ]
null
null
null
nanowrimoPosts.ipynb
wcmckee/wcmckee
19315a37b592b7bcebb5f2720c965aea58f928ce
[ "MIT" ]
null
null
null
20.313386
142
0.499806
[ [ [ "nanowrite blog post gener\n\nscript to create blog posts templates november for nano write.\n\nCreates 30 posts. One for each day of the month.\n\nrst files + meta\n\nSave type as you type it to json file that has time stamp attached to it. \n\nrst name is nanowrimo (year) day (day) ", "_____no_output_____" ] ], [ [ "import os", "_____no_output_____" ], [ "for novran in range(1,31):\n print ('nanowrimo15day' + str(novran))", "nanowrimo15day1\nnanowrimo15day2\nnanowrimo15day3\nnanowrimo15day4\nnanowrimo15day5\nnanowrimo15day6\nnanowrimo15day7\nnanowrimo15day8\nnanowrimo15day9\nnanowrimo15day10\nnanowrimo15day11\nnanowrimo15day12\nnanowrimo15day13\nnanowrimo15day14\nnanowrimo15day15\nnanowrimo15day16\nnanowrimo15day17\nnanowrimo15day18\nnanowrimo15day19\nnanowrimo15day20\nnanowrimo15day21\nnanowrimo15day22\nnanowrimo15day23\nnanowrimo15day24\nnanowrimo15day25\nnanowrimo15day26\nnanowrimo15day27\nnanowrimo15day28\nnanowrimo15day29\nnanowrimo15day30\n" ], [ "for worcu in range(1,31):\n print(worcu)\n os.system('wc -w /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day' + str(worcu) + '.rst > /home/wcmckee/nano/' + str(worcu))", "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n" ], [ "mylisit = list()", "_____no_output_____" ], [ "for worcu in range(1,31):\n opfilz = open('/home/wcmckee/nano/' + str(worcu), 'r')\n mylisit.append((opfilz.read()))\n opfilz.close()", "_____no_output_____" ], [ "bahg = list()", "_____no_output_____" ], [ "behp = list()", "_____no_output_____" ], [ "for bah in bahg:\n print(bah[0:10])\n behp.append(bah[0:10])", "2905, /hom\n1446, /hom\n1739, /hom\n2186, /hom\n1791, /hom\n1808, /hom\n2940, /hom\n1684, /hom\n1676, /hom\n1459, /hom\n1126, /hom\n1791, /hom\n1685, /hom\n1195, /hom\n2199, /hom\n985, /home\n1674, /hom\n1714, /hom\n1765, /hom\n1667, /hom\n742, /home\n2294, /hom\n1992, /hom\n2689, /hom\n2606, /hom\n1904, /hom\n2436, /hom\n2950, /hom\n1, /home/w\n1, /home/w\n" ], [ "for beh in behp:\n print(beh)", "2905, /hom\n1446, /hom\n1739, /hom\n2186, /hom\n1791, /hom\n1808, /hom\n2940, /hom\n1684, /hom\n1676, /hom\n1459, /hom\n1126, /hom\n1791, /hom\n1685, /hom\n1195, /hom\n2199, /hom\n985, /home\n1674, /hom\n1714, /hom\n1765, /hom\n1667, /hom\n742, /home\n2294, /hom\n1992, /hom\n2689, /hom\n2606, /hom\n1904, /hom\n2436, /hom\n2950, /hom\n1, /home/w\n1, /home/w\n" ], [ "for myli in mylisit:\n print(myli.replace(' ', ', '))\n bahg.append(myli.replace(' ', ', '))", "2905, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day1.rst\n\n1446, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day2.rst\n\n1739, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day3.rst\n\n2186, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day4.rst\n\n1791, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day5.rst\n\n1808, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day6.rst\n\n2940, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day7.rst\n\n1684, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day8.rst\n\n1676, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day9.rst\n\n1459, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day10.rst\n\n1126, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day11.rst\n\n1791, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day12.rst\n\n1685, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day13.rst\n\n1195, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day14.rst\n\n2199, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day15.rst\n\n985, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day16.rst\n\n1674, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day17.rst\n\n1714, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day18.rst\n\n1765, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day19.rst\n\n1667, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day20.rst\n\n742, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day21.rst\n\n2294, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day22.rst\n\n1992, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day23.rst\n\n2689, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day24.rst\n\n2606, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day25.rst\n\n1904, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day26.rst\n\n2436, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day27.rst\n\n2950, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day28.rst\n\n1, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day29.rst\n\n1, /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day30.rst\n\n" ], [ "os.system('wc -w /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day*.rst')", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d074e48ab8f41c10ca2110c11ca6c3b1e02c2154
5,364
ipynb
Jupyter Notebook
locale/examples/01-filter/interpolate.ipynb
tkoyama010/pyvista-doc-translations
23bb813387b7f8bfe17e86c2244d5dd2243990db
[ "MIT" ]
4
2020-08-07T08:19:19.000Z
2020-12-04T09:51:11.000Z
locale/examples/01-filter/interpolate.ipynb
tkoyama010/pyvista-doc-translations
23bb813387b7f8bfe17e86c2244d5dd2243990db
[ "MIT" ]
19
2020-08-06T00:24:30.000Z
2022-03-30T19:22:24.000Z
locale/examples/01-filter/interpolate.ipynb
tkoyama010/pyvista-doc-translations
23bb813387b7f8bfe17e86c2244d5dd2243990db
[ "MIT" ]
1
2021-03-09T07:50:40.000Z
2021-03-09T07:50:40.000Z
31.00578
435
0.550895
[ [ [ "%matplotlib inline\nfrom pyvista import set_plot_theme\nset_plot_theme('document')", "_____no_output_____" ] ], [ [ "Interpolating {#interpolate_example}\n=============\n\nInterpolate one mesh\\'s point/cell arrays onto another mesh\\'s nodes\nusing a Gaussian Kernel.\n", "_____no_output_____" ] ], [ [ "# sphinx_gallery_thumbnail_number = 4\nimport pyvista as pv\nfrom pyvista import examples", "_____no_output_____" ] ], [ [ "Simple Surface Interpolation\n============================\n\nResample the points\\' arrays onto a surface\n", "_____no_output_____" ] ], [ [ "# Download sample data\nsurface = examples.download_saddle_surface()\npoints = examples.download_sparse_points()\n\np = pv.Plotter()\np.add_mesh(points, point_size=30.0, render_points_as_spheres=True)\np.add_mesh(surface)\np.show()", "_____no_output_____" ] ], [ [ "Run the interpolation\n", "_____no_output_____" ] ], [ [ "interpolated = surface.interpolate(points, radius=12.0)\n\n\np = pv.Plotter()\np.add_mesh(points, point_size=30.0, render_points_as_spheres=True)\np.add_mesh(interpolated, scalars=\"val\")\np.show()", "_____no_output_____" ] ], [ [ "Complex Interpolation\n=====================\n\nIn this example, we will in interpolate sparse points in 3D space into a\nvolume. These data are from temperature probes in the subsurface and the\ngoal is to create an approximate 3D model of the temperature field in\nthe subsurface.\n\nThis approach is a great for back-of-the-hand estimations but pales in\ncomparison to kriging\n", "_____no_output_____" ] ], [ [ "# Download the sparse data\nprobes = examples.download_thermal_probes()", "_____no_output_____" ] ], [ [ "Create the interpolation grid around the sparse data\n", "_____no_output_____" ] ], [ [ "grid = pv.UniformGrid()\ngrid.origin = (329700, 4252600, -2700)\ngrid.spacing = (250, 250, 50)\ngrid.dimensions = (60, 75, 100)", "_____no_output_____" ], [ "dargs = dict(cmap=\"coolwarm\", clim=[0,300], scalars=\"temperature (C)\")\ncpos = [(364280.5723737897, 4285326.164400684, 14093.431895014139),\n (337748.7217949739, 4261154.45054595, -637.1092549935128),\n (-0.29629216102673206, -0.23840196609932093, 0.9248651025279784)]\n\np = pv.Plotter()\np.add_mesh(grid.outline(), color='k')\np.add_mesh(probes, render_points_as_spheres=True, **dargs)\np.show(cpos=cpos)", "_____no_output_____" ] ], [ [ "Run an interpolation\n", "_____no_output_____" ] ], [ [ "interp = grid.interpolate(probes, radius=15000, sharpness=10, strategy='mask_points')", "_____no_output_____" ] ], [ [ "Visualize the results\n", "_____no_output_____" ] ], [ [ "vol_opac = [0, 0, .2, 0.2, 0.5, 0.5]\n\np = pv.Plotter(shape=(1,2), window_size=[1024*3, 768*2])\np.enable_depth_peeling()\np.add_volume(interp, opacity=vol_opac, **dargs)\np.add_mesh(probes, render_points_as_spheres=True, point_size=10, **dargs)\np.subplot(0,1)\np.add_mesh(interp.contour(5), opacity=0.5, **dargs)\np.add_mesh(probes, render_points_as_spheres=True, point_size=10, **dargs)\np.link_views()\np.show(cpos=cpos)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d074efa9b4fa2cc945047e66fd6459b718e030db
20,018
ipynb
Jupyter Notebook
AutoEncoder/AutoEncoder.ipynb
CostaDiego/economy_ml_review
36ac4e4093dd3cab3596213e459a864a665cca63
[ "MIT" ]
null
null
null
AutoEncoder/AutoEncoder.ipynb
CostaDiego/economy_ml_review
36ac4e4093dd3cab3596213e459a864a665cca63
[ "MIT" ]
null
null
null
AutoEncoder/AutoEncoder.ipynb
CostaDiego/economy_ml_review
36ac4e4093dd3cab3596213e459a864a665cca63
[ "MIT" ]
null
null
null
97.174757
14,074
0.816165
[ [ [ "from keras.layers import Dense,Conv2D,MaxPooling2D,UpSampling2D\nfrom keras import Input, Model\nfrom keras.datasets import mnist\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "\nencoding_dim = 20\ninput_img = Input(shape=(784,))\nencoded = Dense(encoding_dim, activation='relu')(input_img)\ndecoded = Dense(784, activation='sigmoid')(encoded)\nautoencoder = Model(input_img, decoded)", "_____no_output_____" ], [ "encoder = Model(input_img, encoded)\nencoded_input = Input(shape=(encoding_dim,))\ndecoder_layer = autoencoder.layers[-1]\ndecoder = Model(encoded_input, decoder_layer(encoded_input))", "_____no_output_____" ], [ "autoencoder.compile(optimizer='adam', loss='binary_crossentropy')", "_____no_output_____" ], [ "(x_train, y_train), (x_test, y_test) = mnist.load_data()", "_____no_output_____" ], [ "x_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\nx_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))\nx_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))\nprint(x_train.shape)\nprint(x_test.shape)", "(60000, 784)\n(10000, 784)\n" ], [ "autoencoder.fit(x_train, x_train,\n epochs=15,\n batch_size=256,\n validation_data=(x_test, x_test))", "Epoch 1/15\n235/235 [==============================] - 1s 5ms/step - loss: 0.2976 - val_loss: 0.2104\nEpoch 2/15\n235/235 [==============================] - 1s 5ms/step - loss: 0.1886 - val_loss: 0.1708\nEpoch 3/15\n235/235 [==============================] - 1s 4ms/step - loss: 0.1620 - val_loss: 0.1514\nEpoch 4/15\n235/235 [==============================] - 1s 5ms/step - loss: 0.1465 - val_loss: 0.1397\nEpoch 5/15\n235/235 [==============================] - 1s 6ms/step - loss: 0.1376 - val_loss: 0.1330\nEpoch 6/15\n235/235 [==============================] - 1s 5ms/step - loss: 0.1323 - val_loss: 0.1288\nEpoch 7/15\n235/235 [==============================] - 1s 5ms/step - loss: 0.1288 - val_loss: 0.1260\nEpoch 8/15\n235/235 [==============================] - 1s 5ms/step - loss: 0.1262 - val_loss: 0.1235\nEpoch 9/15\n235/235 [==============================] - 2s 7ms/step - loss: 0.1240 - val_loss: 0.1215\nEpoch 10/15\n235/235 [==============================] - 1s 5ms/step - loss: 0.1222 - val_loss: 0.1198\nEpoch 11/15\n235/235 [==============================] - 1s 6ms/step - loss: 0.1206 - val_loss: 0.1185\nEpoch 12/15\n235/235 [==============================] - 1s 6ms/step - loss: 0.1194 - val_loss: 0.1174\nEpoch 13/15\n235/235 [==============================] - 1s 5ms/step - loss: 0.1186 - val_loss: 0.1166\nEpoch 14/15\n235/235 [==============================] - 1s 6ms/step - loss: 0.1180 - val_loss: 0.1162\nEpoch 15/15\n235/235 [==============================] - 1s 6ms/step - loss: 0.1176 - val_loss: 0.1158\n" ], [ "encoded_img = encoder.predict(x_test)\ndecoded_img = decoder.predict(encoded_img)\nplt.figure(figsize=(20, 4))\nfor i in range(5):\n # Imagens originais\n ax = plt.subplot(2, 5, i + 1)\n plt.imshow(x_test[i].reshape(28, 28))\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n # Imagens reconstruidas\n ax = plt.subplot(2, 5, i + 1 + 5)\n plt.imshow(decoded_img[i].reshape(28, 28))\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d074fd8374b9a35844107a737d4c7d3844827c20
19,744
ipynb
Jupyter Notebook
tutorials/ranking/drmmtks.ipynb
Ambitioner-c/MatchZoo-py
bb088edce8e01c2c2326ca1a8ac647f0d23f088d
[ "Apache-2.0" ]
468
2019-07-03T02:43:52.000Z
2022-03-30T05:51:03.000Z
tutorials/ranking/drmmtks.ipynb
Ambitioner-c/MatchZoo-py
bb088edce8e01c2c2326ca1a8ac647f0d23f088d
[ "Apache-2.0" ]
126
2019-07-04T15:51:57.000Z
2021-07-31T13:14:40.000Z
tutorials/ranking/drmmtks.ipynb
Ambitioner-c/MatchZoo-py
bb088edce8e01c2c2326ca1a8ac647f0d23f088d
[ "Apache-2.0" ]
117
2019-07-04T11:31:08.000Z
2022-03-18T12:21:32.000Z
31.691814
171
0.565843
[ [ [ "import torch\nimport numpy as np\nimport pandas as pd\nimport matchzoo as mz\nprint('matchzoo version', mz.__version__)", "matchzoo version 1.1.1\n" ], [ "ranking_task = mz.tasks.Ranking(losses=mz.losses.RankHingeLoss())\nranking_task.metrics = [\n mz.metrics.NormalizedDiscountedCumulativeGain(k=3),\n mz.metrics.NormalizedDiscountedCumulativeGain(k=5),\n mz.metrics.MeanAveragePrecision()\n]\nprint(\"`ranking_task` initialized with metrics\", ranking_task.metrics)", "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n" ], [ "print('data loading ...')\ntrain_pack_raw = mz.datasets.wiki_qa.load_data('train', task=ranking_task)\ndev_pack_raw = mz.datasets.wiki_qa.load_data('dev', task=ranking_task, filtered=True)\ntest_pack_raw = mz.datasets.wiki_qa.load_data('test', task=ranking_task, filtered=True)\nprint('data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`')", "data loading ...\ndata loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n" ], [ "preprocessor = mz.preprocessors.BasicPreprocessor(\n truncated_length_left = 10,\n truncated_length_right = 100,\n filter_low_freq = 2\n)", "_____no_output_____" ], [ "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\ndev_pack_processed = preprocessor.transform(dev_pack_raw)\ntest_pack_processed = preprocessor.transform(test_pack_raw)", "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2118/2118 [00:00<00:00, 11001.23it/s]\nProcessing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 18841/18841 [00:03<00:00, 5972.72it/s]\nProcessing text_right with append: 100%|██████████| 18841/18841 [00:00<00:00, 995451.11it/s]\nBuilding FrequencyFilter from a datapack.: 100%|██████████| 18841/18841 [00:00<00:00, 165418.50it/s]\nProcessing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 106788.94it/s]\nProcessing text_left with extend: 100%|██████████| 2118/2118 [00:00<00:00, 603091.37it/s]\nProcessing text_right with extend: 100%|██████████| 18841/18841 [00:00<00:00, 730393.10it/s]\nBuilding Vocabulary from a datapack.: 100%|██████████| 404432/404432 [00:00<00:00, 3237271.33it/s]\nProcessing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2118/2118 [00:00<00:00, 11244.91it/s]\nProcessing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 18841/18841 [00:03<00:00, 5965.35it/s]\nProcessing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 151505.92it/s]\nProcessing text_left with transform: 100%|██████████| 2118/2118 [00:00<00:00, 222132.82it/s]\nProcessing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 142060.31it/s]\nProcessing text_left with transform: 100%|██████████| 2118/2118 [00:00<00:00, 556055.07it/s]\nProcessing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 787531.83it/s]\nProcessing length_left with len: 100%|██████████| 2118/2118 [00:00<00:00, 779462.65it/s]\nProcessing length_right with len: 100%|██████████| 18841/18841 [00:00<00:00, 908091.90it/s]\nProcessing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 122/122 [00:00<00:00, 10722.40it/s]\nProcessing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 1115/1115 [00:00<00:00, 5876.72it/s]\nProcessing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 153493.80it/s]\nProcessing text_left with transform: 100%|██████████| 122/122 [00:00<00:00, 87024.67it/s]\nProcessing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 112074.60it/s]\nProcessing text_left with transform: 100%|██████████| 122/122 [00:00<00:00, 137407.38it/s]\nProcessing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 487506.41it/s]\nProcessing length_left with len: 100%|██████████| 122/122 [00:00<00:00, 162704.32it/s]\nProcessing length_right with len: 100%|██████████| 1115/1115 [00:00<00:00, 637493.04it/s]\nProcessing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 237/237 [00:00<00:00, 10475.15it/s]\nProcessing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2300/2300 [00:00<00:00, 5817.60it/s]\nProcessing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 153176.44it/s]\nProcessing text_left with transform: 100%|██████████| 237/237 [00:00<00:00, 172249.19it/s]\nProcessing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 141452.21it/s]\nProcessing text_left with transform: 100%|██████████| 237/237 [00:00<00:00, 240631.82it/s]\nProcessing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 707043.33it/s]\nProcessing length_left with len: 100%|██████████| 237/237 [00:00<00:00, 281122.75it/s]\nProcessing length_right with len: 100%|██████████| 2300/2300 [00:00<00:00, 782900.44it/s]\n" ], [ "preprocessor.context", "_____no_output_____" ], [ "glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=100)\nterm_index = preprocessor.context['vocab_unit'].state['term_index']\nembedding_matrix = glove_embedding.build_matrix(term_index)\nl2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\nembedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]", "_____no_output_____" ], [ "trainset = mz.dataloader.Dataset(\n data_pack=train_pack_processed,\n mode='pair',\n num_dup=2,\n num_neg=1,\n batch_size=20,\n resample=True,\n sort=False\n)\ntestset = mz.dataloader.Dataset(\n data_pack=test_pack_processed,\n batch_size=20\n)", "_____no_output_____" ], [ "padding_callback = mz.models.DRMMTKS.get_default_padding_callback()\n\ntrainloader = mz.dataloader.DataLoader(\n dataset=trainset,\n stage='train',\n callback=padding_callback\n)\ntestloader = mz.dataloader.DataLoader(\n dataset=testset,\n stage='dev',\n callback=padding_callback\n)", "_____no_output_____" ], [ "model = mz.models.DRMMTKS()\n\nmodel.params['task'] = ranking_task\nmodel.params['embedding'] = embedding_matrix\nmodel.params['mask_value'] = 0\nmodel.params['top_k'] = 10\nmodel.params['mlp_activation_func'] = 'tanh'\n\nmodel.build()\n\nprint(model)\nprint('Trainable params: ', sum(p.numel() for p in model.parameters() if p.requires_grad))", "DRMMTKS(\n (embedding): Embedding(16675, 100, padding_idx=0)\n (attention): Attention(\n (linear): Linear(in_features=100, out_features=1, bias=False)\n )\n (mlp): Sequential(\n (0): Sequential(\n (0): Linear(in_features=10, out_features=128, bias=True)\n (1): Tanh()\n )\n (1): Sequential(\n (0): Linear(in_features=128, out_features=128, bias=True)\n (1): Tanh()\n )\n (2): Sequential(\n (0): Linear(in_features=128, out_features=128, bias=True)\n (1): Tanh()\n )\n (3): Sequential(\n (0): Linear(in_features=128, out_features=1, bias=True)\n (1): Tanh()\n )\n )\n (out): Linear(in_features=1, out_features=1, bias=True)\n)\nTrainable params: 1702163\n" ], [ "optimizer = torch.optim.Adadelta(model.parameters())\n\ntrainer = mz.trainers.Trainer(\n model=model,\n optimizer=optimizer,\n trainloader=trainloader,\n validloader=testloader,\n validate_interval=None,\n epochs=10\n)", "_____no_output_____" ], [ "trainer.run()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0750082a6bec7f56ea271a6067d1cc73e793707
2,790
ipynb
Jupyter Notebook
fundamentals_2018.9/distributions/.ipynb_checkpoints/conclusion-checkpoint.ipynb
topseer/APL_Great
7ae3bd06e4d520d023bc9b992c88b6e3c758d551
[ "MIT" ]
null
null
null
fundamentals_2018.9/distributions/.ipynb_checkpoints/conclusion-checkpoint.ipynb
topseer/APL_Great
7ae3bd06e4d520d023bc9b992c88b6e3c758d551
[ "MIT" ]
null
null
null
fundamentals_2018.9/distributions/.ipynb_checkpoints/conclusion-checkpoint.ipynb
topseer/APL_Great
7ae3bd06e4d520d023bc9b992c88b6e3c758d551
[ "MIT" ]
null
null
null
42.923077
414
0.653405
[ [ [ "# Conclusion\n\nIn this chapter we looked at Mathematical distributions. Mathematical distributions have a *generating story* (or many such stories) that describe processes that give rise to data with certain characteristics that appear over and over again. We need only provide specific *parameter* to specialize them for our own data. This makes them good models for our data, a point we will return to in a later chapter.", "_____no_output_____" ], [ "## Review\n\n1. What is a **random variable**?\n2. What is the difference between **probability mass** and **probability density**?\n3. What three things are probability distributions good for modeling?\n4. What is a **statistic**? Give three examples of a statistic.\n5. What is the difference between an accountant's \"total sales\" and a data scientist's \"total sales\"?\n6. What does the **first moment** of the empirical distribution measure? **Second moment**?\n7. What is does it mean if $X \\sim U(10, 20)$ for continuous $X$?\n8. What is a **Bernoulli trial**? What is $p$? Is \"success\" always \"good\"?\n9. What was the generating story we told for the **Exponential distribution**?\n10. Why is the Exponential distribution **\"memoryless\"**? Compare it to the **Weibull distribution** if needed.\n11. How is the Exponential distribution a special case of the **Gamma distribution**?\n12. What is the generating story for the **Binomial distribution**?\n13. How does the Binomial distribution derive from the **Exponential distribution**?\n14. What is the generating story for the **Poisson distribution**?\n15. What are two potential problems with using the Poisson distribution as a model and how are they solved?\n16. What is the specific version of the **Central Limit Theorem**? What is the general version?\n17. What is the generating story for the **Normal distribution**?\n18. What is the generating story for the **Log-Normal distribution**?\n19. How are the Log-Normal and Normal distributions related?", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown" ] ]
d07508e64592a3d7f2c3de3bb06f9ddafba20218
11,340
ipynb
Jupyter Notebook
02_data_representation/text_embeddings.ipynb
modoai/ml-design-patterns
cfe5a1f46f1691663c56ec53382b398e0c8ca505
[ "Apache-2.0" ]
1,149
2020-04-09T21:20:56.000Z
2022-03-31T02:41:53.000Z
02_data_representation/text_embeddings.ipynb
QuintonQu/ml-design-patterns
060eb9f9be1d7f7e2d7e103a29a01386723c22fe
[ "Apache-2.0" ]
28
2020-06-14T15:17:59.000Z
2022-02-17T10:13:08.000Z
02_data_representation/text_embeddings.ipynb
QuintonQu/ml-design-patterns
060eb9f9be1d7f7e2d7e103a29a01386723c22fe
[ "Apache-2.0" ]
296
2020-04-28T06:26:41.000Z
2022-03-31T06:52:33.000Z
31.5
556
0.527249
[ [ [ "# Document embeddings in BigQuery\n\nThis notebook shows how to do use a pre-trained embedding as a vector representation of a natural language text column.\nGiven this embedding, we can use it in machine learning models.", "_____no_output_____" ], [ "## Embedding model for documents\n\nWe're going to use a model that has been pretrained on Google News. Here's an example of how it works in Python. We will use it directly in BigQuery, however.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nimport tensorflow_hub as tfhub\n\nmodel = tf.keras.Sequential()\nmodel.add(tfhub.KerasLayer(\"https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1\",\n output_shape=[20], input_shape=[], dtype=tf.string))\nmodel.summary()\nmodel.predict([\"\"\"\nLong years ago, we made a tryst with destiny; and now the time comes when we shall redeem our pledge, not wholly or in full measure, but very substantially. At the stroke of the midnight hour, when the world sleeps, India will awake to life and freedom.\nA moment comes, which comes but rarely in history, when we step out from the old to the new -- when an age ends, and when the soul of a nation, long suppressed, finds utterance. \n\"\"\"])", "Model: \"sequential_4\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nkeras_layer_3 (KerasLayer) (None, 20) 400020 \n=================================================================\nTotal params: 400,020\nTrainable params: 0\nNon-trainable params: 400,020\n_________________________________________________________________\n" ] ], [ [ "## Loading model into BigQuery\n\nThe Swivel model above is already available in SavedModel format. But we need it on Google Cloud Storage before we can load it into BigQuery.", "_____no_output_____" ] ], [ [ "%%bash\nBUCKET=ai-analytics-solutions-kfpdemo # CHANGE AS NEEDED\n\nrm -rf tmp\nmkdir tmp\nFILE=swivel.tar.gz\nwget --quiet -O tmp/swivel.tar.gz https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1?tf-hub-format=compressed\ncd tmp\ntar xvfz swivel.tar.gz\ncd ..\nmv tmp swivel\ngsutil -m cp -R swivel gs://${BUCKET}/swivel\nrm -rf swivel\n\necho \"Model artifacts are now at gs://${BUCKET}/swivel/*\"", "assets/\nassets/tokens.txt\nsaved_model.pb\nvariables/\nvariables/variables.data-00000-of-00001\nvariables/variables.index\nModel artifacts are now at gs://ai-analytics-solutions-kfpdemo/swivel/*\n" ] ], [ [ "Let's load the model into a BigQuery dataset named advdata (create it if necessary)", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE MODEL advdata.swivel_text_embed\nOPTIONS(model_type='tensorflow', model_path='gs://ai-analytics-solutions-kfpdemo/swivel/*')", "_____no_output_____" ] ], [ [ "From the BigQuery web console, click on \"schema\" tab for the newly loaded model. We see that the input is called sentences and the output is called output_0:\n<img src=\"swivel_schema.png\" />", "_____no_output_____" ] ], [ [ "%%bigquery\nSELECT output_0 FROM\nML.PREDICT(MODEL advdata.swivel_text_embed,(\nSELECT \"Long years ago, we made a tryst with destiny; and now the time comes when we shall redeem our pledge, not wholly or in full measure, but very substantially.\" AS sentences))", "_____no_output_____" ] ], [ [ "## Create lookup table\n\nLet's create a lookup table of embeddings. We'll use the comments field of a storm reports table from NOAA.\nThis is an example of the Feature Store design pattern.", "_____no_output_____" ] ], [ [ "%%bigquery\nCREATE OR REPLACE TABLE advdata.comments_embedding AS\nSELECT\n output_0 as comments_embedding,\n comments\nFROM ML.PREDICT(MODEL advdata.swivel_text_embed,(\n SELECT comments, LOWER(comments) AS sentences\n FROM `bigquery-public-data.noaa_preliminary_severe_storms.wind_reports`\n))", "_____no_output_____" ] ], [ [ "For an example of using these embeddings in text similarity or document clustering, please see the following Medium blog post: https://medium.com/@lakshmanok/how-to-do-text-similarity-search-and-document-clustering-in-bigquery-75eb8f45ab65", "_____no_output_____" ], [ "Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d0750939a5bb507777f196d3454f194a61c33ac5
241,248
ipynb
Jupyter Notebook
2-Regression/3-Linear/notebook.ipynb
GDaglio/ML-For-Beginners
0b7ad551455490d0ca46f6de1469ee64ee08fb10
[ "MIT" ]
null
null
null
2-Regression/3-Linear/notebook.ipynb
GDaglio/ML-For-Beginners
0b7ad551455490d0ca46f6de1469ee64ee08fb10
[ "MIT" ]
null
null
null
2-Regression/3-Linear/notebook.ipynb
GDaglio/ML-For-Beginners
0b7ad551455490d0ca46f6de1469ee64ee08fb10
[ "MIT" ]
null
null
null
125.063764
86,274
0.823766
[ [ [ "## Pumpkin Pricing\n\nLoad up required libraries and dataset. Convert the data to a dataframe containing a subset of the data: \n\n- Only get pumpkins priced by the bushel\n- Convert the date to a month\n- Calculate the price to be an average of high and low prices\n- Convert the price to reflect the pricing by bushel quantity", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, classification_report \nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom sklearn.linear_model import LogisticRegression\nimport sklearn\nimport numpy as np\nimport calendar\nimport seaborn as sns\n\npumpkins = pd.read_csv('../data/US-pumpkins.csv')\n\npumpkins.head()\n", "_____no_output_____" ], [ "\npumpkins = pumpkins[pumpkins['Package'].str.contains('bushel', case=True, regex=True)]\n\nnew_columns = ['Package', 'Variety', 'City Name', 'Month', 'Low Price', 'High Price', 'Date', 'City Num', 'Variety Num']\n\n\npumpkins = pumpkins.drop([c for c in pumpkins.columns if c not in new_columns], axis=1)\n\nprice = (pumpkins['Low Price'] + pumpkins['High Price']) / 2\n\nmonth = pd.DatetimeIndex(pumpkins['Date']).month\n\n\nnew_pumpkins = pd.DataFrame({'Month': month, 'Variety': pumpkins['Variety'], 'City': pumpkins['City Name'], 'Package': pumpkins['Package'], 'Low Price': pumpkins['Low Price'],'High Price': pumpkins['High Price'], 'Price': price})\n\nnew_pumpkins.loc[new_pumpkins['Package'].str.contains('1 1/9'), 'Price'] = price/1.1\n\nnew_pumpkins.loc[new_pumpkins['Package'].str.contains('1/2'), 'Price'] = price*2\n\nnew_pumpkins.head()\n", "_____no_output_____" ] ], [ [ "A basic scatterplot reminds us that we only have month data from August through December. We probably need more data to be able to draw conclusions in a linear fashion.", "_____no_output_____" ] ], [ [ "new_pumpkins[\"Month_str\"] = new_pumpkins['Month'].apply(lambda x: calendar.month_abbr[x])\nplt.scatter('Month_str', 'Price', data=new_pumpkins)", "_____no_output_____" ], [ "plt.scatter(\"City\", \"Price\", data=new_pumpkins)", "_____no_output_____" ], [ "new_pumpkins.iloc[:, 0:-1] = new_pumpkins.iloc[:, 0:-1].apply(LabelEncoder().fit_transform)", "_____no_output_____" ], [ "new_pumpkins.head(10)", "_____no_output_____" ], [ "print(new_pumpkins[\"City\"].corr(new_pumpkins[\"Price\"]))", "0.30005978395013266\n" ], [ "print(new_pumpkins[\"Package\"].corr(new_pumpkins[\"Price\"]))", "0.6307979292333199\n" ], [ "new_pumpkins.dropna(inplace=True)\n\nnew_columns = [\"Package\", \"Price\"]\n\nlil_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis=\"columns\")", "_____no_output_____" ], [ "X = lil_pumpkins.values[:, :1]\ny = lil_pumpkins.values[:, 1:2]\nX", "_____no_output_____" ], [ "from sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\nlil_reg = LinearRegression()\nlil_reg.fit(X_train, y_train)\n\npred = lil_reg.predict(X_test)\n\naccuracy_score = lil_reg.score(X_train, y_train)\nprint(f\"Model accuracy: {accuracy_score}\")", "Model accuracy: 0.3639348759602836\n" ], [ "plt.scatter(X_test, y_test, color=\"black\")\nplt.plot(X_test, pred, color=\"blue\", linewidth=3)\n\nplt.xlabel(\"Package\")\nplt.ylabel(\"Price\")", "_____no_output_____" ], [ "lil_reg.predict([[2.75]])", "_____no_output_____" ], [ "new_columns = ['Variety', 'Package', 'City', 'Month', 'Price']\npoly_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis=\"columns\")", "_____no_output_____" ], [ "corr = poly_pumpkins.corr()\ncorr.style.background_gradient(cmap=\"coolwarm\")", "_____no_output_____" ], [ "X = poly_pumpkins.iloc[:, 3:4].values\ny = poly_pumpkins.iloc[:, 4:5].values", "_____no_output_____" ], [ "from sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.pipeline import make_pipeline\n\npipeline = make_pipeline(PolynomialFeatures(4), LinearRegression())\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\npipeline.fit(X_train, y_train)\n\ny_pred = pipeline.predict(X_test)", "_____no_output_____" ], [ "df = pd.DataFrame({\"x\": X_test[:,0], \"y\":y_pred[:,0]})\ndf.sort_values(by=\"x\", inplace=True)\n\n# chiamo pd.DataFrame per creare un nuovo df\npoints = pd.DataFrame(df).to_numpy()", "_____no_output_____" ], [ "plt.plot(points[:, 0], points[:, 1], color=\"blue\", linewidth=3)\nplt.xlabel(\"Package\")\nplt.ylabel(\"Price\")\nplt.scatter(X, y, color=\"black\")", "_____no_output_____" ], [ "accuracy_score = pipeline.score(X_train, y_train)\naccuracy_score", "_____no_output_____" ], [ "pipeline.predict([[2.75]])", "_____no_output_____" ] ], [ [ "# Lecture 1-4 - Binary classification", "_____no_output_____" ] ], [ [ "pumpkins = pd.read_csv('../data/US-pumpkins.csv')\n\nnew_columns = ['Color','Origin','Item Size','Variety','City Name','Package']\n\nnew_pumpkins = pumpkins[new_columns]\nnew_pumpkins.dropna(inplace=True)\nnew_pumpkins = new_pumpkins.apply(LabelEncoder().fit_transform)\nnew_pumpkins", "c:\\Users\\Gabriele\\Documents\\GitHub\\ML-For-Beginners\\.venv\\lib\\site-packages\\pandas\\util\\_decorators.py:311: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n return func(*args, **kwargs)\n" ], [ "g = sns.PairGrid(new_pumpkins)\ng.map(sns.scatterplot)", "_____no_output_____" ], [ "sns.swarmplot(x=\"Color\", y=\"Item Size\", data=new_pumpkins)", "c:\\Users\\Gabriele\\Documents\\GitHub\\ML-For-Beginners\\.venv\\lib\\site-packages\\seaborn\\categorical.py:1296: UserWarning: 80.6% of the points cannot be placed; you may want to decrease the size of the markers or use stripplot.\n warnings.warn(msg, UserWarning)\nc:\\Users\\Gabriele\\Documents\\GitHub\\ML-For-Beginners\\.venv\\lib\\site-packages\\seaborn\\categorical.py:1296: UserWarning: 37.2% of the points cannot be placed; you may want to decrease the size of the markers or use stripplot.\n warnings.warn(msg, UserWarning)\n" ], [ "sns.catplot(x=\"Color\", y=\"Item Size\", kind=\"violin\", data=new_pumpkins)", "_____no_output_____" ], [ "Selected_features = ['Origin','Item Size','Variety','City Name','Package']\n\nX = new_pumpkins[Selected_features]\ny = new_pumpkins[\"Color\"]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)", "_____no_output_____" ], [ "model = LogisticRegression()\nmodel.fit(X_train, y_train)\npredictions = model.predict(X_test)\n\nprint(classification_report(y_test, predictions))\n# print(f\"Predicted labels: {predictions}\")\nprint(f\"Accuracy: {sklearn.metrics.accuracy_score(y_test, predictions)}\")", " precision recall f1-score support\n\n 0 0.83 0.98 0.90 166\n 1 0.00 0.00 0.00 33\n\n accuracy 0.81 199\n macro avg 0.42 0.49 0.45 199\nweighted avg 0.69 0.81 0.75 199\n\nAccuracy: 0.8140703517587939\n" ], [ "from sklearn.metrics import confusion_matrix\n\nconfusion_matrix(y_test, predictions)", "_____no_output_____" ], [ "y_scores = model.predict_proba(X_test)\n\nfpr, tpr, thresholds = roc_curve(y_test, y_scores[:, 1])\nsns.lineplot([0, 1], [0, 1])\nsns.lineplot(fpr, tpr)", "c:\\Users\\Gabriele\\Documents\\GitHub\\ML-For-Beginners\\.venv\\lib\\site-packages\\seaborn\\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n warnings.warn(\nc:\\Users\\Gabriele\\Documents\\GitHub\\ML-For-Beginners\\.venv\\lib\\site-packages\\seaborn\\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n warnings.warn(\n" ], [ "auc = roc_auc_score(y_test, y_scores[:, 1])\nprint(auc)", "0.6976998904709748\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d075097ab7cd9478e8145679a562bdab990317a9
115,070
ipynb
Jupyter Notebook
AppliedDataPresentationInPython/PCADemo.ipynb
menlanshu/PythonDataScienceLearn
279c31e256c942c7339f9f76e3c75d6498f236ec
[ "MIT" ]
null
null
null
AppliedDataPresentationInPython/PCADemo.ipynb
menlanshu/PythonDataScienceLearn
279c31e256c942c7339f9f76e3c75d6498f236ec
[ "MIT" ]
null
null
null
AppliedDataPresentationInPython/PCADemo.ipynb
menlanshu/PythonDataScienceLearn
279c31e256c942c7339f9f76e3c75d6498f236ec
[ "MIT" ]
null
null
null
76.9699
64,848
0.698418
[ [ [ "%matplotlib notebook\n%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "from sklearn.datasets import load_breast_cancer", "_____no_output_____" ], [ "breast = load_breast_cancer()\nprint(breast.data.shape)", "(569, 30)\n" ], [ "# indicate it's malignant or benign\nbreast_data = breast.data\nbreast_label = breast.target", "_____no_output_____" ], [ "labels = np.reshape(breast_label, (-1,1))", "_____no_output_____" ], [ "final_breast_data = np.concatenate([breast_data, labels], axis=1)", "_____no_output_____" ], [ "final_breast_data.shape", "_____no_output_____" ], [ "breast_dataset = pd.DataFrame(final_breast_data)", "_____no_output_____" ], [ "features = breast.feature_names", "_____no_output_____" ], [ "features_labels = np.append(features, 'label')", "_____no_output_____" ], [ "breast_dataset.columns = features_labels", "_____no_output_____" ], [ "breast_dataset.head()", "_____no_output_____" ], [ "data = pd.DataFrame(breast.data, columns=[breast.feature_names])", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "breast_dataset['label'].replace(0, 'Benign',inplace=True)\nbreast_dataset['label'].replace(1, 'Malignant',inplace=True)", "_____no_output_____" ], [ "breast_dataset.tail()", "_____no_output_____" ], [ "from sklearn.preprocessing import StandardScaler\nx = breast_dataset.loc[:, features].values\nx = StandardScaler().fit_transform(x) # normalizing the features", "_____no_output_____" ], [ "np.mean(x),np.std(x)", "_____no_output_____" ], [ "feat_cols = ['feature'+str(i) for i in range(x.shape[1])]", "_____no_output_____" ], [ "normalised_breast = pd.DataFrame(x,columns=feat_cols)", "_____no_output_____" ], [ "normalised_breast.tail()", "_____no_output_____" ], [ "from sklearn.decomposition import PCA\npca_breast = PCA(n_components=2)\nprincipalComponents_breast = pca_breast.fit_transform(x)", "_____no_output_____" ], [ "pca_breast", "_____no_output_____" ], [ "principalComponents_breast ", "_____no_output_____" ], [ "principal_breast_Df = pd.DataFrame(data = principalComponents_breast\n , columns = ['principal component 1', 'principal component 2'])", "_____no_output_____" ], [ "principal_breast_Df.tail()", "_____no_output_____" ], [ "print('Explained variation per principal component: {}'.format(pca_breast.explained_variance_ratio_))", "Explained variation per principal component: [0.44272026 0.18971182]\n" ], [ "plt.figure()\nplt.figure(figsize=(10,10))\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=14)\nplt.xlabel('Principal Component - 1',fontsize=20)\nplt.ylabel('Principal Component - 2',fontsize=20)\nplt.title(\"Principal Component Analysis of Breast Cancer Dataset\",fontsize=20)\ntargets = ['Benign', 'Malignant']\ncolors = ['r', 'g']\nfor target, color in zip(targets,colors):\n indicesToKeep = breast_dataset['label'] == target\n plt.scatter(principal_breast_Df.loc[indicesToKeep, 'principal component 1']\n , principal_breast_Df.loc[indicesToKeep, 'principal component 2'], c = color, s = 50)\n\nplt.legend(targets,prop={'size': 15})", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0751be344a54f08f6c01b4c47a9d04dfff4da23
32,898
ipynb
Jupyter Notebook
bronze/B54_Quantum_Teleportation_Solutions.ipynb
ozlemsalehi/bronze-boun
37f853ead907b95e9ab20bb0a7f923126f00dc8f
[ "Apache-2.0", "CC-BY-4.0" ]
31
2019-10-06T19:13:26.000Z
2022-03-16T14:53:23.000Z
bronze/B54_Quantum_Teleportation_Solutions.ipynb
ozlemsalehi/bronze-boun
37f853ead907b95e9ab20bb0a7f923126f00dc8f
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
bronze/B54_Quantum_Teleportation_Solutions.ipynb
ozlemsalehi/bronze-boun
37f853ead907b95e9ab20bb0a7f923126f00dc8f
[ "Apache-2.0", "CC-BY-4.0" ]
12
2020-03-07T09:15:40.000Z
2022-03-21T16:41:24.000Z
69.699153
16,016
0.745942
[ [ [ "<table width=\"100%\"> <tr>\n <td style=\"background-color:#ffffff;\">\n <a href=\"http://qworld.lu.lv\" target=\"_blank\"><img src=\"../images/qworld.jpg\" width=\"35%\" align=\"left\"> </a></td>\n <td style=\"background-color:#ffffff;vertical-align:bottom;text-align:right;\">\n prepared by Abuzer Yakaryilmaz (<a href=\"http://qworld.lu.lv/index.php/qlatvia/\" target=\"_blank\">QLatvia</a>)\n <br>\n updated by Melis Pahalı | December 5, 2019\n <br>\n updated by Özlem Salehi | September 17, 2020\n </td> \n</tr></table>", "_____no_output_____" ], [ "<table width=\"100%\"><tr><td style=\"color:#bbbbbb;background-color:#ffffff;font-size:11px;font-style:italic;text-align:right;\">This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. </td></tr></table>\n$ \\newcommand{\\bra}[1]{\\langle #1|} $\n$ \\newcommand{\\ket}[1]{|#1\\rangle} $\n$ \\newcommand{\\braket}[2]{\\langle #1|#2\\rangle} $\n$ \\newcommand{\\dot}[2]{ #1 \\cdot #2} $\n$ \\newcommand{\\biginner}[2]{\\left\\langle #1,#2\\right\\rangle} $\n$ \\newcommand{\\mymatrix}[2]{\\left( \\begin{array}{#1} #2\\end{array} \\right)} $\n$ \\newcommand{\\myvector}[1]{\\mymatrix{c}{#1}} $\n$ \\newcommand{\\myrvector}[1]{\\mymatrix{r}{#1}} $\n$ \\newcommand{\\mypar}[1]{\\left( #1 \\right)} $\n$ \\newcommand{\\mybigpar}[1]{ \\Big( #1 \\Big)} $\n$ \\newcommand{\\sqrttwo}{\\frac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\dsqrttwo}{\\dfrac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\onehalf}{\\frac{1}{2}} $\n$ \\newcommand{\\donehalf}{\\dfrac{1}{2}} $\n$ \\newcommand{\\hadamard}{ \\mymatrix{rr}{ \\sqrttwo & \\sqrttwo \\\\ \\sqrttwo & -\\sqrttwo }} $\n$ \\newcommand{\\vzero}{\\myvector{1\\\\0}} $\n$ \\newcommand{\\vone}{\\myvector{0\\\\1}} $\n$ \\newcommand{\\vhadamardzero}{\\myvector{ \\sqrttwo \\\\ \\sqrttwo } } $\n$ \\newcommand{\\vhadamardone}{ \\myrvector{ \\sqrttwo \\\\ -\\sqrttwo } } $\n$ \\newcommand{\\myarray}[2]{ \\begin{array}{#1}#2\\end{array}} $\n$ \\newcommand{\\X}{ \\mymatrix{cc}{0 & 1 \\\\ 1 & 0} } $\n$ \\newcommand{\\Z}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & -1} } $\n$ \\newcommand{\\Htwo}{ \\mymatrix{rrrr}{ \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} } } $\n$ \\newcommand{\\CNOT}{ \\mymatrix{cccc}{1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 0 & 1 \\\\ 0 & 0 & 1 & 0} } $\n$ \\newcommand{\\norm}[1]{ \\left\\lVert #1 \\right\\rVert } $", "_____no_output_____" ], [ "<h2> <font color=\"blue\"> Solutions for </font>Quantum Teleportation</h2>", "_____no_output_____" ], [ "<a id=\"task1\"></a>\n<h3> Task 1 </h3>\n\nCalculate the new quantum state after this CNOT operator.", "_____no_output_____" ], [ "<h3>Solution</h3>", "_____no_output_____" ], [ "The state before CNOT is $ \\sqrttwo \\big( a\\ket{000} + a \\ket{011} + b\\ket{100} + b \\ket{111} \\big) $.", "_____no_output_____" ], [ "CNOT(first_qubit,second_qubit) is applied.\n\nIf the value of the first qubit is 1, then the value of the second qubit is flipped.\n\nThus, the new quantum state after this CNOT is\n\n$$ \\sqrttwo \\big( a\\ket{000} + a \\ket{011} + b\\ket{110} + b \\ket{101} \\big). $$", "_____no_output_____" ], [ "<a id=\"task2\"></a>\n<h3> Task 2 </h3>\n\nCalculate the new quantum state after this Hadamard operator.\n\nVerify that the resulting quantum state can be written as follows:\n\n$$ \n \\frac{1}{2} \\ket{00} \\big( a\\ket{0}+b\\ket{1} \\big) +\n \\frac{1}{2} \\ket{01} \\big( a\\ket{1}+b\\ket{0} \\big) +\n \\frac{1}{2} \\ket{10} \\big( a\\ket{0}-b\\ket{1} \\big) +\n \\frac{1}{2} \\ket{11} \\big( a\\ket{1}-b\\ket{0} \\big) .\n$$", "_____no_output_____" ], [ "<h3>Solution</h3>", "_____no_output_____" ], [ "The state before Hadamard is $ \\sqrttwo \\big( a\\ket{000} + a \\ket{011} + b\\ket{110} + b \\ket{101} \\big). $\n\nThe effect of Hadamard to the first qubit is given below:\n\n$ H \\ket{0yz} \\rightarrow \\sqrttwo \\ket{0yz} + \\sqrttwo \\ket{1yz} $\n\n$ H \\ket{1yz} \\rightarrow \\sqrttwo \\ket{0yz} - \\sqrttwo \\ket{1yz} $\n\nFor each triple $ \\ket{xyz} $ in the quantum state, we apply this transformation:", "_____no_output_____" ], [ "$ \n \\frac{1}{2} \\big( a\\ket{000} + a\\ket{100} \\big) + \n \\frac{1}{2} \\big( a\\ket{011} + a\\ket{111} \\big) + \n \\frac{1}{2} \\big( b\\ket{010} - b\\ket{110} \\big) + \n \\frac{1}{2} \\big( b\\ket{001} - b\\ket{101} \\big) .\n$", "_____no_output_____" ], [ "We can rearrange the summation so that we can separate Asja's qubit from the Balvis' qubit:\n\n$ \n \\frac{1}{2} \\big( a\\ket{000}+b\\ket{001} \\big) + \n \\frac{1}{2} \\big( a\\ket{011}+b\\ket{010} \\big) + \n \\frac{1}{2} \\big( a\\ket{100} - b\\ket{101} \\big) + \n \\frac{1}{2} \\big( a\\ket{111}- b\\ket{110} \\big) $.", "_____no_output_____" ], [ "This is equivalent to\n\n$$ \n \\frac{1}{2} \\ket{00} \\big( a\\ket{0}+b\\ket{1} \\big) +\n \\frac{1}{2} \\ket{01} \\big( a\\ket{1}+b\\ket{0} \\big) +\n \\frac{1}{2} \\ket{10} \\big( a\\ket{0}-b\\ket{1} \\big) +\n \\frac{1}{2} \\ket{11} \\big( a\\ket{1}-b\\ket{0} \\big) .\n$$", "_____no_output_____" ], [ "<a id=\"task3\"></a>\n<h3> Task 3 </h3>\n\nAsja sends the measurement outcomes to Balvis by using two classical bits: $ x $ and $ y $. \n\nFor each $ (x,y) $ pair, determine the quantum operator(s) that Balvis can apply to obtain $ \\ket{v} = a\\ket{0}+b\\ket{1} $ exactly.", "_____no_output_____" ], [ "<h3>Solution</h3>", "_____no_output_____" ], [ "<b>Measurement outcome \"00\":</b> The state of Balvis' qubit is $ a\\ket{0}+b\\ket{1} $. \n\nBalvis does not need to apply any extra operation.\n\n<b>Measurement outcome \"01\":</b> The state of Balvis' qubit is $ a\\ket{1}+b\\ket{0} $. \n\nIf Balvis applies <u>NOT operator</u>, then the state becomes: $ a\\ket{0}+b\\ket{1} $.\n\n<b>Measurement outcome \"10\":</b> The state of Balvis' qubit is $ a\\ket{0}-b\\ket{1} $. \n\nIf Balvis applies <u>Z operator</u>, then the state becomes: $ a\\ket{0}+b\\ket{1} $.\n\n<b>Measurement outcome \"11\":</b> The state of Balvis' qubit is $ a\\ket{1}-b\\ket{0} $. \n\nIf Balvis applies <u>NOT operator</u> and <u>Z operator</u>, then the state becomes: $ a\\ket{0}+b\\ket{1} $.", "_____no_output_____" ], [ "<a id=\"task4\"></a>\n<h3> Task 4 </h3>\n\nCreate a quantum circuit with three qubits and two classical bits.\n\nAssume that Asja has the first two qubits and Balvis has the third qubit. \n\nImplement the protocol given above until Balvis makes the measurement.\n<ul>\n <li>Create entanglement between Asja's second qubit and Balvis' qubit.</li>\n <li>The state of Asja's first qubit can be initialized to a randomly picked angle.</li>\n <li>Asja applies CNOT and Hadamard operators to her qubits.</li>\n <li>Asja measures her own qubits and the results are stored in the classical registers. </li>\n</ul>\n\nAt this point, read the state vector of the circuit by using \"statevector_simulator\". \n\n<i> When a circuit having measurement is simulated by \"statevector_simulator\", the simulator picks one of the outcomes, and so we see one of the states after the measurement.</i>\n\nVerify that the state of Balvis' qubit is in one of these: $ \\ket{v_{00}}$, $ \\ket{v_{01}}$, $ \\ket{v_{10}}$, and $ \\ket{v_{11}}$.\n\n<i> Follow the Qiskit order. That is, let qreg[2] be Asja's first qubit, qreg[1] be Asja's second qubit and let qreg[0] be Balvis' qubit.</i>", "_____no_output_____" ], [ "<h3>Solution</h3>", "_____no_output_____" ] ], [ [ "from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,Aer\nfrom random import randrange\nfrom math import sin,cos,pi\n\n# We start with 3 quantum registers\n# qreg[2]: Asja's first qubit - qubit to be teleported\n# qreg[1]: Asja's second qubit\n# qreg[0]: Balvis' qubit\n\nqreg=QuantumRegister(3)\ncreg=ClassicalRegister(2) #Classical register with 2 qubits is enough\nqcir=QuantumCircuit(qreg,creg)\n\n# Generation of the entangled state.\n# Asja's second qubit is entangled with Balvis' qubit.\nqcir.h(qreg[1])\nqcir.cx(qreg[1],qreg[0])\nqcir.barrier()\n\n# We create a random qubit to teleport.\n# We pick a random angle.\nd=randrange(360) \nr=2*pi*d/360\nprint(\"Picked angle is \"+str(d)+\" degrees, \"+str(round(r,2))+\" radians.\")\n\n# The amplitudes of the angle.\nx=cos(r)\ny=sin(r)\nprint(\"cos component of the angle: \"+str(round(x,2))+\", sin component of the angle: \"+str(round(y,2)))\nprint(\"So to be teleported state is \"+str(round(x,2))+\"|0>+\"+str(round(y,2))+\"|1>.\")\n\n#Asja's qubit to be teleported\n# Generation of random qubit by rotating the quantum register at the amount of picked angle.\nqcir.ry(2*r,qreg[2])\nqcir.barrier()\n\n#CNOT operator by Asja where first qubit is the control and second qubit is the target\nqcir.cx(qreg[2],qreg[1])\nqcir.barrier()\n\n#Hadamard operator by Asja on her first qubit\nqcir.h(qreg[2])\nqcir.barrier()\n\n#Measurement by Asja stored in classical registers\nqcir.measure(qreg[1],creg[0])\nqcir.measure(qreg[2],creg[1])\nprint()\n\nresult=execute(qcir,Aer.get_backend('statevector_simulator'),optimization_level=0).result()\nprint(\"When you use statevector_simulator, one of the possible outcomes is picked randomly. Classical registers contain:\")\nprint(result.get_counts()) \nprint()\n\nprint(\"The final statevector.\")\nv=result.get_statevector()\nfor i in range(len(v)):\n print(v[i].real)\nprint()\n\nqcir.draw(output='mpl')", "_____no_output_____" ] ], [ [ "<a id=\"task5\"></a>\n<h3> Task 5 </h3>\n\nImplement the protocol above by including the post-processing part done by Balvis, i.e., the measurement results by Asja are sent to Balvis and then he may apply $ X $ or $ Z $ gates depending on the measurement results.\n\nWe use the classically controlled quantum operators. \n\nSince we do not make measurement on $ q[2] $, we define only 2 classical bits, each of which can also be defined separated.\n\n```python\nq = QuantumRegister(3)\nc2 = ClassicalRegister(1,'c2')\nc1 = ClassicalRegister(1,'c1')\nqc = QuantumCircuit(q,c1,c2)\n...\nqc.measure(q[1],c1)\n...\nqc.x(q[0]).c_if(c1,1) # x-gate is applied to q[0] if the classical bit c1 is equal to 1\n```\n\nRead the state vector and verify that Balvis' state is $ \\myvector{a \\\\ b} $ after the post-processing.", "_____no_output_____" ], [ "<h3>Solution</h3>", "_____no_output_____" ], [ "<i>Classically controlled</i> recovery operations are also added as follows. Below, the state vector is used to confirm that quantum teleportation is completed.", "_____no_output_____" ] ], [ [ "from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,Aer\nfrom random import randrange\nfrom math import sin,cos,pi\n\n# We start with 3 quantum registers\n# qreg[2]: Asja's first qubit - qubit to be teleported\n# qreg[1]: Asja's second qubit\n# qreg[0]: Balvis' qubit\n\nqreg=QuantumRegister(3)\nc1=ClassicalRegister(1)\nc2=ClassicalRegister(1)\nqcir=QuantumCircuit(qreg,c1,c2)\n\n# Generation of the entangled state.\n# Asja's second qubit is entangled with Balvis' qubit.\nqcir.h(qreg[1])\nqcir.cx(qreg[1],qreg[0])\nqcir.barrier()\n\n# We create a random qubit to teleport.\n# We pick a random angle.\nd=randrange(360) \nr=2*pi*d/360\nprint(\"Picked angle is \"+str(d)+\" degrees, \"+str(round(r,2))+\" radians.\")\n\n# The amplitudes of the angle.\nx=cos(r)\ny=sin(r)\nprint(\"Cos component of the angle: \"+str(round(x,2))+\", sin component of the angle: \"+str(round(y,2)))\nprint(\"So to be teleported state is \"+str(round(x,2))+\"|0>+\"+str(round(y,2))+\"|1>.\")\n\n#Asja's qubit to be teleported\n# Generation of random qubit by rotating the quantum register at the amount of picked angle.\nqcir.ry(2*r,qreg[2])\nqcir.barrier()\n\n#CNOT operator by Asja where first qubit is the control and second qubit is the target\nqcir.cx(qreg[2],qreg[1])\nqcir.barrier()\n\n#Hadamard operator by Asja on the first qubit\nqcir.h(qreg[2])\nqcir.barrier()\n\n#Measurement by Asja stored in classical registers\nqcir.measure(qreg[1],c1)\nqcir.measure(qreg[2],c2)\nprint()\n\n#Post processing by Balvis\nqcir.x(qreg[0]).c_if(c1,1)\nqcir.z(qreg[0]).c_if(c2,1)\n\nresult2=execute(qcir,Aer.get_backend('statevector_simulator'),optimization_level=0).result()\nprint(\"When you use statevector_simulator, one of the possible outcomes is picked randomly. Classical registers contain:\")\nprint(result2.get_counts()) # \nprint()\n\nprint(\"The final statevector.\")\nv=result2.get_statevector()\nfor i in range(len(v)):\n print(v[i].real)\nprint()\n\nqcir.draw(output='mpl')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ] ]
d07528734fb1d91c07adeea1f862ca118fff50bb
11,787
ipynb
Jupyter Notebook
DLISIO_Simple_Reading.ipynb
dcslagel/DLISIO_Notebooks
97ca43490a46b104bd278357c183d58134b2c6b8
[ "MIT" ]
10
2019-05-07T05:45:19.000Z
2021-11-27T12:39:03.000Z
DLISIO_Simple_Reading.ipynb
dcslagel/DLISIO_Notebooks
97ca43490a46b104bd278357c183d58134b2c6b8
[ "MIT" ]
4
2020-08-07T13:54:19.000Z
2020-11-13T15:18:45.000Z
DLISIO_Simple_Reading.ipynb
dcslagel/DLISIO_Notebooks
97ca43490a46b104bd278357c183d58134b2c6b8
[ "MIT" ]
5
2019-10-17T11:39:14.000Z
2022-03-16T04:18:16.000Z
28.960688
391
0.539662
[ [ [ "# DLISIO in a Nutshell", "_____no_output_____" ], [ "## Importing", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport os\nimport pandas as pd\nimport dlisio\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.lib.recfunctions as rfn\n\nimport hvplot.pandas\nimport holoviews as hv\nfrom holoviews import opts, streams\nfrom holoviews.plotting.links import DataLink\nhv.extension('bokeh', logo=None)", "_____no_output_____" ] ], [ [ "### You can work with a single file using the cell below - or by adding an additional for loop to the code below, you can work through a list of files. Another option is to use os.walk to get all .dlis files in a parent folder. Example:\n\n for (root, dirs, files) in os.walk(folderpath):\n for f in files:\n filepath = os.path.join(root, f)\n if filepath.endswith('.' + 'dlis'):\n print(filepath)\n \n### But for this example, we will work with a single .dlis file specified in the cell below. Note that there are some .dlis file formats that are not supported by DLISIO yet - good to catch them in a try except loop if you are reading files enmasse.", "_____no_output_____" ], [ "### We will load a dlis file from the open source Volve dataset available here: https://data.equinor.com/dataset/Volve", "_____no_output_____" ] ], [ [ "filepath = r\"\"", "_____no_output_____" ] ], [ [ "## Query for specific curve\n\n### Very quickly you can use regex to find certain curves in a file (helpful if you are scanning a lot of files for certain curves)", "_____no_output_____" ] ], [ [ "with dlisio.dlis.load(filepath) as file:\n for d in file:\n depth_channels = d.find('CHANNEL','DEPT')\n for channel in depth_channels:\n print(channel.name)\n print(channel.curves())", "_____no_output_____" ] ], [ [ "## Examining internal files and frames\n\n### Keep in mind that dlis files can contain multiple files and multiple frames. You can quickly get a numpy array of the curves in each frame below.", "_____no_output_____" ] ], [ [ "with dlisio.dlis.load(filepath) as file:\n print(file.describe())", "_____no_output_____" ], [ "with dlisio.dlis.load(filepath) as file:\n for d in file:\n for fram in d.frames:\n print(d.channels)\n print(fram.curves())", "_____no_output_____" ] ], [ [ "## Metadata including Origin information (well name and header)", "_____no_output_____" ] ], [ [ "with dlisio.dlis.load(filepath) as file:\n for d in file:\n print(d.describe())\n for fram in d.frames:\n print(fram.describe())\n for channel in d.channels:\n print(channel.describe())", "_____no_output_____" ], [ "with dlisio.dlis.load(filepath) as file:\n for d in file:\n for origin in d.origins:\n print(origin.describe())", "_____no_output_____" ] ], [ [ "## Reading a full dlis file\n\n### But most likely we want a single data frame of every curve, no matter which frame it came from. So we write a bit more code to look through each frame, then look at each channel and get the curve name and unit information along with it. We will also save the information about which internal file and which frame each curve resides in. ", "_____no_output_____" ] ], [ [ "curves_L = []\ncurves_name = []\nlongs = []\nunit = []\nfiles_L = []\nfiles_num = []\nframes = []\nframes_num = []\nwith dlisio.dlis.load(filepath) as file:\n for d in file:\n files_L.append(d)\n frame_count = 0\n for fram in d.frames:\n if frame_count == 0:\n frames.append(fram)\n frame_count = frame_count + 1\n for channel in d.channels:\n curves_name.append(channel.name)\n longs.append(channel.long_name)\n unit.append(channel.units)\n files_num.append(len(files_L))\n frames_num.append(len(frames))\n curves = channel.curves()\n curves_L.append(curves)", "_____no_output_____" ], [ "curve_index = pd.DataFrame(\n{'Curve': curves_name,\n'Long': longs,\n'Unit': unit,\n'Internal_File': files_num,\n'Frame_Number': frames_num\n})", "_____no_output_____" ], [ "curve_index", "_____no_output_____" ] ], [ [ "## Creating a Pandas dataframe for the entire .dlis file\n\n### We have to be careful creating a dataframe for the whole .dlis file as often there are some curves that represent mulitple values (numpy array of list values). So, you can use something like:\n\ndf = pd.DataFrame(data=curves_L, index=curves_name).T\n\n### to view the full dlis file with lists as some of the curve values.\n\n### Or we will use the code below to process each curve's 2D numpy array, stacking it if the curve contains multiple values per sample. Then we convert each curve into its own dataframe (uniquifying the column names by adding a .1, .2, .3...etc). Then, to preserve the order with the curve index above, append each data frame together in order to build the final dlis full dataframe.", "_____no_output_____" ] ], [ [ "def df_column_uniquify(df):\n df_columns = df.columns\n new_columns = []\n for item in df_columns:\n counter = 0\n newitem = item\n while newitem in new_columns:\n counter += 1\n newitem = \"{}_{}\".format(item, counter)\n new_columns.append(newitem)\n df.columns = new_columns\n return df", "_____no_output_____" ], [ "curve_df = pd.DataFrame()\nname_index = 0\nfor c in curves_L:\n name = curves_name[name_index]\n np.vstack(c)\n try:\n num_col = c.shape[1]\n col_name = [name] * num_col\n df = pd.DataFrame(data=c, columns=col_name)\n name_index = name_index + 1\n df = df_column_uniquify(df)\n curve_df = pd.concat([curve_df, df], axis=1)\n except:\n num_col = 0\n df = pd.DataFrame(data=c, columns=[name])\n name_index = name_index + 1\n curve_df = pd.concat([curve_df, df], axis=1)\n continue", "_____no_output_____" ], [ "curve_df.head()", "_____no_output_____" ], [ "## If we have a simpler dlis file with a single logical file and single frame and with single data values in each channel.\nwith dlisio.dlis.load(filepath) as file:\n logical_count = 0\n for d in file:\n frame_count = 0\n for fram in d.frames:\n if frame_count == 0 & logical_count == 0:\n curves = fram.curves()\n curve_df = pd.DataFrame(curves, index=curves[fram.index])", "_____no_output_____" ], [ "curve_df.head()", "_____no_output_____" ] ], [ [ "### Then we can set the index and start making some plots.", "_____no_output_____" ] ], [ [ "curve_df = df_column_uniquify(curve_df)\ncurve_df['DEPTH_Calc_ft'] = curve_df.loc[:,'TDEP'] * 0.0083333 #0.1 inch/12 inches per foot\ncurve_df['DEPTH_ft'] = curve_df['DEPTH_Calc_ft']\ncurve_df = curve_df.set_index(\"DEPTH_Calc_ft\")\ncurve_df.index.names = [None]\ncurve_df = curve_df.replace(-999.25,np.nan)\nmin_val = curve_df['DEPTH_ft'].min()\nmax_val = curve_df['DEPTH_ft'].max()\ncurve_list = list(curve_df.columns)\ncurve_list.remove('DEPTH_ft')", "_____no_output_____" ], [ "curve_df.head()", "_____no_output_____" ], [ "def curve_plot(log, df, depthname):\n aplot = df.hvplot(x=depthname, y=log, invert=True, flip_yaxis=True, shared_axes=True,\n height=600, width=300).opts(fontsize={'labels': 16,'xticks': 14, 'yticks': 14})\n return aplot;", "_____no_output_____" ], [ "plotlist = [curve_plot(x, df=curve_df, depthname='DEPTH_ft') for x in curve_list]\nwell_section = hv.Layout(plotlist).cols(len(curve_list))\nwell_section", "_____no_output_____" ] ], [ [ "# Hopefully that is enough code to get you started working with DLISIO. There is much more functionality which can be accessed with help(dlisio) or at the read the docs.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
d07529bfad67513f710ed6948aecc5b0456b59f6
10,032
ipynb
Jupyter Notebook
day15/plottingACourse5_ChitonCave.ipynb
nManger/adventOfCode2021
c48a1e50311298fb36a5094ffae952e6c200b27d
[ "MIT" ]
null
null
null
day15/plottingACourse5_ChitonCave.ipynb
nManger/adventOfCode2021
c48a1e50311298fb36a5094ffae952e6c200b27d
[ "MIT" ]
null
null
null
day15/plottingACourse5_ChitonCave.ipynb
nManger/adventOfCode2021
c48a1e50311298fb36a5094ffae952e6c200b27d
[ "MIT" ]
null
null
null
27.113514
119
0.431519
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d0754cde7485c84aa306bf91d398db393d199494
106,765
ipynb
Jupyter Notebook
EMNIST/emnist-letters.ipynb
khanhtran2000/OCR-Dev
da8ebaf7e11bad01388a9b73585a093a258990e9
[ "Apache-2.0" ]
5
2020-05-31T19:22:32.000Z
2021-03-15T10:38:17.000Z
EMNIST/emnist-letters.ipynb
khanhtran2000/OCR-Dev
da8ebaf7e11bad01388a9b73585a093a258990e9
[ "Apache-2.0" ]
null
null
null
EMNIST/emnist-letters.ipynb
khanhtran2000/OCR-Dev
da8ebaf7e11bad01388a9b73585a093a258990e9
[ "Apache-2.0" ]
null
null
null
106,765
106,765
0.860451
[ [ [ "# Import modules\nimport numpy as np \nimport pandas as pd \nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport math\n\nfrom sklearn.model_selection import train_test_split\nimport sklearn.metrics as metrics\n\n#keras\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import BatchNormalization, Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D\nfrom tensorflow.keras.callbacks import LearningRateScheduler, EarlyStopping\nfrom tensorflow.keras.metrics import top_k_categorical_accuracy", "_____no_output_____" ], [ "def reduce_mem_usage(df):\n \"\"\" iterate through all the columns of a dataframe and modify the data type\n to reduce memory usage. \n \"\"\"\n start_mem = df.memory_usage().sum() / 1024**2\n print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n \n for col in df.columns:\n col_type = df[col].dtype\n \n if col_type != object:\n c_min = df[col].min()\n c_max = df[col].max()\n if str(col_type)[:3] == 'int':\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64) \n else:\n if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n df[col] = df[col].astype(np.float16)\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n df[col] = df[col].astype(np.float32)\n else:\n df[col] = df[col].astype(np.float64)\n else:\n df[col] = df[col].astype('category')\n\n end_mem = df.memory_usage().sum() / 1024**2\n print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n \n return df\n\n\ndef import_data(file):\n \"\"\"create a dataframe and optimize its memory usage\"\"\"\n df = pd.read_csv(file, parse_dates=True, keep_date_col=True)\n df = reduce_mem_usage(df)\n return df", "_____no_output_____" ], [ "train = import_data(r'../input/emnist/emnist-letters-train.csv')\ntest = import_data(r'../input/emnist/emnist-letters-test.csv')\n\nprint(\"Train: %s, Test: %s\" %(train.shape, test.shape))", "Memory usage of dataframe is 531.82 MB\nMemory usage after optimization is: 124.57 MB\nDecreased by 76.6%\nMemory usage of dataframe is 88.63 MB\nMemory usage after optimization is: 20.10 MB\nDecreased by 77.3%\nTrain: (88799, 785), Test: (14799, 785)\n" ], [ "# iam_1 = import_data('../input/iam-edited/iam_1_edit.csv')\n# iam_2 = import_data('../input/iam-edited/iam_2_edit.csv')\n# iam_3 = import_data('../input/iam-edited/iam_3_edit.csv')\n# iam_4 = import_data('../input/iam-edited/iam_11_edit.csv')", "_____no_output_____" ], [ "# iam = pd.concat([iam_1,iam_2,iam_3,iam_4],axis=0)\n# iam.columns = train.columns.values\n\n# iam_35_labels = list(iam['35'].values)\n# iam_labels = []\n\n# for i in iam['35'].values:\n# if i < 58:\n# i -= 48\n# iam_labels.append(i)\n# elif 58 < i < 91:\n# i -= 55\n# iam_labels.append(i)\n# elif 91 < i:\n# i -= 61\n# iam_labels.append(i)\n\n# iam['35'].replace(dict(zip(iam_35_labels,iam_labels)),inplace=True)\n# iam", "_____no_output_____" ], [ "mapp = pd.read_csv(\n r'../input/emnist/emnist-letters-mapping.txt',\n delimiter=' ',\n index_col=0,\n header=None,\n squeeze=True\n)", "_____no_output_____" ], [ "# train_half = pd.DataFrame(columns=list(train.columns.values))\n\n# for label in mapp.values:\n# train_label = train[train['35']==(label-48)]\n# train_label = train_label.iloc[::2]\n# train_half = pd.concat([train_half,train_label],axis=0)\n ", "_____no_output_____" ], [ "# train_x_half = train_half.iloc[:,1:] # Get the images\n# train_y_half = train_half.iloc[:,0] # Get the label\n\n# del train_half", "_____no_output_____" ], [ "# train_x_half = np.asarray(train_x_half)\n# train_x_half = np.apply_along_axis(rotate, 1, train_x_half)\n# print (\"train_x:\",train_x_half.shape)", "_____no_output_____" ], [ "# iam_x = iam.iloc[:,1:] # Get the images\n# iam_y = iam.iloc[:,0] # Get the label\n\n# del iam", "_____no_output_____" ], [ "# iam_x = np.asarray(iam_x)\n# iam_x = np.apply_along_axis(rotate, 1, iam_x)\n# print (\"iam_x:\",iam_x.shape)", "_____no_output_____" ], [ "# train_x = np.concatenate((train_x_half,iam_x),axis=0)\n# print(train_x.shape)\n# train_y = np.concatenate((train_y_half,iam_y),axis=0)\n# print(train_y.shape)\n\n# del train_x_half\n# del train_y_half\n# del iam_x\n# del iam_y", "_____no_output_____" ], [ "# train_new = pd.concat([train_half,iam],0)\n# train_new.shape", "_____no_output_____" ], [ "# Constants\nHEIGHT = 28\nWIDTH = 28\n\n# del train_half\n# del iam ", "_____no_output_____" ], [ "# Split x and y\ntrain_x = train.iloc[:,1:] # Get the images\ntrain_y = train.iloc[:,0] # Get the label\ndel train # free up some memory\n\ntest_x = test.iloc[:,1:]\ntest_y = test.iloc[:,0]\ndel test", "_____no_output_____" ], [ "# Reshape and rotate EMNIST images\ndef rotate(image):\n image = image.reshape(HEIGHT, WIDTH)\n image = np.fliplr(image)\n image = np.rot90(image)\n return image ", "_____no_output_____" ], [ "# Flip and rotate image\ntrain_x = np.asarray(train_x)\ntrain_x = np.apply_along_axis(rotate, 1, train_x)\nprint (\"train_x:\",train_x.shape)\n\ntest_x = np.asarray(test_x)\ntest_x = np.apply_along_axis(rotate, 1, test_x)\nprint (\"test_x:\",test_x.shape)", "train_x: (88799, 28, 28)\ntest_x: (14799, 28, 28)\n" ], [ "# Normalize\ntrain_x = train_x / 255.0\ntest_x = test_x / 255.0\nprint(type(train_x[0,0,0]))\nprint(type(test_x[0,0,0]))", "<class 'numpy.float64'>\n<class 'numpy.float64'>\n" ], [ "# Plot image\nfor i in range(100,109):\n plt.subplot(330 + (i+1))\n plt.subplots_adjust(hspace=0.5, top=1)\n plt.imshow(train_x[i], cmap=plt.get_cmap('gray'))\n plt.title(chr(mapp.iloc[train_y[i]-1,0]))", "_____no_output_____" ], [ "# Number of classes\nnum_classes = train_y.nunique() # .nunique() returns the number of unique objects\nprint(num_classes) ", "26\n" ], [ "# One hot encoding\ntrain_y = to_categorical(train_y-1, num_classes)\ntest_y = to_categorical(test_y-1, num_classes)\nprint(\"train_y: \", train_y.shape)\nprint(\"test_y: \", test_y.shape)", "train_y: (88799, 26)\ntest_y: (14799, 26)\n" ], [ "# partition to train and val\ntrain_x, val_x, train_y, val_y = train_test_split(train_x, \n train_y, \n test_size=0.10, \n random_state=7)\n\nprint(train_x.shape, val_x.shape, train_y.shape, val_y.shape)", "(79919, 28, 28) (8880, 28, 28) (79919, 26) (8880, 26)\n" ], [ "# Reshape\ntrain_x = train_x.reshape(-1, HEIGHT, WIDTH, 1)\ntest_x = test_x.reshape(-1, HEIGHT, WIDTH, 1)\nval_x = val_x.reshape(-1, HEIGHT, WIDTH, 1)", "_____no_output_____" ], [ "# Create more images via data augmentation\ndatagen = ImageDataGenerator(\n rotation_range = 10,\n zoom_range = 0.10,\n width_shift_range=0.1,\n height_shift_range=0.1\n)\n\ntrain_gen = datagen.flow(train_x, train_y, batch_size=64)\nval_gen = datagen.flow(val_x, val_y, batch_size=64)", "_____no_output_____" ], [ "# Building model\n# ((Si - Fi + 2P)/S) + 1\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=3, activation='relu', input_shape=(HEIGHT, WIDTH, 1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32, kernel_size=3,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32, kernel_size=5, strides=2, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\n\n\nmodel.add(Conv2D(64, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size=3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size=5, strides=2, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\n\n\nmodel.add(Conv2D(128, kernel_size=4, activation='relu'))\nmodel.add(BatchNormalization())\n\n\nmodel.add(Flatten())\nmodel.add(Dropout(0.4))\nmodel.add(Dense(units=num_classes, activation='softmax'))\n\ninput_shape = (None, HEIGHT, WIDTH, 1)\nmodel.build(input_shape)\nmodel.summary()\n", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 26, 26, 32) 320 \n_________________________________________________________________\nbatch_normalization (BatchNo (None, 26, 26, 32) 128 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 24, 24, 32) 9248 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 24, 24, 32) 128 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 12, 12, 32) 25632 \n_________________________________________________________________\nbatch_normalization_2 (Batch (None, 12, 12, 32) 128 \n_________________________________________________________________\ndropout (Dropout) (None, 12, 12, 32) 0 \n_________________________________________________________________\nconv2d_3 (Conv2D) (None, 10, 10, 64) 18496 \n_________________________________________________________________\nbatch_normalization_3 (Batch (None, 10, 10, 64) 256 \n_________________________________________________________________\nconv2d_4 (Conv2D) (None, 8, 8, 64) 36928 \n_________________________________________________________________\nbatch_normalization_4 (Batch (None, 8, 8, 64) 256 \n_________________________________________________________________\nconv2d_5 (Conv2D) (None, 4, 4, 64) 102464 \n_________________________________________________________________\nbatch_normalization_5 (Batch (None, 4, 4, 64) 256 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 4, 4, 64) 0 \n_________________________________________________________________\nconv2d_6 (Conv2D) (None, 1, 1, 128) 131200 \n_________________________________________________________________\nbatch_normalization_6 (Batch (None, 1, 1, 128) 512 \n_________________________________________________________________\nflatten (Flatten) (None, 128) 0 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 128) 0 \n_________________________________________________________________\ndense (Dense) (None, 26) 3354 \n=================================================================\nTotal params: 329,306\nTrainable params: 328,474\nNon-trainable params: 832\n_________________________________________________________________\n" ], [ "my_callbacks = [\n # Decrease learning rate\n LearningRateScheduler(lambda x: 1e-3 * 0.95 ** x),\n # Training will stop there is no improvement in val_loss after 3 epochs\n EarlyStopping(monitor=\"val_acc\", \n patience=3, \n mode='max', \n restore_best_weights=True)\n]\n\n# def top_3_accuracy(y_true, y_pred):\n# return top_k_categorical_accuracy(y_true, y_pred, k=3)\n\n\n# TRAIN NETWORKS\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n# history = model.fit(train_x, train_y, \n# epochs=100,\n# verbose=1, validation_data=(val_x, val_y), \n# callbacks=my_callbacks)\n\n# With datagen\nhistory = model.fit_generator(train_gen, steps_per_epoch=train_x.shape[0]//64, epochs=100,\n validation_data=val_gen, validation_steps=val_x.shape[0]//64, callbacks=my_callbacks)", "Train for 1248 steps, validate for 138 steps\nEpoch 1/100\n1248/1248 [==============================] - 36s 29ms/step - loss: 0.3048 - accuracy: 0.9061 - val_loss: 0.2035 - val_accuracy: 0.9321\nEpoch 2/100\n1248/1248 [==============================] - 34s 27ms/step - loss: 0.2427 - accuracy: 0.9202 - val_loss: 0.1902 - val_accuracy: 0.9332\nEpoch 3/100\n1248/1248 [==============================] - 34s 27ms/step - loss: 0.2270 - accuracy: 0.9242 - val_loss: 0.1792 - val_accuracy: 0.9385\nEpoch 4/100\n1248/1248 [==============================] - 35s 28ms/step - loss: 0.2193 - accuracy: 0.9259 - val_loss: 0.1642 - val_accuracy: 0.9391\nEpoch 5/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.2098 - accuracy: 0.9300 - val_loss: 0.1768 - val_accuracy: 0.9402\nEpoch 6/100\n1248/1248 [==============================] - 33s 27ms/step - loss: 0.2037 - accuracy: 0.9320 - val_loss: 0.1603 - val_accuracy: 0.9436\nEpoch 7/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1989 - accuracy: 0.9324 - val_loss: 0.1620 - val_accuracy: 0.9451\nEpoch 8/100\n1248/1248 [==============================] - 33s 27ms/step - loss: 0.1899 - accuracy: 0.9349 - val_loss: 0.1576 - val_accuracy: 0.9451\nEpoch 9/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1898 - accuracy: 0.9353 - val_loss: 0.1562 - val_accuracy: 0.9443\nEpoch 10/100\n1248/1248 [==============================] - 33s 27ms/step - loss: 0.1880 - accuracy: 0.9364 - val_loss: 0.1580 - val_accuracy: 0.9444\nEpoch 11/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1820 - accuracy: 0.9378 - val_loss: 0.1560 - val_accuracy: 0.9475\nEpoch 12/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1786 - accuracy: 0.9384 - val_loss: 0.1580 - val_accuracy: 0.9445\nEpoch 13/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1759 - accuracy: 0.9395 - val_loss: 0.1530 - val_accuracy: 0.9453\nEpoch 14/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1725 - accuracy: 0.9397 - val_loss: 0.1555 - val_accuracy: 0.9441\nEpoch 15/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1713 - accuracy: 0.9402 - val_loss: 0.1495 - val_accuracy: 0.9474\nEpoch 16/100\n1248/1248 [==============================] - 32s 25ms/step - loss: 0.1697 - accuracy: 0.9407 - val_loss: 0.1493 - val_accuracy: 0.9461\nEpoch 17/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1701 - accuracy: 0.9415 - val_loss: 0.1447 - val_accuracy: 0.9494\nEpoch 18/100\n1248/1248 [==============================] - 32s 25ms/step - loss: 0.1624 - accuracy: 0.9436 - val_loss: 0.1527 - val_accuracy: 0.9462\nEpoch 19/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1637 - accuracy: 0.9426 - val_loss: 0.1440 - val_accuracy: 0.9492\nEpoch 20/100\n1248/1248 [==============================] - 32s 25ms/step - loss: 0.1618 - accuracy: 0.9438 - val_loss: 0.1425 - val_accuracy: 0.9474\nEpoch 21/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1585 - accuracy: 0.9447 - val_loss: 0.1550 - val_accuracy: 0.9462\nEpoch 22/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1587 - accuracy: 0.9456 - val_loss: 0.1425 - val_accuracy: 0.9500\nEpoch 23/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1574 - accuracy: 0.9448 - val_loss: 0.1409 - val_accuracy: 0.9502\nEpoch 24/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1570 - accuracy: 0.9460 - val_loss: 0.1454 - val_accuracy: 0.9488\nEpoch 25/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1552 - accuracy: 0.9458 - val_loss: 0.1480 - val_accuracy: 0.9484\nEpoch 26/100\n1248/1248 [==============================] - 30s 24ms/step - loss: 0.1539 - accuracy: 0.9460 - val_loss: 0.1416 - val_accuracy: 0.9506\nEpoch 27/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1509 - accuracy: 0.9474 - val_loss: 0.1480 - val_accuracy: 0.9487\nEpoch 28/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1495 - accuracy: 0.9467 - val_loss: 0.1401 - val_accuracy: 0.9497\nEpoch 29/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1493 - accuracy: 0.9474 - val_loss: 0.1386 - val_accuracy: 0.9529\nEpoch 30/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1495 - accuracy: 0.9472 - val_loss: 0.1406 - val_accuracy: 0.9494\nEpoch 31/100\n1248/1248 [==============================] - 31s 24ms/step - loss: 0.1480 - accuracy: 0.9478 - val_loss: 0.1403 - val_accuracy: 0.9505\nEpoch 32/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1465 - accuracy: 0.9485 - val_loss: 0.1395 - val_accuracy: 0.9485\nEpoch 33/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1467 - accuracy: 0.9469 - val_loss: 0.1403 - val_accuracy: 0.9534\nEpoch 34/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1462 - accuracy: 0.9487 - val_loss: 0.1400 - val_accuracy: 0.9498\nEpoch 35/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1458 - accuracy: 0.9484 - val_loss: 0.1380 - val_accuracy: 0.9518\nEpoch 36/100\n1248/1248 [==============================] - 32s 25ms/step - loss: 0.1447 - accuracy: 0.9480 - val_loss: 0.1466 - val_accuracy: 0.9512\nEpoch 37/100\n1248/1248 [==============================] - 31s 24ms/step - loss: 0.1428 - accuracy: 0.9483 - val_loss: 0.1426 - val_accuracy: 0.9523\nEpoch 38/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1415 - accuracy: 0.9495 - val_loss: 0.1345 - val_accuracy: 0.9505\nEpoch 39/100\n1248/1248 [==============================] - 30s 24ms/step - loss: 0.1398 - accuracy: 0.9490 - val_loss: 0.1366 - val_accuracy: 0.9514\nEpoch 40/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1425 - accuracy: 0.9494 - val_loss: 0.1396 - val_accuracy: 0.9521\nEpoch 41/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1402 - accuracy: 0.9491 - val_loss: 0.1364 - val_accuracy: 0.9523\nEpoch 42/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1404 - accuracy: 0.9497 - val_loss: 0.1391 - val_accuracy: 0.9537\nEpoch 43/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1420 - accuracy: 0.9493 - val_loss: 0.1371 - val_accuracy: 0.9518\nEpoch 44/100\n1248/1248 [==============================] - 33s 27ms/step - loss: 0.1399 - accuracy: 0.9495 - val_loss: 0.1369 - val_accuracy: 0.9504\nEpoch 45/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1392 - accuracy: 0.9500 - val_loss: 0.1375 - val_accuracy: 0.9524\nEpoch 46/100\n1248/1248 [==============================] - 34s 27ms/step - loss: 0.1372 - accuracy: 0.9505 - val_loss: 0.1376 - val_accuracy: 0.9523\nEpoch 47/100\n1248/1248 [==============================] - 33s 26ms/step - loss: 0.1374 - accuracy: 0.9501 - val_loss: 0.1396 - val_accuracy: 0.9526\nEpoch 48/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1371 - accuracy: 0.9507 - val_loss: 0.1327 - val_accuracy: 0.9532\nEpoch 49/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1364 - accuracy: 0.9508 - val_loss: 0.1326 - val_accuracy: 0.9522\nEpoch 50/100\n1248/1248 [==============================] - 32s 25ms/step - loss: 0.1372 - accuracy: 0.9499 - val_loss: 0.1391 - val_accuracy: 0.9524\nEpoch 51/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1356 - accuracy: 0.9515 - val_loss: 0.1352 - val_accuracy: 0.9529\nEpoch 52/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1367 - accuracy: 0.9507 - val_loss: 0.1364 - val_accuracy: 0.9526\nEpoch 53/100\n1248/1248 [==============================] - 32s 26ms/step - loss: 0.1366 - accuracy: 0.9501 - val_loss: 0.1387 - val_accuracy: 0.9517\nEpoch 54/100\n1248/1248 [==============================] - 31s 25ms/step - loss: 0.1339 - accuracy: 0.9503 - val_loss: 0.1370 - val_accuracy: 0.9520\nEpoch 55/100\n1248/1248 [==============================] - 32s 25ms/step - loss: 0.1346 - accuracy: 0.9513 - val_loss: 0.1370 - val_accuracy: 0.9529\nEpoch 56/100\n" ], [ "# plot accuracy and loss\ndef plotacc(epochs, acc, val_acc):\n # Plot training & validation accuracy values\n plt.plot(epochs, acc, 'b')\n plt.plot(epochs, val_acc, 'r')\n plt.title('Model accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Val'], loc='upper left')\n plt.show()\n\ndef plotloss(epochs, acc, val_acc):\n # Plot training & validation accuracy values\n plt.plot(epochs, acc, 'b')\n plt.plot(epochs, val_acc, 'r')\n plt.title('Model loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Val'], loc='upper left')\n plt.show()", "_____no_output_____" ], [ "#%%\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1,len(acc)+1)", "_____no_output_____" ], [ "# Accuracy curve\nplotgraph(epochs, acc, val_acc)\n\n# loss curve\nplotloss(epochs, loss, val_loss)", "_____no_output_____" ], [ "# del train_x\n# del train_y\n\nscore = model.evaluate(test_x, test_y, verbose=0)\nprint(\"Test loss:\", score[0])\nprint(\"Test accuracy:\", score[1])", "Test loss: 0.15562304878689265\nTest accuracy: 0.9464829\n" ], [ "model.save(\"emnist_model_letters_aug.h5\")", "_____no_output_____" ], [ "model.save_weights(\"emnist_model_weights_letters_aug.h5\")", "_____no_output_____" ], [ "y_pred = model.predict(test_x)\ny_pred = (y_pred > 0.5)\n\ncm = metrics.confusion_matrix(test_y.argmax(axis=1), y_pred.argmax(axis=1))\nprint(cm)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0755c499ac22f637b9ba7ef518bb440a03688e9
23,728
ipynb
Jupyter Notebook
q2q_transfer_learning.ipynb
Jerry2001Qu/quantum-transfer-learning
231def697d689e761af997634318bb31d6785c01
[ "Apache-2.0" ]
43
2019-12-17T04:58:49.000Z
2022-02-27T17:02:07.000Z
q2q_transfer_learning.ipynb
Jerry2001Qu/quantum-transfer-learning
231def697d689e761af997634318bb31d6785c01
[ "Apache-2.0" ]
9
2020-01-20T19:43:31.000Z
2022-03-12T07:13:38.000Z
q2q_transfer_learning.ipynb
pkino/quantum-transfer-learning
e92df0c0794c283dd51dde7be5f2d8496ebb85b5
[ "Apache-2.0" ]
26
2020-01-20T04:23:21.000Z
2022-03-23T06:05:31.000Z
39.67893
347
0.559128
[ [ [ "# Example 5: Quantum-to-quantum transfer learning.", "_____no_output_____" ], [ "This is an example of a continuous variable (CV) quantum network for state classification, developed according to the *quantum-to-quantum transfer learning* scheme presented in [1]. \n\n## Introduction \n\n\nIn this proof-of-principle demonstration we consider two distinct toy datasets of Gaussian and non-Gaussian states. Such datasets can be generated according to the following simple prescriptions:\n\n**Dataset A**: \n- Class 0 (Gaussian): random Gaussian layer applied to the vacuum. \n- Class 1 (non-Gaussian): random non-Gaussian Layer applied to the vacuum. \n \n**Dataset B**: \n- Class 0 (Gaussian): random Gaussian layer applied to a coherent state with amplitude $\\alpha=1$.\n- Class 1 (non-Gaussian): random Gaussian layer applied to a single photon Fock state $|1\\rangle$.\n\n**Variational Circuit A**: \nOur starting point is a single-mode variational circuit [2] (a non-Gaussian layer), pre-trained on _Dataset A_. We assume that after the circuit is applied, the output mode is measured with an _on/off_ detector. By averaging over many shots, one can estimate the vacuum probability:\n\n$$\np_0 = | \\langle \\psi_{\\rm out} |0 \\rangle|^2. \n$$\n\nWe use _Dataset A_ and train the circuit to rotate Gaussian states towards the vacuum while non-Gaussian states far away from the vacuum. For the final classification we use the simple decision rule:\n\n$$\np_0 \\ge 0 \\longrightarrow {\\rm Class=0.} \\\\\np_0 < 0 \\longrightarrow {\\rm Class=1.}\n$$\n\n**Variational Circuit B**: \nOnce _Circuit A_ has been optimized, we can use is as a pre-trained block\napplicable also to the different _Dataset B_. In other words, we implement a _quantum-to-quantum_ transfer learning model:\n\n_Circuit B_ = _Circuit A_ (pre-trained) followed by a sequence of _variational layers_ (to be trained).\n\nAlso in this case, after the application of _Circuit B_, we assume to measure the single mode with an _on/off_ detector, and we apply a similar classification rule:\n\n$$\np_0 \\ge 0 \\longrightarrow {\\rm Class=1.} \\\\\np_0 < 0 \\longrightarrow {\\rm Class=0.}\n$$\n\nThe motivation for this transfer learning approach is that, even if _Circuit A_ is optimized on a different dataset, it can still act as a good pre-processing block also for _Dataset B_. Ineeed, as we are going to show, the application of _Circuit A_ can significantly improve the training efficiency of _Circuit B_.", "_____no_output_____" ], [ "## General setup\n\nThe main imported modules are: the `tensorflow` machine learning framework, the quantum CV \nsoftware `strawberryfields` [3] and the python plotting library `matplotlib`. All modules should be correctly installed in the system before running this notebook.", "_____no_output_____" ] ], [ [ "# Plotting\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\n# TensorFlow\nimport tensorflow as tf\n\n# Strawberryfields (simulation of CV quantum circuits)\nimport strawberryfields as sf\nfrom strawberryfields.ops import Dgate, Kgate, Sgate, Rgate, Vgate, Fock, Ket\n\n# Other modules\nimport numpy as np\nimport time\n\n# System variables\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # avoid warning messages\nos.environ['OMP_NUM_THREADS'] = '1' # set number of threads.\nos.environ['CUDA_VISIBLE_DEVICES'] = '1' # select the GPU unit.\n\n# Path with pre-trained parameters\nweights_path = 'results/weights/'", "_____no_output_____" ] ], [ [ "Setting of the main parameters of the network model and of the training process.<br>", "_____no_output_____" ] ], [ [ "# Hilbert space cutoff\ncutoff = 15\n\n# Normalization cutoff (must be equal or smaller than cutoff dimension)\ntarget_cutoff = 15\n\n# Normalization weight\nnorm_weight = 0\n\n# Batch size\nbatch_size = 8\n\n# Number of batches (i.e. number training iterations)\nnum_batches = 500\n\n# Number of state generation layers\ng_depth = 1\n\n# Number of pre-trained layers (for transfer learning)\npre_depth = 1\n\n# Number of state classification layers\nq_depth = 3\n\n# Standard deviation of random state generation parameters\nrot_sd = np.math.pi * 2\ndis_sd = 0\nsq_sd = 0.5\nnon_lin_sd = 0.5 # this is used as fixed non-linear constant.\n\n# Standard deviation of initial trainable weights\nactive_sd = 0.001\npassive_sd = 0.001\n\n# Magnitude limit for trainable active parameters\nclip = 1 \n\n# Learning rate \nlr = 0.01 \n\n# Random seeds\ntf.set_random_seed(0)\nrng_data = np.random.RandomState(1)\n\n# Reset TF graph\ntf.reset_default_graph()", "_____no_output_____" ] ], [ [ "## Variational circuits for state generation and classificaiton", "_____no_output_____" ], [ "### Input states: _Dataset B_\n\nThe dataset is introduced by defining the corresponding random variational circuit that generates input Gaussian and non-Gaussian states.\n\n", "_____no_output_____" ] ], [ [ "# Placeholders for class labels\nbatch_labels = tf.placeholder(dtype=tf.int64, shape = [batch_size])\nbatch_labels_fl = tf.to_float(batch_labels)\n\n# State generation parameters\n# Squeezing gate\nsq_gen = tf.placeholder(dtype = tf.float32, shape = [batch_size,g_depth])\n\n# Rotation gates \nr1_gen = tf.placeholder(dtype = tf.float32, shape = [batch_size,g_depth])\nr2_gen = tf.placeholder(dtype = tf.float32, shape = [batch_size,g_depth])\nr3_gen = tf.placeholder(dtype = tf.float32, shape = [batch_size,g_depth])\n\n# Explicit definitions of the ket tensors of |0> and |1> \nnp_ket0, np_ket1 = np.zeros((2, batch_size, cutoff))\nnp_ket0[:,0] = 1.0\nnp_ket1[:,1] = 1.0\nket0 = tf.constant(np_ket0, dtype = tf.float32, shape = [batch_size, cutoff])\nket1 = tf.constant(np_ket1, dtype = tf.float32, shape = [batch_size, cutoff])\n\n# Ket of the quantum states associated to the label: i.e. |batch_labels>\nket_init = ket0 * (1.0 - tf.expand_dims(batch_labels_fl, 1)) + ket1 * tf.expand_dims(batch_labels_fl, 1)\n\n# State generation layer\ndef layer_gen(i, qmode):\n \n # If label is 0 (Gaussian) prepare a coherent state with alpha=1 otherwise prepare fock |1>\n Ket(ket_init) | qmode\n Dgate((1.0 - batch_labels_fl) * 1.0, 0) | qmode\n \n # Random Gaussian operation (without displacement)\n Rgate(r1_gen[:, i]) | qmode\n Sgate(sq_gen[:, i], 0) | qmode\n Rgate(r2_gen[:, i]) | qmode\n\n return qmode", "_____no_output_____" ] ], [ [ "### Loading of pre-trained block (_Circuit A_)\n\nWe assume that _Circuit A_ has been already pre-trained (e.g. by running a dedicated Python script) and that the associated optimal weights have been saved to a NumPy file. Here we first load the such parameters and then we define _Circuit A_ as a constant pre-processing block.", "_____no_output_____" ] ], [ [ "# Loading of pre-trained weights\ntrained_params_npy = np.load('pre_trained/circuit_A.npy')\nif trained_params_npy.shape[1] < pre_depth:\n print(\"Error: circuit q_depth > trained q_depth.\")\n raise SystemExit(0)\n \n# Convert numpy arrays to TF tensors\ntrained_params = tf.constant(trained_params_npy)\n \nsq_pre = trained_params[0]\nd_pre = trained_params[1]\nr1_pre = trained_params[2]\nr2_pre = trained_params[3]\nr3_pre = trained_params[4]\nkappa_pre = trained_params[5]\n\n# Definition of the pre-trained Circuit A (single layer)\n\ndef layer_pre(i, qmode):\n \n # Rotation gate\n Rgate(r1_pre[i]) | qmode\n # Squeezing gate\n Sgate(tf.clip_by_value(sq_pre[i], -clip, clip), 0) \n # Rotation gate\n Rgate(r2_pre[i]) | qmode\n # Displacement gate\n Dgate(tf.clip_by_value(d_pre[i], -clip, clip) , 0) | qmode\n # Rotation gate\n Rgate(r3_pre[i]) | qmode\n # Cubic gate\n Vgate(tf.clip_by_value(kappa_pre[i], -clip, clip) ) | qmode\n \n return qmode", "_____no_output_____" ] ], [ [ "### Addition of trainable layers (_Circuit B_)\n\nAs discussed in the introduction, _Circuit B_ can is obtained by adding some additional layers that we are going to train on _Dataset B_.", "_____no_output_____" ] ], [ [ "# Trainable variables\nwith tf.name_scope('variables'):\n\n # Squeeze gate\n sq_var = tf.Variable(tf.random_normal(shape=[q_depth], stddev=active_sd))\n\n # Displacement gate\n d_var = tf.Variable(tf.random_normal(shape=[q_depth], stddev=active_sd))\n\n # Rotation gates \n r1_var = tf.Variable(tf.random_normal(shape=[q_depth], stddev=passive_sd))\n r2_var = tf.Variable(tf.random_normal(shape=[q_depth], stddev=passive_sd))\n r3_var = tf.Variable(tf.random_normal(shape=[q_depth], stddev=passive_sd))\n\n # Kerr gate\n kappa_var = tf.Variable(tf.random_normal(shape=[q_depth], stddev=active_sd))\n\n # 0-depth parameter (just to generate a gradient)\n x_var = tf.Variable(0.0)\n\nparameters = [sq_var, d_var, r1_var, r2_var, r3_var, kappa_var]\n \n# Definition of a single trainable variational layer\ndef layer_var(i, qmode):\n\n Rgate(r1_var[i]) | qmode\n Sgate(tf.clip_by_value(sq_var[i], -clip, clip), 0) | qmode\n Rgate(r2_var[i]) | qmode\n Dgate(tf.clip_by_value(d_var[i], -clip, clip) , 0) | qmode\n Rgate(r3_var[i]) | qmode\n Vgate(tf.clip_by_value(kappa_var[i], -clip, clip) ) | qmode\n\n return qmode", "_____no_output_____" ] ], [ [ "## Symbolic evaluation of the full network\n\nWe first instantiate a _StrawberryFields_ quantum simulator, taylored for simulating a single-mode quantum optical system. Then we synbolically evaluate a batch of output states.", "_____no_output_____" ] ], [ [ "prog = sf.Program(1)\neng = sf.Engine('tf', backend_options={'cutoff_dim': cutoff, 'batch_size': batch_size})\n \n# Circuit B \nwith prog.context as q:\n \n # State generation network\n for k in range(g_depth):\n layer_gen(k, q[0])\n\n # Pre-trained network (Circuit A)\n for k in range(pre_depth):\n layer_pre(k, q[0])\n\n # State classification network\n for k in range(q_depth):\n layer_var(k, q[0])\n \n # Special case q_depth==0 \n if q_depth == 0:\n Dgate(0.001, x_var ) | q[0] # almost identity operation just to generate a gradient.\n\n# Symbolic computation of the output state\nresults = eng.run(prog, run_options={\"eval\": False}) \nout_state = results.state\n\n# Batch state norms\nout_norm = tf.to_float(out_state.trace())\n\n# Batch mean energies\nmean_n = out_state.mean_photon(0) ", "_____no_output_____" ] ], [ [ "## Loss function, accuracy and optimizer.\n\nAs usual in machine learning, we need to define a loss function that we are going to minimize during the training phase.\n\nAs discussed in the introduction, we assume that only the vacuum state probability `p_0` is measured. Ideally, `p_0` should be large for non-Gaussian states (_label 1_), while should be small for Gaussian states (_label 0_). The circuit can be trained to this task by minimizing the _cross entropy_ loss function defined in the next cell.\n\nMoreover, if `norm_weight` is different from zero, also a regularization term is added to the full cost function in order to reduce quantum amplitudes beyond the target Hilbert space dimension `target_cutoff`.", "_____no_output_____" ] ], [ [ "# Batch vacuum probabilities\np0 = out_state.fock_prob([0]) \n\n# Complementary probabilities\nq0 = 1.0 - p0\n\n# Cross entropy loss function\neps = 0.0000001\nmain_loss = tf.reduce_mean(-batch_labels_fl * tf.log(p0 + eps) - (1.0 - batch_labels_fl) * tf.log(q0 + eps))\n\n# Decision function\npredictions = tf.sign(p0 - 0.5) * 0.5 + 0.5\n\n# Accuracy between predictions and labels\naccuracy = tf.reduce_mean((predictions + batch_labels_fl - 1.0) ** 2)\n\n# Norm loss. This is monitored but not minimized.\nnorm_loss = tf.reduce_mean((out_norm - 1.0) ** 2)\n\n# Cutoff loss regularization. This is monitored and minimized if norm_weight is nonzero.\nc_in = out_state.all_fock_probs()\ncut_probs = c_in[:, :target_cutoff]\ncut_norms = tf.reduce_sum(cut_probs, axis=1)\ncutoff_loss = tf.reduce_mean((cut_norms - 1.0) ** 2 ) \n\n# Full regularized loss function\nfull_loss = main_loss + norm_weight * cutoff_loss\n\n# Optimization algorithm\noptim = tf.train.AdamOptimizer(learning_rate=lr)\ntraining = optim.minimize(full_loss) ", "_____no_output_____" ] ], [ [ "## Training and testing", "_____no_output_____" ], [ "Up to now we just defined the analytic graph of the quantum network without numerically evaluating it. Now, after initializing a _TensorFlow_ session, we can finally run the actual training and testing phases. ", "_____no_output_____" ] ], [ [ "# Function generating a dictionary of random parameters for a batch of states.\ndef random_dict():\n param_dict = { # Labels (0 = Gaussian, 1 = non-Gaussian)\n batch_labels: rng_data.randint(2, size=batch_size),\n \n # Squeezing and rotation parameters \n sq_gen: rng_data.uniform(low=-sq_sd, high=sq_sd, size=[batch_size, g_depth]),\n r1_gen: rng_data.uniform(low=-rot_sd, high=rot_sd, size=[batch_size, g_depth]),\n r2_gen: rng_data.uniform(low=-rot_sd, high=rot_sd, size=[batch_size, g_depth]),\n r3_gen: rng_data.uniform(low=-rot_sd, high=rot_sd, size=[batch_size, g_depth]),\n }\n return param_dict\n\n# TensorFlow session\nwith tf.Session() as session:\n session.run(tf.global_variables_initializer())\n\n train_loss = 0.0\n train_loss_sum = 0.0\n train_acc = 0.0\n train_acc_sum = 0.0\n\n test_loss = 0.0\n test_loss_sum = 0.0\n test_acc = 0.0\n test_acc_sum = 0.0\n\n # =========================================================\n # \tTraining Phase \n # =========================================================\n \n if q_depth > 0:\n for k in range(num_batches):\n rep_time = time.time()\n \n # Training step\n [_training,\n _full_loss,\n _accuracy,\n _norm_loss] = session.run([ training,\n full_loss,\n accuracy,\n norm_loss], feed_dict=random_dict())\n train_loss_sum += _full_loss\n train_acc_sum += _accuracy\n train_loss = train_loss_sum / (k + 1)\n train_acc = train_acc_sum / (k + 1)\n \n # Training log\n if ((k + 1) % 100) == 0:\n print('Train batch: {:d}, Running loss: {:.4f}, Running acc {:.4f}, Norm loss {:.4f}, Batch time {:.4f}'\n .format(k + 1, train_loss, train_acc, _norm_loss, time.time() - rep_time))\n\n # =========================================================\n # \tTesting Phase \n # =========================================================\n num_test_batches = min(num_batches, 1000)\n\n for i in range(num_test_batches): \n rep_time = time.time()\n \n # Evaluation step\n [_full_loss,\n _accuracy,\n _norm_loss,\n _cutoff_loss,\n _mean_n,\n _parameters] = session.run([full_loss,\n accuracy,\n norm_loss,\n cutoff_loss,\n mean_n,\n parameters], feed_dict=random_dict())\n test_loss_sum += _full_loss\n test_acc_sum += _accuracy\n test_loss = test_loss_sum / (i + 1)\n test_acc = test_acc_sum / (i + 1)\n \n # Testing log\n if ((i + 1) % 100) == 0:\n print('Test batch: {:d}, Running loss: {:.4f}, Running acc {:.4f}, Norm loss {:.4f}, Batch time {:.4f}'\n .format(i + 1, test_loss, test_acc, _norm_loss, time.time() - rep_time))\n\n# Compute mean photon number of the last batch of states\nmean_fock = np.mean(_mean_n)\n \nprint('Training and testing phases completed.')\nprint('RESULTS:')\nprint('{:>11s}{:>11s}{:>11s}{:>11s}{:>11s}{:>11s}'.format('train_loss', 'train_acc', 'test_loss', 'test_acc', 'norm_loss', 'mean_n'))\nprint('{:11f}{:11f}{:11f}{:11f}{:11f}{:11f}'.format(train_loss, train_acc, test_loss, test_acc, _norm_loss, mean_fock)) ", "Train batch: 100, Running loss: 0.6885, Running acc 0.3700, Norm loss 0.0460, Batch time 0.0494\nTrain batch: 200, Running loss: 0.6673, Running acc 0.3750, Norm loss 0.0599, Batch time 0.0498\nTrain batch: 300, Running loss: 0.6575, Running acc 0.3825, Norm loss 0.0495, Batch time 0.0502\nTrain batch: 400, Running loss: 0.6463, Running acc 0.3975, Norm loss 0.1070, Batch time 0.0497\nTrain batch: 500, Running loss: 0.6113, Running acc 0.4765, Norm loss 0.1387, Batch time 0.0862\nTest batch: 100, Running loss: 0.4438, Running acc 0.8762, Norm loss 0.0613, Batch time 0.0206\nTest batch: 200, Running loss: 0.4376, Running acc 0.8825, Norm loss 0.0801, Batch time 0.0202\nTest batch: 300, Running loss: 0.4345, Running acc 0.8808, Norm loss 0.0391, Batch time 0.0199\nTest batch: 400, Running loss: 0.4359, Running acc 0.8775, Norm loss 0.0698, Batch time 0.0260\nTest batch: 500, Running loss: 0.4354, Running acc 0.8755, Norm loss 0.1015, Batch time 0.0256\nTraining and testing phases completed.\nRESULTS:\n train_loss train_acc test_loss test_acc norm_loss mean_n\n 0.611272 0.476500 0.435440 0.875500 0.101467 5.336512\n" ] ], [ [ "## References\n\n[1] Andrea Mari, Thomas R. Bromley, Josh Izaac, Maria Schuld, and Nathan Killoran. _Transfer learning in hybrid classical-quantum neural networks_. [arXiv:1912.08278](https://arxiv.org/abs/1912.08278), (2019).\n\n[2] Nathan Killoran, Thomas R. Bromley, Juan Miguel Arrazola, Maria Schuld, Nicolás Quesada, and Seth Lloyd. _Continuous-variable quantum neural networks_. [arXiv:1806.06871](https://arxiv.org/abs/1806.06871), (2018).\n\n[3] Nathan Killoran, Josh Izaac, Nicolás Quesada, Ville Bergholm, Matthew Amy, and Christian Weedbrook. _Strawberry Fields: A Software Platform for Photonic Quantum Computing_. [Quantum, 3, 129 (2019)](https://doi.org/10.22331/q-2019-03-11-129).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
d0757f07559712b0abe52758831b94ecec22fc1d
15,166
ipynb
Jupyter Notebook
app.ipynb
csiro-hydrogeology/lithology-viewer
12a30c90a39c7616994181967854523ec548a9d3
[ "BSD-3-Clause" ]
6
2019-11-02T05:23:23.000Z
2021-03-13T21:43:59.000Z
app.ipynb
csiro-hydrogeology/lithology-viewer
12a30c90a39c7616994181967854523ec548a9d3
[ "BSD-3-Clause" ]
null
null
null
app.ipynb
csiro-hydrogeology/lithology-viewer
12a30c90a39c7616994181967854523ec548a9d3
[ "BSD-3-Clause" ]
4
2019-09-27T05:38:25.000Z
2020-08-25T01:20:15.000Z
29.22158
327
0.542925
[ [ [ "## Borehole lithology logs viewer\n\nInteractive view of borehole data used for [exploratory lithology analysis](https://github.com/csiro-hydrogeology/pyela)\n\nPowered by [Voila](https://github.com/QuantStack/voila), [ipysheet](https://github.com/QuantStack/ipysheet) and [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet)\n\n### Data \n\nThe sample borehole data around Canberra, Australia is derived from the Australian Bureau of Meteorology [National Groundwater Information System](http://www.bom.gov.au/water/groundwater/ngis/index.shtml). You can check the licensing for these data; the short version is that use for demo and learning purposes is fine.\n", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "# from bqplot import Axis, Figure, Lines, LinearScale\n# from bqplot.interacts import IndexSelector\n# from ipyleaflet import basemaps, FullScreenControl, LayerGroup, Map, MeasureControl, Polyline, Marker, MarkerCluster, CircleMarker, WidgetControl\n# from ipywidgets import Button, HTML, HBox, VBox, Checkbox, FileUpload, Label, Output, IntSlider, Layout, Image, link\nfrom ipywidgets import Output, HTML\nfrom ipyleaflet import Map, Marker, MarkerCluster, basemaps", "_____no_output_____" ], [ "import ipywidgets as widgets\nimport ipysheet", "_____no_output_____" ], [ "example_folder = \"./examples\"", "_____no_output_____" ], [ "# classified_logs_filename = os.path.join(cbr_datadir_out,'classified_logs.pkl')\n# with open(classified_logs_filename, 'rb') as handle:\n# df = pickle.load(handle)", "_____no_output_____" ], [ "# geoloc_filename = os.path.join(cbr_datadir_out,'geoloc.pkl')\n# with open(geoloc_filename, 'rb') as handle:\n# geoloc = pickle.load(handle)", "_____no_output_____" ], [ "df = pd.read_csv(os.path.join(example_folder,'classified_logs.csv'))", "_____no_output_____" ], [ "geoloc = pd.read_csv(os.path.join(example_folder,'geoloc.csv'))", "_____no_output_____" ], [ "DEPTH_FROM_COL = 'FromDepth'\nDEPTH_TO_COL = 'ToDepth'\n\nTOP_ELEV_COL = 'TopElev'\nBOTTOM_ELEV_COL = 'BottomElev'\n\nLITHO_DESC_COL = 'Description'\nHYDRO_CODE_COL = 'HydroCode'\n\nHYDRO_ID_COL = 'HydroID'\nBORE_ID_COL = 'BoreID'", "_____no_output_____" ], [ "# if we want to keep vboreholes that have more than one row\nx = df[HYDRO_ID_COL].values\nunique, counts = np.unique(x, return_counts=True)\nmultiple_counts = unique[counts > 1]\n# len(multiple_counts), len(unique)", "_____no_output_____" ], [ "keep = set(df[HYDRO_ID_COL].values)\nkeep = set(multiple_counts)\ns = geoloc[HYDRO_ID_COL]", "_____no_output_____" ], [ "geoloc = geoloc[s.isin(keep)]", "_____no_output_____" ], [ "class GlobalThing:\n def __init__(self, bore_data, displayed_colnames = None):\n self.marker_info = dict()\n self.bore_data = bore_data\n if displayed_colnames is None:\n displayed_colnames = [BORE_ID_COL, DEPTH_FROM_COL, DEPTH_TO_COL, LITHO_DESC_COL] # 'Lithology_1', 'MajorLithCode']]\n self.displayed_colnames = displayed_colnames\n \n def add_marker_info(self, lat, lon, code):\n self.marker_info[(lat, lon)] = code\n \n def get_code(self, lat, lon):\n return self.marker_info[(lat, lon)]\n\n def data_for_hydroid(self, ident):\n df_sub = self.bore_data.loc[df[HYDRO_ID_COL] == ident]\n return df_sub[self.displayed_colnames]\n\n def register_geolocations(self, geoloc):\n for index, row in geoloc.iterrows():\n self.add_marker_info(row.Latitude, row.Longitude, row.HydroID)", "_____no_output_____" ], [ "globalthing = GlobalThing(df, displayed_colnames = [BORE_ID_COL, DEPTH_FROM_COL, DEPTH_TO_COL, LITHO_DESC_COL, 'Lithology_1'])\nglobalthing.register_geolocations(geoloc)", "_____no_output_____" ], [ "def plot_map(geoloc, click_handler):\n \"\"\"\n Plot the markers for each borehole, and register a custom click_handler\n \"\"\"\n mean_lat = geoloc.Latitude.mean()\n mean_lng = geoloc.Longitude.mean()\n # create the map\n m = Map(center=(mean_lat, mean_lng), zoom=12, basemap=basemaps.Stamen.Terrain)\n m.layout.height = '600px'\n # show trace\n markers = []\n for index, row in geoloc.iterrows():\n message = HTML()\n message.value = str(row.HydroID)\n message.placeholder = \"\"\n message.description = \"HydroID\"\n marker = Marker(location=(row.Latitude, row.Longitude))\n marker.on_click(click_handler)\n marker.popup = message\n markers.append(marker)\n marker_cluster = MarkerCluster(\n markers=markers\n )\n # not sure whether we could register once instead of each marker:\n # marker_cluster.on_click(click_handler)\n m.add_layer(marker_cluster);\n # m.add_control(FullScreenControl())\n return m", "_____no_output_____" ], [ "# If printing a data frame straight to an output widget\ndef raw_print(out, ident):\n bore_data = globalthing.data_for_hydroid(ident)\n out.clear_output()\n with out:\n print(ident) \n print(bore_data)\n \ndef click_handler_rawprint(**kwargs):\n blah = dict(**kwargs)\n xy = blah['coordinates']\n ident = globalthing.get_code(xy[0], xy[1])\n raw_print(out, ident)\n", "_____no_output_____" ], [ "# to display using an ipysheet\ndef mk_sheet(d):\n return ipysheet.pandas_loader.from_dataframe(d)\n\ndef upate_display_df(ident):\n bore_data = globalthing.data_for_hydroid(ident)\n out.clear_output()\n with out:\n display(mk_sheet(bore_data)) \n\ndef click_handler_ipysheet(**kwargs):\n blah = dict(**kwargs)\n xy = blah['coordinates']\n ident = globalthing.get_code(xy[0], xy[1])\n upate_display_df(ident)\n", "_____no_output_____" ], [ "out = widgets.Output(layout={'border': '1px solid black'})", "_____no_output_____" ] ], [ [ "Note: it may take a minute or two for the display to first appear....\n\nSelect a marker:", "_____no_output_____" ] ], [ [ "plot_map(geoloc, click_handler_ipysheet)\n# plot_map(geoloc, click_handler_rawprint)", "_____no_output_____" ] ], [ [ "Descriptive lithology:", "_____no_output_____" ] ], [ [ "out", "_____no_output_____" ], [ "## Appendix A : qgrid, but at best ended up with \"Model not available\". May not work yet with Jupyter lab 1.0.x\n\n# import qgrid\n\n# d = data_for_hydroid(10062775)\n# d\n\n# import ipywidgets as widgets\n\n# def build_qgrid():\n# qgrid.set_grid_option('maxVisibleRows', 10)\n# col_opts = { \n# 'editable': False,\n# }\n# qgrid_widget = qgrid.show_grid(d, show_toolbar=False, column_options=col_opts)\n# qgrid_widget.layout = widgets.Layout(width='920px')\n# return qgrid_widget, qgrid\n\n# qgrid_widget, qgrid = build_qgrid()\n\n# display(qgrid_widget)\n\n# pitch_app = widgets.VBox(qgrid_widget)\n# display(pitch_app)\n\n# def click_handler(**kwargs):\n# blah = dict(**kwargs)\n# xy = blah['coordinates']\n# ident = globalthing.get_code(xy[0], xy[1])\n# bore_data = data_for_hydroid(ident)\n# grid.df = bore_data", "_____no_output_____" ], [ "\n## Appendix B: using striplog \n\n# from striplog import Striplog, Interval, Component, Legend, Decor\n\n\n# import matplotlib as mpl\n# lithologies = ['shale', 'clay','granite','soil','sand', 'porphyry','siltstone','gravel', '']\n# lithology_color_names = ['lightslategrey', 'olive', 'dimgray', 'chocolate', 'gold', 'tomato', 'teal', 'lavender', 'black']\n# lithology_colors = [mpl.colors.cnames[clr] for clr in lithology_color_names]\n\n# clrs = dict(zip(lithologies, lithology_colors))\n\n# def mk_decor(lithology, component):\n# dcor = {'color': clrs[lithology],\n# 'component': component,\n# 'width': 2}\n# return Decor(dcor)\n\n# def create_striplog_itvs(d):\n# itvs = []\n# dcrs = []\n# for index, row in d.iterrows():\n# litho = row.Lithology_1\n# c = Component({'description':row.Description,'lithology': litho})\n# decor = mk_decor(litho, c)\n# itvs.append(Interval(row.FromDepth, row.ToDepth, components=[c]) )\n# dcrs.append(decor)\n# return itvs, dcrs\n\n# def click_handler(**kwargs):\n# blah = dict(**kwargs)\n# xy = blah['coordinates']\n# ident = globalthing.get_code(xy[0], xy[1])\n# bore_data = data_for_hydroid(ident)\n# itvs, dcrs = create_striplog_itvs(bore_data)\n# s = Striplog(itvs)\n# with out:\n# print(ident)\n# print(s.plot(legend = Legend(dcrs)))\n\n# def plot_striplog(bore_data, ax=None):\n# itvs, dcrs = create_striplog_itvs(bore_data)\n# s = Striplog(itvs)\n# s.plot(legend = Legend(dcrs), ax=ax)\n\n# def plot_evaluation_metrics(bore_data):\n# fig, ax = plt.subplots(figsize=(12, 3))\n# # actual plotting\n# plot_striplog(bore_data, ax=ax)\n# # finalize\n# fig.suptitle(\"Evaluation metrics with cutoff\\n\", va='bottom')\n# plt.show()\n# plt.close(fig)\n\n# %matplotlib inline\n# from ipywidgets import interactive\n# import matplotlib.pyplot as plt\n# import numpy as np\n\n# def f(m, b):\n# plt.figure(2)\n# x = np.linspace(-10, 10, num=1000)\n# plt.plot(x, m * x + b)\n# plt.ylim(-5, 5)\n# plt.show()\n\n# interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))\n# output = interactive_plot.children[-1]\n# output.layout.height = '350px'\n# interactive_plot\n\n# def update_sheet(s, d):\n# print(\"before: %s\"%(s.rows))\n# s.rows = len(d)\n# for i in range(len(d.columns)):\n# s.cells[i].value = d[d.columns[i]].values", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d0758a38e32cf4a597e80bca529017d46ff5b8fb
5,666
ipynb
Jupyter Notebook
kernel/Dot/I_kexec.ipynb
nufeng1999/Myjupyter-kernel
7862ce8afae139d39ad2896f3e36a19b5df9923e
[ "MIT" ]
null
null
null
kernel/Dot/I_kexec.ipynb
nufeng1999/Myjupyter-kernel
7862ce8afae139d39ad2896f3e36a19b5df9923e
[ "MIT" ]
null
null
null
kernel/Dot/I_kexec.ipynb
nufeng1999/Myjupyter-kernel
7862ce8afae139d39ad2896f3e36a19b5df9923e
[ "MIT" ]
null
null
null
33.928144
137
0.543417
[ [ [ "## do_runcode\n##%overwritefile\n##%file:src/do_dot_runcode.py\n##%noruncode\n def do_runcode(self,return_code,fil_ename,magics,code, silent, store_history=True,\n user_expressions=None, allow_stdin=True):\n return_code=return_code\n fil_ename=fil_ename\n bcancel_exec=False\n retinfo=self.mymagics.get_retinfo()\n retstr=''\n\n ## 代码运行前\n ## 有解释器则使用解释器执行文件 fil_ename,否则直接执行文件 fil_ename\n src = None\n has_error = False\n try:\n src = Source(code)\n png_src = src.pipe(format=\"svg\")\n except subprocess.CalledProcessError as _called_error:\n has_error = True\n error = _called_error.stderr\n except Exception as e:\n self.mymagics._logln(str(e),3)\n if not has_error:\n data_string = base64.b64encode(png_src).decode(\"utf-8\",errors='ignore')\n mimetype='image/svg+xml'\n header=\"<div><img alt=\\\"Output\\\" src=\\\"data:\"+mimetype+\";base64,\"\n end=\"\\\"></div>\"\n data_string=header+data_string+end\n self.send_response(self.iopub_socket, 'display_data', {'data': {mimetype:data_string}, 'metadata': {mimetype:{}}})\n else:\n self.mymagics._logln(error.decode(),3)\n ## if p.returncode != 0:\n ## self.mymagics._log(\"Executable exited with code {}\".format(p.returncode),2)\n return bcancel_exec,retinfo,magics, code,fil_ename,retstr", "[MyPythonKernel101844] Info:file h:\\Jupyter\\Myjupyter-kernel\\kernel\\Dot\\src/do_dot_runcode.py created successfully\n" ], [ "## do_compile_code\n##%overwritefile\n##%file:src/do_dot_compilecode.py\n##%noruncode\n def do_compile_code(self,return_code,fil_ename,magics,code, silent, store_history=True,\n user_expressions=None, allow_stdin=True):\n bcancel_exec=False\n retinfo=self.mymagics.get_retinfo()\n retstr=''\n binary_filename=fil_ename\n # if len(self.kernel_info['compiler']['cmd'])>0:\n # ## 执行编译\n # returncode,binary_filename=self._exec_sc_(fil_ename,magics)\n # if returncode!=0:return True,retinfo, code,fil_ename,retstr\n\n return bcancel_exec,retinfo,magics, code,binary_filename,retstr", "[MyPythonKernel220407] Info:file h:\\Jupyter\\Myjupyter-kernel\\kernel\\Dot\\src/do_dot_compilecode.py created successfully\n" ], [ "## do_dot_create_codefile\n##%overwritefile\n##%file:src/do_dot_create_codefile.py\n##%noruncode\n def do_create_codefile(self,magics,code, silent, store_history=True,\n user_expressions=None, allow_stdin=True):\n fil_ename=''\n bcancel_exec=False\n retinfo=self.mymagics.get_retinfo()\n retstr=''\n \n source_file=self.mymagics.create_codetemp_file(magics,code,suffix=self.kernel_info['extension'])\n fil_ename=source_file.name\n \n return bcancel_exec,retinfo,magics, code,fil_ename,retstr", "[MyPythonKernel220407] Info:file h:\\Jupyter\\Myjupyter-kernel\\kernel\\Dot\\src/do_dot_create_codefile.py created successfully\n" ], [ "## do_dot_preexecute\n##%overwritefile\n##%file:src/do_dot_preexecute.py\n##%noruncode\n def do_preexecute(self,code, magics,silent, store_history=True,\n user_expressions=None, allow_stdin=False):\n bcancel_exec=False\n retinfo=self.mymagics.get_retinfo()\n ## 需要运行代码并且需要 main()函数则调用 _add_main 函数处理\n if (len(self.mymagics.addkey2dict(magics,'noruncode'))<1 \n and len(self.kernel_info['needmain'])>0 ):\n magics, code = self.mymagics._add_main(magics, code)\n\n return bcancel_exec,retinfo,magics, code", "[MyPythonKernel220407] Info:file h:\\Jupyter\\Myjupyter-kernel\\kernel\\Dot\\src/do_dot_preexecute.py created successfully\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
d07593215bbe625f471798a2c03c506ea6449d01
58,744
ipynb
Jupyter Notebook
src/archive/main.ipynb
claudioperez/elle-0004
c010c5b81c36f175ecb80b0bfb0d194f35379065
[ "Apache-2.0" ]
null
null
null
src/archive/main.ipynb
claudioperez/elle-0004
c010c5b81c36f175ecb80b0bfb0d194f35379065
[ "Apache-2.0" ]
null
null
null
src/archive/main.ipynb
claudioperez/elle-0004
c010c5b81c36f175ecb80b0bfb0d194f35379065
[ "Apache-2.0" ]
null
null
null
114.066019
8,692
0.845567
[ [ [ "# Series Inelastic Cantilever", "_____no_output_____" ], [ "This notebook verifies the `elle.beam2dseries` element against an analysis run with the FEDEASLab `Inel2dFrm_wOneComp` element.", "_____no_output_____" ] ], [ [ "import anon\nimport anon as ana\nimport elle.beam2d\nimport elle.solvers\nimport elle.sections\nimport anon.ops as anp", "_____no_output_____" ] ], [ [ "### Model Definition", "_____no_output_____" ] ], [ [ "from elle.beam2dseries import no_3, no_4, no_5, no_6\nfrom elle.sections import aisc", "_____no_output_____" ], [ "L = 72.0\nE = 29e3\nfy = 60.0\nHi = 1.0e-6\nHk = 1e-9 #1.0e-9", "_____no_output_____" ], [ "sect = aisc.load('W14x426','A, I, Zx')\nNp = fy*sect['A']\nMp = fy*sect['Zx']\nHi = Hi * 6.* E*sect['I']/L * anp.ones((2,1))\nHk = Hk * 6.* E*sect['I']/L * anp.ones((2,1))\nxyz = anp.array([[0.0, 0.0],[0.0, L]])\nMp_vector = anp.array([Mp,Mp])[:,None]", "/home/claudio/miniconda3/envs/piplin/lib/python3.8/site-packages/jax/lib/xla_bridge.py:116: UserWarning: No GPU/TPU found, falling back to CPU.\n warnings.warn('No GPU/TPU found, falling back to CPU.')\n" ], [ "u = anp.zeros(3)", "_____no_output_____" ], [ "limit_surface = elle.beam2dseries.no_6\ngeometry = elle.beam2d.geom_no1\ntransform = elle.beam2d.transform(geometry)\nbasic_response = elle.beam2d.resp_no1\n\n\nBeamResponse = transform( # <u>, p, state -> u, <p>, state\n limit_surface(\n basic_response(E=E,**sect),\n Mp=Mp_vector,Hi=Hi,Hk=Hk,tol=1e-7\n ),\n xyz=xyz\n)\nBeamResponse", "_____no_output_____" ], [ "ag = anon.autodiff.jacfwd(geometry(xyz), 1, 0)", "_____no_output_____" ], [ "BeamModel = elle.solvers.invert_no2(BeamResponse, nr=3, maxiter=20, tol=1e-6)\nBeamModel", "_____no_output_____" ] ], [ [ "## Loading", "_____no_output_____" ] ], [ [ "# Np = 0.85*Np\nq_ref = anp.array([[ 0.0*Np, 0.0, 0.000*Mp],\n [-0.4*Np, 0.0, 0.000*Mp],\n [-0.4*Np, 0.0, 0.400*Mp],\n [-0.4*Np, 0.0, 0.700*Mp],\n [-0.32*Np, 0.0, 0.600*Mp],\n [-0.2*Np, 0.0, 0.400*Mp],\n [-0.1*Np, 0.0, 0.200*Mp],\n [-0.0*Np, 0.0, 0.000*Mp]])\n\n\n# steps = [5,8,15,15,15,15,10]\nsteps = [5,5,5,5,5,5,5]\n\nload_history = elle.sections.load_hist(q_ref, steps)", "_____no_output_____" ] ], [ [ "### Model Initialization", "_____no_output_____" ] ], [ [ "u, q = [], []\nu0, p0 = anp.zeros((6,1)), anp.zeros((6,1))\n# vi = U_to_V(U[0])\nBeamResponse(u0,p0)", "_____no_output_____" ], [ "pi, ui, state = BeamModel(p0, u0)\nu.append(ui)\nq.append(state[0])\n# [print(s) for s in state]\n# print(ui)", "_____no_output_____" ] ], [ [ "### Analysis Procedure", "_____no_output_____" ] ], [ [ "for i in range(len(load_history)):\n pi = ag(ui, pi).T @ load_history[i][:, None]\n pi, ui, state = BeamModel(pi, ui, state)\n u.append(ui)\n q.append(state[0])", "/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.\n warnings.warn(f\"Failed to converge on function {f} inversion.\")\n" ] ], [ [ "## Post Processing and Validation", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n# plt.style.use('trois-pas');\n# %config InlineBackend.figure_format = 'svg'", "_____no_output_____" ], [ "fig, ax = plt.subplots()\n\nax.plot([ ui[1] for ui in u ],[ qi[2] for qi in q ], '.');\n# ax.plot([ ui[1] for ui in u ],\n# [ pi['Elem'][0]['q'][1] for pi in data['Post'] ], '.', label='FEDEASLab');\n# plt.legend()\nfig.savefig('../img/no1-analysis.svg')", "_____no_output_____" ], [ "plt.plot([ i for i in range(len(q)) ], [ qi[0] for qi in q ], '.')\n# plt.plot([ i for i in range(len(q)) ], [ pi['Elem'][0]['q'][0] for pi in post ], '.', label='FEDEASLab')\n# plt.legend();", "_____no_output_____" ], [ "plt.plot([ i for i in range(len(q)) ], [ qi[1] for qi in q ], 'x');\n# plt.plot([ i for i in range(len(q)) ],\n# [ pi['Elem'][0]['q'][1] for pi in data['Post'] ], '.', label='FEDEASLab');\n# plt.legend();", "_____no_output_____" ], [ "plt.plot([ i for i in range(len(q)) ], [ qi[2] for qi in q ], '.');\n# plt.plot([ i for i in range(len(q)) ],\n# [ pi['Elem'][0]['q'][2] for pi in post ], '.', label='FEDEASLab');\n# plt.legend();", "_____no_output_____" ], [ "plt.plot([i for i in range(len(u))],[ ui[1] for ui in u ], '.');", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d0759e582f7dcde77c62beba31d40c4fc4ba714b
225,214
ipynb
Jupyter Notebook
.ipynb_checkpoints/PSDandSNR-checkpoint.ipynb
nishantbalaji/e4e-data-visualization
4b56bd63b6da11e3a7fd3c0881eb228d5692f21f
[ "MIT" ]
null
null
null
.ipynb_checkpoints/PSDandSNR-checkpoint.ipynb
nishantbalaji/e4e-data-visualization
4b56bd63b6da11e3a7fd3c0881eb228d5692f21f
[ "MIT" ]
null
null
null
.ipynb_checkpoints/PSDandSNR-checkpoint.ipynb
nishantbalaji/e4e-data-visualization
4b56bd63b6da11e3a7fd3c0881eb228d5692f21f
[ "MIT" ]
null
null
null
112.046766
58,719
0.68153
[ [ [ "import folium\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib ", "_____no_output_____" ], [ "data = pd.read_csv('MDD_Dataset_PSD_and_SNR.csv')\ncoords = pd.read_excel('AudioMothPeru_Coordinates.xlsx', engine='openpyxl')", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "data = data.drop(columns=['SourceFile', 'Directory', 'FileSize', 'AudioMothID', \n 'Encoding', 'NumChannels', 'SampleRate', 'AvgBytesPerSec',\n 'BitsPerSample', 'Artist', 'FileType', 'MIMEType', 'LOWER_FREQUENCY',\n 'UPPER_FREQUENCY', 'Error'])\n# Only has 8 entries, not a good sample\ndata.drop(data[data['AudioMothCode'] == 'AM-18'].index, inplace=True)\ndata", "_____no_output_____" ], [ "coords", "_____no_output_____" ], [ "devices_PSD = {}\ndevices_SNR = {}\ndevices_time = {}\ndevices_list = data.drop_duplicates(subset=['AudioMothCode']).loc[:,'AudioMothCode'].values", "_____no_output_____" ], [ "def Average(lst): \n return sum(lst) / len(lst)", "_____no_output_____" ], [ "def colors_from_values(values, palette_name):\n # normalize the values to range [0, 1]\n normalized = (values - min(values)) / (max(values) - min(values))\n # convert to indices\n indices = np.round(normalized * (len(values) - 1)).astype(np.int32)\n # use the indices to get the colors\n palette = sns.color_palette(palette_name, len(values))\n return np.array(palette).take(indices, axis=0)", "_____no_output_____" ], [ "# Add the PSD and SNR values to their corresponding audiomoths\nPSD_averages = []\nSNR_averages = []\nfor name in devices_list:\n dictPSD = {}\n dictSNR = {}\n dicttime = {}\n dictPSD['AudioMothCode'] = name\n dictPSD['values'] = data[data['AudioMothCode'] == name].loc[:,'PSD'].values\n dictPSD['Average PSD'] = Average(dictPSD['values'])\n devices_PSD[name] = dictPSD\n PSD_averages.append(Average(dictPSD['values']))\n \n dictSNR['AudioMothCode'] = name\n dictSNR['values'] = data[data['AudioMothCode'] == name].loc[:,'SNR'].values\n dictSNR['Average SNR'] = Average(dictSNR['values'])\n devices_SNR[name] = dictSNR\n SNR_averages.append(Average(dictSNR['values']))\n \n dicttime['AudioMothCode'] = name\n dicttime['values'] = data[data['AudioMothCode'] == name].loc[:,'HourDecTime'].values\n dicttime['average'] = Average(dictPSD['values'])\n# dicttime['values'] = list(map(int, dicttime['values']))\n devices_time[name] = dicttime\n", "_____no_output_____" ], [ "PSD_BAR = pd.DataFrame(devices_PSD, columns = devices_list)\nPSD_BAR = PSD_BAR.drop('values')\nPSD_BAR = PSD_BAR.T", "_____no_output_____" ], [ "PSD_BAR", "_____no_output_____" ], [ "APSD = sns.barplot(x='AudioMothCode', y='Average PSD', data=PSD_BAR, palette=\"crest\")\nAPSD.set_xticklabels(APSD.get_xticklabels(), rotation=90, horizontalalignment='right')\nAPSD.set_title('Average PSD Values per AudioMoth')\nAPSD", "_____no_output_____" ], [ "SNR_BAR = pd.DataFrame(devices_SNR, columns = devices_list)\nSNR_BAR = SNR_BAR.drop('values')\nSNR_BAR = SNR_BAR.T", "_____no_output_____" ], [ "SNR_BAR", "_____no_output_____" ], [ "ASNR = sns.barplot(x='AudioMothCode', y='Average SNR', data=SNR_BAR, palette=\"crest\")\nASNR.set_xticklabels(ASNR.get_xticklabels(), rotation=90, horizontalalignment='right')\nASNR.set_title('Average SNR Values per AudioMoth')\nASNR", "_____no_output_____" ], [ "hour_index = 0\nfor name in device_names: \n for i in range(0, 23):\n \n\n\nPSDheat = data\nPSDheat.pivot(\"AudioMothCode\", \"HourDecTime\", \"PSD\")\nheatmapPSD = sns.heatmap()", "_____no_output_____" ], [ "def mapcolor(value):\n if value > 0.0: \n return 'blue'\n return 'red'", "_____no_output_____" ], [ "mPSD = folium.Map(location=[-11.382,-69.951], zoom_start=10, tiles='Stamen Terrain')\n# mPSD = folium.Map(location=[-11.382,-69.951], zoom_start=10,\n# tiles='https://api.mapbox.com/styles/v1/nishantbalaji/ckoqa9o9x35hd18qe8rpnlsug/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoibmlzaGFudGJhbGFqaSIsImEiOiJja2xkOGl3cjcxc21yMndtdmxtZWpxeGRuIn0.isOPq2BjpvuzwjZMXW1yWA',\n# attr='Mapbox')\n# trying to style it to look nicer, but lets get the images on the map first\n# zoom_start=12,\n# tiles='https://api.mapbox.com/styles/v1/nishantbalaji/ckoqa9o9x35hd18qe8rpnlsug/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoibmlzaGFudGJhbGFqaSIsImEiOiJja2xkOGl3cjcxc21yMndtdmxtZWpxeGRuIn0.isOPq2BjpvuzwjZMXW1yWA',\n# attr='Mapbox'\n\n\n\nfor i in range(0,len(devices_list)):\n folium.CircleMarker(\n location=[coords.iloc[i]['Lat'], coords.iloc[i]['Long']],\n popup=PSD_BAR.iloc[i]['AudioMothCode']+\" \\nAverage PSD: \"+str(PSD_BAR.iloc[i]['Average PSD']),\n radius=float(abs(PSD_BAR.iloc[i]['Average PSD']))* 2,\n color=mapcolor(PSD_BAR.iloc[i]['Average PSD']),\n fill=True,\n fill_color=mapcolor(PSD_BAR.iloc[i]['Average PSD'])\n ).add_to(mPSD)", "_____no_output_____" ], [ "mPSD", "_____no_output_____" ], [ "mSNR = folium.Map(location=[-11.382,-69.951], zoom_start=10, tiles='Stamen Terrain')\n# mSNR = folium.Map(location=[-11.382,-69.951], zoom_start=10,\n# tiles='https://api.mapbox.com/styles/v1/nishantbalaji/ckoqa9o9x35hd18qe8rpnlsug/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoibmlzaGFudGJhbGFqaSIsImEiOiJja2xkOGl3cjcxc21yMndtdmxtZWpxeGRuIn0.isOPq2BjpvuzwjZMXW1yWA',\n# attr='Mapbox')\n\n\n\nfor i in range(0,len(devices_list)):\n folium.CircleMarker(\n location=[coords.iloc[i]['Lat'], coords.iloc[i]['Long']],\n popup=SNR_BAR.iloc[i]['AudioMothCode']+\" \\nAverage SNR: \"+str(SNR_BAR.iloc[i]['Average SNR']),\n radius=float(abs(SNR_BAR.iloc[i]['Average SNR'])) * 40,\n color=mapcolor(SNR_BAR.iloc[i]['Average SNR']),\n fill=True,\n fill_color=mapcolor(SNR_BAR.iloc[i]['Average SNR'])\n ).add_to(mSNR)", "_____no_output_____" ], [ "mSNR", "_____no_output_____" ], [ "mPSD.save(\"AveragePSD.html\")\nmSNR.save(\"AverageSNR.html\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0759e611a565cbebb672bcb7e90d71e8e5d1ff5
19,706
ipynb
Jupyter Notebook
notebooks/metrics_classification.ipynb
lesteve/scikit-learn-mooc
b822586b98e71dbbf003bde86be57412cb170291
[ "CC-BY-4.0" ]
1
2022-01-25T19:20:21.000Z
2022-01-25T19:20:21.000Z
notebooks/metrics_classification.ipynb
lesteve/scikit-learn-mooc
b822586b98e71dbbf003bde86be57412cb170291
[ "CC-BY-4.0" ]
null
null
null
notebooks/metrics_classification.ipynb
lesteve/scikit-learn-mooc
b822586b98e71dbbf003bde86be57412cb170291
[ "CC-BY-4.0" ]
null
null
null
34.693662
155
0.639095
[ [ [ "# Classification\n\nThis notebook aims at giving an overview of the classification metrics that\ncan be used to evaluate the predictive model generalization performance. We can\nrecall that in a classification setting, the vector `target` is categorical\nrather than continuous.\n\nWe will load the blood transfusion dataset.", "_____no_output_____" ] ], [ [ "import pandas as pd\n\nblood_transfusion = pd.read_csv(\"../datasets/blood_transfusion.csv\")\ndata = blood_transfusion.drop(columns=\"Class\")\ntarget = blood_transfusion[\"Class\"]", "_____no_output_____" ] ], [ [ "<div class=\"admonition note alert alert-info\">\n<p class=\"first admonition-title\" style=\"font-weight: bold;\">Note</p>\n<p class=\"last\">If you want a deeper overview regarding this dataset, you can refer to the\nAppendix - Datasets description section at the end of this MOOC.</p>\n</div>", "_____no_output_____" ], [ "Let's start by checking the classes present in the target vector `target`.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\ntarget.value_counts().plot.barh()\nplt.xlabel(\"Number of samples\")\n_ = plt.title(\"Number of samples per classes present\\n in the target\")", "_____no_output_____" ] ], [ [ "We can see that the vector `target` contains two classes corresponding to\nwhether a subject gave blood. We will use a logistic regression classifier to\npredict this outcome.\n\nTo focus on the metrics presentation, we will only use a single split instead\nof cross-validation.", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\n\ndata_train, data_test, target_train, target_test = train_test_split(\n data, target, shuffle=True, random_state=0, test_size=0.5)", "_____no_output_____" ] ], [ [ "We will use a logistic regression classifier as a base model. We will train\nthe model on the train set, and later use the test set to compute the\ndifferent classification metric.", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LogisticRegression\n\nclassifier = LogisticRegression()\nclassifier.fit(data_train, target_train)", "_____no_output_____" ] ], [ [ "## Classifier predictions\nBefore we go into details regarding the metrics, we will recall what type\nof predictions a classifier can provide.\n\nFor this reason, we will create a synthetic sample for a new potential donor:\nhe/she donated blood twice in the past (1000 c.c. each time). The last time\nwas 6 months ago, and the first time goes back to 20 months ago.", "_____no_output_____" ] ], [ [ "new_donor = [[6, 2, 1000, 20]]", "_____no_output_____" ] ], [ [ "We can get the class predicted by the classifier by calling the method\n`predict`.", "_____no_output_____" ] ], [ [ "classifier.predict(new_donor)", "_____no_output_____" ] ], [ [ "With this information, our classifier predicts that this synthetic subject\nis more likely to not donate blood again.\n\nHowever, we cannot check whether the prediction is correct (we do not know\nthe true target value). That's the purpose of the testing set. First, we\npredict whether a subject will give blood with the help of the trained\nclassifier.", "_____no_output_____" ] ], [ [ "target_predicted = classifier.predict(data_test)\ntarget_predicted[:5]", "_____no_output_____" ] ], [ [ "## Accuracy as a baseline\nNow that we have these predictions, we can compare them with the true\npredictions (sometimes called ground-truth) which we did not use until now.", "_____no_output_____" ] ], [ [ "target_test == target_predicted", "_____no_output_____" ] ], [ [ "In the comparison above, a `True` value means that the value predicted by our\nclassifier is identical to the real value, while a `False` means that our\nclassifier made a mistake. One way of getting an overall rate representing\nthe generalization performance of our classifier would be to compute how many\ntimes our classifier was right and divide it by the number of samples in our\nset.", "_____no_output_____" ] ], [ [ "import numpy as np\n\nnp.mean(target_test == target_predicted)", "_____no_output_____" ] ], [ [ "This measure is called the accuracy. Here, our classifier is 78%\naccurate at classifying if a subject will give blood. `scikit-learn` provides\na function that computes this metric in the module `sklearn.metrics`.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import accuracy_score\n\naccuracy = accuracy_score(target_test, target_predicted)\nprint(f\"Accuracy: {accuracy:.3f}\")", "_____no_output_____" ] ], [ [ "`LogisticRegression` also has a method named `score` (part of the standard\nscikit-learn API), which computes the accuracy score.", "_____no_output_____" ] ], [ [ "classifier.score(data_test, target_test)", "_____no_output_____" ] ], [ [ "## Confusion matrix and derived metrics\nThe comparison that we did above and the accuracy that we calculated did not\ntake into account the type of error our classifier was making. Accuracy\nis an aggregate of the errors made by the classifier. We may be interested\nin finer granularity - to know independently what the error is for each of\nthe two following cases:\n\n- we predicted that a person will give blood but she/he did not;\n- we predicted that a person will not give blood but she/he did.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import ConfusionMatrixDisplay\n\n_ = ConfusionMatrixDisplay.from_estimator(classifier, data_test, target_test)", "_____no_output_____" ] ], [ [ "The in-diagonal numbers are related to predictions that were correct\nwhile off-diagonal numbers are related to incorrect predictions\n(misclassifications). We now know the four types of correct and erroneous\npredictions:\n\n* the top left corner are true positives (TP) and corresponds to people\n who gave blood and were predicted as such by the classifier;\n* the bottom right corner are true negatives (TN) and correspond to\n people who did not give blood and were predicted as such by the\n classifier;\n* the top right corner are false negatives (FN) and correspond to\n people who gave blood but were predicted to not have given blood;\n* the bottom left corner are false positives (FP) and correspond to\n people who did not give blood but were predicted to have given blood.\n\nOnce we have split this information, we can compute metrics to highlight the\ngeneralization performance of our classifier in a particular setting. For\ninstance, we could be interested in the fraction of people who really gave\nblood when the classifier predicted so or the fraction of people predicted to\nhave given blood out of the total population that actually did so.\n\nThe former metric, known as the precision, is defined as TP / (TP + FP)\nand represents how likely the person actually gave blood when the classifier\npredicted that they did.\nThe latter, known as the recall, defined as TP / (TP + FN) and\nassesses how well the classifier is able to correctly identify people who\ndid give blood.\nWe could, similarly to accuracy, manually compute these values,\nhowever scikit-learn provides functions to compute these statistics.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import precision_score, recall_score\n\nprecision = precision_score(target_test, target_predicted, pos_label=\"donated\")\nrecall = recall_score(target_test, target_predicted, pos_label=\"donated\")\n\nprint(f\"Precision score: {precision:.3f}\")\nprint(f\"Recall score: {recall:.3f}\")", "_____no_output_____" ] ], [ [ "These results are in line with what was seen in the confusion matrix. Looking\nat the left column, more than half of the \"donated\" predictions were correct,\nleading to a precision above 0.5. However, our classifier mislabeled a lot of\npeople who gave blood as \"not donated\", leading to a very low recall of\naround 0.1.\n\n## The issue of class imbalance\nAt this stage, we could ask ourself a reasonable question. While the accuracy\ndid not look bad (i.e. 77%), the recall score is relatively low (i.e. 12%).\n\nAs we mentioned, precision and recall only focuses on samples predicted to be\npositive, while accuracy takes both into account. In addition, we did not\nlook at the ratio of classes (labels). We could check this ratio in the\ntraining set.", "_____no_output_____" ] ], [ [ "target_train.value_counts(normalize=True).plot.barh()\nplt.xlabel(\"Class frequency\")\n_ = plt.title(\"Class frequency in the training set\")", "_____no_output_____" ] ], [ [ "We observe that the positive class, `'donated'`, comprises only 24% of the\nsamples. The good accuracy of our classifier is then linked to its ability to\ncorrectly predict the negative class `'not donated'` which may or may not be\nrelevant, depending on the application. We can illustrate the issue using a\ndummy classifier as a baseline.", "_____no_output_____" ] ], [ [ "from sklearn.dummy import DummyClassifier\n\ndummy_classifier = DummyClassifier(strategy=\"most_frequent\")\ndummy_classifier.fit(data_train, target_train)\nprint(f\"Accuracy of the dummy classifier: \"\n f\"{dummy_classifier.score(data_test, target_test):.3f}\")", "_____no_output_____" ] ], [ [ "With the dummy classifier, which always predicts the negative class `'not\ndonated'`, we obtain an accuracy score of 76%. Therefore, it means that this\nclassifier, without learning anything from the data `data`, is capable of\npredicting as accurately as our logistic regression model.\n\nThe problem illustrated above is also known as the class imbalance problem.\nWhen the classes are imbalanced, accuracy should not be used. In this case,\none should either use the precision and recall as presented above or the\nbalanced accuracy score instead of accuracy.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import balanced_accuracy_score\n\nbalanced_accuracy = balanced_accuracy_score(target_test, target_predicted)\nprint(f\"Balanced accuracy: {balanced_accuracy:.3f}\")", "_____no_output_____" ] ], [ [ "The balanced accuracy is equivalent to accuracy in the context of balanced\nclasses. It is defined as the average recall obtained on each class.\n\n## Evaluation and different probability thresholds\n\nAll statistics that we presented up to now rely on `classifier.predict` which\noutputs the most likely label. We haven't made use of the probability\nassociated with this prediction, which gives the confidence of the\nclassifier in this prediction. By default, the prediction of a classifier\ncorresponds to a threshold of 0.5 probability in a binary classification\nproblem. We can quickly check this relationship with the classifier that\nwe trained.", "_____no_output_____" ] ], [ [ "target_proba_predicted = pd.DataFrame(classifier.predict_proba(data_test),\n columns=classifier.classes_)\ntarget_proba_predicted[:5]", "_____no_output_____" ], [ "target_predicted = classifier.predict(data_test)\ntarget_predicted[:5]", "_____no_output_____" ] ], [ [ "Since probabilities sum to 1 we can get the class with the highest\nprobability without using the threshold 0.5.", "_____no_output_____" ] ], [ [ "equivalence_pred_proba = (\n target_proba_predicted.idxmax(axis=1).to_numpy() == target_predicted)\nnp.all(equivalence_pred_proba)", "_____no_output_____" ] ], [ [ "The default decision threshold (0.5) might not be the best threshold that\nleads to optimal generalization performance of our classifier. In this case, one\ncan vary the decision threshold, and therefore the underlying prediction, and\ncompute the same statistics presented earlier. Usually, the two metrics\nrecall and precision are computed and plotted on a graph. Each metric plotted\non a graph axis and each point on the graph corresponds to a specific\ndecision threshold. Let's start by computing the precision-recall curve.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import PrecisionRecallDisplay\n\ndisp = PrecisionRecallDisplay.from_estimator(\n classifier, data_test, target_test, pos_label='donated',\n marker=\"+\"\n)\n_ = disp.ax_.set_title(\"Precision-recall curve\")", "_____no_output_____" ] ], [ [ "<div class=\"admonition tip alert alert-warning\">\n<p class=\"first admonition-title\" style=\"font-weight: bold;\">Tip</p>\n<p class=\"last\">Scikit-learn will return a display containing all plotting element. Notably,\ndisplays will expose a matplotlib axis, named <tt class=\"docutils literal\">ax_</tt>, that can be used to add\nnew element on the axis.\nYou can refer to the documentation to have more information regarding the\n<a class=\"reference external\" href=\"https://scikit-learn.org/stable/visualizations.html#visualizations\">visualizations in scikit-learn</a></p>\n</div>\n\nOn this curve, each blue cross corresponds to a level of probability which we\nused as a decision threshold. We can see that, by varying this decision\nthreshold, we get different precision vs. recall values.\n\nA perfect classifier would have a precision of 1 for all recall values. A\nmetric characterizing the curve is linked to the area under the curve (AUC)\nand is named average precision (AP). With an ideal classifier, the average\nprecision would be 1.\n\nThe precision and recall metric focuses on the positive class, however, one\nmight be interested in the compromise between accurately discriminating the\npositive class and accurately discriminating the negative classes. The\nstatistics used for this are sensitivity and specificity. Sensitivity is just\nanother name for recall. However, specificity measures the proportion of\ncorrectly classified samples in the negative class defined as: TN / (TN +\nFP). Similar to the precision-recall curve, sensitivity and specificity are\ngenerally plotted as a curve called the receiver operating characteristic\n(ROC) curve. Below is such a curve:", "_____no_output_____" ] ], [ [ "from sklearn.metrics import RocCurveDisplay\n\ndisp = RocCurveDisplay.from_estimator(\n classifier, data_test, target_test, pos_label='donated',\n marker=\"+\")\ndisp = RocCurveDisplay.from_estimator(\n dummy_classifier, data_test, target_test, pos_label='donated',\n color=\"tab:orange\", linestyle=\"--\", ax=disp.ax_)\n_ = disp.ax_.set_title(\"ROC AUC curve\")", "_____no_output_____" ] ], [ [ "This curve was built using the same principle as the precision-recall curve:\nwe vary the probability threshold for determining \"hard\" prediction and\ncompute the metrics. As with the precision-recall curve, we can compute the\narea under the ROC (ROC-AUC) to characterize the generalization performance of\nour classifier. However, it is important to observe that the lower bound of\nthe ROC-AUC is 0.5. Indeed, we show the generalization performance of a dummy\nclassifier (the orange dashed line) to show that even the worst generalization\nperformance obtained will be above this line.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d075ac52423f4b41b3191604aacc09a851929d7b
21,460
ipynb
Jupyter Notebook
resultados/4.Proxy.ipynb
jacsonrbinf/minicurso-mineracao-interativa
79b479f5fa68c317902e069826977748b00bbae9
[ "MIT" ]
2
2019-10-30T04:33:32.000Z
2019-10-30T04:36:29.000Z
resultados/4.Proxy.ipynb
jacsonrbinf/minicurso-mineracao-interativa
79b479f5fa68c317902e069826977748b00bbae9
[ "MIT" ]
null
null
null
resultados/4.Proxy.ipynb
jacsonrbinf/minicurso-mineracao-interativa
79b479f5fa68c317902e069826977748b00bbae9
[ "MIT" ]
4
2019-10-29T23:05:00.000Z
2022-03-13T18:17:31.000Z
32.863706
429
0.51123
[ [ [ "Para entrar no modo apresentação, execute a seguinte célula e pressione `-`", "_____no_output_____" ] ], [ [ "%reload_ext slide", "_____no_output_____" ] ], [ [ "<span class=\"notebook-slide-start\"/>\n\n# Proxy\n\nEste notebook apresenta os seguintes tópicos:\n\n- [Introdução](#Introdu%C3%A7%C3%A3o)\n- [Servidor de proxy](#Servidor-de-proxy)", "_____no_output_____" ], [ "## Introdução\n\nExiste muita informação disponível em repositórios software.\n\nA seguir temos uma *screenshot* do repositório `gems-uff/sapos`.\n\n<img src=\"images/githubexample.png\" alt=\"Página Inicial de Repositório no GitHub\" width=\"auto\"/>", "_____no_output_____" ], [ "Nessa imagem, vemos a organização e nome do repositório\n\n<img src=\"images/githubexample1.png\" alt=\"Página Inicial de Repositório no GitHub com nome do repositório selecionado\" width=\"auto\"/>", "_____no_output_____" ], [ "Estrelas, forks, watchers \n\n<img src=\"images/githubexample2.png\" alt=\"Página Inicial de Repositório no GitHub com watchers, star e fork selecionados\" width=\"auto\"/>", "_____no_output_____" ], [ "Número de issues e pull requests \n\n<img src=\"images/githubexample3.png\" alt=\"Página Inicial de Repositório no GitHub com numero de issues e pull requests selecionados\" width=\"auto\"/>", "_____no_output_____" ], [ "Número de commits, branches, releases, contribuidores e licensa <span class=\"notebook-slide-extra\" data-count=\"1\"/>\n\n<img src=\"images/githubexample4.png\" alt=\"Página Inicial de Repositório no GitHub com número de commits, branches, releases, contribuidores e licensa selecionados\" width=\"auto\"/>", "_____no_output_____" ], [ "Arquivos\n\n<img src=\"images/githubexample5.png\" alt=\"Página Inicial de Repositório no GitHub com arquivos selecionados\" width=\"auto\"/>\n", "_____no_output_____" ], [ "Mensagem e data dos commits que alteraram esses arquivos por último \n\n<img src=\"images/githubexample6.png\" alt=\"Página Inicial de Repositório no GitHub com arquivos selecionados\" width=\"auto\"/>", "_____no_output_____" ], [ "Podemos extrair informações de repositórios de software de 3 formas:\n\n- Crawling do site do repositório\n- APIs que fornecem dados\n- Diretamente do sistema de controle de versões\n\nNeste minicurso abordaremos as 3 maneiras, porém daremos mais atenção a APIs do GitHub e extração direta do Git.", "_____no_output_____" ], [ "## Servidor de proxy\n\nServidores de repositório costumam limitar a quantidade de requisições que podemos fazer.\n\nEm geral, essa limitação não afeta muito o uso esporádico dos serviços para mineração. Porém, quando estamos desenvolvendo algo, pode ser que passemos do limite com requisições repetidas.\n\nPara evitar esse problema, vamos configurar um servidor de proxy simples em flask.", "_____no_output_____" ], [ "Quando estamos usando um servidor de proxy, ao invés de fazermos requisições diretamente ao site de destino, fazemos requisições ao servidor de proxy, que, em seguida, redireciona as requisições para o site de destino.\n\nAo receber o resultado da requisição, o proxy faz um cache do resultado e nos retorna o resultado.\n\nSe uma requisição já tiver sido feita pelo servidor de proxy, ele apenas nos retorna o resultado do cache.", "_____no_output_____" ], [ "### Implementação do Proxy\n\nA implementação do servidor de proxy está no arquivo `proxy.py`. Como queremos executar o proxy em paralelo ao notebook, o servidor precisa ser executado externamente.\n\nEntretanto, o código do proxy será explicado aqui.", "_____no_output_____" ], [ "Começamos o arquivo com os imports necessários. \n\n```python\nimport hashlib\nimport requests\nimport simplejson\nimport os\nimport sys\nfrom flask import Flask, request, Response\n```\n\nA biblioteca `hashlib` é usada para fazer hash das requisições. A biblioteca `requests` é usada para fazer requisições ao GitHub. A biblioteca `simplejson` é usada para transformar requisiçoes e respostas em JSON. A biblioteca `os` é usada para manipular caminhos de diretórios e verificar a existência de arquivos. A biblioteca `sys` é usada para pegar os argumentos da execução. Por fim, `flask` é usada como servidor.\n\n", "_____no_output_____" ], [ "Em seguida, definimos o site para qual faremos proxy, os headers excluídos da resposta recebida, e criamos um `app` pro `Flask`. Note que `SITE` está sendo definido como o primeiro argumendo da execução do programa ou como https://github.com/, caso não haja argumento.\n\n```python\nif len(sys.argv) > 1:\n SITE = sys.argv[1]\nelse:\n SITE = \"https://github.com/\"\nEXCLUDED_HEADERS = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']\n\napp = Flask(__name__)\n```", "_____no_output_____" ], [ "Depois, definimos uma função para tratar todas rotas e métodos possíveis que o servidor pode receber.\n\n```python\nMETHODS = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE']\[email protected]('/', defaults={'path': ''}, methods=METHODS)\[email protected]('/<path:path>', methods=METHODS)\ndef catch_all(path):\n```", "_____no_output_____" ], [ "Dentro desta função, definimos um dicionário de requisição com base na requisição que foi recebida pelo `flask`.\n\n```python\n request_dict = {\n \"method\": request.method,\n \"url\": request.url.replace(request.host_url, SITE),\n \"headers\": {key: value for (key, value) in request.headers if key != 'Host'},\n \"data\": request.get_data(),\n \"cookies\": request.cookies,\n \"allow_redirects\": False\n }\n```\n\nNesta requsição, substituímos o host pelo site de destino.\n", "_____no_output_____" ], [ "Em seguida, convertemos o dicionário para JSON e calculamos o hash SHA1 do resultado.\n\n```python\n request_json = simplejson.dumps(request_dict, sort_keys=True)\n sha1 = hashlib.sha1(request_json.encode(\"utf-8\")).hexdigest()\n path_req = os.path.join(\"cache\", sha1 + \".req\")\n path_resp = os.path.join(\"cache\", sha1 + \".resp\")\n```\n\nNo diretório `cache` armazenamos arquivos `{sha1}.req` e `{sha1}.resp` com a requisição e resposta dos resultados em cache.", "_____no_output_____" ], [ "Com isso, ao receber uma requisição, podemos ver se `{sha1}.req` existe. Se existir, podemos comparar com a nossa requisição (para evitar conflitos). Por fim, se forem iguais, podemos retornar a resposta que está em cache.\n\n```python\n if os.path.exists(path_req):\n with open(path_req, \"r\") as req:\n req_read = req.read()\n if req_read == request_json:\n with open(path_resp, \"r\") as dump:\n response = simplejson.load(dump)\n return Response(\n response[\"content\"],\n response[\"status_code\"],\n response[\"headers\"]\n )\n```", "_____no_output_____" ], [ "Se a requisição não estiver em cache, transformamos o dicionário da requisição em uma requisição do `requests` para o GitHub, excluimos os headers populados pelo `flask` e criamos um JSON para a resposta.\n\n```python\n resp = requests.request(**request_dict)\n headers = [(name, value) for (name, value) in resp.raw.headers.items()\n if name.lower() not in EXCLUDED_HEADERS]\n response = {\n \"content\": resp.content,\n \"status_code\": resp.status_code,\n \"headers\": headers\n }\n response_json = simplejson.dumps(response, sort_keys=True)\n```", "_____no_output_____" ], [ "Depois disso, salvamos a resposta no cache e retornamos ela para o cliente original.\n\n```python\n with open(path_resp, \"w\") as dump:\n dump.write(response_json)\n with open(path_req, \"w\") as req:\n req.write(request_json)\n return Response(\n response[\"content\"],\n response[\"status_code\"],\n response[\"headers\"]\n )\n```", "_____no_output_____" ], [ "No fim do script, iniciamos o servidor.\n\n```python\nif __name__ == '__main__':\n app.run(debug=True)\n```", "_____no_output_____" ], [ "### Uso do Proxy\n\nExecute a seguinte linha em um terminal:\n\n```bash\npython proxy.py\n```\n\nAgora, toda requisição que faríamos a github.com, passaremos a fazer a localhost:5000. Por exemplo, ao invés de acessar https://github.com/gems-uff/sapos, acessaremos http://localhost:5000/gems-uff/sapos\n", "_____no_output_____" ], [ "### Requisição com requests\n\nA seguir fazemos uma requisição com requests para o proxy. <span class=\"notebook-slide-extra\" data-count=\"2\"/>", "_____no_output_____" ] ], [ [ "SITE = \"http://localhost:5000/\" # Se não usar o proxy, alterar para https://github.com/", "_____no_output_____" ], [ "import requests\n\nresponse = requests.get(SITE + \"gems-uff/sapos\")\nresponse.headers['server'], response.status_code", "_____no_output_____" ] ], [ [ "<span class=\"notebook-slide-scroll\" data-position=\"-1\"/>\n\nPodemos que o resultado foi obtido do GitHub e que a requisição funcionou, dado que o resultado foi 200. ", "_____no_output_____" ], [ "Continua: [5.Crawling.ipynb](5.Crawling.ipynb)", "_____no_output_____" ], [ "&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n\n&nbsp;\n\n&nbsp;\n\n&nbsp;\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
d075ac543b800b90cb4576ebbb43b2e84ff1b796
21,504
ipynb
Jupyter Notebook
P3-Kaggle-Clasificacion/P3/prueba30.ipynb
jcgq/Inteligecia-de-negocio
78a993c339fb8eb399ef3513fc225bc951b293e6
[ "MIT" ]
1
2021-05-25T13:44:26.000Z
2021-05-25T13:44:26.000Z
P3-Kaggle-Clasificacion/P3/prueba30.ipynb
jcgq/Inteligecia-de-negocio
78a993c339fb8eb399ef3513fc225bc951b293e6
[ "MIT" ]
null
null
null
P3-Kaggle-Clasificacion/P3/prueba30.ipynb
jcgq/Inteligecia-de-negocio
78a993c339fb8eb399ef3513fc225bc951b293e6
[ "MIT" ]
null
null
null
35.368421
146
0.63551
[ [ [ "import pandas as pd\nimport numpy as np\nimport time\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing as pp\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import preprocessing\nimport xgboost as xgb\nfrom sklearn.ensemble import BaggingClassifier\nimport lightgbm as lgb\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import preprocessing as pp\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import tree\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_val_predict\nfrom statistics import mode\nfrom sklearn.model_selection import cross_val_score, cross_validate, train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nimport xgboost as xgb\nimport lightgbm as lgb\n\n#Todas las librerías para los distintos algoritmos\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.naive_bayes import ComplementNB\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import OneClassSVM\nfrom sklearn.svm import SVC\nfrom sklearn.svm import NuSVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nimport matplotlib.pyplot as plt\nimport sklearn.metrics as metrics\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import BaggingClassifier\nimport statistics\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.decomposition import PCA\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nimport warnings\nfrom mlxtend.classifier import StackingClassifier\nfrom mlxtend.classifier import StackingCVClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom pylab import rcParams\n \nfrom collections import Counter\n\nwarnings.simplefilter('ignore')\n", "_____no_output_____" ], [ "data_train= pd.read_csv(\"./datos/train.csv\",na_values=[\"?\"])\ndata_test= pd.read_csv(\"./datos/test.csv\",na_values=[\"?\"])\ndata_trainCopia = data_train.copy()\ndata_testCopia = data_test.copy()\nNombre = LabelEncoder().fit(pd.read_csv(\"./datos/nombre.csv\").Nombre)\nAño = LabelEncoder().fit(pd.read_csv(\"./datos/ao.csv\").Año)\nCiudad = LabelEncoder().fit(pd.read_csv(\"./datos/ciudad.csv\").Ciudad)\nCombustible = LabelEncoder().fit(pd.read_csv(\"./datos/combustible.csv\").Combustible)\nConsumo = LabelEncoder().fit(pd.read_csv(\"./datos/consumo.csv\").Consumo)\nDescuento = LabelEncoder().fit(pd.read_csv(\"./datos/descuento.csv\").Descuento)\nKilometros = LabelEncoder().fit(pd.read_csv(\"./datos/kilometros.csv\").Kilometros)\nMano = LabelEncoder().fit(pd.read_csv(\"./datos/mano.csv\").Mano)\nPotencia = LabelEncoder().fit(pd.read_csv(\"./datos/potencia.csv\").Potencia)\nAsientos = LabelEncoder().fit(pd.read_csv(\"./datos/asientos.csv\").Asientos)\nMotor_CC=LabelEncoder().fit(pd.read_csv(\"./datos/motor_cc.csv\").Motor_CC)\nTipo_marchas=LabelEncoder().fit(pd.read_csv(\"./datos/Tipo_marchas.csv\").Tipo_marchas)\n\ndata_trainCopia['Nombre']=data_trainCopia['Nombre'].fillna(mode(data_trainCopia['Nombre']))\ndata_trainCopia['Año']=data_trainCopia['Año'].fillna(mode(data_trainCopia['Año']))\ndata_trainCopia['Ciudad']=data_trainCopia['Ciudad'].fillna(mode(data_trainCopia['Ciudad']))\n#data_trainCopia['Kilometros']=data_trainCopia['Kilometros'].fillna(mode(data_trainCopia['Kilometros']))\ndata_trainCopia['Combustible']=data_trainCopia['Combustible'].fillna(mode(data_trainCopia['Combustible']))\ndata_trainCopia['Tipo_marchas']=data_trainCopia['Tipo_marchas'].fillna(mode(data_trainCopia['Tipo_marchas']))\n#data_trainCopia['Mano']=data_trainCopia['Mano'].fillna(mode(data_trainCopia['Mano']))\ndata_trainCopia['Consumo']=data_trainCopia['Consumo'].fillna(mode(data_trainCopia['Consumo']))\ndata_trainCopia['Motor_CC']=data_trainCopia['Motor_CC'].fillna(mode(data_trainCopia['Motor_CC']))\ndata_trainCopia['Potencia']=data_trainCopia['Potencia'].fillna(mode(data_trainCopia['Potencia']))\ndata_trainCopia['Asientos']=data_trainCopia['Asientos'].fillna(mode(data_trainCopia['Asientos']))\ndata_trainCopia['Descuento']=data_trainCopia['Descuento'].fillna(mode(data_trainCopia['Descuento']))\n\n#Eliminamos las columnas que no necesitamos\ndata_trainCopia=data_trainCopia.drop(['Descuento'], axis=1)\ndata_trainCopia=data_trainCopia.drop(['id'], axis=1)\ndata_trainCopia=data_trainCopia.drop(['Kilometros'], axis=1)\ndata_testCopia=data_testCopia.drop(['Descuento'], axis=1)\ndata_testCopia=data_testCopia.drop(['id'], axis=1)\ndata_testCopia=data_testCopia.drop(['Kilometros'], axis=1)\n\n\n#Eliminamos los nan de los ids\ndata_trainCopia=data_trainCopia.dropna() \ndata_testCopia=data_testCopia.dropna() \n\n#Codificación de las filas\ndata_trainCopia.Nombre = Nombre.transform(data_trainCopia.Nombre)\ndata_trainCopia.Año = Año.transform(data_trainCopia.Año)\ndata_trainCopia.Ciudad = Ciudad.transform(data_trainCopia.Ciudad)\ndata_trainCopia.Combustible = Combustible.transform(data_trainCopia.Combustible)\ndata_trainCopia.Potencia = Potencia.transform(data_trainCopia.Potencia)\ndata_trainCopia.Consumo = Consumo.transform(data_trainCopia.Consumo)\n#data_trainCopia.Kilometros = Kilometros.transform(data_trainCopia.Kilometros)\ndata_trainCopia.Mano = Mano.transform(data_trainCopia.Mano)\ndata_trainCopia.Motor_CC = Motor_CC.transform(data_trainCopia.Motor_CC)\ndata_trainCopia.Tipo_marchas = Tipo_marchas.transform(data_trainCopia.Tipo_marchas)\ndata_trainCopia.Asientos = Asientos.transform(data_trainCopia.Asientos)\n#-------------------------------------------------------------------------------------------\ndata_testCopia.Nombre = Nombre.transform(data_testCopia.Nombre)\ndata_testCopia.Año = Año.transform(data_testCopia.Año)\ndata_testCopia.Ciudad = Ciudad.transform(data_testCopia.Ciudad)\ndata_testCopia.Combustible = Combustible.transform(data_testCopia.Combustible)\ndata_testCopia.Potencia = Potencia.transform(data_testCopia.Potencia)\ndata_testCopia.Consumo = Consumo.transform(data_testCopia.Consumo)\n#data_testCopia.Kilometros = Kilometros.transform(data_testCopia.Kilometros)\ndata_testCopia.Mano = Mano.transform(data_testCopia.Mano)\ndata_testCopia.Tipo_marchas = Tipo_marchas.transform(data_testCopia.Tipo_marchas)\ndata_testCopia.Asientos = Asientos.transform(data_testCopia.Asientos)\ndata_testCopia.Motor_CC = Motor_CC.transform(data_testCopia.Motor_CC)\n\ntarget = pd.read_csv('./datos/precio_cat.csv')\ntarget_train=data_trainCopia['Precio_cat']\ndata_trainCopia=data_trainCopia.drop(['Precio_cat'], axis=1)", "_____no_output_____" ], [ "GradientBoostingClassifier(criterion='friedman_mse', init=None,\n learning_rate=0.1, loss='deviance', max_depth=3,\n max_features=None, max_leaf_nodes=None,\n min_impurity_split=1e-07, min_samples_leaf=1,\n min_samples_split=2, min_weight_fraction_leaf=0.0,\n n_estimators=100, presort='auto', random_state=None,\n subsample=1.0, verbose=0, warm_start=False)", "_____no_output_____" ], [ "from imblearn.over_sampling import SMOTE\nXo, yo = SMOTE(random_state=42).fit_resample(data_trainCopia, target_train)", "_____no_output_____" ], [ "clf = GradientBoostingClassifier(learning_rate=0.07, n_estimators=700, max_depth=2)\n\nscores = cross_val_score(clf, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(Xo, yo)\npreclf = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 86.74643350207087\n" ], [ "clf = GradientBoostingClassifier(learning_rate=0.09, n_estimators=700, max_depth=2)\n\nscores = cross_val_score(clf, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(Xo, yo)\npreclf = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 87.47353888633226\n" ], [ "clf = GradientBoostingClassifier(learning_rate=0.9, n_estimators=750, max_depth=2)\n\nscores = cross_val_score(clf, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(Xo, yo)\npreclfOverGradient = clfEntrenado.predict(data_testCopia)\n\n\ndfAux = pd.DataFrame({'id':data_test['id']})\ndfAux.set_index('id', inplace=True)\ndfFinal = pd.DataFrame({'id': data_test['id'], 'Precio_cat': preclfOverGradient}, columns=['id', 'Precio_cat'])\ndfFinal.set_index('id', inplace=True)\ndfFinal.to_csv(\"./soluciones/GradientOverSamplingConRandomStateScoreLocal895628.csv\")", "Score Validacion Cruzada 89.5904279797515\n" ], [ "clf = GradientBoostingClassifier(learning_rate=0.055, n_estimators=2500, max_depth=2)\n\nscores = cross_val_score(clf, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(Xo, yo)\npreclfOverGradient = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 89.12103083294983\n" ], [ "clf = GradientBoostingClassifier(learning_rate=0.5, n_estimators=400)\n\nscores = cross_val_score(clf, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(Xo, yo)\npreclfOverGradient = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 90.57524160147261\n" ], [ "clf = GradientBoostingClassifier(learning_rate=0.5, n_estimators=100, max_depth=6)\n\nscores = cross_val_score(clf, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(Xo, yo)\npreclfOverGradient = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 91.32995858260469\n" ], [ "clf = GradientBoostingClassifier(learning_rate=0.5, n_estimators=100, max_depth=6)\n\nscores = cross_val_score(clf, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(Xo, yo)\npreclfOverGradient = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 90.86976530142661\n" ], [ "clf = GradientBoostingClassifier(learning_rate=0.5, n_estimators=100, max_depth=6)\n\nscores = cross_val_score(clf, data_trainCopia, target_train, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(data_trainCopia, target_train)\npreclfOverGradient = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 81.41986578670067\n" ], [ "lgbm1 = lgb.LGBMClassifier(learning_rate=0.5, objective='binary', n_estimators=550, n_jobs=2, \n num_leaves=11, max_depth=-1, reg_alpha=0.1)\n\nscores = cross_val_score(lgbm1, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada CON MODELO\", np.mean(scores)*100)\n\nlgbmEntrenado = lgbm1.fit(Xo, yo)\npreMamaJuanca = lgbmEntrenado.predict(data_testCopia)", "Score Validacion Cruzada CON MODELO 91.07225034514498\n" ], [ "lgbm1 = lgb.LGBMClassifier(learning_rate=0.5, objective='binary', n_estimators=550, n_jobs=2, \n num_leaves=11, max_depth=-1, reg_alpha=0.1)\n\nscores = cross_val_score(lgbm1, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada CON MODELO\", np.mean(scores)*100)\n\nlgbmEntrenado = lgbm1.fit(Xo, yo)\npreMamaJuanca = lgbmEntrenado.predict(data_testCopia)", "Score Validacion Cruzada CON MODELO 90.74091118269672\n" ], [ "lgbm1 = lgb.LGBMClassifier(learning_rate=0.2, objective='binary', n_estimators=550, n_jobs=2, \n num_leaves=11, max_depth=-1)\n\nscores = cross_val_score(lgbm1, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada CON MODELO\", np.mean(scores)*100)\n\nlgbmEntrenado = lgbm1.fit(Xo, yo)\npreMamaJuanca = lgbmEntrenado.predict(data_testCopia)", "Score Validacion Cruzada CON MODELO 90.92498849516797\n" ], [ "lgbm1 = lgb.LGBMClassifier(learning_rate=0.2, objective='multiclassova', n_estimators=550, n_jobs=2, \n num_leaves=11, max_depth=-1)\n\nscores = cross_val_score(lgbm1, data_trainCopia, target_train, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada CON MODELO\", np.mean(scores)*100)\n\nlgbmEntrenado = lgbm1.fit(data_trainCopia, target_train)\npreMamaJuanca = lgbmEntrenado.predict(data_testCopia)", "Score Validacion Cruzada CON MODELO nan\n" ], [ "lgbm1 = lgb.LGBMClassifier(learning_rate=0.3, objective='binary', n_estimators=500, n_jobs=2, \n num_leaves=11, max_depth=-1)\n\nscores = cross_val_score(lgbm1, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada CON MODELO\", np.mean(scores)*100)\n\nlgbmEntrenado = lgbm1.fit(Xo, yo)\npreMamaJuanca = lgbmEntrenado.predict(data_testCopia)", "Score Validacion Cruzada CON MODELO 91.21951219512195\n" ], [ "lgbm1 = lgb.LGBMClassifier(learning_rate=0.3, objective='binary', n_estimators=60, n_jobs=2, num_leaves=8, max_depth=8)\n\nscores = cross_val_score(lgbm1, data_trainCopia, target_train, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada CON MODELO\", np.mean(scores)*100)\n\nlgbmEntrenado = lgbm1.fit(data_trainCopia, target_train)\npreMamaJuanca = lgbmEntrenado.predict(data_testCopia)", "Score Validacion Cruzada CON MODELO 83.2513368983957\n" ], [ "#GRADIENT BOOSTING CON PARAMETROS DE GRIDSHARE Y DATOS SIN NORMALIZAR\nclf = GradientBoostingClassifier(learning_rate=0.3, n_estimators=70, max_depth=4)\n\nscores = cross_val_score(clf, data_trainCopia, target_train, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(data_trainCopia, target_train)\npreclfOverGradient = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 83.01604278074865\n" ], [ "#ESTO ME HA DICHO QUE ES LO QUE ME VA A SUBIR\n#GRADIENT BOOSTING CON PARAMETROS DE GRIDSHARE Y DATOS NORMALIZADOS\nclf = GradientBoostingClassifier(learning_rate=0.5, n_estimators=70, max_depth=5, random_state=42)\n\nscores = cross_val_score(clf, Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada\", np.mean(scores)*100)\n\nclfEntrenado = clf.fit(Xo, yo)\npreclfOverGradient = clfEntrenado.predict(data_testCopia)", "Score Validacion Cruzada 90.98552078468005\n" ], [ "\nlgbm1 = lgb.LGBMClassifier(learning_rate=0.7, objective='binary', n_estimators=70, n_jobs=2, num_leaves=10, max_depth=4, random_state=42)\n\nscores = cross_val_score(lgbm1,Xo, yo, cv=5, scoring='accuracy')\nprint(\"Score Validacion Cruzada CON MODELO\", np.mean(scores)*100)\n\nlgbmEntrenado = lgbm1.fit(Xo, yo)\npreMamaJuanca = lgbmEntrenado.predict(data_testCopia)", "Score Validacion Cruzada CON MODELO 78.67351704810835\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d075b2e71f2b4defbc8896bc34dced58ec3cd9a9
2,659
ipynb
Jupyter Notebook
709.ToLowerCase.ipynb
charlesxu90/leetcode_py
e649c138c62aa2ce6c4ba77d39c7172e96f24811
[ "Apache-2.0" ]
null
null
null
709.ToLowerCase.ipynb
charlesxu90/leetcode_py
e649c138c62aa2ce6c4ba77d39c7172e96f24811
[ "Apache-2.0" ]
null
null
null
709.ToLowerCase.ipynb
charlesxu90/leetcode_py
e649c138c62aa2ce6c4ba77d39c7172e96f24811
[ "Apache-2.0" ]
null
null
null
20.937008
116
0.450921
[ [ [ "Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.\n\nExample 1:\n```javascript\nInput: \"Hello\"\nOutput: \"hello\"\n```\nExample 2:\n```javascript\nInput: \"here\"\nOutput: \"here\"\n```\nExample 3:\n```javascript\nInput: \"LOVELY\"\nOutput: \"lovely\"\n```", "_____no_output_____" ] ], [ [ "class Solution(object):\n def toLowerCase(self, str):\n \"\"\"\n type: str, str\n rtype: str\n \"\"\"\n return str.lower()", "_____no_output_____" ], [ "if __name__ == '__main__':\n sol = Solution()\n print(sol.toLowerCase(\"Hello\"))\n print(sol.toLowerCase(\"here\"))\n print(sol.toLowerCase(\"LOVELY\"))", "hello\nhere\nlovely\n" ], [ "\n# Time: O(n)\n# Space: O(1)\n\n# Implement function ToLowerCase() that has a string parameter str,\n# and returns the same string in lowercase.\n\nclass Solution(object):\n def toLowerCase(self, str):\n \"\"\"\n :type str: str\n :rtype: str\n \"\"\"\n return \"\".join(\n [chr(ord('a')+ord(c)-ord('A')) \n if 'A' <= c <= 'Z' else c for c in str]\n )", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ] ]
d075c06e807badb2968ef52ca6bbda0192175c3e
5,594
ipynb
Jupyter Notebook
notebooks/introduction_dataset.ipynb
siyunb/Nipype_tutorial
ed7470b6c3c1ec18ec225ad5765e15e9951b793b
[ "BSD-3-Clause" ]
93
2016-09-09T18:39:42.000Z
2022-03-26T14:49:53.000Z
notebooks/introduction_dataset.ipynb
siyunb/Nipype_tutorial
ed7470b6c3c1ec18ec225ad5765e15e9951b793b
[ "BSD-3-Clause" ]
143
2017-03-04T13:26:03.000Z
2021-08-20T16:44:24.000Z
notebooks/introduction_dataset.ipynb
siyunb/Nipype_tutorial
ed7470b6c3c1ec18ec225ad5765e15e9951b793b
[ "BSD-3-Clause" ]
73
2016-11-14T15:21:28.000Z
2022-02-24T22:57:35.000Z
34.9625
533
0.632106
[ [ [ "<p></p>\n<p style=\"text-align:center\"><font size=\"20\">BRAIN IMAGING</font></p>\n<p style=\"text-align:center\"><font size=\"20\">DATA STRUCTURE</font></p>", "_____no_output_____" ], [ "The dataset for this tutorial is structured according to the [Brain Imaging Data Structure (BIDS)](http://bids.neuroimaging.io/). BIDS is a simple and intuitive way to organize and describe your neuroimaging and behavioral data. Neuroimaging experiments result in complicated data that can be arranged in many different ways. So far there is no consensus on how to organize and share data obtained in neuroimaging experiments. BIDS tackles this problem by suggesting a new standard for the arrangement of neuroimaging datasets.", "_____no_output_____" ], [ "The idea of BIDS is that the file and folder names follow a strict set of rules:\n\n![](../static/images/bids.png)\n", "_____no_output_____" ], [ "Using the same structure for all of your studies will allow you to easily reuse all of your scripts between studies. But additionally, it also has the advantage that sharing code with and using scripts from other researchers will be much easier.", "_____no_output_____" ], [ "# Tutorial Dataset\n\nFor this tutorial, we will be using a subset of the [fMRI dataset (ds000114)](https://openfmri.org/dataset/ds000114/) publicly available on [openfmri.org](https://openfmri.org). **If you're using the suggested Docker image you probably have all data needed to run the tutorial within the Docker container.**\nIf you want to have data locally you can use [Datalad](http://datalad.org/) to download a subset of the dataset, via the [datalad repository](http://datasets.datalad.org/?dir=/workshops/nih-2017/ds000114). In order to install dataset with all subrepositories you can run:", "_____no_output_____" ] ], [ [ "%%bash\ncd /data\ndatalad install -r ///workshops/nih-2017/ds000114", "_____no_output_____" ] ], [ [ "In order to download data, you can use ``datalad get foldername`` command, to download all files in the folder ``foldername``. For this tutorial we only want to download part of the dataset, i.e. the anatomical and the functional `fingerfootlips` images:", "_____no_output_____" ] ], [ [ "%%bash\ncd /data/ds000114\ndatalad get -J 4 derivatives/fmriprep/sub-*/anat/*preproc.nii.gz \\\n sub-01/ses-test/anat \\\n sub-*/ses-test/func/*fingerfootlips*", "_____no_output_____" ] ], [ [ "So let's have a look at the tutorial dataset.", "_____no_output_____" ] ], [ [ "!tree -L 4 /data/ds000114/", "_____no_output_____" ] ], [ [ "As you can, for every subject we have one anatomical T1w image, five functional images, and one diffusion weighted image.\n\n**Note**: If you used `datalad` or `git annex` to get the dataset, you can see symlinks for the image files.", "_____no_output_____" ], [ "# Behavioral Task\n\nSubject from the ds000114 dataset did five behavioral tasks. In our dataset two of them are included. \n\nThe **motor task** consisted of ***finger tapping***, ***foot twitching*** and ***lip pouching*** interleaved with fixation at a cross.\n\nThe **landmark task** was designed to mimic the ***line bisection task*** used in neurological practice to diagnose spatial hemineglect. Two conditions were contrasted, specifically judging if a horizontal line had been bisected exactly in the middle, versus judging if a horizontal line was bisected at all. More about the dataset and studies you can find [here](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3641991/).\n\nTo each of the functional images above, we therefore also have a tab-separated values file (``tva``), containing information such as stimuli onset, duration, type, etc. So let's have a look at one of them:", "_____no_output_____" ] ], [ [ "%%bash\ncd /data/ds000114\ndatalad get sub-01/ses-test/func/sub-01_ses-test_task-linebisection_events.tsv", "_____no_output_____" ], [ "!cat /data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-linebisection_events.tsv", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
d075c53c2ae3bd4c376c09c7fb3b428d5ef74e02
25,186
ipynb
Jupyter Notebook
L14/2-resnet-example.ipynb
sum-coderepo/stat453-deep-learning-ss21
5930e569a674b4f056b2baef9cd16898cbe965a8
[ "MIT" ]
175
2021-01-28T03:46:43.000Z
2022-03-29T14:22:14.000Z
L14/2-resnet-example.ipynb
sum-coderepo/stat453-deep-learning-ss21
5930e569a674b4f056b2baef9cd16898cbe965a8
[ "MIT" ]
3
2021-04-25T16:06:50.000Z
2021-12-27T17:31:19.000Z
L14/2-resnet-example.ipynb
sum-coderepo/stat453-deep-learning-ss21
5930e569a674b4f056b2baef9cd16898cbe965a8
[ "MIT" ]
83
2021-02-02T23:39:21.000Z
2022-03-30T02:16:26.000Z
35.928673
272
0.486064
[ [ [ "STAT 453: Deep Learning (Spring 2021) \nInstructor: Sebastian Raschka ([email protected]) \n\nCourse website: http://pages.stat.wisc.edu/~sraschka/teaching/stat453-ss2021/ \nGitHub repository: https://github.com/rasbt/stat453-deep-learning-ss21\n\n---", "_____no_output_____" ] ], [ [ "%load_ext watermark\n%watermark -a 'Sebastian Raschka' -v -p torch", "Author: Sebastian Raschka\n\nPython implementation: CPython\nPython version : 3.9.2\nIPython version : 7.21.0\n\ntorch: 1.9.0a0+d819a21\n\n" ] ], [ [ "- Runs on CPU or GPU (if available)", "_____no_output_____" ], [ "# A Convolutional ResNet and Residual Blocks", "_____no_output_____" ], [ "Please note that this example does not implement a really deep ResNet as described in literature but rather illustrates how the residual blocks described in He et al. [1] can be implemented in PyTorch.\n\n- [1] He, Kaiming, et al. \"Deep residual learning for image recognition.\" *Proceedings of the IEEE conference on computer vision and pattern recognition*. 2016.", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import time\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom torchvision import transforms", "_____no_output_____" ] ], [ [ "## Settings and Dataset", "_____no_output_____" ] ], [ [ "##########################\n### SETTINGS\n##########################\n\n# Device\ndevice = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n\n# Hyperparameters\nrandom_seed = 123\nlearning_rate = 0.01\nnum_epochs = 10\nbatch_size = 128\n\n# Architecture\nnum_classes = 10\n\n\n##########################\n### MNIST DATASET\n##########################\n\n# Note transforms.ToTensor() scales input images\n# to 0-1 range\ntrain_dataset = datasets.MNIST(root='data', \n train=True, \n transform=transforms.ToTensor(),\n download=True)\n\ntest_dataset = datasets.MNIST(root='data', \n train=False, \n transform=transforms.ToTensor())\n\n\ntrain_loader = DataLoader(dataset=train_dataset, \n batch_size=batch_size, \n shuffle=True)\n\ntest_loader = DataLoader(dataset=test_dataset, \n batch_size=batch_size, \n shuffle=False)\n\n# Checking the dataset\nfor images, labels in train_loader: \n print('Image batch dimensions:', images.shape)\n print('Image label dimensions:', labels.shape)\n break", "Image batch dimensions: torch.Size([128, 1, 28, 28])\nImage label dimensions: torch.Size([128])\n" ] ], [ [ "## ResNet with identity blocks", "_____no_output_____" ], [ "The following code implements the residual blocks with skip connections such that the input passed via the shortcut matches the dimensions of the main path's output, which allows the network to learn identity functions. Such a residual block is illustrated below:\n\n![](./2-resnet-ex/resnet-ex-1-1.png)", "_____no_output_____" ] ], [ [ "##########################\n### MODEL\n##########################\n\n\nclass ConvNet(torch.nn.Module):\n\n def __init__(self, num_classes):\n super(ConvNet, self).__init__()\n \n #########################\n ### 1st residual block\n #########################\n \n self.block_1 = torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=1,\n out_channels=4,\n kernel_size=(1, 1),\n stride=(1, 1),\n padding=0),\n torch.nn.BatchNorm2d(4),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv2d(in_channels=4,\n out_channels=1,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n torch.nn.BatchNorm2d(1)\n )\n \n self.block_2 = torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=1,\n out_channels=4,\n kernel_size=(1, 1),\n stride=(1, 1),\n padding=0),\n torch.nn.BatchNorm2d(4),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv2d(in_channels=4,\n out_channels=1,\n kernel_size=(3, 3),\n stride=(1, 1),\n padding=1),\n torch.nn.BatchNorm2d(1)\n )\n\n #########################\n ### Fully connected\n ######################### \n self.linear_1 = torch.nn.Linear(1*28*28, num_classes)\n\n \n def forward(self, x):\n \n #########################\n ### 1st residual block\n #########################\n shortcut = x\n x = self.block_1(x)\n x = torch.nn.functional.relu(x + shortcut)\n \n #########################\n ### 2nd residual block\n #########################\n shortcut = x\n x = self.block_2(x)\n x = torch.nn.functional.relu(x + shortcut)\n \n #########################\n ### Fully connected\n #########################\n logits = self.linear_1(x.view(-1, 1*28*28))\n return logits\n\n \ntorch.manual_seed(random_seed)\nmodel = ConvNet(num_classes=num_classes)\nmodel = model.to(device)\n \noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) ", "_____no_output_____" ] ], [ [ "### Training", "_____no_output_____" ] ], [ [ "def compute_accuracy(model, data_loader):\n correct_pred, num_examples = 0, 0\n for i, (features, targets) in enumerate(data_loader): \n features = features.to(device)\n targets = targets.to(device)\n logits = model(features)\n _, predicted_labels = torch.max(logits, 1)\n num_examples += targets.size(0)\n correct_pred += (predicted_labels == targets).sum()\n return correct_pred.float()/num_examples * 100\n\n\nstart_time = time.time()\nfor epoch in range(num_epochs):\n model = model.train()\n for batch_idx, (features, targets) in enumerate(train_loader):\n \n features = features.to(device)\n targets = targets.to(device)\n \n ### FORWARD AND BACK PROP\n logits = model(features)\n cost = torch.nn.functional.cross_entropy(logits, targets)\n optimizer.zero_grad()\n \n cost.backward()\n \n ### UPDATE MODEL PARAMETERS\n optimizer.step()\n \n ### LOGGING\n if not batch_idx % 250:\n print ('Epoch: %03d/%03d | Batch %03d/%03d | Cost: %.4f' \n %(epoch+1, num_epochs, batch_idx, \n len(train_loader), cost))\n\n model = model.eval() # eval mode to prevent upd. batchnorm params during inference\n with torch.set_grad_enabled(False): # save memory during inference\n print('Epoch: %03d/%03d training accuracy: %.2f%%' % (\n epoch+1, num_epochs, \n compute_accuracy(model, train_loader)))\n\n print('Time elapsed: %.2f min' % ((time.time() - start_time)/60))\n \nprint('Total Training Time: %.2f min' % ((time.time() - start_time)/60))", "Epoch: 001/010 | Batch 000/469 | Cost: 2.6938\nEpoch: 001/010 | Batch 250/469 | Cost: 0.3444\nEpoch: 001/010 training accuracy: 91.21%\nTime elapsed: 0.29 min\nEpoch: 002/010 | Batch 000/469 | Cost: 0.4317\nEpoch: 002/010 | Batch 250/469 | Cost: 0.4750\nEpoch: 002/010 training accuracy: 92.69%\nTime elapsed: 0.57 min\nEpoch: 003/010 | Batch 000/469 | Cost: 0.2430\nEpoch: 003/010 | Batch 250/469 | Cost: 0.2722\nEpoch: 003/010 training accuracy: 92.56%\nTime elapsed: 0.86 min\nEpoch: 004/010 | Batch 000/469 | Cost: 0.2547\nEpoch: 004/010 | Batch 250/469 | Cost: 0.2330\nEpoch: 004/010 training accuracy: 92.79%\nTime elapsed: 1.15 min\nEpoch: 005/010 | Batch 000/469 | Cost: 0.0948\nEpoch: 005/010 | Batch 250/469 | Cost: 0.2342\nEpoch: 005/010 training accuracy: 93.24%\nTime elapsed: 1.43 min\nEpoch: 006/010 | Batch 000/469 | Cost: 0.2508\nEpoch: 006/010 | Batch 250/469 | Cost: 0.2552\nEpoch: 006/010 training accuracy: 93.11%\nTime elapsed: 1.72 min\nEpoch: 007/010 | Batch 000/469 | Cost: 0.0941\nEpoch: 007/010 | Batch 250/469 | Cost: 0.3898\nEpoch: 007/010 training accuracy: 93.14%\nTime elapsed: 2.00 min\nEpoch: 008/010 | Batch 000/469 | Cost: 0.2865\nEpoch: 008/010 | Batch 250/469 | Cost: 0.1691\nEpoch: 008/010 training accuracy: 93.73%\nTime elapsed: 2.29 min\nEpoch: 009/010 | Batch 000/469 | Cost: 0.3685\nEpoch: 009/010 | Batch 250/469 | Cost: 0.1544\nEpoch: 009/010 training accuracy: 92.88%\nTime elapsed: 2.58 min\nEpoch: 010/010 | Batch 000/469 | Cost: 0.3586\nEpoch: 010/010 | Batch 250/469 | Cost: 0.4787\nEpoch: 010/010 training accuracy: 93.65%\nTime elapsed: 2.87 min\nTotal Training Time: 2.87 min\n" ], [ "print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader)))", "Test accuracy: 92.16%\n" ] ], [ [ "## ResNet with convolutional blocks for resizing", "_____no_output_____" ], [ "The following code implements the residual blocks with skip connections such that the input passed via the shortcut matches is resized to dimensions of the main path's output. Such a residual block is illustrated below:\n\n![](./2-resnet-ex/resnet-ex-1-2.png)", "_____no_output_____" ] ], [ [ "class ResidualBlock(torch.nn.Module):\n \"\"\" Helper Class\"\"\"\n\n def __init__(self, channels):\n \n super(ResidualBlock, self).__init__()\n \n self.block = torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=channels[0],\n out_channels=channels[1],\n kernel_size=(3, 3),\n stride=(2, 2),\n padding=1),\n torch.nn.BatchNorm2d(channels[1]),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv2d(in_channels=channels[1],\n out_channels=channels[2],\n kernel_size=(1, 1),\n stride=(1, 1),\n padding=0), \n torch.nn.BatchNorm2d(channels[2])\n )\n\n self.shortcut = torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=channels[0],\n out_channels=channels[2],\n kernel_size=(1, 1),\n stride=(2, 2),\n padding=0),\n torch.nn.BatchNorm2d(channels[2])\n )\n \n def forward(self, x):\n shortcut = x\n \n block = self.block(x)\n shortcut = self.shortcut(x) \n x = torch.nn.functional.relu(block+shortcut)\n\n return x", "_____no_output_____" ], [ "##########################\n### MODEL\n##########################\n\n\n\nclass ConvNet(torch.nn.Module):\n\n def __init__(self, num_classes):\n super(ConvNet, self).__init__()\n \n self.residual_block_1 = ResidualBlock(channels=[1, 4, 8])\n self.residual_block_2 = ResidualBlock(channels=[8, 16, 32])\n \n self.linear_1 = torch.nn.Linear(7*7*32, num_classes)\n\n \n def forward(self, x):\n\n out = self.residual_block_1(x)\n out = self.residual_block_2(out)\n \n logits = self.linear_1(out.view(-1, 7*7*32))\n return logits\n\n \ntorch.manual_seed(random_seed)\nmodel = ConvNet(num_classes=num_classes)\n\nmodel.to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) ", "_____no_output_____" ] ], [ [ "### Training", "_____no_output_____" ] ], [ [ "for epoch in range(num_epochs):\n model = model.train()\n for batch_idx, (features, targets) in enumerate(train_loader):\n \n features = features.to(device)\n targets = targets.to(device)\n \n ### FORWARD AND BACK PROP\n logits = model(features)\n cost = torch.nn.functional.cross_entropy(logits, targets)\n optimizer.zero_grad()\n \n cost.backward()\n \n ### UPDATE MODEL PARAMETERS\n optimizer.step()\n \n ### LOGGING\n if not batch_idx % 50:\n print ('Epoch: %03d/%03d | Batch %03d/%03d | Cost: %.4f' \n %(epoch+1, num_epochs, batch_idx, \n len(train_dataset)//batch_size, cost))\n\n model = model.eval() # eval mode to prevent upd. batchnorm params during inference\n with torch.set_grad_enabled(False): # save memory during inference\n print('Epoch: %03d/%03d training accuracy: %.2f%%' % (\n epoch+1, num_epochs, \n compute_accuracy(model, train_loader)))", "Epoch: 001/010 | Batch 000/468 | Cost: 2.4548\nEpoch: 001/010 | Batch 050/468 | Cost: 0.2955\nEpoch: 001/010 | Batch 100/468 | Cost: 0.1596\nEpoch: 001/010 | Batch 150/468 | Cost: 0.1105\nEpoch: 001/010 | Batch 200/468 | Cost: 0.1173\nEpoch: 001/010 | Batch 250/468 | Cost: 0.1747\nEpoch: 001/010 | Batch 300/468 | Cost: 0.0986\nEpoch: 001/010 | Batch 350/468 | Cost: 0.1371\nEpoch: 001/010 | Batch 400/468 | Cost: 0.1583\nEpoch: 001/010 | Batch 450/468 | Cost: 0.1172\nEpoch: 001/010 training accuracy: 97.29%\nEpoch: 002/010 | Batch 000/468 | Cost: 0.1137\nEpoch: 002/010 | Batch 050/468 | Cost: 0.0812\nEpoch: 002/010 | Batch 100/468 | Cost: 0.0268\nEpoch: 002/010 | Batch 150/468 | Cost: 0.0891\nEpoch: 002/010 | Batch 200/468 | Cost: 0.0918\nEpoch: 002/010 | Batch 250/468 | Cost: 0.0894\nEpoch: 002/010 | Batch 300/468 | Cost: 0.0487\nEpoch: 002/010 | Batch 350/468 | Cost: 0.0395\nEpoch: 002/010 | Batch 400/468 | Cost: 0.0729\nEpoch: 002/010 | Batch 450/468 | Cost: 0.0465\nEpoch: 002/010 training accuracy: 97.92%\nEpoch: 003/010 | Batch 000/468 | Cost: 0.0624\nEpoch: 003/010 | Batch 050/468 | Cost: 0.0483\nEpoch: 003/010 | Batch 100/468 | Cost: 0.0574\nEpoch: 003/010 | Batch 150/468 | Cost: 0.0765\nEpoch: 003/010 | Batch 200/468 | Cost: 0.1354\nEpoch: 003/010 | Batch 250/468 | Cost: 0.1235\nEpoch: 003/010 | Batch 300/468 | Cost: 0.1017\nEpoch: 003/010 | Batch 350/468 | Cost: 0.0681\nEpoch: 003/010 | Batch 400/468 | Cost: 0.0438\nEpoch: 003/010 | Batch 450/468 | Cost: 0.1454\nEpoch: 003/010 training accuracy: 98.13%\nEpoch: 004/010 | Batch 000/468 | Cost: 0.0770\nEpoch: 004/010 | Batch 050/468 | Cost: 0.0204\nEpoch: 004/010 | Batch 100/468 | Cost: 0.0570\nEpoch: 004/010 | Batch 150/468 | Cost: 0.0614\nEpoch: 004/010 | Batch 200/468 | Cost: 0.0572\nEpoch: 004/010 | Batch 250/468 | Cost: 0.0353\nEpoch: 004/010 | Batch 300/468 | Cost: 0.0270\nEpoch: 004/010 | Batch 350/468 | Cost: 0.0930\nEpoch: 004/010 | Batch 400/468 | Cost: 0.0832\nEpoch: 004/010 | Batch 450/468 | Cost: 0.0512\nEpoch: 004/010 training accuracy: 98.57%\nEpoch: 005/010 | Batch 000/468 | Cost: 0.0429\nEpoch: 005/010 | Batch 050/468 | Cost: 0.0750\nEpoch: 005/010 | Batch 100/468 | Cost: 0.0065\nEpoch: 005/010 | Batch 150/468 | Cost: 0.0870\nEpoch: 005/010 | Batch 200/468 | Cost: 0.0320\nEpoch: 005/010 | Batch 250/468 | Cost: 0.0463\nEpoch: 005/010 | Batch 300/468 | Cost: 0.0611\nEpoch: 005/010 | Batch 350/468 | Cost: 0.0231\nEpoch: 005/010 | Batch 400/468 | Cost: 0.0404\nEpoch: 005/010 | Batch 450/468 | Cost: 0.0195\nEpoch: 005/010 training accuracy: 98.85%\nEpoch: 006/010 | Batch 000/468 | Cost: 0.0530\nEpoch: 006/010 | Batch 050/468 | Cost: 0.0614\nEpoch: 006/010 | Batch 100/468 | Cost: 0.0070\nEpoch: 006/010 | Batch 150/468 | Cost: 0.0147\nEpoch: 006/010 | Batch 200/468 | Cost: 0.1086\nEpoch: 006/010 | Batch 250/468 | Cost: 0.0107\nEpoch: 006/010 | Batch 300/468 | Cost: 0.0102\nEpoch: 006/010 | Batch 350/468 | Cost: 0.0190\nEpoch: 006/010 | Batch 400/468 | Cost: 0.1027\nEpoch: 006/010 | Batch 450/468 | Cost: 0.0590\nEpoch: 006/010 training accuracy: 99.03%\nEpoch: 007/010 | Batch 000/468 | Cost: 0.0061\nEpoch: 007/010 | Batch 050/468 | Cost: 0.0112\nEpoch: 007/010 | Batch 100/468 | Cost: 0.0361\nEpoch: 007/010 | Batch 150/468 | Cost: 0.0968\nEpoch: 007/010 | Batch 200/468 | Cost: 0.0246\nEpoch: 007/010 | Batch 250/468 | Cost: 0.0144\nEpoch: 007/010 | Batch 300/468 | Cost: 0.0238\nEpoch: 007/010 | Batch 350/468 | Cost: 0.0086\nEpoch: 007/010 | Batch 400/468 | Cost: 0.0220\nEpoch: 007/010 | Batch 450/468 | Cost: 0.0672\nEpoch: 007/010 training accuracy: 99.04%\nEpoch: 008/010 | Batch 000/468 | Cost: 0.0551\nEpoch: 008/010 | Batch 050/468 | Cost: 0.0156\nEpoch: 008/010 | Batch 100/468 | Cost: 0.0025\nEpoch: 008/010 | Batch 150/468 | Cost: 0.0116\nEpoch: 008/010 | Batch 200/468 | Cost: 0.0093\nEpoch: 008/010 | Batch 250/468 | Cost: 0.0275\nEpoch: 008/010 | Batch 300/468 | Cost: 0.0581\nEpoch: 008/010 | Batch 350/468 | Cost: 0.0211\nEpoch: 008/010 | Batch 400/468 | Cost: 0.0224\nEpoch: 008/010 | Batch 450/468 | Cost: 0.0520\nEpoch: 008/010 training accuracy: 99.19%\nEpoch: 009/010 | Batch 000/468 | Cost: 0.0218\nEpoch: 009/010 | Batch 050/468 | Cost: 0.0742\nEpoch: 009/010 | Batch 100/468 | Cost: 0.0200\nEpoch: 009/010 | Batch 150/468 | Cost: 0.1219\nEpoch: 009/010 | Batch 200/468 | Cost: 0.0438\nEpoch: 009/010 | Batch 250/468 | Cost: 0.0195\nEpoch: 009/010 | Batch 300/468 | Cost: 0.0356\nEpoch: 009/010 | Batch 350/468 | Cost: 0.0959\nEpoch: 009/010 | Batch 400/468 | Cost: 0.0272\nEpoch: 009/010 | Batch 450/468 | Cost: 0.1140\nEpoch: 009/010 training accuracy: 99.09%\nEpoch: 010/010 | Batch 000/468 | Cost: 0.0308\nEpoch: 010/010 | Batch 050/468 | Cost: 0.0333\nEpoch: 010/010 | Batch 100/468 | Cost: 0.0286\nEpoch: 010/010 | Batch 150/468 | Cost: 0.0202\nEpoch: 010/010 | Batch 200/468 | Cost: 0.0193\nEpoch: 010/010 | Batch 250/468 | Cost: 0.0057\nEpoch: 010/010 | Batch 300/468 | Cost: 0.0331\nEpoch: 010/010 | Batch 350/468 | Cost: 0.0200\nEpoch: 010/010 | Batch 400/468 | Cost: 0.0588\nEpoch: 010/010 | Batch 450/468 | Cost: 0.0202\nEpoch: 010/010 training accuracy: 99.07%\n" ], [ "print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader)))", "Test accuracy: 98.13%\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d075c70295fc8e6064fa5644a49de99ef303602e
171,120
ipynb
Jupyter Notebook
notebooks/HiddenMarkovModel.ipynb
kad99kev/HiddenMarkovModel
b0deec188b515cfffd4f9295a91962951da20ec6
[ "MIT" ]
1
2021-04-01T05:24:29.000Z
2021-04-01T05:24:29.000Z
notebooks/HiddenMarkovModel.ipynb
kad99kev/HiddenMarkovModel
b0deec188b515cfffd4f9295a91962951da20ec6
[ "MIT" ]
null
null
null
notebooks/HiddenMarkovModel.ipynb
kad99kev/HiddenMarkovModel
b0deec188b515cfffd4f9295a91962951da20ec6
[ "MIT" ]
null
null
null
334.21875
127,524
0.917631
[ [ [ "# Hidden Markov Model\n\n## What is a Hidden Markov Model?\nA Hidden Markov Model (HMM) is a statistical Markov model in with the system being modeled is assumed to be a Markov process with **hidden** states.\n\nAn HMM allows us to talk about both observed events (like words that we see in the input) and hidden events (like Part-Of-Speech tags).\n\nAn HMM is specified by the following components:\n![image.png](attachment:image.png)\n\n**State Transition Probabilities** are the probabilities of moving from state i to state j.\n![image-2.png](attachment:image-2.png)\n\n**Observation Probability Matrix** also called emission probabilities, express the probability of an observation Ot being generated from a state i.\n![image-4.png](attachment:image-4.png)\n\n**Initial State Distribution** $\\pi$<sub>i</sub> is the probability that the Markov chain will start in state i. Some state j with $\\pi$<sub>j</sub>=0 means that they cannot be initial states.\n\nHence, the entire Hidden Markov Model can be described as,\n![image-3.png](attachment:image-3.png)", "_____no_output_____" ] ], [ [ "# Inorder to get the notebooks running in current directory\nimport os, sys, inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0, parentdir) \n\nimport hmm", "_____no_output_____" ] ], [ [ "Let us take a simple example with two hidden states and two observable states.\n\nThe **Hidden states** will be **Rainy** and **Sunny**.\n\nThe **Observable states** will be **Sad** and **Happy**.\n\nThe transition and emission matrices are given below.\n\nThe initial probabilities are obtained by computing the stationary distribution of the transition matrix.\nThis means that for a given matrix A, the stationary distribution would be given as,\n$\\pi$A = $\\pi$", "_____no_output_____" ] ], [ [ "# Hidden\nhidden_states = [\"Rainy\", \"Sunny\"]\ntransition_matrix = [[0.5, 0.5], [0.3, 0.7]]", "_____no_output_____" ], [ "# Observable\nobservable_states = [\"Sad\", \"Happy\"]\nemission_matrix = [[0.8, 0.2], [0.4, 0.6]]", "_____no_output_____" ], [ "# Inputs\ninput_seq = [0, 0, 1]\n\nmodel = hmm.HiddenMarkovModel(\n observable_states, hidden_states, transition_matrix, emission_matrix\n)", "_____no_output_____" ], [ "model.print_model_info()\nmodel.visualize_model(output_dir=\"simple_demo\", notebook=True)", "**************************************************\nObservable States: ['Sad', 'Happy']\nEmission Matrix:\n Sad Happy\nRainy 0.8 0.2\nSunny 0.4 0.6\nHidden States: ['Rainy', 'Sunny']\nTransition Matrix:\n Rainy Sunny\nRainy 0.5 0.5\nSunny 0.3 0.7\nInitial Probabilities: [0.375 0.625]\n" ] ], [ [ "Here the <span style=\"color: blue;\">blue</span> lines indicate the hidden transitions.\n\nHere the <span style=\"color: red;\">red</span> lines indicate the emission transitions.", "_____no_output_____" ], [ "# Problem 1:\nComputing Likelihood: Given an HMM $\\lambda$ = (A, B) and an observation sequence O, determine the likelihood P(O | $\\lambda$)\n\n## How It Is Calculated?\nFor our example, for the given **observed** sequence - (Sad, Sad, Happy) the probabilities will be calculated as,\n\n<em>\n\nP(Sad, Sad, Happy) = \n\nP(Rainy) * P(Sad | Rainy) * P(Rainy | Rainy) * P(Sad | Rainy) * P(Rainy | Rainy) * P(Happy | Rainy)\n\n+\n\nP(Rainy) * P(Sad | Rainy) * P(Rainy | Rainy) * P(Sad | Rainy) * P(Sunny | Rainy) * P(Happy | Sunny)\n\n+\n\nP(Rainy) * P(Sad | Rainy) * P(Sunny | Rainy) * P(Sad | Sunny) * P(Rainy | Sunny) * P(Happy | Rainy)\n\n+\n\nP(Rainy) * P(Sad | Rainy) * P(Sunny | Rainy) * P(Sad | Sunny) * P(Sunny | Sunny) * P(Happy | Sunny)\n\n+\n\nP(Sunny) * P(Sad | Sunny) * P(Rainy | Sunny) * P(Sad | Rainy) * P(Rainy | Rainy) * P(Happy | Rainy)\n\n+\n\nP(Sunny) * P(Sad | Sunny) * P(Rainy | Sunny) * P(Sad | Rainy) * P(Sunny | Rainy) * P(Happy | Sunny)\n\n+\n\nP(Sunny) * P(Sad | Sunny) * P(Sunny | Sunny) * P(Sad | Sunny) * P(Rainy | Sunny) * P(Happy | Rainy)\n\n+\n\nP(Sunny) * P(Sad | Sunny) * P(Sunny | Sunny) * P(Sad | Sunny) * P(Sunny | Sunny) * P(Happy | Sunny)\n\n</em>\n\n## The Problems With This Method\nThis however, is a naive way of computation. The number of multiplications this way is of the order of 2TN<sup>T</sup>. \n\nwhere T is the length of the observed sequence and N is the number of hidden states.\n\nThis means that the time complexity increases exponentially as the number of hidden states increases.\n\n# Forward Algorithm\nWe are computing *P(Rainy) * P(Sad | Rainy)* and *P(Sunny) * P(Sad | Sunny)* a total of 4 times.\n\nEven parts like\n\n*P(Rainy) * P(Sad | Rainy) * P(Rainy | Rainy) * P(Sad | Rainy)*, \n\n*P(Rainy) * P(Sad | Rainy) * P(Sunny | Rainy) * P(Sad | Sunny)*, \n\n*P(Sunny) * P(Sad | Sunny) * P(Rainy | Sunny) * P(Sad | Rainy)* and \n\n*P(Sunny) * P(Sad | Sunny) * P(Sunny | Sunny) * P(Sad | Sunny)* are repeated.\n\nWe can avoid so many computation by using recurrance relations with the help of **Dynamic Programming**.\n\n![ForwardHMM](../assets/ForwardHMM.png)\n\n\nIn code, it can be written as:\n\n```\nalpha[:, 0] = self.pi * emission_matrix[:, input_seq[0]] # Initialize\n\nfor t in range(1, T):\n for s in range(n_states):\n alpha[s, t] = emission_matrix[s, input_seq[t]] * np.sum(\n alpha[:, t - 1] * transition_matrix[:, s]\n )\n```\n\nThis will lead to the following computations:\n\n![Computation](../assets/Computation.png)", "_____no_output_____" ] ], [ [ "alpha, a_probs = model.forward(input_seq)\nhmm.print_forward_result(alpha, a_probs)", "**************************************************\nAlpha:\n[[0.3 0.18 0.0258]\n [0.25 0.13 0.1086]]\nProbability of sequence: 0.13440000000000002\n" ] ], [ [ "# Backward Algorithm\nThe Backward Algorithm is the time-reversed version of the Forward Algorithm.", "_____no_output_____" ] ], [ [ "beta, b_probs = model.backward(input_seq)\nhmm.print_backward_result(beta, b_probs)", "**************************************************\nBeta:\n[[0.256 0.4 1. ]\n [0.2304 0.48 1. ]]\nProbability of sequence: 0.13440000000000002\n" ] ], [ [ "# Problem 2: \nGiven an observation sequence O and an HMM λ = (A,B), discover the best hidden state sequence Q.\n\n## Viterbi Algorithm\nThe Viterbi Algorithm increments over each time step, finding the maximum probability of any path that gets to state i at time t, that also has the correct observations for the sequence up to time t.\n\nThe algorithm also keeps track of the state with the highest probability at each stage. At the end of the sequence, the algorith will iterate backwards selecting the state that won which creates the most likely path or sequence of hidden states that led to the sequence of observations.\n\nIn code, it is written as:\n```\ndelta[:, 0] = self.pi * emission_matrix[:, input_seq[0]] # Initialize\nfor t in range(1, T):\n for s in range(n_states):\n delta[s, t] = (\n np.max(delta[:, t - 1] * transition_matrix[:, s])\n * emission_matrix[s, input_seq[t]]\n )\n phi[s, t] = np.argmax(delta[:, t - 1] * transition_matrix[:, s])\n```\n\nThe Viterbi Algorithm is identical to the forward algorithm except that it takes the **max** over the\nprevious path probabilities whereas the forward algorithm takes the **sum**.\n\nThe code for the Backtrace is written as:\n```\npath[T - 1] = np.argmax(delta[:, T - 1]) # Initialize\nfor t in range(T - 2, -1, -1):\n path[t] = phi[path[t + 1], [t + 1]]\n```", "_____no_output_____" ] ], [ [ "path, delta, phi = model.viterbi(input_seq)\nhmm.print_viterbi_result(input_seq, observable_states, hidden_states, path, delta, phi)", "**************************************************\nStarting Forward Walk\nState=0 : Sequence=1 | phi[0, 1]=0.0\nState=1 : Sequence=1 | phi[1, 1]=1.0\nState=0 : Sequence=2 | phi[0, 2]=0.0\nState=1 : Sequence=2 | phi[1, 2]=0.0\n**************************************************\nStart Backtrace\nPath[1]=0\nPath[0]=0\n**************************************************\nViterbi Result\nDelta:\n[[0.3 0.12 0.012]\n [0.25 0.07 0.036]]\nPhi:\n[[0. 0. 0.]\n [0. 1. 0.]]\nResult:\n Observation BestPath\n0 Sad Rainy\n1 Sad Rainy\n2 Happy Sunny\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d075c78a88459c0657404a4d89bbdd55a67818ed
60,630
ipynb
Jupyter Notebook
Errata/Chapter 3.ipynb
karshtharyani/DeepReinforcementLearningInAction
9dc40a43b43f05daf9aecb7e3ec7592cf38720e5
[ "MIT" ]
474
2018-06-17T18:22:58.000Z
2022-03-30T22:39:04.000Z
Errata/Chapter 3.ipynb
mongoooo/DeepReinforcementLearningInAction
e02e932eb6cb6dabf563614288554b9cf7ad048f
[ "MIT" ]
28
2018-08-05T03:54:14.000Z
2022-01-02T14:03:19.000Z
Errata/Chapter 3.ipynb
mongoooo/DeepReinforcementLearningInAction
e02e932eb6cb6dabf563614288554b9cf7ad048f
[ "MIT" ]
215
2018-06-18T14:44:00.000Z
2022-03-31T08:39:51.000Z
62.440783
14,484
0.748046
[ [ [ "# Deep Reinforcement Learning in Action\n### by Alex Zai and Brandon Brown\n\n#### Chapter 3", "_____no_output_____" ], [ "##### Listing 3.1", "_____no_output_____" ] ], [ [ "from Gridworld import Gridworld\ngame = Gridworld(size=4, mode='static')", "_____no_output_____" ], [ "import sys", "_____no_output_____" ], [ "game.display()", "_____no_output_____" ], [ "game.makeMove('d')\ngame.makeMove('d')\ngame.makeMove('d')\ngame.display()", "_____no_output_____" ], [ "game.reward()", "_____no_output_____" ], [ "game.board.render_np()", "_____no_output_____" ], [ "game.board.render_np().shape", "_____no_output_____" ] ], [ [ "##### Listing 3.2", "_____no_output_____" ] ], [ [ "import numpy as np\nimport torch\nfrom Gridworld import Gridworld\nimport random\nfrom matplotlib import pylab as plt\n \nl1 = 64\nl2 = 150\nl3 = 100\nl4 = 4\n \nmodel = torch.nn.Sequential(\n torch.nn.Linear(l1, l2),\n torch.nn.ReLU(),\n torch.nn.Linear(l2, l3),\n torch.nn.ReLU(),\n torch.nn.Linear(l3,l4)\n)\nloss_fn = torch.nn.MSELoss()\nlearning_rate = 1e-3\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n \ngamma = 0.9\nepsilon = 1.0", "_____no_output_____" ], [ "action_set = {\n 0: 'u',\n 1: 'd',\n 2: 'l',\n 3: 'r',\n}", "_____no_output_____" ] ], [ [ "##### Listing 3.3", "_____no_output_____" ] ], [ [ "epochs = 1000\nlosses = []\nfor i in range(epochs):\n game = Gridworld(size=4, mode='static')\n state_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/10.0\n state1 = torch.from_numpy(state_).float()\n status = 1\n while(status == 1):\n qval = model(state1)\n qval_ = qval.data.numpy()\n if (random.random() < epsilon):\n action_ = np.random.randint(0,4)\n else:\n action_ = np.argmax(qval_)\n \n action = action_set[action_]\n game.makeMove(action)\n state2_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/10.0\n state2 = torch.from_numpy(state2_).float()\n reward = game.reward() #-1 for lose, +1 for win, 0 otherwise\n with torch.no_grad():\n newQ = model(state2.reshape(1,64))\n maxQ = torch.max(newQ)\n if reward == -1: # if game still in play\n Y = reward + (gamma * maxQ)\n else:\n Y = reward\n Y = torch.Tensor([Y]).detach().squeeze()\n X = qval.squeeze()[action_]\n loss = loss_fn(X, Y)\n optimizer.zero_grad()\n loss.backward()\n losses.append(loss.item())\n optimizer.step()\n state1 = state2\n if reward != -1: #game lost\n status = 0\n if epsilon > 0.1:\n epsilon -= (1/epochs)", "_____no_output_____" ], [ "plt.plot(losses)", "_____no_output_____" ], [ "m = torch.Tensor([2.0])\nm.requires_grad=True\nb = torch.Tensor([1.0])\nb.requires_grad=True\ndef linear_model(x,m,b):\n y = m @ x + b\n return y\ny = linear_model(torch.Tensor([4.]), m,b)", "_____no_output_____" ], [ "y", "_____no_output_____" ], [ "y.grad_fn", "_____no_output_____" ], [ "with torch.no_grad():\n y = linear_model(torch.Tensor([4]),m,b)", "_____no_output_____" ], [ "y", "_____no_output_____" ], [ "y.grad_fn", "_____no_output_____" ], [ "y = linear_model(torch.Tensor([4.]), m,b)\ny.backward()\nm.grad", "_____no_output_____" ], [ "b.grad", "_____no_output_____" ] ], [ [ "##### Listing 3.4", "_____no_output_____" ] ], [ [ "def test_model(model, mode='static', display=True):\n i = 0\n test_game = Gridworld(mode=mode)\n state_ = test_game.board.render_np().reshape(1,64) + np.random.rand(1,64)/10.0\n state = torch.from_numpy(state_).float()\n if display:\n print(\"Initial State:\")\n print(test_game.display())\n status = 1\n while(status == 1):\n qval = model(state)\n qval_ = qval.data.numpy()\n action_ = np.argmax(qval_)\n action = action_set[action_]\n if display:\n print('Move #: %s; Taking action: %s' % (i, action))\n test_game.makeMove(action)\n state_ = test_game.board.render_np().reshape(1,64) + np.random.rand(1,64)/10.0\n state = torch.from_numpy(state_).float()\n if display:\n print(test_game.display())\n reward = test_game.reward()\n if reward != -1: #if game is over\n if reward > 0: #if game won\n status = 2\n if display:\n print(\"Game won! Reward: %s\" % (reward,))\n else: #game is lost\n status = 0\n if display:\n print(\"Game LOST. Reward: %s\" % (reward,))\n i += 1\n if (i > 15):\n if display:\n print(\"Game lost; too many moves.\")\n break\n win = True if status == 2 else False\n return win", "_____no_output_____" ], [ "test_model(model, 'static')", "Initial State:\n[['+' '-' ' ' 'P']\n [' ' 'W' ' ' ' ']\n [' ' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']]\nMove #: 0; Taking action: l\n[['+' '-' 'P' ' ']\n [' ' 'W' ' ' ' ']\n [' ' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']]\nMove #: 1; Taking action: d\n[['+' '-' ' ' ' ']\n [' ' 'W' 'P' ' ']\n [' ' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']]\nMove #: 2; Taking action: d\n[['+' '-' ' ' ' ']\n [' ' 'W' ' ' ' ']\n [' ' ' ' 'P' ' ']\n [' ' ' ' ' ' ' ']]\nMove #: 3; Taking action: l\n[['+' '-' ' ' ' ']\n [' ' 'W' ' ' ' ']\n [' ' 'P' ' ' ' ']\n [' ' ' ' ' ' ' ']]\nMove #: 4; Taking action: l\n[['+' '-' ' ' ' ']\n [' ' 'W' ' ' ' ']\n ['P' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']]\nMove #: 5; Taking action: u\n[['+' '-' ' ' ' ']\n ['P' 'W' ' ' ' ']\n [' ' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']]\nMove #: 6; Taking action: u\n[['+' '-' ' ' ' ']\n [' ' 'W' ' ' ' ']\n [' ' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']]\nGame won! Reward: 10\n" ] ], [ [ "##### Listing 3.5", "_____no_output_____" ] ], [ [ "from collections import deque\nepochs = 5000\nlosses = []\nmem_size = 1000\nbatch_size = 200\nreplay = deque(maxlen=mem_size)\nmax_moves = 50\nh = 0\nfor i in range(epochs):\n game = Gridworld(size=4, mode='random')\n state1_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/100.0\n state1 = torch.from_numpy(state1_).float()\n status = 1\n mov = 0\n while(status == 1): \n mov += 1\n qval = model(state1)\n qval_ = qval.data.numpy()\n if (random.random() < epsilon):\n action_ = np.random.randint(0,4)\n else:\n action_ = np.argmax(qval_)\n \n action = action_set[action_]\n game.makeMove(action)\n state2_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/100.0\n state2 = torch.from_numpy(state2_).float()\n reward = game.reward()\n done = True if reward > 0 else False\n exp = (state1, action_, reward, state2, done)\n replay.append(exp)\n state1 = state2\n \n if len(replay) > batch_size:\n minibatch = random.sample(replay, batch_size)\n state1_batch = torch.cat([s1 for (s1,a,r,s2,d) in minibatch])\n action_batch = torch.Tensor([a for (s1,a,r,s2,d) in minibatch])\n reward_batch = torch.Tensor([r for (s1,a,r,s2,d) in minibatch])\n state2_batch = torch.cat([s2 for (s1,a,r,s2,d) in minibatch])\n done_batch = torch.Tensor([d for (s1,a,r,s2,d) in minibatch])\n \n Q1 = model(state1_batch)\n with torch.no_grad():\n Q2 = model(state2_batch)\n \n Y = reward_batch + gamma * ((1 - done_batch) * torch.max(Q2,dim=1)[0])\n X = \\\n Q1.gather(dim=1,index=action_batch.long().unsqueeze(dim=1)).squeeze()\n loss = loss_fn(X, Y.detach())\n optimizer.zero_grad()\n loss.backward()\n losses.append(loss.item())\n optimizer.step()\n \n if reward != -1 or mov > max_moves:\n status = 0\n mov = 0\nlosses = np.array(losses)", "_____no_output_____" ], [ "plt.plot(losses)", "_____no_output_____" ], [ "test_model(model,mode='random')", "Initial State:\n[['P' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']\n [' ' ' ' ' ' 'W']\n ['-' '+' ' ' ' ']]\nMove #: 0; Taking action: r\n[[' ' 'P' ' ' ' ']\n [' ' ' ' ' ' ' ']\n [' ' ' ' ' ' 'W']\n ['-' '+' ' ' ' ']]\nMove #: 1; Taking action: d\n[[' ' ' ' ' ' ' ']\n [' ' 'P' ' ' ' ']\n [' ' ' ' ' ' 'W']\n ['-' '+' ' ' ' ']]\nMove #: 2; Taking action: d\n[[' ' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']\n [' ' 'P' ' ' 'W']\n ['-' '+' ' ' ' ']]\nMove #: 3; Taking action: d\n[[' ' ' ' ' ' ' ']\n [' ' ' ' ' ' ' ']\n [' ' ' ' ' ' 'W']\n ['-' '+' ' ' ' ']]\nGame won! Reward: 10\n" ] ], [ [ "##### Listing 3.6", "_____no_output_____" ] ], [ [ "max_games = 1000\nwins = 0\nfor i in range(max_games):\n win = test_model(model, mode='random', display=False)\n if win:\n wins += 1\nwin_perc = float(wins) / float(max_games)\nprint(\"Games played: {0}, # of wins: {1}\".format(max_games,wins))\nprint(\"Win percentage: {}\".format(100.0*win_perc))", "Games played: 1000, # of wins: 908\nWin percentage: 90.8\n" ] ], [ [ "##### Listing 3.7", "_____no_output_____" ] ], [ [ "import copy\n \nmodel = torch.nn.Sequential(\n torch.nn.Linear(l1, l2),\n torch.nn.ReLU(),\n torch.nn.Linear(l2, l3),\n torch.nn.ReLU(),\n torch.nn.Linear(l3,l4)\n)\n \nmodel2 = model2 = copy.deepcopy(model)\nmodel2.load_state_dict(model.state_dict())\nsync_freq = 50\n\nloss_fn = torch.nn.MSELoss()\nlearning_rate = 1e-3\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)", "_____no_output_____" ] ], [ [ "##### Listing 3.8", "_____no_output_____" ] ], [ [ "from IPython.display import clear_output", "_____no_output_____" ], [ "from collections import deque\nepochs = 5000\nlosses = []\nmem_size = 1000\nbatch_size = 200\nreplay = deque(maxlen=mem_size)\nmax_moves = 50\nh = 0\nsync_freq = 500\nj=0\nfor i in range(epochs):\n game = Gridworld(size=4, mode='random')\n state1_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/100.0\n state1 = torch.from_numpy(state1_).float()\n status = 1\n mov = 0\n while(status == 1): \n j+=1\n mov += 1\n qval = model(state1)\n qval_ = qval.data.numpy()\n if (random.random() < epsilon):\n action_ = np.random.randint(0,4)\n else:\n action_ = np.argmax(qval_)\n \n action = action_set[action_]\n game.makeMove(action)\n state2_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/100.0\n state2 = torch.from_numpy(state2_).float()\n reward = game.reward()\n done = True if reward > 0 else False\n exp = (state1, action_, reward, state2, done)\n replay.append(exp) \n state1 = state2\n \n if len(replay) > batch_size:\n minibatch = random.sample(replay, batch_size)\n state1_batch = torch.cat([s1 for (s1,a,r,s2,d) in minibatch])\n action_batch = torch.Tensor([a for (s1,a,r,s2,d) in minibatch])\n reward_batch = torch.Tensor([r for (s1,a,r,s2,d) in minibatch])\n state2_batch = torch.cat([s2 for (s1,a,r,s2,d) in minibatch])\n done_batch = torch.Tensor([d for (s1,a,r,s2,d) in minibatch])\n Q1 = model(state1_batch) \n with torch.no_grad():\n Q2 = model2(state2_batch)\n Y = reward_batch + gamma * ((1-done_batch) * \\\n torch.max(Q2,dim=1)[0])\n X = Q1.gather(dim=1,index=action_batch.long() \\\n .unsqueeze(dim=1)).squeeze()\n loss = loss_fn(X, Y.detach())\n print(i, loss.item())\n clear_output(wait=True)\n optimizer.zero_grad()\n loss.backward()\n losses.append(loss.item())\n optimizer.step()\n \n if j % sync_freq == 0:\n model2.load_state_dict(model.state_dict())\n if reward != -1 or mov > max_moves:\n status = 0\n mov = 0\n \nlosses = np.array(losses)", "4999 0.012652655132114887\n" ], [ "plt.plot(losses)", "_____no_output_____" ], [ "test_model(model,mode='random')", "Initial State:\n[[' ' ' ' ' ' ' ']\n [' ' ' ' ' ' 'W']\n ['+' ' ' ' ' ' ']\n ['-' 'P' ' ' ' ']]\nMove #: 0; Taking action: u\n[[' ' ' ' ' ' ' ']\n [' ' ' ' ' ' 'W']\n ['+' 'P' ' ' ' ']\n ['-' ' ' ' ' ' ']]\nMove #: 1; Taking action: l\n[[' ' ' ' ' ' ' ']\n [' ' ' ' ' ' 'W']\n ['+' ' ' ' ' ' ']\n ['-' ' ' ' ' ' ']]\nGame won! Reward: 10\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d075de62fe96958e07e7506aa88d89621a06eebf
79,021
ipynb
Jupyter Notebook
Mantle_Boundaries.ipynb
SHDShim/cider2018_tutorial
e46f2e43bb2f6ef80aa9403b675b446bc0979ecb
[ "Apache-2.0" ]
2
2020-12-07T11:21:46.000Z
2021-08-18T09:14:02.000Z
Mantle_Boundaries.ipynb
SHDShim/cider2018_tutorial
e46f2e43bb2f6ef80aa9403b675b446bc0979ecb
[ "Apache-2.0" ]
null
null
null
Mantle_Boundaries.ipynb
SHDShim/cider2018_tutorial
e46f2e43bb2f6ef80aa9403b675b446bc0979ecb
[ "Apache-2.0" ]
1
2021-08-18T09:14:04.000Z
2021-08-18T09:14:04.000Z
173.291667
63,804
0.883778
[ [ [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'", "_____no_output_____" ] ], [ [ "# 0. General note", "_____no_output_____" ], [ "* This notebook produces figures and calculations presented in [Ye et al. 2017, JGR](https://agupubs.onlinelibrary.wiley.com/doi/abs/10.1002/2016JB013811).\n\n* This notebook demonstrates how to correct pressure scales for the existing phase boundary data.", "_____no_output_____" ], [ "# 1. Global setup", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nfrom uncertainties import unumpy as unp\nimport pytheos as eos", "_____no_output_____" ] ], [ [ "# 2. Pressure calculations for PPv", "_____no_output_____" ], [ "* Data from Tateno2009\n\nT (K) | Au-Tsuchiya | Pt-Holmes | MgO-Speziale\n------|-------------|-----------|--------------\n3500 | 120.4 | 137.7 | 135.6\n2000 | 110.5 | 126.8 | 115.8\n\n* Dorogokupets2007\n\nT (K) | Au | Pt | MgO \n------|-------------|-----------|--------------\n3500 | 119.7 | 135.2 | 129.6\n2000 | 108.9 | 123.2 | 113.2\n\n<b>\n* In conclusion, PPV boundary discrepancy is not likely due to pressure scale problem.\n</b>", "_____no_output_____" ] ], [ [ "t_ppv = np.asarray([3500., 2000.])", "_____no_output_____" ], [ "Au_T = eos.gold.Tsuchiya2003()\nAu_D = eos.gold.Dorogokupets2007()\n\nv = np.asarray([51.58,51.7])\np_Au_T_ppv = Au_T.cal_p(v, t_ppv)\np_Au_D_ppv = Au_D.cal_p(v, t_ppv)\nprint(p_Au_T_ppv, p_Au_D_ppv)\nprint('slopes: ', (p_Au_T_ppv[0]-p_Au_T_ppv[1])/(t_ppv[0]-t_ppv[1]),\\\n (p_Au_D_ppv[0]-p_Au_D_ppv[1])/(t_ppv[0]-t_ppv[1]) )", "[120.4394917114189+/-0.009819156315686408\n 110.4900924018267+/-0.009709312775041275] [119.7228389957068+/-0.009397458639736574\n 108.86638382366034+/-0.009303587653953853]\nslopes: 0.00663293+/-0.00000019 0.00723764+/-0.00000010\n" ], [ "Pt_H = eos.platinum.Holmes1989()\nPt_D = eos.platinum.Dorogokupets2007()\n\nv = np.asarray([48.06, 48.09])\np_Pt_H_ppv = Pt_H.cal_p(v, t_ppv)\np_Pt_D_ppv = Pt_D.cal_p(v, t_ppv)\nprint(p_Pt_H_ppv, p_Pt_D_ppv)\nprint('slopes: ', (p_Pt_H_ppv[0]-p_Pt_H_ppv[1])/(t_ppv[0]-t_ppv[1]),\\\n (p_Pt_D_ppv[0]-p_Pt_D_ppv[1])/(t_ppv[0]-t_ppv[1]) )", "[137.6555991946231+/-0.013599646548263514\n 126.72997767244723+/-0.013563105650520829] [135.2453540348088+/-0.01256394315079498\n 123.20614456480777+/-0.012523012644444907]\nslopes: 0.007283748+/-0.000000024 0.00802614+/-0.00000024\n" ], [ "MgO_S = eos.periclase.Speziale2001()\nMgO_D = eos.periclase.Dorogokupets2007()\n\nv = np.asarray([52.87, 53.6])\np_MgO_S_ppv = MgO_S.cal_p(v, t_ppv)\np_MgO_D_ppv = MgO_D.cal_p(v, t_ppv)\nprint(p_MgO_S_ppv, p_MgO_D_ppv)\nprint('slopes: ', (p_MgO_S_ppv[0]-p_MgO_S_ppv[1])/(t_ppv[0]-t_ppv[1]), \\\n (p_MgO_D_ppv[0]-p_MgO_D_ppv[1])/(t_ppv[0]-t_ppv[1]) )", "[135.56997269894586+/-0.9530902142955003\n 115.8281642808288+/-0.49022460541552476] [129.57114762303976+/-0.0071388388100554765\n 113.23868528253495+/-0.006849434801332905]\nslopes: 0.01316+/-0.00032 0.01088831+/-0.00000020\n" ] ], [ [ "# 3. Post-spinel", "_____no_output_____" ], [ "Fei2004\n\nScales| PT | PT \n------|------------|------------\nMgO-S | 23.6, 1573 | 22.8, 2173\nMgO-D | 23.1, 1573 | 22.0, 2173\n\nYe2014\n\nScales | PT | PT\n-------|------------|------------\nPt-F | 25.2, 1550 | 23.2, 2380\nPt-D | 24.6, 1550 | 22.5, 2380 \nAu-F | 28.3, 1650 | 27.1, 2150\nAu-D | 27.0, 1650 | 25.6, 2150", "_____no_output_____" ] ], [ [ "MgO_S = eos.periclase.Speziale2001()\nMgO_D = eos.periclase.Dorogokupets2007()\n\nv = np.asarray([68.75, 70.3])\nt_MgO = np.asarray([1573.,2173.])\np_MgO_S = MgO_S.cal_p(v, t_MgO)\np_MgO_D = MgO_D.cal_p(v, t_MgO)\nprint(p_MgO_S, p_MgO_D)\nprint('slopes: ', (p_MgO_S[0]-p_MgO_S[1])/(t_MgO[0]-t_MgO[1]), (p_MgO_D[0]-p_MgO_D[1])/(t_MgO[0]-t_MgO[1]) )", "[23.64022290732067+/-0.22706825547643575\n 22.87853717791088+/-0.3102166053839235] [23.137126505601984+/-0.0029845506738880247\n 21.993704969833033+/-0.0027476972864245606]\nslopes: -0.00127+/-0.00015 -0.0019057+/-0.0000004\n" ], [ "Pt_F = eos.platinum.Fei2007bm3()\nPt_D = eos.platinum.Dorogokupets2007()\n\nv = np.asarray([57.43, 58.85])\nt_Pt = np.asarray([1550., 2380.])\np_Pt_F = Pt_F.cal_p(v, t_Pt)\np_Pt_D = Pt_D.cal_p(v, t_Pt)\nprint(p_Pt_F, p_Pt_D)\nprint('slopes: ', (p_Pt_F[0]-p_Pt_F[1])/(t_Pt[0]-t_Pt[1]), (p_Pt_D[0]-p_Pt_D[1])/(t_Pt[0]-t_Pt[1]) )", "[25.200649645974792+/-0.25969718379544227\n 23.230785354652753+/-0.2648410029437544] [24.59913157550942+/-0.005887323086638988\n 22.499791438857738+/-0.0052772503634970006]\nslopes: -0.00237+/-0.00009 -0.0025293+/-0.0000009\n" ], [ "Au_F = eos.gold.Fei2007bm3()\nAu_D = eos.gold.Dorogokupets2007()\n\nv = np.asarray([62.33,63.53])\nt_Au = np.asarray([1650., 2150.])\np_Au_F = Au_F.cal_p(v, t_Au)\np_Au_D = Au_D.cal_p(v, t_Au)\nprint(p_Au_F, p_Au_D)\nprint('slopes: ', (p_Au_F[0]-p_Au_F[1])/(t_Au[0]-t_Au[1]), (p_Au_D[0]-p_Au_D[1])/(t_Au[0]-t_Au[1]) )", "[28.16271932337142+/-0.2760383097641682\n 26.998871383434775+/-0.30416857634961575] [26.971967227663487+/-0.003928755274354221\n 25.587752685336014+/-0.003565439028788304]\nslopes: -0.00233+/-0.00008 -0.0027684+/-0.0000008\n" ], [ "f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,3.5))\n#ax.plot(unp.nominal_values(p_Au_T), t, c='b', ls='--', label='Au-Tsuchiya')\nlw = 4\nl_alpha = 0.3\n\nax1.plot(unp.nominal_values(p_Au_D), t_Au, c='b', ls='-', alpha=l_alpha, label='Au-D07', lw=lw)\nax1.annotate('Au-D07', xy=(25.7, 2100), xycoords='data',\n xytext=(26.9, 2100), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='right', verticalalignment='center')\n\nax1.plot(unp.nominal_values(p_Au_D-2.5), t_Au, c='b', ls='-', label='Au-mD07', lw=lw)\nax1.annotate('Au-D07,\\n corrected', xy=(24.35, 1700), xycoords='data',\n xytext=(24.8, 1700), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='left', verticalalignment='center')\n\n#ax.plot(unp.nominal_values(p_Pt_H), t, c='r', ls='--', label='Pt-Holmes')\nax1.plot(unp.nominal_values(p_Pt_D), t_Pt, c='r', ls='-', label='Pt-D07', lw=lw)\nax1.annotate('Pt-D07', xy=(22.7, 2300), xycoords='data',\n xytext=(23.1, 2300), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='left', verticalalignment='center')\n\nax1.plot(unp.nominal_values(p_MgO_S), t_MgO, c='k', ls='-', alpha=l_alpha, label='MgO-S01', lw=lw)\nax1.annotate('MgO-S01', xy=(22.9, 2150), xycoords='data',\n xytext=(22.5, 2250), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='right', verticalalignment='top')\n\nax1.plot(unp.nominal_values(p_MgO_D), t_MgO, c='k', ls='-', label='MgO-D07', lw=lw)\nax1.annotate('MgO-D07', xy=(22.7, 1800), xycoords='data',\n xytext=(22.3, 1800), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='right', verticalalignment='center')\n\nax1.fill([23.5,24,24,23.5], [1700,1700,2000,2000], 'k', alpha=0.2)\n\nax1.set_xlabel(\"Pressure (GPa)\"); ax1.set_ylabel(\"Temperature (K)\")\n#l = ax1.legend(loc=3, fontsize=10, handlelength=2.5); l.get_frame().set_linewidth(0.5)\n\nax2.plot(unp.nominal_values(p_Au_T_ppv), t_ppv, c='b', ls='-', alpha=l_alpha, label='Au-T04', lw=lw)\nax2.annotate('Au-T04', xy=(120, 3400), xycoords='data',\n xytext=(122, 3400), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='left', verticalalignment='center')\n\nax2.plot(unp.nominal_values(p_Au_D_ppv), t_ppv, c='b', ls='-', label='Au-D07', lw=lw)\nax2.annotate('Au-D07', xy=(119, 3400), xycoords='data',\n xytext=(117, 3400), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='right', verticalalignment='center')\n\nax2.plot(unp.nominal_values(p_Pt_H_ppv), t_ppv, c='r', ls='-', alpha=l_alpha, label='Pt-H89', lw=lw)\nax2.annotate('Pt-H89', xy=(129, 2300), xycoords='data',\n xytext=(132, 2300), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='left', verticalalignment='center')\n\nax2.plot(unp.nominal_values(p_Pt_D_ppv), t_ppv, c='r', ls='-', label='Pt-D07', lw=lw)\nax2.annotate('Pt-D07', xy=(124, 2150), xycoords='data',\n xytext=(123.7, 2300), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='center', verticalalignment='bottom')\n\nax2.plot(unp.nominal_values(p_MgO_S_ppv), t_ppv, c='k', ls='-', alpha=l_alpha, label='MgO-S01', lw=lw)\nax2.annotate('MgO-S01', xy=(132, 3250), xycoords='data',\n xytext=(132.2, 3550), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='left', verticalalignment='bottom')\n\nax2.plot(unp.nominal_values(p_MgO_D_ppv), t_ppv, c='k', ls='-', label='MgO-D07', lw=lw)\nax2.annotate('MgO-D07', xy=(128, 3400), xycoords='data',\n xytext=(128, 3550), textcoords='data',\n arrowprops=dict(facecolor='k', alpha=0.5, shrink=1, width = 0.1, headwidth=5),\n horizontalalignment='center', verticalalignment='bottom')\n\nax2.set_xlabel(\"Pressure (GPa)\"); ax2.set_ylabel(\"Temperature (K)\")\nax2.set_ylim(1900, 3700.)\n#l = ax2.legend(loc=0, fontsize=10, handlelength=2.5); l.get_frame().set_linewidth(0.5)\n\nax1.text(0.05, 0.03, 'a', horizontalalignment='center',\\\n verticalalignment='bottom', transform = ax1.transAxes,\\\n fontsize = 32)\nax2.text(0.05, 0.03, 'b', horizontalalignment='center',\\\n verticalalignment='bottom', transform = ax2.transAxes,\\\n fontsize = 32)\n\nax1.set_yticks(ax1.get_yticks()[::2])\n#ax2.set_yticks(ax2.get_yticks()[::2])\nplt.tight_layout(pad=0.6)\n\nplt.savefig('f-boundaries.pdf', bbox_inches='tight', \\\n pad_inches=0.1)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ] ]
d0760f1e2cf4629d5bdd746b9f04b50a677df826
7,367
ipynb
Jupyter Notebook
notebooks/chapter08_ml/05_svm.ipynb
svaksha/cookbook-code
960becec4cc48f14991ed9d8525d5bcd21bc42a7
[ "BSD-2-Clause" ]
5
2015-11-26T14:18:23.000Z
2018-06-08T00:46:35.000Z
notebooks/chapter08_ml/05_svm.ipynb
kunalj101/cookbook-code
adcbdeb6b92e448350ce2643003a2a0719e574ca
[ "BSD-2-Clause" ]
null
null
null
notebooks/chapter08_ml/05_svm.ipynb
kunalj101/cookbook-code
adcbdeb6b92e448350ce2643003a2a0719e574ca
[ "BSD-2-Clause" ]
8
2015-11-14T23:18:50.000Z
2019-08-20T22:47:07.000Z
32.742222
417
0.505362
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d0761136e764d6f9c190e539c8283b97cd5cca22
16,187
ipynb
Jupyter Notebook
12-Generators.ipynb
MoRa-0/wwtop
9217ae72e3158a3c22d9d782549088192c081643
[ "CC0-1.0" ]
13
2017-06-23T02:58:23.000Z
2022-01-19T08:39:55.000Z
12-Generators.ipynb
xishansnow/wwtop
9217ae72e3158a3c22d9d782549088192c081643
[ "CC0-1.0" ]
null
null
null
12-Generators.ipynb
xishansnow/wwtop
9217ae72e3158a3c22d9d782549088192c081643
[ "CC0-1.0" ]
7
2017-10-13T01:08:52.000Z
2022-01-19T03:08:06.000Z
24.232036
254
0.531599
[ [ [ "# Generators\n\n# 生成器", "_____no_output_____" ], [ "> Here we'll take a deeper dive into Python generators, including *generator expressions* and *generator functions*.\n\n本章我们深入讨论Python的生成器,包括*生成器表达式*和*生成器函数*", "_____no_output_____" ], [ "## Generator Expressions\n\n## 生成器表达式", "_____no_output_____" ], [ "> The difference between list comprehensions and generator expressions is sometimes confusing; here we'll quickly outline the differences between them:\n\n列表解析和生成器表达式之间的区别很容易令人混乱;下面我们快速地说明一下它们之间的区别:", "_____no_output_____" ], [ "### List comprehensions use square brackets, while generator expressions use parentheses\n\n### 列表解析使用中括号,而生成器表达式使用小括号\n\n> This is a representative list comprehension:\n\n下面是一个很有代表性的列表解析:", "_____no_output_____" ] ], [ [ "[n ** 2 for n in range(12)]", "_____no_output_____" ] ], [ [ "> While this is a representative generator expression:\n\n下面这个却是一个生成器表达式:", "_____no_output_____" ] ], [ [ "(n ** 2 for n in range(12))", "_____no_output_____" ] ], [ [ "> Notice that printing the generator expression does not print the contents; one way to print the contents of a generator expression is to pass it to the ``list`` constructor:\n\n你会注意到直接打印生成器表达式并不会输出生成器的内容;可以使用`list`将生成器转换为一个列表然后输出:", "_____no_output_____" ] ], [ [ "G = (n ** 2 for n in range(12))\nlist(G)", "_____no_output_____" ] ], [ [ "### A list is a collection of values, while a generator is a recipe for producing values\n\n### 列表是一个集合,而生成器只是产生集合值的配方\n\n> When you create a list, you are actually building a collection of values, and there is some memory cost associated with that.\nWhen you create a generator, you are not building a collection of values, but a recipe for producing those values.\nBoth expose the same iterator interface, as we can see here:\n\n当你创建一个列表,你真实地创建了一个集合,当然这个集合存储在内存当中需要一定的空间。当你创建了一个生成器,你并没有创建一个集合,你仅仅是指定了产生集合值的方法。两者都实现了迭代器接口,由下面两个例子可以看到:", "_____no_output_____" ] ], [ [ "L = [n ** 2 for n in range(12)]\nfor val in L:\n print(val, end=' ')", "0 1 4 9 16 25 36 49 64 81 100 121 " ], [ "G = (n ** 2 for n in range(12))\nfor val in G:\n print(val, end=' ')", "0 1 4 9 16 25 36 49 64 81 100 121 " ] ], [ [ "> The difference is that a generator expression does not actually compute the values until they are needed.\nThis not only leads to memory efficiency, but to computational efficiency as well!\nThis also means that while the size of a list is limited by available memory, the size of a generator expression is unlimited!\n\n区别在于生成器仅在你用到值的时候才会按照配方计算一个值返回给你。这样的好处不仅仅是节省内存,还能节省计算资源。这还意味着,列表的大小受限于可用内存的大小,而生成器的大小是无限的。\n\n> An example of an infinite generator expression can be created using the ``count`` iterator defined in ``itertools``:\n\n我们可以使用`itertools`里面的`count`函数来构造一个无限的生成器表达式:", "_____no_output_____" ] ], [ [ "from itertools import count\ncount()", "_____no_output_____" ], [ "for i in count():\n print(i, end=' ')\n if i >= 10: break", "0 1 2 3 4 5 6 7 8 9 10 " ] ], [ [ "> The ``count`` iterator will go on happily counting forever until you tell it to stop; this makes it convenient to create generators that will also go on forever:\n\n`count`函数会永远的迭代下去除非你停止了它的运行;这也可以用来创建永远运行的生成器:", "_____no_output_____" ] ], [ [ "factors = [2, 3, 5, 7]\nG = (i for i in count() if all(i % n > 0 for n in factors))\nfor val in G:\n print(val, end=' ')\n if val > 40: break", "1 11 13 17 19 23 29 31 37 41 " ] ], [ [ "> You might see what we're getting at here: if we were to expand the list of factors appropriately, what we would have the beginnings of is a prime number generator, using the Sieve of Eratosthenes algorithm. We'll explore this more momentarily.\n\n上面的例子你应该已经看出来了:如果我们使用Sieve of Eratosthenes算法,将factors列表进行合适的扩展的话,那么我们将会得到一个质数的生成器。", "_____no_output_____" ], [ "### A list can be iterated multiple times; a generator expression is single-use\n\n### 列表可以被迭代多次;生成器只能是一次使用\n\n> This is one of those potential gotchas of generator expressions.\nWith a list, we can straightforwardly do this:\n\n这是生成器的一个著名的坑。使用列表时,我们可以如下做:", "_____no_output_____" ] ], [ [ "L = [n ** 2 for n in range(12)]\nfor val in L:\n print(val, end=' ')\nprint()\n\nfor val in L:\n print(val, end=' ')", "0 1 4 9 16 25 36 49 64 81 100 121 \n0 1 4 9 16 25 36 49 64 81 100 121 " ] ], [ [ "> A generator expression, on the other hand, is used-up after one iteration:\n\n生成器表达式则不一样,只能迭代一次:", "_____no_output_____" ] ], [ [ "G = (n ** 2 for n in range(12))\nlist(G)", "_____no_output_____" ], [ "list(G)", "_____no_output_____" ] ], [ [ "> This can be very useful because it means iteration can be stopped and started:\n\n这是非常有用的特性,因为这意味着迭代能停止和开始:", "_____no_output_____" ] ], [ [ "G = (n**2 for n in range(12))\nfor n in G:\n print(n, end=' ')\n if n > 30: break # 生成器停止运行\n\nprint(\"\\ndoing something in between\")\n\nfor n in G: # 生成器继续运行\n print(n, end=' ')", "0 1 4 9 16 25 36 \ndoing something in between\n49 64 81 100 121 " ] ], [ [ "> One place I've found this useful is when working with collections of data files on disk; it means that you can quite easily analyze them in batches, letting the generator keep track of which ones you have yet to see.\n\n作者发现这个特性在使用磁盘上存储的数据文件时特别有用;它意味着你可以很容易的按批次来分析数据,让生成器记录下目前的处理进度。", "_____no_output_____" ], [ "## Generator Functions: Using ``yield``\n\n## 生成器函数:使用 `yield`\n\n> We saw in the previous section that list comprehensions are best used to create relatively simple lists, while using a normal ``for`` loop can be better in more complicated situations.\nThe same is true of generator expressions: we can make more complicated generators using *generator functions*, which make use of the ``yield`` statement.\n\n从上面的讨论中,我们可以知道列表解析适用于创建相对简单的列表,如果列表的生成规则比较复杂,还是使用普通`for`循环更加合适。对于生成器表达式来说也一样:我们可以使用*生成器函数*创建更加复杂的生成器,这里需要用到`yield`关键字。\n\n> Here we have two ways of constructing the same list:\n\n我们有两种方式来构建同一个列表:", "_____no_output_____" ] ], [ [ "L1 = [n ** 2 for n in range(12)]\n\nL2 = []\nfor n in range(12):\n L2.append(n ** 2)\n\nprint(L1)\nprint(L2)", "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]\n[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]\n" ] ], [ [ "> Similarly, here we have two ways of constructing equivalent generators:\n\n类似的,我们也有两种方法来构建相同的生成器:", "_____no_output_____" ] ], [ [ "G1 = (n ** 2 for n in range(12))\n\ndef gen():\n for n in range(12):\n yield n ** 2\n\nG2 = gen()\nprint(*G1)\nprint(*G2)", "0 1 4 9 16 25 36 49 64 81 100 121\n0 1 4 9 16 25 36 49 64 81 100 121\n" ] ], [ [ "> A generator function is a function that, rather than using ``return`` to return a value once, uses ``yield`` to yield a (potentially infinite) sequence of values.\nJust as in generator expressions, the state of the generator is preserved between partial iterations, but if we want a fresh copy of the generator we can simply call the function again.\n\n生成器函数与普通函数的区别在于,生成器函数不是使用`return`来一次性返回值,而是使用`yield`来产生一系列(可能无穷多个)值。就像生成器表达式一样,生成器的状态会被生成器自己保留并记录,如果你需要一个新的生成器,你可以再次调用函数。", "_____no_output_____" ], [ "## Example: Prime Number Generator\n\n## 例子:质数生成器\n\n> Here I'll show my favorite example of a generator function: a function to generate an unbounded series of prime numbers.\nA classic algorithm for this is the *Sieve of Eratosthenes*, which works something like this:\n\n下面作者将介绍他最喜欢的生成器函数的例子:一个可以产生无穷多个质数序列的函数。计算质数又一个经典算法*Sieve of Eratosthenes*,它的工作原理如下:", "_____no_output_____" ] ], [ [ "# 产生可能的质数序列\nL = [n for n in range(2, 40)]\nprint(L)", "[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]\n" ], [ "# 剔除所有被第一个元素整除的数\nL = [n for n in L if n == L[0] or n % L[0] > 0]\nprint(L)", "[2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39]\n" ], [ "# 剔除所有被第二个元素整除的数\nL = [n for n in L if n == L[1] or n % L[1] > 0]\nprint(L)", "[2, 3, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37]\n" ], [ "# 剔除所有被第三个元素整除的数\nL = [n for n in L if n == L[2] or n % L[2] > 0]\nprint(L)", "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]\n" ] ], [ [ "> If we repeat this procedure enough times on a large enough list, we can generate as many primes as we wish.\n\n如果我们在一个很大的列表上重复这个过程足够多次,我们可以生成我们需要的质数。\n\n> Let's encapsulate this logic in a generator function:\n\n我们将这个逻辑封装到一个生成器函数中:", "_____no_output_____" ] ], [ [ "def gen_primes(N):\n \"\"\"Generate primes up to N\"\"\"\n primes = set() # 使用primes集合存储找到的质数\n for n in range(2, N):\n if all(n % p > 0 for p in primes): # primes中的元素都不能整除n -> n是质数\n primes.add(n) # 将n加入primes集合\n yield n # 产生序列\n\nprint(*gen_primes(100))", "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97\n" ] ], [ [ "> That's all there is to it!\nWhile this is certainly not the most computationally efficient implementation of the Sieve of Eratosthenes, it illustrates how convenient the generator function syntax can be for building more complicated sequences.\n\n虽然这可能不是最优化的Sieve of Eratosthenes算法实现,但是它表明声称其函数语法是多么简便,而且可以用来构建很复杂的序列。", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d07626ba79099d69291e4580d9c61c790e044632
124,012
ipynb
Jupyter Notebook
Basic_Image_Classifier.ipynb
DivyaWadehra/60daysofudacity
c57c3625681e3829f70bf45ab03b115abb74bef5
[ "MIT" ]
9
2019-08-18T18:43:28.000Z
2021-04-27T22:33:42.000Z
Basic_Image_Classifier.ipynb
DivyaWadehra/60daysofudacity
c57c3625681e3829f70bf45ab03b115abb74bef5
[ "MIT" ]
1
2019-07-22T11:51:32.000Z
2019-07-22T11:51:32.000Z
Basic_Image_Classifier.ipynb
DivyaWadehra/60daysofudacity
c57c3625681e3829f70bf45ab03b115abb74bef5
[ "MIT" ]
4
2019-10-30T18:50:29.000Z
2020-02-20T16:06:09.000Z
108.496938
20,206
0.791101
[ [ [ "<a href=\"https://colab.research.google.com/github/reallygooday/60daysofudacity/blob/master/Basic_Image_Classifier.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "hand-written digits dataset from UCI: http://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits", "_____no_output_____" ] ], [ [ "# Importing load_digits() from the sklearn.datasets package\n\nfrom sklearn.datasets import load_digits\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\ndigits_data = load_digits()", "_____no_output_____" ], [ "digits_data.keys()", "_____no_output_____" ], [ "labels = pd.Series(digits_data['target'])", "_____no_output_____" ], [ "data = pd.DataFrame(digits_data['data'])\ndata.head(1)", "_____no_output_____" ], [ "first_image = data.iloc[0]\nnp_image = first_image.values\nnp_image = np_image.reshape(8,8)\n\nplt.imshow(np_image, cmap='gray_r')", "_____no_output_____" ], [ "f, axarr = plt.subplots(2, 4)\n\naxarr[0, 0].imshow(data.iloc[0].values.reshape(8,8), cmap='gray_r')\naxarr[0, 1].imshow(data.iloc[99].values.reshape(8,8), cmap='gray_r')\naxarr[0, 2].imshow(data.iloc[199].values.reshape(8,8), cmap='gray_r')\naxarr[0, 3].imshow(data.iloc[299].values.reshape(8,8), cmap='gray_r')\n\naxarr[1, 0].imshow(data.iloc[999].values.reshape(8,8), cmap='gray_r')\naxarr[1, 1].imshow(data.iloc[1099].values.reshape(8,8), cmap='gray_r')\naxarr[1, 2].imshow(data.iloc[1199].values.reshape(8,8), cmap='gray_r')\naxarr[1, 3].imshow(data.iloc[1299].values.reshape(8,8), cmap='gray_r')", "_____no_output_____" ], [ "from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import KFold\n\n# 50% Train / test validation\ndef train_knn(nneighbors, train_features, train_labels):\n knn = KNeighborsClassifier(n_neighbors = nneighbors)\n knn.fit(train_features, train_labels)\n return knn\n\ndef test(model, test_features, test_labels):\n predictions = model.predict(test_features)\n train_test_df = pd.DataFrame()\n train_test_df['correct_label'] = test_labels\n train_test_df['predicted_label'] = predictions\n overall_accuracy = sum(train_test_df[\"predicted_label\"] == train_test_df[\"correct_label\"])/len(train_test_df) \n return overall_accuracy\n\ndef cross_validate(k):\n fold_accuracies = []\n kf = KFold(n_splits = 4, random_state=2)\n for train_index, test_index in kf.split(data):\n train_features, test_features = data.loc[train_index], data.loc[test_index]\n train_labels, test_labels = labels.loc[train_index], labels.loc[test_index]\n model = train_knn(k, train_features, train_labels)\n overall_accuracy = test(model, test_features, test_labels)\n fold_accuracies.append(overall_accuracy)\n return fold_accuracies\n \nknn_one_accuracies = cross_validate(1)\nnp.mean(knn_one_accuracies)", "_____no_output_____" ], [ "k_values = list(range(1,10))\nk_overall_accuracies = []\n\nfor k in k_values:\n k_accuracies = cross_validate(k)\n k_mean_accuracy = np.mean(k_accuracies)\n k_overall_accuracies.append(k_mean_accuracy)\n \nplt.figure(figsize=(8,4))\nplt.title(\"Mean Accuracy vs. k\")\nplt.plot(k_values, k_overall_accuracies)", "_____no_output_____" ], [ "\n#Neural Network With One Hidden Layer\nfrom sklearn.neural_network import MLPClassifier\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import KFold\n\n# 50% Train / test validation\ndef train_nn(neuron_arch, train_features, train_labels):\n mlp = MLPClassifier(hidden_layer_sizes=neuron_arch)\n mlp.fit(train_features, train_labels)\n return mlp\n\ndef test(model, test_features, test_labels):\n predictions = model.predict(test_features)\n train_test_df = pd.DataFrame()\n train_test_df['correct_label'] = test_labels\n train_test_df['predicted_label'] = predictions\n overall_accuracy = sum(train_test_df[\"predicted_label\"] == train_test_df[\"correct_label\"])/len(train_test_df) \n return overall_accuracy\n\ndef cross_validate(neuron_arch):\n fold_accuracies = []\n kf = KFold(n_splits = 4, random_state=2)\n for train_index, test_index in kf.split(data):\n train_features, test_features = data.loc[train_index], data.loc[test_index]\n train_labels, test_labels = labels.loc[train_index], labels.loc[test_index]\n \n model = train_nn(neuron_arch, train_features, train_labels)\n overall_accuracy = test(model, test_features, test_labels)\n fold_accuracies.append(overall_accuracy)\n return fold_accuracies\n \n \n", "_____no_output_____" ], [ "from sklearn.neural_network import MLPClassifier\nnn_one_neurons = [\n (8,),\n (16,),\n (32,),\n (64,),\n (128,),\n (256,)\n]\nnn_one_accuracies = []\n\nfor n in nn_one_neurons:\n nn_accuracies = cross_validate(n)\n nn_mean_accuracy = np.mean(nn_accuracies)\n nn_one_accuracies.append(nn_mean_accuracy)\n\nplt.figure(figsize=(8,4))\nplt.title(\"Mean Accuracy vs. Neurons In Single Hidden Layer\")\n\nx = [i[0] for i in nn_one_neurons]\nplt.plot(x, nn_one_accuracies)", "/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n" ], [ "# Neural Network With Two Hidden Layers\nnn_two_neurons = [\n (64,64),\n (128, 128),\n (256, 256)\n]\nnn_two_accuracies = []\n\nfor n in nn_two_neurons:\n nn_accuracies = cross_validate(n)\n nn_mean_accuracy = np.mean(nn_accuracies)\n nn_two_accuracies.append(nn_mean_accuracy)\n\nplt.figure(figsize=(8,4))\nplt.title(\"Mean Accuracy vs. Neurons In Two Hidden Layers\")\n\nx = [i[0] for i in nn_two_neurons]\nplt.plot(x, nn_two_accuracies)", "_____no_output_____" ], [ "nn_two_accuracies", "_____no_output_____" ], [ "#Neural Network With Three Hidden Layers\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import KFold\n\n# 50% Train / test validation\ndef train_nn(neuron_arch, train_features, train_labels):\n mlp = MLPClassifier(hidden_layer_sizes=neuron_arch)\n mlp.fit(train_features, train_labels)\n return mlp\n\ndef test(model, test_features, test_labels):\n predictions = model.predict(test_features)\n train_test_df = pd.DataFrame()\n train_test_df['correct_label'] = test_labels\n train_test_df['predicted_label'] = predictions\n overall_accuracy = sum(train_test_df[\"predicted_label\"] == train_test_df[\"correct_label\"])/len(train_test_df) \n return overall_accuracy\n\ndef cross_validate_six(neuron_arch):\n fold_accuracies = []\n kf = KFold(n_splits = 6, random_state=2)\n for train_index, test_index in kf.split(data):\n train_features, test_features = data.loc[train_index], data.loc[test_index]\n train_labels, test_labels = labels.loc[train_index], labels.loc[test_index]\n \n model = train_nn(neuron_arch, train_features, train_labels)\n overall_accuracy = test(model, test_features, test_labels)\n fold_accuracies.append(overall_accuracy)\n return fold_accuracies", "_____no_output_____" ], [ "nn_three_neurons = [\n (10, 10, 10),\n (64, 64, 64),\n (128, 128, 128)\n]\n\nnn_three_accuracies = []\n\nfor n in nn_three_neurons:\n nn_accuracies = cross_validate_six(n)\n nn_mean_accuracy = np.mean(nn_accuracies)\n nn_three_accuracies.append(nn_mean_accuracy)\n\nplt.figure(figsize=(8,4))\nplt.title(\"Mean Accuracy vs. Neurons In Three Hidden Layers\")\n\nx = [i[0] for i in nn_three_neurons]\nplt.plot(x, nn_three_accuracies)", "/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/neural_network/multilayer_perceptron.py:566: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (200) reached and the optimization hasn't converged yet.\n % self.max_iter, ConvergenceWarning)\n" ], [ "nn_three_accuracies", "_____no_output_____" ] ], [ [ "#Image Classification with PyTorch", "_____no_output_____" ] ], [ [ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport torchvision\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "train_loader = torch.utils.data.DataLoader(\n datasets.MNIST('./data', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor()\n ])),\n batch_size=32, shuffle=False)", " 0%| | 0/9912422 [00:00<?, ?it/s]" ], [ "test_loader = torch.utils.data.DataLoader(\n datasets.MNIST('./data', train=False,\n transform=transforms.Compose([\n transforms.ToTensor()\n ])),\n batch_size=32, shuffle=False)", "_____no_output_____" ], [ "class BasicNN(nn.Module):\n def __init__(self):\n super(BasicNN, self).__init__()\n self.net = nn.Linear(28 * 28, 10)\n def forward(self, x):\n batch_size = x.size(0)\n x = x.view(batch_size, -1)\n output = self.net(x)\n return F.softmax(output)", "_____no_output_____" ], [ "model = BasicNN()\noptimizer = optim.SGD(model.parameters(), lr=0.001)", "_____no_output_____" ], [ "def test():\n total_loss = 0\n correct = 0\n for image, label in test_loader:\n image, label = Variable(image), Variable(label)\n output = model(image)\n total_loss += F.cross_entropy(output, label)\n correct += (torch.max(output, 1)[1].view(label.size()).data == label.data).sum()\n total_loss = total_loss.data[0]/ len(test_loader)\n accuracy = correct / len(test_loader.dataset)\n return total_loss, accuracy", "_____no_output_____" ], [ "def train():\n model.train()\n for image, label in train_loader:\n image, label = Variable(image), Variable(label)\n optimizer.zero_grad()\n output = model(image)\n loss = F.cross_entropy(output, label)\n loss.backward()\n optimizer.step()", "_____no_output_____" ], [ "best_test_loss = None\nfor e in range(1, 150):\n train()\n test_loss, test_accuracy = test()\n print(\"\\n[Epoch: %d] Test Loss:%5.5f Test Accuracy:%5.5f\" % (e, test_loss, test_accuracy))\n # Save the model if the test_loss is the lowest\n if not best_test_loss or test_loss < best_test_loss:\n best_test_loss = test_loss\n else:\n break\nprint(\"\\nFinal Results\\n-------------\\n\"\"Loss:\", best_test_loss, \"Test Accuracy: \", test_accuracy)", "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:9: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.\n if __name__ == '__main__':\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0763921dd7708230f66b68bfceb34787777f49b
28,100
ipynb
Jupyter Notebook
coursework/02-ANN-Artificial-Neural-Networks/Basic PyTorch ANN - Iris.ipynb
saint1729/deep-learning-pytorch
7157c32d58a8d053cf56811eb03af9adb37597d1
[ "MIT" ]
null
null
null
coursework/02-ANN-Artificial-Neural-Networks/Basic PyTorch ANN - Iris.ipynb
saint1729/deep-learning-pytorch
7157c32d58a8d053cf56811eb03af9adb37597d1
[ "MIT" ]
null
null
null
coursework/02-ANN-Artificial-Neural-Networks/Basic PyTorch ANN - Iris.ipynb
saint1729/deep-learning-pytorch
7157c32d58a8d053cf56811eb03af9adb37597d1
[ "MIT" ]
null
null
null
46.989967
12,712
0.656868
[ [ [ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "class Model(nn.Module):\n def __init__(self, in_features=4, h1=8, h2=9, out_features=3):\n super().__init__()\n \n self.fc1 = nn.Linear(in_features, h1)\n self.fc2 = nn.Linear(h1, h2)\n self.out = nn.Linear(h2, out_features)\n \n \n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.out(x)\n \n return x", "_____no_output_____" ], [ "torch.manual_seed(32)\n\nmodel = Model()", "_____no_output_____" ], [ "df = pd.read_csv(\"../Data/iris.csv\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.tail()", "_____no_output_____" ], [ "X = df.drop(\"target\", axis=1)\ny = df[\"target\"]", "_____no_output_____" ], [ "X = X.values\ny = y.values", "_____no_output_____" ], [ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=33)", "_____no_output_____" ], [ "X_train = torch.FloatTensor(X_train)\nX_test = torch.FloatTensor(X_test)", "_____no_output_____" ], [ "y_train = torch.LongTensor(y_train)\ny_test = torch.LongTensor(y_test)", "_____no_output_____" ], [ "criterion = nn.CrossEntropyLoss()\n\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01)", "_____no_output_____" ], [ "epochs = 100\nlosses = []\n\nfor i in range(epochs):\n y_pred = model.forward(X_train)\n loss = criterion(y_pred, y_train)\n losses.append(loss)\n if i % 10 == 0:\n print(f\"epoch {i} and loss is: {loss}\")\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()", "epoch 0 and loss is: 1.1507115364074707\nepoch 10 and loss is: 0.9377315640449524\nepoch 20 and loss is: 0.779825747013092\nepoch 30 and loss is: 0.6099401116371155\nepoch 40 and loss is: 0.4007992744445801\nepoch 50 and loss is: 0.25436317920684814\nepoch 60 and loss is: 0.15053054690361023\nepoch 70 and loss is: 0.10086945444345474\nepoch 80 and loss is: 0.08128312975168228\nepoch 90 and loss is: 0.0723142996430397\n" ], [ "plt.plot(range(epochs), losses)\nplt.ylabel(\"Loss\")\nplt.xlabel(\"Epoch\")", "_____no_output_____" ], [ "with torch.no_grad():\n y_eval = model.forward(X_test)\n loss = criterion(y_eval, y_test)", "_____no_output_____" ], [ "loss", "_____no_output_____" ], [ "correct = 0\n\nwith torch.no_grad():\n for i, data in enumerate(X_test):\n y_val = model.forward(data)\n print(f\"{i + 1}. {str(y_val)} {y_test[i]}\")\n if y_val.argmax().item() == y_test[i]:\n correct += 1\n\nprint(f\"We got {correct} correct!\")", "1. tensor([-2.1252, 4.8064, -0.8628]) 1\n2. tensor([-1.7985, 5.3098, -1.5449]) 1\n3. tensor([ 6.3542, 0.8438, -10.0541]) 0\n4. tensor([-3.9123, 4.5958, 1.1693]) 1\n5. tensor([-7.4713, 3.2021, 5.7853]) 2\n6. tensor([-10.4976, 1.6459, 9.6297]) 2\n7. tensor([ 6.3201, 0.9917, -10.1532]) 0\n8. tensor([ 7.0468, 0.7059, -10.9137]) 0\n9. tensor([-7.2061, 3.3477, 5.3565]) 2\n10. tensor([-9.3960, 2.5759, 8.1033]) 2\n11. tensor([-9.8808, 2.3475, 8.7141]) 2\n12. tensor([ 6.2748, 0.6655, -9.7613]) 0\n13. tensor([-9.3142, 2.1880, 8.1947]) 2\n14. tensor([-3.7803, 4.5050, 1.0752]) 1\n15. tensor([-7.8657, 3.0117, 6.2303]) 2\n16. tensor([-1.8867, 5.1572, -1.3345]) 1\n17. tensor([-5.7006, 3.5030, 3.6696]) 2\n18. tensor([ 7.1789, 0.7369, -11.1350]) 0\n19. tensor([-3.2944, 4.7931, 0.3475]) 1\n20. tensor([-7.7665, 3.7629, 5.7095]) 2\n21. tensor([ 6.6499, 0.7889, -10.4252]) 0\n22. tensor([ 7.4357, 0.8918, -11.6600]) 0\n23. tensor([-9.7584, 2.1744, 8.6654]) 2\n24. tensor([ 6.5770, 0.7421, -10.2733]) 0\n25. tensor([-7.4144, 2.8719, 5.9445]) 2\n26. tensor([-6.1551, 3.4030, 4.2300]) 2\n27. tensor([-3.1634, 4.7460, 0.2703]) 1\n28. tensor([-1.5446, 4.9031, -1.5557]) 1\n29. tensor([-7.4335, 3.1101, 5.7350]) 2\n30. tensor([-6.7037, 3.1187, 4.9595]) 2\nWe got 30 correct!\n" ], [ "torch.save(model.state_dict(), \"my_iris_model.pt\")", "_____no_output_____" ], [ "new_model = Model()\nnew_model.load_state_dict(torch.load(\"my_iris_model.pt\"))", "_____no_output_____" ], [ "new_model.eval()", "_____no_output_____" ], [ "mystery_iris = torch.tensor([5.6, 3.7, 2.2, 0.5])", "_____no_output_____" ], [ "with torch.no_grad():\n print(new_model(mystery_iris))\n print(new_model(mystery_iris).argmax())", "tensor([ 5.9522, 1.5596, -10.0054])\ntensor(0)\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0763b15ac76c20042114caf3d49e513bc43c73a
43,356
ipynb
Jupyter Notebook
analysis/.ipynb_checkpoints/Untitled-checkpoint.ipynb
mathisonian/consumer-complaints
24dc36d81b4cddb9d14980e8fe36e115cf5e34da
[ "MIT" ]
6
2017-03-20T19:22:29.000Z
2021-01-21T20:25:34.000Z
analysis/.ipynb_checkpoints/Untitled-checkpoint.ipynb
mathisonian/dashcam
4e241bc16d815906e4e283ea87ad16323a258e0d
[ "MIT" ]
null
null
null
analysis/.ipynb_checkpoints/Untitled-checkpoint.ipynb
mathisonian/dashcam
4e241bc16d815906e4e283ea87ad16323a258e0d
[ "MIT" ]
3
2018-01-15T21:40:45.000Z
2019-11-09T02:33:38.000Z
49.045249
140
0.377479
[ [ [ "import pandas as pd\nimport numpy as np\nfrom altair import Chart, load_dataset", "_____no_output_____" ], [ "csv_path = \"../data/consumer-complaints.csv\"", "_____no_output_____" ], [ "complaints = pd.read_csv(csv_path, parse_dates=[0], infer_datetime_format=True, low_memory=False)", "_____no_output_____" ], [ "complaints.head()", "_____no_output_____" ], [ "complaints[complaints['Company public response'].notnull()]['Company public response'].value_counts()", "_____no_output_____" ], [ "complaints['Tags'].value_counts()", "_____no_output_____" ], [ "complaints['Company response to consumer'].value_counts()", "_____no_output_____" ], [ "len(complaints)", "_____no_output_____" ], [ "complaints['Company'].value_counts()", "_____no_output_____" ], [ "boa = complaints[complaints['Company'] == 'Bank of America']", "_____no_output_____" ], [ "boa.groupby(['Product', 'Sub-product']).size()", "_____no_output_____" ], [ "boa.groupby(['Issue', 'Sub-issue']).size()", "_____no_output_____" ], [ "complaints.groupby(['Issue', 'Sub-issue']).size()", "_____no_output_____" ], [ "wrong_debt = complaints[complaints['Sub-issue'] == 'Debt is not mine']\npaid_debt = complaints[complaints['Sub-issue'] == 'Debt was paid']", "_____no_output_____" ], [ "wrong_debt['Company'].value_counts()", "_____no_output_____" ], [ "paid_debt['Company'].value_counts()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0763cb9e943b9f4edab9e76444e1d0d136f326d
179,372
ipynb
Jupyter Notebook
Modulo 4 - Analisi per regioni/regioni/Lombardia/.ipynb_checkpoints/Confronto LOMBARDIA-checkpoint.ipynb
SofiaBlack/Towards-a-software-to-measure-the-impact-of-the-COVID-19-outbreak-on-Italian-deaths
c418eba90dc07f58633e7e4cd2719c46f0a6b202
[ "Unlicense" ]
3
2021-04-02T21:54:52.000Z
2021-04-13T14:24:29.000Z
Modulo 4 - Analisi per regioni/regioni/Lombardia/.ipynb_checkpoints/Confronto LOMBARDIA-checkpoint.ipynb
SofiaBlack/COVID-19_deaths_analysis
c418eba90dc07f58633e7e4cd2719c46f0a6b202
[ "Unlicense" ]
null
null
null
Modulo 4 - Analisi per regioni/regioni/Lombardia/.ipynb_checkpoints/Confronto LOMBARDIA-checkpoint.ipynb
SofiaBlack/COVID-19_deaths_analysis
c418eba90dc07f58633e7e4cd2719c46f0a6b202
[ "Unlicense" ]
null
null
null
103.863347
60,724
0.829516
[ [ [ "<h1>REGIONE LOMBARDIA</h1>", "_____no_output_____" ], [ "Confronto dei dati relativi ai decessi registrati dall'ISTAT e i decessi causa COVID-19 registrati dalla Protezione Civile Italiana con i decessi previsti dal modello predittivo SARIMA.", "_____no_output_____" ], [ "<h2>DECESSI MENSILI REGIONE LOMBARDIA ISTAT</h2>", "_____no_output_____" ], [ "Il DataFrame contiene i dati relativi ai decessi mensili della regione <b>Lombardia</b> dal <b>2015</b> al <b>30 settembre 2020</b>.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\nimport pandas as pd\ndecessi_istat = pd.read_csv('../../csv/regioni/lombardia.csv')\ndecessi_istat.head()", "_____no_output_____" ], [ "decessi_istat['DATA'] = pd.to_datetime(decessi_istat['DATA'])\ndecessi_istat.TOTALE = pd.to_numeric(decessi_istat.TOTALE)\n", "_____no_output_____" ] ], [ [ "<h3>Recupero dei dati inerenti al periodo COVID-19</h3>", "_____no_output_____" ] ], [ [ "decessi_istat = decessi_istat[decessi_istat['DATA'] > '2020-02-29']\ndecessi_istat.head()\n", "_____no_output_____" ] ], [ [ "<h3>Creazione serie storica dei decessi ISTAT</h3>", "_____no_output_____" ] ], [ [ "decessi_istat = decessi_istat.set_index('DATA')\ndecessi_istat = decessi_istat.TOTALE\ndecessi_istat", "_____no_output_____" ] ], [ [ "<h2>DECESSI MENSILI REGIONE LOMBARDIA CAUSATI DAL COVID</h2>", "_____no_output_____" ], [ "Il DataFrame contine i dati forniti dalla Protezione Civile relativi ai decessi mensili della regione <b>Lombardia</b> da <b> marzo 2020</b> al <b>30 settembre 2020</b>.", "_____no_output_____" ] ], [ [ "covid = pd.read_csv('../../csv/regioni_covid/lombardia.csv')\ncovid.head()", "_____no_output_____" ], [ "covid['data'] = pd.to_datetime(covid['data'])\ncovid.deceduti = pd.to_numeric(covid.deceduti)", "_____no_output_____" ], [ "covid = covid.set_index('data')\ncovid.head()", "_____no_output_____" ] ], [ [ "<h3>Creazione serie storica dei decessi COVID-19</h3>", "_____no_output_____" ] ], [ [ "covid = covid.deceduti", "_____no_output_____" ] ], [ [ "<h2>PREDIZIONE DECESSI MENSILI REGIONE SECONDO MODELLO SARIMA</h2>", "_____no_output_____" ], [ "Il DataFrame contiene i dati riguardanti i decessi mensili della regione <b>Lombardia</b> secondo la predizione del modello SARIMA applicato. ", "_____no_output_____" ] ], [ [ "predictions = pd.read_csv('../../csv/pred/predictions_SARIMA_lombardia.csv')\npredictions.head()", "_____no_output_____" ], [ "predictions.rename(columns={'Unnamed: 0': 'Data', 'predicted_mean':'Totale'}, inplace=True)\npredictions.head()", "_____no_output_____" ], [ "predictions['Data'] = pd.to_datetime(predictions['Data'])\npredictions.Totale = pd.to_numeric(predictions.Totale)", "_____no_output_____" ] ], [ [ "<h3>Recupero dei dati inerenti al periodo COVID-19</h3>", "_____no_output_____" ] ], [ [ "predictions = predictions[predictions['Data'] > '2020-02-29']\npredictions.head()", "_____no_output_____" ], [ "predictions = predictions.set_index('Data')\npredictions.head()", "_____no_output_____" ] ], [ [ "<h3>Creazione serie storica dei decessi secondo la predizione del modello</h3>", "_____no_output_____" ] ], [ [ "predictions = predictions.Totale", "_____no_output_____" ] ], [ [ "<h1>INTERVALLI DI CONFIDENZA </h1>", "_____no_output_____" ], [ "<h3>Limite massimo</h3>", "_____no_output_____" ] ], [ [ "upper = pd.read_csv('../../csv/upper/predictions_SARIMA_lombardia_upper.csv')\nupper.head()", "_____no_output_____" ], [ "upper.rename(columns={'Unnamed: 0': 'Data', 'upper TOTALE':'Totale'}, inplace=True)\nupper['Data'] = pd.to_datetime(upper['Data'])\nupper.Totale = pd.to_numeric(upper.Totale)\nupper.head()", "_____no_output_____" ], [ "upper = upper[upper['Data'] > '2020-02-29']\nupper = upper.set_index('Data')\nupper.head()", "_____no_output_____" ], [ "upper = upper.Totale", "_____no_output_____" ] ], [ [ "<h3>Limite minimo", "_____no_output_____" ] ], [ [ "lower = pd.read_csv('../../csv/lower/predictions_SARIMA_lombardia_lower.csv')\nlower.head()", "_____no_output_____" ], [ "lower.rename(columns={'Unnamed: 0': 'Data', 'lower TOTALE':'Totale'}, inplace=True)\nlower['Data'] = pd.to_datetime(lower['Data'])\nlower.Totale = pd.to_numeric(lower.Totale)\nlower.head()", "_____no_output_____" ], [ "lower = lower[lower['Data'] > '2020-02-29']\nlower = lower.set_index('Data')\nlower.head()", "_____no_output_____" ], [ "lower = lower.Totale", "_____no_output_____" ] ], [ [ "<h1> CONFRONTO DELLE SERIE STORICHE </h1>", "_____no_output_____" ], [ "Di seguito il confronto grafico tra le serie storiche dei <b>decessi totali mensili</b>, dei <b>decessi causa COVID-19</b> e dei <b>decessi previsti dal modello SARIMA</b> della regione <b>Lombardia</b>.\n<br />\nI mesi di riferimento sono: <b>marzo</b>, <b>aprile</b>, <b>maggio</b>, <b>giugno</b>, <b>luglio</b>, <b>agosto</b> e <b>settembre</b>.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(15,4))\nplt.title('LOMBARDIA - Confronto decessi totali, decessi causa covid e decessi del modello predittivo', size=18)\nplt.plot(covid, label='decessi accertati covid')\nplt.plot(decessi_istat, label='decessi totali')\nplt.plot(predictions, label='predizione modello')\nplt.legend(prop={'size': 12})\nplt.show()", "_____no_output_____" ], [ "plt.figure(figsize=(15,4))\nplt.title(\"LOMBARDIA - Confronto decessi totali ISTAT con decessi previsti dal modello\", size=18)\nplt.plot(predictions, label='predizione modello')\nplt.plot(upper, label='limite massimo')\nplt.plot(lower, label='limite minimo')\nplt.plot(decessi_istat, label='decessi totali')\nplt.legend(prop={'size': 12})\nplt.show()", "_____no_output_____" ] ], [ [ "<h2>Calcolo dei decessi COVID-19 secondo il modello predittivo</h2>", "_____no_output_____" ], [ "Differenza tra i decessi totali rilasciati dall'ISTAT e i decessi secondo la previsione del modello SARIMA.", "_____no_output_____" ] ], [ [ "n = decessi_istat - predictions\nn_upper = decessi_istat - lower \nn_lower = decessi_istat - upper\n\nplt.figure(figsize=(15,4))\nplt.title(\"LOMBARDIA - Confronto decessi accertati covid con decessi covid previsti dal modello\", size=18)\nplt.plot(covid, label='decessi covid accertati - Protezione Civile')\nplt.plot(n, label='devessi covid previsti - modello SARIMA')\nplt.plot(n_upper, label='limite massimo - modello SARIMA')\nplt.plot(n_lower, label='limite minimo - modello SARIMA')\nplt.legend(prop={'size': 12})\nplt.show()", "_____no_output_____" ] ], [ [ "Gli <b>intervalli</b> corrispondono alla differenza tra i decessi totali forniti dall'ISTAT per i mesi di marzo, aprile, maggio e giugno 2020 e i valori degli <b>intervalli di confidenza</b> (intervallo superiore e intervallo inferiore) del modello predittivo SARIMA dei medesimi mesi.", "_____no_output_____" ] ], [ [ "d = decessi_istat.sum()\nprint(\"Decessi 2020:\", d)", "Decessi 2020: 82533\n" ], [ "d_m = predictions.sum()\nprint(\"Decessi attesi dal modello 2020:\", d_m)", "Decessi attesi dal modello 2020: 57096.764646363634\n" ], [ "d_lower = lower.sum()\nprint(\"Decessi attesi dal modello 2020 - livello mimino:\", d_lower)", "Decessi attesi dal modello 2020 - livello mimino: 47027.967064348566\n" ] ], [ [ "<h3>Numero totale dei decessi accertati COVID-19 per la regione Lombardia </h3>", "_____no_output_____" ] ], [ [ "m = covid.sum()\nprint(int(m))", "16955\n" ] ], [ [ "<h3>Numero totale dei decessi COVID-19 previsti dal modello per la regione Lombardia </h3>", "_____no_output_____" ], [ "<h4>Valore medio", "_____no_output_____" ] ], [ [ "total = n.sum()\nprint(int(total))", "25436\n" ] ], [ [ "<h4>Valore massimo", "_____no_output_____" ] ], [ [ "total_upper = n_upper.sum()\nprint(int(total_upper))", "35505\n" ] ], [ [ "<h4>Valore minimo", "_____no_output_____" ] ], [ [ "total_lower = n_lower.sum()\nprint(int(total_lower))", "15367\n" ] ], [ [ "<h3>Calcolo del numero dei decessi COVID-19 non registrati secondo il modello predittivo SARIMA della regione Lombardia</h3>", "_____no_output_____" ], [ "<h4>Valore medio", "_____no_output_____" ] ], [ [ "x = decessi_istat - predictions - covid\nx = x.sum()\nprint(int(x))", "8481\n" ] ], [ [ "<h4>Valore massimo", "_____no_output_____" ] ], [ [ "x_upper = decessi_istat - lower - covid\nx_upper = x_upper.sum()\nprint(int(x_upper))", "18550\n" ] ], [ [ "<h4>Valore minimo", "_____no_output_____" ] ], [ [ "x_lower = decessi_istat - upper - covid\nx_lower = x_lower.sum()\nprint(int(x_lower))", "-1587\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0763f53db7c2f47a3b3a10cea4061884dda6d04
5,542
ipynb
Jupyter Notebook
notebooks/02 Extracting Data Using APIs.ipynb
HybridNeos/pluralsight_titanic
9e6904ffaaa2e7b1724fb77cba8a8c67aef45cfa
[ "MIT" ]
null
null
null
notebooks/02 Extracting Data Using APIs.ipynb
HybridNeos/pluralsight_titanic
9e6904ffaaa2e7b1724fb77cba8a8c67aef45cfa
[ "MIT" ]
null
null
null
notebooks/02 Extracting Data Using APIs.ipynb
HybridNeos/pluralsight_titanic
9e6904ffaaa2e7b1724fb77cba8a8c67aef45cfa
[ "MIT" ]
null
null
null
24.741071
921
0.542043
[ [ [ "## Extracting Data Using APIs", "_____no_output_____" ], [ "#### import package", "_____no_output_____" ] ], [ [ "import requests", "_____no_output_____" ] ], [ [ "#### basic usage", "_____no_output_____" ] ], [ [ "# url \nurl = 'https://api.data.gov/ed/collegescorecard/v1/schools?school.name=boston%20college&api_key=qXweBRNPXvP8wo1Ewouaa2ASWZOJHUQUzz4Sbncs'", "_____no_output_____" ], [ "# using get command , returns response object\nresult = requests.get(url)", "_____no_output_____" ], [ "# exploring response object : status_code\nresult.status_code", "_____no_output_____" ], [ "# exploring response object : headers\nresult.headers", "_____no_output_____" ], [ "# exploring response object : text\nresult.text", "_____no_output_____" ], [ "# in json object\nx = dict(result.json())\nx = x['results']\n;", "_____no_output_____" ], [ "x[0].keys()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
d0764ee0e602af85e2dfd7c595293bb163917bae
275,081
ipynb
Jupyter Notebook
P1.ipynb
meetguogengli/Project1-Finding-Lane-Lines-on-the-Road
d1392951f48ec673befccf04c0d8ae834c732337
[ "MIT" ]
1
2021-04-07T04:08:26.000Z
2021-04-07T04:08:26.000Z
P1.ipynb
meetguogengli/Project1-Finding-Lane-Lines-on-the-Road
d1392951f48ec673befccf04c0d8ae834c732337
[ "MIT" ]
null
null
null
P1.ipynb
meetguogengli/Project1-Finding-Lane-Lines-on-the-Road
d1392951f48ec673befccf04c0d8ae834c732337
[ "MIT" ]
null
null
null
341.291563
129,288
0.926618
[ [ [ "# Self-Driving Car Engineer Nanodegree\n\n\n## Project: **Finding Lane Lines on the Road** \n***\nIn this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n\nOnce you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n\nIn addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n\n---\nLet's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n\n**Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n\n---", "_____no_output_____" ], [ "**The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.**\n\n---\n\n<figure>\n <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n </figcaption>\n</figure>\n <p></p> \n<figure>\n <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n </figcaption>\n</figure>", "_____no_output_____" ], [ "**Run the cell below to import some packages. If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.** ", "_____no_output_____" ], [ "## Import Packages", "_____no_output_____" ] ], [ [ "#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\n%matplotlib inline", "_____no_output_____" ] ], [ [ "## Read in an Image", "_____no_output_____" ] ], [ [ "#reading in an image\nimage = mpimg.imread('test_images/solidWhiteRight.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(image), 'with dimensions:', image.shape)\nplt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')", "This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)\n" ] ], [ [ "## Ideas for Lane Detection Pipeline", "_____no_output_____" ], [ "**Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**\n\n`cv2.inRange()` for color selection \n`cv2.fillPoly()` for regions selection \n`cv2.line()` to draw lines on an image given endpoints \n`cv2.addWeighted()` to coadd / overlay two images\n`cv2.cvtColor()` to grayscale or change color\n`cv2.imwrite()` to output images to file \n`cv2.bitwise_and()` to apply a mask to an image\n\n**Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**", "_____no_output_____" ], [ "## Helper Functions", "_____no_output_____" ], [ "Below are some helper functions to help get you started. They should look familiar from the lesson!", "_____no_output_____" ] ], [ [ "import math\nfrom scipy import stats\n\ndef grayscale(img):\n \"\"\"Applies the Grayscale transform\n This will return an image with only one color channel\n but NOTE: to see the returned image as grayscale\n (assuming your grayscaled image is called 'gray')\n you should call plt.imshow(gray, cmap='gray')\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Or use BGR2GRAY if you read an image with cv2.imread()\n # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \ndef canny(img, low_threshold, high_threshold):\n \"\"\"Applies the Canny transform\"\"\"\n return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n `vertices` should be a numpy array of integer points.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=2):\n \"\"\"\n NOTE: this is the function you might want to use as a starting point once you want to \n average/extrapolate the line segments you detect to map out the full\n extent of the lane (going from the result shown in raw-lines-example.mp4\n to that shown in P1_example.mp4). \n \n Think about things like separating line segments by their \n slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n line vs. the right line. Then, you can average the position of each of \n the lines and extrapolate to the top and bottom of the lane.\n \n This function draws `lines` with `color` and `thickness`. \n Lines are drawn on the image inplace (mutates the image).\n If you want to make the lines semi-transparent, think about combining\n this function with the weighted_img() function below\n \"\"\"\n# for line in lines:\n# for x1,y1,x2,y2 in line:\n# cv2.line(img, (x1, y1), (x2, y2), color, thickness)\n sizeY = img.shape[0]\n sizeX = img.shape[1]\n \n pointsLeft = []\n pointsRight = []\n \n for line in lines:\n for x1,y1,x2,y2 in line: \n #cv2.line(img, (x1 , y1) , (x2 , y2) , [0, 255, 0], thickness)\n # Gets the midpoint of a line\n posX = (x1 + x2) * 0.5\n posY = (y1 + y2) * 0.5\n \n # Determines whether the midpoint is loaded on the right or left side of the image and classifies it\n if posX < sizeX * 0.5 :\n pointsLeft.append((posX, posY))\n else:\n pointsRight.append((posX, posY))\n \n # Get m and b from linear regression\n left = stats.linregress(pointsLeft)\n right = stats.linregress(pointsRight)\n \n left_m = left.slope\n right_m = right.slope\n left_b = left.intercept\n right_b = right.intercept\n \n # Define the points of left line x = (y - b) / m \n left_y1 = int(sizeY)\n left_x1 = int((left_y1 - left_b) / left_m)\n left_y2 = int(sizeY * 0.6)\n left_x2 = int((left_y2 - left_b) / left_m)\n \n # Define the points of right line x = (y - b) / m \n right_y1 = int(sizeY)\n right_x1 = int((right_y1 - right_b) / right_m)\n right_y2 = int(sizeY * 0.6)\n right_x2 = int((right_y2 - right_b) / right_m)\n \n # Draw two lane lines\n cv2.line(img, (left_x1 , left_y1 ) , (left_x2 , left_y2 ) , color, thickness)\n cv2.line(img, (right_x1 , right_y1) , (right_x2 , right_y2) , color, thickness)\n \n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\"\n `img` should be the output of a Canny transform.\n \n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n draw_lines(line_img, lines)\n return line_img\n\n# Python 3 has support for cool math symbols.\n\ndef weighted_img(img, initial_img, α=0.8, β=1., γ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n \n `initial_img` should be the image before any processing.\n \n The result image is computed as follows:\n \n initial_img * α + img * β + γ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, γ)", "_____no_output_____" ] ], [ [ "## Test Images\n\nBuild your pipeline to work on the images in the directory \"test_images\" \n**You should make sure your pipeline works well on these images before you try the videos.**", "_____no_output_____" ] ], [ [ "import os\nos.listdir(\"test_images/\")", "_____no_output_____" ] ], [ [ "## Build a Lane Finding Pipeline\n\n", "_____no_output_____" ], [ "Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n\nTry tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.", "_____no_output_____" ] ], [ [ "# TODO: Build your pipeline that will draw lane lines on the test_images\n# then save them to the test_images_output directory.\n\nimage = mpimg.imread(\"test_images/\"+os.listdir(\"test_images/\")[4])\n\nweighted_image = process_image(image)\nplt.imshow(weighted_image)", "_____no_output_____" ] ], [ [ "## Test on Videos\n\nYou know what's cooler than drawing lanes over images? Drawing lanes over video!\n\nWe can test our solution on two provided videos:\n\n`solidWhiteRight.mp4`\n\n`solidYellowLeft.mp4`\n\n**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n\n**If you get an error that looks like this:**\n```\nNeedDownloadError: Need ffmpeg exe. \nYou can download it by calling: \nimageio.plugins.ffmpeg.download()\n```\n**Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**", "_____no_output_____" ] ], [ [ "# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML", "_____no_output_____" ], [ "\n\ndef process_image(image):\n # NOTE: The output you return should be a color image (3 channel) for processing video below\n # TODO: put your pipeline here,\n # you should return the final output (image where lines are drawn on lanes)\n gray = grayscale(image)\n kernel_size = 9\n blur_gray = gaussian_blur(gray, kernel_size)\n\n low_threshold = 100\n high_threshold = 150\n edges = canny(blur_gray, low_threshold, high_threshold)\n \n ysize = image.shape[0]\n xsize = image.shape[1]\n\n vertices = np.array([[(xsize * 0.10 , ysize * 0.90), \n (xsize * 0.46 , ysize * 0.60), \n (xsize * 0.54 , ysize * 0.60), \n (xsize * 0.90 , ysize * 0.90)]], dtype=np.int32)\n# imshape = image.shape\n # vertices = np.array([[(0,imshape[0]),(0, 0), (imshape[1], 0), (imshape[1],imshape[0])]], dtype=np.int32)\n# vertices = np.array([[(0,imshape[0]),(450, 320), (490, 320), (imshape[1],imshape[0])]], dtype=np.int32)\n masked_edges = region_of_interest(edges, vertices)\n\n rho = 2 # distance resolution in pixels of the Hough grid\n theta = np.pi/180 # angular resolution in radians of the Hough grid\n threshold = 10 # minimum number of votes (intersections in Hough grid cell)\n min_line_len = 5 #minimum number of pixels making up a line\n max_line_gap = 5 # maximum gap in pixels between connectable line segments\n line_image = np.copy(image)*0 # creating a blank to draw lines on\n\n line_img = hough_lines(masked_edges, rho, theta, threshold, min_line_len, max_line_gap)\n weighted_image = weighted_img(line_img, image)\n \n return weighted_image", "_____no_output_____" ] ], [ [ "Let's try the one with the solid white lane on the right first ...", "_____no_output_____" ] ], [ [ "white_output = 'test_videos_output/solidWhiteRight.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n%time white_clip.write_videofile(white_output, audio=False)", "[MoviePy] >>>> Building video test_videos_output/solidWhiteRight.mp4\n[MoviePy] Writing video test_videos_output/solidWhiteRight.mp4\n" ] ], [ [ "Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.", "_____no_output_____" ] ], [ [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))", "_____no_output_____" ] ], [ [ "## Improve the draw_lines() function\n\n**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n\n**Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**", "_____no_output_____" ], [ "Now for the one with the solid yellow lane on the left. This one's more tricky!", "_____no_output_____" ] ], [ [ "yellow_output = 'test_videos_output/solidYellowLeft.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\nyellow_clip = clip2.fl_image(process_image)\n%time yellow_clip.write_videofile(yellow_output, audio=False)", "[MoviePy] >>>> Building video test_videos_output/solidYellowLeft.mp4\n[MoviePy] Writing video test_videos_output/solidYellowLeft.mp4\n" ], [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))", "_____no_output_____" ] ], [ [ "\n## Writeup and Submission\n\nIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.\n", "_____no_output_____" ], [ "## Optional Challenge\n\nTry your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!", "_____no_output_____" ] ], [ [ "challenge_output = 'test_videos_output/challenge.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n# clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)\nclip3 = VideoFileClip('test_videos/challenge.mp4')\nchallenge_clip = clip3.fl_image(process_image)\n%time challenge_clip.write_videofile(challenge_output, audio=False)", "[MoviePy] >>>> Building video test_videos_output/challenge.mp4\n[MoviePy] Writing video test_videos_output/challenge.mp4\n" ], [ "HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(challenge_output))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
d07655bd007fda20e6da53128038809055672b1b
10,679
ipynb
Jupyter Notebook
examples/usage.ipynb
metaperture/autoargs
bfc1e653b7f6c4a3a2753e60dca7f63be3355461
[ "BSD-3-Clause" ]
6
2015-10-13T03:30:50.000Z
2019-07-24T23:13:56.000Z
examples/usage.ipynb
metaperture/autoargs
bfc1e653b7f6c4a3a2753e60dca7f63be3355461
[ "BSD-3-Clause" ]
1
2016-09-21T21:38:48.000Z
2016-09-21T21:38:48.000Z
examples/usage.ipynb
metaperture/autoargs
bfc1e653b7f6c4a3a2753e60dca7f63be3355461
[ "BSD-3-Clause" ]
null
null
null
23.114719
181
0.507913
[ [ [ "from imp import reload\nimport autoargs; reload(autoargs);", "_____no_output_____" ] ], [ [ "## argparse made easy!", "_____no_output_____" ] ], [ [ "# pass your function and args from your sys.argv, and you're off to the races!\ndef myprint(arg1, arg2):\n print(\"arg1:\", arg1)\n print(\"arg2:\", arg2)\nautoargs.autocall(myprint, [\"first\", \"second\"])", "arg1: first\narg2: second\n" ], [ "# if you want your arguments to be types, use any function that expects a string\n# and returns the type you want in your arg annotation\ndef str_repeat(s: str, n: int):\n print((s * n).strip())\nautoargs.autocall(str_repeat, [\"args are easy!\\n\", \"3\"])\n# if your args value is a string, it gets split using shlex\nautoargs.autocall(str_repeat, \"'still easy!\\n' 3\")", "args are easy!\nargs are easy!\nargs are easy!\nstill easy!\nstill easy!\nstill easy!\n" ], [ "import functools\nimport operator\n# varargs are supported too!\ndef product(*args: float):\n return functools.reduce(operator.mul, args, 1.0)\nprint(autoargs.autocall(product, [\"5\", \"10\", \"0.5\"]))\n\ndef join(delimiter, *args):\n return delimiter.join(args)\nprint(autoargs.autocall(join, [\", \", \"pretty easy\", \"right?\"]))", "25.0\npretty easy, right?\n" ], [ "def aggregate(*args: float, op: {'sum', 'mul'}):\n if op == \"sum\":\n return sum(args)\n elif op == \"mul\":\n return product(*args)\nautoargs.autocall(aggregate, [\"--help\"])", "usage: aggregate [-h] --op {sum,mul} [args [args ...]]\n\npositional arguments:\n args float\n\noptional arguments:\n -h, --help show this help message and exit\n --op {sum,mul}\n" ], [ "# kwargs are supported using command-line syntax\ndef land_of_defaults(a=\"default-a\", argb=\"b default\"):\n print(a, argb)\nautoargs.autocall(land_of_defaults, []) # => \"\" (no args in call)\nautoargs.autocall(land_of_defaults, ['-aOverride!']) # => \"-aOverride!\"\nautoargs.autocall(land_of_defaults, ['-a', 'Override!']) # => \"-a Override!\"\nautoargs.autocall(land_of_defaults, ['--argb', 'Override!']) # => \"--argb Override!\"\n# warning! if an argument has a default, it can only be given via this kwarg syntax", "default-a b default\nOverride! b default\nOverride! b default\ndefault-a Override!\n" ], [ "# if you want to require a kwarg, use a kwonly-arg\ndef required_arg(normal, default=\"boring\", *, required):\n print(normal, default, required)\nautoargs.autocall(required_arg, [\"normal\", \"--required\", \"val\"])\nautoargs.autocall(required_arg, [\"normal\"])", "normal boring val\n" ] ], [ [ "### Invalid Arg Handling\n\nSpeaking of errors, invalid arguments are caught by the parser. This means that you get CLI-like error messages, like the user would be expecting if this were a CLI interface.", "_____no_output_____" ] ], [ [ "def oops(arg: int):\n return \"%s is an integer!\" % arg\nautoargs.autocall(oops, [])", "usage: oops [-h] arg\noops: error: the following arguments are required: arg\n" ], [ "autoargs.autocall(oops, [\"spam\"])", "usage: oops [-h] arg\noops: error: argument arg: invalid int value: 'spam'\n" ], [ "autoargs.autocall(oops, [\"20\", \"spam\"])", "usage: oops [-h] arg\noops: error: unrecognized arguments: spam\n" ] ], [ [ "## parser", "_____no_output_____" ] ], [ [ "# if you want access to the parser, go right ahead!\nparser = autoargs.autoparser(myprint)\nparser", "_____no_output_____" ], [ "parsed = parser.parse_args([\"first\", \"second\"])\nparsed", "_____no_output_____" ], [ "vars(parsed)", "_____no_output_____" ] ], [ [ "## todo:\n\n - parsing a whole module/object (fns become subparsers)\n - using autoargs to call other module's fns from command line\n - setup.py\n - add to pypi\n - proper docs\n - all of the above with appropriate testing\n \nstay tuned for these and (potentially) other ideas! feel free to add issues", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
d0765f67b693c1e511425d45e28e6acbf833bb8e
566,209
ipynb
Jupyter Notebook
1_5_CNN_Layers/1. Conv Layer Visualization.ipynb
OanaGaskey/ComputerVision-Exercises
c897e42ec3beff4c6fc9d621cb21805b0c15377a
[ "MIT" ]
2
2020-03-27T19:09:36.000Z
2020-03-27T19:43:47.000Z
1_5_CNN_Layers/.ipynb_checkpoints/1. Conv Layer Visualization-checkpoint.ipynb
OanaGaskey/ComputerVision-Exercises
c897e42ec3beff4c6fc9d621cb21805b0c15377a
[ "MIT" ]
5
2021-03-19T11:46:47.000Z
2022-03-12T00:21:22.000Z
1_5_CNN_Layers/1. Conv Layer Visualization.ipynb
OanaGaskey/ComputerVision-Exercises
c897e42ec3beff4c6fc9d621cb21805b0c15377a
[ "MIT" ]
null
null
null
1,505.875
179,908
0.956458
[ [ [ "## Convolutional Layer\n\nIn this notebook, we visualize four filtered outputs (a.k.a. feature maps) of a convolutional layer.", "_____no_output_____" ], [ "### Import the image", "_____no_output_____" ] ], [ [ "import cv2\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# TODO: Feel free to try out your own images here by changing img_path\n# to a file path to another image on your computer!\nimg_path = 'images/udacity_sdc.png'\n#img_path = 'C:/Users/oanag/Pictures/2019/FranceCoteDAzur_2019-04-26/FranceCoteDAzur-134.JPG'\n# load color image \nbgr_img = cv2.imread(img_path)\n# convert to grayscale\ngray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY)\n\n# normalize, rescale entries to lie in [0,1]\ngray_img = gray_img.astype(\"float32\")/255\n\n# plot image\nplt.imshow(gray_img, cmap='gray')\nplt.show()", "_____no_output_____" ] ], [ [ "### Define and visualize the filters", "_____no_output_____" ] ], [ [ "import numpy as np\n\n## TODO: Feel free to modify the numbers here, to try out another filter!\nfilter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]])\n\nprint('Filter shape: ', filter_vals.shape)\n#nicely print matrix\nprint(filter_vals)\n", "Filter shape: (4, 4)\n[[-1 -1 1 1]\n [-1 -1 1 1]\n [-1 -1 1 1]\n [-1 -1 1 1]]\n" ], [ "# Defining four different filters, \n# all of which are linear combinations of the `filter_vals` defined above\n\n# define four filters\nfilter_1 = filter_vals\nfilter_2 = -filter_1\nfilter_3 = filter_1.T\nfilter_4 = -filter_3\nfilters = np.array([filter_1, filter_2, filter_3, filter_4])\n\n# For an example, print out the values of filter 1\nprint(filters)", "[[[-1 -1 1 1]\n [-1 -1 1 1]\n [-1 -1 1 1]\n [-1 -1 1 1]]\n\n [[ 1 1 -1 -1]\n [ 1 1 -1 -1]\n [ 1 1 -1 -1]\n [ 1 1 -1 -1]]\n\n [[-1 -1 -1 -1]\n [-1 -1 -1 -1]\n [ 1 1 1 1]\n [ 1 1 1 1]]\n\n [[ 1 1 1 1]\n [ 1 1 1 1]\n [-1 -1 -1 -1]\n [-1 -1 -1 -1]]]\n" ], [ "### do not modify the code below this line ###\n\n# visualize all four filters\nfig = plt.figure(figsize=(10, 5))\nfor i in range(4):\n ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[])\n ax.imshow(filters[i], cmap='gray')\n ax.set_title('Filter %s' % str(i+1))\n width, height = filters[i].shape\n for x in range(width):\n for y in range(height):\n ax.annotate(str(filters[i][x][y]), xy=(y,x),\n horizontalalignment='center',\n verticalalignment='center',\n color='white' if filters[i][x][y]<0 else 'black')", "_____no_output_____" ] ], [ [ "### Define a convolutional layer \n\nInitialize a single convolutional layer so that it contains all your created filters. Note that you are not training this network; you are initializing the weights in a convolutional layer so that you can visualize what happens after a forward pass through this network!", "_____no_output_____" ] ], [ [ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n \n# define a neural network with a single convolutional layer with four filters\nclass Net(nn.Module):\n \n def __init__(self, weight):\n super(Net, self).__init__()\n # initializes the weights of the convolutional layer to be the weights of the 4 defined filters\n k_height, k_width = weight.shape[2:]\n # assumes there are 4 grayscale filters\n self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False)\n self.conv.weight = torch.nn.Parameter(weight)\n\n def forward(self, x):\n # calculates the output of a convolutional layer\n # pre- and post-activation\n conv_x = self.conv(x)\n activated_x = F.relu(conv_x)\n \n # returns both layers\n return conv_x, activated_x\n \n# instantiate the model and set the weights\nweight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor)\nmodel = Net(weight)\n\n# print out the layer in the network\nprint(model)", "Net(\n (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False)\n)\n" ] ], [ [ "### Visualize the output of each filter\n\nFirst, we'll define a helper function, `viz_layer` that takes in a specific layer and number of filters (optional argument), and displays the output of that layer once an image has been passed through.", "_____no_output_____" ] ], [ [ "# helper function for visualizing the output of a given layer\n# default number of filters is 4\ndef viz_layer(layer, n_filters= 4):\n fig = plt.figure(figsize=(20, 20))\n \n for i in range(n_filters):\n ax = fig.add_subplot(1, n_filters, i+1, xticks=[], yticks=[])\n # grab layer outputs\n ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray')\n ax.set_title('Output %s' % str(i+1))", "_____no_output_____" ] ], [ [ "Let's look at the output of a convolutional layer, before and after a ReLu activation function is applied.", "_____no_output_____" ] ], [ [ "# plot original image\nplt.imshow(gray_img, cmap='gray')\n\n# visualize all filters\nfig = plt.figure(figsize=(12, 6))\nfig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05)\nfor i in range(4):\n ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[])\n ax.imshow(filters[i], cmap='gray')\n ax.set_title('Filter %s' % str(i+1))\n\n \n# convert the image into an input Tensor\ngray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1)\n\n# get the convolutional layer (pre and post activation)\nconv_layer, activated_layer = model(gray_img_tensor)\n\n# visualize the output of a conv layer\nviz_layer(conv_layer)", "_____no_output_____" ], [ "# after a ReLu is applied\n# visualize the output of an activated conv layer\nviz_layer(activated_layer)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d076672504afc858e112542332b264e729608b0e
1,788
ipynb
Jupyter Notebook
challenge problems/Challenge Problem 02 Student Version.ipynb
shaheen19/Adv_Py_Scripting_for_GIS_Course
d5e3109c47b55d10a7b8c90e5eac837f659af200
[ "Apache-2.0" ]
7
2020-01-22T14:22:57.000Z
2021-12-22T11:33:40.000Z
challenge problems/Challenge Problem 02 Student Version.ipynb
achapkowski/Adv_Py_Scripting_for_GIS_Course
d5e3109c47b55d10a7b8c90e5eac837f659af200
[ "Apache-2.0" ]
null
null
null
challenge problems/Challenge Problem 02 Student Version.ipynb
achapkowski/Adv_Py_Scripting_for_GIS_Course
d5e3109c47b55d10a7b8c90e5eac837f659af200
[ "Apache-2.0" ]
2
2020-04-22T11:33:01.000Z
2021-01-04T21:16:04.000Z
20.089888
110
0.526846
[ [ [ "# Challenge Problem 02 \n# Working with Datetimes", "_____no_output_____" ], [ "1. Write a Python program to add year(s) with a given date and display the new date. Go to the editor\n\n```\nSample Data : (addYears is the user defined function name)\nprint(addYears(datetime.date(2015,1,1), -1))\nprint(addYears(datetime.date(2015,1,1), 0))\nprint(addYears(datetime.date(2015,1,1), 2))\nprint(addYears(datetime.date(2000,2,29),1))\n\nExpected Output :\n2014-01-01\n2015-01-01\n2017-01-01\n2001-03-01\n```", "_____no_output_____" ] ], [ [ "import datetime\n# insert code here", "_____no_output_____" ] ], [ [ "2. Write a Python program to get the date of the last Tuesday.", "_____no_output_____" ] ], [ [ "import datetime\n# insert code here", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0767166d30485062cb3094115d56859638ad9c5
968,707
ipynb
Jupyter Notebook
ipynb/Sierpinski.ipynb
kajalkatiyar/pytudes
0bb9b2fe9ab219fb776bca498f6d34cb2f8db65e
[ "MIT" ]
1
2019-05-10T09:16:23.000Z
2019-05-10T09:16:23.000Z
ipynb/Sierpinski.ipynb
kajalkatiyar/pytudes
0bb9b2fe9ab219fb776bca498f6d34cb2f8db65e
[ "MIT" ]
null
null
null
ipynb/Sierpinski.ipynb
kajalkatiyar/pytudes
0bb9b2fe9ab219fb776bca498f6d34cb2f8db65e
[ "MIT" ]
2
2019-12-06T14:45:40.000Z
2019-12-09T07:00:07.000Z
2,883.056548
209,330
0.949895
[ [ [ "# A Chaos Game with Triangles\n\nJohn D. Cook [proposed](https://www.johndcook.com/blog/2017/07/08/the-chaos-game-and-the-sierpinski-triangle/) an interesting \"game\" from the book *[Chaos and Fractals](https://smile.amazon.com/Chaos-Fractals-New-Frontiers-Science/dp/0387202293)*: start at a vertex of an equilateral triangle. Then move to a new point halfway between the current point and one of the three vertexes of the triangle, chosen at random. Repeat to create *N* points, and plot them. What do you get? \n\nI'll refactor Cook's code a bit and then we'll see:", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport random\n\ndef random_walk(vertexes, N):\n \"Walk halfway from current point towards a random vertex; repeat for N points.\"\n points = [random.choice(vertexes)]\n for _ in range(N-1):\n points.append(midpoint(points[-1], random.choice(vertexes)))\n return points\n\ndef show_walk(vertexes, N=5000):\n \"Walk halfway towards a random vertex for N points; show reults.\"\n Xs, Ys = transpose(random_walk(vertexes, N))\n Xv, Yv = transpose(vertexes)\n plt.plot(Xs, Ys, 'r.')\n plt.plot(Xv, Yv, 'bs')\n plt.gca().set_aspect('equal')\n plt.gcf().set_size_inches(9, 9)\n plt.axis('off')\n plt.show()\n \ndef midpoint(p, q): return ((p[0] + q[0])/2, (p[1] + q[1])/2)\n\ndef transpose(matrix): return zip(*matrix)\n\ntriangle = ((0, 0), (0.5, (3**0.5)/2), (1, 0))", "_____no_output_____" ], [ "show_walk(triangle, 20)", "_____no_output_____" ] ], [ [ "OK, the first 20 points don't tell me much. What if I try 20,000 points?", "_____no_output_____" ] ], [ [ "show_walk(triangle, 20000)", "_____no_output_____" ] ], [ [ "Wow! The [Sierpinski Triangle](https://en.wikipedia.org/wiki/Sierpinski_triangle)! \nWhat happens if we start with a different set of vertexes, like a square?", "_____no_output_____" ] ], [ [ "square = ((0, 0), (0, 1), (1, 0), (1, 1))\n\nshow_walk(square)", "_____no_output_____" ] ], [ [ "There doesn't seem to be any structure there. Let's try again to make sure:", "_____no_output_____" ] ], [ [ "show_walk(square, 20000)", "_____no_output_____" ] ], [ [ "I'm still not seeing anything but random points. How about a right triangle?", "_____no_output_____" ] ], [ [ "right_triangle = ((0, 0), (0, 1), (1, 0))\n\nshow_walk(right_triangle, 20000)", "_____no_output_____" ] ], [ [ "We get a squished Serpinski triangle. How about a pentagon? (I'm lazy so I had Wolfram Alpha [compute the vertexes](https://www.wolframalpha.com/input/?i=vertexes+of+regular+pentagon).)", "_____no_output_____" ] ], [ [ "pentagon = ((0.5, -0.688), (0.809, 0.262), (0., 0.850), (-0.809, 0.262), (-0.5, -0.688))\n\nshow_walk(pentagon)", "_____no_output_____" ] ], [ [ "To clarify, let's try again with different numbers of points:", "_____no_output_____" ] ], [ [ "show_walk(pentagon, 10000)", "_____no_output_____" ], [ "show_walk(pentagon, 20000)", "_____no_output_____" ] ], [ [ "I definitely see a central hole, and five secondary holes surrounding that, and then, maybe 15 holes surrounding those? Or maybe not 15; hard to tell. Is a \"Sierpinski Pentagon\" a thing? I hadn't heard of it but a [quick search](https://www.google.com/search?q=sierpinski+pentagon) reveals that yes indeed, it is [a thing](http://ecademy.agnesscott.edu/~lriddle/ifs/pentagon/sierngon.htm), and it does have 15 holes surrounding the 5 holes. Let's try the hexagon:", "_____no_output_____" ] ], [ [ "hexagon = ((0.5, -0.866), (1, 0), (0.5, 0.866), (-0.5, 0.866), (-1, 0), (-0.5, -0.866))\n\nshow_walk(hexagon)", "_____no_output_____" ], [ "show_walk(hexagon, 20000)", "_____no_output_____" ] ], [ [ "You can see a little of the six-fold symmetry, but it is not as clear as the triangle and pentagon.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]