Advertisement
Guest User

asdad

a guest
Feb 29th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.41 KB | None | 0 0
  1. var fs = require('fs');
  2. var readline = require('readline');
  3. var { google } = require("googleapis");
  4. var googleAuth = require('google-auth-library');
  5. var desobj = require('./decision-tree.js');
  6. var util = require('util')
  7. var basepath = '../json_files/';
  8.  
  9. // If modifying these scopes, delete your previously saved credentials
  10. // at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
  11. var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
  12. var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
  13. process.env.USERPROFILE) + '/.credentials/';
  14. var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
  15.  
  16. // Load client secrets from a local file.
  17. fs.readFile('client_id.json', function processClientSecrets(err, content) {
  18. if (err) {
  19. console.log('Error loading client secret file: ' + err);
  20. return;
  21. }
  22. // Authorize a client with the loaded credentials, then call the
  23. // Google Sheets API.
  24. authorize(JSON.parse(content), listMajors);
  25. });
  26.  
  27. /**
  28. * Create an OAuth2 client with the given credentials, and then execute the
  29. * given callback function.
  30. *
  31. * @param {Object} credentials The authorization client credentials.
  32. * @param {function} callback The callback to call with the authorized client.
  33. */
  34. function authorize(credentials, callback) {
  35. var clientSecret = credentials.installed.client_secret;
  36. var clientId = credentials.installed.client_id;
  37. var redirectUrl = credentials.installed.redirect_uris[0];
  38. var auth = new googleAuth();
  39. var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
  40.  
  41. // Check if we have previously stored a token.
  42. fs.readFile(TOKEN_PATH, function(err, token) {
  43. if (err) {
  44. getNewToken(oauth2Client, callback);
  45. } else {
  46. oauth2Client.credentials = JSON.parse(token);
  47. callback(oauth2Client);
  48. }
  49. });
  50. }
  51.  
  52. /**
  53. * Get and store new token after prompting for user authorization, and then
  54. * execute the given callback with the authorized OAuth2 client.
  55. *
  56. * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
  57. * @param {getEventsCallback} callback The callback to call with the authorized
  58. * client.
  59. */
  60. function getNewToken(oauth2Client, callback) {
  61. var authUrl = oauth2Client.generateAuthUrl({
  62. access_type: 'offline',
  63. scope: SCOPES
  64. });
  65. console.log('Authorize this app by visiting this url: ', authUrl);
  66. var rl = readline.createInterface({
  67. input: process.stdin,
  68. output: process.stdout
  69. });
  70. rl.question('Enter the code from that page here: ', function(code) {
  71. rl.close();
  72. oauth2Client.getToken(code, function(err, token) {
  73. if (err) {
  74. console.log('Error while trying to retrieve access token', err);
  75. return;
  76. }
  77. oauth2Client.credentials = token;
  78. storeToken(token);
  79. callback(oauth2Client);
  80. });
  81. });
  82. }
  83.  
  84. /**
  85. * Store token to disk be used in later program executions.
  86. *
  87. * @param {Object} token The token to store to disk.
  88. */
  89. function storeToken(token) {
  90. try {
  91. fs.mkdirSync(TOKEN_DIR);
  92. } catch (err) {
  93. if (err.code != 'EEXIST') {
  94. throw err;
  95. }
  96. }
  97. fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  98. console.log('Token stored to ' + TOKEN_PATH);
  99. }
  100.  
  101. /**
  102. * Print the names and majors of students in a sample spreadsheet:
  103. * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
  104. */
  105. var complete = 2;
  106. var sheet_columns;
  107. var sheet_rows;
  108.  
  109. function getConfigValues(auth, spreadsheetId,spreadsheetTab,callback) {
  110. var sheets = google.sheets('v4');
  111.  
  112. sheets.spreadsheets.values.get({
  113. auth: auth,
  114. spreadsheetId: spreadsheetId,
  115. range: spreadsheetTab + '!B1:B2'
  116. }, function(err, response) {
  117. if (err) {
  118. console.log('The API returned an error: ' + err);
  119. return;
  120. }
  121. var rows = response.values;
  122.  
  123. if (rows.length == 0) {
  124. console.log('No data found.');
  125. }
  126.  
  127. callback({
  128. columns: response.values[0],
  129. rows: response.values[1]
  130. });
  131. });
  132.  
  133. return ;
  134. }
  135.  
  136. function listMajors(auth) {
  137. var sheets = google.sheets('v4');
  138. var spreadsheetId = '1Hy3rmXSarcwD7E7N-bcoJzVx8yQ9CICtjtsV_rtekvk';
  139. // var spreadsheetTab = 'MarioAStar';
  140. // var spreadsheetTab = 'Shopping';
  141. // var spreadsheetTab = 'Lab';
  142. // var spreadsheetTab = 'Iris';
  143. // var spreadsheetTab = 'Wine';
  144. // var spreadsheetTab = 'Youtube';
  145. // var spreadsheetTab = 'xor';
  146. var spreadsheetTab = process.argv[2];
  147.  
  148. getConfigValues(auth, spreadsheetId,spreadsheetTab, function(config){
  149. console.log(config);
  150. sheets.spreadsheets.values.get({
  151. auth: auth,
  152. spreadsheetId: spreadsheetId,
  153. range: spreadsheetTab + '!' + config.columns
  154. }, function(err, response) {
  155. if (err) {
  156. console.log('The API returned an error: ' + err);
  157. return;
  158. }
  159. var rows = response.values;
  160. if (rows.length == 0) {
  161. console.log('No data found.');
  162. } else {
  163. complete--;
  164. sheet_columns = rows[0];
  165. start();
  166. }
  167. });
  168.  
  169. sheets.spreadsheets.values.get({
  170. auth: auth,
  171. spreadsheetId: spreadsheetId,
  172. range: spreadsheetTab + '!' + config.rows
  173. }, function(err, response) {
  174. if (err) {
  175. console.log('The API returned an error: ' + err);
  176. return;
  177. }
  178. var rows = response.values;
  179. if (rows.length == 0) {
  180. console.log('No data found.');
  181. } else {
  182. complete--;
  183. sheet_rows = rows;
  184. start();
  185. }
  186. });
  187. });
  188.  
  189. }
  190.  
  191. function isNumeric(num){
  192. return !isNaN(num)
  193. }
  194.  
  195. var start = function() {
  196. if(complete > 0) return;
  197.  
  198. var dt = desobj.dt;
  199.  
  200. // Training set
  201. var data = [];
  202.  
  203. for (var i = 0; i < sheet_rows.length; i++) {
  204. var row = sheet_rows[i];
  205. // Print columns A and E, which correspond to indices 0 and 4.
  206.  
  207. var obj = {};
  208. for (var e = 0; e < sheet_columns.length; e++) {
  209. var numeric = isNumeric(row[e]);
  210. if(numeric) {
  211. obj[sheet_columns[e].trim()] = parseFloat(row[e]);
  212. } else {
  213. obj[sheet_columns[e].trim()] = row[e];
  214. }
  215. }
  216. data.push(obj);
  217. }
  218.  
  219. fs.writeFile(basepath + "data.json", JSON.stringify(obj), function(err) {
  220. if(err) {
  221. return console.log(err);
  222. }
  223.  
  224. console.log("The file was saved!");
  225. });
  226.  
  227. // Configuration
  228. var config = {
  229. trainingSet: data,
  230. categoryAttr: 'action',
  231. ignoredAttributes: ['ignored']
  232. };
  233.  
  234. fs.writeFile(basepath + "config.json", JSON.stringify(config), function(err) {
  235. if(err) {
  236. return console.log(err);
  237. }
  238.  
  239. console.log("The file was saved!");
  240. });
  241.  
  242. // Building Decision Tree
  243. var decisionTree = new dt.DecisionTree(config);
  244.  
  245. // Building Random Forest
  246. var numberOfTrees = 3;
  247. var randomForest = new dt.RandomForest(config, numberOfTrees);
  248.  
  249. // Testing Decision Tree and Random Forest
  250. var comic = data[0];
  251.  
  252. fs.writeFile(basepath + "input.json", JSON.stringify(comic), function(err) {
  253. if(err) {
  254. return console.log(err);
  255. }
  256.  
  257. console.log("The file was saved!");
  258. });
  259.  
  260. var decisionTreePrediction = decisionTree.predict(comic);
  261. var randomForestPrediction = randomForest.predict(comic);
  262.  
  263. // Displaying predictions
  264. console.log(JSON.stringify(comic, null, 0));
  265. console.log(JSON.stringify(decisionTreePrediction, null, 0));
  266. console.log(JSON.stringify(randomForestPrediction, null, 0));
  267.  
  268. var tree = treeToHtml(decisionTree.root);
  269.  
  270. // Displaying Decision Tree
  271. console.log(util.inspect(tree, false, null));
  272.  
  273. fs.writeFile(basepath + "tree.json", JSON.stringify(tree), function(err) {
  274. if(err) {
  275. return console.log(err);
  276. }
  277.  
  278. console.log("The file was saved!");
  279. });
  280.  
  281. fs.writeFile(basepath + "tree.html", '<head><link rel="stylesheet" href="../base.css"></head><body><div class="weee" style=" width: 100%; height: 100%; overflow-x: scroll; overflow-y: scroll;"><div class="tree" id="displayTree" style=" width: 9000px; height: 9000px;"><div class="tree" id="displayTree">' + htmlCss(decisionTree.root) + '</div></div>', function(err) {
  282. if(err) {
  283. return console.log(err);
  284. }
  285.  
  286. console.log("The file was saved!");
  287. });
  288.  
  289. // Display error rating
  290. var errors = 0;
  291. var rtErrors = [0,0,0];
  292.  
  293. for (var i = data.length - 1; i >= 0; i--) {
  294. var actionToPredict = data[i].action;
  295. var sample = data[i];
  296. sample.action = "";
  297.  
  298. if(decisionTree.predict(sample) != actionToPredict) {
  299. errors++;
  300. }
  301.  
  302. if(randomForest['trees'][0].predict(sample) != actionToPredict) rtErrors[0]++;
  303. if(randomForest['trees'][1].predict(sample) != actionToPredict) rtErrors[1]++;
  304. if(randomForest['trees'][2].predict(sample) != actionToPredict) rtErrors[2]++;
  305. }
  306.  
  307. console.log('Error Rate:' + ((errors/data.length)*100) + '%');
  308.  
  309. var minI = {value: Infinity, index: null};
  310. for (var i = 0; i < rtErrors.length; i++)
  311. if(rtErrors[i] < minI.value)
  312. minI = {value: rtErrors[i], index: i};
  313.  
  314. console.log('RError Rate:' + ((rtErrors[minI.index]/data.length)*100) + '%');
  315.  
  316. fs.writeFile(basepath + "rtree.html", '<head><link rel="stylesheet" href="../base.css"></head><body><div class="weee" style=" width: 100%; height: 100%; overflow-x: scroll; overflow-y: scroll;"><div class="tree" id="displayTree" style=" width: 9000px; height: 9000px;"><div class="tree" id="displayTree">' + htmlCss(randomForest.trees[minI.index].root) + '</div></div>', function(err) {
  317. if(err) {
  318. return console.log(err);
  319. }
  320.  
  321. console.log("The file was saved!");
  322. });
  323.  
  324. // Recursive (DFS) function for displaying inner structure of decision tree
  325. function treeToHtml(tree) {
  326. // only leafs containing category
  327. if (tree.category) {
  328. return [' "', tree.category, '"'].join('');
  329. }
  330.  
  331. var myBranch = {};
  332. var branchName = ['"',tree.attribute,' ',tree.predicateName,' ',tree.pivot,' ?"'].join('');
  333.  
  334. myBranch[branchName] = {
  335. 'yes': treeToHtml(tree.match),
  336. 'no': treeToHtml(tree.notMatch)
  337. };
  338.  
  339. return myBranch;
  340. }
  341.  
  342. // Recursive (DFS) function for displaying inner structure of decision tree
  343. function htmlCss(tree) {
  344. // only leafs containing category
  345. if (tree.category) {
  346. return ['<ul>',
  347. '<li>',
  348. '<a href="#">',
  349. '<b>', tree.category, '</b>',
  350. '</a>',
  351. '</li>',
  352. '</ul>'].join('');
  353. }
  354.  
  355. return ['<ul>',
  356. '<li>',
  357. '<a href="#">',
  358. '<b>', tree.attribute, ' ', tree.predicateName, ' ', tree.pivot, ' ?</b>',
  359. '</a>',
  360. '<ul>',
  361. '<li>',
  362. '<a href="#">yes', '(', tree.matchedCount, ')', '</a>',
  363. htmlCss(tree.match),
  364. '</li>',
  365. '<li>',
  366. '<a href="#">no', '(', tree.notMatchedCount, ')', '</a>',
  367. htmlCss(tree.notMatch),
  368. '</li>',
  369. '</ul>',
  370. '</li>',
  371. '</ul>'].join('');
  372. }
  373.  
  374. var id = 0;
  375. var stack = [];
  376.  
  377. var treeParse = function (tree, id) {
  378. for(var i in tree) {
  379. var output = {
  380. id: id,
  381. question: i,
  382. yes: typeof(tree[i]['yes']) == "object" ? treeParse(tree[i]['yes'], id+1) : tree[i]['yes'],
  383. no: typeof(tree[i]['no']) == "object" ? treeParse(tree[i]['no'], id+1) : tree[i]['no']
  384. };
  385.  
  386. // console.log(output);
  387.  
  388. stack.push(output);
  389. }
  390. return 'goto id: ' + id;
  391. }
  392.  
  393. treeParse(tree, 1);
  394.  
  395. fs.writeFile(basepath + "stack.json", JSON.stringify(stack, null, 2), function(err) {
  396. if(err) {
  397. return console.log(err);
  398. }
  399.  
  400. console.log("The file was saved!");
  401. });
  402.  
  403. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement