Jupyter notebook into post

download jupyter notebook as html,

add that html source code to XYZ Html

embed that to post like

scatter
In [1]:
import numpy as np

from bokeh.plotting import figure, show, output_file
from bokeh.io import output_notebook

N = 4000
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
radii = np.random.random(size=N) * 1.5
colors = ["#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)]
In [2]:
output_notebook()
Loading BokehJS ...
In [3]:
p = figure()

p.scatter(x, y, radius=radii,
          fill_color=colors, fill_alpha=0.6,
          line_color=None)

# output_file("color_scatter.html", title="color_scatter.py example")

show(p)  # open a browser
In [ ]:
 
explore-Copy1
In [1]:
import pandas as pd
import matplotlib.pyplot as plt
from time import time

%matplotlib inline
plt.rcParams['figure.figsize'] = (1.5, 1.5) # set default size of plots
# plt.rcParams['image.interpolation'] = 'nearest'
# plt.rcParams['image.cmap'] = 'gray'
In [2]:
from sklearn.decomposition import PCA, RandomizedPCA, randomized_svd
from sklearn.cluster import KMeans
from sklearn.manifold import Isomap
from sklearn.model_selection import train_test_split, KFold
In [3]:
train=pd.read_csv('train.csv')
test=pd.read_csv('test.csv')
train.shape,test.shape
Out[3]:
((42000, 785), (28000, 784))
In [4]:
train.head(1)
Out[4]:
label pixel0 pixel1 pixel2 pixel3 pixel4 pixel5 pixel6 pixel7 pixel8 ... pixel774 pixel775 pixel776 pixel777 pixel778 pixel779 pixel780 pixel781 pixel782 pixel783
0 1 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0

1 rows × 785 columns

In [5]:
test.head(1)
Out[5]:
pixel0 pixel1 pixel2 pixel3 pixel4 pixel5 pixel6 pixel7 pixel8 pixel9 ... pixel774 pixel775 pixel776 pixel777 pixel778 pixel779 pixel780 pixel781 pixel782 pixel783
0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0

1 rows × 784 columns

In [9]:
label=train.pop('label')
In [7]:
def fuckpca(train,test,n):
    start=time()
    pca=PCA(n_components=n,whiten=True)
    train=pca.fit_transform(train)
    test=pca.transform(test)
    print 'used {:.2f}s'.format(time()-start)
    return train,test
In [8]:
train_pca,test_pca=fuckpca(train,test,36)
used 4.97s
In [9]:
train_pca.shape,test_pca.shape
Out[9]:
((42000L, 36L), (28000L, 36L))
In [10]:
plt.imshow(train_pca[3].reshape(6,-1))
Out[10]:
<matplotlib.image.AxesImage at 0x1b99b358>
In [11]:
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor
In [12]:
model=GradientBoostingClassifier(verbose=1,n_estimators=300)
model
Out[12]:
GradientBoostingClassifier(criterion='friedman_mse', init=None,
              learning_rate=0.1, loss='deviance', max_depth=3,
              max_features=None, max_leaf_nodes=None,
              min_impurity_split=1e-07, min_samples_leaf=1,
              min_samples_split=2, min_weight_fraction_leaf=0.0,
              n_estimators=300, presort='auto', random_state=None,
              subsample=1.0, verbose=1, warm_start=False)
In [99]:
start=time()
model.fit(train_pca,label)
print 'used {:.2f}s'.format(time()-start)
      Iter       Train Loss   Remaining Time 
         1       79940.9682            6.62m
         2       70830.7802            6.62m
         3       64173.7553            6.61m
         4       59037.7864            6.58m
         5       54599.3908            6.58m
         6       50886.2372            6.57m
         7       47761.6971            6.55m
         8       45040.9071            6.54m
         9       42543.2014            6.55m
        10       40319.8099            6.56m
        20       27069.1592            6.42m
        30       20786.5203            6.28m
        40       17051.2103            6.03m
        50       14576.1295            5.82m
        60       12778.5881            5.59m
        70       11447.6600            5.35m
        80       10375.5170            5.12m
        90        9518.4201            4.88m
       100        8816.3706            4.64m
       200        5027.3031            2.26m
       300        3355.2391            0.00s
used 405.63s
In [100]:
result=model.predict(test_pca)
In [ ]:
 
In [13]:
def save():
    import numpy as np
    submit=pd.DataFrame({'ImageId':np.arange(1,len(result)+1),'Label':result})
    submit.to_csv('gbc.csv',index=False)
In [14]:
# sub=pd.concat([pd.Series(np.arange(1,len(result)+1)),pd.Series(result)],axis=1)
# sub.columns=['ImageId','Label']
In [108]:
model.score(after,label)
Out[108]:
0.9878095238095238
In [115]:
tr=model.predict(after)
In [128]:
(tr==label).sum()/float(label.shape[0])
Out[128]:
0.9878095238095238
In [129]:
from sklearn.metrics import confusion_matrix
In [ ]:
 
In [4]:
from sklearn.svm import SVC
In [5]:
svc=SVC(verbose=1)
svc
Out[5]:
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=1)
In [7]:
train_pca=train
test_pca=test
In [10]:
start=time()
svc.fit(train_pca,label)
print 'used {:.2f}s'.format(time()-start)
[LibSVM]used 4429.63s
In [19]:
result=svc.predict(test_pca)
In [21]:
save()
In [17]:
from sklearn import svm,datasets
from sklearn.model_selection import GridSearchCV
In [13]:
iris = datasets.load_iris()
iris.data[0:4]
Out[13]:
array([[ 5.1,  3.5,  1.4,  0.2],
       [ 4.9,  3. ,  1.4,  0.2],
       [ 4.7,  3.2,  1.3,  0.2],
       [ 4.6,  3.1,  1.5,  0.2]])
In [14]:
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 5, 10]}
In [15]:
model = svm.SVC()
In [18]:
classifier =GridSearchCV(model, parameters)
In [19]:
classifier.fit(iris.data, iris.target)
Out[19]:
GridSearchCV(cv=None, error_score='raise',
       estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False),
       fit_params={}, iid=True, n_jobs=1,
       param_grid={'kernel': ('linear', 'rbf'), 'C': [1, 5, 10]},
       pre_dispatch='2*n_jobs', refit=True, return_train_score=True,
       scoring=None, verbose=0)
In [20]:
classifier.best_params_
Out[20]:
{'C': 1, 'kernel': 'linear'}
In [37]:
# classifier.cv_results_
In [38]:
classifier.best_estimator_
Out[38]:
SVC(C=1, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='linear',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)
In [24]:
import scipy
In [33]:
print scipy.stats.expon(scale=100)
<scipy.stats._distn_infrastructure.rv_frozen object at 0x0000000008E57E10>
In [ ]:
 
In [39]:
parameter_dist = {
  'C': scipy.stats.expon(scale=100),
  'kernel': ['linear'],
  'gamma': scipy.stats.expon(scale=.1),
}
In [119]:
classifier = grid_search.RandomizedSearchCV(model, parameter_dist)
classifier.fit(iris.data, iris.target)
Out[119]:
RandomizedSearchCV(cv=None, error_score='raise',
          estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False),
          fit_params={}, iid=True, n_iter=10, n_jobs=1,
          param_distributions={'kernel': ['linear'], 'C': <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000000008E79FD0>, 'gamma': <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000000008E70080>},
          pre_dispatch='2*n_jobs', random_state=None, refit=True,
          scoring=None, verbose=0)
In [120]:
classifier.best_params_, classifier.best_score_
Out[120]:
({'C': 1.3991944739478859, 'gamma': 0.0022802232812657304, 'kernel': 'linear'},
 0.9933333333333333)
In [63]:
wtf=scipy.stats.expon(scale=10)
In [66]:
print wtf.rvs(5)
[ 10.29516445   1.53962143   2.67578885   0.21101641   1.31133069]
In [ ]:
wtf.rvs
In [ ]:
 

Leave a Reply

Your email address will not be published.