markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Recommended to avoid The [documentation](https://github.com/HIPS/autograd/blob/master/docs/tutorial.md) recommends to avoid inplace operations such as
a += b a -= b a*= b a /=b
_____no_output_____
CC0-1.0
doc/src/GradientOptim/autodiff/examples_allowed_functions.ipynb
ndavila/MachineLearningMSU
B-Value estimates from Maximum LikelihoodHere we implement the maximum likelihood method from Tinti and Mulargia [1987]. We will compute the distribution of b-values from the stochastic event set and compare with the Comcat catalog. We will filter both the stochastic event sets and the catalog above Mw 3.95.
import time import os import pandas as pd import numpy as np import scipy.stats as stats from csep.utils.plotting import plot_mfd import csep %pylab inline def bval_ml_est(mws, dmw): # compute the p term from eq 3.10 in marzocchi and sandri [2003] def p(): top = dmw # assuming that the magn...
-0.0620467887229116
MIT
notes/maximum_likelihood.ipynb
thbeutin/csep2
Verifying computation of $a$ from Michael [2014]$log(N(m)) = a - bM$ $ a = log(N(m)/T) + bM $From Table 2 in Michael [2014], $T$: 1900 $-$ 2009 $M_c:$ 7.7 $N^{\prime}:$ 100 $b$ = 1.59 $\pm$ 0.13
Np = 100 b = 1.59 Mc = 7.7 T = 2009-1900 sigma = 0.13 def a_val(N, M, b, T): return np.log10(N/T) + M*b a = a_val(Np, Mc, b, T) print(a) def a_err(a, b, sigma): return a*sigma/b print(a_err(a, b, sigma)) Np = 635 b = 1.07 Mc = 7.0 T = 2009-1918 sigma = 0.03 def a_val(N, M, b, T): return np.log10(N/T) +...
8.209635928141394 0.23456102651832553
MIT
notes/maximum_likelihood.ipynb
thbeutin/csep2
List the available countries to download data for
pb.footballdata.list_countries()
_____no_output_____
MIT
examples/football-data.co.uk.ipynb
martineastwood/penaltyblog
Download the data for the English Premier League
pb.footballdata.fetch_data("England", 2020, 0)
_____no_output_____
MIT
examples/football-data.co.uk.ipynb
martineastwood/penaltyblog
Download the data for the French Ligue 2
pb.footballdata.fetch_data("France", 2020, 1)
_____no_output_____
MIT
examples/football-data.co.uk.ipynb
martineastwood/penaltyblog
Investigate behavior of `curry` and `partial`
from toolz.curried import * def clump3(a, b, c): return a, b, c @curry def curried_clump3(a, b, c): return a, b, c partial1_clump3=partial(clump3, 1) partial12_clump3=partial(clump3, 1, 2) print(f'clump3(1, 2, 3)={clump3(1, 2, 3)}') print(f'clump3(3, 1, 2)={clump3(3, 1, 2)}') print() print(f'curried_clump3(1)(2...
_____no_output_____
MIT
curry_n_partial.ipynb
mrwizard82d1/learn_toolz
Convolutional Neural Network (CNN) Image Classifier for Persian Numbers
import tensorflow as tf from scipy.io import loadmat import numpy as np import matplotlib.pyplot as plt import random import math from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten, Dense, Conv2D, MaxPool2D, Dropout, BatchNormalization from tensorflow.keras.optimizers import Adam...
_____no_output_____
MIT
CNN_Persian_DigitsClassifier.ipynb
saniaki/Digit-Image-Classifier
[HODA dataset](http://farsiocr.ir/%D9%85%D8%AC%D9%85%D9%88%D8%B9%D9%87-%D8%AF%D8%A7%D8%AF%D9%87/%D9%85%D8%AC%D9%85%D9%88%D8%B9%D9%87-%D8%A7%D8%B1%D9%82%D8%A7%D9%85-%D8%AF%D8%B3%D8%AA%D9%86%D9%88%DB%8C%D8%B3-%D9%87%D8%AF%DB%8C/) HODA Daset reader from: https://github.com/amir-saniyan/HodaDatasetReader
# *-* coding: utf-8 *-* # Hoda Dataset Reader # Python code for reading Hoda farsi digit dataset. # Hoda Farsi Digit Dataset: # http://farsiocr.ir/ # http://farsiocr.ir/مجموعه-داده/مجموعه-ارقام-دستنویس-هدی # http://dadegan.ir/catalog/hoda # Repository: # https://github.com/amir-saniyan/HodaDatasetReader import stru...
_____no_output_____
MIT
CNN_Persian_DigitsClassifier.ipynb
saniaki/Digit-Image-Classifier
Visualization fucntions
def show_images(n,image_array,label_array, cmap=None): ''' show random n number of images from image_array with corresponding label_array ''' total_rows = math.floor(n/4)+1 random_list = random.sample(range(0, image_array.shape[0]), n) fig, axes = plt.subplots(total_rows, 4, figsize=(16, total_r...
_____no_output_____
MIT
CNN_Persian_DigitsClassifier.ipynb
saniaki/Digit-Image-Classifier
Check training images
n = 10 # number of images to show # showing images and correspoind labels from train set show_images(n,train_images,train_labels)
_____no_output_____
MIT
CNN_Persian_DigitsClassifier.ipynb
saniaki/Digit-Image-Classifier
CNN neural network classifier
def CNN_NN(input_shape, dropout_rate, reg_rate): model = Sequential([ Conv2D(8, (3,3), activation='relu', input_shape=input_shape, kernel_initializer="he_uniform", bias_initializer="ones", kernel_regularizer=regularizers.l2(reg_rate), name='CONV2D_1_1_relu'), BatchNor...
test accuracy: 0.983 test loss: 0.097
MIT
CNN_Persian_DigitsClassifier.ipynb
saniaki/Digit-Image-Classifier
Model predictions
def get_model_best_epoch(model, checkpoint_path): ''' get model saved best epoch ''' model.load_weights(checkpoint_path) return model # CNN model best epoch model_CNN = CNN_NN(input_shape= (32,32,1), dropout_rate = 0.3, reg_rate=1e-4) model_CNN = get_model_best_epoch(model_CNN, 'Trained models ...
_____no_output_____
MIT
CNN_Persian_DigitsClassifier.ipynb
saniaki/Digit-Image-Classifier
ComparisonTo do a comparison between MLP and CNN model, the MLP model is created here and the trained wights are loaded
def MLP_NN(input_shape, reg_rate): ''' Multilayer Perceptron (MLP) classification model ''' model = Sequential([ Flatten(input_shape=input_shape), Dense(256, activation='relu', kernel_initializer="he_uniform", bias_initializer="ones", kernel_regularizer=regularizers.l2(reg_...
_____no_output_____
MIT
CNN_Persian_DigitsClassifier.ipynb
saniaki/Digit-Image-Classifier
As a warm-up, you'll review some machine learning fundamentals and submit your initial results to a Kaggle competition. SetupThe questions below will give you feedback on your work. Run the following cell to set up the feedback system.
# Set up code checking import os if not os.path.exists("../input/train.csv"): os.symlink("../input/home-data-for-ml-course/train.csv", "../input/train.csv") os.symlink("../input/home-data-for-ml-course/test.csv", "../input/test.csv") from learntools.core import binder binder.bind(globals()) from learntools....
_____no_output_____
Apache-2.0
notebooks/ml_intermediate/raw/ex1.ipynb
aurnik/learntools
You will work with data from the [Housing Prices Competition for Kaggle Learn Users](https://www.kaggle.com/c/home-data-for-ml-course) to predict home prices in Iowa using 79 explanatory variables describing (almost) every aspect of the homes. ![Ames Housing dataset image](https://i.imgur.com/lTJVG4e.png)Run the next ...
import pandas as pd from sklearn.model_selection import train_test_split # Read the data X_full = pd.read_csv('../input/train.csv', index_col='Id') X_test_full = pd.read_csv('../input/test.csv', index_col='Id') # Obtain target and predictors y = X_full.SalePrice features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlr...
_____no_output_____
Apache-2.0
notebooks/ml_intermediate/raw/ex1.ipynb
aurnik/learntools
Use the next cell to print the first several rows of the data. It's a nice way to get an overview of the data you will use in your price prediction model.
X_train.head()
_____no_output_____
Apache-2.0
notebooks/ml_intermediate/raw/ex1.ipynb
aurnik/learntools
Step 1: Evaluate several modelsThe next code cell defines five different random forest models. Run this code cell without changes. (_To review **random forests**, look [here](https://www.kaggle.com/dansbecker/random-forests)._)
from sklearn.ensemble import RandomForestRegressor # Define the models model_1 = RandomForestRegressor(n_estimators=50, random_state=0) model_2 = RandomForestRegressor(n_estimators=100, random_state=0) model_3 = RandomForestRegressor(n_estimators=100, criterion='mae', random_state=0) model_4 = RandomForestRegressor(n_...
_____no_output_____
Apache-2.0
notebooks/ml_intermediate/raw/ex1.ipynb
aurnik/learntools
To select the best model out of the five, we define a function `score_model()` below. This function returns the mean absolute error (MAE) from the validation set. Recall that the best model will obtain the lowest MAE. (_To review **mean absolute error**, look [here](https://www.kaggle.com/dansbecker/model-validation...
from sklearn.metrics import mean_absolute_error # Function for comparing different models def score_model(model, X_t=X_train, X_v=X_valid, y_t=y_train, y_v=y_valid): model.fit(X_t, y_t) preds = model.predict(X_v) return mean_absolute_error(y_v, preds) for i in range(0, len(models)): mae = score_model(...
_____no_output_____
Apache-2.0
notebooks/ml_intermediate/raw/ex1.ipynb
aurnik/learntools
Use the above results to fill in the line below. Which model is the best model? Your answer should be one of `model_1`, `model_2`, `model_3`, `model_4`, or `model_5`.
# Fill in the best model best_model = ____ # Check your answer step_1.check() #%%RM_IF(PROD)%% best_model = model_3 step_1.assert_check_passed() # Lines below will give you a hint or solution code #_COMMENT_IF(PROD)_ step_1.hint() #_COMMENT_IF(PROD)_ step_1.solution()
_____no_output_____
Apache-2.0
notebooks/ml_intermediate/raw/ex1.ipynb
aurnik/learntools
Step 2: Generate test predictionsGreat. You know how to evaluate what makes an accurate model. Now it's time to go through the modeling process and make predictions. In the line below, create a Random Forest model with the variable name `my_model`.
# Define a model my_model = ____ # Your code here # Check your answer step_2.check() #%%RM_IF(PROD)%% my_model = 3 step_2.assert_check_failed() #%%RM_IF(PROD)%% my_model = best_model step_2.assert_check_passed() # Lines below will give you a hint or solution code #_COMMENT_IF(PROD)_ step_2.hint() #_COMMENT_IF(PROD)_ s...
_____no_output_____
Apache-2.0
notebooks/ml_intermediate/raw/ex1.ipynb
aurnik/learntools
Run the next code cell without changes. The code fits the model to the training and validation data, and then generates test predictions that are saved to a CSV file. These test predictions can be submitted directly to the competition!
# Fit the model to the training data my_model.fit(X, y) # Generate test predictions preds_test = my_model.predict(X_test) # Save predictions in format used for competition scoring output = pd.DataFrame({'Id': X_test.index, 'SalePrice': preds_test}) output.to_csv('submission.csv', index=False)
_____no_output_____
Apache-2.0
notebooks/ml_intermediate/raw/ex1.ipynb
aurnik/learntools
时间转换及处理 str类型的时间转换为datetime类型的时间
from datetime import datetime time = '2010-05-01 00:00:00' time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S") type(time),time
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
datetime类型的时间转换为str类型的时间
from datetime import datetime time = datetime(2010, 5, 1, 0, 0) time = datetime.strftime(time, "%Y-%m-%d %H:%M:%S") type(time),time import tushare as ts df = ts.get_k_data('600519','2020-08-01','2020-08-05') df type(df.date[140]),df.date[140] import pandas as pd #dateframe 日期数据,字符型转换成datetime日期格式 df.date = pd.to_dateti...
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
获取 日期数据 的年、月、日、时、分
df.date.dt.time df.date.dt.date from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" df.date.dt.year df.date.dt.month df.date.dt.day df.date.dt.hour df.date.dt.minute df.date.dt.second
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
时间加减
from datetime import datetime,timedelta start = '2010-05-01 00:00:00' start = datetime.strptime(start, "%Y-%m-%d %H:%M:%S") time = start+timedelta(days=60) time = datetime.strftime(time, "%Y-%m-%d %H:%M:%S") time from datetime import datetime,timedelta start = '2010-05-01 00:00:00' start = datetime.strptime(start, "%Y-...
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
dateime模块 datetime模块中包含如下类: ![1.png](attachment:1.png) date类 today(...):返回当前日期
import datetime datetime.date.today()
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
date对象由year年份、month月份及day日期三部分构成:
import datetime a = datetime.date.today() a a.year,a.month,a.day
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
用于日期比较大小的方法 ![2.png](attachment:2.png)
a=datetime.date(2020,3,1) b=datetime.date(2020,9,4) a.__eq__(b) a.__ge__(b) a.__le__(b)
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
获得二个日期相差多少天 ![3.png](attachment:3.png)
a=datetime.date(2020,3,1) b=datetime.date(2020,9,4) a.__sub__(b).days a.__rsub__(b).days
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
日期的字符串输出
import datetime a = datetime.date.today() a.__format__('%Y-%m-%d') import datetime a = datetime.date.today() a.__format__('%Y/%m/%d') import datetime a = datetime.date.today() a.__str__()
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
time类 time类由hour小时、minute分钟、second秒、microsecond毫秒和tzinfo五部分组成
import datetime a = datetime.time(12,20,59,899) a.__str__() a.__format__('%H:%M:%S')
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
datetime类 datetime类其实是可以看做是date类和time类的合体,其大部分的方法和属性都继承于这二个类 返回现在的时间
import datetime a = datetime.datetime.now() a a.date(),a.time()
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
combine(…):将一个date对象和一个time对象合并生成一个datetime对象
datetime.datetime.combine(a.date(),a.time())
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
strptime(…):根据string, format 2个参数,返回一个对应的datetime对象:
datetime.datetime.strptime('2017-3-22 15:25','%Y-%m-%d %H:%M')
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
strftime(…):根据datetime, format 的参数,返回一个对应的str:
a = datetime.datetime.now() datetime.datetime.strftime(a,'%Y-%m-%d %H:%M:%S')
_____no_output_____
MIT
.ipynb_checkpoints/1.6 时间转换及处理-checkpoint.ipynb
Yanie1asdfg/Quant-Lectures
Torrent To Google Drive Downloader **Important Note:** To get more disk space:> Go to Runtime -> Change Runtime and give GPU as the Hardware Accelerator. You will get around 384GB to download any torrent you want. Install libtorrent and Initialize Session
!python -m pip install --upgrade pip setuptools wheel !python -m pip install lbry-libtorrent !apt install python3-libtorrent import libtorrent as lt ses = lt.session() ses.listen_on(6881, 6891) downloads = []
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
l-i-e-d-j-i-6-7-8-w-d/Torrent-To-Google-Drive-Downloader
Mount Google DriveTo stream files we need to mount Google Drive.
from google.colab import drive drive.mount("/content/drive")
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
l-i-e-d-j-i-6-7-8-w-d/Torrent-To-Google-Drive-Downloader
Add From Torrent FileYou can run this cell to add more files as many times as you want
from google.colab import files source = files.upload() params = { "save_path": "/content/drive/My Drive/Torrent", "ti": lt.torrent_info(list(source.keys())[0]), } downloads.append(ses.add_torrent(params))
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
l-i-e-d-j-i-6-7-8-w-d/Torrent-To-Google-Drive-Downloader
Add From Magnet LinkYou can run this cell to add more files as many times as you want
params = {"save_path": "/content/drive/My Drive/Torrent"} while True: magnet_link = input("Enter Magnet Link Or Type Exit: ") if magnet_link.lower() == "exit": break downloads.append( lt.add_magnet_uri(ses, magnet_link, params) )
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
l-i-e-d-j-i-6-7-8-w-d/Torrent-To-Google-Drive-Downloader
Start DownloadSource: https://stackoverflow.com/a/5494823/7957705 and [3 issue](https://github.com/FKLC/Torrent-To-Google-Drive-Downloader/issues/3) which refers to this [stackoverflow question](https://stackoverflow.com/a/6053350/7957705)
import time from IPython.display import display import ipywidgets as widgets state_str = [ "queued", "checking", "downloading metadata", "downloading", "finished", "seeding", "allocating", "checking fastresume", ] layout = widgets.Layout(width="auto") style = {"description_width": "ini...
_____no_output_____
MIT
Torrent_To_Google_Drive_Downloader.ipynb
l-i-e-d-j-i-6-7-8-w-d/Torrent-To-Google-Drive-Downloader
Monte Carlo MethodsIn this notebook, you will write your own implementations of many Monte Carlo (MC) algorithms. While we have provided some starter code, you are welcome to erase these hints and write your code from scratch. Part 0: Explore BlackjackEnvWe begin by importing the necessary packages.
import sys import gym import numpy as np from collections import defaultdict from plot_utils import plot_blackjack_values, plot_policy
_____no_output_____
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Use the code cell below to create an instance of the [Blackjack](https://github.com/openai/gym/blob/master/gym/envs/toy_text/blackjack.py) environment.
env = gym.make('Blackjack-v0')
_____no_output_____
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Each state is a 3-tuple of:- the player's current sum $\in \{0, 1, \ldots, 31\}$,- the dealer's face up card $\in \{1, \ldots, 10\}$, and- whether or not the player has a usable ace (`no` $=0$, `yes` $=1$).The agent has two potential actions:``` STICK = 0 HIT = 1```Verify this by running the code cell below.
print(env.observation_space) print(env.action_space)
Tuple(Discrete(32), Discrete(11), Discrete(2)) Discrete(2)
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Execute the code cell below to play Blackjack with a random policy. (_The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to get some experience with the output that is returned as the agent interacts with the environment._)
for i_episode in range(3): state = env.reset() while True: print(state) action = env.action_space.sample() state, reward, done, info = env.step(action) if done: print('End game! Reward: ', reward) print('You won :)\n') if reward > 0 else print('You lost :(...
(12, 10, False) End game! Reward: -1.0 You lost :( (19, 10, False) End game! Reward: -1 You lost :( (18, 2, False) End game! Reward: -1 You lost :(
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Part 1: MC PredictionIn this section, you will write your own implementation of MC prediction (for estimating the action-value function). We will begin by investigating a policy where the player _almost_ always sticks if the sum of her cards exceeds 18. In particular, she selects action `STICK` with 80% probability ...
def generate_episode_from_limit_stochastic(bj_env): episode = [] state = bj_env.reset() while True: probs = [0.8, 0.2] if state[0] > 18 else [0.2, 0.8] action = np.random.choice(np.arange(2), p=probs) next_state, reward, done, info = bj_env.step(action) episode.append((state,...
_____no_output_____
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Execute the code cell below to play Blackjack with the policy. (*The code currently plays Blackjack three times - feel free to change this number, or to run the cell multiple times. The cell is designed for you to gain some familiarity with the output of the `generate_episode_from_limit_stochastic` function.*)
for i in range(3): print(generate_episode_from_limit_stochastic(env))
[((17, 9, False), 1, -1)] [((16, 6, False), 1, -1)] [((18, 8, False), 1, -1)]
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Now, you are ready to write your own implementation of MC prediction. Feel free to implement either first-visit or every-visit MC prediction; in the case of the Blackjack environment, the techniques are equivalent.Your algorithm has three arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episo...
def mc_prediction_q(env, num_episodes, generate_episode, gamma=1.0): # initialize empty dictionaries of arrays returns_sum = defaultdict(lambda: np.zeros(env.action_space.n)) N = defaultdict(lambda: np.zeros(env.action_space.n)) Q = defaultdict(lambda: np.zeros(env.action_space.n)) # loop over episo...
[((19, 10, False), 0, 1.0)] states: ((19, 10, False),) actions: (0,) rewards: (1.0,)
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Use the cell below to obtain the action-value function estimate $Q$. We have also plotted the corresponding state-value function.To check the accuracy of your implementation, compare the plot below to the corresponding plot in the solutions notebook **Monte_Carlo_Solution.ipynb**.
# obtain the action-value function Q = mc_prediction_q(env, 500000, generate_episode_from_limit_stochastic) # obtain the corresponding state-value function V_to_plot = dict((k,(k[0]>18)*(np.dot([0.8, 0.2],v)) + (k[0]<=18)*(np.dot([0.2, 0.8],v))) \ for k, v in Q.items()) # plot the state-value function plot_b...
Episode 500000/500000.
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Part 2: MC ControlIn this section, you will write your own implementation of constant-$\alpha$ MC control. Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.- `alpha`: Th...
import random def generate_episode_from_q(env, Q, nA, epsilon): epsidoe = [] state = env.reset() while True: # from the reset state, we can make choice or sample randamly action = np.random.choice(np.arange(nA), p=get_probs(Q, nA, epsilon)) if state in Q else env.action_space.sample() ...
_____no_output_____
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Use the cell below to obtain the estimated optimal policy and action-value function. Note that you should fill in your own values for the `num_episodes` and `alpha` parameters.
# obtain the estimated optimal policy and action-value function policy, Q = mc_control(env, 500000, 0.02)
Episode 500000/500000.
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Next, we plot the corresponding state-value function.
# obtain the corresponding state-value function V = dict((k,np.max(v)) for k, v in Q.items()) # plot the state-value function plot_blackjack_values(V)
_____no_output_____
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
Finally, we visualize the policy that is estimated to be optimal.
# plot the policy plot_policy(policy)
_____no_output_____
MIT
2-Valued-Based Methods/monte-carlo/Monte_Carlo.ipynb
zhaolongkzz/DRL-of-Udacity
To Do1. Try different architectures2. Try stateful/stateless LSTM.3. Add OAT, holidays.4. Check if data has consecutive blocks.
import numpy as np import pandas as pd from scipy import stats from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.callbacks import EarlyStopping from keras.layers import Dropout, Dense, LSTM from statsmodels.tsa.stattools im...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Import data Power data
df_power = pd.read_csv(power_data_folder + '/power_' + site + '.csv', index_col=[0], parse_dates=True) df_power.columns = ['power'] df_power.head() df_power.plot(figsize=(18,5))
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Check for missing data
df_power.isna().any()
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Clean data
# Resample to 5min df_processed = df_power.resample('5T').mean() df_processed.head() df_processed.plot(figsize=(18,5))
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Check for missing data
print(df_processed.isna().any()) print('\n') missing = df_processed['power'].isnull().sum() total = df_processed['power'].shape[0] print('% Missing data for power: ', (missing/total)*100, '%')
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Depending on the percent missing data, either drop it or forward fill the NaN's
# Option 1: Drop NaN's df_processed.dropna(inplace=True) # # Option 2: ffill NaN's # df_processed = df_processed.fillna(method='ffill')
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Normalize data
scaler = MinMaxScaler(feature_range=(0,1)) df_normalized = pd.DataFrame(scaler.fit_transform(df_processed), columns=df_processed.columns, index=df_processed.index) df_normalized.head()
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Check for missing data
df_normalized.isna().any()
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Check for stationarity
result = adfuller(df_normalized['power'], autolag='AIC') output = pd.Series(result[0:4], index=['Test Statistic', 'p-value', '#Lags Used', '#Observations Used']) for key, value in result[4].items(): output['Critical Value (%s)' % key] = value output
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
HVAC States data
df_hvac_states = pd.read_csv(hvac_states_data_folder + '/hvac_states_' + site + '.csv', index_col=[0], parse_dates=True) df_hvac_states.columns = ['zone' + str(i) for i in range(len(df_hvac_states.columns))] df_hvac_states.head()
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Check for missing data
df_hvac_states.isna().any()
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Convert categorical (HVAC states) into dummy variables
var_to_expand = df_hvac_states.columns # One-hot encode the HVAC states for var in var_to_expand: add_var = pd.get_dummies(df_hvac_states[var], prefix=var, drop_first=True) # Add all the columns to the model data df_hvac_states = df_hvac_states.join(add_var) # Drop the original column that was expan...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Join power and hvac_states data
# CHECK: pd.concat gives a lot of duplicate indices. # Try below code to see, # start = pd.Timestamp('2018-02-10 06:00:00+00:00') # df.loc[start] df = pd.concat([df_normalized, df_hvac_states], axis=1) df.head() df = df.drop_duplicates() missing = df.isnull().sum() total = df.shape[0] print('missing data for power: '...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Depending on the percent missing data, either drop it or forward fill the NaN's
# Option 1: Drop NaN's df.dropna(inplace=True) # # Option 2: ffill NaN's # df = df.fillna(method='ffill')
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Visualizations Box plot
df_box_plot = pd.DataFrame(df['power']) df_box_plot['quarter'] = df_box_plot.index.quarter df_box_plot.boxplot(column='power', by='quarter')
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Histogram
df['power'].hist()
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
ACF and PACF
fig1 = plot_acf(df_processed['power'], lags=50) fig2 = plot_pacf(df_processed['power'], lags=50)
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Prepare data Split into training & testing data
X_train = df[(df.index < '2019-01-01')] y_train = df.loc[(df.index < '2019-01-01'), 'power'] X_test = df[(df.index >= '2019-01-01')] y_test = df.loc[(df.index >= '2019-01-01'), 'power']
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Prepare data for LSTMNote: NUM_TIMESTEPS is a hyper-parameter too!
# Number of columns in X_train NUM_FEATURES = len(X_train.columns) # A sequence contains NUM_TIMESTEPS number of elements and predicts NUM_MODEL_PREDICTIONS number of predictions NUM_TIMESTEPS = 24 # Since this is an iterative method, model will predict only 1 timestep ahead NUM_MODEL_PREDICTIONS = 1 # 4 hour p...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
LSTM
model = Sequential([ LSTM(units=128, input_shape=(NUM_TIMESTEPS, NUM_FEATURES), return_sequences=True), Dropout(0.2), LSTM(units=128, return_sequences=True), Dropout(0.2), LSTM(units=128, activation='softmax', return_sequences=False), Dropout(0.2), Dense(NUM_MODEL_PREDICT...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Results Loss
train_loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = [x for x in range(len(train_loss))] df_train_loss = pd.DataFrame(train_loss, columns=['train_loss'], index=epochs) df_val_loss = pd.DataFrame(val_loss, columns=['val_loss'], index=epochs) df_loss = pd.concat([df_train_loss, df_val_...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Accuracy
train_acc = history.history['acc'] val_acc = history.history['val_acc'] epochs = [x for x in range(len(train_acc))] df_train_acc = pd.DataFrame(train_acc, columns=['train_acc'], index=epochs) df_val_acc = pd.DataFrame(val_acc, columns=['val_acc'], index=epochs) df_acc = pd.concat([df_train_acc, df_val_acc], ax...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Plot predicted & true values
# Make predictions through trained model pred_y = model.predict(test_x) # Convert predicted and actual values to dataframes (for plotting) df_y_pred = pd.DataFrame(scaler.inverse_transform(pred_y), index=y_test[NUM_TIMESTEPS:-NUM_MODEL_PREDICTIONS].index, columns=['po...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Make predictions through iterative fitting for a particular timestamp Choose a particular timestamp
timestamp = pd.Timestamp('2019-01-01 23:45:00+00:00') # Keep copy of timestamp to use it after the for loop orig_timestamp = timestamp X_test_pred = X_test.copy() for _ in range(NUM_ACTUAL_PREDICTIONS): # Create test sequence test = np.array(X_test_pred.loc[:timestamp].tail(NUM_TIMESTEPS)) test = np....
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Plot
arr_pred = np.reshape(X_test_pred.loc[orig_timestamp:,'power'].head(NUM_ACTUAL_PREDICTIONS).values, (-1, 1)) arr_true = np.reshape(X_test.loc[orig_timestamp:,'power'].head(NUM_ACTUAL_PREDICTIONS).values, (-1, 1)) df_pred = pd.DataFrame(scaler.inverse_transform(arr_pred), index=X_test_pred.loc[...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
Get accuracy and mse of the entire test set using iterative fittingNote: This takes a while to compute!
# These two lists store the entire dataframes of 48 predictions of each element in test set! # This is not really necessary but only to double check if the outputs are in the correct format predicted_values = [] true_values = [] for i in range(NUM_TIMESTEPS, len(X_test)-NUM_ACTUAL_PREDICTIONS): # Keep copy of...
_____no_output_____
BSD-2-Clause
services/energy_consumption_forecast/lstm/LSTM (Iterative).ipynb
phgupta/XBOS
**Project 4 Notebook 1****Data Acquisition**Using the Google Chrome web browser extension "Web Scraper", I scraped stories and other data from Fanfiction.net. I searched for Hunger Games stories, filtering for stories that were rated T, and that had Katniss Everdeen (there are 4 fields where you can put characters, and...
import numpy as np import nltk import pandas as pd
_____no_output_____
MIT
Notebook-1-Project-4-Hunger-Games-Fanfiction-webscraping.ipynb
sutrofog/Sillman-Metis-Project4
The data was scraped in two batches and saved in .csv files. I read in the two files, created Pandas DataFrames, and then joined the two DataFrames using append.
data = pd.read_csv('Project-4-data/fanfiction-katniss1_pre_page_69.csv') data.head() data.info() data2=pd.read_csv('Project-4-data/fanfiction-katniss1_p69-end_complete.csv') data.head() data2.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1718 entries, 0 to 1717 Data columns (total 11 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 web-scraper-order 1718 non-null object 1 web-scraper-start-url 1718 non-null object 2 stor...
MIT
Notebook-1-Project-4-Hunger-Games-Fanfiction-webscraping.ipynb
sutrofog/Sillman-Metis-Project4
Append the dataframes to make a dataframe with the complete dataset.
katniss=data.append(data2) katniss.head() katniss.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 3443 entries, 0 to 1717 Data columns (total 13 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 web-scraper-order 3443 non-null object 1 web-scraper-start-url 3443 non-null object 2 stor...
MIT
Notebook-1-Project-4-Hunger-Games-Fanfiction-webscraping.ipynb
sutrofog/Sillman-Metis-Project4
Removed some unnecessary columns.
##Can delete columns "previous_pages" and "next_pages". ##These are links that the scraping extension put in. katniss.drop(["previous_pages", "previous_pages-href", "next_pages", "next_pages-href"], axis=1, inplace=True ) katniss.head() katniss.info() #replace punctuation with a white space, remove number...
_____no_output_____
MIT
Notebook-1-Project-4-Hunger-Games-Fanfiction-webscraping.ipynb
sutrofog/Sillman-Metis-Project4
I can delete a couple columns to save space. 'story_text' and 'story_text_no_quotes'using: >katniss.drop(["story_text", "story_text_no_quotes"], axis=1, inplace=True )
#katniss.to_csv('katniss-word-tokenized_only.csv') katniss.head() #Now I can try to take out the stopwords. katniss['story_text_without_stopwords'] = katniss['story_text'].apply(lambda x: [item for item in x if item not in stop]) katniss.head() #Super! It worked! Save it as a .csv katniss.to_csv('katniss-wtok-no-stops-...
_____no_output_____
MIT
Notebook-1-Project-4-Hunger-Games-Fanfiction-webscraping.ipynb
sutrofog/Sillman-Metis-Project4
Homework 2Cross Validation Problem In this homework, you will use cross validation to analyze the effect on model qualityof the number of model parameters and the noise in the observational data.You do this analysis in the context of design of experiments.The two factors are (i) number of model parameters and (ii) the...
IS_COLAB = False # if IS_COLAB: !pip install tellurium !pip install SBstoat # # Constants for standalone notebook if not IS_COLAB: CODE_DIR = "/home/ubuntu/advancing-biomedical-models/common" else: from google.colab import drive drive.mount('/content/drive') CODE_DIR = "/content/drive/My Drive/W...
_____no_output_____
MIT
assignments/Homework2.ipynb
BioModelTools/topics-course
Now You Code 4: Syracuse WeatherWrite a program to load the Syracuse weather data from Dec 2015 inJSON format into a Python list of dictionary. The file with the weather data is in your `Now-You-Code` folder: `"NYC4-syr-weather-dec-2015.json"`You should load this data into a Python list of dictionary using the `json` ...
# Step 2: Write code import json def load_weather_data(): with open('NYC4-syr-weather-dec-2015.json') as f: data = f.read() weather = json.loads(data) return weather def extract_weather_info(weather): info = {} info['mean temp'] = weather['Mean TemperatufeF'] info['high...
_____no_output_____
MIT
content/lessons/10/Now-You-Code/NYC4-Syracuse-Weather.ipynb
jferna22-su/ist256
Постановка задачиРассмотрим несколько моделей линейной регрессии, чтобы выяснить более оптимальную для первых 20 зданий.Данные:* http://video.ittensive.com/machine-learning/ashrae/building_metadata.csv.gz* http://video.ittensive.com/machine-learning/ashrae/weather_train.csv.gz* http://video.ittensive.com/machine-learn...
import pandas as pd from pandas.tseries.holiday import USFederalHolidayCalendar as calendar import numpy as np from scipy.interpolate import interp1d from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression, Lasso, Ridge, ElasticNet, BayesianRidge def reduce_mem_usage (df):...
_____no_output_____
MIT
ASHRAE/competitive_reg_models.ipynb
Costigun/kaggle_practice
Линейная регрессия\begin{equation}z = Ax + By + C, |z-z_0|^2 \rightarrow min\end{equation}Лассо + LARS Лассо\begin{equation}\frac{1}{2n}|z-z_0|^2 + a(|A|+|B|) \rightarrow min\end{equation}Гребневая регрессия\begin{equation}|z-z_0|^2 + a(A^2 + B^2) \rightarrow min\end{equation}ElasticNet: Лассо + Гребневая регрессия\beg...
lr_models = { "LinearRegression":LinearRegression, "Lasso-0.01":Lasso, "Lasso-0.1":Lasso, "Lasso-1.0":Lasso, "Ridge-0.01":Ridge, "Ridge-0.1":Ridge, "Ridge-1.0":Ridge, "ELasticNet-1-1":ElasticNet, "ELasticNet-0.1-1":ElasticNet, "ELasticNet-1-0.1":ElasticNet, "ELasticNet-0.1-0....
[-0.05204313 5.44504565 5.41921165 5.47881611 5.41753305 5.43838778 5.45137392 5.44059806] [-0.04938976 5.44244413 5.41674949 5.47670968 5.41516617 5.43591691 5.44949479 5.43872264] [-0.05138182 5.44439819 5.41859905 5.47829205 5.41694412 5.43777302 5.45090643 5.44013149]
MIT
ASHRAE/competitive_reg_models.ipynb
Costigun/kaggle_practice
import matplotlib.pyplot as mpl import matplotlib.ticker as plticker import numpy as np from scipy.optimize import minimize_scalar import pathlib if not pathlib.Path("mpl_utils.py").exists(): !curl -O https://raw.githubusercontent.com/joaochenriques/MCTE_2022/main/libs/mpl_utils.py &> /dev/null import mpl_utils as m...
_____no_output_____
MIT
ChannelFlows/Simulation/ChannelFlowSimulation.ipynb
joaochenriques/MCTE_2022
**Setup the problem**
ρw = 1025 # [kg/m³] salt water density g = 9.8 # [m/s²] gravity aceleration T = 12.0*3600.0 + 25.2*60.0 # [s] tide period L = 20000 # [m] channel length h = 60 # [m] channel depth b = 4000 # [m] channel width a = 1.2 # [m] tidal amplitude S = h*b # [m²] channel area twopi = 2*np.pi ...
_____no_output_____
MIT
ChannelFlows/Simulation/ChannelFlowSimulation.ipynb
joaochenriques/MCTE_2022
**Solution of the ODE**$\displaystyle \frac{dQ^*}{dt^*}=\cos(t^*) - (\Theta_\text{f}^*+BC_\text{T} \Theta_\text{T}^*) \, Q^* \, |Q^*|$$\displaystyle \frac{d E_\text{T}^*}{dt^*}= BC_\text{P} \, |{Q^*}^3|$where $B$, $\Theta_\text{f}^*$ and $\Theta_\text{T}^*$ are constants, and $C_\text{T}$ and $C_\text{P}$ are computed...
def f_star( ys, ts, Θ_f_star, Θ_T_star, Fr_0, B_rows ): ( Q_star, E_star ) = ys BC_T_rows = np.zeros( len( B_rows ) ) BC_P_rows = np.zeros( len( B_rows ) ) B_0 = np.nan for j, B in enumerate( B_rows ): # do not repeat the computations if B is equal to the previous iteration if B_...
_____no_output_____
MIT
ChannelFlows/Simulation/ChannelFlowSimulation.ipynb
joaochenriques/MCTE_2022
**Solution with channel bed friction and turbines thrust**
periods = 4 ppp = 100 # points per period num = int(ppp*periods) # stores time vector ts_vec = np.linspace( 0, (2*np.pi) * periods, num ) Delta_ts = ts_vec[1] - ts_vec[0] # vector that stores the lossless solution time series ys_lossless_vec = np.zeros( ( num, 2 ) ) # solution of (Eq. 3) without "friction" term for...
_____no_output_____
MIT
ChannelFlows/Simulation/ChannelFlowSimulation.ipynb
joaochenriques/MCTE_2022
The blockage factor per turbine row $i$ is$$B_i=\displaystyle \frac{\left( n_\text{T} A_\text{T}\right)_i}{S_i}$$where $\left( n_\text{T} A_\text{T}\right)_i$ is the area of all turbines of row $i$, and $S_i$ is the cross-sectional area of the channel at section $i$.
fig, (ax1, ax2) = mpl.subplots(1,2, figsize=(12, 4.5) ) fig.subplots_adjust( wspace = 0.17 ) B_local = 0.1 n_step = 18 for n_mult in tqdm( ( 0, 1, 2, 4, 8, 16 ) ): n_rows = n_step * n_mult B_rows = [B_local] * n_rows # vector that stores the solution time series ys_vec = np.zeros( ( num, 2 ) ) #...
_____no_output_____
MIT
ChannelFlows/Simulation/ChannelFlowSimulation.ipynb
joaochenriques/MCTE_2022
**Plot the solution as function of the number of turbines**
n_rows_lst = range( 0, 512+1, 8 ) # number of turbines [-] Ps_lst = [] B_local = 0.1 ys1_vec = np.zeros( ( num, 2 ) ) for n_rows in tqdm( n_rows_lst ): B_rows = [B_local]*n_rows # solution of (Eq. 3) with "friction" terms # the initial conditions are always (0,0) for i, ts in enumerate( ts_vec[1:] ): ...
_____no_output_____
MIT
ChannelFlows/Simulation/ChannelFlowSimulation.ipynb
joaochenriques/MCTE_2022
**TOOLS FOR DEMOGRAPHY** Token y Drive
# Token para GEE import ee from google.colab import auth auth.authenticate_user() ee.Authenticate() ee.Initialize() # Vincular con Drive from google.colab import drive drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
MIT
Phyton/Manejo_Datos.ipynb
jcms2665/100-Days-Of-ML-Code
Manejo de Bases de Datos---
# Instalación de paquetes !pip install pyreadstat !pip install simpledbf # Cargar paquetes import os # Directorios import csv import matplotlib.pyplot as plt import numpy as np # Data frame import pandas as pd import pyreadstat os.getcwd() a="/content/drive/MyDr...
_____no_output_____
MIT
Phyton/Manejo_Datos.ipynb
jcms2665/100-Days-Of-ML-Code
Table of Contents1&nbsp;&nbsp;Exploratory data analysis1.1&nbsp;&nbsp;Desribe data1.1.1&nbsp;&nbsp;Sample size1.1.2&nbsp;&nbsp;Descriptive statistics1.1.3&nbsp;&nbsp;Shapiro-Wilk Test1.1.4&nbsp;&nbsp;Histograms1.2&nbsp;&nbsp;Kendall's Tau correlation1.3&nbsp;&nbsp;Correlation Heatmap
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import shapiro, kendalltau from sklearn import linear_model import statsmodels.api as sm df = pd.read_csv('data/cleaned_data_gca.csv')
_____no_output_____
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
Exploratory data analysis Desribe data Sample size
print('Sample size socio-demographics =', df[df.columns[0]].count()) print('Sample size psychological variables =', df[df.columns[4]].count())
Sample size socio-demographics = 33 Sample size psychological variables = 34
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
Descriptive statistics **Descriptive statistics for numeric data**
descriptive_stat = df.describe() descriptive_stat = descriptive_stat.T descriptive_stat['skew'] = df.skew() descriptive_stat['kurtosis'] = df.kurt() descriptive_stat.insert(loc=5, column='median', value=df.median()) descriptive_stat=descriptive_stat.apply(pd.to_numeric, errors='ignore') descriptive_stat
_____no_output_____
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses
**Descriptive statistics for categorical data**
for col in list(df[['gender','education level']]): print('variable:', col) print(df[col].value_counts(dropna=False).to_string()) print('')
variable: gender Männlich 18 Weiblich 14 Divers 1 NaN 1 variable: education level Hochschulabschluss 16 Abitur 8 derzeit noch Schüler\*in 5 derzeit noch Schüler/*in 3 Fachhochschulabschluss 1 NaN 1
MIT
210601 gca data analyses.ipynb
rbnjd/gca_data_analyses