Saravanan666/pypi-org huggingface dataset:
Package: keras-datasets
keras\_datasets===============A repository hosting keras dataset generators|Open Source Love| |license| |GitHub release| |PyPI|.. |Open Source Love| image:: https://badges.frapsoft.com/os/v2/open-source.svg?v=103:target: https://opensource.org/licenses/MIT/.. |license| image:: https://img.shields.io/github/license/DEKHTIARJonathan/keras_datasets.svg:target: https://github.com/DEKHTIARJonathan/keras_datasets.. |GitHub release| image:: https://img.shields.io/github/release/DEKHTIARJonathan/keras_datasets.svg:target: https://github.com/DEKHTIARJonathan/keras_datasets.. |PyPI| image:: https://img.shields.io/pypi/v/keras_datasets.svg:target:
Package: keras-declarative
This package is in alpha stage.
This README is a work in progress.Creating ExperimentsThere are two types of experiments:trainingexperiments, which involve
training a new or existing model, andtestingexperiments, which involve
testing an existing model.keras.train --config_file path/to/config/file.yaml

keras.test --config_file path/to/config/file.yamlSpecifying Keras ObjectsKeras Declarative automatically discovers objects, such as layers and loss
functions, which are available in core TensorFlow, TensorFlow MRI and TF
Playground. This means these objects can be used in the configuration file
without explicit registration.Serializable Keras objects, such as layers and loss functions, are specified by
a class name and a configuration dictionary. If no parameters should be passed
to the object, the configuration dictionary may be omitted.# class name and parameterstraining:optimizer:class_name:Adamconfig:learning_rate:0.001# class name only (instantiated with default parameters)training:optimizer:AdamExternal ModulesIt is possible to use objects defined in external modules within Keras
Declarative, i.e., objects that are not part of either core TensorFlow,
TensorFlow MRI or TF Playground. This is particularly useful to define
preprocessing functions but can be used for any other purpose. External modules
can be specified with the$externaldirective.Any external modules used during an experiment will be automatically saved to
the experiment folder to enable reproducibility.data:transforms:train:-type:mapmap:map_func:$external:# Use a preprocessing function defined in an external module.filename:/path/to/preprocessing_fn.pyobject_name:preprocessing_fn# Any parameters that should be passed to this object may be# specified here.args:nullkwargs:nullAnchors and AliasesIf you need to repeat a node more than once, you can anchor it once with the&character and then alias it any number of times using the*character.
For example, to use the same list of data transforms for the training and
validation sets, you may use:data:transforms:train:&transforms# Define the list of transforms here.val:*transforms# Reusing training transforms here.Hyperparameter TuningKeras Declarative can configure the Keras Tuner to automatically tune one or
more parameters.Most parameters can be set as tunable using the$tunabledirective. For
example, to tune the kernel size of a U-Net model, you might use:model:network:class_name:UNetconfig:scales:3base_filters:32kernel_size:$tunable:type:intint:name:kernel_sizemin_value:3max_value:7step:2Valid tunable types areboolean,choice,fixed,floatandint. For
more details, seehttps://keras.io/api/keras_tuner/hyperparameters/.The tuner type and options can be specified withtuning.tunerparameter:tuning:tuner:class_name:Hyperbandconfig:objective:name:val_ssimdirection:maxmax_epochs:100Available tuners areRandomSearch,BayesianOptimizationandHyperband. For more details about these tuners and their options, seehttps://keras.io/api/keras_tuner/tuners/.Note that some parameters cannot be tuned. These include all parameters
underexperimentand underdata.sources.
Package: keras-diagram
Print ASCII diagrams of yourKerasmodels to visualize the
layers and their shapes.InputLayer (None, 50, 300)
      Reshape (None, 1, 50, 300)
Convolution2D (None, 250, 48, 1)
         Relu (None, 250, 48, 1)
 MaxPooling2D (None, 250, 1, 1)
      Flatten (None, 250)
      Dropout (None, 250)
        Dense (None, 7)
      Softmax (None, 7)A more complex model frombabi_rnn.py:InputLayer (None, 5)
                                  Embedding (None, 5, 50)
InputLayer (None, 552)              Dropout (None, 5, 50)
 Embedding (None, 552, 50)             LSTM (None, 50)
   Dropout (None, 552, 50)     RepeatVector (None, 552, 50)
           \______________________________/
                          |
                     Merge (None, 552, 50)
                      LSTM (None, 50)
                   Dropout (None, 50)
                     Dense (None, 36)To installpip install keras_diagramNote for Conda installation (Python 3.5):pip install pypandocTo usefrom keras_diagram import ascii

model = Sequential()
model.add(...)

print(ascii(model))Developing./test.py       # run tests via docker
./publish.py    # build distributions and publish to pypi
./shell.py      # run bash above docker container with current folder mounted
Package: keras-ding
Keras callback for playing a sound when training is complete. The callbacks additionally works also within jupyter notebook,
so that if you are working on a notebook on a remote machine it plays the audio within your browser and not in the server.How do I install this package?You will need a couple packages that you might not already have installed:sudoaptinstallpython3-devsudoaptinstalllibasound2-devFinally as usual, just download it using pip:pipinstallkeras_dingUsage examplesSo suppose you have your Keras modelmy_keras_modeland you want to hear a sound when it is done training.
Here you go:fromkeras_dingimportKerasDingmy_keras_model.fit(x,y,callbacks=[KerasDing()])What abount a custom sound? Just pass it as an argument.fromkeras_dingimportKerasDingmy_keras_model.fit(x,y,callbacks=[KerasDing(path="my_custom_sound.mp3")])
Package: keras-embed-sim
Keras Embedding Similarity[中文|English]Compute the similarity between the outputs and the embeddings.Installpipinstallkeras-embed-simUsagefromtensorflowimportkerasfromkeras_embed_simimportEmbeddingRet,EmbeddingSiminput_layer=keras.layers.Input(shape=(None,),name='Input')embed,embed_weights=EmbeddingRet(input_dim=20,output_dim=100,mask_zero=True,)(input_layer)output_layer=EmbeddingSim()([embed,embed_weights])
Package: keras-ernie
keras ERNIEPre-trained ERNIE models could be loaded for feature extraction and prediction.Installpipinstallkeras-ernieUsageDownload pre-trained ERNIE modelsLoad the pre-trained ERNIE modelsConvert pre-trained ERNIE model to Tensor modelDownload Pre-trained ERNIE ModelsNotes: Currently, only the following models are supported.ModelDescriptionERNIE 1.0 Base for Chinesewith params, config and vocabsERNIE 1.0 Base for Chinese(max-len-512)with params, config and vocabsERNIE 2.0 Base for Englishwith params, config and vocabsLoad Pre-trained ERNIE Modelsimportosfromkeras_ernieimportload_from_checkpointernie_path="/root/ERNIE_stable-1.0.1"init_checkpoint=os.path.join(ernie_path,'params')ernie_config_path=os.path.join(ernie_path,'ernie_config.json')ernie_vocab_path=os.path.join(ernie_path,'vocab.txt')ernie_version="stable-1.0.1"model=load_from_checkpoint(init_checkpoint,ernie_config_path,ernie_vocab_path,ernie_version,max_seq_len=128,num_labels=2,use_fp16=False,training=False,seq_len=None,name='ernie')model.summary()Convert Pre-trained ERNIE Model To Tensor Modelimportosfromkeras_ernieimportErnieArgsfromkeras_ernieimportconvert_paddle_to_tensorernie_path="/root/ERNIE_stable-1.0.1"init_checkpoint=os.path.join(ernie_path,'params')ernie_config_path=os.path.join(ernie_path,'ernie_config.json')ernie_vocab_path=os.path.join(ernie_path,'vocab.txt')tensor_checkpoints_dir="/root/checkpoints"args=ErnieArgs(init_checkpoint,ernie_config_path,ernie_vocab_path,max_seq_len=128,num_labels=2,use_fp16=False)convert_paddle_to_tensor(args,tensor_checkpoints_dir)
Package: keras-facenet
keras-facenetThis is a simple wrapper aroundthis wonderful implementation of FaceNet. I wanted something that could be used in other applications, that could use any of the four trained models provided in the linked repository, and that took care of all the setup required to get weights and load them. I prefer using Keras wherever possible because of its API, so I used theexample provided hereand implemented it as part of the code.Enough background -- so how are you supposed to use this?Installingpip install keras-facenetUsageTo get embeddings for the faces in an image, you can do something like the following.from keras_facenet import FaceNet
embedder = FaceNet()

# Gets a detection dict for each face
# in an image. Each one has the bounding box and
# face landmarks (from mtcnn.MTCNN) along with
# the embedding from FaceNet.
detections = embedder.extract(image, threshold=0.95)

# If you have pre-cropped images, you can skip the
# detection step.
embeddings = embedder.embeddings(images)LoggingTo see what's going on under the hood, set logging to viewINFOlogs. If using in a Jupyter notebook, you can use the following.import logging

logging.basicConfig()
log = logging.getLogger()
log.setLevel('INFO')
Package: keras-flops
keras-flopsFLOPs calculator for neural network architecture written in tensorflow (tf.keras) v2.2+This stands on the shoulders of giants,tf.profiler.RequirementsPython 3.6+Tensorflow 2.2+InstallationUsing pip:pip install keras-flopsExampleSee colab examplesherein details.fromtensorflow.kerasimportModel,Inputfromtensorflow.keras.layersimportDense,Flatten,Conv2D,MaxPooling2D,Dropoutfromkeras_flopsimportget_flops# build modelinp=Input((32,32,3))x=Conv2D(32,kernel_size=(3,3),activation="relu")(inp)x=Conv2D(64,(3,3),activation="relu")(x)x=MaxPooling2D(pool_size=(2,2))(x)x=Dropout(0.25)(x)x=Flatten()(x)x=Dense(128,activation="relu")(x)x=Dropout(0.5)(x)out=Dense(10,activation="softmax")(x)model=Model(inp,out)# Calculae FLOPSflops=get_flops(model,batch_size=1)print(f"FLOPS:{flops/10**9:.03}G")# >>> FLOPS: 0.0338 GSupportSupporttf.keras.layersas follows,namelayerConvConv[1D/2D/3D]Conv[1D/2D]TransposeDepthwiseConv2DSeparableConv[1D/2D]PoolingAveragePooling[1D/2D]GlobalAveragePooling[1D/2D/3D]MaxPooling[1D/2D]GlobalMaxPool[1D/2D/3D]NormalizationBatchNormalizationActivationSoftmaxAttentionAttentionAdditiveAttentionothersDenseNot supportedNot supporttf.keras.layersas follows. They are calculated as zero or smaller value than correct value.namelayerConvConv3DTransposePoolingAveragePooling3DMaxPooling3DUpSampling[1D/2D/3D]NormalizationLayerNormalizationRNNSimpleRNNLSTMGRUothersEmbedding
Package: keras-flower
Keras FlowerA Simple Flower classification package using DenseNet201.Classes   :104 classes of flowersTraining Data Set :Petals to the Metal - Flower Classification on TPUUsageUse pip install to install this packagepip install keras_flowerTo get all prediction resultsimport keras_flower as kf
predictions = kf.predict_by_path("file/to/predict.png")
print(predictions)Sample output:[1.4414026e-06 1.6031330e-06 1.6295390e-06 1.1156463e-06 2.7592062e-06
...
 1.1587109e-06 4.1556059e-06 1.0784672e-05 6.0254356e-06]To get top prediction result withflower labelsimport keras_flower as kf
