proffreda

tflearn-titanic.py

Jan 29th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. from __future__ import print_function
  2.  
  3. import numpy as np
  4. import tflearn
  5.  
  6. # Download the Titanic dataset
  7. from tflearn.datasets import titanic
  8. titanic.download_dataset('titanic_dataset.csv')
  9.  
  10. # Load CSV file, indicate that the first column represents labels
  11. from tflearn.data_utils import load_csv
  12. data, labels = load_csv('titanic_dataset.csv', target_column=0,
  13. categorical_labels=True, n_classes=2)
  14.  
  15.  
  16. # Preprocessing function
  17. def preprocess(data, columns_to_ignore):
  18. # Sort by descending id and delete columns
  19. for id in sorted(columns_to_ignore, reverse=True):
  20. [r.pop(id) for r in data]
  21. for i in range(len(data)):
  22. # Converting 'sex' field to float (id is 1 after removing labels column)
  23. data[i][1] = 1. if data[i][1] == 'female' else 0.
  24. return np.array(data, dtype=np.float32)
  25.  
  26. # Ignore 'name' and 'ticket' columns (id 1 & 6 of data array)
  27. to_ignore=[1, 6]
  28.  
  29. # Preprocess data
  30. data = preprocess(data, to_ignore)
  31.  
  32. # Build neural network
  33. net = tflearn.input_data(shape=[None, 6])
  34. net = tflearn.fully_connected(net, 32)
  35. net = tflearn.fully_connected(net, 32)
  36. net = tflearn.fully_connected(net, 2, activation='softmax')
  37. net = tflearn.regression(net)
  38.  
  39. # Define model
  40. model = tflearn.DNN(net)
  41. # Start training (apply gradient descent algorithm)
  42. model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)
  43.  
  44. # Let's create some data for DiCaprio and Winslet
  45. dicaprio = [3, 'Jack Dawson', 'male', 19, 0, 0, 'N/A', 5.0000]
  46. winslet = [1, 'Rose DeWitt Bukater', 'female', 17, 1, 2, 'N/A', 100.0000]
  47. # Preprocess data
  48. dicaprio, winslet = preprocess([dicaprio, winslet], to_ignore)
  49. # Predict surviving chances (class 1 results)
  50. pred = model.predict([dicaprio, winslet])
  51. print("DiCaprio Surviving Rate:", pred[0][1])
  52. print("Winslet Surviving Rate:", pred[1][1])
Add Comment
Please, Sign In to add comment