Saravanan666/pypi-org huggingface dataset:
Package: keras-htr
A toolkit for developing handwritten text recognition (HTR) pipelinesEasy to use toolkit for the rapid development of offline handwritten text recognition (HTR) system.
The toolkit provides a set of useful utilities and scripts for training and evaluating
models and performing recognition. It is shipped with ready-to-train model
implementations for HTR tasks.Key featuresbuilt-in model implementationsautomatic data pre-processingbuilt-in performance metrics: LER (label error rate)data-set independencehandwriting language independenceBuilt-in models1D-LSTM [1] by Joan PuigcerverQuick startCreate working HTR system in just 4 steps:Subclass Source class representing raw data examplesUse the data source to build a datasetTrain model with a particular architecture on the datasetTake trained model and use it to perform recognitionYou only need to focus on the first step. Once you implement a class
for a data source, the steps that follow will automatically pre-process
the data,  train a neural network and save it.Below is example of training 1D-LSTM model on synthetic images using SyntheticSource class.Build a dataset using synthetic words data source, store it in temp_ds folderpython build_lines_dataset.py --source='keras_htr.data_source.synthetic.SyntheticSource' --destination=temp_dsNote that the source argument expects a fully-qualified name of a class representing a data source.Train a modelpython train.py temp_ds --units=32 --epochs=35 --model_path=conv_lstm_model.h5Run demo scriptpython demo.py conv_lstm_model.h5 temp_ds/testRecognize handwritingpython htr.py conv_lstm_model.h5 temp_ds/character_table.txt temp_ds/test/0.pngData sourcesA data source is a Python generator that yields raw examples in the form of tuples
(text, line_image). The Keras-HTR toolkit uses data sources to construct a train/val/test split,
build a character table, collect useful meta-information about the data set such as
average image height, width and more.To train a model on your data, you need to create your subclass of Source class and
implement an iterator method that yields a pair (line_image, text) at each step.
Here line_image is either a path to an image file or Pillow image object, the text
is a corresponding transcription.SyntheticSourceIt is generator of printed text examplesIAMSourceIt is generator of handwritings taken from IAM handwriting database.
Before you can use this source, you have to download the actual database:http://www.fki.inf.unibe.ch/databases/iam-handwriting-database.References[1]Joan Puigcerver. Are Multidimensional Recurrent Layers Really Necessary for Handwritten Text Recognition?
Package: keras-image-classification-wrapper
keras-image-classification-wrapperA thin wrapper around keras image classification applications.Installationpipinstallkeras-image-classification-wrapperUsagedefclassify(image:Union[str,bytes,pillow.Image.Image],results:int=3,model:str=INCEPTIONV3,)->tuple:Classify an image.resultshas to be less that 5, since keras applications don't give more than five results.modelhas to be one of:XCEPTION,VGG16,VGG19,RESNET50,RESNET101,RESNET152,RESNET50V2,RESNET101V2,RESNET152V2,RESNETRS101,RESNETRS152,RESNETRS200,RESNETRS270,RESNETRS350,RESNETRS420,REGNETX002,REGNETX004,REGNETX006,REGNETX008,REGNETX016,REGNETX032,REGNETX040,REGNETX064,REGNETX080,REGNETX120,REGNETX160,REGNETX320,REGNETY002,REGNETY004,REGNETY006,REGNETY008,REGNETY016,REGNETY032,REGNETY040,REGNETY064,REGNETY080,REGNETY120,REGNETY160,REGNETY320,INCEPTIONV3,INCEPTIONRESNETV2,MOBILENET,MOBILENETV2,MOBILENETV3SMALL,MOBILENETV3LARGE,DENSENET121,DENSENET169,DENSENET201,NASNETMOBILE,NASNETLARGE,EFFICIENTNETB0,EFFICIENTNETB1,EFFICIENTNETB2,EFFICIENTNETB3,EFFICIENTNETB4,EFFICIENTNETB5,EFFICIENTNETB6,EFFICIENTNETB7,EFFICIENTNETV2B0,EFFICIENTNETV2B1,EFFICIENTNETV2B2,EFFICIENTNETV2B3,EFFICIENTNETV2S,EFFICIENTNETV2M,EFFICIENTNETV2L. Take a look atmodel characteristics, if you are not sure, which one to choose.defload_model(model:str)->None:Preload a model.Loading of desired model is done automatically at the first call ofclassify. But it can take significant time, if weights need to be downloaded. So you can preload a model.Usage examplesWith local files:importkeras_image_classificationasimage_classificationfile_path="path/to/image.png"labels=image_classification.classify(file_path,results=3,model=image_classification.INCEPTIONV3)print(labels)With byte-like objects (here withrequests):importrequestsimportkeras_image_classificationasimage_classificationresponse=requests.get("https://http.cat/100")assertresponse.status_code==200labels=image_classification.classify(response.content,results=3,model=image_classification.INCEPTIONV3)print(labels)You can also passpillowimages directly:importPILaspillowimportkeras_image_classificationasimage_classificationfile_path="path/to/image.png"image=pillow.Image.open(file_path)labels=image_classification.classify(image,results=3,model=image_classification.INCEPTIONV3)print(labels)Output:({'imagenet_id': 'n02123394', 'label': 'Persian_cat', 'probability': 0.7993967533111572},
 {'imagenet_id': 'n06359193', 'label': 'web_site', 'probability': 0.03162319213151932},
 {'imagenet_id': 'n03598930', 'label': 'jigsaw_puzzle', 'probability': 0.013497020117938519})