for predicted, score in kf.predict_name_by_path("/path/to/file.png"):
    print(predicted, score)Sample output:sunflower 0.99960905ValidationData set :102 Category Flower DatasetNo of images :8189Overall accuracy :0.9715confusion matrix :102flowers_confusion_matrix.csvclassification report :102flowers_classification_report.txtclassification report summary:precision    recall  f1-score   support
                micro avg       0.97      0.97      0.97      8189
                macro avg       0.95      0.94      0.94      8189
             weighted avg       0.97      0.97      0.97      8189Demo
Package: kerasfuse
KerasFuse🚧 Warning this project is under heavy development and not ready for production. ABI changes can happen frequently until reach stable version 🚧KerasFuse is a Python library that combines the power of TensorFlow and Keras with various computer vision techniques for medical image analysis tasks. It provides a collection of modules and functions to facilitate the development of deep learning models in TensorFlow Keras for tasks such as image segmentation, classification, and more.Getting StartedRequirementsKerasFuse is a project that relies heavily on the Tensorflow and Keras libraries. It is designed to work seamlessly with these powerful tools for deep learning and neural network development. In order to use KerasFuse effectively, please ensure that you have the following:Python 3.8+Tensorflow 2.12.0+Keras 2.12.0+OpenCV 4.7+Scikit-Learn 1.2.2+Installation$pipinstallkerasfuse---> 100%DevelopmentPoetry Installationpoetryinstall
poetryshellTipIf you have multiple Python versions on your system, you can set your Python version by usingpoetry env. Here's an example of how to use it:poetryenvusepython3.10More details atpoetry-switching-between-environmentsPip Installationspython3-mvenv.venvsource.venv/bin/activate
pip3install-rrequirements.txtLicenseThis project is licensed under the terms of the GPL-3.0 license.
Package: keras-gcn
Keras Graph Convolutional NetworkGraph convolutional layers.Installpipinstallkeras-gcnUsageGraphConvfromtensorflowimportkerasfromkeras_gcnimportGraphConvDATA_DIM=3data_layer=keras.layers.Input(shape=(None,DATA_DIM))edge_layer=keras.layers.Input(shape=(None,None))conv_layer=GraphConv(units=32,step_num=1,)([data_layer,edge_layer])step_numis the maximum distance of two nodes that could be considered as neighbors. Ifstep_numis greater than 1, then the inputs of edges must be 0-1 matrices.GraphMaxPool&GraphAveragePoolPooling layers with thestep_numargument.
Package: kerasgen
kerasgenA Keras/Tensorflow compatible image data generator for creating balanced batches.
This datagenerator is compatible with TripletLoss as it guarantees the existence of postive pairs in every batch.InstallationpipinstallkerasgenUsagefromkerasgen.balanced_image_datasetimportbalanced_image_dataset_from_directorytrain_ds=balanced_image_dataset_from_directory(directory,num_classes_per_batch=2,num_images_per_class=5,image_size=(256,256),validation_split=0.2,subset='training',seed=555,safe_triplet=True)val_ds=balanced_image_dataset_from_directory(directory,num_classes_per_batch=2,num_images_per_class=5,image_size=(256,256),validation_split=0.2,subset='validation',seed=555,safe_triplet=True)Generates a balanced per batchtf.data.Datasetfrom image files in a directory.Your directory structure should be:main_directory/
...class_a/
......a_image_1.jpg
......a_image_2.jpg
...class_b/
......b_image_1.jpg
......b_image_2.jpgBehind the scenes, this API creates a different dataset for every class and by using weighted random sampling, a number of classes is drawn(num_classes_per_batch)and a specific number of images is selected from every choosen class(num_images_per_class)as long as there are enough samples from this class.If there is no enough samples remaining from the choosen class, it is skipped and another class is choosen (This behaviour can be disabled and we indefinitely repeat the datasets)Settingsafe_triplettoFalse(Default) makes sure that every image is seen exactly one time per epoch but it does not guarantee a fixed num_classes_per_batch or num_images_per_class in later batches.Settingsafe_triplettoTruedoes not guarantee that every epoch will include all different samples from the dataset. But as sampling weighted per class, every epoch will include a very high percentage of the dataset and should approach 100% as dataset size increases. This however guarantee that both num_classes_per_batch and num_images_per_class are fixed for all batches including later ones.If you are to use this generator with TripletLoss, your should either:Setsafe_triplettoTrueKeepsafe_tripletdefaultFalsevalue but be careful with choosing the batch_size so you do not end up with a last batch containing a single class (or a single sample)Batch size is calculated by multiplying num_classes_per_batch and num_images_per_class.RequirementsTensorflow >= 2.9Numpy >= 1.19Compatible withtf.data.DatasetAPITripletHardLossTripletSemiHardLossv0.1.3 TF>= 2.9v0.1.2 TF>= 2.7
LicenceMITAuthorsKerasGenwas written byMahmoud BahaaIf you use this software, please cite it using the metadata from thisCITATION.cff
Package: keras-gpt-2
Keras GPT-2[中文|English]Load pretrained weights and predict withGPT-2.Installpipinstallkeras-gpt-2Demoimportosfromkeras_gpt_2importload_trained_model_from_checkpoint,get_bpe_from_files,generatemodel_folder='xxx/yyy/117M'config_path=os.path.join(model_folder,'hparams.json')checkpoint_path=os.path.join(model_folder,'model.ckpt')encoder_path=os.path.join(model_folder,'encoder.json')vocab_path=os.path.join(model_folder,'vocab.bpe')print('Load model from checkpoint...')model=load_trained_model_from_checkpoint(config_path,checkpoint_path)print('Load BPE from files...')bpe=get_bpe_from_files(encoder_path,vocab_path)print('Generate text...')output=generate(model,bpe,['From the day forth, my arm'],length=20,top_k=1)# If you are using the 117M model and top_k equals to 1, then the result will be:# "From the day forth, my arm was broken, and I was in a state of pain. I was in a state of pain,"print(output[0])
Package: keras-gpt-copilot
Keras GPT Copilot is the first Python package designed to integrate an LLM copilot within the model development workflow, offering iterative feedback options for enhancing the performance of your Keras deep learning models. Utilizing the power of OpenAI’s GPT models, Keras GPT Copilot can use any of the compatible models (GPT4 is recommended). However, the prompt-only mode allows for compatibility with other large language models.
Package: keras-gradient-accumulation
Keras Gradient Accumulation[中文|English]Installpipinstallkeras-gradient-accumulationUsageWrapperfromkeras_gradient_accumulationimportGradientAccumulationoptimizer=GradientAccumulation('adam',accumulation_steps=8)Adamfromkeras_gradient_accumulationimportAdamAccumulatedoptimizer=AdamAccumulated(accumulation_steps=8)Known IssuesNot available for batch normalizationNot compatible withOptimizerV2
Package: keras-grid-search-cacheable
keras GridSearch CacheableDescripciónCuando está desarrollando un componente enKERASyTensorflowy requiere hacer búsqueda de parámetros mediante GridSearch puede ser muy tardado y requerir mucho reproceso al ejecutar su código.Para dar solución a esto se creó elkeras GridSearch Cacheablecon el objetivo de extender las funcionalidades de cacheo deSK-LearnaKERAS.InstalaciónEn Google Colaboratory:Ejecute el siguiente fragmento de códigodef downloadDriveFile(file_id,file_name,file_extension):
  !wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id='$file_id -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id="$file_id -O "$file_name"."$file_extension" && rm -rf /tmp/cookies.txt

