path
stringlengths
13
17
screenshot_names
sequencelengths
1
873
code
stringlengths
0
40.4k
cell_type
stringclasses
1 value
2040512/cell_10
[ "text_html_output_1.png" ]
from sklearn import preprocessing import pandas as pd daily_Data = pd.read_csv('../input/KaggleV2-May-2016.csv') from sklearn import preprocessing le = preprocessing.LabelEncoder() le.fit(daily_Data['Gender']) daily_Data['Gender'] = le.transform(daily_Data['Gender']) le.fit(daily_Data['No-show']) daily_Data['No-show'] = le.transform(daily_Data['No-show']) le.fit(daily_Data['Neighbourhood']) daily_Data['Neighbourhood'] = le.transform(daily_Data['Neighbourhood']) daily_Data['AppointmentDay'].head()
code
2040512/cell_5
[ "text_plain_output_1.png" ]
import pandas as pd daily_Data = pd.read_csv('../input/KaggleV2-May-2016.csv') print('Age:', sorted(daily_Data.Age.unique())) print('Gender:', daily_Data.Gender.unique()) print('Neighbourhood', daily_Data.Neighbourhood.unique()) print('Scholarship:', daily_Data.Scholarship.unique()) print('Hipertension:', daily_Data.Hipertension.unique()) print('Diabetes:', daily_Data.Diabetes.unique()) print('Alcoholism:', daily_Data.Alcoholism.unique()) print('Handcap:', daily_Data.Handcap.unique()) print('SMS_received:', daily_Data.SMS_received.unique())
code
89132381/cell_13
[ "text_plain_output_1.png" ]
import pandas as pd df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') df.dtypes feature_list = [feature for feature in df.columns] discrete_feature = [feature for feature in feature_list if len(df[feature].unique()) < 25] print('Discrete Variables Count: {}'.format(len(discrete_feature))) print('Discrete features are ', discrete_feature) cont_feature = [feature for feature in feature_list if len(df[feature].unique()) > 25] print('Continuous Variables Count: {}'.format(len(cont_feature))) print('Continuous features are ', cont_feature)
code
89132381/cell_9
[ "image_output_1.png" ]
import pandas as pd df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') df.describe()
code
89132381/cell_2
[ "text_plain_output_1.png", "image_output_1.png" ]
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import os for dirname, _, filenames in os.walk('/kaggle/input/'): for filename in filenames: print(os.path.join(dirname, filename)) print('Setup complete, packages loaded')
code
89132381/cell_11
[ "text_plain_output_1.png" ]
import pandas as pd df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') df.dtypes
code
89132381/cell_7
[ "image_output_1.png" ]
import pandas as pd df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') print(df.isnull().any())
code
89132381/cell_15
[ "text_plain_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') df.dtypes feature_list = [feature for feature in df.columns] fig, ax = plt.subplots(figsize=(10,8)) sns.heatmap(df.corr(),annot=True,ax=ax,cmap="Greys") fig = plt.figure(figsize=(18, 15)) gs = fig.add_gridspec(3, 3) gs.update(wspace=0.5, hspace=0.25) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, 0]) ax4 = fig.add_subplot(gs[1, 1]) ax5 = fig.add_subplot(gs[1, 2]) ax6 = fig.add_subplot(gs[2, 0]) ax7 = fig.add_subplot(gs[2, 1]) ax8 = fig.add_subplot(gs[2, 2]) background_color = '#ffffff' color_palette = ['#397367', '#63CCCA', '#5DA399', '#42858C', '#35393C'] fig.patch.set_facecolor(background_color) ax0.set_facecolor(background_color) ax1.set_facecolor(background_color) ax2.set_facecolor(background_color) ax3.set_facecolor(background_color) ax4.set_facecolor(background_color) ax5.set_facecolor(background_color) ax6.set_facecolor(background_color) ax7.set_facecolor(background_color) ax8.set_facecolor(background_color) ax0.spines['bottom'].set_visible(False) ax0.spines['left'].set_visible(False) ax0.spines['top'].set_visible(False) ax0.spines['right'].set_visible(False) ax0.tick_params(left=False, bottom=False) ax0.set_xticklabels([]) ax0.set_yticklabels([]) ax0.text(0.5, 0.5, 'Count plot for various\n categorical features\n_________________', horizontalalignment='center', verticalalignment='center', fontsize=18, fontweight='bold', fontfamily='serif', color='#000000') ax1.text(0.3, 750, 'Sex', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.countplot(ax=ax1, data=df, x='sex', palette=color_palette) ax1.set_xlabel('') ax1.set_ylabel('') ax2.text(0.3, 730, 'Exang', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.countplot(ax=ax2, data=df, x='exang', palette=color_palette) ax2.set_xlabel('') ax2.set_ylabel('') ax3.text(1.5, 630, 'Ca', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax3.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.countplot(ax=ax3, data=df, x='ca', palette=color_palette) ax3.set_xlabel('') ax3.set_ylabel('') ax4.text(1.5, 530, 'Cp', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax4.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.countplot(ax=ax4, data=df, x='cp', palette=color_palette) ax4.set_xlabel('') ax4.set_ylabel('') ax5.text(0.5, 900, 'Fbs', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax5.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.countplot(ax=ax5, data=df, x='fbs', palette=color_palette) ax5.set_xlabel('') ax5.set_ylabel('') ax6.text(0.75, 550, 'Restecg', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax6.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.countplot(ax=ax6, data=df, x='restecg', palette=color_palette) ax6.set_xlabel('') ax6.set_ylabel('') ax7.text(0.85, 520, 'Slope', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax7.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.countplot(ax=ax7, data=df, x='slope', palette=color_palette) ax7.set_xlabel('') ax7.set_ylabel('') ax8.text(1.2, 570, 'Thal', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax8.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.countplot(ax=ax8, data=df, x='thal', palette=color_palette) ax8.set_xlabel('') ax8.set_ylabel('') for s in ['top', 'right', 'left']: ax1.spines[s].set_visible(False) ax2.spines[s].set_visible(False) ax3.spines[s].set_visible(False) ax4.spines[s].set_visible(False) ax5.spines[s].set_visible(False) ax6.spines[s].set_visible(False) ax7.spines[s].set_visible(False) ax8.spines[s].set_visible(False)
code
89132381/cell_16
[ "text_plain_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') df.dtypes feature_list = [feature for feature in df.columns] fig, ax = plt.subplots(figsize=(10,8)) sns.heatmap(df.corr(),annot=True,ax=ax,cmap="Greys") fig = plt.figure(figsize=(18,15)) gs = fig.add_gridspec(3,3) gs.update(wspace=0.5, hspace=0.25) ax0 = fig.add_subplot(gs[0,0]) ax1 = fig.add_subplot(gs[0,1]) ax2 = fig.add_subplot(gs[0,2]) ax3 = fig.add_subplot(gs[1,0]) ax4 = fig.add_subplot(gs[1,1]) ax5 = fig.add_subplot(gs[1,2]) ax6 = fig.add_subplot(gs[2,0]) ax7 = fig.add_subplot(gs[2,1]) ax8 = fig.add_subplot(gs[2,2]) background_color = "#ffffff" color_palette = ["#397367","#63CCCA","#5DA399","#42858C","#35393C"] fig.patch.set_facecolor(background_color) ax0.set_facecolor(background_color) ax1.set_facecolor(background_color) ax2.set_facecolor(background_color) ax3.set_facecolor(background_color) ax4.set_facecolor(background_color) ax5.set_facecolor(background_color) ax6.set_facecolor(background_color) ax7.set_facecolor(background_color) ax8.set_facecolor(background_color) # Title of the plot ax0.spines["bottom"].set_visible(False) ax0.spines["left"].set_visible(False) ax0.spines["top"].set_visible(False) ax0.spines["right"].set_visible(False) ax0.tick_params(left=False, bottom=False) ax0.set_xticklabels([]) ax0.set_yticklabels([]) ax0.text(0.5,0.5, 'Count plot for various\n categorical features\n_________________', horizontalalignment='center', verticalalignment='center', fontsize=18, fontweight='bold', fontfamily='serif', color="#000000") # Sex count ax1.text(0.3, 750, 'Sex', fontsize=14, fontweight='bold', fontfamily='serif', color="#000000") ax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5)) sns.countplot(ax=ax1,data=df,x='sex',palette=color_palette) ax1.set_xlabel("") ax1.set_ylabel("") # Exng count ax2.text(0.3, 730, 'Exang', fontsize=14, fontweight='bold', fontfamily='serif', color="#000000") ax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5)) sns.countplot(ax=ax2,data=df,x='exang',palette=color_palette) ax2.set_xlabel("") ax2.set_ylabel("") # Caa count ax3.text(1.5, 630, 'Ca', fontsize=14, fontweight='bold', fontfamily='serif', color="#000000") ax3.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5)) sns.countplot(ax=ax3,data=df,x='ca',palette=color_palette) ax3.set_xlabel("") ax3.set_ylabel("") # Cp count ax4.text(1.5, 530, 'Cp', fontsize=14, fontweight='bold', fontfamily='serif', color="#000000") ax4.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5)) sns.countplot(ax=ax4,data=df,x='cp',palette=color_palette) ax4.set_xlabel("") ax4.set_ylabel("") # Fbs count ax5.text(0.5, 900, 'Fbs', fontsize=14, fontweight='bold', fontfamily='serif', color="#000000") ax5.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5)) sns.countplot(ax=ax5,data=df,x='fbs',palette=color_palette) ax5.set_xlabel("") ax5.set_ylabel("") # Restecg count ax6.text(0.75, 550, 'Restecg', fontsize=14, fontweight='bold', fontfamily='serif', color="#000000") ax6.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5)) sns.countplot(ax=ax6,data=df,x='restecg',palette=color_palette) ax6.set_xlabel("") ax6.set_ylabel("") # Slp count ax7.text(0.85, 520, 'Slope', fontsize=14, fontweight='bold', fontfamily='serif', color="#000000") ax7.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5)) sns.countplot(ax=ax7,data=df,x='slope',palette=color_palette) ax7.set_xlabel("") ax7.set_ylabel("") # Thall count ax8.text(1.2, 570, 'Thal', fontsize=14, fontweight='bold', fontfamily='serif', color="#000000") ax8.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1,5)) sns.countplot(ax=ax8,data=df,x='thal',palette=color_palette) ax8.set_xlabel("") ax8.set_ylabel("") for s in ["top","right","left"]: ax1.spines[s].set_visible(False) ax2.spines[s].set_visible(False) ax3.spines[s].set_visible(False) ax4.spines[s].set_visible(False) ax5.spines[s].set_visible(False) ax6.spines[s].set_visible(False) ax7.spines[s].set_visible(False) ax8.spines[s].set_visible(False) fig = plt.figure(figsize=(18, 16)) gs = fig.add_gridspec(2, 3) gs.update(wspace=0.3, hspace=0.15) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax2 = fig.add_subplot(gs[0, 2]) ax3 = fig.add_subplot(gs[1, 0]) ax4 = fig.add_subplot(gs[1, 1]) ax5 = fig.add_subplot(gs[1, 2]) background_color = '#ffffff' color_palette = ['#397367', '#63CCCA', '#5DA399', '#42858C', '#35393C'] fig.patch.set_facecolor(background_color) ax0.set_facecolor(background_color) ax1.set_facecolor(background_color) ax2.set_facecolor(background_color) ax3.set_facecolor(background_color) ax4.set_facecolor(background_color) ax5.set_facecolor(background_color) ax0.spines['bottom'].set_visible(False) ax0.spines['left'].set_visible(False) ax0.spines['top'].set_visible(False) ax0.spines['right'].set_visible(False) ax0.tick_params(left=False, bottom=False) ax0.set_xticklabels([]) ax0.set_yticklabels([]) ax0.text(0.5, 0.5, 'Box plot for various\n continuous features\n_________________', horizontalalignment='center', verticalalignment='center', fontsize=18, fontweight='bold', fontfamily='serif', color='#000000') ax1.text(-0.05, 81, 'Age', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax1.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.boxenplot(ax=ax1, y=df['age'], palette=['#397367'], width=0.6) ax1.set_xlabel('') ax1.set_ylabel('') ax2.text(-0.05, 208, 'Trestbps', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax2.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.boxenplot(ax=ax2, y=df['trestbps'], palette=['#63CCCA'], width=0.6) ax2.set_xlabel('') ax2.set_ylabel('') ax3.text(-0.05, 600, 'Chol', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax3.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.boxenplot(ax=ax3, y=df['chol'], palette=['#5DA399'], width=0.6) ax3.set_xlabel('') ax3.set_ylabel('') ax4.text(-0.09, 210, 'Thalach', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax4.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.boxenplot(ax=ax4, y=df['thalach'], palette=['#42858C'], width=0.6) ax4.set_xlabel('') ax4.set_ylabel('') ax5.text(-0.1, 6.6, 'Oldpeak', fontsize=14, fontweight='bold', fontfamily='serif', color='#000000') ax5.grid(color='#000000', linestyle=':', axis='y', zorder=0, dashes=(1, 5)) sns.boxenplot(ax=ax5, y=df['oldpeak'], palette=['#35393C'], width=0.6) ax5.set_xlabel('') ax5.set_ylabel('') for s in ['top', 'right', 'left']: ax1.spines[s].set_visible(False) ax2.spines[s].set_visible(False) ax3.spines[s].set_visible(False) ax4.spines[s].set_visible(False) ax5.spines[s].set_visible(False)
code
89132381/cell_14
[ "text_html_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') df.dtypes feature_list = [feature for feature in df.columns] fig, ax = plt.subplots(figsize=(10, 8)) sns.heatmap(df.corr(), annot=True, ax=ax, cmap='Greys')
code
89132381/cell_12
[ "text_plain_output_1.png" ]
import pandas as pd df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') df.dtypes feature_list = [feature for feature in df.columns] print('There are', len(feature_list), 'features found in the data')
code
89132381/cell_5
[ "image_output_1.png" ]
import pandas as pd df = pd.read_csv('/kaggle/input/heart-disease-dataset/heart.csv') print('Dataset has', df.shape[0], 'entries and', df.shape[1], 'variables')
code
326886/cell_4
[ "text_plain_output_1.png" ]
import matplotlib.pyplot as plt import numpy as np import pandas as pd import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter import string from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression pd.options.mode.chained_assignment = None def get_title(name): name = name.split(',')[1] name = name.split('.')[0] return name.strip() def get_title_grouped(name): title = get_title(name) if title in ['Rev', 'Dr', 'Col', 'Major', 'the Countess', 'Sir', 'Lady', 'Jonkheer', 'Capt', 'Dona', 'Don']: title = 'Rare' elif title in ['Ms', 'Mlle']: title = 'Miss' elif title == 'Mme': title = 'Mrs' return title def get_deck(cabin): if isinstance(cabin, str): if cabin[0] == 'T': return np.nan return cabin[0] return cabin train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') full = pd.concat([train, test]) # feature engineering described in previous notebooks full['Embarked'].fillna('C', inplace=True) full['Fare'].fillna(8.05, inplace=True) full['Title'] = full['Name'].apply(get_title_grouped) full['Deck'] = full['Cabin'].apply(get_deck) full['Family size'] = full['Parch'] + full['SibSp'] ticket_nums = [int(n.split()[-1]) for n in full['Ticket'].values if n.split()[-1].isdigit()] plt.hist(ticket_nums, 50) plt.xlabel('Ticket number') plt.ylabel('Count') plt.show()
code
326886/cell_20
[ "text_plain_output_1.png" ]
from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LinearRegression from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt import numpy as np import pandas as pd import string import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter import string from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression pd.options.mode.chained_assignment = None def get_title(name): name = name.split(',')[1] name = name.split('.')[0] return name.strip() def get_title_grouped(name): title = get_title(name) if title in ['Rev', 'Dr', 'Col', 'Major', 'the Countess', 'Sir', 'Lady', 'Jonkheer', 'Capt', 'Dona', 'Don']: title = 'Rare' elif title in ['Ms', 'Mlle']: title = 'Miss' elif title == 'Mme': title = 'Mrs' return title def get_deck(cabin): if isinstance(cabin, str): if cabin[0] == 'T': return np.nan return cabin[0] return cabin train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') full = pd.concat([train, test]) # feature engineering described in previous notebooks full['Embarked'].fillna('C', inplace=True) full['Fare'].fillna(8.05, inplace=True) full['Title'] = full['Name'].apply(get_title_grouped) full['Deck'] = full['Cabin'].apply(get_deck) full['Family size'] = full['Parch'] + full['SibSp'] ticket_nums = [int(n.split()[-1]) for n in full['Ticket'].values if n.split()[-1].isdigit()] ticket_nums = [num for num in ticket_nums if num < 2000000] def get_ticket_num(ticket): ticket_num = ticket.split() ticket_num = ''.join((char for char in ticket_num[-1].strip() if char not in string.punctuation)) if not ticket_num.isdigit(): return np.nan return int(ticket_num) full['Ticket number'] = full['Ticket'].apply(get_ticket_num) full['Ticket number'].fillna(np.nanmedian(full['Ticket number'].values), inplace=True) full.drop(['Name', 'Ticket', 'Cabin', 'Parch', 'SibSp'], axis=1, inplace=True) encoders = {} to_encode = ['Embarked', 'Sex', 'Title'] for col in to_encode: encoders[col] = LabelEncoder() encoders[col].fit(full[col]) full[col] = encoders[col].transform(full[col]) age_train = full[full['Age'].notnull()] age_predict = full[~full['Age'].notnull()] lr = LinearRegression() lr.fit(age_train.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1), age_train['Age']) predicted_ages = lr.predict(age_predict.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1)) age_predict['Age'] = [max(0.0, age) for age in predicted_ages] full = pd.concat([age_train, age_predict]).sort_values('PassengerId') ages = age_train.Age ages.plot.kde(label='Original') ages = full.Age ages.plot.kde(label='With predicted missing values') train = full[full.PassengerId < 892] test = full[full.PassengerId >= 892] rf = RandomForestClassifier(n_estimators=100, oob_score=True) rf.fit(train.drop(['Survived', 'PassengerId'], axis=1), train['Survived']) rf.score(train.drop(['Survived', 'PassengerId'], axis=1), train['Survived'])
code
326886/cell_6
[ "image_output_1.png" ]
import matplotlib.pyplot as plt import numpy as np import pandas as pd import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter import string from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression pd.options.mode.chained_assignment = None def get_title(name): name = name.split(',')[1] name = name.split('.')[0] return name.strip() def get_title_grouped(name): title = get_title(name) if title in ['Rev', 'Dr', 'Col', 'Major', 'the Countess', 'Sir', 'Lady', 'Jonkheer', 'Capt', 'Dona', 'Don']: title = 'Rare' elif title in ['Ms', 'Mlle']: title = 'Miss' elif title == 'Mme': title = 'Mrs' return title def get_deck(cabin): if isinstance(cabin, str): if cabin[0] == 'T': return np.nan return cabin[0] return cabin train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') full = pd.concat([train, test]) # feature engineering described in previous notebooks full['Embarked'].fillna('C', inplace=True) full['Fare'].fillna(8.05, inplace=True) full['Title'] = full['Name'].apply(get_title_grouped) full['Deck'] = full['Cabin'].apply(get_deck) full['Family size'] = full['Parch'] + full['SibSp'] ticket_nums = [int(n.split()[-1]) for n in full['Ticket'].values if n.split()[-1].isdigit()] ticket_nums = [num for num in ticket_nums if num < 2000000] plt.hist(ticket_nums, 50) plt.xlabel('Ticket number') plt.ylabel('Count') plt.show()
code
326886/cell_16
[ "image_output_1.png" ]
from sklearn.linear_model import LinearRegression from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt import numpy as np import pandas as pd import string import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter import string from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression pd.options.mode.chained_assignment = None def get_title(name): name = name.split(',')[1] name = name.split('.')[0] return name.strip() def get_title_grouped(name): title = get_title(name) if title in ['Rev', 'Dr', 'Col', 'Major', 'the Countess', 'Sir', 'Lady', 'Jonkheer', 'Capt', 'Dona', 'Don']: title = 'Rare' elif title in ['Ms', 'Mlle']: title = 'Miss' elif title == 'Mme': title = 'Mrs' return title def get_deck(cabin): if isinstance(cabin, str): if cabin[0] == 'T': return np.nan return cabin[0] return cabin train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') full = pd.concat([train, test]) # feature engineering described in previous notebooks full['Embarked'].fillna('C', inplace=True) full['Fare'].fillna(8.05, inplace=True) full['Title'] = full['Name'].apply(get_title_grouped) full['Deck'] = full['Cabin'].apply(get_deck) full['Family size'] = full['Parch'] + full['SibSp'] ticket_nums = [int(n.split()[-1]) for n in full['Ticket'].values if n.split()[-1].isdigit()] ticket_nums = [num for num in ticket_nums if num < 2000000] def get_ticket_num(ticket): ticket_num = ticket.split() ticket_num = ''.join((char for char in ticket_num[-1].strip() if char not in string.punctuation)) if not ticket_num.isdigit(): return np.nan return int(ticket_num) full['Ticket number'] = full['Ticket'].apply(get_ticket_num) full['Ticket number'].fillna(np.nanmedian(full['Ticket number'].values), inplace=True) full.drop(['Name', 'Ticket', 'Cabin', 'Parch', 'SibSp'], axis=1, inplace=True) encoders = {} to_encode = ['Embarked', 'Sex', 'Title'] for col in to_encode: encoders[col] = LabelEncoder() encoders[col].fit(full[col]) full[col] = encoders[col].transform(full[col]) age_train = full[full['Age'].notnull()] age_predict = full[~full['Age'].notnull()] lr = LinearRegression() lr.fit(age_train.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1), age_train['Age']) predicted_ages = lr.predict(age_predict.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1)) age_predict['Age'] = [max(0.0, age) for age in predicted_ages] full = pd.concat([age_train, age_predict]).sort_values('PassengerId') ages = age_train.Age ages.plot.kde(label='Original') ages = full.Age ages.plot.kde(label='With predicted missing values') full_with_deck = full[full['Deck'].notnull()] full_without_deck = full[~full['Deck'].notnull()] full_with_deck_means, full_without_deck_means = ([], []) for col in full_with_deck: if col not in ['Deck', 'PassengerId']: sum_means = np.nanmean(full_with_deck[col].values) + np.nanmean(full_without_deck[col].values) full_with_deck_means.append(np.nanmean(full_with_deck[col].values) / sum_means) full_without_deck_means.append(np.nanmean(full_without_deck[col].values) / sum_means) bar_width = 0.35 opacity = 0.4 x_index = np.arange(len(full_with_deck_means)) plt.bar(x_index, full_with_deck_means, bar_width, alpha=opacity, color='b', label='With deck value') plt.bar(x_index + bar_width, full_without_deck_means, bar_width, alpha=opacity, color='r', label='Missing deck value') plt.legend(loc='upper center', prop={'size': 9}) plt.ylabel('Ratio of means') plt.xticks(x_index + bar_width, [col for col in full_with_deck if col not in ['PassengerId', 'Deck']]) plt.show()
code
326886/cell_24
[ "text_plain_output_1.png" ]
from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LinearRegression from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt import numpy as np import pandas as pd import string import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter import string from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression pd.options.mode.chained_assignment = None def get_title(name): name = name.split(',')[1] name = name.split('.')[0] return name.strip() def get_title_grouped(name): title = get_title(name) if title in ['Rev', 'Dr', 'Col', 'Major', 'the Countess', 'Sir', 'Lady', 'Jonkheer', 'Capt', 'Dona', 'Don']: title = 'Rare' elif title in ['Ms', 'Mlle']: title = 'Miss' elif title == 'Mme': title = 'Mrs' return title def get_deck(cabin): if isinstance(cabin, str): if cabin[0] == 'T': return np.nan return cabin[0] return cabin train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') full = pd.concat([train, test]) # feature engineering described in previous notebooks full['Embarked'].fillna('C', inplace=True) full['Fare'].fillna(8.05, inplace=True) full['Title'] = full['Name'].apply(get_title_grouped) full['Deck'] = full['Cabin'].apply(get_deck) full['Family size'] = full['Parch'] + full['SibSp'] ticket_nums = [int(n.split()[-1]) for n in full['Ticket'].values if n.split()[-1].isdigit()] ticket_nums = [num for num in ticket_nums if num < 2000000] def get_ticket_num(ticket): ticket_num = ticket.split() ticket_num = ''.join((char for char in ticket_num[-1].strip() if char not in string.punctuation)) if not ticket_num.isdigit(): return np.nan return int(ticket_num) full['Ticket number'] = full['Ticket'].apply(get_ticket_num) full['Ticket number'].fillna(np.nanmedian(full['Ticket number'].values), inplace=True) full.drop(['Name', 'Ticket', 'Cabin', 'Parch', 'SibSp'], axis=1, inplace=True) encoders = {} to_encode = ['Embarked', 'Sex', 'Title'] for col in to_encode: encoders[col] = LabelEncoder() encoders[col].fit(full[col]) full[col] = encoders[col].transform(full[col]) age_train = full[full['Age'].notnull()] age_predict = full[~full['Age'].notnull()] lr = LinearRegression() lr.fit(age_train.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1), age_train['Age']) predicted_ages = lr.predict(age_predict.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1)) age_predict['Age'] = [max(0.0, age) for age in predicted_ages] full = pd.concat([age_train, age_predict]).sort_values('PassengerId') ages = age_train.Age ages.plot.kde(label='Original') ages = full.Age ages.plot.kde(label='With predicted missing values') full_with_deck = full[full['Deck'].notnull()] full_without_deck = full[~full['Deck'].notnull()] full_with_deck_means, full_without_deck_means = ([], []) for col in full_with_deck: if col not in ['Deck', 'PassengerId']: sum_means = np.nanmean(full_with_deck[col].values) + np.nanmean(full_without_deck[col].values) full_with_deck_means.append(np.nanmean(full_with_deck[col].values) / sum_means) full_without_deck_means.append(np.nanmean(full_without_deck[col].values) / sum_means) bar_width = 0.35 opacity = 0.4 x_index = np.arange(len(full_with_deck_means)) plt.xticks(x_index + bar_width, [col for col in full_with_deck if col not in ['PassengerId', 'Deck']]) train = full[full.PassengerId < 892] test = full[full.PassengerId >= 892] rf = RandomForestClassifier(n_estimators=100, oob_score=True) rf.fit(train.drop(['Survived', 'PassengerId'], axis=1), train['Survived']) rf.score(train.drop(['Survived', 'PassengerId'], axis=1), train['Survived']) rf.oob_score_ features = list(zip(train.drop(['Survived', 'PassengerId'], axis=1).columns.values, rf.feature_importances_)) features.sort(key=lambda f: f[1]) names = [f[0] for f in features] lengths = [f[1] for f in features] pos = np.arange(len(features)) + 0.5 plt.barh(pos, lengths, align='center', color='r', alpha=opacity) plt.yticks(pos, names) plt.xlabel('Gini importance') plt.show()
code
326886/cell_14
[ "image_output_1.png" ]
from collections import Counter from sklearn.linear_model import LinearRegression from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt import numpy as np import pandas as pd import string import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter import string from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression pd.options.mode.chained_assignment = None def get_title(name): name = name.split(',')[1] name = name.split('.')[0] return name.strip() def get_title_grouped(name): title = get_title(name) if title in ['Rev', 'Dr', 'Col', 'Major', 'the Countess', 'Sir', 'Lady', 'Jonkheer', 'Capt', 'Dona', 'Don']: title = 'Rare' elif title in ['Ms', 'Mlle']: title = 'Miss' elif title == 'Mme': title = 'Mrs' return title def get_deck(cabin): if isinstance(cabin, str): if cabin[0] == 'T': return np.nan return cabin[0] return cabin train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') full = pd.concat([train, test]) # feature engineering described in previous notebooks full['Embarked'].fillna('C', inplace=True) full['Fare'].fillna(8.05, inplace=True) full['Title'] = full['Name'].apply(get_title_grouped) full['Deck'] = full['Cabin'].apply(get_deck) full['Family size'] = full['Parch'] + full['SibSp'] ticket_nums = [int(n.split()[-1]) for n in full['Ticket'].values if n.split()[-1].isdigit()] ticket_nums = [num for num in ticket_nums if num < 2000000] def get_ticket_num(ticket): ticket_num = ticket.split() ticket_num = ''.join((char for char in ticket_num[-1].strip() if char not in string.punctuation)) if not ticket_num.isdigit(): return np.nan return int(ticket_num) full['Ticket number'] = full['Ticket'].apply(get_ticket_num) full['Ticket number'].fillna(np.nanmedian(full['Ticket number'].values), inplace=True) full.drop(['Name', 'Ticket', 'Cabin', 'Parch', 'SibSp'], axis=1, inplace=True) encoders = {} to_encode = ['Embarked', 'Sex', 'Title'] for col in to_encode: encoders[col] = LabelEncoder() encoders[col].fit(full[col]) full[col] = encoders[col].transform(full[col]) age_train = full[full['Age'].notnull()] age_predict = full[~full['Age'].notnull()] lr = LinearRegression() lr.fit(age_train.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1), age_train['Age']) predicted_ages = lr.predict(age_predict.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1)) age_predict['Age'] = [max(0.0, age) for age in predicted_ages] full = pd.concat([age_train, age_predict]).sort_values('PassengerId') ages = age_train.Age ages.plot.kde(label='Original') ages = full.Age ages.plot.kde(label='With predicted missing values') Counter(full['Deck'].values)
code
326886/cell_22
[ "image_output_1.png" ]
from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LinearRegression from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt import numpy as np import pandas as pd import string import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter import string from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression pd.options.mode.chained_assignment = None def get_title(name): name = name.split(',')[1] name = name.split('.')[0] return name.strip() def get_title_grouped(name): title = get_title(name) if title in ['Rev', 'Dr', 'Col', 'Major', 'the Countess', 'Sir', 'Lady', 'Jonkheer', 'Capt', 'Dona', 'Don']: title = 'Rare' elif title in ['Ms', 'Mlle']: title = 'Miss' elif title == 'Mme': title = 'Mrs' return title def get_deck(cabin): if isinstance(cabin, str): if cabin[0] == 'T': return np.nan return cabin[0] return cabin train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') full = pd.concat([train, test]) # feature engineering described in previous notebooks full['Embarked'].fillna('C', inplace=True) full['Fare'].fillna(8.05, inplace=True) full['Title'] = full['Name'].apply(get_title_grouped) full['Deck'] = full['Cabin'].apply(get_deck) full['Family size'] = full['Parch'] + full['SibSp'] ticket_nums = [int(n.split()[-1]) for n in full['Ticket'].values if n.split()[-1].isdigit()] ticket_nums = [num for num in ticket_nums if num < 2000000] def get_ticket_num(ticket): ticket_num = ticket.split() ticket_num = ''.join((char for char in ticket_num[-1].strip() if char not in string.punctuation)) if not ticket_num.isdigit(): return np.nan return int(ticket_num) full['Ticket number'] = full['Ticket'].apply(get_ticket_num) full['Ticket number'].fillna(np.nanmedian(full['Ticket number'].values), inplace=True) full.drop(['Name', 'Ticket', 'Cabin', 'Parch', 'SibSp'], axis=1, inplace=True) encoders = {} to_encode = ['Embarked', 'Sex', 'Title'] for col in to_encode: encoders[col] = LabelEncoder() encoders[col].fit(full[col]) full[col] = encoders[col].transform(full[col]) age_train = full[full['Age'].notnull()] age_predict = full[~full['Age'].notnull()] lr = LinearRegression() lr.fit(age_train.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1), age_train['Age']) predicted_ages = lr.predict(age_predict.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1)) age_predict['Age'] = [max(0.0, age) for age in predicted_ages] full = pd.concat([age_train, age_predict]).sort_values('PassengerId') ages = age_train.Age ages.plot.kde(label='Original') ages = full.Age ages.plot.kde(label='With predicted missing values') train = full[full.PassengerId < 892] test = full[full.PassengerId >= 892] rf = RandomForestClassifier(n_estimators=100, oob_score=True) rf.fit(train.drop(['Survived', 'PassengerId'], axis=1), train['Survived']) rf.score(train.drop(['Survived', 'PassengerId'], axis=1), train['Survived']) rf.oob_score_
code
326886/cell_12
[ "image_output_1.png" ]
from sklearn.linear_model import LinearRegression from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt import numpy as np import pandas as pd import string import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter import string from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression pd.options.mode.chained_assignment = None def get_title(name): name = name.split(',')[1] name = name.split('.')[0] return name.strip() def get_title_grouped(name): title = get_title(name) if title in ['Rev', 'Dr', 'Col', 'Major', 'the Countess', 'Sir', 'Lady', 'Jonkheer', 'Capt', 'Dona', 'Don']: title = 'Rare' elif title in ['Ms', 'Mlle']: title = 'Miss' elif title == 'Mme': title = 'Mrs' return title def get_deck(cabin): if isinstance(cabin, str): if cabin[0] == 'T': return np.nan return cabin[0] return cabin train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') full = pd.concat([train, test]) # feature engineering described in previous notebooks full['Embarked'].fillna('C', inplace=True) full['Fare'].fillna(8.05, inplace=True) full['Title'] = full['Name'].apply(get_title_grouped) full['Deck'] = full['Cabin'].apply(get_deck) full['Family size'] = full['Parch'] + full['SibSp'] ticket_nums = [int(n.split()[-1]) for n in full['Ticket'].values if n.split()[-1].isdigit()] ticket_nums = [num for num in ticket_nums if num < 2000000] def get_ticket_num(ticket): ticket_num = ticket.split() ticket_num = ''.join((char for char in ticket_num[-1].strip() if char not in string.punctuation)) if not ticket_num.isdigit(): return np.nan return int(ticket_num) full['Ticket number'] = full['Ticket'].apply(get_ticket_num) full['Ticket number'].fillna(np.nanmedian(full['Ticket number'].values), inplace=True) full.drop(['Name', 'Ticket', 'Cabin', 'Parch', 'SibSp'], axis=1, inplace=True) encoders = {} to_encode = ['Embarked', 'Sex', 'Title'] for col in to_encode: encoders[col] = LabelEncoder() encoders[col].fit(full[col]) full[col] = encoders[col].transform(full[col]) age_train = full[full['Age'].notnull()] age_predict = full[~full['Age'].notnull()] lr = LinearRegression() lr.fit(age_train.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1), age_train['Age']) predicted_ages = lr.predict(age_predict.drop(['Deck', 'Survived', 'PassengerId', 'Age'], axis=1)) age_predict['Age'] = [max(0.0, age) for age in predicted_ages] full = pd.concat([age_train, age_predict]).sort_values('PassengerId') ages = age_train.Age ages.plot.kde(label='Original') ages = full.Age ages.plot.kde(label='With predicted missing values') plt.xlabel('Age') plt.legend(prop={'size': 9}) plt.show()
code
2017953/cell_21
[ "text_html_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender boolean_filter = (medals.Event_gender == 'W') & (medals.Gender == 'Men') medals[boolean_filter] medals.iloc[[23675]] medals.iloc[[23675], [6]] = 'Women' medals.iloc[[23675]] Nsports = medals[['NOC', 'Sport']].groupby('NOC', as_index=False).agg({'Sport': 'nunique'}).sort_values('Sport', ascending=False) Nsports.head(15)
code
2017953/cell_13
[ "text_plain_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender
code
2017953/cell_9
[ "text_html_output_1.png", "text_plain_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted.head(15)
code
2017953/cell_4
[ "image_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') print(medals.info()) medals.head()
code
2017953/cell_23
[ "text_html_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender boolean_filter = (medals.Event_gender == 'W') & (medals.Gender == 'Men') medals[boolean_filter] medals.iloc[[23675]] medals.iloc[[23675], [6]] = 'Women' medals.iloc[[23675]] Nsports = medals[['NOC', 'Sport']].groupby('NOC', as_index=False).agg({'Sport': 'nunique'}).sort_values('Sport', ascending=False) during_cold_war = (medals.Edition >= 1952) & (medals.Edition <= 1988) is_usa_urs = medals.NOC.isin(['USA', 'URS']) cold_war_medals = medals.loc[during_cold_war & is_usa_urs] country_grouped = cold_war_medals.groupby('NOC') Nsports = country_grouped['Sport'].nunique().sort_values(ascending=False) print(Nsports)
code
2017953/cell_7
[ "text_plain_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') medal_counts = medals['NOC'].value_counts() print('The total medals: %d' % medal_counts.sum()) print('\nTop 15 countries:\n', medal_counts.head(15))
code
2017953/cell_18
[ "text_html_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender boolean_filter = (medals.Event_gender == 'W') & (medals.Gender == 'Men') medals[boolean_filter] medals.iloc[[23675]] medals.iloc[[23675], [6]] = 'Women' medals.iloc[[23675]]
code
2017953/cell_28
[ "text_html_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender boolean_filter = (medals.Event_gender == 'W') & (medals.Gender == 'Men') medals[boolean_filter] medals.iloc[[23675]] medals.iloc[[23675], [6]] = 'Women' medals.iloc[[23675]] Nsports = medals[['NOC', 'Sport']].groupby('NOC', as_index=False).agg({'Sport': 'nunique'}).sort_values('Sport', ascending=False) during_cold_war = (medals.Edition >= 1952) & (medals.Edition <= 1988) is_usa_urs = medals.NOC.isin(['USA', 'URS']) cold_war_medals = medals.loc[during_cold_war & is_usa_urs] country_grouped = cold_war_medals.groupby('NOC') Nsports = country_grouped['Sport'].nunique().sort_values(ascending=False) medals_won_by_country = medals.pivot_table(index='Edition', columns='NOC', values='Athlete', aggfunc='count') cold_war_usa_usr_medals = medals_won_by_country.loc[1952:1988, ['USA', 'URS']] medals.Medal = pd.Categorical(values=medals.Medal, categories=['Bronze', 'Silver', 'Gold'], ordered=True) usa = medals[medals.NOC == 'USA'] usa_medals_by_year = usa.groupby(['Edition', 'Medal'])['Athlete'].count() usa_medals_by_year = usa_medals_by_year.unstack(level='Medal') usa_medals_by_year.plot.area(figsize=(12, 8), title='USA medals over time in Olympic games') urs = medals[medals.NOC == 'URS'] usa_medals_by_year = urs.groupby(['Edition', 'Medal'])['Athlete'].count() usa_medals_by_year = usa_medals_by_year.unstack(level='Medal') usa_medals_by_year.plot.area(figsize=(12, 8), title='URS medals over time in Olympic games') plt.show()
code
2017953/cell_15
[ "text_html_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender boolean_filter = (medals.Event_gender == 'W') & (medals.Gender == 'Men') medals[boolean_filter]
code
2017953/cell_3
[ "text_plain_output_1.png" ]
from subprocess import check_output import numpy as np import pandas as pd import matplotlib.pyplot as plt from subprocess import check_output print(check_output(['ls', '../input']).decode('utf8'))
code
2017953/cell_17
[ "text_html_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender boolean_filter = (medals.Event_gender == 'W') & (medals.Gender == 'Men') medals[boolean_filter] medals.iloc[[23675]]
code
2017953/cell_31
[ "text_plain_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) for place, country in enumerate(counted.index): if country == 'HUN': print('Hungary is the ' + str(place + 1) + ' country in the total Olympic medals ranking') break
code
2017953/cell_24
[ "text_html_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender boolean_filter = (medals.Event_gender == 'W') & (medals.Gender == 'Men') medals[boolean_filter] medals.iloc[[23675]] medals.iloc[[23675], [6]] = 'Women' medals.iloc[[23675]] Nsports = medals[['NOC', 'Sport']].groupby('NOC', as_index=False).agg({'Sport': 'nunique'}).sort_values('Sport', ascending=False) during_cold_war = (medals.Edition >= 1952) & (medals.Edition <= 1988) is_usa_urs = medals.NOC.isin(['USA', 'URS']) cold_war_medals = medals.loc[during_cold_war & is_usa_urs] country_grouped = cold_war_medals.groupby('NOC') Nsports = country_grouped['Sport'].nunique().sort_values(ascending=False) medals_won_by_country = medals.pivot_table(index='Edition', columns='NOC', values='Athlete', aggfunc='count') cold_war_usa_usr_medals = medals_won_by_country.loc[1952:1988, ['USA', 'URS']] print('Consistency during cold war\n', cold_war_usa_usr_medals.idxmax(axis='columns')) print('\nTotal counts\n', cold_war_usa_usr_medals.idxmax(axis='columns').value_counts())
code
2017953/cell_27
[ "text_html_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) medals_by_gender = medals.groupby(['Event_gender', 'Gender']).count() medals_by_gender boolean_filter = (medals.Event_gender == 'W') & (medals.Gender == 'Men') medals[boolean_filter] medals.iloc[[23675]] medals.iloc[[23675], [6]] = 'Women' medals.iloc[[23675]] Nsports = medals[['NOC', 'Sport']].groupby('NOC', as_index=False).agg({'Sport': 'nunique'}).sort_values('Sport', ascending=False) during_cold_war = (medals.Edition >= 1952) & (medals.Edition <= 1988) is_usa_urs = medals.NOC.isin(['USA', 'URS']) cold_war_medals = medals.loc[during_cold_war & is_usa_urs] country_grouped = cold_war_medals.groupby('NOC') Nsports = country_grouped['Sport'].nunique().sort_values(ascending=False) medals_won_by_country = medals.pivot_table(index='Edition', columns='NOC', values='Athlete', aggfunc='count') cold_war_usa_usr_medals = medals_won_by_country.loc[1952:1988, ['USA', 'URS']] medals.Medal = pd.Categorical(values=medals.Medal, categories=['Bronze', 'Silver', 'Gold'], ordered=True) usa = medals[medals.NOC == 'USA'] usa_medals_by_year = usa.groupby(['Edition', 'Medal'])['Athlete'].count() usa_medals_by_year = usa_medals_by_year.unstack(level='Medal') usa_medals_by_year.plot.area(figsize=(12, 8), title='USA medals over time in Olympic games') plt.show()
code
2017953/cell_12
[ "text_html_output_1.png", "text_plain_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) medals = pd.read_csv('../input/.csv') counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count') counted['totals'] = counted.sum(axis='columns') counted = counted.sort_values('totals', ascending=False) counted = medals.pivot_table(index='NOC', values='Athlete', columns='Medal', aggfunc='count', margins=True, margins_name='Totals_all') counted = counted.sort_values('Totals_all', ascending=False) ev_gen_uniques = medals[['Event_gender', 'Gender']].drop_duplicates() ev_gen_uniques
code
73087956/cell_4
[ "text_plain_output_2.png", "text_plain_output_1.png" ]
import pandas as pd av = pd.read_csv('../input/seti-adversarial-validation/oof.csv') tmp = pd.read_csv('../input/seti-breakthrough-listen/train_labels.csv') tmp['label'] = tmp['target'] av = pd.merge(av, tmp[['id', 'label']], on='id', how='left') av.query('target == 0 and pred > 1e-4')
code
73087956/cell_1
[ "text_plain_output_1.png" ]
!pip install git+https://github.com/rwightman/pytorch-image-models import timm
code
73087956/cell_3
[ "text_html_output_1.png" ]
import numpy as np import os import random import torch class CFG: seed = 46 debug = False n_fold = 4 n_epoch = 11 height = 480 width = 480 model_name = 'efficientnet_b0' lr = 0.0001 min_lr = 1e-06 weight_decay = 0.0001 T_max = 10 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f'Using device {CFG.device}') def seed_torch(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_torch(CFG.seed)
code
73087956/cell_5
[ "text_plain_output_35.png", "text_plain_output_43.png", "text_plain_output_37.png", "text_plain_output_5.png", "text_plain_output_30.png", "application_vnd.jupyter.stderr_output_2.png", "text_plain_output_15.png", "text_plain_output_9.png", "text_plain_output_44.png", "text_plain_output_40.png", "text_plain_output_31.png", "text_plain_output_20.png", "text_plain_output_4.png", "text_plain_output_13.png", "text_plain_output_45.png", "text_plain_output_14.png", "text_plain_output_32.png", "text_plain_output_29.png", "text_plain_output_27.png", "text_plain_output_10.png", "text_plain_output_6.png", "text_plain_output_24.png", "text_plain_output_21.png", "text_plain_output_25.png", "text_plain_output_18.png", "text_plain_output_36.png", "text_plain_output_3.png", "text_plain_output_22.png", "text_plain_output_38.png", "text_plain_output_7.png", "text_plain_output_16.png", "text_plain_output_8.png", "text_plain_output_26.png", "text_plain_output_41.png", "text_plain_output_34.png", "text_plain_output_42.png", "text_plain_output_23.png", "text_plain_output_28.png", "text_plain_output_1.png", "text_plain_output_33.png", "text_plain_output_39.png", "text_plain_output_19.png", "text_plain_output_17.png", "text_plain_output_11.png", "text_plain_output_12.png", "text_plain_output_46.png" ]
from sklearn.model_selection import StratifiedKFold import numpy as np import os import pandas as pd import random import torch class CFG: seed = 46 debug = False n_fold = 4 n_epoch = 11 height = 480 width = 480 model_name = 'efficientnet_b0' lr = 0.0001 min_lr = 1e-06 weight_decay = 0.0001 T_max = 10 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def seed_torch(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_torch(CFG.seed) av = pd.read_csv('../input/seti-adversarial-validation/oof.csv') tmp = pd.read_csv('../input/seti-breakthrough-listen/train_labels.csv') tmp['label'] = tmp['target'] av = pd.merge(av, tmp[['id', 'label']], on='id', how='left') av.query('target == 0 and pred > 1e-4') train = av.query('target == 0 and pred > 1e-4').reset_index(drop=True) train['target'] = train['label'] train = train.drop(['label', 'pred'], axis=1) test = pd.read_csv('../input/seti-breakthrough-listen/sample_submission.csv') train['file_path'] = train['id'].apply(lambda x: f'../input/seti-breakthrough-listen/train/{x[0]}/{x}.npy') test['file_path'] = test['id'].apply(lambda x: f'../input/seti-breakthrough-listen/test/{x[0]}/{x}.npy') print(train['target'].value_counts()) if CFG.debug: CFG.n_epoch = 2 train = train.sample(n=1000, random_state=CFG.seed).reset_index(drop=True) test = test.sample(n=1000, random_state=CFG.seed).reset_index(drop=True) skf = StratifiedKFold(n_splits=CFG.n_fold, shuffle=True, random_state=CFG.seed) for fold, (_, val_index) in enumerate(skf.split(train, train['target'])): train.loc[val_index, 'fold'] = fold train['fold'] = train['fold'].astype(int) train.groupby(['fold', 'target']).size()
code
33097852/cell_21
[ "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[var]], axis=1) #box plot overallqual/saleprice var = 'OverallQual' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); var = 'YearBuilt' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(16, 8)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); plt.xticks(rotation=90); sns.set(font_scale=1) correlation_train = train.corr() train.corr()
code
33097852/cell_13
[ "text_html_output_1.png" ]
import pandas as pd train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) data.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))
code
33097852/cell_9
[ "text_html_output_1.png" ]
import pandas as pd train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) train['SalePrice'].describe()
code
33097852/cell_25
[ "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[var]], axis=1) #box plot overallqual/saleprice var = 'OverallQual' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); var = 'YearBuilt' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(16, 8)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); plt.xticks(rotation=90); sns.set(font_scale=1) correlation_train = train.corr() train.corr() train_total = train.isnull().sum().sort_values(ascending=False) train_percent = (train.isnull().sum() / train.isnull().count()).sort_values(ascending=False) train_missing_data = pd.concat([train_total, train_percent], axis=1, keys=['Total', 'Percent']) train_missing_data.head(20)
code
33097852/cell_23
[ "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[var]], axis=1) #box plot overallqual/saleprice var = 'OverallQual' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); var = 'YearBuilt' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(16, 8)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); plt.xticks(rotation=90); sns.set(font_scale=1) correlation_train = train.corr() train.corr() sns.set() cols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt'] sns.pairplot(train[cols], size=2.5) plt.show()
code
33097852/cell_20
[ "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[var]], axis=1) #box plot overallqual/saleprice var = 'OverallQual' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); var = 'YearBuilt' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(16, 8)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); plt.xticks(rotation=90); sns.set(font_scale=1) correlation_train = train.corr() plt.figure(figsize=(30, 20)) sns.heatmap(correlation_train, annot=True, fmt='.1f')
code
33097852/cell_6
[ "image_output_1.png" ]
import pandas as pd train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) test.head()
code
33097852/cell_26
[ "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[var]], axis=1) #box plot overallqual/saleprice var = 'OverallQual' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); var = 'YearBuilt' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(16, 8)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); plt.xticks(rotation=90); sns.set(font_scale=1) correlation_train = train.corr() train.corr() train_total = train.isnull().sum().sort_values(ascending=False) train_percent = (train.isnull().sum() / train.isnull().count()).sort_values(ascending=False) train_missing_data = pd.concat([train_total, train_percent], axis=1, keys=['Total', 'Percent']) test_total = test.isnull().sum().sort_values(ascending=False) test_percent = (test.isnull().sum() / test.isnull().count()).sort_values(ascending=False) test_missing_data = pd.concat([test_total, test_percent], axis=1, keys=['Total', 'Percent']) test_missing_data.head(35)
code
33097852/cell_19
[ "text_plain_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[var]], axis=1) #box plot overallqual/saleprice var = 'OverallQual' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=var, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000); var = 'YearBuilt' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(16, 8)) fig = sns.boxplot(x=var, y='SalePrice', data=data) fig.axis(ymin=0, ymax=800000) plt.xticks(rotation=90)
code
33097852/cell_7
[ "text_html_output_1.png" ]
import pandas as pd train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) sample_submission.head()
code
33097852/cell_18
[ "text_plain_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'OverallQual' data = pd.concat([train['SalePrice'], train[var]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=var, y='SalePrice', data=data) fig.axis(ymin=0, ymax=800000)
code
33097852/cell_8
[ "text_html_output_1.png" ]
import pandas as pd train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) print(train.shape) print(test.shape) print(sample_submission.shape)
code
33097852/cell_15
[ "text_html_output_1.png" ]
import pandas as pd train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) var = 'GrLivArea' data = pd.concat([train['SalePrice'], train[var]], axis=1) var = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[var]], axis=1) data.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))
code
33097852/cell_10
[ "text_html_output_1.png" ]
import pandas as pd import seaborn as sns train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) sns.distplot(train['SalePrice'])
code
33097852/cell_5
[ "text_html_output_1.png" ]
import pandas as pd train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv', header=0) test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv', header=0) sample_submission = pd.read_csv('../input/house-prices-advanced-regression-techniques/sample_submission.csv', header=0) train.head()
code
2031298/cell_13
[ "text_html_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df1['Survived'].value_counts().plot.bar(color='r') plt.show() df1['Pclass'].value_counts().plot.bar() plt.show() df1['Sex'].value_counts().plot.bar(color='g') plt.show() df1['SibSp'].value_counts().plot.bar() plt.show() plt.show() df1['Embarked'].value_counts().plot.bar() plt.show()
code
2031298/cell_25
[ "application_vnd.jupyter.stderr_output_1.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df12 = df1.fillna(df1.mean()) i = df1[['Age', 'Fare', 'Survived']] plt.style.use('seaborn-colorblind') corr = df1.corr() freq_1 = pd.crosstab(index=df1['Survived'], columns=df1['Pclass']) freq_2 = pd.crosstab(index=df1['Survived'], columns=df1['Sex']) freq_3 = pd.crosstab(index=df1['Survived'], columns=df1['SibSp']) freq_4 = pd.crosstab(index=df1['Survived'], columns=df1['Parch']) freq_5 = pd.crosstab(index=df1['Survived'], columns=df1['Pclass']) freq_6 = pd.crosstab(index=df1['Survived'], columns=df1['Embarked']) l = [freq_1, freq_2, freq_3, freq_4, freq_5, freq_6] for i in l: print(i)
code
2031298/cell_23
[ "text_plain_output_1.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df12 = df1.fillna(df1.mean()) i = df1[['Age', 'Fare', 'Survived']] plt.style.use('seaborn-colorblind') corr = df1.corr() sns.heatmap(corr[['Age', 'Fare']], annot=True, linewidth=0.1) plt.show()
code
2031298/cell_20
[ "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df12 = df1.fillna(df1.mean()) plt.figure() df1.plot.scatter('Age', 'Fare') plt.show()
code
2031298/cell_11
[ "text_html_output_1.png" ]
import pandas as pd df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df1.describe()
code
2031298/cell_7
[ "text_plain_output_1.png" ]
import pandas as pd df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df1.head()
code
2031298/cell_8
[ "image_output_5.png", "image_output_4.png", "image_output_6.png", "image_output_3.png", "image_output_2.png", "image_output_1.png" ]
import pandas as pd df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df2.head()
code
2031298/cell_16
[ "image_output_5.png", "image_output_4.png", "image_output_3.png", "image_output_2.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df12 = df1.fillna(df1.mean()) plt.hist(df12.Age, alpha=0.3) sns.rugplot(df12.Age) plt.show()
code
2031298/cell_17
[ "image_output_2.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df12 = df1.fillna(df1.mean()) plt.hist(df12.Fare) sns.rugplot(df12.Fare, alpha=0.3) plt.show()
code
2031298/cell_14
[ "text_html_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df1[['Age', 'Fare']].describe() df1['Age'].value_counts().plot.hist(grid=True, color='b', alpha=0.7) plt.show() df1['Fare'].value_counts().plot.hist(grid=True, color='r') plt.show()
code
2031298/cell_22
[ "image_output_1.png" ]
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df12 = df1.fillna(df1.mean()) i = df1[['Age', 'Fare', 'Survived']] plt.style.use('seaborn-colorblind') pd.tools.plotting.scatter_matrix(i) plt.show()
code
2031298/cell_12
[ "text_html_output_1.png" ]
import pandas as pd df1 = pd.read_csv('../input/train.csv') df2 = pd.read_csv('../input/test.csv') df1.describe(include=['O'])
code
1006119/cell_9
[ "application_vnd.jupyter.stderr_output_1.png" ]
from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse=False) x_train = vec.fit_transform(x_train.to_dict(orient='record')) x_test = vec.transform(x_test.to_dict(orient='record')) vec.get_feature_names()
code
1006119/cell_11
[ "application_vnd.jupyter.stderr_output_1.png" ]
from sklearn.feature_extraction import DictVectorizer from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) data_train = pd.read_csv('train.csv') data_test = pd.read_csv('test.csv') data_x = data_train[['Pclass', 'Age', 'Sex']] data_y = data_train['Survived'] age_mean = data_x.mean()['Age'] data_x = data_x.fillna(age_mean) for i in range(1, 4): data_x.loc[data_x.Pclass == i, 'Pclass'] = str(i) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(data_x, data_y, test_size=0.25, random_state=33) y_train.value_counts() from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse=False) x_train = vec.fit_transform(x_train.to_dict(orient='record')) x_test = vec.transform(x_test.to_dict(orient='record')) vec.get_feature_names() from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier() dtc.fit(x_train, y_train) dtc_y_predict = dtc.predict(x_test)
code
1006119/cell_19
[ "application_vnd.jupyter.stderr_output_1.png" ]
from sklearn.feature_extraction import DictVectorizer from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) data_train = pd.read_csv('train.csv') data_test = pd.read_csv('test.csv') data_x = data_train[['Pclass', 'Age', 'Sex']] data_y = data_train['Survived'] age_mean = data_x.mean()['Age'] data_x = data_x.fillna(age_mean) for i in range(1, 4): data_x.loc[data_x.Pclass == i, 'Pclass'] = str(i) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(data_x, data_y, test_size=0.25, random_state=33) y_train.value_counts() from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse=False) x_train = vec.fit_transform(x_train.to_dict(orient='record')) x_test = vec.transform(x_test.to_dict(orient='record')) vec.get_feature_names() from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier() dtc.fit(x_train, y_train) dtc_y_predict = dtc.predict(x_test) dtc.score(x_test, y_test) run_x = data_test[['Pclass', 'Age', 'Sex']] run_x = run_x.fillna(age_mean) for i in range(1, 4): run_x.loc[run_x.Pclass == i, 'Pclass'] = str(i) run_x = vec.transform(run_x.to_dict(orient='record')) run_y_predict = dtc.predict(run_x) pd.DataFrame({'PassengerId': data_test.PassengerId, 'Survived': run_y_predict}).to_csv('gender_submission.csv', index=False)
code
1006119/cell_1
[ "text_plain_output_1.png" ]
from subprocess import check_output import numpy as np import pandas as pd from subprocess import check_output print(check_output(['ls', '../input']).decode('utf8'))
code
1006119/cell_7
[ "application_vnd.jupyter.stderr_output_1.png" ]
from sklearn.model_selection import train_test_split import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) data_train = pd.read_csv('train.csv') data_test = pd.read_csv('test.csv') data_x = data_train[['Pclass', 'Age', 'Sex']] data_y = data_train['Survived'] age_mean = data_x.mean()['Age'] data_x = data_x.fillna(age_mean) for i in range(1, 4): data_x.loc[data_x.Pclass == i, 'Pclass'] = str(i) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(data_x, data_y, test_size=0.25, random_state=33) y_train.value_counts()
code
1006119/cell_18
[ "application_vnd.jupyter.stderr_output_1.png" ]
from sklearn.feature_extraction import DictVectorizer from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) data_train = pd.read_csv('train.csv') data_test = pd.read_csv('test.csv') data_x = data_train[['Pclass', 'Age', 'Sex']] data_y = data_train['Survived'] age_mean = data_x.mean()['Age'] data_x = data_x.fillna(age_mean) for i in range(1, 4): data_x.loc[data_x.Pclass == i, 'Pclass'] = str(i) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(data_x, data_y, test_size=0.25, random_state=33) y_train.value_counts() from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse=False) x_train = vec.fit_transform(x_train.to_dict(orient='record')) x_test = vec.transform(x_test.to_dict(orient='record')) vec.get_feature_names() from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier() dtc.fit(x_train, y_train) dtc_y_predict = dtc.predict(x_test) dtc.score(x_test, y_test) run_x = data_test[['Pclass', 'Age', 'Sex']] run_x = run_x.fillna(age_mean) for i in range(1, 4): run_x.loc[run_x.Pclass == i, 'Pclass'] = str(i) run_x = vec.transform(run_x.to_dict(orient='record')) run_y_predict = dtc.predict(run_x)
code
1006119/cell_15
[ "application_vnd.jupyter.stderr_output_1.png" ]
from sklearn.feature_extraction import DictVectorizer from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) data_train = pd.read_csv('train.csv') data_test = pd.read_csv('test.csv') data_x = data_train[['Pclass', 'Age', 'Sex']] data_y = data_train['Survived'] age_mean = data_x.mean()['Age'] data_x = data_x.fillna(age_mean) for i in range(1, 4): data_x.loc[data_x.Pclass == i, 'Pclass'] = str(i) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(data_x, data_y, test_size=0.25, random_state=33) y_train.value_counts() from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse=False) x_train = vec.fit_transform(x_train.to_dict(orient='record')) x_test = vec.transform(x_test.to_dict(orient='record')) vec.get_feature_names() from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier() dtc.fit(x_train, y_train) dtc_y_predict = dtc.predict(x_test) dtc.score(x_test, y_test)
code
1006119/cell_16
[ "application_vnd.jupyter.stderr_output_1.png" ]
from sklearn.feature_extraction import DictVectorizer from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) data_train = pd.read_csv('train.csv') data_test = pd.read_csv('test.csv') data_x = data_train[['Pclass', 'Age', 'Sex']] data_y = data_train['Survived'] age_mean = data_x.mean()['Age'] data_x = data_x.fillna(age_mean) for i in range(1, 4): data_x.loc[data_x.Pclass == i, 'Pclass'] = str(i) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(data_x, data_y, test_size=0.25, random_state=33) y_train.value_counts() from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse=False) x_train = vec.fit_transform(x_train.to_dict(orient='record')) x_test = vec.transform(x_test.to_dict(orient='record')) vec.get_feature_names() from sklearn.tree import DecisionTreeClassifier dtc = DecisionTreeClassifier() dtc.fit(x_train, y_train) dtc_y_predict = dtc.predict(x_test) print(classification_report(y_test, dtc_y_predict, target_names=['died', 'surived']))
code
1006119/cell_3
[ "application_vnd.jupyter.stderr_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) data_train = pd.read_csv('train.csv') data_test = pd.read_csv('test.csv')
code
1006119/cell_5
[ "application_vnd.jupyter.stderr_output_1.png" ]
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) data_train = pd.read_csv('train.csv') data_test = pd.read_csv('test.csv') data_x = data_train[['Pclass', 'Age', 'Sex']] data_y = data_train['Survived'] age_mean = data_x.mean()['Age'] data_x = data_x.fillna(age_mean) for i in range(1, 4): data_x.loc[data_x.Pclass == i, 'Pclass'] = str(i) data_x.head()
code
33101666/cell_13
[ "text_html_output_1.png", "application_vnd.jupyter.stderr_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) interp = ClassificationInterpretation.from_learner(learner) learner2 = cnn_learner(data, models.resnet152, metrics=accuracy) learner2.fit(3) interp2 = ClassificationInterpretation.from_learner(learner2) interp2.plot_top_losses(9, figsize=(10, 10))
code
33101666/cell_9
[ "image_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) interp = ClassificationInterpretation.from_learner(learner) interp.most_confused()
code
33101666/cell_4
[ "image_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5)
code
33101666/cell_2
[ "image_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch()
code
33101666/cell_1
[ "text_plain_output_1.png" ]
import os import numpy as np import pandas as pd import os for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) break
code
33101666/cell_7
[ "text_plain_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) interp = ClassificationInterpretation.from_learner(learner) interp.plot_confusion_matrix()
code
33101666/cell_15
[ "image_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) interp = ClassificationInterpretation.from_learner(learner) learner2 = cnn_learner(data, models.resnet152, metrics=accuracy) learner2.fit(3) interp2 = ClassificationInterpretation.from_learner(learner2) interp2.most_confused()
code
33101666/cell_3
[ "text_html_output_1.png", "application_vnd.jupyter.stderr_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() data.show_batch()
code
33101666/cell_17
[ "text_plain_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) interp = ClassificationInterpretation.from_learner(learner) learner2 = cnn_learner(data, models.resnet152, metrics=accuracy) learner2.fit(3) interp2 = ClassificationInterpretation.from_learner(learner2) interp2.most_confused() interp2.plot_top_losses(k=8)
code
33101666/cell_14
[ "image_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) interp = ClassificationInterpretation.from_learner(learner) learner2 = cnn_learner(data, models.resnet152, metrics=accuracy) learner2.fit(3) interp2 = ClassificationInterpretation.from_learner(learner2) interp2.plot_confusion_matrix()
code
33101666/cell_10
[ "application_vnd.jupyter.stderr_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) interp = ClassificationInterpretation.from_learner(learner) interp.most_confused() interp.plot_top_losses(k=8)
code
33101666/cell_12
[ "image_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) learner2 = cnn_learner(data, models.resnet152, metrics=accuracy) learner2.fit(3)
code
33101666/cell_5
[ "image_output_1.png" ]
from fastai.vision import * data = ImageList.from_folder('/kaggle/input/turkish-lira-banknote-dataset/').random_split_by_pct().label_from_folder().transform(get_transforms(), size=122).databunch() learner = cnn_learner(data, models.resnet18, metrics=accuracy) learner.fit(5) interp = ClassificationInterpretation.from_learner(learner) interp.plot_top_losses(9, figsize=(10, 10))
code
320604/cell_21
[ "text_plain_output_1.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass debt_data = get_data('debt') plot_two_fields(debt_data, 'debt', 'loan_amnt', 'int_rate', [100.0, 100000.0, 5.0, 30.0], 'loan amount', 'interest rate', 'semilogx')
code
320604/cell_13
[ "text_plain_output_1.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass medical_data = get_data('medical')
code
320604/cell_9
[ "text_plain_output_1.png" ]
import matplotlib.pyplot as plt import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass cc_data = get_data('credit card') plot_two_fields(cc_data, 'credit card', 'annual_inc', 'loan_amnt', [1000.0, 10000000.0, 0.0, 35000.0], 'annual income', 'loan amount', 'semilogx')
code
320604/cell_25
[ "text_plain_output_1.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass debt_data = get_data('debt') plot_two_fields(debt_data, 'debt', 'home_ownership', 'funded_amnt', [-1, 6, 0.0, 35000.0], 'home ownership', 'funded amount', 'standard')
code
320604/cell_23
[ "text_plain_output_1.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass debt_data = get_data('debt') plot_two_fields(debt_data, 'debt', 'annual_inc', 'loan_amnt', [1000.0, 10000000.0, 0.0, 35000.0], 'annual income', 'loan amount', 'semilogx')
code
320604/cell_33
[ "text_plain_output_1.png", "image_output_1.png" ]
from sklearn import tree import matplotlib.pyplot as plt import numpy as np import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass debt_data = get_data('debt') def create_classifier(f, t, nt): """Create classifier for predicting loan status. Print accuracy. Arguments: f (list of tuples) -- [(sample 1 features), (sample 2 features),...] t (list) -- [sample 1 target, sample 2 target,...] nt (int) -- number of samples to use in training set """ training_set_features = [] training_set_target = [] testing_set_features = [] testing_set_target = [] for i in np.arange(0, nt, 1): training_set_features.append(f[i]) training_set_target.append(t[i]) for i in np.arange(nt, len(f), 1): testing_set_features.append(f[i]) testing_set_target.append(t[i]) clf = tree.DecisionTreeClassifier() clf = clf.fit(training_set_features, training_set_target) n = 0 n_correct = 0 n0 = 0 n0_correct = 0 n1 = 0 n1_correct = 0 for i in range(len(testing_set_features)): t = testing_set_target[i] p = clf.predict(np.asarray(testing_set_features[i]).reshape(1, -1)) if t == 0: if t == p[0]: equal = 'yes' n_correct += 1 n0_correct += 1 else: equal = 'no' n += 1 n0 += 1 elif t == 1: if t == p[0]: equal = 'yes' n_correct += 1 n1_correct += 1 else: equal = 'no' n += 1 n1 += 1 else: pass n_accuracy = 100.0 * n_correct / n n0_accuracy = 100.0 * n0_correct / n0 n1_accuracy = 100.0 * n1_correct / n1 create_classifier(debt_data[0], debt_data[1], 2000)
code
320604/cell_20
[ "text_plain_output_1.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass debt_data = get_data('debt')
code
320604/cell_6
[ "text_plain_output_1.png", "image_output_1.png" ]
import matplotlib.pyplot as plt import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass cc_data = get_data('credit card')
code
320604/cell_29
[ "text_plain_output_1.png", "image_output_1.png" ]
from sklearn import tree import matplotlib.pyplot as plt import numpy as np import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass cc_data = get_data('credit card') def create_classifier(f, t, nt): """Create classifier for predicting loan status. Print accuracy. Arguments: f (list of tuples) -- [(sample 1 features), (sample 2 features),...] t (list) -- [sample 1 target, sample 2 target,...] nt (int) -- number of samples to use in training set """ training_set_features = [] training_set_target = [] testing_set_features = [] testing_set_target = [] for i in np.arange(0, nt, 1): training_set_features.append(f[i]) training_set_target.append(t[i]) for i in np.arange(nt, len(f), 1): testing_set_features.append(f[i]) testing_set_target.append(t[i]) clf = tree.DecisionTreeClassifier() clf = clf.fit(training_set_features, training_set_target) n = 0 n_correct = 0 n0 = 0 n0_correct = 0 n1 = 0 n1_correct = 0 for i in range(len(testing_set_features)): t = testing_set_target[i] p = clf.predict(np.asarray(testing_set_features[i]).reshape(1, -1)) if t == 0: if t == p[0]: equal = 'yes' n_correct += 1 n0_correct += 1 else: equal = 'no' n += 1 n0 += 1 elif t == 1: if t == p[0]: equal = 'yes' n_correct += 1 n1_correct += 1 else: equal = 'no' n += 1 n1 += 1 else: pass n_accuracy = 100.0 * n_correct / n n0_accuracy = 100.0 * n0_correct / n0 n1_accuracy = 100.0 * n1_correct / n1 create_classifier(cc_data[0], cc_data[1], 2000)
code
320604/cell_2
[ "text_plain_output_1.png", "image_output_1.png" ]
import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] print('Names of tables in SQLite database: {0}'.format(table_names)) num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] print('Number of records in table: {0}'.format(num_rows)) def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 print('Column names:') for k in r.keys(): print('{0:d}\t{1}'.format(i, k)) i += 1 conn.close() print_details() print_column_names()
code
320604/cell_11
[ "text_plain_output_1.png" ]
import matplotlib.pyplot as plt import sqlite3 import matplotlib.pyplot as plt import numpy as np import sqlite3 from sklearn import tree def sql_query(s): """Return results for a SQL query. Arguments: s (str) -- SQL query string Returns: (list) -- SQL query results """ conn = sqlite3.connect('../input/database.sqlite') c = conn.cursor() c.execute(s) result = c.fetchall() conn.close() return result def print_details(): """Print database details including table names and the number of rows. """ table_names = sql_query('SELECT name FROM sqlite_master ' + "WHERE type='table' " + 'ORDER BY name;')[0][0] num_rows = sql_query('SELECT COUNT(*) FROM loan;')[0][0] def print_column_names(): """Print the column names in the 'loan' table. Note that the "index" column name is specific to Python and is not part of the original SQLite database. """ conn = sqlite3.connect('../input/database.sqlite') conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM loan LIMIT 2;') r = c.fetchone() i = 1 for k in r.keys(): i += 1 conn.close() emp_length_dict = {'n/a': 0, '< 1 year': 0, '1 year': 1, '2 years': 2, '3 years': 3, '4 years': 4, '5 years': 5, '6 years': 6, '7 years': 7, '8 years': 8, '9 years': 9, '10+ years': 10} home_ownership_dict = {'MORTGAGE': 0, 'OWN': 1, 'RENT': 2, 'OTHER': 3, 'NONE': 4, 'ANY': 5} features_dict = {'loan_amnt': 0, 'int_rate': 1, 'annual_inc': 2, 'delinq_2yrs': 3, 'open_acc': 4, 'dti': 5, 'emp_length': 6, 'funded_amnt': 7, 'tot_cur_bal': 8, 'home_ownership': 9} def get_data(s): """Return features and targets for a specific search term. Arguments: s (str) -- string to search for in loan "title" field Returns: (list of lists) -- [list of feature tuples, list of targets] (features) -- [(sample1 features), (sample2 features),...] (target) -- [sample1 target, sample2 target,...] """ data = sql_query('SELECT ' + 'loan_amnt,int_rate,annual_inc,' + 'loan_status,title,delinq_2yrs,' + 'open_acc,dti,emp_length,' + 'funded_amnt,tot_cur_bal,home_ownership ' + 'FROM loan ' + "WHERE application_type='INDIVIDUAL';") features_list = [] target_list = [] n = 0 n0 = 0 n1 = 0 for d in data: test0 = isinstance(d[0], float) test1 = isinstance(d[1], str) test2 = isinstance(d[2], float) test3 = isinstance(d[3], str) test4 = isinstance(d[4], str) test5 = isinstance(d[5], float) test6 = isinstance(d[6], float) test7 = isinstance(d[7], float) test8 = isinstance(d[8], str) test9 = isinstance(d[9], float) test10 = isinstance(d[10], float) if test0 and test1 and test2 and test3 and test4 and test5 and test6 and test7 and test8 and test9 and test10: try: d1_float = float(d[1].replace('%', '')) except: continue try: e = emp_length_dict[d[8]] except: continue try: h = home_ownership_dict[d[11]] except: continue if s.lower() in d[4].lower(): if d[3] == 'Fully Paid' or d[3] == 'Current': target = 0 n += 1 n0 += 1 elif 'Late' in d[3] or d[3] == 'Charged Off': target = 1 n += 1 n1 += 1 else: continue features = (d[0], float(d[1].replace('%', '')), d[2], d[5], d[6], d[7], emp_length_dict[d[8]], d[9], d[10], home_ownership_dict[d[11]]) features_list.append(features) target_list.append(target) else: pass result = [features_list, target_list] return result def create_scatter_plot(x0_data, y0_data, x1_data, y1_data, pt, pa, x_label, y_label, axis_type): ax = plt.gca() ax.set_axis_bgcolor('#BBBBBB') ax.set_axisbelow(True) plt.axis(pa) plt.xticks(fontsize=16) plt.yticks(fontsize=16) if axis_type == 'semilogx': plt.semilogx(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogx(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'semilogy': plt.semilogy(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.semilogy(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') elif axis_type == 'loglog': plt.loglog(x0_data, y0_data, label='0: "Fully Paid" or "Current"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='b') plt.loglog(x1_data, y1_data, label='1: "Late" or "Charged Off"', linestyle='None', marker='.', markersize=8, alpha=0.5, color='r') plt.clf() def plot_two_fields(data, s, f1, f2, pa, x_label, y_label, axis_type): x0_list = [] y0_list = [] x1_list = [] y1_list = [] features_list = data[0] target_list = data[1] for i in range(len(features_list)): x = features_list[i][features_dict[f1]] y = features_list[i][features_dict[f2]] if target_list[i] == 0: x0_list.append(x) y0_list.append(y) elif target_list[i] == 1: x1_list.append(x) y1_list.append(y) else: pass cc_data = get_data('credit card') plot_two_fields(cc_data, 'credit card', 'home_ownership', 'funded_amnt', [-1, 6, 0.0, 35000.0], 'home ownership', 'funded amount', 'standard')
code