1
1
# https://deeplearningcourses.com/c/data-science-supervised-machine-learning-in-python
2
2
# https://www.udemy.com/data-science-supervised-machine-learning-in-python
3
3
# This is an example of a Bayes classifier on MNIST data.
4
+ from __future__ import print_function , division
5
+ from future .utils import iteritems
6
+ from builtins import range , input
7
+ # Note: you may need to update your version of future
8
+ # sudo pip install -U future
9
+
4
10
5
11
import numpy as np
6
12
from util import get_data
9
15
from scipy .stats import multivariate_normal as mvn
10
16
11
17
class Bayes (object ):
12
- def fit (self , X , Y , smoothing = 10e-3 ):
18
+ def fit (self , X , Y , smoothing = 1e-2 ):
13
19
N , D = X .shape
14
20
self .gaussians = dict ()
15
21
self .priors = dict ()
@@ -30,27 +36,27 @@ def predict(self, X):
30
36
N , D = X .shape
31
37
K = len (self .gaussians )
32
38
P = np .zeros ((N , K ))
33
- for c , g in self .gaussians . iteritems ( ):
39
+ for c , g in iteritems ( self .gaussians ):
34
40
mean , cov = g ['mean' ], g ['cov' ]
35
41
P [:,c ] = mvn .logpdf (X , mean = mean , cov = cov ) + np .log (self .priors [c ])
36
42
return np .argmax (P , axis = 1 )
37
43
38
44
39
45
if __name__ == '__main__' :
40
46
X , Y = get_data (10000 )
41
- Ntrain = len (Y ) / 2
47
+ Ntrain = len (Y ) // 2
42
48
Xtrain , Ytrain = X [:Ntrain ], Y [:Ntrain ]
43
49
Xtest , Ytest = X [Ntrain :], Y [Ntrain :]
44
50
45
51
model = Bayes ()
46
52
t0 = datetime .now ()
47
53
model .fit (Xtrain , Ytrain )
48
- print "Training time:" , (datetime .now () - t0 )
54
+ print ( "Training time:" , (datetime .now () - t0 ) )
49
55
50
56
t0 = datetime .now ()
51
- print "Train accuracy:" , model .score (Xtrain , Ytrain )
52
- print "Time to compute train accuracy:" , (datetime .now () - t0 ), "Train size:" , len (Ytrain )
57
+ print ( "Train accuracy:" , model .score (Xtrain , Ytrain ) )
58
+ print ( "Time to compute train accuracy:" , (datetime .now () - t0 ), "Train size:" , len (Ytrain ) )
53
59
54
60
t0 = datetime .now ()
55
- print "Test accuracy:" , model .score (Xtest , Ytest )
56
- print "Time to compute test accuracy:" , (datetime .now () - t0 ), "Test size:" , len (Ytest )
61
+ print ( "Test accuracy:" , model .score (Xtest , Ytest ) )
62
+ print ( "Time to compute test accuracy:" , (datetime .now () - t0 ), "Test size:" , len (Ytest ) )
0 commit comments