markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
If you're uploading many queries at a time, you can upload in batches. This saves API calls and allows you to just pass in a list rather than iterating over the upload function.
queries.upload_all([ {"name":"Pets", "includedTerms":"dogs OR cats", "backfill_date":"2016-01-01T05:00:00"}, {"name":"ice cream cake", "includedTerms":"(\"ice cream\" OR icecream) AND (cake)"}, {"name": "Test1", "includedTerms": "akdnvaoifg;anf"}, {"name": ...
DEMO.ipynb
anthonybu/api_sdk
mit
Channels will be shown as queries and can be deleted as queries, but must be uploaded differently. You must be authenticated in the app to upload channels. In order to upload a channel you must pass in the name of the channel, the handle you'd like to track and the type of channel. As with keyword queries, we can upl...
queries.upload_channel(name = "Brandwatch", handle = "brandwatch", channel_type = "twitter") queries.upload_all_channel([{"name": "BWReact", "handle": "BW_React", "channel_type": "twitter"}, ...
DEMO.ipynb
anthonybu/api_sdk
mit
We can delete queries one at a time, or in batches.
queries.delete(name = "Brandwatch Engagement") queries.delete_all(["Pets", "Test3", "Brandwatch", "BWReact", "Brandwatch Careers"])
DEMO.ipynb
anthonybu/api_sdk
mit
Groups You'll notice that a lot of the things that were true for queries are also true for groups. Many of the functions are nearly identical with any adaptations necessary handled behind the scenes for ease of use. Again (as with queries), we need to create an object with which we can manipulate groups within the acc...
groups = BWGroups(project)
DEMO.ipynb
anthonybu/api_sdk
mit
And can check for exisiting groups in the same way as before.
groups.names
DEMO.ipynb
anthonybu/api_sdk
mit
Now let's check which queries are in each group in the account
for group in groups.names: print(group) print(groups.get_group_queries(group)) print()
DEMO.ipynb
anthonybu/api_sdk
mit
We can easily create a group with any preexisting queries. (Recall that upload accepts two boolean keyword arguments - "create_only" and "modify_only" (both defaulting to False) - which specifies what API verbs the function is allowed to use; for instance, if we set "create_only" to True then the function will post a n...
groups.upload(name = "group 1", queries = ["Test1", "Test2"])
DEMO.ipynb
anthonybu/api_sdk
mit
Or upload new queries and create a group with them, all in one call
groups.upload_queries_as_group(group_name = "group 2", query_data_list = [{"name": "Test3", "includedTerms": "adcioahnanva"}, {"name": "Test4", ...
DEMO.ipynb
anthonybu/api_sdk
mit
We can either delete just the group, or delete the group and the queries at the same time.
groups.delete("group 1") print() groups.deep_delete("group 2")
DEMO.ipynb
anthonybu/api_sdk
mit
Downloading Mentions (From a Query or a Group) You can download mentions from a Query or from a Group (the code does not yet support Channels) There is a function get_mentions() in the classes BWQueries and in BWGroups. They are used the same way. Be careful with time zones, as they affect the date range and alter the ...
today = (datetime.date.today() + datetime.timedelta(days=1)).isoformat() + "T05:00:00" start = (datetime.date.today() - datetime.timedelta(days=29)).isoformat() + "T05:00:00"
DEMO.ipynb
anthonybu/api_sdk
mit
To use get_mentions(), the minimum parameters needed are name (query name in this case, or group name if downloading mentions from a group), startDate, and endDate
filtered = queries.get_mentions(name = "ice cream cake", startDate = start, endDate = today)
DEMO.ipynb
anthonybu/api_sdk
mit
There are over a hundred filters you can use to only download the mentions that qualify. see the full list in the file filters.py Here, different filters are used, which take different data types. filters.py details which data type is used with each filter. Some filters, like sentiment and xprofession below, have a lim...
filtered = queries.get_mentions(name = "ice cream cake", startDate = start, endDate = today, sentiment = "positive", twitterVerified = False, impactMin = 5...
DEMO.ipynb
anthonybu/api_sdk
mit
To filter by tags, pass in a list of strings where each string is a tag name. You can filter by categories in two differnt ways: on a subcategory level or a parent category level. To filter on a subcategory level, use the category keyword and pass in a dictionary, where each the keys are the parent categories and the ...
filtered = queries.get_mentions(name = "ice cream cake", startDate = start, endDate = today, parentCategory = ["Colors", "Days"], category = {"Colors": ["Blue", "Yellow"], ...
DEMO.ipynb
anthonybu/api_sdk
mit
Categories Instantiate a BWCategories object by passing in your project as a parameter, which loads all of the categories in your project. Print out ids to see which categories are currently in your project.
categories = BWCategories(project) categories.ids
DEMO.ipynb
anthonybu/api_sdk
mit
Upload categories individually with upload(), or in bulk with upload_all(). If you are uploading many categories, it is more efficient to use upload_all(). For upload(), pass in name and children. name is the string which represents the parent category, and children is a list of dictionaries where each dictionary is a ...
categories.upload(name = "Droids", children = ["r2d2", "c3po"])
DEMO.ipynb
anthonybu/api_sdk
mit
Now let's upload a few categories and then check what parent categories are in the system
categories.upload_all([{"name":"month", "children":["January","February"]}, {"name":"Time of Day", "children":["morning", "evening"]}])
DEMO.ipynb
anthonybu/api_sdk
mit
To add children/subcategories, call upload() and pass in the parent category name and a list of the new subcategories to add. If you'd like to instead overwrite the existing subcategories with new subcategories, call upload() and pass in the parameter overwrite_children = True.
categories.upload(name = "Droids", children = ["bb8"])
DEMO.ipynb
anthonybu/api_sdk
mit
To rename a category, call rename(), with parameters name and new_name.
categories.rename(name = "month", new_name = "Months") categories.ids["Months"]
DEMO.ipynb
anthonybu/api_sdk
mit
You can delete categories either individually with delete(), or in bulk with delete_all(). You also have the option to delete the entire parent category or just some of the subcategories. To delete ALL CATEGORIES in a project, call clear_all_in_project with no parameters. Be careful with this one, and do not use unl...
categories.delete({"name": "Months", "children":["February"]}) categories.delete_all([{"name": "Droids", "children": ["bb8", "c3po"]}]) categories.delete("Droids") categories.delete_all(["Months", "Time of Day"]) categories.ids
DEMO.ipynb
anthonybu/api_sdk
mit
Tags Instantiate a BWTags object by passing in your project as a parameter, which loads all of the tags in your project. Print out ids to see which tags are currently in your project.
tags = BWTags(project) tags.names
DEMO.ipynb
anthonybu/api_sdk
mit
There are two ways to upload tags: individually and in bulk. When uploading many tags, it is more efficient to use upload_all. In upload, pass in the name of the tag. In upload_all, pass in a list of dictionaries, where each dictionary contains "name" as the key and the tag name as the its value
tags.upload(name = "yellow") tags.upload_all([{"name":"green"}, {"name":"blue"}, {"name":"purple"}]) tags.names
DEMO.ipynb
anthonybu/api_sdk
mit
To change the name of a tag, but mantain its id, upload it with keyword arguments name and new_name.
tags.upload(name = "yellow", new_name = "yellow-orange blend") tags.names
DEMO.ipynb
anthonybu/api_sdk
mit
As with categories, there are three ways of deleting tags. Delete one tag by calling delete and passing in a string, the name of the tag to delete Delete multiple tags by calling delete_all and passing in a list of strings, where each string is a name of a tag to delete To delete ALL TAGS in a project, call clear_all_...
tags.delete("purple") tags.delete_all(["blue", "green", "yellow-orange blend"]) tags.names
DEMO.ipynb
anthonybu/api_sdk
mit
Brandwatch Lists Note: to avoid ambiguity between the python data type "list" and a Brandwatch author list, site list, or location list, the latter is referred to in this demo as a "Brandwatch List." BWAuthorLists, BWSiteLists, BWLocationLists work almost identically. First, instantiate your the object which contains t...
authorlists = BWAuthorLists(project) authorlists.names
DEMO.ipynb
anthonybu/api_sdk
mit
To upload a Brandwatch List, pass in a name as a string and the contents of your Brandwatch List as a list of strings. The keyword "authors" is used for BWAuthorLists, shown below. The keyword "domains"is used for BWSiteLists. The keyword "locations" is used for BWLocationLists. To see the contents of a Brandwatch List...
authorlists.upload(name = "Writers", authors = ["Edward Albee", "Tenessee Williams", "Anna Deavere Smith"]) authorlists.get("Writers")["authors"] authorlists.upload(name = "Writers", new_name = "Playwrights", authors = ["Edward Albee", "Tenessee Williams", "...
DEMO.ipynb
anthonybu/api_sdk
mit
To add items to a Brandwatch List without reentering all of the existing items, call add_items
authorlists.add_items(name = "Playwrights", items = ["Eugene O'Neill"]) authorlists.get("Playwrights")["authors"]
DEMO.ipynb
anthonybu/api_sdk
mit
To delete a Brandwatch List, pass in its name. Note the ids before the Brandwatch List is deleted, compared to after it is deleted. The BWLists object is updated to reflect the Brandwatch Lists in the project after each upload and each delete
authorlists.names authorlists.delete("Playwrights") authorlists.names
DEMO.ipynb
anthonybu/api_sdk
mit
The only difference between how you use BWAuthorlists compared to how you use BWSiteLists and BWLocationLists is the parameter which is passed in. BWAuthorlists: authors = ["edward albee", "tenessee williams", "Anna Deavere Smith"] BWSiteLists: domains = ["github.com", "stackoverflow.com", "docs.python.org"] *BWLocati...
rules = BWRules(project) rules.names
DEMO.ipynb
anthonybu/api_sdk
mit
Every rule must have a name, an action, and filters. The first step to creating a rule through the API is to prepare filters by calling filters(). If your desired rules applies to a query (or queries), include queryName as a filter and pass in a list of the queries you want to apply it to. There are over a hundred fil...
filters = rules.filters(queryName = "ice cream cake", sentiment = "positive", twitterVerified = False, impactMin = 50, xprofession = ["Politician", "Legal"]) filters = rules.filters(queryName = ["Australian Animals", "i...
DEMO.ipynb
anthonybu/api_sdk
mit
The second step is to prepare the rule action by calling rule_action(). For this function, you must pass in the action and setting. Below I've used examples of adding categories and tags, but you can also set sentiment or workflow (as in the front end). If you pass in a category or tag that does not yet exist, it will...
action = rules.rule_action(action = "addTag", setting = ["animal food"])
DEMO.ipynb
anthonybu/api_sdk
mit
The last step is to upload! Pass in the name, filters, and action. Scope is optional - it will default to query if queryName is in the filters and otherwise be set to project. Backfill is also optional - it will default to False. The upload() function will automatically check the validity of your search string and g...
rules.upload(name = "rule", scope = "query", filter = filters, ruleAction = action, backfill = True)
DEMO.ipynb
anthonybu/api_sdk
mit
You can also upload rules in bulk. Below we prepare a bunch of filters and actions at once.
filters1 = rules.filters(search = "caknvfoga;vnaei") filters2 = rules.filters(queryName = ["Australian Animals"], search = "(bloop NEAR/10 blorp)") filters3 = rules.filters(queryName = ["Australian Animals", "ice cream cake"], search = '"hello world"') action1 = rules.rule_action(action = "addCategories", setting = {"...
DEMO.ipynb
anthonybu/api_sdk
mit
When uploading in bulk, it is helpful (but not necessary) to use the rules() function before uploading in order to keep the dictionaries organized.
rule1 = rules.rule(name = "rule1", filter = filters1, action = action1, scope = "project") rule2 = rules.rule(name = "rule2", filter = filters2, action = action2) rule3 = rules.rule(name = "rule3", ...
DEMO.ipynb
anthonybu/api_sdk
mit
As with other resources, we can delete, delete_all or clear_all_in_project
rules.delete(name = "rule") rules.delete_all(names = ["rule1", "rule2", "rule3"]) rules.names
DEMO.ipynb
anthonybu/api_sdk
mit
Signals Instantiate a BWSignals object by passing in your project as a parameter, which loads all of the signals in your project. Print out ids to see which signals are currently in your project.
signals = BWSignals(project) signals.names
DEMO.ipynb
anthonybu/api_sdk
mit
Again, we can upload signals individually or in batch. You must pass at least a name, queries (list of queries you'd like the signal to apply to) and subscribers. For each subscriber, you have to pass both an emailAddress and notificationThreshold. The notificationThreshold will be a number 1, 2 or 3 - where 1 means ...
signals.upload(name= "New Test", queries= ["ice cream cake"], parentCategory = ["Colors"], subscribers= [{"emailAddress": "test12345@brandwatch.com", "notificationThreshold": 1}]) signals.upload_all([{"name": "Signal Me", "queries": ["ice cream cake"], ...
DEMO.ipynb
anthonybu/api_sdk
mit
Signals can be deleted individually or in bulk.
signals.delete("New Test") signals.delete_all(["Signal Me", "Signal Test"]) signals.names
DEMO.ipynb
anthonybu/api_sdk
mit
Patching Mentions To patch the metadata on mentions, whether those mentions come from queries or from groups, you must first instantiate a BWMentions object and pass in your project as a parameter.
mentions = BWMentions(project) filtered = queries.get_mentions(name = "ice cream cake", startDate = start, endDate = today, parentCategory = ["Colors", "Days"], category = {"Colors": ["Blue...
DEMO.ipynb
anthonybu/api_sdk
mit
if you don't want to upload your tags and categories ahead of time, you don't have to! BWMentions will do that for you, but if there are a lot of differnet tags/categories, it's definitely more efficient to upload them in bulk ahead of time For this example, i'm arbitrarily patching a few of the mentions, rather than a...
mentions.patch_mentions(filtered[0:10], action = "addTag", setting = ["cold"]) mentions.patch_mentions(filtered[5:12], action = "starred", setting = True) mentions.patch_mentions(filtered[6:8], action = "addCategories", setting = {"color":["green", "blue"]})
DEMO.ipynb
anthonybu/api_sdk
mit
Herança
# Criando a classe Animal - Super-classe class Animal(): def __init__(self): print("Animal criado") def Identif(self): print("Animal") def comer(self): print("Comendo") # Criando a classe Cachorro - Sub-classe class Cachorro(Animal): def __init__(self): Anima...
Cap05/Notebooks/DSA-Python-Cap05-04-Heranca.ipynb
dsacademybr/PythonFundamentos
gpl-3.0
1. Introduction In this notebook we explore an application of clustering algorithms to shape segmentation from binary images. We will carry out some exploratory work with a small set of images provided with this notebook. Most of them are not binary images, so we must do some preliminary work to extract he binary shape...
name = "birds.jpg" name = "Seeds.jpg" birds = imread("Images/" + name) birdsG = np.sum(birds, axis=2) plt.imshow(birdsG, cmap=plt.get_cmap('gray')) plt.grid(False) plt.axis('off') plt.show()
U_lab1.Clustering/Lab_ShapeSegmentation_draft/LabSessionClustering.ipynb
ML4DS/ML4all
mit
2. Thresholding Select an intensity threshold by manual inspection of the image histogram
plt.hist(birdsG.ravel(), bins=256) plt.show()
U_lab1.Clustering/Lab_ShapeSegmentation_draft/LabSessionClustering.ipynb
ML4DS/ML4all
mit
Plot the binary image after thresholding.
if name == "birds.jpg": th = 256 elif name == "Seeds.jpg": th = 650 birdsBN = birdsG > th # If there are more white than black pixels, reverse the image if np.sum(birdsBN) > float(np.prod(birdsBN.shape)/2): birdsBN = 1-birdsBN plt.imshow(birdsBN, cmap=plt.get_cmap('gray')) plt.grid(False) plt.axis('off') ...
U_lab1.Clustering/Lab_ShapeSegmentation_draft/LabSessionClustering.ipynb
ML4DS/ML4all
mit
3. Dataset generation Extract pixel coordinates dataset from image
(h, w) = birdsBN.shape bW = birdsBN * range(w) bH = birdsBN * np.array(range(h))[:,np.newaxis] pSet = [t for t in zip(bW.ravel(), bH.ravel()) if t!=(0,0)] X = np.array(pSet) print X plt.scatter(X[:, 0], X[:, 1], s=5); plt.axis('equal') plt.show()
U_lab1.Clustering/Lab_ShapeSegmentation_draft/LabSessionClustering.ipynb
ML4DS/ML4all
mit
4. k-means clustering algorithm
from sklearn.cluster import KMeans est = KMeans(50) # 4 clusters est.fit(X) y_kmeans = est.predict(X) plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=5, cmap='rainbow', linewidth=0.0) plt.axis('equal') plt.show()
U_lab1.Clustering/Lab_ShapeSegmentation_draft/LabSessionClustering.ipynb
ML4DS/ML4all
mit
5. Spectral clustering algorithm 5.1. Affinity matrix Compute and visualize the affinity matrix
from sklearn.metrics.pairwise import rbf_kernel gamma = 5 sf = 4 Xsub = X[0::sf] print Xsub.shape gamma = 0.001 K = rbf_kernel(Xsub, Xsub, gamma=gamma) plt.imshow(K, cmap='hot') plt.colorbar() plt.title('RBF Affinity Matrix for gamma = ' + str(gamma)) plt.grid('off') plt.show() from sklearn.cluster import SpectralCl...
U_lab1.Clustering/Lab_ShapeSegmentation_draft/LabSessionClustering.ipynb
ML4DS/ML4all
mit
例題9-2 「係数ダミー」 以下のようにモデルを設定して回帰分析を行う。 $Y_{i} = \alpha + \beta X_{i} + \gamma D_{i} + \delta D_{i} X_{i} + u_{i}$
# データ読み込み data = pd.read_csv('example/k0902.csv') data # 説明変数設定 X = data[['X', 'D', 'DX']] X = sm.add_constant(X) X # 被説明変数設定 Y = data['Y'] Y # OLSの実行(Ordinary Least Squares: 最小二乗法) model = sm.OLS(Y,X) results = model.fit() print(results.summary()) # ダミー別データ data_d0 = data[data["D"] == 0] data_d1 = data[data["D"] =...
Dummy.ipynb
ogaway/Econometrics
gpl-3.0
例題9-3 「t検定による構造変化のテスト」 例題9-2において$\gamma = 0$に関するP値は0.017であり、$\delta = 0$に関するP値は0.003であることから、標準的な有意水準を設定すれば、いずれのダミー変数も有意であるといえる。 例題9-4 「F検定による構造変化のテスト」
# ダミー変数を加えない時のOLSモデル作成 X = data[['X']] X = sm.add_constant(X) model2 = sm.OLS(Y,X) results2 = model2.fit() # anova(Analysis of Variance) print(sm.stats.anova_lm(results2, results))
Dummy.ipynb
ogaway/Econometrics
gpl-3.0
Import non-standard libraries (install as needed)
from osgeo import ogr,osr import folium import simplekml
Lecture 11/.ipynb_checkpoints/Satoshi Nakamoto Lecture 11 Jupyter Notebook-checkpoint.ipynb
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
mit
Optional directory creation
if not exists('./data'): makedirs('./data') chdir("./data")
Lecture 11/.ipynb_checkpoints/Satoshi Nakamoto Lecture 11 Jupyter Notebook-checkpoint.ipynb
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
mit
Is the ESRI Shapefile driver available?
driverName = "ESRI Shapefile" drv = ogr.GetDriverByName( driverName ) if drv is None: print "%s driver not available.\n" % driverName else: print "%s driver IS available.\n" % driverName
Lecture 11/.ipynb_checkpoints/Satoshi Nakamoto Lecture 11 Jupyter Notebook-checkpoint.ipynb
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
mit
Define a function which will create a shapefile from the points input and export it as kml if the option is set to True.
def shpFromPoints(filename, layername, points, save_kml = True): spatialReference = osr.SpatialReference() spatialReference.ImportFromProj4('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') ds = drv.CreateDataSource(filename) layer=ds.CreateLayer(layername, spatialReference, ogr.wkbPoint) layerDef...
Lecture 11/.ipynb_checkpoints/Satoshi Nakamoto Lecture 11 Jupyter Notebook-checkpoint.ipynb
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
mit
Define the file and layer name as well as the points to be mapped.
filename = "wageningenpoints.shp" layername = "wagpoints" pts = [(5.665777,51.987398), (5.663133,51.978434)] shpFromPoints(filename, layername, pts)
Lecture 11/.ipynb_checkpoints/Satoshi Nakamoto Lecture 11 Jupyter Notebook-checkpoint.ipynb
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
mit
Define a function to create a nice map with the points using folium library.
def mapFromPoints(pts, outname, zoom_level, save = True): mean_long = mean([pt[1] for pt in pts]) mean_lat = mean([pt[0] for pt in pts]) point_map = folium.Map(location=[mean_long, mean_lat], zoom_start = zoom_level) for pt in pts: folium.Marker([pt[1], pt[0]],\ popup = folium.Popup(foli...
Lecture 11/.ipynb_checkpoints/Satoshi Nakamoto Lecture 11 Jupyter Notebook-checkpoint.ipynb
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
mit
Call the function specifying the list of points, the output map name and its zoom level. If not False, the map is saved as an html
mapFromPoints(pts, "SatoshiNakamotoMap", zoom_level = 15)
Lecture 11/.ipynb_checkpoints/Satoshi Nakamoto Lecture 11 Jupyter Notebook-checkpoint.ipynb
SatoshiNakamotoGeoscripting/SatoshiNakamotoGeoscripting
mit
Introduction The Corpus Callosum (CC) is the largest white matter structure in the central nervous system that connects both brain hemispheres and allows the communication between them. The CC has great importance in research studies due to the correlation between shape and volume with some subject's characteristics, s...
#Loading labeled segmentations seg_label = genfromtxt('../../dataset/Seg_Watershed/watershed_label.csv', delimiter=',').astype('uint8') list_masks = seg_label[np.logical_or(seg_label[:,1] == 0, seg_label[:,1] == 1), 0] #Extracting segmentations list_labels = seg_label[np.logical_or(seg_label[:,1] == 0, seg_label[:,1] ...
dev/Autoencoderxclass.ipynb
wilomaku/IA369Z
gpl-3.0
Shape signature for comparison Signature is a shape descriptor that measures the rate of variation along the segmentation contour. As shown in figure, the curvature $k$ in the pivot point $p$, with coordinates ($x_p$,$y_p$), is calculated using the next equation. This curvature depict the angle between the segments $\o...
smoothness = 700 #Smoothness degree = 5 #Spline degree fit_res = 0.35 resols = np.arange(0.01,0.5,0.01) #Signature resolutions resols = np.insert(resols,0,fit_res) #Insert resolution for signature fitting points = 500 #Points of Spline reconstruction prof_vec = np.empty((len(list_masks),resols.shape[0],points)) #Initi...
dev/Autoencoderxclass.ipynb
wilomaku/IA369Z
gpl-3.0
Autoencoder
def train(model,train_loader,loss_fn,optimizer,epochs=100,patience=5,criteria_stop="loss"): hist_train_loss = hist_val_loss = hist_train_acc = hist_val_acc = np.array([]) best_epoch = patience_count = 0 print("Training starts along %i epoch"%epochs) for e in range(epochs): correct_train = corre...
dev/Autoencoderxclass.ipynb
wilomaku/IA369Z
gpl-3.0
Testing in new datasets ROQS test
#Loading labeled segmentations seg_label = genfromtxt('../../dataset/Seg_ROQS/roqs_label.csv', delimiter=',').astype('uint8') list_masks = seg_label[np.logical_or(seg_label[:,1] == 0, seg_label[:,1] == 1), 0] #Extracting segmentations list_labels = seg_label[np.logical_or(seg_label[:,1] == 0, seg_label[:,1] == 1), 1] ...
dev/Autoencoderxclass.ipynb
wilomaku/IA369Z
gpl-3.0
Pixel-based test
#Loading labeled segmentations seg_label = genfromtxt('../../dataset/Seg_pixel/pixel_label.csv', delimiter=',').astype('uint8') list_masks = seg_label[np.logical_or(seg_label[:,1] == 0, seg_label[:,1] == 1), 0] #Extracting segmentations list_labels = seg_label[np.logical_or(seg_label[:,1] == 0, seg_label[:,1] == 1), 1...
dev/Autoencoderxclass.ipynb
wilomaku/IA369Z
gpl-3.0
Declaring a pre-processing configuration The pre-processing configuration defines how to interpret the raw crowdsourcing input. To do this, we need to define a configuration class. First, we import the default CrowdTruth configuration class:
import crowdtruth from crowdtruth.configuration import DefaultConfig
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Our test class inherits the default configuration DefaultConfig, while also declaring some additional attributes that are specific to the Person Type Annotation in Video task: inputColumns: list of input columns from the .csv file with the input data outputColumns: list of output columns from the .csv file with the an...
class TestConfig(DefaultConfig): inputColumns = ["videolocation", "subtitles", "imagetags", "subtitletags"] outputColumns = ["selected_answer"] # processing of a closed task open_ended_task = False annotation_vector = ["archeologist", "architect", "artist", "astronaut", "athlete", "businesspers...
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Pre-processing the input data After declaring the configuration of our input file, we are ready to pre-process the crowd data:
data, config = crowdtruth.load( file = "../data/person-video-multiple-choice.csv", config = TestConfig() ) data['judgments'].head()
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Computing the CrowdTruth metrics The pre-processed data can then be used to calculate the CrowdTruth metrics:
results = crowdtruth.run(data, config)
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Video fragment quality The video fragments metrics are stored in results["units"]. The uqs column in results["units"] contains the video fragment quality scores, capturing the overall workers agreement over each video fragment.
results["units"].head()
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Distribution of video fragment quality scores The histogram below shows video fragment quality scores are nicely distributed, with both low and high quality video fragments.
import matplotlib.pyplot as plt %matplotlib inline plt.hist(results["units"]["uqs"]) plt.xlabel("Video Fragment Quality Score") plt.ylabel("Video Fragments")
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
The unit_annotation_score column in results["units"] contains the video fragment-annotation scores, capturing the likelihood that an annotation is expressed in a video fragment. For each video fragment, we store a dictionary mapping each annotation to its video fragment-annotation score.
results["units"]["unit_annotation_score"].head()
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Ambiguous video fragments A low unit quality score can be used to identify ambiguous video fragments. First, we sort the unit quality metrics stored in results["units"] based on the quality score (uqs), in ascending order. Thus, the most clear video fragments are found at the tail of the new structure:
results["units"].sort_values(by=["uqs"])[["input.videolocation", "uqs", "unit_annotation_score"]].head()
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Below we show an example video fragment with low quality score, where workers couldn't agree on what annotation best describes the person in the video. The role of the person in the video is not directly specified, so the workers made assumptions based on the topic of discussion.
from IPython.display import HTML print(results["units"].sort_values(by=["uqs"])[["uqs"]].iloc[0]) print("\n") print("Person types picked for the video below:") for k, v in results["units"].sort_values(by=["uqs"])[["unit_annotation_score"]].iloc[0]["unit_annotation_score"].items(): if v > 0: print(str(k) +...
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Unambiguous video fragments Similarly, a high unit quality score represents lack of ambiguity of the video fragment.
results["units"].sort_values(by=["uqs"], ascending=False)[["input.videolocation", "uqs", "unit_annotation_score"]].head()
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Below we show an example unambiguous video fragment - no person appears in the video, so most workers picked the none option in the crowd task.
print(results["units"].sort_values(by=["uqs"], ascending=False)[["uqs"]].iloc[0]) print("\n") print("Person types picked for the video below:") for k, v in results["units"].sort_values(by=["uqs"], ascending=False)[["unit_annotation_score"]].iloc[0]["unit_annotation_score"].items(): if v > 0: print(str(k) +...
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Worker Quality Scores The worker metrics are stored in results["workers"]. The wqs columns in results["workers"] contains the worker quality scores, capturing the overall agreement between one worker and all the other workers.
results["workers"].head()
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Distribution of worker quality scores The histogram below shows the worker quality scores are distributed across a wide spectrum, from low to high quality workers.
plt.hist(results["workers"]["wqs"]) plt.xlabel("Worker Quality Score") plt.ylabel("Workers")
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Low quality workers Low worker quality scores can be used to identify spam workers, or workers that have misunderstood the annotation task.
results["workers"].sort_values(by=["wqs"]).head()
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Example annotations from low quality worker 44606916 (with the second lowest quality score) for video fragment 1856509900:
import operator work_id = results["workers"].sort_values(by=["wqs"]).index[1] work_units = results["judgments"][results["judgments"]["worker"] == work_id]["unit"] work_judg = results["judgments"][results["judgments"]["unit"] == work_units.iloc[0]] print("JUDGMENTS OF LOW QUALITY WORKER %d FOR VIDEO %d:" % (work_id, ...
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Example annotations from the same low quality worker (44606916) for a second video fragment (1856509903):
work_judg = results["judgments"][results["judgments"]["unit"] == work_units.iloc[1]] print("JUDGMENTS OF LOW QUALITY WORKER %d FOR VIDEO %d:" % (work_id, work_units.iloc[1])) for k, v in work_judg[work_judg["worker"] == work_id]["output.selected_answer"].iloc[0].items(): if v > 0: print(str(k) + " : " + st...
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
High quality workers High worker quality scores can be used to identify reliable workers.
results["workers"].sort_values(by=["wqs"], ascending=False).head()
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Example annotations from worker 6432269 (with the highest worker quality score) for video fragment 1856509904:
work_id = results["workers"].sort_values(by=["wqs"], ascending=False).index[0] work_units = results["judgments"][results["judgments"]["worker"] == work_id]["unit"] work_judg = results["judgments"][results["judgments"]["unit"] == work_units.iloc[0]] print("JUDGMENTS OF HIGH QUALITY WORKER %d FOR VIDEO %d:" % (work_id, ...
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Example annotations from worker 6432269 (with the highest worker quality score) for video fragment 1856509908:
work_id = results["workers"].sort_values(by=["wqs"], ascending=False).index[0] work_units = results["judgments"][results["judgments"]["worker"] == work_id]["unit"] work_judg = results["judgments"][results["judgments"]["unit"] == work_units.iloc[1]] print("JUDGMENTS OF HIGH QUALITY WORKER %d FOR VIDEO %d:" % (work_id, ...
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Worker Quality vs. # Annotations As we can see from the plot below, there is no clear correlation between worker quality and number of annotations collected from the worker.
plt.scatter(results["workers"]["wqs"], results["workers"]["judgment"]) plt.xlabel("WQS") plt.ylabel("# Annotations")
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
Annotation Quality Scores The annotation metrics are stored in results["annotations"]. The aqs column contains the annotation quality scores, capturing the overall worker agreement over one annotation. There is a slight correlation between the number of annotations (column output.selected_answer) and the annotation qua...
results["annotations"]["output.selected_answer"] = 0 for idx in results["judgments"].index: for k,v in results["judgments"]["output.selected_answer"][idx].items(): if v > 0: results["annotations"].loc[k, "output.selected_answer"] += 1 results["annotations"] = results["annotations"].sort_v...
tutorial/notebooks/Multiple Choice Task - Person Type Annotation in Video.ipynb
CrowdTruth/CrowdTruth-core
apache-2.0
DDL to construct table for SQL transformations: sql CREATE TABLE kaggle_sf_crime ( dates TIMESTAMP, category VARCHAR, descript VARCHAR, dayofweek VARCHAR, pd_district VARCHAR, resolution VARCHAR, addr VARCHAR, X FLOAT, Y FLOAT); Getting training data into a locally hosted PostgreSQL data...
#data_path = "./data/train_transformed.csv" #df = pd.read_csv(data_path, header=0) #x_data = df.drop('category', 1) #y = df.category.as_matrix() ########## Adding the date back into the data #import csv #import time #import calendar #data_path = "./data/train.csv" #dataCSV = open(data_path, 'rt') #csvData = list(csv....
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Local, individual load of updated data set (with weather data integrated) into training, development, and test subsets.
data_path = "/Users/Bryan/Desktop/UC_Berkeley_MIDS_files/Courses/W207_Intro_To_Machine_Learning/Final_Project/x_data_3.csv" df = pd.read_csv(data_path, header=0) x_data = df.drop('category', 1) y = df.category.as_matrix() # Impute missing values with mean values: x_complete = x_data.fillna(x_data.mean()) X_raw = x_com...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Sarah's School data that we may still get to work as features: (Negated with hashtags for now, as will cause file dependency issues if run locally for everyone. Will be run by Isabell in final notebook with correct files she needs)
### Read in zip code data #data_path_zip = "./data/2016_zips.csv" #zips = pd.read_csv(data_path_zip, header=0, sep ='\t', usecols = [0,5,6], names = ["GEOID", "INTPTLAT", "INTPTLONG"], dtype ={'GEOID': int, 'INTPTLAT': float, 'INTPTLONG': float}) #sf_zips = zips[(zips['GEOID'] > 94000) & (zips['GEOID'] < 94189)] ### M...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Formatting to meet Kaggle submission standards: (Negated with hashtags for now, as will cause file dependency issues if run locally for everyone. Will be run by Isabell in final notebook with correct files she needs)
# The Kaggle submission format requires listing the ID of each example. # This is to remember the order of the IDs after shuffling #allIDs = np.array(list(df.axes[0])) #allIDs = allIDs[shuffle] #testIDs = allIDs[800000:] #devIDs = allIDs[700000:800000] #trainIDs = allIDs[:700000] # Extract the column names for the re...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Generate baseline prediction probabilities from MNB classifier and store in a .csv file (Negated with hashtags for now, as will cause file dependency issues if run locally for everyone. Will be run by Isabell in final notebook with correct files she needs)
# Generate a baseline MNB classifier and make it return prediction probabilities for the actual test data #def MNB(): # mnb = MultinomialNB(alpha = 0.0000001) # mnb.fit(train_data, train_labels) # print("\n\nMultinomialNB accuracy on dev data:", mnb.score(dev_data, dev_labels)) # return mnb.predict_proba(de...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Note: the code above will shuffle data differently every time it's run, so model accuracies will vary accordingly.
## Data sub-setting quality check-point print(train_data[:1]) print(train_labels[:1]) # Modeling quality check-point with MNB--fast model def MNB(): mnb = MultinomialNB(alpha = 0.0000001) mnb.fit(train_data, train_labels) print("\n\nMultinomialNB accuracy on dev data:", mnb.score(dev_data, dev_labels)) ...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Defining Performance Criteria As determined by the Kaggle submission guidelines, the performance criteria metric for the San Francisco Crime Classification competition is Multi-class Logarithmic Loss (also known as cross-entropy). There are various other performance metrics that are appropriate for different domains: ...
def model_prototype(train_data, train_labels, eval_data, eval_labels): knn = KNeighborsClassifier(n_neighbors=5).fit(train_data, train_labels) bnb = BernoulliNB(alpha=1, binarize = 0.5).fit(train_data, train_labels) mnb = MultinomialNB().fit(train_data, train_labels) log_reg = LogisticRegression().fit(t...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Adding Features, Hyperparameter Tuning, and Model Calibration To Improve Prediction For Each Classifier Here we seek to optimize the performance of our classifiers in a three-step, dynamnic engineering process. 1) Feature addition We previously added components from the weather data into the original SF crime data as ...
list_for_ks = [] list_for_ws = [] list_for_ps = [] list_for_log_loss = [] def k_neighbors_tuned(k,w,p): tuned_KNN = KNeighborsClassifier(n_neighbors=k, weights=w, p=p).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = tuned_KNN.predict_proba(mini_dev_data) list_for_ks.append(this_k) ...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Model calibration: Here we will calibrate the KNN classifier with both Platt Scaling and with Isotonic Regression using CalibratedClassifierCV with various parameter settings. The "method" parameter can be set to "sigmoid" or to "isotonic", corresponding to Platt Scaling and to Isotonic Regression respectively.
list_for_ks = [] list_for_ws = [] list_for_ps = [] list_for_ms = [] list_for_log_loss = [] def knn_calibrated(k,w,p,m): tuned_KNN = KNeighborsClassifier(n_neighbors=k, weights=w, p=p).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = tuned_KNN.predict_proba(mini_dev_data) ccv = Calibra...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Comments on results for Hyperparameter tuning and Calibration for KNN: We see that the best log loss we achieve for KNN is with _ neighbors, _ weights, and _ power parameter. When we add-in calibration, we see that the the best log loss we achieve for KNN is with _ neighbors, _ weights, _ power parameter, and _ calibra...
list_for_as = [] list_for_bs = [] list_for_log_loss = [] def BNB_tuned(a,b): bnb_tuned = BernoulliNB(alpha = a, binarize = b).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = bnb_tuned.predict_proba(mini_dev_data) list_for_as.append(this_a) list_for_bs.append(this_b) working_l...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Model calibration: BernoulliNB Here we will calibrate the BNB classifier with both Platt Scaling and with Isotonic Regression using CalibratedClassifierCV with various parameter settings. The "method" parameter can be set to "sigmoid" or to "isotonic", corresponding to Platt Scaling and to Isotonic Regression respecti...
list_for_as = [] list_for_bs = [] list_for_ms = [] list_for_log_loss = [] def BNB_calibrated(a,b,m): bnb_tuned = BernoulliNB(alpha = a, binarize = b).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = bnb_tuned.predict_proba(mini_dev_data) ccv = CalibratedClassifierCV(bnb_tuned, method ...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Hyperparameter tuning: Multinomial Naive Bayes For the Multinomial Naive Bayes classifer, we seek to optimize the alpha parameter (Laplace smoothing parameter).
list_for_as = [] list_for_log_loss = [] def MNB_tuned(a): mnb_tuned = MultinomialNB(alpha = a).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities =mnb_tuned.predict_proba(mini_dev_data) list_for_as.append(this_a) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = dev_predi...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Model calibration: MultinomialNB Here we will calibrate the MNB classifier with both Platt Scaling and with Isotonic Regression using CalibratedClassifierCV with various parameter settings. The "method" parameter can be set to "sigmoid" or to "isotonic", corresponding to Platt Scaling and to Isotonic Regression respec...
list_for_as = [] list_for_ms = [] list_for_log_loss = [] def MNB_calibrated(a,m): mnb_tuned = MultinomialNB(alpha = a).fit(mini_train_data, mini_train_labels) ccv = CalibratedClassifierCV(mnb_tuned, method = m, cv = 'prefit') ccv.fit(mini_calibrate_data, mini_calibrate_labels) ccv_prediction_probabilit...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Tuning: Gaussian Naive Bayes For the Gaussian Naive Bayes classifier there are no inherent parameters within the classifier function to optimize, but we will look at our log loss before and after adding noise to the data that is hypothesized to give it a more normal (Gaussian) distribution, which is required by the GNB...
def GNB_pre_tune(): gnb_pre_tuned = GaussianNB().fit(mini_train_data, mini_train_labels) dev_prediction_probabilities =gnb_pre_tuned.predict_proba(mini_dev_data) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = dev_prediction_probabilities, labels = crime_labels_mini_dev) print("Multi-clas...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Model calibration: GaussianNB Here we will calibrate the GNB classifier with both Platt Scaling and with Isotonic Regression using CalibratedClassifierCV with various parameter settings. The "method" parameter can be set to "sigmoid" or to "isotonic", corresponding to Platt Scaling and to Isotonic Regression respectiv...
list_for_ms = [] list_for_log_loss = [] def GNB_calibrated(m): # Gaussian Naive Bayes requires the data to have a relative normal distribution. Sometimes # adding noise can improve performance by making the data more normal: mini_train_data_noise = np.random.rand(mini_train_data.shape[0],mini_train_data.sh...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Logistic Regression Hyperparameter tuning: For the Logistic Regression classifier, we can seek to optimize the following classifier parameters: penalty (l1 or l2), C (inverse of regularization strength), solver ('newton-cg', 'lbfgs', 'liblinear', or 'sag') Model calibration: See above Decision Tree (Bryan) Hyperparamet...
### All the work from Sarah's notebook: import theano from theano import tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams print (theano.config.device) # We're using CPUs (for now) print (theano.config.floatX )# Should be 64 bit for CPUs np.random.seed(0) from IPython.display import d...
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Model calibration: See above Random Forest (Sam, possibly in AWS) Hyperparameter tuning: For the Random Forest classifier, we can seek to optimize the following classifier parameters: n_estimators (the number of trees in the forsest), max_features, max_depth, min_samples_leaf, bootstrap (whether or not bootstrap sample...
# Here we will likely use Pipeline and GridSearchCV in order to find the overall classifier with optimized Multi-class Log Loss. # This will be the last step after all attempts at feature addition, hyperparameter tuning, and calibration are completed # and the corresponding performance metrics are gathered.
iterations/misc/Cha_Goodgame_Kao_Moore_W207_Final_Project_updated_08_19_2230.ipynb
samgoodgame/sf_crime
mit
Benchmarking GP codes Implemented the right way, GPs can be super fast! Let's compare the time it takes to evaluate our GP likelihood and the time it takes to evaluate the likelihood computed with the snazzy george and celerite packages. We'll learn how to use both along the way. Let's create a large, fake dataset for ...
import numpy as np np.random.seed(0) t = np.linspace(0, 10, 10000) y = np.random.randn(10000) sigma = np.ones(10000)
Sessions/Session13/Day2/02-Fast-GPs.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Our GP
def ExpSquaredCovariance(t, A=1.0, l=1.0, tprime=None): """ Return the ``N x M`` exponential squared covariance matrix. """ if tprime is None: tprime = t TPrime, T = np.meshgrid(tprime, t) return A ** 2 * np.exp(-0.5 * (T - TPrime) ** 2 / l ** 2) def ln_gp_likelihood(t, y, sig...
Sessions/Session13/Day2/02-Fast-GPs.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit