Credits: Forked from Parallel Machine Learning with scikit-learn and IPython by Olivier Grisel
importnumpyasnp
a=np.array([1,2,3])print(a)print(a.shape)print(a.dtype)
[1 2 3] (3,) int64
b=np.array([[0,2,4],[1,3,5]])print(b)print(b.shape)print(b.dtype)
[[0 2 4] [1 3 5]] (2, 3) int64
np.zeros(5)
array([0., 0., 0., 0., 0.])
np.ones(shape=(3,4),dtype=np.int32)
array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], dtype=int32)
c=b*0.5print(c)print(c.shape)print(c.dtype)
[[0. 1. 2. ] [0.5 1.5 2.5]] (2, 3) float64
d=a+cprint(d)
[[1. 3. 5. ] [1.5 3.5 5.5]]
d[0]
array([1., 3., 5.])
d[0,0]
1.0
d[:,0]
array([1. , 1.5])
d.sum()
19.5
d.mean()
3.25
d.sum(axis=0)
array([ 2.5, 6.5, 10.5])
d.mean(axis=1)
array([3. , 3.5])
e=np.arange(12)print(e)
[ 0 1 2 3 4 5 6 7 8 9 10 11]
# f is a view of contents of ef=e.reshape(3,4)print(f)
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]]
# Set values of e from index 5 onwards to 0e[5:]=0print(e)
[0 1 2 3 4 0 0 0 0 0 0 0]
# f is also updatedf
array([[0, 1, 2, 3], [4, 0, 0, 0], [0, 0, 0, 0]])
# OWNDATA shows f does not own its dataf.flags
C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False
a
array([1, 2, 3])
b
array([[0, 2, 4], [1, 3, 5]])
d
array([[1. , 3. , 5. ], [1.5, 3.5, 5.5]])
np.concatenate([a,a,a])
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
# Use broadcasting when needed to do this automaticallynp.vstack([a,b,d])
array([[1. , 2. , 3. ], [0. , 2. , 4. ], [1. , 3. , 5. ], [1. , 3. , 5. ], [1.5, 3.5, 5.5]])
# In machine learning, useful to enrich or # add new/concatenate features with hstacknp.hstack([b,d])
array([[0. , 2. , 4. , 1. , 3. , 5. ], [1. , 3. , 5. , 1.5, 3.5, 5.5]])
%matplotlib inline importpylabaspltimportseabornseaborn.set()
# Create evenly spaced numbers over the specified intervalx=np.linspace(0,2,10)plt.plot(x,'o-');plt.show()
# Create sample data, add some noisex=np.random.uniform(1,100,1000)y=np.log(x)+np.random.normal(0,.3,1000)plt.scatter(x,y)plt.show()
importnumpyasnpZL=np.array([[5],[2],[-1],[3]])ZL
array([[ 5], [ 2], [-1], [ 3]])
t=np.exp(ZL)t
array([[148.4131591 ], [ 7.3890561 ], [ 0.36787944], [ 20.08553692]])
# sum of ti and this we do by normalizing thse entries, lets add them upnp.sum(t)
176.25563156586637
AL=t/np.sum(t)AL
array([[0.84203357], [0.04192238], [0.00208719], [0.11395685]])