Package: keras-image-helper
Keras Image HelperA lightweight library for pre-processing images for pre-trained keras modelsImagine you have a Keras model. To use it, you need to apply a certain pre-processing
function to all the images. Something like that:fromtensorflow.keras.applications.xceptionimportpreprocess_inputWhat if you want to now deploy this model to AWS Lambda? Or deploy your model with TF-Serving?
You don't want to use the entire TensorFlow package just for that.The solution is simple - usekeras_image_helperUsageFor an xception model:fromkeras_image_helperimportcreate_preprocessorpreprocessor=create_preprocessor('xception',target_size=(299,299))url='http://bit.ly/mlbookcamp-pants'X=preprocessor.from_url(url)Now you can useXfor your model:preds=model.predict(X)That's all :tada:For more examples, checktest.ipynbCurrently you can use the following pre-processors:xceptionresnet50vgg16inception_v3If something you need is missing, PRs are welcomeInstallationIt's available on PyPI, so you can install it with pip:pipinstallkeras_image_helperOr with Pipenv:pipenvinstallkeras_image_helperYou can also install the latest version from this repo:gitclonegit@github.com:alexeygrigorev/keras-image-helper.git
pythonsetup.pyinstallPublishingUse twine for that:pipinstalltwineGenerate a wheel:pythonsetup.pysdistbdist_wheelCheck the packages:twinecheckdist/*Upload the library to test PyPI to verify everything is working:twineupload--repository-urlhttps://test.pypi.org/legacy/dist/*
Package: keras-layer-normalization
Keras Layer NormalizationImplementation of the paper:Layer NormalizationInstallpipinstallkeras-layer-normalizationUsagefromtensorflowimportkerasfromkeras_layer_normalizationimportLayerNormalizationinput_layer=keras.layers.Input(shape=(2,3))norm_layer=LayerNormalization()(input_layer)model=keras.models.Model(inputs=input_layer,outputs=norm_layer)model.compile(optimizer='adam',loss='mse',metrics={},)model.summary()
Package: keras-layernorm-rnn
keras-layernorm-rnnTable of ContentsInstallationUsageCommandsSupportContributingInstallationThekeras-layernorm-rnngit repois available asPyPi packagepip install keras-layernorm-rnn
pip install git+ssh://git@github.com/kmedian/keras-layernorm-rnn.gitUsageCheck theexamplesfolder for notebooks.import tensorflow as tf
from keras_layernorm_rnn import LayernormLSTM3

model = tf.keras.Sequential([
    LayernormLSTM3(units=8, return_sequences=False),  # Many-to-One
    tf.keras.layers.Dense(1, activation='linear')
])CommandsInstall a virtual environmentpython3 -m venv .venv
source .venv/bin/activate
pip3 install --upgrade pip
pip3 install -r requirements.txt(If your git repo is stored in a folder with whitespaces, then don't use the subfolder.venv. Use an absolute path without whitespaces.)Python commandsJupyter for the examples:jupyter labCheck syntax:flake8 --ignore=F401 --exclude=$(grep -v '^#' .gitignore | xargs | sed -e 's/ /,/g')Run Unit Test:python keras_layernorm_rnn/layernorm_simplernn_test.pyUpload to PyPi with twine:python setup.py sdist && twine upload -r pypi dist/*Clean upfind . -type f -name "*.pyc" | xargs rm
find . -type d -name "__pycache__" | xargs rm -r
rm -r .pytest_cache
rm -r .venvSupportPleaseopen an issuefor support.ContributingPlease contribute usingGithub Flow. Create a branch, add commits, andopen a pull request.
Package: keras-lookahead
Keras Lookahead[中文|English]Unofficial implementation of thelookahead mechanismfor optimizers.Installpipinstallkeras-lookaheadExternal Linkstensorflow/addons:LookAheadUsageArguments:optimizer: Original optimizer.sync_period: thekin the paper. The synchronization period.slow_step: theαin the paper. The step size of slow weights.fromkeras_lookaheadimportLookaheadoptimizer=Lookahead('adam',sync_period=5,slow_step=0.5)Custom optimizers can also be used:fromkeras_radamimportRAdamfromkeras_lookaheadimportLookaheadoptimizer=Lookahead(RAdam())
Package: keras-loves-torchtext
Keras ❤️ torchtextKeras is loveKeras is lifeKeras loves torchtexttorchtextis a great library, putting a layer of abstraction over the usually very heavy data component in NLP projects, making the work with complex datasets a pace.
Sadly, as torchtext is based and built on PyTorch, using it with Keras is not directly possible.Keras ❤️ torchtextis to the rescue by providing lightweight wrappers for some Torchtext classes, making them easily work with Keras.Installationpipinstallkeras-loves-torchtextExamplesWrap atorchtext.data.IteratorwithWrapIteratorand use it to train a Keras model:fromtorchtext.dataimportDataset,Field,IteratorfromklttimportWrapIterator...fields=[('text',Field()),('label',Field(sequential=False))]dataset=Dataset(examples,fields)iterator=Iterator(dataset,batch_size=32)# Keras ❤️ torchtext comes to playdata_gen=WrapIterator(iterator,x_fields=['text'],y_fields=['label'])model.fit_generator(iter(data_gen),steps_per_epoch=len(data_gen))Easily wrap multiple iterators at once:fromtorchtext.dataimportDataset,Field,IteratorfromklttimportWrapIterator...fields=[('text',Field()),('label',Field(sequential=False))]dataset=Dataset(examples,fields)splits=dataset.split()iterators=Iterator.splits(splits,batch_size=32)train,valid,test=WrapIterator.wraps(iterators,x_fields=['text'],y_fields=['label'])model.fit_generator(iter(train),steps_per_epoch=len(train),validation_data=iter(valid),validation_steps=len(valid))loss,acc=model.evaluate_generator(iter(test),steps=len(test))Further and full working examples can be found in theexamplesfolder.DocumentationTodoSeeexamplesand inline documentation for now.
Package: keras-lr-multiplier
Keras LR MultiplierThis repo is outdated and will no longer be maintained.Learning rate multiplier wrapper for optimizers.Installpipinstallgit+https://github.com/CyberZHG/keras-lr-multiplier.gitUsageBasicLRMultiplieris a wrapper for optimizers to assign different learning rates to specific layers (or weights). The first argument is the original optimizer which could be either an identifier (e.g.'Adam') or an initialized object (e.g.Adam(lr=1e-2)). The second argument is a dict that maps prefixes to learning rate multipliers. The multiplier for a weight is the value mapped from thelongest matched prefixin the given dict, and the default multiplier1.0will be used if there is no prefix matched.fromkeras.modelsimportSequentialfromkeras.layersimportDensefromkeras_lr_multiplierimportLRMultipliermodel=Sequential()model.add(Dense(units=5,input_shape=(5,),activation='tanh',name='Dense',))model.add(Dense(units=2,activation='softmax',name='Output',))model.compile(optimizer=LRMultiplier('adam',{'Dense':0.5,'Output':1.5}),loss='sparse_categorical_crossentropy',)LambdaThe multiplier can be a callable object. The input argument is the number of steps starting from 0.fromkerasimportbackendasKfromkeras_lr_multiplierimportLRMultiplierLRMultiplier('adam',{'Dense':lambdat:2.0-K.minimum(1.9,t*1e-4)})
Package: kerasltiprovider
Your short description here.into-ai.github.io/kerasltiprovider$pipinstallkerasltiproviderSee theofficial documentationfor more information.importkerasltiproviderDevelopmentTo get a development instance up and running quickly, run:$ FLASK_SECRET_KEY=123 ASSIGNMENTS_PY_CONFIG=$(realpath ./examples/sample_assignments.py) ENABLE_DEBUG_LAUNCHER=True PRODUCTION=False CONSUMER_KEY_SECRET=123=test python serve.pyFor detailed instructions seeCONTRIBUTING.TestsYou can run tests with$invoketest$invoketest--min-coverage=90# Fail when code coverage is below 90%$invoketype-check# Run mypy type checksLinting and formattingLint and format the code with$invokeformat$invokelintAll of this happens when you runinvokepre-commit.NoteThis project is still in the alpha stage and should not be considered production ready.
Package: kerasltisubmission
This python package allows you to submit your trainedkerasmodels to akerasltiprovider(seehere)
that proxies anyLTIconforming learning platform for grading.$pipinstallkerasltisubmissionimportkerasltisubmission# Looking for the provider?# See https://github.com/into-ai/kerasltiproviderprovider=LTIProvider(input_api_endpoint="http://localhost:8080",submission_api_endpoint="http://localhost:8080/submit",user_token="7dd7367c-40c2-43cb-a052-bb04e1d0a858",)# Submit your keras modelsubmission=Submission(assignment_id=12,model=model)provider.submit(submission)For a complete example, seeexample.py.
Also see theofficial documentationas well as thedocumentationof
thekerasltiprovider.DevelopmentFor detailed instructions seeCONTRIBUTING.TestsYou can run tests with$invoketest$invoketest--min-coverage=90# Fail when code coverage is below 90%$invoketype-check# Run mypy type checksLinting and formattingLint and format the code with$invokeformat$invokelintAll of this happens when you runinvokepre-commit.NoteThis project is still in the alpha stage and should not be considered production ready.
Package: keras-merge
Keras MergeKeras Merge allows to merge two Keras model instances without having access to
their generating functions.Release NotesVersionCommentv1.1Copying over weights from source models to merged model (active by default, disable using:km.merge(..., copy_weights=False))v1.0Initial ReleaseUsageimportkeras_mergeaskmfromkerasimportModel,Inputimportnumpyasnpfromkeras.utilsimportplot_modeldefmodel(mul:bool)->Model:x=Input(shape=(2,3))y=Input(shape=(2,3))ifmul:z=x*yelse:z=x+yreturnModel(inputs=[x,y],outputs=z)A=model(True)B=model(False)C=km.merge(A,B,# models[*A.inputs,B.inputs[0]],# inputsB.outputs,# outputs[# mapping [(src->dst), ...](A.outputs[0],B.inputs[1])])a=np.random.rand(1,2,3)b=np.random.rand(1,2,3)c=np.random.rand(1,2,3)d=A([a,b])e=B([c,d])f=C([a,b,c])print("A+B:    ",np.reshape(e,-1))print("Merged: ",np.reshape(f,-1))plot_model(A,to_file='A.png')plot_model(B,to_file='B.png')plot_model(C,to_file='C.png')How to buildpip3installillyrian
illyriankeras_merge.json
pip3installkeras_merge-1.0-py3-none-any.whl
Package: keras-metrics
Keras MetricsThis package provides metrics for evaluation of Keras classification models.
The metrics are safe to use for batch-based model evaluation.InstallationTo install the package from the PyPi repository you can execute the following
command:pipinstallkeras-metricsUsageThe usage of the package is simple:importkerasimportkeras_metricsaskmmodel=models.Sequential()model.add(keras.layers.Dense(1,activation="sigmoid",input_dim=2))model.add(keras.layers.Dense(1,activation="softmax"))model.compile(optimizer="sgd",loss="binary_crossentropy",metrics=[km.binary_precision(),km.binary_recall()])Similar configuration for multi-label binary crossentropy:importkerasimportkeras_metricsaskmmodel=models.Sequential()model.add(keras.layers.Dense(1,activation="sigmoid",input_dim=2))model.add(keras.layers.Dense(2,activation="softmax"))# Calculate precision for the second label.precision=km.binary_precision(label=1)# Calculate recall for the first label.recall=km.binary_recall(label=0)model.compile(optimizer="sgd",loss="binary_crossentropy",metrics=[precision,recall])Keras metrics package also supports metrics for categorical crossentropy and
sparse categorical crossentropy:importkeras_metricsaskmc_precision=km.categorical_precision()sc_precision=km.sparse_categorical_precision()# ...Tensorflow KerasTensorflow library provides thekeraspackage as parts of its API, in
order to usekeras_metricswith Tensorflow Keras, you are advised to
perform model training with initialized global variables:importnumpyasnpimportkeras_metricsaskmimporttensorflowastfimporttensorflow.kerasaskerasmodel=keras.Sequential()model.add(keras.layers.Dense(1,activation="softmax"))model.compile(optimizer="sgd",loss="binary_crossentropy",metrics=[km.binary_true_positive()])x=np.array([[0],[1],[0],[1]])y=np.array([1,0,1,0]# Wrap model.fit into the session with global# variables initialization.withtf.Session()ass:s.run(tf.global_variables_initializer())model.fit(x=x,y=y)
Package: keras-mixed-sequence
Lazily loading mixed sequences using Keras Sequence,
focused on multi-task models.How do I install this package?As usual, just download it using pip:pipinstallkeras_mixed_sequenceUsage examplesExample for traditional single-task modelsFirst of all let’s create a simple single-task model:fromtensorflow.keras.layersimportDensefromtensorflow.keras.modelsimportSequentialmodel=Sequential([Dense(1,activation="relu")])model.compile(optimizer="nadam",loss="relu")Then we proceed to load or otherwise create the training data.
Here there will be listed, in the future, some custom
Sequence objects that have been created for the purpose
of being used alongside this library.X=either_a_numpy_array_or_sequence_for_inputy=either_a_numpy_array_or_sequence_for_outputNow we combine the training data using the MixedSequence
object.fromkeras_mixed_sequenceimportMixedSequencesequence=MixedSequence(X,y,batch_size=batch_size)Finally, we can train the model:frommultiprocessingimportcpu_countmodel.fit_generator(sequence,steps_per_epoch=sequence.steps_per_epoch,epochs=2,verbose=0,use_multiprocessing=True,workers=cpu_count(),shuffle=True)Example for multi-task modelsFirst of all let’s create a simple multi-taks model:fromtensorflow.keras.modelsimportModelfromtensorflow.keras.layersimportDense,Inputinputs=Input(shape=(10,))output1=Dense(units=10,activation="relu",name="output1")(inputs)output2=Dense(units=10,activation="relu",name="output2")(inputs)model=Model(inputs=inputs,outputs=[output1,output2],name="my_model")model.compile(optimizer="nadam",loss="MSE")Then we proceed to load or otherwise create the training data.
Here there will be listed, in the future, some custom
Sequence objects that have been created for the purpose
of being used alongside this library.X=either_a_numpy_array_or_sequence_for_inputy1=either_a_numpy_array_or_sequence_for_output1y2=either_a_numpy_array_or_sequence_for_output2Now we combine the training data using the MixedSequence
object.fromkeras_mixed_sequenceimportMixedSequencesequence=MixedSequence(x=X,y={"output1":y1,"output2":y2},batch_size=batch_size)Finally, we can train the model:frommultiprocessingimportcpu_countmodel.fit_generator(sequence,steps_per_epoch=sequence.steps_per_epoch,epochs=2,verbose=0,use_multiprocessing=True,workers=cpu_count(),shuffle=True)
Package: keras-mixnets
Keras MixNets: Mixed Depthwise Convolutional KernelsKeras Implementation of MixNets from the paperMixNets: : Mixed Depthwise Convolution Kernels.Code ported from the official codebasehttps://github.com/tensorflow/tpu/blob/master/models/official/mnasnet/mixnetMixed Depthwise Convolutional KernelFrom the above paper, a Mixed Convolution is a group of convolutions with varying filter sizes. The paper suggests that [3x3, 5x5, 7x7] can be used safely without any loss in performance (and possible increase in performance), while a 9x9 or 11x11 may degrade performance if used without proper architecture search.UsageDue to the use of Model Subclassing, the keras model built *cannotbe deserialized usingload_model. You must build the model each time. tf.keras supports writing Layers which have additional Layers within them, but as Keras itself does not support it yet, these models cannot be deserialized usingload_model.fromkeras_mixnetsimportMixNetSmall# Medium and Large can also be usedmodel=MixNetSmall((224,224,3),include_top=True)WeightsWeights for these models have not been ported yet from Tensorflow.RequirementsTensorflow 1.14+ (Not 2.x)Keras 2.2.4+
Package: keras-model-client
keras-model-clientPython client API for theKeras Model Server.Install from PyPI:pipinstallkeras-model-clientBasic usage:fromkeras_model_clientimportpredict# Using Detectron2 with the default model serverresult=predict('/path/to/image.jpg','image_queue_detectron2')# Using YOLOv5 with a custom model serverresult=predict('/path/to/image.jpg','image_queue_yolov5',url='http://your-model-server/predictor/')print(result)# PredictionResult(success=True, predictions=[...])Note:The default model server is currently hosted athttps://adamant.tator.io:8082/.CLIThe package provides a command-line interface invoked withmodel-server-predict. For example:model-server-predict/path/to/image.jpgimage_queue_detectron2-fjsonwill run the image at/path/to/image.jpgthrough the Detectron2 model and format the results as JSON. Additional help is available with the-hor--helpflag.Install from sourceClone the repository:gitclonehttps://github.com/kevinsbarnard/keras-model-clientcdkeras-model-clientand install from source with Poetry:poetryinstallor with pip:pipinstall.
Package: keras-model-cv
Keras Cross-validationkeras-model-cvallows you to cross-validatekerasmodel.Installationpipinstallkeras-model-cvorpipinstallgit+https://github.com/dubovikmaster/keras-model-cv.gitQuickstartfromkeras_model_cvimportKerasCVfromsklearn.model_selectionimportKFoldimporttensorflowastftf.get_logger().setLevel("INFO")mnist=tf.keras.datasets.mnist(x_train,y_train),(x_test,y_test)=mnist.load_data()defbuild_model(hidden_units,dropout):model=tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,28)),tf.keras.layers.Dense(hidden_units,activation="relu"),tf.keras.layers.Dropout(dropout),tf.keras.layers.Dense(10),])model.compile(optimizer="adam",loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=["accuracy"],)returnmodelPARAMS={'hidden_units':16,'dropout':.3}if__name__=='__main__':cv=KerasCV(build_model,KFold(n_splits=3,random_state=1234,shuffle=True),PARAMS,preprocessor=tf.keras.layers.Normalization(),save_history=True,directory='my_awesome_project',name='my_cv',)cv.fit(x_train,y_train,verbose=0,epochs=3)print(cv.get_cv_score())Out:lossaccuracymean0.2831940.919783std0.0042150.002887You can add another aggregate function (for more info see:pandas.DataFrame.agg):print(cv.get_cv_score(agg_func={'loss':min,'accuracy':max}))Out:loss0.27959accuracy0.92010Also, you can get all train history for each splits aspandasdataframe:cv.get_train_history()Out:lossaccuracysplitepochs00.9572610.6793750110.5956460.8098500220.5411240.8248500330.8354930.7224751140.5745810.8109251250.5260980.8292001360.8131720.7362002170.5568710.8168752280.5129160.82955023You can show train history as matplotlib plot:cv.show_train_history()What about metrics per splits?cv.get_split_scores()Out:accuracylosssplit00.92010.282442010.91980.290500120.91730.2795902Ifsave_history=Truetrain history,  validation metrics and info about split will be saved to the specified directory.
In our example:my_awesome_project/|--my_cv/|--split_0/|--history.yml|--validation_metric.yml|--split_info.yml|--split_1/|--split_2/LicenceMIT license