downloadDriveFile("1G9uWCkxwyE-qISaYbXYtnM21wT1kz11X","CacheableKeras","py")
from cacheable_keras.cacheable import KerasCacheableEn GeneralTODO: Pendiente por agregar a pipUsoExtienda la clase en su componente:from CacheableKeras import KerasCacheable

class YourComponent(BaseEstimator, TransformerMixin, KerasCacheable):
    def __init__(self, ...):Nota: Este ejemplo es para unTransformerMixinperfectamente puede usarse enRegressorMixinoClassifierMixinsegun sea el objetivo de su componente.Defina Funciones Personalizadas:Puede decir las funciones que quiere que su modelo ejecute sobrescribiendo el métodoget_custom_objectsasí:def get_custom_objects(self):
    return { 'custom_loss': self.custom_loss }Nota: Este método debe retornar un diccionario{ ‘function_name’ : self.reference_function }y la reference_function debe estar definida enYourComponent.
En caso de necesitar más de una función personalizada agréguela al diccionario.Personalice la configuración:keras GridSearch Cacheabletrabaja por defecto conTODOSlos parámetros de entradaYourComponent.
Sin embargo, si por algún motivo no desea cachear todos los parámetros de entrada sobrescriba el métodoget_params_cacheableasí:def get_params_cacheable(self):
    return ['Parameter 1','Parameter 2',... 'Parameter N']Nota: Tenga en cuidado al realizar esta modificación, si no colocaTODOSlos parámetros obligatorios paraYourComponental cargar el modelo creado desde su manejador de cache se retornará un error.Producto desarrollado bajo el curso de posgrado de aprendizaje de máquina avanzado impartido por el profesor Andrés Marino Álvarez – Universidad NacionalDaniel Espinosa - 2020
