/
blogger_py.py
323 lines (303 loc) · 12.6 KB
/
blogger_py.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# -*- coding: utf-8 -*-
"""blogger_py.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1pjzSPxUXmQJxyiVjpq-Aog-T7MsUoEav
"""
import numpy,pylab,torch,torchvision
import torchvision.transforms as transforms
tr0=(0.5,0.5,0.5)
transform=transforms.Compose([transforms.ToTensor(),
transforms.Normalize(tr0,tr0)])
trainset=torchvision.datasets.CIFAR10(root='./data',
train=True,
download=True,
transform=transform)
trainloader=torch.utils.data.DataLoader(trainset,
batch_size=int(8),
shuffle=True,
num_workers=int(2))
classes=('plane','car','bird','cat','deer',
'dog','frog','horse','ship','truck')
def imshow(img):
npimg=img.numpy()/2.0+0.5
pylab.figure(figsize=(11,2))
tr1=(int(1),int(2),int(0))
pylab.imshow(numpy.transpose(npimg,tr1))
pylab.show()
dataiter=iter(trainloader); images,labels=dataiter.next()
imshow(torchvision.utils.make_grid(images))
print(' '.join('%5s'%classes[labels[j]]
for j in range(8)))
import networkx as nx, pylab as pl
G3=nx.MultiDiGraph()
pl.figure(figsize=(9,9)); pl.axis('off')
edges=[('♔','♕'),('♔','♖'),('♔','♗'),
('♔','♘'),('♕','♘'),('♖','♘'),
('♖','♚'),('♖','♛'),('♗','♖'),
('♗','♚'),('♘','♛'),('♚','♛'),
('♛','♜'),('♛','♝'),('♜','♝'),('♜','♞')]
G3.add_edges_from(edges); pos=nx.shell_layout(G3)
nx.draw_networkx_edges(G3,pos,width=3,alpha=.5,
edge_color='slategray',
arrowsize=50,arrowstyle='-|>')
nx.draw_networkx_nodes(G3,pos,node_size=1600,alpha=.7,
node_shape='h',node_color='steelblue')
nx.draw_networkx_labels(G3,pos,font_size=25,
font_weight='bold');
"""The fragment of the truth table of the expression F is given. <br/>
Values in empty table cells are unknown and can be any of the possible ones.<br/>
x1 x2 x3 F <br/>
0 <br/>
0 1 0 0 <br/>
List in ascending order without commas and spaces <br/>
the numbers of logical expressions that can correspond to F.
- 1) ¬x1∧x2∧¬x3
- 2) x1∨¬x2∨¬x3
- 3) x1∧¬x2∧¬x3
- 4) ¬x1∧¬x2∧x3
- 5) x1∨¬x2∨x3
"""
def F(x):
return [int((not x[0]) and x[1] and (not x[2])),
int(x[0] or (not x[1]) or (not x[2])),
int(x[0] and (not x[1]) and (not x[2])),
int((not x[0]) and (not x[1]) and x[2]),
int(x[0] or (not x[1]) or x[2])]
def Fcheck(f,x):
print('[x1,x2,x3] =',x,'=> [F1,F2,F3,F4,F5] =',f(x))
n=[i for i in range(len(f(x))) if f(x)[i]==0]
bc=[[x1,x2,x3]
for x1 in [0,1] for x2 in [0,1] for x3 in [0,1]]
s,c='',0; print('Truth Tables')
for i in n:
print('F',i+1)
for el in bc:
if F(el)[i]==0: c+=1
print(el,F(el)[i])
if c>1: s+=str(i+1)
print('F',i+1,'= 0 in',c,'cases'); c=0
print('Answer:',s)
Fcheck(F,[0,1,0])
"""These symbols are encoded unequally (along the length) by code: A-0, Б-10, В-110, Г-111. <br/>
The initial message: ВГВБАВА. Encode the message with this code. <br/>
Obtain the resulting sequence in a hexadecimal form. <br/>
In the answer, write down the sequence of hexadecimal digits without commas.
"""
def strdecode(s):
s0=s; ln=[('А','0'),('Б','10'),('В','110'),('Г','111')]
for (l,n) in ln: s=s.replace(l,n)
print(s0,' => ',s,' => ',hex(int(s,2))[2:].upper())
strdecode('ВГВБАВА')
import numpy,pandas
style_dict={'font-size':'150%','text-shadow':'#aaa 2px 2px 2px'}
head_styler=(('color','slategray'),('font-size','200%'),
('text-shadow','#aaa 2px 2px 2px'))
index=[chr(i) for i in range(ord('a'),ord('h')+1)];
columns=['♔','♕','♖',
'♗','♘','♙']
df=pandas.DataFrame(numpy.random.randn(8,6),
index=index,columns=columns)
df.style.set_properties(**style_dict)\
.background_gradient(cmap='Pastel1')\
.set_table_styles([dict(selector='th',props=head_styler)])
# Commented out IPython magic to ensure Python compatibility.
import pylab; from skimage import data,color,measure
from IPython.core.magic import register_line_magic
@register_line_magic
def vector(file):
img=data.imread("https://olgabelitskaya.github.io/"+file)
level=.855; gray_img=color.colorconv.rgb2grey(img)
contours=measure.find_contours(gray_img,level)
pylab.figure(figsize=(9,9)); pylab.gca().invert_yaxis()
[pylab.plot(c[:,1],c[:,0],lw=1) for c in contours]
pylab.xticks([]); pylab.yticks([]); pylab.show()
# %vector pattern03.jpeg
import cv2,pylab,urllib; path='https://olgabelitskaya.github.io/new/'
for f in ['10.png','24.png']:
input_file=urllib.request.urlopen(path+f); output_file=open(f,'wb')
output_file.write(input_file.read())
output_file.close(); input_file.close()
edge=cv2.imread('10.png'); edge2=cv2.imread('24.png');
edge=cv2.GaussianBlur(edge,(2*3+1,2*3+1),-1)[3:-3,3:-3]
edge2=cv2.GaussianBlur(edge2,(2*5+1,2*5+1),-1)[5:-5,5:-5]
s1='size: %s, shape: %s, type: %s'%(edge.size,edge.shape,edge.dtype)
s2='size: %s, shape: %s, type: %s'%(edge2.size,edge2.shape,edge2.dtype)
gray_edge=cv2.cvtColor(edge,cv2.COLOR_BGR2GRAY)
gray_edge2=cv2.cvtColor(edge2,cv2.COLOR_BGR2GRAY)
edges=cv2.Canny(gray_edge,60,230); edge[edges!=0]=(0,0,255)
edges2=cv2.Canny(gray_edge2,50,120); edge2[edges2!=0]=(0,0,255)
pylab.figure(figsize=(12,7))
pylab.subplot(121); pylab.title(s1,fontsize=10,loc='left')
pylab.imshow(cv2.cvtColor(edge,cv2.COLOR_BGR2RGB))
pylab.subplot(122); pylab.title(s2,fontsize=10,loc='left')
pylab.imshow(cv2.cvtColor(edge2,cv2.COLOR_BGR2RGB))
pylab.show()
import pylab,numpy
columns=['Fresh','Milk','Grocery','Frozen',
'Detergents_Paper','Delicatessen']
rows=['Customer 1','Customer 2','Customer 3']
colors = ['#3636ff','#36ff36','#ff3636']
data=[[26373,36423,22019,5154,4337,16523],
[16165,4230,7595,201,4003,57],
[14276,803,3045,485,100,518]]
pylab.figure(figsize=(12,7))
pylab.ylabel('Value'); pylab.xticks([]);
x=numpy.arange(len(columns))+0.2
y=numpy.array([0.0]*len(columns))
bar_width=0.5; cell_text=[]
for i in range(len(rows)):
pylab.bar(x,data[i],bar_width,bottom=y,color=colors[i])
y=y+data[i]; cell_text.append(['%1.0f'%(d)for d in data[i]])
pylab.table(cellText=cell_text,rowLabels=rows,
rowColours=colors,colLabels=columns,loc='bottom')
pylab.title('Samples of the Wholesale Customers Dataset')
pylab.subplots_adjust(left=0.1,bottom=0.05); pylab.show()
from sklearn.feature_extraction.text import CountVectorizer
corpus=['Have you already set your goals for the New Year?',
'Do you want to lose ten kilos, run a marathon or speak fluent English?',
'Some experts believe that you need systems, not goals.',
'A system is something you do on a regular basis. ',
'This means focusing on what you can control (your actions) rather than what you can’t.',
'For example, do not focus on losing ten kilos.',
'Focus on shopping for healthy food and cooking something light every day.',
'Do not focus on the marathon.',
'Focus on the training schedule.',
'Invent a system to improve your English, one step at a time.',
'Good luck!']
c_vectorizer=CountVectorizer(min_df=1); corpus_features=c_vectorizer.fit_transform(corpus)
corpus_array=corpus_features.toarray().astype('int16'); c_analyzer=c_vectorizer.build_analyzer()
import pylab; pylab.figure(figsize=(12,7))
pylab.title("The Words' Occurrence in Sentences",fontsize=12)
for i in range(len(corpus_array)):
pylab.scatter(range(len(corpus_array[i])),(corpus_array[i]*0.5+i),marker='s')
pylab.grid(); pylab.show()
import numpy,pylab,time
from sklearn import manifold,datasets
X,y=datasets.load_digits(return_X_y=True)
tsne=manifold.TSNE(n_components=2,learning_rate=700.0)
t0=time.time(); X_emb=tsne.fit_transform(X)
t=time.time()-t0
x_min,x_max=numpy.min(X_emb,0),numpy.max(X_emb,0)
X_emb=(X_emb-x_min)/(x_max-x_min)
f,ax=pylab.subplots(1,figsize=(9,9))
for i in range(X_emb.shape[0]):
pylab.text(X_emb[i,0],X_emb[i,1],str(y[i]),
color=pylab.cm.hsv(.1*y[i]))
pylab.title("t-SNE embedding %f s"%t)
pylab.axis("off"); pylab.show()
import pandas,seaborn,pylab
pylab.style.use('seaborn-pastel')
user="https://raw.githubusercontent.com/OlgaBelitskaya/"
path1="machine_learning_engineer_nd009/"
path2="master/Machine_Learning_Engineer_ND_P3/"
data=pandas.read_csv(user+path1+path2+"customers.csv")
data.drop(['Region','Channel'],axis=1,inplace=True)
data.plot.area(stacked=False,figsize=(12,7))
pylab.title('Data Values by Product Categories')
pylab.grid(); pylab.show()
import pandas,pylab
fp='https://data.cityofnewyork.us/resource/'
f='h7rb-945c.json'
input_file=urllib.request.urlopen(fp+f)
output_file=open(f,'wb')
output_file.write(input_file.read())
output_file.close(); input_file.close()
se=pandas.read_json(fp+f)
fl=['graduation_rate','city','council_district']
se=se[fl].dropna()
se['graduation_rate_range']=se.shape[0]*['0']
se['graduation_rate']=se['graduation_rate']\
.astype('str').str.replace("N/A","0").astype('float')
se['council_district']=se['council_district']\
.astype('int').astype('str')
se.loc[se['graduation_rate']<=0.5,
'graduation_rate_range']='gr <= 0.5'
se.loc[(se['graduation_rate']>0.5)&(se['graduation_rate']<=0.75),
'graduation_rate_range']='0.5 < gr <= 0.75'
se.loc[(se['graduation_rate']>0.75)&(se['graduation_rate']<=0.9),
'graduation_rate_range'] = '0.75 < gr <= 0.9'
se.loc[se['graduation_rate']>0.90,
'graduation_rate_range']='gr > 0.9'
gr_list=['gr <= 0.5','0.5 < gr <= 0.75',
'0.75 < gr <= 0.9','gr > 0.9']
fig,ax=pylab.subplots(nrows=2,ncols=1,figsize=(12,12))
s='Student Graduation Rate by Council Districts and Cities'
ax[0].tick_params('x',rotation=90)
pandas.crosstab(se['council_district'],
se['graduation_rate_range'])[gr_list]\
.plot.bar(ax=ax[0],cmap=pylab.cm.bwr)
city_list=['New York','Bronx','Brooklyn','Staten Island',
'Jamaica','Flushing','Long Island City','Manhattan']
data=se.loc[se['city'].isin(city_list)]
pandas.crosstab(data['city'],
se['graduation_rate_range'])[gr_list]\
.plot.barh(ax=ax[1],cmap=pylab.cm.bwr)
pylab.suptitle(s); pylab.grid(); pylab.show()
import pandas,pylab,urllib
fp='https://data.cityofnewyork.us/resource/'
f='h7rb-945c.json'
input_file=urllib.request.urlopen(fp+f)
output_file=open(f,'wb')
output_file.write(input_file.read())
output_file.close(); input_file.close()
se=pandas.read_json(fp+f)
fl=['dbn','ell_programs','language_classes',
'finalgrades','total_students',
'graduation_rate','attendance_rate',
'college_career_rate','pct_stu_safe',
'pct_stu_enough_variety','latitude',
'longitude','council_district','city']
se=se[fl].dropna()
f,ax=pylab.subplots(ncols=2,figsize=(12,7))
for i in range(2):
se[fl[i+5]]=se[fl[i+5]].astype('str')\
.str.replace("N/A","0").astype('float')
se.plot(kind="scatter",
x="longitude",y="latitude",
s=10,c=fl[i+5],
cmap=pylab.cm.jet,
title=fl[i+5].replace("_"," "),
ax=ax[i],alpha=.8,grid=True)
ax[i].set_facecolor('slategray')
pylab.show()
import numpy
A=numpy.array(range(1,9)).reshape(2,2,2)
B=['♔','♕','♖','♗'];
B=numpy.array(B,dtype=object).reshape(2,2)
AB1=numpy.tensordot(A,B,1)
AB01=numpy.tensordot(A,B,(0,1))
AB10=numpy.tensordot(A,B,(1,0))
def result(X):
for i in range(2):
for j in range(2):
for k in range(2):
print(X[i,j,k])
print(X.shape)
result(AB1); result(AB01); result(AB10)
import sympy
x,y,z,t,u,v,w=sympy.symbols('x,y,z,t,u,v,w')
A=sympy.Array([[[x*sympy.cos(u)*z**2-y,
x**3*u*v**6-sympy.sin(w*t)],
[t*sympy.tan(u*w),
sympy.exp(y)*z*u-w]],
[[y**3*v**5-t,x*sympy.log(w)*z**4],
[x-sympy.exp(z)*w**7,y*t**8*u*v]]])
for el in [x,y,z,t,u,v,w]:
print(A.diff(el))
import pylab,numpy
from mpl_toolkits.mplot3d import Axes3D
t=1.1; cq=numpy.arange(0,1,0.13)
cq=numpy.concatenate((cq,numpy.repeat(cq,2)))
xq=[1,-1,1,-1,1,-1,1,-1]
yq=[1,1,-1,-1,1,1,-1,-1]
zq=[1,1,1,1,-1,-1,-1,-1]
f=pylab.figure(figsize=(9,9))
ax=f.add_subplot(111,projection='3d')
q=ax.quiver(8*[0],8*[0],8*[0],xq,yq,zq,lw=10,
colors=pylab.cm.hsv(cq),alpha=0.5)
ax.set_xlabel('$\mathscr{X}$',fontsize=15)
ax.set_ylabel('$\mathscr{Y}$',fontsize=15)
ax.set_zlabel('$\mathscr{Z}$',fontsize=15)
ax.set_xlim(-t,t); ax.set_ylim(-t,t)
ax.set_zlim(-t,t); pylab.show()