diff --git "a/4413.jsonl" "b/4413.jsonl" new file mode 100644--- /dev/null +++ "b/4413.jsonl" @@ -0,0 +1,763 @@ +{"seq_id":"8968346131","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"CipXoFp6OYQ0\"\nfrom sklearn.datasets import load_iris\nimport numpy as np\n\niris = load_iris()\nX = iris.data[:, :2] # Use the first two features for clustering\n\n# + id=\"YRMmj4ydOiZc\"\nfrom sklearn.preprocessing import StandardScaler\n\n# Scaling Data\nscaler = StandardScaler()\nscaler.fit(X)\nX = scaler.transform(X)\n\n# + id=\"avbiaOG2Op6y\"\ngrid_size = 0.5\n\n# + id=\"9ZjfCyCwP5--\"\nx_min, x_max = np.min(X[:, 0]), np.max(X[:, 0])\ny_min, y_max = np.min(X[:, 1]), np.max(X[:, 1])\n\nx_range = np.arange(x_min, x_max, grid_size)\ny_range = np.arange(y_min, y_max, grid_size)\n\nxx, yy = np.meshgrid(x_range, y_range)\ngrid = np.c_[xx.ravel(), yy.ravel()]\n\n\n# + id=\"noXwQ2-_P9yV\"\nfrom sklearn.neighbors import NearestNeighbors\n\nnbrs = NearestNeighbors(n_neighbors=1).fit(grid)\ndistances, indices = nbrs.kneighbors(X)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 472} id=\"YrJdMTwLQDrR\" outputId=\"021828b6-3cd3-471f-a0b5-9c3a3b975179\"\nimport matplotlib.pyplot as plt\n\nplt.scatter(X[:, 0], X[:, 1], s=50, c=indices)\nplt.title('Grid-based Clustering')\nplt.xlabel('Sepal Length (cm)')\nplt.ylabel('Sepal Width (cm)')\nplt.show()\n","repo_name":"sunny9sinha/Blog_Clustering","sub_path":"Grid_Based_Clustering.ipynb","file_name":"Grid_Based_Clustering.ipynb","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"70"} +{"seq_id":"3729708476","text":"# +\nimport os\nimport numpy as np\nimport torch\nimport open3d as o3d\nimport matplotlib.pyplot as plt\nimport cv2\nimport torch_scatter as scatter\n\n\ndef euler2mat(angle):\n \"\"\"Convert euler angles to rotation matrix.\n :param angle: [3] or [b, 3]\n :return\n rotmat: [3, 3] or [b, 3, 3]\n source\n https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py\n \"\"\"\n\n if len(angle.size()) == 1:\n x, y, z = angle[0], angle[1], angle[2]\n _dim = 0\n _view = [3, 3]\n elif len(angle.size()) == 2:\n b, _ = angle.size()\n x, y, z = angle[:, 0], angle[:, 1], angle[:, 2]\n _dim = 1\n _view = [b, 3, 3]\n\n else:\n assert False\n\n cosz = torch.cos(z)\n sinz = torch.sin(z)\n\n # zero = torch.zeros([b], requires_grad=False, device=angle.device)[0]\n # one = torch.ones([b], requires_grad=False, device=angle.device)[0]\n zero = z.detach()*0\n one = zero.detach()+1\n zmat = torch.stack([cosz, -sinz, zero,\n sinz, cosz, zero,\n zero, zero, one], dim=_dim).reshape(_view)\n\n cosy = torch.cos(y)\n siny = torch.sin(y)\n\n ymat = torch.stack([cosy, zero, siny,\n zero, one, zero,\n -siny, zero, cosy], dim=_dim).reshape(_view)\n\n cosx = torch.cos(x)\n sinx = torch.sin(x)\n\n xmat = torch.stack([one, zero, zero,\n zero, cosx, -sinx,\n zero, sinx, cosx], dim=_dim).reshape(_view)\n\n rot_mat = xmat @ ymat @ zmat\n # print(rot_mat)\n return rot_mat\n\ndef points2img(points, colors, angle, translation, image_height, image_width, size_x=4, size_y=4, return_info=False, step=False):\n \"\"\" Points to Image\n\n Args:\n points (Torch.Tensor): [B, num_points, 3]\n colors (Torch.Tensor): [B, num_points, 3] or None\n angle (Torch.Tensor): [v, 3]\n translation (Torch.Tensor): [v, 3]\n image_height (int): \n image_width (int): \n size_x (int, optional): _description_. Defaults to 4.\n size_y (int, optional): _description_. Defaults to 4.\n \n Return:\n imgs (Torch.Tensor): [B, v, image_height, image_width, 3]\n \"\"\"\n B_ori, N, _ = points.shape\n \n v = angle.shape[0]\n angle = angle.to(points.device)\n rot_mat = euler2mat(angle).transpose(1, 2)\n \n # translation = torch.tensor(views_[:, 1, :]).float().to(points_.device)\n # translation = translation.unsqueeze(1)\n if torch.is_tensor(translation):\n trans = translation\n elif translation == 'mid':\n points_mean = points.mean(dim=1).unsqueeze(1) # [batch, 1, 3]\n points_mean *= torch.tensor([[1, 1, 1/3]])\n trans = points_mean\n elif translation == 'min':\n points_min = points.min(dim=1)[0].unsqueeze(1)\n trans = points_min\n else:\n trans = torch.tensor([[0, 0, 0]]).to(points.device)\n \n points -= trans\n points = torch.matmul(points.unsqueeze(1), rot_mat) # [batch, v, num_points, 3]\n points = points.reshape(-1, N, 3)\n\n t = points[:, :, 2].min(dim=1, keepdim=True)[0]/2\n\n sel = torch.zeros_like(points)\n sel[0:4, :, :] = (points[0:4, :, 2] <= 0).unsqueeze(-1)\n sel[4:12, :, :] = (points[4:12, :, 2] <= t[4:12]).unsqueeze(-1)\n \n points[0:4, :, :] = points[0:4, :, :] * (points[0:4, :, 2] <= 0).unsqueeze(-1)\n points[4:12, :, :] = points[4:12, :, :] * (points[4:12, :, 2] <= t[4:12]).unsqueeze(-1)\n\n B = B_ori*v\n if colors is not None:\n colors = torch.repeat_interleave(colors, v, dim=0)\n \n assert size_x % 2 == 0 or size_x == 1\n assert size_y % 2 == 0 or size_y == 1\n \n \n coord_x = points[:, :, 0] - points[:, :, 0].min(dim=1)[0].unsqueeze(-1) # [batch, num_points]\n coord_y = points[:, :, 1] - points[:, :, 1].min(dim=1)[0].unsqueeze(-1) # [batch, num_points]\n\n scale = 150\n \n coord_x = coord_x * scale + size_x/2\n coord_y = coord_y * scale + size_y/2\n \n _i = torch.linspace(-size_x/2, size_x/2-1, size_x, requires_grad=False, device=points.device)\n _j = torch.linspace(-size_y/2, size_y/2-1, size_y, requires_grad=False, device=points.device)\n \n extended_x = coord_x.unsqueeze(2).repeat([1, 1, size_x]) + _i # [batch, num_points, size_x]\n extended_y = coord_y.unsqueeze(2).repeat([1, 1, size_y]) + _j # [batch, num_points, size_y]\n extended_x = torch.clamp(extended_x, 0, image_width-1)\n extended_y = torch.clamp(extended_y, 0, image_height-1)\n \n extended_x = extended_x.ceil().long()\n extended_y = extended_y.ceil().long()\n \n extended_x = extended_x.unsqueeze(3).repeat([1, 1, 1, size_y]) # [batch, num_points, size_x, size_y]\n extended_y = extended_y.unsqueeze(2).repeat([1, 1, size_x, 1]) # [batch, num_points, size_x, size_y]\n \n # print(extended_x.min(), extended_x.max(), extended_y.min(), extended_y.max())\n # print(extended_x.shape, extended_y.shape)\n \n depth = points[:, :, 2]\n depth -= depth.min(dim=1)[0].unsqueeze(-1)\n depth /= depth.max(dim=1)[0].unsqueeze(-1)\n depth = depth.unsqueeze(1).unsqueeze(3).unsqueeze(4).repeat(1, 3, 1, size_x, size_y)\n if colors is not None:\n if colors.max() > 1:\n colors = colors / 255\n value = colors.unsqueeze(3).unsqueeze(4).repeat(1, 1, 1, size_x, size_y).permute(0, 2, 1, 3, 4) # [batch, 3, num_points, size_x, size_y]\n else:\n value = depth # [batch, 3, num_points, size_x, size_y]\n \n coordinates = extended_x.reshape([B, -1]) * image_width + extended_y.reshape([B, -1]) # [batch, num_points*size_x*size_y] \n coordinates = coordinates.unsqueeze(1).repeat(1, 3, 1) # [batch, 3, num_points*size_x*size_y] \n coordinates[:, 1, :] += image_height * image_width\n coordinates[:, 2, :] += image_height * image_width * 2\n coordinates = coordinates.reshape([B, -1]) # [batch, 3*num_points*size_x*size_y]\n \n value = value.reshape([B, -1])\n \n # imgs = torch.zeros([B, 3*image_height*image_width], device='cpu')\n # coordinates = coordinates.to('cpu')\n # value = value.to('cpu')\n # imgs = imgs.scatter_(1, coordinates.long(), value)\n # imgs = imgs.to(points.device)\n \n depth = depth.reshape([B, -1]) * 1000\n depth = depth.floor()\n if colors is not None:\n depth += (value / 2)\n imgs = torch.zeros([B, 3*image_height*image_width]).to(points.device)\n out, argmax = scatter.scatter_max(src=depth, index=coordinates.long(), out=imgs, dim=1)\n if colors is not None:\n imgs -= imgs.floor()\n imgs *= 2\n\n imgs = imgs.reshape([B_ori, v, 3, image_height, image_width])\n \n if not return_info:\n return imgs\n else:\n info = {}\n info['x_min'] = points[:, :, 0].min(dim=1)[0].unsqueeze(-1) # [batch, 1]\n info['y_min'] = points[:, :, 1].min(dim=1)[0].unsqueeze(-1) # [batch, 1]\n info['scale'] = scale\n info['rot_mat'] = rot_mat\n info['through'] = t\n return imgs, info\n \n\n\nn = \"scene0000_00_aligned_vert.npy\"\nmesh_vertices = np.load(os.path.join('./scenes/', n))\npoints = torch.tensor(mesh_vertices[:, 0:3])\ncolors = torch.tensor(mesh_vertices[:, 3:6])\nprint(points.max(dim=0)[0], points.min(dim=0)[0])\n\n\n# name = os.listdir('./raw_scenes/')\n# name = [n for n in name if n.endswith('.ply')]\n\n# n = \"scene0020_00_vh_clean_2.ply\"\n# pcd = o3d.io.read_point_cloud(os.path.join('./raw_scenes/', n))\n# points = torch.tensor(np.asarray(pcd.points)).float()\n# colors = torch.tensor(np.asarray(pcd.colors)).float()\n# print(points.max(dim=0)[0], points.min(dim=0)[0])\n\nworld2grid_gen = torch.tensor([[21.3325, 0.186166, 0, 15.5466], \n [-2.22001e-009, 2.54388e-007, 21.3333, 15.96],\n [0.186166, -21.3325, 2.54397e-007, 81.3357], \n [0, 0, 0, 1]])\nworld2grid = torch.tensor([[20.1711, 6.94545, 0, -21.3023], \n [-8.28237e-008, 2.40538e-007, 21.3333, 16.0125], \n [6.94545, -20.1711, 2.54397e-007, 154.848], \n [0, 0, 0, 1]])\nintrinsic_depth = torch.tensor([[573.702, 0, 324.702, 0],\n [0, 574.764, 240.97, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\npose = torch.tensor([[0.294751, 0.357687, -0.886105, 3.17002],\n [0.951536, -0.195028, 0.23779, 2.91021],\n [-0.0877612, -0.913249, -0.397837, 2.08994],\n [0, 0, 0, 1]])\n\n\npoints_h = torch.cat([points, torch.ones(points.shape[0], 1, device=points.device)], dim=1)\nprint(points_h.max(dim=0)[0], points_h.min(dim=0)[0])\n\n# points_h = torch.matmul(torch.inverse(world2grid_gen), points_h.transpose(0, 1)).transpose(0, 1)\n# print(points_h.max(dim=0)[0], points_h.min(dim=0)[0])\n\npoints_h = torch.matmul(torch.inverse(world2grid), points_h.transpose(0, 1)).transpose(0, 1)\nprint(points_h.max(dim=0)[0], points_h.min(dim=0)[0])\n\npoints_h = torch.matmul(pose, points_h.transpose(0, 1)).transpose(0, 1)\nprint(points_h.max(dim=0)[0], points_h.min(dim=0)[0])\n\npoints_h = torch.matmul(intrinsic_depth, points_h.transpose(0, 1)).transpose(0, 1)\nprint(points_h.max(dim=0)[0], points_h.min(dim=0)[0])\n\n# image_width = 320\n# image_height = 240\n# mask = (points_h[:, 0] > 0) & (points_h[:, 0] < image_width) & (points_h[:, 1] > 0) & (points_h[:, 1] < image_height)\n\n# angles = torch.tensor([\n# [0, -np.pi/3, np.pi/4],\n# [0, -np.pi/3, 3*np.pi/4],\n# [0, -np.pi/3, 5*np.pi/4],\n# [0, -np.pi/3, 7*np.pi/4],\n \n# [0, -np.pi/3, 0],\n# [0, -np.pi/3, np.pi/4],\n# [0, -np.pi/3, 2*np.pi/4],\n# [0, -np.pi/3, 3*np.pi/4],\n# [0, -np.pi/3, 4*np.pi/4],\n# [0, -np.pi/3, 5*np.pi/4],\n# [0, -np.pi/3, 6*np.pi/4],\n# [0, -np.pi/3, 7*np.pi/4]\n# ])\n\n# imgs, info = points2img(points, angle=angles, translation='mid', image_height=256, image_width=256, colors=colors, size_x=4, size_y=4, return_info=True)\n\n# plt.figure(figsize=(20, 20))\n# for v in range(angles.shape[0]):\n# img = imgs[0, v].detach().numpy().transpose(1, 2, 0)\n# plt.subplot(3, 4, v+1)\n# plt.imshow(img)\n# plt.tight_layout() \n# plt.show()\n\n# intrisic_depth = np.array([[577.591, 0, 318.905, 0], [0, 578.73, 242.684, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n\n# -\n\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot as plt\n","repo_name":"JoycexxZ/MISC","sub_path":"scannet_related/point2dep_new.ipynb","file_name":"point2dep_new.ipynb","file_ext":"py","file_size_in_byte":10526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"70"} +{"seq_id":"19218244510","text":"# +\nimport path, os\nfrom IPython.display import display\npath.setPathLocalNotebook()\nfrom unittest.mock import Mock\n\nfrom diffuserslib import DiffusersPipelines, DiffusersPipeline, DiffusersModel\n\npipelines = DiffusersPipelines(device = \"mps\", safety_checker=False)\n# pipelines.addPresets(getHuggingFacePresetsList())\n# pipelines.createImageToImagePipeline('runwayml/stable-diffusion-v1-5')\n\n\ndef dummyPipeline(prompt, **kwargs):\n print(kwargs)\n ret = Mock()\n ret.images = [kwargs['image']]\n return ret\n\npipelines.pipelineImageToImage = DiffusersPipeline(DiffusersModel(\"dummy\", \"dummy\"), dummyPipeline)\n# pipelines.pipelineImageToImage = Mock()\n\n# +\nfrom diffuserslib import Scene, SceneRenderer\n\nscene = Scene.from_file(\"./data/script.yml\", pipelines)\n\n\nrenderer = SceneRenderer(pipelines)\nrenderer.renderSceneFrames(scene, sequenceIndexes=[2], resumeFrame=0)\n# renderer.renderVideo()\n\n# +\nfrom diffuserslib import Scene, Sequence, SceneRenderer, RotateTransform, ImageToImageTransform, LinearInterpolation\nfrom PIL import Image\n\n\ninitimage = Image.open(\"./data/rabbit.png\")\nsequence = Sequence(name=\"01_dog\", length=5, transforms=[\n RotateTransform(length=5, interpolation=LinearInterpolation(), xcentre=0, ycentre=0, angle=90, zoom=0.5), \n ImageToImageTransform(pipelines=pipelines, length=5, prompt=\"a dog\")\n ])\n\nrenderer = SceneRenderer(\"./output\", pipelines)\nrenderer.renderSequenceFrames(sequence, initimage)\n\n\n\n\n# -\n\nfrom diffuserslib import SceneRenderer\nrenderer = SceneRenderer(None)\nrenderer.renderVideo('/Users/rob/GoogleDrive/stable-diffusion/projects/test/output')\n","repo_name":"pigatron-industries/diffusers-playground","sub_path":"notebooks/examples/test_animation.ipynb","file_name":"test_animation.ipynb","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"82"} +{"seq_id":"15493194293","text":"import pandas as pd\nfrom scipy import sparse\n\nratings = pd.read_csv('ratings.csv')\nevent = pd.read_csv('event.csv')\nratings = pd.merge(event,ratings)\nratings.head()\n\nratings = pd.merge(event,ratings).drop(['event_date','event_city','event_time','event_cat'],axis=1)\nratings.head()\n\nuserRatings = ratings.pivot_table(index=['user_id'],columns=['event_name'],values='rating')\nuserRatings.head()\n\ncorrMatrix = userRatings.corr(method='pearson')\ncorrMatrix.head(100)\n\n\ndef get_similar(event_name,rating):\n similar_ratings = corrMatrix[event_name]*(rating-2.5)\n similar_ratings = similar_ratings.sort_values(ascending=False)\n print(type(similar_ratings))\n return similar_ratings\n\n\n# +\n\nevent_rating = [(\"The Royal Agricultural Winter Fair\",5),(\"Big Data Toronto (BDT)\",1),(\"Understanding Emotional Intelligence\",5)]\nsimilar_event = pd.DataFrame()\nfor event,rating in event_rating:\n similar_event = similar_event.append(get_similar(event,rating),ignore_index = True)\n\nsimilar_event.head(10)\n# -\n\nsimilar_event.sum().sort_values(ascending=False).head(20)\n","repo_name":"Abdelwahab-khalil/jupyter_event","sub_path":"Filtring_test.ipynb","file_name":"Filtring_test.ipynb","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"82"} +{"seq_id":"40389257441","text":"# # Modeling with Random Forests\n\n# _This notebook will use Random Forests modeling to classify the Reddit data into the correct subreddit. First, the joined data will be split into train and test data, then preprocessed with Latent Semantic Analysis for dimensionality reduction, and then have the Random Forests model applied._\n\n# +\n# Importing necessary libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\nfrom sklearn.ensemble import RandomForestClassifier\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem import WordNetLemmatizer\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n# -\n\n# ## Joining, Preprocessing the Data\n\n# +\n# Reading the dataset\njoin = pd.read_csv('./datasets/joined.csv')\njoin.head()\n\n# Assigning target\ntarget = join['subreddit']\n\n# Dropping selftext and title columns\ndf = join.drop(['selftext','title'], axis=1)\n\n# Importing nltk's English stop words\n# Note: Using CamelCase to prevent overwriting variable later\nstopWords = stopwords.words('english')\n\n# From the EDA, I concluded that the following words were very common \n# in both /r/Jokes and /r/AntiJokes and were added noise. \n# I added these words to the nltk stop words\nstopWords.extend(['wa', 'say', 'said', 'did', 'like', 'asked', 'woman', \n 'don', 'know', 'year', 'wife', 'good', 'want', 'got', \n 'ha', 'people', 'make', 'tell', 'didn', 'joke', 'x200b', \n 'way', 'think', 'walk', 'll', 'home', 't'])\n\n# Tokenizing by alphanumeric characters\ntokenizer = RegexpTokenizer('\\w+')\n\n# Making all tokens lowercase\ntokens = [tokenizer.tokenize(post.lower()) for post in (df['joined'])]\n\n# Initializing lemmatizer\nlemmatizer = WordNetLemmatizer()\n\n# First had to lemmatize each word\n# then rejoin words into one string\nlems = []\nfor post in tokens:\n tok_post = []\n for word in post:\n tok_post.append(lemmatizer.lemmatize(word))\n posts = \" \".join(tok_post)\n lems.append(posts)\n\n# Adding the lemmatized data back to the DataFrame\njoin['text'] = lems\njoin['text'].astype(str)\n\n# Dropping unnecessary columns\njoin=join.drop(['selftext','title','joined'],axis=1)\njoin.shape\n# -\n\n# _Adding in columns for word count and character count. According to the EDA, I believe that these columns will help add signal to the model._\n\njoin['char_count'] = join['text'].map(len)\njoin['word_count'] = join['text'].map(lambda x: len(x.split()))\n\njoin.head()\n\n# ## Train-Test-Splitting the Data\n\n# +\nX = join[['text','char_count','word_count']]\ny = join['subreddit']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n# -\n\nX_train.shape\n\n# ## Using TFIDF to Vectorize the Data\n\n# +\n# Initializing the TFIDF Vectorizer\ntfidf = TfidfVectorizer(stop_words=stopWords, min_df=1, max_df=1.0)\n\n# Fitting and transforming the data\nX_train_tf = tfidf.fit_transform(X_train['text'])\nX_test_tf = tfidf.transform(X_test['text'])\n# -\n\nX_train_tf.shape\n\n# ## Using SVD for Dimensionality Reduction\n\nX_train_tf_df = pd.DataFrame(X_train_tf.todense(), columns=tfidf.get_feature_names())\nX_test_tf_df = pd.DataFrame(X_test_tf.todense(), columns=tfidf.get_feature_names())\n\n# Initializing the SVD model\n# From the LSA notebook, it was determined that 346 components \n# would allow for a variance explained score of 75%\nSVD = TruncatedSVD(n_components=346)\nX_train_svd = SVD.fit_transform(X_train_tf_df)\nX_test_svd = SVD.transform(X_test_tf_df)\n\n# Wrapped the SVD model into a DataFrame for the purpose of \n# adding back in the word_count and character_count features\nX_train_svd_df = pd.DataFrame(X_train_svd)\nX_test_svd_df = pd.DataFrame(X_test_svd)\n\n# Had to reset the index of the original X_train and X_test data\n# Had trouble adding this data back into the SVD Dataframe \n# and resetting the index solved the issue\nX_train = X_train.reset_index()\nX_test = X_test.reset_index()\n\n# Adding word_count and char_count back into the train and test data\nX_train_svd_df['word_count'] = X_train['word_count']\nX_train_svd_df['char_count'] = X_train['char_count']\nX_test_svd_df['word_count'] = X_test['word_count']\nX_test_svd_df['char_count'] = X_test['char_count']\n\n# ## Using the Random Forests Model\n\n# _Random Forest models take advantage of the aggregating nature of bagged decision tree models coupled with the factor of limited random features, forcing the model to make decisions based on a fraction of the available information. The aggregation results in a model that has low variance and high accuracy._\n\nrf = RandomForestClassifier(random_state=42)\nparams = {\n 'n_estimators' : [175, 200, 225],\n 'max_depth' : [None],\n # Using 1.0 will use all features, quick way to test bagging classifier\n 'max_features' : ['auto', 1.0],\n 'min_samples_split' : [2,3]\n}\ngrid = GridSearchCV(rf, param_grid = params, cv=5)\ngrid.fit(X_train_svd_df, y_train)\nprint(grid.best_score_)\ngrid.best_params_\n\n# _With GridSearch and Random Forests, my baseline accuracy is now at about 64%. I decided to try to fit an Extra Trees model to see if it increases my accuracy. Extra Trees model builds on top of the Random Forests model but has an additional factor of randomness (random values to divide the features, which are also randomly selected)._\n\nfrom sklearn.ensemble import ExtraTreesClassifier\net = ExtraTreesClassifier(random_state=42)\nparams = {\n 'n_estimators' : [100, 150, 200],\n 'max_depth' : [None,3,4],\n # Using 1.0 will use all features, quick way to test bagging classifier\n 'max_features' : ['auto', 1.0],\n 'min_samples_split' : [2,3,4]\n}\ngrid1 = GridSearchCV(et, param_grid = params, cv=5)\ngrid1.fit(X_train_svd_df, y_train)\nprint(grid1.best_score_)\ngrid1.best_params_\n\ngrid1.score(X_test_svd_df, y_test)\n\n# _Extra Trees modeling doesn't seem to improve the baseline accuracy in this case, achieving roughly the same score._\n\n# _In this notebook, I took the cleaned and preprocessed data and applied Random Forests and Extra Trees models to try to build a high accuracy model. The highest score achieved was about 64% accuracy. Next, I will apply Gradient Boosting to try to achieve a higher accuracy score in the next notebook._\n","repo_name":"rbkim1990/reddit-nlp-project","sub_path":"notebooks/04.A - Modeling with Random Forests.ipynb","file_name":"04.A - Modeling with Random Forests.ipynb","file_ext":"py","file_size_in_byte":6329,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"82"} +{"seq_id":"31233707969","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# +\nfrom apiclient.discovery import build\n\napi_key = \"AIzaSyC4wU8gLZPxsmzk-9F5TW6DA7tazqn-xxo\"\n\nyoutube = build('youtube', 'v3', developerKey=api_key)\n# -\n\n# # Learning to use API\n\ninitialSearch = youtube.search().list(q=\"dotadoya\", part=\"snippet\", type=\"video\")\n#creates a search query with a specific keyword, and searches for only videos\nresults = initialSearch.execute()\n#executes query\n\nresults\n\nfor item in results['items']:\n print(item['snippet']['title'])\n#prints title of each YouTube video\n\ncommentsOnVideo = youtube.commentThreads().list(part=\"snippet\", maxResults=5, videoId=\"4SrFOMHYTZ4\")\n#creates a query that returns 5 comments from videoId that is specified\ncom = commentsOnVideo.execute()\n#executes query\nfor item in com['items']:\n print(item['snippet']['topLevelComment']['snippet']['textOriginal'])\n #prints only the top-level comments from a comment thread\n\nratingsOnVideo = youtube.videos().list(part=\"statistics\", id=\"sExkreoldwA\")\n#creates a query that returns only the statistics of a certain video\nratings = ratingsOnVideo.execute()\n\nratings\n\nlikeNum = float(ratings['items'][0]['statistics']['likeCount'])\n#gets total likes from a video\ndislikeNum = float(ratings['items'][0]['statistics']['dislikeCount'])\n#gets total dislikes from a video\nlikeDislikeRatio = likeNum/dislikeNum\n#returns like : dislike ratio\nprint(likeDislikeRatio)\n\n# +\nvideosIDList = []\n\nfor i in range(0, len(results['items'])):\n videosIDList.append(results['items'][i]['id']['videoId'])\n\nvideosIDList\n\n# +\nvideosComments = []\n\nfor vidId in videosIDList:\n commentsOnVideos = youtube.commentThreads().list(part=\"snippet\", maxResults=5, videoId=vidId)\n comms = commentsOnVideos.execute()\n \n for comment in comms['items']:\n videosComments.append(str(comment['snippet']['topLevelComment']['snippet']['textOriginal']))\n\nvideosComments\n# -\n\nlen(videosComments)\n\n# +\nlikeDislikeRatioList = []\n\nfor vidId in videosIDList:\n ratingsFromVideo = youtube.videos().list(part=\"statistics\", id=vidId)\n ratingsOfVideos = ratingsFromVideo.execute()\n likeNumber = float(ratingsOfVideos['items'][0]['statistics']['likeCount'])\n dislikeNumber = float(ratingsOfVideos['items'][0]['statistics']['dislikeCount'])\n likeDislikeRatioList.append(likeNumber/dislikeNumber)\n\nlikeDislikeRatioList\n\n# +\nrelatedVideos = youtube.search().list(relatedToVideoId=\"4SrFOMHYTZ4\", type=\"video\", part=\"snippet\", maxResults=10)\n#finds 10 videos which are related to this specific video\nvideosNetwork = relatedVideos.execute()\n\nfor item in videosNetwork['items']:\n print(\"Video Title: \", item['snippet']['title'], \" Video ID: \", item['id']['videoId'])\n #returns video title and ID\n# -\n\n# # Using API to search for RSL Videos\n\nRSLPlaylist = youtube.playlistItems().list(part=\"snippet\", maxResults=20, playlistId=\"PLKsMVIY2OJRPVWbWjH05cxG1CB0cbP_uv\")\n#collects all the videos in the Raid Shadow Legends 'Commercials' playlist\nRSLPlaylist_ = RSLPlaylist.execute()\n\nRSLPlaylist_\n\nRSLPlaylist_['items'][0]\n\n# +\nRSLVideoId = []\nRSLVideoName = []\n\nfor i in range(0, len(RSLPlaylist_['items'])):\n RSLVideoId.append(RSLPlaylist_['items'][i]['snippet']['resourceId']['videoId'])\n RSLVideoName.append(RSLPlaylist_['items'][i]['snippet']['title'])\n#adds ID of videos in playlist to the RSLVideoId list, and names of videos in playlist to the RSLVideoName\n\n# +\nVideosRelatedToRSL = []\n#list to hold videos related to RSL adverts\n\nfor RSLVideoID_ in RSLVideoId:\n RSLRelated = youtube.search().list(relatedToVideoId=RSLVideoID_, type=\"video\", part=\"snippet\", maxResults=20)\n RSLRelated_ = RSLRelated.execute()\n #for each video, return 20 videos that are related to it\n \n for item in RSLRelated_['items']:\n VideosRelatedToRSL.append((RSLVideoID_, item['id']['videoId']))\n #adds seed video and related videos to list\n\n# +\nVideosRelatedToRSL_Names = []\n\nfor RSLVideoName_ in RSLVideoName:\n for item in RSLRelated_['items']:\n VideosRelatedToRSL_Names.append((RSLVideoName_, item['snippet']['title']))\n\nVideosRelatedToRSL_Names\n# -\n\nVideosRelatedToRSL[:19]\n\nwith open('Related Videos/RSLRelatedVidsTitles.csv', 'w', newline='', encoding='utf-8') as file:\n writer = csv.writer(file)\n writer.writerows(VideosRelatedToRSL_Names)\n\nwith open('Related Videos/RSLRelatedVidsIDs.csv', 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerows(VideosRelatedToRSL)\n #saves list of related videos to a csv file\n #each row has the seed video and then the video that is related to it\n\n# +\nRSLComments = []\n#list to hold all comments\n\nfor RSLVideoId_ in RSLVideoId:\n RSLComms = youtube.commentThreads().list(part=\"snippet\", maxResults=100, videoId=RSLVideoId_)\n RSLComms_ = RSLComms.execute()\n #for each video, return 100 comments\n \n for comment in RSLComms_['items']:\n RSLComments.append(comment['snippet']['topLevelComment']['snippet']['textOriginal'])\n #add each comment to the list\n# -\n\nwith open('RSLVidsComments.csv', 'w', newline='', encoding=\"utf-8\") as file:\n writer = csv.writer(file)\n writer.writerows(RSLComments)\n #save comments to a csv file\n\n# +\nlikesNumber = []\ndislikesNumber = []\n#lists to hold likes and dislikes numbers\n\nfor AdID in RSLVideoId:\n ratingsFromAd = youtube.videos().list(part=\"statistics\", id=AdID)\n ratings_ = ratingsFromAd.execute()\n likesNumber.append(int(ratings_['items'][0]['statistics']['likeCount']))\n dislikesNumber.append(int(ratings_['items'][0]['statistics']['dislikeCount']))\n #for each video, add the number of likes/dislikes to relevant list\n\n# +\ny_pos = np.arange(len(RSLVideoId))\n\n\nlikesBar = plt.barh(y_pos, likesNumber, alpha=0.4, color='g', label='Likes')\ndislikesBar = plt.barh(y_pos, dislikesNumber, alpha=0.7, color='b', label='Dislikes')\n\nplt.yticks(y_pos, RSLVideoName)\nplt.title(\"Number of Likes/Dislikes for Each RSL Commercial\")\nplt.legend()\nplt.show()\n#plots the like/dislike splits into a graph for each video\n","repo_name":"jabirhiirad/dissertation-proj","sub_path":"Code/YouTubeAPIandTwint/.ipynb_checkpoints/RSLYouTubeScrape-checkpoint.ipynb","file_name":"RSLYouTubeScrape-checkpoint.ipynb","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"86"} +{"seq_id":"5999428604","text":"# +\n#task 1\nimport numpy as np\nbugs=[]\nwith open(\"input_day24.txt\",\"r\") as file:\n\n fileLines=file.readlines()\n for j,line in enumerate(fileLines):\n for i,e in enumerate(line[:-1]):\n if e == '#':\n bugs.append((j,i))\n \nprint(len(bugs))\n\ndef getOffsetFromDirection(direction):\n if direction == 1:\n return np.array([-1,0])\n elif direction == 2:\n return np.array([0,1])\n elif direction == 3:\n return np.array([1,0])\n elif direction == 4:\n return np.array([0,-1])\n else:\n return 0\n\ndef getNumberOfAdjacentBugs(bugs,j,i):\n num = 0\n #print(bugs,j,i)\n for direction in range(1,5):\n index = np.array([j,i]) + getOffsetFromDirection(direction)\n #print(index)\n if tuple(index) in bugs:\n num += 1\n return num\n\ndef visualize(bugs):\n outputStr = ''\n for j in range(0,5):\n for i in range(0,5):\n if (j,i) in bugs:\n outputStr += '#'\n else:\n outputStr += '.'\n outputStr += '\\n'\n print(outputStr)\n\ndef timestep(bugs):\n #print(bugs)\n newBugs=[]\n for j in range(0,5):\n for i in range(0,5):\n isBug = False\n if (j,i) in bugs:\n isBug = True\n numAdjacentBugs = getNumberOfAdjacentBugs(bugs,j,i)\n if isBug:\n if numAdjacentBugs == 1:\n newBugs.append((j,i))\n else:\n if numAdjacentBugs == 1 or numAdjacentBugs == 2:\n newBugs.append((j,i))\n return newBugs\n \ndef runUntilRepeatedPopulation(bugs):\n bugs.sort()\n history=[bugs]\n t = 1\n while True:\n print(\"Timestep: \", t)\n newBugs = timestep(history[-1])\n newBugs.sort()\n \n #visualize(newBugs)\n\n for b in history:\n if b == newBugs:\n print(\"Found former population!\")\n return newBugs\n \n history.append(newBugs)\n t+=1\n \nrepeatedPopulation=runUntilRepeatedPopulation(bugs)\n\nprint(repeatedPopulation)\n\ndef getRating(population):\n rating=0\n for b in population:\n index = b[0] * 5 + b[1]\n rating += 2**index\n return rating\nprint(\"Biodiversity rating: \", getRating(repeatedPopulation))\n\n# +\n#task 2\nimport numpy as np\nbugs=[]\nwith open(\"input_day24.txt\",\"r\") as file:\n\n fileLines=file.readlines()\n for j,line in enumerate(fileLines):\n for i,e in enumerate(line[:-1]):\n if e == '#':\n bugs.append((j,i))\n \n\ndef getOffsetFromDirection(direction):\n if direction == 1:\n return np.array([-1,0])\n elif direction == 2:\n return np.array([0,1])\n elif direction == 3:\n return np.array([1,0])\n elif direction == 4:\n return np.array([0,-1])\n else:\n return 0\n\ndef getNumberOfAdjacentBugs(population,level,j,i):\n if j == 2 and i == 2:\n return 0\n num = 0\n #print(population,level,j,i)\n for direction in range(1,5):\n index = np.array([j,i]) + getOffsetFromDirection(direction)\n #print(index)\n # check current level\n if tuple(index) in population[level]:\n num += 1\n # check lower level if on boarder\n if level != min(*population.keys()):\n if index[0] == -1 and (1,2) in population[level-1]:\n num+=1\n if index[0] == 5 and (3,2) in population[level-1]:\n num+=1\n if index[1] == -1 and (2,1) in population[level-1]:\n num+=1\n if index[1] == 5 and (2,3) in population[level-1]:\n num+=1\n # check higher level if close to center\n if level != max(*population.keys()):\n if tuple(index) == (2,2):\n if (j,i) == (1,2):\n for iRec in range(0,5):\n if (0,iRec) in population[level+1]:\n num+=1\n if (j,i) == (3,2):\n for iRec in range(0,5):\n if (4,iRec) in population[level+1]:\n num+=1\n if (j,i) == (2,1):\n for jRec in range(0,5):\n if (jRec,0) in population[level+1]:\n num+=1\n if (j,i) == (2,3):\n for jRec in range(0,5):\n if (jRec,4) in population[level+1]:\n num+=1\n \n return num\n\ndef visualize(population):\n for level in population:\n outputStr = 'Depth '+str(level)+'\\n'\n for j in range(0,5):\n for i in range(0,5):\n if (j,i) in population[level]:\n outputStr += '#'\n elif (j,i) == (2,2):\n outputStr += '?'\n else:\n outputStr += '.'\n outputStr += '\\n'\n print(outputStr)\n\ndef numberOfBugsPerLevel(population):\n numBugs={}\n for level in population:\n numBugs[level]= len(population[level])\n return numBugs\n\ndef addEntryToPopulation(population,level,j,i):\n if level in population:\n population[level].append((j,i))\n else:\n population[level] = [(j,i)]\n\ndef timestep(population):\n #print(bugs)\n newPopulation={}\n numBugsPerLevel=numberOfBugsPerLevel(population)\n \n # check if new level has to be added\n levelRange=[*numBugsPerLevel.keys()]\n minLevel = min(levelRange)\n maxLevel = max(levelRange)\n if numBugsPerLevel[minLevel] != 0:\n minLevel -= 1\n population[minLevel] = []\n if numBugsPerLevel[maxLevel] != 0:\n maxLevel += 1\n population[maxLevel] = []\n #print(population)\n for level in range(minLevel,maxLevel+1):\n newPopulation[level]=[]\n for j in range(0,5):\n for i in range(0,5):\n if (j,i) == (2,2):\n continue\n isBug = False\n if (j,i) in population[level]:\n isBug = True\n numAdjacentBugs = getNumberOfAdjacentBugs(population,level,j,i)\n #print(level,j,i,\" -> \", isBug, numAdjacentBugs)\n if isBug:\n if numAdjacentBugs == 1:\n addEntryToPopulation(newPopulation,level,j,i)\n else:\n if numAdjacentBugs == 1 or numAdjacentBugs == 2:\n addEntryToPopulation(newPopulation,level,j,i)\n #print(\"->\",newPopulation)\n return newPopulation\n \ndef runTimesteps(bugs,timesteps):\n population={0: bugs}\n for t in range(0,timesteps):\n print(\"Timestep: \", t)\n visualize(population)\n newPopulation = timestep(population)\n population,newPopulation = newPopulation,_\n return population\n\npop = runTimesteps(bugs,200)\nvisualize(pop)\nnumBugPerLevel=numberOfBugsPerLevel(pop)\nnumBugs = sum(numBugPerLevel[l] for l in numBugPerLevel)\nprint(numBugs)\n# -\n\n\n","repo_name":"chret/adventOfCode","sub_path":"2019/Day24.ipynb","file_name":"Day24.ipynb","file_ext":"py","file_size_in_byte":7039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"86"} +{"seq_id":"70769036445","text":"import numpy as np\nimport pandas as pd\n\n# +\ndf = pd.read_csv(\"data.csv\")\ndf.columns = ['Date','M2','M1']\ndf['Date'] = df['Date'].astype(np.datetime64)\n\n# 'M2g','M1g','M1g-M2g'\ndf.insert(3,'M2g',None)\ndf.insert(4,'M1g',None)\ndf.insert(5,'M1g-M2g',None)\ndf = df.set_index('Date')\n\ndf['M2g'] = df['M2'].pct_change(periods=12)\ndf['M1g'] = df['M1'].pct_change(periods=12)\ndf['M1g-M2g'] = df['M1g'] - df['M2g']\n# -\n\ndf.head()\n\nfor index in df.index:\n print (index, df.loc[index].values[0], df.loc[index].values[1], \n df.loc[index].values[2], df.loc[index].values[3])\n\n# +\n# %matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport matplotlib.pyplot as plt\nfigsize(20, 8)\nplt.style.use('bmh')\n# plt.style.use('ggplot')\n\nax1 = df['M2g'].plot(kind='line')\nax2 = df['M1g'].plot(kind='line')\nax3 = df['M1g-M2g'].plot(kind='line')\nplt.title(\"Credit Supply\")\nplt.legend()\n\nplt.savefig('creditSupply.png')\nplt.show()\n# -\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"goldman99999/moneysupply-mvc","sub_path":".ipynb_checkpoints/CreditSupply-checkpoint.ipynb","file_name":"CreditSupply-checkpoint.ipynb","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"86"} +{"seq_id":"21482094534","text":"f=open(\"count_2w.txt\",\"r\")\nlines=f.readlines\n\nmini=lines[:10]\n\nmini[0]\n\nmini[0].split()\n\n# +\nmini_list = []\nfor m in lines:\n (w1,w2,count)=m.split()\n count = int(count)\n mini_list.append(((w1,w2),count))\n\n \n# -\n\nmini_list\n\nmini_list[0]\n\nf=open(\"goog2w_list.txt\",\"r\")\nlines=f.readlines\n\n\n","repo_name":"karan1015/nlp-lab","sub_path":"NLP-LAB-02.ipynb","file_name":"NLP-LAB-02.ipynb","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"74"} +{"seq_id":"13949938361","text":"#\n# Project depth map as point cloud\n\n# +\nimport numpy as np\nimport plotly.graph_objects as go\nimport imageio\nimport cv2\ndef project_image(image_path):\n # Load the image using imageio\n image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n image = cv2.imread(image_path, as_gray=True)\n \n # Normalize the image pixel values between 0 and 1\n image = image.astype(np.float32) / 255.0\n \n # Get the shape of the image\n height, width = image.shape\n \n # Create a grid of x, y coordinates\n x = np.arange(width)\n y = np.arange(height)\n x_grid, y_grid = np.meshgrid(x, y)\n \n # Define the 3D surface data\n surface = go.Surface(\n x=x_grid,\n y=y_grid,\n z=image,\n colorscale='gray',\n showscale=False\n )\n \n # Create the figure layout\n layout = go.Layout(\n scene=dict(\n aspectmode='data',\n xaxis=dict(title='X'),\n yaxis=dict(title='Y'),\n zaxis=dict(title='Intensity')\n )\n )\n \n # Create the figure\n fig = go.Figure(data=[surface], layout=layout)\n \n # Show the figure\n fig.show()\n\n# Provide the path to your image file\nimage_path = 'dataset\\preprocessing\\BRICK\\IMAGES\\P_20230605_181851.jpg'\n\n# Call the function to project the image\nproject_image(image_path)\n\n# -\n\n\n\n# +\n\"\"\"\nI forgot what this does, but hey someone else can figure it out\n\"\"\"\nimport numpy as np\nimport plotly.graph_objects as go\nimport skimage.io as sio\nimport cv2\n\nx = np.linspace(-2,2, 128)\nx, z = np.meshgrid(x,x)\ny = np.sin(x**2*z)\n\nfig = go.Figure(go.Surface(x=x, y=y, z=z,\n colorscale='RdBu', \n showscale=False))\n\nimage = cv2.imread(\"dataset\\preprocessing\\BRICK\\IMAGES\\P_20230605_181851.jpg\", cv2.IMREAD_COLOR) \nimage = cv2.resize(image, (1024, 1024))\nprint(image.shape)\nimg = image[:,:, 1] \n\nY = 0.5 * np.ones(y.shape)\n\nfig.add_surface(x=x, y=Y, z=z, \n surfacecolor=np.flipud(img), \n colorscale='gray', \n showscale=False)\nfig.update_layout(width=image.shape[0], height=image.shape[1], \n scene_camera_eye_z=0.6, \n scene_aspectratio=dict(x=0.9, y=1, z=1))\nfig.show()\n","repo_name":"dreamsproxy/The-Construct-Project","sub_path":"LiquidScan/examples/code/plot_depth.ipynb","file_name":"plot_depth.ipynb","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"74"} +{"seq_id":"37561230593","text":"import pandas as pd\nimport dash\nimport numpy as np\nimport plotly.express as px\nimport pandas_profiling\n\n# # Import the csv file\n\nimport pandas_profiling\n\ndf=pd.read_csv('BPD_Part_1_Victim_Based_Crime_Data.csv')\n\n# # Data Integrity Check\n\n# generating the EDA \ndf.profile_report(title='Pandas Profiling Report').to_file(output_file=\"eda.html\")\n\n# * Duplicates of records\n# * High correlation between some variables\n# * Missing values on two variables\n\n# ## Grouping the records to keep the number of incidents but drop duplicates\n\ndf_nodup=df.fillna('')\\\n .groupby(df.columns.tolist()).apply(len)\\\n .rename('group_count')\\\n .reset_index()\\\n .replace('',np.nan)\\\n .sort_values(by = ['group_count'], ascending = False)\n\n# ## ~~ Convert the Data/Time to proper time format~~\n\n# +\n# df_nodup.CrimeDate=pd.to_datetime(df_nodup.CrimeDate)\n# df_nodup.CrimeTime=pd.to_timedelta(df_nodup.CrimeTime)\n# df_nodup.CrimeTime_dt=pd.to_datetime(df_nodup.CrimeTime)\n# -\n\n# ## Handling missing values\n\ndf_nodup.info()\n\ndf_nodup[df_nodup['vri_name1'].notna()].head(10)\n\n# df_nodup[df_nodup['vri_name1'].notna()][['vri_name1','District']].\npd.pivot_table(index=['vri_name1'], columns=['District'], data=df_nodup[df_nodup['vri_name1'].notna()][['vri_name1','District','Total Incidents']], aggfunc=np.sum)\n\ndf_nodup=df_nodup.drop(columns=['Location 1','vri_name1'])\n\n# ## Value Consistency\n\ndf_nodup.CrimeCode.unique()\n\ndf_nodup.Description.unique()\n\n# +\n#Before Mapping\n# -\n\ndf_nodup['Inside/Outside'].unique()\n\ndf_nodup['Inside/Outside']=df_nodup['Inside/Outside'].map({'O':'Outside','I':'Inside'})\n\n# +\n#After Mapping\n# -\n\ndf_nodup['Inside/Outside'].unique()\n\n\n\n# +\n# cleaning posts\n# -\n\ndf_nodup.loc[df_nodup['Post'].notna(),'Post']=df_nodup[df_nodup['Post'].notna()]['Post'].apply(lambda x: str(x).replace('.0',''))\n\ndf_nodup['Post'].unique()\n\n\n\ndf_nodup.to_csv('cleaned_df.csv',index=False)\n\n\n\n\n\n\n\ndf_nodup['Year']=df_nodup.CrimeDate.dt.year\n\ndf_nodup['Month']=df_nodup.CrimeDate.dt.month\n\ndf_nodup['Day']=df_nodup.CrimeDate.dt.day\n\ndf_nodup['DayofWeek']=df_nodup.CrimeDate.dt.dayofweek\n\ndf_nodup.CrimeTime_dt.dt.hour\n\ndf_nodup.to_csv('nodup.csv')\n\n\n","repo_name":"ReichYang/rdsdash","sub_path":".ipynb_checkpoints/data_prepro-checkpoint.ipynb","file_name":"data_prepro-checkpoint.ipynb","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"74"} +{"seq_id":"18194785336","text":"# # 08. Train a model\n\n# \n\nimport sys\nsys.version\n\n# +\nfrom azure.ai.formrecognizer import FormTrainingClient\nfrom azure.core.credentials import AzureKeyCredential\n\nendpoint = \"tobereplaced\"\ncredential = AzureKeyCredential(\"key\")\n\nform_training_client = FormTrainingClient(endpoint, credential)\n\ncontainer_sas_url = \"tobereplaced\"\n# -\n\n# ## Model Training\n\npoller = form_training_client.begin_training(\n container_sas_url, use_training_labels=False, model_name=\"my Azure Form Recognizer model\"\n)\nmodel = poller.result()\n\n# ## Model results\n\n# +\n# Custom model information\nprint(\"Model ID: {}\".format(model.model_id))\nprint(\"Model name: {}\".format(model.model_name))\nprint(\"Is composed model?: {}\".format(model.properties.is_composed_model))\nprint(\"Status: {}\".format(model.status))\nprint()\nprint(\"Training started on: {}\".format(model.training_started_on))\nprint(\"Training completed on: {}\".format(model.training_completed_on))\n\nprint(\"\\nRecognized fields:\")\nfor submodel in model.submodels:\n print(\n \"The submodel with form type '{}' and model ID '{}' has recognized the following fields: {}\".format(\n submodel.form_type, submodel.model_id,\n \", \".join(\n [\n field.label if field.label else name\n for name, field in submodel.fields.items()\n ]\n ),\n )\n )\n# -\n\n# Training result information\nfor doc in model.training_documents:\n print(\"Document name: {}\".format(doc.name))\n print(\"Document status: {}\".format(doc.status))\n print(\"Document page count: {}\".format(doc.page_count))\n print(\"Document errors: {}\".format(doc.errors))\n\n\n","repo_name":"retkowsky/Azure_Form_Recognizer","sub_path":"08. Train a model.ipynb","file_name":"08. Train a model.ipynb","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"74"} +{"seq_id":"11759673263","text":"import pandas as pd\ndf=pd.read_csv(\"wheather_data\")\n\ntype(df.day[0]) # Here all which is written in day column nothing but a string \n\ndf\n\ndf1=df.fillna(0) # here it fill NAN or missing value with 0 in whole data frame\ndf1\n\ndf1=df.fillna({\n 'temperature':'0', # by using dicsnary we can fill missing value accordingly\n 'windspeed':'0', # Let if we fill 'missing event' column with 0 then here is no\n 'event':'No event' # significance of 0 event so fill accordngly with 'fillna'\n})\ndf1\n\ndf1=df.fillna(method=\"ffill\") # If we observe care fully there is no significance\ndf1 # of 0 temperature and 0 wind speed so here \"ffill\" \n # method fill the missing value by thier previous day value\n # similarly \"bfill\"fill the missing value by thier next day value\n\ndf1=df.fillna(method=\"bfill\") # it copy the next day value and fill to missing box\ndf1\n\ndf1=df.fillna(method=\"bfill\",axis=\"columns\") # by default it copy previous data by using rows but if you want to copy the data \ndf1 # by using columns then we can specify \"axis='colums'\"111\n\ndf=pd.read_csv(\"wheather_data\",parse_dates=[\"day\"]) # Here parse_dates makes day string into actual date format \ndf\n\ndf.set_index('day',inplace=True) # To set day as index\ndf\n\ndf1=df.interpolate() # By using interpulate it some how come with real guess\ndf1 # by default it use linear interpulation to guess the value it come with mid value of previous and next value \n\ndf1=df.interpolate(method=\"time\") #if we want to guess value by dates then use\"time\", if we obseve carefully for temperture date\ndf1 # 2017-01-05 is more clousre to 4 so guess should come clousre to 28 such as 29 not 30\n\ndf\n\ndf1=df.dropna() # In some situation if we have to drop all data which have at least one missing value or 'NAN' value\n # then use dropna\ndf1\n\ndf1=df.dropna(thresh=1) # here threshold value specify that if we have at least one real data or at least one non NAN value \ndf1 # the keep the rows \n\ndf1=df.dropna(thresh=2) # if we have at least 2 non NAN value keep the rows \ndf1\n\ndf\n\n# +\n# how to fill missing date in data frame \n#In our data we have missing data of 2nd and 3rd January\n# so using \"date_range\" we can insert dates in our data\n\ndt=pd.date_range(\"01-01-2017\",\"01-12-2017\")\nindx=pd.DatetimeIndex(dt)\ndf1=df1.reindex(indx)\n\n# -\n\ndf1\n\n\n","repo_name":"yadavlav7978/Machine-Learning","sub_path":"5Handle Missing Data fillna dropna interpolate/5Handle Missing Data fillna dropna interpolate.ipynb","file_name":"5Handle Missing Data fillna dropna interpolate.ipynb","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"74"} +{"seq_id":"25496747716","text":"import pandas as pd\nimport warnings\nimport numpy as np\nwarnings.filterwarnings('ignore')\nimport time\nfrom tqdm import tqdm\nimport threading\n\ncoupon = pd.read_csv(r'/Users/andyhsu/Documents/GitHub/台灣代駕BMS/優惠券分析/input/coupon.csv')\ndata = pd.read_csv(r'/Users/andyhsu/Documents/GitHub/台灣代駕BMS/優惠券分析/input/前處理完資料.csv')\n\ncoupon.head()\n\ndata_merge = data.merge(coupon,left_on='id',right_on='Task_ID',how='left')\n\ndata_merge[['UserCreditValue','Coupon_Title']]\n\n# # 有29076筆資料,雖然沒有使用優惠券但UserCreditValue仍不為0\n\n優惠券_無資料_但有折扣 = data_merge[(data_merge['UserCreditValue']!=0) & ~(np.isnan(data_merge['UserCreditValue'])) & (pd.isna(data_merge['Coupon_Title']))]\n\n\ndef 折扣資料補齊(UserCreditValue,Coupon_Title):\n if UserCreditValue !=0 and np.isnan(UserCreditValue) == False and pd.isna(Coupon_Title):\n return str(round(UserCreditValue,0)).replace('.0','') + '元折價券'\n else:\n pass\n\n\ndata_merge['Coupon_Title_補'] = data_merge.apply(lambda x:折扣資料補齊(x['UserCreditValue'],x['Coupon_Title']),axis=1)\n\ndata_merge\n\nfor x in tqdm(range(len(data_merge))):\n if pd.isna(data_merge.iloc[x,-2]) and data_merge.iloc[x,-1] != None:\n data_merge.iloc[x,-2] = data_merge.iloc[x,-1]\n\ndata_merge = data_merge.drop(columns=['Coupon_Title_補'])\n\ndata_merge.to_csv('/Users/andyhsu/Documents/GitHub/台灣代駕BMS/優惠券分析/output/優惠券合併補齊資料.csv',encoding='utf-8-sig',index=False,header=True)\n\n有優惠券_缺折扣金額 = data_merge[((data_merge['UserCreditValue']==0) | np.isnan(data_merge['UserCreditValue'])) & ~(pd.isna(data_merge['Coupon_Title']))]\n\n\n","repo_name":"andyHSU-DS/Dcard_Portfolio","sub_path":"台灣代駕 Coupon Analysis/優惠券分析_整理/優惠券分析_整理.ipynb","file_name":"優惠券分析_整理.ipynb","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"86"} +{"seq_id":"23070399879","text":"# + [markdown] colab_type=\"text\" id=\"KdUFcDsdzRyw\"\n# # Clonamos el repositorio para obtener los dataSet\n\n# + colab_type=\"code\" id=\"mHReFf3_y9ms\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 153} outputId=\"3fa17b53-daae-435a-aad3-5c1148b6b889\"\n# !git clone https://github.com/joanby/tensorflow.git\n\n# + [markdown] colab_type=\"text\" id=\"vNKZXgtKzU2x\"\n# # Damos acceso a nuestro Drive\n\n# + colab_type=\"code\" id=\"5gu7KWnzzUQ0\" colab={}\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + [markdown] colab_type=\"text\" id=\"1gUxIkHWzfHV\"\n# # Test it\n\n# + colab_type=\"code\" id=\"mIQt3jBMzYRE\" colab={}\n# !ls '/content/drive/My Drive' \n\n# + [markdown] colab_type=\"text\" id=\"mHsK36uN0XB-\"\n# # Google colab tools\n\n# + colab_type=\"code\" id=\"kTzwfUPWzrm4\" colab={}\nfrom google.colab import files # Para manejar los archivos y, por ejemplo, exportar a su navegador\nimport glob # Para manejar los archivos y, por ejemplo, exportar a su navegador\nfrom google.colab import drive # Montar tu Google drive\n\n# + [markdown] id=\"yQQ8nLiMY6wM\" colab_type=\"text\"\n# ##Especificando la versión de TensorFlow\n#\n# Ejecutando \"importar tensorflow\" importará la versión por defecto (actualmente 2.x). Puedes usar la 1.x ejecutando una celda con la \"versión mágica de tensorflow\" **antes de ejecutar \"importar tensorflow\".\n#\n# ### Si no funciona hacer el pip install\n#\n\n# + id=\"1j---G3ZY6wN\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"f363a778-c70c-4292-b3c6-5024ef8c2657\"\n# #!pip install tensorflow==1.14\n# %tensorflow_version 1.x\n\n# + [markdown] id=\"S-OIfuWLujbt\" colab_type=\"text\"\n# # Importar Tensorflow\n\n# + id=\"OPSus73fumtP\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"9d80de70-b52c-4436-d10e-c7b7b6fc078e\"\nimport tensorflow as tf\nprint(tf.__version__)\nimport matplotlib.pyplot as plt\n\n# + id=\"VQheSGsEBdD3\" colab_type=\"code\" colab={}\nsession = tf.Session()\n\n# + [markdown] id=\"qzlBylUEmQJ0\" colab_type=\"text\"\n# # Puertas lógicas\n\n# + [markdown] id=\"Yn7x1RnM9z1n\" colab_type=\"text\"\n# $$f(x) = a\\cdot x$$\n\n# + id=\"bpp2MFme9yi_\" colab_type=\"code\" colab={}\na = tf.Variable(tf.constant(4.0))\nx_val = 5.0\nx_data =tf.placeholder(dtype=tf.float32)\n\n# + id=\"FtAMNEmv91ht\" colab_type=\"code\" colab={}\nmultiplication = tf.multiply(a,x_data)\n\n# + [markdown] id=\"5xAIc9Hr93to\" colab_type=\"text\"\n# $$loss = (a\\cdot x - target)^2$$\n\n# + id=\"zMXBzH1892dr\" colab_type=\"code\" colab={}\nloss = tf.square(tf.subtract(multiplication, 50.0))## L2\n\n# + id=\"ZCLFhO3b95Nq\" colab_type=\"code\" colab={}\ninit = tf.global_variables_initializer()\nsession.run(init)\n\n# + id=\"KGJySYc596LB\" colab_type=\"code\" colab={}\nmy_optim = tf.train.GradientDescentOptimizer(0.01)\ntrain_step = my_optim.minimize(loss)\n\n# + id=\"5DnrbxPg97OT\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 204} outputId=\"64907137-c029-45f4-eadc-c51c8734fa51\"\nprint(\"Optimización del valor de a para conseguir a*5 = 50\")\nfor i in range(10):\n session.run(train_step, feed_dict={x_data: x_val})\n a_val = session.run(a)\n mult_out = session.run(multiplication, feed_dict={x_data:x_val})\n print(str(a_val)+\" x \"+str(x_val)+\" = \"+str(mult_out))\n\n# + [markdown] id=\"k6Kx3tYr99mv\" colab_type=\"text\"\n# $$f(x) = a\\cdot x + b $$\n\n# + [markdown] id=\"OJVVXkij-A6o\" colab_type=\"text\"\n# ¿Qué tiene que valer $a$ y $b$ para que $f(5) = 50.0$?\n\n# + id=\"rzga25Ly98SK\" colab_type=\"code\" colab={}\nfrom tensorflow.python.framework import ops \nops.reset_default_graph()\n\n# + id=\"eXElbge0-Cg-\" colab_type=\"code\" colab={}\nsession = tf.Session()\n\n# + id=\"GNj1_nT6-Dc2\" colab_type=\"code\" colab={}\na = tf.Variable(tf.constant(5.0))\nb = tf.Variable(tf.constant(5.0))\nx_val = 5.0\nx_data = tf.placeholder(dtype = tf.float32)\n\n# + id=\"QxtZUqFe-Emp\" colab_type=\"code\" colab={}\nmult_add = tf.add(tf.multiply(a, x_data), b)\n\n# + id=\"2xLMTZg0-Fk2\" colab_type=\"code\" colab={}\nloss = tf.square(tf.subtract(mult_add, 50.0))\n\n# + id=\"d-aHpuhp-Goe\" colab_type=\"code\" colab={}\nmy_optim = tf.train.GradientDescentOptimizer(0.01)\ntrain_step = my_optim.minimize(loss)\n\n# + id=\"9S9xpUu7-HdP\" colab_type=\"code\" colab={}\ninit = tf.global_variables_initializer()\nsession.run(init)\n\n# + id=\"m33Npxx1-IRx\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 272} outputId=\"197c98db-060b-49d0-f3d2-750e15f1850f\"\nfor i in range(15):\n session.run(train_step, feed_dict={x_data : x_val})\n a_val, b_val = (session.run(a), session.run(b))\n result = session.run(mult_add, feed_dict={x_data:x_val})\n print(str(a_val)+\" x \"+str(x_val)+\" + \"+str(b_val)+ \" = \"+str(result))\n","repo_name":"joanby/tensorflow","sub_path":"scripts/tema07/01_operational_gates_colab.ipynb","file_name":"01_operational_gates_colab.ipynb","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-jupyter-script","pt":"86"} +{"seq_id":"5116097212","text":"# +\n# import modules\nimport librosa\nimport librosa.display\nimport IPython.display as ipd\nimport matplotlib.pyplot as plt\nimport scipy.signal\nfrom scipy import stats\nfrom scipy.io import wavfile\nimport numpy as np\nimport math\nfrom sklearn.metrics import pairwise_distances\n\nbandLimits = [0, 200, 400, 800, 1600, 3200, 6400] \ncombFilterPulses = 8\nminBpm = 60\nmaxBpm = 240\n\n# +\ny, sr = librosa.load('Data/genres_original/pop/pop.00001.wav', offset=10)\ny_comp, sr = librosa.load('Data/genres_original/pop/pop.00001.wav', offset=20) \n\n# y, sr = librosa.load('RileyKaraoke.wav', offset=20, duration=20)\n# y_comp, sr = librosa.load('RileyKaraoke.wav', offset=10, duration=20) \n\n# +\ntempo, beat_times = librosa.beat.beat_track(y, sr=sr, units='time')\ntempo, comp_beat_times = librosa.beat.beat_track(y_comp, sr=sr, units='time')\n\nhop_length = 512\nframe_length = 1024\n \nchroma_ref = librosa.feature.chroma_cqt(y=y, sr=sr, hop_length=hop_length)\nchroma_comp = librosa.feature.chroma_cqt(y=y_comp, sr=sr, hop_length=hop_length)\n\nmfcc_ref = librosa.feature.mfcc(y=y, sr=sr, hop_length=hop_length)\nmfcc_comp = librosa.feature.mfcc(y=y_comp, sr=sr, hop_length=hop_length)\n\n# Use time-delay embedding to get a cleaner recurrence matrix\nx_ref = librosa.feature.stack_memory(chroma_ref, n_steps=10, delay=3)\nx_comp = librosa.feature.stack_memory(chroma_comp, n_steps=10, delay=3)\n# -\n\n# corr = scipy.correlate(beat_times, comp_beat_times, mode='full')\n# corr = librosa.segment.cross_similarity(chroma_ref, chroma_comp, metric='cosine', mode='distance')\n# corr\ncorr = 1-pairwise_distances(mfcc_ref, metric=\"cosine\")\n \n\ndef detect_tempo(signal, accuracy: int, minBpm: int, maxBpm: int, bandsLimits, sr,\n combFilterPulses):\n n = len(signal[0])\n bands_amount = len(bandsLimits)\n dft = np.zeros([bands_amount, n], dtype=complex)\n\n if minBpm < 60:\n minBpm = 60\n\n if maxBpm > 240:\n maxBpm = 240\n\n for band in range(0, bands_amount):\n dft[band] = np.fft.fft(signal[band])\n\n maxEnergy = 0\n for bpm in range(minBpm, maxBpm, accuracy):\n this_bpm_energy = 0\n fil = np.zeros(n)\n\n filter_step = np.floor(60 / bpm * sr)\n percent_done = 100 * (bpm - minBpm) / (maxBpm - minBpm)\n print(\"%.2f\" % percent_done, \"%\")\n\n for a in range(0, combFilterPulses):\n fil[a * int(filter_step) + 1] = 1\n\n dftfil = np.fft.fft(fil)\n\n for band in range(0, bands_amount):\n x = (abs(dftfil * dft[band])) ** 2\n this_bpm_energy = this_bpm_energy + sum(x)\n\n if this_bpm_energy > maxEnergy:\n songBpm = bpm\n maxEnergy = this_bpm_energy\n\n return songBpm\n\n\n# +\n__methods = []\n \ndef detect_metre(signal, tempo: int, bandlimits, sr):\n nbands = len(bandlimits)\n\n __methods.append(__five_forth)\n __methods.append(__four_forth)\n __methods.append(__six_eigth)\n __methods.append(__three_forth)\n\n metres = {}\n for method in __methods:\n metre, metre_dft = method(tempo, sr)\n metres[metre] = metre_dft\n\n maxe = 0\n done = 0\n todo = len(metres.keys())\n for metrum in metres:\n done += 1\n percent_done = 100 * done / todo\n print(\"%.2f\" % percent_done, \"%\")\n\n e = 0\n for band in range(0, nbands):\n filt = scipy.correlate(signal[band], metres[metrum])\n f_filt = abs(np.fft.fft(filt))\n x = abs(f_filt) ** 2\n e = e + sum(x)\n\n if e > maxe:\n song_metre = metrum\n maxe = e\n\n return song_metre\n \ndef __four_forth(song_tempo: int, sampling_frequency: int):\n fil = np.zeros(int(4 * sampling_frequency * (60 / song_tempo)))\n nstep = np.floor(60 / song_tempo * sampling_frequency)\n\n value = 1 / 2\n fil[int(1 * nstep)] = 1 * value\n fil[int(3 * nstep)] = 1 * value\n\n return \"4\\\\4\", fil\n\ndef __three_forth(song_tempo: int, sampling_frequency: int):\n fil = np.zeros(int(6 * sampling_frequency * (60 / song_tempo)))\n nstep = np.floor(60 / song_tempo * sampling_frequency)\n\n value = 1 / 2\n fil[int(2 * nstep)] = 1 * value\n fil[int(5 * nstep)] = 1 * value\n\n return \"3\\\\4\", fil\n\ndef __five_forth(song_tempo: int, sampling_frequency: int):\n fil = np.zeros(int(5 * sampling_frequency * (60 / song_tempo)))\n nstep = np.floor(60 / song_tempo * sampling_frequency)\n\n value = 1 / 3\n fil[int(1 * nstep)] = 1 * value\n fil[int(3 * nstep)] = 1 * value\n fil[int(4 * nstep)] = 1 * value\n\n return \"5\\\\4\", fil\n\ndef __six_eigth(song_tempo: int, sampling_frequency: int):\n fil = np.zeros(int(3 * sampling_frequency * (60 / song_tempo)))\n nstep = np.floor((60 / song_tempo * sampling_frequency) / 2)\n\n value = 1 / 2\n fil[int(0 * nstep)] = 1 * value\n fil[int(3 * nstep)] = 1 * value\n\n return \"6\\\\8\", fil\n\n\n# -\n\nmetre = detect_metre(corr, tempo, bandLimits, sr)\nprint ('meter is', metre)\n\n\n","repo_name":"pianistprogrammer/TimeSignatureEstimator","sub_path":"correlation.ipynb","file_name":"correlation.ipynb","file_ext":"py","file_size_in_byte":5215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"86"} +{"seq_id":"23308123035","text":"# Q1. Create one variable containing following type of data:\n# (i) string\n# (ii) list\n# (iii) float\n# (iv) tuple\n#\n\n# Ans -\n# i) a = \"Hello, World!\"\n# ii) mylist = [\"apple\", \"banana\", \"cherry\"]\n# iii) float b = 67.89\n# iv) mytuple = (\"apple\", \"banana\", \"cherry\")\n#\n\n# Q2. Given are some following variables containing data:\n# (i) var1 = ‘ ‘\n# (ii) var2 = ‘[ DS , ML , Python]’\n# (iii) var3 = [ ‘DS’ , ’ML’ , ‘Python’ ]\n# (iv) var4 = 1.\n# What will be the data type of the above given variable.\n\n# ANS - i) String ii)String iii)List iv)int\n\n# Q3. Explain the use of the following operators using an example:\n# (i) /\n# (ii) %\n# (iii) //\n# (iv) **\n\n# ANS -\n# i) Division operator\n# ii) Modulo\n# iii)Floor division\n# iv) Power\n\n# +\na=5/2\nb=5%2\nc=5//2\nd=2**3\n\nprint(a,b,c,d)\n# -\n\n# Q4. Create a list of length 10 of your choice containing multiple types of data. Using for loop print the\n# element and its data type.\n\nmyList = [\"sayantan\", 10, 10.89, \"Apple\", \"Banana\", 25, \"cherry\", 55, 64, 78]\nfor i in myList:\n print(i)\n print (type(i))\n\n# Q5.Using a while loop, verify if the number A is purely divisible by number B and if so then how many\n# times it can be divisible.\n\na=int(input())\nb=int(input())\nc=0\nif a/b==0:\n while(a/b>=b and type(a/b)==int):\n c+=1\n a/=b\n c\nelse:\n print(\"not divisible\")\n\n# Q6. Create a list containing 25 int type data. Using for loop and if-else condition print if the element is\n# divisible by 3 or not.\n#\n\nl=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]\nl1=[]\nl2=[]\nfor i in l:\n if i%3==0:\n l1.append(i)\n else:\n l2.append(i)\nl1\n\n# What do you understand about mutable and immutable data types? Give examples for both showing\n# this property.\n\n# Mutable data types :-\n# Anything is said to be mutable when anything can be modified or changed. The term \"mutable\" in Python refers to an object's capacity to modify its values. These are frequently the things that hold a data collection.\n# \n# examples - \n# Lists\n# Dictionaries\n# Sets\n# User-Defined Classes (It depends on the user to define the characteristics of the classes)\n#\n# Immutable data types :-\n# Immutable refers to a state in which no change can occur over time. A Python object is referred to as immutable if we cannot change its value over time. The value of these Python objects is fixed once they are made.\n# \n# examples-\n# Numbers (Integer, Float, Complex, Decimal, Rational & Booleans)\n# Tuples\n# Strings\n# Frozen Sets\n\n\n","repo_name":"SayantanGhosh001/Deta-Science-","sub_path":"Assignment1.ipynb","file_name":"Assignment1.ipynb","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"75"} +{"seq_id":"11746112908","text":"# %matplotlib notebook\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport gym\nimport time\n\n# +\nfrom gym.envs.registration import register\n\nregister(\n id='FrozenLakeNotSlippery-v0', # make sure this is a custom name!\n entry_point='gym.envs.toy_text:FrozenLakeEnv',\n kwargs={'map_name' : '4x4', 'is_slippery': False},\n max_episode_steps=100,\n reward_threshold=.78, # optimum = .8196\n)\n# -\n\nfrom IPython.display import clear_output\n\n# +\nenv = gym.make('FrozenLakeNotSlippery-v0')\nenv.reset()\n\nfor step in range(5):\n# env.render()\n action = env.action_space.sample()\n observation, reward, done , info = env.step(action)\n time.sleep(0.02)\n clear_output(wait=True)\n if done:\n env.reset()\nenv.close()\n \n \n\n# +\naction_size = env.action_space.n\nstate_size = env.observation_space.n\n\n\nq_table = np.zeros([state_size,action_size])\n# -\n\nq_table\n\nEPOCHS = 20000 #episodes\nALPHA = 0.8 # Learning Rate\nGAMMA = 0.95 # Discount Rate\nepsilon = 1.0\nmax_epsilon = 1.0\nmin_epsilon = 0.01\ndecay_rate = 0.001\n\n\ndef epsilon_greedy_action_selection(epsilon,q_table,discrete_state):\n \n random_number = np.random.random()\n \n \n if random_number > epsilon:\n state_row = q_table[discrete_state,:]\n \n action = np.argmax(state_row)\n \n else:\n action = env.action_space.sample()\n \n return action\n\n\ndef compute_next_q_value(old_q_value,reward,next_optimal_q_value):\n return old_q_value + ALPHA * (reward + GAMMA * next_optimal_q_value - old_q_value)\n\n\ndef reduce_epsilon(epsilon,epoch):\n return min_epsilon + (max_epsilon - min_epsilon)*np.exp(-decay_rate*epoch)\n\n# +\n# reward = []\n# log_interval = 1000\n\n# for episode in range(EPOCHS):\n \n# state = env.reset()\n# done = False\n# total_reward = 0\n \n \n# while not done:\n \n# action = epsilon_greedy_action_selection(epsilon, q_table , state)\n \n# new_state , reward , done , info = env.step(action)\n \n# old_q_value = q_table[state,action]\n \n# next_optimal_q_value = np.max(q_table[new_state,:])\n \n# next_q = compute_next_q_value(old_q_value,reward,next_optimal_q_value)\n \n# q_table[state,action] = next_q\n \n# total_rewards = total_rewards + reward\n \n# state = new_state\n \n# episode += 1\n \n# epsilon = reduce_epsilon(epsilon,episode)\n \n# rewards.append(total_rewards)\n \n# if episode % log_interval ==0 :\n# print(np.sum(rewards))\n \n# env.close()\n\n# +\n# List of rewards\nrewards = []\nlog_interval = 1000\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.ion()\nfig.canvas.draw()\nepoch_plot_tracker = []\ntotal_reward_plot_tracker = []\n\n# Play 20k games\nfor episode in range(EPOCHS):\n # Reset the environment\n state = env.reset()\n done = False\n total_rewards = 0\n \n while not done:\n action = epsilon_greedy_action_selection(epsilon,q_table, state)\n\n # Take the action (a) and observe the outcome state(s') and reward (r)\n new_state, reward, done, info = env.step(action)\n\n \n # Look up current/old qtable value Q(s_t,a_t)\n old_q_value = q_table[state,action] \n\n # Get the next optimal Q-Value\n next_optimal_q_value = np.max(q_table[new_state, :]) \n\n # Compute next q value\n next_q = compute_next_q_value(old_q_value, reward, next_optimal_q_value) \n\n # Update Q Table\n q_table[state,action] = next_q\n\n \n \n total_rewards = total_rewards + reward\n \n # Our new state is state\n state = new_state\n\n \n episode += 1\n epsilon = reduce_epsilon(epsilon,episode) \n rewards.append(total_rewards)\n total_reward_plot_tracker.append(np.sum(rewards))\n epoch_plot_tracker.append(episode)\n\n\n if episode % log_interval==0:\n ax.clear()\n ax.plot(epoch_plot_tracker,total_reward_plot_tracker)\n fig.canvas.draw()\n\n\nenv.close()\n# -\n\n\n","repo_name":"harshp77/Reinforcement-Learing-Projects","sub_path":"Frozen Lake V0.ipynb","file_name":"Frozen Lake V0.ipynb","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"75"} +{"seq_id":"72386243443","text":"# # BAG-OF-WORDS (NLP) - COMPARING DIFFERENT CLASSIFICATION MODEL\n\n# ## IMPORTING THE LIBRARIES\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# ## IMPORTING THE DATASET\n\ndataset=pd.read_csv('Restaurant_Reviews.tsv',delimiter='\\t',quoting=3)\ndataset\n\n# ## CLEANING THE TEXTS \n# * REMOVING THE PUNCTUATIONS (LIKE , . ' ' etc)\n# * CONVERTING THE TEXT TO LOWER CASE\n# * REMOVING THE STOPWORDS\n# * STEMMING THE DATA\n\nimport re\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\ncorpus=[]\nfor i in range (0,1000):\n new_word=re.sub('[^a-zA-z]',' ',dataset.Review[i])\n new_word=new_word.lower()\n new_word=new_word.split()\n all_stopwords=stopwords.words('english')\n all_stopwords.remove('not')\n ps=PorterStemmer()\n new_word=[ps.stem(word) for word in new_word if not word in set(all_stopwords)]\n new_word=\" \".join(new_word)\n corpus.append(new_word)\ncorpus\n\n# # CREATING THE BAG-OF-WORDS MODEL\n# Here we are coverting the text into the vector having count of each word in the text \n\nfrom sklearn.feature_extraction.text import CountVectorizer\ncv=CountVectorizer(max_features=1500)\nx=cv.fit_transform(corpus).toarray()\ny=dataset.iloc[:,-1].values\n\nprint(x)\n\nprint(y)\n\n# ## SPLITTING THE DATASET INTO THE TRAINING SET AND TEST SET\n\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.20,random_state=0)\n\nprint('X_TRAIN')\nprint(x_train)\nprint('\\n')\nprint('X_TEST')\nprint(x_test)\nprint('\\n')\nprint('Y_TRAIN')\nprint(y_train)\nprint('\\n')\nprint('Y_TEST')\nprint(y_test)\n\n# # 1) TRAINING OUR FIRST CLASSIFICATION MODEL --> LOGISTIC REGRESSION\n\nfrom sklearn.linear_model import LogisticRegression\nclassifier1=LogisticRegression(random_state=0)\nclassifier1.fit(x_train,y_train)\n\n# ## PREDICTING THE RESULTS ON TEST SET\n\ny_pred=classifier1.predict(x_test)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1))\n\nplt.plot(y_pred,y_test,color='red')\nplt.title('Pred vs Test')\nplt.xlabel('Predicted values')\nplt.ylabel('Actual test values')\nplt.show()\n\n# ## MAKING CONFUSION MATRIX\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\ncm1=confusion_matrix(y_test,y_pred)\nprint(cm1)\naccuracy_score1=accuracy_score(y_test,y_pred)\nprint(accuracy_score1)\n\n# # 2) TRAINING OUR SECOND CLASSIFICATION MODEL --> SUPPORT VECTOR MACHINE(SVM)\n\nfrom sklearn.svm import SVC\nclassifier2=SVC(kernel='linear',random_state=0)\nclassifier2.fit(x_train,y_train)\n\n# ## PREDICTING THE RESULTS ON TEST SET\n\ny_pred=classifier2.predict(x_test)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1))\n\nplt.plot(y_pred,y_test,color='blue')\nplt.title('Pred vs Test')\nplt.xlabel('Predicted values')\nplt.ylabel('Actual test values')\nplt.show()\n\n# ## MAKING CONFUSION MATRIX\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\ncm2=confusion_matrix(y_test,y_pred)\nprint(cm2)\naccuracy_score2=accuracy_score(y_test,y_pred)\nprint(accuracy_score2)\n\n# ###
Accuracy: SVM(79%)>Logistic_Regression(77.5%)
\n\n# # 3) TRAINING OUR THIRD CLASSIFICATION MODEL --> K-NEAREST NEIGHBORS(K-NN)\n\nfrom sklearn.neighbors import KNeighborsClassifier\nclassifier3=KNeighborsClassifier(n_neighbors=10,metric='minkowski',p=2)\nclassifier3.fit(x_train,y_train)\n\n# ## PREDICTING THE RESULTS ON TEST SET\n\ny_pred=classifier3.predict(x_test)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1))\n\nplt.plot(y_pred,y_test,color='green')\nplt.title('Pred vs Test')\nplt.xlabel('Predicted values')\nplt.ylabel('Actual test values')\nplt.show()\n\n# ## MAKING CONFUSION MATRIX\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\ncm3=confusion_matrix(y_test,y_pred)\nprint(cm3)\naccuracy_score3=accuracy_score(y_test,y_pred)\nprint(accuracy_score3)\n\n# ###
Accuracy: SVM(79%)>Logistic_Regression(77.5%)>K-NN(66%)
\n\n# # 4) TRAINING OUR FOURTH CLASSIFICATION MODEL --> NAIVE BAYES\n\nfrom sklearn.naive_bayes import GaussianNB\nclassifier4=GaussianNB()\nclassifier4.fit(x_train,y_train)\n\n# ## PREDICTING THE RESULTS ON TEST SET\n\ny_pred=classifier4.predict(x_test)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1))\n\nplt.plot(y_pred,y_test,color='magenta')\nplt.title('Pred vs Test')\nplt.xlabel('Predicted values')\nplt.ylabel('Actual test values')\nplt.show()\n\n# ## MAKING CONFUSION MATRIX\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\ncm4=confusion_matrix(y_test,y_pred)\nprint(cm4)\naccuracy_score4=accuracy_score(y_test,y_pred)\nprint(accuracy_score4)\n\n# ###
Accuracy: SVM(79%)>Logistic_Regression(77.5%)>Naive Bayes(73%)>K-NN(66%)
\n\n# # 5) TRAINING OUR FIFTH CLASSIFICATION MODEL --> KERNEL-SVM\n\nfrom sklearn.svm import SVC\nclassifier5=SVC(kernel='rbf',random_state=0)\nclassifier5.fit(x_train,y_train)\n\n# ## PREDICTING THE RESULTS ON TEST SET\n\ny_pred=classifier5.predict(x_test)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1))\n\nplt.plot(y_pred,y_test,color='yellow')\nplt.title('Pred vs Test')\nplt.xlabel('Predicted values')\nplt.ylabel('Actual test values')\nplt.show()\n\n# ## MAKING THE CONFUSION MATRIX\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\ncm5=confusion_matrix(y_test,y_pred)\nprint(cm5)\naccuracy_score5=accuracy_score(y_test,y_pred)\nprint(accuracy_score5)\n\n# ###
Accuracy: SVM(79%)>Kernel-SVM(78%)>Logistic_Regression(77.5%)>Naive Bayes(73%)>K-NN(66%)
\n\n# # 6) TRAINING OUR SIXTH CLASSIFICATION MODEL --> DECISION TREE CLASSIFICATION\n\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier6=DecisionTreeClassifier(criterion='entropy',random_state=0)\nclassifier6.fit(x_train,y_train)\n\n# ## PREDICTING THE RESULTS ON TEST SET\n\ny_pred=classifier6.predict(x_test)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1))\n\nplt.plot(y_pred,y_test,color='purple')\nplt.title('Pred vs Test')\nplt.xlabel('Predicted values')\nplt.ylabel('Actual test values')\nplt.show()\n\n# ## MAKING THE CONFUSION MATRIX\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\ncm6=confusion_matrix(y_test,y_pred)\nprint(cm6)\naccuracy_score6=accuracy_score(y_test,y_pred)\nprint(accuracy_score6)\n\n# ###
Accuracy: SVM(79%)>Kernel-SVM(78%)>Logistic_Regression(77.5%)>Decision Tree Classification(75%)>Naive Bayes(73%)>K-NN(66%)
\n\n# # 7) TRAINING OUR SEVENTH CLASSIFICATION MODEL --> RANDOM FOREST CLASSIFICATION\n\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier7=RandomForestClassifier(n_estimators=10,criterion='entropy',random_state=0)\nclassifier7.fit(x_train,y_train)\n\n# ## PREDICTING THE RESULTS ON TEST SET\n\ny_pred=classifier7.predict(x_test)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1),y_test.reshape(len(y_test),1)),1))\n\nplt.plot(y_pred,y_test,color='orange')\nplt.title('Pred vs Test')\nplt.xlabel('Predicted values')\nplt.ylabel('Actual test values')\nplt.show()\n\n# ## MAKING THE CONFUSION MATRIX\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\ncm7=confusion_matrix(y_test,y_pred)\nprint(cm7)\naccuracy_score7=accuracy_score(y_test,y_pred)\nprint(accuracy_score7)\n\n# ###
Accuracy: SVM(79%)>Kernel-SVM(78%)>Logistic_Regression(77.5%)>Decision Tree Classification(75%)>Naive Bayes(73%)>Random Forest Regression(72.5)>K-NN(66%)
\n\n# # VISUILISING THE DIFFERENT ACCURACIES \n\naccuracy_model_list=[accuracy_score1,accuracy_score2,accuracy_score3,accuracy_score4,accuracy_score5,accuracy_score6,accuracy_score7]\n\naccuracy_model_list\n\nmodel_name=['Logistic Regression','Support Vector Machine(SVM)','K-Nearest Neighbors(K-NN)','Naive Bayes','Kernel SVM','Decision Tree Classification','Random Forest Classification']\nzipp=list(zip(model_name,accuracy_model_list))\nprint(zipp)\n\ndataFrame_comparison=pd.DataFrame(zipp,columns=['Classification Model','Accuracy'])\n\ndataFrame_comparison\n\n# SORTED IN DESCENDING ORDER BY THE VALUE OF ACCURACY_SCORE\ndataFrame_comparison.nlargest(n=10,columns=['Accuracy'])\n\nlist1=[x for x in range(1,8)]\nplt.scatter(list1,accuracy_model_list,color='red')\nplt.title('Model name and there accuracies')\nplt.xlabel('Model Name 1:Logistic Regression, 2:SVM, 3:K-NN, 4:Naive Bayes, 5:Kernel-SVM, 6:Decision Tree Classification, 7:Random forest classification')\nplt.ylabel('Accuracy')\nplt.show()\n\n# # CONCLUSION\n# From the above predictions we can see that the accuracy_score of Support Vector Machine(SVM) is highest i.e. 0.790 , therefore here in this case the SVM model fits best\n","repo_name":"gopal2804/NATURAL_LANGUAGE_PROCESSION-NLP---BAG_OF_WORDS-PROJECT","sub_path":"natural language processing project.ipynb","file_name":"natural language processing project.ipynb","file_ext":"py","file_size_in_byte":8668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"75"} +{"seq_id":"71747984599","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"oE12YvYMkPC1\"\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nfrom sklearn import svm\nimport numpy as np\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 423} id=\"xxRyiZxklDVo\" outputId=\"3ec955a0-442f-4bfe-e4d5-d0cb9e9c3beb\"\ntitanic=pd.read_csv(\"https://raw.githubusercontent.com/ezioauditore-tech/AI/main/datasets/Titanic/train.csv\")\ntitanic\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"9uzKxiLxnRlM\" outputId=\"53a56e01-4db1-490a-88a3-73dbc626d162\"\ntitanic.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"o3tys3Cvl33v\" outputId=\"98ff2e36-baec-4199-eba4-a4c207358e1b\"\ntitanic.drop(['PassengerId','Name','Ticket'],axis=1,inplace=True)\ntitanic.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"F8lgZhpmmJh_\" outputId=\"c853ed13-1180-4a92-cbc4-59088447cb5d\"\ntitanic.isnull().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 112} id=\"WfcOr2pCmRPl\" outputId=\"b78f89c2-1bcd-4fbe-ce3d-3d283e0282fd\"\ntitanic[titanic.Embarked.isnull()]\n\n# + id=\"x3SlLfl1p2m3\"\ntitanic.drop(['Cabin'],axis=1,inplace=True)\ntitanic[\"Age\"]=titanic[\"Age\"].fillna(titanic[\"Age\"].median())\ntitanic[\"Embarked\"]=titanic[\"Embarked\"].fillna(\"C\")\ntitanic.Sex=titanic.Sex.replace(['male','female'],[0,1])\ntitanic.Embarked=titanic.Embarked.replace(['S','C','Q'],[0,1,2])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 423} id=\"ArCVXDYop2dt\" outputId=\"c969b0f1-459d-4835-9e0d-1fbbd7e09734\"\ntitanic_test=pd.read_csv(\"https://raw.githubusercontent.com/ezioauditore-tech/AI/main/datasets/Titanic/test.csv\")\ntitanic_test\n\n# + id=\"_vb5_R4cp2Qz\"\ntitanic_test.drop(['Cabin'],axis=1,inplace=True)\ntitanic_test[\"Age\"]=titanic_test[\"Age\"].fillna(titanic_test[\"Age\"].median())\ntitanic_test[\"Embarked\"]=titanic_test[\"Embarked\"].fillna(\"C\")\ntitanic_test.Sex=titanic_test.Sex.replace(['male','female'],[0,1])\ntitanic_test.Embarked=titanic_test.Embarked.replace(['S','C','Q'],[0,1,2])\n\n# + id=\"PP7Mf7RrqiPd\"\ntitanic_test.dropna(inplace=True)\n\n# + id=\"PK99S7vHpu0T\"\nfeatures=[\"Pclass\",\"Sex\",\"Age\",\"SibSp\",\"Parch\",\"Fare\",\"Embarked\"]\n\n# + id=\"KinKmtC7q2Bz\"\nc=0.7\nclf=svm.SVC(kernel='linear',C=c).fit(titanic[features],titanic[\"Survived\"])\n\n# + id=\"F4bvDSl8rJsm\"\nprediction=clf.predict(titanic_test[features])\n\n# + id=\"PEUtPvGTr3qX\"\n\n","repo_name":"AMIRTHAVARSHINI13/svm","sub_path":"SVM1.ipynb","file_name":"SVM1.ipynb","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"1024838412","text":"# +\nimport tensorflow as tf\n\nprint(tf.__version__)\n# -\n\nfmnist = tf.keras.datasets.fashion_mnist\n\n# Load the training and test split of the Fashion MNIST dataset\n(training_images, training_labels), (test_images, test_labels) = fmnist.load_data()\n\n# +\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# You can put between 0 to 59999 here\nindex = 32456\n\n# Set number of characters per row when printing\nnp.set_printoptions(linewidth=320)\n\n# Print the label and image\nprint(f'LABEL: {training_labels[index]}')\nprint(f'\\nIMAGE PIXEL ARRAY:\\n {training_images[index]}')\n\n# Visualize the image\nplt.imshow(training_images[index])\n# -\n\n# Build the classification model\nmodel = tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape = (28,28)), \n tf.keras.layers.Dense(128, activation=tf.nn.relu), \n tf.keras.layers.Dense(10, activation=tf.nn.softmax)])\n","repo_name":"usamabajwa86/PKC1-2023","sub_path":"day31/tf.ipynb","file_name":"tf.ipynb","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"41563606402","text":"# Dataset com base https://www.kaggle.com/thedownhill/art-images-drawings-painting-sculpture-engraving/home\n#\n# Context: \n# Dataset for classifying different styles of art. Main categories have been taken here
\n# Content: \n# 5 kinds of data downloaded from google images, yandex images and this site:\n#\n# Drawings and watercolours
\n# Works of painting
\n# Sculpture
\n# Graphic Art
\n# Iconography (old Russian art)
\n#\n#\n# Data is separated on training and validation sets\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Conv2D, MaxPooling2D\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nimport os, shutil\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom collections import Counter\nimport keras\nfrom keras.utils import to_categorical\n\nIMG_SIZE = 100\n\n# +\n# filtro do erro para não exibir\nimport warnings\nwarnings.filterwarnings(\"ignore\", \"(Possibly )?corrupt EXIF data\", UserWarning)\n\nbase_dir = './dataset'\n\ntrain_dir = os.path.join(base_dir, 'training_set')\nvalidation_dir = os.path.join(base_dir, 'validation_set')\n\n# criando os rotulos\nlabels = [x for x in os.listdir(train_dir)]\n\nfrom PIL import Image\n\nos.mkdir(os.path.join(base_dir, 'training_set_convert'))\nos.mkdir(os.path.join(base_dir, 'validation_set_convert'))\ntrain_dir_convert = os.path.join(base_dir, 'training_set_convert')\nvalidation_dir_convert = os.path.join(base_dir, 'validation_set_convert')\n\nfor i in labels:\n os.mkdir(os.path.join(train_dir_convert, i))\n os.mkdir(os.path.join(validation_dir_convert, i))\n\nfor i in labels:\n _dir = os.path.join(train_dir, i)\n _dir_conv = os.path.join(train_dir_convert, i)\n for x in os.listdir(_dir):\n try:\n img = Image.open(os.path.join(_dir, x))\n img = img.resize((IMG_SIZE,IMG_SIZE), Image.ANTIALIAS)\n img.save(os.path.join(_dir_conv, x))\n except Exception:\n pass\n\nfor i in labels:\n _dir = os.path.join(validation_dir, i)\n _dir_conv = os.path.join(validation_dir_convert, i)\n for x in os.listdir(_dir):\n try:\n img = Image.open(os.path.join(_dir, x))\n img = img.resize((IMG_SIZE,IMG_SIZE), Image.ANTIALIAS)\n img.save(os.path.join(_dir_conv, x))\n except (Exception, UserWarning):\n pass\n\n\n# +\nbatch_size = 20\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.1,\n zoom_range=0.1,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_dir = train_dir_convert\nvalidation_dir = validation_dir_convert\n\ntrain_generator = train_datagen.flow_from_directory(train_dir, \n target_size=(IMG_SIZE,IMG_SIZE), \n batch_size=batch_size, \n class_mode='categorical')\n\nvalidation_generator = test_datagen.flow_from_directory(validation_dir, \n target_size=(IMG_SIZE,IMG_SIZE), \n batch_size=batch_size, \n class_mode='categorical')\n \n\n# +\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), input_shape=(IMG_SIZE, IMG_SIZE, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(5, activation='softmax'))\n\nmodel.summary()\n\n# +\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=7818/batch_size, \n epochs=10, \n validation_data=validation_generator, \n validation_steps=856/batch_size)\n\n\n# -\n\ndef tratar_img(img):\n img = cv2.imread(img)\n img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))\n return img.reshape(1,IMG_SIZE,IMG_SIZE,3)\n\n\n# +\nprint(model.predict(tratar_img('desenho.jpg')))\n\nprint(labels)\n","repo_name":"DeividWillyan/MachineLearning","sub_path":"Estudos_MachineLearning/DeepLearning3.ipynb","file_name":"DeepLearning3.ipynb","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"11807967131","text":"# ## Kata 01\n\n# Fecha\n\n# +\nfrom datetime import date\n\nprint(\"Today's date is: \" + str(date.today()))\n# -\n\n# Parsec a años luz\n\n# +\nparsec = 11\n\nlightyears = parsec * 3.26156\n\nprint(str(parsec) + \" parsec, is \" + str(lightyears) + \" lightyears\")\n","repo_name":"RobertoArgote21/Katas-Innovaccion","sub_path":"Kata1/kata1.ipynb","file_name":"kata1.ipynb","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"25874931983","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib \nimport matplotlib.pyplot as plt\n# Explore fluctuations in stock markers vs. the Shekel rate. ref: https://www.themarker.com/markets/.premium-1.10783174\n\n# NASDAQ closing\n# source: https://finance.yahoo.com/quote/%5EIXIC/history/\nnasdaq = pd.read_csv('../data/IXIC-20220508.csv')\n\n#nasdaq.set_index(pd.to_datetime(nasdaq['Date']), drop=True, inplace=True)\nnasdaq.set_index('Date', drop=True, inplace=True)\nnasdaq\n\n# USD-ILS exchange rates\n# Source https://excelrates.com/historical-exchange-rates/USD-ILS\nILS = pd.read_excel('../data/USD-ILS-20220508.xlsx')\n\nILS.set_index('Date', drop=True, inplace=True)\nILS\n\nmerge=pd.merge(nasdaq, ILS, how='inner', left_index=True, right_index=True)\nmerge['USD'] = 1 / merge['ILS']\n\nmerge\n\n\ndef rev(s):\n return s[::-1]\n\n\n# +\nsns.set_context('talk')\n#sns.set_style(\"darkgrid\", {\"figure.figsize\": [10, 7.5], \"lines.linewidth\": 5.5})\nax = sns.lineplot(data=merge['Close'], color=\"g\", label=rev('נאסדק'))\nax.set_xticklabels(ax.get_xticklabels(),rotation = -45)\n\nax.legend(loc=0)\nax2 = plt.twinx()\nax3 = sns.lineplot(data=merge['USD'], color=\"b\", ax=ax2, label=rev('דולר/שקל'))\nax3.legend(loc=2)\n# -\n\ncr = merge['USD'].rolling(30).corr(merge['Close'])\n\nax = sns.lineplot(data=cr)\n#ax.set_xticklabels(ax.get_xticklabels(),rotation = -45)\nax.tick_params(axis='x', rotation=-45)\n\n\ncr[-25:-1]\n","repo_name":"dpelleg/notebooks","sub_path":"charts/code/nasdaq-vs-ILS-themarker.ipynb","file_name":"nasdaq-vs-ILS-themarker.ipynb","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"73680761559","text":"# +\n#depreciated, forgot this is a python 2.x package. Will move over as time allows.\n# -\n\nimport mechanize as m\n\nurl = \"http://monerobenchmarks.info/list.php\"\ngpu_master_url = \"https://www.videocardbenchmark.net/gpu_list.php\"\n\n# +\nbr = m.Browser()\nbr.open(gpu_master_url)\nprint(br.response().read())\n\nforms = [f for f in br.forms()]\nctrl = forms[0].controls[0]\n#for selections in ctrl.get_items():\n# ctrl.set(selections)\n# print(br.response())\nctrl = ctrl.get_items()[1]\nprint(br.response().read())\n#ctrl.set_value_by_label(ctrl.get_items()[1])\n#br.select_form(nr = 0)\n#br.form['username'] = USERNAME\n# -\n\nbr = m.Browser()\nbr.open(url)\nforms = [f for f in br.forms()]\nctrl = forms[0].controls[0]\n#for selections in ctrl.get_items():\n# ctrl.set(selections)\n# print(br.response())\nctrl = ctrl.get_items()[1]\nprint(br.response().read())\n#ctrl.set_value_by_label(ctrl.get_items()[1])\n#br.select_form(nr = 0)\n#br.form['username'] = USERNAME\n\ndir(br)#.dir()\n\nresponse = br.response() # this is a copy of response\nheaders = response.info() # currently, this is a mimetools.Message\nheaders[\"Content-type\"] = \"text/html; charset=utf-8\"\nresponse.set_data(response.get_data().replace(\" state\n \n W = self.W\n \n E = np.matmul( W , PS.T)\n E = -0.5 * np.matmul( PS , E)\n E = E[0][0]\n \n return E\n \n \n def GetAllEnergies(self):\n \n # Generate the PresentStates (as calling method 'AsyncUpdate' before this method \n # might distort PresentStates)\n ps = self.GeneratePresentStates()\n \n E = list( map(self.GetEnergy , ps) )\n \n self.E = E\n \n return E\n \n \n def AsyncUpdate(self,presentstate):\n \n # Making presentstate to be 1-D array for simplicity\n presentstate = presentstate.reshape(self.N)\n \n # i should run from 0 to (self.N - 1), (In Async.Update, a neuron is randomly chosen\n # and updated, here its a loop)\n i = 0\n \n while True:\n \n #Update the ith neuron,Continue until a stationary point is reached\n presentstate[i] = self.signum(np.matmul( A.W[i] , presentstate.T))\n \n #Check if Stationary State is reached \n newstate = self.GetNextState(presentstate)\n IsStat = np.equal(newstate , presentstate)\n \n if( np.all(IsStat)):\n #Stationary State is reached\n break\n \n #Otherwise Continue loop\n if( i == (self.N-1) ):\n i = 0\n else:\n i += 1\n \n pass\n \n \n return list(presentstate) \n \n \n def AsyncUpdateAll(self , ps):\n \n #Updates the array of states passed,ps Asynchronously\n return list(map(self.AsyncUpdate,ps))\n pass\n \n \n \n def DocumentStates(self):\n \n # Documentation of data\n \n self.ReadMemoryFile()\n self.WeightMatrix()\n self.GeneratePresentStates()\n self.ns = self.GenerateNextStates(self.ps)\n self.GetStationaryStates()\n self.GetLimitCycles()\n self.GetAllEnergies()\n \n fp = open('DiscreteHopfieldTable.csv','w')\n csvwriter = csv.writer(fp)\n csvwriter.writerows([ ['Fundamental Memory =' , self.inputs] , ['Weight Matrix =', self.W] \\\n ,[] ,[ None, 'SYNCHRONOUS UPDATE'] ,[]])\n \n fieldnames = ['StateIndex','PresentState','NextState','Energy','Nature']\n csvwriter = csv.DictWriter(fp,fieldnames=fieldnames)\n csvwriter.writeheader()\n \n N = self.N\n ps = self.ps.reshape(2**N , N)\n ns = self.ns.reshape(2**N , N)\n \n \n for i in range(2 ** self.N):\n csvwriter.writerow({'StateIndex': i+1,'PresentState': list(ps[i]), \\\n 'NextState': list(ns[i]),'Energy':self.E[i], 'Nature': self.NatureOfStates[i] })\n \n \n ns_Async = self.AsyncUpdateAll(ps)\n #Regenerate PresentStates as method 'AsyncUpdate' distorts it\n ps = self.GeneratePresentStates().reshape(2**N , N)\n \n csvwriter = csv.writer(fp)\n csvwriter.writerows( [[None]]*4 + [['', 'ASYNCHRONOUS UPDATE']] + [[]])\n fieldnames = ['StateIndex','InitialState','FinalState']\n csvwriter = csv.DictWriter(fp,fieldnames=fieldnames)\n csvwriter.writeheader()\n \n for i in range(2 ** self.N):\n csvwriter.writerow({'StateIndex': i+1,'InitialState': list(ps[i]),'FinalState': list(ns_Async[i]) })\n \n\n fp.close()\n \n \n pass \n \n\nA = DiscreteHopfieldNet('fund_mem.csv')\n\nA.WeightMatrix()\n\nA.GeneratePresentStates()\n\nA.DocumentStates()\n\n\n\n# +\n# Probing the Hopfield Network\n\nx = np.array([[-1,1,0] , [1,1,0] , [-1,0,1] , [1,-1,1]])\nA.AsyncUpdateAll(x)\n","repo_name":"wittynerd/NeuralNetworksLab","sub_path":"3.DiscreteHopfieldNetwork/Discrete_Hopfield_Network.ipynb","file_name":"Discrete_Hopfield_Network.ipynb","file_ext":"py","file_size_in_byte":9899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"23112339574","text":"import torch\n\nx = torch.randn(3)\n\nx\n\nx = torch.randn(3, requires_grad=True)\n\nx\n\ny = x + 2\n\ny\n\nz = y * y * 2\nz\n\nz = z.mean()\nz\n\nz.backward()\n\n\nx.grad\n\n# grad can only be called on scalar outputs, so what if z is not of a scalar value?\n# apparently we need a vector of matching dimension of the base tensor, like for dz/dx, so we need a vector to match size of x.\n# Wish I remember more from my linear algebra class\n\nz = y * y * 2\nv = torch.tensor([0.1, 1, 0.001], dtype=torch.float32)\nz.backward(v)\nx.grad\n\n# Ways to disable the auto grad:\n\n# +\n# x.requires_grad_(False)\n# x.detach() # this creates a new tensor that doesn't have the auto grad\n# -\n\n# Or use the 'with' statement with torch.no_grad()\n\n# +\n# with torch.no_grad():\n# -\n\n# Grad values are accumulatives, as in they add up when getting called repeatedly.\n\nweights = torch.ones(4, requires_grad=True)\nweights\n\nfor epoch in range(3):\n model_output = (weights * 3).sum()\n model_output.backward()\n print(weights.grad)\n\n# So key thing to remember is to zero out the grad attributes when you want fresh grad values.\n# Note the sytax to zero it out looks funny, 'grad' looks like an attribute, but has function.\n\nfor epoch in range(3):\n model_output = (weights * 3).sum()\n model_output.backward()\n print(weights.grad)\n weights.grad.zero_()\n","repo_name":"nlscng/solid-happiness","sub_path":"03_autograd.ipynb","file_name":"03_autograd.ipynb","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"492498102","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"RYpDMj8gjF09\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"1ad8ca99-68aa-4c36-8571-140f891e5403\"\n# !pip install requests gradio -q\n\n# + id=\"GKs1no7tjUH2\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"5534bf05-6020-435e-d982-9091d4aa3048\"\n# !pip install cohere -q\n\n# + id=\"dqNt-ayOjX-d\"\nimport cohere\n\n# + id=\"5gecit2lsSsl\"\nco = cohere.Client('v4yYhTlQxlqmR1BlnE73myqICmp1VxBMYudBEASA')\n\n\n# + id=\"M8norrtYjZSF\"\ndef write_post(topic):\n response = co.generate(\n model = 'command-xlarge-20221108',\n prompt=f'Create a Alzheimer disease Blogpost for the \\\"{topic}\\\":',\n max_tokens=300, \n temperature=0.9, \n k=0, \n p=0.75, \n frequency_penalty=0, \n presence_penalty=0, \n stop_sequences=[], \n return_likelihoods='NONE')\n return response.generations[0].text \n\n\n# + id=\"lZufVkInjZZ3\"\nimport gradio as gr\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 592} id=\"uLVnipOJk8gA\" outputId=\"fc2e250a-60f6-42f6-b1f0-a81702b076bd\"\nwith gr.Blocks(css=\".gradio-container {background-image: url(https://i.picsum.photos/id/53/1280/1280.jpg?hmac=QP5opo-oENp5iFwsSiWH8azQuR0w0bwps6MT6yvhKwA)}\") as demo:\n gr.Markdown(\"# AI generated answer about Alzheimer's Disease\")\n inp = gr.Textbox(placeholder=\"Enter your topic\", label=\"Topic\")\n btn = gr.Button(\"Generate 🚀\")\n out = gr.Textbox(label=\"Answer\")\n btn.click(fn=write_post, inputs=inp, outputs=out)\n gr.Markdown(\"\")\n gr.Markdown(\"© 2023 by AlzAssistant.com\")\n gr.Markdown(\"**All technologies are supported by Cohere API\")\ndemo.launch(share = True, debug=True)\n","repo_name":"wxi003/git_test","sub_path":"Generation.ipynb","file_name":"Generation.ipynb","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"41475097327","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nimport tensorflow\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom sklearn.model_selection import train_test_split\n\ndf=pd.read_csv('Churn_Modelling.csv')\n\ndf.head()\n\ndf=df.drop(labels=['RowNumber', 'CustomerId', 'Surname'],axis=1)\n\nx=df.iloc[:,:-1]\ny=df['Exited']\n\nx.head()\n\ny.head()\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n\nlabel1=LabelEncoder()\nx['Geography']=label1.fit_transform(x['Geography'])\n\nx.head(10)\n\nlabel=LabelEncoder()\nx['Gender']=label.fit_transform(x['Gender'])\n\nx.head()\n\nx=pd.get_dummies(x,drop_first='True',columns=['Geography'])\n\nx.head()\n\n#standard scaler\nfrom sklearn.preprocessing import StandardScaler\n\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.2,random_state=1,stratify=y)\n\nscaler=StandardScaler()\nx_train=scaler.fit_transform(x_train)\nx_test=scaler.fit_transform(x_test)\n\n# +\nmodel=Sequential()\nmodel.add(Dense(x_train.shape[1],activation='relu',input_dim=x_train.shape[1]))\n#model.add(Dense(32,activation='relu'))\n\nmodel.add(Dense(128,activation='relu'))\n#model.add(Dense(256,activation='relu'))\n\nmodel.add(Dense(1,activation='sigmoid'))\n# -\n\ny_train = np.asarray(y_train)\ny_test = np.asarray(y_test)\nx_train=np.asarray(x_train)\nx_test=np.asarray(x_test)\n\nmodel.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\n\nhistory=model.fit(x_train,y_train,batch_size=10,epochs=10,verbose=1,validation_data=(x_test,y_test))\n\n\ndef plot_learningCurve(history, epochs):\n \n\n # Plot training & validation accuracy\n epoch_range = range(1, epochs+1)\n plt.plot(epoch_range, history.history['accuracy'])\n plt.plot(epoch_range, history.history['val_accuracy'])\n plt.title('Model accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Val'], loc='upper left')\n plt.show()\n \n # Plot training & validation loss values\\n\",\n plt.plot(epoch_range, history.history['loss'])\n plt.plot(epoch_range, history.history['val_loss'])\n plt.title('Model loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Val'], loc='upper left')\n plt.show()\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nplot_learningCurve(history, 10)\n\ny_pred=model.predict_classes(x_test)\n\ny_pred\n\ny_test\n\nmodel.evaluate(x_test,y_test)\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score\n\nconfusion_matrix(y_test,y_pred)\n\naccuracy_score(y_test,y_pred)\n\n\n","repo_name":"imkundang/Churn-Model","sub_path":"customer_churn_modelling_keras.ipynb","file_name":"customer_churn_modelling_keras.ipynb","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"85"} +{"seq_id":"23198467818","text":"# +\n# Setting Up Dependencies\nimport requests\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport time\nimport gmaps\nfrom config import api_key\nfrom config import w_key\nimport numpy as np\n\ngkey = api_key\ngmaps.configure(api_key=gkey)\n\n# +\nbrewery_id = []\n\nfor x in range(100):\n brewery_id.append(np.random.randint(0, 6000))\n\n brewery_id\n\nunique_brewery = pd.DataFrame({\"ID\" : brewery_id})\n\nunique_id = list(unique_brewery[\"ID\"].unique())\n\nprint(f\"Gathered {len(unique_id)} unique Brewery IDs.\")\n\n# +\n# Retrieving Raw Brewery Data\nraw_brewery_data = []\nstart = time.time()\nfor x in range(len(unique_id)):\n try:\n url = \"https://api.openbrewerydb.org/breweries/\" + str(unique_id[x])\n response = requests.get(url).json()\n raw_brewery_data.append(response)\n print(f\"({x+1}/{len(unique_id)}) Retrieved Brewery ID {unique_id[x]}...\")\n\n except:\n print(f\"({x+1}/{len(unique_id)}) Timeout for Brewery ID {unique_id[x]}... skipping\")\n \nstop = time.time()\ntime_elapsed = round((stop - start)/60,2)\nprint(f\"\\nRetrieved {len(unique_id)} breweries... Time elapsed: {time_elapsed} minutes.\")\n# -\n\n# Creating DataFrame\nbrewery_df = pd.DataFrame(raw_brewery_data)\nbrewery_df.to_csv(\"raw_brewery_data.csv\")\nbrewery_df\n\n# Drop rows with \"None\" Lats/Lngs\nbrewery_df = brewery_df[brewery_df.latitude.str.contains(\"None\") == False]\nprint(f\"Dropped {len(unique_id) - len(brewery_df)} breweries from DataFrame which did not have coordinates.\\nTotal Brewery count: {len(brewery_df)}\") \n \n\nbrewery_loc = brewery_df[['latitude','longitude']].astype(float)\nbrewery_loc.head()\n\n# +\nfig = gmaps.figure()\n\n# Create heat layer\nheat_layer = gmaps.heatmap_layer(brewery_loc, dissipating=False, max_intensity=10, point_radius=1)\n\n# Add layer\nfig.add_layer(heat_layer)\n\n# Display figure\nfig\n# -\n\n#Grabbing list of breweries from brewery_df\nbrewery_names = brewery_df['name'].tolist()\nbrewery_cities = brewery_df['city'].tolist()\n\n#Grabbing weather info for cities\nurl = \"http://api.openweathermap.org/data/2.5/weather?\"\nunits = \"imperial\"\nquery_url = f\"{url}appid={w_key}&units={units}&q=\"\ntemps=[]\nfor city in brewery_cities:\n city_dic = {'name':'','temp':''}\n response = requests.get(query_url + city).json()\n city_dic['name'] = response['name']\n city_dic['temp'] = response['main']['temp_max']\n temps.append(city_dic)\n\n#Turn weather info into dataframe\ntemp_df = pd.DataFrame(temps)\ntemp_df = temp_df.rename(columns = {'name':'city'})\ntemp_df.head()\n\n#Grabbing Brewery info\n#base url for google places\nbase_url2 = \"https://maps.googleapis.com/maps/api/place/findplacefromtext/json\"\nratings=[]\nbad_names = []\nfor name in brewery_names:\n rat_dic = {'name': name,'rating':''}\n params = {'input': name, 'inputtype': 'textquery',\n 'fields':'rating', 'key': api_key }\n response = requests.get(base_url2, params=params).json()\n try:\n rat_dic['rating'] = response['candidates'][0]['rating']\n ratings.append(rat_dic)\n except:\n #creating a list of names that don't return anything \n bad_names.append(name)\n\nratings_df = pd.DataFrame(ratings)\nratings_df.head()\n\n\n","repo_name":"gmurphy794/beerstuff","sub_path":"Beer Project.ipynb","file_name":"Beer Project.ipynb","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"77"} +{"seq_id":"5385844762","text":"# # 2-dimension\n\n# +\ndef backpackThree(size, val, total):\n \n # result[i][j] 為 size的前i個物品 填入 total為j的被包時 最大允許總價值 (可重覆)\n \n if size == None or size == [] or val == None or val == [] or len(size) != len(val) or total <= 0:\n \n return 0\n \n result = [[0 for _ in range(total + 1)] for _ in range(len(size) + 1)]\n \n for i in range(1, len(size) + 1):\n \n for j in range(1, total + 1):\n \n if j < size[i - 1]: #不取 list1[i - 1] (t < list1[i - 1] -> 因為 target < 愈加的物品),直接往上看 \n # -> result[i - 1][j]\n \n result[i][j] = result[i - 1][j]\n \n else:\n \n result[i][j] = max(result[i - 1][j], result[i][j - size[i - 1]] + val[i - 1])\n #a #b\n \n # a: 不放第i件物品 (i - 1) -> 直接看上一層 \n # b: 放第i件物品 -> 放完第i件物品,再看是否可以再放入 第i件 物品 -> \"同一層\",然後j要把第i件物品的重量扣掉\n \n return result[-1][-1]\n\nprint (backpackThree([2,3,5,7], [1,5,2,4], 10))\nprint (backpackThree([2,3,5], [1,5,2], 10))\nprint (backpackThree([1,2,3], [1,5,2], 8))\nprint (backpackThree([1,2,3], [1,5,2], 6))\n\n\n# -\n\n# # 1-dimension\n\n# +\ndef backpackThree1(total, size, val):\n \n # result[j] 代表為j的背包 放��size中前i個物品時的 可允許的最大價值 (可重覆)\n \n if total == 0 or size == [] or val == []:\n \n return 0\n \n result = [0 for _ in range(total + 1)]\n \n for i in range(1, len(size) + 1):\n \n for j in range(1, total + 1): #不是倒著走 -> 越小的越先被updated -> 一直加總 -> 可重覆\n \n if j >= size[i - 1]:\n \n result[j] = max(result[j], result[j - size[i - 1]] + val[i - 1])\n \n return result[-1]\n\nprint (backpackThree1(15, [2,3,5,7], [1,5,2,4]))\nprint (backpackThree1(10, [2,3,5], [1,5,2]))\nprint (backpackThree1(8, [1,2,3], [1,5,2]))\nprint (backpackThree1(6, [1,2,3], [1,5,2]))\n","repo_name":"a1928375/LeetCode","sub_path":"backpackThree.ipynb","file_name":"backpackThree.ipynb","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"77"} +{"seq_id":"17057986105","text":"## Load required packages\n# %pylab inline --no-import-all\nimport numpy as np\nimport numpy\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.optimizers import Adam, SGD\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.preprocessing import MinMaxScaler\n\n## Load data\nwith np.load(\"training-dataset.npz\") as data:\n img = data[\"x\"] ## test dataset\n lbl = data[\"y\"]\n\n## Check shapes and types of the dataset\nprint(img.shape)\nprint(lbl.shape)\nprint(type(img))\nprint(type(lbl))\n\n## Display example digits\nplt.figure(figsize=(15,8))\nfor index, (image, label) in enumerate(zip(img[0:10], lbl[0:10])):\n plt.subplot(2, 5, index + 1)\n plt.imshow(np.reshape(image, (28,28)), cmap=plt.cm.gray)\n plt.title('Training: %i\\n' % label, fontsize = 20)\n\n## Source: Hands-On Machine Learning Book\n# %matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nsome_digit = x_train[36000]\n#print(some_digit)\nsome_digit_image = some_digit.reshape(28, 28)\nplt.imshow(some_digit_image, cmap = matplotlib.cm.binary,\ninterpolation=\"nearest\")\nplt.axis(\"off\")\nplt.show()\n\n\n# +\ndef visualize_input(img, ax):\n ax.imshow(img, cmap='hot')\n width, height = img.shape\n thresh = img.max()/2.5\n for x in range(width):\n for y in range(height):\n ax.annotate(str(round(img[x][y],2)), xy=(y,x),\n horizontalalignment='center',\n verticalalignment='center',\n color='white' if img[x][y]