Add files using upload-large-folder tool
Browse files- .gitattributes +4 -0
- 2193.jsonl +3 -0
- 2198.jsonl +3 -0
- 2199.jsonl +3 -0
- 2206.jsonl +3 -0
- 6646.jsonl +13 -0
- 6647.jsonl +0 -0
- 6649.jsonl +0 -0
- 665.jsonl +0 -0
- 6650.jsonl +0 -0
- 6652.jsonl +0 -0
- 6655.jsonl +0 -0
- 6663.jsonl +0 -0
- 6666.jsonl +0 -0
- 669.jsonl +0 -0
- 671.jsonl +0 -0
- 674.jsonl +0 -0
- 676.jsonl +0 -0
- 678.jsonl +0 -0
- 681.jsonl +0 -0
- 683.jsonl +0 -0
.gitattributes
CHANGED
|
@@ -952,3 +952,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 952 |
2170.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 953 |
2203.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 954 |
220.jsonl filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 952 |
2170.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 953 |
2203.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 954 |
220.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 955 |
+
2198.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 956 |
+
2199.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 957 |
+
2206.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 958 |
+
2193.jsonl filter=lfs diff=lfs merge=lfs -text
|
2193.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9f3bb3869895e9b630a62496dde47056bd82bdcc65db50e3c4d88a91184313be
|
| 3 |
+
size 65664528
|
2198.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:94faa05350eaec4fd52895a101efe2561813c4b5c19281439237850a6409e314
|
| 3 |
+
size 52157320
|
2199.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:258cd4a74dbfa68cd80b8ed53aa3c3f12c7ae64d7280ff27eaa1638e3f22d7ca
|
| 3 |
+
size 73459524
|
2206.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c746736649e48668cb13670f07fb21387dabcfb02ba2c3029978a001f9bdeac7
|
| 3 |
+
size 59990438
|
6646.jsonl
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"seq_id":"22583000364","text":"import pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport bt\nimport talib\n\n\n# %matplotlib inline\n\n# ### Signal Strategy - Function\n\ndef signal_strategy(ticker, period, name, start_date='2020-2-1', end_date='2020-11-1'):\n price_data = bt.get(ticker, start=start_date, end=end_date)\n sma = price_data.rolling(period).mean()\n # Bt Strategy\n bt_strategy = bt.Strategy(name,\n [\n bt.algos.SelectWhere(price_data > sma),\n bt.algos.WeighEqually(),\n bt.algos.Rebalance()\n ])\n # Backtest\n bt_backtest = bt.Backtest(bt_strategy, price_data)\n # Backtest\n return bt_backtest\n \n\n\n# Create signal strategy backtest\nticker = 'tsla'\nsma10 = signal_strategy(ticker, period=10, name='SMA10')\nsma30 = signal_strategy(ticker, period=30, name='SMA30')\nsma50 = signal_strategy(ticker, period=50, name='SMA50')\n\n# Run all backtests and plot the resutls\nbt_results = bt.run(sma10, sma30, sma50)\nbt_results.plot(figsize=(12,12), title='Strategy optimization')\n\n\n# ### Buy & Hold\n\ndef buy_and_hold(ticker, name, start_date='2020-2-1', end_date='2020-11-1'):\n price_data = bt.get(ticker, start=start_date, end=end_date)\n # Bt Strategy\n bt_strategy = bt.Strategy(name,\n [\n bt.algos.RunOnce(),\n bt.algos.SelectAll(),\n bt.algos.WeighEqually(),\n bt.algos.Rebalance()\n ])\n # Backtest\n bt_backtest = bt.Backtest(bt_strategy, price_data)\n # Backtest\n return bt_backtest\n \n\n\n# +\n# Create benchmark strategy backtest\nbenchmark = buy_and_hold('tsla', name='benchmark')\n\n# Run all backtests and plot the resutls\nbt_results = bt.run(sma10, sma30, sma50, benchmark)\nbt_results.plot(figsize=(12,12), title='Strategy benchmarking')\n# -\n\n\n","repo_name":"kartskri/FinancialTrading","sub_path":"snippets/financial-trading/strategy_functions.ipynb","file_name":"strategy_functions.ipynb","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 2 |
+
{"seq_id":"24968018921","text":"# + [markdown] id=\"Myj3zC7za06J\"\n# # Regression Discontinuity\n\n# + [markdown] id=\"_zrYcknjvBRM\"\n# By Keeping the 21 as the threshold for age, we will be exploring the data with an RDD by writing very simple code (no package needed, just average to one side of the threshold minus average to the other side) to determine if alcohol increases the chances of death by accident, suicide and/or others (the three given columns) and commenting on the question “Should the legal age for drinking be reduced from 21?”\n#\n# We will be using the drinking.csv dataset for this problem.\n\n# + id=\"RCUbuRlNa06Z\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import MultipleLocator\n\n# + id=\"cH0CZhEda06a\" outputId=\"f7a92c23-b730-4b4d-f116-5fd23b03f938\"\n### importing the dataset\ndata = pd.read_csv(\"drinking.csv\")\ndata.describe()\n\n\n# + id=\"j09FmBMya06b\" outputId=\"e081fc4f-c9e1-4919-bda3-80734667d921\"\ndata\n\n# + id=\"wubZWhgra06c\" outputId=\"495936c4-fac8-4477-ea60-67e634984a84\"\n## RDD\n\n# Define the threshold\nage_threshold = 21\nBandwidth = 1\n\n# Split the data into two groups just above treshold and just below\nbelow_21 = data.query(\"(age >= @age_threshold - @Bandwidth) and (age < @age_threshold )\")\nabove_21 = data.query(\"(age <= @age_threshold + @Bandwidth) and (age >= @age_threshold )\")\n# Calculate the average for each group\nabove_average = above_21[['others', 'accident', 'suicide']].mean()\nbelow_average = below_21[['others', 'accident', 'suicide']].mean()\n\n# Calculating the difference between the groups\ndifference = above_average - below_average\nprint(difference)\n\n# + [markdown] id=\"XXoy1v5Pa06d\"\n# ### “Should the legal age for drinking be reduced from 21?”\n# Based on the results above we can clearly see that alcohol increased the chances of death by all three causes. I don't think legal age should be reduced from 21, mainly because, this would mean increasing the chances of death for younger people, which is not good. Since we also only looked at the very short bandwith near the age of 21(+-1), we can observe how as people become of drinking age their chances of death increases.\n\n# + id=\"dpY9xBgMa06i\" outputId=\"402e3c2b-6f2e-4234-c329-7cb98a7e6789\"\n### Accident vs Age\nage_threshold = 21 # Set the age threshold\nbandwidth = 1 # Set the bandwidth\n\n# Create a scatter plot\nplt.scatter(data['age'], data['accident'])\nplt.axvline(x = age_threshold, color='red')\n\n## set the bandwidth to be 1 year (i.e., 21 +- 1)\nx_major_locator = MultipleLocator(bandwidth)\nax = plt.gca()\nax.xaxis.set_major_locator(x_major_locator)\n\n# Set the plot title and axis labels\nplt.title('Accident vs Age')\nplt.xlabel('Age')\nplt.ylabel('Death by accident')\n\nplt.show()\n\n# + id=\"LslU6lSSa06l\" outputId=\"ffd5ab78-349e-4411-b34b-6bf57505aa6b\"\n### Suicide vs Age\nage_threshold = 21 # Set the age threshold\nbandwidth = 1 # Set the bandwidth\n\n# Create a scatter plot\nplt.scatter(data['age'], data['suicide'])\nplt.axvline(x = age_threshold, color='red')\n\n## set the bandwidth to be 1 year (i.e., 21 +- 1)\nx_major_locator = MultipleLocator(bandwidth)\nax = plt.gca()\nax.xaxis.set_major_locator(x_major_locator)\n\n# Set the plot title and axis labels\nplt.title('Suicide vs Age')\nplt.xlabel('Age')\nplt.ylabel('Death by suicide')\n\nplt.show()\n\n# + id=\"UWsO0CZda06p\" outputId=\"a3dd529c-32e4-4da8-cd1b-f85198fcecbd\"\n### Others vs Age\nage_threshold = 21 # Set the age threshold\nbandwidth = 1 # Set the bandwidth\n\n# Create a scatter plot\nplt.scatter(data['age'], data['others'])\nplt.axvline(x = age_threshold, color='red')\n\n## set the bandwidth to be 1 year (i.e., 21 +- 1)\nx_major_locator = MultipleLocator(bandwidth)\nax = plt.gca()\nax.xaxis.set_major_locator(x_major_locator)\n\n# Set the plot title and axis labels\nplt.title('Others vs Age')\nplt.xlabel('Age')\nplt.ylabel('Death by others')\n\nplt.show()\n\n# + [markdown] id=\"tccLEifXa06p\"\n# We can clearly see from all of the graphs above, right around the age of 21, within very short bandwidth, the chances of death increase very significantly by all 3 causes. This is a prime example of Regression discontinuity and how we can observe the treatment effect of drinking age, again very close to the age of 21 since we want to minimize the effect of other covariates that might also be increasing the chance of death\n\n# + [markdown] id=\"X9YrflHYa06q\"\n# ### What might be the effect of choosing a smaller bandwidth? What if we chose the maximum bandwidth?\n# In Regression discontinuity, we try to observe and measure the effeect of some treatment, drinking age in our case, on some variable of interest, chance of death in our case. When measuring treatment effect we want to choose the bandwith around the treshold as small as possible to minimize the effects of other covariates that might be affecting the variable of interest, and measure exactly the effect of treatment. If we increase bandwidth around the treshold we will also be increasing the effects of other covariates that might affect the variable of death, and decrease the accuracy of our measurement of treatment effec.\n\n# + [markdown] id=\"VAfhuGOTa064\"\n# # Treatment Effects\n\n# + [markdown] id=\"ENyGseLRv42S\"\n# Using hotel_cancellation.csv dataset, we will try to estimate the treatment effects if a ‘different room is assigned’ as the treatment indicator and interpret its effect on the room being ‘canceled’. We will use all the other columns as the covariates and write our observations for the results.\n\n# + id=\"yjU6AJ_Ya064\"\nimport pandas as pd\nimport statsmodels.api as sm\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport statsmodels.formula.api as smf\n\n# + id=\"DyELjeV7a064\" outputId=\"7da04d86-0538-467f-83fb-03cf0c858cb6\"\nHC = pd.read_csv(\"hotel_cancellation.csv\")\nprint(HC)\n\nHC['different_room_assigned_Yes'] = (HC['different_room_assigned'] == True).astype(int)\nHC['Room_is_canceled'] = (HC['is_canceled'] == True ).astype(int)\nHC = HC.dropna(subset = ['lead_time', 'arrival_date_year', 'arrival_date_week_number', 'arrival_date_day_of_month', 'days_in_waiting_list', 'different_room_assigned', 'is_canceled']).reset_index()\n\nprint(len(HC))\nprint(HC)\n\nHC = HC[['lead_time', 'arrival_date_year', 'arrival_date_week_number', 'arrival_date_day_of_month', 'days_in_waiting_list', 'different_room_assigned_Yes', 'Room_is_canceled']]\nHC.head()\n\n# + id=\"ClGIQVesa065\" outputId=\"259a5230-6f30-4b00-fa8a-04ed44aad82f\"\n# Specify the response and treatment variables\ny = HC['Room_is_canceled']\nx = HC[['lead_time', 'arrival_date_year', 'arrival_date_week_number', 'arrival_date_day_of_month', 'days_in_waiting_list', 'different_room_assigned_Yes']]\n\n# Fit a logistic regression model\nmodel = sm.Logit(y, x)\nresult = model.fit()\n# Print the treatment effect estimates\nresult.summary()\n\n# + [markdown] id=\"65UROa5ra065\"\n# ### Interpretations\n# #### From the results of our logistic regression, we can say that assigning customer to a different room multiplies the odds of cancellation by exp(-2.518556).\n# #### Since the coefficient is a negative number, it actually decreases the odds of cancellation.\n# #### The ods of cancellation gets multiplied by 0.08 (exp(-2.518556)), compared to the customers that were not assigned to a different room.\n# #### That is kind of counterintiuitive but might be due to the fact that customers were getting assigned to better rooms. Who knows :)\n#\n# #### When it comes to other covariates, all of them seem to have statistically significant effect on cancellation, except the arrival date of the month.\n# #### Most of the the significant variables also decrease the odds of cancellation, just like the treatment variable.(Interpretations hold the same for all variables.)\n# #### Only the lead time seems to increase the odds of cancellation, which is understandable, since bookings with higher lead time tend to have higher cancellation chance.\n\n# + [markdown] id=\"BMFNsmnma065\"\n# ## Double Lasso\n\n# + [markdown] id=\"gZLvn_xKwUOu\"\n# Now, we will use double logistic regression to measure the effect of ‘different room is assigned’ on the room being ‘canceled’.\n\n# + id=\"IJnmvnfta066\" outputId=\"6fa9fd2f-59bc-475e-9ecf-d03eda5c3276\"\nmodel1 = sm.Logit(y, x).fit()\ny_hat = np.array(model1.predict(x)).reshape(len(x), 1)\nx_new = np.hstack((x, y_hat))\nmodel2 = sm.Logit(y, x_new).fit()\nprint(model2.params)\nmodel2.summary()\n\n# + [markdown] id=\"StBs1dlIa066\"\n# #### Here, coefficient of x6 shows the treatment effect.\n#\n# #### After running a double logistic regression, the effects of assigning customer to a different room weakens which is understandable. When we run a double logistic regression, we also make sure to consider the effects of treatment on the variable of interest, that is due to other covariates. After accounting for those effects, assigning customer to a different room mulplies the odds of cancellation by 0.13 (exp(-1.9815)). It still decreases the odds of cancellation, but the effect is weaker compared to what we found from normal logistic regression.\n\n# + [markdown] id=\"Sdzh3_Pua066\"\n# # Bootstrap\n# Finally, we will use bootstrap to estimate the standard error of the treatment effects measured above\n\n# + id=\"qzS-lmrda066\" outputId=\"3a2a6f16-61a9-43c8-eb79-9d3e1b02eb37\"\n# Define the number of bootstrap resamples\nn_resamples = 1000\n\n# Initialize a matrix to store the treatment effect estimates\ntreat_effects = np.zeros((n_resamples, model2.params.shape[0] - 1))\n\n# Use bootstrapping to estimate the standard error of the treatment effects\ni = 0\nwhile i < n_resamples:\n resample_index = np.random.choice(HC.index, size = HC.index.size, replace = True)\n resample = HC.iloc[resample_index]\n x_resample = x.iloc[resample_index]\n y_resample = y.iloc[resample_index]\n model1 = sm.Logit(y_resample, x_resample).fit()\n y_hat = np.array(model1.predict(x_resample)).reshape(len(y_hat), 1)\n x_new = np.hstack((x_resample, y_hat))\n model2 = sm.Logit(y_resample, x_new).fit()\n treat_effects[i, :] = model2.params[:-1]\n i += 1\n\n# Calculate the standard error of the treatment effects\ntreat_effects_se = treat_effects.std(axis=0)\n\n# Print the standard errors of the treatment effect estimates\nprint('Standard errors of the treatment effects:')\nprint(treat_effects_se)\n\n# + [markdown] id=\"2jBZmpNGa067\"\n# ### As a result of bootstrapping we estimated the standard error of the treatment effect from double logistic regression to be 0.167. This is very close to what we got as a result of running normal double logistic regression which is 0.164\n","repo_name":"murads994/Treatment-Effects-Regression-Discontinuity-Double-Lasso","sub_path":"Treatment_Effects,_Regression_Discontiunity_and_Bootstrap.ipynb","file_name":"Treatment_Effects,_Regression_Discontiunity_and_Bootstrap.ipynb","file_ext":"py","file_size_in_byte":10495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 3 |
+
{"seq_id":"33256748204","text":"# +\n# coding: utf-8\n\nimport cv2\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport glob\nimport json\n\nIMG_SIZE = (180, 320)\ndrop_ratio=0.2\n\n\n# +\nclass VideoAnalyze():\n def __init__(self,video_name):\n # 特徴量抽出\n # A-KAZE検出器の生成\n# self.detector = cv2.AKAZE_create()\n# self.detector = cv2.KAZE_create()\n# self.detector = cv2.ORB_create()\n # Brute-Force Matcher生成\n# self.bf=cv2.BFMatcher(cv2.NORM_L1,crossCheck=False)\n self.cascade = cv2.CascadeClassifier('cascade.xml') #分類器の指定\n self.video_name=video_name\n # 8近傍の定義\n self.neiborhood8 = np.array([[1, 1, 1],[1, 1, 1],[1, 1, 1]],np.uint8)\n\n def show(self, match):\n img1=match['img1']\n img2=match['img2']\n plt.figure(figsize=(16,12))\n # 左\n plt.subplot(2,2,1)\n plt.imshow(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB))\n # 右\n plt.subplot(2,2,2)\n plt.imshow(cv2.cvtColor(img2, cv2.COLOR_BGR2RGB))\n plt.show()\n \n\n def show_matching(self, match):\n matched=match['matched']\n kp1=match['kp1']\n kp2=match['kp2']\n img1=match['img1']\n img2=match['img2']\n # 対応する特徴点同士を描画\n img = cv2.drawMatchesKnn(img1, kp1, img2, kp2, matched, None, flags=2)\n# img = cv2.drawMatches(img1, kp1, img2, kp2, matched, None, flags=2)\n plt.figure(figsize=(16,12))\n plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n plt.show()\n\n# def compare_frame(self, frame, frame_path):\n def compare_frame(self, frame):\n # 特徴量の検出と特徴量ベクトルの計算\n self.top_match={}\n gray_tmp=frame.copy()\n# gray_tmp = cv2.cvtColor(tmp, cv2.COLOR_BGR2GRAY)\n gray_tmp = cv2.resize(gray_tmp, IMG_SIZE)\n gray_tmp=gray_tmp[10:320, 0:180]\n# __, target_des = self.detector.detectAndCompute(gray_tmp, None)\n y=310\n x=180\n# target_hist = cv2.calcHist([gray_tmp], [0], None, [256], [0, 256])\n target_hist1 = cv2.calcHist([gray_tmp[0:int(y/2), 0:int(x/2)]], [0], None, [256], [0, 256])\n target_hist2 = cv2.calcHist([gray_tmp[0:int(y/2), int(x/2):x]], [0], None, [256], [0, 256])\n target_hist3 = cv2.calcHist([gray_tmp[int(y/2):y, 0:int(x/2)]], [0], None, [256], [0, 256])\n target_hist4 = cv2.calcHist([gray_tmp[int(y/2):y, int(x/2):x]], [0], None, [256], [0, 256])\n for path in glob.glob('./base_img/*.png'):\n try:\n # matches = bf.match(target_des, d_dict[path]['des'])\n # dist = [m.distance for m in matches]\n # matched = [m for m in matches]\n # matched = sorted(matches, key=lambda x:x.distance)\n\n# matches = self.bf.knnMatch(target_des, self.d_dict[path]['des'], k=2)\n# dist = []\n# matched=[]\n# for m, n in matches:\n# if m.distance < drop_ratio * n.distance:\n# matched.append([m])\n# dist.append(m.distance)\n\n# ret = sum(dist) / len(dist)\n ret=[]\n# ret.append(cv2.compareHist(target_hist, self.d_dict[path]['hist'], cv2.HISTCMP_CHISQR_ALT))\n ret.append(cv2.compareHist(target_hist1, self.d_dict[path]['hist1'], cv2.HISTCMP_CHISQR_ALT))\n ret.append(cv2.compareHist(target_hist2, self.d_dict[path]['hist2'], cv2.HISTCMP_CHISQR_ALT))\n ret.append(cv2.compareHist(target_hist3, self.d_dict[path]['hist3'], cv2.HISTCMP_CHISQR_ALT))\n ret.append(cv2.compareHist(target_hist4, self.d_dict[path]['hist4'], cv2.HISTCMP_CHISQR_ALT))\n# print(\"{0} : {1} : {2}\".format(path, frame_path,sum(ret)))\n if not self.top_match or self.top_match['ret'] > sum(ret):\n self.top_match['ret']=sum(ret)\n self.top_match['path']=path\n self.top_match['ts']={'img1':self.d_dict[path]['img'],'img2':gray_tmp}\n# self.top_match['ts']={'matched':matched, 'img1':self.d_dict[path]['img'], \\\n# 'kp1':self.d_dict[path]['kp'],'img2':gray_tmp, 'kp2':__,} \n except cv2.error:\n ret = 100000\n\n# print(self.top_match['path'], self.top_match['ret'])\n# self.show_matching(self.top_match['ts'])\n# self.show(self.top_match['ts'])\n\n def create_base_sienario(self, frame, rect, senario_dict, i):\n tmp=frame.copy()\n for (x, y, w, h) in rect:\n if y < 30 or h > 500 or w > 500:\n continue\n # タップライン\n height, width = tmp.shape[:2]\n if h < 100:\n h_buff=int((100-h)/2) \n y = y - h_buff\n h = h + h_buff*2\n tap_line=tmp[y:y+h, 0:width]\n tap_line_name='./s_img/tap_line_{0}.jpg'.format(i)\n cv2.imwrite(tap_line_name, tap_line)\n senario_dict[i]={}\n senario_dict[i]['line']={}\n senario_dict[i]['line']['base']=self.top_match['path']\n senario_dict[i]['line']['match']=tap_line_name\n senario_dict[i]['line']['is_parent']=True\n senario_dict[i]['line']['scale']=1\n\n # タップ位置\n if w < 100:\n w_buff=int((100-w)/2)\n x-=w_buff\n w+=w_buff*2\n tap_img=tmp[y:y+h, x:x+w]\n tap_name='./s_img/tap_{0}.jpg'.format(i)\n cv2.imwrite(tap_name, tap_img)\n senario_dict[i]['tap']={}\n senario_dict[i]['tap']['base']=None\n senario_dict[i]['tap']['match']=tap_name\n senario_dict[i]['tap']['scale']=1\n i+=1\n return i\n\n def flame_diff(self,im1,im2,im3,th, tl,blur):\n im1=cv2.cvtColor(im1, cv2.COLOR_RGB2GRAY)\n im2=cv2.cvtColor(im2, cv2.COLOR_RGB2GRAY)\n im3=cv2.cvtColor(im3, cv2.COLOR_RGB2GRAY)\n\n d1 = cv2.absdiff(im3, im2)\n d2 = cv2.absdiff(im2, im1)\n diff = cv2.bitwise_and(d1, d2)\n \n # 差分が閾値より小さければTrue\n #mask = np.where((diff<th)&(diff>tl))\n mask = diff<th\n\n # 背景画像と同じサイズの配列生成\n im_mask = np.empty((im1.shape[0],im1.shape[1]),np.uint8)\n im_mask[:][:]=255\n # Trueの部分(背景)は黒塗り\n im_mask[mask]=0\n\n # 8近傍で膨張処理\n im_mask = cv2.dilate(im_mask,\n self.neiborhood8,\n iterations=5)\n # ノイズ除去\n im_mask = cv2.medianBlur(im_mask,blur)\n\n return im_mask\n\n def find_rect(self,image):\n # hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV_FULL)\n # h = hsv[:, :, 0]\n # s = hsv[:, :, 1]\n # mask = np.zeros(h.shape, dtype=np.uint8)\n # mask[((h < 20) | (h > 200)) & (s > 128)] = 255\n _, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n rects = []\n for contour in contours:\n approx = cv2.convexHull(contour)\n rect = cv2.boundingRect(approx)\n rects.append(np.array(rect))\n return rects\n \n def main(self):\n senario_dict={}\n self.d_dict={}\n for img_path in glob.glob('./base_img/*.png'):\n gray_img = cv2.imread(img_path)\n# gray_img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n gray_img = cv2.resize(gray_img, IMG_SIZE)\n gray_img=gray_img[10:320, 0:180]\n# kp, des = self.detector.detectAndCompute(gray_img, None) \n self.d_dict[img_path]={}\n# self.d_dict[img_path]['des']=des\n# self.d_dict[img_path]['kp']=kp\n self.d_dict[img_path]['img']=gray_img\n y=310\n x=180\n# self.d_dict[img_path]['hist'] = cv2.calcHist([gray_img], [0], None, [256], [0, 256])\n self.d_dict[img_path]['hist1'] = cv2.calcHist([gray_img[0:int(y/2), 0:int(x/2)]], [0], None, [256], [0, 256])\n self.d_dict[img_path]['hist2'] = cv2.calcHist([gray_img[0:int(y/2), int(x/2):x]], [0], None, [256], [0, 256])\n self.d_dict[img_path]['hist3'] = cv2.calcHist([gray_img[int(y/2):y, 0:int(x/2)]], [0], None, [256], [0, 256])\n self.d_dict[img_path]['hist4'] = cv2.calcHist([gray_img[int(y/2):y, int(x/2):x]], [0], None, [256], [0, 256])\n i=0\n ct=0\n is_print=True\n cap = cv2.VideoCapture(self.video_name)\n _, frame1 = cap.read()\n _, frame2 = cap.read()\n ret, frame3 = cap.read()\n #print(\"{0}: is Open {1}\".format(self.video_name, cap.isOpened()))\n# prev_detect=np.array([[-1,-1,-1,-1]])\n while ret:\n# for frame_path in glob.glob('./cat_img/*.png'):\n# ret, frame = cap.read()\n# frame = cv2.imread(frame_path)\n# if frame is None:\n# break\n frame_fs = self.flame_diff(frame1.copy(),frame2.copy(),frame3.copy(), 5, 0,5)\n rect = self.find_rect(frame_fs.copy())\n ct+=1\n if ct>10:\n is_print=True\n\n if is_print and len(rect) and len(rect) <10:\n is_print=False\n ct=0\n print(len(rect), rect)\n label = cv2.connectedComponentsWithStats(frame_fs)\n # ラベルの個数nと各ラベルの重心座標cogを取得\n n = label[0] - 1\n cog = np.delete(label[3], 0, 0)\n #print(cog)\n #print(int(cog[:,0].mean()))\n #print(int(cog[:,1].mean()))\n #break\n # 重心に赤円を描く\n #for i in range(n):\n #im2 = cv2.circle(im2,(int(rect[:,0].mean()),int(rect[:,1].mean())), 40, (0,0,0), -1)\n test2 = cv2.circle(frame2.copy(),(int(cog[:,0].mean()),int(cog[:,1].mean())), 40, (0,0,0), -1)\n cv2.imwrite(\"./test/test{0:0>3}.jpg\".format(i) ,test2)\n\n #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # detectMultiScale(Mat image, MatOfRect objects, double scaleFactor, int minNeighbors, int flag, Size minSize, Size maxSize)\n# detect = self.cascade.detectMultiScale(frame, 1.1, 3) #物体の検出\n# print (detect,prev_detect)\n# if type(detect) is tuple or (detect == prev_detect).all():\n# prev_detect= np.array([[-1,-1,-1,-1]]) if type(detect) is tuple else detect\n# continue\n# print(detect)\n# self.compare_frame(frame, frame_path)\n self.compare_frame(frame2)\n i=self.create_base_sienario(frame2, rect, senario_dict, i)\n\n frame1 = frame2\n frame2 = frame3\n ret, frame3 = cap.read()\n# prev_detect=detect\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n # print(senario_dict)\n# cap.release()\n return senario_dict\n# -\n\n# テストベースシナリオ\nif __name__ == '__main__':\n va=VideoAnalyze('./test.mp4')\n senario_dict=va.main()\n print(senario_dict)\n f = open('{0}.json'.format(\"base_senario\"), 'w')\n json.dump(senario_dict, f)\n f.close()\n\n\n","repo_name":"nitoage/machine-learning","sub_path":"compare-features/video_analyze.ipynb","file_name":"video_analyze.ipynb","file_ext":"py","file_size_in_byte":11443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 4 |
+
{"seq_id":"40197830459","text":"# +\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# -\n\n# Reading the dataset\ndf = pd.read_csv('Downloads/card_transdata.csv')\ndf.head()\n\ndf.shape\n\ndf.describe()\n\n# Cheking missing values in columns\ndf_missing_values = df.isnull().sum()\ndf_missing_values \n\n# # data distribution analysis\n\nclasses = df['fraud'].value_counts()\nclasses\n#classes.describe()\n\nsns.countplot('fraud', data=df)\nplt.title('Number of fraud vs non-fraud transcations')\nplt.show()\n\n# Creating fraud dataframe\ndata_fraud = df[df['fraud'] == 1]\n# Creating non fraud dataframe\ndata_non_fraud = df[df['fraud'] == 0]\n\n# Distribution plot\nplt.figure(figsize=(8,5))\nax = sns.distplot(data_fraud['distance_from_home'],label='fraudt',hist=False)\nax = sns.distplot(data_non_fraud['distance_from_home'],label='non fraud',hist=False)\nax.set(xlabel='Seconds elapsed between the transction and the first transction')\nplt.show()\n\n# Dropping the Time column\ndf.drop('distance_from_home', axis=1, inplace=True)\n\n\n# # distribution of classes with amount\n\n# Distribution plot\nplt.figure(figsize=(8,5))\nax = sns.distplot(data_fraud['online_order'],label='fraudulent',hist=False)\nax = sns.distplot(data_non_fraud['distance_from_home'],label='non fraudulent',hist=False)\nax.set(xlabel='Transction Amount')\nplt.show()\n#here we can see that fraud transactions are densed with low range of amount whereas non fraud transactions are spreaded through high range of amount.\n\n# # train test-spliting\n\n# Import library\nfrom sklearn.model_selection import train_test_split\n\n# Putting feature variables into X\nX = df.drop(['fraud'], axis=1)\n\n# Putting target variable to y\ny = df['fraud']\n\n# Splitting data into train and test set 80:20\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, test_size=0.2, random_state=50)\n\n# # feature scaling\n\n# Standardization method\nfrom sklearn.preprocessing import StandardScaler\n# Instantiate the Scaler\nscaler = StandardScaler()\n# Fit the data into scaler and transform\nX_train['fraud'] = scaler.fit_transform(X_train[['fraud']])\nX_train.head()\n\n# # scale the test set\n\n# Transform the test set\nX_test['fraud'] = scaler.transform(X_test[['fraud']])\nX_test.head()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"NiharikaSurampudi/Fraud_Detection_Project","sub_path":"MiniProject_Verzeo-checkpoint.ipynb","file_name":"MiniProject_Verzeo-checkpoint.ipynb","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 5 |
+
{"seq_id":"73821730695","text":"# + id=\"wdre0c-k6Cxs\"\nimport jax.numpy as np\nfrom jax import random, vmap, grad, jit\nfrom jax.experimental import optimizers\n\nimport itertools\nfrom functools import partial\nfrom tqdm import trange\nimport numpy.random as npr\nimport matplotlib.pyplot as plt\nimport sklearn.datasets\n\n# %matplotlib inline\n\n# + id=\"oGmNhKY06I3g\"\ndef MLP(layers):\n def init(rng_key):\n def init_layer(key, d_in, d_out):\n k1, k2 = random.split(key)\n glorot_stddev = 1. / np.sqrt((d_in + d_out) / 2.)\n W = glorot_stddev*random.normal(k1, (d_in, d_out))\n b = np.zeros(d_out)\n return W, b\n key, *keys = random.split(rng_key, len(layers))\n params = list(map(init_layer, keys, layers[:-2], layers[1:-1]))\n # Last layer\n k1, k2 = random.split(key)\n params.append(init_layer(k1, layers[-2], layers[-1]))\n params.append(init_layer(k2, layers[-2], layers[-1]))\n return params\n def apply(params, inputs):\n for W, b in params[:-2]:\n outputs = np.dot(inputs, W) + b\n inputs = np.tanh(outputs)\n W, b = params[-1]\n mu = np.dot(inputs, W) + b\n W, b = params[-2]\n Sigma = np.dot(inputs, W) + b\n return mu, Sigma\n return init, apply\n\n\n# + id=\"BMtghCNe6K0x\"\nclass VAE():\n def __init__(self, X, layers_Q, layers_P, rng_key = random.PRNGKey(0), beta = 1.0, ):\n # Normalize data\n self.Xmean, self.Xstd = X.mean(0), X.std(0)\n X = (X - self.Xmean)/self.Xstd\n\n # Store the normalized trainind data\n self.X = X\n\n # Latent dimenions\n self.Z_dim = layers_Q[-1]\n\n # Regularization parameter beta\n self.beta = beta\n\n # Initialization and evaluation functions\n self.net_Q_init, self.net_Q_apply = MLP(layers_Q)\n self.net_P_init, self.net_P_apply = MLP(layers_P)\n \n # Initialize parameters, not committing to a batch shape\n key_Q, key_P = random.split(rng_key, 2)\n net_Q_params = self.net_Q_init(key_Q)\n net_P_params = self.net_P_init(key_P)\n params = (net_Q_params, net_P_params)\n \n # Use optimizers to set optimizer initialization and update functions\n self.opt_init, \\\n self.opt_update, \\\n self.get_params = optimizers.adam(optimizers.exponential_decay(1e-3, \n decay_steps=2000, \n decay_rate=0.9))\n self.opt_state = self.opt_init(params)\n\n # Logger to monitor the loss functions\n self.KL_loss_log = []\n self.recon_loss_log = []\n self.itercount = itertools.count()\n\n\n def per_example_ELBO(self, params, batch):\n net_Q_params, net_P_params = params\n X, eps = batch\n # Encoder: q(z|x)\n Z_mu, Z_logsigma = self.net_Q_apply(net_Q_params, X)\n # Re-parametrization trick\n Z = Z_mu + eps*np.sqrt(np.exp(Z_logsigma))\n # Decoder: p(x|z)\n X_mu, X_Sigma = self.net_P_apply(net_P_params, Z)\n # KL[q(z|x)||p(z)] \n KL_loss = 0.5*np.sum(np.exp(Z_logsigma) + Z_mu**2 - 1.0 - Z_logsigma)\n # -log p(x|z): Gaussian likelihood\n recon_loss = 0.5*np.sum((X-X_mu)**2/np.exp(X_Sigma) + X_Sigma + np.log(2.0*np.pi))\n return recon_loss, KL_loss\n\n def loss(self, params, batch):\n pe_loss = lambda x: self.per_example_ELBO(params, x)\n recon_loss, KL_loss = vmap(pe_loss)(batch)\n loss = self.beta*KL_loss + recon_loss\n return np.mean(loss)\n\n # Define a compiled update step\n @partial(jit, static_argnums=(0,))\n def step(self, i, opt_state, batch):\n params = self.get_params(opt_state)\n g = grad(self.loss)(params, batch)\n return self.opt_update(i, g, opt_state)\n\n def data_stream(self, n, num_batches, batch_size):\n rng = npr.RandomState(0)\n while True:\n perm = rng.permutation(n)\n for i in range(num_batches):\n batch_idx = perm[i*batch_size:(i+1)*batch_size]\n eps = random.normal(random.PRNGKey(i), (batch_idx.shape[0], self.Z_dim))\n yield self.X[batch_idx, :], eps\n\n def train(self, num_epochs = 100, batch_size = 64): \n # Build a data iterator\n n = self.X.shape[0]\n num_complete_batches, leftover = divmod(n, batch_size)\n num_batches = num_complete_batches + bool(leftover) \n batch = iter(self.data_stream(n, num_batches, batch_size))\n # Run training loop\n pbar = trange(num_epochs)\n for epoch in pbar:\n for i in range(num_batches):\n self.opt_state = self.step(next(self.itercount), self.opt_state, next(batch))\n params = self.get_params(self.opt_state)\n pe_loss = lambda x: self.per_example_ELBO(params, x)\n recon_loss, KL_loss = vmap(pe_loss)(next(batch))\n recon_loss = np.mean(recon_loss) \n KL_loss = np.mean(KL_loss) \n self.KL_loss_log.append(KL_loss)\n self.recon_loss_log.append(recon_loss)\n pbar.set_postfix({'Reconstruction loss': recon_loss, 'KL loss': KL_loss})\n\n # Encode a single input point\n @partial(jit, static_argnums=(0,))\n def encode(self, params, X):\n net_Q_params, _ = params\n # Encoder: q(z|x)\n X = (X - self.Xmean)/self.Xstd\n Z_mu, Z_logsigma = self.net_Q_apply(net_Q_params, X)\n return Z_mu, np.exp(Z_logsigma)\n\n # Decode a single latent point\n @partial(jit, static_argnums=(0,))\n def decode(self, params, Z):\n _, net_P_params = params\n # Decoder: p(x|z)\n X_mu, _ = self.net_P_apply(net_P_params, Z)\n # De-normalize\n X_mu = X_mu * self.Xstd + self.Xmean\n return X_mu\n\n # Reconstruct a single input point\n @partial(jit, static_argnums=(0,))\n def reconstruct(self, rng_key, params, X): \n net_Q_params, net_P_params = params\n # Encoder: q(z|x)\n X = (X - self.Xmean)/self.Xstd\n Z_mu, Z_logsigma = self.net_Q_apply(net_Q_params, X) \n # Re-parametrization trick\n eps = random.normal(rng_key, (self.Z_dim,))\n Z = Z_mu + eps*np.sqrt(np.exp(Z_logsigma))\n # Decoder: p(x|z)\n X_mu, _ = self.net_P_apply(net_P_params, Z)\n # De-normalize\n X_mu = X_mu * self.Xstd + self.Xmean\n return X_mu\n\n # Generate a single sample\n @partial(jit, static_argnums=(0,))\n def generate(self, rng_key, params):\n _, net_P_params = params\n eps = random.normal(rng_key, (self.Z_dim,))\n X_mu, X_Sigma = self.net_P_apply(net_P_params, eps)\n X = random.multivariate_normal(rng_key, X_mu, np.diag(np.exp(X_Sigma)))\n X = X * self.Xstd + self.Xmean\n return X\n\n# + id=\"DNU2OhtCFdik\"\n# Load Iris data-set\nX = sklearn.datasets.load_iris().data\ny = sklearn.datasets.load_iris().target\n\n# + id=\"EOid5lqTFicb\"\n# Model creation\nZ_dim = 2\nX_dim = X.shape[1]\ninit_key = random.PRNGKey(0)\nlayers_P = np.array([Z_dim,50,50,X_dim])\nlayers_Q = np.array([X_dim,50,50,Z_dim]) \nmodel = VAE(X, layers_Q, layers_P, init_key)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"z0C6gshYFxon\" outputId=\"3e0a188d-8f0b-49c4-afc2-f1aa88a43ae5\"\nmodel.train(num_epochs = 2000, batch_size = 256)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 296} id=\"kD6AxtKs2iZD\" outputId=\"8440e298-1602-46fd-ff41-e6212dc8d24c\"\n# Encode data and visualize the latent space\nopt_params = model.get_params(model.opt_state)\nenc_fn = lambda x: model.encode(opt_params, x)\nz_mu, z_std = vmap(enc_fn)(X)\n\nplt.figure(1)\nplt.scatter(z_mu[:,0],z_mu[:,1], c = y)\nplt.xlabel('$z_1$')\nplt.ylabel('$z_2$')\nplt.tight_layout()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"eVqHQw87ujkZ\" outputId=\"cc09a789-5d58-412b-aabd-f2e326db607a\"\n# Generate new samples\nnum_samples = 2000\nkeys = random.split(random.PRNGKey(0), num_samples)\ngen_fn = lambda key: model.generate(key, opt_params)\nx_star = vmap(gen_fn)(keys)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 296} id=\"1HkVmufU3hW6\" outputId=\"4bcd3549-4c34-4559-fb60-2f9a859d27fc\"\n# Plot convergence\nplt.figure()\nplt.plot(model.recon_loss_log, label = 'Reconstruction loss')\nplt.plot(model.KL_loss_log, label = 'KL loss')\nplt.legend()\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.tight_layout()\n","repo_name":"PredictiveIntelligenceLab/ENM5310","sub_path":"Notebooks/VAE.ipynb","file_name":"VAE.ipynb","file_ext":"py","file_size_in_byte":8423,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-jupyter-script","pt":"45"}
|
| 6 |
+
{"seq_id":"42250838458","text":"# # Matplotlib\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport numpy as np\n\n# ## Overview\n\n# ### Matplotlib’s Split Personality\n# Matplotlib is unusual in that it offers two different interfaces to plotting.\n#\n# One is a simple MATLAB-style API (Application Programming Interface) that was written to help MATLAB refugees find a ready home.\n#\n# The other is a more “Pythonic” object-oriented API.\n#\n# For reasons described below, we recommend that you use the second API.\n\n# ## The APIs\n\nx = np.linspace(0, 10, 1000)\ny = np.sin(x)\n\n# ### The MATLAB-style API\n\nplt.plot(x, y, 'b-', linewidth=2)\nplt.show()\n\n# ### The Object-Oriented API\n\n# +\nfig, ax = plt.subplots()\n# fig is a Figure instance: a \"blank canvas\"\n# ax is a AxesSubplot instance a frame for plotting in\n\nax.plot(x, y, 'b+', linewidth=2, label = 'sine function')\nax.legend()\nax.set_title('b for blue, + for thicker')\nplt.show()\n\n# +\nfig, ax = plt.subplots()\n\n# alpha adds transparency (the lowest, the smoother)\n# the text between $ signs is interpreted as LaTeX\n# we can 'control' our y-axis by setting its tick rate with ax.set_yticks\nax.plot(x, y, 'r-', linewidth=2, label='$y=\\sin(x)$', alpha = 0.6)\nax.legend(loc = 'upper center')\nax.set_yticks([-1, 0, 1])\nax.set_title('r for red, - for thinner')\nplt.show()\n# -\n\n# ## More Features\n\n# ### Multiples Plots in One Axis\n\n# +\nfrom scipy.stats import norm\nfrom random import uniform\n\nfig, ax = plt.subplots()\nx = np.linspace(-4, 4, 150)\nfor i in range(3):\n m, s = uniform(-1, 1), uniform(1, 2)\n y = norm.pdf(x, loc=m, scale=s)\n current_label = f'$\\mu = {m:.2}$'\n ax.plot(x, y, linewidth=2, alpha=0.6, label=current_label)\nax.legend()\nplt.show()\n# -\n\n# ### Multiple Subplots\n\nnum_rows, num_cols = 3, 2\nfig, axes = plt.subplots(num_rows, num_cols, figsize=(10, 12))\nfor i in range(num_rows):\n for j in range(num_cols):\n m, s = uniform(-1, 1), uniform(1, 2)\n x = norm.rvs(loc=m, scale=s, size=100)\n axes[i, j].hist(x, alpha=0.6, bins=20)\n t = f'$\\mu = {m:.2}, \\quad \\sigma = {s:.2}$'\n axes[i, j].set(title=t, xticks=[-4, 0, 4], yticks=[])\nplt.show()\n\n# ### 3D Plots\n\n# +\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\nfrom matplotlib import cm\n\n\ndef f(x, y):\n return np.cos(x**2 + y**2) / (1 + x**2 + y**2)\n\nxgrid = np.linspace(-3, 3, 50)\nygrid = xgrid\nx, y = np.meshgrid(xgrid, ygrid)\n\nfig = plt.figure(figsize=(8, 6))\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(x,\n y,\n f(x, y),\n rstride=2, cstride=2,\n cmap=cm.jet,\n alpha=0.7,\n linewidth=0.25)\nax.set_zlim(-0.5, 1.0)\nplt.show()\n\n\n# -\n\n# ### A Customizing Function\n\n# +\ndef subplots():\n \"Custom subplots with axes through the origin\"\n fig, ax = plt.subplots()\n\n # Set the axes through the origin\n for spine in ['left', 'bottom']:\n ax.spines[spine].set_position('zero')\n for spine in ['right', 'top']:\n ax.spines[spine].set_color('none')\n\n ax.grid()\n return fig, ax\n\n\nfig, ax = subplots() # Call the local version, not plt.subplots()\nx = np.linspace(-2, 10, 200)\ny = np.sin(x)\nax.plot(x, y, 'r-', linewidth=2, label='sine function', alpha=0.6)\nax.legend(loc='lower right')\nplt.show()\n","repo_name":"guilhermeolivsilva/quantecon-python-programming","sub_path":"Lectures/08_Matplotlib.ipynb","file_name":"08_Matplotlib.ipynb","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 7 |
+
{"seq_id":"8938868441","text":"# # 1. Importing libraries\n\n# +\n# to ignore warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# loading, manipulation and plotting the data\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# %matplotlib inline\n\n# splitting the data\nfrom sklearn.model_selection import train_test_split\n\n# regression models\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.ensemble import AdaBoostRegressor\n\n# model evaluation metrics\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error\n# -\n\n# # 2. Loading the data\n\ncar_df = pd.read_csv('./data/car data.csv')\n\n# getting first five rows from car_df dataframe\ncar_df.head()\n\n# getting Statistical info about the numerical columns in the data\ncar_df.describe()\n\n# getting info about the data\ncar_df.info()\n\n# # From above data we get to know two things :\n# * Is there any null values in the dataset\n# * Data type of each columns\n\n# we know that this dataset does not have any null values but let us clarify again in other method\ncar_df.isnull().sum()\n\n# **confirmed there are no null values in the dataset**\n\n# # 3. Data preparation\n\n# we will drop 'Car_Name' column from our car_df dataframe\ncar_df.drop('Car_Name', axis=1, inplace=True)\n\n# converting categorical data columns like ['Fuel_Type', 'Seller_Type', 'Transmission'] into numerical columns\ncar_df = pd.get_dummies(data=car_df, drop_first=True)\n\n# checking the columns datatypes\ncar_df.dtypes\n\n# **Categorical columns are converted to numerical columns**\n\ncar_df.head()\n\nX = car_df.drop('Selling_Price', axis=1) # features or independent variables \ny = car_df['Selling_Price'] # outcome or target or dependent variable\n\n# # 4. Splitting the datasets into train and test sets\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n# # 5. Data modelling\n\n# +\n# lets us put all our regression models into dictionary\n\nmodels = {'Linear' : LinearRegression(),\n 'RandomForest' : RandomForestRegressor(),\n 'DecisionTree' : DecisionTreeRegressor(),\n 'GradientBoosting' : GradientBoostingRegressor(),\n 'AdaBoost' : AdaBoostRegressor()}\n\n\n# -\n\ndef fit_and_score(models, X_train, X_test, y_train, y_test):\n \n np.random.seed(42)\n \n model_scores = {}\n \n for name, model in models.items():\n \n model.fit(X_train, y_train)\n \n model_scores[name] = model.score(X_test, y_test)\n \n return model_scores\n\n\nmodel_scores = fit_and_score(models, X_train, X_test, y_train, y_test)\n\nmodel_scores\n\ncompare_models = pd.DataFrame(model_scores, index=['accuracy'])\ncompare_models.T.plot(kind = 'bar')\n\n# **from above information we can say that Gradient boosting is giving higher accuracy than other models, so we choose Gradient Boosting as the good estimator for this dataset** \n\ngradient_boost_model = GradientBoostingRegressor()\ngradient_boost_model.fit(X_train, y_train)\ngradient_boost_model.score(X_test, y_test)\n\n# # 6. Model Evaluations\n\npredictions = gradient_boost_model.predict(X_test)\n\n# model predictions\npredictions[:5]\n\n# Actuals\ny_test[:5]\n\nplt.scatter(y_test, predictions)\nplt.xlabel('Actual values')\nplt.ylabel('Model predicted values')\nplt.title('RESIDUALS : Actuals vs Predicted')\nplt.show()\n\n# calculating mean_square_error, mean_absolute_error and r2_score\nmse = mean_squared_error(y_test, predictions)\nmae = mean_absolute_error(y_test, predictions)\nr2_score = r2_score(y_test, predictions)\n\nprint(\"Mean Squared Error : \", mse)\nprint(\"Mean Absolute Error : \", mae)\nprint(\"R2_score : \", r2_score)\n\n# Residual plot : MAKE SURE ITS LOOKS LIKE NORMAL DISTRIBUTION\nsns.distplot((y_test - predictions), bins=50)\n\n# # 7. Making predictions \n\nX_test[:1]\n\ncustom_data_prediction = gradient_boost_model.predict([[2020, 14.0, 80000, 0, 0, 1, 0, 1]])\n\ncustom_data_prediction\n\n# ### For given custom inputs data :\n#\n# * year = 2020\n# * present_price = 14.0\n# * kms_driven = 80000\n# * owner = 0\n# * fuel_type_diesel = 0\n# * fuel_type_petrol = 1\n# * seller_type_indivdual = 0\n# * transmission_manual = 1\n#\n# ## PREDICTED :\n#\n# Selling price is = 9.955\n\n# # END\n\n\n","repo_name":"venu9251/Regression","sub_path":"Car price prediction beginner .ipynb","file_name":"Car price prediction beginner .ipynb","file_ext":"py","file_size_in_byte":4290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 8 |
+
{"seq_id":"15420251372","text":"# +\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport cycler\nimport time\nimport numpy as np\nimport tqdm\nimport multiprocessing as mproc\n\n\nimport seaborn as sns\n\nimport util\nimport dtaidistance.dtw\nfrom dtaidistance import dtw_visualisation as dtwvis\n\nexperiments = [{'dist_type': 'fit','n_bins': 3000, 'predefined_dists': True},\n {'dist_type': 'empirical','n_bins': 3000, 'predefined_dists': True}\n ]\n\n\n# -\n\ndef process_sample_input(input):\n results = {}\n tweets_per_file = util.load_data(**input)\n if len(tweets_per_file) == 0:\n return\n\n for e in experiments:\n d_type = e['dist_type']\n args = (e['n_bins'], tweets_per_file, d_type, e['predefined_dists'])\n results[d_type] = util.run(args)\n \n filename = f'../results/detect_drifts_m_{input[\"month\"]}_' \\\n + f'd_{input[\"days_range\"][0]}_' \\\n + f'{input[\"days_range\"][1]}' \\\n + f'_{int(time.time())}.pkl'\n pd.to_pickle(results, filename)\n print(filename)\n\n\n\ninput_params_full = []\nfor month in range(8,9):\n input_params_month = []\n for week in range(5):\n input_params_month.append(\n { 'days_range': (week*7+1,(week+1)*7+1 if week < 4 else 32), \n 'month': month,\n 'hours_range': (0,24),\n }\n )\n input_params_full.append(input_params_month)\n\nfor input_month_params in input_params_full:\n args_gen = (input for input in input_month_params)\n p = mproc.Pool(processes=5)\n results = p.imap(process_sample_input, args_gen)\n\n tqdm.tqdm(total=len(input_month_params))\n\n p.close()\n p.join()\n\n# +\nimport requests\nfrom datetime import datetime\nimport time\n\nhora = datetime.now()\nhora = hora.strftime(\"%H:%M:%S\")\n\nurl = 'https://api.dontpad.com/thalistdg'\n\nheaders = {}\n\nbody = {\n \"text\": f\"Terminou {hora}\",\n \"captcha-token-v2\":\t\"\",\n \"force\": \"true\",\n}\n\n\ntry:\n req = requests.post(url,headers=headers, params=body)\n print(req)\nexcept Exception as ex:\n # raise ex\n time.sleep(5)\n req = requests.post(url,headers=headers, params=body)\n\n# -\n\n# !shutdown\n\n# +\nlist_table_times = []\nlist_table_dist_vs_mini = []\nlist_table_fit_vs_empirical = []\n\nfor file in util.results_drifts_file_names:\n results = pd.read_pickle('../results/' + file)\n results_times = {}\n results_drifts = {}\n dtw_dist_vs_minibatch = {}\n dtw_fit_vs_empirical = {}\n \n for exp_type in results:\n results_drifts[exp_type] = results[exp_type][0]\n results_times[exp_type] = results[exp_type][1]\n\n dtw_dist_vs_minibatch[exp_type] = {k:dtaidistance.dtw.distance(results_drifts[exp_type].get(k, []), results_drifts[exp_type]['mini-batch'])\n for k in util.approx_methods}\n \n table_times = pd.DataFrame(results_times)\n table_times = table_times.rename(columns={'fit': 'Fitter time', 'empirical': 'Empirical time'})\n list_table_times.append(table_times)\n\n table_dist_vs_mini = pd.DataFrame(dtw_dist_vs_minibatch)\n table_dist_vs_mini = table_dist_vs_mini.rename(columns={'fit': 'Fitter DTW', 'empirical': 'Empirical DTW'})\n list_table_dist_vs_mini.append(table_dist_vs_mini)\n\n dtw_fit_vs_empirical = {'Fitter vs Empirical':\n {k:dtaidistance.dtw.distance(results_drifts['fit'].get(k, []), results_drifts['empirical'].get(k, []))\n for k in results_drifts['fit'].keys()},\n 'Fitter drifts':\n {k:len(results_drifts['fit'][k]) for k in results_drifts['fit'].keys()},\n 'Empirical drifts':\n {k:len(results_drifts['empirical'][k]) for k in results_drifts['fit'].keys()}\n }\n table_fit_vs_emp = pd.DataFrame(dtw_fit_vs_empirical)\n list_table_fit_vs_empirical.append(table_fit_vs_emp)\n\n\n# +\ntable_times = pd.concat(list_table_times)\ntable_times = table_times.groupby(table_times.index).mean()\n\ntable_dist_vs_mini = pd.concat(list_table_dist_vs_mini)\ntable_dist_vs_mini = table_dist_vs_mini.groupby(table_dist_vs_mini.index).mean()\n\ntable_fit_vs_empirical = pd.concat(list_table_fit_vs_empirical)\ntable_fit_vs_empirical = table_fit_vs_empirical.groupby(table_fit_vs_empirical.index).mean()\n\n# +\ntable_times_dist_vs_mini = pd.concat([table_times.T, table_dist_vs_mini.T]).T\ntable_times_dist_vs_mini = table_times_dist_vs_mini.style.format(precision=0, thousands=\".\", decimal=\",\")\n\ntable_fit_vs_empirical = table_fit_vs_empirical.style.format(precision=0, thousands=\".\", decimal=\",\")\n\ndisplay(table_times_dist_vs_mini)\ndisplay(table_fit_vs_empirical)\n\ntable_times_dist_vs_mini.to_latex('../table_times_dist_vs_mini.tex')\ntable_fit_vs_empirical.to_latex('../table_fit_vs_empirical.tex')\n\n# +\nf_vs_e = [(results_drifts['fit'].get(k, []), results_drifts['empirical'].get(k, [])) for k in results_drifts['fit'].keys() if k != 'Page Hinkley']\n\nfigg, axs = plt.subplots(4, 2, figsize=(12,5), sharey=True, gridspec_kw={'hspace':0.0, 'wspace':0.0})\n\nfor i,k in enumerate(results_drifts['fit'].keys()):\n if k == 'Page Hinkley':\n continue\n s1 = np.array(results_drifts['fit'].get(k, []))\n s2 = np.array(results_drifts['empirical'].get(k, []))\n\n print(k)\n if i == 3 or i == 4:\n init = 2\n else:\n init = 0\n\n if i == 1:\n axs[0][0].set_title(k)\n elif i == 2:\n axs[0][1].set_title(k)\n elif i == 3:\n axs[2][0].set_title(k)\n elif i == 4:\n axs[2][1].set_title(k)\n\n path = dtaidistance.dtw.warping_path(s1, s2)\n dtwvis.plot_warping(s1, s2, path, fig=figg, axs=axs.T[(i-1)%2][init:])\n\n\n# +\ndef read_all_weeks(file_names):\n results_all_fit = []\n results_all_empirical = []\n \n for file_name in file_names:\n results = pd.read_pickle(f'../results/{file_name}')\n\n results_times = {}\n results_drifts = {}\n dict_one_week = {} \n\n for exp_type in results:\n results_drifts[exp_type] = results[exp_type][0]\n results_times[exp_type] = results[exp_type][1]\n\n dict_one_week[exp_type] = {k:dtaidistance.dtw.distance(results_drifts[exp_type].get(k, []), results_drifts[exp_type]['mini-batch'])\n for k in util.approx_methods}\n\n \n results_one_week_fit = pd.DataFrame(dict_one_week['fit'], index=[''])\n results_all_fit.append(results_one_week_fit)\n\n results_one_week_empirical = pd.DataFrame(dict_one_week['empirical'], index=[''])\n results_all_empirical.append(results_one_week_empirical)\n \n\n return pd.concat(results_all_fit), pd.concat(results_all_empirical)\n\n\n# -\n\nresults_dtw = read_all_weeks(util.results_drifts_file_names)\n\n# +\nfont = {\n 'family':'serif', \n 'weight':'normal', \n 'size':12\n}\nmatplotlib.rc('font', **font)\n\naxes_prop_cycle = {\n 'markersize':[8]*20,\n 'linewidth':[1]*20,\n 'markevery': [8]*20,\n 'marker':['o', 'X', 's', 'P', 'D']*4,\n 'color':sns.color_palette(\"Set1\", 20)\n}\nmatplotlib.rc('axes', prop_cycle=cycler.cycler(**axes_prop_cycle))\n\nmatplotlib.rc('mathtext', fontset='cm')\n\npd.options.display.float_format = '{:,.4f}'.format\n\ndef show_results(results, axs, d_type, legend=False):\n bps = axs[0].boxplot(results, vert=False, patch_artist=True)\n axs[0].set_xscale('log')\n axs[0].grid(axis='x')\n axs[0].set_title(r'Distribution type: ' + d_type)\n axs[0].set_yticklabels([])\n \n for i, j, k, l in zip(bps['boxes'], bps['medians'], axes_prop_cycle['marker'][3::-1], axes_prop_cycle['color']):\n i.set_facecolor(l)\n j.set_color('black')\n j.set_marker(k)\n j.set_markevery(1)\n j.set_markerfacecolor(l)\n \n sns.ecdfplot(results, log_scale=True, ax=axs[1], legend=legend, alpha=0.8, palette=axes_prop_cycle['color'][:4])\n axs[1].grid()\n axs[1].set_ylim([-0.05, 1.05])\n \n return bps\n\nfig, axs = plt.subplots(2,2, sharex=True, figsize=(8,5), gridspec_kw={'hspace':0.0, 'wspace':0.0})\n\nfor e, (i,j, k) in enumerate(zip(results_dtw, axs.T, ['Fitter', 'Empirical'])):\n zz = show_results(results_dtw[e], j, k, e == 0)\n j[0].set_yticklabels([])\n \n if e:\n j[1].set_yticklabels([])\n j[1].set_ylabel('')\n \n\naxs[1,0].set_ylabel('Cumulative Probability')\naxs[1,1].set_xlabel('DTW value')\naxs[1,1].xaxis.set_label_coords(0, -.2)\nsns.move_legend(axs[1,0], loc='lower center', ncol=5, bbox_to_anchor=(1.0, -0.55))\n\nfor i, j in zip(axs[1,0].legend_.legendHandles, axes_prop_cycle['marker'][3::-1]): \n i.set_marker(j)\n i.set_markersize(6)\n\n\nfig.tight_layout()\n\nfig.savefig('../figs/twitter_dtw.pdf')\n","repo_name":"thalistdg/TCC","sub_path":"src/detect_drifts.ipynb","file_name":"detect_drifts.ipynb","file_ext":"py","file_size_in_byte":8657,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"45"}
|
| 9 |
+
{"seq_id":"3102192526","text":"import numpy as np \ndata=[1,2,3,4,5,6]\na1=np.array(data)\na1\n\ndata=[[1,2,3,4],[5,6,7,8]]\na2=np.array(data)\na2\n\na1.ndim\n\na2.ndim\n\na3=np.array([12,23,34,45])\na3\n\na4=np.array([1,2,3,4],ndmin=5)\na4\n\n#\n\na4.ndim\n\na1.shape\n\na2.shape\n\na2.shape[0]\n\na2.shape[1]\n\na2.size\n\nnp.arange(5)\n\nnp.arange(0,8)\n\nnp.arange(2,10)\n\nnp.arange(2,10,2)\n\na=np.array([10,20,30,40])\nnew_a=a.reshape(2,2)\nnew_a\n\nnp.reshape(a,(2,2))\n\na5=np.arange(0,10)\na5\n\nnp.reshape(a5,(2,5))\n\nnp.reshape(a5,(5,2))\n\na5[2]\n\na5[5]\n\na2[0,1]\n\na2[1,3]\n\n# +\n#math operations \n# -\n\na=np.array([1,2,3,4,5])\na-5\n\na*5\n\na**2\n\na%5\n\na=np.arange(5,15,2)\na\n\nnp.mean(a)\n\nnp.median(a)\n\nnp.std(a)\n\n#slicing\n\n\na5[0:3]\n\na5[:4]\n\na5[3:]\n\na5[1:6:2]\n\na5[::2]\n\na5[-1]\n\na2[1,0:2]\n\na5[-4:-1]\n\na2[:-1]\n\na=np.array([[1,2,3,4,5],[6,7,8,9,10]])\na\n\na[::-1,::-1]\n\n\n\nnp.flip(a,axis=0)\n\nnp.flip(a,axis=1)\n\n#special array\n\n\nnp.zeros(5)\n\nnp.zeros((2,3))\n\nnp.ones(5,dtype=np.int32)\n\nnp.random.rand(2,3)\n\nnp.full((2,2),7)\n\nnp.eye(3)\n\nnp.eye(3,dtype=np.int32)\n\nnp.eye(3,dtype=np.int32,k=1)\n\nnp.eye(3,dtype=np.int32,k=-1)\n\n# +\n#stacking and concatenating\n# -\n\na=np.arange(0,5)\nb=np.arange(6,11 )\nnp.vstack((a,b))\n\nnp.hstack((a,b))\n\nnp.concatenate((a,b),axis=0)\n\nnp.concatenate((a,b),axis=1)\n\n\n\na=np.array([[1,2],[3,4]])\nnp.append(a,[[5,6]],axis=0)\n\na=np.array([[1,2],[3,4]])\nnp.append(a,[[5],[6]],axis=1)\n\n\n","repo_name":"Karthi1003/session-5","sub_path":"session5 intro to data science , numpy.ipynb","file_name":"session5 intro to data science , numpy.ipynb","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 10 |
+
{"seq_id":"34442667072","text":"# # Insurance \n# ## Linear Regression\n# <!-- -->\n# **Project Contenet**\n# <li><a href='#intro'>Introduction</a></li>\n# <li><a href='#wrang'>Data Wranglling</a></li>\n# <li><a href='#eda'>Exploratory Data Analysis</a></li>\n# <li><a href='#mch'>Machine Learning Engineer</a></li>\n# <li><a href='#conc'>Conclusion</a></li>\n\n# <a id='intro'></a>\n# ## Introduction\n\n# dataset contain 7 features:\n#\n# age.\n# sex\n# bmI:Body Mass Index.\n# children.\n# smoker.\n# region.\n# charges.\n#\n# **Project Goal**\n# Apply a full data science process on medical assurance data including full data analysis and ML to predict medical assurance charges\n\n# ### Basic Imports\n\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom datasist.structdata import detect_outliers\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import SVR\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom xgboost import XGBRegressor\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\nsns.set_theme(rc={'figure.figsize':[10,5]},style='darkgrid',palette='flare',font_scale=1.2)\n\n\n# <a id='wrang'></a>\n# ## Data Wranglling\n# Process contains \n# <li><a href='#dc'>Data Discovery</a></li>\n# <li><a href='#clea'>Data Cleaning</a></li>\n# <li><a href='#vald'>Data Validating</a></li>\n\n# <a id='dc'></a>\n# ## Data Discovery\n\ndef load_data(path):\n df = pd.read_csv(path)\n df.name = path.split('.')[0] \n print(f'{df.name} dataset loaded successfuly')\n return df\n\n\ndf= load_data('insurance.csv')\n\n\ndef explore_data(df,num_row=5):\n print(f'{df.name} dataset contain {df.shape[0]} rows & {df.shape[1]} columns')\n print(f' Top {num_row} rows:')\n display(df.head(num_row))\n print('*'*50)\n print(f'Last {num_row} rows:')\n display(df.tail(num_row))\n\n\nexplore_data(df)\n\n\ndef data_type_missing(df):\n type_df = pd.DataFrame()\n type_df['features'] = df.columns\n type_df['first_val'] = pd.Series([df[col][0] for col in df.columns])\n type_df.set_index('features',inplace=True)\n type_df['dtype'] = df.dtypes\n type_df['count_missing'] = df.isna().sum()\n type_df['missing_%'] = df.isna().sum() / df.shape[0] * 100\n display(type_df)\n print('*'*50)\n print(df.info())\n\n\ndata_type_missing(df)\n\n\ndef quantitative_descriptive_stats(df):\n desc_df = df.describe()\n desc_df.loc['range'] = desc_df.loc['max'] -desc_df.loc['min']\n desc_df.loc['iqr'] = desc_df.loc['75%'] -desc_df.loc['25%']\n desc_df.loc['min_whisker'] = desc_df.loc['25%'] - 1.5 * desc_df.loc['iqr']\n desc_df.loc['max_whisker'] = desc_df.loc['75%'] + 1.5 * desc_df.loc['iqr']\n display(desc_df)\n for col in df.select_dtypes(include=['number']).columns:\n sns.boxplot(data=df,x=col)\n plt.title(f'{col} distribution')\n plt.show()\n\n\nquantitative_descriptive_stats(df) \n\n\ndef qualitative_decripitive_stats(df):\n display(df.describe(exclude=['number']))\n for col in df.select_dtypes(include=['O']).columns:\n print(f'{col} has {df[col].nunique()} unique values')\n if df[col].nunique()<=10:\n print(df[col].value_counts())\n sns.countplot(data=df,x=col)\n plt.title(f'{col} Frequency')\n plt.show()\n print(\"*\"*50)\n\n\nqualitative_decripitive_stats(df)\n\n\ndef duplicates(df):\n print(f'{df.name} has {df.duplicated().sum()} duplicated rows')\n if df.duplicated().sum() > 0:\n print('First duplicated')\n display(df[df.duplicated(keep='first')])\n print('*'*50)\n print('Last duplicated')\n display(df[df.duplicated(keep='last')])\n\n\nduplicates(df)\n\n# #### Finding:\n# * Insurance dataset contain 1338 rows & 7 columns. \n# * Dataset has the right features datatypes & it contains quantitative & qualitative vaiables.\n# * Dataset doesn't contain any missing values. \n# * Dataset has 1 duplicated row.\n# * Dataset has outliers on bmi & charges will handle them later. \n\n# <a id='clea'></a>\n# #### Data Cleaning\n# **Drop Duplicated row**\n\ndf.drop_duplicates(inplace=True)\n\n# <a id='vald'></a>\n# #### Data Validating\n\nduplicates(df)\n\nexplore_data(df)\n\n\n# * Dataset is ready now for analysis. \n\n# <a id='eda'></a>\n# ## Exploratory Data Analysis\n# <li><a href='#uni'>Univariate Analysis</a></li>\n# <li><a href='#bi'>Bivariate Analysis</a></li>\n# <li><a href='#multi'>multivariate Analysis</a></li>\n\n# <a id='uni'></a>\n# #### Univariate Analysis\n# #### Quantitative Continues Variable \n\ndef quantit_uni(df,col):\n fig, (ax1, ax2) = plt.subplots(2)\n ax1 = sns.histplot(data= df,x=col,ax=ax1)\n ax2 = sns.boxplot(data=df,x=col,ax=ax2)\n fig.suptitle(f'{col} Distribution')\n plt.show()\n display(df[col].describe())\n\n\n\nquantit_uni(df,'bmi')\n\n# * bmi has normal distribution with mean 30.66 & stdandrd deviation 6.10\n# * 75% of the data have bmi 34.7 while 90% of the data has the range from (13.7 to 47.29) & only 5% of the data is greater than 47.29 with maximum 53.13 appear as maximum outliers. \n\nquantit_uni(df,'charges')\n\n# * charges has right skewed distribution with mean 13279.12 & stdandrd deviation 12110.36 which indicated that data has a huge disperession\n# * 25% of the vahrges has value 4746.34, 50% of the data has charges 9386.16 & 75% of the data 16657.71.\n# * 90% of the data is within range (-13109.15,34489.35) while 5% of the data is greater than 34489.35 with maximum 63770.42 appear as outliers.\n\nquantit_uni(df,'age')\n\n\n# * Data is unimodal it has one one mode on 18 except that it has almost a uniform distribution with mean 39.22 and standard deviation 14.04 with no ouliers.\n\ndef discrete_uni(df,col):\n fig, (ax1, ax2) = plt.subplots(2)\n ax1 = sns.countplot(data= df,x=col,ax=ax1)\n ax2 = sns.boxplot(data=df,x=col,ax=ax2)\n fig.suptitle(f'{col} Distribution')\n plt.show()\n display(df[col].describe())\n\n\n\ndiscrete_uni(df,'children')\n\n\n# * Children has a unimodal with value 0 & mean 1 with no ouliers & the maximum is 5\n\n# #### Qualitative univariate analysis\n\ndef qualitative_uni(df):\n for col in df.select_dtypes(include=['O']).columns:\n print(f'{col} has {df[col].nunique()} unique values')\n if df[col].nunique()<=10:\n print(df[col].value_counts())\n sns.countplot(data=df,x=col)\n plt.title(f'{col} Frequency')\n plt.show()\n print(\"*\"*50)\n\n\nqualitative_uni(df)\n\n# * sex has 2 unique values & it almost has a uniform distribution. \n# * smoker has 2 unique values & it's a unimodal with value no smoker. \n# * region has 4 unique values & hardly we can say it has a unimodal with value southeast. \n\n# ### Explore Outliers\n\noutliers = df.loc[detect_outliers(df,0,['charges'])]\noutliers\n\nquantit_uni(outliers,'bmi')\n\n# * in charges outliers data bmi hardly has normal distribution with mean 35.56 & stdandrd deviation 4.43.\n# * 75% of the data have bmi 37.66 while 90% of the data has the range from (26 to 45).\n\nquantit_uni(outliers,'charges')\n\n# * charges has right skewed distribution with mean 42103.95 & stdandrd deviation 5582.17 which indicated that data has a huge disperession\n# * 25% of the vahrges has value 37786.14, 50% of the data has charges 40974.16 & 75% of the data 45786.70.\n\nquantit_uni(outliers,'age')\n\n# * Data is bimodal it has one two mode on 19 & 64.\n\ndiscrete_uni(outliers,'children')\n\n# * Children has a unimodal with value 0 & mean 1 with no ouliers & the maximum is 4\n\n# #### Qualitative univariate analysis\n\nqualitative_uni(outliers)\n\n# * sex has 2 unique values & it's a unimodal with value male. \n# * smoker has 2 unique values & it's a unimodal with value smoker. \n# * region has 4 unique values & easily we can say it has a unimodal with value southeast.\n\n# * we will cut 5% of the maximum & minimum values of caharges & compelete our analysis on that approach even on prediction & will see the result how it would be.\n\nclean = df[(df['charges'] >= -13109) & (df['charges'] <=34490) ]\nclean.size\n\n# <a id='bi'></a>\n# ## Bivariate Analysis\n#\n# **Two quantitaive variable**\n\nsns.pairplot(clean)\n\nsns.heatmap(clean.corr(),annot=True,fmt='0.2f')\n\n# * it appear that age have a meduim positive correlation with charges, while bmi has a slight negative effect on charges & children has slight positive correlation on it.\n\n# **one quantitaive & one qualitative**\n\nclean.columns\n\n# **charges vs sex**\n\nsns.boxplot(data=clean,x='charges',y='sex')\nplt.title(\"charges vs sex\")\nplt.show()\n\nsex_charges = clean.groupby('sex').describe()['charges']\ndisplay(sex_charges)\n\n# * from graph above we can find that male has little more variation the female due to charges also both of them is positively skewed.\n# * Male & female is positively skewed also both of them has outliers\n# * female 50% of the data has range (4885,14454) while male (4654,19006). \n\n# **bmi vs sex**\n\nsns.boxplot(data=clean,x='bmi',y='sex')\nplt.title(\"bmi vs sex\")\nplt.show()\n\nsex_bmi = clean.groupby('sex').describe()['bmi']\ndisplay(sex_bmi)\n\n# * from graph above we can find that male & female almost have same variation due to bmi, also both of them is positively skewed.\n# * Male & female is positively skewed also both of them has outliers\n# * female 50% of the data has range (26,34) while male (26,35) alomst has same range of data. \n\n# **age vs sex**\n\nsns.boxplot(data=clean,x='age',y='sex')\nplt.title(\"age vs sex\")\nplt.show()\n\nsex_age = clean.groupby('sex').describe()['age']\ndisplay(sex_age)\n\n# * from graph above we can find that male & female have same variation due to ages male are negatively skewed while female positively skewed.\n# * both of them has no outliers\n# * female 50% of the data has range (27,51) while male (26,51) alomst has same range of data. \n\n# **cahrges vs smoker**\n\nsns.boxplot(data=clean,x='charges',y='smoker')\nplt.title(\"charges vs smoker\")\nplt.show()\n\nsmoker_charges = clean.groupby('smoker').describe()['charges']\ndisplay(smoker_charges)\n\n# * from graph above we can find that non smoker has more variation on charges than smoker charges.\n# * non smoker has outliers in charges while smoker doesn't. \n# * smoker is negatively skewed while non smoker positively skewed\n# * from above we can indicates that smoker has more charges than non smoker. \n\n# **bmi vs smoker**\n\nsns.boxplot(data=clean,x='bmi',y='smoker')\nplt.title(\"bmi vs smoker\")\nplt.show()\n\nsmoker_bmi = clean.groupby('smoker').describe()['bmi']\ndisplay(smoker_bmi)\n\n# * from graph above we can find that almost have same variation.\n# * non smoker has outliers in bmi while smoker doesn't. \n# * both of them are positively skewed due to bmi.\n# * from above we can indicates that smoker has less bmi than non smoker. \n\n# **age vs smoker**\n\nsns.boxplot(data=clean,x='age',y='smoker')\nplt.title(\"age vs smoker\")\nplt.show()\n\nsmoker_age = clean.groupby('smoker').describe()['age']\ndisplay(smoker_age)\n\n# * from graph above we can find that smoker & non smoker almost have same variation due to age with no outliers on both.\n# * smoker is positively skewed while non smoker is negatively skewed to age.\n# * smoker & non smoker almost has the same range due to ages with min 18 & max 64. \n\n# **charges vs region**\n\nsns.boxplot(data=clean,x='charges',y='region')\nplt.title(\"charges vs region\")\nplt.show()\n\nregion_charges = clean.groupby('region').describe()['charges']\ndisplay(region_charges)\n\n# * from graph above we can find that northeast & northwest almost have same variation due to charges while the are less than southeast & southwest which are amlost equal.\n# * all region are is positively skewed.\n# * all region have outliers. \n# * there are a little difference on ranges.\n\n# **bmi vs region**\n\nsns.boxplot(data=clean,x='bmi',y='region')\nplt.title(\"bmi vs region\")\nplt.show()\n\nregion_bmi = clean.groupby('region').describe()['bmi']\ndisplay(region_bmi)\n\n# * from graph above we can find that all region have same variation due to bmi.\n# * all region are is positively skewed.\n# * all region have outliers. \n# * there are a little difference on ranges.\n\n# **age vs region**\n\nsns.boxplot(data=clean,x='age',y='region')\nplt.title(\"age vs region\")\nplt.show()\n\nregion_age = clean.groupby('region').describe()['age']\ndisplay(region_age)\n\n# * from graph above we can find that all region have same variation due to ages.\n# * northeast & southeast are is negetively skewed while othere are positively skewed.\n# * There are no outliers in all regions. \n# * age ranges almost equal.\n\n# <a id='multi'></a>\n# ## multivariate Analysis\n\nsns.pairplot(clean,hue='smoker',palette='rocket')\n\nsns.pairplot(clean,hue='sex',palette='mako')\n\nsns.pairplot(clean,hue='region',palette='rocket')\n\n# * From above we can find that data is distributed normally due to categories there are no big varaition on distribution as we cleared on qualitative bivariate analysis \n\nsns.set_theme(rc={'figure.figsize':[8,10]})\ng = sns.FacetGrid(clean, col=\"smoker\", row=\"region\",hue='sex')\ng.map(sns.scatterplot, \"charges\", \"age\")\nplt.title('Charges vs ages by smoker, region & sex')\nplt.legend(loc='lower right')\nplt.show()\n\n# * almost same distribution on both male & female while now we can see a linear correlation between all variables vs charges \n# * will go through next steps in order to implies linear regression model.\n\n# <a id='mch'></a>\n# ## Machine Learning Engineer\n#\n# ### Deal with categorical variable \n# * use one hot encoded to convert categorical variable to nmerical\n\nclean.columns\n\ncateg= clean.select_dtypes(include=['O']).columns\ncateg\n\n\ndef one_hot(df):\n categ= df.select_dtypes(include=['O']).columns\n clean = pd.get_dummies(df,columns=categ,drop_first=True)\n display(clean.head())\n return clean\n\n\nclean= one_hot(clean)\n\n\n# ### split data into train & test\n#\n\ndef x_y(df):\n x= df.drop('charges',axis=1)\n y= df['charges']\n print(x.shape,y.shape)\n return x,y\n\n\nx,y = x_y(clean)\n\n\ndef train_test(x,y,test_size=0.33, random_state=42):\n x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=test_size, random_state=random_state)\n print(x_train.size, x_test.size, y_train.size, y_test.size)\n return x_train, x_test, y_train, y_test\n\n\nx_train, x_test, y_train, y_test = train_test(x,y,test_size=0.33, random_state=42)\n\n\n# ### Feature Scaling\n# use standard scaler\n\ndef standard_scaler(x_train,y_train):\n scaler= StandardScaler()\n scaler.fit(x_train)\n scaled_x_train = scaler.transform(x_train)\n scaled_x_test = scaler.transform(x_test)\n return scaled_x_train,scaled_x_test\n\n\nscaled_x_train,scaled_x_test = standard_scaler(x_train,y_train)\n\n\n# ### Linear Regression model\n\n# +\ndef linear_model(x_train,x_test,y_train,y_test):\n model = LinearRegression()\n model.fit(scaled_x_train,y_train)\n y_pred_train = model.predict(scaled_x_train)\n y_pred_test = model.predict(scaled_x_test)\n\n print(f'train_score: {model.score(scaled_x_train,y_train)}')\n print(f'train_score: {model.score(scaled_x_test,y_test)}')\n print(\"\\n\")\n print(f\"Train R2: {r2_score(y_train, y_pred_train)}\")\n print(f\"Test R2: {r2_score(y_test, y_pred_test)}\")\n print(\"\\n\")\n print(f\"Train MAE: {mean_absolute_error(y_train, y_pred_train)}\")\n print(f\"Test MAE: {mean_absolute_error(y_test, y_pred_test)}\")\n print(\"\\n\")\n print(f\"Train RMSE: {np.sqrt(mean_squared_error(y_train, y_pred_train))}\")\n print(f\"Test RMSE: {np.sqrt(mean_squared_error(y_test, y_pred_test))}\")\n return model, y_pred_test\n\n \n# -\n\nmodel , y_pred_test = linear_model(scaled_x_train,scaled_x_test,y_train,y_test)\n\n# ## Another approch \n# remove outliers to zero using detect_outliers\n\nclean_detect = df.drop(detect_outliers(df,0,['charges','bmi']))\nclean_detect.shape\n\n# ### Deal with categorical variable \n# * use one hot encoded to convert categorical variable to nmerical\n\nclean_detect= one_hot(clean_detect)\n\n# ### split data into train & test\n#\n\nx,y = x_y(clean_detect)\n\nx_train, x_test, y_train, y_test = train_test(x,y,test_size=0.33, random_state=42)\n\n# ### Feature Scaling\n# use standard scaler\n\nscaled_x_train,scaled_x_test = standard_scaler(x_train,y_train)\n\n# ### Linear Regression model\n\nmodel2 , y_pred_test2 = linear_model(scaled_x_train,scaled_x_test,y_train,y_test)\n\n# * as we see the test R^2 are less on the second approach so we will improve on the first approach \n\nclean2= clean.copy()\nclean2.head()\n\nsns.set_theme(rc={'figure.figsize':[8,5]})\nsns.boxplot(data=clean2,x='bmi')\n\nsns.boxplot(data=clean2,x='charges')\n\nfeatures=['bmi','charges']\nfor col in features:\n idx = detect_outliers(clean2,0,[col])\n clean2.loc[idx,col] = clean2[col].median()\n\nclean2[['bmi','charges']].describe()\n\nsns.set_theme(rc={'figure.figsize':[8,5]})\nsns.boxplot(data=clean2,x='bmi')\n\nsns.boxplot(data=clean2,x='charges')\n\n# ### split data into train & test\n#\n\nx,y = x_y(clean2)\n\nx_train, x_test, y_train, y_test = train_test(x,y,test_size=0.33, random_state=42)\n\n# ### Feature Scaling\n# use standard scaler\n\nscaled_x_train,scaled_x_test = standard_scaler(x_train,y_train)\n\n# ### Linear Regression model\n\nmodel3 , y_pred_test3 = linear_model(scaled_x_train,scaled_x_test,y_train,y_test)\n\n# As we can see now wehen replaced the outliers in charges & bmi with median we have less R2 the best model was clean the first one with Train R2: 0.60 & Test R2: 0.60\n\n# * **Lets us check other models on the first data clean using:** \n# * 'LR': LinearRegression(),\n# * 'SVM': SVR(),\n# * 'KNN': KNeighborsRegressor(),\n# * 'DT': DecisionTreeRegressor(),\n# * 'RF': RandomForestRegressor(),\n# * 'XGB': XGBRegressor()\n\nx,y = x_y(clean)\n\nx_train, x_test, y_train, y_test = train_test(x,y,test_size=0.33, random_state=42)\n\n# +\nmodels = {\n 'LR': LinearRegression(),\n 'SVM': SVR(),\n 'KNN': KNeighborsRegressor(),\n 'DT': DecisionTreeRegressor(),\n 'RF': RandomForestRegressor(),\n 'XGB': XGBRegressor()\n}\n\n\nfor name, model in models.items():\n print(f\"Model: {name}\")\n print(\"-\"*20)\n model.fit(x_train, y_train)\n y_pred_train = model.predict(x_train)\n y_pred_test = model.predict(x_test)\n print(f\"Train MAE: {mean_absolute_error(y_train, y_pred_train)}\")\n print(f\"Test MAE: {mean_absolute_error(y_test, y_pred_test)}\")\n print(f\"Train RMSE: {np.sqrt(mean_squared_error(y_train, y_pred_train))}\")\n print(f\"Test RMSE: {np.sqrt(mean_squared_error(y_test, y_pred_test))}\")\n print(f\"Train R2: {r2_score(y_train, y_pred_train)}\")\n print(f\"Test R2: {r2_score(y_test, y_pred_test)}\")\n print(\"\\n\")\n# -\n\n# * **Best model wa linear regression on clean dataset with trimmed 5% of the dataset due to outliers on charges**\n\nmodel , y_pred_test = linear_model(scaled_x_train,scaled_x_test,y_train,y_test)\n\n# <a id='conc'></a>\n# ## Conclusion\n# * Model: LR: has a weak linear model with Train R2: 0.60 & Test R2: 0.60 , features has no linear correlation with the response chrages tha's one of the reasons that r2 is weak as we apllied linear regression model on this while no linearity with the response.\n# * Model: RF, Model: XGB have overfitting problem . \n\n\n","repo_name":"esraagamal-111/InsurancePrediction","sub_path":"Insurance_Linear_regression.ipynb","file_name":"Insurance_Linear_regression.ipynb","file_ext":"py","file_size_in_byte":19158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 11 |
+
{"seq_id":"770973963","text":"# + [markdown] id=\"0SWi0mgM5hDS\"\n# # **OLYMPICS DATA ANALYSIS** \n\n# + id=\"lJG_-h3nEU9u\"\n#@title Importing dataset\n\nurl1 = 'https://raw.githubusercontent.com/tejaschaudhari192/Olympics-data-analysis/master/Dataset/athlete_events.csv'\nurl2 = 'https://raw.githubusercontent.com/tejaschaudhari192/Olympics-data-analysis/master/Dataset/noc_regions.csv'\n\n# + id=\"6vp4FKwEqytK\"\n#@title Importing Libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# %matplotlib inline\n\n# + id=\"scsAg384N8Zs\"\n# athletes = pd.read_csv('C:/Users/Tejas/Teja Server ⚡/programming/Projects/Olympics/Dataset/athlete_events.csv')\nathletes = pd.read_csv(url1)\n# regions = pd.read_csv('C:/Users/Tejas/Teja Server ⚡/programming/Projects/Olympics/Dataset/noc_regions.csv')\nregions = pd.read_csv(url2)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 389} id=\"oR3tQhGKOHaI\" outputId=\"32319524-56c2-4fdc-c65f-53b2e6f4b3cf\"\nathletes.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"l5UffI-KOb5I\" outputId=\"c2f7c9c5-2b38-4940-ee06-45117882885e\"\nregions.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 496} id=\"ZCc5jdOH67NM\" outputId=\"14f1b51a-57f0-46de-a366-09d2e24865a2\"\n#Join The Dataframes\nathletes_df = athletes.merge(regions, how = 'left', on = 'NOC')\nathletes_df.head() \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"9R22srOlqI6v\" outputId=\"1b4fda85-ce44-4a8a-f872-df074d75e8ea\"\nathletes_df.shape\n\n# + id=\"aeyXNT9zrGFV\"\n#Column Name Consistent\nathletes_df.rename( columns = {'region' : 'Regions', 'notes' : 'Notes'}, inplace= True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 496} id=\"5UJoXwS8r1nf\" outputId=\"7b5fd960-e3f3-445b-b2c5-5ba5c910ea11\"\nathletes_df.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"bGqCNdV_r8T2\" outputId=\"1e6b552f-e4a5-42e1-8b69-463c7ca5ff58\"\nathletes_df.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 300} id=\"YhXaBD2HsFSO\" outputId=\"530783a2-5228-4838-b90e-6f72b557d9a0\"\n\n\nathletes_df.describe()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"WPaqkQXssTWX\" outputId=\"5f40ea86-595a-4ff1-8c32-c1cdb0f987a8\"\n#Check Null Values\nnan_values = athletes_df.isna()\nnan_columns = nan_values.any()\nnan_columns\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8PDyZYwYtjC9\" outputId=\"3d5eae73-6ede-4f60-d7fb-b8a76eee0b46\"\nathletes_df.isnull().sum()\n\n# + id=\"owcHZET5uC7U\"\n#Colums Containing Null Values\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 979} id=\"y744PoQiuDwf\" outputId=\"99f3cbd8-cd7a-430c-c296-45cbcf8200b9\"\n#India Details \nathletes_df.query('Team == \"India\"').head(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 840} id=\"oF97acKHuQ5l\" outputId=\"f55c7c9b-6af6-4d17-b3fa-475a254495df\"\n#Pakistan Details\nathletes_df.query('Team == \"Pakistan\"').head(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ZddSLRCry08o\" outputId=\"20462785-b19b-4582-b170-a96a286019ed\"\n#Top Coutries Participation\n\ntop10_countries = athletes_df.Team.value_counts().sort_values(ascending=False).head(10)\ntop10_countries\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 354} id=\"-dhNMHmVzSL4\" outputId=\"07bf1678-a959-4e13-b732-0d661a713a8d\"\n#Plot For Top 10 Coutries\nplt.figure(figsize = (10,5) )\nplt.title('Overall Participation by Country')\nsns.barplot(x=top10_countries.index, y = top10_countries, palette = 'Set2')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 547} id=\"qC3LRGeHUMyJ\" outputId=\"011beec8-37d4-4cf3-e5e3-9d551f32cc0b\"\n#Age Distribution of The Participation\nplt.figure(figsize = (10,5) )\nplt.title('Age Distributions')\nplt.xlabel('Age')\nplt.ylabel('Numbr of participants')\nplt.hist(athletes_df.Age, bins = np.arange(10,80,2), color = 'red', edgecolor = 'yellow')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-AEFp4XdUMyK\" outputId=\"52475d28-1992-4708-bac7-0f6c4fcdc678\"\n#Winter Olympics Sports\nwinter_sports = athletes_df[athletes_df.Season == 'Winter'].Sport.unique()\nwinter_sports\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"PKGgB22YUMyK\" outputId=\"d15d699a-00f6-4c5e-fd1a-c8e7ebfa91f9\"\n#Summer Olympics Sports\nsummer_sports = athletes_df[athletes_df.Season == 'Summer'].Sport.unique()\nsummer_sports\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"MTaiZCQAUMyL\" outputId=\"989b7482-9013-479b-c831-79b245b171b4\"\n#Male and Female Participants\ngender_counts = athletes_df.Sex.value_counts()\ngender_counts\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 427} id=\"JQEU8YgyUMyL\" outputId=\"816979bc-ca1c-429e-cf11-fa6a6769bfdf\"\n# Pie Plot For Male and Female Athletes\nplt.figure(figsize = (10,5))\nplt.title('Gender Distribution')\nplt.pie(gender_counts, labels=gender_counts.index, autopct = '%1.1f%%', shadow = True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_Nkv3BiTUMyM\" outputId=\"316ff00b-97da-4ae0-a9f1-50d0ee681ef8\"\n#Total Medals\nathletes_df.Medal.value_counts()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"oMN2i8jxYGoO\" outputId=\"bc834868-a447-4d67-e86c-3daeb57cc6be\"\n#Total Number of Female Athletes in Each Olympics.\nfemale_participants = athletes_df[(athletes_df.Sex=='F') & (athletes_df.Season=='Summer')][['Sex','Year']]\nfemale_participants = female_participants.groupby('Year').count().reset_index()\nfemale_participants.head()\n\n# + id=\"O3jT0uUPNize\"\nwomenOlympics = athletes_df[(athletes_df.Sex == 'F') & (athletes_df.Season == 'Summer')]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 573} id=\"Z8dR8WI6PvuZ\" outputId=\"b4fc6605-be69-4e0f-f982-d37c97b4db62\"\nsns.set(style=\"darkgrid\")\nplt.figure(figsize=(20, 10))\nsns.countplot(x='Year', data=womenOlympics, palette =\"Spectral\")\nplt.title('Women Participation')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 580} id=\"wciyqfopR_N5\" outputId=\"53a27bcb-3ecd-4230-a2aa-56b83a556055\"\npart = womenOlympics.groupby('Year')['Sex'].value_counts()\nplt.figure(figsize=(20,10))\npart.loc[:, 'F'].plot()\nplt.title('Plot of Female Athletes Over Time')\n\n# + id=\"Yt1Cs7i_S-Ep\"\n#Gold Medal Athletes\n\ngoldmedals = athletes_df[(athletes_df.Medal == 'Gold')]\n\n# + id=\"N_sEkjC2TpVS\"\n#Take Only the Values That Are Different Feom NaN\ngoldmedals = goldmedals[np.isfinite(goldmedals['Age'])]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"keBLIdHNUK8L\" outputId=\"132093f1-a8ae-403f-97ac-b4b8f2fcae03\"\n#Gold Beyond 60\n\ngoldmedals['ID'][goldmedals['Age'] > 60]. count()\n\n# + [markdown] id=\"-dpeCd0zjvv_\"\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Ty2sW5YtU0qr\" outputId=\"ae7767a7-852f-4581-a7f8-6d9bb4008930\"\nsporting_event = goldmedals['Sport'][goldmedals['Age']>60]\nsporting_event\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 429} id=\"GIozVgN7VcZp\" outputId=\"11d85005-6568-4999-b81a-754373a4da0f\"\n#Plot For Sporting Event\n\nplt.figure(figsize=(10,5))\nplt.tight_layout()\nsns.countplot(sporting_event)\nplt.title('Gold Medals for Athletes Over 60 Years')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"jSnyNQSpWL04\" outputId=\"7d372f4d-1ab0-4fc7-963c-d322d48fe3c8\"\n#Gold Medal From Each Country\n\ngoldmedals.Regions.value_counts().reset_index(name='Medal').head(5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 399} id=\"3E9IVOGYbPeG\" outputId=\"e7def03f-cba1-40d4-c756-44817df3eb2d\"\ntotalGoldMedals = goldmedals.Regions.value_counts().reset_index(name='Medal').head(6)\ng = sns.catplot(x=\"index\", y=\"Medal\", data=totalGoldMedals, height=5,kind=\"bar\", palette=\"rocket\")\ng.despine(left=True)\ng.set_xlabels(\"Top 5 Countries\")\ng.set_ylabels(\"Number of Medals\")\nplt.title('Gold Medal Per Country')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"uzqVBbX2bovr\" outputId=\"45b66911-46b5-49a4-c9d0-f2d61b435ac2\"\n#Rio Olympics\n\nmax_year = athletes_df.Year.max()\nprint(max_year)\n\nteam_names = athletes_df[(athletes_df.Year == max_year) & (athletes_df.Medal == 'Gold')].Team\n\nteam_names.value_counts().head(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 285} id=\"Qx-73a69eIVa\" outputId=\"5176ca9b-4a2e-468a-f472-d448621b4be2\"\nsns.barplot(x=team_names.value_counts().head(20), y=team_names.value_counts().head(20).index)\n\nplt.ylabel(None);\nplt.xlabel('Country Wise Medal For The Year 2016');\n\n# + id=\"thlhSKzff817\"\nnot_null_medals = athletes_df[(athletes_df['Height'].notnull()) & (athletes_df['Weight'])]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 645} id=\"rredkgoggKG5\" outputId=\"0e81d616-f442-4ebc-8546-2e893be6a246\"\nplt.figure(figsize = (12, 10))\naxis = sns.scatterplot(x=\"Height\", y=\"Weight\", data=not_null_medals, hue=\"Sex\")\nplt.title('Height vs Weight of Olympics Medalists')\n","repo_name":"tejaschaudhari192/Olympics-data-analysis","sub_path":"Notebook/Olympics using py.ipynb","file_name":"Olympics using py.ipynb","file_ext":"py","file_size_in_byte":8662,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"45"}
|
| 12 |
+
{"seq_id":"35757291585","text":"# # Exercício 3\n#\n# \n#\n# Aqui está a resolução das duas primeiras alíneas usando fatorização de Crout, a decomposição LU usando eliminação gaussiana está feita no outro ficheiro relativo ao exercício 3.\n\nimport numpy as np\n\n\n# ## Alínea 1\n#\n# Rescrevemos as equações ([Ver mais](https://www.notion.so/guilhermebaos/10-Decomposi-o-LU-f67b4bf846f1473d97f1b294a2442928?pvs=4#7725df887ded42f4a2f28c4d9215eb15)) do seguinte modo:\n#\n# $$\n# \\begin{align*}\n#\n# \\ell_{ji} &= a_{ji} - \\sum_{k=0}^{i-1}\\ell_{jk} u_{ki} \\quad\\quad\\quad\\quad&\\text{Avaliado para }j \\ge i\n# \\\\\\\\\n#\n# u_{ij} &= \\frac1{\\ell_{ii}}\\left(a_{ij} - \\sum_{k=0}^{i-1}\\ell_{ik} u_{kj}\\right) \\quad\\quad\\quad\\quad&\\text{Avaliado para }j > i\n#\n# \\end{align*}\n# $$\n#\n# Agora começamos a contar em 0 !\n\n# +\ndef lucrout(A: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Dado uma matriz A calcula a sua decomposição LU sem pivotagem usando fatorização de Crout.\n\n ### Retorno\n Devolve um tuplo da forma (L, U).\n \"\"\"\n\n N = A.shape[0]\n L, U = np.zeros((N, N)), np.identity(N)\n \n for i in range(N):\n L[i:N, i] = A[i:N, i] - L[i:N, :i] @ U[:i, i]\n U[i, i+1:N] = (A[i, i+1:N] - L[i, :i] @ U[:i, i+1:N]) / L[i][i]\n \n return L, U\n\n# Versão mais legível:\n'''\nN = A.shape[0]\nL, U = np.zeros((N, N)), np.identity(N)\n\nfor i in range(N):\n for j in range(i, N):\n L[j][i] = A[j][i] - L[j, :i] @ U[:i, i]\n \n div = L[i][i]\n for j in range(i + 1, N):\n U[i][j] = (A[i][j] - L[i, :i] @ U[:i, j]) / div\n\nreturn L, U\n'''\n\n# +\nA = np.array([[2, 1, 4, 1], [3, 4, -1, -1], [1, -4, 1, 5], [2, -2, 1, 3]], dtype=np.float64)\nbb = np.array([-4, 3, 9, 7], dtype=np.float64)\n\nL, U = lucrout(A)\nprint(A)\nprint(L @ U)\nprint(L)\nprint(U)\n\n# -\n\ndef lusolve(Ao: np.ndarray, bbo: np.ndarray) -> np.ndarray:\n \"\"\"\n Resolve o sistema de D equações definido por A * xx = bb usando decomposição LU sem pivotagem.\n\n ### Retorno\n Devolve um array que contém o vetor solução.\n \"\"\"\n\n # Evitar side effects\n A = np.copy(Ao)\n bb = np.copy(bbo)\n\n N = len(bb)\n\n # Obter a decomposição LU\n L, U = lucrout(A)\n\n # Substituição progressiva -> Resolver L * yy = bb\n yy = np.zeros(N)\n yy[0] = bb[0] / L[0, 0]\n for i in range(1, N):\n yy[i] = (bb[i] - (L[i, :i] @ yy[:i])) / L[i][i]\n \n # Substituição regressiva -> Resolver U * xx = yy\n xx = np.zeros(N)\n xx[-1] = yy[-1] / U[N-1, N-1]\n for i in range(N-1, -1, -1):\n xx[i] = (yy[i] - (U[i][i+1:] @ xx[i+1:])) / U[i][i]\n \n return xx\n\n\nprint(lusolve(A, bb))\nprint(np.linalg.solve(A, bb))\n","repo_name":"guilhermebaos/Aulas-Uni","sub_path":"Física Computacional/PLs/05-Equações/03-Decomposição-LU-Crout.ipynb","file_name":"03-Decomposição-LU-Crout.ipynb","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
| 13 |
+
{"seq_id":"14231249696","text":"# %load_ext autoreload\n# %autoreload 2\n\n# ## Intro Neural Networks\n#\n# #### 3Blue1Brown Videos\n#\n# [What are Neural Nets](https://www.youtube.com/watch?v=aircAruvnKk)\n#\n# [How Neural Nets Learn](https://www.youtube.com/watch?v=IHZwWFHWa-w)\n#\n# [What is Backprop](https://www.youtube.com/watch?v=Ilg3gGewQ5U)\n#\n# [Math behind Backprop](https://www.youtube.com/watch?v=tIeHLnjs5U8)\n\n# ## Intro Project\n\n# [project based off](https://towardsdatascience.com/handwritten-digit-mnist-pytorch-977b5338e627)\n\nimport numpy as np\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nfrom time import time\nfrom torchvision import datasets, transforms\nfrom torch import nn, optim\n\n# +\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,)),\n ])\n\n\ntrainset = datasets.MNIST('Training_Data', download=True, train=True, transform=transform)\nvalset = datasets.MNIST('Testing_Data', download=True, train=False, transform=transform)\n\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\nvalloader = torch.utils.data.DataLoader(valset, batch_size=64, shuffle=True)\n\n# +\ndataiter = iter(trainloader)\nimages, labels = next(dataiter)\n\nprint(images.shape)\nprint(labels.shape)\n# -\n\nplt.imshow(images[1].numpy().squeeze(), cmap='gray_r');\nlabels[0]\n\nprint(labels)\n\nfigure = plt.figure()\nnum_of_images = 64\nfor index in range(len(images)):\n plt.subplot(8, 8, index + 1)\n plt.axis('off')\n plt.imshow(images[index].numpy().squeeze(), cmap='gray_r')\n\n# +\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Net(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(28*28, 128)\n self.fc2 = nn.Linear(128, 64)\n self.fc3 = nn.Linear(64, 10)\n\n def forward(self, x):\n x = torch.flatten(x,1)\n\n x = self.fc1(x)\n x = F.relu(x)\n x = self.fc2(x)\n x = F.relu(x)\n x = self.fc3(x)\n x = F.log_softmax(x, dim=1)\n return x\n\n\nmodel = Net()\n\n# +\ncriterion = nn.NLLLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.003, momentum=0.9)\n\ntime0 = time()\nepochs = 15\nfor e in range(epochs):\n running_loss = 0\n for images, labels in trainloader:\n \n # Training pass\n optimizer.zero_grad()\n \n output = model(images)\n loss = criterion(output, labels)\n \n #This is where the model learns by backpropagating\n loss.backward()\n \n #And optimizes its weights here\n optimizer.step()\n \n running_loss += loss.item()\n else:\n print(\"Epoch {} - Training loss: {}\".format(e, running_loss/len(trainloader)))\n \nprint(\"\\nTraining Time (in minutes) =\",(time()-time0)/60)\n\n# +\ncorrect_count, all_count = 0, 0\nfor images,labels in valloader:\n for i in range(len(labels)):\n img = images[i].view(1, 784)\n with torch.no_grad():\n logps = model(img)\n\n \n ps = torch.exp(logps)\n probab = list(ps.numpy()[0])\n pred_label = probab.index(max(probab))\n true_label = labels.numpy()[i]\n if(true_label == pred_label):\n correct_count += 1\n all_count += 1\n\nprint(\"Number Of Images Tested =\", all_count)\nprint(\"\\nModel Accuracy =\", (correct_count/all_count))\n","repo_name":"Jmshaver/Twitter-Sentiment-Analysis","sub_path":"week5.ipynb","file_name":"week5.ipynb","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"45"}
|
6647.jsonl
ADDED
|
File without changes
|
6649.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
665.jsonl
ADDED
|
File without changes
|
6650.jsonl
ADDED
|
File without changes
|
6652.jsonl
ADDED
|
File without changes
|
6655.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
6663.jsonl
ADDED
|
File without changes
|
6666.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
669.jsonl
ADDED
|
File without changes
|
671.jsonl
ADDED
|
File without changes
|
674.jsonl
ADDED
|
File without changes
|
676.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
678.jsonl
ADDED
|
File without changes
|
681.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
683.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|