markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Now it is time to stitch all that together.
For that we will use OWSLib*.
Constructing the filter is probably the most complex part.
We start with a list comprehension using the fes.Or to create the variables filter.
The next step is to exclude some unwanted results (ROMS Average files) using fes.Not.
To select the des... | from owslib import fes
from utilities import fes_date_filter
kw = dict(wildCard='*',
escapeChar='\\',
singleChar='?',
propertyname='apiso:AnyText')
or_filt = fes.Or([fes.PropertyIsLike(literal=('*%s*' % val), **kw)
for val in name_list])
# Exclude ROMS Averages and His... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
Now we are ready to load a csw object and feed it with the filter we created. | from owslib.csw import CatalogueServiceWeb
csw = CatalogueServiceWeb('http://www.ngdc.noaa.gov/geoportal/csw',
timeout=60)
csw.getrecords2(constraints=filter_list, maxrecords=1000, esn='full')
fmt = '{:*^64}'.format
print(fmt(' Catalog information '))
print("CSW version: {}".format(csw.vers... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
We found 13 datasets!
Not bad for such a narrow search area and time-span.
What do we have there?
Let's use the custom service_urls function to split the datasets into OPeNDAP and SOS endpoints. | from utilities import service_urls
dap_urls = service_urls(csw.records, service='odp:url')
sos_urls = service_urls(csw.records, service='sos:url')
print(fmt(' SOS '))
for url in sos_urls:
print('{}'.format(url))
print(fmt(' DAP '))
for url in dap_urls:
print('{}.html'.format(url)) | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
We will ignore the SOS endpoints for now and use only the DAP endpoints.
But note that some of those SOS and DAP endpoints look suspicious.
The Scripps Institution of Oceanography (SIO/UCSD) data should not appear in a search for the Boston Harbor.
That is a known issue and we are working to sort it out. Meanwhile we ... | from utilities import is_station
non_stations = []
for url in dap_urls:
try:
if not is_station(url):
non_stations.append(url)
except RuntimeError as e:
print("Could not access URL {}. {!r}".format(url, e))
dap_urls = non_stations
print(fmt(' Filtered DAP '))
for url in dap_urls:
... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
We still need to find endpoints for the observations.
For that we'll use pyoos' NdbcSos and CoopsSoscollectors.
The pyoos API is different from OWSLib's, but note that we are re-using the same query variables we create for the catalog search (bbox, start, stop, and sos_name.) | from pyoos.collectors.ndbc.ndbc_sos import NdbcSos
collector_ndbc = NdbcSos()
collector_ndbc.set_bbox(bbox)
collector_ndbc.end_time = stop
collector_ndbc.start_time = start
collector_ndbc.variables = [sos_name]
ofrs = collector_ndbc.server.offerings
title = collector_ndbc.server.identification.title
print(fmt(' NDBC... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
That number is misleading!
Do we have 955 buoys available there?
What exactly are the offerings?
There is only one way to find out.
Let's get the data! | from utilities import collector2table, get_ndbc_longname
ndbc = collector2table(collector=collector_ndbc)
names = []
for s in ndbc['station']:
try:
name = get_ndbc_longname(s)
except ValueError:
name = s
names.append(name)
ndbc['name'] = names
ndbc.set_index('name', inplace=True)
ndbc.he... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
That makes more sense.
Two buoys were found in the bounding box,
and the name of at least one of them makes sense.
Now the same thing for CoopsSos. | from pyoos.collectors.coops.coops_sos import CoopsSos
collector_coops = CoopsSos()
collector_coops.set_bbox(bbox)
collector_coops.end_time = stop
collector_coops.start_time = start
collector_coops.variables = [sos_name]
ofrs = collector_coops.server.offerings
title = collector_coops.server.identification.title
print... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
We found one more.
Now we can merge both into one table and start downloading the data. | from pandas import concat
all_obs = concat([coops, ndbc])
all_obs.head()
from pandas import DataFrame
from owslib.ows import ExceptionReport
from utilities import pyoos2df, save_timeseries
iris.FUTURE.netcdf_promote = True
data = dict()
col = 'sea_water_temperature (C)'
for station in all_obs.index:
try:
... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
The cell below reduces or interpolates,
depending on the original frequency of the data,
to 1 hour frequency time-series. | from pandas import date_range
index = date_range(start=start, end=stop, freq='1H')
for k, v in data.iteritems():
data[k] = v.reindex(index=index, limit=1, method='nearest')
obs_data = DataFrame.from_dict(data)
obs_data.head() | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
And now the same for the models. Note that now we use the is_model to filter out non-model endpotins. | import warnings
from iris.exceptions import (CoordinateNotFoundError, ConstraintMismatchError,
MergeError)
from utilities import (quick_load_cubes, proc_cube, is_model,
get_model_name, get_surface)
cubes = dict()
for k, url in enumerate(dap_urls):
print('\n[Readi... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
And now we can use the iris cube objects we collected to download model data near the buoys we found above.
We will need get_nearest_water to search the 10 nearest model
points at least 0.08 degrees away from each buys.
(This step is still a little bit clunky and need some improvements!) | from iris.pandas import as_series
from utilities import (make_tree, get_nearest_water,
add_station, ensure_timeseries, remove_ssh)
model_data = dict()
for mod_name, cube in cubes.items():
print(fmt(mod_name))
try:
tree, lon, lat = make_tree(cube)
except CoordinateNotFoundErro... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
To end this post let's plot the 3 buoys we found together with the nearest model grid point. | import matplotlib.pyplot as plt
buoy = '44013'
fig , ax = plt.subplots(figsize=(11, 2.75))
obs_data[buoy].plot(ax=ax, label='Buoy')
for model in model_data.keys():
try:
model_data[model][buoy].plot(ax=ax, label=model)
except KeyError:
pass # Could not find a model at this location.
leg = a... | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
That is it!
We fetched data based only on a bounding box, time-range, and variable name.
The workflow is not as smooth as we would like.
We had to mix OWSLib catalog searches with to different pyoos collector to download the observed and modeled data.
Another hiccup are all the workarounds used to go from iris cubes to... | HTML(html) | content/downloads/notebooks/2015-10-12-fetching_data.ipynb | ioos/system-test | unlicense |
Create Keras model
<p>
First, write an input_fn to read the data. | import shutil
import numpy as np
import tensorflow as tf
print(tf.__version__)
# Determine CSV, label, and key columns
CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',')
LABEL_COLUMN = 'weight_pounds'
KEY_COLUMN = 'key'
# Set default values for each CSV column. Treat is_male and... | quests/endtoendml/labs/3_keras_wd.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Next, define the feature columns. mother_age and gestation_weeks should be numeric.
The others (is_male, plurality) should be categorical. | ## Build a Keras wide-and-deep model using its Functional API
def rmse(y_true, y_pred):
return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true)))
# Helper function to handle categorical columns
def categorical_fc(name, values):
orig = tf.feature_column.categorical_column_with_vocabulary_list(name, values)
... | quests/endtoendml/labs/3_keras_wd.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
We can visualize the DNN using the Keras plot_model utility. | tf.keras.utils.plot_model(model, 'wd_model.png', show_shapes=False, rankdir='LR') | quests/endtoendml/labs/3_keras_wd.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Train and evaluate | TRAIN_BATCH_SIZE = 32
NUM_TRAIN_EXAMPLES = 10000 * 5 # training dataset repeats, so it will wrap around
NUM_EVALS = 5 # how many times to evaluate
NUM_EVAL_EXAMPLES = 10000 # enough to get a reasonable sample, but not so much that it slows down
trainds = load_dataset('train*', TRAIN_BATCH_SIZE, tf.estimator.ModeKeys.... | quests/endtoendml/labs/3_keras_wd.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Visualize loss curve | # plot
import matplotlib.pyplot as plt
nrows = 1
ncols = 2
fig = plt.figure(figsize=(10, 5))
for idx, key in enumerate(['loss', 'rmse']):
ax = fig.add_subplot(nrows, ncols, idx+1)
plt.plot(history.history[key])
plt.plot(history.history['val_{}'.format(key)])
plt.title('model {}'.format(key))
plt.yl... | quests/endtoendml/labs/3_keras_wd.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Save the model | import shutil, os, datetime
OUTPUT_DIR = 'babyweight_trained'
shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
EXPORT_PATH = os.path.join(OUTPUT_DIR, datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
tf.saved_model.save(model, EXPORT_PATH) # with default serving function
print("Exported trained model to {}".format(EXPORT_... | quests/endtoendml/labs/3_keras_wd.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
创建客户端 | from hanlp_restful import HanLPClient
HanLP = HanLPClient('https://www.hanlp.com/api', auth=None, language='zh') # auth不填则匿名,zh中文,mul多语种 | plugins/hanlp_demo/hanlp_demo/zh/con_restful.ipynb | hankcs/HanLP | apache-2.0 |
申请秘钥
由于服务器算力有限,匿名用户每分钟限2次调用。如果你需要更多调用次数,建议申请免费公益API秘钥auth。
短语句法分析
任务越少,速度越快。如指定仅执行短语句法分析: | doc = HanLP('2021年HanLPv2.1为生产环境带来次世代最先进的多语种NLP技术。', tasks='con') | plugins/hanlp_demo/hanlp_demo/zh/con_restful.ipynb | hankcs/HanLP | apache-2.0 |
返回值为一个Document: | print(doc) | plugins/hanlp_demo/hanlp_demo/zh/con_restful.ipynb | hankcs/HanLP | apache-2.0 |
doc['con']为Tree类型,是list的子类。
可视化短语句法树: | doc.pretty_print() | plugins/hanlp_demo/hanlp_demo/zh/con_restful.ipynb | hankcs/HanLP | apache-2.0 |
转换为bracketed格式: | print(doc['con'][0]) | plugins/hanlp_demo/hanlp_demo/zh/con_restful.ipynb | hankcs/HanLP | apache-2.0 |
为已分词的句子执行短语句法分析: | HanLP(tokens=[
["HanLP", "为", "生产", "环境", "带来", "次世代", "最", "先进", "的", "多语种", "NLP", "技术", "。"],
["我", "的", "希望", "是", "希望", "张晚霞", "的", "背影", "被", "晚霞", "映红", "。"]
], tasks='con').pretty_print() | plugins/hanlp_demo/hanlp_demo/zh/con_restful.ipynb | hankcs/HanLP | apache-2.0 |
Now let's apply the B function to a typical coil. We'll assume copper (at resistivity of 1.68x10<sup>-8</sup> ohm-m) conductors at a packing density of 0.75, inner radius of 1.25 cm, power of 100 W and with supposedly optimal $\alpha$ and $\beta$ of 3 and 2, respectively: | resistivity = 1.68E-8 # ohm-meter
r1 = 0.0125 # meter
packing = 0.75
power = 100.0 # watts
B = BFieldUnitless(power, packing, resistivity, r1, 3, 2)
print("B Field: {:.3} T".format(B)) | solenoids/solenoid.ipynb | tiggerntatie/emagnet.py | mit |
Now try any combination of factors (assuming packing of 0.75 and standard copper conductors) to compute the field: | from ipywidgets import interactive
from IPython.display import display
def B(power, r1, r2, length, x):
return "{:.3} T".format(BField(power, 0.75, resistivity, r1, r2, length, x))
v = interactive(B,
power=(0.0, 200.0, 1),
r1 = (0.01, 0.1, 0.001),
r2 = (0.02, 0.5, 0.001),
length = (0.01, 2, 0.01... | solenoids/solenoid.ipynb | tiggerntatie/emagnet.py | mit |
For a given inner radius, power and winding configuration, the field strength is directly proportional to G. Therefore, we can test the assertion that G is maximum when $\alpha$ is 3 and $\beta$ is 2 by constructing a map of G as a function of $\alpha$ and $\beta$: | from pylab import pcolor, colorbar, meshgrid, contour
from numpy import arange
a = arange(1.1, 6.0, 0.1)
b = arange(0.1, 4.0, 0.1)
A, B = meshgrid(a,b)
G = GFactorUnitless(A, B)
contour(A, B, G, 30)
colorbar()
xlabel("Unitless parameter, Alpha")
ylabel("Unitless parameter, Beta")
suptitle("Electromagnet 'G Factor'")
sh... | solenoids/solenoid.ipynb | tiggerntatie/emagnet.py | mit |
Although it is apparent that the maximum G Factor occurs near the $\alpha=3$, $\beta=2$ point, it is not exactly so: | from scipy.optimize import minimize
def GMin(AB):
return -GFactorUnitless(AB[0], AB[1])
res = minimize(GMin, [3, 2])
print("G Factor is maximum at Alpha = {:.4}, Beta = {:.4}".format(*res.x)) | solenoids/solenoid.ipynb | tiggerntatie/emagnet.py | mit |
Load and prepare the data
A critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon! | data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head()
rides.corr() # Maybe some freatures strongly correlate and can be removed from the model | first-neural-network/DLND_Your_first_neural_network.ipynb | ksooklall/deep_learning_foundation | mit |
We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set). | # Hold out the last 60 days or so of the remaining data as a validation set
train_features, train_targets = features[:-60*24], targets[:-60*24]
val_features, val_targets = features[-60*24:], targets[-60*24:]
#print("Train_freatures shape: {}\nTrain_targets shape:{}".format(np.shape(train_features),np.shape(train_target... | first-neural-network/DLND_Your_first_neural_network.ipynb | ksooklall/deep_learning_foundation | mit |
Time to build the network
Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.
<img src="assets/neural_network.p... | class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
# Initialize we... | first-neural-network/DLND_Your_first_neural_network.ipynb | ksooklall/deep_learning_foundation | mit |
Training the network
Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se... | import sys
### Set the hyperparameters here ###
iterations = 12000
learning_rate = 0.4
hidden_nodes = 19
output_nodes = 1
N_i = train_features.shape[1]
network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
train_loss = var_loss = 0
losses = {'train':[], 'validation':[]}
for ii in range(iterations):... | first-neural-network/DLND_Your_first_neural_network.ipynb | ksooklall/deep_learning_foundation | mit |
Check out your predictions
Here, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly. | fig, ax = plt.subplots(figsize=(8,4))
mean, std = scaled_features['cnt']
predictions = network.run(test_features).T*std + mean
ax.plot(predictions[0], label='Prediction')
ax.plot((test_targets['cnt']*std + mean).values, label='Data')
ax.set_xlim(right=len(predictions))
ax.legend()
dates = pd.to_datetime(rides.ix[test... | first-neural-network/DLND_Your_first_neural_network.ipynb | ksooklall/deep_learning_foundation | mit |
Now, we have to compute a representative value of the funding amount for each type of invesstment. We can either choose the mean or the median - let's have a look at the distribution of raised_amount_usd to get a sense of the distribution of data. | # distribution of raised_amount_usd
sns.boxplot(y=df['raised_amount_usd'])
plt.yscale('log')
plt.show() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Let's also look at the summary metrics. | # summary metrics
df['raised_amount_usd'].describe() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Note that there's a significant difference between the mean and the median - USD 9.5m and USD 2m. Let's also compare the summary stats across the four categories. | # comparing summary stats across four categories
sns.boxplot(x='funding_round_type', y='raised_amount_usd', data=df)
plt.yscale('log')
plt.show()
# compare the mean and median values across categories
df.pivot_table(values='raised_amount_usd', columns='funding_round_type', aggfunc=[np.median, np.mean]) | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Note that there's a large difference between the mean and the median values for all four types. For type venture, for e.g. the median is about 20m while the mean is about 70m.
Thus, the choice of the summary statistic will drastically affect the decision (of the investment type). Let's choose median, since there are q... | # compare the median investment amount across the types
df.groupby('funding_round_type')['raised_amount_usd'].median().sort_values(ascending=False) | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
The median investment amount for type 'private_equity' is approx. USD 20m, which is beyond Spark Funds' range of 5-15m. The median of 'venture' type is about USD 5m, which is suitable for them. The average amounts of angel and seed types are lower than their range.
Thus, 'venture' type investment will be most suited to... | # filter the df for private equity type investments
df = df[df.funding_round_type=="venture"]
# group by country codes and compare the total funding amounts
country_wise_total = df.groupby('country_code')['raised_amount_usd'].sum().sort_values(ascending=False)
print(country_wise_total) | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Let's now extract the top 9 countries from country_wise_total. | # top 9 countries
top_9_countries = country_wise_total[:9]
top_9_countries | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Among the top 9 countries, USA, GBR and IND are the top three English speaking countries. Let's filter the dataframe so it contains only the top 3 countries. | # filtering for the top three countries
df = df[(df.country_code=='USA') | (df.country_code=='GBR') | (df.country_code=='IND')]
df.head() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
After filtering for 'venture' investments and the three countries USA, Great Britain and India, the filtered df looks like this. | # filtered df has about 38800 observations
df.info() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
One can visually analyse the distribution and the total values of funding amount. | # boxplot to see distributions of funding amount across countries
plt.figure(figsize=(10, 10))
sns.boxplot(x='country_code', y='raised_amount_usd', data=df)
plt.yscale('log')
plt.show() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Now, we have shortlisted the investment type (venture) and the three countries. Let's now choose the sectors.
Sector Analysis
First, we need to extract the main sector using the column category_list. The category_list column contains values such as 'Biotechnology|Health Care' - in this, 'Biotechnology' is the 'main cat... | # extracting the main category
df.loc[:, 'main_category'] = df['category_list'].apply(lambda x: x.split("|")[0])
df.head() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
We can now drop the category_list column. | # drop the category_list column
df = df.drop('category_list', axis=1)
df.head() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Now, we'll read the mapping.csv file and merge the main categories with its corresponding column. | # read mapping file
mapping = pd.read_csv("mapping.csv", sep=",")
mapping.head() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Firstly, let's get rid of the missing values since we'll not be able to merge those rows anyway. | # missing values in mapping file
mapping.isnull().sum()
# remove the row with missing values
mapping = mapping[~pd.isnull(mapping['category_list'])]
mapping.isnull().sum() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Now, since we need to merge the mapping file with the main dataframe (df), let's convert the common column to lowercase in both. | # converting common columns to lowercase
mapping['category_list'] = mapping['category_list'].str.lower()
df['main_category'] = df['main_category'].str.lower()
# look at heads
print(mapping.head())
print(df.head()) | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Let's have a look at the category_list column of the mapping file. These values will be used to merge with the main df. | mapping['category_list'] | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
To be able to merge all the main_category values with the mapping file's category_list column, all the values in the main_category column should be present in the category_list column of the mapping file.
Let's see if this is true. | # values in main_category column in df which are not in the category_list column in mapping file
df[~df['main_category'].isin(mapping['category_list'])] | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Notice that values such as 'analytics', 'business analytics', 'finance', 'nanatechnology' etc. are not present in the mapping file.
Let's have a look at the values which are present in the mapping file but not in the main dataframe df. | # values in the category_list column which are not in main_category column
mapping[~mapping['category_list'].isin(df['main_category'])] | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
If you see carefully, you'll notice something fishy - there are sectors named alter0tive medicine, a0lytics, waste ma0gement, veteri0ry, etc. This is not a random quality issue, but rather a pattern. In some strings, the 'na' has been replaced by '0'. This is weird - maybe someone was trying to replace the 'NA' values ... | # replacing '0' with 'na'
mapping['category_list'] = mapping['category_list'].apply(lambda x: x.replace('0', 'na'))
print(mapping['category_list']) | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
This looks fine now. Let's now merge the two dataframes. | # merge the dfs
df = pd.merge(df, mapping, how='inner', left_on='main_category', right_on='category_list')
df.head()
# let's drop the category_list column since it is the same as main_category
df = df.drop('category_list', axis=1)
df.head()
# look at the column types and names
df.info() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Converting the 'wide' dataframe to 'long'
You'll notice that the columns representing the main category in the mapping file are originally in the 'wide' format - Automotive & Sports, Cleantech / Semiconductors etc.
They contain the value '1' if the company belongs to that category, else 0. This is quite redundant. We c... | help(pd.melt)
# store the value and id variables in two separate arrays
# store the value variables in one Series
value_vars = df.columns[9:18]
# take the setdiff() to get the rest of the variables
id_vars = np.setdiff1d(df.columns, value_vars)
print(value_vars, "\n")
print(id_vars)
# convert into long
long_df = p... | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
We can now get rid of the rows where the column 'value' is 0 and then remove that column altogether. | # remove rows having value=0
long_df = long_df[long_df['value']==1]
long_df = long_df.drop('value', axis=1)
# look at the new df
long_df.head()
len(long_df)
# renaming the 'variable' column
long_df = long_df.rename(columns={'variable': 'sector'})
# info
long_df.info() | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
The dataframe now contains only venture type investments in countries USA, IND and GBR, and we have mapped each company to one of the eight main sectors (named 'sector' in the dataframe).
We can now compute the sector-wise number and the amount of investment in the three countries. | # summarising the sector-wise number and sum of venture investments across three countries
# first, let's also filter for investment range between 5 and 15m
df = long_df[(long_df['raised_amount_usd'] >= 5000000) & (long_df['raised_amount_usd'] <= 15000000)]
# groupby country, sector and compute the count and sum
df.... | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
This will be much more easy to understand using a plot. | # plotting sector-wise count and sum of investments in the three countries
plt.figure(figsize=(16, 14))
plt.subplot(2, 1, 1)
p = sns.barplot(x='sector', y='raised_amount_usd', hue='country_code', data=df, estimator=np.sum)
p.set_xticklabels(p.get_xticklabels(),rotation=30)
plt.title('Total Invested Amount (USD)')
plt... | Investment Case Group Project/3_Analysis.ipynb | prk327/CoAca | gpl-3.0 |
Two-layer model with head-specified line-sink
Two-layer aquifer bounded on top by a semi-confined layer. Head above the semi-confining layer is 5. Head line-sink located at $x=0$ with head equal to 2, cutting through layer 0 only. | ml = ModelMaq(kaq=[1, 2], z=[4, 3, 2, 1, 0], c=[1000, 1000], \
topboundary='semi', hstar=5)
ls = HeadLineSink1D(ml, xls=0, hls=2, layers=0)
ml.solve()
x = linspace(-200, 200, 101)
h = ml.headalongline(x, zeros_like(x))
plot(x, h[0], label='layer 0')
plot(x, h[1], label='layer 1')
legend(loc='best') | notebooks/timml_xsection.ipynb | mbakker7/timml | mit |
1D inhomogeneity
Three strips with semi-confined conditions on top of all three | ml = ModelMaq(kaq=[1, 2], z=[4, 3, 2, 1, 0], c=[1000, 1000], topboundary='semi', hstar=5)
StripInhomMaq(ml, x1=-inf, x2=-50, kaq=[1, 2], z=[4, 3, 2, 1, 0], c=[1000, 1000], npor=0.3,
topboundary='semi', hstar=15)
StripInhomMaq(ml, x1=-50, x2=50, kaq=[1, 2], z=[4, 3, 2, 1, 0], c=[1000, 1000], npor=0.3, ... | notebooks/timml_xsection.ipynb | mbakker7/timml | mit |
Three strips with semi-confined conditions at the top of the strip in the middle only. The head is specified in the strip on the left and in the strip on the right. | ml = ModelMaq(kaq=[1, 2], z=[4, 3, 2, 1, 0], c=[1000, 1000], topboundary='semi', hstar=5)
StripInhomMaq(ml, x1=-inf, x2=-50, kaq=[1, 2], z=[3, 2, 1, 0], c=[1000], npor=0.3,
topboundary='conf')
StripInhomMaq(ml, x1=-50, x2=50, kaq=[1, 2], z=[4, 3, 2, 1, 0], c=[1000, 1000], npor=0.3,
t... | notebooks/timml_xsection.ipynb | mbakker7/timml | mit |
Impermeable wall
Flow from left to right in three-layer aquifer with impermeable wall in bottom 2 layers | from timml import *
from pylab import *
ml = ModelMaq(kaq=[1, 2, 4], z=[5, 4, 3, 2, 1, 0], c=[5000, 1000])
uf = Uflow(ml, 0.002, 0)
rf = Constant(ml, 100, 0, 20)
ld1 = ImpLineDoublet1D(ml, xld=0, layers=[0, 1])
ml.solve()
x = linspace(-100, 100, 101)
h = ml.headalongline(x, zeros_like(x))
Qx, _ = ml.disvecalongl... | notebooks/timml_xsection.ipynb | mbakker7/timml | mit |
Load data | import numpy as np
from sklearn.datasets import load_digits
digits = load_digits()
X = digits.data # data in pixels
y = digits.target # digit labels
print(X.shape)
print(y.shape)
print(np.unique(y)) | 6 Cluster and CNN.ipynb | irsisyphus/machine-learning | apache-2.0 |
Visualize data | import matplotlib.pyplot as plt
import pylab as pl
num_rows = 4
num_cols = 5
fig, ax = plt.subplots(nrows=num_rows, ncols=num_cols, sharex=True, sharey=True)
ax = ax.flatten()
for index in range(num_rows*num_cols):
img = digits.images[index]
label = digits.target[index]
ax[index].imshow(img, cmap='Greys',... | 6 Cluster and CNN.ipynb | irsisyphus/machine-learning | apache-2.0 |
Data sets: training versus test | if Version(sklearn_version) < '0.18':
from sklearn.cross_validation import train_test_split
else:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=1)
num_training = y_train.shape[0]
num_test = y_test.shape[0]
pr... | 6 Cluster and CNN.ipynb | irsisyphus/machine-learning | apache-2.0 |
Answer
We first write a scoring function for clustering so that we can use for GridSearchCV.
Take a look at use_scorer under scikit learn. | ## Note: We do not guarantee that there is a one-to-one correspondence, and therefore the toy result is different.
## See Explanation for more information
def clustering_accuracy_score(y_true, y_pred):
n_labels = len(list(set(y_true)))
n_clusters = len(list(set(y_pred)))
Pre = np.zeros((n_clusters, n_... | 6 Cluster and CNN.ipynb | irsisyphus/machine-learning | apache-2.0 |
Explanation
I adopt a modified version of F-value selection, that is, for each cluster, select the best label class with highest F-score. This accuracy calculating method supports the condition that number of clusters not equal to number of labels, which supports GridSearchCV on number of clusters.
Formula: Let $C[i]$ ... | from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import KernelPCA
from sklearn.cluster import KMeans
from sklearn.metrics import make_scorer
from scipy.stats import mode
pipe = Pipeline([('scl', StandardScaler()),
('pca', KernelPCA()),
... | 6 Cluster and CNN.ipynb | irsisyphus/machine-learning | apache-2.0 |
Use GridSearchCV to tune hyper-parameters. | if Version(sklearn_version) < '0.18':
from sklearn.grid_search import GridSearchCV
else:
from sklearn.model_selection import GridSearchCV
pcs = list(range(1, 60))
kernels = ['linear', 'rbf', 'cosine']
initTypes = ['random', 'k-means++']
clusters = list(range(10, 20))
tfs = [True, False]
param_grid = [{'pca__n... | 6 Cluster and CNN.ipynb | irsisyphus/machine-learning | apache-2.0 |
Visualize mis-clustered samples, and provide your explanation. | mapping = cluster_mapping(y_train, best_model.predict(X_train))
y_test_pred = np.array(list(map(lambda x: mapping[x], best_model.predict(X_test))))
miscl_img = X_test[y_test != y_test_pred][:25]
correct_lab = y_test[y_test != y_test_pred][:25]
miscl_lab = y_test_pred[y_test != y_test_pred][:25]
fig, ax = plt.subplots... | 6 Cluster and CNN.ipynb | irsisyphus/machine-learning | apache-2.0 |
Explanation
Since the accuracy is 84.4%, which means more than 1 digit will be incorrectly clustered in a group of 10 digits, the error is still considered to be high (compared with using neural networks or other methods).
The mis-clustered samples, as we can observe from the picture above, are generally two kinds:
1. ... | # Functions to build a user-defined wide resnet for cifa-10
# Author: Somshubra Majumdar https://github.com/titu1994/Wide-Residual-Networks
# Modified By: Gao Chang, HKU
from keras.models import Model
from keras.layers import Input, merge, Activation, Dropout, Flatten, Dense
from keras.layers.convolutional import Conv... | 6 Cluster and CNN.ipynb | irsisyphus/machine-learning | apache-2.0 |
Save configuration | import os
try:
import cPickle as pickle
except ImportError:
import pickle
import iris
import cf_units
from datetime import datetime
from utilities import CF_names, fetch_range, start_log
# 1-week start of data.
kw = dict(start=datetime(2014, 7, 1, 12), days=6)
start, stop = fetch_range(**kw)
# SECOORA region... | notebooks/timeSeries/ssh/00-fetch_data.ipynb | ocefpaf/secoora | mit |
Add SECOORA models and observations | from utilities import titles, fix_url
for secoora_model in secoora_models:
if titles[secoora_model] not in dap_urls:
log.warning('{} not in the NGDC csw'.format(secoora_model))
dap_urls.append(titles[secoora_model])
# NOTE: USEAST is not archived at the moment!
# https://github.com/ioos/secoora/is... | notebooks/timeSeries/ssh/00-fetch_data.ipynb | ocefpaf/secoora | mit |
Clean the DataFrame | from utilities import get_coops_metadata, to_html
columns = {'datum_id': 'datum',
'sensor_id': 'sensor',
'station_id': 'station',
'latitude (degree)': 'lat',
'longitude (degree)': 'lon',
'vertical_position (m)': 'height',
'water_surface_height_above_ref... | notebooks/timeSeries/ssh/00-fetch_data.ipynb | ocefpaf/secoora | mit |
Uniform 6-min time base for model/data comparison | from owslib.ows import ExceptionReport
from utilities import pyoos2df, save_timeseries
iris.FUTURE.netcdf_promote = True
log.info(fmt(' Observations '))
outfile = '{}-OBS_DATA.nc'.format(run_name)
outfile = os.path.join(run_name, outfile)
log.info(fmt(' Downloading to file {} '.format(outfile)))
data, bad_station = ... | notebooks/timeSeries/ssh/00-fetch_data.ipynb | ocefpaf/secoora | mit |
Split good and bad vertical datum stations. | pattern = '|'.join(bad_station)
if pattern:
all_obs['bad_station'] = all_obs.station.str.contains(pattern)
observations = observations[~observations.station.str.contains(pattern)]
else:
all_obs['bad_station'] = ~all_obs.station.str.contains(pattern)
# Save updated `all_obs.csv`.
fname = '{}-all_obs.csv'.fo... | notebooks/timeSeries/ssh/00-fetch_data.ipynb | ocefpaf/secoora | mit |
SECOORA Observations | import numpy as np
from pandas import DataFrame
def extract_series(cube, station):
time = cube.coord(axis='T')
date_time = time.units.num2date(cube.coord(axis='T').points)
data = cube.data
return DataFrame(data, columns=[station], index=date_time)
if buoys:
secoora_obs_data = []
for station, ... | notebooks/timeSeries/ssh/00-fetch_data.ipynb | ocefpaf/secoora | mit |
These buoys need some QA/QC before saving | from utilities.qaqc import filter_spikes, threshold_series
if buoys:
secoora_obs_data.apply(threshold_series, args=(0, 40))
secoora_obs_data.apply(filter_spikes)
# Interpolate to the same index as SOS.
index = obs_data.index
kw = dict(method='time', limit=30)
secoora_obs_data = secoora_obs_dat... | notebooks/timeSeries/ssh/00-fetch_data.ipynb | ocefpaf/secoora | mit |
Loop discovered models and save the nearest time-series | from iris.exceptions import (CoordinateNotFoundError, ConstraintMismatchError,
MergeError)
from utilities import time_limit, get_model_name, is_model
log.info(fmt(' Models '))
cubes = dict()
with warnings.catch_warnings():
warnings.simplefilter("ignore") # Suppress iris warnings.
... | notebooks/timeSeries/ssh/00-fetch_data.ipynb | ocefpaf/secoora | mit |
Rawest Plot (100k sampling) | rawestImg = sitk.GetArrayFromImage(inImg) ##convert to simpleITK image to normal numpy ndarray
## Randomly sample 100k points
import random
x = rawestImg[:,0,0]
y = rawestImg[0,:,0]
z = rawestImg[0,0,:]
# mod by x to get x, mod by y to get y, mod by z to get z
xdimensions = len(x)
ydimensions = len(y)
zdimensions =... | Jupyter/Filter_and_Plotly_Luke.ipynb | NeuroDataDesign/seelviz | apache-2.0 |
Filter image | ## Clean out noise (Filter Image)
(values, bins) = np.histogram(sitk.GetArrayFromImage(inImg), bins=100, range=(0,500))
plt.plot(bins[:-1], values)
counts = np.bincount(values)
maximum = np.argmax(counts)
lowerThreshold = 100 #maximum
upperThreshold = sitk.GetArrayFromImage(inImg).max()+1
filteredImg = sitk.Thresho... | Jupyter/Filter_and_Plotly_Luke.ipynb | NeuroDataDesign/seelviz | apache-2.0 |
Randomly sample 100k points | filterImg = sitk.GetArrayFromImage(filteredImg) ##convert to simpleITK image to normal numpy ndarray
print filterImg[0][0]
## Randomly sample 100k points after filtering
x = filterImg[:,0,0]
y = filterImg[0,:,0]
z = filterImg[0,0,:]
# mod by x to get x, mod by y to get y, mod by z to get z
xdimensions = len(x)
ydi... | Jupyter/Filter_and_Plotly_Luke.ipynb | NeuroDataDesign/seelviz | apache-2.0 |
UNUSED:
spacingImg = inImg.GetSpacing()
spacing = tuple(i * 50 for i in spacingImg)
print spacingImg
print spacing
inImg.SetSpacing(spacingImg)
inImg_download = inImg # Aut1367 set to default spacing
inImg = imgResample(inImg, spacing=refImg.GetSpacing())
Img_reorient = imgReorient(inImg, "LPS", "RSA") #specific reori... | from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly import tools
import plotly
plotly.offline.init_notebook_mode()
import plotly.graph_objs as go
x = X_val
y = Y_val
z = Z_val
trace1 = go.Scatter3d(
x = x,
y = y,
z = z,
mode='markers',
marker=dict(
size=1.2,... | Jupyter/Filter_and_Plotly_Luke.ipynb | NeuroDataDesign/seelviz | apache-2.0 |
Filter Image Again
Don't do this
Clean out noise (Filter Image)
(values, bins) = np.histogram(filterImg, bins=100, range=(0,500))
plt.plot(bins[:-1], values)
counts = np.bincount(values)
maximum = np.argmax(counts)
lowerThreshold = maximum
upperThreshold = filterImg.max()+1
filterX2Img = sitk.Threshold(inImg,lowerThres... | ## Histogram Equalization
## Cut from generateHistogram from clarityviz
import cv2
im = filterImg
img = im[:,:,:]
shape = im.shape
#affine = im.get_affine()
x_value = shape[0]
y_value = shape[1]
z_value = shape[2]
#####################################################
imgflat = img.reshape(-1)
#img_grey = np.array(imgfl... | Jupyter/Filter_and_Plotly_Luke.ipynb | NeuroDataDesign/seelviz | apache-2.0 |
Plotting post filtering/HistEq | x_histeq = newer_img[:,0,0]
y_histeq = newer_img[0,:,0]
z_histeq = newer_img[0,0,:]
## Randomly sample 100k points after filtering
xdimensions = len(x)
ydimensions = len(y)
zdimensions = len(z)
index = random.sample(xrange(0,xdimensions*ydimensions*zdimensions),100000) #66473400 is multiplying xshape by yshape by zs... | Jupyter/Filter_and_Plotly_Luke.ipynb | NeuroDataDesign/seelviz | apache-2.0 |
Load Data | train = pd.read_csv("train.csv")
train.describe() | titanic/titanic.ipynb | ajmendez/explore | mit |
Clean Data
On the outset it seems that there are some issues with the number of observations for the columns (e.g., Age, Cabin, Embarked).
* Gender is non numeric
* Embarked is also a string
* Age -- Missing and incorrect data | # Cleanup Gender and Embarked
train['Sex'] = np.where(train['Sex'] == 'male', 0, 1)
train['Embarked'] = train['Embarked'].fillna('Z').map(dict(C=0, S=1, Q=2, Z=3))
# AGE -- quickly look at data
train['hasage'] = np.isnan(train['Age'])
train.hist('Age', by='Survived', bins=25)
train.groupby('Survived').mean() | titanic/titanic.ipynb | ajmendez/explore | mit |
There is a clear difference in the distributions in ages between thoes who survived and not. Also from the table you can see the differences in the mean values of the passenger class (pclass), ages, and Fares. Note it is also more likely to have a missing age if you did not survive. Rather than attempting to model t... | # Age is missing values
train['Age'] = np.where(np.isfinite(train['Age']), train['Age'], -1) | titanic/titanic.ipynb | ajmendez/explore | mit |
Feature Creation | # Remap cabin to a numeric value depending on the letter
m = {chr(i+97).upper():i for i in range(26)}
shortenmap = lambda x: m[x[0]]
train['cleancabin'] = train['Cabin'].fillna('Z').apply(shortenmap)
train['cleancabin'].hist()
# Get person title / family name
# These might be overfitting the data since the title is co... | titanic/titanic.ipynb | ajmendez/explore | mit |
Classify!
First test different techniques to see how well they predict the training set. | predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", 'cleancabin', 'nfamily', 'ntitle']
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier, AdaBoostRegressor
from sklearn.svm import SVC, ... | titanic/titanic.ipynb | ajmendez/explore | mit |
Logistic Regression | scores = cross_validation.cross_val_score(
LogisticRegression(random_state=0),
train[predictors],
train["Survived"],
cv=3
)
print('{:0.1f}'.format(100*scores.mean())) | titanic/titanic.ipynb | ajmendez/explore | mit |
Random Forest | scores = cross_validation.cross_val_score(
RandomForestClassifier(
random_state=0,
n_estimators=150,
min_samples_split=4,
min_samples_leaf=2
),
train[predictors],
train["Survived"],
cv=3
)
print('{:0.1f}'.format(100*scores.mean())) | titanic/titanic.ipynb | ajmendez/explore | mit |
Gradient Boost | scores = cross_validation.cross_val_score(
GradientBoostingClassifier(n_estimators=100,
learning_rate=1.0,
max_depth=1,
random_state=0),
train[predictors],
train["Survived"],
cv=3
)
print('{:0.1f}'.format(100... | titanic/titanic.ipynb | ajmendez/explore | mit |
Support Vector Machine Classifier | scores = cross_validation.cross_val_score(
SVC(random_state=0),
train[predictors],
train["Survived"],
cv=3
)
print('{:0.1f}'.format(100*scores.mean())) | titanic/titanic.ipynb | ajmendez/explore | mit |
Support Vector Machine Classifier with AdaBoost?!
Broken! | scores = cross_validation.cross_val_score(
AdaBoostRegressor(SVC(kernel='poly', random_state=0), random_state=0, n_estimators=500, learning_rate=0.5),
train[predictors],
train["Survived"],
cv=3
)
print('{:0.1f}'.format(100*scores.mean())) | titanic/titanic.ipynb | ajmendez/explore | mit |
AdaBoost | scores = cross_validation.cross_val_score(
AdaBoostClassifier(random_state=0, n_estimators=100),
train[predictors],
train["Survived"],
cv=3
)
print('{:0.1f}'.format(100*scores.mean())) | titanic/titanic.ipynb | ajmendez/explore | mit |
K Nearest Neighbors + Bagging | bagging = BaggingClassifier(KNeighborsClassifier(), max_samples=0.5, max_features=0.5, random_state=0)
scores = cross_validation.cross_val_score(
bagging,
train[predictors],
train["Survived"],
cv=3
)
print('{:0.1f}'.format(100*scores.mean())) | titanic/titanic.ipynb | ajmendez/explore | mit |
Voting Classifier with multiple classifiers | est = [('GNB', GaussianNB()),
('LR', LogisticRegression(random_state=1)),
('RFC',RandomForestClassifier(random_state=1))]
alg = BaggingClassifier(VotingClassifier(est, voting='soft'), max_samples=0.5, max_features=0.5)
scores = cross_validation.cross_val_score(
alg,
train[predictors],
trai... | titanic/titanic.ipynb | ajmendez/explore | mit |
Measure feature Strength | forest = ExtraTreesClassifier(n_estimators=250,
random_state=0)
forest.fit(train[predictors], train['Survived'])
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
... | titanic/titanic.ipynb | ajmendez/explore | mit |
matplotlib
matplotlib is a powerful plotting module that is part of Python's standard library. The website for matplotlib is at http://matplotlib.org/. And you can find a bunch of examples at the following two locations: http://matplotlib.org/examples/index.html and http://matplotlib.org/gallery.html.
matplotlib contai... | # Import matplotlib.pyplot
| winter2017/econ129/python/Econ129_Class_04.ipynb | letsgoexploring/teaching | mit |
Next, we want to make sure that the plots that we create are displayed in this notebook. To achieve this we have to issue a command to be interpretted by Jupyter -- called a magic command. A magic command is preceded by a % character. Magics are not Python and will create errs if used outside of the Jupyter notebook | # Magic command for the Jupyter Notebook
| winter2017/econ129/python/Econ129_Class_04.ipynb | letsgoexploring/teaching | mit |
A quick matplotlib example
Create a plot of the sine function for x values between -6 and 6. Add axis labels and a title. | # Import numpy as np
# Create an array of x values from -6 to 6
# Create a variable y equal to the sin of x
# Use the plot function to plot the
# Add a title and axis labels
| winter2017/econ129/python/Econ129_Class_04.ipynb | letsgoexploring/teaching | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.