code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def setModelPath(self, path : str) -> None: """ Sets the path to the pretrained weight. """ if os.path.isfile(path): extension_check(path) self.__model_path = path self.__model_loaded = False else: raise ValueError( ...
Sets the path to the pretrained weight.
setModelPath
python
OlafenwaMoses/ImageAI
imageai/Classification/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/Custom/__init__.py
MIT
def classifyImage(self, image_input: Union[str, np.ndarray, Image.Image], result_count: int) -> Tuple[List[str], List[float]]: """ 'classifyImage()' function is used to classify a given image by receiving the following arguments: * image_input: file path, numpy array or PIL image of the inpu...
'classifyImage()' function is used to classify a given image by receiving the following arguments: * image_input: file path, numpy array or PIL image of the input image. * result_count (optional) , the number of classifications to be sent which must be whole numbers between 1 and total ...
classifyImage
python
OlafenwaMoses/ImageAI
imageai/Classification/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/Custom/__init__.py
MIT
def __load_image(self, image_path : str) -> Tuple[List[str], torch.Tensor]: """ Loads image/images from the given path. If image_path is a directory, this function only load the images in the directory (it does not visit the sub- directories). This function also convert the loaded image/...
Loads image/images from the given path. If image_path is a directory, this function only load the images in the directory (it does not visit the sub- directories). This function also convert the loaded image/images to the specification expected by the MobileNetV2 architecture.
__load_image
python
OlafenwaMoses/ImageAI
imageai/densenet121/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/densenet121/__init__.py
MIT
def load_model(self) -> None: """ Loads the mobilenet vison weight into the model architecture. """ if not self.__has_loaded_weights: try: import re state_dict = torch.load(self.__model_path, map_location=self.__device) # '.'s a...
Loads the mobilenet vison weight into the model architecture.
load_model
python
OlafenwaMoses/ImageAI
imageai/densenet121/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/densenet121/__init__.py
MIT
def classify(self, image_path : str, top_n : int = 5, verbose : bool = True) -> List[List[Tuple[str, str]]]: """ Classfies image/images according to the classes provided by imagenet. Parameters: ----------- image_path: a path to a single image or a path to a directory contai...
Classfies image/images according to the classes provided by imagenet. Parameters: ----------- image_path: a path to a single image or a path to a directory containing images. If image_path is a path to a file, this functions classifie...
classify
python
OlafenwaMoses/ImageAI
imageai/densenet121/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/densenet121/__init__.py
MIT
def __load_image_retinanet(self, input_image : str) -> Tuple[List[str], List[torch.Tensor], List[torch.Tensor]]: """ Loads image from the given path. """ allowed_file_extensions = ["jpg", "jpeg", "png"] images = [] scaled_images = [] fnames = [] d...
Loads image from the given path.
__load_image_retinanet
python
OlafenwaMoses/ImageAI
imageai/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/__init__.py
MIT
def setModelTypeAsYOLOv3(self): """ 'setModelTypeAsYOLOv3()' is used to set the model type to the YOLOv3 model. :return: """ self.__anchors = self.__anchors_yolov3 self.__model_type = "yolov3"
'setModelTypeAsYOLOv3()' is used to set the model type to the YOLOv3 model. :return:
setModelTypeAsYOLOv3
python
OlafenwaMoses/ImageAI
imageai/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/__init__.py
MIT
def setModelTypeAsTinyYOLOv3(self): """ 'setModelTypeAsTinyYOLOv3()' is used to set the model type to the TinyYOLOv3 model. :return: """ self.__anchors = self.__anchors_tiny_yolov3 self.__model_type = "tiny-yolov3"
'setModelTypeAsTinyYOLOv3()' is used to set the model type to the TinyYOLOv3 model. :return:
setModelTypeAsTinyYOLOv3
python
OlafenwaMoses/ImageAI
imageai/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/__init__.py
MIT
def setModelTypeAsRetinaNet(self): """ 'setModelTypeAsRetinaNet()' is used to set the model type to the RetinaNet model. :return: """ self.__anchors = self.__anchors_tiny_yolov3 self.__model_type = "retinanet"
'setModelTypeAsRetinaNet()' is used to set the model type to the RetinaNet model. :return:
setModelTypeAsRetinaNet
python
OlafenwaMoses/ImageAI
imageai/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/__init__.py
MIT
def setModelPath(self, path: str) -> None: """ 'setModelPath()' function is required and is used to set the file path to the model adopted from the list of the available 3 model types. The model path must correspond to the model type. :param model_path: :return: """ ...
'setModelPath()' function is required and is used to set the file path to the model adopted from the list of the available 3 model types. The model path must correspond to the model type. :param model_path: :return:
setModelPath
python
OlafenwaMoses/ImageAI
imageai/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/__init__.py
MIT
def CustomObjects(self, **kwargs): """ The 'CustomObjects()' function allows you to handpick the type of objects ( from the COCO classes ) you want to detect from an image. The objects are pre-initiated in the function variables and predefined as 'False', which you can easily set to tru...
The 'CustomObjects()' function allows you to handpick the type of objects ( from the COCO classes ) you want to detect from an image. The objects are pre-initiated in the function variables and predefined as 'False', which you can easily set to true for any number of objects available. This fu...
CustomObjects
python
OlafenwaMoses/ImageAI
imageai/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/__init__.py
MIT
def detectObjectsFromImage(self, input_image: Union[str, np.ndarray, Image.Image], output_image_path: str=None, output_type: str ="file", extract_detected_objects: bool=False, minimum_percentage_probability: int=50, display_percentage_proba...
Detects objects in an image using the unique classes provided by COCO. :param input_image: path to an image file, cv2 image or PIL image :param output_image_path: path to save input image with predictions rendered :param output_type: type of output for rendered image. Acceptabl...
detectObjectsFromImage
python
OlafenwaMoses/ImageAI
imageai/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/__init__.py
MIT
def detectObjectsFromVideo(self, input_file_path="", camera_input=None, output_file_path="", frames_per_second=20, frame_detection_interval=1, minimum_percentage_probability=50, log_progress=False, display_percentage_probability=True, display_object_name=Tru...
'detectObjectsFromVideo()' function is used to detect objects observable in the given video path or a camera input: * input_file_path , which is the file path to the input video. It is required only if 'camera_input' is not set * camera_input , allows you to parse in camera input for live video...
detectObjectsFromVideo
python
OlafenwaMoses/ImageAI
imageai/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/__init__.py
MIT
def setDataDirectory(self, data_directory: str): """ 'setDataDirectory()' is required to set the path to which the data/dataset to be used for training is kept. The input dataset must be in the YOLO format. The directory can have any name, but it must have 'train' and 'validation' sub-directory....
'setDataDirectory()' is required to set the path to which the data/dataset to be used for training is kept. The input dataset must be in the YOLO format. The directory can have any name, but it must have 'train' and 'validation' sub-directory. In the 'train' and 'validation' sub-directories, there must...
setDataDirectory
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/__init__.py
MIT
def setTrainConfig(self, object_names_array: List[str], batch_size: int=4, num_experiments=100, train_from_pretrained_model: str = None): """ 'setTrainConfig()' function allows you to set the properties for the training instances. It accepts the following values: - object_names_array , this is a...
'setTrainConfig()' function allows you to set the properties for the training instances. It accepts the following values: - object_names_array , this is an array of the names of the different objects in your dataset, in the index order your dataset is annotated - batch_size (optional), this is...
setTrainConfig
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/__init__.py
MIT
def trainModel(self) -> None: """ 'trainModel()' function starts the actual model training. Once the training starts, the training instance creates 3 sub-folders in your dataset folder which are: - json, where the JSON configuration file for using your trained model is stored - ...
'trainModel()' function starts the actual model training. Once the training starts, the training instance creates 3 sub-folders in your dataset folder which are: - json, where the JSON configuration file for using your trained model is stored - models, where your trained models are sto...
trainModel
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/__init__.py
MIT
def __load_image_yolo(self, input_image : Union[str, np.ndarray, Image.Image]) -> Tuple[List[str], List[np.ndarray], torch.Tensor, torch.Tensor]: """ Loads image/images from the given path. If the given path is a directory, this function only load the images in the directory (it does noot visit ...
Loads image/images from the given path. If the given path is a directory, this function only load the images in the directory (it does noot visit the subdirectories).
__load_image_yolo
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/__init__.py
MIT
def loadModel(self) -> None: """ Loads the pretrained weights in the specified model path. """ self.__load_classes_and_anchors() if self.__model_type == "yolov3": self.__model = YoloV3( anchors=self.__anchors, num_classes=len(self.__cl...
Loads the pretrained weights in the specified model path.
loadModel
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/__init__.py
MIT
def generate_anchors(dataset, n=9, img_size=416, thr=4.0, gen=1000, verbose=True): """ Creates kmeans-evolved anchors from training dataset Arguments: dataset: a loaded dataset i.e. subclass of torch.utils.data.Dataset n: number of anchors img_size: image size used for t...
Creates kmeans-evolved anchors from training dataset Arguments: dataset: a loaded dataset i.e. subclass of torch.utils.data.Dataset n: number of anchors img_size: image size used for training thr: anchor-label wh ratio threshold used for training, default=4.0 ...
generate_anchors
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/yolo/custom_anchors.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/yolo/custom_anchors.py
MIT
def __xywhn2xyxy(self, nlabel : torch.Tensor, width : int, height : int) -> torch.Tensor: """ Transformed label from normalized center_x, center_y, width, height to x_1, y_1, x_2, y_2 """ label = nlabel.clone() label[:, 1] = (nlabel[:, 1] - (nlabel[:, 3] / 2)) * width ...
Transformed label from normalized center_x, center_y, width, height to x_1, y_1, x_2, y_2
__xywhn2xyxy
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/yolo/dataset.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/yolo/dataset.py
MIT
def __process_label(self, label : np.ndarray, image_width : int, image_height : int) -> torch.Tensor: """ Process corresponding label and resize the ground truth bounding boxes to match the dimension of the resizes image. """ #max_box = 50 scaling_factor = min( ...
Process corresponding label and resize the ground truth bounding boxes to match the dimension of the resizes image.
__process_label
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/yolo/dataset.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/yolo/dataset.py
MIT
def ap_per_class(tp, conf, pred_cls, target_cls): """ Compute the average precision, given the recall and precision curves. Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. # Arguments tp: True positives (nparray, nx1 or nx10). conf: Objectness value from 0-1 (nparray). ...
Compute the average precision, given the recall and precision curves. Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. # Arguments tp: True positives (nparray, nx1 or nx10). conf: Objectness value from 0-1 (nparray). pred_cls: Predicted object classes (nparray). ...
ap_per_class
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/yolo/metric.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/yolo/metric.py
MIT
def xywh2xyxy(box_coord : torch.Tensor): """ Convert bounding box coordinates from center_x, center_y, width, height to x_1, y_1, x_2, x_3 """ n = box_coord.clone() n[:, 0] = (box_coord[:, 0] - (box_coord[:, 2] / 2)) n[:, 1] = (box_coord[:, 1] - (box_coord[:, 3] / 2)) n[:, 2] = (box_coor...
Convert bounding box coordinates from center_x, center_y, width, height to x_1, y_1, x_2, x_3
xywh2xyxy
python
OlafenwaMoses/ImageAI
imageai/Detection/Custom/yolo/validate.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Detection/Custom/yolo/validate.py
MIT
def read_image(path: str, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor: """ Reads a JPEG or PNG image into a 3 dimensional RGB or grayscale Tensor. Optionally converts the image to the desired format. The values of the output tensor are uint8 in [0, 255]. Args:...
Reads a JPEG or PNG image into a 3 dimensional RGB or grayscale Tensor. Optionally converts the image to the desired format. The values of the output tensor are uint8 in [0, 255]. Args: path (str): path of the JPEG or PNG image. mode (ImageReadMode): the read mo...
read_image
python
OlafenwaMoses/ImageAI
imageai/retinanet/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/retinanet/utils.py
MIT
def draw_bbox_and_label(x : torch.Tensor, label : str, img : np.ndarray) -> np.ndarray: """ Draws the predicted bounding boxes on the original image. """ x1,y1,x2,y2 = tuple(map(int, x)) if x is not None: img = cv.rectangle(img, (x1,y1), (x2,y2), (0, 255, 0), 1) t_size = cv.getTextSize(l...
Draws the predicted bounding boxes on the original image.
draw_bbox_and_label
python
OlafenwaMoses/ImageAI
imageai/yolov3/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/yolov3/utils.py
MIT
def letterbox_image( image : np.ndarray, inp_dim : Tuple[int, int]) -> np.ndarray: """ Resizes images into the dimension expected by the network. This function fills extra spaces in the image with grayscale, if the image is smaller than the expected dimesion. This implementation keep...
Resizes images into the dimension expected by the network. This function fills extra spaces in the image with grayscale, if the image is smaller than the expected dimesion. This implementation keeps the aspect ration of the original image.
letterbox_image
python
OlafenwaMoses/ImageAI
imageai/yolov3/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/yolov3/utils.py
MIT
def prepare_image( image : np.ndarray, inp_dim : Tuple[int, int]) -> torch.Tensor: """ Prepared the input to match the expectation of the network. """ img = letterbox_image(image, inp_dim) img = img[:, :, ::-1].transpose((2, 0, 1)).copy() img = torch.from_numpy(img).float().div(2...
Prepared the input to match the expectation of the network.
prepare_image
python
OlafenwaMoses/ImageAI
imageai/yolov3/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/yolov3/utils.py
MIT
def bbox_iou(bbox1 : torch.Tensor, bbox2 : torch.Tensor, device="cpu"): """ Returns the IoU value of overlapping boxes """ b1_x1, b1_y1, b1_x2, b1_y2 = bbox1[:, 0], bbox1[:, 1], bbox1[:, 2], bbox1[:, 3] b2_x1, b2_y1, b2_x2, b2_y2 = bbox2[:, 0], bbox2[:, 1], bbox2[:, 2], bbox2[:, 3] # intersecti...
Returns the IoU value of overlapping boxes
bbox_iou
python
OlafenwaMoses/ImageAI
imageai/yolov3/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/yolov3/utils.py
MIT
def transform_prediction( pred : torch.Tensor, inp_dim : int, anchors : Union[List[int], Tuple[int, ...], torch.Tensor], num_classes : int, device : str = "cpu" ) -> torch.Tensor: """ Transforms the predictions of the convolutional layers from batch_si...
Transforms the predictions of the convolutional layers from batch_size x (3 * 5+num_classes) x grid_size x grid_size to batch_size x (grid_size * grid_size * anchors) x num_classes aids the concatenation of the prediction at the three detection layers and also for easy representatio...
transform_prediction
python
OlafenwaMoses/ImageAI
imageai/yolov3/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/yolov3/utils.py
MIT
def get_predictions( pred : torch.Tensor, num_classes : int, objectness_confidence : float = 0.5, nms_confidence_level : float = 0.4, device : str = "cpu") -> Union[torch.Tensor, int]: """ This function filters the bounding boxes predicted by the network by first disc...
This function filters the bounding boxes predicted by the network by first discarding bounding boxes that has low objectness score, and then proceeds to filter overlapping bounding boxes using the non-maximum suppression algorithm. Parameters: ----------- pred: a tensor (pred...
get_predictions
python
OlafenwaMoses/ImageAI
imageai/yolov3/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/yolov3/utils.py
MIT
def loadModel(self, classification_speed="normal"): """ 'loadModel()' function is used to load the model structure into the program from the file path defined in the setModelPath() function. This function receives an optional value which is "classification_speed". The value is used to re...
'loadModel()' function is used to load the model structure into the program from the file path defined in the setModelPath() function. This function receives an optional value which is "classification_speed". The value is used to reduce the time it takes to classify an image, down to about 50% ...
loadModel
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Classification/__init__.py
MIT
def classifyImage(self, image_input, result_count=5, input_type="file"): """ 'classifyImage()' function is used to classify a given image by receiving the following arguments: * input_type (optional) , the type of input to be parsed. Acceptable values are "file", "array" and "stream" ...
'classifyImage()' function is used to classify a given image by receiving the following arguments: * input_type (optional) , the type of input to be parsed. Acceptable values are "file", "array" and "stream" * image_input , file path/numpy array/image file stream of the image. ...
classifyImage
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Classification/__init__.py
MIT
def setDataDirectory(self, data_directory="", train_subdirectory="train", test_subdirectory="test", models_subdirectory="models", json_subdirectory="json"): """ 'setDataDirectory()' - data_directory , is required to set the path to which the data/dataset to be used for ...
'setDataDirectory()' - data_directory , is required to set the path to which the data/dataset to be used for training is kept. The directory can have any name, but it must have 'train' and 'test' sub-directory. In the 'train' and 'test' sub-directories, there must be ...
setDataDirectory
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Classification/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Classification/Custom/__init__.py
MIT
def trainModel(self, num_objects, num_experiments=200, enhance_data=False, batch_size = 32, initial_learning_rate=1e-3, show_network_summary=False, training_image_size = 224, continue_from_model=None, transfer_from_model=None, transfer_with_full_training=True, initial_num_objects = None, save_full_model = False): ...
'trainModel()' function starts the model actual training. It accepts the following values: - num_objects , which is the number of classes present in the dataset that is to be used for training - num_experiments , also known as epochs, it is the number of times the network will train on all the ...
trainModel
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Classification/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Classification/Custom/__init__.py
MIT
def loadFullModel(self, classification_speed="normal", num_objects=10): """ 'loadFullModel()' function is used to load the model structure into the program from the file path defined in the setModelPath() function. As opposed to the 'loadModel()' function, you don't need to specify the model typ...
'loadFullModel()' function is used to load the model structure into the program from the file path defined in the setModelPath() function. As opposed to the 'loadModel()' function, you don't need to specify the model type. This means you can load any Keras model trained with or without ImageAI and perf...
loadFullModel
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Classification/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Classification/Custom/__init__.py
MIT
def setModelPath(self, model_path): """ 'setModelPath()' function is required and is used to set the file path to a RetinaNet object detection model trained on the COCO dataset. :param model_path: :return: """ if (self.__modelPathAdded == False): ...
'setModelPath()' function is required and is used to set the file path to a RetinaNet object detection model trained on the COCO dataset. :param model_path: :return:
setModelPath
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/__init__.py
MIT
def loadModel(self, detection_speed="normal"): """ 'loadModel()' function is required and is used to load the model structure into the program from the file path defined in the setModelPath() function. This function receives an optional value which is "detection_speed". ...
'loadModel()' function is required and is used to load the model structure into the program from the file path defined in the setModelPath() function. This function receives an optional value which is "detection_speed". The value is used to reduce the time it takes to de...
loadModel
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/__init__.py
MIT
def detectObjectsFromImage(self, input_image="", output_image_path="", input_type="file", output_type="file", extract_detected_objects=False, minimum_percentage_probability=50, display_percentage_probability=True, display_object_name=True, ...
'detectObjectsFromImage()' function is used to detect objects observable in the given image path: * input_image , which can be a filepath, image numpy array or image file stream * output_image_path (only if output_type = file) , file path to the output image that wil...
detectObjectsFromImage
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/__init__.py
MIT
def CustomObjects(self, person=False, bicycle=False, car=False, motorcycle=False, airplane=False, bus=False, train=False, truck=False, boat=False, traffic_light=False, fire_hydrant=False, stop_sign=False, parking_meter=False, bench=False, bird=False, cat...
The 'CustomObjects()' function allows you to handpick the type of objects you want to detect from an image. The objects are pre-initiated in the function variables and predefined as 'False', which you can easily set to true for any number of ob...
CustomObjects
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/__init__.py
MIT
def setModelPath(self, model_path): """ 'setModelPath()' function is required and is used to set the file path to a RetinaNet, YOLOv3 or TinyYOLOv3 object detection model trained on the COCO dataset. :param model_path: :return: """ if (self.__modelPathAdded...
'setModelPath()' function is required and is used to set the file path to a RetinaNet, YOLOv3 or TinyYOLOv3 object detection model trained on the COCO dataset. :param model_path: :return:
setModelPath
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/__init__.py
MIT
def detectObjectsFromVideo(self, input_file_path="", camera_input=None, output_file_path="", frames_per_second=20, frame_detection_interval=1, minimum_percentage_probability=50, log_progress=False, display_percentage_probability=True, display_object_name=Tru...
'detectObjectsFromVideo()' function is used to detect objects observable in the given video path or a camera input: * input_file_path , which is the file path to the input video. It is required only if 'camera_input' is not set * camera_input , allows you to parse in camera ...
detectObjectsFromVideo
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/__init__.py
MIT
def CustomObjects(self, person=False, bicycle=False, car=False, motorcycle=False, airplane=False, bus=False, train=False, truck=False, boat=False, traffic_light=False, fire_hydrant=False, stop_sign=False, parking_meter=False, bench=False, bird=False, cat...
The 'CustomObjects()' function allows you to handpick the type of objects you want to detect from a video. The objects are pre-initiated in the function variables and predefined as 'False', which you can easily set to true for any number of obj...
CustomObjects
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/__init__.py
MIT
def setDataDirectory(self, data_directory): """ 'setDataDirectory()' is required to set the path to which the data/dataset to be used for training is kept. The directory can have any name, but it must have 'train' and 'validation' sub-directory. In the 'train' and 'va...
'setDataDirectory()' is required to set the path to which the data/dataset to be used for training is kept. The directory can have any name, but it must have 'train' and 'validation' sub-directory. In the 'train' and 'validation' sub-directories, there must be 'images' and 'a...
setDataDirectory
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def setGpuUsage(self, train_gpus): """ 'setGpuUsage' function allows you to set the GPUs to be used while training train_gpu can be: - an integer, indicating the number of GPUs to use - a list of integers, indicating the id of the GPUs to be used - a string, indicating th...
'setGpuUsage' function allows you to set the GPUs to be used while training train_gpu can be: - an integer, indicating the number of GPUs to use - a list of integers, indicating the id of the GPUs to be used - a string, indicating the it og the id of the GPUs to be used, separat...
setGpuUsage
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def setTrainConfig(self, object_names_array, batch_size=4, num_experiments=100, train_from_pretrained_model=""): """ 'setTrainConfig()' function allows you to set the properties for the training instances. It accepts the following values: - object_names_array , this is an array of the names ...
'setTrainConfig()' function allows you to set the properties for the training instances. It accepts the following values: - object_names_array , this is an array of the names of the different objects in your dataset - batch_size (optional), this is the batch size for the training instance ...
setTrainConfig
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def trainModel(self): """ 'trainModel()' function starts the actual model training. Once the training starts, the training instance creates 3 sub-folders in your dataset folder which are: - json, where the JSON configuration file for using your trained model is stored - models...
'trainModel()' function starts the actual model training. Once the training starts, the training instance creates 3 sub-folders in your dataset folder which are: - json, where the JSON configuration file for using your trained model is stored - models, where your trained models are st...
trainModel
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def evaluateModel(self, model_path, json_path, batch_size=4, iou_threshold=0.5, object_threshold=0.2, nms_threshold=0.45): """ 'evaluateModel()' is used to obtain the mAP metrics for your model(s). It accepts the following values: - model_path ( model file or folder), this value can be the par...
'evaluateModel()' is used to obtain the mAP metrics for your model(s). It accepts the following values: - model_path ( model file or folder), this value can be the part to your model file or the path to the folder containing all your saved model files - json_path , this is the path the the ...
evaluateModel
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def loadModel(self): """ 'loadModel' is used to load the model into the CustomObjectDetection class :return: None """ if self.__model_type == "yolov3": detection_model_json = json.load(open(self.__detection_config_json_path)) self.__model_labels = detec...
'loadModel' is used to load the model into the CustomObjectDetection class :return: None
loadModel
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def detectObjectsFromImage(self, input_image="", output_image_path="", input_type="file", output_type="file", extract_detected_objects=False, minimum_percentage_probability=50, nms_treshold=0.4, display_percentage_probability=True, display_object_name=True, ...
'detectObjectsFromImage()' function is used to detect objects observable in the given image: * input_image , which can be a filepath or image numpy array in BGR * output_image_path (only if output_type = file) , file path to the output image that will contain the detect...
detectObjectsFromImage
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def loadModel(self): """ 'loadModel' is used to load the model into the CustomVideoObjectDetection class :return: """ if (self.__model_loaded == False): if(self.__model_type == "yolov3"): detector = CustomObjectDetection() detector.se...
'loadModel' is used to load the model into the CustomVideoObjectDetection class :return:
loadModel
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def detectObjectsFromVideo(self, input_file_path="", camera_input=None, output_file_path="", frames_per_second=20, frame_detection_interval=1, minimum_percentage_probability=50, log_progress=False, display_percentage_probability=True, display_object_name=Tru...
'detectObjectsFromVideo()' function is used to detect objects observable in the given video path or a camera input: * input_file_path , which is the file path to the input video. It is required only if 'camera_input' is not set * camera_input , allows you to parse in camera input for l...
detectObjectsFromVideo
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def label_color(self, label): """ Return a color from a set of predefined colors. Contains 80 colors in total. Args label: The label to get the color for. Returns A list of three values representing a RGB color. If no color is defined for a certain label, t...
Return a color from a set of predefined colors. Contains 80 colors in total. Args label: The label to get the color for. Returns A list of three values representing a RGB color. If no color is defined for a certain label, the color green is returned and a warning ...
label_color
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/__init__.py
MIT
def get_color(label): """ Return a color from a set of predefined colors. Contains 80 colors in total. code originally from https://github.com/fizyr/keras-retinanet/ Args label: The label to get the color for. Returns A list of three values representing a RGB color. """ if label ...
Return a color from a set of predefined colors. Contains 80 colors in total. code originally from https://github.com/fizyr/keras-retinanet/ Args label: The label to get the color for. Returns A list of three values representing a RGB color.
get_color
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/utils/colors.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/utils/colors.py
MIT
def evaluate(model, generator, iou_threshold, obj_thresh, nms_thresh, net_h=416, net_w=416, save_path=None): """ Evaluate a given dataset using a given model. code originally from https://github.com/fizyr/keras-retinanet...
Evaluate a given dataset using a given model. code originally from https://github.com/fizyr/keras-retinanet # Arguments model : The model to evaluate. generator : The generator that represents the dataset to evaluate. iou_threshold : The threshold used to consider whe...
evaluate
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/utils/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/utils/utils.py
MIT
def compute_overlap(a, b): """ Code originally from https://github.com/rbgirshick/py-faster-rcnn. Parameters ---------- a: (N, 4) ndarray of float b: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ area = (b[:, 2] ...
Code originally from https://github.com/rbgirshick/py-faster-rcnn. Parameters ---------- a: (N, 4) ndarray of float b: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes
compute_overlap
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Detection/Custom/utils/utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Detection/Custom/utils/utils.py
MIT
def preprocess_input(x): """Preprocesses a tensor encoding a batch of images. # Arguments x: input Numpy tensor, 4D. data_format: data format of the image tensor. # Returns Preprocessed tensor. """ # 'RGB'->'BGR' x = x[..., ::-1] # Zero-center by mean pixel x[...
Preprocesses a tensor encoding a batch of images. # Arguments x: input Numpy tensor, 4D. data_format: data format of the image tensor. # Returns Preprocessed tensor.
preprocess_input
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Prediction/imagenet_utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Prediction/imagenet_utils.py
MIT
def decode_predictions(preds, top=5): """Decodes the prediction of an ImageNet model. # Arguments preds: Numpy tensor encoding a batch of predictions. top: integer, how many top-guesses to return. # Returns A list of lists of top class prediction tuples `(class_name, class_...
Decodes the prediction of an ImageNet model. # Arguments preds: Numpy tensor encoding a batch of predictions. top: integer, how many top-guesses to return. # Returns A list of lists of top class prediction tuples `(class_name, class_description, score)`. One list of tup...
decode_predictions
python
OlafenwaMoses/ImageAI
imageai_tf_deprecated/Prediction/imagenet_utils.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai_tf_deprecated/Prediction/imagenet_utils.py
MIT
def avg_darknesses(training_data): """ Return a defaultdict whose keys are the digits 0 through 9. For each digit we compute a value which is the average darkness of training images containing that digit. The darkness for any particular image is just the sum of the darknesses for each pixel.""" dig...
Return a defaultdict whose keys are the digits 0 through 9. For each digit we compute a value which is the average darkness of training images containing that digit. The darkness for any particular image is just the sum of the darknesses for each pixel.
avg_darknesses
python
MichalDanielDobrzanski/DeepLearningPython
mnist_average_darkness.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/mnist_average_darkness.py
MIT
def guess_digit(image, avgs): """Return the digit whose average darkness in the training data is closest to the darkness of ``image``. Note that ``avgs`` is assumed to be a defaultdict whose keys are 0...9, and whose values are the corresponding average darknesses across the training data.""" darkn...
Return the digit whose average darkness in the training data is closest to the darkness of ``image``. Note that ``avgs`` is assumed to be a defaultdict whose keys are 0...9, and whose values are the corresponding average darknesses across the training data.
guess_digit
python
MichalDanielDobrzanski/DeepLearningPython
mnist_average_darkness.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/mnist_average_darkness.py
MIT
def load_data(): """Return the MNIST data as a tuple containing the training data, the validation data, and the test data. The ``training_data`` is returned as a tuple with two entries. The first entry contains the actual training images. This is a numpy ndarray with 50,000 entries. Each entry is,...
Return the MNIST data as a tuple containing the training data, the validation data, and the test data. The ``training_data`` is returned as a tuple with two entries. The first entry contains the actual training images. This is a numpy ndarray with 50,000 entries. Each entry is, in turn, a numpy nd...
load_data
python
MichalDanielDobrzanski/DeepLearningPython
mnist_loader.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/mnist_loader.py
MIT
def load_data_wrapper(): """Return a tuple containing ``(training_data, validation_data, test_data)``. Based on ``load_data``, but the format is more convenient for use in our implementation of neural networks. In particular, ``training_data`` is a list containing 50,000 2-tuples ``(x, y)``. ``x`` ...
Return a tuple containing ``(training_data, validation_data, test_data)``. Based on ``load_data``, but the format is more convenient for use in our implementation of neural networks. In particular, ``training_data`` is a list containing 50,000 2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarr...
load_data_wrapper
python
MichalDanielDobrzanski/DeepLearningPython
mnist_loader.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/mnist_loader.py
MIT
def vectorized_result(j): """Return a 10-dimensional unit vector with a 1.0 in the jth position and zeroes elsewhere. This is used to convert a digit (0...9) into a corresponding desired output from the neural network.""" e = np.zeros((10, 1)) e[j] = 1.0 return e
Return a 10-dimensional unit vector with a 1.0 in the jth position and zeroes elsewhere. This is used to convert a digit (0...9) into a corresponding desired output from the neural network.
vectorized_result
python
MichalDanielDobrzanski/DeepLearningPython
mnist_loader.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/mnist_loader.py
MIT
def __init__(self, sizes): """The list ``sizes`` contains the number of neurons in the respective layers of the network. For example, if the list was [2, 3, 1] then it would be a three-layer network, with the first layer containing 2 neurons, the second layer 3 neurons, and the ...
The list ``sizes`` contains the number of neurons in the respective layers of the network. For example, if the list was [2, 3, 1] then it would be a three-layer network, with the first layer containing 2 neurons, the second layer 3 neurons, and the third layer 1 neuron. The biases and ...
__init__
python
MichalDanielDobrzanski/DeepLearningPython
network.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network.py
MIT
def feedforward(self, a): """Return the output of the network if ``a`` is input.""" for b, w in zip(self.biases, self.weights): a = sigmoid(np.dot(w, a)+b) return a
Return the output of the network if ``a`` is input.
feedforward
python
MichalDanielDobrzanski/DeepLearningPython
network.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network.py
MIT
def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): """Train the neural network using mini-batch stochastic gradient descent. The ``training_data`` is a list of tuples ``(x, y)`` representing the training inputs and the desired outputs. The other non...
Train the neural network using mini-batch stochastic gradient descent. The ``training_data`` is a list of tuples ``(x, y)`` representing the training inputs and the desired outputs. The other non-optional parameters are self-explanatory. If ``test_data`` is provided then the n...
SGD
python
MichalDanielDobrzanski/DeepLearningPython
network.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network.py
MIT
def update_mini_batch(self, mini_batch, eta): """Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta`` is the learning rate.""" nabla_b = [np.zeros(b.shape)...
Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta`` is the learning rate.
update_mini_batch
python
MichalDanielDobrzanski/DeepLearningPython
network.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network.py
MIT
def backprop(self, x, y): """Return a tuple ``(nabla_b, nabla_w)`` representing the gradient for the cost function C_x. ``nabla_b`` and ``nabla_w`` are layer-by-layer lists of numpy arrays, similar to ``self.biases`` and ``self.weights``.""" nabla_b = [np.zeros(b.shape) for b in...
Return a tuple ``(nabla_b, nabla_w)`` representing the gradient for the cost function C_x. ``nabla_b`` and ``nabla_w`` are layer-by-layer lists of numpy arrays, similar to ``self.biases`` and ``self.weights``.
backprop
python
MichalDanielDobrzanski/DeepLearningPython
network.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network.py
MIT
def evaluate(self, test_data): """Return the number of test inputs for which the neural network outputs the correct result. Note that the neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation.""" test_results = [(np.a...
Return the number of test inputs for which the neural network outputs the correct result. Note that the neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation.
evaluate
python
MichalDanielDobrzanski/DeepLearningPython
network.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network.py
MIT
def __init__(self, sizes, cost=CrossEntropyCost): """The list ``sizes`` contains the number of neurons in the respective layers of the network. For example, if the list was [2, 3, 1] then it would be a three-layer network, with the first layer containing 2 neurons, the second layer 3 ne...
The list ``sizes`` contains the number of neurons in the respective layers of the network. For example, if the list was [2, 3, 1] then it would be a three-layer network, with the first layer containing 2 neurons, the second layer 3 neurons, and the third layer 1 neuron. The biases and ...
__init__
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def default_weight_initializer(self): """Initialize each weight using a Gaussian distribution with mean 0 and standard deviation 1 over the square root of the number of weights connecting to the same neuron. Initialize the biases using a Gaussian distribution with mean 0 and standard ...
Initialize each weight using a Gaussian distribution with mean 0 and standard deviation 1 over the square root of the number of weights connecting to the same neuron. Initialize the biases using a Gaussian distribution with mean 0 and standard deviation 1. Note that the first l...
default_weight_initializer
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def large_weight_initializer(self): """Initialize the weights using a Gaussian distribution with mean 0 and standard deviation 1. Initialize the biases using a Gaussian distribution with mean 0 and standard deviation 1. Note that the first layer is assumed to be an input layer, and ...
Initialize the weights using a Gaussian distribution with mean 0 and standard deviation 1. Initialize the biases using a Gaussian distribution with mean 0 and standard deviation 1. Note that the first layer is assumed to be an input layer, and by convention we won't set any biases for ...
large_weight_initializer
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def SGD(self, training_data, epochs, mini_batch_size, eta, lmbda = 0.0, evaluation_data=None, monitor_evaluation_cost=False, monitor_evaluation_accuracy=False, monitor_training_cost=False, monitor_training_accuracy=False, early_stopping...
Train the neural network using mini-batch stochastic gradient descent. The ``training_data`` is a list of tuples ``(x, y)`` representing the training inputs and the desired outputs. The other non-optional parameters are self-explanatory, as is the regularization parameter ``lmbda``. T...
SGD
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def update_mini_batch(self, mini_batch, eta, lmbda, n): """Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The ``mini_batch`` is a list of tuples ``(x, y)``, ``eta`` is the learning rate, ``lmbda`` is the regularization ...
Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The ``mini_batch`` is a list of tuples ``(x, y)``, ``eta`` is the learning rate, ``lmbda`` is the regularization parameter, and ``n`` is the total size of the training data...
update_mini_batch
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def accuracy(self, data, convert=False): """Return the number of inputs in ``data`` for which the neural network outputs the correct result. The neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation. The flag ``conve...
Return the number of inputs in ``data`` for which the neural network outputs the correct result. The neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation. The flag ``convert`` should be set to False if the data set is ...
accuracy
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def total_cost(self, data, lmbda, convert=False): """Return the total cost for the data set ``data``. The flag ``convert`` should be set to False if the data set is the training data (the usual case), and to True if the data set is the validation or test data. See comments on the simil...
Return the total cost for the data set ``data``. The flag ``convert`` should be set to False if the data set is the training data (the usual case), and to True if the data set is the validation or test data. See comments on the similar (but reversed) convention for the ``accuracy`` met...
total_cost
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def save(self, filename): """Save the neural network to the file ``filename``.""" data = {"sizes": self.sizes, "weights": [w.tolist() for w in self.weights], "biases": [b.tolist() for b in self.biases], "cost": str(self.cost.__name__)} f = open(fil...
Save the neural network to the file ``filename``.
save
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def load(filename): """Load a neural network from the file ``filename``. Returns an instance of Network. """ f = open(filename, "r") data = json.load(f) f.close() cost = getattr(sys.modules[__name__], data["cost"]) net = Network(data["sizes"], cost=cost) net.weights = [np.array(w) ...
Load a neural network from the file ``filename``. Returns an instance of Network.
load
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def vectorized_result(j): """Return a 10-dimensional unit vector with a 1.0 in the j'th position and zeroes elsewhere. This is used to convert a digit (0...9) into a corresponding desired output from the neural network. """ e = np.zeros((10, 1)) e[j] = 1.0 return e
Return a 10-dimensional unit vector with a 1.0 in the j'th position and zeroes elsewhere. This is used to convert a digit (0...9) into a corresponding desired output from the neural network.
vectorized_result
python
MichalDanielDobrzanski/DeepLearningPython
network2.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network2.py
MIT
def shared(data): """Place the data into shared variables. This allows Theano to copy the data to the GPU, if one is available. """ shared_x = theano.shared( np.asarray(data[0], dtype=theano.config.floatX), borrow=True) shared_y = theano.shared( np.asarr...
Place the data into shared variables. This allows Theano to copy the data to the GPU, if one is available.
shared
python
MichalDanielDobrzanski/DeepLearningPython
network3.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network3.py
MIT
def __init__(self, layers, mini_batch_size): """Takes a list of `layers`, describing the network architecture, and a value for the `mini_batch_size` to be used during training by stochastic gradient descent. """ self.layers = layers self.mini_batch_size = mini_batch_size...
Takes a list of `layers`, describing the network architecture, and a value for the `mini_batch_size` to be used during training by stochastic gradient descent.
__init__
python
MichalDanielDobrzanski/DeepLearningPython
network3.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network3.py
MIT
def SGD(self, training_data, epochs, mini_batch_size, eta, validation_data, test_data, lmbda=0.0): """Train the network using mini-batch stochastic gradient descent.""" training_x, training_y = training_data validation_x, validation_y = validation_data test_x, test_y = test_d...
Train the network using mini-batch stochastic gradient descent.
SGD
python
MichalDanielDobrzanski/DeepLearningPython
network3.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network3.py
MIT
def __init__(self, filter_shape, image_shape, poolsize=(2, 2), activation_fn=sigmoid): """`filter_shape` is a tuple of length 4, whose entries are the number of filters, the number of input feature maps, the filter height, and the filter width. `image_shape` is a tuple ...
`filter_shape` is a tuple of length 4, whose entries are the number of filters, the number of input feature maps, the filter height, and the filter width. `image_shape` is a tuple of length 4, whose entries are the mini-batch size, the number of input feature maps, the image hei...
__init__
python
MichalDanielDobrzanski/DeepLearningPython
network3.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network3.py
MIT
def accuracy(self, y): "Return the accuracy for the mini-batch." return T.mean(T.eq(y, self.y_out))
Return the accuracy for the mini-batch.
accuracy
python
MichalDanielDobrzanski/DeepLearningPython
network3.py
https://github.com/MichalDanielDobrzanski/DeepLearningPython/blob/master/network3.py
MIT
def _detect(env): """ Try to detect the kotlinc binary """ try: return env["kotlinc"] except KeyError: pass kotlin = env.Detect("kotlinc") if kotlin: return kotlin SCons.Warnings.warn(KotlinNotFound, "Could not find kotlinc executable")
Try to detect the kotlinc binary
_detect
python
algorithm-archivists/algorithm-archive
builders/kotlin.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/builders/kotlin.py
MIT
def Kotlin(env, target, source=None, *args, **kw): """ A pseudo-Builder wrapper for the kotlinc executable. kotlinc [options] file """ if not SCons.Util.is_List(target): target = [target] if not source: source = target[:] if not SCons.Util.is_List(source): source ...
A pseudo-Builder wrapper for the kotlinc executable. kotlinc [options] file
Kotlin
python
algorithm-archivists/algorithm-archive
builders/kotlin.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/builders/kotlin.py
MIT
def KotlinJar(env, target, source=None, *args, **kw): """ A pseudo-Builder wrapper for creating JAR files with the kotlinc executable. kotlinc [options] file -d target """ if not SCons.Util.is_List(target): target = [target] if not source: source = target[:] if not SCons....
A pseudo-Builder wrapper for creating JAR files with the kotlinc executable. kotlinc [options] file -d target
KotlinJar
python
algorithm-archivists/algorithm-archive
builders/kotlin.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/builders/kotlin.py
MIT
def KotlinRuntimeJar(env, target, source=None, *args, **kw): """ A pseudo-Builder wrapper for creating standalone JAR files with the kotlinc executable. kotlinc [options] file -d target -include-runtime """ if not SCons.Util.is_List(target): target = [target] if not source: s...
A pseudo-Builder wrapper for creating standalone JAR files with the kotlinc executable. kotlinc [options] file -d target -include-runtime
KotlinRuntimeJar
python
algorithm-archivists/algorithm-archive
builders/kotlin.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/builders/kotlin.py
MIT
def generate(env): """Add Builders and construction variables for kotlinc to an Environment.""" env["KOTLINC"] = _detect(env) env.SetDefault( KOTLINC="kotlinc", KOTLINSUFFIX=".kt", KOTLINEXTENSION="Kt", KOTLINCLASSSUFFIX=".class", KOTLINJARSUFFIX=".jar", KOT...
Add Builders and construction variables for kotlinc to an Environment.
generate
python
algorithm-archivists/algorithm-archive
builders/kotlin.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/builders/kotlin.py
MIT
def f(x, normalize=False): ''' Function proportional to target distribution, a sum of Gaussians. For testing, set normalize to True, to get target distribution exactly. ''' # Gaussian heights, width parameters, and mean positions respectively: a = np.array([10., 3., 1.]).reshape(3, 1) b = np...
Function proportional to target distribution, a sum of Gaussians. For testing, set normalize to True, to get target distribution exactly.
f
python
algorithm-archivists/algorithm-archive
contents/metropolis/code/python/metropolis.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/metropolis/code/python/metropolis.py
MIT
def metropolis_step(x, f=f, g=g): '''Perform one full iteration and return new position.''' x_proposed = x + g() a = min(1, (f(x_proposed) / f(x)).item()) x_new = np.random.choice([x_proposed, x], p=[a, 1-a]) return x_new
Perform one full iteration and return new position.
metropolis_step
python
algorithm-archivists/algorithm-archive
contents/metropolis/code/python/metropolis.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/metropolis/code/python/metropolis.py
MIT
def metropolis_iterate(x0, num_steps): '''Iterate metropolis algorithm for num_steps using iniital position x_0''' for n in range(num_steps): if n == 0: x = x0 else: x = metropolis_step(x) yield x
Iterate metropolis algorithm for num_steps using iniital position x_0
metropolis_iterate
python
algorithm-archivists/algorithm-archive
contents/metropolis/code/python/metropolis.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/metropolis/code/python/metropolis.py
MIT
def test_metropolis_iterate(num_steps, xmin, xmax, x0): ''' Calculate error in normalized density histogram of data generated by metropolis_iterate() by using normalized-root-mean-square-deviation metric. ''' bin_width = 0.25 bins = np.arange(xmin, xmax + bin_width/2, bin_width) ...
Calculate error in normalized density histogram of data generated by metropolis_iterate() by using normalized-root-mean-square-deviation metric.
test_metropolis_iterate
python
algorithm-archivists/algorithm-archive
contents/metropolis/code/python/metropolis.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/metropolis/code/python/metropolis.py
MIT
def monte_carlo(n_samples, radius = 1): """Return the estimate of pi using the monte carlo algorithm.""" in_circle_count = 0 for i in range(n_samples): # Sample x, y from the uniform distribution x = random.uniform(0, radius) y = random.uniform(0, radius) # Count the number of points inside the circle ...
Return the estimate of pi using the monte carlo algorithm.
monte_carlo
python
algorithm-archivists/algorithm-archive
contents/monte_carlo_integration/code/python/monte_carlo.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/monte_carlo_integration/code/python/monte_carlo.py
MIT
def init(par: Param, voffset: float, wfcoffset: float) -> Operators: """Initialize the wavefunction coefficients and the potential.""" opr = Operators(len(par.x)) opr.V = 0.5 * (par.x - voffset) ** 2 opr.wfc = np.exp(-((par.x - wfcoffset) ** 2) / 2, dtype=complex) if par.im_time: opr.K = np....
Initialize the wavefunction coefficients and the potential.
init
python
algorithm-archivists/algorithm-archive
contents/split-operator_method/code/python/split_op.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/split-operator_method/code/python/split_op.py
MIT
def next_choice(self): """Return the next person in the own preference list""" try: return self.preference[self.pref_index] except IndexError: return None
Return the next person in the own preference list
next_choice
python
algorithm-archivists/algorithm-archive
contents/stable_marriage_problem/code/python/stable_marriage.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/stable_marriage_problem/code/python/stable_marriage.py
MIT
def propose_to_next(self): """Propose to the next person in the own preference list""" person = self.next_choice person.candidates.append(self) self.pref_index += 1
Propose to the next person in the own preference list
propose_to_next
python
algorithm-archivists/algorithm-archive
contents/stable_marriage_problem/code/python/stable_marriage.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/stable_marriage_problem/code/python/stable_marriage.py
MIT
def pick_preferred(self): """Pick a new partner or stay with the old one if they are preferred""" # Iterate own preferences in order for person in self.preference: # Pick the first person that's either a new candidate or the # current partner if person == self...
Pick a new partner or stay with the old one if they are preferred
pick_preferred
python
algorithm-archivists/algorithm-archive
contents/stable_marriage_problem/code/python/stable_marriage.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/stable_marriage_problem/code/python/stable_marriage.py
MIT
def partner(self, person): """Set a person as the new partner and sets the partner of that person as well""" # Do nothing if nothing would change if person != self._partner: # Remove self from current partner if self._partner is not None: self._pa...
Set a person as the new partner and sets the partner of that person as well
partner
python
algorithm-archivists/algorithm-archive
contents/stable_marriage_problem/code/python/stable_marriage.py
https://github.com/algorithm-archivists/algorithm-archive/blob/master/contents/stable_marriage_problem/code/python/stable_marriage.py
MIT
def sorted_dict(to_sort): """Helper function to sort list of string inside dictionaries in order to compare them""" if isinstance(to_sort, dict): new_dict = {} for k in sorted(to_sort.keys()): new_dict[k] = sorted_dict(to_sort[k]) return new_dict if isinstance(to_sort, li...
Helper function to sort list of string inside dictionaries in order to compare them
sorted_dict
python
keleshev/schema
test_schema.py
https://github.com/keleshev/schema/blob/master/test_schema.py
MIT
def test_optional_key_convert_failed_randomly_while_with_another_optional_object(): """ In this test, created_at string "2015-10-10 00:00:00" is expected to be converted to a datetime instance. - it works when the schema is s = Schema({ 'created_at': _datetime_valida...
In this test, created_at string "2015-10-10 00:00:00" is expected to be converted to a datetime instance. - it works when the schema is s = Schema({ 'created_at': _datetime_validator, Optional(basestring): object, }) - but wh...
test_optional_key_convert_failed_randomly_while_with_another_optional_object
python
keleshev/schema
test_schema.py
https://github.com/keleshev/schema/blob/master/test_schema.py
MIT