diff --git "a/2856.jsonl" "b/2856.jsonl" new file mode 100644--- /dev/null +++ "b/2856.jsonl" @@ -0,0 +1,159 @@ +{"seq_id":"28582843519","text":"# # Day 25\n\n# ###### Working with CSV data & pandas library\n\n# - Two primary data structures of pandas \n# - Dataframe (2d)\n# - Series (1d)\n\n# +\nimport pandas as pd\n\ndata = pd.read_csv('weather_data.csv')\nprint(data['temp'])\n# -\n\n# Converting to dictionary\ndata_dict = data.to_dict()\nprint(data_dict)\n\n# +\n# Converting to list\ntemp_list = data['temp'].to_list()\navg_temp = sum(temp_list)/len(temp_list)\n\n# Average temperature\nprint(data['temp'].mean())\n\n# Max temperature\nprint(data['temp'].max())\n\n# +\n# Get data in columns\nprint(data['condition'])\nprint(data.condition)\n\n# Get data in rows\nprint(data[data['day']=='Monday'])\n# -\n\n# Max temp row\nprint(data[data['temp'] == data['temp'].max()])\n\n# Create dataframe from scratch\ndata_dict = {\n 'students' : ['Ram','Shyam','Baburao'],\n 'roll' : [21,33,40]\n}\ndf = pd.DataFrame(data_dict)\ndf\n# Save as new csv\ndf.to_csv('filename.csv')\n\n# ---\n\n# ###### The Great Squirrel Data Analysis\n\ndf = pd.read_csv('2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv')\ndf.head()\n\n# squirrel_count\ngrey_squirrel_count = len(df[df['Primary Fur Color']=='Gray'])\nprint(grey_squirrel_count)\ncinnamon_squirrel_count = len(df[df['Primary Fur Color']=='Cinnamon'])\nprint(cinnamon_squirrel_count)\nblack_squirrel_count = len(df[df['Primary Fur Color']=='Black'])\nprint(black_squirrel_count)\n\n# ---\n","repo_name":"abhijeetpandit7/Python-Bootcamp","sub_path":"Day-25-IndiaMapQuiz/Pandas Intro.ipynb","file_name":"Pandas Intro.ipynb","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"37915362655","text":"# +\nimport os\nimport cv2\nfrom natsort import natsorted\n\n\ndef make_video(image_folder):\n # Get a list of image filenames sorted alphabetically\n image_filenames = natsorted(os.listdir(image_folder))\n print(image_filenames)\n\n # Get the dimensions of the first image (assuming all images have the same dimensions)\n first_image = cv2.imread(os.path.join(image_folder, image_filenames[0]))\n height, width, layers = first_image.shape\n\n # Define the codec and create a VideoWriter object\n video_filename = f'{image_folder}output_video.mp4'\n fourcc = cv2.VideoWriter_fourcc(*'mp4v') # You can change the codec as needed\n video = cv2.VideoWriter(video_filename, fourcc, 10, (width, height))\n\n # Loop through the sorted image filenames and add frames to the video\n for image_filename in image_filenames:\n image_path = os.path.join(image_folder, image_filename)\n frame = cv2.imread(image_path)\n video.write(frame)\n\n # Release the VideoWriter and close the video file\n video.release()\n\n print(f\"Video '{video_filename}' created successfully.\")\n\n\n# +\nimport os\nfrom natsort import natsorted\nimport subprocess\nimport imageio\n\nimport os\nos.environ[\"IMAGEIO_FFMPEG_EXE\"] = \"/Users/sherryyang/anaconda3/envs/omnipose/lib/python3.10/site-packages/imageio_ffmpeg/binaries/ffmpeg-osx64-v4.4\"\n\n\ndef make_video(image_folder):\n # Get a list of image filenames sorted alphabetically\n image_filenames = natsorted(os.listdir(image_folder))\n print(image_filenames)\n\n # Ensure they're TIFF images\n tif_files = [f for f in image_filenames if f.endswith('.tif')]\n\n # FFmpeg command to create a high-quality MP4 video\n # This uses the libx264 codec with veryslow preset and crf 0 (lossless compression)\n cmd = [\n 'ffmpeg',\n '-framerate', '10', # 10 frames per second\n '-i', os.path.join(image_folder, '%06d.tif'), # Assumes the images are named sequentially, like 000001.tif, 000002.tif, etc.\n '-c:v', 'libx264',\n '-preset', 'veryslow',\n '-crf', '0',\n os.path.join(image_folder, 'output_video.mp4')\n ]\n\n subprocess.run(cmd)\n\n print(f\"Video created successfully in {os.path.join(image_folder, 'output_video.mp4')}\")\n\n# Example usage:\n\n\n\n# +\nfrom PIL import Image\nimport os\n\n\ndef make_merged_image():\n # Get a list of image filenames sorted alphabetically\n image_filenames = sorted(os.listdir(image_folder))\n\n # Open the first image to get the size\n base_image = Image.open(os.path.join(image_folder, image_filenames[0]))\n width, height = base_image.size\n\n # Create a new image with RGBA mode (allows transparency)\n merged_image = Image.new('RGBA', (width, height), (0, 0, 0, 0))\n\n # Loop through the sorted image filenames and paste each image on top of the merged image\n for image_filename in image_filenames:\n image_path = os.path.join(image_folder, image_filename)\n image = Image.open(image_path)\n merged_image = Image.alpha_composite(merged_image, image)\n\n # Save the final overlapped image\n merged_image.save('merged_image.png')\n\n print(\"Merged image created successfully.\")\n\n\n# -\n\nmake_video('/Users/sherryyang/Documents/wiggins-lab/data/1024/xy5/phase/video')\n\nmake_video('./output/')\n\nmake_video('./output/')\n\n\n","repo_name":"yyang35/super-segger-tracker","sub_path":"[tool]_make_video_etc.ipynb","file_name":"[tool]_make_video_etc.ipynb","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"39936300554","text":"# +\nfrom exbook import book as eb\n\neb[21]\n\n\n# +\ndef value_count(ls):\n dict = {}\n for value in ls:\n if value in dict:\n dict[value]+=1\n else: \n dict[value] = 1\n return dict\n\neb[21].check(value_count)\n","repo_name":"car155/DAO2702","sub_path":"Question 22.ipynb","file_name":"Question 22.ipynb","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"7604203252","text":"# + [markdown] id=\"34EuFqEbQ99w\"\n# ## Conecciones con pandas y MySQL\n#\n# Generalmente en las organizaciones los datos se encuentran en Bases de datos que pueden ser estructuradas (MySQL, MariaDB, SQL Server, PostgreSQL, etc) y no estructuradas (MongoDB, Dynamo DB, etc), en la sesion de hoy trabajaremos con Conecciones a MySQL\n\n# + [markdown] id=\"3hiQ70AKQ99_\"\n# \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"DAtyt3O7Q9-A\" outputId=\"73df475d-5768-4474-fb90-80d5136844cd\"\n# !pip install mysql-connector-python\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"XOZpJ43gQ9-G\" outputId=\"23b475ce-f010-493f-9b8f-ad6e23d11031\"\nimport mysql.connector\nimport pandas as pd\n# Define the connection string (assuming a typical localhost setup for demonstration)\nconnection_string = {\n 'user' : 'doadmin',\n 'password' : 'AVNS_sAMuAiwTX_UzEy6cR63',\n 'host' : 'db-ro-mysql-nyc1-25804-do-user-13295890-0.b.db.ondigitalocean.com',\n 'port' : 25060,\n 'database' :'defaultdb'\n}\n\n# Establish the connection\nconnection = mysql.connector.connect(**connection_string)\n\n# Check if connection is established\nif connection.is_connected():\n print(\"Connected to MySQL server\")\n df = pd.read_sql(\"SELECT*FROM ejercicio1\",connection)\n connection.close()\nelse:\n print(\"Failed to connect\")\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 423} id=\"LLvBeyXzTAyd\" outputId=\"762ee42d-202e-4b11-a57c-375d4c0ebb03\"\ndf\ndf.drop('ID_Venta', axis = 1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 229} id=\"Vh4RunxQVrzf\" outputId=\"e744ad96-a5a3-410b-aafb-6f8100383b4e\"\ndf.groupby(\"Hora_Dia\").sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"n6FxJNk9XK4p\" outputId=\"43fb2b30-7ca9-4bc5-f071-e85fc68a7cf5\"\ncategorias = ['Electrónica', 'Ropa', 'Alimentos', 'Muebles']\nhora_dia = ['Mañana', 'Tarde', 'Noche']\nn = 100\ndf = pd.DataFrame({\n 'ID_Venta': np.arange(1, n + 1),\n 'Categoria': np.random.choice(categorias, n),\n 'Hora_Dia': np.random.choice(hora_dia, n),\n 'Unidades_Vendidas': np.random.randint(1, 20, n),\n 'Ingresos': np.random.uniform(100, 500, n)\n})\ndf.head()\n","repo_name":"DanAndCastRod/python_DataScience","sub_path":"session4_2_mysql_conect.ipynb","file_name":"session4_2_mysql_conect.ipynb","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"41"} +{"seq_id":"2407080293","text":"# +\nimport os\nimport tarfile\nimport urllib.request\nimport pandas as pd\n\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml2/master/\"\nHOUSING_PATH = os.path.join(\"datasets\", \"housing\")\nHOUSING_URL = DOWNLOAD_ROOT + \"datasets/housing/housing.tgz\"\n\ndef fetch_housing_data(housing_url=HOUSING_URL,housing_path=HOUSING_PATH):\n os.makedirs(housing_path,exist_ok=True)\n tgz_path = os.path.join(housing_path,\"housing.tgz\")\n urllib.request.urlretrieve(housing_url, tgz_path)\n housing_tgz = tarfile.open(tgz_path)\n housing_tgz.extractall(path=housing_path)\n housing_tgz.close()\n\n\ndef load_housing_data(housing_path=HOUSING_PATH):\n csv_path = os.path.join(housing_path,\"housing.csv\")\n return pd.read_csv(csv_path)\n\n\n# +\n#running the functions to fetch and load data\nfetch_housing_data()\nhousing = load_housing_data()\n\n#getting the dataframe information:\n\nprint(housing.head())\nprint(housing.info())\nprint(housing.describe())\nprint(housing[\"ocean_proximity\"].value_counts())\n# -\n\n#data viusualization:\nimport matplotlib.pyplot as plt\nhousing.hist(bins=50, figsize=(20,15))\nplt.show()\n\n#spliting the data into training and testing sets:\nfrom sklearn.model_selection import train_test_split\ntrain_set,test_set=train_test_split(housing,test_size=0.25,random_state=42)\n\n#defining the income categories:\nimport numpy as np\nhousing[\"income_cat\"]= pd.cut(housing[\"median_income\"],bins=[0.,1.5,3,4.5,6.,np.inf],labels=[1,2,3,4,5])\nhousing[\"income_cat\"].hist()\nplt.show()\n\n# +\nfrom sklearn.model_selection import StratifiedShuffleSplit\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\nfor train_index, test_index in split.split(housing,housing[\"income_cat\"]):\n strat_train_set=housing.loc[train_index]\n strat_test_set=housing.loc[test_index]\n\n#droping the income cat columns of the set:\nfor set_ in (strat_train_set,strat_test_set):\n set_.drop(\"income_cat\", axis=1, inplace=True)\n# -\n\n#exploring the data through visualization:\nhousing=strat_train_set.copy()\nhousing.plot(kind=\"scatter\",x=\"longitude\",y=\"latitude\",alpha=0.1)\n\n#exploring the data through visualization:\nhousing=strat_train_set.copy()\nhousing.plot(kind=\"scatter\",x=\"longitude\",y=\"latitude\",alpha=0.4,s=housing[\"population\"]/100,label=\"population\",figsize=(10,7),c=\"median_house_value\",cmap=plt.get_cmap(\"jet\"))\nplt.legend()\nplt.show()\n\n# +\n#explorign the data through corelation matrix:\ncorr_matrix = housing.corr()\n\nhousing.head()\n\nprint(list(enumerate(housing.keys())))\n\nprint(corr_matrix[\"median_house_value\"].sort_values(ascending=False))\n\nplt.matshow(housing.corr())\nplt.show()\n# -\n\n#explorign the data through correlation plots:\nfrom pandas.plotting import scatter_matrix\nattrbutes=['median_house_value','median_income','total_rooms','housing_median_age']\nscatter_matrix(housing[attrbutes],figsize=(12,8))\n\n\nprint(list(enumerate(housing.keys())))\n\n# +\n#defining new attributes for the dataset:\nhousing[\"rooms_per_household\"]=housing[\"total_rooms\"]/housing[\"households\"]\nhousing[\"bedrooms_per_room\"]=housing[\"total_bedrooms\"]/housing[\"total_rooms\"]\nhousing[\"population_per_household\"]=housing[\"population\"]/housing[\"households\"]\n\ncorr_matrix = housing.corr()\nprint(corr_matrix[\"median_house_value\"].sort_values(ascending=False))\n\nplt.matshow(housing.corr())\nplt.show()\n\n# +\n#preparing the data for machine learning implementation:\n#clean start:\nhousing = strat_train_set.drop(\"median_house_value\",axis=1)\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n\n#replaceing the NaN values with the calculated mean.\n'''\nmedian = housing[\"total_bedrooms\"].median()\nhousing[\"total_bedrooms\"].fillna(median,inplace=True)\n'''\nfrom sklearn.impute import SimpleImputer\n\nimputer = SimpleImputer(strategy=\"mean\")\n\n#only numerical data:\nhousing_num = housing.drop(\"ocean_proximity\",axis=1)\nimputer.fit(housing_num)\n#creating final traingin data:\nX = imputer.transform(housing_num)\nhousing_tr=pd.DataFrame(X,columns=housing_num.columns,index=housing_num.index)\n\nprint(X)\nprint(housing_tr)\n# -\n\n#transfering categorical variables into numeric description: - machine learning algoritms dont work on text they work on vectors/tensors\nfrom sklearn.preprocessing import OneHotEncoder\ncat_econder = OneHotEncoder()\nhousing_cat=housing[[\"ocean_proximity\"]]\nhousing_cat_1hot = cat_econder.fit_transform(housing_cat)\n#print(housing_cat_1hot)\nprint(housing_cat_1hot.toarray())\nprint(cat_econder.categories_)\n\n#reminder on what is housing data:\nprint(type(housing)) #a DataFrame\nprint(housing.head())\nprint(housing.keys())\nprint(housing.values)\n\n#creating custom transformers:\nfrom sklearn.base import BaseEstimator, TransformerMixin\n#defining indexes of attibutes in the dataset:\nrooms_ix, bedrooms_ix, population_ix,households_ix= 3,4,5,6\n#defining the class that inherits from sklearn transformers to enable adding parameters to the dataset:\nclass CombinedAttibutesAdder(BaseEstimator,TransformerMixin):\n def __init__(self,add_bedrooms_per_room=True):\n self.add_bedrooms_per_room = add_bedrooms_per_room\n def fit(self,X,y=None):\n return self\n def transform(self,X):\n rooms_per_household=X[:,rooms_ix]/X[:,households_ix]\n population_per_household=X[:,population_ix]/X[:,households_ix]\n if self.add_bedrooms_per_room:\n bedrooms_per_room=X[:,bedrooms_ix]/X[:,rooms_ix]\n return np.c_[X,rooms_per_household,population_per_household,bedrooms_per_room]\n else:\n return np.c_[X,rooms_per_household,population_per_household]\n#read up on what np.c_ does! - arrays concatination along axis.\n'''\nnp.c_[np.array([1,2,3]), np.array([4,5,6])]\narray([[1, 4],\n [2, 5],\n [3, 6]])\n'''\nattr_adder=CombinedAttibutesAdder(add_bedrooms_per_room=False)\nhousing_extra_attirbs = attr_adder.transform(housing.values)\n\n# +\n#feature scaling for optimal learning experience :)\n#STANDARDIZATION & MIN-MAX SCALING as two basica algorythms:\n\n#sklearn PIPELINES: - execution of data transfromations in a tipical order:\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.impute import SimpleImputer\n\nnum_pipeline = Pipeline([\n #imputer allows to clean the data form NANs and replace them with median values:\n (\"imputer\",SimpleImputer(strategy=\"median\")),\n #attribs_adder has been defined in a previous block as a class that allows to extend the attributes:\n (\"attribs_adder\",CombinedAttibutesAdder()),\n #std_scaler standardizes the data:\n (\"std_scaler\",StandardScaler()),\n])\n\n#learning ready data:\nhousing_num_tr = num_pipeline.fit_transform(housing_num)\n\n\n# +\n#Column transformer - allows to perform transformations of a pipeline column by column and distinguish numeriacal and cathegorical data:\nfrom sklearn.compose import ColumnTransformer\n\n\"\"\"\nprint(housing_num)\nprint(list(housing_num))\n\"\"\"\nnum_attribs=list(housing_num)\ncat_attribs=[\"ocean_proximity\"]\n\n#combined pipeline that applies different transformations based on the attibutes of the datafarme:\nfull_pipeline = ColumnTransformer([\n (\"num\",num_pipeline,num_attribs),\n (\"cat\",OneHotEncoder(),cat_attribs),\n])\n\nhousing_prepared=full_pipeline.fit_transform(housing)\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n# -\n\nprint(housing)\n\n# +\n#choosing the model and training:\n#linear regression model:\n\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\nlin_reg.fit(housing_prepared,housing_labels)\n#testing the model:\nsome_data = housing.iloc[:5]\nsome_labels = housing_labels.iloc[:5]\nsome_data_prepared = housing_prepared[:5]\n\nprint(\"Predictions: \",lin_reg.predict(some_data_prepared))\nprint(\"Actual Values: \",list(some_labels))\nprint(lin_reg.score(some_data_prepared,some_labels))\n\n#model underfitting\n\n# +\n#choosing the model and training:\n#decision tree model:\n\nfrom sklearn.tree import DecisionTreeRegressor\ntree_reg = DecisionTreeRegressor()\ntree_reg.fit(housing_prepared,housing_labels)\n#testing the model:\nsome_data = housing.iloc[:5]\nsome_labels = housing_labels.iloc[:5]\nsome_data_prepared = housing_prepared[:5]\n\nprint(\"Predictions: \",tree_reg.predict(some_data_prepared))\nprint(\"Actual Values: \",list(some_labels))\nprint(tree_reg.score(some_data_prepared,some_labels))\n\n#model overfitting\n\n# +\n#model cross validation for more precise understanding of performance:\n\nfrom sklearn.model_selection import cross_val_score\n\nscores = cross_val_score(tree_reg,housing_prepared,housing_labels,scoring=\"neg_mean_squared_error\",cv=10)\ntree_rmse_scores = np.sqrt(-scores)\n\n\n# +\ndef display_scores(scores):\n print(\"Scores: \",scores)\n print(\"Mean :\",scores.mean())\n print(\"Standard Deviation :\",scores.std())\n\ndisplay_scores(tree_rmse_scores)\n# -\n\nlin_scores = cross_val_score(lin_reg,housing_prepared,housing_labels,scoring=\"neg_mean_squared_error\",cv=10)\nlin_rmse_scores = np.sqrt(-lin_scores)\n\n\n# +\ndef display_scores(scores):\n print(\"Scores: \",scores)\n print(\"Mean :\",scores.mean())\n print(\"Standard Deviation :\",scores.std())\n\ndisplay_scores(lin_rmse_scores)\n\n# +\nfrom sklearn.ensemble import RandomForestRegressor\nforest_reg = RandomForestRegressor()\nforest_reg.fit(housing_prepared,housing_labels)\n#testing the model:\nsome_data = housing.iloc[:5]\nsome_labels = housing_labels.iloc[:5]\nsome_data_prepared = housing_prepared[:5]\n\nprint(\"Predictions: \",forest_reg.predict(some_data_prepared))\nprint(\"Actual Values: \",list(some_labels))\nprint(tree_reg.score(some_data_prepared,some_labels))\n\nforest_scores = cross_val_score(forest_reg,housing_prepared,housing_labels,scoring=\"neg_mean_squared_error\",cv=10)\nforest_rmse_scores = np.sqrt(-forest_scores)\n\ndef display_scores(scores):\n print(\"Scores: \",scores)\n print(\"Mean :\",scores.mean())\n print(\"Standard Deviation :\",scores.std())\n\ndisplay_scores(forest_rmse_scores)\n\n# +\n#Finetuning the models:\n\n#01.Grid search\n#02.Randomize search\n#03.Ensemble methods\n\nfrom sklearn.model_selection import GridSearchCV\n\nparam_grid = [\n # try 12 (3×4) combinations of hyperparameters\n {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},\n # then try 6 (2×3) combinations with bootstrap set as False\n {'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]},\n ]\n\nforest_reg = RandomForestRegressor(random_state=42)\n# train across 5 folds, that's a total of (12+6)*5=90 rounds of training \ngrid_search = GridSearchCV(forest_reg, param_grid, cv=5,\n scoring='neg_mean_squared_error',\n return_train_score=True)\ngrid_search.fit(housing_prepared, housing_labels)\n\n# -\n\ngrid_search.best_params_\ngrid_search.best_estimator_\n\n# +\ncvres = grid_search.cv_results_\nfor mean_score, params in zip(cvres[\"mean_test_score\"], cvres[\"params\"]):\n print(np.sqrt(-mean_score), params)\n \npd.DataFrame(grid_search.cv_results_)\n\n# +\nfeature_importances = grid_search.best_estimator_.feature_importances_\nfeature_importances\n\nextra_attribs = [\"rooms_per_hhold\", \"pop_per_hhold\", \"bedrooms_per_room\"]\n#cat_encoder = cat_pipeline.named_steps[\"cat_encoder\"] # old solution\ncat_encoder = full_pipeline.named_transformers_[\"cat\"]\ncat_one_hot_attribs = list(cat_encoder.categories_[0])\nattributes = num_attribs + extra_attribs + cat_one_hot_attribs\nsorted(zip(feature_importances, attributes), reverse=True)\n\n# +\nfrom sklearn.metrics import mean_squared_error\n\nfinal_model = grid_search.best_estimator_\nhousing = strat_train_set.drop(\"median_house_value\",axis=1)\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n\nhousing_prepared=full_pipeline.fit_transform(housing)\n\nhousing_test = strat_test_set.drop(\"median_house_value\",axis=1)\nhousing_test_lables = strat_test_set[\"median_house_value\"].copy()\n\nhousing_test_prepared=full_pipeline.fit_transform(housing)\n\nfinal_predictions = final_model.predict(housing_test_prepared)\n\nfinal_score = final_model.score(housing_test_prepared,housing_labels)\n\nprint(final_score)\n","repo_name":"baczkowskij/Machine-Learning-With-Scikit-Keras-Tensorflow","sub_path":"Chapter_02_End_to_End_Machine_Learning_Project/End_to_End_Machine_Learning_Project.ipynb","file_name":"End_to_End_Machine_Learning_Project.ipynb","file_ext":"py","file_size_in_byte":11907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"41"} +{"seq_id":"16041990807","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"6LnkP-PWvBN-\"\n# # 7 - Document Classification Using RNN\n\n# + [markdown] id=\"q5flqwAJv99t\"\n# References:\n# - [RNN with keras](https://www.tensorflow.org/guide/keras/rnn)\n# - [Text Classification using RNN](https://www.tensorflow.org/text/tutorials/text_classification_rnn)\n\n# + [markdown] id=\"mJ3vWYxKw9O-\"\n# ## Dataset\n\n# + [markdown] id=\"B-0rpdNnx_Pf\"\n# - Dataset Used : Imdb Movie Review dataset\n# - Dataset Url : https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n# - Dataset Home Page: https://ai.stanford.edu/~amaas/data/sentiment\n\n# + [markdown] id=\"Z3vhCm5_bdIB\"\n# ## Importing the required modules\n\n# + id=\"Zo86H7NqbhHx\"\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport re\nimport shutil\nimport string\n\n# + [markdown] id=\"recoIGKAgIcF\"\n# ## Dataset\n\n# + [markdown] id=\"lt_oMUN-cBb2\"\n# ### Downloading the dataset \n\n# + [markdown] id=\"X5-Dng2ucPtq\"\n# - Dataset: Imdb Large Movie Review Dataset v1.0 \n# - Home Page : https://ai.stanford.edu/~amaas/data/sentiment/\n# - Dataset URL : https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n\n# + id=\"y5lbithLcRSR\"\nurl = \"https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\"\n\ndataset = tf.keras.utils.get_file(\n \"aclImdb_v1\", url,\n untar=True, cache_dir='.',\n cache_subdir=''\n)\n\ndataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb')\n\n\n# + [markdown] id=\"ZQqwkhlcc4Cd\"\n# ### Exploring the dataset directory\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"WdsJr12zc6Rm\" outputId=\"1277e0f8-d4b7-4725-92f2-aee85ac94e57\"\nos.listdir(dataset_dir)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"esSEyuDCdl5s\" outputId=\"2b64247c-0b84-40a8-84b2-7c8441c96c4b\"\ntrain_dir = os.path.join(dataset_dir,\"train\")\nos.listdir(train_dir)\n\n# + [markdown] id=\"JrV6GAMseC2V\"\n# Here `pos` and `neg` are the folders containing positive and negative reviews.\n#\n#\n\n# + [markdown] id=\"pwTuaZ7MgQi7\"\n# ### Removing unwanted folders from training folder\n\n# + [markdown] id=\"QlVXlhOAgYpT\"\n# `unsup` contains data for unsupervised learning which is not needed for this exercise. so we remove that using `shutil.rmtree()`\n\n# + id=\"K8zcOZdpd7ki\"\nshutil.rmtree(os.path.join(train_dir,\"unsup\"))\n\n# + [markdown] id=\"jZ2d_5-6e6nh\"\n# ### Loading the dataset\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"LQk9TCWUfPuz\" outputId=\"2b7eeb40-27e3-4752-fcc4-eb6540a9e03d\"\nbatch_size = 128\nseed = 42\n\nraw_train_ds = tf.keras.utils.text_dataset_from_directory(\n 'aclImdb/train', \n batch_size=batch_size, \n validation_split=0.2, \n subset='training', \n seed=seed)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GQvx6SI9g1rR\" outputId=\"1296445a-c3db-4b7f-abe2-8c9331069b44\"\nraw_val_ds = tf.keras.utils.text_dataset_from_directory(\n 'aclImdb/train', \n batch_size=batch_size, \n validation_split=0.2, \n subset='validation', \n seed=seed)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"LrrWVRE4g2OB\" outputId=\"fa868dda-13c2-4dc5-e0fb-9e1f1176805a\"\nraw_test_ds = tf.keras.utils.text_dataset_from_directory(\n 'aclImdb/test', \n batch_size=batch_size)\n\n# + id=\"pkkgKzkop62e\"\nAUTOTUNE = tf.data.AUTOTUNE\n\ntrain_ds = raw_train_ds.cache().prefetch(buffer_size=AUTOTUNE)\nval_ds = raw_val_ds.cache().prefetch(buffer_size=AUTOTUNE)\ntest_ds = raw_test_ds.cache().prefetch(buffer_size=AUTOTUNE)\n\n\n# + [markdown] id=\"ofoJ1-yCgDbe\"\n# ## Preprocessing the text\n\n# + [markdown] id=\"XOEK9hx7hmAW\"\n# ### Standardization Function\n\n# + id=\"OVdcJFvuhpj1\"\ndef custom_standardization(input_data):\n lowercase = tf.strings.lower(input_data)\n stripped_html = tf.strings.regex_replace(lowercase, '
', ' ')\n return tf.strings.regex_replace(\n stripped_html,\n f'[{re.escape(string.punctuation)}]',\n ''\n )\n\n\n# + [markdown] id=\"7Lm1d8EviUoo\"\n# ### Text Vectorization\n\n# + [markdown] id=\"KXAF9X2WijpN\"\n# - Create a `TextVectorization` layer with the `custom_standardization` function\n# - Adapt it with the training data\n# - Create a function that applies vectorization only to the text in the dataset so that it can be mapped to the dataset\n#\n\n# + id=\"lFGWSE2MiXkg\"\nmax_features = 10000\nsequence_length = 250\n\nvectorize_layer = tf.keras.layers.TextVectorization(\n standardize=custom_standardization,\n max_tokens=max_features,\n output_mode='int',\n output_sequence_length=sequence_length)\nvectorize_layer.adapt(raw_train_ds.map(lambda x, y: x))\n\n# + [markdown] id=\"J94G16x38a1Y\"\n# ## Creating the Model\n\n# + id=\"oSUAOVED169l\"\nmodel = tf.keras.Sequential([\n vectorize_layer,\n tf.keras.layers.Embedding(\n input_dim=len(vectorize_layer.get_vocabulary()),\n output_dim=64,\n # Use masking to handle the variable sequence lengths\n mask_zero=True),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(1)\n])\n\n\n# + id=\"mxCo7RO36HHG\"\nmodel.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n optimizer=tf.keras.optimizers.Adam(1e-4),\n metrics=['accuracy'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Jh4UlTF964nE\" outputId=\"dd9fd815-5c5a-42d2-eb15-bc15398a52b3\"\nmodel.summary()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-t5s_q0w66BP\" outputId=\"930bee4e-6a1e-488a-cb7a-fad25030ddc8\"\nhistory = model.fit(train_ds, epochs=10,\n validation_data=val_ds,\n validation_steps=30)\n\n\n# + id=\"WH9pOKqHwtDK\"\ndef plot_graphs(history, metric):\n plt.plot(history.history[metric])\n plt.plot(history.history['val_'+metric], '')\n plt.xlabel(\"Epochs\")\n plt.ylabel(metric)\n plt.legend([metric, 'val_'+metric])\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 338} id=\"1a5q4Y_D7Opr\" outputId=\"4fdc8fba-49a7-440b-a252-e7df18f7e26d\"\nplt.figure(figsize=(10, 5))\nplt.subplot(1, 2, 1)\nplot_graphs(history, 'accuracy')\nplt.ylim(None, 1)\nplt.subplot(1, 2, 2)\nplot_graphs(history, 'loss')\nplt.ylim(0, None)\nplt.show()\n\n\n# + [markdown] id=\"5fZ0xiupCGLP\"\n# ## Evaluating the model\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"dGfyHDb5BkeN\" outputId=\"fdaed3b2-c6dd-4f1e-b29b-1285bdbd7728\"\ntest_loss, test_acc = model.evaluate(test_ds)\n\nprint('Test Loss:', test_loss)\nprint('Test Accuracy:', test_acc)\n\n\n# + [markdown] id=\"UCi0lHDNEXVt\"\n# ## Sample Predictions\n\n# + id=\"JH_waIzUCVd4\"\nimport numpy as np\n\n# + id=\"tIoxho8KCKCc\"\nsamples = np.array([\n 'The movie was awesome, wonderful and amazing.',\n \"The Movies is the bad and waste of time.\" \n])\npredictions = model.predict(samples)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"aAdd711TCYKT\" outputId=\"1be28a5e-8634-4cfc-d17c-334bd6790a3b\"\npredictions\n","repo_name":"livinNector/deep-learning-tools-lab","sub_path":"7 - Sentence Classification Using RNN.ipynb","file_name":"7 - Sentence Classification Using RNN.ipynb","file_ext":"py","file_size_in_byte":7133,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"41"} +{"seq_id":"3454819154","text":"# +\n#while loop\n# -\n\nx=0\nwhile x < 5 :\n print (f'the current value of x is {x}')\n x+=1\n\nx=0 \nwhile x<5 :\n print (x)\n x +=1\n\nx= 0\nwhile x<5:\n print (x)\n x+=1\nelse:\n print ('x is greater than 5')\n\nx=0\nwhile x<5:\n if x == 2:\n break\n print (x)\n x += 1\n\nmystring = 'sammy'\nfor letter in mystring:\n if letter == 'a' :\n continue\n print (letter)\n\nfor num in range (10):\n print (num)\n\nfor num in range(0,11,2):\n print (num)\n\nlist(range(0,11,2))\n\nlist(range(0,11))\n\nlist(range(0,11,2)) \n\n\n","repo_name":"SidUsman/learning-python","sub_path":"note-books/while loop.ipynb","file_name":"while loop.ipynb","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"41"} +{"seq_id":"8213100968","text":"# # Getting Financial Data - Google Finance\n\n# ### Introduction:\n#\n# This time you will get data from a website.\n#\n#\n# ### Step 1. Import the necessary libraries\n\nimport pandas as pd\nimport numpy as np\nimport datetime as datetime\nfrom pandas_datareader import data, wb\n\n\n# ### Step 2. Create your time range (start and end variables). The start date should be 01/01/2015 and the end should today (whatever your today is)\n\nstart=datetime.datetime(2015,1,1)\nend=datetime.datetime.today()\nstart ,end\n\n\n# ### Step 3. Select the Apple, Tesla, Twitter, IBM, LinkedIn stocks symbols and assign them to a variable called stocks\n\nstocks=['AAPL','TSLA','IBM','LNKD']\n\n# ### Step 4. Read the data from google, assign to df and print it\n\ndf=data.DataReader(stocks,'google',start,end)\n\n\n# ### Step 5. What is the type of structure of df ?\n\ntype(df)\n\n# ### Step 6. Print all the Items axis values\n# #### To learn more about the Panel structure go to [documentation](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#panel) \n\ndf.items\n\n# ### Step 7. Good, now we know the data avaiable. Create a dataFrame called vol, with the Volume values.\n\nvol=df['Volume']\nvol\n\n# ### Step 8. Aggregate the data of Volume to weekly\n# #### Hint: Be careful to not sum data from the same week of 2015 and other years.\n\nvol['Week']=vol.index.week\nvol['Year']=vol.index.year\nweek=vol.groupby(['Week','Year']).sum()\nweek.head()\n\n# ### Step 9. Find all the volume traded in the year of 2015\n\n#vol.drop('Week',axis=1,inplace=True)\nvol['Year']=vol.index.year\nvol[vol.Year==2015].sum()\n\n# ### BONUS: Create your own question and answer it.\n\n\n","repo_name":"kaushiks90/Pandas-Exercise","sub_path":"Code/.ipynb_checkpoints/Solution24-checkpoint.ipynb","file_name":"Solution24-checkpoint.ipynb","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"10187369980","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"Ov26gDy-UXl0\"\nimport numpy as np\nimport keras\nimport sys\nfrom keras.models import Model\nfrom keras.utils import plot_model\nfrom keras.models import load_model\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom random import randint\nimport imageio\nimport argparse\nfrom skimage.util.shape import view_as_blocks\n\n\n\n# + id=\"t-hRvm_tUicH\"\nmodel_hide=load_model(\"/content/drive/MyDrive/models_mix/hide2.h5\",compile=False)\n\n\n# + id=\"GVM1OZbpU5OO\"\ndef normalize_batch(imgs):\n '''Performs channel-wise z-score normalization'''\n\n return (imgs - np.array([0.485, 0.456, 0.406])) /np.array([0.229, 0.224, 0.225])\n\n# Denormalize outputs\ndef denormalize_batch(imgs,should_clip=True):\n imgs= (imgs * np.array([0.229, 0.224, 0.225])) + np.array([0.485, 0.456, 0.406])\n \n if should_clip:\n imgs= np.clip(imgs,0,1)\n return imgs\n\n# Custom block shuffling\ndef shuffle(im, inverse = False):\n \n # Configure block size, rows and columns\n blk_size=56\n rows=np.uint8(img.shape[0]/blk_size)\n cols=np.uint8(img.shape[1]/blk_size)\n\n # Create a block view on image\n img_blks=view_as_blocks(im,block_shape=(blk_size,blk_size,3)).squeeze()\n img_shuff=np.zeros((img.shape[0],img.shape[1],3),dtype=np.uint8)\n\n # Secret key maps\n map={0:2, 1:0, 2:3, 3:1}\n inv_map = {v: k for k, v in map.items()}\n\n # Perform block shuffling\n for i in range(0,rows):\n for j in range(0,cols):\n x,y = i*blk_size, j*blk_size\n if(inverse):\n img_shuff[x:x+blk_size, y:y+blk_size] = img_blks[inv_map[i],inv_map[j]]\n else:\n img_shuff[x:x+blk_size, y:y+blk_size] = img_blks[map[i],map[j]]\n \n return img_shuff\n\n\n# + id=\"lwx-spPlVITZ\"\nsecretin = np.array(Image.open(\"/content/drive/MyDrive/secret mix test/9031426R.png\").convert('RGB').resize((224,224))).reshape(1,224,224,3)/255\ncoverin = np.array(Image.open(\"/content/drive/MyDrive/new cover_test/00114.jpg\").convert('RGB').resize((224,224))).reshape(1,224,224,3)/255\n\n# + id=\"nHz5_X_8XQGe\"\ncoverout=model_hide.predict([normalize_batch(secretin),normalize_batch(coverin)])\n\n# + id=\"ybZTRry9Xei7\"\ncoverout = denormalize_batch(coverout)\ncoverout=np.squeeze(coverout)*255.0\ncoverout=np.uint8(coverout)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 286} id=\"Byvf6u2mXk4Z\" outputId=\"8cd4d52a-df02-4135-9a7c-739553d5bcc6\"\nimageio.imsave('container3.png',coverout)\nplt.imshow(coverout)\n","repo_name":"Amoghkori/Deep-Learning-Projects","sub_path":"image_hide.ipynb","file_name":"image_hide.ipynb","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"32572094603","text":"# + id=\"lVAK2Z1dNB5H\"\n#SVM Classification\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# from sklearn import svm\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV,RandomizedSearchCV\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.model_selection import train_test_split, cross_val_score\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 487} id=\"_H-PYh1OJco0\" outputId=\"b729e697-ab8c-4fdf-977b-694351b66c6f\"\n#import dataset\nforest=pd.read_csv('/content/forestfires.csv')\nforest\n\n# + [markdown] id=\"7sM_U0lFMBZD\"\n# EDA\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 299} id=\"51utfiXiJr-l\" outputId=\"248c95f9-80db-4937-bf49-9f1c19dc4e3e\"\nforest.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 393} id=\"bdXZqzjoMHzw\" outputId=\"7dae874b-0d94-4f4c-e9cb-9226a72f033f\"\nforest.describe()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Fo_Lv4ceMQVi\" outputId=\"b6f6c48d-806d-4ee8-b5fc-e120bf3eaca6\"\nforest.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pMuQJNc9MWMs\" outputId=\"a1cf685a-b17c-4e0f-a626-77acdf04883c\"\nforest.isnull().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 393} id=\"A_xxFnKfNTTj\" outputId=\"aa0105af-5929-4d80-c7c8-b7807ceff728\"\nforest[forest.duplicated()]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cBhuF2eZpACm\" outputId=\"6bb0b655-4421-4aeb-d9fd-46153d8eeb8c\"\nforest.pop('month') #pop is used to remove coloumns\nforest.pop('day')\n\n# + id=\"hw3P50GRONMU\"\nforest1=forest.drop_duplicates() #to deleting duplicate record\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 487} id=\"eaCz_bs4OY5d\" outputId=\"ae0a0b12-59fd-4328-f6a7-6044c4cf4a7a\"\nforest1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"uoSbciRITpQD\" outputId=\"49600ba2-54f0-422b-a19f-2a4ac82e3ce7\"\nforest1['size_category'].value_counts()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 471} id=\"b53ToeNJQr3q\" outputId=\"6c94d237-d45a-4642-9baa-fb93b9549e86\"\nforest1['size_category'].value_counts().plot.bar()\n\n# + id=\"x5mPTEQtRwFo\"\n#From above graph we can say most of forest fires where in small quantity \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"ntiSoibpcHO4\" outputId=\"b1b41add-5fbc-49aa-fade-aa7eb138c1eb\"\n# Drawing boxplot for indepent variables with continuous values\ncols = ['FFMC', 'DMC', 'DC', 'ISI', 'temp', 'RH', 'wind', 'area']\nplt.figure(figsize=(10,15))\n\ni=1\nfor col in cols:\n plt.subplot(4,2,i)\n sns.boxplot(y=col, data=forest,width=0.2)\n i+=1\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 484} id=\"WhMl3mdeZ4Wc\" outputId=\"ed891bd8-8ecb-4dc2-d7d3-5fb5ea231d17\"\npd.crosstab(forest['size_category'],forest['month']).mean().plot(kind='bar')\n\n# + id=\"BDjeUfcnaioS\"\n#above plot we conclude that majority of fire occurs in month August & Sep\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 484} id=\"LaquWoDCdzbN\" outputId=\"2d3ffeee-2a6e-4efc-e1d7-3eb7bed23b97\"\npd.crosstab(forest['size_category'],forest['day']).mean().plot(kind='bar')\n\n# + id=\"LiSjFDJjfjUE\"\n# For Sunday & Friday have recored most cases of fire\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 487} id=\"bSY86ntYiU-j\" outputId=\"fe679a72-97ea-4774-d7fc-4519401bda25\"\nforest1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"s8JVSjNxgXOW\" outputId=\"274f0e6a-73ca-4601-8083-68bb6ae3deca\"\n#displaying pairplot to check relationship\nsns.pairplot(forest1,x_vars=['FFMC', 'DMC', 'DC', 'ISI', 'temp', 'RH', 'wind', 'area'],\n y_vars=['FFMC', 'DMC', 'DC', 'ISI', 'temp', 'RH', 'wind', 'area'],hue='size_category',\n kind='reg',diag_kind='kde')\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 449} id=\"4rlsI8xKjqxz\" outputId=\"5a9e9d81-10c9-4de4-ceee-cfa5e6bcd0cf\"\nsns.scatterplot(x='temp',y='RH',data=forest1,hue='size_category')\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 449} id=\"wmvPXQ1gkdXx\" outputId=\"7c93c046-2dc2-4603-e1e1-15f71c2349a3\"\nsns.scatterplot(x='temp',y='DMC',data=forest1,hue='size_category')\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"tkm4NBQgk4ZY\" outputId=\"90ccd5da-7a27-4614-ebd6-f6d2fabcb650\"\ncor=forest.corr()\ncor\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 897} id=\"HZMDCzYulpc1\" outputId=\"54f699a1-7ba6-4614-da2e-1425c579c512\"\n#checking corelation \nplt.figure(figsize=(12,10))\nsns.heatmap(cor, annot=True,)\nplt.show()\n\n# + [markdown] id=\"12WbYUnum40t\"\n# Feature Engineering\n\n# + id=\"tvQx68btmPYu\"\narray = forest1.values\nx = forest1.iloc[:,0:28]\ny = forest1.iloc[:,28]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 487} id=\"M9abwFzVp3PB\" outputId=\"9edaf0fa-face-4839-a0e1-88f2d51f1979\"\nx\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"qS9evjnfqtcV\" outputId=\"5c425623-c372-4111-ae3b-3e0227fb46d4\"\ny\n\n\n# + id=\"U3lpaaRFq89C\"\n#Normalization\ndef norm_func(i):\n x = (i-i.min())/(i.max()-i.min())\n return (x)\n\n\n# + id=\"oAVYNCsGrZDM\"\nforestfires=norm_func(x)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 487} id=\"F6NtOfpzrlBO\" outputId=\"1fe47d07-4e90-4863-aee6-d123b8279f8e\"\nforestfires\n\n# + id=\"iJvXUYAKr0Db\"\nX_train, X_test, y_train, y_test = train_test_split(x,y, test_size = 0.3)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"22SZ_1per95Y\" outputId=\"71bac0a8-f7f3-449d-84d4-de85f8397378\"\nX_train.shape, y_train.shape, X_test.shape, y_test.shape\n\n# + [markdown] id=\"k_45YPKXsgVW\"\n# SVM Model\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 74} id=\"Z9UBJ-kksjvr\" outputId=\"9d94a9af-ad09-4fa6-e1b1-cf5ced796ec0\"\n#Kernel=Linear\nmodel_linear = SVC(kernel = \"linear\")\nmodel_linear.fit(X_train,y_train)\n\n# + id=\"HEL7fEdGtA50\"\npred_test_linear = model_linear.predict(X_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"SCsnhd36tJBS\" outputId=\"dc65190a-fa3a-4982-b90d-b2c71e9369ec\"\nnp.mean(pred_test_linear==y_test) #97.38% accuracy\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"EIAs9DHntmMK\" outputId=\"6e5a5be1-b1ea-498f-9413-269ce183b7f3\"\nacc = accuracy_score(y_test, pred_test_linear) * 100\nprint(\"Accuracy =\", acc)\nconfusion_matrix(y_test, pred_test_linear)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 74} id=\"uyO0_1CLtsos\" outputId=\"b5c4d0e1-eb34-408a-b315-7cf1fd647bd0\"\n#kernel=Poly\nmodel_poly = SVC(kernel = \"poly\")\nmodel_poly.fit(X_train,y_train)\n\n# + id=\"5b_dKcHet-WZ\"\npred_test_poly = model_poly.predict(X_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"9n2G6d2XuK51\" outputId=\"eda40ff3-6ef4-473e-cf09-6674c2e126e2\"\nnp.mean(pred_test_poly==y_test) #73.85% accuracy\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"L3O9IOGduc_L\" outputId=\"025e99d8-77b6-4dab-9eb8-d88fdcb4c8e4\"\nacc = accuracy_score(y_test, pred_test_linear) * 100\nprint(\"Accuracy =\", acc)\nconfusion_matrix(y_test, pred_test_linear)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 74} id=\"CaHhXH5Huw6i\" outputId=\"7380f360-5beb-4b0c-d726-d3c21b2141a0\"\n#kernel=rbf\nmodel_rbf = SVC(kernel = \"rbf\")\nmodel_rbf.fit(X_train,y_train)\n\n# + id=\"s0bIBB4wvGEy\"\npred_test_rbf = model_rbf.predict(X_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"HQtJhkXovNlF\" outputId=\"4adc47f4-b9fa-4b91-8ceb-0fe833f7e880\"\nnp.mean(pred_test_rbf==y_test) #Accuracy =72.54%\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 74} id=\"l06u-quRvf0m\" outputId=\"43979ce3-4c3d-40aa-bb32-d98a53afe4f3\"\n#Kernel=Sigmoid\nmodel_sig = SVC(kernel = \"sigmoid\")\nmodel_sig.fit(X_train,y_train)\n\n# + id=\"jKT0O5Glvk5X\"\npred_test_sig = model_sig.predict(X_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"WBrYbYAqvuB1\" outputId=\"03cca709-a5a8-4fc3-a1f8-7e833b520c89\"\nnp.mean(pred_test_sig==y_test) \n","repo_name":"aschobhe/data-science-assignments","sub_path":"Asssignment_17_SVM_Forestfires.ipynb","file_name":"Asssignment_17_SVM_Forestfires.ipynb","file_ext":"py","file_size_in_byte":7925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"35981427583","text":"# +\n# The imports we need for this project are as follows:\n# import libraries needed\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# -\n\ncid = \"XXX\"\nsecret = \"XXX\"\n#Authentication - without user\nclient_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)\nsp = spotipy.Spotify(client_credentials_manager = client_credentials_manager)\n\ndf = pd.read_csv('top_200_weekly.csv')\ndf.head()\n\ndf.nunique()\n\n# ### Missing value\n\ndf.info()\n\ndf.loc[df['Artist'].isna()].style.highlight_null(null_color='darkgreen')\n\n# +\n# Toy exxample get \n# track = 'spotify:track:4iJyoBOLtHqaGxP12qzhQI'\n# track = sp.track(track)\n# # print(track.keys())\n# print(track['name'])\n# print([a['name'] for a in track['artists']])\n\ntracks = list(df.loc[df['Artist'].isna()]['URI'])\nfor track in tracks:\n print('*'*20)\n print(track)\n track = sp.track(track)\n\n print(track['name'],[a['name'] for a in track['artists']]) \n# -\n\ndf.nunique()\n\n# ### New datasets\n\ndf_rank = df[['Week End','ID','Position']]\n# df_rank = df_rank.sort_values(by=['Week End','Position'])\ndf_rank.head()\n\ndf_rank_pivot = df_rank.pivot(index=['Week End'],columns=['Position'],values=['ID'])\ndf_rank_pivot.to_csv('week_position.csv',index_label=False)\n\ndf_rank_pivot.head()\n\n# ### Q1. What is the pattern of longevity of success songs?\n\ndf_1 = df.copy()\n\ndf_1.nunique()\n\ndf_1[['ID','URI']].groupby(by=['ID']).count()['URI'].sort_values()[-5:]\n\ndf_1[df_1.ID=='7qiZfU4dY1lWllzX7mPBI3'].head(1)\n\ndf_1[df_1.ID=='5uCax9HTNlzGybIStD3vDh'].head(1)\n\ndf_1[df_1.ID=='0tgVpDi06FyKpA1z0VMD4v'].head(1)\n\ndf_1[df_1.ID=='6gBFPUFcJLzWGx4lenP6h2'].head(1)\n\ndf_1[df_1.ID=='7m9OqQk4RVRkw9JJdeAw96'].head(1)\n\ndata = list(df_1[['ID','URI']].groupby(by=['ID']).count()['URI'])\nprint(data[:10])\nprint(f\"Number of tracks: {len(data)}\")\nprint(f\"\")\n\ndf_1[['ID','URI']].groupby(by=['ID']).count()\n\n# +\n# plt.figure(figsize=(10,5))\n# plt.title('Longevity of bestsellers',loc='center')\nfig, ax = plt.subplots(figsize=(7,5))\n# hist, bins, _ = plt.hist(data, 50, facecolor='g', alpha=0.75)\nplt.hist(data, 50, facecolor='g',edgecolor=\"black\", alpha=0.7)#,rwidth=0.85)\n# top1\nax.annotate(text='', xy=(257, 1), xycoords='data',\n xytext=(-50, 230), textcoords='offset points',#'axes fraction',\n arrowprops=dict(arrowstyle='->',facecolor='black'),#, shrink=0.05,width=0.3,headwidth=3),\n # horizontalalignment='right', verticalalignment='top',\n # textprops=dict()\n )\nax.text(180, 2700, 'Shape of You \\nEd Sheeran \\n257 weeks', style='italic',fontweight='medium')\n # bbox={'facecolor': 'g', 'alpha': 0.5, 'pad': 10})\n# top2\nax.annotate(text='', xy=(255, 1), xycoords='data',\n xytext=(-80, 175), textcoords='offset points',#'axes fraction',\n arrowprops=dict(arrowstyle='->',facecolor='black'),#, shrink=0.05,width=0.3,headwidth=3),\n )\nax.text(140, 2000, \"Say You Won't Let Go \\nJames Arthur \\n255 weeks\", style='italic',fontweight='medium')\n # bbox={'facecolor': 'g', 'alpha': 0.35, 'pad': 10})\n\n# top3\nax.annotate(text='', xy=(250, 1), xycoords='data',\n xytext=(-100, 110), textcoords='offset points',#'axes fraction',\n arrowprops=dict(arrowstyle='->',facecolor='black'),#, shrink=0.05,width=0.3,headwidth=3),\n )\nax.text(150, 1400, \"Perfect \\nEd Sheeran \\n250 weeks\", style='italic',fontweight='medium')\n # bbox={'facecolor': 'g', 'alpha': 0.2, 'pad': 10})\n\n# top4\nax.annotate(text='', xy=(224, 1), xycoords='data',\n xytext=(-120, 110), textcoords='offset points',#'axes fraction',\n arrowprops=dict(arrowstyle='->',facecolor='black'),#, shrink=0.05,width=0.3,headwidth=3),\n )\nax.text(90, 1200, \"Goosebumps \\nTravis Scott \\n224 weeks\", style='italic',fontweight='medium')\n\n# top5\nax.annotate(text='', xy=(215, 1), xycoords='data',\n xytext=(-150, 70), textcoords='offset points',#'axes fraction',\n arrowprops=dict(arrowstyle='->',facecolor='black'),#, shrink=0.05,width=0.3,headwidth=3),\n )\nax.text(50, 700, \"Jocelyn Flores \\nXXXTENTACION \\n215 weeks\", style='italic',fontweight='medium')\n \n# ID\n# 7m9OqQk4RVRkw9JJdeAw96 215\n# 6gBFPUFcJLzWGx4lenP6h2 224\n# 0tgVpDi06FyKpA1z0VMD4v 250\n# 5uCax9HTNlzGybIStD3vDh 255\n# 7qiZfU4dY1lWllzX7mPBI3 257\nplt.xlabel('Number of Weeks on Charts',fontsize=11,fontweight='medium')\nplt.ylabel('Number of Tracks',fontsize=11,fontweight='medium') \n# histogram on log scale. \n# Use non-equal bin sizes, such that they look equal on log scale.\n# logbins = np.logspace(np.log10(bins[0]),np.log10(bins[-1]),len(bins))\n# plt.title('Longevity of Success Tracks',loc='center')\nplt.savefig('figures/figure0.png',dpi=300)\n\nplt.show()\n# -\n\nfig, ax = plt.subplots(figsize=(7,5))\nplt.hist(data, bins=50,facecolor='b',edgecolor=\"black\", alpha=0.7,log=True)#,histtype=\"step\",cumulative=True)\n# plt.hist(data, alpha=0.5,log=True,histtype=\"step\",cumulative=True)\n# plt.xscale('log')\n# plt.yscale('log')\nplt.xlabel('Number of Weeks on Charts',fontsize=11,fontweight='medium')\nplt.ylabel('Number of Tracks (log)',fontsize=11,fontweight='medium')\n# plt.title('Longevity of Success Tracks (log)',loc='center')\n# plt.tight_layout()\nax.text(210, 1.1, \"1\", style='italic',fontweight='bold',c='black',fontsize=12)\nax.text(220, 1.1, \"1\", style='italic',fontweight='bold',c='black',fontsize=12)\nax.text(245, 1.1, \"1\", style='italic',fontweight='bold',c='black',fontsize=12)\nax.text(252, 2.1, \"2\", style='italic',fontweight='bold',c='black',fontsize=12)\nplt.savefig('figures/figure1.png',dpi=300)\nplt.show()\n\nnumber_of_week = list(df_1.groupby(by=['ID'])['Position'].count())\nbest_rank = list(df_1.groupby(by=['ID'])['Position'].min())\n\ndf_1.groupby(by=['ID'])['Position'].count()\n\ndf_1.groupby(by=['ID'])['Position'].min()\n\n# +\n# plt.figure(figsize=(7,5))\n# plt.scatter(number_of_week,best_rank,c='red',alpha=0.7,linewidths=0.0000001)\n# plt.ylim((201, 0))\n# # plt.ylim((0, 201))\n# plt.xscale('log')\n# # plt.yscale('log')\n# # plt.title('Best rank vs Number of weeks stayes')\n# plt.xlabel('Number of weeks on Global Top 200')\n# plt.ylabel('Best rank')\n# plt.tight_layout()\n\n# plt.savefig('figures/figure2.png')\n# plt.show()\n\n# +\nfrom collections import defaultdict\n\ncombination = list(zip(number_of_week,best_rank))\n\ncounter = defaultdict(int)\n\nfor c in combination:\n # x.append(c[0])\n # y.append(c[1])\n counter[c] += 1\n \n\nx = [i[0] for i in counter.keys()]\ny = [i[1] for i in counter.keys()]\ns = list(counter.values())\nsize = [np.pi*i*i for i in s]\nlen(size),len(x),len(y)\n\n# +\nplt.figure(figsize=(7,5))\nplt.scatter(x,y,s=size,c=\"blue\",alpha=0.7)\nplt.ylim((201, 0))\n# plt.ylim((0, 201))\nplt.xscale('log')\n\n# plt.title('Best rank vs Number of weeks stayes')\nplt.xlabel('Number of Weeks on Charts',fontsize=11,fontweight='medium')\nplt.ylabel('Best Rank',fontsize=11,fontweight='medium')\n# plt.tight_layout()\n\nplt.savefig('figures/figure2.png',dpi=300)\nplt.show()\n\n# +\n# GO DEEPER OF THE TOP FIVE\n# 7m9OqQk4RVRkw9JJdeAw96 215\n# 6gBFPUFcJLzWGx4lenP6h2 224\n# 0tgVpDi06FyKpA1z0VMD4v 250\n# 5uCax9HTNlzGybIStD3vDh 255\n# 7qiZfU4dY1lWllzX7mPBI3 257\n# -\n\ndf = pd.read_csv('top_200_weekly.csv')\ndf.head()\n\ndf_top5 = df[(df['ID']=='7qiZfU4dY1lWllzX7mPBI3') | \n (df['ID']=='5uCax9HTNlzGybIStD3vDh') |\n (df['ID']=='0tgVpDi06FyKpA1z0VMD4v') |\n (df['ID']=='6gBFPUFcJLzWGx4lenP6h2') |\n (df['ID']=='7m9OqQk4RVRkw9JJdeAw96')\n ]\ndf_top5.head()\n\ndf_top5.loc[:,'Year'] = pd.Series(map(lambda x:int(x[:4]) ,df['Week End']))\ndf_top5.loc[:,'Month'] = pd.Series(map(lambda x:int(x[5:7]) ,df['Week End']))\n\ndf_top5.info()\ndf_top5.head()\n\ndf_top5.to_csv('top5.csv', index=False)\n\ndf_top5 = pd.read_csv('top5.csv',parse_dates=['Week End'])\n# df_top5.set_index('Week End', inplace=True)\ndf_top5.head()\n\nids = ['7m9OqQk4RVRkw9JJdeAw96',\n'6gBFPUFcJLzWGx4lenP6h2',\n'0tgVpDi06FyKpA1z0VMD4v',\n'5uCax9HTNlzGybIStD3vDh',\n'7qiZfU4dY1lWllzX7mPBI3']\nprint(f\"isd:{ids}\")\n\nfor i,t in enumerate(ids[::-1]):\n _1 = df_top5[df_top5['ID'] == t]\n df_1 = _1.groupby(by=['Year','Month']).min().reset_index()\n position_1 = df_1.pivot( \"Year\",\"Month\", \"Position\").fillna(0).astype('int64')\n # heatmap\n fig, ax = plt.subplots(figsize=(8,3))\n mask = position_1==0\n sns.heatmap(position_1, cmap=\"summer\",annot=True, annot_kws={\"size\": 10},fmt='d',\n linewidths=0.5, linecolor='white',ax=ax,mask=mask,cbar_kws={'label':'Best Position'})\n plt.tight_layout()\n path = f\"figures/top5_{i+1}.png\"\n plt.savefig(path,dpi=300)\n plt.show()\n # break\n\n_1\n\nsns.set_style(\"white\")\nplt.figure(figsize=(12,6))\nplt.ylim((201, 0))\npalette = [\"green\",\"orange\",\"red\",\"blue\",\"purple\"]\nsns.lineplot(x='Week End',y='Position',data=df_top5,hue='Track Name',palette=palette,marker='o')\nplt.xlabel('Date',size=12)\nplt.tight_layout()\nplt.savefig(\"figures/top5.png\",dpi=300)\nplt.show()\n\n\n\n# ### Q6. What are the relations between position, length of stay of a song on the list and song streams? \n\ndf = pd.read_csv('top_200_weekly.csv')\ndf.head()\n\ndata_streams = df.groupby(by='ID').max()['Streams']\n\n# +\nfig, ax = plt.subplots(figsize=(7,5))\n# plt.hist(data_streams,bins=100,facecolor='g', alpha=0.7)\nplt.hist(data_streams, 100, facecolor='green',edgecolor=\"black\", alpha=0.7)#,rwidth=0.85)\nplt.xscale('log')\n# plt.yscale('log')\n# plt.title('Number of songs vs Streams')\nplt.xlabel('Streams')\nplt.ylabel('Number od songs')\nplt.tight_layout()\n\nplt.savefig('figures/figure3.png',dpi=300)\nplt.show()\nplt.show()\n\n# +\nfig, ax = plt.subplots(figsize=(7,5))\nplt.scatter(best_rank,data_streams,facecolor='blue', alpha=0.7)#,c='DarkBlue')\n# plt.ylim((201, 0))\n# plt.xscale('log')\n# plt.yscale('log')\n# plt.title('Best rank vs Number of weeks stayes')\nplt.xlabel('Best rank')\nplt.ylabel('Streams')\nplt.tight_layout()\n\nplt.savefig('figures/figure4.png',dpi=300)\nplt.show()\n\n# +\nfig, ax = plt.subplots(figsize=(7,5))\nplt.scatter(number_of_week,data_streams,facecolor='red', alpha=0.7)#,c='DarkBlue')\n# sns.scatterplot(number_of_week,data_streams,data=df_1)\n# plt.ylim((201, 0))\n# plt.xscale('log')\nplt.yscale('log')\n# plt.title('Best rank vs Number of weeks stayes')\nplt.xlabel('Number of weeks stayes')\nplt.ylabel('Streams')\nplt.tight_layout()\n\nplt.savefig('figures/figure5.png',dpi=300)\nplt.show()\n\n# +\n# from random import randint\n# # %matplotlib tk\n# import matplotlib.pyplot as plt\n# from matplotlib.animation import FuncAnimation\n# from IPython.display import HTML\n# # create empty lists for the x and y data\n# x = []\n# y = []\n\n# # create the figure and axes objects\n# fig, ax = plt.subplots()\n\n# # function that draws each frame of the animation\n# def animate(i):\n# pt = randint(1,9) # grab a random integer to be the next y-value in the animation\n# x.append(i)\n# y.append(pt)\n\n# ax.clear()\n# ax.plot(x, y)\n# ax.set_xlim([0,20])\n# ax.set_ylim([0,10])\n \n \n# # run the animation\n# ani = FuncAnimation(fig, animate, frames=20, interval=500, repeat=False)\n# # HTML(ani.to_html5_video())\n# ani.save(\"sin1.gif\",writer='pillow')\n# plt.show()\n","repo_name":"chennnxu/HitsOnSpotify","sub_path":"3_analysis_tracks.ipynb","file_name":"3_analysis_tracks.ipynb","file_ext":"py","file_size_in_byte":11205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"73443458692","text":"# + colab={} colab_type=\"code\" id=\"RQr9JaI_mkfo\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# + colab={} colab_type=\"code\" id=\"wN1o9zjrr8HQ\"\ndf = pd.read_csv('diabetes.csv')\n\n# + colab={} colab_type=\"code\" id=\"EPdby81lEVcf\"\nX = df.iloc[:, 0:7]\ny = df['Outcome']\n\nfrom sklearn.model_selection import train_test_split\nX_train, y_train, X_test, y_test = train_test_split(X, y, test_size = 0.20)\n\n# + colab={} colab_type=\"code\" id=\"GRzf_CTDEVUz\"\nmodel = LogisticRegression()\n\n# + colab={} colab_type=\"code\" id=\"fUT2xp_eEVQl\"\nmodel.fit(X_train, y_train)\n\n# + colab={} colab_type=\"code\" id=\"rJm-LCgtEVK-\"\n# coefficients of the trained model\nprint('Coefficient of model :', model.coef_)\n\n# intercept of the model\nprint('Intercept of model',model.intercept_)\n\n# + colab={} colab_type=\"code\" id=\"PBACA9g7E2rD\"\n# predict the target on the train dataset\npredict_train = model.predict(train_x)\nprint('Target on train data',predict_train) \n\n# Accuray Score on train dataset\naccuracy_train = accuracy_score(train_y,predict_train)\nprint('accuracy_score on train dataset : ', accuracy_train)\n\n# predict the target on the test dataset\npredict_test = model.predict(test_x)\nprint('Target on test data',predict_test) \n\n# Accuracy Score on test dataset\naccuracy_test = accuracy_score(test_y,predict_test)\nprint('accuracy_score on test dataset : ', accuracy_test)\n\n# + [markdown] colab_type=\"text\" id=\"bfCmvqJhsg-X\"\n# ##Fitting a model between two columns col1 and col2:\n# col1 contains the basis of classification and\n# col2 contains the classification result(1 or 0)\n\n# + colab={} colab_type=\"code\" id=\"2ajdXzItr8Qr\"\nlogistic_model = LogisticRegression()\nlogistic_model.fit(dataframe[[\"col1\"]], dataframe[\"col2\"])\nfitted_labels = logistic_model.predict(dataframe[['col1']])\nplt.scatter(dataframe['col1'], fitted_labels)\n","repo_name":"sarthakrastogi/notesonnotebooks","sub_path":"ML Algorithms/Logistic_Regression.ipynb","file_name":"Logistic_Regression.ipynb","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"72762459320","text":"# + id=\"zlU5dsSk3-HT\"\nimport pandas as pd\nimport seaborn as sns\nimport statsmodels.api as sm\nimport numpy as np\nfrom scipy.stats import pearsonr\nfrom scipy import stats\n\n# + id=\"caUYF-oy3_nb\"\nboston_url = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ST0151EN-SkillsNetwork/labs/boston_housing.csv'\nboston_df=pd.read_csv(boston_url)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"zKMt-MVo4AB5\" outputId=\"ef9d7d01-a3ef-4cc4-e4cc-7453782e8b7b\"\nboston_df.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 350} id=\"p29BI56Y694D\" outputId=\"4945d3ed-659d-42d1-b1c2-275d23e3dc40\"\n#For the \"Median value of owner-occupied homes\" provide a boxplot\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplt.figure(figsize=(10,5))\nsns.boxplot(x=boston_df.MEDV)\nplt.title(\"Boxplot for MEDV\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 405} id=\"D05XIXS44OLh\" outputId=\"1d7f47f6-73a7-4d38-d7b4-c7c5b46b3ce4\"\nplt.figure(figsize=(10,5))\nsns.distplot(a=boston_df.CHAS,bins=10, kde=False)\nplt.title(\"Histogram for Charles river\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 350} id=\"ZlUs7Dc64glU\" outputId=\"429cf6f3-f6fa-4f65-bd0c-ef8cdfb8fd09\"\nplt.figure(figsize=(10,5))\nsns.histplot(data=boston_df, x=\"PTRATIO\")\nplt.title(\"Histogram Plot for the PT ratio\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 350} id=\"eskw23s-5aSe\" outputId=\"358e8dbb-4793-44d4-e636-8b8a336bac59\"\nplt.figure(figsize=(10,5))\nsns.scatterplot(data=boston_df, x=\"NOX\", y=\"INDUS\")\nplt.title(\"ScatterPlot for the NOX variable vs the INDUS variable\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"NUib3G-I5qXu\" outputId=\"741a276c-8f5b-4b9e-bf7e-b2dfb81e6178\"\nlist1 = boston_df['NOX']\nlist2 = boston_df['INDUS'] \n# Apply the pearsonr()\ncorr, _ = pearsonr(list1, list2)\nprint('Pearsons correlation: %.3f' % corr)\nprint('From the above firgure, it can be seen that NOX and INDUS are correlated')\n\n# + id=\"Bs5c7t-26NU9\"\nboston_df.loc[(boston_df[\"AGE\"] <= 35),'age_group'] = '35 years and younger'\nboston_df.loc[(boston_df[\"AGE\"] > 35) & (boston_df[\"AGE\"]<70),'age_group'] = 'between 35 and 70 years'\nboston_df.loc[(boston_df[\"AGE\"] >= 70),'age_group'] = '70 years and older'\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 350} id=\"UMd5knmf9Kwr\" outputId=\"c36024a8-ca69-4ac5-aad3-9667c52a05c8\"\nplt.figure(figsize=(10,5))\nsns.boxplot(x=boston_df.MEDV, y=boston_df.age_group, data=boston_df)\nplt.title(\"Boxplot for the MEDV variable vs the AGE variable\")\nplt.show()\n\n# + [markdown] id=\"0srF0TEB99R2\"\n# For each of the following questions;\n#\n# Is there a significant difference in median value of houses bounded by the Charles river or not? (T-test for independent samples)\n#\n# Is there a difference in Median values of houses (MEDV) for each proportion of owner occupied units built prior to 1940 (AGE)? (ANOVA)\n#\n# Can we conclude that there is no relationship between Nitric oxide concentrations and proportion of non-retail business acres per town? (Pearson Correlation)\n#\n# What is the impact of an additional weighted distance to the five Boston employment centres on the median value of owner occupied homes? (Regression analysis)\n#\n# Be sure to:\n#\n# State your hypothesis.\n#\n# Use α = 0.05\n#\n# Perform the test Statistics.\n#\n# State the conclusion from the test.\n\n# + [markdown] id=\"w0lyl_tB_7jB\"\n# **Is there a significant difference in median value of houses bounded by the Charles river or not? (T-test for independent samples)**\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"2RONDtwa-T2G\" outputId=\"14a02653-6979-4d94-844d-8ac25e9c61be\"\nrvs1=boston_df.loc[(boston_df['CHAS'] ==1),'MEDV']\nrvs2=boston_df.loc[(boston_df['CHAS'] ==0),'MEDV']\nstats.ttest_ind(rvs1, rvs2)\n\n# + [markdown] id=\"UBNJHdUyAACA\"\n# Null Hypothesis(): Both average MEDV are the same\n#\n# Alternative Hypothesis(): Both average MEDV are NOT the same\n#\n# Since alpha =0.05 and the pvalue < alpha. Therefore, the we reject NULL hypothesis\n#\n\n# + [markdown] id=\"q_a8Yj65ArYQ\"\n#\n# **Is there a difference in Median values of houses (MEDV) for each proportion of owner occupied units built prior to 1940 (AGE)? (ANOVA)**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_hZBxlfx_K1z\" outputId=\"1e3eda9c-2cca-43ad-8d59-08c43830903f\"\nlow = boston_df[boston_df[\"age_group\"] == '35 years and younger'][\"MEDV\"]\nmid = boston_df[boston_df[\"age_group\"] == 'between 35 and 70 years'][\"MEDV\"]\nhigh = boston_df[boston_df[\"age_group\"] == '70 years and older'][\"MEDV\"]\nstats.f_oneway(low, mid, high)\n\n# + [markdown] id=\"gaZanHORLMvx\"\n# Th null hypothesis is the hypothesis that all age groups have same mean MEDV values. Because the pvalue < alpha, therefore, the NULL hypothesis is rejected.\n\n# + [markdown] id=\"1wfCy5viLrJb\"\n# **Can we conclude that there is no relationship between Nitric oxide concentrations and proportion of non-retail business acres per town? (Pearson Correlation)**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"r6vDhCimKjqc\" outputId=\"6ea6e3b8-3892-4854-d924-394cbad5dc46\"\nNOX_data=boston_df['NOX']\nINDUS_data=boston_df['INDUS']\nres = stats.pearsonr(NOX_data,INDUS_data )\nres\n\n# + [markdown] id=\"GztdrTpzLqSS\"\n# The Null hypothesis is that there is no relationship between NOX and INDUS variable. However, the pvalue < alpha. Therefore, the NULL hypothesis is rejected. This can also be conlcuded from scateerplot plot\n\n# + [markdown] id=\"8hMBnbz9MkFV\"\n# **What is the impact of an additional weighted distance to the five Boston employment centres on the median value of owner occupied homes? (Regression analysis)**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 498} id=\"HyGNzFEXMhZU\" outputId=\"3f94dfc9-a167-4ed0-def1-2dd24b14adec\"\nx=boston_df['DIS']\ny=boston_df['MEDV']\nx = sm.add_constant(x)\nmodel = sm.OLS(y,x)\nresults = model.fit()\nresults.summary()\n\n# + [markdown] id=\"ipGo9MZCNmRD\"\n# **The DIS parameter add 1.0916 units more than average to MEDV**\n\n# + id=\"Pbu3bLeENfHs\"\n\n","repo_name":"sreenivasraghavan71/Coursera","sub_path":"Assignment.ipynb","file_name":"Assignment.ipynb","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"32200546479","text":"# %matplotlib notebook\n\nfrom create_ice_cube_image_data import *\nfrom numba import jit\nfbatch={'1':\"/scratch/ICE-CUBE/batch_1.parquet\"}\nice_cube=ice_cube_data(fbatch=fbatch,\n fsensor=\"/scratch/ICE-CUBE/sensor_geometry.csv\",\n fmetaf=\"/scratch/ICE-CUBE/train_meta.parquet\",\n every_nth_event=10,\n width={'x':10,'y':10,'z':60})\n\n# +\n#import matplotlib.pyplot as plt\n#threedee = plt.figure(figsize=(5, 5)).gca(projection='3d')\n#threedee.scatter(ice_cube.events['x'],ice_cube.events['y'],ice_cube.events['z'])\n#plt.show()\n# -\n\nimg_data, labels= ice_cube.create_img_data()\nimg_data.shape\n\neventdict={}\nfor ievent,indexevent in enumerate(ice_cube.events.index.unique().to_list()):\n eventdict[ievent]=indexevent\n \n\neventdraw=200\n\n# +\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# create a meshgrid for the x, y, and z coordinates\n#x, y, z = np.meshgrid(np.arange(img_width), np.arange(img_height), np.arange(img_depth))\nx,y,z,=img_data[eventdraw].nonzero()\n\n# plot the 3D image using the meshgrid and the pixel values\nax.scatter(x,y,z)#, c=x_train[0].flatten(),cmap='gray_r',s=20)\n\n# set the axis labels and limits\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nax.set_xlim([0, 10])\nax.set_ylim([0, 10])\nax.set_zlim([0, 60])\n\n# show the 3D plot\nplt.show()\n\n# +\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# plot the 3D image using the meshgrid and the pixel values\nax.scatter(ice_cube.events.loc[eventdict[eventdraw]]['x'],ice_cube.events.loc[eventdict[eventdraw]]['y'],ice_cube.events.loc[eventdict[eventdraw]]['z'])\n\n# set the axis labels and limits\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nax.set_xlim([0, 10])\nax.set_ylim([0, 10])\nax.set_zlim([0, 60])\n\n# show the 3D plot\nplt.show()\n\n# +\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# plot the 3D image using the meshgrid and the pixel values\nax.scatter(ice_cube.realevents.loc[eventdict[eventdraw]]['x'],ice_cube.realevents.loc[eventdict[eventdraw]]['y'],ice_cube.realevents.loc[eventdict[eventdraw]]['z'])\n\n# set the axis labels and limits\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nax.set_xlim([-500, 500])\nax.set_ylim([-500, 500])\nax.set_zlim([-500, 500])\n\n# show the 3D plot\nplt.show()\n# -\n\nimg_data=img_data.reshape(19976, 11, 11, 61,1)\nimg_data.shape\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(img_data, labels, test_size=0.9, random_state=42)\n\n# +\nimport tensorflow as tf\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv3D, MaxPooling3D, Flatten, Dense\n\n# create a sequential model\nmodel = Sequential()\n\n# add a 3D convolutional layer with 32 filters, a 3x3x3 kernel size, and ReLU activation\nmodel.add(Conv3D(32, (3, 3, 3), activation='relu', input_shape=X_train[0].shape))\n\n# add a 3D max pooling layer with a 2x2x2 pool size\nmodel.add(MaxPooling3D(pool_size=(2, 2, 2)))\n\n# flatten the output of the previous layer\nmodel.add(Flatten())\n\n# add a fully connected (Dense) layer with 128 units and ReLU activation\nmodel.add(Dense(100, activation='relu'))\n\n# add the output layer with 2 units (assuming 2 classes) and softmax activation\nmodel.add(Dense(2, activation='relu'))\n\n# compile the model with categorical crossentropy loss and Adam optimizer\nmodel.compile(loss='mse', optimizer='adam',metrics=[\"categorical_accuracy\"])\n\n# assuming X_train contains the image data and y_train contains the labels, fit the model\nmodel.fit(X_train, y_train, epochs=10, batch_size=32)\n# -\n\nmodel.predict(X_test)\n\ny_test\n\nmodel.predict(X_train)\n\ny_train\n","repo_name":"Exploratory-Machine-Learning/ICE-CUBE","sub_path":"CNN3d_ice_cube.ipynb","file_name":"CNN3d_ice_cube.ipynb","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"15299045054","text":"# +\nfrom strands import Schrodinger2D, Rectangle\n\ns = Schrodinger2D(lambda x, y: 10*(x*x + y*y), Rectangle(-1,1,-1,1), maxBasisSize=32, gridSize=(48,48))\n# -\n\neigs = s.eigenfunctions(10)\neigs\n\n# +\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nE4, f4 = eigs[4]\nE5, f5 = eigs[5]\nprint(E4, E5)\nxs = np.linspace(-1,1, 1000)\nX, Y = np.meshgrid(xs, xs)\nZ = f4(X, Y) - 0.4*f5(X, Y)\n\nplt.pcolormesh(X, Y, Z)\n\n# +\nimport imageio\n\nimageio.imwrite('eigenfunction.exr', Z.astype(\"float32\"))\n# -\n\n\n","repo_name":"toonijn/PhD-thesis","sub_path":"flipbook/eigenfunction.ipynb","file_name":"eigenfunction.ipynb","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"18920909408","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"aMLCuJS-WT6l\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport pywt\nfrom scipy.optimize import curve_fit\n\nimport seaborn as sns\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom scipy import stats\nimport scipy\n\n\n# + id=\"bBsBNF7VWYel\"\ndef denoise(y2):\n fft_signal = y2\n y3 = y2\n # y3 = []\n # count = 0\n # while(count < len(y2)):\n # y3.append(y2[count])\n # count += 1000\n def filter_signal(th):\n f_s = fft_filter(th)\n return np.real(np.fft.ifft(f_s))\n def fft_filter(perc):\n fft_signal = np.fft.fft(y3)\n fft_abs = np.abs(fft_signal)\n th=perc*(2*fft_abs[0:int(len(y3))]/((len(y3)))).max()\n fft_tof=fft_signal.copy()\n fft_tof_abs=np.abs(fft_tof)\n fft_tof[fft_tof_abs<=th]=0\n return fft_tof\n def fft_filter_amp(th):\n fft = np.fft.fft(y3)\n fft_tof=fft.copy()\n fft_tof_abs=np.abs(fft_tof)\n fft_tof_abs=2*fft_tof_abs/(len(fft_tof_abs)/2.)\n fft_tof_abs[fft_tof_abs<=th]=0\n return fft_tof_abs[0:int(len(fft_tof_abs)/2.)]\n th_list = np.linspace(0,1,5)\n th_list = th_list[0:len(th_list)-1]\n th_list = np.array([0, 0.25, 0.5, 0.75])\n th_list = np.linspace(0,0.02,1000)\n th_list = th_list[0:len(th_list)]\n p_values = []\n corr_values = []\n for t in th_list:\n filt_signal = filter_signal(t)\n res = stats.spearmanr(y3,y3-filt_signal)\n p_values.append(res.pvalue)\n corr_values.append(res.correlation)\n th_opt = th_list[np.array(corr_values).argmin()]\n opt_signal = filter_signal(th_opt)\n return opt_signal\n","repo_name":"ethanbrown33/enge_anc","sub_path":"DenoisingFunction.ipynb","file_name":"DenoisingFunction.ipynb","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"70084266362","text":"# # Banco de dados\n# Aqui nós criamos o banco de dados hm1. Ele conterá os dados coletados da página do autor desejado, utilizando a função scrape\n\nfrom sqlite3 import dbapi2 as sq3\nimport os\nimport sqlite3\nimport pandas as pd\nimport altair as alt\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom scraper_scholar import * \n\n\ndados = scrape('Jeffrey Heer') #Coletando informações pela função scrape\nprint(dados[0:5])\n\n# Construindo o banco de dados\n\nourschema = '''\n DROP TABLE IF EXISTS \"author\";\n DROP TABLE IF EXISTS \"paper\";\n DROP TABLE IF EXISTS \"author_paper\";\n CREATE TABLE \"author\" (\n \"id\" INTEGER PRIMARY KEY NOT NULL ,\n \"author\" VARCHAR NOT NULL UNIQUE\n );\n CREATE TABLE \"paper\" ( \n \"id\" INTEGER PRIMARY KEY NOT NULL ,\n \"paper\" VARCHAR NOT NULL UNIQUE\n );\n CREATE TABLE \"author_paper\" (\n 'author_id' VARCHAR,\n 'paper_id' VARCHAR,\n FOREIGN KEY(author_id) REFERENCES author(id)\n FOREIGN KEY(paper_id) REFERENCES paper(id)\n );\n '''\n\nPATHSTART=\".\"\ndef get_db(dbfile):\n sqlite_db = sq3.connect(os.path.join(PATHSTART, dbfile))\n return sqlite_db\ndef init_db(dbfile, schema):\n \"\"\"Creates the database tables.\"\"\"\n db = get_db(dbfile)\n db.cursor()\n db.executescript(schema)\n db.commit()\n return db\n\n\ndb=init_db(\"hw1.db\", ourschema)\n\n# +\n#criando data papers, authors e authors_paper\nx = []\nfor i in dados:\n for j in i['authors']:\n x.append([i['title'],j.strip()])\nx = pd.DataFrame(x,columns=['paper','author'])\n\nx1 = list(sorted(set(x['paper'])))\nx2 = list(sorted(set(x['author'])))\npaper=pd.DataFrame(x1,columns=['paper'])\n\nauthor=pd.DataFrame(x2,columns=['author']) \n# -\n\npaper.head(5)\n\n# Inserindo dados\n\nauthor.to_sql(\"author\", db, if_exists=\"append\", index=False)\npaper.to_sql(\"paper\", db, if_exists=\"append\", index=False)\n\n\ndef make_query(tabela):\n c=db.cursor().execute(\"SELECT * FROM {};\".format(tabela))\n return c.fetchall()\n\n\n# +\na = make_query('author')\nt = make_query('paper')\na = pd.DataFrame(a,columns=['author_id','author'])\nt = pd.DataFrame(t,columns=['paper_id','paper'])\nauthor_paper = pd.merge(x,a,on='author') \nauthor_paper = pd.merge(author_paper,t,on='paper') \n\n\n# -\n\nauthor_paper.head(5)\n\n#author_paper = pd.concat([author_paper['author_id'],author_paper['paper_id']],axis=1)\nauthor_paper.to_sql(\"author_paper\", db, if_exists=\"append\", index=False,)\n\n\n","repo_name":"joaovictorpasseri/FDS-Homeworks","sub_path":"hm1/Banco de Dados e Site.ipynb","file_name":"Banco de Dados e Site.ipynb","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"41292385930","text":"# Our data management libraries\nimport pandas as pd\n\ndf = pd.read_csv('ecommerce-behavior-data-from-multi-category-store/2019-Nov.csv',chunksize = 10000)\n\nfor chunk in df:\n display(chunk.head())\n break\n\n\n","repo_name":"Hmmsien/ECommerce_behavior","sub_path":".ipynb_checkpoints/Ecommerce-Behavior-Analytics-checkpoint.ipynb","file_name":"Ecommerce-Behavior-Analytics-checkpoint.ipynb","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"27490563458","text":"# + id=\"kPG2iGOUuinR\"\ndef scientificNotation(number, exponent):\n\n answer = 10**exponent\n answer = number * answer\n \n return answer\n\n\n\n# + [markdown] id=\"iqwkA_qSwaMa\"\n# 6\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"QEhpjiQRwKVW\" outputId=\"37a147fa-b3b4-4f36-8d4f-edb792d0bf64\"\nscientificNotation(4.9,-4) * scientificNotation(4.9,-4)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"iXFw1ax2vHeo\" outputId=\"efca09ae-6281-45b1-b2d6-34b36086331b\"\nscientificNotation(-2.2, -4) / scientificNotation(2.4, -7)\n\n# + [markdown] id=\"XbsrrZBGwcok\"\n# 7\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oQwOLr-NwdaX\" outputId=\"7620a0aa-2e54-4e90-a7b2-ddd0071bda32\"\nscientificNotation(5.3,-4) * scientificNotation(9.2,-4)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"UhSLAxj3u-rL\" outputId=\"3b6f2786-3f94-4cb7-e4d1-8daebacb866a\"\nscientificNotation(1.8, -4) / scientificNotation(4.9, -7)\n\n# + [markdown] id=\"oE7bsn6lwqfF\"\n# 8\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"BkZ1f5VbwrVC\" outputId=\"3b278db8-983f-4443-8481-0573134ffe62\"\nscientificNotation(0.7,-4) * scientificNotation(-5.0,-4)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VuqKIaFlvNR-\" outputId=\"8286d162-553f-4d91-f07e-e0281a3a9502\"\nscientificNotation(6.4, -4) / scientificNotation(-3.5, -8)\n\n# + [markdown] id=\"gGjx8pQ3w23B\"\n# 9\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"MAagm4adw3wb\" outputId=\"ea9afad1-1040-413c-92b4-c1263080ca53\"\nscientificNotation(-1.0,-5) * scientificNotation(-5.3,-4)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"C5_AjNtLvNbj\" outputId=\"4c9bfe71-9bfb-4e10-b44b-4d05952871b3\"\nscientificNotation(7.2, -4) / scientificNotation(-5, -9)\n\n# + [markdown] id=\"C01BiKzxxHLi\"\n# 10\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"5m3STG7_xKI8\" outputId=\"c1a2ceda-c9a4-4964-b4b5-10a5273a1bdf\"\nscientificNotation(3.9,-4) * scientificNotation(-1.1,-4)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"5OFvg9NZvNjv\" outputId=\"1d6a974b-eeaa-4b14-e9d3-270da4de4779\"\nscientificNotation(-3.2, -4) / scientificNotation(-4.29, -8)\n","repo_name":"morganbenavidez/Chemistry","sub_path":"ScientificNotation.ipynb","file_name":"ScientificNotation.ipynb","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"36918986619","text":"# # Reinforcement learning\n# ### Snake - Monte Carlo\n# Play games and iteratively improve the state values and corresponding policy\n\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom matplotlib import animation\nfrom IPython.display import HTML, Image\n\n# ### Setup\n\n# +\n'''Modified with improved 'graphics' '''\n\nimport numpy as np\n\nim = 5\n\nclass Game():\n \n def __init__(self,grid,snake_size, snake_pad=2):\n self.board = np.ones((grid,grid,3))\n self.image = np.ones((grid*im,grid*im,3))\n self.snake = Snake(self.board,snake_size)\n self.pad = snake_pad\n self.apple = None\n self.score = 0\n self.total = 0\n self.deaths = 0\n\n def reset(self):\n self.snake.reset(self.pad)\n self.spawn_apple()\n\n def draw(self):\n # white background\n self.board[:,:,:] = 1\n self.image[:,:,:] = 1\n # black snake\n \n # head\n x,y = self.snake.pos\n self.board[x,y,:] = 0\n self.image[x*im:(x+1)*im,y*im:(y+1)*im,:] = 0\n d = self.snake.d\n xx,yy = [((x+1)*im-1,(y+1)*im-1),((x)*im,(y+1)*im-1),(x*im,y*im),(x*im,y*im)][d]\n self.image[xx,yy,:] = 1\n xx,yy = [((x+1)*im-1,y*im),((x+1)*im-1,(y+1)*im-1),(x*im,(y+1)*im-1),((x+1)*im-1,y*im)][d]\n self.image[xx,yy,:] = 1\n\n for s in self.snake.segments[1:]:\n x,y = s\n self.board[x,y,:] = 0\n self.image[x*im:(x+1)*im,y*im:(y+1)*im,:] = 0\n # tail\n if (len(self.snake.segments)>0):\n x,y = self.snake.segments[0]\n self.board[x,y,:] = 0 \n #self.image[x*im:(x+1)*im,y*im:(y+1)*im,1] = 0\n if (len(self.snake.segments)>1):\n n,m = self.snake.segments[1]\n else:\n n,m = self.snake.pos\n if (n==x and m>y):\n self.image[x*im:(x+1)*im,(y+1)*im-1,:] = 0\n self.image[x*im+1:(x+1)*im-1,(y+1)*im-2,:] = 0\n self.image[x*im+1:(x+1)*im-1,(y+1)*im-3,:] = 0\n self.image[x*im+2:(x+1)*im-2,(y+1)*im-4,:] = 0\n self.image[x*im+2:(x+1)*im-2,(y+1)*im-5,:] = 0\n elif (n==x and mx and m==y):\n self.image[(x+1)*im-1,y*im:(y+1)*im,:] = 0\n self.image[(x+1)*im-2,y*im+1:(y+1)*im-1,:] = 0\n self.image[(x+1)*im-3,y*im+1:(y+1)*im-1,:] = 0\n self.image[(x+1)*im-4,y*im+2:(y+1)*im-2,:] = 0\n self.image[(x+1)*im-5,y*im+2:(y+1)*im-2,:] = 0\n \n # red apple\n x,y = self.apple\n self.board[x,y,1:] = 0\n self.image[x*im:(x+1)*im,y*im:(y+1)*im,1:] = 0\n for i in range(2):\n for j in range(2):\n self.image[(x+i)*im-i,(y+j)*im-j,:] = 1\n\n def spawn_apple(self):\n # dummy x,y for while loop\n x,y = self.snake.pos\n # keep generating new apples until a free cell is rolled\n while ((x,y) in self.snake.segments+[self.snake.pos]):\n x = np.random.randint(self.board.shape[0])\n y = np.random.randint(self.board.shape[1])\n self.apple = np.array([x,y],dtype=int)\n\n def iterate(self):\n reward = 0\n episode = 0\n # move snake\n self.snake.move()\n # check death condition\n grid = len(self.board)\n p = self.snake.pos\n a = self.apple\n if ((p[0]<0 or p[0]>=grid or p[1]<0 or p[1]>=grid) or (p in self.snake.segments)):\n self.lose()\n episode = -1\n reward = -1\n elif (p == a).all():\n # eat apple\n self.eat()\n episode = 1\n reward = 1\n return reward, episode\n\n def lose(self):\n self.reset()\n self.score=0\n self.deaths+=1\n\n def eat(self):\n self.snake.eat()\n self.score+=1\n self.total+=1\n old = self.apple\n self.spawn_apple()\n\n def get_state(self):\n grid = len(self.board)\n state = np.zeros(6)\n x,y = self.snake.pos\n 'S,E,N,W'\n if ((x+1,y) in self.snake.segments or x+1>=grid):\n state[0] = 1\n if ((x-1,y) in self.snake.segments or x-1<0):\n state[2] = 1\n if ((x,y+1) in self.snake.segments or y+1>=grid):\n state[1] = 1\n if ((x,y-1) in self.snake.segments or y-1<0):\n state[3] = 1\n state[4] = np.sign(x-self.apple[0])\n state[5] = np.sign(y-self.apple[1])\n return state\n\nclass Snake():\n \n movement = ([[1,0],[0,1],[-1,0],[0,-1]])\n \n def __init__(self,board,starting_size):\n # the board on which the snake is moving\n self.grid = board.shape\n # position of head\n self.pos = None\n # direction facing\n self.d = 0\n # number of tail segments\n self.size = starting_size\n self.s_size = starting_size\n # position of tail segments\n self.segments = []\n \n def reset(self,pad=2):\n # pad starting position\n x = np.random.randint(pad,self.grid[0]-pad)\n y = np.random.randint(pad,self.grid[1]-pad)\n self.pos = (x,y)\n self.d = np.random.randint(4)\n self.size = self.s_size\n self.segments = []\n \n def move(self):\n # add head's position to segments\n self.segments.append(self.pos)\n # move head\n x,y = self.pos\n dx,dy = self.movement[self.d]\n self.pos = (x+dx,y+dy)\n # remove one segment if needed\n seg = None\n if (len(self.segments)>self.size):\n seg = self.segments.pop(0)\n # return new position and position that has been cleared\n return self.pos, seg\n \n def eat(self):\n self.size+=1\n\n\n# -\n\n# modified dictionary that incorporates random defaults and epsilon greedy\nclass Policy(dict):\n \n import random\n \n def __init__(self,actions,epsilon=0.1):\n '''\n A policy with built in epsilon greedy and a uniform random choice for non initialized keys \n actions - list of all possible actions\n epsilon - chance for explore\n '''\n self.actions = actions\n self.eps = epsilon\n super().__init__(self)\n \n def __getitem__(self, key):\n c = random.random()\n if (cscore):\n score = game.score\n # get current state\n s = tuple(game.get_state())\n # choose action\n a = policy[s]\n # update history before moving to the next state\n history.append((s,r,a))\n # apply action\n game.snake.d = a\n # run one game step, get reward and check if episode is finished\n r,e = game.iterate() \n if (e==-1):\n # game is lost, add final dummy state\n history.append((LOSS,r,0))\n # start a new episode\n break\n if (e==1):\n # eat apple, add modified state\n eat = np.array(s)\n eat[-2:] = 0\n history.append((tuple(eat),r,0))\n r = 0\n # update Q returns (values for this episode)\n q_values = []\n value = 0\n for s,r,a in reversed(history):\n q_values.append((s,a,value))\n # update value\n value = r + g*value\n q_values.reverse()\n # update aggregated q_values\n for s,a,v in q_values:\n # aggregated values\n if ((s,a) in agg):\n agg[(s,a)].append(v)\n else:\n agg[(s,a)] = [v]\n # average\n if (s in Q):\n Q[s][a] = np.mean(agg[(s,a)])\n else:\n Q[s] = {}\n Q[s][a] = np.mean(agg[(s,a)])\n # update policy\n for s in Q:\n aq = ([i for i in Q[s].items()])\n a = np.argmax([i[1] for i in aq])\n policy[s] = [i[0] for i in aq][a]\n # print progress\n if (i%1000==0):\n print(i,turns,score)\n# -\n\n# ### Animation\n\n# +\n# render a game animation\nfig, ax = plt.subplots()\nimage = ax.imshow(game.image)\n\ng = Game(grid, s_size)\ng.reset()\n\npolicy.eps = 0\n\ndef init():\n image.set_data(g.image)\n return (image,)\n\ndef animate(i):\n s = g.get_state()\n a = policy[tuple(s)]\n g.snake.d = a\n g.iterate() \n g.draw()\n image.set_data(g.image)\n \n return (image,)\n\nanim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=600, interval=120, \n blit=True)\n# -\n\nanim.save('./movies/iter20000.gif', writer='imagemagick', fps=18)\n\nImage(url='./movies/iter20000.gif')\n\nImage(url='./movies/iter5000.gif')\n\nImage(url='./movies/iter1000.gif')\n\nImage(url='./movies/iter100.gif')\n\nImage(url='./movies/iter1.gif')\n\n\n","repo_name":"ralhadeff/machine-learning-tools","sub_path":"ReinforcementLearning/animations/movie.ipynb","file_name":"movie.ipynb","file_ext":"py","file_size_in_byte":10163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"12816524688","text":"# +\n#importing libraries\n\n# +\nimport numpy as np\nimport pandas as pd\npd.plotting.register_matplotlib_converters()\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# %matplotlib inline\nimport seaborn as sns\nfrom sklearn import preprocessing\n\nprint(\"Setup Complete\")\n# -\n\n#read data\ndataframe=pd.read_csv('Bondora_raw.zip')\n\ndataframe.info()\n\n# +\n#Finding nulls and dropping features with more than 30% nulls\n# -\n\nnulls=[]\n\n\ndef null_values() : \n lst = dataframe.isnull().sum()\n for i in range(len(lst)) :\n if lst[i] != 0 :\n x= lst[i]\n col = dataframe.columns[i]\n y= (x/dataframe.shape[0])*100\n if y >= 30:\n nulls.append(col)\n\n print(\"col num : \" +str(i) + \" / \" + col + \" / \" + str(x) + \" nulls /\"+ str(round(y,2)) +\" %\")\nnull_values()\n\nnulls\n\ndataframe=dataframe.drop(columns= nulls,axis=1)\ndataframe\n\n# +\ndataframe['ReportAsOfEOD']= pd.to_datetime(dataframe['ReportAsOfEOD'],format=\"%Y-%m-%d\")\n\ndataframe['ReportAsOfEOD'].unique()\n# -\n\ndataframe=dataframe.drop(columns='ReportAsOfEOD',axis=1)\ndataframe\n\n# +\n#spiliting ( num , obj , bool ) \n# -\n\nobj_data=dataframe.select_dtypes('object')\nnum_dataframe=dataframe.drop(obj_data.columns,axis=1)\nnum_dataframe\n\nbool_data= num_dataframe.select_dtypes('bool')\nbool_data.isnull().sum()\n\n# +\n#encoding bool data\n\nlabel_encoder = preprocessing.LabelEncoder()\n\nbool_data['NewCreditCustomer']= label_encoder.fit_transform(bool_data['NewCreditCustomer'])\nbool_data['ActiveScheduleFirstPaymentReached']= label_encoder.fit_transform(bool_data['ActiveScheduleFirstPaymentReached'])\nbool_data['Restructured']= label_encoder.fit_transform(bool_data['Restructured'])\n\nbool_data\n# -\n\nbool_data['NewCreditCustomer']\n\nobj_data.isnull().sum()\n\n\n# +\n#Filling missing data\n# -\n\nobj_data=obj_data.fillna('unkown')\n\nobj_data.isnull().sum()\n\n\ndef fill_with_median(col,data):\n for i in col:\n median=data[i].median()\n data[i]= data[i].fillna(value=median,axis=0)\nfill_with_median(num_dataframe.columns,num_dataframe) \n\nnum_dataframe.isnull().sum()\n\nnum_dataframe\n\n# +\nnum_cat=num_dataframe[['Education','EmploymentStatus','HomeOwnershipType','LanguageCode','MaritalStatus','UseOfLoan']]\n\nnum_dataframe=num_dataframe.drop(num_cat,axis=1)\nnum_dataframe=num_dataframe.drop(bool_data.columns,axis=1)\n# -\n\nnum_dataframe\n\n\n# +\n#inding outliers and replace it with nearst value in range ( upper limit , lower limit )\n\n# +\ndef find_outliers_IQR(df_col,df):\n for i in df_col:\n q1=df[i].quantile(0.25)\n\n q3=df[i].quantile(0.75)\n\n IQR=q3-q1\n upper_lim=q3+1.5*IQR\n lower_lim=q1-1.5*IQR\n outliers = df[i][((df[i]<(q1-1.5*IQR)) | (df[i]>(q3+1.5*IQR)))]\n\n outliers_lower = df[i][((df[i]<(lower_lim)))]\n df[i][outliers_lower.index]=(q1-1.5*IQR)\n \n \n \n outliers_upper = df[i][((df[i]>(upper_lim)))]\n df[i][outliers_upper.index]=(q3+1.5*IQR)\n \n \n print(i)\n print(outliers.count() )\n \n\n# -\n\nfind_outliers_IQR(num_dataframe.columns,num_dataframe)\n\n\ndef find_outliers_IQR(df_col,df):\n \n for i in df_col:\n q1=df[i].quantile(0.25)\n\n q3=df[i].quantile(0.75)\n\n IQR=q3-q1\n\n outliers = df[i][((df[i]<(q1-1.5*IQR)) | (df[i]>(q3+1.5*IQR)))]\n \n print(i)\n print(outliers.count() )\nfind_outliers_IQR(num_dataframe.columns,num_dataframe)\n\n# plotting box plot for features \nnum_dataframe.plot(kind='box', subplots=True,figsize=(50,50), layout=(10,8))\nplt.show()\n\nnum_dataframe\n\n# +\n#visualizing range of borrow age and their genders\n\n# +\nsns.set_theme(style=\"darkgrid\")\n\nsns.kdeplot(num_dataframe['Age'],shade=True)\n\n# +\n#plotting bool data\nsns.set_theme(style=\"darkgrid\")\n\nfeatures_bool_data= list(bool_data.columns)\nfeatures_bool_data_viz= [\"NewCreditCustomer\", \"ActiveScheduleFirstPaymentReached\",\"Restructured\"]\nfor i in features_bool_data_viz:\n bool_data[i].value_counts().plot(kind='bar', figsize=(5,5))\n plt.title(i)\n plt.show()\n\n# +\n#exploring features with wrong inputs and deal with it\n# -\n\nnum_cat['EmploymentStatus'].unique()\n\n# +\nsns.set_theme(style=\"darkgrid\")\n\nplt.subplot(1,2,1)\nplt.figure(figsize = (6, 4))\n\nround(num_cat['EmploymentStatus'].value_counts()/num_cat.shape[0]*100,2).plot.pie( autopct = '%.2f%%',\n textprops = {'size' : 'x-large','color' : '0'},explode = (0.1, 0.1,0.1,0.1,0.1,0.1,0.1))\n\nplt.figure(figsize = (6, 4))\n\nplt.subplot(1,2,2)\nsns.countplot(num_cat['EmploymentStatus'],palette='deep')\nplt.show()\n# -\n\n# drop feature because it contain large number of wrong values\nnum_cat=num_cat.drop('EmploymentStatus',axis=1)\n\nnum_cat\n\nnum_cat['Education'].unique()\n\n# +\nsns.set_theme(style=\"darkgrid\")\n\nsns.countplot(num_cat['Education'],palette='deep')\nplt.title('Education', fontsize = 18, fontweight = 'bold')\n# -\n\nbool_data['NewCreditCustomer']\n\n\nnum_cat['UseOfLoan'].unique()\n\n# +\nsns.set_theme(style=\"darkgrid\")\n\nsns.countplot(num_cat['UseOfLoan'],palette='deep')\nplt.title('Use Of Loan', fontsize = 18, fontweight = 'bold')\n# -\n\nnum_cat=num_cat.drop('UseOfLoan',axis=1)\n\nnum_cat\n\nnum_cat['MaritalStatus'].unique()\n\n\n# +\nsns.set_theme(style=\"darkgrid\")\n\nsns.countplot(num_cat['MaritalStatus'], palette='deep')\nplt.title('Martial State', fontsize = 18, fontweight = 'bold')\n# -\n\nnum_cat=num_cat.drop('MaritalStatus',axis=1)\n\nnum_cat['HomeOwnershipType'].unique()\n\n# +\nsns.set_theme(style=\"darkgrid\")\n\nsns.countplot(num_cat['HomeOwnershipType'],palette='deep')\nplt.title('Home Onwership Type', fontsize = 18, fontweight = 'bold')\n\n# +\nsns.set_theme(style=\"darkgrid\")\n\nsns.countplot(num_cat['LanguageCode'],palette='deep')\nplt.title('Language Code', fontsize = 18, fontweight = 'bold')\n\n# +\n#corr between num features\n\nplt.figure(figsize = (45, 45))\n\nsns.heatmap(num_dataframe.corr(), annot=True)\n\n# +\nsns.set_theme(style=\"darkgrid\")\n\nsns.lineplot(x=num_dataframe['Interest'], y=num_dataframe['ProbabilityOfDefault'],color='teal')\n# -\n\n\n\n\n\n\n\n\n","repo_name":"Satakshi20/Technocolabs","sub_path":"EDA.ipynb","file_name":"EDA.ipynb","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"4172433108","text":"# ## House price prediction\n\n# - Data understanding and exploration\n# - Data Visualisation \n# - Data preparation\n# - Feature Selection with RFE\n# - Model building and evaluation with LinearRegression\n# - Apply regularization using Lasso and Ridge\n\n# ### Data understanding and exploration\n# 1. Load the data\n# 2. Handle Nan in columns either by deleting the columns or imputing them\n# 3. Apply log transformation for the predictor variable\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn import linear_model,metrics\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#Load the the data\ndf= pd.read_csv('train.csv')\n\ndf.head()\n\n# check the percentage of nulls in a column\n#Printing columns only with non zero NA's\nnan_columns=df.isna().any()\ncols=df.columns[nan_columns]\nround((df[cols].isnull().sum()/len(df.index))*100,2)\n\n\n# Nan replacement \ndef nan_replacement(column_name,default_val):\n df[column_name].replace(np.nan, default_val,inplace=True)\n\n\n# replaced column Nan with following values\nnan_replacement('Alley','No Alley')\nnan_replacement('MasVnrType','None')\nnan_replacement('MasVnrArea',0)\nnan_replacement('BsmtExposure','No Basement')\nnan_replacement('BsmtFinType1','No Basement')\nnan_replacement('BsmtFinType2','No Basement')\nnan_replacement('BsmtQual','No Basement')\nnan_replacement('BsmtCond','No Basement')\nnan_replacement('FireplaceQu','No Fireplace')\nnan_replacement('GarageType','No Garage')\nnan_replacement('GarageFinish','No Garage')\nnan_replacement('GarageQual','No Garage')\nnan_replacement('GarageCond','No Garage')\nnan_replacement('MiscFeature','None')\nnan_replacement('Fence','No Fence')\nnan_replacement('PoolQC','No Pool')\n\n# check the percentage of nulls in a column\n#Printing columns only with non zero NA's\nnan_columns=df.isna().any()\ncols=df.columns[nan_columns]\ndf[cols].isnull().sum()\n\ndf.LotFrontage.describe()\n\n# Imputing LotFrontage with Median\nimputeval=df.LotFrontage.median()\nnan_replacement('LotFrontage',imputeval)\n\n# drop row not having Electrical \ndf= df[~(df.Electrical.isna())]\n\ndf.shape\n\n# dropping GarageYrBlt\ndf.drop(columns='GarageYrBlt',inplace=True)\n\n# No column has missing null values\ndf.columns.isnull().sum()\n\n# dropping Id as all values are unique\ndf.drop(columns='Id',inplace=True)\n\n# encode with only 2 types\ndf['Street']= df.Street.map({'Pave':0,'Grvl':1})\ndf['Utilities']= df.Utilities.map({'AllPub':0,'NoSeWa':1})\ndf['CentralAir']=df.CentralAir.map({'Y':0,'N':1})\n\n#ordinal columns\nordinal_cols=['ExterQual', 'ExterCond','HeatingQC','KitchenQual']\n\n\ndef ordinalCategColToNumeric(cols,df=df):\n for col in cols:\n df[col]=df[col].map({'NA':0,'Po':1,'Fa':2,'TA':3,'Gd':4,'Ex':5})\n df[col]=df[col].fillna(0).astype(np.int64)\n\n\nordinalCategColToNumeric(ordinal_cols)\n\n\n# Custom method to plot numeric columns which has scatterplot of column vs Saleprice and \n#to check the distribution of column using\n# distplot and boxplot\ndef plotNumericCols(column, figsize=(16,4),rotation =0):\n fig,axes=plt.subplots(1,2,figsize=figsize)\n sns.scatterplot(x=df[column],y=df.SalePrice,ax=axes[0])\n sns.boxplot(x=df[column],ax=axes[1])\n axes[0].title.set_text('Saleprice vs '+column)\n axes[1].title.set_text('Distribution of '+column)\n plt.show()\n\n\nsns.distplot(df.SalePrice)\n\n# #### As the SalePrice is positively skewed , we will apply log transformation.\n\ndf.SalePrice=df.SalePrice.apply(lambda x: np.log(x))\n\nsns.distplot(df.SalePrice)\n\nsns.boxplot(df.SalePrice)\n\n\n# recursively remove the outliers\ndef removeOutliers(column_name,df):\n flag=False\n while ~flag:\n Q1=np.percentile(df[column_name],25)\n Q3=np.percentile(df[column_name],75)\n IQR=Q3-Q1\n upperFence= Q3+(1.5*IQR)\n lowerFence=Q1-(1.5*IQR)\n temp_df= df[(df[column_name]>=lowerFence) & (df[column_name]<=upperFence)]\n if (len(df)-len(temp_df)) ==0:\n return df\n else:\n df=temp_df\n\n\ndf.columns\n\ndf=removeOutliers('SalePrice',df)\n\ndf.shape\n\nsns.boxplot(df.SalePrice)\n\n# There are no outliers now in SalePrice\n\n# ### Data Exploration\n# 1.Plot scatterplot and boxplot for numeric columns\n# 2.Plot boxplot and countplots for non-numeric columns\n\nplotNumericCols('TotalBsmtSF')\n\n# Values after 3000 are too far away from the whiskers , Hence dropping them\n\ndf= df[df.TotalBsmtSF <3000]\nplotNumericCols('TotalBsmtSF')\n\n# With increase in total basement sf, sale price also increases.\n\nplotNumericCols('BsmtUnfSF')\n\n# As BsmntUnfSF increases , saleprice also increases\n\nplotNumericCols('BsmtFinSF2')\n\n# Looks like very few rows have non zero values for BsmtFinSF2 and no pattern seen.\n\nplotNumericCols('BsmtFinSF1')\n\n# With increase in BsmtFinSF1, sale price also increases\n\nplotNumericCols('MasVnrArea')\n\n# Most of the rows have MasVnrArea as zero and with increase in MasVnrArea, SalePrice also increases\n\ndf['remodelledAge']= df.YearRemodAdd.apply(lambda x : 2020-x)\ndf.drop(columns=['YearRemodAdd'],inplace=True)\n\n# As YearRemodAdd increases SalePrice also increases\n\nplotNumericCols('remodelledAge')\n\ndf['age']= df.YearBuilt.apply(lambda x : 2020-x)\ndf.drop(columns=['YearBuilt'],inplace=True)\n\n# As YearBuilt increases SalePrice also increases\n\nplotNumericCols('age')\n\nplotNumericCols('LotArea')\n\ndf= df[df.LotArea <100000]\nplotNumericCols('LotArea')\n\nplotNumericCols('MSSubClass')\n\n# Need to consider MSSubClas as categorical column instead of numeric\n\ndf.MSSubClass=df.MSSubClass.astype('object')\n\nplotNumericCols('1stFlrSF')\n\n# 1stFlrSF has outliers after 2500. Hence removing them \n\ndf=df[df['1stFlrSF'] <2500]\nplotNumericCols('1stFlrSF')\n\n# As 1stFlrSF increases, SalePrice increases\n\nplotNumericCols('2ndFlrSF')\n\n# As 2ndFlrSF increases , SalePrice increases\n\nplotNumericCols('LowQualFinSF')\n\n# Most of the LowQualFinSF is zeros, no pattern seen for non-zeros\n\nplotNumericCols('GrLivArea')\n\n# As GrLivArea increases SalePrice also increases.\n\nplotNumericCols('GarageArea')\n\ndf= df[df.GarageArea <1200]\nplotNumericCols('GarageArea')\n\n# As GarageArea increases SalePrice also increases\n\nplotNumericCols('WoodDeckSF')\n\n# No Pattern seen for WoodDeckSF\n\nplotNumericCols('OpenPorchSF')\n\n# No Pattern seen for OpenPorchSF\n\nplotNumericCols('EnclosedPorch')\n\n# No Pattern seen for EnclosedPorch\n\nplotNumericCols('3SsnPorch')\n\nplotNumericCols('ScreenPorch')\n\nplotNumericCols('PoolArea')\n\n# As there are very few rows having pool , we will convert this to yes or no\n\nplotNumericCols('MiscVal')\n\nplotNumericCols('MoSold')\n\n# No pattern seen for month dropping the month column\n\ndf.drop(columns=['MoSold'], inplace=True)\n\nplotNumericCols('YrSold')\n\n# No pattern seen for Year sold . Dropping the columns\n\ndf.drop(columns=['YrSold'], inplace=True)\n\ndf.columns\n\ndf_object= df.select_dtypes(include=['object'])\nlen(df_object.columns)\n\ndf_object.columns\n\n\n# Custom method to check the categorical data\ndef plotgraphs(column, figsize=(13,4),rot=0):\n fig,axes=plt.subplots(1,2,figsize=figsize)\n sns.boxplot(x=df[column],y=df.SalePrice,ax=axes[0])\n sns.countplot(x=df[column],ax=axes[1])\n axes[0].tick_params('x',labelrotation=rot)\n axes[1].tick_params('x',labelrotation=rot)\n axes[0].title.set_text('Distribution of SalePrice with '+column)\n axes[1].title.set_text('count of '+column)\n plt.show()\n\n\nplotgraphs('MSSubClass')\n\nplotgraphs('Street')\n\n# Most of the rows have the street as 0 , so dropping the street columns\n\ndf.drop(columns=['Street'], inplace=True)\n\nplotgraphs('Alley')\n\n# As Alley is highly skewed , dropping the column\n\ndf.drop(columns=['Alley'], inplace=True)\n\nplotgraphs('LotShape')\n\nplotgraphs('LandContour')\n\n# As most of the rows have Lvl, dropping the column\n\ndf.drop(columns=['LandContour'],inplace=True)\n\nplotgraphs('Utilities')\n\n# Most of the rows have Utilities as 0. Dropping the column\n\ndf.drop(columns=['Utilities'], inplace=True)\n\nplotgraphs('LotConfig')\n\nplotgraphs('LandSlope')\n\n# LandSlope column has Gtl value for most ot columns. Hence dropping the column\n\ndf.drop(columns=['LandSlope'], inplace=True)\n\nplotgraphs('Neighborhood',figsize=(18,4),rot=45)\n\nplotgraphs('Condition1')\n\n# Most of the rows have Norm for condition1 . Hence dropping the column\n\ndf.drop(columns=['Condition1'],inplace=True)\n\nplotgraphs('Condition2')\n\n# droping the condition 2 as most of them have rows as norm\ndf.drop(columns=['Condition2'],inplace=True)\n\nplotgraphs('BldgType')\n\nplotgraphs('HouseStyle')\n\ndf.HouseStyle.value_counts()\n\nplotgraphs('RoofStyle')\n\n# As, data is skewed , Dropping the column.\n\ndf.drop(columns=['RoofStyle'],inplace=True)\n\nplotgraphs('RoofMatl')\n\ndf.drop(columns=['RoofMatl'],inplace=True)\n\nplotgraphs('Exterior1st',rot=45)\n\ndf.Exterior1st.value_counts()\n\n# Considering the types having count less than 40 as others\notherList=['ImStucc','CBlock','AsphShn','BrkComm','Stone','AsbShng','Stucco','WdShing']\ndf.Exterior1st=df.Exterior1st.apply(lambda x : 'Others' if x in otherList else x)\ndf.Exterior1st.value_counts()\n\nplotgraphs('Exterior2nd',rot=45)\n\ndf.Exterior2nd.value_counts()\n\n# Considering the types having count less than 40 as others\notherList=['ImStucc','CBlock','AsphShn','Brk Cmn','Stone','AsbShng','BrkFace','Stucco','Wd Shng']\ndf.Exterior2nd=df.Exterior2nd.apply(lambda x : 'Other' if x in otherList else x)\ndf.Exterior2nd.value_counts()\n\nplotgraphs('MasVnrType')\n\nplotgraphs('Foundation')\n\notherList=['Wood','Slab','Stone']\ndf.Foundation=df.Foundation.apply(lambda x : 'Other' if x in otherList else x)\ndf.Foundation.value_counts()\n\nplotgraphs('BsmtExposure')\n\nplotgraphs('BsmtFinType1')\n\nplotgraphs('BsmtFinType2')\n\n# AS column values are highly skewed , dropping the column\n\ndf.drop(columns='BsmtFinType2',inplace=True)\n\nplotgraphs('Heating')\n\n# AS column values are highly skewed , dropping the column\n\ndf.drop(columns=['Heating'], inplace=True)\n\nplotgraphs('CentralAir')\n\n# AS column values are highly skewed , dropping the column\n\ndf.drop(columns=['CentralAir'], inplace=True)\n\nplotgraphs('Electrical')\n\n# AS column values are highly skewed , dropping the column\n\ndf.drop(columns=['Electrical'], inplace=True)\n\nplotgraphs('Functional')\n\n# AS column values are highly skewed , dropping the column\n\ndf.drop(columns=['Functional'], inplace=True)\n\nplotgraphs('GarageType')\n\notherList=['No Garage','Basement','2Types','CarPort']\ndf.GarageType=df.GarageType.apply(lambda x : 'Other' if x in otherList else x)\ndf.GarageType.value_counts()\n\nplotgraphs('GarageFinish')\n\nplotgraphs('PavedDrive')\n\n# AS column values are highly skewed , dropping the column\n\ndf.drop(columns=['PavedDrive'], inplace=True)\n\nplotgraphs('Fence')\n\n# AS column values are highly skewed , dropping the column\n\ndf.drop(columns=['Fence'], inplace=True)\n\nplotgraphs('MiscFeature')\n\ndf.drop(columns=['MiscFeature'],inplace=True)\n\nplotgraphs('SaleType')\n\ndf.SaleType.value_counts()\n\n# Considering the types having count less than 40 as others\notherList=['ConLI','CWD','ConLw','Oth','Con']\ndf.SaleType=df.SaleType.apply(lambda x : 'Other' if x in otherList else x)\ndf.SaleType.value_counts()\n\nplotgraphs('SaleCondition')\n\n# ### Create dummies for object dtypes\n\ndf_numeric= df.select_dtypes(include=['float64','int64'])\n\nlen(df_numeric.columns)\n\ndf_object= df.select_dtypes(include=['object'])\n\nlen(df_object.columns)\n\n# create dummies for categorical variables\ndf_dummies=pd.get_dummies(df_object,drop_first=True)\ndf_dummies.head()\n\n# concat numerical and dummy columns\ndf=df.drop(columns=list(df_object.columns),axis=1)\n\ndf= pd.concat([df,df_dummies],axis=1)\n\ndf.shape\n\ny= df.pop('SalePrice')\nX=df\n\nX=df\n\n# split test and train data\nfrom sklearn.model_selection import train_test_split\nnp.random.seed(0)\nX_train,X_test,y_train,y_test= train_test_split(X,y,train_size=0.7,test_size=0.3,random_state=100)\n\n# Scale test and train data\nfrom sklearn.preprocessing import MinMaxScaler\nscaler= MinMaxScaler()\ncols=X_train.columns\nX_train[cols]= scaler.fit_transform(X_train[cols])\nX_test[cols]= scaler.transform(X_test[cols])\n\n# ### RFE to select top attributes\n\nfrom sklearn.feature_selection import RFE\n\nX_train.describe()\n\nregression=LinearRegression()\nmodel=RFE(regression,30).fit(X_train,y_train)\ntop_features= X.columns[model.support_]\ntop_features\n\nimport statsmodels.api as sm\n\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\n# #### p-value for 1stFlrSF is greater than 0.05 . Hence we are not considering the column\n\ntop_features=top_features.drop('1stFlrSF')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\n# #### p-value for Neighborhood_Blueste is greater than 0.05 . Hence we are not considering the column\n\ntop_features=top_features.drop('Neighborhood_Blueste')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\n# #### p-value for 2ndFlrSF is greater than 0.05 . Hence we are not considering the column\n\ntop_features=top_features.drop('2ndFlrSF')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\n# #### p-value for Exterior2nd_Other is greater than 0.05 . Hence we are not considering the column\n\ntop_features=top_features.drop('Exterior2nd_Other')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\n# #### p-value for Exterior1st_CemntBd is greater than 0.05 . Hence we are not considering the column\n\ntop_features=top_features.drop('Exterior1st_CemntBd')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\n# p-value for Exterior2nd_MetalSd is greater than 0.05 . Hence we are not considering the column\n\ntop_features=top_features.drop('Exterior2nd_MetalSd')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\n# #### p-value for Exterior2nd_VinylSd is greater than 0.05 . Hence we are not considering the column\n\ntop_features=top_features.drop('Exterior2nd_VinylSd')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\ntop_features=top_features.drop('Exterior2nd_Wd Sdng')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\ndef printVIF(col , X_train):\n vif = pd.DataFrame()\n vif['Features'] = col\n vif['VIF'] = [variance_inflation_factor(X_train[col].values, i) for i in range(X_train[col].shape[1])]\n vif['VIF'] = round(vif['VIF'], 2)\n vif = vif.sort_values(by = \"VIF\", ascending = False)\n print(vif)\n\n\n# Checking the VIF values\nprintVIF(top_features,X_train)\n\ntop_features=top_features.drop('PoolQC_No Pool')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\ntop_features=top_features.drop('PoolArea')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\ntop_features=top_features.drop('Exterior2nd_Plywood')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nprintVIF(top_features,X_train)\n\ntop_features=top_features.drop('SaleType_New')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nprintVIF(top_features,X_train)\n\ntop_features=top_features.drop('ExterCond')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nprintVIF(top_features,X_train)\n\ntop_features=top_features.drop('OverallCond')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nprintVIF(top_features,X_train)\n\ntop_features=top_features.drop('GarageCars')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\ntop_features=top_features.drop('Exterior2nd_HdBoard')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nprintVIF(top_features,X_train)\n\nplt.figure(figsize=(10,8))\nsns.heatmap(X_train[top_features].corr(),annot=True)\nplt.show()\n\ntop_features=top_features.drop('TotalBsmtSF')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nprintVIF(top_features,X_train)\n\nplt.figure(figsize=(10,8))\nsns.heatmap(X_train[top_features].corr(),annot=True)\nplt.show()\n\ntop_features=top_features.drop('OverallQual')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nprintVIF(top_features,X_train)\n\ntop_features=top_features.drop('KitchenQual')\nX_train_sm= sm.add_constant(X_train[top_features])\nlr=sm.OLS(y_train,X_train_sm).fit()\nlr.summary()\n\nprintVIF(top_features,X_train)\n\n# ## Ridge\n\n# create model with ridge\nridge=Ridge()\nfolds=5\nparams={'alpha':[0.0001,0.001,0.01,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,2,3,4,5,6,7,8,9,10,20,50,100,500,1000]}\nridge_cv=GridSearchCV(estimator=ridge,param_grid=params,\n scoring='neg_mean_absolute_error',cv=folds,\n return_train_score=True,verbose=1)\nridge_cv.fit(X_train[top_features],y_train)\n\ncv_results=pd.DataFrame(ridge_cv.cv_results_)\ncv_results.head()\n\nridge_cv.best_score_\nridge_cv.best_score_\n\nridge_cv.best_params_\n\ncv_results=cv_results[cv_results['param_alpha']<200]\n\ncv_results['param_alpha']=cv_results['param_alpha'].astype('int32')\nplt.plot(cv_results['param_alpha'],cv_results['mean_train_score'])\nplt.plot(cv_results['param_alpha'],cv_results['mean_test_score'])\nplt.xlabel('alpha')\nplt.ylabel('Negative Mean Absolute Error')\nplt.title('Negative Mean Absolute Error and alpha')\nplt.legend(['train score','test score'],loc='upper left')\nplt.show()\n\nalpha=0.3\nridge=Ridge(alpha=alpha)\nridge.fit(X_train[top_features],y_train)\n\n# get r2 score\ny_train_pred= ridge.predict(X_train[top_features])\n\ntrain_r2score= metrics.r2_score(y_train,y_train_pred)\nprint(train_r2score)\n\ny_test_pred=ridge.predict(X_test[top_features])\ntest_r2score= metrics.r2_score(y_test,y_test_pred)\nprint(test_r2score)\n\narr=ridge.coef_\ncount=0\nridge_coef={}\nfor ind,i in enumerate(arr):\n if ~(i==0):\n count=count+1\n ridge_coef[X_train[top_features].columns[ind]]=i\nprint(count)\n\nridge_coef['intercept']=ridge.intercept_\n\nridge_coef\n\n# ### Lasso\n\nlasso=Lasso()\n\n# create model with lasso\nfolds=5\nlasso_cv=GridSearchCV(estimator=lasso,param_grid=params,\n scoring='neg_mean_absolute_error',cv=folds,\n return_train_score=True,verbose=1)\nlasso_cv.fit(X_train[top_features],y_train)\n\ncv_results=pd.DataFrame(lasso_cv.cv_results_)\ncv_results=cv_results[cv_results['param_alpha']<10]\ncv_results.head()\n\ncv_results['param_alpha']=cv_results['param_alpha'].astype('int32')\nplt.plot(cv_results['param_alpha'],cv_results['mean_train_score'])\nplt.plot(cv_results['param_alpha'],cv_results['mean_test_score'])\nplt.xlabel('alpha')\nplt.ylabel('Negative Mean Absolute Error')\nplt.title('Negative Mean Absolute Error and alpha')\nplt.legend(['train score','test score'],loc='upper left')\nplt.show()\n\nlasso_cv.best_params_\n\nalpha =0.0001\nlasso= Lasso(alpha=alpha)\nlasso.fit(X_train[top_features],y_train)\n\narr=lasso.coef_\ncount=0\nlasso_coef={}\nfor ind,i in enumerate(arr):\n if ~(i==0):\n count=count+1\n lasso_coef[X_train[top_features].columns[ind]]=i\nprint(count)\n\nlasso_coef['intercept']=lasso.intercept_\n\nlasso.intercept_\n\n# r2score on train data\nlasso_train_pred= lasso.predict(X_train[top_features])\nlasso_train_r2score= metrics.r2_score(y_train,lasso_train_pred)\nlasso_train_r2score\n\n# r2score on test data\nlasso_test_pred= lasso.predict(X_test[top_features])\nlasso_test_r2score= metrics.r2_score(y_test,lasso_test_pred)\nlasso_test_r2score\n\nlasso_coef\n\n# ### Residual Analysis\n\nfig = plt.figure()\nsns.distplot((y_test - lasso_test_pred), bins = 20)\n# Plot heading\nfig.suptitle('Lasso Terms', fontsize = 20) \n# Give the X-label\nplt.xlabel('Errors', fontsize = 18)\n\n# #### Error terms are normally distributted with mean zero\n\nfig = plt.figure()\nsns.distplot((y_test - y_test_pred), bins = 20)\n# Plot heading\nfig.suptitle('Ridge Error Terms', fontsize = 20) \n# Give the X-label\nplt.xlabel('Errors', fontsize = 18)\n\n# ## We will use Lasso Regression\n\n# ### Model can be predicted with following formula\n\n# #### math.exp(11.719520394448518+LotArea*(0.3057204613235849)+BsmtFinSF1*(0.2702133910347825)\n# #### +GrLivArea*(1.1954197777988813)+KitchenAbvGr*(-0.41796213659986353)+OpenPorchSF*(0.16046288072739243)\n# #### +ScreenPorch*(0.1183569121474998)+age*(-0.6811100206299725)+MSSubClass_160*(-0.1461495721685714)\n# #### +Neighborhood_Crawfor*(0.22622654125514555)+Neighborhood_MeadowV*(-0.24032666583170104)+SaleCondition_Partial*(0.1331327320451184))\n\n\n","repo_name":"mounicayelchuri/HousePricePrediction","sub_path":"Housepricing.ipynb","file_name":"Housepricing.ipynb","file_ext":"py","file_size_in_byte":20952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"17107510536","text":"# # 328 Odd Even Linked List\n# - given head of singly linked list, return a reordered list with all odd numbered indices first followed by all the even numbered indices\n# - first node is odd, second is even and so on\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\ndef odd_even_list(head):\n if head is None:\n return head\n \n odd = head\n even = head.next\n even_head = even\n \n while even is not None and even.next is not None:\n odd.next = even.next\n odd = odd.next\n even.next = odd.next\n even = even.next\n \n odd.next = even_head\n return head\n\n\ntest1 = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))\nresult = odd_even_list(test1)\nwhile result is not None:\n print(result.val)\n result = result.next\n\n\n","repo_name":"owenmccadden/data_structures_and_algorithms","sub_path":"linked_lists/.ipynb_checkpoints/328_odd_even_linked_list-checkpoint.ipynb","file_name":"328_odd_even_linked_list-checkpoint.ipynb","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"4901850816","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"uCaR8SOjNmfS\"\nimport numpy as np\n\n# + id=\"moeblV0gOS22\"\nfirst_numpy_array = np.array([1,2,3,4])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1lhudMRVOZxY\" outputId=\"d37f7840-e19e-423a-b3ed-f355600c09c0\"\nprint(first_numpy_array)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VT5LC5CBOcSX\" outputId=\"3150a2ee-6103-40f8-a330-450b08feaa86\"\narray_zero = np.zeros((3,3))\narray_zero\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4HTctU22Ojqw\" outputId=\"5f8f1ea5-11b4-4f3d-a3e6-0002657f2032\"\narray_ones= np.ones((3,3))\narray_ones\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-OgVVCAFOoUl\" outputId=\"6a1e4475-0d09-4678-c737-c4e33724e0ea\"\narray_empty = np.empty((2,3))\narray_empty\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"qnVflZsdOx_l\" outputId=\"9a5179a3-ae57-4290-98bc-dc176ee013b5\"\nnp_arange = np.arange(12)\nprint(np_arange)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ZjcWyC-TO3f-\" outputId=\"67956883-2fda-422e-f39c-62359218562e\"\nnp_arange.reshape(3,4)\n\n# + id=\"d2uFNunmPBKE\"\nnp_linspace = np.linspace(1,6,5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"AV7JGPrRPKCv\" outputId=\"172cc527-7abb-4ca5-d849-cf10c96046eb\"\nprint(np_linspace)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"BdZ7HiXDPNOR\" outputId=\"2e230975-bb78-49ba-9984-ccd825885573\"\noneD_array = np.arange(15)\nprint(oneD_array)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Y_8pA6eUPcqd\" outputId=\"8d8a425b-0756-4226-867f-35b7621f057f\"\ntwoD_arr = oneD_array.reshape(3,5)\nprint(twoD_arr)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"AtjNkVeqPi5U\" outputId=\"b176c0eb-13ec-4a33-93e4-5df1ed22d82d\"\nthreeD_array = np.arange(27).reshape(3,3,3)\nprint(threeD_array)\n\n# + id=\"YoVqzuyhPudV\"\n\n\n# + [markdown] id=\"onPa_VolfWRa\"\n# SciPy - Eigenvalues and Eigenvector\n\n# + id=\"bGoEPnb_fg7s\"\nimport numpy as np\nfrom scipy import linalg\n\n# + id=\"ByuV-m2Efx9w\"\ntest_rating_data = np.array([[5,8],[7,9]])\neigenValues, eigenVector = linalg.eig(test_rating_data)\nfirst_eigen, second_eigen = eigenValues\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-RRZQxKAgR4F\" outputId=\"bb6efadb-8a3c-4fde-da74-b961ac86d7d7\"\nprint(first_eigen, second_eigen)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"HTnIiGvFgYcl\" outputId=\"e8712207-dcba-495b-9f1b-6857f51900de\"\nprint(eigenVector[:,0])\n\n# + id=\"pFzzZzZfgfhr\"\n\n\n# + [markdown] id=\"Ppr0o7hPgsTn\"\n# SciPy - CDF and PDF\n\n# + id=\"0ZRMt8celdCS\"\nfrom scipy.stats import norm\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pFFLcIpalgjb\" outputId=\"3b17d864-dc3c-4cfa-e408-2510522b0b3e\"\nnorm.rvs(loc=0,scale=1,size=20)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"CC6tvKuslpMp\" outputId=\"9143d0d3-2ae1-4409-f089-712c1b951654\"\n#Cumulative Distribution Function\nnorm.cdf(10, loc=1,scale=3)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"RzAyuQUYmc3V\" outputId=\"0b7182d8-ecfb-4fe9-8dae-48d76a7c0d8e\"\n#Probability Density Function\nnorm.pdf(14,loc=1,scale=1)\n\n# + id=\"IY63kXJkmorI\"\n\n\n# + id=\"nHP-InYRtrsf\"\n\n\n# + [markdown] id=\"xKzV-YTBtmUa\"\n# Web Scraping - Navigating the Tree\n\n# + id=\"bkEn62wntsbv\"\nfrom bs4 import BeautifulSoup\n\n# + id=\"Mt6Aak0FtzNb\"\nbook_html_doc = \"\"\n\n# + id=\"gsyspviTuGrk\"\n\n","repo_name":"khushboo-gehi/Data-Science-Projects-in-Python","sub_path":"_DSPy.ipynb","file_name":"_DSPy.ipynb","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"43015750568","text":"# +\n# Imports here\n# %matplotlib inline\n# %config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\n### Import packages\nimport torch\nimport numpy as np\nfrom torch import nn, optim\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom torchvision import datasets, transforms, models\nfrom PIL import Image\nimport os\n\n\n# -\n\ndef predict(image_path, model,device='cpu'):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n model.eval()\n eval_img = process_image(image_path)\n eval_img = eval_img.unsqueeze(0).to(device)\n logits = model.forward(eval_img)\n ps = F.softmax(logits, dim=1)\n return ps\n\n\n# +\nfrom collections import OrderedDict\ndef load_base_model(device, classes):\n model = models.resnet152(pretrained=True)\n\n ## Freeze parameters so we don't backprop through them\n for param in model.parameters():\n param.requires_grad = False\n \n for param in model.layer3.parameters():\n param.requires_grad = False\n \n for param in model.layer4.parameters():\n param.requires_grad = False\n\n \n fc = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(2048, 1024)),\n ('relu', nn.ReLU()),\n ('fc2', nn.Linear(1024, len(classes))),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n\n model.fc = fc\n model.to(device)\n return model\n\ndef load_checkpoint(device, classes):\n model = load_base_model(device, classes)\n temp_model = torch.load('model_resnet_maxaccu_152_p99.pt', map_location=lambda storage, loc: storage)\n fc = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(2048, 1024)),\n ('relu', nn.ReLU()),\n ('fc2', nn.Linear(1024, len(temp_model['fc.fc2.weight']))),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n model.fc = fc\n model.load_state_dict(torch.load('model_resnet152_p99.pt', map_location=lambda storage, loc: storage))\n return model\n\n\n# +\ndef imshow(image, ax=None, title=None, normalize=True):\n \"\"\"Imshow for Tensor.\"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n image = image.numpy().transpose((1, 2, 0))\n\n if normalize:\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = std * image + mean\n image = np.clip(image, 0, 1)\n\n ax.imshow(image)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.tick_params(axis='both', length=0)\n ax.set_xticklabels('')\n ax.set_yticklabels('')\n\n return ax\n\ndef top_classes(img_path, model, device, classes):\n processed_image = process_image(img_path)\n img_result = predict(img_path, model, device)\n probs, idx = torch.topk(img_result, 10)\n probs,idx = probs.squeeze(), idx.squeeze()\n \n title = img_path\n img = Image.open(img_path)\n \n labels = []\n probabilities = []\n for i,prob in enumerate(probs):\n labels.append(classes[idx[i].item()])\n probabilities.append(prob.item())\n print(img_result.size())\n \n fig, (ax1, ax2) = plt.subplots(figsize=(6,10), ncols=1, nrows=2)\n ax1.set_title(title)\n ax1.imshow(img)\n ax1.axis('off')\n y_pos = np.arange(len(probabilities))\n ax2.barh(y_pos, probabilities)\n ax2.set_yticks(y_pos)\n ax2.set_yticklabels([x for x in labels])\n ax2.invert_yaxis()\n \n \ndef process_image(image):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n \n # TODO: Process a PIL image for use in a PyTorch model\n img = Image.open( image )\n img.load()\n normalize = transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]\n )\n preprocess = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize\n ])\n img_tensor = preprocess(img)\n return img_tensor\n\ndef getClassesFromFiles():\n my_classes = []\n for filename in os.listdir(\"./url_files/\"):\n if filename.find(\"_valid.txt\") == -1 and filename.find(\".txt\") > 0:\n my_classes.append(filename.replace('.txt',''))\n my_classes = sorted(my_classes)\n return my_classes\n\n\n# -\n\ndevice_to = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nclass_names = getClassesFromFiles()\ntop_classes('data/valid/autumn/00000006.jpg', load_checkpoint(device_to, class_names), device_to, class_names)\n\n# !wget https://images.pexels.com/photos/1633522/pexels-photo-1633522.jpeg\nprint(device_to)\n\n\n# !mv pexels-photo-1633522.jpeg running-dogs.jpeg\n\ntop_classes('running-dogs.jpeg', load_checkpoint(device_to, class_names), device_to, class_names)\n","repo_name":"ismaproco/image2hashtag","sub_path":"predict_classes.ipynb","file_name":"predict_classes.ipynb","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"11603229766","text":"# # Exercici 1\n# #### Descarrega el dataset adjunt preu lloguer per trimestre i barri.csv extret de la web OpenDataBCN i resumeix-lo estadísticament i gràficament.\n#\n# #### Crea almenys una visualització per:\n\n# +\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# -\n\ndf = pd.read_csv('C:/RAUL/NISSAN/GENERAL/USB/FORMACION/BootCamp - Data Scientist_Analist/IT Academy Cibernarium - Data Science/Data Science Itinerario/4.- Visualitzación gráfica de datos/Entrega/preu lloguer per trimestre i barri.csv')\n\n\n# * Resum estadístic\n\ndf.isnull().sum()\n\ndf.head()\n\ndf['Preu'] = df['Preu'].astype(float) # Canviem el tipus de la columna preu per poder fer càlculs\n\n#Eliminem els registres que no ténen dades de Preu ja que a priori no són interessants per fer l'anàlisis\ndf = df[df['Preu'] != '--']\n\ndf.shape\n\ndf.info()\n\ndf_Preu_mensual = df[df['Lloguer_mitja'] == 'Lloguer mitjà mensual (Euros/mes)']\ndf_Preu_mensual.describe().round(4)\n\ndf_Preu_m2 = df[df['Lloguer_mitja'] == 'Lloguer mitjà per superfície (Euros/m2 mes)']\ndf_Preu_m2.describe().round(4)\n\ndf_pvt=df[[\"Nom_Districte\", \"Lloguer_mitja\"]]\npivotTable = df_pvt.pivot_table(index= \"Nom_Districte\", columns= \"Lloguer_mitja\", values=\"Lloguer_mitja\", aggfunc= 'size', fill_value=0)\npivotTable\n\n# * Una variable categòrica (Districte o Barri)\n\ndf_Barris=df['Nom_Districte']\ndf_Barris = df_Barris.value_counts().rename_axis('Barris').reset_index(name='N_registres')\ndf_Barris.set_index('Barris', inplace=True) #Quan es dibuixa directament amb plotly l'índex és el que es fa servir per\n# les categories de les coordenades X, si es fa amb el \n\n# +\np1=df_Barris.plot(kind='bar', figsize=(8, 5))\nplt.title('Registres per districtes')\nplt.ylabel('N_registres')\nplt.xlabel('Districtes')\nplt.figure(figsize=(10, 2.7))\n\nplt.show()\n# -\n\n# * Una variable numèrica (Preu)\n\ndf_Preu_mensual_1=df_Preu_mensual.sort_values(by='Preu', ascending=False)\ndf_Preu_mensual_1.reset_index(drop=True, inplace=True)\ndf_Preu_mensual_1=df_Preu_mensual_1['Preu']\n\ndf_Preu_m2_1=df_Preu_m2.sort_values(by='Preu', ascending=False)\ndf_Preu_m2_1.reset_index(drop=True, inplace=True)\ndf_Preu_m2_1=df_Preu_m2_1['Preu']\n\n# +\nplt.subplot(1, 2, 1)\n\nplt.subplot(1, 2, 1)\np2=df_Preu_mensual_1.plot(kind='hist', x='df_Preu_mensual', figsize=(10, 6))\nplt.title('Histograma Preus mensual')\nplt.xlabel('€ / mes')\nplt.ylabel('Registres')\n\nplt.subplot(1, 2, 2)\np3=df_Preu_m2_1.plot(kind='hist', x='df_Preu_m2', figsize=(8, 6))\nplt.title('Histograma Preus per m2')\nplt.xlabel('€ / m2')\nplt.ylabel('Registres')\n# -\n\n# * Una variable numèrica i una categòrica (Districte i Preu)\n\ndf_Preu_mensual_2=df_Preu_mensual.sort_values(by='Preu', ascending=False)\ndf_Preu_mensual_2.reset_index(drop=True, inplace=True)\ndf_Preu_mensual_Districte=df_Preu_mensual_2[['Nom_Districte','Preu']]\n\ndf_Preu_m2_2=df_Preu_m2.sort_values(by='Preu', ascending=False)\ndf_Preu_m2_2.reset_index(drop=True, inplace=True)\ndf_Preu_m2_Districte=df_Preu_m2_2[['Nom_Districte','Preu']]\n\n# +\nplt.subplot(1, 2, 1)\n\n# Adjust the subplot layout parameters\n\nplt.subplot(1, 2, 1)\np4=plt.scatter(df_Preu_mensual[\"Nom_Districte\"].astype(str), df_Preu_mensual[\"Preu\"])\nplt.margins(x=0.1)\nplt.xticks(rotation=90)\n\nplt.title('Preus mensuals per distrticte', y=1.05)\nplt.xlabel('Districtes')\nplt.ylabel('€ / mes')\n\n\n\nplt.subplot(1, 2, 2)\np5=plt.scatter(df_Preu_m2[\"Nom_Districte\"].astype(str), df_Preu_m2[\"Preu\"])\nplt.margins(x=0.1)\nplt.xticks(rotation=90)\n\nplt.title('Preus per m2 i distrticte', y=1.05)\nplt.xlabel('Districtes')\nplt.ylabel('€ / m2')\n\nplt.subplots_adjust(right=1.50)\n\nplt.show()\n\n# +\nf, axes = plt.subplots(1, 2, figsize=(12, 5))\n\nax0=sns.stripplot(data=df_Preu_mensual, x=\"Nom_Districte\", y=\"Preu\", ax=axes[0])\nax0.set_xticklabels(ax0.get_xticklabels(),rotation=90)\nax0.set(xlabel='Districtes', ylabel='€ / mes')\nax0.set_title(\"Preus mensuals per distrticte\")\n\nax1=sns.stripplot(data=df_Preu_m2, x=\"Nom_Districte\", y=\"Preu\", ax=axes[1])\nax1.set_xticklabels(ax1.get_xticklabels(),rotation=90)\nax1.set(xlabel='Districtes', ylabel='€ / m2')\nax1.set_title(\"Preus m2 per distrticte\") \n\n\n# +\nf, axes = plt.subplots(1, 2, figsize=(12, 5))\n\nax2=sns.boxplot(data=df_Preu_mensual, x=\"Nom_Districte\", y=\"Preu\", ax=axes[0])\nax2.set_xticklabels(ax0.get_xticklabels(),rotation=90)\nax2.set(xlabel='Districtes', ylabel='€ / mes')\nax2.set_title(\"Preus mensuals per distrticte\")\n\nax3=sns.boxplot(data=df_Preu_m2, x=\"Nom_Districte\", y=\"Preu\", ax=axes[1])\nax3.set_xticklabels(ax1.get_xticklabels(),rotation=90)\nax3.set(xlabel='Districtes', ylabel='€ / m2')\nax3.set_title(\"Preus m2 per distrticte\") \n\n# -\n\n# * Dues variables numèriques (Any o Trimestre i Preu)\n\n# +\nf, axes = plt.subplots(1, 2, figsize=(10, 4))\n\nax4=sns.violinplot(data=df_Preu_mensual, x=\"Trimestre\", y=\"Preu\", ax=axes[0], inner=None, color=\".8\")\nax4=sns.stripplot(data=df_Preu_mensual, x=\"Trimestre\", y=\"Preu\", ax=axes[0])\nax4.set(xlabel='Trimestre', ylabel='€ / mes')\nax4.set_title(\"Preus mensuals per trimestre\")\n\nax5=sns.violinplot(data=df_Preu_m2, x=\"Trimestre\", y=\"Preu\", ax=axes[1], inner=None, color=\".8\")\nax5=sns.stripplot(data=df_Preu_m2, x=\"Trimestre\", y=\"Preu\", ax=axes[1])\nax5.set(xlabel='Trimestre', ylabel='€ / m2')\nax5.set_title(\"Preus m2 per trimestre\") \n# -\n\n# * Tres variables (Barri o Districte, Trimestre i Preu)\n\n# +\nf, axes = plt.subplots(1, 2, figsize=(20, 8))\n\nax6=sns.barplot(data=df_Preu_mensual, x=\"Nom_Districte\", y=\"Preu\", ax=axes[0], hue='Trimestre')\nax6.set_xticklabels(ax0.get_xticklabels(),rotation=90)\nax6.set_ylim(500, 1900)\nax6.set(xlabel='Districtes', ylabel='€ / mes')\nax6.set_title(\"Preus mensuals per distrticte i trimestre\")\n\nax7=sns.barplot(data=df_Preu_m2, x=\"Nom_Districte\", y=\"Preu\", ax=axes[1], hue='Trimestre')\nax7.set_xticklabels(ax1.get_xticklabels(),rotation=90)\nax7.set_ylim(8, 18)\nax7.set(xlabel='Districtes', ylabel='€ / m2')\nax7.set_title(\"Preus m2 per distrticte i trimestre\") \n\n\n# -\n\n# # Exercici 2\n# #### Exporta els gràfics com imatges o com HTML.\n\n# Funció per exportar gràfics a partir del nom que li volem donar i el que té asignat.\ndef exporta_a_jpg(nombre_fichero, grafico):\n fig = grafico.get_figure()\n fig.savefig(nombre_fichero+\".jpeg\")\n\n\nexporta_a_jpg('Registres per districtes', p1)\n\nexporta_a_jpg('Histograma Preus mensual + Preus m2', p2)\n\nexporta_a_jpg('Preus mensuals per distrticte i preus m2 per districte', p4)\n\nexporta_a_jpg('Preus mensuals per distrticte i preus m2 per districte_2', ax0)\n\nexporta_a_jpg('Preus mensuals per distrticte i preus m2 per districte_2 (Boxplot)', ax2)\n\nexporta_a_jpg('Preus mensuals per trimestre i preus m2 per trimestre (Violinplot)', ax4)\n\nexporta_a_jpg('Preus mensuals i preus m2 per districte i trimestre (Barplot)', ax6)\n\n# # Exercici 3\n# #### Proposa alguna visualització que creguis que pot resultar interessant.\n\n# +\nfig, ax = plt.subplots(figsize=(10, 5))\n\ndf_Barris.plot.pie(y='N_registres', legend=False, autopct='%1.2f%%', ax=ax)\nplt.title('Registres per districtes')\nax.set_ylabel(None)\nplt.show()\n\n# -\n\ndf_Preu_mensual_2=df_Preu_mensual[[\"Nom_Districte\", \"Preu\"]]\n\nfig, ax = plt.subplots(figsize=(10,6))\nsns_plot = sns.histplot(data=df_Preu_mensual_2, x=\"Preu\", hue=\"Nom_Districte\", multiple=\"stack\")\nax.set_title(\"Preus mensuals per distrticte\")\n\ndf_Preu_mensual_2=df_Preu_mensual[[\"Nom_Districte\", \"Preu\"]]\n\n# +\ndf_Preu_m2_2=df_Preu_m2[[\"Nom_Districte\", \"Preu\"]]\n\nfig, ax = plt.subplots(figsize=(10,6))\nsns.histplot(data=df_Preu_m2_2, x=\"Preu\", hue=\"Nom_Districte\", multiple=\"stack\")\nax.set_title(\"Preus m2 per distrticte\")\n","repo_name":"raugaca/estructures_Dataframe_Sprint4","sub_path":"Tasca M4 T01.ipynb","file_name":"Tasca M4 T01.ipynb","file_ext":"py","file_size_in_byte":7603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"4"} +{"seq_id":"17356367801","text":"# # Amortization (workspace notebook)\n#\n# We can use this notebook to work on our `amortization` application. Since this is located on `src/classworks` we can import directly the `amortization` module.\n\n# We use the `settings` module to save the applications configuration. In this case, we can get the `AMORTIZATION_TABLE_DIRPATH` that represents the \"location\" of the `TABLE` directory in the filesystem.\n#\n# Let's create the folder if not exists. We can add this logic into the `setup` command:\n\nimport os\nfrom amortization.settings import AMORTIZATION_TABLE_DIRPATH\n\nAMORTIZATION_TABLE_DIRPATH\n\n# Create the folder if not exists\nif not os.path.exists(AMORTIZATION_TABLE_DIRPATH):\n os.makedirs(AMORTIZATION_TABLE_DIRPATH)\n\n# Import the `Amortization` class and create two instances.\n\n# +\nimport pandas as pd\nfrom fintools import Amortization\n\npd.options.display.float_format = '${:,.2f}'.format\n\n# Create a couple Amortization instances\namortization_a = Amortization(amount=50000, rate=0.08, n=8)\namortization_b = Amortization(amount=18000, rate=0.34/12, n=6)\n# -\n\n# We should be able to get a dataframe\ndf = amortization_b.get_table()\ndf\n\n# We should be able to get other implementations we already have on fintools:\n\n# +\nfrom fintools.rates import Cetes28\n\ncetes28 = Cetes28()\n# -\n\ncetes28.get_dataframe().iloc[-1].value\n\n# Let's create a quick visualization:\n\nimport matplotlib.pyplot as plt\n\n# +\na = Amortization(amount=18000, rate=0.10, n=10)\ndf = a.get_table()\n\nplot = df.plot.bar(x=\"t\", y=[\"principal\", \"interest\"], stacked=True)\nplt.title(\"Amortization Payments: ${:,.2f}\".format(a.annuity))\nplt.ylabel(\"$$$\")\nplt.grid()\nplt.show()\n# -\n\ndf.annuity[1:].unique().tolist().pop()\n\nplot.get_figure()\n\n\n","repo_name":"douglasparism/CREDIT-RISK-2021A","sub_path":"src/classwork/amortization.ipynb","file_name":"amortization.ipynb","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"4"} +{"seq_id":"699145294","text":"# ![image.png](attachment:image.png)\n\n# normalization\n# 适用于分布有明显便捷的情况; 受outlier影响较大\n# eg:学生分数, 像素点\n#\n# 将所有的数据映射到统一尺度\n# 最值归一化: 把所有数据映射到0-1之间\n# ![image.png](attachment:image.png)\n\n# ## 均值方差归一化 standardization\n# ### 把所有数据归一到均值为0方差为1的分布中, 适用于数据分布没有明显的边界, 有可能存在极端数据值\n\n# ![image.png](attachment:image.png)\n\n# # 数据归一化处理\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# ## 最值归一化 Normalization\n\nx = np.random.randint(0, 100, size=100)\n\nx\n\n(x - np.min(x)) / (np.max(x)- np.min(x))\n\nX = np.random.randint(0, 100, (50, 2))\n\nX[:10, :]\n\nX = np.array(X, dtype=float)\n\nX[:10, :]\n\nX[:, 0] = (X[:, 0] - np.min(X[:,0])) / (np.max(X[:,0]) - np.min(X[:,0]))\nX[:, 1] = (X[:, 1] - np.min(X[:,1])) / (np.max(X[:,1]) - np.min(X[:,1]))\n\nX[:10, :]\n\nplt.scatter(X[:, 0], X[:,1])\nplt.show()\n\nnp.mean(X[:,0])\n\nnp.mean(X[:,1])\n\nnp.std(X[:, 0])\n\n# ## 均值方差归一化 Standardization\n\nX2 = np.random.randint(0, 100, (50, 2))\n\nX2 = np.array(X2, dtype=float)\n\nX2[:10,:]\n\nX2[:,0] = (X2[:,0] - np.mean(X2[:,0])) / np.std(X2[:, 0])\n\nX2[:,1] = (X2[:,1] - np.mean(X2[:,1])) / np.std(X2[:, 1])\n\nX2[:10, :]\n\nplt.scatter(X2[:,0], X2[:,1])\nplt.show()\n\nnp.mean(X2[:,0])\n\nnp.std(X2[:,0])\n\n\n","repo_name":"DorianXXUUU/MachineLearningNotebook","sub_path":"KNN/06-Feature_Scaling.ipynb","file_name":"06-Feature_Scaling.ipynb","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"4"} +{"seq_id":"16992545236","text":"import pydotplus\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, accuracy_score\nfrom sklearn.base import BaseEstimator\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom IPython.display import Image\nfrom sklearn import tree\nfrom scipy import optimize\nfrom sklearn import datasets, cross_validation, metrics, neighbors\nfrom matplotlib.colors import ListedColormap\nfrom pandas import DataFrame\n# %pylab inline\n\nwith open('german_credit.csv') as f:\n x = [i for i in f]\n\nfor i in range(len(x)):\n if i > 0:\n x[i] = (x[i].split(','))\ny = x[0]\nx = x[1:]\ntargets = []\nfor i in range(len(x)):\n for j in range(len(x[i]) - 1):\n x[i][j] = int(x[i][j])\n x[i][len(x[i]) - 1] = int(x[i][len(x[i]) - 1][0])\n targets.append(x[i][0])\n x[i] = x[i][1:]\n\nx = np.array(x)\n\ny = y.split(',')\n\ny[9] = y[9].replace('&', '')\n\ny\n\nmodel = tree.DecisionTreeClassifier(max_depth=3)\nmodel.fit(x, targets)\n\ndot_data = tree.export_graphviz(model, out_file=\"small_tree.out\", \n feature_names=y[1:],\n max_depth = 3,\n class_names=['0', '1'], \n filled=True, rounded=True, \n special_characters=True)\n\ngraph = pydotplus.graphviz.graph_from_dot_file(\"small_tree.out\") \nImage(graph.create_png())\n\n# #### Дерево наилучшим образом разбивает выборку по признакам. В первом узле разбиение выполнено по признаку, отвечающему за баланс пользователя. Причем видно, что в левой части появляются узлы, в которых алгоритм отвечает нулем, то есть кредит не выдается. Что неудивительно, так как баланс клиента низкий. То же самое можно сказать про длительность неоплаченного кредита и т.д.\n\ndepth_of_tree = np.linspace(1, 100, 100)\nac_cross = [0.0 for i in range(len(depth_of_tree))]\nac_train = [0.0 for i in range(len(depth_of_tree))]\nfor k in range(1, len(depth_of_tree)):\n model = tree.DecisionTreeClassifier(max_depth=k)\n model.fit(x, targets)\n ac_cross[k] = cross_validation.cross_val_score(model, x, targets).mean()\n ac_train[k] = accuracy_score(targets, model.predict(x))\n\npyplot.plot(depth_of_tree[1:], ac_cross[1:], color = 'red', label = 'cross_validation')\npyplot.plot(depth_of_tree[1:], ac_train[1:], color = 'blue', label = 'train_dataset')\npyplot.xlabel(\"k\")\npyplot.ylabel(\"accuracy\")\npyplot.title(\"accuracy\")\naxis = pyplot.gca()\naxis.legend(loc = 4)\npyplot.ylim(0, 1.1)\n\n# ### На обучающей выборке качество быстро выходит на 1. А как же иначе? Ведь она обучающая. Алгоритм подогнался, и при достаточно большой глубине дерева выдает точные ответы. На кроссвалидации точность примерно 0.7 при всех k.\n\n\n","repo_name":"iat7/ML2017","sub_path":"hw_2_2.ipynb","file_name":"hw_2_2.ipynb","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"4"} +{"seq_id":"24113957090","text":"# Modelo para anlisis de sentmientos para luego precedir si tiene sintomas de depresion.\n\nfrom string import punctuation\nimport pandas as pd\nimport nltk\nimport re\n\n# read the data from tweets_public.csv and create a dataframe\ndf = pd.read_csv('data/tweets_public.csv', encoding='utf-8')\ndf.head()\n\ndf.shape\n\n# # Preprocesamiento\n# Limpieza de datos\n\n# create a new dataframe with only the text and airline_sentiment columns and tweet id with the name df_sentiment\ndf_sentiment = df[['text', 'airline_sentiment', 'tweet_id']]\n\n# transform the text letters to lowercase\ndf_sentiment['text'] = df_sentiment['text'].str.lower()\ndf_sentiment.head()\n\n# Referencia: https://stackoverflow.com/questions/6718633/python-regular-expression-again-match-url\n# remove the urls from the text but keep all the text after the url\ndf_sentiment.loc[:, 'text'] = df_sentiment['text'].apply(lambda x: re.split('http[s]*\\S+', str(x))[0])\ndf_sentiment.head()\n\n# remove the punctuation from the text\ndf_sentiment.loc[:, 'text'] = df_sentiment['text'].apply(lambda x: ''.join(c for c in x if c not in punctuation))\ndf_sentiment.head()\n\n# change the \\n to a space\ndf_sentiment.loc[:, 'text'] = df_sentiment['text'].apply(lambda x: x.replace('\\n', ' '))\ndf_sentiment.head()\n\n# +\n# remove the stopwrods from the text\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nstop_words = set(stopwords.words('spanish'))\ndf_sentiment.loc[:, 'text'] = df_sentiment['text'].apply(lambda x: ' '.join([word for word in x.split() if word.lower() not in stop_words]))\ndf_sentiment.head()\n\n# +\n# remove the emojis from the text\n\n# regular expression pattern to remove emojis from text\nemoji_pattern = re.compile(\"[\"\n u\"\\U0001F600-\\U0001F64F\" # faces\n u\"\\U0001F300-\\U0001F5FF\" # simbols & pictographs\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n u\"\\U0001F1E0-\\U0001F1FF\" # flags\n \"]+\", flags=re.UNICODE)\n\n# use lambda function to remove the emojis from the text\ndf_sentiment.loc[:, 'text'] = df_sentiment['text'].apply(lambda x: emoji_pattern.sub(r'', x))\ndf_sentiment.head()\n# -\n\n# remove the numbers from the text\ndf_sentiment.loc[:, 'text'] = df_sentiment['text'].apply(lambda x: re.sub(r'\\d+', '', x))\ndf_sentiment.head()\n\ndf_sentiment = df[['text', 'airline_sentiment']]\n# df_sentiment['label'] = df_sentiment['airline_sentiment'].apply(lambda x: '1 start' if x == 'negative' else '5 stars')\ndf_sentiment['label'] = df_sentiment['airline_sentiment'].apply(lambda x: 0 if x == 'negative' else 1)\ndf_sentiment = df_sentiment[['text', 'label']]\ndf_sentiment\n\n# save the dataframe to a csv file\ndf_sentiment.to_csv('data/clean_tweets_sentiment.csv', index=False)\n\n# # Hugging Face\n\nmodel_preload1 = \"nlptown/bert-base-multilingual-uncased-sentiment\"\n# model_preload = \"distilbert-base-uncased\"\n# model_preload = \"xlm-roberta-base\"\n# model_preload = \"distilbert-base-multilingual-cased\"\n# model_preload = \"bert-base-multilingual-cased\"\nmodel_preload = 'dccuchile/bert-base-spanish-wwm-cased'\n# model_preload = \"RoBERTa-base\"\n\n# +\n\ndata = [\"Amo el mundo en el que vivo\", \"Odio a todas las personas que conozco\"]\n# -\n\nfrom transformers import pipeline\nsentiment_pipeline = pipeline(\"sentiment-analysis\")\nsentiment_pipeline(data)\n\nsentiment_pipeline('no estoy normal')\n\nspecific_model = pipeline(\"sentiment-analysis\", model=model_preload1)\nspecific_model(data)\n\nspecific_model('estoy normal')\n\nspecific_model('estoy triste')\n\n# ## Fine tuning\n\n# +\n# import torch\n# torch.cuda.is_available()\n\n# +\n# torch.cuda.empty_cache()\n# -\n\nfrom datasets import load_dataset\nlocal_train = load_dataset(\"csv\", data_files=\"data/clean_tweets_sentiment.csv\", split=\"train[:70%]\")\nlocal_test = load_dataset(\"csv\", data_files=\"data/clean_tweets_sentiment.csv\", split=\"train[70%:]\")\n\nprint(local_train.shape)\nprint(local_test.shape)\nprint(local_train[0])\nprint(local_test[0])\n\n# +\nsmall_train_dataset = local_train.shuffle(seed=42).select(\n list(list(range(300)))\n)\nsmall_test_dataset = local_test.shuffle(seed=42).select(list(list(range(100))))\n# # split df_sentiment in 70% train and 30% test\n# from sklearn.model_selection import train_test_split\n\n# train, test = train_test_split(df_sentiment, test_size=0.3, random_state=42)\n# train.shape, test.shape\n# -\n\nfrom transformers import AutoTokenizer\ntokenizer = AutoTokenizer.from_pretrained(model_preload)\n\n\n# +\ndef preprocess_function(examples):\n return tokenizer(examples[\"text\"], truncation=True)\n\n# user the function preprocess_function to tokenize the train and test data\n# tokenized_train = train['text'].apply(lambda x: tokenizer(x, truncation=True))\n# tokenized_test = test['text'].apply(lambda x: tokenizer(x, truncation=True))\ntokenized_train = small_train_dataset.map(preprocess_function, batched=True)\ntokenized_test = small_test_dataset.map(preprocess_function, batched=True)\n# -\n\nfrom transformers import DataCollatorWithPadding\ndata_collator = DataCollatorWithPadding(tokenizer=tokenizer)\n\n# ## train the model\n\nfrom transformers import AutoModelForSequenceClassification\nmodel = AutoModelForSequenceClassification.from_pretrained(model_preload, num_labels=2, id2label={0: \"negative\", 1: \"positive\"})\n\n\n# +\nimport numpy as np\nfrom datasets import load_metric\n \ndef compute_metrics(eval_pred):\n load_accuracy = load_metric(\"accuracy\")\n load_f1 = load_metric(\"f1\")\n \n logits, labels = eval_pred\n predictions = np.argmax(logits, axis=-1)\n accuracy = load_accuracy.compute(predictions=predictions, references=labels)[\"accuracy\"]\n f1 = load_f1.compute(predictions=predictions, references=labels)[\"f1\"]\n return {\"accuracy\": accuracy, \"f1\": f1}\n\n\n# -\n\nfrom huggingface_hub import notebook_login\nnotebook_login()\n\n# +\nfrom transformers import TrainingArguments, Trainer\n \nrepo_name = \"raulangelj/huggingface_sentiment_analysis\"\n \ntraining_args = TrainingArguments(\n output_dir=repo_name,\n learning_rate=2e-5,\n per_device_train_batch_size=25,\n per_device_eval_batch_size=25,\n num_train_epochs=2,\n weight_decay=0.01,\n save_strategy=\"epoch\",\n push_to_hub=True,\n)\n \ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=tokenized_train,\n eval_dataset=tokenized_test,\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_metrics,\n)\n# -\n\ntrainer.train()\n\ntrainer.evaluate()\n\ntrainer.push_to_hub()\n\ndata\n\n# +\nfrom transformers import pipeline\n \nsentiment_model = pipeline(model=repo_name)\nsentiment_model(data)\n# -\n\nsentiment_model('no me siento bien')\n\nsentiment_model('hoy es el mejor dia de mi vida')\n\nsentiment_model('ya no puedo con mi vida, no quiero que me hablen')\n\n# # Funcion a utilizar en proyecto\n\n# +\nimport unicodedata\nfrom transformers import pipeline\n\ndef has_first_person_pronouns(text):\n first_person_pronouns = [\"yo\", \"me\", \"mi\", \"conmigo\"]\n \n words = text.split()\n for word in words:\n normalize_word = remove_accent(word.lower())\n if normalize_word in first_person_pronouns:\n return True\n \n return False\n\ndef remove_accent(word):\n return ''.join((c for c in unicodedata.normalize('NFD', word) if unicodedata.category(c) != 'Mn'))\n\n# # ? should we use this?\ndef has_depression_words(text):\n depression_words = [\n \"depresion\", \"tristeza\", \"desesperanza\", \"desmotivacion\", \"soledad\", \"ansiedad\",\n \"desgano\", \"desanimo\", \"desaliento\", \"abatimiento\", \"melancolia\", \"desolacion\",\n \"apatia\", \"angustia\", \"pesimismo\", \"desesperacion\", \"desamparo\", \"desconsuelo\",\n \"agotamiento\", \"cansancio\", \"desinteres\", \"insomnio\", \"culpa\", \"llanto\", \"suicidio\",\n \"autolesion\", \"desorden\", \"trastorno\", \"descontrol\", \"vacio\", \"apetito\", \"fatiga\",\n \"inutilidad\", \"retroceso\", \"preocupacion\", \"retraimiento\", \"negatividad\", \"desvalorizacion\",\n \"desesperado\", \"desesperanza\", \"perdida\", \"esperanza\", \"autoestima\", \"autoestima\",\n \"irritabilidad\", \"decision\", \"concentracion\", \"motivacion\", \"indefension\", \"vida\",\n \"conexion\", \"pena\", \"abandono\", \"inseguridad\", \"desapego\", \"agonia\", \"miedo\", \"rumiacion\",\n \"tratamiento\", \"terapia\", \"psicologo\", \"psiquiatra\", \"medicacion\", \"cura\", \"superacion\",\n \"autoayuda\", \"apoyo\", \"rehabilitacion\"\n ]\n \n words = text.split()\n for word in words:\n normalize_word = remove_accent(word.lower())\n if normalize_word in depression_words:\n return True\n \n return False\n\ndef has_possible_depression_sintom(text):\n # To know if has depression sintoms, we will check 3 things:\n # 1. If the text has first person pronouns\n # 2. If the text has negative sentiment\n # 3. If the text has words related to depression\n # If the text has the 3 things, we will say that the text has depression sintoms\n # If the text has 2 of the 3 things, we will say that the text has possible depression sintoms\n # If the text has 1 of the 3 things, we will say that the text has no depression sintoms\n sentiment_model = pipeline(model=\"raulangelj/huggingface_sentiment_analysis\")\n is_negative_sentiment = sentiment_model(text)[0]['label'] == 'negative'\n # sentiment_model(data)\n is_depression_words = has_depression_words(text)\n is_first_person_pronouns = has_first_person_pronouns(text)\n # if all the conditions are true, then the text has depression sintoms\n if is_negative_sentiment and is_depression_words and is_first_person_pronouns:\n # return 'depression'\n return True\n # if 2 of the 3 conditions are true, then the text has possible depression sintoms\n # if (is_negative_sentiment and is_depression_words) or (is_negative_sentiment and is_first_person_pronouns) or (is_depression_words and is_first_person_pronouns):\n # # return 'possible_depression'\n # return True\n # if 1 of the 3 conditions are true, then the text has no depression sintoms\n if is_negative_sentiment or is_depression_words or is_first_person_pronouns:\n # return 'no_depression'\n return False\n # if none of the conditions are true, then the text has no depression sintoms\n # return 'no_depression'\n return False\n\n\n# -\n\nexample_text_depression = \"Últimamente, me cuesta encontrar motivación para levantarme de la cama por las mañanas. Siento una tristeza constante que no puedo sacudir, como si estuviera atrapado en una nube gris. Incluso las actividades que solían traerme alegría ahora me resultan abrumadoras y sin sentido. Me siento agotado todo el tiempo, tanto física como emocionalmente. La soledad se ha convertido en mi compañera constante, y me resulta difícil conectar con los demás. No puedo evitar sentir que he perdido el control de mi vida y que no hay esperanza de que las cosas mejoren. Estos pensamientos negativos y la sensación de vacío me invaden, y a veces me encuentro llorando sin razón aparente. Me preocupa que estos sentimientos persistan y no sé qué hacer para superar esta desesperanza abrumadora.\"\nexample_text_no_depression = \"El sol brilla radiante en el cielo azul mientras disfruto de un paseo por el parque. Río y converso con mis amigos, sintiéndome lleno de energía y entusiasmo. Me siento agradecido por las bendiciones en mi vida y tengo metas emocionantes que persigo con determinación. Cada día es una oportunidad para crecer, aprender y disfrutar de las pequeñas cosas que hacen que la vida sea maravillosa. Me rodeo de personas positivas que me apoyan y me animan en mis sueños. La vida es un viaje emocionante y estoy emocionado de ver lo que el futuro me depara.\"\nexample_text_no_depression_sad = \"Atravesé un momento difícil en mi vida recientemente. Experimenté una pérdida personal significativa que me dejó con el corazón apesadumbrado. Durante un tiempo, sentí una profunda tristeza y una sensación de vacío en mi interior. Sin embargo, me permití sentir y procesar estas emociones, encontrando consuelo en el amor y el apoyo de mis seres queridos. Poco a poco, comencé a encontrar la paz dentro de mí y a enfocarme en las cosas positivas que todavía tengo en mi vida. Aprendí a apreciar más cada momento y a encontrar la fortaleza para seguir adelante. Aunque todavía tengo momentos de tristeza, también encuentro alegría y esperanza en las pequeñas cosas de la vida. La adversidad me ha enseñado a ser más resiliente y a valorar cada experiencia, tanto positiva como negativa.\"\nprint(has_possible_depression_sintom(example_text_depression))\nprint(has_possible_depression_sintom(example_text_no_depression))\nprint(has_possible_depression_sintom(example_text_no_depression_sad))\n","repo_name":"raulangelj/analisis_sentimientos_depresion","sub_path":"sentimientos.ipynb","file_name":"sentimientos.ipynb","file_ext":"py","file_size_in_byte":12552,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"4"} +{"seq_id":"39042147056","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"SkRplJmkb2XU\" outputId=\"77712dae-8557-48be-be78-5d19792c1c5a\"\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import datasets, layers, models\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimg_width, img_height, img_num_channels = 32, 32, 3\n\n(x_train, y_train), (x_test, y_test) = datasets.cifar100.load_data()\n\nnum_classes =100\n\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nx_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\n\n\nmodel = tf.keras.models.Sequential() \nmodel.add(tf.keras.layers.Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=input_shape)) \nmodel.add(Dropout(0.2)) \nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2))) \nmodel.add(tf.keras.layers.Conv2D(64, (3, 3), padding='same', activation='relu')) \nmodel.add(Dropout(0.2)) \nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2))) \nmodel.add(tf.keras.layers.Conv2D(128, (3, 3), padding='same', activation='relu')) \nmodel.add(Dropout(0.2)) \nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))\nmodel.add(tf.keras.layers.Conv2D(256, (3, 3), padding='same', activation='relu')) \nmodel.add(Dropout(0.2)) \nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))\nmodel.add(tf.keras.layers.Conv2D(512, (3, 3), padding='same', activation='relu')) \nmodel.add(Dropout(0.2)) \nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))\n\nmodel.add(tf.keras.layers.Flatten()) \nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) \nmodel.add(Dropout(0.2)) \nmodel.add(tf.keras.layers.Dense(256, activation=tf.nn.relu))\nmodel.add(Dropout(0.2)) \nmodel.add(tf.keras.layers.Dense(100, activation=tf.nn.softmax)) \nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) \nmodel.build(input_shape=(None,32,32,1)) \n \nmodel.summary() \n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\ndatagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True,\n validation_split=0.2)\n\ndatagen.fit(x_train)\n\nmodel.fit_generator(datagen.flow(x_train, y_train, batch_size=256),\n steps_per_epoch=x_train.shape[0] // 256,\n epochs=20,\n validation_data=(x_test, y_test)\n)\n# Generate generalization metrics\nscore = model.evaluate(x_test, y_test)\nprint('Test loss:', score[0]) \nprint('Test accuracy:', score[1])\n#print(f'Test loss: {score[0]} / Test accuracy: {score[1]}')\n\npredictions = model.predict([x_test])\n#print(predictions)\n\nprint(np.argmax(predictions[0]))\n\n\nimg_path = x_test[0]\nprint(img_path.shape)\nif(len(img_path.shape) == 3):\n plt.imshow(np.squeeze(img_path))\nelif(len(img_path.shape) == 2):\n plt.imshow(img_path)\nelse:\n print(\"Image cannot be shown\")\n","repo_name":"Yashwanth1102/CIFAR100-with-DataAugmentation","sub_path":"cifar100-with-dataaugmentation.ipynb","file_name":"cifar100-with-dataaugmentation.ipynb","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"4"} +{"seq_id":"22292961592","text":"#GENERAL Library\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport random\nimport time\n\n# # OVERVIEW\n\n# #### Main Path\n\n#PATH PROCESS Library\nimport os\nimport os.path\nfrom pathlib import Path\nimport glob\nfrom scipy.io import loadmat\nimport nibabel as nib\nimport csv\n\nMain_Path = Path(\"C://Users//didel//Downloads//JUB University//3rd semster//ImageProcessing//SDOBenchmark-data-full\\SDOBenchmark-data-full//training\")\n\n# ##### Data CSV file Process\n\nMain_Train_CSV = list(Main_Path.glob(r\"**/*.csv\"))\n\nprint(len(Main_Train_CSV))\n\nTrain_CSV = Main_Train_CSV[0]\n\nprint(Train_CSV)\n\nReading_CSV = pd.read_csv(Train_CSV)\n\nprint(Reading_CSV.columns)\n\nprint(len(Reading_CSV))\n\nprint(Reading_CSV.head(-1))\n\nprint(Reading_CSV.isnull().sum())\n\nprint(Reading_CSV[\"peak_flux\"][0])\n\nprint(int(Reading_CSV[\"peak_flux\"][0]))\n\nprint(int(Reading_CSV[\"peak_flux\"][8334]))\n\nprint(Reading_CSV[\"start\"][8334])\n\nprint(Reading_CSV[\"start\"][8334][0:10])\n\n# * DATETIME TRANSFORMATION \n\nprint(type(Reading_CSV[\"start\"][8334][0:10]))\n\nTesting_Date_Transformation = Reading_CSV[\"start\"][8334][0:10].replace(\"-\",\"\")\n\nprint(Testing_Date_Transformation)\n\nTesting_Date_Array = np.array(int(Testing_Date_Transformation))\n\nprint(type(Testing_Date_Array))\n\n# #\n\n# * Data Process\n#\n# ###### Engineering\n\nJPG_Path = list(Main_Path.glob(r\"**/*.jpg\"))\n\nSorted_JPG_Path = sorted(JPG_Path)\n\nReading_CSV[\"New_ID\"] = Sorted_JPG_Path[:8336]\n\nprint(Reading_CSV.head(-1))\n\nprint(Reading_CSV[\"New_ID\"][0])\nprint(\"---\"*10)\nprint(Reading_CSV[\"id\"][0])\n\n# #\n\n# * New Data\n\n# +\nNew_Start = []\nNew_End = []\nNew_Path = []\n\nfor x_start,x_end,x_path in zip(Reading_CSV.start.values,Reading_CSV.end.values,Reading_CSV.New_ID.values):\n \n x_start = x_start[0:10]\n x_start = x_start.replace(\"-\",\"\")\n x_start = np.array(x_start,dtype=\"float32\")\n \n x_end = x_end[0:10]\n x_end = x_end.replace(\"-\",\"\")\n x_end = np.array(x_end,dtype=\"float32\")\n \n New_Start.append(x_start)\n New_End.append(x_end)\n New_Path.append(x_path)\n# -\n\nprint(\"LEN START: \",len(New_Start))\nprint(\"LEN END: \",len(New_End))\nprint(\"LEN PATH: \",len(New_Path))\n\nprint(New_Start[0])\nprint(\"--\"*10)\nprint(New_End[0])\nprint(\"--\"*10)\nprint(New_Path[0])\n\nprint(type(New_Start[0]))\nprint(\"--\"*10)\nprint(type(New_End[0]))\nprint(\"--\"*10)\nprint(type(New_Path[0]))\n\n# # \n\n# * To DataFrame\n\nStart_Series = pd.Series(New_Start,name=\"START\").astype(np.float32)\nEnd_Series = pd.Series(New_End,name=\"END\").astype(np.float32)\nPath_Series = pd.Series(New_Path,name=\"PATH\").astype(str)\n\nMain_Data = pd.concat([Path_Series,Start_Series,End_Series],axis=1)\n\nprint(Main_Data.head(-1))\n\n# # Vision\n\n# * Simple\n\n#IMAGE PROCESS Library\nfrom PIL import Image\nfrom keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport cv2\nfrom keras.applications.vgg16 import preprocess_input, decode_predictions\nfrom keras.preprocessing import image\nfrom skimage.feature import hessian_matrix, hessian_matrix_eigvals\nfrom scipy.ndimage.filters import convolve\nfrom skimage import data, io, filters\nimport skimage\nfrom skimage.morphology import convex_hull_image, erosion\nfrom IPython import display\nfrom scipy.ndimage import gaussian_filter\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nimport matplotlib.patches as patches\n\n# +\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][33]),cv2.COLOR_BGR2RGB)\n\nfigure = plt.figure(figsize=(10,10))\n\nplt.xlabel(Example_IMG.shape)\nplt.ylabel(Example_IMG.size)\nplt.imshow(Example_IMG)\n# -\n\n# * Multi\n\n# +\nfigure,axis = plt.subplots(5,5,figsize=(10,10))\n\nfor indexing,operations in enumerate(axis.flat):\n \n Reading_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][indexing]),cv2.COLOR_BGR2RGB)\n \n operations.set_xlabel(Reading_IMG.shape)\n operations.set_ylabel(Reading_IMG.size)\n operations.imshow(Reading_IMG)\n\nplt.tight_layout()\nplt.show()\n# -\n\n# * 2D\n\n# #### How do scientists predict and track solar flares?\n# * Scientists typically track solar cycles by counting sunspots—flares of activity spurred by knots of magnetic field loops. The sunspot number climbs over the course of a solar cycle, then drops near zero as magnetic activity subsides.\n\n# +\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][13]),cv2.COLOR_BGR2RGB)\n\nfigure = plt.figure(figsize=(10,10))\n\nplt.xlabel(Example_IMG[:,:,0].shape)\nplt.ylabel(Example_IMG[:,:,0].size)\nplt.imshow(Example_IMG[:,:,0])\n# -\n\n# * Threshold\n\n# +\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][13]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\n\nfigure = plt.figure(figsize=(10,10))\n\nplt.xlabel(Threshold_IMG.shape)\nplt.ylabel(Threshold_IMG.size)\nplt.imshow(Threshold_IMG)\n\n# +\nfigure,axis = plt.subplots(1,2,figsize=(10,10))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][13]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,2,figsize=(10,10))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][23]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,2,figsize=(10,10))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][2]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,2,figsize=(10,10))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][404]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\n# -\n\n# * Hessian Spectrum \n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(10,10))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][404]),cv2.COLOR_BGR2GRAY)\nHessian_IMG = hessian_matrix(Example_IMG,sigma=0.20,order=\"rc\")\nMax_IMG,Min_IMG = hessian_matrix_eigvals(Hessian_IMG)\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Max_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Min_IMG)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(10,10))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][44]),cv2.COLOR_BGR2GRAY)\nHessian_IMG = hessian_matrix(Example_IMG,sigma=0.20,order=\"rc\")\nMax_IMG,Min_IMG = hessian_matrix_eigvals(Hessian_IMG)\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Max_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Min_IMG)\naxis[2].axis(\"off\")\n# -\n\n# * Canny-Threshold Concat\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(10,10))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][44]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Canny_IMG)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(10,10))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][333]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Canny_IMG)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][333]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\nConcat_IMG = cv2.addWeighted(Example_IMG[:,:,0],0.8,Canny_IMG,0.4,0.5)\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Canny_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Concat_IMG)\naxis[2].axis(\"off\")\n# -\n\n# * Contours\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][13]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\nConcat_IMG = cv2.addWeighted(Example_IMG[:,:,0],0.8,Canny_IMG,0.4,0.5)\ncontours,_ = cv2.findContours(Canny_IMG,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n\nfor contour in contours:\n x,y,w,h = cv2.boundingRect(contour)\n Rect_IMG = cv2.rectangle(Concat_IMG,(x,y),(x+w,y+h),(255,0,0),2)\n \naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Concat_IMG,cmap=\"hot\")\naxis[1].axis(\"off\")\naxis[2].imshow(Threshold_IMG)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][333]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\nConcat_IMG = cv2.addWeighted(Example_IMG[:,:,0],0.8,Canny_IMG,0.4,0.5)\ncontours,_ = cv2.findContours(Canny_IMG,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n\nfor contour in contours:\n x,y,w,h = cv2.boundingRect(contour)\n Rect_IMG = cv2.rectangle(Concat_IMG,(x,y),(x+w,y+h),(255,0,0),2)\n \naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Concat_IMG,cmap=\"hot\")\naxis[1].axis(\"off\")\naxis[2].imshow(Threshold_IMG)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][113]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\nConcat_IMG = cv2.addWeighted(Example_IMG[:,:,0],0.8,Canny_IMG,0.4,0.5)\ncontours,_ = cv2.findContours(Canny_IMG,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n\nfor contour in contours:\n x,y,w,h = cv2.boundingRect(contour)\n Rect_IMG = cv2.rectangle(Concat_IMG,(x,y),(x+w,y+h),(255,0,0),2)\n \naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Concat_IMG,cmap=\"hot\")\naxis[1].axis(\"off\")\naxis[2].imshow(Threshold_IMG)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][188]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\nConcat_IMG = cv2.addWeighted(Example_IMG[:,:,0],0.8,Canny_IMG,0.4,0.5)\ncontours,_ = cv2.findContours(Canny_IMG,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n\nfor contour in contours:\n x,y,w,h = cv2.boundingRect(contour)\n Rect_IMG = cv2.rectangle(Concat_IMG,(x,y),(x+w,y+h),(255,0,0),2)\n \naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Concat_IMG,cmap=\"hot\")\naxis[1].axis(\"off\")\naxis[2].imshow(Threshold_IMG)\naxis[2].axis(\"off\")\n# -\n\n# * Layer Concat\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][13]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\nCopy_Main = Example_IMG.copy()\nCopy_Main[Canny_IMG == 1] = [0,255,0]\nCopy_Main[Canny_IMG == 2] = [0,0,255]\nCopy_Main_Two = Example_IMG.copy()\n\nConcat_IMG = cv2.addWeighted(Copy_Main,0.5,Copy_Main_Two,0.7,0,Copy_Main_Two)\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Canny_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Concat_IMG)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][13]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\nCopy_Main = Example_IMG.copy()\nCopy_Main[Canny_IMG == 255] = [255,0,0]\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Canny_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Copy_Main)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][123]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\nCopy_Main = Example_IMG.copy()\nCopy_Main[Canny_IMG == 255] = [255,0,0]\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Canny_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Copy_Main)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][223]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\nCopy_Main = Example_IMG.copy()\nCopy_Main[Threshold_IMG[:,:,0] == 255] = [255,0,0]\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Copy_Main)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][1]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\nCopy_Main = Example_IMG.copy()\nCopy_Main[Threshold_IMG[:,:,0] == 255] = [255,0,0]\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Copy_Main)\naxis[2].axis(\"off\")\n\n# +\nfigure,axis = plt.subplots(1,3,figsize=(15,15))\n\nExample_IMG = cv2.cvtColor(cv2.imread(Main_Data[\"PATH\"][17]),cv2.COLOR_BGR2RGB)\n_,Threshold_IMG = cv2.threshold(Example_IMG,200,255,cv2.THRESH_BINARY)\nCanny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\nCopy_Main = Example_IMG.copy()\nCopy_Main[Threshold_IMG[:,:,0] == 255] = [255,0,0]\n\naxis[0].imshow(Example_IMG)\naxis[0].axis(\"off\")\naxis[1].imshow(Threshold_IMG)\naxis[1].axis(\"off\")\naxis[2].imshow(Copy_Main)\naxis[2].axis(\"off\")\n# -\n\n# # Data Transformation\n\n# * For Prediction\n\n#SCALER & TRANSFORMATION Library\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.utils.np_utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom keras import regularizers\nfrom sklearn.preprocessing import LabelEncoder\n\n# +\nX_Start = []\nX_End = []\nX_Image = []\n\nfor img,start_i,end_i in zip(Main_Data.PATH.values,Main_Data.START.values,Main_Data.END.values):\n Picking_IMG = cv2.cvtColor(cv2.imread(img),cv2.COLOR_BGR2RGB)\n Picking_IMG = cv2.resize(Picking_IMG,(180,180))\n Picking_IMG = Picking_IMG / 255.\n \n X_Image.append(Picking_IMG)\n X_Start.append(start_i)\n X_End.append(end_i)\n# -\n\nprint(np.shape(np.array(X_Image)))\nprint(np.shape(np.array(X_Start)))\nprint(np.shape(np.array(X_End)))\n\nTrain_JPG = np.array(X_Image,dtype=\"float32\")\nTrain_START = np.array(X_Start,dtype=\"float32\")\nTrain_END = np.array(X_End,dtype=\"float32\")\n\nprint(Train_JPG.shape)\nprint(Train_START.shape)\nprint(Train_END.shape)\n\n# +\nScalar_Function = MinMaxScaler()\n\nTrain_START_R = Scalar_Function.fit_transform(Train_START.reshape(-1,1))\nTrain_END_R = Scalar_Function.fit_transform(Train_END.reshape(-1,1))\n# -\n\n# * For Auto-Encoder\n\n# +\nX_Mask = []\nX_New_IMG = []\n\nfor img_i in Main_Data.PATH.values:\n Picking_IMG = cv2.cvtColor(cv2.imread(img_i),cv2.COLOR_BGR2RGB)\n _,Threshold_IMG = cv2.threshold(Picking_IMG,200,255,cv2.THRESH_BINARY)\n Canny_IMG = cv2.Canny(Threshold_IMG,10,100)\n\n Copy_Main = Picking_IMG.copy()\n Copy_Main[Canny_IMG == 255] = [255,0,0]\n \n Copy_Main = cv2.resize(Copy_Main,(180,180))\n Copy_Main = Copy_Main / 255.\n \n Picking_IMG = cv2.resize(Picking_IMG,(180,180))\n Picking_IMG = Picking_IMG / 255.\n \n X_Mask.append(Copy_Main)\n X_New_IMG.append(Picking_IMG)\n\n# +\nX_Mask = []\nX_New_IMG = []\n\nbatch_size = 1 \nfor start_idx in range(0, len(Main_Data.PATH.values), batch_size):\n end_idx = start_idx + batch_size\n \n # Process images in the current batch\n for img_path in Main_Data.PATH.values[start_idx:end_idx]:\n Picking_IMG = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)\n _, Threshold_IMG = cv2.threshold(Picking_IMG, 200, 255, cv2.THRESH_BINARY)\n Canny_IMG = cv2.Canny(Threshold_IMG, 10, 100)\n\n Copy_Main = Picking_IMG.copy()\n Copy_Main[Canny_IMG == 255] = [255, 0, 0]\n\n Copy_Main = cv2.resize(Copy_Main, (180, 180))\n Copy_Main = Copy_Main / 255.\n\n Picking_IMG = cv2.resize(Picking_IMG, (180, 180))\n Picking_IMG = Picking_IMG / 255.\n\n X_Mask.append(Copy_Main)\n X_New_IMG.append(Picking_IMG)\n\n# After the loop, X_Mask and X_New_IMG will contain the processed images\n\n# -\n\nX_Mask = np.array(X_Mask,dtype=\"float32\")\nX_New_IMG = np.array(X_New_IMG,dtype=\"float32\")\n\n\n\n\n\n#ACCURACY CONTROL library\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report, roc_auc_score, roc_curve\nfrom sklearn.model_selection import GridSearchCV, cross_val_score\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n#OPTIMIZER library\nfrom keras.optimizers import RMSprop,Adam,Optimizer,Optimizer, SGD\n\n#MODEL LAYERS Library\nfrom tensorflow.keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization,MaxPooling2D,BatchNormalization,\\\n Permute, TimeDistributed, Bidirectional,GRU, SimpleRNN,\\\nLSTM, GlobalAveragePooling2D, SeparableConv2D, ZeroPadding2D, Convolution2D, ZeroPadding2D,Reshape, Conv2DTranspose,\\\nLeakyReLU, GaussianNoise, GlobalMaxPooling2D, ReLU, Input, Concatenate\nfrom keras import models\nfrom keras import layers\nimport tensorflow as tf\nfrom keras.applications import VGG16,VGG19,inception_v3\nfrom keras import backend as K\nfrom keras.utils import plot_model\nfrom keras.datasets import mnist\nimport keras\nfrom keras.models import Model\n\n#IGNORING WARNINGS Library\nfrom warnings import filterwarnings\nfilterwarnings(\"ignore\",category=DeprecationWarning)\nfilterwarnings(\"ignore\", category=FutureWarning) \nfilterwarnings(\"ignore\", category=UserWarning)\n","repo_name":"radidel/radidel.github.io","sub_path":"Solar_flares.ipynb","file_name":"Solar_flares.ipynb","file_ext":"py","file_size_in_byte":18055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"14621573869","text":"# + pycharm={\"name\": \"#%%\\n\"}\n# Import necessary libraries and modules\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nimport tadasets\nfrom sklearn.metrics import pairwise_distances\n\n\n# + pycharm={\"name\": \"#%%\\n\"}\n# Function to create a Vietoris-Rips complex given a distance matrix and radius\ndef create_simplicial_complex(D, r):\n \"\"\"\n Input: distance matrix and not negative radius\n Output: networkx graph\n \"\"\"\n\n G = nx.Graph()\n G.add_nodes_from(list(range(len(D))))\n edge_list = np.argwhere(D <= r)\n G.add_edges_from(edge_list)\n\n # Remove self-loops\n G.remove_edges_from(nx.selfloop_edges(G))\n\n return G\n\n\n# + pycharm={\"name\": \"#%%\\n\"}\n# Generate three sets of 2D points with different means and covariances\nX1 = np.random.multivariate_normal([0, 0], np.array([[1, 0], [0, 1]]), size=10)\nX2 = np.random.multivariate_normal([7, 0], np.array([[1, 0], [0, 0.2]]), size=8)\nX3 = np.random.multivariate_normal([0, 11], np.array([[1, 0], [0, 1]]), size=12)\n\n# Combine the three sets of points into one array\nX = np.concatenate((X1, X2, X3))\n\n# Plot the combined points\nplt.plot(X[:, 0], X[:, 1], 'o')\nplt.axis('equal')\nplt.show()\n\n# + pycharm={\"name\": \"#%%\\n\"}\nX\n\n# + pycharm={\"name\": \"#%%\\n\"}\n# Set random seed for reproducibility\nnp.random.seed(9)\n\n# Generate points from a noisy d-sphere using Tadasets library\nx = tadasets.dsphere(n=50, d=1, noise=0.1)\ny = np.array([[1, 0], [0, 1], [2, 2]])\n\n# Plot the points from the d-sphere\nplt.scatter(x[:, 0], x[:, 1])\nplt.axis('equal')\nplt.show()\n\n# + pycharm={\"name\": \"#%%\\n\"}\nnuevox = pd.DataFrame(x)\nnuevoy = pd.DataFrame(y)\n\n# + pycharm={\"name\": \"#%%\\n\"}\nnuevox\n\n# + pycharm={\"name\": \"#%%\\n\"}\nnuevoy\n\n# + pycharm={\"name\": \"#%%\\n\"}\n# Convert x and y (another dataset) to pandas dataframes\nnuevox = pd.DataFrame(x)\nnuevoy = pd.DataFrame(y)\n\n# Calculate pairwise distance matrices for x and y\ndist = pairwise_distances(x)\nplt.imshow(dist)\nplt.show()\n\n# + pycharm={\"name\": \"#%%\\n\"}\ny = pairwise_distances(y)\nplt.imshow(y)\nplt.show()\n\n# + pycharm={\"name\": \"#%%\\n\"}\n# Create and plot Vietoris-Rips complex for radius 0.5\nr = 0.5\nG = create_simplicial_complex(dist, r)\nnx.draw_kamada_kawai(G)\n\n# + pycharm={\"name\": \"#%%\\n\"}\nposi = {n: x[n, :] for n in range(len(x))}\nplt.figure(figsize=(5, 5))\n\nnx.draw_networkx(G, pos=posi, with_labels=False, node_size=20)\nplt.axis('equal')\nplt.show()\n\n# + pycharm={\"name\": \"#%%\\n\"}\n# Create and plot Vietoris-Rips complex for radius 0.7\nr = 0.7\nG = create_simplicial_complex(dist, r)\nnx.draw_kamada_kawai(G)\n\n# + pycharm={\"name\": \"#%%\\n\"}\nposi = {n: x[n, :] for n in range(len(x))}\nplt.figure(figsize=(5, 5))\n\nnx.draw_networkx(G, pos=posi, with_labels=False, node_size=20)\nplt.axis('equal')\nplt.show()\n\n# + pycharm={\"name\": \"#%%\\n\"}\n# Create and plot Vietoris-Rips complex for radius 1\nr = 1\nG = create_simplicial_complex(dist, r)\nnx.draw_kamada_kawai(G)\n\n# + pycharm={\"name\": \"#%%\\n\"}\nposi = {n: x[n, :] for n in range(len(x))}\nplt.figure(figsize=(5, 5))\n\nnx.draw_networkx(G, pos=posi, with_labels=False, node_size=20)\nplt.axis('equal')\nplt.show()\n","repo_name":"cesar-xyz/Topologia","sub_path":"complejoSimplicial.ipynb","file_name":"complejoSimplicial.ipynb","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"7754447719","text":"# + id=\"jjqL4lTWDUhP\" colab_type=\"code\" outputId=\"16a84d47-f240-41cc-8b3b-b7310aa532fb\" executionInfo={\"status\": \"ok\", \"timestamp\": 1587542145260, \"user_tz\": -480, \"elapsed\": 3244, \"user\": {\"displayName\": \"Liao Jack\", \"photoUrl\": \"\", \"userId\": \"16157886839679822522\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 50}\nimport keras\nkeras.__version__\n\n# + [markdown] id=\"1fFvz2ojDUhU\" colab_type=\"text\"\n# # Sequence processing with convnets\n# ## Implementing a 1D convnet\n#\n# In Keras, you would use a 1D convnet via the `Conv1D` layer, which has a very similar interface to `Conv2D`. It takes as input 3D tensors \n# with shape `(samples, time, features)` and also returns similarly-shaped 3D tensors. The convolution window is a 1D window on the temporal \n# axis, axis 1 in the input tensor.\n#\n# Let's build a simple 2-layer 1D convnet and apply it to the IMDB sentiment classification task that you are already familiar with.\n#\n# As a reminder, this is the code for obtaining and preprocessing the data:\n\n# + id=\"GeEdmRH7DUhU\" colab_type=\"code\" outputId=\"5e33ed47-bc4a-4d1c-9c80-b42b72160ff7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1587542154704, \"user_tz\": -480, \"elapsed\": 12675, \"user\": {\"displayName\": \"Liao Jack\", \"photoUrl\": \"\", \"userId\": \"16157886839679822522\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 151}\nfrom keras.datasets import imdb\nfrom keras.preprocessing import sequence\n\nmax_features = 10000 # number of words to consider as features\nmax_len = 500 # cut texts after this number of words (among top max_features most common words)\n\nprint('Loading data...')\n(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)\nprint(len(x_train), 'train sequences')\nprint(len(x_test), 'test sequences')\n\nprint('Pad sequences (samples x time)')\nx_train = sequence.pad_sequences(x_train, maxlen=max_len)\nx_test = sequence.pad_sequences(x_test, maxlen=max_len)\nprint('x_train shape:', x_train.shape)\nprint('x_test shape:', x_test.shape)\n\n# + [markdown] id=\"dBYaA5zPDUhY\" colab_type=\"text\"\n# This is our example 1D convnet for the IMDB dataset:\n\n# + id=\"9MvCtNJeDUhY\" colab_type=\"code\" outputId=\"d8477977-bbbd-4268-bfd0-f33b38ffa327\" executionInfo={\"status\": \"ok\", \"timestamp\": 1587542198373, \"user_tz\": -480, \"elapsed\": 56334, \"user\": {\"displayName\": \"Liao Jack\", \"photoUrl\": \"\", \"userId\": \"16157886839679822522\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 759}\nfrom keras.models import Sequential\nfrom keras import layers\nfrom keras.optimizers import RMSprop\n\nmodel = Sequential()\nmodel.add(layers.Embedding(max_features, 128, input_length=max_len))\nmodel.add(layers.Conv1D(32, 7, activation='relu'))\nmodel.add(layers.MaxPooling1D(5))\nmodel.add(layers.Conv1D(32, 7, activation='relu'))\nmodel.add(layers.GlobalMaxPooling1D())\nmodel.add(layers.Dense(1))\n\nmodel.summary()\n\nmodel.compile(optimizer=RMSprop(lr=1e-4),\n loss='binary_crossentropy',\n metrics=['acc'])\nhistory = model.fit(x_train, y_train,\n epochs=10,\n batch_size=128,\n validation_split=0.2)\n\n# + [markdown] id=\"aoOijqtYDUhb\" colab_type=\"text\"\n# 繪圖\n\n# + id=\"iyXKwEU4DUhb\" colab_type=\"code\" outputId=\"b54fb5b1-a7d5-432d-8f17-f6b4f566f810\" executionInfo={\"status\": \"ok\", \"timestamp\": 1587542198817, \"user_tz\": -480, \"elapsed\": 56767, \"user\": {\"displayName\": \"Liao Jack\", \"photoUrl\": \"\", \"userId\": \"16157886839679822522\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 545}\nimport matplotlib.pyplot as plt\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n# + [markdown] id=\"sma33T51DUhf\" colab_type=\"text\"\n# ## Combining CNNs and RNNs to process long sequences\n\n# + id=\"bA7PgyAXkn1Z\" colab_type=\"code\" outputId=\"96057e29-e4c4-4c8a-b998-79f7b97a98b8\" executionInfo={\"status\": \"ok\", \"timestamp\": 1587542204980, \"user_tz\": -480, \"elapsed\": 62917, \"user\": {\"displayName\": \"Liao Jack\", \"photoUrl\": \"\", \"userId\": \"16157886839679822522\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 235}\n# !wget https://s3.amazonaws.com/keras-datasets/jena_climate_2009_2016.csv.zip\n# !unzip jena_climate_2009_2016.csv.zip\n\n# + id=\"--7RfsIpDUhg\" colab_type=\"code\" colab={}\n# We reuse the following variables defined in the last section:\n# float_data, train_gen, val_gen, val_steps\n\nimport os\nimport numpy as np\n\ndata_dir = './'\nfname = os.path.join(data_dir, 'jena_climate_2009_2016.csv')\n\nf = open(fname)\ndata = f.read()\nf.close()\n\nlines = data.split('\\n')\nheader = lines[0].split(',')\nlines = lines[1:]\n\nfloat_data = np.zeros((len(lines), len(header) - 1))\nfor i, line in enumerate(lines):\n values = [float(x) for x in line.split(',')[1:]]\n float_data[i, :] = values\n \nmean = float_data[:200000].mean(axis=0)\nfloat_data -= mean\nstd = float_data[:200000].std(axis=0)\nfloat_data /= std\n\ndef generator(data, lookback, delay, min_index, max_index,\n shuffle=False, batch_size=128, step=6):\n if max_index is None:\n max_index = len(data) - delay - 1\n i = min_index + lookback\n while 1:\n if shuffle:\n rows = np.random.randint(\n min_index + lookback, max_index, size=batch_size)\n else:\n if i + batch_size >= max_index:\n i = min_index + lookback\n rows = np.arange(i, min(i + batch_size, max_index))\n i += len(rows)\n\n samples = np.zeros((len(rows),\n lookback // step,\n data.shape[-1]))\n targets = np.zeros((len(rows),))\n for j, row in enumerate(rows):\n indices = range(rows[j] - lookback, rows[j], step)\n samples[j] = data[indices]\n targets[j] = data[rows[j] + delay][1]\n yield samples, targets\n \nlookback = 1440\nstep = 6\ndelay = 144\nbatch_size = 128\n\ntrain_gen = generator(float_data,\n lookback=lookback,\n delay=delay,\n min_index=0,\n max_index=200000,\n shuffle=True,\n step=step, \n batch_size=batch_size)\nval_gen = generator(float_data,\n lookback=lookback,\n delay=delay,\n min_index=200001,\n max_index=300000,\n step=step,\n batch_size=batch_size)\ntest_gen = generator(float_data,\n lookback=lookback,\n delay=delay,\n min_index=300001,\n max_index=None,\n step=step,\n batch_size=batch_size)\n\n# This is how many steps to draw from `val_gen`\n# in order to see the whole validation set:\nval_steps = (300000 - 200001 - lookback) // batch_size\n\n# This is how many steps to draw from `test_gen`\n# in order to see the whole test set:\ntest_steps = (len(float_data) - 300001 - lookback) // batch_size\n\n# + id=\"pPJQsaN7DUhj\" colab_type=\"code\" outputId=\"d6ddcb57-9fd9-4dd2-c00f-2c9ba6c6c494\" executionInfo={\"status\": \"ok\", \"timestamp\": 1587542495834, \"user_tz\": -480, \"elapsed\": 353759, \"user\": {\"displayName\": \"Liao Jack\", \"photoUrl\": \"\", \"userId\": \"16157886839679822522\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 689}\nfrom keras.models import Sequential\nfrom keras import layers\nfrom keras.optimizers import RMSprop\n\nmodel = Sequential()\nmodel.add(layers.Conv1D(32, 5, activation='relu',\n input_shape=(None, float_data.shape[-1])))\nmodel.add(layers.MaxPooling1D(3))\nmodel.add(layers.Conv1D(32, 5, activation='relu'))\nmodel.add(layers.MaxPooling1D(3))\nmodel.add(layers.Conv1D(32, 5, activation='relu'))\nmodel.add(layers.GlobalMaxPooling1D())\nmodel.add(layers.Dense(1))\n\nmodel.compile(optimizer=RMSprop(), loss='mae')\nhistory = model.fit_generator(train_gen,\n steps_per_epoch=500,\n epochs=20,\n validation_data=val_gen,\n validation_steps=val_steps)\n\n# + [markdown] id=\"r54fhB_cDUho\" colab_type=\"text\"\n# Here are our training and validation Mean Absolute Errors:\n\n# + id=\"r7yK_n2pDUhp\" colab_type=\"code\" outputId=\"edbf76e5-f9a9-4c6d-8ea5-38f729829bce\" executionInfo={\"status\": \"ok\", \"timestamp\": 1587542495837, \"user_tz\": -480, \"elapsed\": 353753, \"user\": {\"displayName\": \"Liao Jack\", \"photoUrl\": \"\", \"userId\": \"16157886839679822522\"}} colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 281}\nimport matplotlib.pyplot as plt\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(loss))\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n\n# + [markdown] id=\"_co70oX3DUhs\" colab_type=\"text\"\n# 為數據集準備高解析率的資料產生器\n\n# + id=\"hrqjAXa-DUhs\" colab_type=\"code\" colab={}\n# This was previously set to 6 (one point per hour).\n# Now 3 (one point per 30 min).\nstep = 3\nlookback = 720 # Unchanged\ndelay = 144 # Unchanged\n\ntrain_gen = generator(float_data,\n lookback=lookback,\n delay=delay,\n min_index=0,\n max_index=200000,\n shuffle=True,\n step=step)\nval_gen = generator(float_data,\n lookback=lookback,\n delay=delay,\n min_index=200001,\n max_index=300000,\n step=step)\ntest_gen = generator(float_data,\n lookback=lookback,\n delay=delay,\n min_index=300001,\n max_index=None,\n step=step)\nval_steps = (300000 - 200001 - lookback) // 128\ntest_steps = (len(float_data) - 300001 - lookback) // 128\n\n# + [markdown] id=\"Jt1k09m9DUhv\" colab_type=\"text\"\n# This is our model, starting with two `Conv1D` layers and following-up with a `GRU` layer:\n\n# + id=\"WrE-mxV0HTjW\" colab_type=\"code\" colab={}\nmodel = Sequential()\nmodel.add(layers.Conv1D(32, 5, activation='relu',\n input_shape=(None, float_data.shape[-1])))\nmodel.add(layers.MaxPooling1D(3))\nmodel.add(layers.Conv1D(32, 5, activation='relu'))\nmodel.add(layers.GRU(32, dropout=0.1, recurrent_dropout=0.5))\nmodel.add(layers.Dense(1))\n\nmodel.summary()\n\nmodel.compile(optimizer=RMSprop(), loss='mae')\nhistory = model.fit_generator(train_gen,\n steps_per_epoch=500,\n epochs=20,\n validation_data=val_gen,\n validation_steps=val_steps)\n\n# + id=\"EHPAvagxHYlp\" colab_type=\"code\" colab={}\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(loss))\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()\n","repo_name":"jackliaoall/deep-learning-with-python-notebooks_exercises","sub_path":"6.4-sequence-processing-with-convnets.ipynb","file_name":"6.4-sequence-processing-with-convnets.ipynb","file_ext":"py","file_size_in_byte":11493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"29830443818","text":"# # Multiple Linear Regression - Ejercicio - Publicidad y Ventas\n\n# **Contexto** \n# Este conjunto de datos contiene las ventas obtenidas, de acuerdo al monto invertido en publicidad en diferentes canales.\n#\n# **Contenido** \n# El conjunto de datos proviene de kaggle: [Advertising dataset](https://www.kaggle.com/datasets/tawfikelmetwally/advertising-dataset). \n# Contiene 200 renglones, con las siguientes columnas: \n#\n# | Variable | Definición | Valor |\n# | --------- | ---------------------------------------- | --------------- |\n# | TV | Inversión en anuncios por TV | miles de USD |\n# | Radio | Inversión en anuncios por radio | miles de USD |\n# | Newspaper | Inversión en anuncios por periódico | miles de USD |\n# | Sales | Ventas obtenidas **(variable objetivo)** | millones de USD | \n#\n# **Planteamiento del problema** \n# Se busca predecir que canales tienen mayor impacto en las ventas obtenidas.\n\n# +\n# Importar librerias\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\n# -\n\n# ## Cargar Datos\n\n# Importar los datos\ndf = pd.read_csv('Advertising.csv')\ndf.head()\n\n# Renombrar columnas\ndf.columns = ['renglón', 'tv', 'radio', 'periodico', 'ventas']\ndf.head()\n\n# ## Normalización\n\n# Variables independientes\nX = df[['tv', 'radio', 'periodico']]\nX.head()\n\n# Normalizar\nscaler = StandardScaler()\nX_adj = scaler.fit_transform(X)\nprint(X_adj)\n\n# Variable dependiente\ny = df['ventas']\ny.head()\n\nprint('X:', len(X_adj), 'y:', len(y))\n\n# ## Modelado\n\n# Conjunto de entrenamiento y pruebas\nX_train, X_test, y_train, y_test = train_test_split(X_adj, y, test_size=0.3, random_state=0)\n\nprint('X_train:', len(X_train), 'y_train:', len(y_train))\nprint('X_test:', len(X_test), 'y_test:', len(y_test))\n\n# Entrenamiento\nmodel = LinearRegression()\nmodel.fit(X_train,y_train)\n\n# Predicciones\nprediction = model.predict(X_test)\nprediction\n\n# Resultados\nprint(model.intercept_)\ncoef = pd.DataFrame(model.coef_, X.columns, columns=['coeficiente'])\ncoef\n\n# ## Evaluacion\n\nprint('MAE:', metrics.mean_absolute_error(y_test, prediction))\nprint('MSE:', metrics.mean_squared_error(y_test, prediction))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, prediction)))\nprint('R2:', metrics.r2_score(y_test, prediction))\n\nax1 = sns.kdeplot(y_test, color=\"r\")\nsns.kdeplot(prediction, color=\"b\", ax=ax1)\n\n\n","repo_name":"csameshiman/Axity_Curso_ML_2023","sub_path":"Ejercicios/Parte 02.Regresión/02-02-MLR-Ejemplo-Pub.ipynb","file_name":"02-02-MLR-Ejemplo-Pub.ipynb","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"14051035630","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport os\nfrom sklearn.model_selection import train_test_split\n\nfile_names = os.listdir('crop_part1')\n\n# +\nimport re\npattern = re.compile(r\"(\\d+)_(\\d+)_(\\d+)\")\n\ndf = pd.DataFrame(columns = ['Age', 'Gender', 'Ethnicity'])\ncount = 0\nfor i in file_names:\n data =list(pattern.search(i).groups())\n df.loc[count] = data\n count += 1\n \n \n#7881 and 7876 are bad values\n# AGE, Gender, Ethnicity\n# 0 is male, 1 is female\n# Race is an integer from 0 to 4, denoting White, Black, Asian, Indian, and Others (like Hispanic, Latino, Middle Eastern).\n# 0 = White\n# 1 = Black\n# 2 = Asian\n# 3 = Indian\n# 4 = Others\n\ndf['JPG'] = file_names\nimg_path = []\ncount = 0\nfor row in df.iterrows():\n path = \"crop_part1/\"+df.JPG.iloc[count]\n img_path.append(path)\n count += 1\ndf['img_path'] = img_path\ndf2 = df[['Age', 'Gender', 'Ethnicity', 'JPG', 'img_path']].copy()\ndf2.head()\n# -\n\ndf3 = pd.DataFrame(columns = ['Age_Range'])\nages = df2['Age'].tolist()\ncount = 0\nfor i in ages:\n i = int(i)\n if i == 0 or i == 1 or i == 2 or i == 3:\n df3.loc[count] = '0-2'\n elif i == 4 or i == 5 or i == 6 or i == 7:\n df3.loc[count] = '4-6'\n elif i == 8 or i == 9 or i == 10 or i == 11 or i == 12 or i == 13 or i == 14:\n df3.loc[count] = '8-13'\n elif i == 15 or i == 16 or i == 17 or i == 18 or i == 19 or i == 20 or i == 21 or i == 22 or i == 23 or i == 24:\n df3.loc[count] = '15-20'\n elif i == 25 or i == 26 or i == 27 or i == 28 or i == 29 or i == 30 or i == 31 or i == 32 or i == 33 or i == 34 or i == 35 or i == 36 or i == 37 :\n df3.loc[count] = '25-32'\n elif i == 38 or i == 39 or i == 40 or i == 41 or i == 42 or i == 43 or i == 44 or i == 45 or i == 46 or i == 47:\n df3.loc[count] = '38-43'\n elif i == 48 or i == 49 or i == 50 or i == 51 or i == 52 or i == 53 or i == 54 or i == 55 or i == 56 or i == 57 or i == 58 or i == 59:\n df3.loc[count] = '48-53'\n else: \n df3.loc[count] = '60+'\n count += 1\ndf3['Age_Range'].value_counts()\n\ndf4 = pd.concat([df2, df3], axis=1, join='inner')\nage_to_label_map = {\n '0-2' :0,\n '4-6' :1,\n '8-13' :2,\n '15-20':3,\n '25-32':4,\n '38-43':5,\n '48-53':6,\n '60+' :7\n}\ndf4['Age_Range_Num'] = df4['Age_Range'].apply(lambda Age_Range: age_to_label_map[Age_Range])\ndf4.head()\n\n# +\ngender_df = pd.concat([df4,pd.get_dummies(df4['Gender'])],axis = 1)\ngender_df = gender_df[['JPG','0','1']]\ngender_df.columns = ['JPG','Male','Female']\ngender_df.to_csv('gender.csv')\n\nage_df = pd.concat([df4,pd.get_dummies(df4['Age_Range'])],axis = 1)\nage_df = age_df[['JPG','0-2','8-13','15-20','25-32','38-43','4-6','48-53','60+']]\nage_df.to_csv('age.csv')\n\nethnicity_df = pd.concat([df4,pd.get_dummies(df4['Ethnicity'])],axis = 1)\nethnicity_df = ethnicity_df[['JPG','0','1','2','3','4']]\nethnicity_df.columns = ['JPG','White','Black','Asian','Indian','Other']\nethnicity_df.to_csv('ethnicity.csv')\n# -\n\n# # Rename Gender Files\n\n \n\n# +\n# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\n\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nsrc_directory = 'crop_part1/'\ndataset_home = 'dataset_male_vs_females2/'\nsubdirs = ['male/', 'female/']\nfor subdir in subdirs:\n newdir = dataset_home + subdir \n makedirs(newdir, exist_ok=True)\n \ncount = 0\nfor file in listdir(src_directory):\n src = src_directory + '/' + file\n if df2.iloc[count]['JPG'] == file and int(df2.iloc[count]['Gender']) == 0:\n dst = dataset_home + 'male/' + file\n copyfile(src, dst)\n elif df2.iloc[count]['JPG'] == file and int(df2.iloc[count]['Gender']) == 1:\n dst = dataset_home + 'female/' + file\n copyfile(src, dst)\n count += 1\n# -\n\ntrainM_names = os.listdir('dataset_male_vs_females2/male')\ntrainF_names = os.listdir('dataset_male_vs_females2/female')\nprint('Train Male: ',len(trainM_names))\nprint('Train Female: ',len(trainF_names))\n# Train Male: 4370\n# Train Female: 5406\n\ndf2.Gender.value_counts()\n\n# # Rename Age Files\n\n# +\n# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\n\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nsrc_directory = 'crop_part1/'\ndataset_home = 'dataset_age2/'\nsubdirs = ['0-2/', '4-6/', '8-13/', '15-20/', '25-32/', '38-43/', '48-53/', '60+/']\nfor subdir in subdirs:\n newdir = dataset_home + subdir \n makedirs(newdir, exist_ok=True)\n\ncount = 0\nfor file in listdir(src_directory):\n src = src_directory + '/' + file\n if df4.iloc[count]['JPG'] == file and int(df4.iloc[count]['Age_Range_Num']) == 0:\n dst = dataset_home + '0-2/' + file\n copyfile(src, dst)\n elif df4.iloc[count]['JPG'] == file and int(df4.iloc[count]['Age_Range_Num']) == 1:\n dst = dataset_home + '4-6/' + file\n copyfile(src, dst)\n elif df4.iloc[count]['JPG'] == file and int(df4.iloc[count]['Age_Range_Num']) == 2:\n dst = dataset_home + '8-13/' + file\n copyfile(src, dst)\n elif df4.iloc[count]['JPG'] == file and int(df4.iloc[count]['Age_Range_Num']) == 3:\n dst = dataset_home + '15-20/' + file\n copyfile(src, dst)\n elif df4.iloc[count]['JPG'] == file and int(df4.iloc[count]['Age_Range_Num']) == 4:\n dst = dataset_home + '25-32/' + file\n copyfile(src, dst)\n elif df4.iloc[count]['JPG'] == file and int(df4.iloc[count]['Age_Range_Num']) == 5:\n dst = dataset_home + '38-43/' + file\n copyfile(src, dst)\n elif df4.iloc[count]['JPG'] == file and int(df4.iloc[count]['Age_Range_Num']) == 6:\n dst = dataset_home + '48-53/' + file\n copyfile(src, dst)\n else:\n dst = dataset_home + '60+/' + file\n copyfile(src, dst)\n \n count+= 1\n\n# +\nnames0 = os.listdir('dataset_age2/0-2')\nnames1 = os.listdir('dataset_age2/4-6')\nnames2 = os.listdir('dataset_age2/8-13')\nnames3 = os.listdir('dataset_age2/15-20')\nnames4 = os.listdir('dataset_age2/25-32')\nnames5 = os.listdir('dataset_age2/38-43')\nnames6 = os.listdir('dataset_age2/48-53')\nnames7 = os.listdir('dataset_age2/60+')\n\n\nprint('0-2: ',len(names0))\nprint('4-6: ',len(names1))\nprint('8-13: ',len(names2))\nprint('15-20: ',len(names3))\nprint('25-32: ',len(names4))\nprint('38-43: ',len(names5))\nprint('48-53: ',len(names6))\nprint('60+: ',len(names7))\nprint('Total: ', str(len(names0)+len(names1)+len(names2)+len(names3)+len(names4)+len(names5)+len(names6)+len(names7)))\n# -\n\ndf4.Age_Range_Num.value_counts()\n\n# # Rename Ethnicity Files\n\ndf2.Ethnicity.value_counts()\n\n# +\n# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\n\n# 0 = White\n# 1 = Black\n# 2 = Asian\n# 3 = Indian\n# 4 = Others\n\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nsrc_directory = 'crop_part1/'\ndataset_home = 'dataset_ethnicity/'\nsubdirs = ['White/', 'Black/', 'Asian/', 'Indian/', 'Others/']\nfor subdir in subdirs:\n newdir = dataset_home + subdir \n makedirs(newdir, exist_ok=True)\n\ncount = 0\nfor file in listdir(src_directory):\n src = src_directory + '/' + file\n if df2.iloc[count]['JPG'] == file and int(df2.iloc[count]['Ethnicity']) == 0:\n dst = dataset_home + 'White/' + file\n copyfile(src, dst)\n elif df2.iloc[count]['JPG'] == file and int(df2.iloc[count]['Ethnicity']) == 1:\n dst = dataset_home + 'Black/' + file\n copyfile(src, dst)\n elif df2.iloc[count]['JPG'] == file and int(df2.iloc[count]['Ethnicity']) == 2:\n dst = dataset_home + 'Asian/' + file\n copyfile(src, dst)\n elif df2.iloc[count]['JPG'] == file and int(df2.iloc[count]['Ethnicity']) == 3:\n dst = dataset_home + 'Indian/' + file\n copyfile(src, dst)\n else:\n dst = dataset_home + 'Others/' + file\n copyfile(src, dst)\n count += 1\n\n# +\nW_names = os.listdir('dataset_Ethnicity/White')\nB_names = os.listdir('dataset_Ethnicity/Black')\nA_names = os.listdir('dataset_Ethnicity/Asian')\nI_names = os.listdir('dataset_Ethnicity/Indian')\nO_names = os.listdir('dataset_Ethnicity/Others')\n\n\nprint('White: ',len(W_names))\nprint('Black: ',len(B_names))\nprint('Asian: ',len(A_names))\nprint('Indian: ',len(I_names))\nprint('Others: ',len(O_names))\nprint('Total: ', str(len(W_names)+len(B_names)+len(A_names)+len(I_names)+len(O_names)))\n\n\n# +\n# White: 5264\n# Black: 405\n# Asian: 1553\n# Indian: 1451\n# Others: 1103\n# Total: 9776\n# -\n\n# # Split files into train, test and val\n# ## Gender\n\n# +\nimport os\nimport numpy as np\nimport shutil\nimport pandas as pd\n\ndef train_test_split(root_dir, classes_dir, processed_dir):\n print(\"########### Train Test Val Script started ###########\")\n #data_csv = pd.read_csv(\"DataSet_Final.csv\") ##Use if you have classes saved in any .csv file\n\n val_ratio = 0.20\n test_ratio = 0.20\n\n for cls in classes_dir:\n # Creating partitions of the data after shuffeling\n print(\"$$$$$$$ Class Name \" + cls + \" $$$$$$$\")\n src = processed_dir +\"/\" + cls # Folder to copy images from\n\n allFileNames = os.listdir(src)\n np.random.shuffle(allFileNames)\n train_FileNames, val_FileNames, test_FileNames = np.split(np.array(allFileNames),\n [int(len(allFileNames) * (1 - (val_ratio + test_ratio))),\n int(len(allFileNames) * (1 - val_ratio)),\n ])\n\n train_FileNames = [src + '//' + name for name in train_FileNames.tolist()]\n val_FileNames = [src + '//' + name for name in val_FileNames.tolist()]\n test_FileNames = [src + '//' + name for name in test_FileNames.tolist()]\n\n print('Total images: '+ str(len(allFileNames)))\n print('Training: '+ str(len(train_FileNames)))\n print('Validation: '+ str(len(val_FileNames)))\n print('Testing: '+ str(len(test_FileNames)))\n\n # # Creating Train / Val / Test folders (One time use)\n os.makedirs(root_dir + '/train//' + cls)\n os.makedirs(root_dir + '/val//' + cls )\n os.makedirs(root_dir + '/test//' + cls)\n # Copy-pasting images\n for name in train_FileNames:\n shutil.copy(name, root_dir + '/train//' + cls)\n\n for name in val_FileNames:\n shutil.copy(name, root_dir + '/val//' + cls)\n\n for name in test_FileNames:\n shutil.copy(name, root_dir + '/test//' + cls)\n\n print(\"########### Train Test Val Script Ended ###########\")\n\n\n# -\n\nnew_direct = 'Gender_Images2'\nclasses = ['male', 'female']\nprocessed_direct = 'dataset_male_vs_females2/'\ntrain_test_split(new_direct, classes, processed_direct)\n\n# ## Age\n\n\n\nnew_direct2 = 'Age_Images2'\nclasses2 = ['0-2/', '4-6/', '8-13/', '15-20/', '25-32/', '38-43/', '48-53/', '60+/']\nprocessed_direct2 = 'dataset_age2/'\ntrain_test_split(new_direct2, classes2, processed_direct2)\n\n# # Ethnicity\n\n# +\n# Race is an integer from 0 to 4, denoting White, Black, Asian, Indian, and Others (like Hispanic, Latino, Middle Eastern).\n# 0 = White\n# 1 = Black\n# 2 = Asian\n# 3 = Indian\n# 4 = Others\n\nnew_direct3 = 'Ethnicity_Images'\nclasses3 = ['White','Black','Asian','Indian','Others']\nprocessed_direct3 = 'dataset_ethnicity/'\n\ntrain_test_split(new_direct3, classes3, processed_direct3)\n# -\n\n\n\n\n","repo_name":"NarainMandyam/GenderEthnicityAge-FaceClassifier","sub_path":"fileFormatting.ipynb","file_name":"fileFormatting.ipynb","file_ext":"py","file_size_in_byte":11659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"36070262117","text":"# # Создание столбцов на ходу\n# - Лена - разработчик\n# - Ваня - дизайнер\n# - Леша - редактор\n\nimport pandas as pd\n\ndf = pd.DataFrame({'dicts': [{'Лена': 1, 'Ваня': 2}, {'Ваня': 3, 'Леша': 5}, {'Настя': 3}]})\ndf\n\n\ndef departments(row):\n if 'Ваня' in row['dicts']:\n row['разработка'] = row['dicts']['Ваня']\n \n if 'Настя' in row['dicts']:\n row['финансы'] = row['dicts']['Настя']\n \n return row\n\n\ndf = df.apply(departments, axis=1)\ndf\n\nstaff = {\n 'Лена': 'разработчик',\n 'Ваня': 'дизайнер',\n 'Настя': 'редактор',\n 'Кеша': 'директорат',\n}\n\n\ndef new_columns(row):\n for name, value in row['dicts'].items():\n if name in staff:\n row[staff[name]] = value\n \n return row\n\n\ndf = df.apply(new_columns, axis=1)\ndf\n","repo_name":"vn322/Netology_DS_course","sub_path":"NumPy, pandas, MPL/3.6.pandas_functions_and_rows.ipynb","file_name":"3.6.pandas_functions_and_rows.ipynb","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"8078350712","text":"# +\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom tqdm.notebook import tqdm\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nimport os\nimport sys\nfrom PIL import Image \nfrom glob import glob\nfrom pathlib import Path\nimport imageio.v2 as imageio\nfrom datetime import datetime\nfrom typing import Union, List, Optional, Tuple\n\nsys.path.append(str(Path().absolute().parent))\nimport plotting\nimport importlib\nimportlib.reload(plotting)\n# from plotting import overlay_masks_on_data\n# -\n\n# # Resources\n# - [5 Ways to Make Histopathology Image Models More Robust to Domain Shifts](https://towardsdatascience.com/5-ways-to-make-histopathology-image-models-more-robust-to-domain-shifts-323d4d21d889)\n#\n# # Questions\n# - Is the transparency/alpha information (RGBA vs RGB) relevant to solve the problem?\n# - The images were captured with different scanners, inducing image variations?\n# - How patches were sampled? There's some overlapping between them?\n# - How to reconstruct the patches?\n# - How to overlap the reconstructed image (from patches) with the mask?\n\n# # Helpers\n\n# +\nbins = np.linspace(0, 255, 52)\n\n\ndef exists(obj):\n return obj is not None\n\n\ndef print_img_info(img: np.ndarray, desc: str = \"\"):\n print(\n desc,\n f\"min: {img.min()}\",\n f\"max: {img.max() }\",\n f\"mean: {img.mean():.2f}\",\n f\"ndim: {img.ndim}\",\n f\"channels: {img.shape[-1]}\",\n )\n\n\ndef read_image(image_path: Union[str, Path]) -> np.ndarray:\n \"\"\"Reads an image from a path and converts it to RGB format.\"\"\"\n if isinstance(image_path, Path):\n image_path = str(image_path)\n image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)\n return image.astype(np.float32)\n\n\ndef read_mask(mask_path: Union[str, Path]) -> np.ndarray:\n \"\"\"Reads a mask from a path and transform it to binary.\"\"\"\n if isinstance(mask_path, Path):\n mask_path = str(mask_path)\n mask = cv2.imread(mask_path, 0) / 255.0\n assert_mask_is_binary(mask)\n return mask.astype(np.float32)\n\n\ndef assert_mask_is_binary(mask: np.ndarray):\n \"\"\"Counts all the pixels different to zero and one to check if binary.\"\"\"\n assert (\n np.count_nonzero((mask != 0) & (mask != 1)) == 0\n ), f\"Mask is not binary. Unique values: {np.unique(mask)}\"\n\n\ndef read_images_grid(\n patches_paths: Union[List[str], List[Path]]\n) -> List[List[np.ndarray]]:\n patches = []\n for i, patches_paths_row in enumerate(patches_paths):\n images_row = []\n for j, patch_path in enumerate(patches_paths_row):\n image = read_image(patch_path) if exists(patch_path) else np.zeros((1024, 1024, 3))\n images_row.append(image)\n patches.append(images_row)\n return patches\n\n\ndef crop_black_frames_from_image(img: np.ndarray) -> np.ndarray: \n positions = np.nonzero(img)\n top = positions[0].min()\n bottom = positions[0].max()\n left = positions[1].min()\n right = positions[1].max()\n return img[top:bottom, left:right]\n\n\ndef sort_paths_from_idxs(\n patches_paths: Union[List[str], List[Path]]\n) -> List[List[Union[str, Path]]]:\n \"\"\"Creates a grid of paths from a list of paths based on their ids.\"\"\"\n if isinstance(patches_paths[0], str):\n patches_paths = [Path(patch_path) for patch_path in patches_paths]\n idxs = [patch_path.stem.split(\"_\")[-2:] for patch_path in patches_paths]\n idxs = [[int(i[0]), int(i[1])] for i in idxs]\n\n # Create the grid.\n (y_min, x_min), (y_max, x_max) = np.min(idxs, axis=0), np.max(idxs, axis=0)\n sorted_paths, missing_patches_idxs = [], []\n for j in range(y_max + 1):\n row_paths = []\n for i in range(x_max + 1):\n if [j, i] not in idxs:\n missing_patches_idxs.append([j, i])\n row_paths.append(None)\n else:\n row_paths.append(patches_paths[idxs.index([j, i])])\n sorted_paths.append(row_paths)\n\n return sorted_paths, missing_patches_idxs\n\n\n\n# -\n\n# # Exploration\n#\n# Create variables pointing to the directories holding the histopathological data\n\n# +\ndset_dir = \"/data/histopathology/TCGA/\"\ndset_dir = Path(dset_dir)\n\npatches_dir = dset_dir / \"patches\"\nmasks_dir = dset_dir / \"masks\"\n\n# In the patches directory are more directories and in the masks directory are png files.\npatches_dirs = sorted(patches_dir.iterdir())\nmasks_paths = sorted(masks_dir.iterdir())\n# -\n\n# ## How to read histopathological images\n#\n# The first thing to check is how are these images codified. Read them with different libraries.\n\n# +\n# Convert to RGB for cv2 images.\nfirst_patch_path = str(sorted(patches_dirs[0].iterdir())[0])\ncv_img = cv2.cvtColor(cv2.imread(first_patch_path), cv2.COLOR_BGR2RGB)\ncv_img_unchanged = cv2.cvtColor(cv2.imread(first_patch_path, -1), cv2.COLOR_BGRA2RGBA)\nio_img = imageio.imread(first_patch_path)\npil_img = np.array(Image.open(first_patch_path))\n\nprint_img_info(cv_img, desc=\"Standard cv imread\")\nprint_img_info(cv_img_unchanged, desc=\"Unchanged cv imread\")\nprint_img_info(io_img, desc=\"Imageio imread\")\nprint_img_info(pil_img, desc=\"PIL imread\")\n\nassert np.array_equal(cv_img_unchanged, io_img) and np.array_equal(\n cv_img_unchanged, pil_img\n), \"Images are not equal.\"\n\n# -\n\n# Imageio, PIL and OpenCV (if specified) read the images without changing their intensity values. The images seem to be codified in RGB with transparency. *Is the transparency information relevant to solve the problem?*\n#\n# Plot the different images to check if there are noticeable differences.\n\nfig, ax = plt.subplots(1, 4, figsize=(40, 10))\nax[0].imshow(cv_img)\nax[0].set_title(\"Standard cv imread\")\nax[1].imshow(cv_img_unchanged)\nax[1].set_title(\"Unchanged cv imread\")\nax[2].imshow(io_img)\nax[2].set_title(\"Imageio imread\")\nax[3].imshow(pil_img)\nax[3].set_title(\"PIL imread\")\n\n\n# There are no noticeable visual differences. Check the mean intensity for the last channel in the images with transparency\n\nfig, ax = plt.subplots(1, 4, figsize=(20, 5))\nax[0].set_title(\"Red channel\")\nax[0].hist(cv_img_unchanged[..., 0].ravel(), density=True, bins=bins)\nax[1].set_title(\"Green channel\")\nax[1].hist(cv_img_unchanged[..., 1].ravel(), density=True, bins=bins)\nax[2].set_title(\"Blue channel\")\nax[2].hist(cv_img_unchanged[..., 2].ravel(), density=True, bins=bins)\nax[3].set_title(\"Alpha channel\")\nax[3].hist(cv_img_unchanged[..., 3].ravel(), density=True, bins=bins)\n\n\n# Might be a bit hasty, but judging by the intensity distribution in the transparency channel, you could use the images with their RGB coding and not RGBA. In fact, if we look at the minimum, maximum and average values we can corroborate that all the information is located in a very small interval.\n\nprint(\n \"Alpha channel ->\",\n \"min:\",\n cv_img_unchanged[..., 3].min(),\n \"max:\",\n cv_img_unchanged[..., 3].max(),\n \"mean:\",\n cv_img_unchanged[..., 3].mean(),\n)\n\n\n# Take more samples and see if the same conclusions can be drawn\n\n# +\npatches_paths = []\nfor patch_dir in patches_dirs:\n patches_paths.extend(sorted(patch_dir.iterdir()))\n\n\nnp.random.seed(4321)\nrandom_patches_paths = np.random.choice(patches_paths, size=200, replace=False)\n\npatches = []\nfor random_patch_path in random_patches_paths:\n patch = cv2.cvtColor(cv2.imread(str(random_patch_path), -1), cv2.COLOR_BGRA2RGBA)\n patches.append(patch)\n\n\npatches = np.array(patches)\nprint_img_info(patches, desc=\"Patches\")\n\n# -\n\n# Plot five patches to see the difference\n\n# plot 5 random patches.\nfig, ax = plt.subplots(1, 5, figsize=(20, 5))\nfor i in range(5):\n ax[i].imshow(patches[i])\n ax[i].set_title(f\"Patch {i}\")\n\n\n# Plot the intensity distribution for each channel of the `patches` array. Compare it against the normalized histogram of the previous image\n\nfig, ax = plt.subplots(1, 4, figsize=(20, 5))\nax[0].set_title(\"Red channel\")\nax[0].hist(patches[..., 0].ravel(), density=True, bins=bins)\nax[0].hist(\n cv_img_unchanged[..., 0].ravel(),\n color=\"red\",\n density=True,\n histtype=\"step\",\n bins=bins,\n)\nax[1].set_title(\"Green channel\")\nax[1].hist(patches[..., 1].ravel(), density=True, bins=bins)\nax[1].hist(\n cv_img_unchanged[..., 1].ravel(),\n color=\"red\",\n density=True,\n histtype=\"step\",\n bins=bins,\n)\nax[2].set_title(\"Blue channel\")\nax[2].hist(patches[..., 2].ravel(), density=True, bins=bins)\nax[2].hist(\n cv_img_unchanged[..., 2].ravel(),\n color=\"red\",\n density=True,\n histtype=\"step\",\n bins=bins,\n)\nax[3].set_title(\"Alpha channel\")\nax[3].hist(patches[..., 3].ravel(), density=True, bins=bins, label=\"200 random patches\")\nax[3].hist(\n cv_img_unchanged[..., 3].ravel(),\n color=\"red\",\n density=True,\n histtype=\"step\",\n bins=bins,\n label=\"1 patch\",\n)\nax[3].legend()\n\n\n# *Distributions look very similar for one or multiple randomly sampled patches. Therefore, it seems that the alpha channel holds a lot of repeated information*. \n\n# ## Defining the splits\n#\n# The dataset has some samples without masks that are meant to be used for test. The samples that have a patches directory and a mask are for training. Compare the ids of the patches directories and the masks to find which are the test samples.\n\n# +\nmask_sample_ids = [mask_path.stem[:-5] for mask_path in masks_paths]\npatches_sample_ids = [patch_dir.name for patch_dir in patches_dirs]\ntest_sample_ids = sorted(list(set(patches_sample_ids).difference(mask_sample_ids)))\ntrain_sample_ids = sorted(list(set(patches_sample_ids).intersection(mask_sample_ids)))\n\nprint(f\"Number of samples with masks: {len(train_sample_ids)} \\n\")\nprint(f\"Samples ids without masks:\", *test_sample_ids, sep=\"\\n- \")\n\n# -\n\n# ## Error checking at upload\n#\n# Iterate over the training and test samples directories to make sure they have patches uploaded and that no mask exist for the test samples\n#\n# ### Train split\n#\n# There are six samples without images inside the patches directories. Aside from that, everything seems fine.\n\nfor train_sample_id in train_sample_ids:\n\n sample_mask_path = masks_dir / f\"{train_sample_id}_mask.png\"\n\n sample_patches_dir = patches_dir / train_sample_id\n sample_patches_paths = sorted(sample_patches_dir.iterdir())\n sample_num_patches = len(sample_patches_paths)\n\n if sample_num_patches == 0:\n print(f\"{train_sample_id} do not have patches\")\n\n if not sample_mask_path.exists():\n print(f\"{train_sample_id} do not have a mask\")\n\n\n# ### Test split\n#\n# Everything seems ordered for the samples in the test split, i.e. all the patch directories contain image and there are no masks.\n\nfor test_sample_id in test_sample_ids:\n\n sample_mask_path = masks_dir / f\"{test_sample_id}_mask.png\"\n\n sample_patches_dir = patches_dir / test_sample_id\n sample_patches_paths = sorted(sample_patches_dir.iterdir())\n sample_num_patches = len(sample_patches_paths)\n\n if sample_num_patches == 0:\n print(f\"{test_sample_id} do not have patches\")\n\n if sample_mask_path.exists():\n print(f\"{test_sample_id} has a mask\")\n\n\n# \n\n# ## Image reconstruction: how to overlap the masks and patches\n#\n# ### Unusual things\n\n# #### Square grid\n#\n# At first, I believed that the patches should make a squared grid. Nevertheless, taking a look at the samples from the training split, this idea quickly goes away.\n\nfor train_sample_id in train_sample_ids:\n\n sample_patches_dir = patches_dir / train_sample_id\n sample_patches_paths = sorted(sample_patches_dir.iterdir())\n sample_num_patches = len(sample_patches_paths)\n\n if sample_num_patches > 0:\n if not np.sqrt(sample_num_patches).is_integer():\n print(\n f\"{train_sample_id}: Number of patches is not a perfect square (n={sample_num_patches}).\"\n )\n\n\n# #### Missing patches\n\n# +\ntoday_str = datetime.now().strftime(\"%Y%m%d\")\nresults_dir = Path(f\"../report/{today_str}/\")\nresults_dir.mkdir(exist_ok=True, parents=True)\n\nreport_dict = {\n \"sample_id\": [],\n \"mask_shape\": [],\n \"reconstructed_image_shape\": [],\n \"num_patches\": [],\n \"num_missing_patches\": [],\n \"missing_patches_idxs\": [],\n}\n\npbar = tqdm(train_sample_ids)\nfor sample_id in pbar:\n\n pbar.set_description(f\"Processing {sample_id}\")\n\n sample_patches_dir = patches_dir / sample_id\n sample_patches_paths = sorted(sample_patches_dir.iterdir())\n\n if len(sample_patches_paths) > 0:\n sorted_sample_patches_paths, missing_patches_idxs = sort_paths_from_idxs(\n sample_patches_paths\n )\n sorted_sample_patches = read_images_grid(sorted_sample_patches_paths)\n reconstructed_sample_image = np.vstack(\n [np.hstack(row) for row in sorted_sample_patches]\n ).astype(np.float32)\n\n sample_mask_path = masks_dir / f\"{sample_id}_mask.png\"\n sample_mask = read_mask(sample_mask_path)\n\n # Process the reconstructed image.\n reconstructed_sample_image = crop_black_frames_from_image(reconstructed_sample_image)\n reconstructed_sample_image = reconstructed_sample_image / 255.0\n \n # Resize mask to cropped reconstructed image.\n height, width = reconstructed_sample_image.shape[:2]\n resized_sample_mask = cv2.resize(sample_mask, (width, height))\n data_with_mask = plotting.overlay_masks_on_data(\n np.expand_dims(reconstructed_sample_image, axis=0),\n np.expand_dims(resized_sample_mask, axis=-1),\n true_mask_with_contours=False,\n ).clip(0, 1)\n\n # Save results.\n sample_results_dir = results_dir / sample_id\n sample_results_dir.mkdir(exist_ok=True)\n\n report_dict[\"sample_id\"].append(sample_id)\n report_dict[\"num_missing_patches\"].append(len(missing_patches_idxs))\n report_dict[\"missing_patches_idxs\"].append(\n \", \".join([str(i) for i in missing_patches_idxs])\n )\n report_dict[\"mask_shape\"].append(sample_mask.shape)\n report_dict[\"reconstructed_image_shape\"].append(\n reconstructed_sample_image.shape\n )\n report_dict[\"num_patches\"].append(len(sample_patches_paths))\n\n plt.figure(figsize=(20, 20))\n plt.imshow(data_with_mask[0])\n for j, i in missing_patches_idxs:\n y, x = 512 + (1024 * j), 350 + (1024 * i)\n plt.annotate(\n f\"$[{j}, {i}]$\",\n xy=(x, y),\n color=\"yellow\",\n fontsize=16,\n )\n plt.savefig(\n str(sample_results_dir / \"reconstructed_image_with_resize_mask.png\"),\n bbox_inches=\"tight\",\n )\n plt.close()\n\n else:\n\n sample_mask_path = masks_dir / f\"{sample_id}_mask.png\"\n sample_mask = read_mask(sample_mask_path)\n\n report_dict[\"sample_id\"].append(sample_id)\n report_dict[\"num_missing_patches\"].append(None)\n report_dict[\"missing_patches_idxs\"].append(None)\n report_dict[\"mask_shape\"].append(sample_mask.shape)\n report_dict[\"reconstructed_image_shape\"].append(None)\n report_dict[\"num_patches\"].append(0)\n\nreport_df = pd.DataFrame(report_dict)\nreport_df.to_excel(results_dir / \"report.xlsx\", index=False)\n\n# -\n\nreport_df\n\n\n# # Quitar TCGA-55-8207-01Z-00-DX1.2dafc442-f927-4b0d-b197-cc8c5f86d0fc\n\n\n","repo_name":"Sangohe/tcga-pathology-lung","sub_path":"notebooks/data-analysis.ipynb","file_name":"data-analysis.ipynb","file_ext":"py","file_size_in_byte":15251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"10490091818","text":"# Import required python libraries and add some formatting options\n\n# +\nfrom math import sqrt\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\nimport matplotlib.pyplot as plt\n\nfloat_formatter = lambda x: \"%.4f\" % x\nnp.set_printoptions(formatter={'float_kind':float_formatter})\n\n\n# -\n\n# Define a function that calculates optimal portfolio by minimising the volatility for a given level of risk\n\ndef optimise_portfolio(target_mu=0.045, corr_factor=1):\n \"\"\" Returns a string decribing optimial portfolio allocation\n \n target_mu: float, target portfolio return\n corr_factor: float, value to scale correlation up by, useful for q1.3\n \n \"\"\"\n \n mu = np.matrix([\n [0.02], \n [0.07], \n [0.15], \n [0.20],\n ])\n\n sigma = np.diag([\n 0.05, \n 0.12, \n 0.17, \n 0.25,\n ])\n\n correlation = np.matrix([\n [1.00, corr_factor * 0.30, corr_factor * 0.30, corr_factor * 0.30],\n [corr_factor * 0.30, 1.00, corr_factor * 0.60, corr_factor * 0.60],\n [corr_factor * 0.30, corr_factor * 0.60, 1.00, corr_factor * 0.60],\n [corr_factor * 0.30, corr_factor * 0.60, corr_factor * 0.60, 1.00],\n ])\n\n covariance = sigma @ correlation @ sigma\n\n start_weights = np.matrix([\n [0.25], \n [0.25], \n [0.25], \n [0.25],\n ])\n\n def calc_sigma(my_weights):\n return sqrt(my_weights.T @ covariance @ my_weights)\n\n r = minimize(calc_sigma, start_weights, tol=0.000000001,\n constraints=(\n {\n 'type': 'eq', \n 'fun': lambda weights: 1.0 - np.sum(weights)\n },\n {\n 'type': 'eq', \n 'fun': lambda weights: target_mu - (weights.T @ mu).item((0, 0))\n }\n ))\n \n optimal_weights = r.x\n pfo_mu = (optimal_weights.T @ mu).item((0, 0))\n pfo_risk = sqrt((optimal_weights.T @ covariance @ optimal_weights).item((0, 0)))\n \n return_value = 'Target:{}'.format(target_mu)\n return_value += ', Optimal Weights:{}'.format(optimal_weights)\n return_value += ', Mu:{:.4f}'.format(pfo_mu)\n return_value += ', SD:{:.4f}'.format(pfo_risk)\n return print(return_value)\n\n\noptimise_portfolio(0.045)\noptimise_portfolio(0.045, corr_factor=1)\noptimise_portfolio(0.045, corr_factor=1.25)\noptimise_portfolio(0.045, corr_factor=1.5)\n\n\ndef optimise_portfolio(risk_free_rate=0.005, corr_factor=1):\n\n mu = np.matrix([\n [0.02], \n [0.07], \n [0.15], \n [0.20],\n ])\n\n sigma = np.diag([\n 0.05, \n 0.12, \n 0.17, \n 0.25,\n ])\n\n correlation = np.matrix([\n [1.00, corr_factor * 0.30, corr_factor * 0.30, corr_factor * 0.30],\n [corr_factor * 0.30, 1.00, corr_factor * 0.60, corr_factor * 0.60],\n [corr_factor * 0.30, corr_factor * 0.60, 1.00, corr_factor * 0.60],\n [corr_factor * 0.30, corr_factor * 0.60, corr_factor * 0.60, 1.00],\n ])\n\n covariance = sigma @ correlation @ sigma\n\n start_weights = np.matrix([\n [0.25], \n [0.25], \n [0.25], \n [0.25],\n ])\n\n def calc_sharpe(my_weights):\n pf_ret = (my_weights.T @ mu).item(0, 0)\n excess_return = pf_ret - risk_free_rate\n pf_sd = sqrt(my_weights.T @ covariance @ my_weights)\n sharpe = excess_return / pf_sd\n return -sharpe\n\n r = minimize(calc_sharpe, start_weights, tol=0.000000001,\n constraints=(\n {\n 'type': 'eq', \n 'fun': lambda weights: 1.0 - np.sum(weights)\n },\n ))\n \n print('')\n print(r.message)\n optimal_weights = r.x\n pfo_mu = (optimal_weights.T @ mu).item((0, 0))\n pfo_excess_return = pfo_mu - risk_free_rate\n pfo_risk = sqrt((optimal_weights.T @ covariance @ optimal_weights).item((0, 0)))\n pfo_sharpe = pfo_excess_return / pfo_risk\n \n print('{:.4f} \\t& {:.4f} \\t& {:.4f} \\t& {:.4f} \\t& {:.4f} \\t& {:.4f} \\t& {:.4f} \\t& {:.4f} \\\\\\\\'.format(risk_free_rate, optimal_weights[0], optimal_weights[1], \n optimal_weights[2], optimal_weights[3], pfo_mu, pfo_risk, pfo_sharpe))\n \n return_value = ' Risk Free:{}'.format(risk_free_rate)\n return_value += '\\n Optimal Weights:{}'.format(optimal_weights)\n return_value += '\\n Mu:{:.4f}'.format(pfo_mu)\n return_value += '\\n SD:{:.4f}'.format(pfo_risk)\n return_value += '\\n Sharpe: {:.4f}'.format(pfo_sharpe)\n return print(return_value)\n\n\noptimise_portfolio(0)\noptimise_portfolio(0.0050)\noptimise_portfolio(0.0075)\noptimise_portfolio(0.0100)\noptimise_portfolio(0.0150)\noptimise_portfolio(0.0175)\n\n\n# Inverse optimisation problem where we generate weights randomly\n\ndef question_2_part_2():\n n_weights = 1500\n \n mu = np.matrix([\n [0.02], \n [0.07], \n [0.15], \n [0.20],\n ])\n \n sigma = np.diag([\n 0.05, \n 0.12, \n 0.17, \n 0.25,\n ])\n \n # draw (time_steps x n_steps) random variables\n r = np.random.randn(4, n_weights)\n print('Sample weights: \\n{}'.format(r[:,:5]))\n \n # find the sum of the four random weights\n s = np.sum(r, axis=0)\n print('Sample sum weights: \\n{}'.format(s[:5]))\n \n # normalise each weight by dividing by sum of weights to ensure sum of weights add up to 1\n random_weights = (r.T / s[:, None]).T # slice with None and combine with broadcasting\n print('Sample normalised weights: \\n{}'.format(random_weights[:,:5]))\n \n # check random weights add up to 1\n # total number of random portfolios = 1500\n # ensure that range of weight values look reasonable\n check_random_weights = pd.DataFrame(random_weights.T)\n check_random_weights['sum'] = check_random_weights.sum(axis=1)\n print('Checking random weight statistics:\\n{}'.format(check_random_weights.describe()))\n \n rand_pf_mu = random_weights.T @ mu\n print('Sample random portfolio expected returns:\\n{}'.format(rand_pf_mu[:5]))\n \n correlation = np.matrix([\n [1.00, 0.30, 0.30, 0.30],\n [0.30, 1.00, 0.60, 0.60],\n [0.30, 0.60, 1.00, 0.60],\n [0.30, 0.60, 0.60, 1.00],\n ])\n\n covariance = sigma @ correlation @ sigma\n \n a = random_weights.T @ covariance @ random_weights\n rand_pf_sigma = np.sqrt(a.diagonal().T)\n print('Sample random portfolio volatility:\\n{}'.format(rand_pf_sigma[:5]))\n \n # combine results into a dataframe so that we can more easily visualise\n df = pd.concat([\n pd.DataFrame(rand_pf_mu, columns=['pf_mu']), \n pd.DataFrame(rand_pf_sigma, columns=['pf_sigma'])\n ], axis=1)\n # display the first five elements\n print(df.head())\n \n return df.plot(x=['pf_sigma'], y=['pf_mu'], kind='scatter', \n xticks=np.arange(0, 0.25, .05), yticks=np.arange(0, 0.25, .05),\n alpha=0.2, figsize=(12, 8), title='Efficient Frontier generated by inverse optimisation'\n )\n\n\nquestion_2_part_2()\n\n# +\ncorr_bump = -0.5\n\ndef plot_for_corr_bump(corr):\n \n n_weights = 1500\n \n mu = np.matrix([\n [0.02], \n [0.07], \n [0.15], \n [0.20],\n ])\n sigma = np.diag([\n 0.05, \n 0.12, \n 0.17, \n 0.25,\n ])\n correlation = np.matrix([\n [1.00, corr, corr, corr],\n [corr, 1.00, corr, corr],\n [corr, corr, 1.00, corr],\n [corr, corr, corr, 1.00],\n ])\n \n # draw (time_steps x n_steps) random variables\n r = np.random.randn(4, n_weights)\n print('Sample weights: \\n{}'.format(r[:,:5]))\n \n # find the sum of the four random weights\n s = np.sum(r, axis=0)\n print('Sample sum weights: \\n{}'.format(s[:5]))\n \n # normalise each weight by dividing by sum of weights to ensure sum of weights add up to 1\n random_weights = (r.T / s[:, None]).T # slice with None and combine with broadcasting\n print('Sample normalised weights: \\n{}'.format(random_weights[:,:5]))\n\n covariance = sigma @ correlation @ sigma\n rand_pf_mu = random_weights.T @ mu\n temp_df = random_weights.T @ covariance @ random_weights\n rand_pf_sigma = np.sqrt(temp_df.diagonal().T)\n df = pd.concat([pd.DataFrame(rand_pf_mu, columns=['pf_mu']), pd.DataFrame(rand_pf_sigma, columns=['pf_sigma'])], axis=1)\n return df.plot(x=['pf_sigma'], y=['pf_mu'], kind='scatter', \n xticks=np.arange(0, 0.25, .05), yticks=np.arange(0, 0.25, .05),\n alpha=0.35, figsize=(12, 8), title='Average correlation = {}'.format(corr)\n )\n\n\n# -\n\nfor x in [-0.5, -0.25, 0, 0.25, 0.5, 0.75, 1]:\n plot_for_corr_bump(x);\n\n\n","repo_name":"yijxiang/quant-finance","sub_path":".ipynb_checkpoints/2019-08-29-optimal-portfolio-allocation-checkpoint.ipynb","file_name":"2019-08-29-optimal-portfolio-allocation-checkpoint.ipynb","file_ext":"py","file_size_in_byte":8653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"9480801041","text":"# +\n#importing libraries\n\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport missingno as mno\n\nimport datetime\n\nplt.style.use('fivethirtyeight')\n# -\n\n#reading the data and also the computation time\n# %time data = pd.read_csv('data-1.csv')\n\n#shape of the dataset\ndata.shape\n\n#checking the columns present in the dataframe\ndata.columns\n\n# ## Data Cleaning\n\n# +\n#checking missing values present in the data\n#with missingno checking missing values for first 40 columns in a matrix form\n\nmno.bar(data.iloc[:, :40],\n color = 'orange',\n sort = 'ascending')\nplt.title('Checking missing values for first half of the data', fontsize= 17)\nplt.show()\n\n# +\n#checking missing values with missingno for second half\n\nmno.bar(data.iloc[:, 40:],\n sort= 'ascending')\nplt.title('Checking missing values for second half of data', fontsize= 17)\nplt.show()\n# -\n\n# #### Missing Values Imputation\n\n# +\n#imputing missing values for continuous varaibles\n\ndata['ShortPassing'].fillna(data['ShortPassing'].mean(), inplace = True)\ndata['Volleys'].fillna(data['Volleys'].mean(), inplace = True)\ndata['Dribbling'].fillna(data['Dribbling'].mean(), inplace = True)\ndata['Curve'].fillna(data['Curve'].mean(), inplace = True)\ndata['FKAccuracy'].fillna(data['FKAccuracy'], inplace = True)\ndata['LongPassing'].fillna(data['LongPassing'].mean(), inplace = True)\ndata['BallControl'].fillna(data['BallControl'].mean(), inplace = True)\ndata['HeadingAccuracy'].fillna(data['HeadingAccuracy'].mean(), inplace = True)\ndata['Finishing'].fillna(data['Finishing'].mean(), inplace = True)\ndata['Crossing'].fillna(data['Crossing'].mean(), inplace = True)\n\ndata['Weight'].fillna('200lbs', inplace = True)\ndata['Contract Valid Until'].fillna(2019, inplace = True)\ndata['Height'].fillna(\"5'11\", inplace = True)\ndata['Loaned From'].fillna('None', inplace = True)\ndata['Joined'].fillna('Jul 1, 2018', inplace = True)\ndata['Jersey Number'].fillna(8, inplace = True)\ndata['Body Type'].fillna('Normal', inplace = True)\ndata['Position'].fillna('ST', inplace = True)\ndata['Club'].fillna('No Club', inplace = True)\ndata['Work Rate'].fillna('Medium/ Medium', inplace = True)\ndata['Skill Moves'].fillna(data['Skill Moves'].median(), inplace = True)\ndata['Weak Foot'].fillna(3, inplace = True)\ndata['Preferred Foot'].fillna('Right', inplace = True)\ndata['International Reputation'].fillna(1, inplace = True)\ndata['Wage'].fillna('€200K', inplace = True)\n# -\n\npd.set_option('max_rows', 100)\ndata.isnull().sum()\n\n# +\n#imputing 0 for rest of missing value\n\ndata.fillna(0, inplace= True)\n# -\n\n#check missing values if present in the dataset\ndata.isnull().sum().sum()\n\n\n# ## Feature Engineering\n\n# +\n#creating new features by aggregrating similar features\n\ndef defending(data):\n return int(round((data[['Marking', 'StandingTackle', \n 'SlidingTackle']].mean()).mean()))\n\ndef general(data):\n return int(round((data[['HeadingAccuracy', 'Dribbling', 'Curve', \n 'BallControl']].mean()).mean()))\n\ndef mental(data):\n return int(round((data[['Aggression', 'Interceptions', 'Positioning', \n 'Vision','Composure']].mean()).mean()))\n\ndef passing(data):\n return int(round((data[['Crossing', 'ShortPassing', \n 'LongPassing']].mean()).mean()))\n\ndef mobility(data):\n return int(round((data[['Acceleration', 'SprintSpeed', \n 'Agility','Reactions']].mean()).mean()))\ndef power(data):\n return int(round((data[['Balance', 'Jumping', 'Stamina', \n 'Strength']].mean()).mean()))\n\ndef rating(data):\n return int(round((data[['Potential', 'Overall']].mean()).mean()))\n\ndef shooting(data):\n return int(round((data[['Finishing', 'Volleys', 'FKAccuracy', \n 'ShotPower','LongShots', 'Penalties']].mean()).mean()))\n\n\n# +\n#adding the above new features into the data\n\ndata['Defending'] = data.apply(defending, axis = 1)\ndata['General'] = data.apply(general, axis = 1)\ndata['Mental'] = data.apply(mental, axis = 1)\ndata['Passing'] = data.apply(passing, axis = 1)\ndata['Mobility'] = data.apply(mobility, axis = 1)\ndata['Power'] = data.apply(power, axis = 1)\ndata['Rating'] = data.apply(rating, axis = 1)\ndata['Shooting'] = data.apply(shooting, axis = 1)\n\n#check the column names in the data after adding new features\ndata.columns\n# -\n\ndata.head()\n\n# ## Data Visualization\n\n# +\n#visualize the new features(skills) created\n\nplt.rcParams['figure.figsize'] = (18,12)\nplt.subplot(2, 4, 1)\nsns.distplot(data['Defending'], color= 'red')\nplt.grid()\n\nplt.subplot(2, 4, 2)\nsns.distplot(data['General'], color= 'black')\nplt.grid()\n\nplt.subplot(2, 4, 3)\nsns.distplot(data['Mental'], color= 'red')\nplt.grid()\n\nplt.subplot(2, 4, 4)\nsns.distplot(data['Passing'], color= 'black')\nplt.grid()\n\nplt.subplot(2, 4, 5)\nsns.distplot(data['Mobility'], color= 'red')\nplt.grid()\n\nplt.subplot(2, 4, 6)\nsns.distplot(data['Power'], color= 'black')\nplt.grid()\n\nplt.subplot(2, 4, 7)\nsns.distplot(data['Rating'], color= 'red')\nplt.grid()\n\nplt.subplot(2, 4, 8)\nsns.distplot(data['Shooting'], color= 'black')\nplt.grid()\n\nplt.suptitle('Score distribution for different abilities')\nplt.show()\n\n# +\n#comparison of preferred foot for players\n\nplt.rcParams['figure.figsize'] = (8,3)\nsns.countplot(data['Preferred Foot'], palette = 'pink')\nplt.title('Most preferred foot for players', fontsize= 12)\nplt.show()\n\n# +\n# plotting a pie chart to represent share of international repuatation\n\nlabels = ['1', '2', '3', '4', '5'] #data['International Reputation'].index\nsizes = data['International Reputation'].value_counts()\ncolors = plt.cm.copper(np.linspace(0, 1, 5))\nexplode = [0.1, 0.1, 0.2, 0.5, 0.9]\n\nplt.rcParams['figure.figsize'] = (9, 9)\nplt.pie(sizes, labels = labels, colors = colors, explode = explode, shadow = True,)\nplt.title('International Repuatation for the Football Players', fontsize = 20)\nplt.legend()\nplt.show()\n# -\n\n# #### Lets check players with Internation rating of 5\n\ndata[data['International Reputation'] == 5][['Name','Nationality',\n 'Overall']].sort_values(by = 'Overall',\n ascending = False).style.background_gradient(cmap = 'magma')\n\n# +\n# plotting a pie chart to represent the share of week foot players\n\nlabels = ['5', '4', '3', '2', '1'] \nsize = data['Weak Foot'].value_counts()\ncolors = plt.cm.Wistia(np.linspace(0, 1, 5))\nexplode = [0, 0, 0, 0, 0.1]\n\nplt.pie(size, labels = labels, colors = colors, explode = explode, shadow = True, startangle = 90)\nplt.title('Distribution of Week Foot among Players', fontsize = 25)\nplt.legend()\nplt.show()\n\n# +\n# different positions acquired by the players \n\nplt.figure(figsize = (13, 15))\nax = sns.countplot(y = 'Position', data = data, palette = 'bone')\nax.set_ylabel(ylabel = 'Different Positions in Football', fontsize = 16)\nax.set_xlabel(xlabel = 'Count of Players', fontsize = 16)\nax.set_title(label = 'Comparison of Positions and Players', fontsize = 20)\nplt.show()\n\n\n# +\n# defining a function for cleaning the Weight data\n\ndef extract_value_from(value):\n out = value.replace('lbs', '')\n return float(out)\n\n# applying the function to weight column\n#data['value'] = data['value'].apply(lambda x: extract_value_from(x))\ndata['Weight'] = data['Weight'].apply(lambda x : extract_value_from(x))\n\n# plotting the distribution of weight of the players\nsns.distplot(data['Weight'], color = 'black')\nplt.title(\"Distribution of Players Weight\", fontsize = 15)\nplt.show()\n\n\n# +\n# defining a function for cleaning the wage column\n\ndef extract_value_from(column):\n out = column.replace('€', '')\n if 'M' in out:\n out = float(out.replace('M', ''))*1000000\n elif 'K' in column:\n out = float(out.replace('K', ''))*1000\n return float(out)\n\n\n# +\n# applying the function to the wage and value column\ndata['Value'] = data['Value'].apply(lambda x: extract_value_from(x))\ndata['Wage'] = data['Wage'].apply(lambda x: extract_value_from(x))\n\n# visualizing the data\nplt.rcParams['figure.figsize'] = (16, 5)\nplt.subplot(1, 2, 1)\nsns.distplot(data['Value'], color = 'violet')\nplt.title('Distribution of Value of the Players', fontsize = 15)\n\nplt.subplot(1, 2, 2)\nsns.distplot(data['Wage'], color = 'purple')\nplt.title('Distribution of Wages of the Players', fontsize = 15)\nplt.show()\n\n# +\n# Skill Moves of Players\n\nplt.figure(figsize = (10, 6))\nax = sns.countplot(x = 'Skill Moves', data = data, palette = 'pastel')\nax.set_title(label = 'Count of players on Basis of their skill moves', fontsize = 20)\nax.set_xlabel(xlabel = 'Number of Skill Moves', fontsize = 16)\nax.set_ylabel(ylabel = 'Count', fontsize = 16)\nplt.show()\n\n# +\n# To show Different Work rate of the players participating in the FIFA 2019\n\nplt.figure(figsize = (15, 5))\nplt.style.use('fivethirtyeight')\n\nsns.countplot(x = 'Work Rate', data = data, palette = 'hls')\nplt.title('Different work rates of the Players Participating in the FIFA 2019', fontsize = 20)\nplt.xlabel('Work rates associated with the players', fontsize = 16)\nplt.ylabel('count of Players', fontsize = 16)\nplt.xticks(rotation = 90)\nplt.show()\n\n# +\n#to show potential and overall scored of players\n\n\nplt.figure(figsize=(16, 4))\nplt.style.use('seaborn-paper')\n\nplt.subplot(1, 2, 1)\nx = data.Potential\nax = sns.distplot(x, bins = 58, kde = False, color = 'y')\nax.set_xlabel(xlabel = \"Player's Potential Scores\", fontsize = 10)\nax.set_ylabel(ylabel = 'Number of players', fontsize = 10)\nax.set_title(label = 'Histogram of players Potential Scores', fontsize = 15)\n\nplt.subplot(1, 2, 2)\ny = data.Overall\nax = sns.distplot(y, bins = 58, kde = False, color = 'y')\nax.set_xlabel(xlabel = \"Player's Overall Scores\", fontsize = 10)\nax.set_ylabel(ylabel = 'Number of players', fontsize = 10)\nax.set_title(label = 'Histogram of players Overall Scores', fontsize = 15)\nplt.show()\n\n# +\n#Overall scores of players with age distribution along with preferred foot\n\nplt.rcParams['figure.figsize'] = (20, 7)\nplt.style.use('seaborn-dark-palette')\n\nsns.boxplot(data['Overall'], data['Age'], hue = data['Preferred Foot'], palette = 'Greys')\nplt.title('Comparison of Overall Scores and age wrt Preferred foot', fontsize = 20)\nplt.show()\n\n# +\n#selecting the countries with highest number of players to compare their overall scores\n\ndata['Nationality'].value_counts().head(10).plot(kind = 'pie', cmap = 'inferno',\n startangle = 90, explode = [0, 0, 0, 0, 0, 0, 0, 0, 0.1, 0])\nplt.title('Countries having Highest Number of players', fontsize = 15)\nplt.axis('off')\nplt.show()\n\n# +\n#distribution of player weight's among the countries\n\nsome_countries = ('England', 'Germany', 'Spain', 'Argentina', 'France', 'Brazil', 'Italy', 'Columbia')\ndata_countries = data.loc[data['Nationality'].isin(some_countries) & data['Weight']]\n\ndata_countries\n# -\n\ndata_countries.columns\n\nplt.rcParams['figure.figsize'] = (15, 7)\nax = sns.violinplot(x = data_countries['Nationality'], y = data_countries['Weight'], palette = 'Reds')\nax.set_xlabel(xlabel = 'Countries', fontsize = 9)\nax.set_ylabel(ylabel = 'Weight in lbs', fontsize = 9)\nax.set_title(label = 'Distribution of Weight of players from different countries', fontsize = 20)\nplt.show()\n\n# +\n#Overall scores for Nations players\n\n\nsome_countries = ('England', 'Germany', 'Spain', 'Argentina', 'France', 'Brazil', 'Italy', 'Columbia')\ndata_countries = data.loc[data['Nationality'].isin(some_countries) & data['Overall']]\n\ndata_countries\n\n# +\n\nplt.rcParams['figure.figsize'] = (15, 7)\nax = sns.barplot(x = data_countries['Nationality'], y = data_countries['Overall'], palette = 'spring')\nax.set_xlabel(xlabel = 'Countries', fontsize = 9)\nax.set_ylabel(ylabel = 'Overall Scores', fontsize = 9)\nax.set_title(label = 'Distribution of overall scores of players from different countries', fontsize = 20)\nplt.show()\n\n# +\n#Nation's players and wages\n\nsome_countries = ('England', 'Germany', 'Spain', 'Argentina', 'France', 'Brazil', 'Italy', 'Columbia')\ndata_countries = data.loc[data['Nationality'].isin(some_countries) & data['Wage']]\n\nplt.rcParams['figure.figsize'] = (15, 7)\nax = sns.barplot(x = data_countries['Nationality'], y = data_countries['Wage'], palette = 'Purples')\nax.set_xlabel(xlabel = 'Countries', fontsize = 9)\nax.set_ylabel(ylabel = 'Wage', fontsize = 9)\nax.set_title(label = 'Distribution of Wages of players from different countries', fontsize = 15)\nplt.grid()\nplt.show()\n\n# +\n#Every player's reputation representing the Countries\n\n#Every Nations' Player and their International Reputation\n\nsome_countries = ('England', 'Germany', 'Spain', 'Argentina', 'France', 'Brazil', 'Italy', 'Columbia')\ndata_countries = data.loc[data['Nationality'].isin(some_countries) & data['International Reputation']]\n\nplt.rcParams['figure.figsize'] = (15, 7)\nax = sns.boxenplot(x = data_countries['Nationality'], y = data_countries['International Reputation'], palette = 'autumn')\nax.set_xlabel(xlabel = 'Countries', fontsize = 9)\nax.set_ylabel(ylabel = 'Distribution of reputation', fontsize = 9)\nax.set_title(label = 'Distribution of International Repuatation of players from different countries', fontsize = 15)\nplt.grid()\nplt.show()\n\n\n# +\n#Players reports function\n\ndef report(player):\n return data[data['Name'] == player][['Nationality','Club',\n 'Overall','Potential',\n 'Contract Valid Until','Wage',\n 'International Reputation']].reset_index(drop = True).T\n\n\n# -\n\nreport('L. Messi')\n\nreport('Cristiano Ronaldo')\n\nreport('Neymar Jr')\n","repo_name":"brianlobo394/FIFA18Players_Analysis","sub_path":"FIFA18_EDA.ipynb","file_name":"FIFA18_EDA.ipynb","file_ext":"py","file_size_in_byte":13639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"21941201151","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ndf=pd.read_csv(\"/home/jayesh/Desktop/cardio_train.csv\") \ndf.head()\nnp.isnan(df).sum()\nprint(type(df))\ndf.columns \n\nduplicates = len(df) - len(df.drop(['id'],axis=1).drop_duplicates())\ndf.drop(['id'],axis=1,inplace=True)\ndf.drop_duplicates(inplace=True)\nprint(f'{duplicates} duplicate records dropped.')\n\ndf.describe().T.round(2)\n\ntmp = pd.crosstab(df['cholesterol'],df['cardio'],normalize='index')\ntmp.reset_index()\ntmp.columns = ['not diseased','diseased']\nfig, ax = plt.subplots(1,1)\nsns.countplot(df['cholesterol'],order=list(tmp.index), ax=ax)\nplot2 = ax.twinx()\nsns.pointplot(tmp.index,tmp['diseased'],order=list(tmp.index),ax=plot2)\nfor patch in ax.patches:\n height = patch.get_height()\n ax.text(patch.get_x()+patch.get_width()/2,height,'{:.2f}{}'.format(height/len(df['cholesterol'])*100,'%'))\nplt.show()\n\nmp = pd.crosstab(df['gluc'],df['cardio'],normalize='index')\ntmp.reset_index()\ntmp.columns = ['not diseased','diseased']\nfig, ax = plt.subplots(1,1)\nsns.countplot(df['gluc'],order=list(tmp.index), ax=ax)\nplot2 = ax.twinx()\nsns.pointplot(tmp.index,tmp['diseased'],order=list(tmp.index),ax=plot2)\nfor patch in ax.patches:\n height = patch.get_height()\n ax.text(patch.get_x()+patch.get_width()/2,height,'{:.2f}{}'.format(height/len(df['gluc'])*100,'%'))\nplt.show()\n\n# +\nfig, (ax1,ax2) = plt.subplots(1,2, figsize=(20,10))\nsns.distplot(df['age'][df['cardio']==0], ax = ax1, color='green')\nsns.distplot(df['age'][df['cardio']==1], ax = ax1,color='coral')\nax1.set_title('Age Distribution')\nax1.legend()\n\nsns.distplot(df['age'][(df['gender']==1) & (df['cardio']==1)],ax = ax2,color='pink')\nsns.distplot(df['age'][(df['gender']==2) & (df['cardio']==1)],ax = ax2,color='blue')\nax2.set_title('Disease count distribution by gender, aged below 54.')\nplt.show()\n\n# +\nfig, (ax1) = plt.subplots(1,1, figsize=(10,10))\nsns.boxenplot(df['cardio'],(df['height']*0.0328084),ax=ax1)\nax1.set_title('Height / Diseased')\nplt.show()\n\n\n# -\n\nfrom pandas_profiling import ProfileReport\nprof = ProfileReport(df)\nprof.to_file(output_file='output.html')\n\ndf.corr()\n##\nX =df.drop('cardio', axis = 1) \ny=df['cardio']\n\n# +\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y,\n train_size=0.7, \n random_state=42,\n stratify=y)\n# -\n\nfrom sklearn.tree import DecisionTreeClassifier\nclf = DecisionTreeClassifier(criterion = 'entropy', min_samples_split=50)\n\nclf.fit(X_train, y_train)\n\ny_pred = clf.predict(X_test)\n\nfrom sklearn.metrics import accuracy_score\nprint('Accuracy Score on train data: ', accuracy_score(y_true=y_train, y_pred=clf.predict(X_train)))\nprint('Accuracy Score on test data: ', accuracy_score(y_true=y_test, y_pred=y_pred))\n\n#after feature engineering\n \n\n# decision tree\nfrom sklearn.tree import DecisionTreeClassifier\nclf = DecisionTreeClassifier(criterion = 'entropy')\n\nclf.fit(X_train, y_train)\n\ny_pred = clf.predict(X_test)\n\nfrom sklearn.metrics import accuracy_score\nprint('Accuracy Score on train data: ', accuracy_score(y_true=y_train, y_pred=clf.predict(X_train)))\nprint('Accuracy Score on test data: ', accuracy_score(y_true=y_test, y_pred=y_pred))\n\n# +\nfrom xgboost import XGBClassifier\nxgb = XGBClassifier()\nxgb.fit(X_train,y_train)\nprint(f'Train Score: {xgb.score(X,y)}')\n\ny_pred = xgb.predict(X_test)\nprint(f'Test Accuracy: {accuracy_score(y_test,y_pred)}')\n# -\n\n\n","repo_name":"belsarej/cardiovascular-Diesease-Predcition","sub_path":"Cardiovascular disease prediction.ipynb","file_name":"Cardiovascular disease prediction.ipynb","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"22631985252","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"qET6IUyof18T\"\nimport yfinance as yf\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"snxmCYs9gAPV\" outputId=\"655d082a-f535-4a5f-a996-892fadea0007\"\ndatos=yf.download(\"^GSPC\",period=\"1y\",interval=\"1h\")\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"zbpIMZ8bgAxu\" outputId=\"aaf2c989-258a-495e-f932-86d8e9829dbb\"\n# Cargar los datos del archivo CSV\ndata = datos\n\n# Calcular los retornos diarios\ndata[\"Returns\"] = data[\"Close\"].pct_change()\n\n# Función para calcular el rendimiento acumulado\ndef calcular_rendimiento(periodo_corta, periodo_larga):\n # Calcular medias móviles\n data[\"SMA_Corta\"] = data[\"Close\"].rolling(window=periodo_corta).mean()\n data[\"SMA_Larga\"] = data[\"Close\"].rolling(window=periodo_larga).mean()\n\n # Generar señales de entrada y salida\n data[\"Signal\"] = 0\n data.loc[data[\"SMA_Corta\"] > data[\"SMA_Larga\"], \"Signal\"] = 1\n data.loc[data[\"SMA_Corta\"] < data[\"SMA_Larga\"], \"Signal\"] = -1\n\n # Calcular retornos acumulados\n data[\"Strategy_Returns\"] = data[\"Signal\"].shift() * data[\"Returns\"]\n data[\"Cumulative_Returns\"] = (1 + data[\"Strategy_Returns\"]).cumprod()\n\n # Retornar rendimiento acumulado final\n return data[\"Cumulative_Returns\"].iloc[-1]\n\n# Parámetros para la optimización\nperiodos_corta = range(10, 101, 10) # Rango de períodos para media móvil corta\nperiodos_larga = range(50, 251, 25) # Rango de períodos para media móvil larga\n\nmejor_rendimiento = float(\"-inf\")\nmejores_periodos = ()\n\n# Bucle para encontrar los períodos que maximizan el rendimiento\nfor periodo_corta in periodos_corta:\n for periodo_larga in periodos_larga:\n rendimiento = calcular_rendimiento(periodo_corta, periodo_larga)\n if rendimiento > mejor_rendimiento:\n mejor_rendimiento = rendimiento\n mejores_periodos = (periodo_corta, periodo_larga)\n\n# Imprimir los mejores períodos encontrados\nprint(\"Mejores períodos: Media Móvil Corta =\", mejores_periodos[0], \", Media Móvil Larga =\", mejores_periodos[1])\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 564} id=\"Fd6g0SUsgUEK\" outputId=\"49328ec0-629e-491f-b7ad-99912f0d2bf0\"\n\n\ndata=datos\n\n# Paso 1: Obtener los datos históricos del S&P 500 del último año\ndata = datos # Reemplaza 'datos_sp500.csv' con el nombre de tu archivo de datos\n\n# Paso 2: Análisis de datos y generación de señales\ndata['SMA40'] = data['Close'].rolling(window=40).mean() # Media móvil de 50 días\ndata['SMA150'] = data['Close'].rolling(window=150).mean() # Media móvil de 200 días\n\n# Generar señales de compra y venta basadas en cruces de medias móviles\ndata['Signal'] = np.where(data['SMA40'] > data['SMA150'], 1, -1)\n\n# Paso 3: Definir reglas de entrada y salida\ndata['Position'] = data['Signal'].shift() # Posición al día siguiente para evitar operar en el mismo día de la señal\n\n# Paso 4: Backtesting y evaluación de la estrategia\ndata['Returns'] = np.log(data['Close'] / data['Close'].shift()) # Retornos logarítmicos diarios\ndata['StrategyReturns'] = data['Position'] * data['Returns']\ncumulative_returns = np.exp(data['StrategyReturns'].cumsum()) # Rendimiento acumulado de la estrategia\n\n# Paso 5: Visualización de los resultados\nplt.figure(figsize=(10, 6))\nplt.plot(cumulative_returns)\nplt.title('Rendimiento acumulado de la estrategia')\nplt.xlabel('Fecha')\nplt.ylabel('Rendimiento acumulado')\nplt.grid(True)\nplt.show()\n\n# + id=\"bKRTBlvPgfWU\"\n\n","repo_name":"karloxkronfeld/Finanzas","sub_path":"FomulaMEDIAS.ipynb","file_name":"FomulaMEDIAS.ipynb","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"44"} +{"seq_id":"25742386408","text":"# # importing libraries\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# # loading dataset\n\ndata = pd.read_csv(\"C:\\\\Users\\\\pc\\\\Desktop\\\\csv datasets\\\\survey lung cancer.csv\")\n\ndata.head(10)\n\nsome_data = data.iloc[:,[10,11,12,13,14,15]]\n\ncancer_smoking = data.iloc[:,[2,15]]\n\n# # smoking count\n\ndata.iloc[:,2]\nsmoking = [i.all() for i in data.iloc[:,2].values==2 if i == True]\nnonsmoking = [i.all() for i in data.iloc[:,2].values == 2 if i==False ]\n\nprint(len(smoking))\nprint(len(nonsmoking))\n\n# # visualization smoking\n\nplt.bar((smoking),len(smoking),width = 0.1)\nplt.bar((nonsmoking),len(nonsmoking),color = 'r',width = 0.1)\nplt.title(\"no. of smokers\")\nplt.xlabel(\"smoking or not\")\nplt.ylabel(\"no. of cases\")\nplt.grid()\n\ndata['LUNG_CANCER'].value_counts()\n\n# # smoking vs cancer\n\ncancer_smoking\n\nplt.hist(data['AGE'],bins=20)\n\nsmoking_cancer = []\nsmoking_nocancer = []\nfor i in range(0,309):\n if data.loc[i, \"SMOKING\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n smoking_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"SMOKING\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='NO':\n smoking_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nnosmoking_cancer = []\nnosmoking_nocancer = []\nfor i in range(0,309):\n if data.loc[i,\"SMOKING\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n nosmoking_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"SMOKING\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='NO':\n nosmoking_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nlen(nosmoking_cancer)\n\nlen(nosmoking_nocancer)\n\nlen(smoking_cancer)\n\nlen(smoking_nocancer)\n\n# # visualization smoking vs cancer\n\nplt.bar(smoking_cancer,len(smoking_cancer),width = 0.1)\nplt.bar(smoking_nocancer,len(smoking_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"smoking kills?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of smoking\")\n\nplt.bar(nosmoking_cancer,len(nosmoking_cancer),width = 0.1)\nplt.bar(nosmoking_nocancer,len(nosmoking_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"smoking kills?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of non-smoking\")\n\n# conclusion: the no. of cases where the patient who did not smoke but still had cancer was reletively lower where the smoker had cancer,still the the diffrence is less, it's safe to say someting other than smoking is largly contributing in cause of cancer, also the diffrence in smoker and non smoker who did nothave cancer is also where low. \n\n# # symptom yellow fingers and what it tells\n\nyellowfingers_cancer = []\nyellowfingers_nocancer = []\nfor i in range(0,309):\n if data.loc[i, \"YELLOW_FINGERS\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n yellowfingers_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"YELLOW_FINGERS\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='NO':\n yellowfingers_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nnoyellowfingers_cancer = []\nnoyellowfingers_nocancer = []\nfor i in range(0,309):\n if data.loc[i, \"YELLOW_FINGERS\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n noyellowfingers_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"YELLOW_FINGERS\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='NO':\n noyellowfingers_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nlen(yellowfingers_nocancer)\n\nlen(yellowfingers_cancer)\n\nlen(noyellowfingers_nocancer)\n\nlen(noyellowfingers_cancer)\n\n# # visualising yellow finger symptom vs cancer\n\nplt.bar(yellowfingers_cancer,len(yellowfingers_cancer),width = 0.1)\nplt.bar(yellowfingers_nocancer,len(yellowfingers_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"what does symptoms suggest?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of yellowfingers\")\n\nplt.bar(noyellowfingers_cancer,len(noyellowfingers_cancer),width = 0.1)\nplt.bar(noyellowfingers_nocancer,len(noyellowfingers_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"what does symptoms suggest?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of non-yellowfingers\")\n\n# conclusion: there are over 160 cases where the patient having yellow fingers symptom was diagnosed cancer positive,where as just over 10 cases where he was diagnosed otherwise,and there are over 20 cases where the patient with no yellowfinger symptoms was diagonosed cancer negative, yellow fingers can be seen as positive symptom \n\n# # alcohol vs cancer\n\nalcohol_cancer = []\nalcohol_nocancer = []\nfor i in range(0,309):\n if data.loc[i,\"ALCOHOL CONSUMING\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n alcohol_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"ALCOHOL CONSUMING\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='NO':\n alcohol_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nlen(alcohol_cancer)\n\nlen(alcohol_nocancer)\n\nnoalcohol_cancer = []\nnoalcohol_nocancer = []\nfor i in range(0,309):\n if data.loc[i,\"ALCOHOL CONSUMING\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n noalcohol_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"ALCOHOL CONSUMING\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='NO':\n noalcohol_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nlen(noalcohol_cancer)\n\nlen(noalcohol_nocancer)\n\n# # visualization alcohol vs cancer\n\nplt.bar(alcohol_cancer,len(alcohol_cancer),width = 0.1)\nplt.bar(alcohol_nocancer,len(alcohol_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"drinking kills?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of drinking\")\n\nplt.bar(noalcohol_cancer,len(noalcohol_cancer),width = 0.1)\nplt.bar(noalcohol_nocancer,len(noalcohol_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"drinking kills?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of non-drinking\")\n\n# conclusion: here we see there are over 160 cases where the patient was drinking and was diaganosed cancer positive, but just about 10 cases when the patient was drinking but was diaganosed cancer negative,we can say drinking is more likely to cause lung cancer as compared to smoking, the above statement is supported by the second graph where we can see it has the highest no. of cancer negative patient who did not do alcohol\n\nsome_data.head(10)\n\n# # symptom coughing vs lung cancer\n\ncoughing_cancer = []\ncoughing_nocancer= []\nfor i in range(0,309):\n if data.loc[i,\"COUGHING\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n coughing_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"COUGHING\"]==2 and data.loc[i,\"LUNG_CANCER\"]== 'NO':\n coughing_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nnocoughing_cancer = []\nnocoughing_nocancer= []\nfor i in range(0,309):\n if data.loc[i,\"COUGHING\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n nocoughing_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"COUGHING\"]==1 and data.loc[i,\"LUNG_CANCER\"]== 'NO':\n nocoughing_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nprint(f'coughing and cancer= {len(coughing_cancer)}')\nprint(f'coughing but no cancer= {len(coughing_nocancer)}')\nprint(f'no coughing but cancer= {len(nocoughing_cancer)}')\nprint(f'no coughing and no cancer= {len(nocoughing_nocancer)}')\n\n# # visualizing coughing vs cancer\n\nplt.bar(coughing_cancer,len(coughing_cancer),width = 0.1)\nplt.bar(coughing_nocancer,len(coughing_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"what does symptoms suggest?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of coughing\")\n\nplt.bar(nocoughing_cancer,len(nocoughing_cancer),width = 0.1)\nplt.bar(nocoughing_nocancer,len(nocoughing_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"what does symptoms suggest?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of not coughing\")\n\n# conclusion: there are over 160 cases where the person diagnosed cancer positive was suffering from coughing where as only 10 cases where did not have cancer when he showed coughing as symptom, whereas there are about 30 cases where person who did not show coughing as symptom was also diagnosed cancer negative.so we can say coughing can be assumed evident symptom for cancer. \n\n# # swallowing difficulties vs lung cancer\n\nswallowingdificulties_cancer = []\nswallowingdificulties_nocancer= []\nfor i in range(0,309):\n if data.loc[i,\"SWALLOWING DIFFICULTY\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n swallowingdificulties_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"SWALLOWING DIFFICULTY\"]==2 and data.loc[i,\"LUNG_CANCER\"]== 'NO':\n swallowingdificulties_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nnoswallowingdificulties_cancer = []\nnoswallowingdificulties_nocancer= []\nfor i in range(0,309):\n if data.loc[i,\"SWALLOWING DIFFICULTY\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n noswallowingdificulties_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"SWALLOWING DIFFICULTY\"]==1 and data.loc[i,\"LUNG_CANCER\"]== 'NO':\n noswallowingdificulties_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nprint(f'swallowing dificulties and cancer= {len(swallowingdificulties_cancer)}')\nprint(f'swallowing dificulties but no cancer= {len(swallowingdificulties_nocancer)}')\nprint(f'no swallowing dificulties but cancer= {len(noswallowingdificulties_cancer)}')\nprint(f'no sawllowing dificulties and no cancer= {len(noswallowingdificulties_nocancer)}')\n\n# # visualizing swallowing dificulties vs lung cancer\n\nplt.bar(swallowingdificulties_cancer,len(swallowingdificulties_cancer),width = 0.1)\nplt.bar(swallowingdificulties_nocancer,len(swallowingdificulties_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"what does symptoms suggest?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of swallowing dificulties\")\n\nplt.bar(noswallowingdificulties_cancer,len(noswallowingdificulties_cancer),width = 0.1)\nplt.bar(noswallowingdificulties_nocancer,len(noswallowingdificulties_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"what does symptoms suggest?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of no swallowing dificulties\")\n\n# conclusion:from the graph we can see there are about 140 cases where the patient diagnosed cancer positive had swallowing dificulties as symptom and only 5 cases where the patient having difficulty swallowing was diagnosed cancer negative\n# and also there are more than 30 cases where patient did not have difficulty swallowing and was also diagnosed cancer negative\n# so with we can say difficulties swallowing is one of the major symptoms of lung cancer\n\n# # chest pain vs lung cancer\n\nsome_data.head(10)\n\nchestpain_cancer = []\nchestpain_nocancer= []\nfor i in range(0,309):\n if data.loc[i,\"CHEST PAIN\"]==2 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n chestpain_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"CHEST PAIN\"]==2 and data.loc[i,\"LUNG_CANCER\"]== 'NO':\n chestpain_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nnochestpain_cancer = []\nnochestpain_nocancer= []\nfor i in range(0,309):\n if data.loc[i,\"CHEST PAIN\"]==1 and data.loc[i,\"LUNG_CANCER\"]=='YES':\n nochestpain_cancer.append(data.loc[i,\"LUNG_CANCER\"])\n elif data.loc[i,\"CHEST PAIN\"]==1 and data.loc[i,\"LUNG_CANCER\"]== 'NO':\n nochestpain_nocancer.append(data.loc[i,\"LUNG_CANCER\"])\n\nprint(f'chest pain and cancer= {len(chestpain_cancer)}')\nprint(f'chest pain but no cancer= {len(chestpain_nocancer)}')\nprint(f'no chest pain but cancer= {len(nochestpain_cancer)}')\nprint(f'no chest pain and no cancer= {len(nochestpain_nocancer)}')\n\n# # visualizing chest pain vs lung cancer\n\nplt.bar(chestpain_cancer,len(chestpain_cancer),width = 0.1)\nplt.bar(chestpain_nocancer,len(chestpain_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"what does symptoms suggest?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of chest pain\")\n\nplt.bar(nochestpain_cancer,len(nochestpain_cancer),width = 0.1)\nplt.bar(nochestpain_nocancer,len(nochestpain_nocancer),width = 0.1,color = 'r')\nplt.grid()\nplt.title(\"what does symptoms suggest?\")\nplt.xlabel(\"lung_cancer\")\nplt.ylabel(\"cases of no chest pain\")\n\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\ndata['GENDER'] = le.fit_transform(data['GENDER'])\ndata['LUNG_CANCER'] = le.fit_transform(data['LUNG_CANCER'])\nx = data.iloc[:,:-1].values\ny= data.iloc[:,-1].values\nfrom sklearn.preprocessing import StandardScaler\nsc =StandardScaler()\nx = sc.fit_transform(x)\n\ndata.head(10)\n\n# # using logistic regression\n\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_actual=train_test_split(x,y,test_size=0.3,random_state=0)\nfrom sklearn.linear_model import LogisticRegression\nlr = LogisticRegression()\nlr.fit(x_train,y_train)\n\nlogistic_pred = lr.predict(x_test)\nfrom sklearn.metrics import confusion_matrix,accuracy_score\nprint(f'confusion matrix: {confusion_matrix(logistic_pred,y_actual)}')\nprint(f'accuracy score: {accuracy_score(logistic_pred,y_actual)}')\n\n# # naive bayes algo.\n\nfrom sklearn.naive_bayes import GaussianNB\ngnb = GaussianNB()\ngnb.fit(x_train,y_train)\n\nnaivebayes_pred= gnb.predict(x_test)\nprint(f'confusion matrix: {confusion_matrix(naivebayes_pred,y_actual)}')\nprint(f'accuracy score: {accuracy_score(naivebayes_pred,y_actual)}')\n\n# # kernel svm\n\nfrom sklearn.svm import SVC\nsvm = SVC(kernel='rbf')\nsvm.fit(x_train,y_train)\n\nsvc_pred = svm.predict(x_test)\nprint(f'confusion matrix: {confusion_matrix(svc_pred,y_actual)}')\nprint(f'accuracy score: {accuracy_score(svc_pred,y_actual)}')\n\nsvm2 = SVC(kernel='linear')\nsvm2.fit(x_train,y_train)\nsvc_linear_pred = svm2.predict(x_test)\nprint(f'confusion matrix: {confusion_matrix(svc_linear_pred,y_actual)}')\nprint(f'accuracy score: {accuracy_score(svc_linear_pred,y_actual)}')\n\n# # k nearest neighbors\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknc = KNeighborsClassifier(n_neighbors=5)\nknc.fit(x_train,y_train)\nknc_pred = knc.predict(x_test)\nprint(f'confusion matrix: {confusion_matrix(knc_pred,y_actual)}')\nprint(f'accuracy score: {accuracy_score(knc_pred,y_actual)}')\n\n# # decision tree clasifier\n\nfrom sklearn.tree import DecisionTreeClassifier\ndtc = DecisionTreeClassifier(criterion='entropy')\ndtc.fit(x_train,y_train)\ndtc_pred = dtc.predict(x_test)\nprint(f'confusion matrix: {confusion_matrix(dtc_pred,y_actual)}')\nprint(f'accuracy score: {accuracy_score(dtc_pred,y_actual)}')\n\n# # random forest classifier\n\nfrom sklearn.ensemble import RandomForestClassifier\nrfc = RandomForestClassifier(n_estimators=5,criterion='entropy')\nrfc.fit(x_train,y_train)\nrfc_pred = rfc.predict(x_test)\nprint(f'confusion matrix: {confusion_matrix(rfc_pred,y_actual)}')\nprint(f'accuracy score: {accuracy_score(rfc_pred,y_actual)}')\n\nlogistic_acc = accuracy_score(logistic_pred,y_actual)\nkernel_pred_linear_acc = accuracy_score(svc_linear_pred,y_actual)\nnaive_acc = accuracy_score(naivebayes_pred,y_actual)\nknearest_acc = accuracy_score(knc_pred,y_actual)\ndecision_acc = accuracy_score(dtc_pred,y_actual)\nrandom_forest_acc = accuracy_score(rfc_pred,y_actual)\n\n# +\nmodels = ['Logistic Regression', 'KNN','naive bayes', 'SVC', 'Decision Tree', 'Random Forest']\nscores = [logistic_acc,knearest_acc,naive_acc,kernel_pred_linear_acc,decision_acc,random_forest_acc]\n\nmodels = pd.DataFrame({'Model' : models, 'Score' : scores})\n\n\nmodels.sort_values(by = 'Score', ascending = False)\n# -\n\n# conclusion: the random forest classification model performed best with 90% accuracy \n","repo_name":"ANUBHAVGithub-code/lung_cancer_prediction_with_EDA_and_ML_models","sub_path":"lung_cancer_prediction_with_EDA_and_ML_models.ipynb","file_name":"lung_cancer_prediction_with_EDA_and_ML_models.ipynb","file_ext":"py","file_size_in_byte":15107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"19675664381","text":"# %matplotlib inline\n\nfrom IPython.html.widgets import interact\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef plot_sine(n,a):\n x = np.arange(0, 20, 0.1);\n y = a*np.sin(x/n)\n plt.plot(x, y)\n\n\n\ninteract(plot_sine, n=(1,10, 0.1), a=(0.2,2, 0.1))\n\n# +\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom IPython.html.widgets import interact, FloatSlider, RadioButtons\n\n# mpl.rcParams['figure.max_open_warning'] = 1\n\ndef plot(amplitude, color):\n\n fig, ax = plt.subplots(figsize=(10, 10),\n subplot_kw={'axisbg':'#EEEEEE',\n 'axisbelow':True})\n\n ax.grid(color='w', linewidth=2, linestyle='solid')\n x = np.linspace(0, 10, 1000)\n ax.plot(x, amplitude * np.sin(x), color=color,\n lw=5, alpha=0.4)\n ax.set_xlim(0, 10)\n ax.set_ylim(-1.1, 1.1)\n return fig\n\nres = interact(\n plot,\n amplitude=FloatSlider(min=0.1, max=1.0, step=0.1, value=0.2),\n color=RadioButtons(options=['blue', 'green', 'red'])\n)\n","repo_name":"ricleal/PythonCode","sub_path":"Widgets/sin2.ipynb","file_name":"sin2.ipynb","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"73683520119","text":"# # Analyzing Fandango's movie ratings\n#\n# We will look at the Fandango's movie website to see if their rating system is suspicious, as a previous analysis (made by Walter Hickey) revealed that their ratings were inflated.\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# %matplotlib inline\n\n# ## Load up files\n#\n# Loading up the two datasets that we will use, an old one with the data before Hickey's analysis, and a newer one with data from after.\n\nold = pd.read_csv('https://raw.githubusercontent.com/fivethirtyeight/data/master/fandango/fandango_score_comparison.csv')\nold.info()\n\nnew = pd.read_csv('https://github.com/mircealex/Movie_ratings_2016_17/raw/master/movie_ratings_16_17.csv')\nnew.info()\n\n# Let's isolate the variables of interest for our analysis:\n\n# +\nfan_old = old[['FILM', 'Fandango_Stars', 'Fandango_Ratingvalue', 'Fandango_votes',\n 'Fandango_Difference']].copy()\nfan_new = new[['movie', 'year', 'fandango']].copy()\n\nfan_old.head(3)\n# -\n\nfan_new.head()\n\n# Our goal is to determine whether there has been any change in Fandango's rating system after Hickey's analysis. The population of interest for our analysis is made of all the movie ratings stored on Fandango's website, regardless of the releasing year.\n#\n# Because we want to find out whether the parameters of this population changed after Hickey's analysis, we're interested in sampling the population at two different periods in time — previous and after Hickey's analysis — so we can compare the two states.\n#\n# The data we're working with was sampled at the moments we want: one sample was taken previous to the analysis, and the other after the analysis. We want to describe the population, so we need to make sure that the samples are representative, otherwise we should expect a large sampling error and, ultimately, wrong conclusions.\n#\n# From Hickey's article and from the README.md of the data set's repository, we can see that he used the following sampling criteria:\n#\n# The movie must have had at least 30 fan ratings on Fandango's website at the time of sampling (Aug. 24, 2015).\n# The movie must have had tickets on sale in 2015.\n# The sampling was clearly not random because not every movie had the same chance to be included in the sample — some movies didn't have a chance at all (like those having under 30 fan ratings or those without tickets on sale in 2015). It's questionable whether this sample is representative of the entire population we're interested to describe. It seems more likely that it isn't, mostly because this sample is subject to temporal trends — e.g. movies in 2015 might have been outstandingly good or bad compared to other years.\n#\n# The sampling conditions for our other sample were (as it can be read in the README.md of the data set's repository):\n#\n# The movie must have been released in 2016 or later.\n# The movie must have had a considerable number of votes and reviews (unclear how many from the README.md or from the data).\n# This second sample is also subject to temporal trends and it's unlikely to be representative of our population of interest.\n#\n# Both these authors had certain research questions in mind when they sampled the data, and they used a set of criteria to get a sample that would fit their questions. Their sampling method is called purposive sampling (or judgmental/selective/subjective sampling). While these samples were good enough for their research, they don't seem too useful for us.\n\n# ## Changing the Goal of our Analysis\n#\n# At this point, we can either collect new data or change our the goal of our analysis. We choose the latter and place some limitations on our initial goal.\n#\n# Instead of trying to determine whether there has been any change in Fandango's rating system after Hickey's analysis, our new goal is to determine whether there's any difference between Fandango's ratings for popular movies in 2015 and Fandango's ratings for popular movies in 2016. This new goal should also be a fairly good proxy for our initial goal.\n#\n# Let's first decide which are the popular movies (we need a criterion), and then see how many of these are available in our two datasets.\n\nfan_old['Fandango_votes'].describe()\n\n# The \"old\" database definitely has a lot of popular movies. The other dataset does not have information on the number of votes. How do we check if the movies in this dataset are popular? One way is to quickly sample a few movies from the dataset and then check manually.\n\nfan_new.sample(10)\n\n# Now we need to isolate the movies from 2015 for the old database, and movies of 2016 for the new database.\n\nfan_old.head()\n\nfan_old['Year'] = fan_old['FILM'].str.extract(r'(?!\\()(\\d{4})(?=\\))')\nfan_old.head()\n\nfan_old['Year'].value_counts()\n\nfan_old_2015 = fan_old[fan_old['Year']=='2015'].copy()\nprint(fan_old_2015.info())\nfan_old_2015.head()\n\nfan_new.head()\n\nfan_new_2016 = fan_new[fan_new['year']==2016].copy()\nfan_new_2016.head()\n\n# Our goal is to determine whether there's any difference between Fandango's ratings for popular movies in 2015 and Fandango's ratings for popular movies in 2016.\n#\n# There are many ways we can go about with our analysis, but let's start simple with making a high-level comparison between the shapes of the distributions of movie ratings for both samples.\n\nplt.style.use('fivethirtyeight')\nfan_old_2015['Fandango_Stars'].plot.kde(label='2015')\nfan_new_2016['fandango'].plot.kde(label='2016')\nplt.legend()\nplt.xlabel('Movie Rating (0-5)', size=12)\nplt.xlim(0,5)\nplt.xticks([0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0])\nplt.title('Fandango Movie Ratings for 2015 and 2016', size=20, y=1.07)\nplt.show()\n\n# Two aspects are striking on the figure above:\n#\n# Both distributions are strongly left skewed.\n# The 2016 distribution is slightly shifted to the left relative to the 2015 distribution.\n# The left skew suggests that movies on Fandango are given mostly high and very high fan ratings. Coupled with the fact that Fandango sells tickets, the high ratings are a bit dubious. It'd be really interesting to investigate this further — ideally in a separate project, since this is quite irrelevant for the current goal of our analysis.\n#\n# The slight left shift of the 2016 distribution is very interesting for our analysis. It shows that ratings were slightly lower in 2016 compared to 2015. This suggests that there was a difference indeed between Fandango's ratings for popular movies in 2015 and Fandango's ratings for popular movies in 2016. We can also see the direction of the difference: the ratings in 2016 were slightly lower compared to 2015.\n\nfan_old_2015['Fandango_Stars'].value_counts(normalize=True).sort_index()*100\n\nfan_new_2016['fandango'].value_counts(normalize=True).sort_index()*100\n\n# Even looking at the frequency tables of ratings in the two datasets, it seems pretty clear that the old data has lots of movies (~38%) with a rating of 4.5. The new dataset is slightly more normally distributed, with 40% of movies having a 4.0 rating.\n#\n# Now we'll compare the two datasets for a few summary statistics.\n\nprint('Means of old and new datasets\\' ratings')\nprint('old:',fan_old_2015['Fandango_Stars'].mean(),\" new:\",fan_new_2016['fandango'].mean())\n\nprint('Medians of old and new datasets\\' ratings')\nprint('old:',fan_old_2015['Fandango_Stars'].median(),\" new:\",fan_new_2016['fandango'].median())\n\nprint('Modes of old and new datasets\\' ratings')\nprint('old:',fan_old_2015['Fandango_Stars'].mode()[0],\" new:\",fan_new_2016['fandango'].mode()[0])\n\n# +\nmean_2015 = fan_old_2015['Fandango_Stars'].mean()\nmean_2016 = fan_new_2016['fandango'].mean()\n\nmedian_2015 = fan_old_2015['Fandango_Stars'].median()\nmedian_2016 = fan_new_2016['fandango'].median()\n\nmode_2015 = fan_old_2015['Fandango_Stars'].mode()[0] # the output of Series.mode() is a bit uncommon\nmode_2016 = fan_new_2016['fandango'].mode()[0]\n\nsummary = pd.DataFrame()\nsummary['2015'] = [mean_2015, median_2015, mode_2015]\nsummary['2016'] = [mean_2016, median_2016, mode_2016]\nsummary.index = ['mean', 'median', 'mode']\nround(summary,2)\n\n# +\nplt.style.use('fivethirtyeight')\nsummary['2015'].plot.bar(color = '#0066FF', align = 'center', label = '2015', width = .25)\nsummary['2016'].plot.bar(color = '#CC0000', align = 'edge', label = '2016', width = .25,\n rot = 0, figsize = (8,5))\n\nplt.title('Comparing summary statistics: 2015 vs 2016', y = 1.07)\nplt.ylim(0,5.5)\nplt.yticks(np.arange(0,5.1,.5))\nplt.ylabel('Stars')\nplt.legend(framealpha = 0, loc = 'upper center')\nplt.show()\n# -\n\n# ## Conclusion\n#\n# Our analysis showed that there's indeed a slight difference between Fandango's ratings for popular movies in 2015 and Fandango's ratings for popular movies in 2016. We also determined that, on average, popular movies released in 2016 were rated lower on Fandango than popular movies released in 2015.\n#\n# We cannot be completely sure what caused the change, but the chances are very high that it was caused by Fandango fixing the biased rating system after Hickey's analysis.\n\n\n","repo_name":"mahikappa/fandango_bias","sub_path":"Fandango movie bias.ipynb","file_name":"Fandango movie bias.ipynb","file_ext":"py","file_size_in_byte":9079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"27300980479","text":"# # Continuous gradients in colorectal tumor\n\n# +\nimport sys\nimport os\nfrom collections import defaultdict\nimport pandas as pd\nimport scanpy as sc\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom glmpca import glmpca\nfrom itertools import combinations\nimport torch\n\nimport sys\nfrom importlib import reload\n\nimport gaston\nfrom gaston import neural_net,cluster_plotting, dp_related, segmented_fit, restrict_spots\nfrom gaston import binning_and_plotting, isodepth_scaling, run_slurm_scripts, parse_adata\nfrom gaston import spatial_gene_classification, plot_cell_types, filter_genes, process_NN_output\n\nimport seaborn as sns\nimport math\n# -\n\n# ## Step 1: Pre-processing\n#\n# Here, GASTON takes as input the output of Space Ranger output. In particular the following files are needed: `filtered_feature_bc_matrix.h5` and `spatial/tissue_positions_list.csv`.\n# Optionally, if one wants to use RGB values as output features, the file `spatial/tissue_hires_image.png`.\n\n# !mkdir -p tumor_tutorial_outputs\n\n# +\ndata_folder='colorectal_tumor_data/'\nuse_RGB=True # set to False if you do not want to use RGB as features\n\ncounts_mat, coords_mat, gene_labels, rgb_mean=parse_adata.get_gaston_input_adata(data_folder, get_rgb=use_RGB, spot_umi_threshold=50)\n\n# save matrices\nnp.save('colorectal_tumor_data/counts_mat.npy', counts_mat)\nnp.save('colorectal_tumor_data/coords_mat.npy', coords_mat)\nnp.save('colorectal_tumor_data/gene_labels.npy', gene_labels)\n# -\n\n# Compute GLM-PCs (we use 5)\n\n# +\nnum_dims=5\npenalty=20 # may need to increase if this is too small\n\nglmpca_res=glmpca.glmpca(counts_mat.T, num_dims, fam=\"poi\", penalty=penalty, verbose=True)\nA = glmpca_res['factors'] # should be of size N x num_dims, where each column is a PC\n\nif use_RGB:\n A=np.hstack((A,rgb_mean)) # attach to RGB mean\nnp.save('colorectal_tumor_data/glmpca.npy', A)\n# -\n\n# visualize top GLM-PCs and RGB mean\nrotated_coords=dp_related.rotate_by_theta(coords_mat, -np.pi/2)\nR=2\nC=4\nfig,axs=plt.subplots(R,C,figsize=(20,10))\nfor r in range(R):\n for c in range(C):\n i=r*C+c\n axs[r,c].scatter(rotated_coords[:,0], rotated_coords[:,1], c=A[:,i],cmap='Reds',s=3)\n if i < num_dims:\n axs[r,c].set_title(f'GLM-PC{i}')\n else:\n axs[r,c].set_title('RGB'[i-num_dims])\n\n# ## Step 2: Train GASTON neural network\n\n# We include how to train the neural network with two options: (1) a command line script and (2) in a notebook. We typically train the neural network 30 different times, each with a different seed, and we use the NN with lowest loss. \n\n# ### Option 1: Slurm (Recommended)\n\n# For option (1), the code below creates 30 different Slurm jobs, one for each initialization. To train the NN for a single initialization run the following command:\n#\n# `gaston -i /path/to/coords.npy -o /path/to/glmpca.npy -d /path/to/output_dir -e 10000 -c 500 -p 20 20 -x 20 20 -z adam -s SEED`\n#\n# for a given `SEED` value (integer)\n#\n# NOTE: please wait for models to finish training before running below code. You can check on their status by running `squeue -u uchitra` (replacing `uchitra` with your username)\n\n# +\n# LOAD DATA generated above\n# path_to_glmpca='colorectal_tumor_data/glmpca.npy'\n# path_to_coords='colorectal_tumor_data/coords_mat.npy'\n\n# To approximately recreate paper figures, use same GLM-PCs from paper \npath_to_glmpca='colorectal_tumor_data/glmpca_from_paper.npy'\npath_to_coords='colorectal_tumor_data/coords_from_paper.npy'\n\n# GASTON NN parameters\nisodepth_arch=[20,20] # architecture (two hidden layers of size 20) for isodepth neural network d(x,y)\nexpression_arch=[20,20] # architecture (two hidden layers of size 20) for 1-D expression function\nepochs = 10000 # number of epochs to train NN\ncheckpoint = 500 # save model after number of epochs = multiple of checkpoint\noptimizer = \"adam\"\nnum_restarts=30 # number of initializations\n\noutput_dir='colorectal_tumor_tutorial_outputs' # folder to save model runs\n\n# REPLACE with your own conda environment name and path\nconda_environment='gaston-package'\npath_to_conda_folder='/n/fs/ragr-data/users/uchitra/miniconda3/bin/activate'\n\nrun_slurm_scripts.train_NN_parallel(path_to_coords, path_to_glmpca, isodepth_arch, expression_arch, \n output_dir, conda_environment, path_to_conda_folder,\n epochs=epochs, checkpoint=checkpoint, \n num_seeds=num_restarts)\n# -\n\n# ### Option 2: train in notebook\n\n# +\npath_to_glmpca='colorectal_tumor_data/glmpca_from_paper.npy'\npath_to_coords='colorectal_tumor_data/coords_from_paper.npy'\n\nA=np.load(path_to_glmpca) # GLM-PCA results used in manuscript\nS=np.load(path_to_coords)\n\n# z-score normalize S and A\nS_torch, A_torch = neural_net.load_rescale_input_data(S,A)\n\n# +\n######################################\n# NEURAL NET PARAMETERS (USER CAN CHANGE)\n# architectures are encoded as list, eg [20,20] means two hidden layers of size 20 hidden neurons\nisodepth_arch=[20,20] # architecture for isodepth neural network d(x,y) : R^2 -> R \nexpression_fn_arch=[20,20] # architecture for 1-D expression function h(w) : R -> R^G\n\nnum_epochs = 10000 # number of epochs to train NN (NOTE: it is sometimes beneficial to train longer)\ncheckpoint = 500 # save model after number of epochs = multiple of checkpoint\nout_dir='colorectal_tumor_tutorial_outputs' # folder to save model runs\noptimizer = \"adam\"\nnum_restarts=30\n\n######################################\n\nseed_list=range(num_restarts)\nfor seed in seed_list:\n print(f'training neural network for seed {seed}')\n out_dir_seed=f\"{out_dir}/rep{seed}\"\n os.makedirs(out_dir_seed, exist_ok=True)\n mod, loss_list = neural_net.train(S_torch, A_torch,\n S_hidden_list=isodepth_arch, A_hidden_list=expression_fn_arch, \n epochs=num_epochs, checkpoint=checkpoint, \n save_dir=out_dir_seed, optim=optimizer, seed=seed, save_final=True)\n# -\n\n# ## Step 3: Process neural network output\n\n# We use the model trained for the paper for reproducibility. If you use the model trained above, then figures will closely match the manuscript --- but not exactly match --- due to PyTorch non-determinism in seeding (see https://github.com/pytorch/pytorch/issues/7068 ). \n\n# +\n# gaston_model, A, S= process_NN_output.process_files('colorectal_tumor_tutorial_outputs') # model trained above\ngaston_model, A, S= process_NN_output.process_files('colorectal_tumor_data/reproduce_tumor') # MATCH PAPER FIGURES\n\n# May need to re-load counts_mat, coords_mat, and gene_labels\ncounts_mat=np.load('colorectal_tumor_data/counts_mat.npy',allow_pickle=True)\ncoords_mat=np.load('colorectal_tumor_data/coords_mat.npy',allow_pickle=True)\ngene_labels=np.load('colorectal_tumor_data/gene_labels.npy',allow_pickle=True)\n# -\n\n# Compute isodepth and GASTON domains \n\n# +\nnum_layers=5\ngaston_isodepth, gaston_labels=dp_related.get_isodepth_labels(gaston_model,A,S,num_layers)\n\n# DATASET-SPECIFIC: so domains are ordered oligodendrocyte to molecular, with increasing isodepth\ngaston_isodepth= np.max(gaston_isodepth) -1 * gaston_isodepth\ngaston_labels=(num_layers-1)-gaston_labels\n# -\n\n# Plot topographic map: isodepth and spatial gradients\n\n# +\nshow_streamlines=True\nrotate = np.radians(-90) # rotate coordinates by -90\narrowsize=2\n\ncluster_plotting.plot_isodepth(gaston_isodepth, S, gaston_model, figsize=(7,6), streamlines=show_streamlines, \n rotate=rotate,arrowsize=arrowsize)\n# -\n\n# Plot GASTON domains\n\ndomain_colors=colors=['plum', 'cadetblue', '#F3D9DC','dodgerblue', '#F44E3F']\ncluster_plotting.plot_clusters(gaston_labels, S, figsize=(6,6), \n colors=domain_colors, s=20, lgd=False, \n show_boundary=True, gaston_isodepth=gaston_isodepth, boundary_lw=5, rotate=rotate)\n\n# ## Continuous gradient analysis\n\n# ### Restrict to domains 1, 2 of tumor\n\n# To isolate the tumor section, we restrict to spots with isodepth lying in a given range. The range of isodepth values will need to be tuned depending on the specific application.\n#\n# In some cases, the tissue geometry cannot be represented with a single isodepth. In this case, we recommend first subsetting your tissue to the specific region of interest (eg from ScanPy clustering), and then running GASTON\n\n# +\n# This is the range we used for reproducing figure papers.\nisodepth_min=4.5\nisodepth_max=6.8\n\ncluster_plotting.plot_clusters_restrict(gaston_labels, S, gaston_isodepth, \n isodepth_min=isodepth_min, isodepth_max=isodepth_max, figsize=(6,6), \n colors=domain_colors, s=20, lgd=False, rotate=rotate)\n# -\n\n# Once you have a range that looks reasonable, then we restrict the isodepth, domain labels, coords matrix, and counts matrix to only be for the green spots\n\n# +\n# Optional: adjust isodepth for physical distance\nadjust_physical=True\nscale_factor=100 # since distance of 1 = 100 microns for 10x Visium\n\n# Optional: plot isodepth for green spots\nplot_isodepth=True\n\n# plotting parameters\nshow_streamlines=True\nrotate=np.radians(-90)\narrowsize=1\n\n\ncounts_mat_restrict, coords_mat_restrict, gaston_isodepth_restrict, gaston_labels_restrict=restrict_spots.restrict_spots(\n counts_mat, coords_mat, S, gaston_isodepth, gaston_labels, \n isodepth_min=isodepth_min, isodepth_max=isodepth_max, \n adjust_physical=adjust_physical, scale_factor=scale_factor,\n plot_isodepth=plot_isodepth, show_streamlines=show_streamlines, \n gaston_model=gaston_model, rotate=rotate, figsize=(6,3), \n arrowsize=arrowsize)\n\n# -\n\n# ### Compute piecewise linear fits\n\n# We restrict to genes with at least 1000 total UMIs, that are not mitochondrial/ribosomal\n\numi_thresh = 1000\nidx_kept, gene_labels_idx=filter_genes.filter_genes(counts_mat, gene_labels, \n umi_threshold=umi_thresh, \n exclude_prefix=['MT-', 'RPL', 'RPS'])\n\n# Compute piecewise linear fit over restricted spots from above\n\n# compute piecewise linear fit for restricted spots\npw_fit_dict=segmented_fit.pw_linear_fit(counts_mat_restrict, gaston_labels_restrict, gaston_isodepth_restrict,\n None, [], idx_kept=idx_kept, umi_threshold=umi_thresh, isodepth_mult_factor=0.01,)\n# for plotting\nbinning_output=binning_and_plotting.bin_data(counts_mat2, gaston_labels2, gaston_isodepth2, \n None, gene_labels, idx_kept=idx_kept, num_bins=15, umi_threshold=umi_thresh)\n\n# Find discontinuous and continuous genes\n\n# +\ndomain_colors=['dodgerblue', '#F44E3F']\n\ndiscont_genes_layer=spatial_gene_classification.get_discont_genes(pw_fit_dict, binning_output,q=0.95)\ncont_genes_layer=spatial_gene_classification.get_cont_genes(pw_fit_dict, binning_output,q=0.8)\n# -\n\n# Plot gene COX7B from manuscript. This is a Type I gene, with only intratumoral variation as shown below (continuous gradient only in domain 1, ie tumor)\n\n# +\ngene_name='COX7B'\nprint(f'gene {gene_name}: discontinuous jump after domain(s) {discont_genes_layer[gene_name]}') \nprint(f'gene {gene_name}: continuous gradient in domain(s) {cont_genes_layer[gene_name]}')\n\n# display log CPM (if you want to do CP500, set offset=500)\noffset=10**6\n\nbinning_and_plotting.plot_gene_pwlinear(gene_name, pw_fit_dict, gaston_labels2, gaston_isodepth2, \n binning_output, cell_type_list=None, pt_size=50, colors=domain_colors, \n linear_fit=True, ticksize=15, figsize=(4,2.5), offset=offset, lw=3,\n domain_boundary_plotting=True)\n# -\n\n# Plot gene SCD from manuscript. This is a Type I gene, with intrastromal and intratumoral variation (continuous gradient in domains 0, 1) but no discontinuity\n\n# +\ngene_name='SCD'\nprint(f'gene {gene_name}: discontinuous after domain(s) {discont_genes_layer[gene_name]}') \nprint(f'gene {gene_name}: continuous in domain(s) {cont_genes_layer[gene_name]}')\n\n# display log CPM (if you want to do CP500, set offset=500)\noffset=10**6\n\nbinning_and_plotting.plot_gene_pwlinear(gene_name, pw_fit_dict, gaston_labels2, gaston_isodepth2, \n binning_output, cell_type_list=None, pt_size=50, colors=domain_colors, \n linear_fit=True, ticksize=15, figsize=(4,2.5), offset=offset, lw=3,\n domain_boundary_plotting=True)\n# -\n\n# Plot gene ACTA2 from manuscript. This is a Type II gene, with both intrastromal variation (gradient in domain 0) and discontinuity\n\n# +\ngene_name='ACTA2'\nprint(f'gene {gene_name}: discontinuous after domain(s) {discont_genes_layer[gene_name]}') \nprint(f'gene {gene_name}: continuous in domain(s) {cont_genes_layer[gene_name]}')\n\n# display log CPM (if you want to do CP500, set offset=500)\noffset=10**6\n\nbinning_and_plotting.plot_gene_pwlinear(gene_name, pw_fit_dict, gaston_labels2, gaston_isodepth2, \n binning_output, cell_type_list=None, pt_size=50, colors=domain_colors, \n linear_fit=True, ticksize=15, figsize=(4,2.5), offset=offset, lw=3,\n domain_boundary_plotting=True)\nplt.ylim((3,5.6))\n# -\n\n# Plot gene TAGLN from manuscript. This is a Type II gene, with both intrastromal variation (gradient in domain 0) and discontinuity\n\n# +\ngene_name='TAGLN'\nprint(f'gene {gene_name}: discontinuous after domain(s) {discont_genes_layer[gene_name]}') \nprint(f'gene {gene_name}: continuous in domain(s) {cont_genes_layer[gene_name]}')\n\n# display log CPM (if you want to do CP500, set offset=500)\noffset=10**6\n\nbinning_and_plotting.plot_gene_pwlinear(gene_name, pw_fit_dict, gaston_labels2, gaston_isodepth2, \n binning_output, cell_type_list=None, pt_size=50, colors=domain_colors, \n linear_fit=True, ticksize=15, figsize=(4,2.5), offset=offset, lw=3,\n domain_boundary_plotting=True)\nplt.ylim((3,6.2))\n# -\n\n# Plot gene COL1A2 from manuscript. This is a Type II gene, with intrastromal/intratumoral variation and discontinuity\n\n# +\ngene_name='COL1A2'\nprint(f'gene {gene_name}: discontinuous after domain(s) {discont_genes_layer[gene_name]}') \nprint(f'gene {gene_name}: continuous in domain(s) {cont_genes_layer[gene_name]}')\n\n# display log CPM (if you want to do CP500, set offset=500)\noffset=10**6\n\nbinning_and_plotting.plot_gene_pwlinear(gene_name, pw_fit_dict, gaston_labels2, gaston_isodepth2, \n binning_output, cell_type_list=None, pt_size=50, colors=domain_colors, \n linear_fit=True, ticksize=15, figsize=(4,2.5), offset=offset, lw=3,\n domain_boundary_plotting=True)\nplt.ylim((4,6.5))\n# -\n\n# Plot gene THBS1 from manuscript. This is a Type III gene, with intrastromal variation\n\n# +\ngene_name='THBS1'\nprint(f'gene {gene_name}: discontinuous after domain(s) {discont_genes_layer[gene_name]}') \nprint(f'gene {gene_name}: continuous in domain(s) {cont_genes_layer[gene_name]}')\n\n# display log CPM (if you want to do CP500, set offset=500)\noffset=10**6\n\nbinning_and_plotting.plot_gene_pwlinear(gene_name, pw_fit_dict, gaston_labels2, gaston_isodepth2, \n binning_output, cell_type_list=None, pt_size=50, colors=domain_colors, \n linear_fit=True, ticksize=15, figsize=(4,2.5), offset=offset, lw=3,\n domain_boundary_plotting=True)\nplt.ylim((3,6))\n# -\n\n\n","repo_name":"raphael-group/GASTON","sub_path":"docs/notebooks/tutorials/tumor_tutorial.ipynb","file_name":"tumor_tutorial.ipynb","file_ext":"py","file_size_in_byte":16035,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"15810890271","text":"# + id=\"jRi3-5Kd8pkv\" colab_type=\"code\" outputId=\"d1a53b11-0722-4a05-c4b0-d5476dae8f6f\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 423}\n#SuperVised Learning\n #1. Classification\n #2. Regression\nimport pandas as pd\niris = pd.read_csv('Iris.csv')\niris\n\n# + id=\"t2C3FLiSBzXt\" colab_type=\"code\" outputId=\"138b114e-5484-4411-894a-23985018087b\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 147}\niris.isnull().sum()\n\n# + id=\"ycB7U_PcAeNT\" colab_type=\"code\" outputId=\"76a79ce0-5811-4890-8f9b-680b3e3e09f2\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36}\niris['Species'].unique()\n\n# + id=\"2Woi1S2UBniw\" colab_type=\"code\" colab={}\n#Encoding of labels\nY = iris['Species'].map({'Iris-setosa':0, \n 'Iris-versicolor':1, \n 'Iris-virginica':2 })\n\n# + id=\"2gqFSL5ECY2L\" colab_type=\"code\" outputId=\"8814b5d8-383c-4ef4-d808-91ca78170ae3\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 423}\n#Features or X or independent variables\nX = iris.drop(['Id','Species'],axis=1) #axis=1 as we are selecting columns\nX\n\n# + id=\"mlm57mguDKsq\" colab_type=\"code\" colab={}\n#Train your model\nfrom sklearn.neighbors import KNeighborsClassifier\nkmodel = KNeighborsClassifier(n_neighbors=3)\n\n# + id=\"xta_XP2QDd9R\" colab_type=\"code\" colab={}\n#Validate your model\n#what is the accuracy of your model ?\n#Training data set\n#Validation data set/ testing data set\n#xtrain-120 , xtest-30\n#ytrain-120 , ytest-30\nfrom sklearn.model_selection import train_test_split\nxtrain,xtest,ytrain,ytest = train_test_split(X,Y,test_size=0.50)\n\n# + id=\"XhzBTWiJL151\" colab_type=\"code\" outputId=\"d4a35682-edf3-45c2-eb69-3bf890eeeb8f\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 73}\nkmodel.fit(xtrain,ytrain)\n\n# + id=\"6bxLcWwoL8Jm\" colab_type=\"code\" outputId=\"a2d70df3-434f-4554-fc55-baecf36c47fa\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 91}\nypred = kmodel.predict(xtest)\nypred\n\n# + id=\"F8H3aKkHLYlT\" colab_type=\"code\" outputId=\"ef2ad73a-cb86-4797-c2be-bb975391f839\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36}\n(ytest == ypred).sum()/len(xtest)\n\n# + id=\"GCICnl6IMqTB\" colab_type=\"code\" outputId=\"fa3a1a97-a86c-4ff1-d327-d944a7713500\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36}\nkmodel.score(xtest,ytest)\n\n# + id=\"TM-tc1VTDa-Q\" colab_type=\"code\" outputId=\"dd28750d-717d-42fc-e4e3-a255de8f4399\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36}\n#Predict the output\n#.predict()\nkmodel.predict([[3.2,2.1,8.9,6.8],[2.1,3.2,3.3,2.1]])\n\n# + id=\"EXWEx7sUJdDb\" colab_type=\"code\" outputId=\"0d6669a1-c5b4-425d-d3a3-dafba85633e5\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36}\n#How to decide the value of k\n# How to tune a a parameter in training\nprint('hello')\n\n# + id=\"GIn3gsb9N4p_\" colab_type=\"code\" outputId=\"1b09dc88-860f-4d84-8d3d-fafaf657657d\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36}\nlen(xtrain)\n\n# + id=\"zrSslmlnPwN7\" colab_type=\"code\" colab={}\n#Parameter tuning , k\n#only be decided by error monitoring\naccuracy = []\nfor i in range(1,10):\n km = KNeighborsClassifier(n_neighbors=i)\n km.fit(xtrain,ytrain)\n s = km.score(xtest,ytest)\n accuracy.append(s)\n\n# + id=\"kTRgaHi4P6vL\" colab_type=\"code\" outputId=\"c2aca6a2-2341-45ab-bccb-6cc37a5bcf1d\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265}\naccuracy\nimport numpy as np\na=np.arange(1,10)\nb=accuracy\nimport matplotlib.pyplot as plt\nplt.plot(a,b)\nplt.show()\n\n# + id=\"CpnTZBIZRo09\" colab_type=\"code\" colab={}\n#High Accuracy\n#4 - Features - sl,sw,pl,pw\n#any 2 feature\nx1 = X['SepalLengthCm']\nx2 = X['SepalWidthCm']\nx3 = X['PetalLengthCm']\nx4 = X['PetalWidthCm']\n\n# + id=\"2TvGImWGT-Do\" colab_type=\"code\" outputId=\"810d91f0-654b-4ec5-a25b-cc0a2709de75\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 239}\nY\n\n# + id=\"xVtqTobCT_PT\" colab_type=\"code\" outputId=\"26193bb2-9e1b-4747-ef51-7caeb9e6077c\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 268}\nplt.scatter(x1,x2,c=Y)\nplt.show()\n\n# + id=\"2Vl-JnIBUHcT\" colab_type=\"code\" outputId=\"1ece32f4-0365-47ac-a19a-e0f72a6879a5\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265}\nplt.scatter(x3,x4,c=Y)\nplt.show()\n\n# + id=\"xzCae-mNU9_Q\" colab_type=\"code\" outputId=\"2d67f9c3-83a3-44ef-b862-638a3ba6efc8\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265}\nplt.scatter(x1,x3,c=Y)\nplt.show()\n\n# + id=\"lbyNE9NWVbYf\" colab_type=\"code\" colab={}\nX['label'] = Y\n\n# + id=\"TYiN6Q2SWg_s\" colab_type=\"code\" outputId=\"d584cc75-a483-458e-e076-9152fc23fea9\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 423}\nX\n\n# + id=\"uap8qU9LWpbC\" colab_type=\"code\" outputId=\"a15ff43a-cfe2-4e90-97a9-00a975ecf98b\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206}\nX.corr()\n\n# + id=\"xOF8ylegWtNg\" colab_type=\"code\" outputId=\"1fcdc00c-9ca4-42bf-f4b9-e2a3c70aa4d0\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36}\nkmodel.predict([[3.2,1.2,0.9,8.9],\n [3.2,1.2,0.9,0.9]])\n\n# + id=\"RFd8npeiaazc\" colab_type=\"code\" colab={}\nname = np.array([['setosa'],\n ['versicolor'],\n ['virginica']])\n\n# + id=\"lze8uRCravxl\" colab_type=\"code\" outputId=\"b8517074-3118-4b92-9513-23432d9c7c33\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 54}\nname[kmodel.predict([[3.2,1.2,0.9,8.9],[3.2,1.2,0.9,0.9]])]\n\n# + id=\"IQ5ynvWva1tq\" colab_type=\"code\" colab={}\n\n","repo_name":"arnav8/Innovians-Tech","sub_path":"Classification.ipynb","file_name":"Classification.ipynb","file_ext":"py","file_size_in_byte":5354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"40"} +{"seq_id":"41308203138","text":"import elasticsearch\nfrom elasticsearch import Elasticsearch \n\nimport tweepy\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nimport time\nimport json\n\nc_key = ''\nsecret_c_key = ''\naccess_token = ''\nsecret_access_token = ''\n\nimport logging\nlogging.getLogger(\"elasticsearch\").setLevel(logging.CRITICAL)\nlogging.basicConfig(level=logging.CRITICAL)\n\nes = Elasticsearch(HOST=\"http://localhost\", PORT=9200) \nelast = Elasticsearch() \n\n\n# +\nclass Listener(StreamListener):\n def __init__(self, number):\n self.counter = 0\n self.number = number\n\n def on_data(self, data):\n dict_data = json.loads(data)\n print (dict_data[\"text\"])\n elast.index(index=\"twitter\",\n doc_type=\"stream\",\n body={\"author\": dict_data[\"user\"][\"screen_name\"],\n \"date\": dict_data[\"created_at\"],\n \"message\": dict_data[\"text\"]})\n self.counter +=1\n if self.counter == self.number:\n return False\n \n return True\n \n def on_error(self, status):\n print (status)\n \nif __name__ == '__main__':\n\n Tweet_Listening = Listener(number = 15) \n Auth = OAuthHandler(c_key, secret_c_key)\n Auth.set_access_token(access_token, secret_access_token)\n Streaming = Stream(Auth, Tweet_Listening)\n Streaming.filter(track=['pizza', 'hamburger'])\n# -\n\n\n\n\n","repo_name":"leopards17/MiniProj3","sub_path":"MiniProj3-Copy1.ipynb","file_name":"MiniProj3-Copy1.ipynb","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"12613386724","text":"import pandas as pd\n\ndf = pd.DataFrame({\n 'Color': ['Red','Blue', 'Green', 'Green', 'Red', 'Blue']\n })\n\ndf\n\nfrom sklearn.preprocessing import LabelEncoder\n\nlabel_encoder = LabelEncoder()\n\nlabel_encoded = pd.DataFrame(label_encoder.fit_transform(df[['Color']]), columns=[['Encoded_Color']])\n\nlabel_encoded\n\npd.concat((df,label_encoded),axis=1)\n","repo_name":"AbhishekWaghchaure/PW_Skills-Data-Science-Masters-course-complete-","sub_path":"March_21_LabelEncoder.ipynb","file_name":"March_21_LabelEncoder.ipynb","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"7037043743","text":"# # Outlier Detection of 4 Digit MWC 4 Players using Tournament Scores using Box-Cox Transformation and Average Percentile Model\n\n# ## Introduction\n#\n# This notebook is the explanation and experimentation on an Alternative of Local Outlier Factor with a simpler model, which is an Average Percentile Model.\n\n# ## Logit Transformation\n\n# **Logit Transformation** is a terminology to transform the score which are in range $[0, 1000000]$ into $(-\\infty, \\infty)$ using the formula\n\n# $$\n# \\text{logit}(x) = \\log(\\frac{x}{1 - x})\n# $$\n\n# Where\n# $$\n# x = \\frac{\\text{score}}{1000000}\n# $$\n\n# This will also theoretically widen the gap between small difference of scores when the scores are higher. For example the difference between $\\text{logit}(0.99) - \\text{logit}(0.985)$ is less than $\\text{logit}(0.995) - \\text{logit}(0.99)$. Which matches the environment in the osu!mania tournament scene since the chance that the score gaps are low in earlier game is higher than the late game.\n\n# ## Box-Cox Transformation\n\n# **Box-Cox Transformation** can be written as\n\n# $$\n# \\text{boxcox}(x) = \\begin{cases}\n# \\frac{x^\\lambda - 1}{\\lambda} & \\lambda \\neq 0\\\\\n# \\log(x) & \\lambda = 0\n# \\end{cases}\n# $$\n\n# Theoretically, the following transformation will make the data more Normally Distributed. We can find the $\\lambda$ using **Maximum Likelihood** which will try to find the $\\lambda$ that maximize how \"Normally Distributed\" the data is.\n#\n# More information and experimentations can be found in [boxcox.ipynb](https://github.com/HowToProgramming/4dm4analysis/blob/main/boxcox.ipynb)\n\n# ## Parametric Average Percentile Model\n\n# **Parametric Average Percentile Model** is based on the idea of how to measure the proportion of the population that a given player has surprassed. The data in this case is multi-dimensional data, that means there are multiple maps in the calculation process of this model. First we standardize the data of each map, then we calculate the **Cumulative Distribution Function** of **Normal Distribution** or any given parametric distribution, we will call that a percentile. After that we average the percentile and get the final result of a given player.\n\n# ### Adjustments\n\n# #### Applying Box-Cox Transformation\n\n# As mentioned in the previous section about Box-Cox Transformation, we transform the Logit-Transformed data using Box-Cox transformation in order to use them in the **Parametric Average Percentile Model**. This will maximize the efficiency of the model, however there is a case where $\\lambda < 0$ which we should aware of because the higher the score, the lower the transformed value is, we then use another adjustment\n\n# $$\n# \\text{sign}(\\lambda) = \\begin{cases}\n# 1 & \\lambda \\geq 0\\\\\n# -1 & \\text{otherwise}\n# \\end{cases}\n# $$\n\n# We multiply them with our standardized value and then use that value to calculate the **Cumulative Distribution Function** in order to catch that issue.\n\n# #### Applying Maps Played into the consideration\n\n# After we got the output from our Model, we then find another factor which the model didn't catch which is the \"Maps Played\". The important behaviour of outperformed players is the fact that they usually are main players of most of the maps. So we try to include this feature by multiplying the outlier value that we got from model with the log of maps played. Which is the following formula:\n\n# $$\n# \\text{Adjusted Outlier Score} = \\text{Outlier Value from Avg. Percentile} \\cdot \\log(\\# \\text{Maps Played} + 1)\n# $$\n\n# We then use this value to detect the outlier or outperformed players.\n\n# #### Applying Participation Rate into Consideration\n\n# Another way to evaluate whether a player should be skillbanned would be to consider the participation of a given player in a team. This can be thought as how much a player \"sandbags\" the team. The way to get the participation rate is to divide a player's score with a maximum team score in a given map.\n\n# But how do we prioritize which map should be considered more or less ? This is an important process in skillbanning because if we equally weighted every map, the model might not be reliable due to early game being equal to late game, so we do the following procedure:\n\n# - We obtain the participation rate using the method from a recent paragraph\n# - We calculate the \"probability of elimination\", means how many teams have been eliminated in a round that a given map is placed.\n# - We then combine two values together using multiplication and averaging for each round, then perform the summation to get a participation value.\n\n# The overall formula will be\n\n# $$\n# \\text{Map Participation Rate} = \\frac{\\text{Player Score}}{\\text{Team Score}} \\cdot (\\text{Probability of Elimination} + \\epsilon)\n# $$\n\n# $$\n# \\text{Overall Participation Rate} = \\sum_{\\text{round} \\in \\text{rounds}} \\text{Avg} (\\text{Map Participation Rate})\n# $$\n\n# Then we combine them into outlier values using this formula:\n\n# $$\n# \\text{Adjusted Outlier Values} = \\left(1 + p\\right)x\n# $$\n#\n# Where $p$ is **Overall Participation Rate** and
\n# $x$ is **Outlier Value** from our Parametric Average Percentile Model\n\n# ## In Layman Terms\n\n# \"At the first instinct, the way to classify the outperforming players is to find the players who are outperforming.\"

- HowToPlayLN, 2022, while thinking how to write this section

\n#\n# But the more important question is, how do we define outperforming ? Given a player, an easy idea is to calculate how many players a given player has surpressed in a certain map. To be precise, we try to compare the player with the entire population of players who are eligible to participate in a tournament. In order to compare (approximate) directly, we need to use the statistical magic called \"Normal Distribution\".\n#\n# But we cannot use the Normal Distribution directly, from the raw score, we need to use some transformation to extract some features and normalize them. First, we use the \"logit transformation\" to seperate the stacked performances of players in the tournament, for example, we can see more distinction between 990k and 995k score than 985k and 990k, which matches the environment of how osu!mania tournaments usually works. Next, we use the \"Box-Cox Transformation\" in order to make data suitable for the statistical magic.\n#\n# We then input the transformed data into the statistical magic that allows us to approximate how much the player has surprassed the population. However, we do this for every single map in a tournament and use all sample players data to determine the approximated value. Then we average the values for all maps a player played in a tournament.\n#\n# Finally, the last feature comes from the nature of the behaviour of outperforming players in a tournament, especially a country team tournament with the format of 3v3 and 6 players for each country. They usually are the first or second player of the maps. With this information, we can add the \"maps played\" feature into the consideration. We do this by taking a logarithm function to maps played to reduce the difference between players who plays in the late game and focus more on them. We then multiply that value to the previous feature, then we get the numbers that will determine whether the player is outperforming.\n\n# ## Code Documentation\n\n# +\nimport os\n\nos.chdir(\"..\")\n# -\n\n# ### Importing Necessary Modules\n#\n# We will use `pandas` for data management, `matplotlib.pyplot` for data visualization and `numpy` to deal with math stuff.\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# For Local Packages, we will use `Dataset` and `get_table_players` to transform dataset into the \n\nfrom utils import Dataset\nfrom utils.outlierdetectionmodel import BoxCoxParametricAveragePercent\nfrom utils.dftransformer import get_table_players\n\n_4dm4_dataset = Dataset('datasets/4dm4.db')\n\n_4dm4_data = _4dm4_dataset.select('scores', columns=['player_name', 'round', 'beatmap_type', 'beatmap_tag', 'score_logit'], where={\n 'beatmap_type': ['LN', 'RC', 'HB'],\n})\n\n_4dm4_data.head()\n\nplayer_table = get_table_players(_4dm4_data)\n\nplayer_table\n\nplayer_table[player_table <= 0] = np.nan\n\n# +\nmodel = BoxCoxParametricAveragePercent()\n\nmodel.fit(player_table.values)\n\n# +\ndf = pd.DataFrame(index=player_table.index)\n\ndf['outlier_values'] = model.predict(player_table.values)\n# -\n\ndf.sort_values(by='outlier_values', ascending=False).head(16)\n\ndf['n_maps_played'] = np.sum(pd.notna(player_table.values), axis=1)\n\ndf\n\ndf['adjusted_ol_values_1'] = df['outlier_values'] * np.log(df['n_maps_played'] + 1)\n\ndf.sort_values(by='adjusted_ol_values_1', ascending=False).head(15)\n\nplt.hist(df['outlier_values'])\nplt.show()\n\nplt.hist(df['adjusted_ol_values_1'])\nplt.show()\n\nparticipation_rate_dataset = _4dm4_dataset.query(\"\"\"select scores.player_name, scores.round, scores.beatmap_type, \nscores.beatmap_tag, scores.score as player_score, team_scores.score as team_score\nfrom scores left join player_data on scores.player_name = player_data.player_name\nleft join team_data on team_data.country_code = player_data.country_code\nleft join team_scores on team_data.country_name = team_scores.country_name and\nscores.beatmap_type = team_scores.beatmap_type and scores.round = team_scores.round and scores.beatmap_tag = team_scores.beatmap_tag\nwhere scores.beatmap_type != \\\"SV\\\"\"\"\")\n\nparticipation_rate_dataset\n\nparticipation_rate_dataset['participation_rate'] = participation_rate_dataset['player_score'] / participation_rate_dataset['team_score']\n\nparticipation_rate_dataset\n\nparticipation_rate_dataset = participation_rate_dataset[['player_name', 'round', 'participation_rate']]\n\naverage_participation_rate = participation_rate_dataset.groupby(['player_name', 'round']).mean()\n\naverage_participation_rate\n\n# +\nteam_survived = _4dm4_dataset.query(\"\"\"\nSELECT last_round, count(country_name) from team_data where last_round != \"\" group by last_round \n\"\"\")\n\nround_order = [\"RO16\", \"QF\", \"SF\", \"F\", \"GF\"]\n# -\n\nteam_survived\n\nteam_survived.index = team_survived['last_round']\n\nteam_survived = team_survived.loc[round_order]\n\nteam_survived\n\nteam_survived['country_eliminated'] = team_survived['count(country_name)'].cumsum()\n\nteam_survived\n\n# +\nteam_survived['p_eliminated'] = team_survived['country_eliminated'] / 32\n\nteam_survived\n# -\n\naverage_participation_rate['multipiler'] = average_participation_rate.index.map(lambda x: team_survived[team_survived['last_round'] == x[1]]['p_eliminated'].values + 0.1 or [0.1])\n\naverage_participation_rate\n\naverage_participation_rate['multipiler'] = average_participation_rate['multipiler'].apply(lambda x: x[0])\n\naverage_participation_rate['value'] = average_participation_rate['participation_rate'] * average_participation_rate['multipiler']\n\naverage_participation_rate\n\naverage_participation_rate = average_participation_rate[['value']]\n\naverage_participation_rate = average_participation_rate.groupby(average_participation_rate.index.map(lambda x: x[0])).sum()\n\ndf\n\ndf['participation_value'] = average_participation_rate['value']\n\ndf\n\ndf['adjusted_ol_values_2'] = df['outlier_values'] + df['outlier_values'] * df['participation_value']\n\ndf.sort_values('adjusted_ol_values_2', ascending=False).head(10)\n\n# ---\n","repo_name":"4digitmwc/4dmanalysis","sub_path":"4dm4analysis/averagepercent_detection.ipynb","file_name":"averagepercent_detection.ipynb","file_ext":"py","file_size_in_byte":11301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"34828445057","text":"# + [markdown] id=\"_GZakiZT-ad8\"\n# **Applying Fractal Clustering o Human Activity recognition data set.**\n\n# + id=\"u7SqTBl9iTN7\"\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport seaborn as seabornInstance \nfrom sklearn.model_selection import train_test_split \nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\n# %matplotlib inline\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"zGu2rMOYiqC0\" outputId=\"8e51de61-7859-4b46-b8e3-b7128e8adc5c\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + id=\"mMoCRlzgixPv\"\nPath = 'drive/My Drive/ML Assignments/dataset'\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 287} id=\"ERiNPLweiyqy\" outputId=\"d877a2ea-e3df-4d6e-a078-e937c1478f9b\"\ndf = pd.read_csv(Path+'/train.csv')\ndf.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 473} id=\"IvgzW71Yl0TH\" outputId=\"eef75ab9-a1e8-42e5-921e-58c80de2c505\"\ndf.dropna()\n\n# + id=\"GDRjVrRvmGW8\"\n\nfrom sklearn.cluster import KMeans\nimport datetime \nfrom dateutil.relativedelta import relativedelta\n\npd.set_option('display.max_columns', 100)\n\n# + id=\"32DPcHm3mSqb\"\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.cluster import KMeans\nfrom sklearn import metrics\n\n\n# + [markdown] id=\"VNuQSSjjD9hV\"\n# **Calculate the performance of clustering using SSE and Sihouette score.**\n\n# + id=\"0b4gh4_cmZ-G\"\ndef plot_cluster(df, max_loop=50):\n \"\"\"\n Looking at the performance of various number of clusters using K-Means.\n Performance is evaluated by within cluster SSE and silhouette score.\n \"\"\"\n try:\n df.drop('cluster', axis=1, inplace=True)\n except:\n next\n X = df.iloc[:,[0,1]]\n \n # robust scaling is used so that the centering and scaling statistics are therefore not influenced by a few number of very large marginal outliers as they are based on percentiles\n rb = RobustScaler()\n X_rb = rb.fit_transform(X)\n \n sse_within_cluster = {}\n silhouette_score = {}\n \n for k in range(2, max_loop):\n kmeans = KMeans(n_clusters=k, random_state=10, n_init=10, n_jobs=-1)\n kmeans.fit(X_rb)\n sse_within_cluster[k] = kmeans.inertia_\n silhouette_score[k] = metrics.silhouette_score(X_rb, kmeans.labels_, random_state=10)\n\n _ = plt.figure(figsize=(10,6))\n ax1 = plt.subplot(211)\n _ = plt.plot(list(sse_within_cluster.keys()), list(sse_within_cluster.values()))\n _ = plt.xlabel(\"Number of Clusters\")\n _ = plt.ylabel(\"SSE Within Cluster\")\n _ = plt.title(\"Within Cluster SSE After K-Means Clustering\")\n _ = plt.xticks([i for i in range(2, max_loop)], rotation=75)\n \n ax2 = plt.subplot(212)\n _ = plt.plot(list(silhouette_score.keys()), list(silhouette_score.values()))\n _ = plt.xlabel(\"Number of Clusters\")\n _ = plt.ylabel(\"Silhouette Score\")\n _ = plt.title(\"Silhouette Score After K-Means Clustering\")\n _ = plt.xticks([i for i in range(2, max_loop)], rotation=75)\n \n plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.5, wspace=0.35)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 446} id=\"WVeezq2arGbu\" outputId=\"9a506994-fd8d-442d-9151-f553ac0e6237\"\nplot_cluster(df, max_loop=25)\n\n\n# + id=\"5frKfzztrvmy\"\ndef apply_cluster(df, clusters=6):\n \"\"\"\n Applying K-Means with the optimal number of clusters identified\n \"\"\"\n try:\n df.drop('cluster', axis=1, inplace=True)\n except:\n next\n X = df.iloc[:,[0,79]]\n rb = RobustScaler()\n X_rb = rb.fit_transform(X)\n kmeans = KMeans(n_clusters=clusters, random_state=17, n_init=10, n_jobs=-1) \n kmeans.fit(X_rb) \n score = metrics.silhouette_score(X_rb, kmeans.labels_, random_state=17)\n df['cluster'] = kmeans.labels_\n sse_within_cluster = kmeans.inertia_\n \n print(\"clustering performance\")\n print(\"sse withing cluster: \" + str(sse_within_cluster.round()))\n print(\"silhouette score: \" + str(score.round(2)))\n return df\n\n\n# + [markdown] id=\"NUdxPdSgGZOp\"\n# **First trial with 6 clusters**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Px0PU4Zer2IA\" outputId=\"3108ce94-f1ce-4eeb-efd9-995a77f12e5f\"\nfirst_trial = apply_cluster(df, clusters=6)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 235} id=\"KJHt14ZLsagd\" outputId=\"c0ed8fe9-326c-4367-da4d-86ada893cb60\"\ncluster_perf_df = (\n first_trial\n .groupby('cluster')\n .agg({\"tBodyAcc-mean()-X\":\"mean\", \"tBodyAcc-mean()-Y\":\"mean\"})\n .sort_values('tBodyAcc-mean()-X')\n .reset_index()\n)\n\ncluster_perf_df\n\n# + id=\"t6hJdvdFs-G-\"\ndf_sub = df.query(\"cluster == 0\").reset_index(drop=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 446} id=\"76cGm8_etD2l\" outputId=\"6dab758a-af41-4c8b-cfd1-4a0a88d0a136\"\nplot_cluster(df_sub, max_loop=25)\n\n# + [markdown] id=\"ypvXrZ3HHHLp\"\n# **Second Trial with 2 clusters**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6D3erPRMtW_6\" outputId=\"37ddfb07-81d1-4e1c-ef30-d2b23befc985\"\nsecond_trial= apply_cluster(df_sub, clusters=2)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 111} id=\"V9DgBmjmxG9f\" outputId=\"c228f115-188f-4186-c92e-064d77b19716\"\ncluster_perf_df = (\n second_trial\n .groupby('cluster')\n .agg({\"tBodyAcc-mean()-X\":\"mean\", \"tBodyAcc-mean()-Y\":\"mean\"})\n .sort_values('tBodyAcc-mean()-X')\n .reset_index()\n)\n\ncluster_perf_df\n\n# + [markdown] id=\"7u447gxzIkFS\"\n# The Silhouette score and SSE values for the trial first and second trial when compared it is founnd that the SSE score has dropped from 8731 to 397\n# where as Sihouette score has decreased a bit from 0.55 to 0.35.\n#\n# From the above we can conclude that cluster 2 is the golden cluster.\n","repo_name":"yadnyshree/ML_Assignments","sub_path":"Fractal_Clustering.ipynb","file_name":"Fractal_Clustering.ipynb","file_ext":"py","file_size_in_byte":5683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"32301327340","text":"# # intro to df 3 module + import dataset\n\nimport pandas as pd\n\nbond=pd.read_csv('jamesbond.csv')\nbond.head()\n\n# # set_index and reset_index methods\n\n# + active=\"\"\n# bond=pd.read_csv('jamesbond.csv',index_col='Film')\n# bond.head(2)\n# -\n\nbond.set_index(keys='Film',inplace=True)\nbond.head(3)\n\nbond.reset_index(inplace=True)\nbond.head(2)\n\n# # retrieve rows by index label with .loc[] accessor\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nbond.loc['A View to a Kill']\n\nbond.loc['Casino Royale']\n\nbond.loc['Diamonds Are Forever':'From Russia With Love']\n\nbond.loc['Diamonds Are Forever':'From Russia With Love':2]\n\nbond.loc['Golden Eye': ]\n\nbond.loc[:'On Her Majesty a Secret Service']\n\nbond.loc[['Die Another Day','Octopussy']]\n\n# +\n#to check whether the index value is present in df\n\n'gold bond' in bond.index\n# -\n\n# # retrieve rows by index position with iloc accessor\n\nbond=pd.read_csv('jamesbond.csv')\nbond.head(3)\n\nbond.iloc[0]\n\nbond.iloc[[0,2]]\n\nbond.iloc[2:8]\nbond.iloc[0:4,2:4] #-----iloc[r,c]\n\n# + active=\"\"\n# loc= label indexing\n# iloc=integer indexing\n# -\n\n# # second arguments to loc and iloc accessors\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nbond.loc['Moonraker','Actor']\nbond.loc['Moonraker','Director']\nbond.loc['Moonraker','Box Office']\n\nbond.loc['Moonraker',['Actor','Director','Box Office']]\n\nbond.loc[['Moonraker','A View to a Kill'],['Actor','Director','Box Office']]\n\nbond.loc['Moonraker','Actor':'Director']\n\nbond.loc['Moonraker':'Skyfall','Actor':'Box Office']\n\nbond.loc['Moonraker': ,'Director':]\n\nbond.iloc[12,3]\n\nbond.iloc[12,3:6]\n\nbond.iloc[[12,15],3:6]\n\nbond.iloc[2:,:5]\n\n# # set a new value for a specific cell\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nbond.loc['Dr. No','Actor'] ='sir sean conery'\n\nbond.loc['Dr. No','Actor']\n\nbond.loc['Dr. No',['Box Office','Budget','Bond Actor Salary']] =[35,2,456]\n\nbond.loc['Dr. No',['Box Office','Budget','Bond Actor Salary']]\n\n# # set multiple value in a dataframe\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nactor_is_seancornery=bond['Actor']=='Sean Connery'\nactor_is_seancornery\n\nbond.loc[actor_is_seancornery]\nbond.loc[actor_is_seancornery,'Actor']\nbond.loc[actor_is_seancornery,'Actor']= 'sir sean cornery'\n\nbond\n\n# # rename index labels or columns in a df\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nbond.rename(mapper={'GoldenEye':'Golden Eye',\n 'A View to a Kill':'AViewToaKill'})\n\nbond.rename(mapper={'GoldenEye':'Golden Eye',\n 'A View to a Kill':'AViewToaKill'},axis=0)\nbond.rename(mapper={'GoldenEye':'Golden Eye',\n 'A View to a Kill':'AViewToaKill'},axis='rows')\nbond.rename(mapper={'GoldenEye':'Golden Eye',\n 'A View to a Kill':'AViewToaKill'},axis='index')\n\nbond.rename(index={'GoldenEye':'Golden Eye',\n 'A View to a Kill':'AViewToaKill'})\n\nbond.rename(mapper={'Year':'release date',\n 'Box Office':'revenue' },axis=1)\n#bond.rename(mapper={'Year':'release date',\n# 'Box Office':'revenue' },axis=columns)\n\nbond.columns=['year','hero','director','revenue','cost','salary']\n\nbond.head(0)\n\n# # delete rows or columns from a dataframe\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nbond.drop('A View to a Kill')\nbond.drop(['Casino Royale','Diamonds Are Forever','Dr. No'])\n#bond.drop('A View to a Kill',inplace=True)\n\nbond.drop('Box Office',axis=1)\nbond.drop(['Box Office','Year'],axis=1)\n#bond.drop(['Box Office','Year'],axis=1,inplace=True)\n\nactor=bond.pop('Actor')\n\nactor\n\ndel bond['Director']\n\nbond\n\n# # create random sample\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nbond.sample()\nbond.sample(n=4)\nbond.sample(frac=.25)\nbond.sample(n=3,axis=1)\n\n# # the nsmallest() and nlargest() methods\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nbond.sort_values('Box Office',ascending=False).head(3)\n\n# +\nbond.nlargest(3,'Box Office')\n\nbond.nsmallest(3,'Box Office')\n# -\n\nbond['Budget'].nlargest(2)\n\n# # filtering with the where method\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nmask=bond['Actor'] == 'Sean Connery'\nbond[mask]\n\nbond.where(mask)\n\nbond.where(bond['Box Office']>800)\n\nmask2=bond['Box Office']>800\n\n# +\n#bond.where(mask & mask2)\n# -\n\n# # query()method\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\nbond.columns=bond.columns.str.replace(' ','_')\n\nbond.query('Actor==\"Sean Connery\"')\nbond.query('Director==\"Terence Young\"')\nbond.query('Director!=\"Terence Young\"')\n\nbond.query('Box_Office > 500')\n\nbond.query(\"Actor =='Roger Moore' or Director =='Terence Young' \")\n\n# +\nbond.query(\"Actor in ['Roger Moore','Sean Connery']\")\n\n#bond.query(\"Actor not in ['Roger Moore','Sean Connery']\")\n\n# + active=\"\"\n# to run query method there should be no space between the column names\n# -\n\n# # review of apply method on a single column\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\n\n# +\ndef convert_to_string_and_millions(number):\n return str(number) +'millions'\n\n#bond['Box Office']=bond['Box Office'].apply(convert_to_string_and_millions)\n\n\n# +\n#bond['Budget']=bond['Budget'].apply(convert_to_string_and_millions)\n# -\n\nc=['Box Office','Budget','Bond Actor Salary']\nfor i in c:\n bond[i]=bond[i].apply(convert_to_string_and_millions)\n\nbond.head(2)\n\n# # apply method with row values\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\n\n# +\ndef good_movie(row):\n actor= row[1]\n budget=row[4]\n \n if actor == 'Roger Moore':\n return 'best'\n elif actor == 'Daniel Craig' and budget >40:\n return 'ok'\n else:\n return 'no clue'\n \nbond.apply(good_movie,axis=1)\n# -\n\n# # # copy method\n\nbond=pd.read_csv('jamesbond.csv',index_col='Film')\nbond.sort_index(inplace=True)\nbond.head(3)\n\ndirectors=bond['Director']\ndirectors.head(3)\n\n# +\n#directors['A View to a Kill']='mister john glen'\n\n# +\n#directors.head(3)\n\n# +\n#bond.head(3)\n# -\n\ndirectors=bond['Director'].copy()\ndirectors.head(3)\n\ndirectors['A View to a Kill']='mister john glen'\n\ndirectors.head(3)\n\nbond.head(3)\n","repo_name":"subhaganesh/data-analysis_using_pandas","sub_path":"dataframes 3 - extraction.ipynb","file_name":"dataframes 3 - extraction.ipynb","file_ext":"py","file_size_in_byte":6512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"34676164251","text":"# +\n#Q1 program to find a number divisible by 7 and not a multiple of 5 ranging between 2000 to 3200\n\nnumber = []\nfor i in range(2000, 3201):\n if (i % 7 == 0) and (i % 5 != 0):\n number.append(i)\nprint(number)\n\n# +\n#Q2 accept users's first and last name and print in a reverse order\n\nfname = input(\"enter your first name: \")\nlname = input(\"enter your last name: \")\nprint(lname + \" \" + fname)\n\n# +\n#Q3 find the volume of a sphere where diameter = 12 cm\n\ndiameter = 12\nradius = diameter/2\nvolume = 4/3 * 3.14 * radius**3\nprint(\"The volume of the sphere is\", volume)\n# -\n\n\n","repo_name":"AvirupM99/PythonAssignments","sub_path":"PythonAssignment1.ipynb","file_name":"PythonAssignment1.ipynb","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"29621788749","text":"## Problem1\nimport random as rd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#input parameters\nprice = 75\ncost = 50\nsalvage = 15\ndemand_mean = 500\ndemand_std = 75\norder = 550\n\n#base case model\ndemand = 450 #we assume this number for demand\nif demand < order: qty_sold = demand\nelse: qty_sold = order\nqty_left = order - qty_sold\nsales_revenue = price * qty_sold\nsalvage_revenue = salvage * qty_left\ntotal_cost = cost * order\nprofit = sales_revenue + salvage_revenue - total_cost\nprint(qty_sold, qty_left, sales_revenue, salvage_revenue, total_cost, profit)\n\n# +\n#simulation trials\nrd.seed(101010)\ntrials = 10000\nsample = list()\nfor i in range(trials):\n demand = rd.normalvariate(demand_mean, demand_std)\n if demand < order: qty_sold = demand \n else: qty_sold = order\n qty_left = order - qty_sold\n sales_revenue = price * qty_sold\n salavage_revenue = salvage * qty_left\n total_cost = cost * order\n profit = sales_revenue + salvage_revenue - total_cost\n sample.append(profit)\n \n(a,b,c) = plt.hist(sample, edgecolor='k')\n# -\n\nmean = sum(sample)/len(sample)\nprint('Mean = $%5.2f' % (sum(sample)/len(sample)))\n\nproportion = sum(1 for x in sample if x < 0.0)/len(sample)\nprint('There is a %5.2f%% chance of incurring a loss on the order.'% (100*proportion))\n\nprint(sample[0:10])\n\n# part(d)\norder_1st = list(range(300,801))\nmean_profit_1st = list()\nfor order in order_1st:\n trials = 10000\n sample = list()\n for i in range(trials):\n demand = rd.normalvariate(demand_mean, demand_std)\n if demand < order: qty_sold = demand \n else: qty_sold = order\n qty_left = order - qty_sold\n sales_revenue = price * qty_sold\n salavage_revenue = salvage * qty_left\n total_cost = cost * order\n profit = sales_revenue + salvage_revenue - total_cost\n sample.append(profit)\n mean_profit = sum(sample)/len(sample)\n mean_profit_1st.append(mean_profit)\n\n\nplt.plot(order_1st, mean_profit_1st)\n\nprint('The optimal order quantity is %d.' % (order_1st[mean_profit_1st.index(max(mean_profit_1st))]))\nprint('The expected profit is $%8.2f.'% (max(mean_profit_1st)))\n\n# +\n##Question 2\n\n#input parameters\nprice_min = 18.95\nprice_max = 26.95\nprice_mode = 24.95\ncost_min = 12.00\ncost_max = 15.00\nintercept = 10000.00\nslope = -250.00\nrand_term_mean = 0.00\nrand_term_std = 10.00\nfixed_cost_mean = 30000\nfixed_cost_std = 5000\n# -\n\n#base case model\nprice = 24.95\ncost = 13.50\nrand_term = -10.00\nquantity_sold = intercept + slope*price + rand_term\nfixed_cost = 30000\nprofit = (price-cost)*quantity_sold - fixed_cost\nprint(quantity_sold, profit)\n\n#simulation\ntrials = 10000\nsample = list()\nfor i in range(trials):\n price = rd.triangular(price_min, price_max, price_mode)\n cost = rd.uniform(cost_min, cost_max)\n rand_term = rd.normalvariate(rand_term_mean, rand_term_std)\n quantity_sold = intercept + slope*price + rand_term\n fixed_cost = rd.normalvariate(fixed_cost_mean, fixed_cost_std)\n profit = (price - cost) * quantity_sold - fixed_cost\n sample.append(profit)\nplt.hist(sample, edgecolor =\"k\")\n\nprint('The expected mean profit is $%8.2f' % (sum(sample)/len(sample)))\nproportion = sum(1 for x in sample if x < 0.0)/len(sample)\nprint('The probability of incurring a lost is %5.2f%%' % (100*proportion))\nprint('The maximum lost is $%5.2f.' % (min(sample)))\n\n# +\n#2a Profit appears to be normally distributed\n","repo_name":"leah1217/Decision-Models","sub_path":"Homework 4 - Leah Ngan Lai.ipynb","file_name":"Homework 4 - Leah Ngan Lai.ipynb","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"28421349266","text":"# +\nlist_of_numbers = [3, 5, 6, 8, 10, 11, 25, 55, 95]\n\n# функция, для нахождения минимума в списке целых\ndef min_value(some_list):\n number = min(some_list)\n return number\nprint(f'The minimum value in the list is {min_value(list_of_numbers)}')\n\n\n# найти количество простых чисел в списке целых\n\ndef get_prime_number(some_list):\n count = 0\n for i in some_list:\n if all(i % j != 0 for j in range(2, i)):\n count += 1\n return count\n \nprint(f'The quantity of prime numbers = {get_prime_number(list_of_numbers)}')\n\n\n# функция, удаляющую из списка целых некоторое заданное число\n\ndef get_delete_number(some_list, number):\n count = 0\n for i in some_list:\n if i == number:\n some_list.remove(i)\n count += 1\n return count\n\nget_delete_number(list_of_numbers, 10)\nprint(list_of_numbers) \n\n# функция, которая возвращает список, содержащий элементы 2-х списков\n\nlist_of_numbers_1 = [3, 5, 6, 8, 10, 25, 55, 95]\nlist_of_numbers_2 = [56, 89, 23, 54]\n\ndef get_full_list(some_list, some_list_2):\n return some_list + some_list_2\n\nprint(get_full_list(list_of_numbers_1, list_of_numbers_2))\n\n# функция, высчитывающуя степень каждого элемента списка целых\n\ndef get_power_of_numbers(some_list, pow_number):\n result_list = []\n for i in some_list:\n result_list.append(i**pow_number)\n return result_list\n\nprint(get_power_of_numbers(list_of_numbers, 2))\n \n \n","repo_name":"nadiia-tokareva/skillup","sub_path":"lesson 3-1.ipynb","file_name":"lesson 3-1.ipynb","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"33475372493","text":"import numpy as np\n\nimport pandas as pd\nsales = pd.read_csv('./FreeCodeCamp-Pandas-Real-Life-Example-master/data/sales_data.csv',parse_dates=['Date'])\nsales.head()\n\nsales.describe()\n\nsales.shape\n\nsales.info()\n\nsales['Unit_Cost'].mean()\n\n# +\n#plot a box plot using the selected feature\n\nimport matplotlib.pyplot as plt \nplt.rcParams[\"font.family\"] = \"sans serif\"\n\nsales['Unit_Cost'].plot(kind='box', vert= False, figsize=(14,6))\n\n \n\n# +\nimport seaborn as sns\n\nplt.figure(figsize=(10,6))\nsns.kdeplot(data=sales, x=sales.Unit_Cost)\nplt.xlabel('Unit Cost')\nplt.show()\n# -\n\n\n\nsales['Age_Group'].value_counts()\n\nsales['Age_Group'].value_counts().plot(kind='pie', figsize=(6,6))\n\nax = sales['Age_Group'].value_counts().plot(kind='bar', figsize=(14,6))\nax.set_ylabel('Number of Sales')\nax.set_xlabel('Age Group')\n\nnew_sales = sales.select_dtypes(include=np.number)\ncorr = new_sales.corr()\nsns.heatmap(corr, annot=False)\nplt.show()\n\ncorr\n\n# +\nimport plotly.express as px\n\npx.line(x=[1,2,3,4], y=[4,5,6,7]).show()\n# -\n\n# !pip install nbformat\n","repo_name":"SebasManco/Projects","sub_path":"MachineLearning/DataScience/.ipynb_checkpoints/my_lecture1-checkpoint.ipynb","file_name":"my_lecture1-checkpoint.ipynb","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"72060773566","text":"import pandas as pd\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nfrom sklearn.ensemble import RandomForestRegressor\nimport numpy as np\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_breast_cancer\nimport sys\nfrom sklearn import tree\nimport matplotlib.pyplot as plt\nimport graphviz\n\n\n# +\ndf = pd.read_csv('train.csv')\ndf_train, df_test = train_test_split(df,test_size = 0.2,shuffle=False)\nfeature_names = ['OverallQual', 'GrLivArea', 'GarageCars']\nX_train = df_train[feature_names]\ny_train = df_train['SalePrice']\ny_train.to_csv('y_train.csv')\n\nX_test = df_test[feature_names]\ny_test = df_test[['SalePrice']]\n# -\n\nX, y = load_breast_cancer(return_X_y=True)\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n# +\n## build sklearn regression trree\ntree_max_depth = 5 # controls overfitting \nmin_samples_leaf = 5 # controls overfitting \n\nsk_dt_reg = tree.DecisionTreeRegressor(max_depth = tree_max_depth, min_samples_leaf = min_samples_leaf, criterion = 'squared_error')\nsk_dt_reg.fit(X_train,y_train)\nsk_dt_preds = sk_dt_reg.predict(X_train)\nsk_dt_scores = r2_score(sk_dt_preds,y_train)\nprint('sk dt scores train:',sk_dt_scores)\nsk_dt_preds = sk_dt_reg.predict(X_test)\nsk_dt_scores = r2_score(sk_dt_preds,y_test)\nprint('sk dt scores test:',sk_dt_scores)\n# -\n\n### plot the tree\ndot_data = tree.export_graphviz(sk_dt_reg,out_file = None,feature_names = feature_names, filled = True, special_characters = True,max_depth=3)\ngraph = graphviz.Source(dot_data)\n# graph\n\n# +\n## build sklearn random forest\nn_estimators = 100\ncriterion='squared_error'\nmax_depth = None\nmin_samples_split = 2\nmin_samples_leaf = 1\nmin_weight_fraction_leaf = 0\nmax_features = sqrt(len(feature_names) - 1)/len(feature_names) # according to GENIE3 suggestion\nmax_leaf_nodes = None\nmin_impurity_decrease = 0\nbootstrap = True\noob_score = True # to use out-of-bag samples to estimate the generalization score (available for bootstrap=True)\nn_jobs = None # number of jobs in parallel. fit, predict, decision_path, and apply can be done in parallel over the trees\nrandom_state=None # controls randomness in bootstrapping as well as drawing features\nverbose=1 \nwarm_start=False # reuse the slution of the previous call to fit and add more ensembles to the estimator. look up on Glosery\nccp_alpha=0 # complexity parameter used for minima cost-complexity pruning. by default, no prunning\nmax_samples = None # if bootstrap is True, the number of samples to draw from the samples. if none, draw X.shape[0]\n\nsk_dt_reg = RandomForestRegressor(n_estimators=n_estimators, criterion=criterion, max_depth=max_depth, min_samples_split=min_samples_split,\n min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, \n max_features=max_features, max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=min_impurity_decrease,\n bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose,\n warm_start=warm_start, ccp_alpha=ccp_alpha, max_samples=max_samples)\nsk_dt_reg.fit(X_train,y_train)\nsk_dt_preds = sk_dt_reg.predict(X_train)\nsk_dt_scores = r2_score(sk_dt_preds,y_train)\nprint('sk dt scores train:',sk_dt_scores)\nsk_dt_preds = sk_dt_reg.predict(X_test)\nsk_dt_scores = r2_score(sk_dt_preds,y_test)\nprint('sk dt scores test:',sk_dt_scores)\n# -\n\n### build sklearn random forest\nsk_dt_reg = RandomForestRegressor()\nsk_dt_reg.fit(X_train,y_train)\nsk_dt_preds = sk_dt_reg.predict(X_train)\nsk_dt_scores = r2_score(sk_dt_preds,y_train)\nprint('sk dt scores train:',sk_dt_scores)\nsk_dt_preds = sk_dt_reg.predict(X_test)\nsk_dt_scores = r2_score(sk_dt_preds,y_test)\nprint('sk dt scores test:',sk_dt_scores)\n\ndot_data = tree.export_graphviz(clf, out_file=None, \n feature_names=iris.feature_names, \n class_names=iris.target_names, \n filled=True, rounded=True, \n special_characters=True) \ngraph = graphviz.Source(dot_data) \n\n\nclass Node:\n def __init__(self, x, y, idxs, min_leaf=5):\n self.x = x \n self.y = y\n self.idxs = idxs \n self.min_leaf = min_leaf\n self.row_count = len(idxs)\n self.col_count = x.shape[1]\n self.val = np.mean(y[idxs]) \n self.score = float('inf')\n self.find_varsplit()\n def find_varsplit(self): #find where to split\n for c in range(self.col_count): self.find_better_split(c) # after this, the row and column of split is determined by scoring\n if self.is_leaf: return\n x = self.split_col\n lhs = np.nonzero(x <= self.split)[0]\n rhs = np.nonzero(x > self.split)[0]\n self.lhs = Node(self.x, self.y, self.idxs[lhs], self.min_leaf)\n self.rhs = Node(self.x, self.y, self.idxs[rhs], self.min_leaf)\n @property\n def split_col(self): return self.x.values[self.idxs,self.var_idx]\n\n @property\n def is_leaf(self): return self.score == float('inf') \n def find_better_split(self, var_idx): # determines row and column of the split\n x = self.x.values[self.idxs, var_idx]\n for r in range(self.row_count):\n lhs = x <= x[r]\n rhs = x > x[r]\n if rhs.sum() < self.min_leaf or lhs.sum() < self.min_leaf: continue # prunning\n\n curr_score = self.find_score(lhs, rhs)\n if curr_score < self.score: \n self.var_idx = var_idx # the chosen column\n self.score = curr_score\n self.split = x[r] # the row to split\n\n def find_score(self, lhs, rhs):\n y = self.y[self.idxs]\n lhs_std = y[lhs].std()\n rhs_std = y[rhs].std()\n# return lhs_std * lhs.sum() + rhs_std * rhs.sum() #score is calculated by: std_l * sum_x_l + std_r*sum_x_r => ??? why sum of ihs? \n return lhs_std + rhs_std #score is calculated by: std_l * sum_x_l + std_r*sum_x_r => ??? why sum of ihs? \n\n def predict(self, x):\n return np.array([self.predict_row(xi) for xi in x])\n\n def predict_row(self, xi):\n if self.is_leaf: return self.val\n node = self.lhs if xi[self.var_idx] <= self.split else self.rhs\n return node.predict_row(xi)\nclass DecisionTreeRegressor:\n \n def fit(self, X, y, min_leaf = 5):\n self.dtree = Node(X, y, idxs = np.array(np.arange(len(y))), min_leaf=min_leaf)\n return self\n\n def predict(self, X):\n return self.dtree.predict(X.values)\nregressor = DecisionTreeRegressor().fit(X_train, y_train)\n\npreds = regressor.predict(X)\nr2_score(y, preds)\n\npred_test = regressor.predict(X_test)\nr2_score(y_test, pred_test)\n","repo_name":"janursa/DT","sub_path":"script.ipynb","file_name":"script.ipynb","file_ext":"py","file_size_in_byte":6763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"19206124922","text":"# ### Author - Nikita Koshti\n\n# # GRIP - THE SPARKS FOUNDATION\n\n# ### DATA SCIENCE AND BUSINESS ANALYTICS INTERNSHIP\n\n# (BATCH-APRIL 2021)\n\n# ### Prediction using unsupervised learning\n\n# ### Task-2 predict the optimum number of clusters and represent it visually from the given iris data.\n\n# In this model we will find number of cluster in iris data by k-Means clustering algorithim\n\n# ### importing and reading data\n\n#importing liabraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n#read the data\ndata=pd.read_csv(\"Iris.csv\")\ndata.head()\n\n#data information\ndata.shape\n\n#data information\ndata.info()\n\n#Describing data\ndata.describe()\n\ndata['Species'].value_counts()\n\n#checking null value\ndata.isnull().sum()\n\n# + active=\"\"\n# We can see there are no null value in dataset\n# -\n\n#Droping ID column and creating plot\ntmp=data.drop('Id', axis=1)\ng=sns.pairplot(tmp,hue='Species',markers='*')\nplt.show()\n\n# ### Findout cluster with KMeans clustering\n\n# +\nx=data.iloc[:,[0,1,2,3]].values\nfrom sklearn.cluster import KMeans\nwcss = [] #within cluster sum of square\n\nfor i in range(1,10):\n kmeans = KMeans(n_clusters = i, init ='k-means++',\n max_iter = 300, n_init = 10, random_state = 0)\n kmeans.fit(x)\n wcss.append(kmeans.inertia_)\nwcss \n# -\n\n#ploting Graph\nplt.figure(figsize=(9,6))\nplt.plot(range(1,10),wcss)\nplt.title('The Elbow method')\nplt.xlabel('Number of cluster')\nplt.ylabel('cluster')\nplt.show()\n\n# From the above graph we can find out the optimum number of clusters to be 3 as the elbow starts having a straight trend after 3\n\n#Appling Kmeans\nkmeans= KMeans(n_clusters = 3, init = 'k-means++',\n max_iter = 300, n_init = 10, random_state = 0)\ny=kmeans.fit_predict(x)\ny\n\ncl=pd.Series(kmeans.labels_)\ndata['cluster']=cl\n\n# ## visualising the clusters\n\n# +\nplt.figure(figsize=(9,6))\nplt.scatter(x[y == 0,0],x[y == 0,1],\n s= 100, c = 'green', label = 'Iris-setosa')\nplt.scatter(x[y == 1,0],x[y == 1,1],\n s= 100, c = 'red', label = 'Iris-versicolour')\nplt.scatter(x[y == 2,0],x[y == 2,1],\n s= 100, c = 'blue', label = 'Iris-virginica')\n\n#ploting the centroids of the clusters\nplt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],\n s= 100, c = 'black', label = 'Centroids')\nplt.legend()\nplt.show()\n\n# +\n#visualising the clusters - On the first two columns\nplt.figure(figsize=(9,6))\nplt.scatter(x[y == 0,0],x[y == 0,2],\n s= 100, c = 'green', label = 'Iris-setosa')\nplt.scatter(x[y == 1,1],x[y == 1,2],\n s= 100, c = 'red', label = 'Iris-versicolour')\nplt.scatter(x[y == 2,1],x[y == 2,2],\n s= 100, c = 'blue', label = 'Iris-virginica')\n\n#ploting the centroids of the clusters\nplt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],\n s= 100, c = 'black', label = 'Centroids')\nplt.legend()\nplt.show()\n# -\n\n# ## Representing the data with the cluster column\n\ndata.iloc[:,:]\n\nx=[5.1,4.6,3.0,6.7]\nkmeans.predict([x])\n\n\n# Through we can assume that our model is predict accurately.\n","repo_name":"NIkita7898-nmk/Predict-the-optimum-number-of-cluster","sub_path":"Task-2 predict the optimum number of clusters and represent it visually.ipynb","file_name":"Task-2 predict the optimum number of clusters and represent it visually.ipynb","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"39929629253","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GIvkYm2-7gCl\" outputId=\"f445fa96-9491-4b53-ecdc-cd378fb57659\"\n# Input total score for each subject\nmaths_score = int(input(\"Enter your overall marks for Maths: \"))\nphysics_score = int(input(\"Enter your overall marks for Physics: \"))\nchemistry_score = int(input(\"Enter your overall marks for Chemistry: \"))\n\n\n# + id=\"mIcD3Xy19jQl\"\n# Calculate the percentage for each subject\ntotal_marks = 100 # Assume the maximum marks for each subject is 100\nmaths_percentage = (maths_score / total_marks) * 100\nphysics_percentage = (physics_score / total_marks) * 100\nchemistry_percentage = (chemistry_score / total_marks) * 100\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"lgRkYiwD9puy\" outputId=\"5e86b15a-20e0-4db6-f8b9-3e6eb8c3ebe0\"\n# Print the results\nprint(f\"Maths - Total Score: {maths_score}, Percentage: {maths_percentage}%\")\nprint(f\"Physics - Total Score: {physics_score}, Percentage: {physics_percentage}%\")\nprint(f\"Chemistry - Total Score: {chemistry_score}, Percentage: {chemistry_percentage}%\")\n\n","repo_name":"atonendeley/IMAGE-STEGANOGRAPHY","sub_path":"Marks2.ipynb","file_name":"Marks2.ipynb","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"31758996470","text":"# # Week 3 Assignment - Clustering Neighborhoods in Toronto\n\n# +\nimport numpy as np # library to handle data in a vectorized manner\n\nimport pandas as pd # library for data analsysis\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\nimport json # library to handle JSON files\n\n# #!conda install -c conda-forge geopy --yes # uncomment this line if you haven't completed the Foursquare API lab\nfrom geopy.geocoders import Nominatim # convert an address into latitude and longitude values\n\nimport requests # library to handle requests\nimport bs4\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\nfrom pandas.io.json import json_normalize # tranform JSON file into a pandas dataframe\n\n# Matplotlib and associated plotting modules\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\n\n# import k-means from clustering stage\nfrom sklearn.cluster import KMeans\n\n# #!conda install -c conda-forge folium=0.5.0 --yes # uncomment this line if you haven't completed the Foursquare API lab\nimport folium # map rendering library\n\nprint('Libraries imported.')\n# -\n\n# ## Pulling the Data from Wikipedia \n\ntables = pd.read_html('List_of_postal_codes_of_Canada:_M.html', header=0)\ndf=tables[0]\ndf = df[df.Borough != 'Not assigned']\n\ndf1=df.groupby('Postcode', as_index=False).agg({'Borough': 'first', 'Neighbourhood' : ' , '.join})\ndf1 = df1.sort_values(by='Postcode')\n\n# correct the not-assigned neighbourhood\ndf1['Neighbourhood'] = np.where(df1['Neighbourhood']=='Not assigned', df1['Borough'], df1['Neighbourhood'])\ndf1\n\ndf1.shape\n\n# ### As an American I cannot tell you how much time I wasted before I realized that \"Neighbourhood\" included a u. We spell it \"Neighborhood\".\n\n# # Part 2: Creating the file with the Lat/Long columns\n\n# ! pip install geocoder\n\nimport geocoder\ng = geocoder.google('Toronto, Ontario')\ng\n\n# ### I could not get even a single report from the geocoder, and wanted to get going with it, so I choose to use the csv.\n\nGS = pd.read_csv('Geospatial_Coordinates.csv')\ndf1.rename(columns={'Postcode' : 'Postal Code', 'Latitude':'Latitude'}, inplace=True)\n\ndf1=df1.merge(GS, on=\"Postal Code\")\ndf1.head()\n\n# # Part 3: Clustering Neighborhoods\n\n# +\naddress = 'Toronto, Ontario'\n\ngeolocator = Nominatim(user_agent=\"ny_explorer\")\nlocation = geolocator.geocode(address)\nlatitude = location.latitude\nlongitude = location.longitude\nprint('The geograpical coordinate of Toronto are {}, {}.'.format(latitude, longitude))\n\n# +\n# First let's make a map.\n# create map of Toronto using latitude and longitude values\nmap_toronto = folium.Map(location=[latitude, longitude], zoom_start=10)\nfor lat, lng, borough, neighborhood in zip(df1['Latitude'], df1['Longitude'], df1['Borough'], df1['Neighbourhood']):\n label = '{}, {}'.format(neighborhood, borough)\n label = folium.Popup(label, parse_html=True)\n folium.CircleMarker(\n [lat, lng],\n radius=5,\n popup=label,\n color='blue',\n fill=True,\n fill_color='#3186cc',\n fill_opacity=0.7,\n parse_html=False).add_to(map_toronto) \n \nmap_toronto\n# -\n\n# ## Get FourSquare Data\n\nCLIENT_ID = 'MJ2INACVWX1BIQZF4PZKQTRJKVYSBM0JHLEPZWPMOAMQPURV' # your Foursquare ID\nCLIENT_SECRET = '5TH5H3G5TOXAKNNGKR22LC2EWJAV5MD0UQBJHVQAZ1WHVEW2' # your Foursquare Secret\nVERSION = '20180605' # Foursquare API version\nLIMIT=100\n\n\ndef getNearbyVenues(names, latitudes, longitudes, radius=500):\n \n venues_list=[]\n for name, lat, lng in zip(names, latitudes, longitudes):\n print(name)\n \n # create the API request URL\n url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(\n CLIENT_ID, \n CLIENT_SECRET, \n VERSION, \n lat, \n lng, \n radius, \n LIMIT)\n \n # make the GET request\n results = requests.get(url).json()[\"response\"]['groups'][0]['items']\n \n # return only relevant information for each nearby venue\n venues_list.append([(\n name, \n lat, \n lng, \n v['venue']['name'], \n v['venue']['location']['lat'], \n v['venue']['location']['lng'], \n v['venue']['categories'][0]['name']) for v in results])\n\n nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])\n nearby_venues.columns = ['Neighborhood', \n 'Neighborhood Latitude', \n 'Neighborhood Longitude', \n 'Venue', \n 'Venue Latitude', \n 'Venue Longitude', \n 'Venue Category']\n \n return(nearby_venues)\n\n\nToronto_venues = getNearbyVenues(names=df1['Neighbourhood'],\n latitudes=df1['Latitude'],\n longitudes=df1['Longitude']\n )\n\n\n# ### Obviously, this is running by postal code, not by \"neighbourhood\" as in the New York example.\n\nprint(Toronto_venues.shape)\nToronto_venues.head()\n\n# ## Look I'll be frank this isn't the kind of data I'm interested in using in my career, and I'm tired of mucking with GSP data, so here's the minimum to get to the clustering.\n\n# +\n# one hot encoding\ntoronto_onehot = pd.get_dummies(Toronto_venues[['Venue Category']], prefix=\"\", prefix_sep=\"\")\n\n# add neighborhood column back to dataframe\ntoronto_onehot['Neighborhood'] = Toronto_venues['Neighborhood'] \n\n# move neighborhood column to the first column\nfixed_columns = [toronto_onehot.columns[-1]] + list(toronto_onehot.columns[:-1])\ntoronto_onehot = toronto_onehot[fixed_columns]\n\ntoronto_onehot.head()\n# -\n\ntoronto_onehot.shape\n\ntoronto_grouped = toronto_onehot.groupby('Neighborhood').mean().reset_index()\ntoronto_grouped\n\ntoronto_grouped.shape\n\n\n# ## Toronto is a nice city, though I prefer Ottawa. I don't actually care about which venues are most common. Here's an implementation of sorting the data so that we are already prioritizing which venues will be viewed on the clustering algorithm. \n\ndef return_most_common_venues(row, num_top_venues):\n row_categories = row.iloc[1:]\n row_categories_sorted = row_categories.sort_values(ascending=False)\n \n return row_categories_sorted.index.values[0:num_top_venues]\n\n\n# +\nnum_top_venues = 10\n\nindicators = ['st', 'nd', 'rd']\n\n# create columns according to number of top venues\ncolumns = ['Neighborhood']\nfor ind in np.arange(num_top_venues):\n try:\n columns.append('{}{} Most Common Venue'.format(ind+1, indicators[ind]))\n except:\n columns.append('{}th Most Common Venue'.format(ind+1))\n\n# create a new dataframe\nneighborhoods_venues_sorted = pd.DataFrame(columns=columns)\nneighborhoods_venues_sorted['Neighborhood'] = toronto_grouped['Neighborhood']\n\nfor ind in np.arange(toronto_grouped.shape[0]):\n neighborhoods_venues_sorted.iloc[ind, 1:] = return_most_common_venues(toronto_grouped.iloc[ind, :], num_top_venues)\n\nneighborhoods_venues_sorted.shape\n# -\n\n# # Part Too Many: The actual clustering\n\n# +\n# set number of clusters\nkclusters = 5\n\ntoronto_grouped_clustering = toronto_grouped.drop('Neighborhood', 1)\n\n# run k-means clustering\nkmeans = KMeans(n_clusters=kclusters, random_state=0).fit(toronto_grouped_clustering)\n\n# check cluster labels generated for each row in the dataframe\nkmeans.labels_\n\n# +\n# add clustering labels\nneighborhoods_venues_sorted.insert(0, 'Cluster Labels', kmeans.labels_)\n\n\n# -\n\nneighborhoods_venues_sorted['Cluster Labels']\n\ndf1.rename(columns={'Neighbourhood' : 'Neighborhood'}, inplace=True)\n\n# +\ntoronto_merged = df1\n\n# merge toronto_grouped with toronto_data to add latitude/longitude for each neighborhood\ntoronto_merged = toronto_merged.join(neighborhoods_venues_sorted.set_index('Neighborhood'), on='Neighborhood')\ntoronto_merged.head()\n# -\n\ntoronto_merged.drop(toronto_merged.index[[16,20,21,93,98]], inplace=True)\ntoronto_merged['Cluster Labels']=toronto_merged['Cluster Labels'].astype(int)\ntoronto_merged.head()\n\n# set color scheme for the clusters\nx = np.arange(kclusters)\nys = [i + x + (i*x)**2 for i in range(kclusters)]\ncolors_array = cm.rainbow(np.linspace(0, 1, len(ys)))\nrainbow = [colors.rgb2hex(i) for i in colors_array]\n\n\n# +\n# create map\nmap_clusters = folium.Map(location=[latitude, longitude], zoom_start=11)\n\n# add markers to the map\nmarkers_colors = []\nfor lat, lon, poi, cluster in zip(toronto_merged['Latitude'], toronto_merged['Longitude'], toronto_merged['Neighborhood'], toronto_merged['Cluster Labels']):\n label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True)\n folium.CircleMarker(\n [lat, lon],\n radius=5,\n popup=label,\n color=rainbow[cluster-1],\n fill=True,\n fill_color=rainbow[cluster-1],\n fill_opacity=0.7).add_to(map_clusters)\n \nmap_clusters\n# -\n\ntoronto_merged.loc[toronto_merged['Cluster Labels'] == 0, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]]\n\ntoronto_merged.loc[toronto_merged['Cluster Labels'] == 1, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]]\n\ntoronto_merged.loc[toronto_merged['Cluster Labels'] == 2, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]]\n\ntoronto_merged.loc[toronto_merged['Cluster Labels'] == 3, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]]\n\ntoronto_merged.loc[toronto_merged['Cluster Labels'] == 4, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]]\n\n# So we see the major differences: Neighborhoods in 0 have food/restaurants/businesses, in 1 they have playground/pool, in 2 they have parks as the most common, 3 its just one place that loves to drink, and 4 has baseball fields. \n","repo_name":"martjios/Coursera_Capstone","sub_path":"Week 3 Assignment - Course 9(3).ipynb","file_name":"Week 3 Assignment - Course 9(3).ipynb","file_ext":"py","file_size_in_byte":9767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"5211881436","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"3FCmKdMF6GW1\"\n# You want to minimize the cost of shipping goods from 2 different warehouses to 4 different customers. Each warehouse has a limited supply and each customer has a certain demand. We need to fulfil the demand of the customers by shipping products from given warehouses such that the overall cost of shipping is minimum and we are also able to satisfy the customer demands using limited supply available with each warehouse.\n# ![image.png](attachment:image.png)\n#\n# The customer demands and the warehouse availability is as follows.\n#\n# ![image-2.png](attachment:image-2.png)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"R8PvKpH26GW7\" outputId=\"587d7102-02b8-4029-d302-74d174f63f5d\"\n# !pip install pulp\nfrom pulp import *\nimport pandas as pd\nimport numpy as np\n\n# + id=\"TlFN8UCI6GW9\"\nn_warehouses = 2\nn_customers = 4\n\n# Cost Matrix\ncost_matrix = np.array([[1, 3, 0.5, 4],\n [2.5, 5, 1.5, 2.5]])\n# Demand Matrix\ncust_demands = np.array([35000, 22000, 18000, 30000])\n\n# Supply Matrix\nwarehouse_supply = np.array([60000, 80000])\n\n# + id=\"xQttVqIY6GW9\"\nmodel = LpProblem(\"Supply-Demand-Problem\", LpMinimize)\n\n# + id=\"ryWhlYnN6GW-\" outputId=\"35cf709e-c73a-4562-c58c-d47ae25867ab\"\nvariable_names = [str(i)+str(j) for j in range(1, n_customers+1) for i in range(1, n_warehouses+1)]\nvariable_names.sort()\nprint(\"Variable Indices:\", variable_names)\n\n# + id=\"bv2mzrsy6GW-\" outputId=\"a83ed67d-0e85-4311-fade-692b591ebb45\"\nDV_variables = LpVariable.matrix(\"X\", variable_names, cat = \"Integer\", lowBound= 0 )\nallocation = np.array(DV_variables).reshape(2,4)\nprint(\"Decision Variable/Allocation Matrix: \")\nprint(allocation)\n\n# + id=\"ZmdGBbCm6GW_\" outputId=\"fb9b68ac-5a19-44ce-f795-04a6c9d3d7df\"\nobj_func = lpSum(allocation*cost_matrix)\nprint(obj_func)\nmodel += obj_func\nprint(model)\n\n# + id=\"2SKvwRK06GXA\" outputId=\"e11d39d3-6ad9-4fb6-c8a3-0cd43971a4a4\"\n#Supply Constraints\nfor i in range(n_warehouses):\n print(lpSum(allocation[i][j] for j in range(n_customers)) <= warehouse_supply[i])\n model += lpSum(allocation[i][j] for j in range(n_customers)) <= warehouse_supply[i] , \"Supply Constraints \" + str(i)\n\n# + id=\"PVCqeCmF6GXA\" outputId=\"c3044f6a-781a-4b4d-cdc8-94fcbee7a13a\"\n# Demand Constraints\nfor j in range(n_customers):\n print(lpSum(allocation[i][j] for i in range(n_warehouses)) >= cust_demands[j])\n model += lpSum(allocation[i][j] for i in range(n_warehouses)) >= cust_demands[j] , \"Demand Constraints \" + str(j)\n\n# + id=\"W9a0QVXN6GXB\" outputId=\"5c1e542d-cadb-450c-8452-18885abfcdf0\"\nprint(model)\n\n# + id=\"Fvrb9Flb6GXC\" outputId=\"28131e23-cafc-4ac3-e96a-b3cb075d251a\"\n#model.solve()\nmodel.solve(PULP_CBC_CMD())\n\nstatus = LpStatus[model.status]\n\nprint(status)\n\n# + id=\"_ZAS5KQm6GXC\" outputId=\"9995464f-e993-4fde-b0c0-0ff723341eba\"\nprint(\"Total Cost:\", model.objective.value())\n\n# Decision Variables\n\nfor v in model.variables():\n try:\n print(v.name,\"=\", v.value())\n except:\n print(\"error couldnt find value\")\n\n# + id=\"JpoEEc736GXC\" outputId=\"7c4c62fc-912a-42de-f1a4-e6864b0b636e\"\n# Warehouse 1 and Warehouse 2 required capacity\n\nfor i in range(n_warehouses):\n print(\"Warehouse \", str(i+1))\n print(lpSum(allocation[i][j].value() for j in range(n_customers)))\n","repo_name":"dele22922/tarea3_feat_eng","sub_path":"EjemploPulpTransp.ipynb","file_name":"EjemploPulpTransp.ipynb","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"26712007682","text":"import pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline \n\ndf = pd.read_csv('.\\Data\\Rios.csv',index_col=0)\ndf.head(5)\n\n# ## Histograma para ver como estan distribuidos nuestros valores \n\nplt.title('Rios') #Matplotlib\nplt.hist(df['Millas'], edgecolor='black', linewidth=1);\n\ndf['Millas'].hist(edgecolor='black', linewidth=1); #Pandas\n\n# ## Hacemos un grafico de caja para ver los outliers \n\nimport seaborn as sns\nsns.boxplot(df.Millas);\n\nnum_features = df[['Millas']] #Pandas\nnum_features.boxplot(grid=False);\n\ndf.boxplot(); #Pandas \n\nplt.boxplot(df['Millas']); #Matplotlib\n\n# ## Valores estadisticos de los Outliers\n\nQ1 = df['Millas'].quantile(0.25)\nQ3 = df['Millas'].quantile(0.75)\nRI = Q3 - Q1\nMediana = df['Millas'].median()\nMin = df['Millas'].min()\nMax = df['Millas'].max()\n\nprint(f'Primer Cuartil:{Q1}')\nprint(f'Segundo Cuartil:{Q3}')\nprint(f'Rango Intercuartil: {RI}')\nprint(f'Mediana:{Mediana}')\nprint(f'Min:{Min}')\nprint(f'Max:{Max}')\n\n# ## Calculo de limites\n\nlim_inf = Q1 - 1.5 * RI #Para los valores que aparecen en el box, lim inf [-245 o 135min] se queda con 135\nlim_sup = Q3 + 1.5 * RI #lim sup [1235 o 3710max] se queda con 1235\n[lim_inf,lim_sup]\n\n# ## Ubicación de los Outliers\n\nmask_outliers = ((df['Millas'] < lim_inf) | (df['Millas'] > lim_sup))\nmask_outliers\n\ndf_outliers = df[mask_outliers] #Me trae los outliers\ndf_outliers\n\ndf_outliers.sort_values('Millas',ascending=False)\n\n# ## Se sacan los datos ya sin outliers\n\nmask_outliers = ((df['Millas'] >= lim_inf) & (df['Millas'] <= lim_sup))\ndf_no_outliers = df[mask_outliers]\ndf_no_outliers\n\n# ## Se vuelve a graficar para corroborar que ya no hay outliers (Se repite el proceso hasta que se eliminan todos los outliers)\n\nplt.boxplot(df_no_outliers['Millas']);\n\nQ1 = df_no_outliers['Millas'].quantile(0.25)\nQ3 = df_no_outliers['Millas'].quantile(0.75)\nRI = Q3 - Q1\nMediana = df_no_outliers['Millas'].median()\nMin = df_no_outliers['Millas'].min()\nMax = df_no_outliers['Millas'].max()\n\nprint(f'Primer Cuartil:{Q1}')\nprint(f'Segundo Cuartil:{Q3}')\nprint(f'Rango Intercuartil: {RI}')\nprint(f'Mediana:{Mediana}')\nprint(f'Min:{Min}')\nprint(f'Max:{Max}')\n\nlim_inf = Q1 - 1.5 * RI #Para los valores que aparecen en el box, lim inf [-245 o 135min] se queda con 135\nlim_sup = Q3 + 1.5 * RI #lim sup [1235 o 3710max] se queda con 1235\n[lim_inf,lim_sup]\n\nmask = ((df_no_outliers['Millas'] >= lim_inf) & (df_no_outliers['Millas'] <= lim_sup))\ndf_no_outliers2 = df_no_outliers[mask]\n\nplt.boxplot(df_no_outliers2['Millas']);\n\nQ1 = df_no_outliers2['Millas'].quantile(0.25)\nQ3 = df_no_outliers2['Millas'].quantile(0.75)\nRI = Q3 - Q1\nMediana = df_no_outliers2['Millas'].median()\nMin = df_no_outliers2['Millas'].min()\nMax = df_no_outliers2['Millas'].max()\n\nlim_inf = Q1 - 1.5 * RI #Para los valores que aparecen en el box, lim inf [-245 o 135min] se queda con 135\nlim_sup = Q3 + 1.5 * RI #lim sup [1235 o 3710max] se queda con 1235\n[lim_inf,lim_sup]\n\nmask = ((df_no_outliers2['Millas'] >= lim_inf) & (df_no_outliers2['Millas'] <= lim_sup))\ndf_no_outliers3 = df_no_outliers2[mask]\n\nplt.boxplot(df_no_outliers3['Millas']);\n","repo_name":"rocooper7/Machine-Learning","sub_path":"5.Curso Prof ML/3. OutlierDetect&Remove/IQR/IQR2.ipynb","file_name":"IQR2.ipynb","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"33704977442","text":"# # Experiment One - R models\n\n# + tags=[\"parameters\"]\nfrom typing import Literal\n\n# decide which dataset and Cal, Tuning and Test set to use\nPREPROCESSING: Literal[\"raw\", \"anderson\", \"mishra\", \"mishra_adj\"] = \"anderson\"\nSET_SPLIT: Literal[\"anderson\", \"mishra\", \"mishra_with_outliers\"] = \"anderson\"\nTRAINING_ORDER: Literal[\"anderson\", \"mishra\", \"mishra_with_outliers\", \"random_1\", \"random_2\", \"random_3\"] = \"anderson\"\nINCLUDE_MISHRA_OUTLIERS: bool = True # True, False\n# -\n\n# ## 1.0 Setup\n\n# +\nimport datetime as dt\nimport os\nimport pandas as pd\n\nimport evaluation\n# -\n\nparams = {\n \"preprocessing\": PREPROCESSING,\n \"set_split\": SET_SPLIT,\n \"training_order\": TRAINING_ORDER,\n \"include_mishra_outliers\": INCLUDE_MISHRA_OUTLIERS,\n \"x_scaled\": False,\n}\n\n# ### 1.1 Prepare Dataset\n\n# +\n# prepare data based on set parameters above\n\n# read in data that has been preprocessed\nif PREPROCESSING == \"anderson\":\n data_file = \"data/input/anderson&etal_2020_pretreatment.csv\"\n # data_file = \"../../data/processed/NAnderson2020MendeleyMangoNIRData_Anderson2020pretreat_AllSetSplits.csv\"\nelif PREPROCESSING in (\"raw\", \"mishra\"):\n data_file = \"data/input/mishra&passos_2021_pretreatment.csv\"\n # data_file = \"../../data/processed/NAnderson2020MendeleyMangoNIRData_Mishra2021Aug_AllSetSplits.csv\"\nelif PREPROCESSING == \"mishra_adj\":\n data_file = \"data/input/mishra&passos_2021_pretreatment_adjusted.csv\"\n # data_file = \"../../data/processed/NAnderson2020MendeleyMangoNIRData_Mishra2021Aug2_AllSetSplits.csv\"\nelse:\n raise Exception(\"choose a valid preprocessing\")\ndata = pd.read_csv(data_file).drop(columns=[\"Unnamed: 0\"])\ndata.insert(0, \"sample_order\", 0)\ndata.insert(1, \"sample_no\", 0)\ndata.insert(2, \"set\", 0)\n\n# include or exclude mishra outliers\nif not INCLUDE_MISHRA_OUTLIERS:\n data = data.query(\"set_mishra != 'Outlier'\").copy()\n\n# assign set split\nif SET_SPLIT == \"anderson\":\n data[\"sample_no\"] = data[\"sample_no_anderson\"]\n data[\"set\"] = data[\"set_anderson\"]\nelif SET_SPLIT == \"mishra\" and not INCLUDE_MISHRA_OUTLIERS:\n data[\"sample_no\"] = data[\"sample_no_mishra\"]\n data[\"set\"] = data[\"set_mishra\"]\nelif SET_SPLIT == \"mishra_with_outliers\" and INCLUDE_MISHRA_OUTLIERS:\n data[\"sample_no\"] = data[\"sample_no_mishra_with_outliers\"]\n data[\"set\"] = data[\"set_mishra_with_outliers\"]\nelse:\n raise Exception(\"choose a valid set split\")\n\n# order data based on ordering selection\nif TRAINING_ORDER == \"mishra\" and SET_SPLIT == \"mishra_with_outliers\":\n TRAINING_ORDER = \"mishra_with_outliers\"\nelif TRAINING_ORDER == \"mishra_with_outliers\" and SET_SPLIT == \"mishra\":\n TRAINING_ORDER = \"mishra\"\ndata.sort_values(by=f\"sample_no_{TRAINING_ORDER}\", inplace=True)\ndata.reset_index(inplace=True, drop=True)\ndata[\"sample_order\"] = data.index + 1\n\ndata.groupby([\"category\", \"set\"]).size()\n# -\n\n# output to csv to be read by r script\ndata.to_csv(\"data/input_r/mango_meta&spectra.csv\")\n\n# ## 2.0 Build Models\n\n# ### 2.2 ANN Anderson et al. (2020)\n#\n# Model replicated in R, please see anderson-etal-2021-ann-model.R script for model training and predictions.\n#\n# Predicted values are read in below and tested.\n\n# +\npredictions_file = \"data/predictions/anderson_etal_2020_ann.csv\"\ntraining_time_file = \"data/input_r/training_time.csv\"\nprediction_time_file = \"data/input_r/prediction_time.csv\"\n\ny_test_comparison = pd.read_csv(predictions_file)\ntraining_time = pd.read_csv(training_time_file)\ntraining_time = training_time[\"x\"].iloc[0]\ntraining_time = dt.timedelta(minutes=training_time) if training_time < 8 else dt.timedelta(seconds=training_time)\nprediction_time = pd.read_csv(prediction_time_file)\nprediction_time = prediction_time[\"x\"].iloc[0]\nprediction_time = dt.timedelta(minutes=prediction_time) if prediction_time < 8 else dt.timedelta(seconds=prediction_time)\nos.remove(training_time_file)\nos.remove(prediction_time_file)\ny_test_comparison\n# -\n\nevaluation.calculate_metrics(\n y_true=y_test_comparison[\"actual\"],\n y_pred=y_test_comparison[\"predicted\"],\n)\n\n# statistical tests against best reported model (Mishra & Passos, 2021)\nmodel_name = \"mishra&passos_2021_best_cnn\"\nbase_model_preds = pd.read_csv(f\"data/predictions/{model_name}.csv\")\nevaluation.significance_difference(\n e_1=base_model_preds.query(\"test_data == 'test'\")[\"y_error\"].to_numpy(),\n e_2=(y_test_comparison[\"actual\"] - y_test_comparison[\"predicted\"]).to_numpy()\n)\n\ntraining_time\n\nprediction_time\n\nprediction_time/len(y_test_comparison)\n\n\n","repo_name":"jemjemwalsh/research-deep-learning-nirs","sub_path":"research/experiments/one/experiment_one_r_models.ipynb","file_name":"experiment_one_r_models.ipynb","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"42"} +{"seq_id":"18514383317","text":"import keras\nimport numpy as np\nfrom keras import layers\nimport random\nimport sys\n\npath = 'phr1.txt'\ntext = open(path, encoding='utf-8').read().lower()\nprint('Corpus length:', len(text))\n\n# +\nlines = text.splitlines()\nphrases, questions = [''], []\nfor line in lines:\n line = line.strip()\n if line:\n phrases[-1] += ' '+line\n if len(questions)=16:\n answer=answer[:15]\n if answer[len(answer)-1]==\".\":\n answer=answer[:14]\n print(\"6단계: \"+answer)\n #7단계\n if len(answer)<=2:\n while len(answer)!=3:\n answer+=answer[len(answer)-1]\n print(\"7단계: \"+answer)\n\n return answer\nprint(solution(\"=.=\"))\n\n\n# +\n#level1/소수 만들기\ndef check(a, b, c): \n total = a + b + c\n for i in range(2, total): \n if total % i == 0 : return False \n return True \n\ndef solution(nums):\n answer = 0\n for i in range(0, len(nums) - 2): \n for j in range(i+1, len(nums) - 1): \n for k in range(j+1, len(nums)): \n if check(nums[i], nums[j], nums[k]): answer += 1\n return answer \nprint(solution([1,2,7,6,4]))\n# Review) \"from itertools import combinations\"라는 것을 이용해서\n# \"A=list(combinations(num,3))\"등을 \n# for i in A: \n# if check(i[0], i[1], i[2]): answer += 1 \n# 위와같이 이렇게 사용할수 있다.\n\n# +\n#level1/소수 만들기\n\ndef solution(nums):\n answer = 0\n sums=0\n for i in range(0, len(nums)-2): \n for j in range(i+1, len(nums)-1): \n for k in range(j+1, len(nums)): \n Flag=True\n sums=nums[i]+nums[j]+nums[k]\n \n for f in range(2,sums):\n if sums%f==0:\n print(\"sums의값은 :\"+str(sums)+\"f의 값은: \"+str(f))\n Flag=False\n if Flag==True:\n print(\"flag가 True인경우!\")\n answer+=1\n return answer \nprint(solution([1,2,7,6,4]))\n#Review)내실수로 시간이 좀걸렸지만 결국 해결했다 ㅎㅎ\n\n# +\n#level1/폰켓몬\n\ndef solution(nums):\n answer = 0\n temp=0\n cnt=0\n temp=len(nums)/2\n list=[0 for _ in range (200001)]\n for i in nums:\n list[i]+=1\n for i in range(len(list)):\n if list[i]!=0:\n cnt+=1\n if cnt>temp:\n return temp\n answer=cnt\n \n \n return answer\n\n\n# -\n\n#level1/키패드 누르기\ndef solution(numbers, hand):\n list=[0 for _ in range(3)]\n list[0]=[1,4,7,\"*\"]\n list[1]=[2,5,8,0]\n list[2]=[3,6,9,\"#\"]\n print(list)\n answer = ''\n\n l=list[0][3]\n r=list[2][3]\n\n for i in numbers:\n temp_l,temp_r=0,0\n print(l,r)\n if i in list[0]:\n l=i\n answer+=\"L\"\n \n elif i in list[2]:\n r=i\n answer+=\"R\"\n \n else:\n print(\"i의 값은? \"+str(i)+\"현재는? \",l,r)\n\n for j in range(4): \n if l==list[1][j]:\n temp_l+=abs(list[1].index(i)-list[1].index(l)) \n \n if l==list[0][j]:\n temp_l+=1\n \n temp_l+=abs(list[1].index(i)-list[0].index(l))\n \n if r==list[1][j]:\n temp_r+=abs(list[1].index(i)-list[1].index(r))\n \n \n if r==list[2][j]:\n temp_r+=1\n \n temp_r+=abs(list[1].index(i)-list[2].index(r))\n \n\n if temp_r>temp_l:\n answer+=\"L\"\n l=i\n elif temp_r