# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/soumilbaldota/TensorFlow_Notebooks_101/blob/main/Titanic_Linear_Regression.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="cgaLYoPvCdbG"
# !pip install -q sklearn

# + id="yUIUB-RQOyL1"
# %tensorflow_version 2.x
from __future__ import absolute_import,division,print_function,unicode_literals
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import clear_output
from six.moves import urllib
import tensorflow.compat.v2.feature_column as fc
import tensorflow as tf


# + id="WdcAIeQY3ckF"
dftrain=pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv")
dftest=pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/eval.csv")
y_train=dftrain.pop("survived")
y_test=dftest.pop("survived")

# + id="4w42IQRrFaPI" outputId="147bb70c-161b-4f25-8048-5b6fd10162a2" colab={"base_uri": "https://localhost:8080/", "height": 195}
dftrain.head()

# + id="2FReL0njFmPg" outputId="4d69f391-b611-4da9-d5bf-bcb39ce28cd0" colab={"base_uri": "https://localhost:8080/", "height": 286}
dftrain.info()

# + id="w8CDLOYk9JZ5" outputId="f6616055-d535-4776-83a5-010c206090cc" colab={"base_uri": "https://localhost:8080/", "height": 282}
dftrain.age.hist(bins=20)

# + id="Z_rKId2R9Y4E" outputId="80c96680-4faf-4507-a3cd-05c98539108b" colab={"base_uri": "https://localhost:8080/", "height": 282}
dftrain["sex"].value_counts().plot(kind='barh')

# + id="5rIMksdl9lyL" outputId="3861c702-1f0c-429d-d5c1-95b8215051e0" colab={"base_uri": "https://localhost:8080/", "height": 443}

dftrain["class"].value_counts().plot(kind='barh')
dftrain.head()

# + id="erY5_20UGOqn" outputId="7a35fdbb-62a8-437d-98ff-50f969c2d4d8" colab={"base_uri": "https://localhost:8080/", "height": 390}
male_survived = 0
female_survived = 0
g = list(y_train)
for i in range(len(g)):
  if g[i] == 1:
    if dftrain['sex'][i] =='male':
      male_survived +=1
    else:
      female_survived+=1
print(male_survived,female_survived)
l=[male_survived,female_survived]
labels = ['male survived','female survived']
fig = plt.figure(figsize=(5,5))
plt.bar(labels, l, color ='orange',  
        width = 0.12) 
  
plt.xlabel("\n\nClasses") 
plt.ylabel("Frequency") 
plt.title("Yo") 
plt.show()

# + id="DhlWNpft-Dwz" outputId="93cba7ad-bbf6-4914-81a3-80b1845788a6" colab={"base_uri": "https://localhost:8080/", "height": 34}
dftest.shape

# + id="6Qe2vucV-a8t"
CATEGORRICAL_COLUMNS=['sex','n_siblings_spouses','parch','class','deck','embark_town','alone']
NUMERICAL_COLUMNS=['age','fare']
feature_columns=[]
for feature_name in CATEGORRICAL_COLUMNS:
  vocabulary=dftrain[feature_name].unique()
  feature_columns.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name,vocabulary))

for feature_name in NUMERICAL_COLUMNS:
  feature_columns.append(tf.feature_column.numeric_column(feature_name,dtype=tf.float32))


# + id="_oubA7JpJsLi"
def make_input_fn(data_df,label_df,num_epochs=10,shuffle=True,batch_size=32):
  def input_fun():
    ds=tf.data.Dataset.from_tensor_slices((dict(data_df),label_df))
    if shuffle :
      ds=ds.shuffle(1000)
    ds=ds.batch(batch_size).repeat(num_epochs)
    return ds
  return input_fun

train_input_fn=make_input_fn(dftrain,y_train)
eval_input_function = make_input_fn(dftest,y_test,num_epochs=1,shuffle=False)

# + id="SGiGO1GOMM31" outputId="b2a35690-1c10-40c2-8556-c3fc0c70b4ec" colab={"base_uri": "https://localhost:8080/", "height": 70}
linear_est=tf.estimator.LinearClassifier(feature_columns=feature_columns)
linear_est.train(train_input_fn)

result=linear_est.evaluate(eval_input_function)
clear_output()
print(result['accuracy'])
print(result)

StarcoderdataJupyterScriptsDedupFiltered