markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
* It creates another variable.
cities.projection2020
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Specifying a `Series` as a new columns cause its values to be added according to the `DataFrame`'s index:
populationIn2000 = pd.Series([11076840, 3889199, 3431204, 2150571, 1430539]) populationIn2000 cities['population_2000'] = populationIn2000 cities
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Other Python data structures (ones without an index) need to be the same length as the `DataFrame`:
populationIn2007 = [12573836, 4466756, 3739353, 2439876] cities['population_2007'] = populationIn2007
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* We can use `del` to remove columns, in the same way `dict` entries can be removed:
cities del cities['population_2000'] cities
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* We can extract the underlying data as a simple `ndarray` by accessing the `values` attribute:
cities.values
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Notice that because of the mix of string and integer (and could be`NaN`) values, the dtype of the array is `object`. * The dtype will automatically be chosen to be as general as needed to accomodate all the columns.
df = pd.DataFrame({'integers': [1,2,3], 'floatNumbers':[0.5, -1.25, 2.5]}) df print(df.values.dtype) df.values
float64
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Pandas uses a custom data structure to represent the indices of Series and DataFrames.
cities.index
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Index objects are immutable:
cities.index[0] = 15
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* This is so that Index objects can be shared between data structures without fear that they will be changed.* That means you can move, copy your meaningful labels to other `DataFrames`
cities cities.index = population2.index cities
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Importing data * A key, but often under appreciated, step in data analysis is importing the data that we wish to analyze.* Though it is easy to load basic data structures into Python using built-in tools or those provided by packages like NumPy, it is non-trivial to import structured data well, and to easily convert this input into a robust data structure.* Pandas provides a convenient set of functions for importing tabular data in a number of formats directly into a `DataFrame` object. * Let's start with some more population data, stored in csv format.
!cat data/population.csv
Provinces;2000;2001;2002;2003;2004;2005;2006;2007;2008;2009;2010;2011;2012;2013;2014;2015;2016;2017 Total;64729501;65603160;66401851;67187251;68010215;68860539;69729967;70586256;71517100;72561312;73722988;74724269;75627384;76667864;77695904;78741053;79814871;80810525 Adana;1879695;1899324;1916637;1933428;1951142;1969512;1988277;2006650;2026319;2062226;2085225;2108805;2125635;2149260;2165595;2183167;2201670;2216475 Adıyaman;568432;571180;573149;574886;576808;578852;580926;582762;585067;588475;590935;593931;595261;597184;597835;602774;610484;615076 Afyonkarahisar;696292;698029;698773;699193;699794;700502;701204;701572;697365;701326;697559;698626;703948;707123;706371;709015;714523;715693 Ağrı;519190;521514;523123;524514;526070;527732;529417;530879;532180;537665;542022;555479;552404;551177;549435;547210;542255;536285 Amasya;333927;333768;333110;332271;331491;330739;329956;328674;323675;324268;334786;323079;322283;321977;321913;322167;326351;329888 Ankara;3889199;3971642;4050309;4128889;4210596;4294678;4380736;4466756;4548939;4650802;4771716;4890893;4965542;5045083;5150072;5270575;5346518;5445026 Antalya;1430539;1480282;1529110;1578367;1629338;1681656;1735239;1789295;1859275;1919729;1978333;2043482;2092537;2158265;2222562;2288456;2328555;2364396 Artvin;167909;168184;168215;168164;168153;168164;168170;168092;166584;165580;164759;166394;167082;169334;169674;168370;168068;166143 Aydın;870460;881911;892345;902594;913340;924446;935800;946971;965500;979155;989862;999163;1006541;1020957;1041979;1053506;1068260;1080839 Balıkesir;1069260;1077362;1084072;1090411;1097187;1104261;1111475;1118313;1130276;1140085;1152323;1154314;1160731;1162761;1189057;1186688;1196176;1204824 Bilecik;197625;198736;199580;200346;201182;202063;202960;203777;193169;202061;225381;203849;204116;208888;209925;212361;218297;221693 Bingöl;240337;242183;243717;245168;246718;248336;249986;251552;256091;255745;255170;262263;262507;265514;266019;267184;269560;273354 Bitlis;318886;320555;321791;322898;324114;325401;326709;327886;326897;328489;328767;336624;337253;337156;338023;340449;341225;341474 Bolu;255576;257926;259953;261902;263967;266114;268305;270417;268882;271545;271208;276506;281080;283496;284789;291095;299896;303184 Burdur;246060;247106;247811;248412;249090;249816;250552;251181;247437;251550;258868;250527;254341;257267;256898;258339;261401;264779 Bursa;2150571;2192169;2231582;2270852;2311735;2353834;2396916;2439876;2507963;2550645;2605495;2652126;2688171;2740970;2787539;2842547;2901396;2936803 Çanakkale;449418;453632;457280;460792;464511;468375;472320;476128;474791;477735;490397;486445;493691;502328;511790;513341;519793;530417 Çankırı;169044;169955;170637;171252;171924;172635;173358;174012;176093;185019;179067;177211;184406;190909;183550;180945;183880;186074 Çorum;567609;566094;563698;560968;558300;555649;552911;549828;545444;540704;535405;534578;529975;532080;527220;525180;527863;528422 Denizli;845493;854958;863396;871614;880267;889229;898387;907325;917836;926362;931823;942278;950557;963464;978700;993442;1005687;1018735 Diyarbakır;1317750;1338378;1357550;1376518;1396333;1416775;1437684;1460714;1492828;1515011;1528958;1570943;1592167;1607437;1635048;1654196;1673119;1699901 Edirne;392134;393292;393896;394320;394852;395449;396047;396462;394644;395463;390428;399316;399708;398582;400280;402537;401701;406855 Elazığ;517551;521467;524710;527774;531048;534467;537954;541258;547562;550667;552646;558556;562703;568239;568753;574304;578789;583671 Erzincan;206815;208015;208937;209779;210694;211658;212639;213538;210645;213288;224949;215277;217886;219996;223633;222918;226032;231511 Erzurum;801287;800311;798119;795482;792968;790505;787952;784941;774967;774207;769085;780847;778195;766729;763320;762321;762021;760476 Eskişehir;651672;662354;672328;682212;692529;703168;714051;724849;741739;755427;764584;781247;789750;799724;812320;826716;844842;860620 Gaziantep;1292817;1330205;1366581;1403165;1441079;1480026;1519905;1560023;1612223;1653670;1700763;1753596;1799558;1844438;1889466;1931836;1974244;2005515 Giresun;410946;412428;413335;414062;414909;415830;416760;417505;421766;421860;419256;419498;419555;425007;429984;426686;444467;437393 Gümüşhane;116008;118147;120166;122175;124267;126423;128628;130825;131367;130976;129618;132374;135216;141412;146353;151449;172034;170173 Hakkari;223264;226676;229839;232966;236234;239606;243055;246469;258590;256761;251302;272165;279982;273041;276287;278775;267813;275761 Hatay;1280457;1296401;1310828;1324961;1339798;1355144;1370831;1386224;1413287;1448418;1480571;1474223;1483674;1503066;1519836;1533507;1555165;1575226 Isparta;418507;419307;419505;419502;419601;419758;419905;419845;407463;420796;448298;411245;416663;417774;418780;421766;427324;433830 Mersin;1488755;1505196;1519824;1534060;1549054;1564588;1580460;1595938;1602908;1640888;1647899;1667939;1682848;1705774;1727255;1745221;1773852;1793931 İstanbul;11076840;11292009;11495948;11699172;11910733;12128577;12351506;12573836;12697164;12915158;13255685;13624240;13854740;14160467;14377018;14657434;14804116;15029231 İzmir;3431204;3477209;3519233;3560544;3603838;3648575;3694316;3739353;3795978;3868308;3948848;3965232;4005459;4061074;4113072;4168415;4223545;4279677 Kars;326292;324908;323005;320898;318812;316723;314570;312205;312128;306536;301766;305755;304821;300874;296466;292660;289786;287654 Kastamonu;351582;353271;354479;355541;356719;357972;359243;360366;360424;359823;361222;359759;359808;368093;368907;372633;376945;372373 Kayseri;1038671;1056995;1074221;1091336;1109179;1127566;1146378;1165088;1184386;1205872;1234651;1255349;1274968;1295355;1322376;1341056;1358980;1376722 Kırklareli;323427;325213;326561;327782;329116;330523;331955;333256;336942;333179;332791;340199;341218;340559;343723;346973;351684;356050 Kırşehir;221473;222028;222267;222403;222596;222824;223050;223170;222735;223102;221876;221015;221209;223498;222707;225562;229975;234529 Kocaeli;1192053;1226460;1259932;1293594;1328481;1364317;1401013;1437926;1490358;1522408;1560138;1601720;1634691;1676202;1722795;1780055;1830772;1883270 Konya;1835987;1855057;1871862;1888154;1905345;1923174;1941386;1959082;1969868;1992675;2013845;2038555;2052281;2079225;2108808;2130544;2161303;2180149 Kütahya;592921;592607;591405;589883;588464;587092;585666;583910;565884;571804;590496;564264;573421;572059;571554;571463;573642;572256 Malatya;685533;691399;696387;701155;706222;711496;716879;722065;733789;736884;740643;757930;762366;762538;769544;772904;781305;786676 Manisa;1276590;1284241;1290180;1295630;1301542;1307760;1314090;1319920;1316750;1331957;1379484;1340074;1346162;1359463;1367905;1380366;1396945;1413041 Kahramanmaraş;937074;947317;956417;965268;974592;984254;994126;1004414;1029298;1037491;1044816;1054210;1063174;1075706;1089038;1096610;1112634;1127623 Mardin;709316;715211;720195;724946;730002;735267;740641;745778;750697;737852;744606;764033;773026;779738;788996;796591;796237;809719 Muğla;663606;678204;692171;706136;720650;735582;750865;766156;791424;802381;817503;838324;851145;866665;894509;908877;923773;938751 Muş;403236;404138;404462;404596;404832;405127;405416;405509;404309;404484;406886;414706;413260;412553;411216;408728;406501;404544 Nevşehir;275262;276309;276971;277514;278138;278814;279498;280058;281699;284025;282337;283247;285190;285460;286250;286767;290895;292365 Niğde;321330;323181;324600;325894;327302;328786;330295;331677;338447;339921;337931;337553;340270;343658;343898;346114;351468;352727 Ordu;705746;708079;709420;710444;711670;713018;714375;715409;719278;723507;719183;714390;741371;731452;724268;728949;750588;742341 Rize;307133;308800;310052;311181;312417;313722;315049;316252;319410;319569;319637;323012;324152;328205;329779;328979;331048;331041 Sakarya;750485;762848;774397;785845;797793;810112;822715;835222;851292;861570;872872;888556;902267;917373;932706;953181;976948;990214 Samsun;1191926;1198574;1203611;1208179;1213165;1218424;1223774;1228959;1233677;1250076;1252693;1251729;1251722;1261810;1269989;1279884;1295927;1312990 Siirt;270832;273982;276806;279562;282461;285462;288529;291528;299819;303622;300695;310468;310879;314153;318366;320351;322664;324394 Sinop;194318;195151;195715;196196;196739;197319;197908;198412;200791;201134;202740;203027;201311;204568;204526;204133;205478;207427 Sivas;651825;650946;649078;646845;644709;642614;640442;638464;631112;633347;642224;627056;623535;623824;623116;618617;621224;621301 Tekirdağ;577812;598658;619152;639837;661237;683199;705692;728396;770772;783310;798109;829873;852321;874475;906732;937910;972875;1005463 Tokat;641033;639371;636715;633682;630722;627781;624744;620722;617158;624439;617802;608299;613990;598708;597920;593990;602662;602086 Trabzon;720620;724340;727080;729529;732221;735072;737969;740569;748982;765127;763714;757353;757898;758237;766782;768417;779379;786326 Tunceli;82554;82871;83074;83241;83433;83640;83849;84022;86449;83061;76699;85062;86276;85428;86527;86076;82193;82498 Şanlıurfa;1257753;1294842;1330964;1367305;1404961;1443639;1483244;1523099;1574224;1613737;1663371;1716254;1762075;1801980;1845667;1892320;1940627;1985753 Uşak;320535;322814;324673;326417;328287;330243;332237;334115;334111;335860;338019;339731;342269;346508;349459;353048;358736;364971 Van;895836;908296;919727;930984;942771;954945;967394;979671;1004369;1022310;1035418;1022532;1051975;1070113;1085542;1096397;1100190;1106891 Yozgat;544446;538313;531220;523696;516096;508398;500487;492127;484206;487365;476096;465696;453211;444211;432560;419440;421041;418650 Zonguldak;630323;629346;627407;625114;622912;620744;618500;615890;619151;619812;619703;612406;606527;601567;598796;595907;597524;596892 Aksaray;351474;353939;355942;357819;359834;361941;364089;366109;370598;376907;377505;378823;379915;382806;384252;386514;396673;402404 Bayburt;75221;75517;75709;75868;76050;76246;76444;76609;75675;74710;74412;76724;75797;75620;80607;78550;90154;80417 Karaman;214461;216318;217902;219417;221026;222700;224409;226049;230145;231872;232633;234005;235424;237939;240362;242196;245610;246672 Kırıkkale;287427;286900;285933;284803;283711;282633;281518;280234;279325;280834;276647;274992;274727;274658;271092;270271;277984;278749 Batman;408820;418186;427172;436165;445508;455118;464954;472487;485616;497998;510200;524499;534205;547581;557593;566633;576899;585252 Şırnak;362700;370314;377574;384824;392364;400123;408065;416001;429287;430424;430109;457997;466982;475255;488966;490184;483788;503236 Bartın;175982;177060;177903;178678;179519;180401;181300;182131;185368;188449;187758;187291;188436;189139;189405;190708;192389;193577 Ardahan;122409;121305;119993;118590;117178;115750;114283;112721;112242;108169;105454;107455;106643;102782;100809;99265;98335;97096 Iğdır;174285;175550;176588;177563;178609;179701;180815;181866;184025;183486;184418;188857;190409;190424;192056;192435;192785;194775 Yalova;144923;150027;155041;160099;165333;170705;176207;181758;197412;202531;203741;206535;211799;220122;226514;233009;241665;251203 Karabük;205172;207241;209056;210812;212667;214591;216557;218463;216248;218564;227610;219728;225145;230251;231333;236978;242347;244453 Kilis;109698;111024;112219;113387;114615;115886;117185;118457;120991;122104;123135;124452;124320;128586;128781;130655;130825;136319 Osmaniye;411163;417418;423214;428943;434930;441108;447428;452880;464704;471804;479221;485357;492135;498981;506807;512873;522175;527724 Düzce;296712;300686;304316;307884;311623;315487;319438;323328;328611;335156;338188;342146;346493;351509;355549;360388;370371;377610
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* This table can be read into a DataFrame using `read_csv`:
populationDF = pd.read_csv("data/population.csv") populationDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Notice that `read_csv` automatically considered the first row in the file to be a header row.* We can override default behavior by customizing some the arguments, like `header`, `names` or `index_col`. * `read_csv` is just a convenience function for `read_table`, since csv is such a common format:
pd.set_option('max_columns', 5) populationDF = pd.read_table("data/population_missing.csv", sep=';') populationDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* The `sep` argument can be customized as needed to accomodate arbitrary separators. * If we have sections of data that we do not wish to import (for example, in this example empty rows), we can populate the `skiprows` argument:
populationDF = pd.read_csv("data/population_missing.csv", sep=';', skiprows=[1,2]) populationDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* For a more useful index, we can specify the first column, which provide a unique index to the data.
populationDF = pd.read_csv("data/population.csv", sep=';', index_col='Provinces') populationDF.index
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Conversely, if we only want to import a small number of rows from, say, a very large data file we can use `nrows`:
pd.read_csv("data/population.csv", sep=';', nrows=4)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Most real-world data is incomplete, with values missing due to incomplete observation, data entry or transcription error, or other reasons. Pandas will automatically recognize and parse common missing data indicators, including `NA`, `NaN`, `NULL`.
pd.read_csv("data/population_missing.csv", sep=';').head(10)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Above, Pandas recognized `NaN` and an empty field as missing data.
pd.isnull(pd.read_csv("data/population_missing.csv", sep=';')).head(10)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Microsoft Excel * Since so much financial and scientific data ends up in Excel spreadsheets, Pandas' ability to directly import Excel spreadsheets is valuable. * This support is contingent on having one or two dependencies (depending on what version of Excel file is being imported) installed: `xlrd` and `openpyxl`.* Importing Excel data to Pandas is a two-step process. First, we create an `ExcelFile` object using the path of the file:
excel_file = pd.ExcelFile('data/population.xlsx') excel_file
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Then, since modern spreadsheets consist of one or more "sheets", we parse the sheet with the data of interest:
excelDf = excel_file.parse("Sheet 1 ") excelDf
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Also, there is a `read_excel` conveneince function in Pandas that combines these steps into a single call:
excelDf2 = pd.read_excel('data/population.xlsx', sheet_name='Sheet 1 ') excelDf2.head(10)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* In, the first day we learned how to read and write `JSON` Files, with that way you can also import JSON files to `DataFrames`. * Also, you can connect to databases and import your data into `DataFrames` by help of 3rd party libraries. Pandas Fundamentals * This section introduces the new user to the key functionality of Pandas that is required to use the software effectively.* For some variety, we will leave our population data behind and employ some `Superhero` data. * The data comes from Marvel Wikia.* The file has the following variables: VariableDefinitionpage_idThe unique identifier for that characters page within the wikianameThe name of the characterurlslugThe unique url within the wikia that takes you to the characterIDThe identity status of the character (Secret Identity, Public identity No Dual Identity)ALIGNIf the character is Good, Bad or NeutralEYEEye color of the characterHAIRHair color of the characterSEXSex of the character (e.g. Male, Female, etc.)GSMIf the character is a gender or sexual minority (e.g. Homosexual characters, bisexual characters)ALIVEIf the character is alive or deceasedAPPEARANCESThe number of appareances of the character in comic books (as of Sep. 2, 2014. Number will become increasingly out of date as time goes on.)FIRST APPEARANCEThe month and year of the character's first appearance in a comic book, if availableYEARThe year of the character's first appearance in a comic book, if available
pd.set_option('max_columns', 12) pd.set_option('display.notebook_repr_html', True) marvelDF = pd.read_csv("data/marvel-wikia-data.csv", index_col='page_id') marvelDF.head(5)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Notice that we specified the `page_id` column as the index, since it appears to be a unique identifier. We could try to create a unique index ourselves by trimming `name`: * First, import the regex module of python.* Then, trim the name column with regex.
import re pattern = re.compile('([a-zA-Z]|-|\s|\.|\')*([a-zA-Z])') heroName = [] for name in marvelDF.name: match = re.search(pattern, name) if match: heroName.append(match.group()) else: heroName.append(name) heroName
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* This looks okay, let's copy '__marvelDF__' to '__marvelDF_newID__' and assign new indexes.
marvelDF_newID = marvelDF.copy() marvelDF_newID.index = heroName marvelDF_newID.head(5)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Let's check the uniqueness of ID's:
marvelDF_newID.index.is_unique
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* So, indices need not be unique. Our choice is not unique because some of superheros have some differenet variations.
pd.Series(marvelDF_newID.index).value_counts()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* The most important consequence of a non-unique index is that indexing by label will return multiple values for some labels:
marvelDF_newID.loc['Peter Parker']
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Let's give a truly unique index by not triming `name` column:
hero_id = marvelDF.name marvelDF_newID = marvelDF.copy() marvelDF_newID.index = hero_id marvelDF_newID.head() marvelDF_newID.index.is_unique
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* We can create meaningful indices more easily using a hierarchical index.* For now, we will stick with the numeric IDs as our index for '__NewID__' DataFrame.
marvelDF_newID.index = range(16376) marvelDF.index = marvelDF['name'] marvelDF_newID.head(5)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Manipulating indices * __Reindexing__ allows users to manipulate the data labels in a DataFrame. * It forces a DataFrame to conform to the new index, and optionally, fill in missing data if requested.* A simple use of `reindex` is reverse the order of the rows:
marvelDF_newID.reindex(marvelDF_newID.index[::-1]).head()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Keep in mind that `reindex` does not work if we pass a non-unique index series. * We can remove rows or columns via the `drop` method:
marvelDF_newID.shape marvelDF_dropped = marvelDF_newID.drop([16375, 16374]) print(marvelDF_newID.shape) print(marvelDF_dropped.shape) marvelDF_dropped = marvelDF_newID.drop(['EYE','HAIR'], axis=1) print(marvelDF_newID.shape) print(marvelDF_dropped.shape)
(16376, 12) (16376, 10)
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Indexing and Selection * Indexing works like indexing in NumPy arrays, except we can use the labels in the `Index` object to extract values in addition to arrays of integers.
heroAppearances = marvelDF.APPEARANCES heroAppearances
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Let's start with Numpy style indexing:
heroAppearances[:3]
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Indexing by Label:
heroAppearances[['Spider-Man (Peter Parker)','Hulk (Robert Bruce Banner)']]
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* We can also slice with data labels, since they have an intrinsic order within the Index:
heroAppearances['Spider-Man (Peter Parker)':'Matthew Murdock (Earth-616)']
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* You can change sliced array, and if you get warning it's ok.
heroAppearances['Minister of Castile D\'or (Earth-616)':'Yologarch (Earth-616)'] = 0 heroAppearances
/Users/alpyuzbasioglu/anaconda2/lib/python2.7/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy """Entry point for launching an IPython kernel.
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* In a `DataFrame` we can slice along either or both axes:
marvelDF[['SEX','ALIGN']] mask = marvelDF.APPEARANCES>50 marvelDF[mask]
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* The indexing field `loc` allows us to select subsets of rows and columns in an intuitive way:
marvelDF.loc['Spider-Man (Peter Parker)', ['ID', 'EYE', 'HAIR']] marvelDF.loc[['Spider-Man (Peter Parker)','Thor (Thor Odinson)'],['ID', 'EYE', 'HAIR']]
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Operations * `DataFrame` and `Series` objects allow for several operations to take place either on a single object, or between two or more objects.* For example, we can perform arithmetic on the elements of two objects, such as change in population across years:
populationDF pop2000 = populationDF['2000'] pop2017 = populationDF['2017'] pop2000DF = pd.Series(pop2000.values, index=populationDF.index) pop2017DF = pd.Series(pop2017.values, index=populationDF.index) popDiff = pop2017DF - pop2000DF popDiff
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Let's assume our '__pop2000DF__' DataFrame has not row which index is "Yalova"
pop2000DF["Yalova"] = np.nan pop2000DF popDiff = pop2017DF - pop2000DF popDiff
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* For accessing not null elements, we can use Pandas'notnull function.
popDiff[popDiff.notnull()]
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* We can add `fill_value` argument to insert a zero for home `NaN` values.
pop2017DF.subtract(pop2000DF, fill_value=0)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* We can also use functions to each column or row of a `DataFrame`
minPop = pop2017DF.values.min() indexOfMinPop = pop2017DF.index[pop2017DF.values.argmin()] print(indexOfMinPop + " -> " + str(minPop)) populationDF['2000'] = np.ceil(populationDF['2000'] / 10000) * 10000 populationDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Sorting and Ranking * Pandas objects include methods for re-ordering data.
populationDF.sort_index(ascending=True).head() populationDF.sort_index().head() populationDF.sort_index(axis=1, ascending=False).head()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* We can also use `order` to sort a `Series` by value, rather than by label. * For a `DataFrame`, we can sort according to the values of one or more columns using the `by` argument of `sort_values`:
populationDF[['2017','2001']].sort_values(by=['2017', '2001'],ascending=[False,True]).head(10)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* __Ranking__ does not re-arrange data, but instead returns an index that ranks each value relative to others in the Series.
populationDF['2010'].rank(ascending=False) populationDF[['2017','2001']].sort_values(by=['2017', '2001'],ascending=[False,True]).rank(ascending=False)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Ties are assigned the mean value of the tied ranks, which may result in decimal values.
pd.Series([50,60,50]).rank()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Alternatively, you can break ties via one of several methods, such as by the order in which they occur in the dataset:
pd.Series([100,50,100]).rank(method='first')
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Calling the `DataFrame`'s `rank` method results in the ranks of all columns:
populationDF.rank(ascending=False)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Hierarchical indexing * Hierarchical indexing is an important feature of pandas enabling you to have multiple (two or more) index levels on an axis.* Somewhat abstractly, it provides a way for you to work with higher dimensional data in a lower dimensional form. * Let’s create a Series with a list of lists or arrays as the index:
data = pd.Series(np.random.randn(10), index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'], [1, 2, 3, 1, 2, 3, 1, 2, 2, 3]]) data data.index
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* With a hierarchically-indexed object, so-called partial indexing is possible, enabling you to concisely select subsets of the data:
data['b'] data['a':'c']
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Selection is even possible in some cases from an “inner” level:
data[:, 1]
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Hierarchical indexing plays a critical role in reshaping data and group-based operations like forming a pivot table. For example, this data could be rearranged into a DataFrame using its unstack method:
dataDF = data.unstack() dataDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* The inverse operation of unstack is stack:
dataDF.stack()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Missing data * The occurence of missing data is so prevalent that it pays to use tools like Pandas, which seamlessly integrates missing data handling so that it can be dealt with easily, and in the manner required by the analysis at hand.* Missing data are represented in `Series` and `DataFrame` objects by the `NaN` floating point value. However, `None` is also treated as missing, since it is commonly used as such in other contexts (NumPy).
weirdSeries = pd.Series([np.nan, None, 'string', 1]) weirdSeries weirdSeries.isnull()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Missing values may be dropped or indexed out:
population2 population2.dropna() population2[population2.notnull()] dataDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* By default, `dropna` drops entire rows in which one or more values are missing.
dataDF.dropna()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* This can be overridden by passing the `how='all'` argument, which only drops a row when every field is a missing value.
dataDF.dropna(how='all')
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* This can be customized further by specifying how many values need to be present before a row is dropped via the `thresh` argument.
dataDF[2]['c'] = np.nan dataDF dataDF.dropna(thresh=2)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* If we want to drop missing values column-wise instead of row-wise, we use `axis=1`.
dataDF[1]['d'] = np.random.randn(1) dataDF dataDF.dropna(axis=1)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Rather than omitting missing data from an analysis, in some cases it may be suitable to fill the missing value in, either with a default value (such as zero) or a value that is either imputed or carried forward/backward from similar data points. * We can do this programmatically in Pandas with the `fillna` argument.
dataDF dataDF.fillna(0) dataDF.fillna({2: 1.5, 3:0.50})
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Notice that `fillna` by default returns a new object with the desired filling behavior, rather than changing the `Series` or `DataFrame` in place.
dataDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* If you don't like this behaviour you can alter values in-place using `inplace=True`.
dataDF.fillna({2: 1.5, 3:0.50}, inplace=True) dataDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Missing values can also be interpolated, using any one of a variety of methods:
dataDF[2]['c'] = np.nan dataDF[3]['d'] = np.nan dataDF
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* We can also propagate non-null values forward or backward.
dataDF.fillna(method='ffill') dataDF.fillna(dataDF.mean())
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
Data summarization * We often wish to summarize data in `Series` or `DataFrame` objects, so that they can more easily be understood or compared with similar data.* The NumPy package contains several functions that are useful here, but several summarization or reduction methods are built into Pandas data structures.
marvelDF.sum()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Clearly, `sum` is more meaningful for some columns than others.(Total Appearances) * For methods like `mean` for which application to string variables is not just meaningless, but impossible, these columns are automatically exculded:
marvelDF.mean()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* The important difference between NumPy's functions and Pandas' methods is that Numpy have different functions for handling missing data like 'nansum' but Pandas use same functions.
dataDF dataDF.mean()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* Sometimes we may not want to ignore missing values, and allow the `nan` to propagate.
dataDF.mean(skipna=False)
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* A useful summarization that gives a quick snapshot of multiple statistics for a `Series` or `DataFrame` is `describe`:
dataDF.describe()
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
* `describe` can detect non-numeric data and sometimes yield useful information about it. Writing Data to Files * Pandas can also export data to a variety of storage formats.* We will bring your attention to just a couple of these.
myDF = populationDF['2000'] myDF.to_csv("data/roundedPopulation2000.csv")
_____no_output_____
Apache-2.0
iPython Notebooks/Introduction to Pandas Part 1.ipynb
AlpYuzbasioglu/Zeppelin-Notebooks
S6 Transfer Function Equivalence3C6 Section 6: equivalence of transfer function expressions imports and definitions
import numpy as np import scipy.linalg as la import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as animation matplotlib.rcParams.update({'font.size': 12,'font.family':'serif'}) import os from IPython.display import HTML, display from ipywidgets import Output, widgets, Layout %matplotlib notebook
_____no_output_____
MIT
S6_transfer_function_equivalance.ipynb
torebutlin/PartIIA-3C6
Setup properties
# setup parameters L = 1 P = 1 m = 1 c = np.sqrt(P/m) x = 0.6*L a = 0.2*L w1 = np.pi*c/L N = 20 # Create axes w = np.linspace(0.01,(N+1)*w1,1000) # Direct approach if x<a: G1 = c/(w*P) * np.sin(w*(L-a)/c) * np.sin(w*x/c) / np.sin(w*L/c) else: G1 = c/(w*P) * np.sin(w*a/c) * np.sin(w*(L-x)/c) / np.sin(w*L/c) plt.figure(figsize=(9,5),dpi=100) yscale = np.percentile(20*np.log10(np.abs(G1)),[1,99]) # Get axis scaling to look ok for undamped case plt.ylim(yscale) plt.xlabel('Frequency') plt.ylabel('$20 \log_{10}|G|$') plt.xlim([0,11*w1]) plt.ylim([yscale[0]-10,yscale[1]+10]) p1 = plt.plot([],[],linestyle='--',linewidth=2,label='direct') p1[0].set_data(w,20*np.log10(np.abs(G1))) p2 = plt.plot([],[],linewidth=2,label='modal sum') G2 = 0 n=0 button = widgets.Button(description="Add another mode",layout=Layout(width='95%')) button.button_style = 'primary' display(button) def next_plot(b): global G2,n n += 1 G2 += 2/(m*L) * np.sin(n*np.pi*a/L) * np.sin(n*np.pi*x/L) / ((n*w1)**2 - w**2) p2[0].set_data(w,20*np.log10(np.abs(G2))) plt.title("number of modes = {}".format(n)) plt.legend(loc='lower left') if n >= 20: button.layout.visibility = 'hidden' button.on_click(next_plot)
_____no_output_____
MIT
S6_transfer_function_equivalance.ipynb
torebutlin/PartIIA-3C6
\ Developer: Ali Hashaam (ali.hashaam@initos.com) \ 5th March 2019 \ © 2019 initOS GmbH \ License MIT \ Library for TSVM and SelfLearning taken from https://github.com/tmadl/semisup-learn \ Library for lagrangean-S3VM taken from https://github.com/fbagattini/lagrangean-s3vm
from sklearn.svm import SVC import pandas as pd import numpy as np from __future__ import division import re from sklearn.model_selection import StratifiedShuffleSplit from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from frameworks.SelfLearning import * from imblearn.over_sampling import SMOTE from collections import Counter from imblearn.under_sampling import RepeatedEditedNearestNeighbours from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV from sklearn.externals import joblib import time import matplotlib.pyplot as plt from sklearn.metrics import classification_report from methods.scikitTSVM import SKTSVM from sklearn.metrics import confusion_matrix from sklearn.utils.multiclass import unique_labels source_domain = pd.read_csv('github_preprocessed_data.csv') target_domain = pd.read_csv('mantis_data_for_domain_adaptation.csv') source_domain.drop(["Unnamed: 0"], axis=1, inplace=True) target_domain.drop(["Unnamed: 0"], axis=1, inplace=True) source_domain['text'] = source_domain['text'].fillna("") target_domain['textual_data'] = target_domain['textual_data'].fillna("") print source_domain['type'].value_counts() print target_domain['type'].value_counts() unlabelled_index_target = target_domain[(target_domain['bug_or_not'].isnull())].index labelled_index_target = target_domain[~(target_domain['bug_or_not'].isnull())].index len(unlabelled_index_target), len(labelled_index_target) target_domain_labeled = target_domain.loc[labelled_index_target] len(target_domain_labeled), len(target_domain) tfidf_vectorizer_source = TfidfVectorizer(max_df=0.95, min_df=2, max_features=500, stop_words='english') source_domain_balanced = source_domain.groupby('type').apply(lambda x: x.sample(400)) print source_domain['type'].value_counts() source_domain_X = tfidf_vectorizer_source.fit_transform(source_domain_balanced['text']) source_domain_Y = np.array(source_domain_balanced['type']) stratified_shuffle_split = StratifiedShuffleSplit(n_splits=3, test_size=0.3, random_state=0) scores = [] iteration = 1 for train_index, test_index in stratified_shuffle_split.split(source_domain_X, source_domain_Y): X_train = source_domain_X[train_index].copy() Y_train = source_domain_Y[train_index].copy() X_test = source_domain_X[test_index].copy() Y_test = source_domain_Y[test_index].copy() clf = MultinomialNB() clf.fit(X_train, Y_train) print clf.score(X_test, Y_test.astype(float)) y_pred = clf.predict(X_test) result = classification_report(Y_test.astype(float), y_pred.astype(float), output_dict=True) src = pd.DataFrame(result) src.transpose().to_csv('{}_{}_{}_latex_table_report.csv'.format('source_vs_source', '500', iteration)) print src.transpose() iteration += 1
0.845833333333 f1-score precision recall support 0.0 0.841202 0.867257 0.816667 120.0 1.0 0.850202 0.826772 0.875000 120.0 macro avg 0.845702 0.847014 0.845833 240.0 micro avg 0.845833 0.845833 0.845833 240.0 weighted avg 0.845702 0.847014 0.845833 240.0 0.85 f1-score precision recall support 0.0 0.848739 0.855932 0.841667 120.0 1.0 0.851240 0.844262 0.858333 120.0 macro avg 0.849990 0.850097 0.850000 240.0 micro avg 0.850000 0.850000 0.850000 240.0 weighted avg 0.849990 0.850097 0.850000 240.0 0.895833333333 f1-score precision recall support 0.0 0.889868 0.943925 0.841667 120.0 1.0 0.901186 0.857143 0.950000 120.0 macro avg 0.895527 0.900534 0.895833 240.0 micro avg 0.895833 0.895833 0.895833 240.0 weighted avg 0.895527 0.900534 0.895833 240.0
MIT
9) domain_adaptation/5.domain_adaptation.ipynb
initOS/research-criticality-identification
Baseline TL Source VS Target Supervised
source_domain_X = tfidf_vectorizer_source.fit_transform(source_domain['text']) source_domain_Y = np.array(source_domain['type']) for x in xrange(5): clf = MultinomialNB() clf.fit(source_domain_X, source_domain_Y) target_domain_labeled_balanced = target_domain_labeled.groupby('type').apply(lambda x: x.sample(90)) target_domain_X = tfidf_vectorizer_source.transform(target_domain_labeled_balanced['textual_data']) target_domain_Y = np.array(target_domain_labeled_balanced['type']) print("members for classes {}".format(",".join("(%s,%s)" % tup for tup in sorted(Counter(target_domain_Y).items())))) score = clf.score(target_domain_X, target_domain_Y.astype(float)) print "Baseline TL Score: "+ str(score) y_pred = clf.predict(target_domain_X) print("members for classes {}".format(",".join("(%s,%s)" % tup for tup in sorted(Counter(y_pred).items())))) result = classification_report(target_domain_Y.astype(float), y_pred.astype(float), output_dict=True) src = pd.DataFrame(result) print src src.transpose().to_csv('{}_{}_{}_latex_table_report.csv'.format('source_vs_target_supervised', '500', x))
members for classes (0.0,90),(1.0,90) Baseline TL Score: 0.566666666667 members for classes (0,44),(1,136) 0.0 1.0 macro avg micro avg weighted avg f1-score 0.417910 0.654867 0.536389 0.566667 0.536389 precision 0.636364 0.544118 0.590241 0.566667 0.590241 recall 0.311111 0.822222 0.566667 0.566667 0.566667 support 90.000000 90.000000 180.000000 180.000000 180.000000 members for classes (0.0,90),(1.0,90) Baseline TL Score: 0.6 members for classes (0,38),(1,142) 0.0 1.0 macro avg micro avg weighted avg f1-score 0.437500 0.689655 0.563578 0.6 0.563578 precision 0.736842 0.563380 0.650111 0.6 0.650111 recall 0.311111 0.888889 0.600000 0.6 0.600000 support 90.000000 90.000000 180.000000 180.0 180.000000 members for classes (0.0,90),(1.0,90) Baseline TL Score: 0.6 members for classes (0,36),(1,144) 0.0 1.0 macro avg micro avg weighted avg f1-score 0.428571 0.692308 0.56044 0.6 0.56044 precision 0.750000 0.562500 0.65625 0.6 0.65625 recall 0.300000 0.900000 0.60000 0.6 0.60000 support 90.000000 90.000000 180.00000 180.0 180.00000 members for classes (0.0,90),(1.0,90) Baseline TL Score: 0.583333333333 members for classes (0,41),(1,139) 0.0 1.0 macro avg micro avg weighted avg f1-score 0.427481 0.672489 0.549985 0.583333 0.549985 precision 0.682927 0.553957 0.618442 0.583333 0.618442 recall 0.311111 0.855556 0.583333 0.583333 0.583333 support 90.000000 90.000000 180.000000 180.000000 180.000000 members for classes (0.0,90),(1.0,90) Baseline TL Score: 0.633333333333 members for classes (0,32),(1,148) 0.0 1.0 macro avg micro avg weighted avg f1-score 0.459016 0.722689 0.590853 0.633333 0.590853 precision 0.875000 0.581081 0.728041 0.633333 0.728041 recall 0.311111 0.955556 0.633333 0.633333 0.633333 support 90.000000 90.000000 180.000000 180.000000 180.000000
MIT
9) domain_adaptation/5.domain_adaptation.ipynb
initOS/research-criticality-identification
TL Source Semi-Supervised
target_domain_unlabeled = target_domain.loc[unlabelled_index_target, ["textual_data", "type"]].copy() target_domain_unlabeled["type"] = -1 source_domain_df = source_domain[["text", "type"]].copy() source_domain_df.rename({"text":"textual_data", "type":"type"}, axis=1, inplace=1) domain_adaptation_df = pd.concat([source_domain_df, target_domain_unlabeled]) len(domain_adaptation_df), len(source_domain_df), len(target_domain_unlabeled) print domain_adaptation_df['type'].value_counts() print target_domain_labeled_balanced['type'].value_counts() from collections import Counter #print("members for classes {}".format(",".join("(%s,%s)" % tup for tup in sorted(Counter(Y).items())))) def domain_adaptation(dom_a_df, target_domain_labeled, classifier, label_type, neg_class, classifier_name): dom_a_df.loc[dom_a_df['type']==0, 'type'] = neg_class dom_a_df.loc[dom_a_df['type']==1, 'type'] = 1 target_domain_labeled.loc[target_domain_labeled['type']==0, 'type'] = neg_class target_domain_labeled.loc[target_domain_labeled['type']==1, 'type'] = 1 tfidf_vectorizer_source = TfidfVectorizer(max_df=0.95, min_df=2, max_features=500, stop_words='english') source_X = tfidf_vectorizer_source.fit_transform(dom_a_df['textual_data']).toarray() source_Y = np.array(dom_a_df['type']) target_domain_X = tfidf_vectorizer_source.transform(target_domain_labeled['textual_data']).toarray() target_domain_Y = np.array(target_domain_labeled['type']) if label_type != 'int': source_Y = source_Y.astype(float) else: source_Y = source_Y.astype(int) classifier.fit(source_X, source_Y) score = classifier.score(target_domain_X, target_domain_Y.astype(int)) joblib.dump(classifier, 'models/DA_{}.pkl'.format(classifier_name)) joblib.dump(target_domain_X, 'models/X_test_DA_{}.pkl'.format(classifier_name)) joblib.dump(target_domain_Y, 'models/Y_test_DA_{}.pkl'.format(classifier_name)) print "{} score: {}".format(classifier_name, score) sklearn_lr = LogisticRegression(solver='lbfgs') domain_adaptation(domain_adaptation_df.copy(), target_domain_labeled_balanced.copy(), SelfLearningModel(sklearn_lr), 'float', 0, 'ST_LR') domain_adaptation(domain_adaptation_df.copy(), target_domain_labeled_balanced.copy(), SKTSVM(), 'int', 0, 'TSVM') def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) # Only use the labels that appear in the data #classes = classes[unique_labels(y_true, y_pred)] if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=['Bug', 'Non-Bug'], yticklabels=['Bug', 'Non-Bug'], title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() #plt.savefig('Confusion_matrix(Phase_3).png', bbox_inches='tight') return ax def get_results(classifier, data_type): dict_features = {} model = joblib.load('models/DA_{}.pkl'.format(classifier, 3)) x_tst = joblib.load('models/X_test_DA_{}.pkl'.format(classifier, 3)) y_tst = joblib.load('models/Y_test_DA_{}.pkl'.format(classifier, 3)) acc = model.score(x_tst, y_tst.astype(data_type)) print acc y_pred = model.predict(x_tst) print("members for classes {}".format(",".join("(%s,%s)" % tup for tup in sorted(Counter(y_tst).items())))) print("members for classes {}".format(",".join("(%s,%s)" % tup for tup in sorted(Counter(y_pred).items())))) result = classification_report(y_tst.astype(data_type), y_pred.astype(data_type), output_dict=True) result_df = pd.DataFrame(result) result_df.transpose().to_csv('DA_{}_latex_table_report.csv'.format(classifier)) np.set_printoptions(precision=2) # Plot non-normalized confusion matrix plot_confusion_matrix(y_tst.astype(data_type), y_pred.astype(data_type), classes=[0, 1], title='Confusion matrix, without normalization') # Plot normalized confusion matrix #plot_confusion_matrix(y_tst.astype(data_type), y_pred.astype(data_type), classes=[0, 1], normalize=True, # title='Normalized confusion matrix') plt.show() print result_df.transpose() return result_df st_results = get_results('ST_LR', float) tsvm_results = get_results('TSVM', int)
0.516666666667 members for classes (0.0,90),(1.0,90) members for classes (0.0,5),(1.0,175) Confusion matrix, without normalization [[ 4 86] [ 1 89]]
MIT
9) domain_adaptation/5.domain_adaptation.ipynb
initOS/research-criticality-identification
1. Connect To Google Drive + Get Data
# MAIN DIRECTORY STILL TO DO from google.colab import drive drive.mount('/content/gdrive') data_file = "/content/gdrive/MyDrive/CSCI4511W/project/sentiments.csv" import pandas as pd import numpy as np cols = ['sentiment','id','date','query_string','user','text'] sms_data = pd.read_csv(data_file, encoding='latin-1',header=None,names=cols) # replace lables 0 = neg 1= pos sms_data.sentiment = sms_data.sentiment.replace({0: 0, 4: 1}) labels = sms_data[sms_data.columns[0]].to_numpy()
_____no_output_____
MIT
project_tfif.ipynb
lauraAriasFdez/Ciphers
Preprocess Data
import re import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer #We import English stop-words from the NLTK package and removed them if found in the sentence. #While removing stop-words, we perform stemming that is if the word is not a stop-word, it will be converted to its root form. This is called stemming. """ https://stackoverflow.com/questions/52026677/sentiment140-preprocessing https://www.analyticsvidhya.com/blog/2020/11/understanding-naive-bayes-svm-and-its-implementation-on-spam-sms/ """ def clean_data(content): stemming = PorterStemmer() for i in range (0,len(content)): ## print where in cleaning they are if (i%1000000==0): print(i ," already cleaned") #remove @mentions tweet = re.sub(r'@[A-Za-z0-9]+',"",content[i]) #remove urls tweet = re.sub(r'https?:\/\/\S+',"",tweet) #remove all unecessary charachters like punctuations tweet = re.sub('[^a-zA-Z]',repl = ' ',string = tweet) tweet.lower() tweet = tweet.split() ## steeeming and remove stop words tweet = [stemming.stem(word) for word in tweet if word not in set(stopwords.words('english'))] tweet = ' '.join(tweet) #cleaned Twwet content[i] = tweet return content
[nltk_data] Downloading package stopwords to /root/nltk_data... [nltk_data] Unzipping corpora/stopwords.zip.
MIT
project_tfif.ipynb
lauraAriasFdez/Ciphers
https://getpocket.com/read/3040941140 Texthero is designed as a Pandas wrapper, so it makes it easier than ever to preprocess and analyze text based Pandas Series
!pip install texthero import pandas as pd import texthero as hero #config import cid, csec, ua custom_cleaning = [ #Replace not assigned values with empty space hero.preprocessing.fillna, hero.preprocessing.lowercase, hero.preprocessing.remove_digits, hero.preprocessing.remove_punctuation, hero.preprocessing.remove_diacritics, hero.preprocessing.remove_stopwords, hero.preprocessing.remove_whitespace, hero.preprocessing.stem ] content = hero.clean(sms_data['text'], pipeline = custom_cleaning) #content = content.to_numpy()
_____no_output_____
MIT
project_tfif.ipynb
lauraAriasFdez/Ciphers
TF-IDF Feature Extraction
from sklearn.feature_extraction.text import TfidfVectorizer tfidf = TfidfVectorizer() tfidf_data = tfidf.fit_transform(content) from sklearn.model_selection import train_test_split tfidf_x_train,tfidf_x_test,y_train,y_test = train_test_split(tfidf_data,labels,test_size = 0.3, stratify=labels,random_state=100)
_____no_output_____
MIT
project_tfif.ipynb
lauraAriasFdez/Ciphers
Multinomial Naive Bayes
from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report, confusion_matrix from sklearn.metrics import f1_score # NAIVE BAYES + TLF print("NAIVE BAYES + TLF______________________________________________________________") clf_multinomialnb = MultinomialNB() clf_multinomialnb.fit(tfidf_x_train,y_train) y_pred = clf_multinomialnb.predict(tfidf_x_test) print(classification_report(y_test,y_pred)) #>>> f1_score(y_true, y_pred, average='weighted') f1_score(y_test,y_pred)
NAIVE BAYES + TLF______________________________________________________________ precision recall f1-score support 0 0.74 0.79 0.76 240000 1 0.77 0.72 0.75 240000 accuracy 0.76 480000 macro avg 0.76 0.76 0.76 480000 weighted avg 0.76 0.76 0.76 480000
MIT
project_tfif.ipynb
lauraAriasFdez/Ciphers
SVM
from sklearn.svm import LinearSVC # SVM + TLF print("LINEAR SVM + TLF______________________________________________________________") linearsvc = LinearSVC() linearsvc.fit(tfidf_x_train,y_train) y_pred = linearsvc.predict(tfidf_x_test) print(classification_report(y_test,y_pred)) f1_score(y_test,y_pred)
LINEAR SVM + TLF______________________________________________________________ precision recall f1-score support 0 0.78 0.75 0.77 240000 1 0.76 0.79 0.77 240000 accuracy 0.77 480000 macro avg 0.77 0.77 0.77 480000 weighted avg 0.77 0.77 0.77 480000
MIT
project_tfif.ipynb
lauraAriasFdez/Ciphers
Logistic Regression
#https://towardsdatascience.com/logistic-regression-using-python-sklearn-numpy-mnist-handwriting-recognition-matplotlib-a6b31e2b166a from sklearn.linear_model import LogisticRegression logisticRegr = LogisticRegression() logisticRegr.fit(tfidf_x_train,y_train) y_pred = logisticRegr.predict(tfidf_x_test) print(classification_report(y_test,y_pred)) f1_score(y_test,y_pred)
_____no_output_____
MIT
project_tfif.ipynb
lauraAriasFdez/Ciphers
Chainer MNIST Model Deployment * Wrap a Chainer MNIST python model for use as a prediction microservice in seldon-core * Run locally on Docker to test * Deploy on seldon-core running on minikube Dependencies * [Helm](https://github.com/kubernetes/helm) * [Minikube](https://github.com/kubernetes/minikube) * [S2I](https://github.com/openshift/source-to-image)```bashpip install seldon-corepip install chainer==6.2.0``` Train locally
#!/usr/bin/env python import argparse import chainer import chainer.functions as F import chainer.links as L import chainerx from chainer import training from chainer.training import extensions # Network definition class MLP(chainer.Chain): def __init__(self, n_units, n_out): super(MLP, self).__init__() with self.init_scope(): # the size of the inputs to each layer will be inferred self.l1 = L.Linear(None, n_units) # n_in -> n_units self.l2 = L.Linear(None, n_units) # n_units -> n_units self.l3 = L.Linear(None, n_out) # n_units -> n_out def forward(self, x): h1 = F.relu(self.l1(x)) h2 = F.relu(self.l2(h1)) return self.l3(h2) def main(): parser = argparse.ArgumentParser(description="Chainer example: MNIST") parser.add_argument( "--batchsize", "-b", type=int, default=100, help="Number of images in each mini-batch", ) parser.add_argument( "--epoch", "-e", type=int, default=20, help="Number of sweeps over the dataset to train", ) parser.add_argument( "--frequency", "-f", type=int, default=-1, help="Frequency of taking a snapshot" ) parser.add_argument( "--device", "-d", type=str, default="-1", help="Device specifier. Either ChainerX device " "specifier or an integer. If non-negative integer, " "CuPy arrays with specified device id are used. If " "negative integer, NumPy arrays are used", ) parser.add_argument( "--out", "-o", default="result", help="Directory to output the result" ) parser.add_argument( "--resume", "-r", type=str, help="Resume the training from snapshot" ) parser.add_argument("--unit", "-u", type=int, default=1000, help="Number of units") parser.add_argument( "--noplot", dest="plot", action="store_false", help="Disable PlotReport extension", ) group = parser.add_argument_group("deprecated arguments") group.add_argument( "--gpu", "-g", dest="device", type=int, nargs="?", const=0, help="GPU ID (negative value indicates CPU)", ) args = parser.parse_args(args=[]) device = chainer.get_device(args.device) print("Device: {}".format(device)) print("# unit: {}".format(args.unit)) print("# Minibatch-size: {}".format(args.batchsize)) print("# epoch: {}".format(args.epoch)) print("") # Set up a neural network to train # Classifier reports softmax cross entropy loss and accuracy at every # iteration, which will be used by the PrintReport extension below. model = L.Classifier(MLP(args.unit, 10)) model.to_device(device) device.use() # Setup an optimizer optimizer = chainer.optimizers.Adam() optimizer.setup(model) # Load the MNIST dataset train, test = chainer.datasets.get_mnist() train_iter = chainer.iterators.SerialIterator(train, args.batchsize) test_iter = chainer.iterators.SerialIterator( test, args.batchsize, repeat=False, shuffle=False ) # Set up a trainer updater = training.updaters.StandardUpdater(train_iter, optimizer, device=device) trainer = training.Trainer(updater, (args.epoch, "epoch"), out=args.out) # Evaluate the model with the test dataset for each epoch trainer.extend(extensions.Evaluator(test_iter, model, device=device)) # Dump a computational graph from 'loss' variable at the first iteration # The "main" refers to the target link of the "main" optimizer. # TODO(niboshi): Temporarily disabled for chainerx. Fix it. if device.xp is not chainerx: trainer.extend(extensions.DumpGraph("main/loss")) # Take a snapshot for each specified epoch frequency = args.epoch if args.frequency == -1 else max(1, args.frequency) trainer.extend(extensions.snapshot(), trigger=(frequency, "epoch")) # Write a log of evaluation statistics for each epoch trainer.extend(extensions.LogReport()) # Save two plot images to the result dir if args.plot and extensions.PlotReport.available(): trainer.extend( extensions.PlotReport( ["main/loss", "validation/main/loss"], "epoch", file_name="loss.png" ) ) trainer.extend( extensions.PlotReport( ["main/accuracy", "validation/main/accuracy"], "epoch", file_name="accuracy.png", ) ) # Print selected entries of the log to stdout # Here "main" refers to the target link of the "main" optimizer again, and # "validation" refers to the default name of the Evaluator extension. # Entries other than 'epoch' are reported by the Classifier link, called by # either the updater or the evaluator. trainer.extend( extensions.PrintReport( [ "epoch", "main/loss", "validation/main/loss", "main/accuracy", "validation/main/accuracy", "elapsed_time", ] ) ) # Print a progress bar to stdout trainer.extend(extensions.ProgressBar()) if args.resume is not None: # Resume from a snapshot chainer.serializers.load_npz(args.resume, trainer) # Run the training trainer.run() if __name__ == "__main__": main()
/Users/dtaniwaki/.pyenv/versions/3.7.4/lib/python3.7/site-packages/chainer/_environment_check.py:41: UserWarning: Accelerate has been detected as a NumPy backend library. vecLib, which is a part of Accelerate, is known not to work correctly with Chainer. We recommend using other BLAS libraries such as OpenBLAS. For details of the issue, please see https://docs.chainer.org/en/stable/tips.html#mnist-example-does-not-converge-in-cpu-mode-on-mac-os-x. Please be aware that Mac OS X is not an officially supported OS. ''') # NOQA
Apache-2.0
doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb
edshee/seldon-core
Wrap model using s2i
!s2i build . seldonio/seldon-core-s2i-python37-ubi8:1.7.0-dev chainer-mnist:0.1 !docker run --name "mnist_predictor" -d --rm -p 5000:5000 chainer-mnist:0.1
b03f58f82ca07e25261be34b75be4a0ffbbfa1ad736d3866790682bf0d8202a3
Apache-2.0
doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb
edshee/seldon-core
Send some random features that conform to the contract
!seldon-core-tester contract.json 0.0.0.0 5000 -p !docker rm mnist_predictor --force
Error: No such container: mnist_predictor
Apache-2.0
doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb
edshee/seldon-core
Test using Minikube**Due to a [minikube/s2i issue](https://github.com/SeldonIO/seldon-core/issues/253) you will need [s2i >= 1.1.13](https://github.com/openshift/source-to-image/releases/tag/v1.1.13)**
!minikube start --memory 4096
😄 minikube v1.2.0 on darwin (amd64) 🔥 Creating virtualbox VM (CPUs=2, Memory=4096MB, Disk=20000MB) ... 🐳 Configuring environment for Kubernetes v1.15.0 on Docker 18.09.6 🚜 Pulling images ... 🚀 Launching Kubernetes ... ⌛ Verifying: apiserver proxy etcd scheduler controller dns 🏄 Done! kubectl is now configured to use "minikube"
Apache-2.0
doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb
edshee/seldon-core
Setup Seldon CoreUse the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlSetup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlAmbassador) and [Install Seldon Core](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlInstall-Seldon-Core). Instructions [also online](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html).
!eval $(minikube docker-env) && s2i build . seldonio/seldon-core-s2i-python37-ubi8:1.7.0-dev chainer-mnist:0.1 !kubectl create -f chainer_mnist_deployment.json !kubectl rollout status deploy/chainer-mnist-deployment-chainer-mnist-predictor-76478b2 !seldon-core-api-tester contract.json `minikube ip` `kubectl get svc ambassador -o jsonpath='{.spec.ports[0].nodePort}'` \ seldon-deployment-example --namespace default -p !minikube delete
_____no_output_____
Apache-2.0
doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb
edshee/seldon-core
验证集
val_probability = pd.DataFrame(val_probability) print(val_probability.shape) print(val_probability.head()) val_probability.drop(labels=[0],axis=1,inplace=True) val_probability.to_csv(r'../processed/val_probability_28212.csv',header=None,index=False)
_____no_output_____
MIT
src/NN_13100+15112.ipynb
VoyagerIII/DigiX--
测试集
import os model_file = r'../model/model28212_NN_' csr_testData0 = sparse.load_npz(r'../trainTestData/trainData13100.npz') csr_testData0.shape csr_testData1 = sparse.load_npz(r'../trainTestData/trainData15112.npz') csr_testData1.shape csr_testData = sparse.hstack((csr_testData0, csr_testData1),format='csr') del csr_trainData0,csr_trainData1 gc.collect() age_test = pd.read_csv(r'../data/age_test.csv',header=None,usecols=[0]) printTime() proflag = True model_Num = 0 for i in list(range(10)): model = load_model(model_file + str(i) + '.h5') if proflag==True: probability = model.predict(csr_testData,batch_size=1024,verbose=1) proflag = False else: probability += model.predict(csr_testData,batch_size=1024,verbose=1) model_Num += 1 print(model_Num) K.clear_session() del model printTime() model_Num probability /= model_Num age = np.argmax(probability,axis=1) age_test = pd.read_csv(r'../data/age_test.csv',header=None,usecols=[0]) age_test = age_test.values type(age_test) print(probability.shape) pro = np.column_stack((age_test,probability)) pro = pd.DataFrame(pro) pro.drop(labels=[0,1],axis=1,inplace=True) print(pro.shape) pro.to_csv(r'../processed/test_probability_28212.csv',index=False,header=False)
_____no_output_____
MIT
src/NN_13100+15112.ipynb
VoyagerIII/DigiX--
Make sure you have installed the pygfe package. You can simply call `pip install pygrpfe` in the terminal or call the magic command `!pip install pygrpfe` from within the notebook. If you are using the binder link, then `pygrpfe` is already installed. You can import the package directly.
import pygrpfe as gfe
_____no_output_____
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
A simple model of wage and participation\begin{align*}Y^*_{it} & = \alpha_i + \epsilon_{it} \\D_{it} &= 1\big[ u(\alpha_i) \geq c(D_{it-1}) + V_{it} \big] \\Y_{it} &= D_{it} Y^*_{it} \\\end{align*}where we use $$u(\alpha) = \frac{e^{(1-\gamma) \alpha } -1}{1-\gamma}$$and use as initial conditions $D_{i1} = 1\big[ u(\alpha_i) \geq c(1) + V_{i1} \big]$.
def dgp_simulate(ni,nt,gamma=2.0,eps_sd=1.0): """ simulates according to the model """ alpha = np.random.normal(size=(ni)) eps = np.random.normal(size=(ni,nt)) v = np.random.normal(size=(ni,nt)) # non-censored outcome W = alpha[:,ax] + eps*eps_sd # utility U = (np.exp( alpha * (1-gamma)) - 1)/(1-gamma) U = U - U.mean() # costs C1 = -1; C0=0; # binary decision Y = np.ones((ni,nt)) Y[:,0] = U.squeeze() > C1 + v[:,0] for t in range(1,nt): Y[:,t] = U > C1*Y[:,t-1] + C0*(1-Y[:,t-1]) + v[:,t] W = W * Y return(W,Y)
_____no_output_____
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
Estimating the modelWe show the steps to estimating the model. Later on, we will run a Monte-Carlo Simulation.We simulate from the DGP we have defined.
ni = 1000 nt = 50 Y,D = dgp_simulate(ni,nt,2.0)
_____no_output_____
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
Step 1: grouping observationsWe group individuals based on their outcomes. We consider as moments the average value of $Y$ and the average value of $D$. We give our gfe function the $t$ sepcific values so that it can compute the within individual variation. This is a measure used to pick the nubmer of groups.The `group` function chooses the number of groups based on the rule described in the paper.
# we create the moments # this has dimension ni x nt x nm M_itm = np.stack([Y,D],axis=2) # we use our sugar function to get the groups G_i,_ = gfe.group(M_itm) print("Number of groups = {:d}".format(G_i.max()))
Number of groups = 11
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
We can plot the grouping:
dd = pd.DataFrame({'Y':Y.mean(1),'G':G_i,'D':D.mean(1)}) plt.scatter(dd.Y,dd.D,c=dd.G*1.0) plt.show()
_____no_output_____
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
Step 2: Estimate the likelihood model with group specific parametersIn the model we proposed, this second step is a probit. We can then directly use python probit routine with group dummies.
ni,nt = D.shape # next we minimize using groups as FE dd = pd.DataFrame({ 'd': D[:,range(1,nt)].flatten(), 'dl':D[:,range(nt-1)].flatten(), 'gi':np.broadcast_to(G_i[:,ax], (ni,nt-1)).flatten()}) yv,Xv = patsy.dmatrices("d ~ 0 + dl + C(gi)", dd, return_type='matrix') mod = Probit(dd['d'], Xv) res = mod.fit(maxiter=2000,method='bfgs') print("Estimated cost parameters = {:.3f}".format(res.params[-1]))
Optimization terminated successfully. Current function value: 0.228267 Iterations: 87 Function evaluations: 88 Gradient evaluations: 88 Estimated cost parameters = 0.985
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
Step 2 (alternative implementation): Pytorch and auto-diffWe next write down a likelihood that we want to optimize. Instead of using the Python routine for the Probit, we make use of automatic differentiation from PyTorch. This makes it easy to modify the estimating model to accomodate for less standard likelihoods! We create a class which initializes the parameters in the `__init__` method and computes the loss in the `loss` method. We will see later how we can use this to define a fixed effect estimator.
class GrpProbit: # initialize parameters and data def __init__(self,D,G_i): # define parameters and tell PyTorch to keep track of gradients self.alpha = torch.tensor( np.ones(G_i.max()+1), requires_grad=True) self.cost = torch.tensor( np.random.normal(1), requires_grad=True) self.params = [self.alpha,self.cost] # predefine some components ni,nt = D.shape self.ni = ni self.G_i = G_i self.Dlag = torch.tensor(D[:,range(0,nt-1)]) self.Dout = torch.tensor(D[:,range(1,nt)]) self.N = torch.distributions.normal.Normal(0,1) # define our loss function def loss(self): Id = self.alpha[self.G_i].reshape(self.ni,1) + self.cost * self.Dlag lik_it = self.Dout * torch.log( torch.clamp( self.N.cdf( Id ), min=1e-7)) + \ (1-self.Dout)*torch.log( torch.clamp( self.N.cdf( -Id ), min=1e-7) ) return(- lik_it.mean()) # initialize the model with groups and estimate it model = GrpProbit(D,G_i) gfe.train(model) print("Estimated cost parameters = {:.3f}".format(model.params[1]))
Estimated cost parameters = 0.985
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
Use PyTorch to estimate Fixed Effect versionSince Pytorch makes use of efficient automatic differentiation, we can use it with many variables. This allows us to give each individual their own group, effectivily estimating a fixed-effect model.
model_fe = GrpProbit(D,np.arange(ni)) gfe.train(model_fe) print("Estimated cost parameters FE = {:.3f}".format(model_fe.params[1]))
Estimated cost parameters FE = 0.901
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
Monte-CarloWe finish with running a short Monte-Carlo exercise.
all = [] import itertools ll = list(itertools.product(range(50), [10,20,30,40])) for r, nt in tqdm.tqdm(ll): ni = 1000 gamma =2.0 Y,D = dgp_simulate(ni,nt,gamma) M_itm = np.stack([Y,D],axis=2) G_i,_ = blm2.group(M_itm,scale=True) model_fe = GrpProbit(D,np.arange(ni)) gfe.train(model_fe) model_gfe = GrpProbit(D,G_i) gfe.train(model_gfe) all.append({ 'c_fe' : model_fe.params[1].item(), 'c_gfe': model_gfe.params[1].item(), 'ni':ni, 'nt':nt, 'gamma':gamma, 'ng':G_i.max()+1}) df = pd.DataFrame(all) df2 = df.groupby(['ni','nt','gamma']).mean().reset_index() plt.plot(df2['nt'],df2['c_gfe'],label="gfe",color="orange") plt.plot(df2['nt'],df2['c_fe'],label="fe",color="red") plt.axhline(1.0,label="true",color="black",linestyle=":") plt.xlabel("T") plt.legend() plt.show() df.groupby(['ni','nt','gamma']).mean()
_____no_output_____
MIT
docs-src/notebooks/nb-gfe-example1.ipynb
tlamadon/pygfe
GDP and life expectancyRicher countries can afford to invest more on healthcare, on work and road safety, and other measures that reduce mortality. On the other hand, richer countries may have less healthy lifestyles. Is there any relation between the wealth of a country and the life expectancy of its inhabitants?The following analysis checks whether there is any correlation between the total gross domestic product (GDP) of a country in 2013 and the life expectancy of people born in that country in 2013. Getting the dataTwo datasets of the World Bank are considered. One dataset, available at http://data.worldbank.org/indicator/NY.GDP.MKTP.CD, lists the GDP of the world's countries in current US dollars, for various years. The use of a common currency allows us to compare GDP values across countries. The other dataset, available at http://data.worldbank.org/indicator/SP.DYN.LE00.IN, lists the life expectancy of the world's countries. The datasets were downloaded as CSV files in March 2016.
import warnings warnings.simplefilter('ignore', FutureWarning) import pandas as pd YEAR = 2018 GDP_INDICATOR = 'NY.GDP.MKTP.CD' gdpReset = pd.read_csv('WB 2018 GDP.csv') LIFE_INDICATOR = 'SP.DYN.LE00.IN_' lifeReset = pd.read_csv('WB 2018 LE.csv') lifeReset.head()
_____no_output_____
MIT
Ugwu Lilian WT-21-138/2018_LE_GDP.ipynb
ruthwaiharo/Week-5-Assessment
Cleaning the dataInspecting the data with `head()` and `tail()` shows that:1. the first 34 rows are aggregated data, for the Arab World, the Caribbean small states, and other country groups used by the World Bank;- GDP and life expectancy values are missing for some countries.The data is therefore cleaned by:1. removing the first 34 rows;- removing rows with unavailable values.
gdpCountries = gdpReset.dropna() lifeCountries = lifeReset.dropna()
_____no_output_____
MIT
Ugwu Lilian WT-21-138/2018_LE_GDP.ipynb
ruthwaiharo/Week-5-Assessment