Package: keras-helper
Helpful Keras Import WrapperThis is a library meant to help get an optimized version of
Keras and other useful libraries without worrying about what
is the underlying implementation (PlaidML, Tensorflow etc.)Usagefromkeras_helperimportkerasifnotkeras:raiseImportError('No keras found')Questions?Reach out toKarthik Kumar Viswanathankarthikkumar at gmail dot comfor any suggestions, feedback. PRs welcome.
Package: keras-hist-graph
Keras History GraphUsesmatplotlibto generate a simple graph of the history object. Particularly useful withJupyterIt will show theaccuracyandlossfor bothtraining dataandvalidation data.
It will also print the maximumvalidation accuracyreached during the training.Installationpip install keras-hist-graphUsageRequiresKerasfromkeras_hist_graphimportplot_historyhistory=model.fit(x,y,...)plot_history(history)Argumentsplot_historynow accepts any of these arguments (in any order)argumentdefaultpossibledetailsfig_size(10, 6)(float,float)Indicateswidthandheightof the resulting graphmin_accuracy0.5[0, 1)Minimum accuracy to graph (often we don't care if acuracy is below 50%)smooth_factor0.75[0, 1]Zero to one, inclusive. Smooths out the curves by averaging previous points. Consider makeing smaller if number of epochs is small.start_epoch5integer >= 0Plot the history starting at this epoch. Useful since the first epochs can have very high loss that makes the later loss hard to analyze visuallyxkcdTrueTrueFalseWhether to render in theXKCDstyle. You might need to render twice for all properties to update if you change the boolean after using the method beforeExample:plot_history(history,fig_size=(11,8.5),min_accuracy=0.8,start_epoch=2,smooth_factor=0.1)NotesWhy use the XKCD style?It’s a great way to communicate the imprecision of the underlying data!
Package: kerashistoryplot
History plot for Keras model trainingPlots training losses and metrics in Jupyter while training yourkerasmodel.This project started as an attempt to extendlivelossplot, but I realized that a rewrite was easier. Key improvements are:keeps full history, including losses for each batch in each epochplots scatter of batch lossesplots arbitrary log entries, such alr(learning rate)simplifies codebase extendibilityBasic UsageInstall package from source:pip install git+https://github.com/ig248/kerashistoryplotOr from PyPi:pip install kerashistoryplotImport function:fromlivehistoryplot.callbacksimportPlotHistoryUse in callbacks:model.fit(X,y,epochs=20,callbacks=[ReduceLROnPlateau(),PlotHistory(batches=True,n_cols=3,figsize=(15,7))])More ExamplesSeenotebooks/TestsRunmakedev-install
maketestReferencesOriginallivelossplot:https://github.com/stared/livelossplot