-
Notifications
You must be signed in to change notification settings - Fork 0
/
alpow.py
1607 lines (1341 loc) · 44.1 KB
/
alpow.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*-coding:utf-8 -*
# ---
import sklearn.preprocessing
import seaborn as sns
import matplotlib.pyplot as plt
import datetime
import requests
import re
import warnings
import pickle
import gc
import subprocess
import operator
import os
import sys
import json
import numpy as np
import pandas as pd
from time import time
from scipy import stats
from webptools import webplib
import pysftp
import hashlib
echo = print
p = print
p('Mainframe alpow included') # mainframe
# import importlib;importlib.reload(alpow);#reload
#os.system('rm -f alpow.py;wget https://alpow.fr/alpow.py')
# requirements
modules = 'wget joblib ipython sklearn seaborn Flask webptools pysftp numpy requests'.split(
' ')
fn = 'versions.txt'
os.system('pip freeze > ' + fn)
installed = ''
with open(fn) as f:
installed += f.read()
for module in modules:
if(module + '==' not in installed):
print('Trying to install :', module)
os.system('pip install ' + module)
# }conf{
np.random.seed(seed=1983)
pd.set_option('display.max_rows', 900)
pd.set_option('display.max_columns', 40)
# or evaluate js document frame innerWidth .
pd.set_option('display.width', 1200)
plt.style.use('fivethirtyeight')
plt.rcParams["figure.figsize"] = (24, 12)
plt.rcParams['figure.facecolor'] = 'white'
#warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings('ignore')
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
lab_enc = sklearn.preprocessing.LabelEncoder()
# }vars{
heightPerGraph = widthPerGraph = 6
demo = 1
verbose = 0
# empty parameters to be overriden
def setG(k, v):
if(k in globals().keys()):
del(globals()[k])
globals()[k] = v
setG('sftp', {'cd': '', 'web': '-', 'h': '-', 'u': '-', 'p': '-'})
considerEmpty = [np.inf, -np.inf, np.nan, 0, 'na', '']
sendimages2ftp = 1
removepng = 1
useFTP = True
# }shortcuts{
# }functions{
def g(x):
return globals()[x]
def md5(x):
res = hashlib.md5(str(x).encode())
return res.hexdigest()
def show():
global demo
if(demo):
plt.show()
return
plt.close()
def findWithinArrayValues(tags, q):
res = []
for k in range(len(tags)):
# for k,v in tags.iterows():
v = tags[k]
try:
if(v.index(q)):
res += [k]
except ValueError:
pass
return res
def message(x):
now = datetime.datetime.now()
url = 'https://1.x24.fr/a/bus.php'
r = requests.post(url, data={0: x})
# re is not defined ... whut ???
def filename(x):
return re.sub(r"[^a-z0-9\-_,\.:]+", '-', x.lower())
def webp(x):
x2 = x.replace('.png', '') + '.webp'
webplib.cwebp(x, x2, '-q 70')
if removepng:
os.system('rm -f ' + x)
if sendimages2ftp:
ftpput(x2)
return x2
def asort(dict):
if type(dict) == list:
return dict # allready
return sorted(dict.items(), key=operator.itemgetter(1), reverse=False)
def arsort(dict):
if type(dict) == list:
return dict # allready
return sorted(dict.items(), key=operator.itemgetter(1), reverse=True)
def nullValues(z):
col_mask = z.isnull().any(axis=0)
row_mask = z.isnull().any(axis=1)
return z.loc[row_mask, col_mask]
def say(x):
html("<script>say(\"" + str(x) + "\")</script>")
def html(x):
import IPython
IPython.display.display(IPython.display.HTML(x))
return
def cleanData(inputDf, fillStrings='na', fillInt=0, considerEmpty=[
np.inf, -np.inf, np.nan, 0, 'na', '']):
#test = pd.read_csv('../input/test.csv')
df = inputDf.copy(deep=True)
rows = df.shape[0]
cols = df.shape[1]
dfs = df.size
nanInfZeroNaEmpty = train.isin(
considerEmpty).sum().sort_values(ascending=False)
nv = nanInfZeroNaEmpty.sum()
p('Total Rows in dataset : ' + str(rows))
p('Total Cols in dataset : ' + str(cols))
p('Total Cells : ' + str(dfs))
p('Cells containing null,inf,NaN,0 or empty values : ' + str(nv) +
' ( ' + str(round(nv * 100 / dfs, 2)) + '% )') # Diagnose null columns
p('_' * 80)
# Fournissent une bonne indication des colonnes à dropper pour le modèke
for i in nanInfZeroNaEmpty.index:
nbempty = nanInfZeroNaEmpty[i]
per = round(nbempty * 100 / rows, 2)
p(i + ' => empty : ' + str(nbempty) + ' ' + str(per) + '%')
p('_' * 140)
for i in df.columns:
if df.dtypes[i] == object:
df[i].fillna(fillStrings, inplace=True) # as strings ! boljemoi !
else:
df.replace([np.inf, -np.inf, np.nan], fillInt,
inplace=True) # replace infinite by Nan
# df.fillna(df.mean(),inplace=True)#Numeric types corrected
# df.fillna(fillInt,inplace=True)#2 rows of Nan -> is valid either for strings or numeric datatype
# dtype as str please !!
p('_' * 140)
# CAUTION !!! WONT FIT INTO MODEL OTHERWISE
p('Cells with null values then : ' + str(nullValues(df).size))
p('_' * 140)
return df
def rg(x):
import requests
r = requests.get(webRepo + sftp['cd'] + '/' + x)
if(r.status_code == 200):
# print(r.text)#r.contents are b-encoded
FPC(x, r.text)
return True
return False
def ftpget(fn, cd=0):
global sftp, cnopts
if(type(fn) == str): # solo
fn = [fn]
if (not useFTP) | (sftp['h'] == '-'):
oks = []
for i in fn:
if(rg(i)):
oks += [i]
p('get:' + ','.join(oks))
return oks
p('ftp disabled')
if(cd == 0):
cd = sftp['cd']
with pysftp.Connection(sftp['h'], username=sftp['u'], password=sftp['p'], cnopts=cnopts) as connection:
with connection.cd(cd):
for i in fn:
connection.get(i)
p('get:' + ','.join(fn))
def ftpputzip(fn, cd=0):
global sftp
if (not useFTP) | (sftp['h'] == '-'):
p('ftp disabled')
return
if(type(fn) == str): # solo
fn = [fn]
zipped = []
for i in fn:
os.system('rm -f ' + i + '.zip')
os.system('zip ' + i + '.zip ' + i)
zipped.append(i + '.zip')
ftpput(zipped, cd)
def ftpexists(fn, cd=0):
if(cd == 0):
cd = sftp['cd']
liste = ftpls(cd)
if(fn in liste):
return True
return False
def getFile(fns, sep='\t'):
notFound = []
found = []
if(type(fns) == str): # solo
fns = [fns]
for fn in fns:
if(os.path.exists(fn)):
found.append(fn)
continue
elif(os.path.exists(fn + '.zip')):
o = subprocess.check_output('unzip -o ' + fn + '.zip', shell=True)
#isApple = True if fruit == 'Apple' else False
if verbose:
p(o)
# os.system('unzip -o '+fn+'.zip')#unzip
found.append(fn)
continue
elif(os.path.exists(fn + '.tgz')):
o = subprocess.check_output('tar xf ' + fn + '.tgz', shell=True)
#isApple = True if fruit == 'Apple' else False
if verbose:
p(o)
# os.system('unzip -o '+fn+'.zip')#unzip
found.append(fn)
continue
elif(ftpexists(fn)):
ftpget(fn)
found.append(fn)
continue
elif(ftpexists(fn + '.zip')):
ftpget(fn + '.zip')
o = subprocess.check_output('unzip -o ' + fn + '.zip', shell=True)
if verbose:
p(o)
# os.system('unzip -o '+fn+'.zip')#unzip
found.append(fn)
continue
elif(ftpexists(fn + '.tgz')):
ftpget(fn + '.tgz')
o = subprocess.check_output('tar xf ' + fn + '.tgz', shell=True)
if verbose:
p(o)
# os.system('unzip -o '+fn+'.zip')#unzip
found.append(fn)
continue
notFound.append(fn)
if verbose:
if(len(found)):
p('Getfile:Found:' + ','.join(found))
if(len(notFound)):
p('Getfile:NotFound:' + ','.join(notFound))
return len(found)
setG('ftplist', [])
def ftpls(cd=0):
global sftp, cnopts
if (not useFTP) | (sftp['h'] == '-'):
rg('list.php')
x = fgc('list.php')
setG('ftplist', x.split(','))
return x.split(',')
if(cd == 0):
cd = sftp['cd']
with pysftp.Connection(sftp['h'], username=sftp['u'], password=sftp['p'], cnopts=cnopts) as connection:
with connection.cd(cd):
setG('ftplist', connection.listdir())
return connection.listdir()
def FPC(fn, data):
x = str(data).strip("\n\r ")
# p(x,end='.')
myfile = open(fn, 'w', newline='\n')
myfile.write(x)
myfile.close()
def fgc(fn, join=True):
lines = []
with open(fn, 'r') as f:
lines += f.read().splitlines()
if join:
return "\n".join(lines)
return lines
def nf(a=0, b=0, c=0, d=0, e=0, f=0, g=0, h=0, i=0, j=0, end=0):
return
# disable it : p=nf
def disablePrint():
global p
p = nf
echo = nf
def enablePrint():
global p
p = print
echo = print
def fgcj(fn):
with open(fn + '.json') as json_file:
return json.load(json_file)
def FPCJ(fn, data): # r,b
with open(fn + '.json', 'w') as json_file:
json.dump(data, json_file)
def uniqueValuesPerColumn(sc, df2):
return df2.groupby(sc)[sc].agg(
['count']).sort_values(
by='count',
ascending=False)
def lemitizeWords(text):
words = token.tokenize(text)
listLemma = []
for w in words:
x = lemma.lemmatize(w, pos="v")
listLemma.append(x)
return ' '.join(map(str, listLemma))
def stopWordsRemove(text):
words = token.tokenize(text)
filtered = [w for w in words if w not in stop_words]
return ' '.join(map(str, filtered))
def extractionMots(x):
import re
# suppression tags ouverture et fermeture ( conservant leur contenus
# interne : code, texte mis en forme, etc .. )
notags = re.sub('<[^<]+?>', '', x)
noHTMLentities = re.sub('&[^;]{1,9};', '', notags) # cleanup & > <
# autres que caractères de base
stripped = re.sub(r"[^a-z0-9',.]+", ' ', noHTMLentities)
lemitized = lemitizeWords(stripped)
# i => retire du sens à la phrase conserve plupart mots clefs
noStopWords = stopWordsRemove(lemitized)
bouillie = re.sub(r"[',. ]+", ' ', noStopWords).strip() # bouillie de mots
#trimSingleLetters : I
return trimAloneNumbers(bouillie)
def stripSimpleTags(x):
import re
x = re.sub('<', '', x) # retrait de gauche
x = re.sub('>', ';', x) # remplacement par un séparateur plus commun
x = re.sub(' +', ' ', x) # multiples espaces potentiel par un unique
return x.lower().strip('; ') # trim
# return re.sub(' +',' ', re.sub('<|>',' ', x))
#x='6 python pandas 34 scikit-learn a7s pmml 7'
def trimAloneNumbers(x):
return re.sub(r'^[0-9]+\s|\s[0-9]+\s|\s[0-9]+$', '', x).strip()
def trimSingleLetters(x):
return re.sub(r'^[a-z]{1}\s|\s[a-z]{1}\s|\s[a-z]{1}$', '', x).strip()
def arrayCount(x):
return len(x)
def uniqueValues(x):
x = np.array(x)
return list(np.unique(x))
def extractTagsn(x):
return re.findall(r'(?<=\<)[^\<\>]+(?=\>)', x)
def extractTags(x, join=1):
res = re.findall(r'(?<=\<)[^\<\>]+(?=\>)', x)
if join:
return ' '.join(res)
return res
def ftpput(fn, cd=0, aszip=0):
global sftp, cnopts
if (not useFTP) | (sftp['h'] == '-'):
p('ftp offline')
return
if(type(fn) == str): # solo
fn = [fn]
if(cd == 0):
cd = sftp['cd']
with pysftp.Connection(sftp['h'], username=sftp['u'], password=sftp['p'], cnopts=cnopts) as connection:
with connection.cd(cd):
for i in fn:
p(i.split('.')[-1], ' ', i, ' ', os.path.exists(i))
if(not os.path.exists(i)):
p('!!!!', i, ' not exists')
assert(False)
continue
if((i.split('.')[-1] not in ['zip', 'jpg', 'png', 'webp', 'tgz', 'mp4', 'mp3', 'mkv', 'pik']) & (os.path.getsize(i) > 5000000 | aszip)):
os.system('rm -f ' + i + '.zip')
os.system('zip ' + i + '.zip ' + i)
i = i + '.zip'
connection.put(i)
now = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") # -%s
if('.tgz' not in i):
p('put : ' + sftp['web'] + i + '?a=' + now) # !
def pltinit(df, i, j, title=False, width=6, height=6):
fig, ax = plt.subplots(figsize=(height, width))
fig.patch.set_facecolor('white')
x = df[i]
y = df[j]
if(title == False):
title = i + ' vs ' + j
plt.title(title)
plt.xlabel(i)
plt.ylabel(j)
return [x, y, filename(i + '.' + j), fig, ax]
def plot(
df,
i='x',
j='y',
rotate=False,
fn=False,
title=False,
width=6,
height=6):
if type(df) == dict:
df = pd.DataFrame.from_dict(
{'x': list(df.keys()), 'y': list(df.values())})
x, y, fn2, fig, ax = pltinit(df, i, j, title, height, width)
if(fn == False):
fn = fn2
# bestCorrelationsKeys.keys():
plt.plot(x, y)
if rotate:
plt.xticks(rotation=rotate)
fn = 'plot' + fn + '.png'
plt.savefig(fn, bbox_inches='tight')
webp(fn)
show()
def scatter1(
df=False,
i=False,
j=False,
ts=0,
x=False,
y=False,
color=False,
fn='',
cmap='brg',
o=1):
if((isinstance(x, np.ndarray)) & (isinstance(y, np.ndarray))):
pass
else:
x, y, fn, fig, ax = pltinit(df, i, j)
if ts:
plt.gca().set_yticklabels(
backgroundcolor='white',
labels=y,
rotation=(0),
fontsize=ts,
linespacing=ts)
# ax.tick_params(axis='y',which='major',pad=ts)
#ax.set_yticklabels(labels=y,rotation = (45), fontsize = 10, va='bottom', ha='left')
if(isinstance(color, pd.Series)):
#plt.scatter(x, y,c=color,cmap=cmap,alpha=o)
sns.scatterplot(
x,
y,
alpha=o,
hue=color,
palette=sns.color_palette(
cmap,
unik(color).shape[0]))
else:
plt.scatter(x, y)
plt.title(fn)
fn = 'scatter' + fn + '.png'
plt.savefig(fn, bbox_inches='tight')
webp(fn)
show()
# type(sup0)==pandas.core.series.Series
def scatter(
df,
a='',
b='',
ts=0,
minx=0,
maxx=0,
miny=0,
maxy=0,
opacity=0.02,
color='blue',
size=2,
axis=0,
xscale=0,
yscale=0,
reg=0,
fn=0):
if(fn == 0):
fn = filename(a + '.' + b + '.png')
# recombiné avec son index
if(type(df) == pd.core.series.Series): # {
if(len(df) == 0):
p('empty.. skipping')
return 0
# x=df.index
# p('serie')
if(maxy == 0): # maxx or de propos
maxy = df.max()
x = range(df.shape[0])
if(axis):
axis.scatter(x, df, s=size, alpha=opacity)
# axis.set_title(fn)
# ax.set_xlim(minx,maxx);ax.set_ylim(miny,maxy)
axis.set_xlabel(a)
axis.set_ylabel(b)
axis.set_facecolor('white')
if(yscale):
axis.set_yscale(yscale)
if(xscale):
axis.set_xscale(xscale)
return 1
plt.figure().set_facecolor('white')
plt.scatter(x, df, s=size, alpha=opacity)
# plt.title(fn)
if maxy:
plt.ylim(miny, maxy)
plt.xlabel(a)
plt.ylabel(b)
if(yscale):
plt.yscale(yscale)
if(xscale):
plt.xscale(xscale)
plt.savefig(fn, bbox_inches='tight')
# ftpput(fn)
webp(fn)
show()
return fn
# }end pandas serie
# Sinon Dataframe ordinaire
elif(axis == 0):
# p('joinplot')
x = df[a]
y = df[b]
args = {
'x': x,
'y': y,
'data': df,
'joint_kws': {
'alpha': opacity,
'color': color}}
if(reg):
args['kind'] = 'reg'
args['joint_kws'] = {'color': color}
args['scatter_kws'] = {'alpha': opacity}
# p(args);#TypeError: regplot() got an unexpected keyword argument
# 'alpha'
sns.jointplot(**args).savefig(fn, bbox_inches='tight')
webp(fn)
show()
return fn
# Rendu sur un axe ..
x, y, fn2, fig, ax = pltinit(df, a, b, axis)
if(maxx == 0):
maxx = x.max()
if(maxy != 0):
maxy = y.max()
if(axis != 0): # specifié non généré
axis.set_xlabel(a)
axis.set_ylabel(b)
axis.scatter(x, y, alpha=opacity, c=color, s=size)
ax = axis
ax.set_facecolor('white')
if(xscale):
ax.set_xscale(xscale)
if(yscale):
ax.set_yscale(yscale)
return 1
if(ts & False):
plt.gca().set_yticklabels(
backgroundcolor='white',
labels=y,
rotation=(0),
fontsize=ts,
linespacing=ts)
# ax.tick_params(axis='y',which='major',pad=ts)
#ax.set_yticklabels(labels=y,rotation = (45), fontsize = 10, va='bottom', ha='left')
if(axis == 0):
if False:
plt.scatter(x, y, alpha=opacity, c=color, s=size)
show()
plt.savefig(fn, bbox_inches='tight')
webp(fn)
def md5(x):
return hashlib.md5(bencode.bencode(x)).hexdigest()
def NewModel1(x_size, y_size):
t_model = Sequential()
t_model.add(Dense(100, activation="tanh", input_shape=(x_size,)))
t_model.add(Dense(50, activation="relu"))
t_model.add(Dense(y_size, activation='linear'))
return(t_model)
def NewModel2(x_size, y_size):
t_model = Sequential()
t_model.add(Dense(100, activation="tanh", input_shape=(x_size,)))
t_model.add(Dropout(0.1))
t_model.add(Dense(50, activation="relu"))
t_model.add(Dense(20, activation="relu"))
t_model.add(Dense(y_size, activation='linear'))
return(t_model)
def NewModel3(x_size, y_size):
t_model = Sequential()
t_model.add(
Dense(
80,
activation="tanh",
kernel_initializer='normal',
input_shape=(
x_size,
)))
t_model.add(Dropout(0.2))
t_model.add(
Dense(
120,
activation="relu",
kernel_initializer='normal',
kernel_regularizer=regularizers.l1(0.01),
bias_regularizer=regularizers.l1(0.01)))
t_model.add(Dropout(0.1))
t_model.add(
Dense(
20,
activation="relu",
kernel_initializer='normal',
kernel_regularizer=regularizers.l1_l2(0.01),
bias_regularizer=regularizers.l1_l2(0.01)))
t_model.add(Dropout(0.1))
t_model.add(Dense(10, activation="relu", kernel_initializer='normal'))
t_model.add(Dropout(0.0))
t_model.add(Dense(y_size, activation='linear'))
return(t_model)
def nn4(x_size, y_size):
model = Sequential([
Dense(32, activation='relu', input_shape=(x_size,)),
Dense(32, activation='relu'),
Dense(y_size, activation='sigmoid')
])
# model.compile(optimizer='sgd',
return model
def histogram(x, name, score):
# k=x.history.keys();p(k)#dict_keys(['val_loss', 'val_mean_absolute_error', 'loss', 'mean_absolute_error'])#"mean_squared_error"
# mean_squared_logarithmic_error
first = x.history['mean_squared_error'][:1]
# TypeError: list indices must be integers or slices, not tuple
last = x.history['mean_squared_error'][-1:]
# p(first[0]);p(last[0])
progress = first[0] - last[0]
p('Progress:' + str(progress))
# plusieurs champs k
for i in x.history.keys():
plt.plot(x.history[i], label=i)
plt.title(str(score) + '/' + name)
x = filename(str(name)) + '.histogram.png'
plt.savefig(x, bbox_inches='tight')
ftpput(x)
plt.close()
return progress
show()
# Fit and Predict at the same time !!!
def fit(x, fn=0, noload=0):
global x1, x2, y1, y2, ep, bs, k, pred, acy, k, toGuess
res = 0
history = 0
if(fn): # changmenet de shape de données en input ..
if(noload == 0 & os.path.isfile(fn)):
getFile(fn)
x = keras.models.load_model(fn)
p('load model:' + fn)
res = 1
if(res == 0):
p('generate model:' + fn)
history = x.fit(
x1,
x2,
validation_data=(
y1,
y2),
epochs=ep,
batch_size=bs,
shuffle=True,
verbose=0)
p('_' * 160)
# history=x.fit(standardize(x1),standardize(x2),validation_data=(standardize(y1),standardize(y2)),epochs=ep,batch_size=bs,shuffle=True,verbose=2)
x.save(fn)
ftpput(fn) # zipped ?
nfm[k] = x
pred[toGuess][k] = x.predict(y1) # mean_squared_log_error
#!!!:ValueError: Mean Squared Logarithmic Error cannot be used when targets contain negative values.
acy[toGuess][k] = round(mean_squared_error(
y2, pred[toGuess][k]) ** (1 / 2))
say(acy[toGuess][k])
p(k + ' => ' + str(acy[toGuess][k]))
if(history):
histogram(history, k, acy[toGuess][k])
p('_' * 120)
# celles du module ?
def globkeys():
p(globals().keys())
def r2(a, b):
return stats.pearsonr(a, b)[0] ** 2
def standardize(df):
mean = np.mean(df, axis=0)
std = np.std(df, axis=0) # +0.000001
return (df - mean) / std
def FPCP(fn, data):
os.system('rm -f ' + fn + '.pickle ' + fn + '.pickle.zip')
f = open(fn + '.pickle', 'wb')
pickle.dump(data, f, protocol=-1)
# d=pickle.dumps(data);f.write(d);f.close();
# can't pickle _thread.RLock objects
# ModuleNotFoundError: No module named 'sklearn.linear_model._logistic
class rewriteClass(pickle.Unpickler):
def find_class(self, module, name):
renamed_module = module
a = module.split('.')
if((a[-1][0] == '_') & (a[-1] not in ['_pickle'])):
p(a[-1], a[-1][0])
del(a[-1])
renamed_module = '.'.join(a)
if module == "sklearn.linear_model._logistic":
renamed_module = "sklearn.linear_model"
return super(rewriteClass, self).find_class(renamed_module, name)
def fgcp(fn):
fn = fn + '.pickle'
getFile(fn)
if verbose:
p('size:', fn, ' : ', os.path.getsize(fn) / 1024 / 1024)
if(os.path.isfile(fn)):
gc.disable()
data = open(fn, "rb")
ret = rewriteClass(data).load()
#ret = pickle.load(data)
data.close()
gc.enable()
return ret
return 0
def loadIfNotSet(x):
if x not in globals().keys():
load(x)
def mail(x):
import requests
url = 'https://1.x24.fr/a/bus.php'
r = requests.post(url, data={'mail': x})
def message(x):
import requests
url = 'https://1.x24.fr/a/bus.php'
r = requests.post(url, data={0: x})
r = requests.post(url, data={'mail': x})
# snscat
def snsscat(
df,
a='',
b='',
ts=0,
minx=0,
maxx=False,
miny=0,
maxy=False,
opacity=0.02,
color='blue',
size=2,
axis=0,
xscale=0,
yscale=0,
fn=False,
kind='scatter',
height=24):
if(fn == False):
fn = filename(a + '.' + b + '.png')
x = df[a]
y = df[b] # fig,ax=plt.subplots(1);#ax=ax.flatten()
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
corr = stats.pearsonr(x, y)[0] ** 2
# x,y,fn2,fig,ax=pltinit(df,a,b,axis)
# ax.scatter(x,y,alpha=opacity,c=color,s=size);
if(maxx == False):
maxx = x.max()
if(maxy == False):
maxy = y.max()
# https://stackoverflow.com/questions/36191906/rescale-axis-on-seaborn-jointgrid-kde-marginal-plots 'ax':ax, 'height':height,
# https://seaborn.pydata.org/generated/seaborn.JointGrid.html
args = {
'height': height,
'dropna': True,
'kind': kind,
'x': x,
'y': y,
'data': df,
'joint_kws': {
'alpha': opacity,
'color': color},
'xlim': [
minx,
maxx],
'ylim': [
miny,
maxy],
'color': 'red'}
args['stat_func'] = r2
args['marginal_kws'] = dict(bins=15, rug=True)
args['annot_kws'] = dict(stat="r") # joinplot annot_kws
# N'apparait pas ..
if(kind in ['reg']):
args['joint_kws'] = {'color': color} # reg no opacity
# not hex,nor kde
args['line_kws'] = {
'label': "y={0:.1f}x+{1:.1f}".format(slope, intercept)}
args['scatter_kws'] = {'alpha': opacity} # ,nor kde
if(kind in ['kde']):
args['joint_kws'] = {'color': color}
args['marginal_kws'] = {} # no bins property
pass
# p(args);#TypeError: regplot() got an unexpected keyword argument
# 'alpha',dir(ax)
g = sns.jointplot(**args) # unpack
ax = g.ax_joint
# g=sns.JointGrid(**args)
"""
g = sns.JointGrid(x="total_bill", y="tip", data=tips)
g = g.plot_joint(plt.scatter,color="g", s=40, edgecolor="white")
g = g.plot_marginals(sns.distplot, kde=False, color="g")
g = g.annotate(stats.pearsonr)
g = g.plot_joint(sns.kdeplot, cmap="Blues_d")
g = g.plot_marginals(sns.kdeplot, shade=True)
"""
if(xscale):
ax.set_xscale('log')
if(kind in ['reg', 'kde']):
g.ax_marg_x.set_xscale('log')
if(yscale):
ax.set_yscale(yscale)
if(kind in ['reg', 'kde']):
g.ax_marg_y.set_yscale('log')
# ax.set_xlabel(a);ax.set_ylabel(b);#déjà attribués
# AttributeError: 'JointGrid' object has no attribute 'set_xlim'
if((kind in ['reg', 'kde']) & False):
regline = g.ax_joint.get_lines()[0]
regline.set_color('black')
regline.set_zorder('99')
#fig.text(1, 1, "An annotation", horizontalalignment='left', size='medium', color='black', weight='semibold')
# dir(g)
# rsquare = lambda a, b:
#rsquare = lambda a, b: 2;g.annotate(rsquare)
#ax = g.axes[0,0]
plt.title(str(int(slope)) + '-' + str(int(intercept)))
g.savefig(fn, bbox_inches='tight')
webp(fn)
# ftpput(fn)
show()
# plt.show()
return 1