Update Python easy update to Python 3.9 with homebrew – To update Mac os python from an older version to the latest python example python 3.9.1 you can do the folowing :
This article briefly describes how to replace its version of python on Mac. I wrote a similar article some time ago.
Comment faire un ping sur Filius ? Filius est un logiciel de simulation de réseau. Ce premier article présente la création d’un réseau ad hoc entre deux ordinateurs et l’utilisation la commande ping.
Etape 1 :
Ajouter les 2 ordinateurs et les relier par un câble réseau.
Filius configuration d’un réseau de 2 ordinateurs
Etape 2 :
Configurer le nom et l’adresse IP des ordinateurs, soit “Ordinateur A” : 198.168.0.10 et “Ordinateur B” : 198.168.0.20
Etape 3 :
Démarrer et installer la ligne de commande sur l’ordinateur A en cliquant dessus.
FIlius installation de la ligne de commande sur ordinateur A
Etape 4 :
Utiliser la commande ping 192.168.0.20. Ping est une commande qui envoie des paquets réseau vers l’adresse demandée et qui mesure les temps de réponse.
minikube v1.17.1 sur Darwin 10.15.7
✨ Utilisation du pilote ssh basé sur le profil existant
👍 Démarrage du noeud de plan de contrôle minikube dans le cluster minikube
🤦 StartHost failed, but will try again: config: please provide an IP address
😿 Failed to start ssh bare metal machine. Running "minikube delete" may fix it: config: please provide an IP address
❌ Exiting due to GUEST_PROVISION: Failed to start host: config: please provide an IP address
😿 If the above advice does not help, please let us know:
👉 https://github.com/kubernetes/minikube/issues/new/choose
Solution – starthost failed, but will try again: config: please provide an ip address
If you are running with docker you will find on https://minikube.sigs.k8s.io/docs/drivers/docker/ what i have done is to delete the last minkube cluster and rerun with the command specify the docker :
minikube delete
You will get :
🔄 Désinstallation de Kubernetes v1.20.2 à l'aide de kubeadm…
🔥 Trying to delete invalid profile minikube
And then :
minikube start --driver=docker
This is working :
😄 minikube v1.17.1 sur Darwin 10.15.7
✨ Utilisation du pilote docker basé sur la configuration de l'utilisateur
👍 Démarrage du noeud de plan de contrôle minikube dans le cluster minikube
🚜 Pulling base image ...
exiting due to drv_not_detected: no possible driver
😄 minikube v1.17.1 sur Darwin 10.15.7 👎 Unable to pick a default driver. Here is what was considered, in preference order: ▪ parallels : Not installed: exec: “prlctl”: executable file not found in $PATH ▪ podman : Not installed: exec: “podman”: executable file not found in $PATH ▪ virtualbox : Not installed: unable to find VBoxManage in $PATH ▪ vmware : Not installed: exec: “docker-machine-driver-vmware”: executable file not found in $PATH ▪ vmwarefusion : Not installed: the ‘vmwarefusion’ driver is no longer available ▪ docker : Not installed: exec: “docker”: executable file not found in $PATH ▪ hyperkit : Not installed: exec: “hyperkit”: executable file not found in $PATH
❌ Exiting due to DRV_NOT_DETECTED: No possible driver was detected. Try specifying –driver, or see https://minikube.sigs.k8s.io/docs/start/
When you try to launch :
minikube start
You get this error :
😄 minikube v1.17.1 sur Darwin 10.15.7
👎 Unable to pick a default driver. Here is what was considered, in preference order:
▪ parallels : Not installed: exec: "prlctl": executable file not found in $PATH
▪ podman : Not installed: exec: "podman": executable file not found in $PATH
▪ virtualbox : Not installed: unable to find VBoxManage in $PATH
▪ vmware : Not installed: exec: "docker-machine-driver-vmware": executable file not found in $PATH
▪ vmwarefusion : Not installed: the 'vmwarefusion' driver is no longer available
▪ docker : Not installed: exec: "docker": executable file not found in $PATH
▪ hyperkit : Not installed: exec: "hyperkit": executable file not found in $PATH
❌ Exiting due to DRV_NOT_DETECTED: No possible driver was detected. Try specifying --driver, or see https://minikube.sigs.k8s.io/docs/start/
Solution setup Docker with homebrew- Unable to pick a default driver :
You can setup Docker with Homebrew Cask : Homebrew Cask is a Homebrew extension for installing GUI software on Mac os like docker.
brew cask install docker
if you get :
Error: Calling `brew cask install` is disabled! Use brew install [--cask] instead.
Then use instead this command and it will works :
brew install docker --cask
Check docker version :
docker --version
If the command doesn’t works :
docker --version
zsh: command not found: docker
So you can run docker app in finder or in command line it will start docker desktop :
open /Applications/Docker.app
Then you can try again minikube :
minikube start
External links – exiting due to drv_not_detected: no possible driver:
runtimeerror: attempting to deserialize object on a cuda device but torch.cuda.is_available() is false. if you are running on a cpu-only machine, please use torch.load with map_location=torch.device(‘cpu’) to map your storages to the cpu, How to solve the error presented here with Pytorch in python in the context of deeplearning?
Introduction
First of all, usually this error is encountered when trying to run your model code on the machine’s CPU instead of the GPU.
lib/python3.6/site-packages/torch/serialization.py", ... in validate_cuda_device
raise RuntimeError('Attempting to deserialize object on a CUDA '
RuntimeError: Attempting to deserialize object on a CUDA device but
torch.cuda.is_available() is False. If you are running on a CPU-only machine,
please use torch.load with map_location='cpu' to map your storages to the CPU.
In this case you encounter an error which is a raised RuntimeError exception.
This means that you are looking to deserialize an object using code that runs with the GPU while the GPU is disabled.
Explanation – runtimeerror: attempting to deserialize object on a cuda device
So when the reloading is done with the wrong configuration you get the error:
lib/python3.6/site-packages/torch/serialization.py", ... in validate_cuda_device
raise RuntimeError('Attempting to deserialize object on a CUDA '
RuntimeError: Attempting to deserialize object on a CUDA device but
torch.cuda.is_available() is False. If you are running on a CPU-only machine,
please use torch.load with map_location='cpu' to map your storages to the CPU.
Solution
Also, As you can see in the Pytorch documentation (see https://pytorch.org/docs/stable/generated/torch.load.html) there is a map_location parameter – (a function, torch.device, string or a dict specifying how to remap storage locations).
This is where we must force the parameter to specify the location to use.
Note that if your model is registered and saved as using the GPU you will have to specify GPU otherwise you will have to put CPU. The objective here is to put a consistent parameter between what has been saved and what is reloaded.
# Load on first GPU
torch.load('mymodel.pt', map_location=lambda storage, loc: storage.cuda(1))
# Lord on GPU 0 and 1
torch.load('mymodel.pt', map_location={'cuda:1':'cuda:0'})
Now, to give change to an x value of using these coins and banknotes, then we will check the first element in the array. And if it’s greater than x, we move on to the next element. Otherwise let’s keep it. Now, after taking a valuable coin or bill from the array of coinAndBill [i], the total value x we need to do will become x – coinAndBill [i].
Here is the associated greedy python algorithm:
pieceEtBillets = [500,200,100,50,20,10,5,2,1]
i = 0
while(x>0):
if(pieceEtBillets[i] > x):
i = i+1
else:
print(str(pieceEtBillets[i]))
x -= pieceEtBillets[i];
renduMonnaieGlouton(33)#Exemple sur 33 euros
A greedy python algorithm (greedy algorithm python) greedily selects the best choice at every step. He hopes that these choices lead to the optimal overall solution to the problem. So, a greedy algorithm does not always give the best solution. However in many problems this is the case.
Greedy Algorithm: Introduction
The problem of giving change is formulated as follows. How to return a given sum with a minimum of coins and banknotes?
Here is an example in python of the resolution of the problem:
If we consider the Euro monetary system without the cents we have the whole
EURO = (1, 2, 5, 10, 20, 50, 100, 200, 500)
Greedy algorithm python : Coin change problem
Now, to give change to an x value of using these coins and banknotes, then we will check the first element in the array. And if it’s greater than x, we move on to the next element. Otherwise let’s keep it. Now, after taking a valuable coin or bill from the array of coinAndBill [i], the total value x we need to do will become x – coinAndBill [i].
Here is the associated greedy python algorithm:
def renduMonnaieGlouton(x):
pieceEtBillets = [500,200,100,50,20,10,5,2,1]
i = 0
while(x>0):
if(pieceEtBillets[i] > x):
i = i+1
else:
print(str(pieceEtBillets[i]))
x -= pieceEtBillets[i];
renduMonnaieGlouton(33)#Exemple sur 33 euros
The output for 33 euro is then:
20
10
2
1
Another example with 55 euro of greedy python algorithm:
def renduMonnaieGlouton(x):
pieceEtBillets = [500,200,100,50,20,10,5,2,1]
i = 0
while(x>0):
if(pieceEtBillets[i] > x):
i = i+1
else:
print(str(pieceEtBillets[i]))
x -= pieceEtBillets[i];
renduMonnaieGlouton(55)#Exemple sur 55 euros
Output :
50
5
Conclusion
The problem of giving change is NP-difficult relative to the number of coins and notes of the monetary system considered (euro in this example). To go further, we can demonstrate that for certain so-called canonical money systems, the use of a greedy algorithm is optimal. A monetary system is said to be canonical if for any sum s the greedy algorithm leads to a minimal decomposition.
NP difficulty is the defining property of a class of problems informally “at least as difficult as the most difficult NP problems”.
A simple example of an NP-hard problem is the sum of subset problem. If P is different from NP then it is unlikely to find a polynomial time algorithm that exactly solves this problem.
Here is the levenshtein python implementation of the Wagner & Fischer algorithm (Wagner-Fischer). It allows to calculate the distance of Levenshtein (distance between two strings of characters).
First, the goal of the algorithm is to find the minimum cost. Minimal cost to transform one channel into another. Then a recursive function allows to return the minimum number of transformation. And to transform a substring of A with n characters into a substring of B with the same number of characters. The solution is given. We must calculate the distance between the 2 letters at the same position in the chain A and B. Then Either the letters and the previous letter are identical. Either there is a difference and in this case we calculate 3 costs. So the first is to delete a letter from the chain A. And insert a letter in the chain A to substitute a letter from the chain A. Then we can then find the minimum cost.
Example of levenshtein python implementation :
import numpy as np
def levenshtein(chaine1, chaine2):
taille_chaine1 = len(chaine1) + 1
taille_chaine2 = len(chaine2) + 1
levenshtein_matrix = np.zeros ((taille_chaine1, taille_chaine2))
for x in range(taille_chaine1):
levenshtein_matrix [x, 0] = x
for y in range(taille_chaine2):
levenshtein_matrix [0, y] = y
for x in range(1, taille_chaine1):
for y in range(1, taille_chaine2):
if chaine1[x-1] == chaine2[y-1]:
levenshtein_matrix [x,y] = min(
levenshtein_matrix[x-1, y] + 1,
levenshtein_matrix[x-1, y-1],
levenshtein_matrix[x, y-1] + 1
)
else:
levenshtein_matrix [x,y] = min(
levenshtein_matrix[x-1,y] + 1,
levenshtein_matrix[x-1,y-1] + 1,
levenshtein_matrix[x,y-1] + 1
)
return (levenshtein_matrix[taille_chaine1 - 1, taille_chaine2 - 1])
print("distance de levenshtein = " + str(levenshtein("Lorem ipsum dolor sit amet", "Laram zpsam dilir siy amot")))
To calculate the Levenshtein distance with a non-recursive algorithm. We use a matrix which contains the Levenshtein distances. Then These are the distances between all the prefixes of the first string and all the prefixes of the second string.
Also we can dynamically calculate the values in this matrix. The last calculated value will be the Levenshtein distance between the two whole chains.
Finally there are many use cases of the Levenshtein distance. Levenshtein distance is used in domains. Computational linguistics, molecular biology. And again bioinformatics, machine learning. Also deep learning, DNA analysis. In addition, a program that does spell checking uses, for example, the Levenshtein distance.
Links on the Wagner & Fischer algorithm (Wagner-Fischer) and the Levenshtein python distance or other language:
There are several approaches to recording (serializing) and loading (deserialize) patterns for inference in PyTorch.
For example you may need to load a model that is already trained and back up that comes from the internet. More recently I answered this question on a discussion forum https://discuss.pytorch.org/t/i-want-to-do-machine-learning-with-android/98753. I take advantage of this article to give some details.
SAVE AND LOAD OF A PRE-TRAINED MODE with load_state_dict
In PyTorch you can save a model by storing in its file its state_dict these are Python dictionaries, they can be easily recorded, updated, modified and restored, adding great modularity to PyTorch models and optimizers.
Otherwise if you don’t make this adjustment don’t have the ability to launch on a GPU you’ll get the following error:
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location-torch.device ('cpu') to map your storages to the CPU.
TorchScript is a way to create models that can be made that can be optimized from the PyTorch code.
Any TorchScript program can be saved from a Python process and loaded into a process where there is no Python dependency.
The code below allows you to save the pre-trained ESPNet model that was backed up by the classic torch.save method via the use of TorchScript.
import torch
model = ESPNet(20,encoderFile="espnet_p_2_q_8.pth", p=2, q=8)
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
#Exemple de save avec TorchScript
torch.jit.save(traced_script_module, "scriptmodel.pth")
An example for loader via TorchScript below:
import torch
model = torch.jit.load("scriptmodel.pth")
The problem of the algorithmic backpack is interesting and is part of the first digital science and computer science program.
This problem illustrates the gluttonous algorithms that list all the possibilities of solving a problem to find the best solution.
The problem of the backpack is a problem of optimization, i.e. a function that must be maximized or minimized and constraints that must be met.
The problem of the backpack
For a backpack of maximum capacity of P and N items each with its own weight and a set value, throw the items inside the backpack so that the final contents have maximum value.
Example of a statement:
Maximum backpack capacity: 11 units
Item number: 5
Object Values: $10.50,20,30.60
Weight of Objects: '1,5,3,2,4'
What is the maximum value that can be put in the backpack considering the maximum capacity constraint of the bag which is 11?
Gluttonous algorithm
An effective solution is to use a gluttonous algorithm. The idea is to calculate the value/weight ratio for each object and sort the object based on this calculated ratio.
You take the object with the highest ratio and add until you can't add any more.
In fractional version it is possible to add fractions of item to the backpack.
Implementation of the problem in non-fractional version
Here is an implementation of the problem in a non-fractional version, i.e. you can't add a fraction of an object to the bag. Only whole objects can be added.
itemsac class:
def __init__ (self, weight, value, index):
self.index - index
self.weight - weight
self.value
self.report - value // weight
#Fonction for comparison between two ObjectsSac
#On compares the ratio calculated to sort them
def __lt__ (self, other):
return self.report< other.rapport
def getValeurMax (weights, values, ability):
TableTrie[]
for i in range:
tableTrie.append (ObjectSac (weigh[i]ts, value[i]s, i))
#Trier the elements of the bag by their report
tableTrie.sort (reverse - True)
MeterValeur - 0
for object in tableauTrie:
WeightCourant - int (object.weight)
ValueCourante - int (object.value)
if capacity - weightsCourant '0:
#on adds the object to the bag
#On subtracts capacity
capacity - weightsCourant
MeterValeur - ValueCourante
#On adds value to the bag
return counterValeur
Weights[1,5,3,2,4]
Values[10,50,20,30,60]
capacity - 11
Maximum value - getValeurMax (weight, values, capacity)
print ("Maximum value in the backpack," ValueMax)
The result is as follows:
py sacados.py
Maximum value in backpack - 120
Implementation of the problem in fractional version
In a fractional version of the backpack problem you can add fractions of object to the backpack.
itemsac class:
def __init__ (self, weight, value, index):
self.index - index
self.weight - weight
self.value
self.report - value // weight
#Fonction for comparison between two ObjectsSac
#On compares the ratio calculated to sort them
def __lt__ (self, other):
return self.report< other.rapport
def getValeurMax (weights, values, ability):
TableTrie[]
for i in range:
tableTrie.append (ObjectSac (weigh[i]ts, value[i]s, i))
#Trier the elements of the bag by their report
tableTrie.sort (reverse - True)
MeterValeur - 0
for object in tableauTrie:
WeightCourant - int (object.weight)
ValueCourante - int (object.value)
if capacity - weightsCourant '0:
#on adds the object to the bag
#On subtracts capacity
capacity - weightsCourant
MeterValeur - ValueCourante
#On adds value to the bag
else
fraction - capacity / weightCouring
MeterValeur -Courante value - fraction
capacity - int (capacity - (weightsCourant - fraction))
Break
return counterValeur
Weights[1,5,3,2,4]
Values[10,50,20,30,60]
capacity - 11
Maximum value - getValeurMax (weight, values, capacity)
print ("Maximum value in the backpack," ValueMax)