path
stringlengths
7
265
concatenated_notebook
stringlengths
46
17M
.ipynb_checkpoints/Amazon_Reviews_ETL_starter_code-checkpoint.ipynb
###Markdown Load Amazon Data into Spark DataFrame ###Code from pyspark import SparkFiles url = "" spark.sparkContext.addFile(url) df = spark.read.option("encoding", "UTF-8").csv(SparkFiles.get(""), sep="\t", header=True, inferSchema=True) df.show() ###Output _____no_output_____ ###Markdown Create DataFrames to match tables ###Code from pyspark.sql.functions import to_date # Read in the Review dataset as a DataFrame # Create the customers_table DataFrame # customers_df = df.groupby("").agg({""}).withColumnRenamed("", "customer_count") # Create the products_table DataFrame and drop duplicates. # products_df = df.select([]).drop_duplicates() # Create the review_id_table DataFrame. # Convert the 'review_date' column to a date datatype with to_date("review_date", 'yyyy-MM-dd').alias("review_date") # review_id_df = df.select([, to_date("review_date", 'yyyy-MM-dd').alias("review_date")]) # Create the vine_table. DataFrame # vine_df = df.select([]) ###Output _____no_output_____ ###Markdown Connect to the AWS RDS instance and write each DataFrame to its table. ###Code # Configure settings for RDS mode = "append" jdbc_url="jdbc:postgresql://<endpoint>:5432/<database name>" config = {"user":"postgres", "password": "<password>", "driver":"org.postgresql.Driver"} # Write review_id_df to table in RDS review_id_df.write.jdbc(url=jdbc_url, table='review_id_table', mode=mode, properties=config) # Write products_df to table in RDS # about 3 min products_df.write.jdbc(url=jdbc_url, table='products_table', mode=mode, properties=config) # Write customers_df to table in RDS # 5 min 14 s customers_df.write.jdbc(url=jdbc_url, table='customers_table', mode=mode, properties=config) # Write vine_df to table in RDS # 11 minutes vine_df.write.jdbc(url=jdbc_url, table='vine_table', mode=mode, properties=config) ###Output _____no_output_____
components/outlier-detection/cifar10/cifar10_outlier.ipynb
###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml !cat ../../../notebooks/resources/seldon-gateway.yaml ###Output _____no_output_____ ###Markdown Setup Resources ###Code !kubectl create namespace cifar10 %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10 !kubectl create -f broker.yaml %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10 spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10 spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 !kubectl apply -f event-display.yaml ###Output _____no_output_____ ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: tfserving-cifar10 namespace: cifar10 spec: protocol: tensorflow transport: rest predictors: - componentSpecs: - spec: containers: - args: - --port=8500 - --rest_api_port=8501 - --model_name=resnet32 - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32 image: tensorflow/serving name: resnet32 ports: - containerPort: 8501 name: http protocol: TCP graph: name: resnet32 type: MODEL endpoint: service_port: 8501 logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10/default name: model replicas: 1 !kubectl apply -f cifar10.yaml ###Output _____no_output_____ ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. Here we configure `seldonio/alibi-detect-server` to use rclone for downloading the artifact. If `RCLONE_ENABLED=true` environmental variable is set or any of the environmental variables contain `RCLONE_CONFIG` in their name then rclonewill be used to download the artifacts. If `RCLONE_ENABLED=false` or no `RCLONE_CONFIG` variables are present then kfserving storage.py logic will be used to download the artifacts. ###Code %%writefile cifar10od.yaml apiVersion: v1 kind: Secret metadata: name: seldon-rclone-secret namespace: cifar10 type: Opaque stringData: RCLONE_CONFIG_GS_TYPE: google cloud storage RCLONE_CONFIG_GS_ANONYMOUS: "true" --- apiVersion: serving.knative.dev/v1 kind: Service metadata: name: vae-outlier namespace: cifar10 spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.8.0-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --http_port - '8080' - --protocol - tensorflow.http - --storage_uri - gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10 - --reply_url - http://hello-display.cifar10 - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector envFrom: - secretRef: name: seldon-rclone-secret !kubectl apply -f cifar10od.yaml ###Output _____no_output_____ ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: vaeoutlier-trigger namespace: cifar10 spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: vae-outlier namespace: cifar10 !kubectl apply -f trigger.yaml ###Output _____no_output_____ ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) ###Output _____no_output_____ ###Markdown Optionally add an authorization token here if you need one.Acquiring this token will be dependent on your auth setup. ###Code TOKEN = "Bearer <my token>" ###Output _____no_output_____ ###Markdown If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following ###Code # CLUSTER_IP="localhost:8004" SERVICE_HOSTNAMES=!(kubectl get ksvc -n cifar10 vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import json import matplotlib.pyplot as plt import numpy as np import tensorflow as tf tf.keras.backend.clear_session() import requests from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype("float32") / 255 X_test = X_test.astype("float32") / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ( "plane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck", ) def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis("off") plt.show() def predict(X): formData = {"instances": X.tolist()} headers = {"Authorization": TOKEN} res = requests.post( "http://" + CLUSTER_IP + "/seldon/cifar10/tfserving-cifar10/v1/models/resnet32/:predict", json=formData, headers=headers, ) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ", res.status_code) return [] def outlier(X): formData = {"instances": X.tolist()} headers = { "Alibi-Detect-Return-Feature-Score": "true", "Alibi-Detect-Return-Instance-Score": "true", "ce-namespace": "default", "ce-modelid": "cifar10", "ce-type": "io.seldon.serving.inference.request", "ce-id": "1234", "ce-source": "localhost", "ce-specversion": "1.0", } headers["Host"] = SERVICE_HOSTNAME_VAEOD headers["Authorization"] = TOKEN res = requests.post("http://" + CLUSTER_IP + "/", json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ", res.status_code) return [] ###Output _____no_output_____ ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx : idx + 1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask( X.reshape(1, 32, 32, 3), mask_size=(10, 10), n_masks=1, channels=[0, 1, 2], mask_type="normal", noise_distr=(0, 1), clip_rng=(0, 1), ) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[-1])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete ns cifar10 ###Output _____no_output_____ ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml !cat ../../../notebooks/resources/seldon-gateway.yaml ###Output apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: seldon-gateway namespace: istio-system spec: selector: istio: ingressgateway # use istio default controller servers: - port: number: 80 name: http protocol: HTTP hosts: - "*" ###Markdown Setup Resources ###Code !kubectl create namespace cifar10 %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10 !kubectl create -f broker.yaml %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10 spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10 spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 !kubectl apply -f event-display.yaml ###Output deployment.apps/hello-display unchanged service/hello-display unchanged ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: tfserving-cifar10 namespace: cifar10 spec: protocol: tensorflow transport: rest predictors: - componentSpecs: - spec: containers: - args: - --port=8500 - --rest_api_port=8501 - --model_name=resnet32 - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32 image: tensorflow/serving name: resnet32 ports: - containerPort: 8501 name: http protocol: TCP graph: name: resnet32 type: MODEL endpoint: service_port: 8501 logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10/default name: model replicas: 1 !kubectl apply -f cifar10.yaml ###Output seldondeployment.machinelearning.seldon.io/tfserving-cifar10 unchanged ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. Here we configure `seldonio/alibi-detect-server` to use rclone for downloading the artifact. If `RCLONE_ENABLED=true` environmental variable is set or any of the enviromental variables contain `RCLONE_CONFIG` in their name then rclonewill be used to download the artifacts. If `RCLONE_ENABLED=false` or no `RCLONE_CONFIG` variables are present then kfserving storage.py logic will be used to download the artifacts. ###Code %%writefile cifar10od.yaml apiVersion: v1 kind: Secret metadata: name: seldon-rclone-secret namespace: cifar10 type: Opaque stringData: RCLONE_CONFIG_GS_TYPE: google cloud storage RCLONE_CONFIG_GS_ANONYMOUS: "true" --- apiVersion: serving.knative.dev/v1 kind: Service metadata: name: vae-outlier namespace: cifar10 spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.8.0-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --http_port - '8080' - --protocol - tensorflow.http - --storage_uri - gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10 - --reply_url - http://hello-display.cifar10 - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector envFrom: - secretRef: name: seldon-rclone-secret !kubectl apply -f cifar10od.yaml ###Output secret/seldon-rclone-secret configured service.serving.knative.dev/vae-outlier configured ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: vaeoutlier-trigger namespace: cifar10 spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: vae-outlier namespace: cifar10 !kubectl apply -f trigger.yaml ###Output trigger.eventing.knative.dev/vaeoutlier-trigger unchanged ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) ###Output 172.18.255.1 ###Markdown Optionally add an authorization token here if you need one.Acquiring this token will be dependent on your auth setup. ###Code TOKEN="Bearer <my token>" ###Output _____no_output_____ ###Markdown If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following ###Code #CLUSTER_IP="localhost:8004" SERVICE_HOSTNAMES=!(kubectl get ksvc -n cifar10 vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import matplotlib.pyplot as plt import numpy as np import json import tensorflow as tf tf.keras.backend.clear_session() from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image import requests train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() def predict(X): formData = { 'instances': X.tolist() } headers = {"Authorization":TOKEN} res = requests.post('http://'+CLUSTER_IP+'/seldon/cifar10/tfserving-cifar10/v1/models/resnet32/:predict', json=formData, headers=headers) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ",res.status_code) return [] def outlier(X): formData = { 'instances': X.tolist() } headers = {"Alibi-Detect-Return-Feature-Score":"true","Alibi-Detect-Return-Instance-Score":"true", \ "ce-namespace": "default","ce-modelid":"cifar10","ce-type":"io.seldon.serving.inference.request", \ "ce-id":"1234","ce-source":"localhost","ce-specversion":"1.0"} headers["Host"] = SERVICE_HOSTNAME_VAEOD headers["Authorization"] = TOKEN res = requests.post('http://'+CLUSTER_IP+'/', json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ",res.status_code) return [] ###Output (50000, 32, 32, 3) (50000, 1) (10000, 32, 32, 3) (10000, 1) ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx:idx+1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output Outlier False ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask(X.reshape(1, 32, 32, 3), mask_size=(10,10), n_masks=1, channels=[0,1,2], mask_type='normal', noise_distr=(0,1), clip_rng=(0,1)) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[-1])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output Outlier True ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete ns cifar10 ###Output namespace "cifar10" deleted ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml ###Output gateway.networking.istio.io/seldon-gateway unchanged ###Markdown Setup Resources ###Code !kubectl create namespace cifar10 %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10 !kubectl create -f broker.yaml %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10 spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10 spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 !kubectl apply -f event-display.yaml ###Output deployment.apps/hello-display created service/hello-display created ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: tfserving-cifar10 namespace: cifar10 spec: protocol: tensorflow transport: rest predictors: - componentSpecs: - spec: containers: - args: - --port=8500 - --rest_api_port=8501 - --model_name=resnet32 - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32 image: tensorflow/serving name: resnet32 ports: - containerPort: 8501 name: http protocol: TCP graph: name: resnet32 type: MODEL endpoint: service_port: 8501 logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10/default name: model replicas: 1 !kubectl apply -f cifar10.yaml ###Output seldondeployment.machinelearning.seldon.io/tfserving-cifar10 created ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. ###Code %%writefile cifar10od.yaml apiVersion: serving.knative.dev/v1 kind: Service metadata: name: vae-outlier namespace: cifar10 spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.5.0-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --http_port - '8080' - --protocol - tensorflow.http - --storage_uri - gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10 - --reply_url - http://hello-display.cifar10 - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector !kubectl apply -f cifar10od.yaml ###Output service.serving.knative.dev/vae-outlier created ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: vaeoutlier-trigger namespace: cifar10 spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: vae-outlier namespace: cifar10 !kubectl apply -f trigger.yaml ###Output trigger.eventing.knative.dev/vaeoutlier-trigger created ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) ###Output 35.240.18.201 ###Markdown If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following ###Code #CLUSTER_IP="localhost:8004" SERVICE_HOSTNAMES=!(kubectl get ksvc -n cifar10 vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import matplotlib.pyplot as plt import numpy as np import json import tensorflow as tf tf.keras.backend.clear_session() from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image import requests train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() def predict(X): formData = { 'instances': X.tolist() } headers = {} res = requests.post('http://'+CLUSTER_IP+'/seldon/cifar10/tfserving-cifar10/v1/models/resnet32/:predict', json=formData, headers=headers) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ",res.status_code) return [] def outlier(X): formData = { 'instances': X.tolist() } headers = {"Alibi-Detect-Return-Feature-Score":"true","Alibi-Detect-Return-Instance-Score":"true", \ "ce-namespace": "default","ce-modelid":"cifar10","ce-type":"io.seldon.serving.inference.request", \ "ce-id":"1234","ce-source":"localhost","ce-specversion":"1.0"} headers["Host"] = SERVICE_HOSTNAME_VAEOD res = requests.post('http://'+CLUSTER_IP+'/', json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ",res.status_code) return [] ###Output WARNING: Logging before flag parsing goes to stderr. E1110 11:58:05.548886 140347082585856 plot.py:39] Importing plotly failed. Interactive plots will not work. ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx:idx+1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output Outlier False ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask(X.reshape(1, 32, 32, 3), mask_size=(10,10), n_masks=1, channels=[0,1,2], mask_type='normal', noise_distr=(0,1), clip_rng=(0,1)) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[-1])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output Outlier True ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete ns cifar10 ###Output namespace "cifar10" deleted ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml !cat ../../../notebooks/resources/seldon-gateway.yaml ###Output _____no_output_____ ###Markdown Setup Resources ###Code !kubectl create namespace cifar10 %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10 !kubectl create -f broker.yaml %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10 spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10 spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 !kubectl apply -f event-display.yaml ###Output _____no_output_____ ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: tfserving-cifar10 namespace: cifar10 spec: protocol: tensorflow transport: rest predictors: - componentSpecs: - spec: containers: - args: - --port=8500 - --rest_api_port=8501 - --model_name=resnet32 - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32 image: tensorflow/serving name: resnet32 ports: - containerPort: 8501 name: http protocol: TCP graph: name: resnet32 type: MODEL endpoint: service_port: 8501 logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10/default name: model replicas: 1 !kubectl apply -f cifar10.yaml ###Output _____no_output_____ ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. Here we configure `seldonio/alibi-detect-server` to use rclone for downloading the artifact. If `RCLONE_ENABLED=true` environmental variable is set or any of the environmental variables contain `RCLONE_CONFIG` in their name then rclonewill be used to download the artifacts. If `RCLONE_ENABLED=false` or no `RCLONE_CONFIG` variables are present then kfserving storage.py logic will be used to download the artifacts. ###Code %%writefile cifar10od.yaml apiVersion: v1 kind: Secret metadata: name: seldon-rclone-secret namespace: cifar10 type: Opaque stringData: RCLONE_CONFIG_GS_TYPE: google cloud storage RCLONE_CONFIG_GS_ANONYMOUS: "true" --- apiVersion: serving.knative.dev/v1 kind: Service metadata: name: vae-outlier namespace: cifar10 spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.8.0-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --http_port - '8080' - --protocol - tensorflow.http - --storage_uri - gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10 - --reply_url - http://hello-display.cifar10 - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector envFrom: - secretRef: name: seldon-rclone-secret !kubectl apply -f cifar10od.yaml ###Output _____no_output_____ ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: vaeoutlier-trigger namespace: cifar10 spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: vae-outlier namespace: cifar10 !kubectl apply -f trigger.yaml ###Output _____no_output_____ ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS = !(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP = CLUSTER_IPS[0] print(CLUSTER_IP) ###Output _____no_output_____ ###Markdown Optionally add an authorization token here if you need one.Acquiring this token will be dependent on your auth setup. ###Code TOKEN = "Bearer <my token>" ###Output _____no_output_____ ###Markdown If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following ###Code # CLUSTER_IP="localhost:8004" SERVICE_HOSTNAMES = !(kubectl get ksvc -n cifar10 vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD = SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import json import matplotlib.pyplot as plt import numpy as np import tensorflow as tf tf.keras.backend.clear_session() import requests from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype("float32") / 255 X_test = X_test.astype("float32") / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ( "plane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck", ) def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis("off") plt.show() def predict(X): formData = {"instances": X.tolist()} headers = {"Authorization": TOKEN} res = requests.post( "http://" + CLUSTER_IP + "/seldon/cifar10/tfserving-cifar10/v1/models/resnet32/:predict", json=formData, headers=headers, ) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ", res.status_code) return [] def outlier(X): formData = {"instances": X.tolist()} headers = { "Alibi-Detect-Return-Feature-Score": "true", "Alibi-Detect-Return-Instance-Score": "true", "ce-namespace": "default", "ce-modelid": "cifar10", "ce-type": "io.seldon.serving.inference.request", "ce-id": "1234", "ce-source": "localhost", "ce-specversion": "1.0", } headers["Host"] = SERVICE_HOSTNAME_VAEOD headers["Authorization"] = TOKEN res = requests.post("http://" + CLUSTER_IP + "/", json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ", res.status_code) return [] ###Output _____no_output_____ ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx : idx + 1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res = !kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data = [] for i in range(0, len(res)): if res[i] == "Data,": data.append(res[i + 1]) j = json.loads(json.loads(data[0])) print("Outlier", j["data"]["is_outlier"] == [1]) ###Output _____no_output_____ ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask( X.reshape(1, 32, 32, 3), mask_size=(10, 10), n_masks=1, channels=[0, 1, 2], mask_type="normal", noise_distr=(0, 1), clip_rng=(0, 1), ) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res = !kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data = [] for i in range(0, len(res)): if res[i] == "Data,": data.append(res[i + 1]) j = json.loads(json.loads(data[-1])) print("Outlier", j["data"]["is_outlier"] == [1]) ###Output _____no_output_____ ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete ns cifar10 ###Output _____no_output_____ ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE with Knative 0.13 and Istio 1.3.1 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml ###Output _____no_output_____ ###Markdown Setup Resources Enabled eventing on default namespace. This will activate a default Knative Broker. ###Code !kubectl label namespace default knative-eventing-injection=enabled ###Output _____no_output_____ ###Markdown Create a Knative service to log events it receives. This will be the example final sink for outlier events. ###Code !pygmentize message-dumper.yaml !kubectl apply -f message-dumper.yaml ###Output _____no_output_____ ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code !pygmentize cifar10.yaml !kubectl apply -f cifar10.yaml ###Output _____no_output_____ ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. ###Code !pygmentize cifar10od.yaml !kubectl apply -f cifar10od.yaml ###Output _____no_output_____ ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code !pygmentize trigger.yaml !kubectl apply -f trigger.yaml ###Output _____no_output_____ ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) SERVICE_HOSTNAMES=!(kubectl get ksvc vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import matplotlib.pyplot as plt import numpy as np import json import tensorflow as tf tf.keras.backend.clear_session() from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image import requests train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() def predict(X): formData = { 'instances': X.tolist() } headers = {} res = requests.post('http://'+CLUSTER_IP+'/seldon/default/tfserving-cifar10/v1/models/resnet32/:predict', json=formData, headers=headers) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ",res.status_code) return [] def outlier(X): formData = { 'instances': X.tolist() } headers = {"Alibi-Detect-Return-Feature-Score":"true","Alibi-Detect-Return-Instance-Score":"true"} headers["Host"] = SERVICE_HOSTNAME_VAEOD res = requests.post('http://'+CLUSTER_IP+'/', json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ",res.status_code) return [] ###Output _____no_output_____ ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx:idx+1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res=!kubectl logs $(kubectl get pod -l serving.knative.dev/configuration=message-dumper -o jsonpath='{.items[0].metadata.name}') user-container data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask(X.reshape(1, 32, 32, 3), mask_size=(10,10), n_masks=1, channels=[0,1,2], mask_type='normal', noise_distr=(0,1), clip_rng=(0,1)) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res=!kubectl logs $(kubectl get pod -l serving.knative.dev/configuration=message-dumper -o jsonpath='{.items[0].metadata.name}') user-container data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[1])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete -f cifar10.yaml !kubectl delete -f cifar10od.yaml !kubectl delete -f trigger.yaml !kubectl delete -f message-dumper.yaml ###Output _____no_output_____ ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml !cat ../../../notebooks/resources/seldon-gateway.yaml ###Output _____no_output_____ ###Markdown Setup Resources ###Code !kubectl create namespace cifar10 %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10 !kubectl create -f broker.yaml %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10 spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10 spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 !kubectl apply -f event-display.yaml ###Output _____no_output_____ ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: tfserving-cifar10 namespace: cifar10 spec: protocol: tensorflow transport: rest predictors: - componentSpecs: - spec: containers: - args: - --port=8500 - --rest_api_port=8501 - --model_name=resnet32 - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32 image: tensorflow/serving name: resnet32 ports: - containerPort: 8501 name: http protocol: TCP graph: name: resnet32 type: MODEL endpoint: service_port: 8501 logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10/default name: model replicas: 1 !kubectl apply -f cifar10.yaml ###Output _____no_output_____ ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. Here we configure `seldonio/alibi-detect-server` to use rclone for downloading the artifact. If `RCLONE_ENABLED=true` environmental variable is set or any of the enviromental variables contain `RCLONE_CONFIG` in their name then rclonewill be used to download the artifacts. If `RCLONE_ENABLED=false` or no `RCLONE_CONFIG` variables are present then kfserving storage.py logic will be used to download the artifacts. ###Code %%writefile cifar10od.yaml apiVersion: v1 kind: Secret metadata: name: seldon-rclone-secret namespace: cifar10 type: Opaque stringData: RCLONE_CONFIG_GS_TYPE: google cloud storage RCLONE_CONFIG_GS_ANONYMOUS: "true" --- apiVersion: serving.knative.dev/v1 kind: Service metadata: name: vae-outlier namespace: cifar10 spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.8.0-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --http_port - '8080' - --protocol - tensorflow.http - --storage_uri - gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10 - --reply_url - http://hello-display.cifar10 - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector envFrom: - secretRef: name: seldon-rclone-secret !kubectl apply -f cifar10od.yaml ###Output _____no_output_____ ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: vaeoutlier-trigger namespace: cifar10 spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: vae-outlier namespace: cifar10 !kubectl apply -f trigger.yaml ###Output _____no_output_____ ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) ###Output _____no_output_____ ###Markdown Optionally add an authorization token here if you need one.Acquiring this token will be dependent on your auth setup. ###Code TOKEN = "Bearer <my token>" ###Output _____no_output_____ ###Markdown If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following ###Code # CLUSTER_IP="localhost:8004" SERVICE_HOSTNAMES=!(kubectl get ksvc -n cifar10 vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import json import matplotlib.pyplot as plt import numpy as np import tensorflow as tf tf.keras.backend.clear_session() import requests from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype("float32") / 255 X_test = X_test.astype("float32") / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ( "plane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck", ) def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis("off") plt.show() def predict(X): formData = {"instances": X.tolist()} headers = {"Authorization": TOKEN} res = requests.post( "http://" + CLUSTER_IP + "/seldon/cifar10/tfserving-cifar10/v1/models/resnet32/:predict", json=formData, headers=headers, ) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ", res.status_code) return [] def outlier(X): formData = {"instances": X.tolist()} headers = { "Alibi-Detect-Return-Feature-Score": "true", "Alibi-Detect-Return-Instance-Score": "true", "ce-namespace": "default", "ce-modelid": "cifar10", "ce-type": "io.seldon.serving.inference.request", "ce-id": "1234", "ce-source": "localhost", "ce-specversion": "1.0", } headers["Host"] = SERVICE_HOSTNAME_VAEOD headers["Authorization"] = TOKEN res = requests.post("http://" + CLUSTER_IP + "/", json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ", res.status_code) return [] ###Output _____no_output_____ ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx : idx + 1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask( X.reshape(1, 32, 32, 3), mask_size=(10, 10), n_masks=1, channels=[0, 1, 2], mask_type="normal", noise_distr=(0, 1), clip_rng=(0, 1), ) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[-1])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete ns cifar10 ###Output _____no_output_____ ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE with Knative 0.13 and Istio 1.3.1 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml ###Output _____no_output_____ ###Markdown Setup Resources Enabled eventing on default namespace. This will activate a default Knative Broker. ###Code !kubectl label namespace default knative-eventing-injection=enabled ###Output _____no_output_____ ###Markdown Create a Knative service to log events it receives. This will be the example final sink for outlier events. ###Code !pygmentize message-dumper.yaml !kubectl apply -f message-dumper.yaml ###Output _____no_output_____ ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code !pygmentize cifar10.yaml !kubectl apply -f cifar10.yaml ###Output _____no_output_____ ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. ###Code !pygmentize cifar10od.yaml !kubectl apply -f cifar10od.yaml ###Output _____no_output_____ ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code !pygmentize trigger.yaml !kubectl apply -f trigger.yaml ###Output _____no_output_____ ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) SERVICE_HOSTNAMES=!(kubectl get ksvc vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import matplotlib.pyplot as plt import numpy as np import json import tensorflow as tf tf.keras.backend.clear_session() from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image import requests train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() def predict(X): formData = { 'instances': X.tolist() } headers = {} res = requests.post('http://'+CLUSTER_IP+'/seldon/default/tfserving-cifar10/v1/models/resnet32/:predict', json=formData, headers=headers) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ",res.status_code) return [] def outlier(X): formData = { 'instances': X.tolist() } headers = {"Alibi-Detect-Return-Feature-Score":"true","Alibi-Detect-Return-Instance-Score":"true"} headers["Host"] = SERVICE_HOSTNAME_VAEOD res = requests.post('http://'+CLUSTER_IP+'/', json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ",res.status_code) return [] ###Output _____no_output_____ ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx:idx+1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res=!kubectl logs $(kubectl get pod -l serving.knative.dev/configuration=message-dumper -o jsonpath='{.items[0].metadata.name}') user-container data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask(X.reshape(1, 32, 32, 3), mask_size=(10,10), n_masks=1, channels=[0,1,2], mask_type='normal', noise_distr=(0,1), clip_rng=(0,1)) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res=!kubectl logs $(kubectl get pod -l serving.knative.dev/configuration=message-dumper -o jsonpath='{.items[0].metadata.name}') user-container data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[1])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete -f cifar10.yaml !kubectl delete -f cifar10od.yaml !kubectl delete -f trigger.yaml !kubectl delete -f message-dumper.yaml ###Output _____no_output_____ ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml !cat ../../../notebooks/resources/seldon-gateway.yaml ###Output _____no_output_____ ###Markdown Setup Resources ###Code !kubectl create namespace cifar10 %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10 !kubectl create -f broker.yaml %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10 spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10 spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 !kubectl apply -f event-display.yaml ###Output _____no_output_____ ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: tfserving-cifar10 namespace: cifar10 spec: protocol: tensorflow transport: rest predictors: - componentSpecs: - spec: containers: - args: - --port=8500 - --rest_api_port=8501 - --model_name=resnet32 - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32 image: tensorflow/serving name: resnet32 ports: - containerPort: 8501 name: http protocol: TCP graph: name: resnet32 type: MODEL endpoint: service_port: 8501 logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10/default name: model replicas: 1 !kubectl apply -f cifar10.yaml ###Output _____no_output_____ ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. Here we configure `seldonio/alibi-detect-server` to use rclone for downloading the artifact. If `RCLONE_ENABLED=true` environmental variable is set or any of the environmental variables contain `RCLONE_CONFIG` in their name then rclonewill be used to download the artifacts. If `RCLONE_ENABLED=false` or no `RCLONE_CONFIG` variables are present then kfserving storage.py logic will be used to download the artifacts. ###Code %%writefile cifar10od.yaml apiVersion: v1 kind: Secret metadata: name: seldon-rclone-secret namespace: cifar10 type: Opaque stringData: RCLONE_CONFIG_GS_TYPE: google cloud storage RCLONE_CONFIG_GS_ANONYMOUS: "true" --- apiVersion: serving.knative.dev/v1 kind: Service metadata: name: vae-outlier namespace: cifar10 spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.8.0-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --http_port - '8080' - --protocol - tensorflow.http - --storage_uri - gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10 - --reply_url - http://hello-display.cifar10 - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector envFrom: - secretRef: name: seldon-rclone-secret !kubectl apply -f cifar10od.yaml ###Output _____no_output_____ ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: vaeoutlier-trigger namespace: cifar10 spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: vae-outlier namespace: cifar10 !kubectl apply -f trigger.yaml ###Output _____no_output_____ ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS = !(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP = CLUSTER_IPS[0] print(CLUSTER_IP) ###Output _____no_output_____ ###Markdown Optionally add an authorization token here if you need one.Acquiring this token will be dependent on your auth setup. ###Code TOKEN = "Bearer <my token>" ###Output _____no_output_____ ###Markdown If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following ###Code # CLUSTER_IP="localhost:8004" SERVICE_HOSTNAMES = !(kubectl get ksvc -n cifar10 vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD = SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import json import matplotlib.pyplot as plt import numpy as np import tensorflow as tf tf.keras.backend.clear_session() import requests from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype("float32") / 255 X_test = X_test.astype("float32") / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ( "plane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck", ) def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis("off") plt.show() def predict(X): formData = {"instances": X.tolist()} headers = {"Authorization": TOKEN} res = requests.post( "http://" + CLUSTER_IP + "/seldon/cifar10/tfserving-cifar10/v1/models/resnet32/:predict", json=formData, headers=headers, ) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ", res.status_code) return [] def outlier(X): formData = {"instances": X.tolist()} headers = { "Alibi-Detect-Return-Feature-Score": "true", "Alibi-Detect-Return-Instance-Score": "true", "ce-namespace": "default", "ce-modelid": "cifar10", "ce-type": "io.seldon.serving.inference.request", "ce-id": "1234", "ce-source": "localhost", "ce-specversion": "1.0", } headers["Host"] = SERVICE_HOSTNAME_VAEOD headers["Authorization"] = TOKEN res = requests.post("http://" + CLUSTER_IP + "/", json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ", res.status_code) return [] ###Output _____no_output_____ ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx : idx + 1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code !kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') ###Output _____no_output_____ ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask( X.reshape(1, 32, 32, 3), mask_size=(10, 10), n_masks=1, channels=[0, 1, 2], mask_type="normal", noise_distr=(0, 1), clip_rng=(0, 1), ) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code !kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') ###Output _____no_output_____ ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete ns cifar10 ###Output _____no_output_____ ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml ###Output gateway.networking.istio.io/seldon-gateway unchanged ###Markdown Setup Resources ###Code !kubectl create namespace cifar10 %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10 !kubectl create -f broker.yaml %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10 spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10 spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 !kubectl apply -f event-display.yaml ###Output deployment.apps/hello-display created service/hello-display created ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: tfserving-cifar10 namespace: cifar10 spec: protocol: tensorflow transport: rest predictors: - componentSpecs: - spec: containers: - args: - --port=8500 - --rest_api_port=8501 - --model_name=resnet32 - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32 image: tensorflow/serving name: resnet32 ports: - containerPort: 8501 name: http protocol: TCP graph: name: resnet32 type: MODEL endpoint: service_port: 8501 logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10/default name: model replicas: 1 !kubectl apply -f cifar10.yaml ###Output seldondeployment.machinelearning.seldon.io/tfserving-cifar10 created ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. ###Code %%writefile cifar10od.yaml apiVersion: serving.knative.dev/v1 kind: Service metadata: name: vae-outlier namespace: cifar10 spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.5.0 imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --http_port - '8080' - --protocol - tensorflow.http - --storage_uri - gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10 - --reply_url - http://hello-display.cifar10 - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector !kubectl apply -f cifar10od.yaml ###Output service.serving.knative.dev/vae-outlier created ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: vaeoutlier-trigger namespace: cifar10 spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: vae-outlier namespace: cifar10 !kubectl apply -f trigger.yaml ###Output trigger.eventing.knative.dev/vaeoutlier-trigger created ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) ###Output 34.77.158.93 ###Markdown Optionally add an authorization token here if you need one.Acquiring this token will be dependent on your auth setup. ###Code TOKEN="Bearer <my token>" ###Output _____no_output_____ ###Markdown If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following ###Code #CLUSTER_IP="localhost:8004" SERVICE_HOSTNAMES=!(kubectl get ksvc -n cifar10 vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import matplotlib.pyplot as plt import numpy as np import json import tensorflow as tf tf.keras.backend.clear_session() from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image import requests train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() def predict(X): formData = { 'instances': X.tolist() } headers = {"Authorization":TOKEN} res = requests.post('http://'+CLUSTER_IP+'/seldon/cifar10/tfserving-cifar10/v1/models/resnet32/:predict', json=formData, headers=headers) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ",res.status_code) return [] def outlier(X): formData = { 'instances': X.tolist() } headers = {"Alibi-Detect-Return-Feature-Score":"true","Alibi-Detect-Return-Instance-Score":"true", \ "ce-namespace": "default","ce-modelid":"cifar10","ce-type":"io.seldon.serving.inference.request", \ "ce-id":"1234","ce-source":"localhost","ce-specversion":"1.0"} headers["Host"] = SERVICE_HOSTNAME_VAEOD headers["Authorization"] = TOKEN res = requests.post('http://'+CLUSTER_IP+'/', json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ",res.status_code) return [] ###Output (50000, 32, 32, 3) (50000, 1) (10000, 32, 32, 3) (10000, 1) ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx:idx+1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output Outlier False ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask(X.reshape(1, 32, 32, 3), mask_size=(10,10), n_masks=1, channels=[0,1,2], mask_type='normal', noise_distr=(0,1), clip_rng=(0,1)) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[-1])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output Outlier True ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete ns cifar10 ###Output namespace "cifar10" deleted ###Markdown Cifar10 Outlier Detection![demo](./demo.png)In this example we will deploy an image classification model along with an outlier detector trained on the same dataset. For in depth details on creating an outlier detection model for your own dataset see the [alibi-detect project](https://github.com/SeldonIO/alibi-detect) and associated [documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/). You can find details for this [CIFAR10 example in their documentation](https://docs.seldon.io/projects/alibi-detect/en/latest/examples/od_vae_cifar10.html) as well.Prequisites: * [Knative eventing installed](https://knative.dev/docs/install/) * Ensure the istio-ingressgateway is exposed as a loadbalancer (no auth in this demo) * [Seldon Core installed](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) * Ensure you install for istio, e.g. for the helm chart `--set istio.enabled=true` Tested on GKE and Kind with Knative 0.18 and Istio 1.7.3 ###Code !pip install -r requirements_notebook.txt ###Output _____no_output_____ ###Markdown Ensure istio gateway installed ###Code !kubectl apply -f ../../../notebooks/resources/seldon-gateway.yaml !cat ../../../notebooks/resources/seldon-gateway.yaml ###Output _____no_output_____ ###Markdown Setup Resources ###Code !kubectl create namespace cifar10 %%writefile broker.yaml apiVersion: eventing.knative.dev/v1 kind: broker metadata: name: default namespace: cifar10 !kubectl create -f broker.yaml %%writefile event-display.yaml apiVersion: apps/v1 kind: Deployment metadata: name: hello-display namespace: cifar10 spec: replicas: 1 selector: matchLabels: &labels app: hello-display template: metadata: labels: *labels spec: containers: - name: event-display image: gcr.io/knative-releases/knative.dev/eventing-contrib/cmd/event_display --- kind: Service apiVersion: v1 metadata: name: hello-display namespace: cifar10 spec: selector: app: hello-display ports: - protocol: TCP port: 80 targetPort: 8080 !kubectl apply -f event-display.yaml ###Output _____no_output_____ ###Markdown Create the SeldonDeployment image classification model for Cifar10. We add in a `logger` for requests - the default destination is the namespace Knative Broker. ###Code %%writefile cifar10.yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: tfserving-cifar10 namespace: cifar10 spec: protocol: tensorflow transport: rest predictors: - componentSpecs: - spec: containers: - args: - --port=8500 - --rest_api_port=8501 - --model_name=resnet32 - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32 image: tensorflow/serving name: resnet32 ports: - containerPort: 8501 name: http protocol: TCP graph: name: resnet32 type: MODEL endpoint: service_port: 8501 logger: mode: all url: http://broker-ingress.knative-eventing.svc.cluster.local/cifar10/default name: model replicas: 1 !kubectl apply -f cifar10.yaml ###Output _____no_output_____ ###Markdown Create the pretrained VAE Cifar10 Outlier Detector. We forward replies to the message-dumper we started. Here we configure `seldonio/alibi-detect-server` to use rclone for downloading the artifact. If `RCLONE_ENABLED=true` environmental variable is set or any of the enviromental variables contain `RCLONE_CONFIG` in their name then rclonewill be used to download the artifacts. If `RCLONE_ENABLED=false` or no `RCLONE_CONFIG` variables are present then kfserving storage.py logic will be used to download the artifacts. ###Code %%writefile cifar10od.yaml apiVersion: v1 kind: Secret metadata: name: seldon-rclone-secret namespace: cifar10 type: Opaque stringData: RCLONE_CONFIG_GS_TYPE: google cloud storage RCLONE_CONFIG_GS_ANONYMOUS: "true" --- apiVersion: serving.knative.dev/v1 kind: Service metadata: name: vae-outlier namespace: cifar10 spec: template: metadata: annotations: autoscaling.knative.dev/minScale: "1" spec: containers: - image: seldonio/alibi-detect-server:1.8.0-dev imagePullPolicy: IfNotPresent args: - --model_name - cifar10od - --http_port - '8080' - --protocol - tensorflow.http - --storage_uri - gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10 - --reply_url - http://hello-display.cifar10 - --event_type - io.seldon.serving.inference.outlier - --event_source - io.seldon.serving.cifar10od - OutlierDetector envFrom: - secretRef: name: seldon-rclone-secret !kubectl apply -f cifar10od.yaml ###Output _____no_output_____ ###Markdown Create a Knative trigger to forward logging events to our Outlier Detector. ###Code %%writefile trigger.yaml apiVersion: eventing.knative.dev/v1 kind: Trigger metadata: name: vaeoutlier-trigger namespace: cifar10 spec: broker: default filter: attributes: type: io.seldon.serving.inference.request subscriber: ref: apiVersion: serving.knative.dev/v1 kind: Service name: vae-outlier namespace: cifar10 !kubectl apply -f trigger.yaml ###Output _____no_output_____ ###Markdown Get the IP address of the Istio Ingress Gateway. This assumes you have installed istio with a LoadBalancer. ###Code CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) ###Output _____no_output_____ ###Markdown Optionally add an authorization token here if you need one.Acquiring this token will be dependent on your auth setup. ###Code TOKEN="Bearer <my token>" ###Output _____no_output_____ ###Markdown If you are using Kind or Minikube you will need to port-forward to the istio ingressgateway and uncomment the following ###Code #CLUSTER_IP="localhost:8004" SERVICE_HOSTNAMES=!(kubectl get ksvc -n cifar10 vae-outlier -o jsonpath='{.status.url}' | cut -d "/" -f 3) SERVICE_HOSTNAME_VAEOD=SERVICE_HOSTNAMES[0] print(SERVICE_HOSTNAME_VAEOD) import matplotlib.pyplot as plt import numpy as np import json import tensorflow as tf tf.keras.backend.clear_session() from alibi_detect.od.vae import OutlierVAE from alibi_detect.utils.perturbation import apply_mask from alibi_detect.utils.visualize import plot_feature_outlier_image import requests train, test = tf.keras.datasets.cifar10.load_data() X_train, y_train = train X_test, y_test = test X_train = X_train.astype('float32') / 255 X_test = X_test.astype('float32') / 255 print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') def show(X): plt.imshow(X.reshape(32, 32, 3)) plt.axis('off') plt.show() def predict(X): formData = { 'instances': X.tolist() } headers = {"Authorization":TOKEN} res = requests.post('http://'+CLUSTER_IP+'/seldon/cifar10/tfserving-cifar10/v1/models/resnet32/:predict', json=formData, headers=headers) if res.status_code == 200: return classes[np.array(res.json()["predictions"])[0].argmax()] else: print("Failed with ",res.status_code) return [] def outlier(X): formData = { 'instances': X.tolist() } headers = {"Alibi-Detect-Return-Feature-Score":"true","Alibi-Detect-Return-Instance-Score":"true", \ "ce-namespace": "default","ce-modelid":"cifar10","ce-type":"io.seldon.serving.inference.request", \ "ce-id":"1234","ce-source":"localhost","ce-specversion":"1.0"} headers["Host"] = SERVICE_HOSTNAME_VAEOD headers["Authorization"] = TOKEN res = requests.post('http://'+CLUSTER_IP+'/', json=formData, headers=headers) if res.status_code == 200: od = res.json() od["data"]["feature_score"] = np.array(od["data"]["feature_score"]) od["data"]["instance_score"] = np.array(od["data"]["instance_score"]) return od else: print("Failed with ",res.status_code) return [] ###Output _____no_output_____ ###Markdown Normal Prediction ###Code idx = 1 X = X_train[idx:idx+1] show(X) predict(X) ###Output _____no_output_____ ###Markdown Lets check the message dumper for an outlier detection prediction. This should be false. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[0])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown Outlier Prediction ###Code np.random.seed(0) X_mask, mask = apply_mask(X.reshape(1, 32, 32, 3), mask_size=(10,10), n_masks=1, channels=[0,1,2], mask_type='normal', noise_distr=(0,1), clip_rng=(0,1)) show(X_mask) predict(X_mask) ###Output _____no_output_____ ###Markdown Now lets check the message dumper for a new message. This should show we have found an outlier. ###Code res=!kubectl logs -n cifar10 $(kubectl get pod -n cifar10 -l app=hello-display -o jsonpath='{.items[0].metadata.name}') data= [] for i in range(0,len(res)): if res[i] == 'Data,': data.append(res[i+1]) j = json.loads(json.loads(data[-1])) print("Outlier",j["data"]["is_outlier"]==[1]) ###Output _____no_output_____ ###Markdown We will now call our outlier detector directly and ask for the feature scores to gain more information about why it predicted this instance was an outlier. ###Code od_preds = outlier(X_mask) ###Output _____no_output_____ ###Markdown We now plot those feature scores returned by the outlier detector along with our original image. ###Code plot_feature_outlier_image(od_preds, X_mask, X_recon=None) ###Output _____no_output_____ ###Markdown Tear Down ###Code !kubectl delete ns cifar10 ###Output _____no_output_____
examples/count/sweep-gregor-i5-12.ipynb
###Markdown When benchmarking you **MUST**1. close all applications2. close docker3. close all but this Web windows4. all pen editors other than jupyter-lab (this notebook) ###Code import os from cloudmesh.common.Shell import Shell from pprint import pprint import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import pandas as pd from tqdm.notebook import tqdm from cloudmesh.common.util import readfile from cloudmesh.common.util import writefile from cloudmesh.common.StopWatch import StopWatch from cloudmesh.common.systeminfo import systeminfo import ipywidgets as widgets sns.set_theme(style="whitegrid") info = systeminfo() user = info["user"] node = info["uname.node"] processors = 4 # Parameters user = "gregor" node = "i5" processors = 12 p = widgets.IntSlider( value=processors, min=2, max=64, step=1, description='Processors:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d' ) u = widgets.Text(value=user, placeholder='The user name', description='User:', disabled=False) n = widgets.Text(value=node, placeholder='The computer name', description='Computer:', disabled=False) display(p) display(u) display(n) processors = p.value user = u.value node = n.value print (processors, user, node) experiments = 10 maximum = 1024 * 100000 intervals = 10 label = f"{user}-{node}-{processors}" output = f"benchmark/{user}" delta = int(maximum / intervals) totals = [64] + list(range(0,maximum, delta))[1:] points = [int(t/processors) for t in totals] print (totals) print(points) os.makedirs(output, exist_ok=True) systeminfo = StopWatch.systeminfo({"user": user, "uname.node": node}) writefile(f"{output}/{label}-sysinfo.log", systeminfo) print (systeminfo) df = pd.DataFrame( {"Size": points} ) df = df.set_index('Size') experiment_progress = tqdm(range(0, experiments), desc ="Experiment") experiment = -1 for experiment in experiment_progress: exoeriment = experiment + 1 log = f"{output}/{label}-{experiment}-log.log" os.system(f"rm {log}") name = points[experiment] progress = tqdm(range(0, len(points)), desc =f"Benchmark {name}", bar_format="{desc:<30} {total_fmt} {r_bar}") i = -1 for state in progress: i = i + 1 n = points[i] #if linux, os: command = f"mpiexec -n {processors} python count-click.py " + \ f"--n {n} --max_number 10 --find 8 --label {label} " + \ f"--user {user} --node={node} " + \ f"| tee -a {log}" #if windows: #command = f"mpiexec -n {processors} python count-click.py " + \ # f"--n {n} --max_number 10 --find 8 --label {label} " + \ # f"--user {user} --node={node} " + \ # f">> {log}" os.system (command) content = readfile(log).splitlines() lines = Shell.cm_grep(content, "csv,Result:") # print(lines) values = [] times = [] for line in lines: msg = line.split(",")[7] t = line.split(",")[4] total, overall, trials, find, label = msg.split(" ") values.append(int(overall)) times.append(float(t)) # print (t, overall) #data = pd.DataFrame(values, times, columns=["Values", "Time"]) #print (data.describe()) #sns.lineplot(data=data, palette="tab10", linewidth=2.5) # df["Size"] = values df[f"Time_{experiment}"] = times # print(df) df = df.rename_axis(columns="Time") df sns.lineplot(data=df, markers=True); plt.savefig(f'{output}/{label}-line.png'); plt.savefig(f'{output}/{label}-line.pdf'); dfs = df.stack().reset_index() dfs = dfs.set_index('Size') dfs = dfs.drop(columns=['Time']) dfs = dfs.rename(columns={0:'Time'}) dfs sns.scatterplot(data=dfs, x="Size", y="Time"); plt.savefig(f"{output}/{label}-scatter.pdf") plt.savefig(f"{output}/{label}-scatter.png") sns.relplot(x="Size", y="Time", kind="line", data=dfs); plt.savefig(f"{output}/{label}-relplot.pdf") plt.savefig(f"{output}/{label}-relplot.png") df.to_pickle(f"{output}/{label}-df.pkl") ###Output _____no_output_____
docs/tutorial/03-model-serving.ipynb
###Markdown Part 3: Serving an ML ModelThis part of the MLRun getting-started tutorial walks you through the steps for creating, deploying, and testinga model-serving function ("a serving function" a.k.a. "a model server") using MLRun Serving and Nuclio runtimes.MLRun serving can take various tasks including MLRun models or standard model files and produce managed real-timeserverless pipelines based on the Nuclio real-time serverless engine, which can be deployed everywhere.[Nuclio](https://nuclio.io/) is a high-performance open-source "serverless" framework that's focused on data, I/O, and compute-intensive workloads.Simple model serving classes can be written in Python or be taken from a set of pre-developed ML/DL classes.The code can handle complex data, feature preparation, and binary data (such as images and video files).The Nuclio serving engine supports the full model-serving life cycle, including auto generation of microservices,APIs, load balancing, model logging and monitoring, and configuration management.MLRun Serving support more advanced real-time data processing and model serving pipelines,for more details and examples see the [MLRun Serving Graphs](../serving/serving-graph.md) documentation.The tutorial consists of the following steps:1. [Setup and Configuration](gs-tutorial-3-step-setup) &mdash; load your project2. [Writing A Simple Serving Class](gs-tutorial-3-step-writing-a-serving-class)3. [Deploying the Model-Serving Function (Service)](gs-tutorial-3-step-deploy-the-serving-function)4. [Using the Model-Serving Function](gs-tutorial-3-step-using-the-live-serving-function)5. [Viewing the Nuclio Serving Function on the Dashboard](gs-tutorial-3-step-view-serving-func-in-ui)By the end of this tutorial you'll learn how to- Create model serving functions.- Deploy models at scale.- Test your deployed models. PrerequisitesThe following steps are a continuation of the previous parts of this getting-started tutorial and rely on the generated outputs.Therefore, make sure to first run parts 1&mdash;[2](02-model-training.ipynb) of the tutorial. Step 1: Setup and Configuration Importing LibrariesRun the following code to import required libraries: ###Code from os import path import mlrun ###Output _____no_output_____ ###Markdown Initializing Your MLRun EnvironmentUse the `set_environment` MLRun method to configure the working environment and default configuration.Set the `project` and `user_project` parameters to the same values that you used in the call to this method in the [Part 1: MLRun Basics](./01-mlrun-basics.ipynbgs-tutorial-1-set-mlrun-envr) tutorial notebook. ###Code # Set the base project name project_name_base = 'getting-started-tutorial' # Initialize the MLRun environment and save the project name and artifacts path project_name, artifact_path = mlrun.set_environment(project=project_name_base, user_project=True) ###Output _____no_output_____ ###Markdown Step 2: Writing A Simple Serving ClassThe serving class is initialized automatically by the model server.All you need is to implement two mandatory methods:- `load` &mdash; downloads the model files and loads the model into memory. This can be done either synchronously or asynchronously.- `predict` &mdash; accepts a request payload and returns prediction (inference) results.For more detailed information on serving classes, see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.md).The following code demonstrates a minimal scikit-learn (a.k.a. sklearn) serving-class implementation: ###Code # nuclio: start-code from cloudpickle import load import numpy as np from typing import List import mlrun class ClassifierModel(mlrun.serving.V2ModelServer): def load(self): """load and initialize the model and/or other elements""" model_file, extra_data = self.get_model('.pkl') self.model = load(open(model_file, 'rb')) def predict(self, body: dict) -> List: """Generate model predictions from sample.""" feats = np.asarray(body['inputs']) result: np.ndarray = self.model.predict(feats) return result.tolist() # nuclio: end-code ###Output _____no_output_____ ###Markdown Step 3: Deploying the Model-Serving Function (Service)To provision (deploy) a function for serving the model ("a serving function") you need to create an MLRun function of type `serving`.You can do this by using the `code_to_function` MLRun method from a web notebook, or by importing an existing serving function or template from the MLRun functions marketplace. Converting a Serving Class to a Serving FunctionThe following code converts the `ClassifierModel` class that you defined in the previous step to a serving function.The name of the class to be used by the serving function is set in `spec.default_class`. ###Code from mlrun import code_to_function serving_fn = code_to_function('serving', kind='serving',image='mlrun/mlrun') serving_fn.spec.default_class = 'ClassifierModel' ###Output _____no_output_____ ###Markdown Add the model created in previous notebook by the training function ###Code model_file = f'store://{project_name}/train-iris-train_iris_model' serving_fn.add_model('my_model',model_path=model_file) from mlrun.platforms import auto_mount serving_fn = serving_fn.apply(auto_mount()) ###Output _____no_output_____ ###Markdown Test Our Function LocallyCreate a test server (mock server) and test it with sample data ###Code my_data = '''{"inputs":[[5.1, 3.5, 1.4, 0.2],[7.7, 3.8, 6.7, 2.2]]}''' server = serving_fn.to_mock_server() server.test("/v2/models/my_model/infer", body=my_data) ###Output _____no_output_____ ###Markdown Building and Deploying the Serving FunctionUse the `deploy` method of the MLRun serving function to build and deploy a Nuclio serving function from your serving-function code. ###Code function_address = serving_fn.deploy() ###Output > 2021-01-25 08:40:23,461 [info] Starting remote function deploy 2021-01-25 08:40:23 (info) Deploying function 2021-01-25 08:40:23 (info) Building 2021-01-25 08:40:23 (info) Staging files and preparing base images 2021-01-25 08:40:23 (info) Building processor image 2021-01-25 08:40:24 (info) Build complete 2021-01-25 08:40:30 (info) Function deploy complete > 2021-01-25 08:40:31,117 [info] function deployed, address=default-tenant.app.aefccdjffbit.iguazio-cd0.com:31805 ###Markdown Step 4: Using the Live Model-Serving FunctionAfter the function is deployed successfully, the serving function has a new HTTP endpoint for handling serving requests.The example tutorial serving function receives HTTP prediction (inference) requests on this endpoint;calls the `infer` method to get the requested predictions; and returns the results on the same endpoint. ###Code print (f'The address for the function is {function_address} \n') !curl $function_address ###Output The address for the function is default-tenant.app.aefccdjffbit.iguazio-cd0.com:31805 {"name": "ModelRouter", "version": "v2", "extensions": []} ###Markdown Testing the Model ServerTest your model server by sending data for inference.The `invoke` serving-function method enables programmatic testing of the serving function.For model inference (predictions), specify the model name followed by `infer`:```/v2/models/{model_name}/infer```For complete model-service API commands &mdash; such as for list models (`models`), get model health (`ready`), and model explanation (`explain`) &mdash; see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.mdmodel-server-api). ###Code serving_fn.invoke('/v2/models/my_model/infer', my_data) ###Output _____no_output_____ ###Markdown Part 3: Serving an ML ModelThis part of the MLRun getting-started tutorial walks you through the steps for implementing ML model serving using MLRun serving and Nuclio runtimes.The tutorial walks you through the steps for creating, deploying, and testing a model-serving function ("a serving function" a.k.a. "a model server").MLRun serving can produce managed real-time serverless pipelines from various tasks, including MLRun models or standard model files.The pipelines use the Nuclio real-time serverless engine, which can be deployed anywhere.[Nuclio](https://nuclio.io/) is a high-performance open-source "serverless" framework that's focused on data, I/O, and compute-intensive workloads.Simple model serving classes can be written in Python or be taken from a set of pre-developed ML/DL classes.The code can handle complex data, feature preparation, and binary data (such as images and video files).The Nuclio serving engine supports the full model-serving life cycle;this includes auto generation of microservices, APIs, load balancing, model logging and monitoring, and configuration management.MLRun serving supports more advanced real-time data processing and model serving pipelines.For more details and examples, see the [MLRun Serving Graphs](../serving/serving-graph.md) documentation.The tutorial consists of the following steps:1. [Setup and Configuration](gs-tutorial-3-step-setup) &mdash; load your project2. [Writing A Simple Serving Class](gs-tutorial-3-step-writing-a-serving-class)3. [Deploying the Model-Serving Function (Service)](gs-tutorial-3-step-deploy-the-serving-function)4. [Using the Live Model-Serving Function](gs-tutorial-3-step-using-the-live-serving-function)5. [Viewing the Nuclio Serving Function on the Dashboard](gs-tutorial-3-step-view-serving-func-in-ui)By the end of this tutorial you'll learn how to- Create model-serving functions.- Deploy models at scale.- Test your deployed models. PrerequisitesThe following steps are a continuation of the previous parts of this getting-started tutorial and rely on the generated outputs.Therefore, make sure to first run parts 1&mdash;[2](02-model-training.ipynb) of the tutorial. Step 1: Setup and Configuration Importing LibrariesRun the following code to import required libraries: ###Code from os import path import mlrun ###Output _____no_output_____ ###Markdown Initializing Your MLRun EnvironmentUse the `set_environment` MLRun method to configure the working environment and default configuration.Set the `project` and `user_project` parameters to the same values that you used in the call to this method in the [Part 1: MLRun Basics](./01-mlrun-basics.ipynbgs-tutorial-1-set-mlrun-envr) tutorial notebook. ###Code # Set the base project name project_name_base = 'getting-started-tutorial' # Initialize the MLRun environment and save the project name and artifacts path project_name, artifact_path = mlrun.set_environment(project=project_name_base, user_project=True) ###Output _____no_output_____ ###Markdown Step 2: Writing A Simple Serving ClassThe serving class is initialized automatically by the model server.All you need is to implement two mandatory methods:- `load` &mdash; downloads the model files and loads the model into memory. This can be done either synchronously or asynchronously.- `predict` &mdash; accepts a request payload and returns prediction (inference) results.For more detailed information on serving classes, see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.md).The following code demonstrates a minimal scikit-learn (a.k.a. sklearn) serving-class implementation: ###Code # nuclio: start-code from cloudpickle import load import numpy as np from typing import List import mlrun class ClassifierModel(mlrun.serving.V2ModelServer): def load(self): """load and initialize the model and/or other elements""" model_file, extra_data = self.get_model('.pkl') self.model = load(open(model_file, 'rb')) def predict(self, body: dict) -> List: """Generate model predictions from sample.""" feats = np.asarray(body['inputs']) result: np.ndarray = self.model.predict(feats) return result.tolist() # nuclio: end-code ###Output _____no_output_____ ###Markdown Step 3: Deploying the Model-Serving Function (Service)To provision (deploy) a function for serving the model ("a serving function") you need to create an MLRun function of type `serving`.You can do this by using the `code_to_function` MLRun method from a web notebook, or by importing an existing serving function or template from the MLRun functions marketplace. Converting a Serving Class to a Serving FunctionThe following code converts the `ClassifierModel` class that you defined in the previous step to a serving function.The name of the class to be used by the serving function is set in `spec.default_class`. ###Code from mlrun import code_to_function serving_fn = code_to_function('serving', kind='serving',image='mlrun/mlrun') serving_fn.spec.default_class = 'ClassifierModel' ###Output _____no_output_____ ###Markdown Add the model created in previous notebook by the training function ###Code model_file = f'store://{project_name}/train-iris-train_iris_model' serving_fn.add_model('my_model',model_path=model_file) from mlrun.platforms import auto_mount serving_fn = serving_fn.apply(auto_mount()) ###Output _____no_output_____ ###Markdown Testing Your Function LocallyTo test your function locally, create a test server (mock server) and test it with sample data. ###Code my_data = '''{"inputs":[[5.1, 3.5, 1.4, 0.2],[7.7, 3.8, 6.7, 2.2]]}''' server = serving_fn.to_mock_server() server.test("/v2/models/my_model/infer", body=my_data) ###Output _____no_output_____ ###Markdown Building and Deploying the Serving FunctionUse the `deploy` method of the MLRun serving function to build and deploy a Nuclio serving function from your serving-function code. ###Code function_address = serving_fn.deploy() ###Output > 2021-01-25 08:40:23,461 [info] Starting remote function deploy 2021-01-25 08:40:23 (info) Deploying function 2021-01-25 08:40:23 (info) Building 2021-01-25 08:40:23 (info) Staging files and preparing base images 2021-01-25 08:40:23 (info) Building processor image 2021-01-25 08:40:24 (info) Build complete 2021-01-25 08:40:30 (info) Function deploy complete > 2021-01-25 08:40:31,117 [info] function deployed, address=default-tenant.app.aefccdjffbit.iguazio-cd0.com:31805 ###Markdown Step 4: Using the Live Model-Serving FunctionAfter the function is deployed successfully, the serving function has a new HTTP endpoint for handling serving requests.The example tutorial serving function receives HTTP prediction (inference) requests on this endpoint;calls the `infer` method to get the requested predictions; and returns the results on the same endpoint. ###Code print (f'The address for the function is {function_address} \n') !curl $function_address ###Output The address for the function is default-tenant.app.aefccdjffbit.iguazio-cd0.com:31805 {"name": "ModelRouter", "version": "v2", "extensions": []} ###Markdown Testing the Model ServerTest your model server by sending data for inference.The `invoke` serving-function method enables programmatic testing of the serving function.For model inference (predictions), specify the model name followed by `infer`:```/v2/models/{model_name}/infer```For complete model-service API commands &mdash; such as for list models (`models`), get model health (`ready`), and model explanation (`explain`) &mdash; see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.mdmodel-server-api). ###Code serving_fn.invoke('/v2/models/my_model/infer', my_data) ###Output _____no_output_____ ###Markdown Part 3: Serving an ML ModelThis part of the MLRun getting-started tutorial walks you through the steps for implementing ML model serving using MLRun serving and Nuclio runtimes.The tutorial walks you through the steps for creating, deploying, and testing a model-serving function ("a serving function" a.k.a. "a model server").MLRun serving can produce managed real-time serverless pipelines from various tasks, including MLRun models or standard model files.The pipelines use the Nuclio real-time serverless engine, which can be deployed anywhere.[Nuclio](https://nuclio.io/) is a high-performance open-source "serverless" framework that's focused on data, I/O, and compute-intensive workloads.Simple model serving classes can be written in Python or be taken from a set of pre-developed ML/DL classes.The code can handle complex data, feature preparation, and binary data (such as images and video files).The Nuclio serving engine supports the full model-serving life cycle;this includes auto generation of microservices, APIs, load balancing, model logging and monitoring, and configuration management.MLRun serving supports more advanced real-time data processing and model serving pipelines.For more details and examples, see the [MLRun Serving Graphs](../serving/serving-graph.md) documentation.The tutorial consists of the following steps:1. [Setup and Configuration](gs-tutorial-3-step-setup) &mdash; load your project2. [Writing A Simple Serving Class](gs-tutorial-3-step-writing-a-serving-class)3. [Deploying the Model-Serving Function (Service)](gs-tutorial-3-step-deploy-the-serving-function)4. [Using the Live Model-Serving Function](gs-tutorial-3-step-using-the-live-serving-function)5. [Viewing the Nuclio Serving Function on the Dashboard](gs-tutorial-3-step-view-serving-func-in-ui)By the end of this tutorial you'll learn how to- Create model-serving functions.- Deploy models at scale.- Test your deployed models. PrerequisitesThe following steps are a continuation of the previous parts of this getting-started tutorial and rely on the generated outputs.Therefore, make sure to first run parts 1&mdash;[2](02-model-training.ipynb) of the tutorial. Step 1: Setup and Configuration Importing LibrariesRun the following code to import required libraries: ###Code import mlrun ###Output _____no_output_____ ###Markdown Initializing Your MLRun EnvironmentUse the `get_or_create_project` MLRun method to create a new project or fetch it from the DB/repository if it already exists.Set the `project` and `user_project` parameters to the same values that you used in the call to this method in the [Part 1: MLRun Basics](./01-mlrun-basics.ipynbgs-tutorial-1-mlrun-envr-init) tutorial notebook. ###Code # Set the base project name project_name_base = 'getting-started' # Initialize the MLRun project object project = mlrun.get_or_create_project(project_name_base, context="./", user_project=True) ###Output > 2022-02-08 19:57:17,874 [info] loaded project getting-started from MLRun DB ###Markdown Step 2: Writing A Simple Serving ClassThe serving class is initialized automatically by the model server.All you need is to implement two mandatory methods:- `load` &mdash; downloads the model files and loads the model into memory. This can be done either synchronously or asynchronously.- `predict` &mdash; accepts a request payload and returns prediction (inference) results.For more detailed information on serving classes, see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.md).The following code demonstrates a minimal scikit-learn (a.k.a. sklearn) serving-class implementation: ###Code # mlrun: start-code from cloudpickle import load import numpy as np from typing import List import mlrun class ClassifierModel(mlrun.serving.V2ModelServer): def load(self): """load and initialize the model and/or other elements""" model_file, extra_data = self.get_model('.pkl') self.model = load(open(model_file, 'rb')) def predict(self, body: dict) -> List: """Generate model predictions from sample.""" feats = np.asarray(body['inputs']) result: np.ndarray = self.model.predict(feats) return result.tolist() # mlrun: end-code ###Output _____no_output_____ ###Markdown Step 3: Deploying the Model-Serving Function (Service)To provision (deploy) a function for serving the model ("a serving function") you need to create an MLRun function of type `serving`.You can do this by using the `code_to_function` MLRun method from a web notebook, or by importing an existing serving function or template from the MLRun functions marketplace. Converting a Serving Class to a Serving FunctionThe following code converts the `ClassifierModel` class that you defined in the previous step to a serving function.The name of the class to be used by the serving function is set in `spec.default_class`. ###Code serving_fn = mlrun.code_to_function('serving', kind='serving',image='mlrun/mlrun') serving_fn.spec.default_class = 'ClassifierModel' ###Output _____no_output_____ ###Markdown Add the model created in previous notebook by the training function ###Code model_file = project.get_artifact_uri('my_model') serving_fn.add_model('my_model',model_path=model_file) ###Output _____no_output_____ ###Markdown Testing Your Function LocallyTo test your function locally, create a test server (mock server) and test it with sample data. ###Code my_data = '''{"inputs":[[5.1, 3.5, 1.4, 0.2],[7.7, 3.8, 6.7, 2.2]]}''' server = serving_fn.to_mock_server() server.test("/v2/models/my_model/infer", body=my_data) ###Output > 2022-02-08 19:58:44,716 [info] model my_model was loaded > 2022-02-08 19:58:44,716 [info] Loaded ['my_model'] ###Markdown Building and Deploying the Serving FunctionUse the `deploy` method of the MLRun serving function to build and deploy a Nuclio serving function from your serving-function code. ###Code function_address = serving_fn.deploy() ###Output > 2022-02-08 19:58:50,645 [info] Starting remote function deploy 2022-02-08 19:58:51 (info) Deploying function 2022-02-08 19:58:51 (info) Building 2022-02-08 19:58:52 (info) Staging files and preparing base images 2022-02-08 19:58:52 (info) Building processor image 2022-02-08 19:59:47 (info) Build complete > 2022-02-08 19:59:52,828 [info] successfully deployed function: {'internal_invocation_urls': ['nuclio-getting-started-admin-serving.default-tenant.svc.cluster.local:8080'], 'external_invocation_urls': ['getting-started-admin-serving-getting-started-admin.default-tenant.app.yh41.iguazio-cd1.com/']} ###Markdown Step 4: Using the Live Model-Serving FunctionAfter the function is deployed successfully, the serving function has a new HTTP endpoint for handling serving requests.The example tutorial serving function receives HTTP prediction (inference) requests on this endpoint;calls the `infer` method to get the requested predictions; and returns the results on the same endpoint. ###Code print (f'The address for the function is {function_address} \n') !curl $function_address ###Output The address for the function is http://getting-started-admin-serving-getting-started-admin.default-tenant.app.yh41.iguazio-cd1.com/ {"name": "ModelRouter", "version": "v2", "extensions": []} ###Markdown Testing the Model ServerTest your model server by sending data for inference.The `invoke` serving-function method enables programmatic testing of the serving function.For model inference (predictions), specify the model name followed by `infer`:```/v2/models/{model_name}/infer```For complete model-service API commands &mdash; such as for list models (`models`), get model health (`ready`), and model explanation (`explain`) &mdash; see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.mdmodel-server-api). ###Code serving_fn.invoke('/v2/models/my_model/infer', my_data) ###Output > 2022-02-08 19:59:53,584 [info] invoking function: {'method': 'POST', 'path': 'http://nuclio-getting-started-admin-serving.default-tenant.svc.cluster.local:8080/v2/models/my_model/infer'} ###Markdown Part 3: Serving an ML ModelThis part of the MLRun getting-started tutorial walks you through the steps for implementing ML model serving using MLRun serving and Nuclio runtimes.The tutorial walks you through the steps for creating, deploying, and testing a model-serving function ("a serving function" a.k.a. "a model server").MLRun serving can produce managed real-time serverless pipelines from various tasks, including MLRun models or standard model files.The pipelines use the Nuclio real-time serverless engine, which can be deployed anywhere.[Nuclio](https://nuclio.io/) is a high-performance open-source "serverless" framework that's focused on data, I/O, and compute-intensive workloads.Simple model serving classes can be written in Python or be taken from a set of pre-developed ML/DL classes.The code can handle complex data, feature preparation, and binary data (such as images and video files).The Nuclio serving engine supports the full model-serving life cycle;this includes auto generation of microservices, APIs, load balancing, model logging and monitoring, and configuration management.MLRun serving supports more advanced real-time data processing and model serving pipelines.For more details and examples, see the [MLRun Serving Graphs](../serving/serving-graph.md) documentation.The tutorial consists of the following steps:1. [Setup and Configuration](gs-tutorial-3-step-setup) &mdash; load your project2. [Writing A Simple Serving Class](gs-tutorial-3-step-writing-a-serving-class)3. [Deploying the Model-Serving Function (Service)](gs-tutorial-3-step-deploy-the-serving-function)4. [Using the Live Model-Serving Function](gs-tutorial-3-step-using-the-live-serving-function)5. [Viewing the Nuclio Serving Function on the Dashboard](gs-tutorial-3-step-view-serving-func-in-ui)By the end of this tutorial you'll learn how to- Create model-serving functions.- Deploy models at scale.- Test your deployed models. PrerequisitesThe following steps are a continuation of the previous parts of this getting-started tutorial and rely on the generated outputs.Therefore, make sure to first run parts 1&mdash;[2](02-model-training.ipynb) of the tutorial. Step 1: Setup and Configuration Importing LibrariesRun the following code to import required libraries: ###Code import mlrun ###Output _____no_output_____ ###Markdown Initializing Your MLRun EnvironmentUse the `get_or_create_project` MLRun method to create a new project or fetch it from the DB/repository if it already exists.Set the `project` and `user_project` parameters to the same values that you used in the call to this method in the [Part 1: MLRun Basics](./01-mlrun-basics.ipynbgs-tutorial-1-set-mlrun-envr) tutorial notebook. ###Code # Set the base project name project_name_base = 'getting-started' # Initialize the MLRun project object project = mlrun.get_or_create_project(project_name_base, context="./", user_project=True) ###Output > 2021-09-09 05:20:36,857 [info] loaded project getting-started from MLRun DB ###Markdown Step 2: Writing A Simple Serving ClassThe serving class is initialized automatically by the model server.All you need is to implement two mandatory methods:- `load` &mdash; downloads the model files and loads the model into memory. This can be done either synchronously or asynchronously.- `predict` &mdash; accepts a request payload and returns prediction (inference) results.For more detailed information on serving classes, see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.md).The following code demonstrates a minimal scikit-learn (a.k.a. sklearn) serving-class implementation: ###Code # mlrun: start-code from cloudpickle import load import numpy as np from typing import List import mlrun class ClassifierModel(mlrun.serving.V2ModelServer): def load(self): """load and initialize the model and/or other elements""" model_file, extra_data = self.get_model('.pkl') self.model = load(open(model_file, 'rb')) def predict(self, body: dict) -> List: """Generate model predictions from sample.""" feats = np.asarray(body['inputs']) result: np.ndarray = self.model.predict(feats) return result.tolist() # mlrun: end-code ###Output _____no_output_____ ###Markdown Step 3: Deploying the Model-Serving Function (Service)To provision (deploy) a function for serving the model ("a serving function") you need to create an MLRun function of type `serving`.You can do this by using the `code_to_function` MLRun method from a web notebook, or by importing an existing serving function or template from the MLRun functions marketplace. Converting a Serving Class to a Serving FunctionThe following code converts the `ClassifierModel` class that you defined in the previous step to a serving function.The name of the class to be used by the serving function is set in `spec.default_class`. ###Code serving_fn = mlrun.code_to_function('serving', kind='serving',image='mlrun/mlrun') serving_fn.spec.default_class = 'ClassifierModel' ###Output _____no_output_____ ###Markdown Add the model created in previous notebook by the training function ###Code model_file = project.get_artifact_uri('my_model') serving_fn.add_model('my_model',model_path=model_file) ###Output _____no_output_____ ###Markdown Testing Your Function LocallyTo test your function locally, create a test server (mock server) and test it with sample data. ###Code my_data = '''{"inputs":[[5.1, 3.5, 1.4, 0.2],[7.7, 3.8, 6.7, 2.2]]}''' server = serving_fn.to_mock_server() server.test("/v2/models/my_model/infer", body=my_data) ###Output > 2021-09-09 05:20:41,738 [info] model my_model was loaded > 2021-09-09 05:20:41,739 [info] Initializing endpoint records > 2021-09-09 05:20:41,798 [info] Loaded ['my_model'] ###Markdown Building and Deploying the Serving FunctionUse the `deploy` method of the MLRun serving function to build and deploy a Nuclio serving function from your serving-function code. ###Code function_address = serving_fn.deploy() ###Output > 2021-09-09 05:20:41,815 [info] Starting remote function deploy 2021-09-09 05:20:42 (info) Deploying function 2021-09-09 05:20:42 (info) Building 2021-09-09 05:20:42 (info) Staging files and preparing base images 2021-09-09 05:20:42 (info) Building processor image 2021-09-09 05:20:43 (info) Build complete 2021-09-09 05:20:49 (info) Function deploy complete > 2021-09-09 05:20:50,139 [info] successfully deployed function: {'internal_invocation_urls': ['nuclio-getting-started-iguazio-serving.default-tenant.svc.cluster.local:8080'], 'external_invocation_urls': ['getting-started-iguazio-serving-getting-started-iguazio.default-tenant.app.jnewriujxdig.iguazio-cd1.com/']} ###Markdown Step 4: Using the Live Model-Serving FunctionAfter the function is deployed successfully, the serving function has a new HTTP endpoint for handling serving requests.The example tutorial serving function receives HTTP prediction (inference) requests on this endpoint;calls the `infer` method to get the requested predictions; and returns the results on the same endpoint. ###Code print (f'The address for the function is {function_address} \n') !curl $function_address ###Output The address for the function is http://getting-started-iguazio-serving-getting-started-iguazio.default-tenant.app.jnewriujxdig.iguazio-cd1.com/ {"name": "ModelRouter", "version": "v2", "extensions": []} ###Markdown Testing the Model ServerTest your model server by sending data for inference.The `invoke` serving-function method enables programmatic testing of the serving function.For model inference (predictions), specify the model name followed by `infer`:```/v2/models/{model_name}/infer```For complete model-service API commands &mdash; such as for list models (`models`), get model health (`ready`), and model explanation (`explain`) &mdash; see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.mdmodel-server-api). ###Code serving_fn.invoke('/v2/models/my_model/infer', my_data) ###Output > 2021-09-09 05:20:50,904 [info] invoking function: {'method': 'POST', 'path': 'http://nuclio-getting-started-iguazio-serving.default-tenant.svc.cluster.local:8080/v2/models/my_model/infer'} ###Markdown Part 3: Serving an ML ModelThis part of the MLRun getting-started tutorial walks you through the steps for implementing ML model serving using MLRun serving and Nuclio runtimes.The tutorial walks you through the steps for creating, deploying, and testing a model-serving function ("a serving function" a.k.a. "a model server").MLRun serving can produce managed real-time serverless pipelines from various tasks, including MLRun models or standard model files.The pipelines use the Nuclio real-time serverless engine, which can be deployed anywhere.[Nuclio](https://nuclio.io/) is a high-performance open-source "serverless" framework that's focused on data, I/O, and compute-intensive workloads.Simple model serving classes can be written in Python or be taken from a set of pre-developed ML/DL classes.The code can handle complex data, feature preparation, and binary data (such as images and video files).The Nuclio serving engine supports the full model-serving life cycle;this includes auto generation of microservices, APIs, load balancing, model logging and monitoring, and configuration management.MLRun serving supports more advanced real-time data processing and model serving pipelines.For more details and examples, see the [MLRun Serving Graphs](../serving/serving-graph.md) documentation.The tutorial consists of the following steps:1. [Setup and Configuration](gs-tutorial-3-step-setup) &mdash; load your project2. [Writing A Simple Serving Class](gs-tutorial-3-step-writing-a-serving-class)3. [Deploying the Model-Serving Function (Service)](gs-tutorial-3-step-deploy-the-serving-function)4. [Using the Live Model-Serving Function](gs-tutorial-3-step-using-the-live-serving-function)5. [Viewing the Nuclio Serving Function on the Dashboard](gs-tutorial-3-step-view-serving-func-in-ui)By the end of this tutorial you'll learn how to- Create model-serving functions.- Deploy models at scale.- Test your deployed models. PrerequisitesThe following steps are a continuation of the previous parts of this getting-started tutorial and rely on the generated outputs.Therefore, make sure to first run parts 1&mdash;[2](02-model-training.ipynb) of the tutorial. Step 1: Setup and Configuration Importing LibrariesRun the following code to import required libraries: ###Code import mlrun ###Output _____no_output_____ ###Markdown Initializing Your MLRun EnvironmentUse the `get_or_create_project` MLRun method to create a new project or fetch it from the DB/repository if it already exists.Set the `project` and `user_project` parameters to the same values that you used in the call to this method in the [Part 1: MLRun Basics](./01-mlrun-basics.ipynbgs-tutorial-1-mlrun-envr-init) tutorial notebook. ###Code # Set the base project name project_name_base = 'getting-started' # Initialize the MLRun project object project = mlrun.get_or_create_project(project_name_base, context="./", user_project=True) ###Output > 2021-09-09 05:20:36,857 [info] loaded project getting-started from MLRun DB ###Markdown Step 2: Writing A Simple Serving ClassThe serving class is initialized automatically by the model server.All you need is to implement two mandatory methods:- `load` &mdash; downloads the model files and loads the model into memory. This can be done either synchronously or asynchronously.- `predict` &mdash; accepts a request payload and returns prediction (inference) results.For more detailed information on serving classes, see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.md).The following code demonstrates a minimal scikit-learn (a.k.a. sklearn) serving-class implementation: ###Code # mlrun: start-code from cloudpickle import load import numpy as np from typing import List import mlrun class ClassifierModel(mlrun.serving.V2ModelServer): def load(self): """load and initialize the model and/or other elements""" model_file, extra_data = self.get_model('.pkl') self.model = load(open(model_file, 'rb')) def predict(self, body: dict) -> List: """Generate model predictions from sample.""" feats = np.asarray(body['inputs']) result: np.ndarray = self.model.predict(feats) return result.tolist() # mlrun: end-code ###Output _____no_output_____ ###Markdown Step 3: Deploying the Model-Serving Function (Service)To provision (deploy) a function for serving the model ("a serving function") you need to create an MLRun function of type `serving`.You can do this by using the `code_to_function` MLRun method from a web notebook, or by importing an existing serving function or template from the MLRun functions marketplace. Converting a Serving Class to a Serving FunctionThe following code converts the `ClassifierModel` class that you defined in the previous step to a serving function.The name of the class to be used by the serving function is set in `spec.default_class`. ###Code serving_fn = mlrun.code_to_function('serving', kind='serving',image='mlrun/mlrun') serving_fn.spec.default_class = 'ClassifierModel' ###Output _____no_output_____ ###Markdown Add the model created in previous notebook by the training function ###Code model_file = project.get_artifact_uri('my_model') serving_fn.add_model('my_model',model_path=model_file) ###Output _____no_output_____ ###Markdown Testing Your Function LocallyTo test your function locally, create a test server (mock server) and test it with sample data. ###Code my_data = '''{"inputs":[[5.1, 3.5, 1.4, 0.2],[7.7, 3.8, 6.7, 2.2]]}''' server = serving_fn.to_mock_server() server.test("/v2/models/my_model/infer", body=my_data) ###Output > 2021-09-09 05:20:41,738 [info] model my_model was loaded > 2021-09-09 05:20:41,739 [info] Initializing endpoint records > 2021-09-09 05:20:41,798 [info] Loaded ['my_model'] ###Markdown Building and Deploying the Serving FunctionUse the `deploy` method of the MLRun serving function to build and deploy a Nuclio serving function from your serving-function code. ###Code function_address = serving_fn.deploy() ###Output > 2021-09-09 05:20:41,815 [info] Starting remote function deploy 2021-09-09 05:20:42 (info) Deploying function 2021-09-09 05:20:42 (info) Building 2021-09-09 05:20:42 (info) Staging files and preparing base images 2021-09-09 05:20:42 (info) Building processor image 2021-09-09 05:20:43 (info) Build complete 2021-09-09 05:20:49 (info) Function deploy complete > 2021-09-09 05:20:50,139 [info] successfully deployed function: {'internal_invocation_urls': ['nuclio-getting-started-iguazio-serving.default-tenant.svc.cluster.local:8080'], 'external_invocation_urls': ['getting-started-iguazio-serving-getting-started-iguazio.default-tenant.app.jnewriujxdig.iguazio-cd1.com/']} ###Markdown Step 4: Using the Live Model-Serving FunctionAfter the function is deployed successfully, the serving function has a new HTTP endpoint for handling serving requests.The example tutorial serving function receives HTTP prediction (inference) requests on this endpoint;calls the `infer` method to get the requested predictions; and returns the results on the same endpoint. ###Code print (f'The address for the function is {function_address} \n') !curl $function_address ###Output The address for the function is http://getting-started-iguazio-serving-getting-started-iguazio.default-tenant.app.jnewriujxdig.iguazio-cd1.com/ {"name": "ModelRouter", "version": "v2", "extensions": []} ###Markdown Testing the Model ServerTest your model server by sending data for inference.The `invoke` serving-function method enables programmatic testing of the serving function.For model inference (predictions), specify the model name followed by `infer`:```/v2/models/{model_name}/infer```For complete model-service API commands &mdash; such as for list models (`models`), get model health (`ready`), and model explanation (`explain`) &mdash; see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.mdmodel-server-api). ###Code serving_fn.invoke('/v2/models/my_model/infer', my_data) ###Output > 2021-09-09 05:20:50,904 [info] invoking function: {'method': 'POST', 'path': 'http://nuclio-getting-started-iguazio-serving.default-tenant.svc.cluster.local:8080/v2/models/my_model/infer'} ###Markdown Part 3: Serving an ML ModelThis part of the MLRun getting-started tutorial walks you through the steps for implementing ML model serving using MLRun serving and Nuclio runtimes.The tutorial walks you through the steps for creating, deploying, and testing a model-serving function ("a serving function" a.k.a. "a model server").MLRun serving can produce managed real-time serverless pipelines from various tasks, including MLRun models or standard model files.The pipelines use the Nuclio real-time serverless engine, which can be deployed anywhere.[Nuclio](https://nuclio.io/) is a high-performance open-source "serverless" framework that's focused on data, I/O, and compute-intensive workloads.Simple model serving classes can be written in Python or be taken from a set of pre-developed ML/DL classes.The code can handle complex data, feature preparation, and binary data (such as images and video files).The Nuclio serving engine supports the full model-serving life cycle;this includes auto generation of microservices, APIs, load balancing, model logging and monitoring, and configuration management.MLRun serving supports more advanced real-time data processing and model serving pipelines.For more details and examples, see the [MLRun Serving Graphs](../serving/serving-graph.md) documentation.The tutorial consists of the following steps:1. [Setup and Configuration](gs-tutorial-3-step-setup) &mdash; load your project2. [Writing A Simple Serving Class](gs-tutorial-3-step-writing-a-serving-class)3. [Deploying the Model-Serving Function (Service)](gs-tutorial-3-step-deploy-the-serving-function)4. [Using the Live Model-Serving Function](gs-tutorial-3-step-using-the-live-serving-function)5. [Viewing the Nuclio Serving Function on the Dashboard](gs-tutorial-3-step-view-serving-func-in-ui)By the end of this tutorial you'll learn how to- Create model-serving functions.- Deploy models at scale.- Test your deployed models. PrerequisitesThe following steps are a continuation of the previous parts of this getting-started tutorial and rely on the generated outputs.Therefore, make sure to first run parts 1&mdash;[2](02-model-training.ipynb) of the tutorial. Step 1: Setup and Configuration Importing LibrariesRun the following code to import required libraries: ###Code from os import path import mlrun ###Output _____no_output_____ ###Markdown Initializing Your MLRun EnvironmentUse the `set_environment` MLRun method to configure the working environment and default configuration.Set the `project` and `user_project` parameters to the same values that you used in the call to this method in the [Part 1: MLRun Basics](./01-mlrun-basics.ipynbgs-tutorial-1-set-mlrun-envr) tutorial notebook. ###Code # Set the base project name project_name_base = 'getting-started-tutorial' # Initialize the MLRun environment and save the project name and artifacts path project_name, artifact_path = mlrun.set_environment(project=project_name_base, user_project=True) ###Output _____no_output_____ ###Markdown Step 2: Writing A Simple Serving ClassThe serving class is initialized automatically by the model server.All you need is to implement two mandatory methods:- `load` &mdash; downloads the model files and loads the model into memory. This can be done either synchronously or asynchronously.- `predict` &mdash; accepts a request payload and returns prediction (inference) results.For more detailed information on serving classes, see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.md).The following code demonstrates a minimal scikit-learn (a.k.a. sklearn) serving-class implementation: ###Code # mlrun: start-code from cloudpickle import load import numpy as np from typing import List import mlrun class ClassifierModel(mlrun.serving.V2ModelServer): def load(self): """load and initialize the model and/or other elements""" model_file, extra_data = self.get_model('.pkl') self.model = load(open(model_file, 'rb')) def predict(self, body: dict) -> List: """Generate model predictions from sample.""" feats = np.asarray(body['inputs']) result: np.ndarray = self.model.predict(feats) return result.tolist() # mlrun: end-code ###Output _____no_output_____ ###Markdown Step 3: Deploying the Model-Serving Function (Service)To provision (deploy) a function for serving the model ("a serving function") you need to create an MLRun function of type `serving`.You can do this by using the `code_to_function` MLRun method from a web notebook, or by importing an existing serving function or template from the MLRun functions marketplace. Converting a Serving Class to a Serving FunctionThe following code converts the `ClassifierModel` class that you defined in the previous step to a serving function.The name of the class to be used by the serving function is set in `spec.default_class`. ###Code from mlrun import code_to_function serving_fn = code_to_function('serving', kind='serving',image='mlrun/mlrun') serving_fn.spec.default_class = 'ClassifierModel' ###Output _____no_output_____ ###Markdown Add the model created in previous notebook by the training function ###Code model_file = f'store://{project_name}/train-iris-train_iris_model' serving_fn.add_model('my_model',model_path=model_file) from mlrun.platforms import auto_mount serving_fn = serving_fn.apply(auto_mount()) ###Output _____no_output_____ ###Markdown Testing Your Function LocallyTo test your function locally, create a test server (mock server) and test it with sample data. ###Code my_data = '''{"inputs":[[5.1, 3.5, 1.4, 0.2],[7.7, 3.8, 6.7, 2.2]]}''' server = serving_fn.to_mock_server() server.test("/v2/models/my_model/infer", body=my_data) ###Output _____no_output_____ ###Markdown Building and Deploying the Serving FunctionUse the `deploy` method of the MLRun serving function to build and deploy a Nuclio serving function from your serving-function code. ###Code function_address = serving_fn.deploy() ###Output > 2021-01-25 08:40:23,461 [info] Starting remote function deploy 2021-01-25 08:40:23 (info) Deploying function 2021-01-25 08:40:23 (info) Building 2021-01-25 08:40:23 (info) Staging files and preparing base images 2021-01-25 08:40:23 (info) Building processor image 2021-01-25 08:40:24 (info) Build complete 2021-01-25 08:40:30 (info) Function deploy complete > 2021-01-25 08:40:31,117 [info] function deployed, address=default-tenant.app.aefccdjffbit.iguazio-cd0.com:31805 ###Markdown Step 4: Using the Live Model-Serving FunctionAfter the function is deployed successfully, the serving function has a new HTTP endpoint for handling serving requests.The example tutorial serving function receives HTTP prediction (inference) requests on this endpoint;calls the `infer` method to get the requested predictions; and returns the results on the same endpoint. ###Code print (f'The address for the function is {function_address} \n') !curl $function_address ###Output The address for the function is default-tenant.app.aefccdjffbit.iguazio-cd0.com:31805 {"name": "ModelRouter", "version": "v2", "extensions": []} ###Markdown Testing the Model ServerTest your model server by sending data for inference.The `invoke` serving-function method enables programmatic testing of the serving function.For model inference (predictions), specify the model name followed by `infer`:```/v2/models/{model_name}/infer```For complete model-service API commands &mdash; such as for list models (`models`), get model health (`ready`), and model explanation (`explain`) &mdash; see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.mdmodel-server-api). ###Code serving_fn.invoke('/v2/models/my_model/infer', my_data) ###Output _____no_output_____ ###Markdown Part 3: Serving an ML ModelThis part of the MLRun getting-started tutorial walks you through the steps for implementing ML model serving using MLRun serving and Nuclio runtimes.The tutorial walks you through the steps for creating, deploying, and testing a model-serving function ("a serving function" a.k.a. "a model server").MLRun serving can produce managed real-time serverless pipelines from various tasks, including MLRun models or standard model files.The pipelines use the Nuclio real-time serverless engine, which can be deployed anywhere.[Nuclio](https://nuclio.io/) is a high-performance open-source "serverless" framework that's focused on data, I/O, and compute-intensive workloads.Simple model serving classes can be written in Python or be taken from a set of pre-developed ML/DL classes.The code can handle complex data, feature preparation, and binary data (such as images and video files).The Nuclio serving engine supports the full model-serving life cycle;this includes auto generation of microservices, APIs, load balancing, model logging and monitoring, and configuration management.MLRun serving supports more advanced real-time data processing and model serving pipelines.For more details and examples, see the [MLRun Serving Graphs](../serving/serving-graph.md) documentation.The tutorial consists of the following steps:1. [Setup and Configuration](gs-tutorial-3-step-setup) &mdash; load your project2. [Writing A Simple Serving Class](gs-tutorial-3-step-writing-a-serving-class)3. [Deploying the Model-Serving Function (Service)](gs-tutorial-3-step-deploy-the-serving-function)4. [Using the Live Model-Serving Function](gs-tutorial-3-step-using-the-live-serving-function)5. [Viewing the Nuclio Serving Function on the Dashboard](gs-tutorial-3-step-view-serving-func-in-ui)By the end of this tutorial you'll learn how to- Create model-serving functions.- Deploy models at scale.- Test your deployed models. PrerequisitesThe following steps are a continuation of the previous parts of this getting-started tutorial and rely on the generated outputs.Therefore, make sure to first run parts 1&mdash;[2](02-model-training.ipynb) of the tutorial. Step 1: Setup and Configuration Importing LibrariesRun the following code to import required libraries: ###Code from os import path import mlrun ###Output _____no_output_____ ###Markdown Initializing Your MLRun EnvironmentUse the `set_environment` MLRun method to configure the working environment and default configuration.Set the `project` and `user_project` parameters to the same values that you used in the call to this method in the [Part 1: MLRun Basics](./01-mlrun-basics.ipynbgs-tutorial-1-set-mlrun-envr) tutorial notebook. ###Code # Set the base project name project_name_base = 'getting-started-tutorial' # Initialize the MLRun environment and save the project name and artifacts path project_name, artifact_path = mlrun.set_environment(project=project_name_base, user_project=True) ###Output _____no_output_____ ###Markdown Step 2: Writing A Simple Serving ClassThe serving class is initialized automatically by the model server.All you need is to implement two mandatory methods:- `load` &mdash; downloads the model files and loads the model into memory. This can be done either synchronously or asynchronously.- `predict` &mdash; accepts a request payload and returns prediction (inference) results.For more detailed information on serving classes, see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.md).The following code demonstrates a minimal scikit-learn (a.k.a. sklearn) serving-class implementation: ###Code # nuclio: start-code from cloudpickle import load import numpy as np from typing import List import mlrun class ClassifierModel(mlrun.serving.V2ModelServer): def load(self): """load and initialize the model and/or other elements""" model_file, extra_data = self.get_model('.pkl') self.model = load(open(model_file, 'rb')) def predict(self, body: dict) -> List: """Generate model predictions from sample.""" feats = np.asarray(body['inputs']) result: np.ndarray = self.model.predict(feats) return result.tolist() # nuclio: end-code ###Output _____no_output_____ ###Markdown Step 3: Deploying the Model-Serving Function (Service)To provision (deploy) a function for serving the model ("a serving function") you need to create an MLRun function of type `serving`.You can do this by using the `code_to_function` MLRun method from a web notebook, or by importing an existing serving function or template from the MLRun functions marketplace. Converting a Serving Class to a Serving FunctionThe following code converts the `ClassifierModel` class that you defined in the previous step to a serving function.The name of the class to be used by the serving function is set in `spec.default_class`. ###Code from mlrun import code_to_function serving_fn = code_to_function('serving', kind='serving',image='mlrun/mlrun') serving_fn.spec.default_class = 'ClassifierModel' ###Output _____no_output_____ ###Markdown Add the model created in previous notebook by the training function ###Code model_file = f'store://{project_name}/train-iris-train_iris_model' serving_fn.add_model('my_model',model_path=model_file) from mlrun.platforms import auto_mount serving_fn = serving_fn.apply(auto_mount()) ###Output _____no_output_____ ###Markdown Testing Your Function LocallyTo test your function locally, create a test server (mock server) and test it with sample data. ###Code my_data = '''{"inputs":[[5.1, 3.5, 1.4, 0.2],[7.7, 3.8, 6.7, 2.2]]}''' server = serving_fn.to_mock_server() server.test("/v2/models/my_model/infer", body=my_data) ###Output _____no_output_____ ###Markdown Building and Deploying the Serving FunctionUse the `deploy` method of the MLRun serving function to build and deploy a Nuclio serving function from your serving-function code. ###Code function_address = serving_fn.deploy() ###Output > 2021-01-25 08:40:23,461 [info] Starting remote function deploy 2021-01-25 08:40:23 (info) Deploying function 2021-01-25 08:40:23 (info) Building 2021-01-25 08:40:23 (info) Staging files and preparing base images 2021-01-25 08:40:23 (info) Building processor image 2021-01-25 08:40:24 (info) Build complete 2021-01-25 08:40:30 (info) Function deploy complete > 2021-01-25 08:40:31,117 [info] function deployed, address=default-tenant.app.aefccdjffbit.iguazio-cd0.com:31805 ###Markdown Step 4: Using the Live Model-Serving FunctionAfter the function is deployed successfully, the serving function has a new HTTP endpoint for handling serving requests.The example tutorial serving function receives HTTP prediction (inference) requests on this endpoint;calls the `infer` method to get the requested predictions; and returns the results on the same endpoint. ###Code print (f'The address for the function is {function_address} \n') !curl $function_address ###Output The address for the function is default-tenant.app.aefccdjffbit.iguazio-cd0.com:31805 {"name": "ModelRouter", "version": "v2", "extensions": []} ###Markdown Testing the Model ServerTest your model server by sending data for inference.The `invoke` serving-function method enables programmatic testing of the serving function.For model inference (predictions), specify the model name followed by `infer`:```/v2/models/{model_name}/infer```For complete model-service API commands &mdash; such as for list models (`models`), get model health (`ready`), and model explanation (`explain`) &mdash; see the [MLRun documentation](https://github.com/mlrun/mlrun/blob/release/v0.6.x-latest/mlrun/serving/README.mdmodel-server-api). ###Code serving_fn.invoke('/v2/models/my_model/infer', my_data) ###Output _____no_output_____
deeplearning.ai - TensorFlow in Practice Specialization/deeplearning.ai - Natural Language Processing in TensorFlow/module1- Sentiment in text/Lesson_2.ipynb
###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import tensorflow as tf from tensorflow import keras from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences sentences = [ 'I love my dog', 'I love my cat', 'You love my dog!', 'Do you think my dog is amazing?' ] tokenizer = Tokenizer(num_words = 100, oov_token="<OOV>") tokenizer.fit_on_texts(sentences) word_index = tokenizer.word_index sequences = tokenizer.texts_to_sequences(sentences) padded = pad_sequences(sequences, maxlen=5) print("\nWord Index = " , word_index) print("\nSequences = " , sequences) print("\nPadded Sequences:") print(padded) # Try with words that the tokenizer wasn't fit to test_data = [ 'i really love my dog', 'my dog loves my manatee' ] test_seq = tokenizer.texts_to_sequences(test_data) print("\nTest Sequence = ", test_seq) padded = pad_sequences(test_seq, maxlen=10) print("\nPadded Test Sequence: ") print(padded) ###Output Word Index = {'<OOV>': 1, 'my': 2, 'love': 3, 'dog': 4, 'i': 5, 'you': 6, 'cat': 7, 'do': 8, 'think': 9, 'is': 10, 'amazing': 11} Sequences = [[5, 3, 2, 4], [5, 3, 2, 7], [6, 3, 2, 4], [8, 6, 9, 2, 4, 10, 11]] Padded Sequences: [[ 0 5 3 2 4] [ 0 5 3 2 7] [ 0 6 3 2 4] [ 9 2 4 10 11]] Test Sequence = [[5, 1, 3, 2, 4], [2, 4, 1, 2, 1]] Padded Test Sequence: [[0 0 0 0 0 5 1 3 2 4] [0 0 0 0 0 2 4 1 2 1]]
2. ITW2/05_Prefix_Infix_and_Postfix.ipynb
###Markdown Wap to evaluate any one of following as valid or invalid.* Postfix eg. ((AB*)(CD/)+)* Infix eg. ((A*B)+(C/D))* Prefix eg. (+(*AB)(/CD)) Wap to convert an:* infix to postfix and vice versa* infix to prefix and vice versa* prefix to postfix expression and vice versa ###Code # Check for operator def is_operator(temp): if temp in '+-*/': return True return False # Check for bracket def is_bracket(temp): if temp in '()': return True return False # Check for operator def is_operand(temp): if temp in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ': return True return False # Validate prefix def v_prefix(temp): s = [] for i in temp: if i != ')': s.append(i) elif i == ')': temp_1 = s.pop(-4) temp_2 = s.pop(-3) temp_3 = s.pop(-2) temp_4 = s.pop() s.append('x') if all([is_operator(temp_2), is_operand(temp_3), is_operand(temp_4), temp_1 == '(', i == ')']): continue else: return False if len(s) == 1: return True else: return False a = input() print(v_prefix(a)) #Validate infix def v_infix(temp): s = [] for i in temp: if i != ')': s.append(i) elif i == ')': temp_1 = s.pop(-4) temp_2 = s.pop(-3) temp_3 = s.pop(-2) temp_4 = s.pop() s.append('x') if all([is_operand(temp_2), is_operator(temp_3), is_operand(temp_4), temp_1 == '(', i == ')']): continue else: return False if len(s) == 1: return True else: return False a = input() print(v_infix(a)) #Validate postfix def v_postfix(temp): a = [] for i in temp: if is_bracket(i): continue if not is_operator(i): a.append(i) else: temp = str(a.pop(-2)) temp += str(a.pop()) temp += i a.append(temp) if len(a) == 1: return True return False a = input() print(v_postfix(a)) ###Output _____no_output_____ ###Markdown Conversions ###Code def pre_in(temp): s = [] for i in temp: if i != ')': s.append(i) elif i == ')': a = '' a += s.pop(-4) a += s.pop(-2) a += s.pop(-2) a += s.pop() a += i s.append(a) return str(s[0]) a = input() print(pre_in(a)) def pre_post(temp): s = [] for i in temp: if i != ')': s.append(i) elif i == ')': a = '' a += s.pop(-4) a += s.pop(-2) a += s.pop() a += s.pop() a += i s.append(a) return str(s[0]) a = input() print(pre_post(a)) def in_post(temp): s = [] for i in temp: if i != ')': s.append(i) elif i == ')': a = '' a += s.pop(-4) a += s.pop(-3) a += s.pop() a += s.pop() a += i s.append(a) return str(s[0]) a = input() print(in_post(a)) def in_pre(temp): s = [] for i in temp: if i != ')': s.append(i) elif i == ')': a = '' a += s.pop(-4) a += s.pop(-2) a += s.pop(-2) a += s.pop() a += i s.append(a) return str(s[0]) a = input() print(in_pre(a)) def post_pre(temp): s = [] for i in temp: if i != ')': s.append(i) elif i == ')': a = '' a += s.pop(-4) a += s.pop() a += s.pop(-2) a += s.pop() a += i s.append(a) return str(s[0]) def post_in(temp): s = [] for i in temp: if i != ')': s.append(i) elif i == ')': a = '' a += s.pop(-4) a += s.pop(-3) a += s.pop() a += s.pop() a += i s.append(a) return str(s[0]) a = input() print(post_pre(a), post_in(a)) ###Output _____no_output_____
covid_vs_normal.ipynb
###Markdown Data Processessing ###Code # counting the amount of x rays images len_normal_train = len([iq for iq in os.scandir('xrays/covidvsnormal/train/normal')]) len_normal_test = len([iq for iq in os.scandir('xrays/covidvsnormal/test/normal')]) len_normal_val = len([iq for iq in os.scandir('xrays/covidvsnormal/val/normal')]) len_covid_train = len([iq for iq in os.scandir('xrays/covidvsnormal/train/covid')]) len_covid_val = len([iq for iq in os.scandir('xrays/covidvsnormal/val/covid')]) len_covid_test = len([iq for iq in os.scandir('xrays/covidvsnormal/test/covid')]) len_train_total = len_normal_train + len_covid_train len_val_total = len_covid_val + len_normal_val len_test_total = len_normal_test + len_covid_test print("Total") print("---------------------") print ("normal: ", len_normal_train) print ("normal no val: ", len_normal_val) print ("normal no test: ", len_normal_test) print("---------------------") print ("covid no train: ", len_covid_train) print ("covid no val: ", len_covid_val) print ("covid no test: ", len_covid_test) print() print("Total") print("---------------------") print("total train: ", len_train_total) print("total val: ", len_val_total) print("total test: ", len_test_total) # extracting the images DIR_NAME = 'xrays/covidvsnormal/' imagePaths=[] for dirname, _, filenames in os.walk(DIR_NAME): for filename in filenames: imagePaths.append(os.path.join(dirname, filename)) # verifying if the images have been extracted imagePaths # assigining the labels to the images data = [] labels = [] # loop over the image paths for imagePath in imagePaths: # extract the class label from the filename label = imagePath.split(os.path.sep)[-2] # load the image, swap color channels, and resize it to be a fixed # 224x224 pixels while ignoring aspect ratio image = cv2.imread(imagePath) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (64, 64)) # update the data and labels lists, respectively data.append(image) labels.append(label) # convert the data and labels to NumPy arrays while scaling the pixel # intensities to the range [0, 1] data = np.array(data) / 255.0 labels = np.array(labels) # verifying the shape data.shape # verifying the labels labels # perform one-hot encoding on the labels lb = LabelBinarizer() labels = lb.fit_transform(labels) labels = to_categorical(labels) # partition the data into training and testing splits using 80% of # the data for training and the remaining 20% for testing (x_train, x_test, y_train, y_test) = train_test_split(data, labels, test_size=0.20, stratify=labels, random_state=42) ###Output _____no_output_____ ###Markdown Data Augmentation ###Code # Data Augmentation def process_data(x_train,y_train, x_test,y_test, batch_size): #to prevent overfitting train_datagen = ImageDataGenerator(shear_range=0.2, rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, horizontal_flip=True, vertical_flip=False, zoom_range=0.2) validation_datagen = ImageDataGenerator() train_generator = train_datagen.flow(x_train,y_train, batch_size=batch_size) validation_generator = validation_datagen.flow(x_test,y_test, batch_size=batch_size) return train_generator, validation_generator ###Output _____no_output_____ ###Markdown Transfer Learning ###Code # adding top layer def addTopModel(bottom_model, num_classes): top_model = bottom_model.output top_model = MaxPooling2D(pool_size=(2,2), strides=2)(top_model) top_model = Flatten(name="flatten")(top_model) top_model = Dense(512, activation="relu")(top_model) top_model = Dropout(0.5)(top_model) top_model = Dense(2, activation='sigmoid')(top_model) model = Model(inputs=bottom_model.input, outputs=top_model) return model def get_model(transferleaner,x_train,y_train, x_test,y_test): m = transferleaner pred = addTopModel(m, num_classes) #data augmentation train_generator, validation_generator = process_data(x_train,y_train, x_test,y_test, batch_size) model.summary() checkpoint = ModelCheckpoint(data_dir+'modelcnd'+'.h5', monitor='val_loss', mode="min", save_best_only=True, verbose=1) earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=30, verbose=1, restore_best_weights=True) learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', patience=30, verbose=1, factor=0.8, min_lr=0.0001, mode="auto", min_delta=0.0001, cooldown=5) callbacks = [checkpoint, earlystop, learning_rate_reduction] model.compile(loss=models_loss, optimizer=models_opt, metrics=['accuracy']) model.fit_generator(train_generator, steps_per_epoch=len_train_total//batch_size, epochs=epochs, callbacks=callbacks, validation_data=validation_generator, validation_steps=len_val_total//batch_size) history = model.fit_generator(train_generator, steps_per_epoch=len_train_total//batch_size, epochs=epochs, callbacks=callbacks, validation_data=validation_generator, validation_steps=len_val_total//batch_size) return model, history # build sequencial model def build_model(bottom_model, num_classes): top_model = bottom_model.output top_model = MaxPooling2D(pool_size=(2,2), strides=2)(top_model) top_model = Flatten(name="flatten")(top_model) top_model = Dense(2, activation='sigmoid')(top_model) model = Model(inputs=bottom_model.input, outputs=top_model) return model ###Output _____no_output_____ ###Markdown Confusion Matrix ###Code # plotting confusion matrix for testing def plot_confusion_matrix(model, x_test, y_test): fig, ax = plt.subplots(figsize=(8,6)) classes = ['COVID','NORMAL'] y_pred = model.predict(x_test, batch_size=batch_size) y_pred = np.argmax(y_pred, axis=1) y_test = np.argmax(y_test, axis=1) print('Confusion Matrix') cm = confusion_matrix(y_test, y_pred, normalize='true') #cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] sns.heatmap(cm,cmap='Purples',fmt='g', annot=True) tick_marks = [0.5,1.5] plt.xticks(tick_marks, classes) plt.yticks(tick_marks, classes) plt.title('Confusion Matrix - Normalized') plt.ylabel('True label') plt.xlabel('Predicted label') bottom, top = ax.get_ylim() ax.set_ylim(bottom + 0.5, top - 0.5) plt.show() acc = accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, average=None) recall = recall_score(y_test, y_pred, average=None) f1 = f1_score(y_test, y_pred, average=None) print("Precision Score: {}".format(precision)) print("Recall Score: {}".format(recall)) print("F1 Score: {}".format(f1)) print("Accuracy Score: {}".format(acc)) return plt.show() ###Output _____no_output_____ ###Markdown ROC AUC ###Code #ROC curve def multiclass_roc_auc_score(x_test, y_test, model, average="micro"): y_pred = model.predict(x_test, batch_size=batch_size) # Convert to Binary classes y_pred_bin = np.argmax(y_pred, axis=1) y_test_bin = np.argmax(y_test, axis=1) fpr, tpr, thresholds = roc_curve(y_test_bin, y_pred_bin) auc_keras = auc(fpr, tpr) print('AUC: {}'.format(auc_keras)) print('Log Loss: {}'.format(metrics.log_loss(y_test.argmax(axis=1), y_pred))) plt.plot(fpr, tpr, color='darkorange', label='ROC curve (area = %0.2f)' % auc_keras) plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.rcParams['font.size'] = 12 plt.title('ROC curve for our model') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(loc='best', fancybox=True) plt.grid(True) return plt.show() ###Output _____no_output_____ ###Markdown Model Loss ###Code #model loss def plot_learning_curves(r): plt.figure(figsize=(12,4)) plt.subplot(1,2,1) plt.plot(r.history['loss']) plt.plot(r.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.grid(True) plt.subplot(1,2,2) plt.plot(r.history['accuracy']) plt.plot(r.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.grid(True) plt.tight_layout() return plt.show() ###Output _____no_output_____ ###Markdown Assigning Parameters ###Code #parameters data_dir = '/' version = '-v5-' num_classes = 2 ig_size= 64 epochs = 100 batch_size = 32 models_loss = 'binary_crossentropy' models_opt = 'adam' #Adam(lr=0.001, decay=0.001/600) #SGD(learning_rate=0.001, momentum=0.9) #ADAM(lr=0.001) ###Output _____no_output_____ ###Markdown Modeling - Base CNN ModelFirst, I used the sequential keras model which is th easiest way to build a model in keras. It allows one to build a model, layer by layer. My first layer will be a Conv2D layer that will deal with my input x-ray images of shape 64, 64, 3 using 64 nodes. The 3 in the shape sigifying that the images are in RGB. The kernel size is set to 3, which means the filter that would be used to scan through every pixel will be a matrix of 3x3. Next, a MaxPooling2D layer was utilized in order to reduce overfitting and dimentionality i.e in order to reduce the number of parameters to learn from and the amount of comuputation performed in the network. I set it to divide the dimentions by a matrix of 2x2 while moving 2 strides after choosing the maximum value of each patch. After this, I flattened the output from the MaxPooling layer in order to make it linear and pass it to the Dense layer implemented, which uses a node of 2 which represents the number of output classes to be predicted. ###Code # calling thesequential model m = Sequential(Conv2D(ig_size, kernel_size=3, activation='relu', input_shape=(64,64,3))) model = build_model(m, num_classes) for layer in m.layers: layer.trainable = False #data augmentation train_generator, validation_generator = process_data(x_train,y_train, x_test,y_test, batch_size) model.summary() checkpoint = ModelCheckpoint(data_dir+'sequentialpnd' + '.h5', monitor='val_loss', mode="min", save_best_only=True, verbose=1) earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=30, verbose=1, restore_best_weights=True) learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', patience=30, verbose=1, factor=0.8, min_lr=0.0001, mode="auto", min_delta=0.0001, cooldown=5) callbacks = [checkpoint, earlystop, learning_rate_reduction] model.compile(loss=models_loss, optimizer=models_opt, metrics=['accuracy']) history = model.fit(train_generator, epochs=epochs, callbacks=callbacks, validation_data=validation_generator, validation_steps=len(x_test) / batch_size, steps_per_epoch=len(x_train) / batch_size) ###Output Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_input (InputLayer) [(None, 64, 64, 3)] 0 _________________________________________________________________ conv2d (Conv2D) (None, 62, 62, 64) 1792 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 31, 31, 64) 0 _________________________________________________________________ flatten (Flatten) (None, 61504) 0 _________________________________________________________________ dense (Dense) (None, 2) 123010 ================================================================= Total params: 124,802 Trainable params: 123,010 Non-trainable params: 1,792 _________________________________________________________________ Epoch 1/100 56/55 [==============================] - ETA: 0s - loss: 0.4357 - accuracy: 0.8181 Epoch 00001: val_loss improved from inf to 0.31784, saving model to /sequentialpnd.h5 56/55 [==============================] - 9s 155ms/step - loss: 0.4357 - accuracy: 0.8181 - val_loss: 0.3178 - val_accuracy: 0.8668 - lr: 0.0010 Epoch 2/100 56/55 [==============================] - ETA: 0s - loss: 0.2440 - accuracy: 0.9096 Epoch 00002: val_loss improved from 0.31784 to 0.19426, saving model to /sequentialpnd.h5 56/55 [==============================] - 7s 123ms/step - loss: 0.2440 - accuracy: 0.9096 - val_loss: 0.1943 - val_accuracy: 0.9278 - lr: 0.0010 Epoch 3/100 56/55 [==============================] - ETA: 0s - loss: 0.2174 - accuracy: 0.9288 Epoch 00003: val_loss improved from 0.19426 to 0.15264, saving model to /sequentialpnd.h5 56/55 [==============================] - 6s 103ms/step - loss: 0.2174 - accuracy: 0.9288 - val_loss: 0.1526 - val_accuracy: 0.9481 - lr: 0.0010 Epoch 4/100 56/55 [==============================] - ETA: 0s - loss: 0.2118 - accuracy: 0.9271 ETA: 0s - loss: 0.2128 - accuracy: 0. Epoch 00004: val_loss improved from 0.15264 to 0.14179, saving model to /sequentialpnd.h5 56/55 [==============================] - 6s 111ms/step - loss: 0.2118 - accuracy: 0.9271 - val_loss: 0.1418 - val_accuracy: 0.9503 - lr: 0.0010 Epoch 5/100 56/55 [==============================] - ETA: 0s - loss: 0.2253 - accuracy: 0.9209 Epoch 00005: val_loss did not improve from 0.14179 56/55 [==============================] - 5s 87ms/step - loss: 0.2253 - accuracy: 0.9209 - val_loss: 0.1761 - val_accuracy: 0.9345 - lr: 0.0010 Epoch 6/100 56/55 [==============================] - ETA: 0s - loss: 0.2104 - accuracy: 0.9243 Epoch 00006: val_loss improved from 0.14179 to 0.13128, saving model to /sequentialpnd.h5 56/55 [==============================] - 5s 92ms/step - loss: 0.2104 - accuracy: 0.9243 - val_loss: 0.1313 - val_accuracy: 0.9571 - lr: 0.0010 Epoch 7/100 56/55 [==============================] - ETA: 0s - loss: 0.1865 - accuracy: 0.9362 Epoch 00007: val_loss improved from 0.13128 to 0.09596, saving model to /sequentialpnd.h5 56/55 [==============================] - 5s 94ms/step - loss: 0.1865 - accuracy: 0.9362 - val_loss: 0.0960 - val_accuracy: 0.9639 - lr: 0.0010 Epoch 8/100 56/55 [==============================] - ETA: 0s - loss: 0.2091 - accuracy: 0.9220 Epoch 00008: val_loss did not improve from 0.09596 56/55 [==============================] - 5s 86ms/step - loss: 0.2091 - accuracy: 0.9220 - val_loss: 0.1074 - val_accuracy: 0.9639 - lr: 0.0010 Epoch 9/100 56/55 [==============================] - ETA: 0s - loss: 0.1760 - accuracy: 0.9350 Epoch 00009: val_loss did not improve from 0.09596 56/55 [==============================] - 6s 100ms/step - loss: 0.1760 - accuracy: 0.9350 - val_loss: 0.1473 - val_accuracy: 0.9503 - lr: 0.0010 Epoch 10/100 56/55 [==============================] - ETA: 0s - loss: 0.1979 - accuracy: 0.9345 Epoch 00010: val_loss improved from 0.09596 to 0.09018, saving model to /sequentialpnd.h5 56/55 [==============================] - 5s 90ms/step - loss: 0.1979 - accuracy: 0.9345 - val_loss: 0.0902 - val_accuracy: 0.9639 - lr: 0.0010 Epoch 11/100 56/55 [==============================] - ETA: 0s - loss: 0.1820 - accuracy: 0.9345 Epoch 00011: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 88ms/step - loss: 0.1820 - accuracy: 0.9345 - val_loss: 0.1316 - val_accuracy: 0.9549 - lr: 0.0010 Epoch 12/100 56/55 [==============================] - ETA: 0s - loss: 0.2237 - accuracy: 0.9215 Epoch 00012: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 87ms/step - loss: 0.2237 - accuracy: 0.9215 - val_loss: 0.1839 - val_accuracy: 0.9436 - lr: 0.0010 Epoch 13/100 56/55 [==============================] - ETA: 0s - loss: 0.2095 - accuracy: 0.9254 Epoch 00013: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 85ms/step - loss: 0.2095 - accuracy: 0.9254 - val_loss: 0.1865 - val_accuracy: 0.9436 - lr: 0.0010 Epoch 14/100 56/55 [==============================] - ETA: 0s - loss: 0.2069 - accuracy: 0.9288 Epoch 00014: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 85ms/step - loss: 0.2069 - accuracy: 0.9288 - val_loss: 0.2235 - val_accuracy: 0.9345 - lr: 0.0010 Epoch 15/100 56/55 [==============================] - ETA: 0s - loss: 0.1793 - accuracy: 0.9395 Epoch 00015: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 85ms/step - loss: 0.1793 - accuracy: 0.9395 - val_loss: 0.1901 - val_accuracy: 0.9391 - lr: 0.0010 Epoch 16/100 56/55 [==============================] - ETA: 0s - loss: 0.1673 - accuracy: 0.9424 Epoch 00016: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 84ms/step - loss: 0.1673 - accuracy: 0.9424 - val_loss: 0.1236 - val_accuracy: 0.9639 - lr: 0.0010 Epoch 17/100 56/55 [==============================] - ETA: 0s - loss: 0.1743 - accuracy: 0.9390 Epoch 00017: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 84ms/step - loss: 0.1743 - accuracy: 0.9390 - val_loss: 0.1153 - val_accuracy: 0.9639 - lr: 0.0010 Epoch 18/100 56/55 [==============================] - ETA: 0s - loss: 0.1728 - accuracy: 0.9401 Epoch 00018: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 84ms/step - loss: 0.1728 - accuracy: 0.9401 - val_loss: 0.2168 - val_accuracy: 0.9323 - lr: 0.0010 Epoch 19/100 56/55 [==============================] - ETA: 0s - loss: 0.1810 - accuracy: 0.9345 Epoch 00019: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 85ms/step - loss: 0.1810 - accuracy: 0.9345 - val_loss: 0.2036 - val_accuracy: 0.9345 - lr: 0.0010 Epoch 20/100 56/55 [==============================] - ETA: 0s - loss: 0.1790 - accuracy: 0.9412 Epoch 00020: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 86ms/step - loss: 0.1790 - accuracy: 0.9412 - val_loss: 0.1702 - val_accuracy: 0.9436 - lr: 0.0010 Epoch 21/100 55/55 [============================>.] - ETA: 0s - loss: 0.1668 - accuracy: 0.9472 Epoch 00021: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 86ms/step - loss: 0.1660 - accuracy: 0.9475 - val_loss: 0.1579 - val_accuracy: 0.9436 - lr: 0.0010 Epoch 22/100 56/55 [==============================] - ETA: 0s - loss: 0.2020 - accuracy: 0.9316 Epoch 00022: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 83ms/step - loss: 0.2020 - accuracy: 0.9316 - val_loss: 0.1789 - val_accuracy: 0.9368 - lr: 0.0010 Epoch 23/100 56/55 [==============================] - ETA: 0s - loss: 0.1633 - accuracy: 0.9458 Epoch 00023: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 82ms/step - loss: 0.1633 - accuracy: 0.9458 - val_loss: 0.1218 - val_accuracy: 0.9616 - lr: 0.0010 Epoch 24/100 56/55 [==============================] - ETA: 0s - loss: 0.1654 - accuracy: 0.9486 Epoch 00024: val_loss did not improve from 0.09018 56/55 [==============================] - 5s 84ms/step - loss: 0.1654 - accuracy: 0.9486 - val_loss: 0.1342 - val_accuracy: 0.9594 - lr: 0.0010 ###Markdown Testing ###Code ## Confusion matrix plot_confusion_matrix(model, x_test, y_test) ## Learning curve plot_learning_curves(history) ## ROC AUC multiclass_roc_auc_score(x_test, y_test, model) # saving model model.save("sequential.h5") from keras.models import load_model model = load_model('./sequential.h5') ###Output _____no_output_____ ###Markdown Modeling - Using VGG19VGG-19 is a transfer learning alorithm which means its an algorithm with 16 convolutional layers that focuses on storing knowledge that can be applied to different but relaed problems. ###Code # assiging the VGG16 model m = VGG19(weights="imagenet", include_top=False, input_tensor=Input(shape=(64, 64, 3))) model = addTopModel(m, num_classes) for layer in m.layers: layer.trainable = False #data augmentation train_generator, validation_generator = process_data(x_train,y_train, x_test,y_test, batch_size) model.summary() checkpoint = ModelCheckpoint(data_dir+'modelcnd' + '.h5', monitor='val_loss', mode="min", save_best_only=True, verbose=1) earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=30, verbose=1, restore_best_weights=True) learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', patience=30, verbose=1, factor=0.8, min_lr=0.0001, mode="auto", min_delta=0.0001, cooldown=5) callbacks = [checkpoint, earlystop, learning_rate_reduction] model.compile(loss=models_loss, optimizer=models_opt, metrics=['accuracy']) history = model.fit(train_generator, epochs=epochs, callbacks=callbacks, validation_data=validation_generator, validation_steps=len(x_test) / batch_size, steps_per_epoch=len(x_train) / batch_size) ###Output Model: "model_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 64, 64, 3)] 0 _________________________________________________________________ block1_conv1 (Conv2D) (None, 64, 64, 64) 1792 _________________________________________________________________ block1_conv2 (Conv2D) (None, 64, 64, 64) 36928 _________________________________________________________________ block1_pool (MaxPooling2D) (None, 32, 32, 64) 0 _________________________________________________________________ block2_conv1 (Conv2D) (None, 32, 32, 128) 73856 _________________________________________________________________ block2_conv2 (Conv2D) (None, 32, 32, 128) 147584 _________________________________________________________________ block2_pool (MaxPooling2D) (None, 16, 16, 128) 0 _________________________________________________________________ block3_conv1 (Conv2D) (None, 16, 16, 256) 295168 _________________________________________________________________ block3_conv2 (Conv2D) (None, 16, 16, 256) 590080 _________________________________________________________________ block3_conv3 (Conv2D) (None, 16, 16, 256) 590080 _________________________________________________________________ block3_conv4 (Conv2D) (None, 16, 16, 256) 590080 _________________________________________________________________ block3_pool (MaxPooling2D) (None, 8, 8, 256) 0 _________________________________________________________________ block4_conv1 (Conv2D) (None, 8, 8, 512) 1180160 _________________________________________________________________ block4_conv2 (Conv2D) (None, 8, 8, 512) 2359808 _________________________________________________________________ block4_conv3 (Conv2D) (None, 8, 8, 512) 2359808 _________________________________________________________________ block4_conv4 (Conv2D) (None, 8, 8, 512) 2359808 _________________________________________________________________ block4_pool (MaxPooling2D) (None, 4, 4, 512) 0 _________________________________________________________________ block5_conv1 (Conv2D) (None, 4, 4, 512) 2359808 _________________________________________________________________ block5_conv2 (Conv2D) (None, 4, 4, 512) 2359808 _________________________________________________________________ block5_conv3 (Conv2D) (None, 4, 4, 512) 2359808 _________________________________________________________________ block5_conv4 (Conv2D) (None, 4, 4, 512) 2359808 _________________________________________________________________ block5_pool (MaxPooling2D) (None, 2, 2, 512) 0 _________________________________________________________________ flatten (Flatten) (None, 2048) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 1049088 _________________________________________________________________ dense_2 (Dense) (None, 2) 1026 ================================================================= Total params: 21,074,498 Trainable params: 1,050,114 Non-trainable params: 20,024,384 _________________________________________________________________ Epoch 1/100 56/55 [==============================] - ETA: 0s - loss: 0.2208 - accuracy: 0.9113 Epoch 00001: val_loss improved from inf to 0.10050, saving model to /modelcnd.h5 56/55 [==============================] - 71s 1s/step - loss: 0.2208 - accuracy: 0.9113 - val_loss: 0.1005 - val_accuracy: 0.9549 - lr: 0.0010 Epoch 2/100 56/55 [==============================] - ETA: 0s - loss: 0.1331 - accuracy: 0.9463 Epoch 00002: val_loss improved from 0.10050 to 0.07233, saving model to /modelcnd.h5 56/55 [==============================] - 82s 1s/step - loss: 0.1331 - accuracy: 0.9463 - val_loss: 0.0723 - val_accuracy: 0.9729 - lr: 0.0010 Epoch 3/100 56/55 [==============================] - ETA: 0s - loss: 0.0985 - accuracy: 0.9605 Epoch 00003: val_loss improved from 0.07233 to 0.05439, saving model to /modelcnd.h5 56/55 [==============================] - 74s 1s/step - loss: 0.0985 - accuracy: 0.9605 - val_loss: 0.0544 - val_accuracy: 0.9865 - lr: 0.0010 Epoch 4/100 56/55 [==============================] - ETA: 0s - loss: 0.0814 - accuracy: 0.9712 Epoch 00004: val_loss improved from 0.05439 to 0.05357, saving model to /modelcnd.h5 56/55 [==============================] - 78s 1s/step - loss: 0.0814 - accuracy: 0.9712 - val_loss: 0.0536 - val_accuracy: 0.9865 - lr: 0.0010 Epoch 5/100 56/55 [==============================] - ETA: 0s - loss: 0.0871 - accuracy: 0.9661 Epoch 00005: val_loss did not improve from 0.05357 56/55 [==============================] - 70s 1s/step - loss: 0.0871 - accuracy: 0.9661 - val_loss: 0.0620 - val_accuracy: 0.9797 - lr: 0.0010 Epoch 6/100 56/55 [==============================] - ETA: 0s - loss: 0.0620 - accuracy: 0.9802 Epoch 00006: val_loss did not improve from 0.05357 56/55 [==============================] - 69s 1s/step - loss: 0.0620 - accuracy: 0.9802 - val_loss: 0.0908 - val_accuracy: 0.9661 - lr: 0.0010 Epoch 7/100 56/55 [==============================] - ETA: 0s - loss: 0.0789 - accuracy: 0.9689 Epoch 00007: val_loss improved from 0.05357 to 0.04287, saving model to /modelcnd.h5 56/55 [==============================] - 72s 1s/step - loss: 0.0789 - accuracy: 0.9689 - val_loss: 0.0429 - val_accuracy: 0.9797 - lr: 0.0010 Epoch 8/100 56/55 [==============================] - ETA: 0s - loss: 0.0739 - accuracy: 0.9729 Epoch 00008: val_loss did not improve from 0.04287 56/55 [==============================] - 72s 1s/step - loss: 0.0739 - accuracy: 0.9729 - val_loss: 0.0498 - val_accuracy: 0.9819 - lr: 0.0010 Epoch 9/100 56/55 [==============================] - ETA: 0s - loss: 0.0833 - accuracy: 0.9672 Epoch 00009: val_loss did not improve from 0.04287 56/55 [==============================] - 82s 1s/step - loss: 0.0833 - accuracy: 0.9672 - val_loss: 0.0467 - val_accuracy: 0.9842 - lr: 0.0010 Epoch 10/100 56/55 [==============================] - ETA: 0s - loss: 0.0737 - accuracy: 0.9718 Epoch 00010: val_loss did not improve from 0.04287 56/55 [==============================] - 76s 1s/step - loss: 0.0737 - accuracy: 0.9718 - val_loss: 0.0523 - val_accuracy: 0.9842 - lr: 0.0010 Epoch 11/100 56/55 [==============================] - ETA: 0s - loss: 0.0754 - accuracy: 0.9729 Epoch 00011: val_loss improved from 0.04287 to 0.03879, saving model to /modelcnd.h5 56/55 [==============================] - 78s 1s/step - loss: 0.0754 - accuracy: 0.9729 - val_loss: 0.0388 - val_accuracy: 0.9774 - lr: 0.0010 Epoch 12/100 56/55 [==============================] - ETA: 0s - loss: 0.0651 - accuracy: 0.9763 Epoch 00012: val_loss did not improve from 0.03879 56/55 [==============================] - 74s 1s/step - loss: 0.0651 - accuracy: 0.9763 - val_loss: 0.0953 - val_accuracy: 0.9684 - lr: 0.0010 Epoch 13/100 56/55 [==============================] - ETA: 0s - loss: 0.0840 - accuracy: 0.9689 Epoch 00013: val_loss did not improve from 0.03879 56/55 [==============================] - 72s 1s/step - loss: 0.0840 - accuracy: 0.9689 - val_loss: 0.0791 - val_accuracy: 0.9684 - lr: 0.0010 Epoch 14/100 56/55 [==============================] - ETA: 0s - loss: 0.0676 - accuracy: 0.9757 Epoch 00014: val_loss did not improve from 0.03879 56/55 [==============================] - 70s 1s/step - loss: 0.0676 - accuracy: 0.9757 - val_loss: 0.0503 - val_accuracy: 0.9842 - lr: 0.0010 Epoch 15/100 56/55 [==============================] - ETA: 0s - loss: 0.0532 - accuracy: 0.9836 Epoch 00015: val_loss did not improve from 0.03879 56/55 [==============================] - 69s 1s/step - loss: 0.0532 - accuracy: 0.9836 - val_loss: 0.0619 - val_accuracy: 0.9797 - lr: 0.0010 ###Markdown Testing ###Code ## Confusion matrix plot_confusion_matrix(model, x_test, y_test) ## Learning curve plot_learning_curves(history) ## ROC AUC multiclass_roc_auc_score(x_test, y_test, model) # saving model model.save("modelcnd.h5") ###Output _____no_output_____
examples/tutorial/opacity_exomol.ipynb
###Markdown Computing CO cross section using ExoMol This tutorial demonstrates how to compute the opacity of CO using ExoMol step by step. ###Code from exojax.spec import xsection from exojax.spec import SijT, doppler_sigma, gamma_natural from exojax.spec.exomol import gamma_exomol from exojax.spec import moldb import numpy as np import seaborn as sns import matplotlib.pyplot as plt plt.style.use('bmh') ###Output /home/kawahara/anaconda3/lib/python3.7/site-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead. import pandas.util.testing as tm ###Markdown First of all, set a wavenumber bin in the unit of wavenumber (cm-1).Here we set the wavenumber range as $1000 \le \nu \le 10000$ (1/cm) with the resolution of 0.01 (1/cm). We call moldb instance with the path of exomole files. ###Code # Setting wavenumber bins and loading HITRAN database nus=np.linspace(1000.0,10000.0,900000,dtype=np.float64) #cm-1 emf='/home/kawahara/exojax/data/CO/12C-16O/Li2015' mdbCO=moldb.MdbExomol(emf,nus) ###Output Background atmosphere: H2 Reading transition file Broadening code level= a0 default broadening parameters are used for 71 J lower states in 152 states ###Markdown Define molecular weight of CO ($\sim 12+16=28$), temperature (K), and pressure (bar).Also, we here assume the 100 % CO atmosphere, i.e. the partial pressure = pressure. ###Code Mmol=28.010446441149536 # molecular weight Tfix=1000.0 # we assume T=1000K Pfix=1.e-3 # we compute P=1.e-3 bar ###Output _____no_output_____ ###Markdown partition function ratio $q(T)$ is defined by $q(T) = Q(T)/Q(T_{ref})$; $T_{ref}$=296 KHere, we use the partition function from the interpolation of partition function ###Code qt=mdbCO.qr_interp(Tfix) ###Output _____no_output_____ ###Markdown Let us compute the line strength S(T) at temperature of Tfix.$S (T;s_0,\nu_0,E_l,q(T)) = S_0 \frac{Q(T_{ref})}{Q(T)} \frac{e^{- h c E_l /k_B T}}{e^{- h c E_l /k_B T_{ref}}} \frac{1- e^{- h c \nu /k_B T}}{1-e^{- h c \nu /k_B T_{ref}}}= q_r(T)^{-1} e^{ s_0 - c_2 E_l (T^{-1} - T_{ref}^{-1})} \frac{1- e^{- c_2 \nu_0/ T}}{1-e^{- c_2 \nu_0/T_{ref}}}$$s_0=\log_{e} S_0$ : logsij0$\nu_0$: nu_lines$E_l$ : elowerWhy the input is $s_0 = \log_{e} S_0$ instead of $S_0$ in SijT? This is because the direct value of $S_0$ is quite small and we need to use float32 for jax. ###Code Sij=SijT(Tfix,mdbCO.logsij0,mdbCO.nu_lines,mdbCO.elower,qt) ###Output _____no_output_____ ###Markdown Then, compute the Lorentz gamma factor (pressure+natural broadening)$\gamma_L = \gamma^p_L + \gamma^n_L$where the pressure broadning $\gamma^p_L = \alpha_{ref} ( T/T_{ref} )^{-n_{texp}} ( P/P_{ref}), $and the natural broadening$\gamma^n_L = \frac{A}{4 \pi c}$ ###Code gammaL = gamma_exomol(Pfix,Tfix,mdbCO.n_Texp,mdbCO.alpha_ref)\ + gamma_natural(mdbCO.A) gamma_exomol(Pfix,Tfix,mdbCO.n_Texp,mdbCO.alpha_ref) fig=plt.figure() fig.add_subplot(211) plt.plot(mdbCO.jlower,mdbCO.n_Texp,".") fig.add_subplot(212) plt.plot(mdbCO.jlower,mdbCO.alpha_ref,".") ###Output _____no_output_____ ###Markdown Thermal broadening$\sigma_D^{t} = \sqrt{\frac{k_B T}{M m_u}} \frac{\nu_0}{c}$ ###Code # thermal doppler sigma sigmaD=doppler_sigma(mdbCO.nu_lines,Tfix,Mmol) ###Output _____no_output_____ ###Markdown Then, the line center... ###Code #line center nu0=mdbCO.nu_lines ###Output _____no_output_____ ###Markdown Although it depends on your GPU, you might need to devide the computation into multiple loops because of the limitation of the GPU memory. Here we assume 30MB for GPU memory (not exactly, memory size for numatrix). ###Code xsv=xsection(nus,nu0,sigmaD,gammaL,Sij,memory_size=30) #use 30MB GPU MEMORY for numax ###Output 100%|██████████| 8257/8257 [01:37<00:00, 84.45it/s] ###Markdown Plot it! ###Code fig=plt.figure(figsize=(10,3)) ax=fig.add_subplot(111) plt.plot(nus,xsv,lw=0.1,label="exojax") plt.yscale("log") plt.xlabel("wavenumber ($cm^{-1}$)") plt.ylabel("cross section ($cm^{2}$)") plt.legend(loc="upper left") plt.savefig("co_exomol.pdf", bbox_inches="tight", pad_inches=0.0) plt.show() fig=plt.figure(figsize=(10,3)) ax=fig.add_subplot(111) plt.plot(1.e8/nus,xsv,lw=1,label="exojax") plt.yscale("log") plt.xlabel("wavelength ($\AA$)") plt.ylabel("cross section ($cm^{2}$)") plt.xlim(22985.,23025) plt.legend(loc="upper left") plt.savefig("co_exomol.pdf", bbox_inches="tight", pad_inches=0.0) plt.show() ###Output _____no_output_____ ###Markdown Important Note Use float64 for wavenumber bin and line center.Below, we see the difference of opacity between float64 case and float 32. ###Code xsv_32=xsection(np.float32(nus),np.float32(nu0),sigmaD,gammaL,Sij,memory_size=30) fig=plt.figure(figsize=(10,6)) ax=fig.add_subplot(211) plt.plot(1.e8/nus,xsv,".",lw=1,label="64",markersize=1) plt.plot(1.e8/nus,xsv_32,".",lw=1,label="32",markersize=1) plt.xlim(22985.,23025) plt.yscale("log") plt.ylabel("xsv $cm^{2}$") ax=fig.add_subplot(212) plt.plot(1.e8/nus,(xsv_32-xsv)/xsv,lw=1,label="difference") plt.xlabel("wavelength ($\AA$)") plt.ylabel("Difference") plt.xlim(22985.,23025) plt.legend(loc="upper left") plt.show() ###Output _____no_output_____ ###Markdown Computing CO cross section using ExoMol This tutorial demonstrates how to compute the opacity of CO using ExoMol step by step. ###Code from exojax.spec import xsection from exojax.spec import SijT, doppler_sigma, gamma_natural from exojax.spec.exomol import gamma_exomol from exojax.spec import moldb import numpy as np import seaborn as sns import matplotlib.pyplot as plt plt.style.use('bmh') ###Output /home/kawahara/anaconda3/lib/python3.7/site-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead. import pandas.util.testing as tm ###Markdown First of all, set a wavenumber bin in the unit of wavenumber (cm-1).Here we set the wavenumber range as $1000 \le \nu \le 10000$ (1/cm) with the resolution of 0.01 (1/cm). We call moldb instance with the path of exomole files. ###Code # Setting wavenumber bins and loading HITRAN database nus=np.linspace(1000.0,10000.0,900000,dtype=np.float64) #cm-1 emf='/home/kawahara/exojax/data/CO/12C-16O/Li2015' mdbCO=moldb.MdbExomol(emf,nus) ###Output Background atmosphere: H2 Reading transition file Broadening code level= a0 default broadening parameters are used for 71 J lower states in 152 states ###Markdown Define molecular weight of CO ($\sim 12+16=28$), temperature (K), and pressure (bar).Also, we here assume the 100 % CO atmosphere, i.e. the partial pressure = pressure. ###Code Mmol=28.010446441149536 # molecular weight Tfix=1000.0 # we assume T=1000K Pfix=1.e-3 # we compute P=1.e-3 bar ###Output _____no_output_____ ###Markdown partition function ratio $q(T)$ is defined by $q(T) = Q(T)/Q(T_{ref})$; $T_{ref}$=296 KHere, we use the partition function from the interpolation of partition function ###Code qt=mdbCO.qr_interp(Tfix) ###Output _____no_output_____ ###Markdown Let us compute the line strength S(T) at temperature of Tfix.$S (T;s_0,\nu_0,E_l,q(T)) = S_0 \frac{Q(T_{ref})}{Q(T)} \frac{e^{- h c E_l /k_B T}}{e^{- h c E_l /k_B T_{ref}}} \frac{1- e^{- h c \nu /k_B T}}{1-e^{- h c \nu /k_B T_{ref}}}= q_r(T)^{-1} e^{ s_0 - c_2 E_l (T^{-1} - T_{ref}^{-1})} \frac{1- e^{- c_2 \nu_0/ T}}{1-e^{- c_2 \nu_0/T_{ref}}}$$s_0=\log_{e} S_0$ : logsij0$\nu_0$: nu_lines$E_l$ : elowerWhy the input is $s_0 = \log_{e} S_0$ instead of $S_0$ in SijT? This is because the direct value of $S_0$ is quite small and we need to use float32 for jax. ###Code Sij=SijT(Tfix,mdbCO.logsij0,mdbCO.nu_lines,mdbCO.elower,qt) ###Output _____no_output_____ ###Markdown Then, compute the Lorentz gamma factor (pressure+natural broadening)$\gamma_L = \gamma^p_L + \gamma^n_L$where the pressure broadning $\gamma^p_L = \alpha_{ref} ( T/T_{ref} )^{-n_{texp}} ( P/P_{ref}), $and the natural broadening$\gamma^n_L = \frac{A}{4 \pi c}$ ###Code gammaL = gamma_exomol(Pfix,Tfix,mdbCO.n_Texp,mdbCO.alpha_ref)\ + gamma_natural(mdbCO.A) gamma_exomol(Pfix,Tfix,mdbCO.n_Texp,mdbCO.alpha_ref) fig=plt.figure() fig.add_subplot(211) plt.plot(mdbCO.jlower,mdbCO.n_Texp,".") fig.add_subplot(212) plt.plot(mdbCO.jlower,mdbCO.alpha_ref,".") ###Output _____no_output_____ ###Markdown Thermal broadening$\sigma_D^{t} = \sqrt{\frac{k_B T}{M m_u}} \frac{\nu_0}{c}$ ###Code # thermal doppler sigma sigmaD=doppler_sigma(mdbCO.nu_lines,Tfix,Mmol) ###Output _____no_output_____ ###Markdown Then, the line center... ###Code #line center nu0=mdbCO.nu_lines ###Output _____no_output_____ ###Markdown Although it depends on your GPU, you might need to devide the computation into multiple loops because of the limitation of the GPU memory. Here we assume 30MB for GPU memory (not exactly, memory size for numatrix). ###Code xsv=xsection(nus,nu0,sigmaD,gammaL,Sij,memory_size=30) #use 30MB GPU MEMORY for numax ###Output 100%|██████████| 8257/8257 [01:37<00:00, 84.45it/s] ###Markdown Plot it! ###Code fig=plt.figure(figsize=(10,3)) ax=fig.add_subplot(111) plt.plot(nus,xsv,lw=0.1,label="exojax") plt.yscale("log") plt.xlabel("wavenumber ($cm^{-1}$)") plt.ylabel("cross section ($cm^{2}$)") plt.legend(loc="upper left") plt.savefig("co_exomol.pdf", bbox_inches="tight", pad_inches=0.0) plt.show() fig=plt.figure(figsize=(10,3)) ax=fig.add_subplot(111) plt.plot(1.e8/nus,xsv,lw=1,label="exojax") plt.yscale("log") plt.xlabel("wavelength ($\AA$)") plt.ylabel("cross section ($cm^{2}$)") plt.xlim(22985.,23025) plt.legend(loc="upper left") plt.savefig("co_exomol.pdf", bbox_inches="tight", pad_inches=0.0) plt.show() ###Output _____no_output_____ ###Markdown Important Note Use float64 for wavenumber bin and line center.Below, we see the difference of opacity between float64 case and float 32. ###Code xsv_32=xsection(np.float32(nus),np.float32(nu0),sigmaD,gammaL,Sij,memory_size=30) fig=plt.figure(figsize=(10,6)) ax=fig.add_subplot(211) plt.plot(1.e8/nus,xsv,".",lw=1,label="64",markersize=1) plt.plot(1.e8/nus,xsv_32,".",lw=1,label="32",markersize=1) plt.xlim(22985.,23025) plt.yscale("log") plt.ylabel("xsv $cm^{2}$") ax=fig.add_subplot(212) plt.plot(1.e8/nus,(xsv_32-xsv)/xsv,lw=1,label="difference") plt.xlabel("wavelength ($\AA$)") plt.ylabel("Difference") plt.xlim(22985.,23025) plt.legend(loc="upper left") plt.show() ###Output _____no_output_____
autonormalize/demos/AutoNormalize + FeatureTools Demo.ipynb
###Markdown Using AutoNormalize with FeatureTools and Compose-ML In this demo we will use AutoNormalize to create our `entityset` from a mock dataset with a single table. We will use composeml and featuretools to generate labels and features, and then create a machine learning model for predicting one hour in advance whether customers will spend over $1200 within the next hour of transactions. ###Code %matplotlib inline from featuretools.autonormalize import autonormalize as an import composeml as cp import featuretools as ft import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report ###Output _____no_output_____ ###Markdown Load Data ###Code transaction_df = ft.demo.load_mock_customer(n_customers=80, n_products=50, n_sessions=200, n_transactions=10000, return_single_table=True) transaction_df.head(3) ###Output _____no_output_____ ###Markdown Generate Labels We create our labeling function, and use compose-ml to create our label maker. Using this, we extract our labels. ###Code def total_spent(df_slice): label = df_slice["amount"].sum() return label label_maker = cp.LabelMaker(target_entity='customer_id', time_index='transaction_time', labeling_function=total_spent, window_size='1h') labels = label_maker.search(transaction_df, minimum_data='2h', num_examples_per_instance=50, gap='2min') labels.head(4) ###Output Elapsed: 00:06 | Remaining: 00:00 | Progress: 100%|██████████████████| customer_id: 75/75 ###Markdown We then transform the labels, to have a threshold of $1200, and shift label times an hour earlier for predicting in advance. ###Code labels = labels.threshold(1200) labels = labels.apply_lead('1h') labels.head(4) labels.describe() ###Output Label Distribution ------------------ True 1579 False 584 Total: 2163 Settings -------- num_examples_per_instance 50 minimum_data 2h window_size 1h gap 2min Transforms ---------- 1. threshold - value: 1200 2. apply_lead - value: 1h ###Markdown Create an `EntitySet` with AutoNormalize To create an `EntitySet` with AutoNormalize we just call `auto_entityset()` on our dataframe. AutoNormalize then automatically detects the dependencies within the data, and normalizes the dataframe accordingly. This gives us an automatically normalized entityset! ###Code es = an.auto_entityset(transaction_df, accuracy=1, name="transactions", time_index='transaction_time') es.add_last_time_indexes() print(es) ###Output 100%|██████████| 10/10 [00:01<00:00, 7.11it/s] ###Markdown It's really that simple. The plot shows you how the library normalized `transaction_df`. ###Code es.plot() ###Output _____no_output_____ ###Markdown Create Feature Matrix Now we generate features using `dfs()`. ###Code feature_matrix, features_defs = ft.dfs( entityset=es, target_entity='customer_id', cutoff_time=labels, cutoff_time_in_index=True, verbose=True, ) features_defs[:20] ###Output Built 73 features Elapsed: 08:15 | Remaining: 00:00 | Progress: 100%|██████████| Calculated: 11/11 chunks ###Markdown Machine Learning Now we preprocess our features, and split the features and corresponding labels into training and testing sets. ###Code y = feature_matrix.pop(labels.name) x = feature_matrix.fillna(0) x, features_enc = ft.encode_features(x, features_defs) x_train, x_test, y_train, y_test = train_test_split( x, y, train_size=.8, test_size=.2, random_state=0, ) ###Output _____no_output_____ ###Markdown Now, we train a random forest classifer on the training set, and then test the models performance by evaluating predictions on the testing set. ###Code clf = RandomForestClassifier(n_estimators=10, random_state=0) clf.fit(x_train, y_train) y_hat = clf.predict(x_test) print(classification_report(y_test, y_hat)) ###Output precision recall f1-score support False 0.67 0.06 0.11 129 True 0.71 0.99 0.83 304 accuracy 0.71 433 macro avg 0.69 0.52 0.47 433 weighted avg 0.70 0.71 0.61 433 ###Markdown This plot is based on scores obtained by the model to illustrate which features are considered important for predictions. ###Code feature_importances = zip(x_train.columns, clf.feature_importances_) feature_importances = pd.Series(dict(feature_importances)) feature_importances = feature_importances.rename_axis('Features') feature_importances = feature_importances.sort_values() top_features = feature_importances.tail(40) plot = top_features.plot(kind='barh', figsize=(5, 12), color='#054571') plot.set_title('Feature Importances') plot.set_xlabel('Scores'); ###Output _____no_output_____
test/Make_test_dataset.ipynb
###Markdown Make some genes ###Code gene_1_list = make_gene_exon_intron_list([100,20,100,20,100]) gene_2_list = make_gene_exon_intron_list([50,20,50]) gene_1_transcript_1_sequence = gene_1_list[0] + gene_1_list[2] gene_1_transcript_2_sequence = gene_1_list[2] + gene_1_list[4] gene_2_transcript_1_sequence = gene_2_list[0] + gene_2_list[2] ###Output _____no_output_____ ###Markdown We make a 200 bp genome sequence, with 20 bases of random nucleotides on either side of the gene. The sequence is also written as a fasta file. ###Code genome_sequence = make_sequence(20) + "".join(gene_1_list) + make_sequence(20) + "".join(gene_2_list) + make_sequence(20) SeqIO.write(SeqRecord.SeqRecord(seq = Seq.Seq(genome_sequence), id = 'test', description = ''), format='fasta', handle = './STAR_GENOME/test.fa') ###Output _____no_output_____ ###Markdown Make a sample gtf and write it to file ###Code import csv list_for_gft_df = [['test', 'FOO', 'gene', 21, 360, '.', '+', '.', 'gene_id "ENSG_test1";']] list_for_gft_df.append(['test', 'FOO', 'transcript', 21, 240, '.', '+', '.', 'gene_id "ENSG_test1"; transcript_id "ENST_test1_1";']) list_for_gft_df.append(['test', 'FOO', 'exon', 21, 120, '.', '+', '.', 'gene_id "ENSG_test1"; transcript_id "ENST_test1_1";']) list_for_gft_df.append(['test', 'FOO', 'exon', 141, 240, '.', '+', '.', 'gene_id "ENSG_test1"; transcript_id "ENST_test1_1";']) list_for_gft_df.append(['test', 'FOO', 'transcript', 141, 360, '.', '+', '.', 'gene_id "ENSG_test1"; transcript_id "ENST_test1_2";']) list_for_gft_df.append(['test', 'FOO', 'exon', 141, 240, '.', '+', '.', 'gene_id "ENSG_test1"; transcript_id "ENST_test1_2";']) list_for_gft_df.append(['test', 'FOO', 'exon', 261, 360, '.', '+', '.', 'gene_id "ENSG_test1"; transcript_id "ENST_test1_2";']) list_for_gft_df.append(['test', 'FOO', 'gene', 381, 500, '.', '+', '.', 'gene_id "ENSG_test2";']) list_for_gft_df.append(['test', 'FOO', 'transcript', 381, 500, '.', '+', '.', 'gene_id "ENSG_test2"; transcript_id "ENST_test2_1";']) list_for_gft_df.append(['test', 'FOO', 'exon', 381, 430, '.', '+', '.', 'gene_id "ENSG_test2"; transcript_id "ENST_test2_1";']) list_for_gft_df.append(['test', 'FOO', 'exon', 451, 500, '.', '+', '.', 'gene_id "ENSG_test2"; transcript_id "ENST_test2_1";']) pd.DataFrame(list_for_gft_df).to_csv("STAR_GENOME/test.gtf", sep = "\t", header = False, index = False, quoting = csv.QUOTE_NONE)#quotechar = '')#, doublequote = False) ###Output _____no_output_____ ###Markdown Make a STAR genome index ###Code ! STAR --runThreadN 1 --runMode genomeGenerate --genomeSAindexNbases 10 --genomeDir ./STAR_GENOME --genomeFastaFiles ./STAR_GENOME/test.fa --sjdbGTFfile ./STAR_GENOME/test.gtf --sjdbOverhang 35 def mutate_dna(dna_str, nm = 1): inds_list = [random.randrange(0,len(dna_str)) for _i in 'a'*nm] new_seq_list = list(dna_str) for _ind in inds_list: current_base = dna_str[_ind] new_base = bases[random.randrange(0,4)] while new_base == current_base: new_base = bases[random.randrange(0,4)] new_seq_list[_ind] = new_base return ''.join(new_seq_list) ###Output _____no_output_____ ###Markdown Make some reads and write them to fastq files ###Code def make_paired_reads_and_write_to_fastq_file(cell_barcode, umi, transcript_seq, read1_fh, read2_fh, read_length = 70, bc_nm = 1, umi_nm = 1): read_id = 'TESTREAD_' + ''.join([random.choice(string.ascii_uppercase + string.digits) for _ind in range(6)]) read_1_str = mutate_dna(cell_barcode, bc_nm) + mutate_dna(umi, umi_nm) + 'TTTTTTTTTT' r1_seqrec = SeqRecord.SeqRecord(id = read_id, description = '', seq = Seq.Seq(read_1_str)) r1_seqrec.letter_annotations['phred_quality'] = [30 for i in range(len(read_1_str))] SeqIO.write(r1_seqrec, format = 'fastq', handle = read1_fh) start_ind = random.randint(0, len(transcript_seq) - read_length) read_2_str = transcript_seq[start_ind:(start_ind + read_length)] r2_seqrec = SeqRecord.SeqRecord(id = read_id, description = '', seq = Seq.Seq(read_2_str)) r2_seqrec.letter_annotations['phred_quality'] = [30 for i in range(read_length)] SeqIO.write(r2_seqrec, format = 'fastq', handle = read2_fh) cell_1_barcode = 'AGATCG' cell_2_barcode = 'CGTAGA' umi_1 = 'ATCCG' umi_2 = 'TAGGT' umi_3 = 'CCTAA' ###Output _____no_output_____ ###Markdown The follwing counts should result: ENSG_test1 ENSG_test2 __no_feature __ambiguous __too_low_aQual __not_aligned __alignment_not_uniquetest_ROW10_R2_umi_labelledAligned 3 2 0 0 0 0 0test_ROW20_R2_umi_labelledAligned 2 3 0 0 0 0 0 ###Code r1_fh = open("./FASTQ/test_R1.fastq", 'w') r2_fh = open("./FASTQ/test_R2.fastq", 'w') #cell 1 make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_1, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_1, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_1, gene_1_transcript_2_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_1, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_1, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_2, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_2, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_2, gene_1_transcript_2_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_3, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_3, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_3, gene_1_transcript_2_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_3, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_1_barcode, umi_3, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) #cell 2 make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_3, gene_1_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_1, gene_1_transcript_2_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_1, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_2, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) make_paired_reads_and_write_to_fastq_file(cell_2_barcode, umi_3, gene_2_transcript_1_sequence, r1_fh, r2_fh, umi_nm = 0) r1_fh.close() r2_fh.close() import pysam bam_obj = pysam.AlignmentFile("/home/rob/Dropbox/python_package_dev/fluidigm_800_chip_processor/test/test_out/test_Seq/test_ROW10_R2_umi_labelledAligned.sortedByCoord.out_tagged.bam", 'r') for _read in bam_obj: _read.set_tag("GN", ",".join(list(set(_read.get_tag('GN').split(','))))) print _read 'foo,bar'.split(',') ###Output _____no_output_____
doc/source/user_guide/Numba.ipynb
###Markdown (numba_for_arviz)= Numba - an overview [Numba](https://numba.pydata.org/numba-doc/latest/index.html) is a just-in-time compiler for Python that works best on code that uses NumPy arrays and functions, and loops.ArviZ includes {ref}`Numba as an optional dependency ` and a number of functions have been included in `utils.py` for systems in which Numba is pre-installed. Additional functionality, {class}`arviz.Numba`, of disabling/re-enabling numba for systems that have Numba installed has also been included. A simple example to display the effectiveness of Numba ###Code import arviz as az import numpy as np import timeit from arviz.utils import conditional_jit, Numba from arviz.stats.diagnostics import ks_summary data = np.random.randn(1000000) def variance(data, ddof=0): # Method to calculate variance without using numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance(data, ddof=1) @conditional_jit def variance_jit(data, ddof=0): # Calculating variance with numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance_jit(data, ddof=1) ###Output 1.54 ms ± 383 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown That is almost 300 times faster!! Let's compare this to NumPy ###Code %timeit np.var(data, ddof=1) ###Output 8.68 ms ± 435 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ###Markdown In certain scenarios, Numba can even outperform NumPy! Numba wihin ArviZLet's see Numba's effect on a few of ArviZ functions ###Code summary_data = np.random.randn(1000, 100, 10) school = az.load_arviz_data("centered_eight").posterior["mu"].values ###Output _____no_output_____ ###Markdown The methods of the {class}`~arviz.Numba` class can be used to enable or disable numba. The attribute `numba_flag` indicates whether numba is enabled within ArviZ or not. ###Code Numba.disable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) Numba.enable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) ###Output 3.97 ms ± 574 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown Numba - an overview Numba is a just-in-time compiler for Python that works best on code that uses NumPy arrays and functions, and loops.ArviZ includes Numba as an optional dependency and a number of functions have been included in **utils.py** for systems in which Numba is pre-installed. An additional functionality of disabling/re-enabling numba for systems which have numba installed has also been included. A simple example to display the effectiveness of Numba ###Code import arviz as az import numpy as np import timeit from arviz.utils import conditional_jit, Numba from arviz.stats.diagnostics import ks_summary data = np.random.randn(1000000) def variance(data, ddof=0): # Method to calculate variance without using numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance(data, ddof=1) @conditional_jit def variance_jit(data, ddof=0): # Calculating variance with numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance_jit(data, ddof=1) ###Output 1.54 ms ± 383 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown **That is almost 300 times faster!! Let's compare this to numpy** ###Code %timeit np.var(data, ddof=1) ###Output 8.68 ms ± 435 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ###Markdown **In certain scenarios, Numba outperforms numpy!** **Let's see Numba's effect on a few of ArviZ functions** ###Code summary_data = np.random.randn(1000, 100, 10) school = az.load_arviz_data("centered_eight").posterior["mu"].values Numba.disable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) Numba.enable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) ###Output 3.97 ms ± 574 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown Numba - an overview Numba is a just-in-time compiler for Python that works best on code that uses NumPy arrays and functions, and loops.ArviZ includes Numba as an optional dependency and a number of functions have been included in **utils.py** for systems in which Numba is pre-installed. An additional functionality of disabling/re-enabling numba for systems which have numba installed has also been included. A simple example to display the effectiveness of Numba ###Code import arviz as az import numpy as np import timeit from arviz.utils import conditional_jit, Numba from arviz.stats import geweke from arviz.stats.diagnostics import ks_summary data = np.random.randn(1000000) def variance(data, ddof=0): # Method to calculate variance without using numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance(data, ddof=1) @conditional_jit def variance_jit(data, ddof=0): # Calculating variance with numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance_jit(data, ddof=1) ###Output 1.54 ms ± 383 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown **That is almost 300 times faster!! Let's compare this to numpy** ###Code %timeit np.var(data, ddof=1) ###Output 8.68 ms ± 435 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ###Markdown **In certain scenarios, Numba outperforms numpy!** **Let's see Numba's effect on a few of ArviZ functions** ###Code summary_data = np.random.randn(1000, 100, 10) school = az.load_arviz_data("centered_eight").posterior["mu"].values Numba.disable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) Numba.enable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) ###Output 3.97 ms ± 574 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown (numba_for_arviz)= Numba - an overview [Numba](https://numba.pydata.org/numba-doc/latest/index.html) is a just-in-time compiler for Python that works best on code that uses NumPy arrays and functions, and loops.ArviZ includes {ref}`Numba as an optional dependency ` and a number of functions have been included in `utils.py` for systems in which Numba is pre-installed. Additional functionality, {class}`arviz.Numba`, of disabling/re-enabling numba for systems that have Numba installed has also been included. A simple example to display the effectiveness of Numba ###Code import arviz as az import numpy as np import timeit from arviz.utils import conditional_jit, Numba from arviz.stats.diagnostics import ks_summary data = np.random.randn(1000000) def variance(data, ddof=0): # Method to calculate variance without using numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance(data, ddof=1) @conditional_jit def variance_jit(data, ddof=0): # Calculating variance with numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance_jit(data, ddof=1) ###Output 1.54 ms ± 383 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown That is almost 300 times faster!! Let's compare this to NumPy ###Code %timeit np.var(data, ddof=1) ###Output 8.68 ms ± 435 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ###Markdown In certain scenarios, Numba can even outperform NumPy! Numba within ArviZLet's see Numba's effect on a few of ArviZ functions ###Code summary_data = np.random.randn(1000, 100, 10) school = az.load_arviz_data("centered_eight").posterior["mu"].values ###Output _____no_output_____ ###Markdown The methods of the {class}`~arviz.Numba` class can be used to enable or disable numba. The attribute `numba_flag` indicates whether numba is enabled within ArviZ or not. ###Code Numba.disable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) Numba.enable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) ###Output 3.97 ms ± 574 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown Numba - an overview [Numba](https://numba.pydata.org/numba-doc/latest/index.html) is a just-in-time compiler for Python that works best on code that uses NumPy arrays and functions, and loops.ArviZ includes {ref}`Numba as an optional dependency ` and a number of functions have been included in **utils.py** for systems in which Numba is pre-installed. Additional functionality of disabling/re-enabling numba for systems that have Numba installed has also been included. A simple example to display the effectiveness of Numba ###Code import arviz as az import numpy as np import timeit from arviz.utils import conditional_jit, Numba from arviz.stats.diagnostics import ks_summary data = np.random.randn(1000000) def variance(data, ddof=0): # Method to calculate variance without using numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance(data, ddof=1) @conditional_jit def variance_jit(data, ddof=0): # Calculating variance with numba a_a, b_b = 0, 0 for i in data: a_a = a_a + i b_b = b_b + i * i var = b_b / (len(data)) - ((a_a / (len(data))) ** 2) var = var * (len(data) / (len(data) - ddof)) return var %timeit variance_jit(data, ddof=1) ###Output 1.54 ms ± 383 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ###Markdown **That is almost 300 times faster!! Let's compare this to NumPy.** ###Code %timeit np.var(data, ddof=1) ###Output 8.68 ms ± 435 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ###Markdown **In certain scenarios, Numba outperforms NumPy!** **Let's see Numba's effect on a few of ArviZ functions.** ###Code summary_data = np.random.randn(1000, 100, 10) school = az.load_arviz_data("centered_eight").posterior["mu"].values Numba.disable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) Numba.enable_numba() Numba.numba_flag %timeit ks_summary(summary_data) %timeit ks_summary(school) ###Output 3.97 ms ± 574 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
week5_eda/analyzing_model_perf.ipynb
###Markdown Approximately 80% of the data belongs to class 1. Therefore the default accuracy is about 80%. The aim here is to obtain an accuracy of 99 - 99.9%.The examples in the original dataset were in time order, and this time order could presumably be relevant in classification. However, this was not deemed relevant for StatLog purposes, so the order of the examples in the original dataset was randomised, and a portion of the original dataset removed for validation purposes.Attribute Information:The shuttle dataset contains 9 attributes all of which are numerical. The first one being time. The last column is the class which has been coded as follows :* 1 Rad Flow* 2 Fpv Close* 3 Fpv Open* 4 High* 5 Bypass* 6 Bpv Close* 7 Bpv Open 2. Load and prepare the datasetLoad the training data into a DataFrame named df_train_data.Create binary classification problem; rename some class labels.Create a DataFrame of nine features named X, drop column 9.Create a DataFrame of labels named y, select only column 9.Split the data into a training set and a test set.3. Create the modelInstantiate a logistic regression classifier with an lbfgs solver.Fit the classifier to the data.4. Calculate accuracyCalculate and print the accuracy of the model on the test data.5. Dummy classifierUse the dummy classifier to calculate the accuracy of a purely random chance.Compare this result to the result of the logistic regression classifier above. What does this result tell you?6. Confusion matrixPrint the confusion matrix.7. Plot a nicer confusion matrix (optional)Use the plot_confusion_matrix() function from above to plot a nicer-looking confusion matrix.8. Calculate metricsPrint the F₁, Fᵦ, precision, recall, and accuracy scores.9. Print a classification report10. Plot the ROC curve and AUCCalculate AUC and plot the curve.11. Plot precision-recall curvePlot the precision-recall curve for the model above.Find the best value for C in the logistic regression classifier for avoiding overfitting. Plot the training and testing accuracy over a range of C values from 0.05 to 1.5.12. Cross-validationPerform five-fold cross-validation for a logistic regression classifier. Print the five accuracy scores and the mean validation score.13. Is this really linear?Your linear classifier is not giving you better accuracy than the dummy classifier. Suppose that the data was not linearly separable. Instantiate and train a KNN model with k = 7. How does the accuracy of the KNN model compare to the logistic regression from above? What does that tell you about the data?14. Random forestNext, instantiate and fit a random forest classifier and calculate the accuracy of that model.Now, answer some additional questions about analyzing model performance. ###Code colnames=['Time','A','B','C','D','E','F','G','H','target'] df_train_data = pd.read_csv('shuttle.tst.csv', names=colnames, header=None) df_train_data.head() # mapping = [1: 'Rad Flow',2: 'Fpv Close', 3: 'Fpv Open',4: 'High',5: 'Bypass',6: 'Bpv Close',7: 'Bpv Open'] # creating a binary label using values =1 at target df_train_data['target_flow'] = df_train_data['target'] < 2 sns.countplot(x=df_train_data['target_flow']) plt.show() X = df_train_data.drop(columns=['target_flow','target']) y = df_train_data['target_flow'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # creating lr model lr = LogisticRegression(solver='lbfgs', random_state=4) lr.fit(X, y) test_score = lr.score(X_test, y_test) train_score = lr.score(X_train, y_train) print('accuracy score: %s' % lr.score(X_test, y_test)) print('# of iterations %s' % lr.n_iter_[0]) print('Score on training data: ', train_score) print('Score on test data: ', test_score) # model accuracy is high with no tuning at 94% # comparing high accuracy of our model to a dummy model dummy = DummyClassifier(strategy = 'most_frequent') dummy.fit(X_train, y_train) dummy.score(X_test, y_test) ###Output _____no_output_____ ###Markdown The dummy classifer randomly guessing correctly 80% of the time so the lr model of 94% is not so great. ###Code predictions = lr.predict(X_test) confusion = confusion_matrix(y_test, predictions, labels=[1, 0]) print(confusion) def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=None, normalize=True): """ Given a scikit-learn confusion matrix (CM), make a nice plot. Arguments --------- cm: Confusion matrix from sklearn.metrics.confusion_matrix target_names: Given classification classes, such as [0, 1, 2] The class names, for example, ['high', 'medium', 'low'] title: The text to display at the top of the matrix cmap: The gradient of the values displayed from matplotlib.pyplot.cm See http://matplotlib.org/examples/color/colormaps_reference.html `plt.get_cmap('jet')` or `plt.cm.Blues` normalize: If `False`, plot the raw numbers If `True`, plot the proportions Usage ----- plot_confusion_matrix(cm = cm, # Confusion matrix created by # `sklearn.metrics.confusion_matrix` normalize = True, # Show proportions target_names = y_labels_vals, # List of names of the classes title = best_estimator_name) # Title of graph Citation --------- http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html """ import matplotlib.pyplot as plt import numpy as np import itertools accuracy = np.trace(cm) / float(np.sum(cm)) misclass = 1 - accuracy if cmap is None: cmap = plt.get_cmap('Blues') plt.figure(figsize=(8, 6)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() if target_names is not None: tick_marks = np.arange(len(target_names)) plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] thresh = cm.max() / 1.5 if normalize else cm.max() / 2 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): if normalize: plt.text(j, i, "{:0.4f}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") else: plt.text(j, i, "{:,}".format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass)) plt.show() plot_confusion_matrix(cm=confusion, target_names = ['Target_flow', 'Not target_flow'], title = 'Confusion Matrix',normalize=False) accuracy = accuracy_score(y_test, predictions) precision = precision_score(y_test, predictions) recall = recall_score(y_test, predictions) f1 = f1_score(y_test, predictions) fbeta_precision = fbeta_score(y_test, predictions, 0.5) fbeta_recall = fbeta_score(y_test, predictions, 2) print('Accuracy score: {:.2f}'.format(accuracy)) print('Precision score: {:.2f}'.format(precision)) print('Recall score: {:.2f}'.format(recall)) print('F1 score: {:.2f}'.format(f1)) print('Fbeta score favoring precision: {:.2f}'.format(fbeta_precision)) print('FBeta score favoring recall: {:.2f}'.format(fbeta_recall)) report = classification_report(y_test, predictions, target_names=['Target_flow', 'Not target_flow']) print(report) probs = lr.predict_proba(X_test)[:, 1] print(probs[1:30]) # plotting the decision threshold in the model occuring at 0.5 pos = [i for i, j in zip(probs, y_test) if j == 1] neg = [i for i, j in zip(probs, y_test) if j == 0] with plt.xkcd(): fig = plt.figure(figsize=(8, 4)) sns.distplot(pos, hist = False, kde = True, color='g', kde_kws = {'shade': True, 'linewidth': 3}) sns.distplot(neg, hist = False, kde = True, color='r', kde_kws = {'shade': True, 'linewidth': 3}) plt.plot([0.5, 0.5], [0, 25], '-b') plt.annotate( 'The probability threshold\npositive to the right\nnegative to the left', xy=(0.51, 15), arrowprops=dict(arrowstyle='->'), xytext=(0.6, 20)) plt.show() fpr, tpr, thresholds = roc_curve(y_test, probs) print(fpr[1:30]) print(tpr[1:30]) print(thresholds[1:30]) fig = plt.figure(figsize = (6, 6)) plt.plot([0, 1], [0, 1], 'k--') plt.plot(fpr, tpr) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC curve for Logistic Regression Model') plt.show() pres, rec, thresholds = precision_recall_curve(y_test, predictions) fig = plt.figure(figsize = (6, 6)) plt.plot(rec, pres) plt.xlabel('Recall') plt.ylabel('Precision') plt.title('Precision-Recall Curve') plt.show() # looking at effects on model by L2 regularization lr_regularized = LogisticRegression(solver='lbfgs', penalty='l2', max_iter=200, random_state=2) lr_regularized.fit(X_train, y_train) test_score = lr_regularized.score(X_test, y_test) train_score = lr_regularized.score(X_train, y_train) print('Score on training data: ', train_score) print('Score on test data: ', test_score) # using and L2 and 100 iterations as parameters, accuracy has increased and underfitting has improved. The range of coefficients is reduced # from -1.5 to 2.5 without L2 to between -1 to 1.5 or from a about a 4 point spread to a 2.5 point spread. fig = plt.figure(figsize=(8, 8)) grid = plt.GridSpec(2, 2, hspace=0.5, wspace=0.5) x = np.arange(0, len(lr.coef_[0]),1) y = lr.coef_[0] ax1 = fig.add_subplot(grid[0, 0]) ax1.plot(x, y, '-g') ax1.set(xlabel='Features', ylabel='Coefficients') ax1.set_title('No Regularization') y_reg = lr_regularized.coef_[0] ax2 = fig.add_subplot(grid[0, 1]) ax2.plot(x, y_reg, '-r') ax2.set(xlabel='Features', ylabel='Coefficients') ax2.set_title('L2 Regularization') ax3 = fig.add_subplot(grid[1, 0:]) ax3.plot(x, y, '-g') ax3.plot(x, y_reg, '-r') ax3.set(xlabel='Features', ylabel='Coefficients') ax3.set_title('Both on same chart for comparison') plt.show() # looking at effect of various values of C on the model c_vals = np.arange(0.05, 1.5, 0.05) test_accuracy = [] train_accuracy = [] for c in c_vals: lr = LogisticRegression(solver='lbfgs', penalty='l2', C=c, max_iter=200, random_state=2) lr.fit(X_train, y_train) test_accuracy.append(lr.score(X_test, y_test)) train_accuracy.append(lr.score(X_train, y_train)) fig = plt.figure(figsize=(8, 4)) ax1 = fig.add_subplot(1, 1, 1) ax1.plot(c_vals, test_accuracy, '-g', label='Test Accuracy') ax1.plot(c_vals, train_accuracy, '-b', label='Train Accuracy') ax1.set(xlabel='C', ylabel='Accuracy') ax1.set_title('Effect of C on Accuracy') ax1.legend() plt.show() # The minimum value of C occurs somewhere at about C = 0.7. df_train_data.shape X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) clf = LogisticRegression(solver='lbfgs') cv_scores = cross_val_score(clf, X_train, y_train, cv = 5) print('Accuracy scores for the five folds: ', cv_scores) print('Mean cross-validation score: {:.3f}'.format(np.mean(cv_scores))) ###Output Accuracy scores for the five folds: [0.93232759 0.94008621 0.93965517 0.92715517 0.93232759] Mean cross-validation score: 0.934
rossmann_timeSeries.ipynb
###Markdown ###Code # Last amended: 19th March, 2021 # Myfolder: github/deeplearning-sequences # Objectives: # i) Feature engineering in Time Series data # ii) Using fastai on tabular data # # https://colab.research.google.com/github/duchaba2/fastai_san_ramon_biztech/blob/master/smbt_rossman_data_clean.ipynb#scrollTo=UImWYEGiaFUS # fastai.core: https://docs.fast.ai/tabular.core.html # https://www.kaggle.com/hortonhearsafoo/fast-ai-lesson-3 # https://github.com/duchaba2/fastai_san_ramon_biztech # Using fastai on tabular data # https://github.com/fastai/fastbook/blob/master/09_tabular.ipynb # Rossmann Data Engineering # Much of it is not implemented # See: https://www.kaggle.com/omgrodas/rossmann-data-engineering # Last amended: 17th March, 2021 # My folder: # Objectives: # i) Predicting sales in Rossmann Store Sales # ii) Feature generation in TimeSeries data ###Output _____no_output_____ ###Markdown The problemRossmann operates over 3,000 drug stores in 7 European countries. Currently, Rossmann store managers are tasked with predicting their daily sales for up to six weeks in advance. Store sales are influenced by many factors, including promotions, competition, school and state holidays, seasonality, and locality. With thousands of individual managers predicting sales based on their unique circumstances, the accuracy of results can be quite varied. Field descriptionsMost of the fields are self-explanatory. The following are descriptions for those that aren't. > **Id** - an Id that represents a (Store, Date) duple within the test set> **Store** - a unique Id for each store> **Sales** - the turnover for any given day (this is what you are predicting)> **Customers** - the number of customers on a given day> **Open** - an indicator for whether the store was open: 0 = closed, 1 = open> **StateHoliday** - indicates a state holiday. Normally all stores, with few exceptions, are closed on state holidays. Note that all schools are closed on public holidays and weekends. a = public holiday, b = Easter holiday, c = Christmas, 0 = None> **SchoolHoliday** - indicates if the (Store, Date) was affected by the closure of public schools> **StoreType** - differentiates between 4 different store models: a, b, c, d> **Assortment** - describes an assortment level: a = basic, b = extra, c = extended> **CompetitionDistance** - distance in meters to the nearest competitor store> **CompetitionOpenSince**[Month/Year] - gives the approximate year and month of the time the nearest competitor was opened> **Promo** - indicates whether a store is running a promo on that day> **Promo2** - Promo2 is a continuing and consecutive promotion for some stores: 0 = store is not participating, 1 = store is participating> **Promo2Since**[Year/Week] - describes the year and calendar week when the store started participating in Promo2> **PromoInterval** - describes the consecutive intervals Promo2 is started, naming the months the promotion is started anew. E.g. "Feb,May,Aug,Nov" means each round starts in February, May, August, November of any given year for that store Libraries and data files ###Code #import pytorch and AI #!pip install --upgrade git+https://github.com/fastai/fastai.git #(Optional) double check your import pytorch and fast.ai version # fastai related # The 'tabular' module has # all the functions as on this page: # https://docs.fast.ai/tabular.core.html from fastai.tabular import * import fastai from fastai.tabular import * from fastai.basics import * import fastai.utils #from fastai.data import * # 1.0 Connect to your google drive # Transfer rossmann files from # gdrive to colab VM from google.colab import drive drive.mount('/content/drive') # 1.1 Copy files from source to Colab source="/content/drive/MyDrive/Colab_data_files/rossmannStoreSales" dest="/content" # 1.1.1 Remove existing folders ! rm -rf $dest/rossmannStoreSales # 1.1.2 Copy files from gdrive to colab VM ! cp -r $source $dest/rossmannStoreSales # 1.1.3 Check ! ls -la $dest/rossmannStoreSales # 1.2 Untar tgz file ! tar -xvzf $dest/rossmannStoreSales/rossmann.tgz -C $dest/rossmannStoreSales/ # 1.2.1 And check if all files are there ! ls -la $dest/rossmannStoreSales # 1.3 Call libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import os # 1.4 Display output of multiple commands from a cell from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" # 1.5 Path to our files path = "/content/rossmannStoreSales" os.chdir(path) os.listdir() ###Output _____no_output_____ ###Markdown CAUTION--Clean-up from gdrive--CAUTIONLet us clean up from gdrive last saved processed files of this project, if they exist. ###Code # 1.6 Our path path = "/content/drive/MyDrive/Colab_data_files/" # 1.6.1 if os.path.exists(path + "joined"): os.remove(path + "joined") # 1.6.2 if os.path.exists(path + "joined_p"): os.remove(path + "joined_p") # 1.6.3 if os.path.exists(path + "joined_fp"): os.remove(path+"joined_fp") # 1.6.4 if os.path.exists(path + "joined_ffp"): os.remove(path+"joined_ffp") # 1.6.5 if os.path.exists(path + "joined_fpg"): os.remove(path+"joined_fpg") # 1.6.6 if os.path.exists(path + "joined_test"): os.remove(path+"joined_test") # 1.6.7 Check if all files deleted os.listdir(path) ###Output _____no_output_____ ###Markdown Read all data ###Code # 2.0 Read all seven files using pandas train = pd.read_csv("train.csv") store = pd.read_csv("store.csv") weather = pd.read_csv("weather.csv") # 2.0.1 test = pd.read_csv("test.csv") # 2.0.2 googletrend = pd.read_csv("googletrend.csv") state_names = pd.read_csv("state_names.csv") store_states = pd.read_csv("store_states.csv") # 2.0.3 Also set options to display all rows/all columns pd.set_option('display.max_columns', None) # or 1000 pd.set_option('display.max_rows', None) # or 1000 pd.set_option('display.max_colwidth', None) # or 199 # 2.0.4 Check if read train.shape , test.shape, store.shape, weather.shape, googletrend.shape, state_names.shape, store_states.shape ###Output _____no_output_____ ###Markdown Explore train data ###Code # 2.1 Look at train data print("\n---train----\n") train.shape # (1017209, 9) print("\n------train------\n") train.head() print("\n-----Summary------\n") train.describe() print("\n-----dtypes------\n") train.dtypes # 2.2 train['Store'].nunique() # 1115 print() train['Promo'].nunique() # 2 train['Promo'].unique() # [1,0] print() train['Open'].nunique() # 2 train['Open'].unique() # [1,0] print() train['SchoolHoliday'].nunique() # 2 train['SchoolHoliday'].unique() print() train['StateHoliday'].nunique() # 5 train['StateHoliday'].unique() # ['0', 'a', 'b', 'c', 0] print() train['Date'].nunique() # 942 # 2.3 About nulls # No nulls here train.isnull().sum() ###Output _____no_output_____ ###Markdown Explore Store data ###Code # 3.0 Look at store data print("\n---shape----\n") store.shape # (1115, 10) print("\n------data------\n") store.head() print("\n-----Summary------\n") store.describe() print("\n-----dtypes------\n") store.dtypes # 3.1 store['StoreType'].unique() # ['c', 'a', 'd', 'b'] print() store['Assortment'].unique() # ['a', 'c', 'b'] print() store['Promo2'].unique() # [0,1] print() np.sort(store['CompetitionOpenSinceYear'].unique()) # Large number of years from 1961, 1990 to 2015 # excluding NaN and 1900 # 3.2 Whenever Promo2 is zero, three other columns carry NaN values store.loc[store['Promo2'] == 0, ['Promo2','Promo2SinceWeek','Promo2SinceYear', 'PromoInterval']].head(5) print() store.isnull().sum() # 3.3 Three cases where CompetitionDistance is NULL # CompetitionOpenSinceMonth and CompetitionOpenSinceYear # are also NULL store.loc[store['CompetitionDistance'].isnull() , :].head() ###Output _____no_output_____ ###Markdown Explore weather data ###Code # 4.0 Look at weather data print("\n---shape----\n") weather.shape # (15840, 24) print("\n------data------\n") weather.head() print("\n-----Summary------\n") weather.describe() print("\n-----dtypes------\n") weather.dtypes # 4.1 Unique values for object features weather['file'].nunique() # 16 print() weather['Date'].nunique() # 990 Some dates are repeating for some 'file' print() weather['Events'].nunique() # 21 unique weather events # 4.2 Null values # Some columns have NULL values # Max_Gust_SpeedKm_h has very large number of NULL values # Events: In 3951 cases no Events recorded weather.isnull().sum().sort_values(ascending = False).head(10) ###Output _____no_output_____ ###Markdown Google trends and other data Explore googletrends ###Code # 5.0 Look at googletrend data print("\n---google trends----\n") googletrend.shape # (1017209, 9) print() googletrend.head() # (15840, 24) print() googletrend.dtypes # 5.1 A little more googletrend['week'].nunique() # 148 print() googletrend['file'].nunique() # 14 ###Output _____no_output_____ ###Markdown Split up '*week*' and '*file*' columns of googletrendThis will create new columns. In pandas you can add new columns to a dataframe by simply defining it. We'll do this for googletrends by extracting dates and state names from the given data and adding those columns.We're also going to replace all instances of state name 'NI' to match the usage in the rest of the data: 'HB,NI'. This is a good opportunity to highlight pandas indexing. We can use .loc[rows, cols] to select a list of rows and a list of columns from the dataframe. In this case, we're selecting rows w/ statename 'NI' by using a boolean list googletrend.State=='NI' and selecting "State".--- ###Code # 6.0 # Refer" # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html # String split with 'expand' googletrend.week.str.split( ' - ', # split on this '_' expand = True # Each split part is a column now )[0].head(2) # select the first split part as a column & display # 6.1 Split 'week' field at ' - ' googletrend['Date'] = googletrend.week.str.split(' - ', expand=True)[0] # 6.2 Split 'file' field at '_' and capture the 2nd index as new column googletrend['State'] = googletrend.file.str.split('_', expand=True)[2] # 6.3 googletrend.loc[googletrend.State=='NI', "State"] = 'HB,NI' googletrend.head() # 6.4 Also check if any 'NI' remaining np.sum(googletrend.State=='NI') # 0 # 6.4.1 googletrend.head(10) ###Output _____no_output_____ ###Markdown More explorations ###Code # 7.0 state_names.head() print() state_names.State.nunique() # 16 print() store_states.head() print() store_states['Store'].nunique() # 1115 print() store_states['State'].nunique() # 12 # 7.1 StateHoliday train.StateHoliday.dtype print() train.StateHoliday[:4] ###Output _____no_output_____ ###Markdown Transform *StateHoliday* fieldWe turn state Holidays to booleans, to make them more convenient for modeling. We can do calculations on pandas fields using notation very similar (often identical) to numpy. ###Code # 7.2 StateHoliday replace by True/False train.StateHoliday = train.StateHoliday!='0' train.StateHoliday[:4] print() # 7.2.1 test.StateHoliday = test.StateHoliday!='0' test.StateHoliday[:4] ###Output _____no_output_____ ###Markdown Date componentsBreak date into its components `add_datepart()` [fastai](https://github.com/fastai/fastai/blob/master/fastai/tabular/core.pyL15) functionThe following extracts particular date fields from a complete datetime for the purpose of constructing categoricals.You should ***always*** consider this feature extraction step when working with date-time. Without expanding your date-time into these additional fields, you can't capture any trend/cyclical behavior as a function of time at any of these granularities. We'll add to every table with a date field. ###Code # 8.0 ## add_datepart() # Break every date-field is broken into multiple components: # ['Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear', # 'Is_month_end', 'Is_month_start', 'Is_quarter_end', # 'Is_quarter_start', 'Is_year_end', 'Is_year_start'] # # Source: https://colab.research.google.com/github/duchaba2/fastai_san_ramon_biztech/blob/master/smbt_rossman_data_clean.ipynb#scrollTo=AgmbiE0MR8LE import re def add_datepart(df, fldname, drop=True, time=False): "Helper function that adds columns relevant to a date." fld = df[fldname] fld_dtype = fld.dtype # If date-field in not of 'date' type, # transform it if isinstance(fld_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype): fld_dtype = np.datetime64 if not np.issubdtype(fld_dtype, np.datetime64): df[fldname] = fld = pd.to_datetime(fld, infer_datetime_format=True) targ_pre = re.sub('[Dd]ate$', '', fldname) attr = [ 'Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear', 'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start' ] if time: attr = attr + ['Hour', 'Minute', 'Second'] # Begin attribute extraction using '.dt. accessor for n in attr: df[targ_pre + n] = getattr(fld.dt, n.lower()) df[targ_pre + 'Elapsed'] = fld.astype(np.int64) // 10 ** 9 # If original date-field is to be dropped, drop it if drop: df.drop(fldname, axis=1, inplace=True) # 8.1 Using above function, breakup # 'dates' in all cases below add_datepart(train, "Date", drop=False) # 8.1.1 add_datepart(test, "Date", drop=False) # 8.1.2 add_datepart(weather, "Date", drop=False) # 8.1.3 add_datepart(googletrend, "Date", drop=False) # 8.1.4 add_datepart(weather, "Date", drop=False) # 8.2 So what are the revised data shapes train.shape # (1017209, 22) print() test.shape # (41088, 21) print() weather.shape # (15840, 37) print() googletrend.shape # (2072, 18) print() # 8.3 And look at one data train.head() ###Output _____no_output_____ ###Markdown The Google trends data has a special category for the whole of the Germany - we'll pull that out so we can use it explicitly. ###Code # 8.4 googletrend.shape # (2072, 18) googletrend.head() print() trend_de = googletrend[googletrend.file == 'Rossmann_DE'] trend_de.shape # (148, 18) print() trend_de.head() ###Output _____no_output_____ ###Markdown Joining tablesWe have several tables. Merge them, one by one `join_df` is a function for joining tables on specific fields. By default, we'll be doing a left outer join of right on the left argument using the given fields for each table. Pandas does joins using the merge method. The suffixes argument describes the naming convention for duplicate fields. We've elected to leave the duplicate field names on the left untouched, and append a "_y" to those on the right. ###Code # 9.0 Define a small function for merging tables # df.merge(right, # how='inner', # left_on=None, # Column or index level names to join on in the left DataFrame # right_on=None, # Column or index level names to join on in the right DataFrame. # suffixes=('_x', '_y')) # a string indicating the suffix to add to overlapping column name def join_df(leftTable, rightTable, left_onField, right_onField=None, suffix='_y'): # 9.0.1 Both right and left fields would be same if right_onField is None: right_onField = left_onField # Both sides are same # 9.0.2 Return merged table return leftTable.merge( rightTable, how='left', # It is 'left' join AND NOT 'inner' join # We cannot loose left-side data left_on=left_onField, right_on=right_onField, suffixes=("", suffix) # left side: no suffix, # right side default is "_y" # unless mentioned in the function # call arguments ) # 9.1 Join1: (weather + state_names) # join_df(leftTable, rightTable, left_onField, right_onField=None, suffix='_y') weather.shape # (15840, 37) print() # 9.2 Suffix is "_y": weather = join_df(weather, # Left df state_names, # right df "file", # Ist column of 'weather': Contains state names "StateName" # Ist column of 'state_name' ) print() # 9.3 weather.shape # (15840, 37+2) # 9.4 Columns 'file' and 'StateName' are the same: weather.head(2) # Both 'file' and 'StateName' columns have same data # 9.5 Join2: (store + stire_states) # join_df(leftTable, rightTable, left_onField, right_onField=None, suffix='_y') store.shape # (1115, 10) print() store = join_df(store, store_states, "Store" ) print() store.shape # (1115, 11) # 9.5.1 Check point weather.shape # (15840, 39) store.shape # (1115, 11) train.shape # (1017209, 22) # Delete any earlier 'joined' del joined # 9.6 join3: (train+store) # join_df(leftTable, rightTable, left_onField, right_onField=None, suffix='_y') train.shape # (1017209, 22) print() joined = join_df(train, store, "Store" ) joined_test = join_df(test, store, "Store") len(joined[joined.StoreType.isnull()]),len(joined_test[joined_test.StoreType.isnull()]) # (0, 0) joined.shape # (1017209, 32) print() joined_test.shape # (41088, 31) # 9.6.1 Check point weather.shape # (15840, 39) store.shape # (1115, 11) train.shape # (1017209, 22) joined.shape # (1017209, 32) # 9.7 join4: (joined+googletrend) joined.shape # (1017209, 32) print() joined = join_df( joined, googletrend, ["State","Year", "Week"] # Left fields to be joined on ) joined_test = join_df(joined_test, googletrend, ["State","Year", "Week"]) len(joined[joined.trend.isnull()]),len(joined_test[joined_test.trend.isnull()]) joined.shape # (1017209, 47) print() joined_test.shape # (41088, 46) # 9.7.1 Check point weather.shape # (15840, 39) store.shape # (1115, 11) train.shape # (1017209, 22) joined.shape # (1017209, 47) #9.8 # join5: (joined+trend_de) Note the suffix here. It is NOT the default '_y' # join_df(leftTable, rightTable, left_onField, right_onField=None, suffix='_y') joined.shape # (1017209, 47) # Use pandas pd.merge here: joined = joined.merge( trend_de, # Right table 'left', # type of join ["Year", "Week"], # On these two fields suffixes=('', '_DE') ) joined_test = joined_test.merge(trend_de, 'left', ["Year", "Week"], suffixes=('', '_DE')) len(joined[joined.trend_DE.isnull()]),len(joined_test[joined_test.trend_DE.isnull()]) # joined.shape # (1017209, 63) joined_test.shape # (41088, 62) # 9.8.1 Check point weather.shape # (15840, 39) store.shape # (1115, 11) train.shape # (1017209, 22) joined.shape # (1017209, 63) #9.9 #join6: (joined+weather) # join_df(leftTable, rightTable, left_onField, right_onField=None, suffix='_y') joined.shape # (1017209, 63) joined = join_df( joined, weather, ["State","Date"] ) joined_test = join_df(joined_test, weather, ["State","Date"]) len(joined[joined.Mean_TemperatureC.isnull()]),len(joined_test[joined_test.Mean_TemperatureC.isnull()]) # (0,0) joined.shape # (1017209, 100) joined_test.shape # (41088, 99) # 9.9.1 Check point weather.shape # (15840, 39) store.shape # (1115, 11) train.shape # (1017209, 22) joined.shape # (1017209, 100) # 9.10 Check joined.columns len(joined.columns) # 100 # 9.11 Assign value to 'name' attribute of DataFrame # We will use it shortly joined.name = "joined" joined_test.name = "joined_test" # 10.0 Remove columns having suffix of '_y' for df in (joined, joined_test): for c in df.columns: if c.endswith('_y'): if c in df.columns: print(c,df.name) df.drop(c, inplace=True, axis=1) # 10.0.1 # Check point weather.shape # (15840, 39) store.shape # (1115, 11) train.shape # (1017209, 22) joined.shape # (1017209, 74) joined_test.shape # (41088, 73) ###Output _____no_output_____ ###Markdown Missing valuesNext we'll fill in missing values to avoid complications with `NA`'s. `NA` (not available) is how Pandas indicates missing values; many models have problems when missing values are present, so it's always important to think about how to deal with them. In these cases, we are picking an arbitrary *signal value* that doesn't otherwise appear in the data. We will also create some features ###Code # 11.0 Just explore joined[['CompetitionOpenSinceYear', 'CompetitionOpenSinceMonth', 'Promo2SinceYear', 'Promo2SinceWeek']].head(5) joined[['CompetitionOpenSinceYear', 'CompetitionOpenSinceMonth', 'Promo2SinceYear', 'Promo2SinceWeek']].describe() ###Output _____no_output_____ ###Markdown Create missing values indicator columnsFor any missing value column, before filling it, create another column to indicate location of missing values ###Code #11.0.1 Create columns that indicates that CompetitionOpenSince is missing for df in (joined,joined_test): #Create column that indicates that CompetitionOpenSince is missing df["CompetitionOpenNA"]=False df.loc[df.CompetitionOpenSinceYear.isna(),"CompetitionOpenNA"]=True # 11.0.2 Create columns that indicates that CompetitionDistance is missing df["CompetitionDistanceNA"]=False df.loc[df.CompetitionDistance.isna(),"CompetitionDistanceNA"]=True ###Output _____no_output_____ ###Markdown Fill missing values ###Code # 11.1 for df in (joined,joined_test): ##AA. 'CompetitionOpenSinceYear' & 'CompetitionOpenSinceMonth' ## 15/01/1900 ==== 354 missing values each # Fill in year as 1900 (354 missing values) df['CompetitionOpenSinceYear'] = df.CompetitionOpenSinceYear.fillna(1900).astype(np.int32) # Fill in month as 1 (354 missing values) df['CompetitionOpenSinceMonth'] = df.CompetitionOpenSinceMonth.fillna(1).astype(np.int32) ##BB. 'Promo2SinceYear' and 'Promo2SinceWeek' # 01/01/1900 ==== 544 missing values # Fill in year as 1900. (544 missing values) df['Promo2SinceYear'] = df.Promo2SinceYear.fillna(1900).astype(np.int32) # Fill in week as 1. (544 missing values) df['Promo2SinceWeek'] = df.Promo2SinceWeek.fillna(1).astype(np.int32) # 11.2 Assume missing CompetitionDistance data is beacuse the competition is to far away to be registered df.loc[df.CompetitionDistance.isna(),"CompetitionDistance"]= df.CompetitionDistance.max()*2 ###Output _____no_output_____ ###Markdown Create new feature from two 'date' features ###Code # 12. We create a new feature from these two features joined[['Date','CompetitionOpenSinceYear','CompetitionOpenSinceMonth'] ].head() # 12.1 Create two features: One new date feature # and one 'days' elapsed feature: for df in (joined,joined_test): # 12.1 Create a new feature 'CompetitionOpenSince' # CompetitionOpenSince whose year is CompetitionOpenSinceYear # and whose month is CompetitionOpenSinceMonth and the # day is 15 (selected randomly) df["CompetitionOpenSince"] = pd.to_datetime( dict ( year=df.CompetitionOpenSinceYear, month=df.CompetitionOpenSinceMonth, day=15 # This is an arbitrary selection ) ) # 12.2 Another feature. Days elapsed from 'CompetitionOpenSince' to current 'date' df["CompetitionDaysOpen"] = df.Date.subtract(df.CompetitionOpenSince).dt.days ###Output _____no_output_____ ###Markdown Data cleaning ###Code # 12.3 Some cleaning of data: for df in (joined,joined_test): # CompetitionDaysOpen feature was just created (See above) df.loc[df.CompetitionDaysOpen<0, "CompetitionDaysOpen"] = 0 # Also before 1990 setting CompetitionDaysOpen as 0 # The earliest CompetitionOpenSinceYear is 1990 df.loc[df.CompetitionOpenSinceYear<1990, "CompetitionDaysOpen"] = 0 # 12.3.1 joined.shape # (1017209, 78) print() import sys np.set_printoptions(threshold=sys.maxsize) np.sort(joined.columns.values) ###Output _____no_output_____ ###Markdown Save processed data to disk--IThis will also delete all tables. File created `joined` ###Code # 12.4 Save data to disk # StackOverflow: https://stackoverflow.com/a/17098736/3282777 path = "/content/drive/MyDrive/Colab_data_files/" joined.to_pickle(path +"joined") joined_test.to_pickle(path +"joined_test") # 12.5 Check saved files: # joined_test size: 18111235 # joined size: 469951247 !ls -la $path # 12.5.1 Clear memory for future work del train del test del weather del googletrend del joined del joined_test ###Output _____no_output_____ ###Markdown Read processed data from disk--IRead file `joined` from disk ###Code # 12.6 Read saved files path = "/content/drive/MyDrive/Colab_data_files/" joined = pd.read_pickle(path +"joined") joined_test =pd.read_pickle(path +"joined_test") # 12.6.1 Verify joined.shape # (1017209, 78) #joined_test.shape # (41088, 75) ###Output _____no_output_____ ###Markdown Feature creationCreate more features Elapsed time It is common when working with time series data to extract data that explains relationships across rows as opposed to columns, e.g.:* Running averages* Time until next event* Time since last eventThis is often difficult to do with most table manipulation frameworks, since they are designed to work with relationships across columns. As such, we've created a class to handle this type of data.We'll define a function `get_elapsed` for cumulative counting across a sorted dataframe. Given a particular field `fld` to monitor, this function will start tracking time since the last occurrence of that field. When the field is seen again, the counter is set to zero.Upon initialization, this will result in datetime na's until the field is encountered. This is reset every time a new store is seen. We'll see how to use this shortly. Let's walk through an example.Say we're looking at School Holiday. We'll first sort by Store, then Date, and then call `add_elapsed('SchoolHoliday', 'After')`:This will apply to each row with School Holiday:* A applied to every row of the dataframe in order of store and date* Will add to the dataframe the days since seeing a School Holiday* If we sort in the other direction, this will count the days until another holiday.The following figure is from this [link](https://docs.fast.ai/tabular.core.htmladd_elapsed_times):![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjwAAAE5CAYAAACUKvq0AAAgAElEQVR4nOy9d3hVx53/r2z2t9lk00ycnm8Sb8ruJvEmjhOv402c2NgG3HABjGlCQqiBekcVkECAQKIICSFUaBICRJUoqiBAEpJACPWGei9Xur2+fn/ci7oAO7ZZK/N6nvPwMGfuzGc+nzlz3jNzzpEZAoFAIBAIBDMcs8dtgEAgEAgEAsGnjRA8AoFAIBAIZjxC8AgEAoFAIJjxCMEjEAgEAoFgxiMEj0AgEAgEghnPJyh4ejgVuQ77dYl06iacasrB28WBiNMVH7v0hsJD2CxZykpLKzzDjtCk/fus/fvpJnW3D2t8D9Klf1heLdWXY9gQmUqbdPLZe1mxrF5pSfy1rk/DUIFAIBAI/uH5RAXPujlPYvbNDyhXTzhVFc0TXzTjeZdzH7v0ktM+/OybX8XMzIyv/G45Baq/z9q/n268X/0WZrMWU/lQ8aVl7ztfxewZJ1oMk8+2nd3Is79+moAzTZ+GoQKBQCAQ/MPzcMGjU1KRk0J8fDzx8fEkHDlDVad85LS6p4q0pATi47fw1jPf4ev/ZUOVSQA0F2dyOD6e+MDlPPnVr/FGYMZDq1N1l3PyoLGu01crGNE1BgN6fTvr/vR9vvecOTdHTqipKbgwat/BFAqbhgFQNN/mwtmz5N/OJyU+noTkdOolo3V1lWdzJDGRhPh44lMuUN9rWqoxDFGYlmQsL/kizZJRlaLqruJ8Ujzx8aG88btv841f2VHzAMHTX1NAckw47/3qi5g99SqbIo11NQwAejmF5xKN9SQmU1BvtFs1VMul02c5e/oMx1PPkH+riBOJiVy6e38FSElpTqrxd4dPU96jGalPO1BH+vFDJCTEEx9/mJw7nQ/1uUAgEAgEM52HCx5lJ6Gvz8LMzGzk+MX8DbQoQNF0Hfu//Pu4c9/+owutaCk5uZFnvvsvY859jYUhWQ+sSt6ei/Vffjbymy9882d4HC5kVF714P+/EwVPP7us/jjOhu//eTUFEhg47cOP/sWMWT+4b/8/8YLdHlr1IC+O5k8//vLo7771PAklemCIU4Hz+f6X7pf3r/x+WTjNSpDfy8Puz+Pb+53nnKl9gOC5udOCfxmT38zMDLOvPEN8KaBtxeqX99O/jOX+WgD66qP49Zj8s37wHeO/L62nn2Fy9zvyk298YeT8L+c5U9gHaCoIeP+3fGHkt1/kraCHi0yBQCAQCGY6j7SlNdRym3PHDnEgdjf2c5/C7J9eIKO+k2vhb2Jm9i0cY7KorM7Dcc5P+eqvXWnrKMbuD1/C7Kn3SS2soPZ8MP9v1teZ53/pgfVkBLyImdnXeN9tJ7F71/O7L5ph9rQ9lSOrMp34vjBR8IC0q4bLqUc4EHsA13d/zz/901fZeBMUGRv4wf9nxi/eCqSwooLwBU9hNusPpFSDLM2FfzIz46tPvYTPrkOcy7mNRAfS2gP86gtm/PiVVcTExrJm7vcwM/s2MXfryAl/CzOzJ3GOzaay5iprX/sJX/2l9QNXeJQDndTcuoLLn7+M2X+bcz6/goraJiQqwKCls7GS3IhVPPn1r7HqQB0Ag/f286svfJ35PgF8+OxP+Omf38duxes89ZP3uFB+kfd+YsaXfrOIPQdi8XnnV5iZmbHyUCcoc3n7p1/EzOxJ3nUOJenMJao6FI8SYoFAIBAIZjQPFTxqaS2RTkuY9545/v7uzHvm25h95SUyK+o57fQrzL7xBndUAE2s+d/v8pXfeVJbfoG3f2LGD1ekAKC/Fsq3v/avzPO//MC64pb+HLN/nsUrS1zw9/fF080F1x0nxjzoqyb4xR/ygxesqbmfNNxOyiYLZr++HD9/P957/t/54le+zaZ8kF/053vf/DfsTsgAOLvmN5g98TsOFANoyE/agZvrGt7766/4zq9eZt/1ZrpvBjPLzIyfPv8OHv7+rPNyx3ltMHlNtSTZ/wdm33zT9IxSI3YvfId//Q+bBwoeI0Nsf/3LmD3nRd9Up6+G8MNZ/4ZtsvGsvGEv//7EH4jKKSLsrT/ypud+jm1dys+fWsCR7CP85etmfONX83Dx8cfX2wNnF2+O5hm3uwbuniPY0w2bJXP46befYoHvETqVD7NPIBAIBIKZzUMFz0DVLn5kZsaTv30VGzsLXvjFVzAze560xh6KD67mq2Zf4X/mvc+CV5/ly2Zm/Ot/u9ImqcT39R9h9o3/4r3Fi3jhl9/CzMyMNwIeLHhK4y355j//G3+YswwbW1vs7dcQmV4GQMkhPxYvns8vvmqG2Vd+wCuLFhOQfBd1ZRovPWGG2f/7K9a2tsz+9Xcw+8LX2XADFBkbeerr/8zPnp/P4g/m8uOvmPGDF9dSPgh1p8NYbW2Lve1yXvwv45bX3ODT9A8VseCpf+G7v3oRcxsbbO3sWRN8hH6NlsKYFfyb2Vf4n9ff531Te7/0a1uqHyZ4VJ2Evf0kZv/8A155ezGL12wkvw2QXsdv2WLmP/9zzMzM+OHvX+dDuy1cygnhp998hogLeWyY/WtmO+4mMegdvv3EHDI7buL84vf515/8iaWrjPY5+mznlgxoycHfZTV29vYsnvsMXzIz459/vYjcwUfsDQKBQCAQzFAeKnh0sntE2r/GT374Xb7/n88yb+E8fv/0YtJbVOjUzUTYvML3npzFz17+ABuLD5n7ji/NGBi8dYQFz/2Ybz3xfeY52PP+q/NwiLj+4MoMA6RuseLXP3qSWbNmMWvWLN7eeBqAC36v8sQT3+JHT/2Mnz31Y74z6wle8c9Arxomaf1S/vPH32PWj37L22/M4bm/vETULZBdDuYXX/sC//KVr/PErG/zvwu9ya4fAiA/bBFPzprFrFlP8v0f/YK37bdQ3G1cCWq+GsuCPz7Ft0w2zHrOlvJe0Ksb2W4zm+89OYufz16MjcVi5r3ry0PfrTJoqbm0mzee/jHf/tYTPPHrtzldA/Sf4JXvPsG3vvcjfvbzn/Pj7z/JrP9axNGMSN7862IO55Wwz+pdrDYf5UyUMy8+Z85N9AzdPYPVnF+Z7J/Fd375KikdQOVBXvxPY9qT3/0h//3KUg5k16Kc4s0wgUAgEAj+kXjk19INBgMj9029AYNh/LnR/+hH82EYd85gGBp5u2jSkXqVfuVIRmN9hjH1jEsbPcbZZxhTL9CZ6s13vvYllkdXjbdxJP/kcsbkmJBnuvYa6L1XSNJUbYpPoai+b1zeqe2eaIthxN8jaYbRtKl+O5XNAoFAIBAIjHzGX1quxWvu98a/sXT/+M58Cps0Dy/iI9CZ6s33vvFlzGPrP9FyJ3Lj8Ooxb0aNPb7CmtiCT7VugUAgEAgED+czFjxqelrrqaiomHzUtaHUfLKrEtrhbmqqq2gfmPglxE8WxVAn1VO1qaKWLol4YlggEAgEgseN+FtaAoFAIBAIZjxC8AgEAoFAIJjxCMEjEAgEAoFgxiMEj0AgEAgEghmPEDwCgUAgEAhmPELwCAQCgUAgmPEIwSMQCAQCgWDG81DBo1AokMlkyGQyFArxl7cFAoFAIBB8/nio4JFIJPT19dHX18fgoPgrlAKBQCAQCD5/PFTwDA0N0d/fT39/PxKJ5LOwSSAQCAQCgeATRQgegUAgEAgEMx4heAQCgUAgEMx4hOARCAQCgUAw4xGCRyAQCAQCwYxHCB6BQCAQCAQzHiF4BAKBQCAQzHiE4BEIBAKBQDDjEYJHIBAIBALBjEcIHsEjoANZI3rD47ZDIBB8bPQyGu/cpU/9uA0RCB4P/+cFj7S2hD0Hr9OlebT0R0POjZPnuVqn+iRM/Fg8uv0G9IbJSkPVVUGIdzKX62Sfin1j6a+4zMW9iQ8UPEXHTxAeV4z0foKun+NRiVhY7SBgZwb35B+zcl0fx/YmYGG1g8DdmTSZ/pxb681cPJcf5GrbwwvW9FazPegE2Q3T/y24mynHCY8v4dP35mdL4bEUwhNuPbxdBgP6T0LRantJjhyNV/P9eBVkG+PV/vC/x6fuqSIs6CQ5jdPnfeR2TULGhcSTJOa1f+RffiJoe0naY/RP0J5sWkxNbMnPxnPFQfI6HsE/3ZWEBZ0k9wH+KUhOISLxNuOuDv0QiYG2hGc1/n1tEAg+p/yfFzzNZ2NYHXKBQf2jpT8Sqno2LNzK8crH98dQH9X+a4cPcOzOFHYOl2H9zjYSb33KMVG1EL/BlUM53Q/IpGaXpRuLtxSiBTBoubo3nFcXRXHmahV3qjuRaT9G3QYNuZE7ePWD6NFyTP7qzz/H/P/dzqXWh8ewPfswzz0XQGrddOpSRbiFGx9uK+LjmPl/FxU7VrqxJKz4Ie0aZIfNRnZmPCjGj4BBQ86e7bz6wT7OXq3iTs1ovHqvn+XtP+8go1X50GLaMg/y3HOBnG6YzupHbdcUdBez+KU1BFwY+qi//PsxqMnZHcari2M4l1dFWU0XcpN/evLO8PZfdpDZ/nD/tGYk8sf/CeRM43StVxBm7sqyHSWT/HP7ZBjOERno/q6GCASfTx6v4NH1cjYpnZ27zxKbcIWy+7P1Meme5v5sSa3HME36g/WCjLyTl9m54yTJV5u4v5KrKr3I+4tjKZZN+PUEe+52qkE5QEH5PdrrqoiPOkV0ejXS+6OFtI1Th8+xc2cqkal36FU8uN6PYn9/fSWHdyWx8u21LHU/zp7IyxS3KAEdFdlX2RmVyfV7I+spSDu7aKyq4PyZm1zNrybnYjbpJb2j9py4xM7wkxzLG2PPcBuph0z2n7pD7xRjbdOFraz2jqF7qsl/byPxMWeJjE5k4cseRGSZ+oehE/e59vicaJumdY+IvgO3OfasSx0zG9f1k5V8kb0HC6junbBCJ+/g5P6zROxN5+zt3pHky5vX85r5EVon2d9AXMxZIqMSWfiyJztzpu/fA/dquVZYS1VJITv3XuBsaffkcqLTOZJayL0BOY03KyjKKyLuxG1Kb5Vx/PRVrtYNP9BORXMl8TFn2LXnDIlp1R9/talntF0LXvZiV+7w+PToCxw5WUiTXMO9awXEbI7hxd9Y8Lp1PNEJ2VSOdJt2TsacJSIqnbOlfQ+vV9+Oy2tr8DvVMZqm6ycz+SJ7DxVS0zthL2Wa8i+FBPGaeRKTes+kdn100aIoTuPtef6EHs5h5+40Tl9rHbn5G7rrObDP5J/UfOr6TWY2VRAXc4Zde85yML1mdNVE1s6JmLNERF3g3KP4R9eG86tr8D/TOZqm7Scz6YLRPxP3mqYp/8LGQOZYJDNxjWrE/r0JLHjZi8irw5NMaMlJxNMrgY5JZwSCmc/jEzzqLpI3xWAfksrefcks/rM/O3N6gF6OjUlf9koI+28MTJ2e94AZqaaHk5EH8Ag+R0LcOdxX7yHlqjF/Y1oitlvS6R87zZnCnt15Eugvx221F++vPUxU7AlszCNIvjYAhl7i1u1mzeZUEuIusP/sXfqU09R7YwDo49jmR7d/oLGa5NBI5v1lI4F7z7EvJotbbUo66utIjTqB19oQFm+/yX0dUnPmKAt+74md0xb+9Nom1jr4Yx99C1T9nNx7AI8Qkz1WeziePwiGXg747GJN6CkS4i4Qe85k/7gYtRHt4cKOS9WT7JNVF+G1ypOV69PY7RnMM8/7kNalpvx0Gh4r1/Psb6x4ecE2XH0Pc73loy7Dabh18hzu5sZyZi/chqvfUW52a2guLiIxLI6Xn16K9d47ozPY9nKCvbfguTWLuC07+N3rwVxuMABKomy9WLQum7G3E1l1IV6WnlhsSGO350ae+ZM3px6w0l95LJKnf72S1cGn8bH14g9vRNMAqGqLRsrZ47We//ytO2n1Heyz9uGlucHMe82WVy2jWL7IicURtzH0VbNpgp1ZLaCpLWDNYicsNlwkMfEyyZdqP5bgkVYV4mmyZ5f7Bp75kw/nOkBde3MkfbdnEP/5tDMnmjU0599ki6U7P/i9G57b0og9nEtVH9B2l41eW/Damknclu387vUQMhqmWxdQU3L8LG7mQfz+N1bMXhiGq38SRWPi9dLTy7CNvjsarynKz7xnABTstfZkkW8OY9fjpmrX6Xsf3T+NaQn86ecWzLeJYVtwGH94ZQMX20FTW4i7hSeWG9PY5RHIfzztzIlmUFbdwHaRE5YbL5GYeJljl+uQA4bWu2zw2or3tkziQsP43RubyGyc3j/FKUb/PPMbK2Yv2oarfxLFPRqai4pICDvA355eht2+Uf9MVX6WyT97VnvwgX/uOP8MVxbgbuGF5cY0drqv55kX1nG2abIlLbkxODqGUy+exxP8A/KYBI+BytRD2Kw6TgsAnWz0iyO9RUbjxWRsHyk9ltRy6bQ1tOWdxHzhFhKvNVBdVcEO+3Ci09oAA9cid7L5cPmYZd2p7InlbKMOQ3M+K2c7syXLOMMq2bmT4IO1oO0g2GIrfkdLaO4fvZW2Tqp3FwlXOqm5cOwj2Q+grryEtcdJesakKaRy1HooPRGLVdh1Uxu05O4NZ/HqM2SfPMYKn0xyL6RwMLuWxrzzrFy0hYPXG6iuKme7XQTRGb2gb2O9+Rb8k27RMjD1Vo++NRtHW3cuNk5UQv3EOHrw25UnUANDOUd5/dUwbqr0SFrbSd+5g9lzQ0m6VkfJnXv0yj/q6KpnoKWNtAhjOcnX6yi500SfUo98SAnaPkLetcU+qsy0QqYgLTCYX764jazbrZQkJ/Dmu6GkNQG04PmWB9YxlaPFG/qIdnDndxYn0QCSrCO8PieMwml3xwxc272d3/7Om7QO6L6cyGsv76BK00+CiyfPrDSW03fhEHPn7KGm7x4BS12xibhChOMG1kRfJdIvFI9jReRu3cJ/TLDzYicoS87w/NNLWbu/gvaPtU8LGHqJWuvO7y1T0QIDGYd4fd4uajT9xDl5jKT3pCUyZ/Z2bpraeyc2jL8tPThmxUDBuYCN/Mdfw8i+3UpJUrzJn9PZpae/uY3z4duZPW8LyTeM8epX6pENKUHby8Z3bFkTfXckXlOVn94C0Iz7mx7YxFY9uF1ztlP08N2fiQ4iZ8dWfvuMD+fu6WEgn9mzndmVUc8hN09+v+o0WqD7fAJzXtnBHQNIC1P549PLcIyrol1yv/1yzvht4Jd/205OaSvFR+J4490tpDc/2D/ndoQxe95WUq5P8I+mhw3zbVkbU27yz9TlX2wBuIfbGx7YHhgzCTH0EmnvxrOrTqEF+i8f5PU5O6b0T2tWDPaOu2kSgkfwD8hjEjxyTm3bT1BiLQB9V1N502ofDcMKLu888Gjpq/Zya9pVZBUXwyL425xQfHxjcXbcT+LlRtOMaJAjbtEcuDB2wVxG6tYJ9qyKolIJnVmpOLudNC0BS4jxjiTa9Ftdy122+EZgaRXB4SudgI6M7RPqzWgC1Jyd2N4H2m+kKDES/4TiKfbbVaSEbmJ3jmnN3TDAvm372HKxkcvRERwobCFn+1FOX6/hwp5IXpo71p7GkZmhprmMUN9wk/0dTHx5Q3rnJE5+gZT1TjgxWI39W3a4nuwBtCQHBvKH5Un0msb76xGbmWt+lK4HN++h5IVvYt7KJCaugynr83jrRU/Cc02GadrYuNyLlxfuwtt7H67uR8iuNYpJRW0OH8xZx76bY8TlQBW2b9rhltoLaDgaEMgfzI/RN+1NYJgEpwDmueQAkL11G3+1SEXeX4vDfHvcT/UDMnZaufDsynT6mkqwXrmVo5m5rFkaRtLN22y3CONoThk7rNYxewo7QU9h0nHcVq/n2T97EZH1MTYd+iuxecMOj9N9gIYjfgE8t/oc6v4a1rxtj+eZAUBKuKULv/vwBING53HAwYtFnpmj8Ve3sGGZ54idbu5HyHmEh+OvbA9hnsWxcQIdQFl3lTde9GLnFVOH10xfvqI6m0Wv+bK/aEy8+ismteuP5in0f2QHSTiwxp83vXKNzbx5ir+95M2J3Ds4v7sGr7ODwBA7VjrzzIcnMI52evKPpuBmFcSzf/FmV14/aDtYv8yTVxaZ7Pc4Sk79w/2TGxbMPMsUJl5OitorvP4Xb3blmfyjbiFo6dTlK6qyWPiaL7HFY+rrL2f1G3Z4nukHNBz0DeA5i+MMTGHDjThfbLec5+O+QyAQfJ55bILn7PYD+MWU0TtYj/dflvMXmzModDou7XzEdKtUOqedCCs5H7IL+9CCSTdx1I34fxjGrivd9DeUkZZ5i2HUpIdPKN/6DFKgMPogfsE3kMiV3DmZiLnLce4Oa9Gq1cjVekBHVlg0rsEFgIGLm6aqV86Zie19oP1GcnaF4bQ9j36pEpVmTGZ9CxGWYaSUdlB0q4mOylr2hkVxprqJWIe9ZBffJdA5lrTKTi7viGTt1kImruGM2q8lY2s0biE3mDghlJSeIHDrNmomPirRfgfL2ea4HKmlPPsMf/x/7/LX9TdMJxXss/NigXcmU78DZ0Cn06J76CKGgihbLxb6ZE2KYdeVo/zhj34kFHVRVd0FqhZCzD2xjiqfVEpP1lFeeN6BuDtK+ituklM1iK69HMvZ5rgm1VGedZpnf/Qef9uQP60lBkUj7u9ZYx7dALo+AhevYWF4DYaeKla9Yo5bcj3lF47z3997i7kRd2i7chYLzwSy00+x4v29nDl7CfP39nK3r5Vtll6T7NR31ZNz7S49BqCnDPO/vc+iiIqP7re225i/vBL35DruZp7i2R+9yyvb7kJXBZazV+JxrJ7y9BT++3tvMntT4f0fsW6OI+/45SCTqtDoDKBpZeNyD2z2TbThQcin3IoC6Mw5wrN/9OdgcRfV1d2gaiZ4xdTld2ce4U/PO5BwR0l/RSE51RJ07XexmD2+XS9tLPjI/jHIG3B5x4plu6uQdTawwWItb3pm0Nl4l1WvWOB1vIG7acd4+ntv8tq2Oxh6Gsm9UW4UKF2lLPvrAj6MagRtN8HLPbAdu2r4UGTsWe05aSsKoCPrML9/LoBDJSb/KJvZsNxzyvK7Lh3m+ecdSSy7758h9K1lmL+8Es+Ueu5mnOSZH73L7JCbUzighXDHFURfe4TnjQSCGchje4ZnqKIEPys/LNwPErUrlYRjxcgARdWjphfxIGuUvXXs9ItgwbItLFuynT2na4w3Tr2U89v3s/DN9ax0iyPtTh9aQFo5vvzE47fR6DUc9vPlT3OCWbF0K45exyjplgMaik8f58NlW1i+dAsu/ueokhhvy6op6tVhQF750ewHUFRfw27VBt59fzeHssc8cmtQk7F7N++/v43dZ+sZ6L7HqQOXqO1pIi7yOm11ZQRHnaGk14Ba0kDEGHsizzUAcOt0yqj9AeepHpr8cQ753VPYefhQ3Dlh6UOn5mrCft5/PQDXkCQ2e0ey93ij6XmiFrze9sQqerqb5QDpu3eQnP+wV2Ob8XzLg9VTDPrq7mqCLX2Z/+EekvK7AD3DZblYmYewZMVWzC33cb7c6F1d3118zf15451gXLedp7JPjUGr4WpcDO+9HoBbSBKbvSKJOnmP6RZ4lE23cV8aQlKVGmQN+FtvZG/eAOg15MXH8O7cDfiHn2dPcDTx5xsoSk0iaMcVitIvsy7sBoU5Z1m77iQd6BkuvzLBziEMSil5R49iY7GJDz8IwHnrJe5JJ75f00/a7h0cK7g3vcu0KnIPmNq1KYlQr0iiT7UY4xUXzTtzNxCw8zx7Nkay98T99qq5fmA/b8wPZMXKfaSVDwF6hu7kYGUewtIVW1lpeT/9QTTh/qbn+K0oE6quKjZa+DF/yR6OFXQDumnL1/XeZd1yY7zctqVR2afBoNVwJW58u6JSmybEq5/zu7aTcrN5WguVTaV4LHfitYXbWfGBH7bB6dTLMb5dFjvqn90bI4k61YZBJeXqkSNYW2xiyQcBuIRdpkmqAwwMlWazasUmo/2rYkirfJh/ptiKuu+fzko2WPgyf0kkxwp7jP6ZpnxdTxk+y4z+cQ9Lo6rf6J/c2H28+3oA7puM/Tn61ET/QFtmBDaukbQ8vq9xCASPlcf6lpZBp0Glmjwl+6jp06NDqVSjVKhRa8f/TqtSo9SMT5tYvq67ltB1W0itUqFUqNGOGUF0Wi0KU9naSXfKqev96PYDeh0Khdo48x5vLWql5iFvqY1UPMmeB9tvYrCIwLXrOF0x1eI46DUaJrgVXW0Gbz3vQETedDcADTdOnqagqnVagQGgrc3gzecd2HltunIMaFQT2q/XGtup1KCd8E0ZjUqNasLeoF6jmb7t46p6cKaJ5Rgekn9qOw2olWoUyuleNVYb/Vbd9kC/TWXPw9IBDDrtZL+NsfNhrzFrqi/yxvOO7L4x+c0gUw2oP9V4qbl+4hQ3a9un948pLnqNBqVy8nNrU5f/gLh8BP+oKy/w+vOO7Ml/TP4ZqmaP7xqOXBXvZwn+cfk//x2eaVG2cyg0nrVrI3F2jcbFNRqHNTsJiiv8xL4kOlh3nQ228dz5yA9HPgLT2L8+/ib9H+tjip8GSi6G+xN1ruzh3+3QSDkfHc2C1zxx3p5D5zSzyN6KHBKOptMtnaZE9bCpHC+cw3Pp+oxmo7KmUja77cXBOQoX12hcXKNY6xBJYMzNh67EfRb0VGSTkHSBHunHfKD570R27/Z4/7hE4eCyj427s0jaG82iuV64Rlyh6zF9xbenPIuEpIv0TfzUxGeEtPE2m1wn+ieG4D1G/yyc44Xrzqt0Pw7/yDpI2u3F7vO3Jm/xCwT/QHx+BY9OTmNFA0VFtZSU1FFSUkdxUTVlDX181EWU6dCq5PR1SCftuX8iTGP/3YY+1I9nzJ4StbSHfon8oasK6LW019VRfKf9gQ9EqiT9DAxKpy/vEcv5pNHKBqi4VUtxyf141FJUXEtZXd+nE/+PyEP99imjlU72T3FJHXdrumiqraOkrIPH9xlPUEr6GZA8Pv9opAOUl0z2T/n/Bf9oFbS1tY585FAg+Efl8yt4BAKBQCAQCB4RIXgEAoFAIBDMeITgEQgEAoFAMOMRgkcgEAgEAsGMRwgegUAgEAgEM2yL8UAAACAASURBVB4heAQCgUAgEMx4hOARCAQCgUAw4xGCRyAQCAQCwYznoYJHr9ej0+nQ6XTo9eLLVQKBQCAQCD5/PFTwCAQCgUAgEHzeEYJHIBAIBALBjEcIHoFAIBAIBDMeIXgEAoFAIBDMeITgEQgEAoFAMOMRgkcgEAgEAsGMRwgegUAgEAgEMx4heAQCgUAgEMx4hOARCAQCgUAw4xGCRyAQCAQCwYxHCB6BQCAQCAQzHiF4BAKBQCAQzHiE4BEIBAKBQDDjEYJHIBAIBALBjEcIHoFAIBAIBDOez43gMRgMaLVaNBrNRzq0Wi06ne5xm/8PwceJz0w+RL8TfNrodLrH3s8fx6HVajEYDI/b/Y8NEfePx+dC8Oj1ehQKBcPDwx/rkMlkaLXax92MGYvBYEClUiGVSj92jGbiIZVKUavVjzs8ghmKWq3+h73mpFIpSqXyH1L0iLh//Lg/uuBRSaivr6VPOc15vZLu1nb65Zop0jsmpOsZbGugrqmXR5kDK5XKkcaOPYalMjQ6DXq1nOFhKVLpMFKZAgMmZxjUyGXDDA9Lkcvl6PX6ceVKe+oozC+hdXC6Rn3aGJD1ddLRM4T+4Zk/VTs0EwKhknRQU9OM/BH6lUajmRSfYakcreF+q3So5MYLVK5SAzrUcpkpZlMfw1IpSs19kapBITOmTcyjUGtAp0T6gLIe9zHVSo9WD2hldLZ2MKz+BAft+2VqPtsbgUEpobWlG/kUHVlnAFDRVltDa5/iM7Xr00Q12ENr1xBa3RANVXX0K/9+n+v0I6PXg/PpdMhksin62zBShQr0auSfUf8eHpaiGplQGtCqZMbxQK4E9OhU8gde69LhYWTK+xMDHRrFVGPDMFLlaLvujwWfhwmFcrCb1s7Bcfc6g0ZKR2sH0o94nep0uhF/3Pe7Tq0w+uczHtcmxV35MeKuGo27epq4yz7BuD+y4OnM3M6CV17GJbYUzVQZlJWErHZhX2H75HRrV2JudoxJ1FJ37Typl8tQPULdcrl8suCRyVFJByjNLyH3bgdKlRyZTIlW0cnFQ2fYtPEgUSdLaB9UoJQbfzNW8GillUS6LGWV+3Zya/sf1Q2fMGpyo/xw33qex3UbUHTeIe3MZZomBELScIOUY5l0P4ISU6lU4+IzLJWj0w5x63ImWzccJCw2m7ttUlQqJd115SQnXaGiQ4JSIZ/2YlAoZNTn5xK2LYndJ0po65eilI8f4BVyKS3ld0i70cCwUo7sMQmaBw8Kw2g0Y64YVSdXz6Ryqw/oz8Pb0o2LzZ/c6qOhKxfvVW5cbJryKv3UMFSkYrUymJuKsR1GTkVmKhnlA4CEvJMp5Fb0fqZ2fZrUJG/F0jeFfvU9zh1OpXLg75m2yKjISCWjvOeRcmu12ikngTK5gqHmWs5nl9MxJEUum75vqjRaNCr5pInERztkaLRymksL2RlymM27zpJb2YtapWSou4mzSZnkVXWjVCmmLUOuVNFbfYt9O48QeuAKZS2DqJTyKdpVw/nsCjpN7RoeHkapfFyT1Uen8mgoFuuSGRyTpmvPwtPSg6yOaX82JaNxl6FQSakpKOBGWTvDcsVnPP4Z4950q8AY993nuFrdh1qlRNJ1jzNJmVyrfnjceypLiI44ypa4q9xtnTrukqZqzmVX0DUm7irVoyiHyTya4NF0EOfnjp+fC8vsQigfHneS4UEJ8v5SNtm5E1PQPjnd3oP9N9unKBgwGAADWrUCyaAEhXbyoDFe8AwjlcvRGgBDH3EhO3GMu4MeLTqdhCsx0dhax7Mz8iyH08voHFSgmCh4DFqa86KxXRnInTHXi0oqYXBINrLaotcbQK9HpRhmaFgxxWqUDtnQIIMS+fgVGr2KIYkEyZAUtX5CfskgQyOrXWpyowPw3naWHtkwEsnw1GJyyroMaLXjLdJp1Ea/3G/L4DBqUxaDXj/Oz0pTxoaLEZivCOL2sAr9lJMNAwaDAYNOzZBEglQ5WVmPFzwy1DoFdVmpOK/YyaaI8xw4do2qDikAbVdTefVFP1Lu9qLTKk0XqQy1VgMGLXpTmkIuo+lOMTEbtvP88l3k1A1hUMvH1KEDdJQei+Ndv8tIDCoU01yYSpUKtVqFzqDFoFOPWS0y1mswaNHrVMYZsUyBRq1Cq9eiVavQ6NQmO4cZnsLO++JbozOWY9BrRgT2ZMGjR3UvnTWLbEitkaPpvY6/tQcX6oeQTOFbvVKKRCJBrpz+RqqbkMfQlYvPKjcuNhlFlFYpQyKRMCQd7b96vQEMWqRDEqTK8X1IozCWJxlzHZgqYkgiYUg63kaDWo5kcAjFnRNYW22iaIzg0apr2LJ6JZuPl6LSjnYuvd4A6FHe7/MGYz+TDUkYksrHr3BMU+9YxrZRP/4EEokE2cRZ9APTB5GOrLgZ0OuNNkgkwyhN+TWyISRDMiqSt2Hpc5SBUW9g0BsALbKhIYakinFtue8rtelCG3tOq64i1Goloal3Rn01yZ4x+acQPErTrFdVksZ8u4Pc6ZOhkstQqtXGvmlQo5QZ+7hBq+LG2ZOcKe0BDKZVgtFyDAYtBp0KxQMEk1QqQ6FW0lt3nfWWW1gXep79iZe5UdOHFgPKtmJWvOTM+lO16FCPXC8Ty5cplPQ1VnI8Mo5XFgYSkd0GBuWkdimLzzPf7hBlpnZNJ3gm+9mAQQ+GkTgae4lOKWVQMoRqJNx6dDod93dLDAY9Op3eOP4ZDOh1KiSSIVQTbgQj16Bq/HWqNvWTsqNbWeV3bILgycbHyouMJtm4MnVaDbpx2zV6NGPG+dG4y9ExTOr69fgfKDUtHGhQKWST42hQGyeLw8aYqTSmscqgRa2cIv8jxF2pVtJbk0egRSi+W86z/2AG+XX96DCgaClk2d+cCT5b98C4yxVK+hoqSNkdy8sLg9id2zFl3OU3z/CW/WEqBkbj/qkKHll1KquXOZJelIe/jQX7rxtnIVpZG6nbA7GzXMumQE/MF7hz+G4fOmU3pyaml3aOKVHDzaQIwuJzaarOZKO7P9situNitRJrlyCutY5f7xgreGRKFVrZIGX5xeSk5+C1dhu+SRWmnJ1Ert7Fwfz7Q5AOuXR4ZAYzIngUdezzWM5fX3iF1REp9GjVNFw5iLetFZYOTgQlXmFIDZLyiwQ5+uEf7IqH/xGaxnZ09SCXYoNxXrMaGwsnth29jgJQ9pcSE+iBnZ0DjtbLWLUumjoZoJZw6cAm3OwsWWrrRNylerQYuJEYjJ25Ex7rA7BftRi30KO0TLyi1INc3D9aV/jJYoZl1ezZEMCFOmPg9e3XCXbxI6N1iLq8w3jbrcbaxhGfTUm0Kw1Iy08T4ObPtogdOFuZY+u+mYL6BhL8V/Lin17GPfYifWPuKd3FKazfeIh7fVXs9fFhc0QE6+ztsLKy4XB+37gby4jgGR5GptIBarK2xxC0s3Qkj1YhpaO+ivRzVzh5+S5t/cMo5DKkMjlajZKmO7c4l1bA9bJOVBpjp1cDtBZh5x9DZrUEvVpuzK9W0nTnNpmXC4leH86ykByGphQ8MqTDEtpbmmi610xe2g2yb9TTL1Mgl8tRKmTUlRRxPq2Aa0WtyHRq5P3dVDe1UnajhLKmDqoKKigua2VQoUCnUdJUarTzxl2jnTKZDKV8iNqbJaSl53M5+zb1naa2TRI8g2TuX8fsZ59n+YZ4ymry2WK1GreAIBzW2GO92oYjBcbVxv7aLEIcrbGzd8DRIYzrvZMH9t6azNE8jtspGFDB4DXWWXmS1a2lr/ocAWsdcXRwxNZiCV77b6Chn5NbAvB29WKNuyMrbQJIr+oHdPTVZhLq5Y7jWkcc7VcSfCCDbgVoh2rZH+iEo4Md9hY+HCtpA0DaXUi4sxP2Nu6Eejux2DyMUtXoNmbNlVgW/vkFXrfyI6uimpNhmzhRWEfx6Wj8/DYRuikYh1VLsVm/h7S0k4R4OGOz8kO2JN9CBaglE+ttnbDdo6f37plxbfSJuYIaUA7Usj/IBSfbVSx1Cia/zii4lQM1U6arBquJCXDCyXY1K312kH9vCOjiWOh2fIPccVgbwOnbTbRUncPfwh5nN2/87eywXn+OAWUpO9Ztp6SzhdSwIIJCd7Deyx2blUvYeqwUNSDrLiDcyQl7aze2bAslwDuRGs2or6pz97Pgf1/gDUsvLlQqUQ3Wj7enUTKu5eMEj2lrob+hioysEs5FxzJ/bTJVgzJ0Wg2dNXe5eOEGGbl19CnVqCU9lObl42nhwqqQC+RmF3O1rBWpTIZaq6WvvpKL6dfJLLjHkEI5MmEcdwwPI5Ubx56WjFSc7dNGV+s1SgbaGsm9lMexs0VUtQ2gUBhvuFOWL5Mi1xpA0c62TRHszGoDvXJc/oysEs5G7ecdh2NUD8qnFTzD3fnscLzv580E+CbTpm3j5Jbt+N2PY2kHPS1XCHFYjfUaexy2H6NLqoXeAkK9QrneZYxL242jbNiURHNvBZHOrvj4+WJtZ4edzz5qpcYxurvyEhsdrbGzc8TJOZzCQTWgpelmCuss7HBx98bPxo7VQakMje253VfxX74Kj6AgbO1ssfXZxz2ZnvbMSNwiTiI3RpmryaHsvtQwRdzlaA3DnA8LY+vRW5QVlHIh8y7tQ0bfKNRqOqrHxF2uRCmXoVDJaS8v59LFAi5cuknZvX5kMvnkuCgfHvemCydwXps+OklXK+hvbSTnUh7HzhZT3TZojLvUGMfe+koupt8gs+Aew0ol8vtxl7cSGhLBnpx2Y9zH5M/IKuHM3hjmO6ZQOyT/LASPlqLE9Vj7JSPXG7i4yZq1Oy5jAEoSArF0j6NHq6WvOJFFf1zMyYYObqVsYtXY9D8s5GD52KVsNblRvnhtT6Px7lHeemkRh4p60WolJPva4LYnm7HzufuCRyaXo5YNcykpEVv7bTi77mTOG4EEn6qho7yQPWExLHx5HeYuB9i89TRp+c1I1aMz8dEtLQPt1w7gsGYbdTo9srJTWFt5ktEoRSurItjOml3ZrSiq4pg7dzkn70rQ6vRjBls1pcd2YOW7n24doG4k3NORw3lNtN5OI+l0ofHiV1cRYmlNfEk7DVl7sXDYRoNCS2fpeVJO3ECJgeKDLrz6jh+3B3Voh24TuMKS6Gut43x1OzkMK79YevSAuoFwb1dSsm+RFOpG0KFbANSeCcPZbx+lRZdxWhvA9S4DoOH8bk9C4m7QUXaIN176gMPFvWi1gySts2XdgTwaS5NxXhtGlVo/7mbSnheD/drd1PeU4Dx/Dl5xt9Fptdw5EoSFYxRtYxTPfcEjV6roqy0jMfoQVu/68c6HuwnZdpJDp8qR6NTU5lzAY1UAf7KM4cY944qNUqmi/OpF3FxCcXaLZqnNLo6VtqNXK5BrdMgrrrJqXQxZNRL0agUqlYq7uek4O2zC2S2KJe+tY+mmXIYN6kmCRyZXoJK1EeXkxcKVO/Gyj2Tp0hB2X20DvYp7hdlsDYnGxSWKD9/dzP78NuQVGbxnGczqRb68u8Sf1R9uZqnFPm5LoP7aBVxdthjttN1Nyp1OMKiouHoeO5tteLhH4xV4hJyaoZGZ08QtLX1nLj5Wblxs1mMYusHad99kXeIdtFottw8Fssotnq7+ejavdSL2pnGSUHc5AifvGDrGju0DZQStcSKuuAuAmkvhuPgfpqOzmEBbH3Jb+7h1PoHzN43nNZUp2KwI4I6khf1O85lvGUOHVktt2g5Wue6lW3aPvU5uxOaZ1tjltZxIiOdWWzfHQzzwOXTNWE5TGu4OGylvbyPB0w6/xCK0WjV5e9x4c643t8csURr0Tex1c2DXpWb0hm4inR2Izani+kFXXprvR+mQDu1QGb5LXuAdrxMMabUM3TqE1TI/Sgd6OBniOb7eNX7kd4yZDKiHyE89MKaNx7FZ5sct2RDpW51w3HkJrVZJ0ZlE0vPbARmnNztMTtf0ciTACdf9WWi1WipSQljiGodE30mk43wWb0xHo9Wh77uG+zI7Dt8eRKvtJMpiASt8UhmQF+Bj4c2N1nvsc5rPAvdjDGm1SIoPYrUsgLLBVhI87PA/WIxWq+bqTifmvOLJbe1YX90j0tWB3Zeb0OsGODzRHucoOsdcc2MFj0KlpauqmECvTTi6RrPW3J/Zq5NokGsYqi9lf8R+PLz3seKdDQQeKWGgp5GEsChen72GOR/uwMUtipCUUuQaHd1VJaxftwU39yjMLbax/UI5SpUS2YQZv0yhRNbZyOlDKbhZbWTunFCCwo+zd/8NWpQa+soL2OweygsLNnHgeifolShUGjori6csX6FSoeuqY0NQOLuy28blv9+uNSv8ecU6mbqhaQSPpo0oZxsCDpeg1aq4EuHInDkBNOjb2eswnw+DL6DR6tD13sLPxp6oa81otUMkrV+D874C1EN5eJi7kmEa3O5lRrLGOZrG7kLWvDYbj6ibKLRSUrc647Y7m6H+KgLtnUm8bby3VaSF4RqURHdnCd7L7Tl6R4JW28GeFe+zwjtpnOChJxvrt98g8GglWu0wJ7c64xGZy3B7Fg5L3bjaD6hriXBy43yjaoq4y9EapKSHbWXRsk14eO7HYVkwLuF5dGi0DNbcJiY8xhj3+RsIOFjAoE5PX20BXs7bcHWJxs0jhpQbbah0Bjoriwjy2YKrexQrLMLYfrEC1ZRxVyHraOTUwRRcLTcwd94WgsKPExWbT5tKQ29ZPptcN/OnhaEk5HeNxLGjooggn1DcPKIxtwhjh6l8hUqFrrOGwMBwInPbx+X399yEk2s09sv9eNU2hQap4jMQPOoOdrpbEHKqEunwMHdPBfP+qhBaBgZJ3uhC8KkqYz7dPfZ6BJF6vYRDmz0JGZMe6erL4XFbWmqu7g/Cb+cFam+l4Lx2M9VaAB034tbjEXp6XOcwCh4pSo2K7rKrOC7ZzqVugGGO7YxhXVIF3bV3OBR7mBVz/bFZd5SomAyyb7UiVSmmEDzQlZ+Ak2M4LUDzmXDst1wwLflruBoViPfuy9SXHcN5zSaqJq6m6/s54ruUOUscWB8YQECAH5bvvoLTrqvoAX3PLXaGBuK5zpUP31zCwZxSzocH4r3/+oQZqoYr+7xx3XIWmdEqDng5EnG+ZjSLro/DPkvG1WUx/1W8D92kNiMGZ/9Y+uVyjoc6s/VkORWnNjDnrRX4BgUQEBCIk/kbLPeKpTD7KG7OW6kx+fn6gfX4RqRTc+sEbk7h1E1YVOq4HoeTy17qOktYb72W8w1G3/UUHsRxbZgpXkZGBY+S/sYqTiWl4rwkiEXm+9gTe4lTF6vpUynQArQUYesbTUaVBLRqlEMNbF4RxOa0RkBFVvQuFtudpsugQT1B8KBVo5DUE7oymN3XjKuM1eeSWB6SjUQ/eYVHJleglLWyy8Ybj32lGIDbxw+wZHMucr2K9qoy7jQPo9fISN+1nQXrc+mvyGDR6liy8q5jaxNKQlouG10iOF3awK7V6wlNbwKUZOzdyeI1Z+lHw4WtobznlU6fQYseA2hHH9ab9AxPTx6+1p5ktAOD1/CxciDtnvFUd34iru4xlFxPZtnb7+LgH0hAQAA+zkt5e5EDOWN08HD+Ad5/410cAkx5nJYwf6kXucU32LTWm0sNxgGh59YpfP3Wsc7NmoUL3SjsaCLB245dl5uMBRkqCF21mtSKIW4d2YbjWivWrt9NToVplXQgH7fFb7HY0YeAgAACAhxZ8N5SDiSfItDZl/R7xrmorukS3rZbuTXuqeVW9nk4EZnZBvSwz8OVhCuVXIkLwCPsvGkW28l+T1si0kyz2P7r+K8NIrsgF78V74yr9/033iHqypjn7TQ6DGPa6ONmzYLFXhTVl7LNzp2Dtyc8L6QoY+Nq18npg0X4ugRzocm0styZg9uqQAq6GonzsmVneiMAkrwYLJx302z6WX16FJ6Bp+mVFRJg48+N1gbivWzZedEU0L5r+K0JIutGBr5r13GhyeSrexfxst3KrXHPO7UQ7e7E3ivdoCrDz2XjeHssvMnsHL3oRm98CnQMcsxnK+4xJcaTVZksc0+mYlDJUFMlJTWdyLU6GtMPMc8yjoohDaDhVHgoOzJN47JOg84wQLL3ZtZGXEMGNGUn8/6CaEp6pagVssmCp7uZjNNpbHDewttvbmd7XDpHkotpGZai0gOKdraGhBOR1QZ69QPL12g0EwSPGi0DHPPegsd+U7sqM1jmfozy6ba02nJwtfXmYrPRb9rGdLzsd1GnbCLWw4ZdF4xx0ZYmY+0eS9v9XpoRhb17HPe6Cwm08SKr3RiXpux9OHvsp769AH8bFzJNc4HBiqO4228h58JRlsx/HyfTNejt+CHvrfTnVNIBHLyjuX+51p6PxMM/ZczWp3FLy9d2A4VDo2W6Wq2nQqHkYoQr2y73oqo4jOP6owyMuWlMFDznQzdj4ZZMnQLoL8Jx/g7S7smQtlRRUtOFQqunPu0g81bFU6sy0HAmnnnLY7kzIEeHcWtbZ+jnqOcmHHZeRw7cyzLG5VafbOq4dzVz+VQa6x1DefutHca4HyuhdVhmjLu8lc0bw9md026Kez9HPDfhuOsGCqAxM4n3Fuzjdr/MGPdxgkdtsicUr7jbAOjLL7PUI4Wqwc9gS0tan4b1nHmYr3XBzc0NFwdzXnlpBacL75K4yZNtafWmnF0kBoWReuUmcZs8xqUn+G/mSMH4VYtRwZOKu1M4tXpTekwgnlvPMvYxIbnc+GCdWqOg8vxxnFefNXZWZQ+Ht+7B63C5KWcHUWv2cfiGccanVyuMS3BTCJ7OG/E4OuygCWg+F47d1vOmpTkt1/evxycindrbJtsmPryj6SbW1xLXqIvU1lZTVVVHe+8AwyoFVVkHcFhoze5zhdTUFrHFwZ4Dl4s5sy0An/iCCQWpyY0OxCsszSR42ojxcGRXeu2YurqIWWeJa/QlamurqKo21iVT6zAMlbE1aCunLl9gk+c6rrTqqDjszTKfGCrqa6mqqqapvYdhhYrWvDicnSKoM/n5yr5A/HZdpLooBRenCOqnETy1nbcItvHkUrN6JN3RYQe1Uwge45aWFlCSFZFASKSxw6JXIRseRq7RoajIw8pnH5nVEtDrUHQV4viSO+98uA1Lq20sXbgeG49T1MiM37EZJ3j0Wobqr+K6MI7CfhkYNJSeSGRFSNa0gkcx3Mw+r00cvDkEKCg6dpBlwdnI0FCXew7rD4Ixt9jGgnd9WbG9gIHKTFb6nqfmTh4Omw+TceUafvY7OHb1GuvmeY7YuWTBemw9T1Ov1CFvq+fAxu3MX7yRZQGnqWgZGHkge5Lg6czFe7WXcfAcuI7vai8uNxvPt+cdwNUzloKcg1jariOzvI6qqirq7rUxIJOjHuPzvit7WWrtS1ZFvSlPO4MyBaq2HHytfcnr6eFi5AbWWHlzoqiaxqJjrLX04XprIwnejkRlt5hKqmbHahuO3TU+e9LdWMnFY7txXLYCa8dIyity8LK1Zl/GHWqqqqiqbaJ3WIq8LgO3NT5ktpgGnv58ghwjKJGN7UjN7HVzIjJrrOCp4EpcCL7hF0yCp4Vod2f2XjYJnu4r+K3dQNb1y3jb2Yyvd2gYhXpM+fpBzu4MMraxuJqGm8msWe1HYVUxm209OXK3b3ynlpUSaGXcdh/HQBG+nkGk1clMNlzFy8qf6+31xHu5EpVpFDy9uXux9Iji/nOmXdeT8F1/hp4RwTM+P125+K7dQNa1i/g4+ZFhuhHTd4Mghwhuycf6qolIV5PgUd7Fz3P9eHssPbnUNtqPRm58chXIqwldEUnSjTa0gLT4Aktdk6gcUjPUUIjv6s0sWb4Nyw/9eMU2hXqpEp1cwqFNwWxNbwSNEqlcDeoGdpj7MXduCCutt2O+PJgly/dzpU2KRjnhjbCRt3Gg+fIZPF0vYtx006AwPXowTsCge2D5Wq0G/YT8BnkVm5dHkpzfbmpXOkvdkqnon0bwNGfgvGYdmS2mtN7rBDlHU6toJNbDheise0YLS5Ox9t7H/XcF2nL24+C2n4aOfAJsfMg13j7ouJ6Aq8d+6tsKCLTzJLfbmC6pPo7v2u1cPhfPqjUB5FaZrsGmdgblCpov7mKVVwymYujIO8K6gOOMfTVG25rDeoc9VJluSZKaY7hb+FKuhN78Q2zcksjxfRvYde7OuK46cUvr3NZthB2vQa03oJRXsf2DcE5VSZE2FuBjtYmly8Ow/NCXV+2P0yBToZH0cik6hg+WBjHfIeH/Z++9u6tKsrTPL/J+gJl31pqZNa67367umqnu6nJZJn0lmZjESQKBHCAPkhBGeBBWSHjvbeKdkBDCyXtz7bneHnv9b/44VxaJhDRVSdbdaz2LxVHcOPvEfuLEPhE7dnC73UMibmDz7BJ+99s1zFmwmdkz1zBjZi3132J3w41LrFh2Kzk5Mc7u4x0YYiTCg2yaWczvfreGrxdsZvZXlXw5q47Hgm7318pL3az5ahdnn9mIAsHmq8zIO03vj+/whLm2Pp25ZecR4zE9iV88yNnV88jbdYV7e8v5csUxVCBqvcXC/5zHmV4TTYdW8cXycdf/Yw4HW50T6n20byVFW7+h7+U5cjI30htLXt9byrL1l6d0eEIRDUP9Nyyas582DRJ99fzpt8spPtWte6vqIJvnV1NzexgtEXotan2Cw9NYR+aiTQwDweaDfD4zh8YAgIMdSxey7lo/vo6TLFm0ccJshi4hnh4o4q9Ld46SuuPxfdpMRs6szyPnoL7MFB6+zqz//BM7m4x0XtnC3GV7dNL7+7jyzQO84RCN+1eyrOoqyZBe9uZlsu36uBkeNJ7UFvLXrN2M7N9or7/LM2MAiNBUU8qXn3xK9uZ7RADvk4N88UUODcne5e5o4H6rCdPTIyxZvIm+ZDs/3FNK4fabDHadJy9tbfL6mNgaalmStZM++0vK5+fyzXB49Hrm4k3JmaJka4wPWpZViHm4vLaGko1PCBBNvfL3pAAAIABJREFUOiKy7lAOP2VByX4aTBoQRQ0a2TR/NVW3jECMWCxCLKIiiVKyfBPzS2tpNGtADNnaQtFXmzjTJ4I0TMHXK/ho5d1pl7RU0cTuvApqHrkhodJ88hBfrXmEFBumckYBG284AQ+Hlq3l88rHeLvuMHPFRTpePGJR2UGu36unKG0DZ18OsjdzDRtum8bpqc/kRBJ6QDgxH/sKV/Hl9maIhaZ2eIJNrPx6MTdMQLCRgrm53DAkHZ76/SzJ3sWgrZ3CWbPY25iciXB2cuPBywmzngn7E7K/nMW+pqShHR3ceNRGwNFIcfpKmtqaWJWZzeF2/eU0eGEtv/1gMU0OKwdXfMpXy88TAnxPD5C2ZDcWyUXDrQaMI7OZkZcUz5jPtTYDhwvnkrOvIXljJ/dv1yPIw2zPWEDhqXYADBc38vGfSng5IcDWQd3yhWy7JgBe9uRlceBhJw9rK8Y5+WZ252ay48ZA8lkfUrCgiEajiUMFX0+670OM8rj6Ay/JT1sy9ozn1/CbPyziic/DuVUZrDjYDICn6xGXH3UCPo6XpL1+XRPYkzuT7EPPAHDd2cbn6btwRi3U5C2h+pb+8ZYQ7rDwk0Wc7FOBEFeKMphVeB6v0kzJ/GIaLQPULV86Wh7HA/IXFNNk6mVXZhrrk7NYwxc28OmHq3g1YYeCndplC9l+wwa42ZP71UR9Fm5meFzg9+jAJ2skwlb2LNnE+ov9gMyZNWv45xlHsMQDnClYReamZySI87x2L7+eeZReUSOhBTleuZrcI/rHYiIcIpoIcL50I1k7n6AlEsRjEeIx7Q27f2QiUZn2C2dYuugyJiKEkjFFWiwBopm1q7ex54kbiE1b/9TlE8TDFnZnbqTq8gAgcaqykn/+6hD9ojq1w6MNsXHhAqq+Meh8OFfFZ5+sYzBqoiZvCTuTTnVCqCfzq1nUvdIZeGtTNgs330cJPSf/i4Wc79fbuX5HNrOy9mJ0PSf7zx+w5qzuyD7cW8qyLQ+RPM/JnjGbA8+T8VW2Nm4+aidovU/aJ5mcHdQAjQv56cxacZLxUVhx+30WfTyLvfX6uPhoXwGLyvVZoIS3k725v+eXn1XRbJbGk+Q1h+fK+vWsP6WvpjharrFwbi0dfi+n8leydOtLIM6zmj38etYxegMKsXgMPVw+SmPNVv4z7yJyXOLCyo1k72pCI67bJfrtdm89e5qlmVcwj7d7PAFBIxUV26h56gFixBJ+zhRvIHvPU0Lj6h+1+4TyCeKamZ2LNrLh2hAgcry8gn+ZeYRB8cde0pLaKU/7kuoHzgmXbfd28dXCAp4a29mTn8WiRcvZsDKHv/4hm1O9PkK+frbnLRm7/kEWJzsmOjyP61azqvomAy0XWZEzMosS5nFtBYWbrr3u8IgisqoRkQROVm3iLx9tIn/5Tj6fU0XFuZ5Rh2d7xh7q7r6Fw9N0mJyR2Zu4SP2preRmLCZzWTY5W85iFeP4nh3Vy0yxazgmWjhWnkV6Zja52UvILt1Bq9mDtf4oGfO+IDu7iPK1JWTO/prqKwNERQvHNxawLDuT9KVZlB98QCASo+lABYWbv0k6PAK1BTnsvDkw4V7RoIWjZVmkL8khNzuT7NIdNJn14S/Uepg//u5XbHuc3AMQF6k/tI6MuQvJyVlO1pIiLnWYsT8/Tl72tuTSVZj6/eWUVN8loJnYtuA3zKq6gG1c37I/OUTusr0M2FtYuyifm8mR0P7kEDnZ2xj4Fofn6oY6yrY+JUAUTVbQVDe39h8h46tS/vmX2fxx7m723x8mEYvR8+Q6i+ZUkLFoO18v2UvNfSPRqI+bNUdI/6qUf/5lDn+ct4faBwZicYXmM3V8+uc1ZGbvISN9DXM21CNOEbQ84vDUFKyl7rHu8Dw/c5Q5VfWocR93t1bz5y+3smTpNhanbWL51ud4uu/ydfFlul49JqvyCDceNLBy8UYudilYXtwgY/ZqXc+l+6h5kNRz70HS07aQnrGdhflHuN5lJxKaZoYHkQurPuejvN08fXmH9VnF3ErO8NgaDpKTswMjYHlykrw5s8lbtpy8tEy2Xm0hOGE9NM5Q/Qlyx5XZcauDoLuZssXFNAh+GuuKmJ2WRm5uISWVhaTPzuNhv4ETxYuYPWMRWcUrmLu0lAsvbBD18+L0LhYvX8byFfkU5S5j+4l63HEQTU2szZhD1oo88tPTKNlzFVs0hqv3Gsu+WkBeTgkV2Wl89tVG2ic4PDFajhXy6axszj99zrFVhRyp76b+0DpKtt1MOjwWavJz2D0SmOmspzS9gPtOEE3Nk+57BZM0PpAlwL19+eOesYCMmUu5YYCA8Snr8hZTkJvFnCUFHHugz5r6jI1TXg8Yn7A+bxEFuVl8nbOKy68EwEbNihz23EnO2CDz8uou0j5Po7CkmGUzvyZ99XX86nPKF5XRZB3icFHeWHnHI0rSinjoSeA33qUyI4u8nFLW5KTzyYwNtEUmttWrIwV8OnMxJ5td+I3PJ+rzYvwM+cQYHi0SwdJ8lXmflvN12m7yc9fxx+zzGEIKAxdPMGNGFfMX7mDZ0o18nXOZwYBCLKox0HCTBZ+V8FXadlYee4kSjuMZfk5xZiULFm5lQcZ2Vp1oQVJUlClz/ugDX+elc+RlXU06PDLhqEzL1Sssm7+a//dXWfzHpxsoP9UyTf2thKIqrddfL6/GYwjNV0afa0XOOv6Yc46BwPRBy57hW1SmZ7Msp5TKnDQ+mbmD4aiZAwW57L1rGG3rgccnyM9IJ3tZDgtKd9JlkwGJppNVzJuTRUFpPkUrcikoOorB3UL551+wcOkKli7LYWFxNR2Czt7+B0fJmTObvGUryE1bQvXNTmTCvLxSTdrn6RSVFpP31deklV+cGLTsekzxlzPJzF9FzrJsFhTvpNMmj7xRubb+C367tAbPpA2ak5e0bm7ZxAcfrGJh+jY+W7SLo0/0Jfeus0f54osNzF9YzfKlG/k65yqWsEL71UvkpG8kLWM78zL3Uvuon1A0jnvwGUWLV7MwbSsLMnZQdrIFWX2z3dvPnyMv51rS4ZEJRyVeXr5E3rwKfvmrLP7zs42sPt2KGonjHmymcHElC9O2sSBjB+Un2whHVVquTi7fhhaPYXlymbmflDM3fTcrstfxp9wLDIk/dtByVMHjcqFOHvCjCi6bXc8do3ro6+jCZHXiC4pj21yV8del5FLHiCTQJD/+oEokrODzBpPLSfp1X3Di9tLxu7RUTUX0OGhp7qS1z47P68bq9CPLMrIUwG624/AEkKYw1HiHJxaS8HqDjL1zItgGumjvGcKf/MqNasky07VPJICht5POzn48o7ELMbzWPjo6ejC7A4S0IIFAslOG/Ax1t9M5ZButUxP1500kfyv5vIjqFHcMj7uXOu5FGQ/h9XhQJ8zQRLAP9dDZ2Y3ZrXeiREgc9yyJ5H11vWSPgV6DDW2ciWIhCa9PJBILE/D4UJNfl6PtNu5uk/PwyLKI2+ZAsPmQZBlZkpHlIKaePpqf9dLRPsCzFz10mz0oikIoJGPp6eNJUydPnvXQY/aiKCKmnj6ejivfY/agKCqa5KP3VRdP28x4vR7Mdh+hxFQpLONENBG7RcDhFZFlCZ/LidHmQVY01KCL1pedPG3ux+zy4HD6Ef0eTFY3fp8Xs+DE7fFiNdtwBWQiYRlLT++onr2WET37aX7aSdPTLtoH3YTHbfF93eGBiORgYNiIT5QRff7X2nbEDAFhkK6uLgZM0+dmCQiDdI4vE9fwebxoCSAmYR3qorOzH7eioQb9yJqR/Sty2HX1Bf09XfTbx7+GIwjDfXR1ddPda0wuOekS9gv0dnXR3Wdi/BCjOEx0dfbi8PjwBmQm76BOhIOYDAPYfBJKwI+kRdCkAP5RzkcRfV7EkZdMTMPv8Y2+c6a776hMeEYVNehDSvaPsNdCd2cHA/YJeTTe4XpSt/Edgziu4T66e4bxBoJ4gxrxRAi/x08oFtX7rzbpWTQZi8WIyeLAJrgQHuxj1op9WCZ1c72t+rH6Qm/UEyZvS5cJaSKm7j4anw1id3mwOdz4RYWIGqCvq4fGxm6GrE4cTh8BUdJ3F6rSaL9rGXAktyxreAzDo3x+1e9AjUzxxUeCRJLnfrcLi9lNUJaRJQlFkXAYhnne3EVr2yCvXnTzqt8+Zf0tAw5kRcZhMLxeXlYIayLGrj4anw/hcI88l4QsTZGHJypjtRgxW/V2tt7fx+wVNQiRSXZJis/cT2dXD4I4/t0RwjrQS3dvH25JRQkoaMJDStMKuN5loeu18uC3DtDZ1cWgefxSaRzXUB89vSM8mTimJWIhJJ8fn9s6hQ4x7u5ew5bT7a+lQhlvd1mR8NhtdLzqpqmpgxf9TkLhEIqsEFb89HYm7S7odhdlCYfBwIvmDpqedvC8U0DSdKdGC0+yyxvtrn/M+V0uLJaJdrcP63ZvS9qxZcCBJOt2d4+rv3XQgaLIozyZWH7E7r2jdhccngl2/3Hz8PydZeRYiZFBRFE1otEwkbCKpqloo4FVMlpIHd0S/CaHJyU/nITD4ddygiiaijYpiZQaChGNhpMIjeWMkGVCEf16bNz18eXHX5cVlUg0TDSioWkhEvEgLd/cZUvlcao2nWbjptNsrDrO6l23eDrkJRYPj26xVFSVcFIvWVXHdBnhkawQDinIskJIS25fD2nJvBTfrmckPDEBmCiKP7FjTYxsWzSfLd8Mf3vRlPwwErJyZl0W6au2cPBAHUX5y9h6/vlbZZmfTqLR6MT3m6wQiui81DSVkJbkoawQiYSJRcOEQiqh8Qk6k/0uFg2PzkhKkoQ2yucIxFWML5vZU3mc9SN9a8NJVm++yOUXVr2vqCqh0MTEn4qm6X10pF9MWf/Y9WnLT/dcUw18moXTa7NIL9uabOflbLvw/doZIG65xdIvlnLH/u1lv7coRq7UbadsSx09ntf/PNnuE9otrI7tqhq1e2iC3SeUj2jjElPKr9nd8KKZ3ZPtvuUiV16+2e7R8XbUlCnqH7s+bfnX7K5Mb/d3kPfC4YlEIsiy/L3O3wiFQv+Q5678LSQej4+muf/bn68io2l+Oh80UFt9ib01V6mpuUrN3ktUH3nEK4MXTfvu3Pm+UFX1J8Y7hcHWVwzYpW8vmpIfTiQT96+d4cTx41xo7P3eR8kkEonvdb7g20FC0yTM7S0c23mJPSN9a98VqmtvcrvN9nfrW/pMsvz6sS2ikXvJdr7Y2PdWx3R8a1urTtqft+FU/wb9WBO4d/U6T/t8U/75b2l3U/srjk6w+2Wqa29xp/0naPe3lPfC4QHds1VV/Yv7XaCq6ntx3sr7LvF4HE3T3tk+Pwhkddy5XeNFzyAr/z10UpR/2MMNU/K3kZFDe3/cvqUQik4zuERDf9e+9V0HvfddUnb/7nZ/bxyelKQkJSlJSUpSkpLvKimHJyUpSUlKUpKSlPzsJeXwpCQlKUlJSlKSkp+9pByelKQkJSlJSUpS8rOXlMOTkpSkJCUpSUlKfvaScnhSkpKUpCQlKUnJz15SDk9KUpKSlKQkJSn52UvK4UlJSlKSkpSkJCU/e0k5PClJSUpSkpKUpORnLymHJyUpSUlKUpKSlPzsJeXwpCQlKUlJSlKSkp+9vJXDE4/HkSSZoCilkEIKKaSQQgopvHf4VocnEgljNA4x0N/B4EAKKaSQQgoppJDC+4dvdXisVhOGoQ4U0UhINqWQQgoppJBCCim8d/hWh2dgoJegdxBNNKIEU0ghhRRSSCGFFN4/fLvD099H0DuEmnJ4UkghhRRSSCGF9xQ/rMMjmomGBELiuP+HnRB1ElctP+qDyEEjIVUgqlpQAn//hv1xYECVrERUK2rQMHo9pDkg4iAsmZADBpSgCTVsR1XNU9pIDQsoP4QDGzCiaDbUsBVlnD5v+1tVshKPupK6/wB1vld4g43eBqIFNWJHlf/ez/EjQ7aiRgQU8TtwYYRLoRSX3oh/UC7JoployAExJ7Gf9biRwgh+OIdHNKF4uxnqeoHbZ0CTzGjiEMMvrnH7xjmed7Uhi+YfaabIhCYZcA6/ZHi4G1k2o074uwFFEgBfEm6ismlagssBI+GQk8RbvCgjYfdYvQknoR/RWKosEPZ2YRh4hsdvRRONaLKAd+g+9x7cYMg6SEi2oAQHENsaCQ72oYjjXoKiCcXTjdj6CtlnmNrpCRhRI07UkOVbnt2EIhmQ+54S7GxDDprfyYlSJTNBRxutjy9x7941hgQDIcn8ep1BA4poRcWDhhc1YkUJGFCCZtS4Cw0vWsKulwsYUVQbGj7UkFkvFzCiaHa9HC5UZXq7jzy7hgdV0f+vBIyoYUfy905UabpnMqBIU+mZfN6IS/+9qDukozYammSjt4FoRnF3EXz5BMmWtONUegaMKIotec2tD4gjDnHCM6ZPwKAPegm3XjYuTNB9chspkgUVL1pMGMeRSXVOp/t0eo630UjflEzI5lcEXz1H9r0bv0b4KfU1EexsH+PSlDYyo8bd03DJOz2X3vAOmY5Lr9X5Bv1H2lMZsZE6YstxXA6aUAIDiG0NBIf79D7+rlxydepcsn8Ll9Q3c0mZikuxt+GSb4xLgTf3o2/lUtA4ro6RdtbffbL55RiXJDMhXzcdT69y68439A536/b8Ed/fKfz98cM4PKKJcNhNxHyZ0vmlPLIMQdyF89UJchfOpaiimCM365El6/eKBVIlM5psIaxYCY1zajTZBvFBbm9fRcWO8wSZ6HioshXN+oRLx7ezfesaqqsP0uMwEgtZUEUzIcWq1ynpL5BIyIrx+UWaWlvQVHvyujF5bwth2YImmghJZvofH6Fm51q2b1nH/gNnMPqM+t8lMyFFL6+3nYmQbJ2guyqaCUlmQrKZkGwZeybRNPpbbeQFJppJqCbqT1Ww8dBxnKKLiGIl5HlJXd5M5pavp6mnj2jIgRZuxTljJtY1t1BCDv0lJppQwk6U4SsIf6jEZx5C1awoigVFtaAkn10NWxAbr+F/0Yai2VFGXgKSWS+nWJIDjwU1bsBXlYPp852IQe/oF6IqmifY53WYiMVsDNyuJvOLj1mxfiNP+oaJKFa08XWKXlTViuJ7hXfnHhxF1XgbXqKEnaiRQQKXjuIo3IT79D3kkAM1LCAPPMK9oRrvs04U2YqiCSjdN3GWb8FZdpygbRhVm2K2MWBCjQmIjy7g2nqAwJABRTajhoyITy7hLNyEs/ocoteCKk3xYpQEVLEd7549OAp34G14hRKxoYhG1JANqfEs7iOXEV1WFFlAC7fg/GIm1rW3x2z0tn1BtqGYr2L9t1k4bvahhi26no0jep7X9QwJKKZ63Ku34iyrIzA0iKIJqOFh/CdqcR+8hOgWUBQBTerGf3w/9oJteC42IidsUw/mihXF24a3egee6w3IooAimV+vc0rH0DSFnlbUkIDclbRR+XGCNgOqZkGNCIg3t2H692X4hl2o6ju0kWhBjQ/jq8zC9OWeMS55X+LdsRtHcTXexlc6l8IDBC4cwVG4GffZ+2Nc6nugc+lFF4psQdUElM4bOMs246w4QdBueDOXHpzDte0ggWEjimxCDdteq3Nq/Ufacz/uQ5cR3QKqZkHqq8ezeQfOki04Nh0l2N+PGrKjhV/h+OwrrFV3UUL2d+OSYkMxXsb6i9k47gwkuWRAfHwRZ+EmXLsuIPqSNjI+wl2xFWf5AQLDQ6iagBoawn98P+7DV8ZxqQvf0RrsBdvxXH6C8iYuedrw7tiB58YTnUuKgBpsw7trN47CarxPWvR+NCWXptBTMqIodlRXC96D+/E2d47O7IjXt2D65XJ8RjdqWCDqesGVA+XMm/MVy7ecRY7Z0f7GA3AKf1t8f4dHNBNWTHjsvVhbjlE4fyWPLX3I7k6u78ohY9sZNNVORJl6dkeVrCSi+rIXMReEbWiiAfm1exmQfAZkTy9WYxsuj4GQZCGkWJF9A/jszZxbV0TlrguvOTya5kJ5sZ+/fjmPbUcOcmB1DlkFG2j3mtG8fdhMrVgMbXh9RsKSBVXs4nzlTAq2HcVg7sftGkQOGvAKbVgMrdisPaiKQEwycqnqC5Zv3ss3l09w45vbCH4TamAYyTeA3dSKYO1DFs0o/gGc5lbMhlaczgE02YoSGCLg6cdjHyTg7sHtHEARLYTlYZymNizGdgKihbBkJqwJ2JoOkr98Dc9cVhKKCVV1ILUcYPHSDfTLTgiZkQMWVHpwLy3EXvMAJWzTByTViCz0IjWdxPr7SnzCMKqvH2m4DWmwA9ln1F/AYhfuvEVYV59FNPYjOQZ1Jyc4gDTQhmTq0V9UohkVE/79GxGWHkbSXKNfWLJ/EL9nEGnaKWIT0ZhA19Wd7Kk9ThANFCNyYHKdHrS4icCJgzg21eJeU4l5xmr8ggHxzl6sn67CdegEjvmlOM8+RbY/xlW6GcufZiDsuI0S8aJYH+LMqMBefQR32XqE1ccR/eZJTosJNWIkePcs9rwKzL+djfNOH1rchjz8BFfFZly1R7B/lYlQfQM5Kkx6HgtqbBDvppVY5u3Ac2Aftq/W4nnRjYoHpecmwkdfMPybbLxDblTViko3riWF2Pc/1G30LoOUJKD4HmH/qAB3cz9qVEAeeoKrYguu2sPYv8xE2H0HJdaCKyMHoego3s1VCAv3E9QGCBw6gC09F9NfluEd9qIlhggc2oNt6RbctbXYM9fhuv9S/7qe0NctKIGXeKp2Inw5F3PmbkR/AC3Wh7+udqzOIfeUzomqWl7Xc889FE8jrkXjbFR5QrdRVEB8ehzh0/X4nQ59puStX25mVIz4d1ch5B7TuRQzEjh2EMfmWtyVFZi/rMRvNyLe3IP101W4Dx3HMa8U54VmZKEeV8kmnUu77qJEPCjmBzqXdh7BvWodwpoT03Pp9lnsueWYfzsH5/0BtLiA1Ht3Yp3aVI6uBTWabM+0HEwfLsc37EHDQeD0Bkx/zMV16DLec9cQDQOoioBKF65FhdgP1OtcepdBQBZQPA+wf1iI+8UAWlRAHmgctZHty0xse++hRF7hTMtBKDmGd9N6hLRaRG0A/8E6Xc+PVuAzetESgwQO7ELI2qpzack63A9fvc4lyYLif4F7fTXCjK8xL92LGAigJfrxri/FsmAnnro92L5ah7e1FyU08feqanlNT2H3LeS4A00ZwLd3PYb//l8I+x+iaE7UqBWx8SjCZ1X43Q5U2YAsWgEPxid1rNt6mmDUlnJ4fub4ng6PiXDIQM+NLSydn8bi+Z/xyWelPBus5+SWLD7586/5zSd/JWdpBQ96uwiFrBO++jXJREB4RuOdC9y9dYG7N8/yqPEBdq9lLA4oaEQJWkkkerixdR1FeYvJWfolCwqqeGkR0NwP2b8yk4z0uXz2m48pr7uKNNnhUZ1ILw+wuHg7xlAQwq1UZ3/B1luvcL44zqayLIqWp1G29QCDlgEaTpTy+Qe/4k+fziA9LZOay/fwBwa4uT+fooI8CvOzOHbnFeGQhRs7FlB15Dyvmu/wquMVathL3zfrKF+VS0HOUr7+fC7Hn7YQMNdzcEMWhflLKFy1msddw3TeWEt+yTKyF+ZRvGwWmYXFNFsEzA8PsbZkOUVFi9l57BoOv42Y3MuZdWlsudAIMQHZbyQSC0LXIeYVbKLXaSIyMhsjGpAt3ciuoWTMjoHg6Wqsv8/D+vt5GP+pDH/QjtRwGntmEbbZedjKjhE0D+DbtwbT//Yhxn9Nw/qnfJwnHiCLA/j27cQ2twQhYyWuyy90p0cyItt7kYQBfYZINBHTrPSdXcHvZmfSaHTDlF/lusPTfW0X1bvrsKpuwqNxX5PqlAzIhm7keIBwqBHhozzcdx/irizFfroFVX6J4+OPMGbsQ3SakR09eDeXYNtzEyUWQHlcg3lBDQoQkm8j/DoXT+sAatiOlpw21+J2FNmAbO5EMj3DmZeL816PPh3u6kcSBtGQEI9WYppdgxS3o44ubXhRcaOZbyHMK8XbLaB0ncfyz3/AuqcBVe3CtbwUW+VOhKwyfINO3RmYYKN37bgmlMAQsrEH2W/U22lUTxHx0GrMaUcR249hWViNqLkJnlqP8f/4AufjHhR7L+LLywiLS/EZvISUV7iWleC42k8UBd/aIiy5J5GibrSYc2wZQ9Mdd9naQ+BCNdaiPYg+L6o6jGzsRHyRrHPQiaoadO4l3Gj49CUHxYjs7Juo58KjiC2HsCzcr9tIuoX113l42gf1+3n6kUy9775U8yYuJUTC6mOEv+Thvv8Id3kpjnNtqOJz7B9+iClzP6JL55JnYzG2mtsoMT/yo72YF9bqegZvYv31Ml3PCVyy6VwydSIZn+LIzcP1oA81ZEF29CDbu8fqVO26nuO5FLaiSEPIxi6Czy/p7Tnk0h2ek1WYvyjFe/spkmkANW5PLiENI5u7kV3D36GdTCiBQaTxXHL2IdmG0BAJ1pVjzjiO2HoES9ouxJCbwPG1GP7PGTgbe1HsvQSfX0RYvBKfyUdIeYEzrwTnjQGiyPhWF2JZcRop5kaLuSZxqR/Z2ov/3HZsxTWIsoxmvoEwbyXePhty2xks/88HWPc8QAm79H42wiU5yaXxes6tQ8aHeHMvtqU7sJcWYj94T29nyTgFl0zEVCMdd/awdtuZlMPzD4Dv5fCosh3VdImijEyutBmIWa9Slr6KeusgCc3EvQP5LNt/hYRmneLmJkKyBU//DfZvLKdqfTlVa0qoPniYAaeNyIQAOivQzaniTHI3niYS6uVUWTo7zl3l1qGV5K8/SjBq4f7OctaMzPCI+hJSSDKNOjyLCjbS6TRCSOBa9TzWX2iEwAvOHt7Kjs0rmP3H+RxpeAkJG/d3Lmb9oSv4JQeqaCKqGBlsOsH2LWsoW/I1C7N3YsfJnS0z+Tozi/JVhWw+cA5vxE/7qRUsKduCRfJgfnqUW0+fEpEGaLy6h21bV7H0r7NYW3uFO0ehRiiDAAAgAElEQVQLydm6g8PrsihfU03t3krONVxj29dzyV+7hurNucz4/SwudRlJSA/ZllHEvaFBYoqFcMiEpfUS+zev48DtR8hBy0QbqRZ9OUqxoQxdQfg4H0+LCdV4Dduf1+ITzGie53i278ZZXIb5f1+K814LakLAu3YFtt03kWU7asSCWH8Ey/+ViX3NLuxzFmP6VQUBv/7SUWQLqpKMQRFNhGUz1qdH2La/lj67jeiUgZBvcHiCk+pMBp5q2Age2Y6lsA7R8BxnRQWOPcdwFK/GUVyBtWQdAZOLEEn999xCCXtRB+9j/3oZQsE2nKtXYf5FNp5OE6rQgHvTDhz5G3Edv4nksaCGbKhyK87MpbrDo5lRRJMe32F7giO9COfNZrSYgPTiKs5VW3GUbMVT34HSdgFrwUbce3djW74ZZ9FybDtP4jtTi73uMvLAPexLV+K3+lC15HON2Gh8n5Iso0uob4ZJ//2ooziiZ6OuZ30H0o2dWFfux7N9DcLyauzLl+A4+xQNL3LXJYS0YnzDbkLRYfx7t2CZWYJj206ED+djKTiDHLMh3jiGI38TjjX78LX2JGenXATPbcFasAfR50GVjahxB3Jnss5BJ2rYiuppxXdgH478DTh3nCRoMqKq5ol63mtBMz3UbVS4HefqVZh+kY2nfUiPExHNqJM3PIj6u+Otlsen4VLg4FYsxQcQh5txlo/jUkk51pIqgmYXIax4Kpdjq7mjzxYO3MU+Jw9b0XacFSsx/SIHT7cZ1foY98Ykl07cRvImuSS+wrE4S3d4NDOKZEXDMlan6kBVzUjPr+BcuQVHyTY8d5/pcS1xJ1LHRYS0Et3hiVqR2m7hzK/ANjcfywf5eJ50oYYtPwiX1Km4ZHmMPa0IV0Mn4vVqrKtq8Wyv1Lm0LBPH+WdoeJHaLyCkleIzeghFB/Hv3oxlZqnOpT/Px1p8DjkmIF4/qnNpbQ2+tl5U1YqGk8DpTQiFNYiqitJyGmvBJtx7d2FbvgVHYR7Czosoni58B/bqXKo+RdA8jktJPZ33W9FsjdjLN+A3DeHfVoTt8CPUqFN/Lmkyl6ZzeExosgXtrdouhfcJ38vh0VQX8rMa5i/fhCEsgukixfNLqBeGIGzhwaECltVdg4htiniOpMPTd51da4qpKC+mYuVyNu+ro98xeaC0kqCds2UbuPm8GwhSv3sJO2oPUrdxJesuPQds3NpURMWIwxMYJuDux+8dHjfDs5VhxQtaB3VFczjY9JSmmlUUr9vJ9cs7WPLpAg43vAKcPKheRNWxm8SQIeHA03OBDVm57Ll4loNli8nI3YkQs3J79yLOvDICAYjZiUU8tJ4uZNeF64iyi2jYBdjo+2YHJcvLOHP9GGsWzmNt7WVuXahkzaWz3KxaxcGjpzh2eANnz9eSk7GYPSeOcePKKe49uI3VK6D577Mzs4pm+yAR2UJYM+Hsv8+RLavYcvoKweC4eJ/x0Bwoj+uwLKgmGAugDV1C+MNa/IFufOvWYF1Ri/fYPqz/kqUPPjjwrlmObf89VCQ0BMTTGzH9uQzPmUt4j13A/7gJKWiZdmZClQXiIX1pcmrifYvDMx6iBTVkJnC8GlvaDvwuByF6cedmYPhLOX6jGenePqw5Wwl6/YRw4dtUiP3gQ9SEV4+bMDbgPX4G74mdWH+3Bp/ZiOp4jvfIUdw76vBcf4TsNaOGHajxblw52biaDGgJmx4TYarHtbgYx5FHKHhQFRNy5108ew/h3nUY34tuVOs9hA9nY87ahyQ5CewrQyjfge3zBZj/UoxtxmKM//0jLBm1BIwDrw/iQSNK0IDo6SfoN6C+65d6yIFifIRrcQmOI/UoyCiN+zH+Yg62PddQ1AHceUtw3OgghB9l6DpC5kr89iBa3IaqDBC8dwnv+RM40kuwrb2GgoBYfxn3jgO4604T6OlDka1o+BCv7cC6shYpLKOpJjTcKIMjdYpocQHV24H/0im9jU9eQxSM+uAzQU83asiObGjAe/ws3uO7sP5+DT7j0JijMhn+IfyeAX2p+F3aSLSghkwEju5ASK/G73YSSnTjzk7H8GEFfpMF6c4erLnbEX1+QjjxbijAfqReD4AN25ANj3U9j+3U9bSaUG3NeA8nufRN/RiXop04s3NwN5vREkLS4XFMrFM1IXfcxbPnEO7dh/E1taCIFt0pHbiGkLkKv0NECxtRw05CRAgj4FmUgSXvNHLcNc3su4Hgd+aSE9nwEFdGCY7jj1GRketrMP7rHGz7vkFR+nHlLMV5u4sQfuT+qwiZZfidYpJL/QTvXMJ34QSOhSXYqr5BwYr46NIYl3r79NhKfAQvb0NYdRCJGCHrTYQ/zcScW4skO/BvK0TYfRMl2D/GpVPXR7k0pmcDKn4C+8sx/stCbAtLMf/Txxj+LQfXmcfIkcnL0Pp7aEqHJzBMwNOPFEw5PD83fL8ZHsVGyHKLNYsWsPn0SU5tW8onv86k3m6AsJnbe5eSsesihKcimxFVNCG6OuhtfUR7yyPaXz2gq/sFXp950teblQRdnC8vpqr6AI9u7KNw8TIutb3k+anVLFleweU7teR88BFF1RdQUQi0nmThb/8n/iO/FlHzEXq1nxlzMjl64xonty4jc0k5vf5OjubPJX/LYZ4+qiH9d59R9/A5CYL0XiljadFKLl+7QudQJ8YntSz6ciHnm+o5WjaHuembscZtXN88m/0P2ke33UeiXl4ezaHq6Dn8kgtNMkPUyOOafNKWlvHo5XVWz/6Y8p0XuHaymKITR7lUtpxd+w6xf/cqTjXc4Xj5EnYcu8Kr5ju0dLYgywJaoJHqpUu40N4Hqhk5YCQSCxBrr2Ne3nq6ncaxJa3xUAQUw21sH2djP3AeV1k+xv+lhIC/DdfcTKyrTuG/fQjz//o1zpsv9ZfG6fVYM9bjPfcNwd4upNZzCF+W4r5YT6D+AcH+HhRlinv9EEtaE+ozo4bNBPZXMvzf/op9z3n8d24RtPQSPLED6+wt+O5ewzF7GbaDD1HkPoJ3rmKfMQvzgu346p8h+YyIr+oJNN7Bvb4Se/U1ZMmColiTU+QetKgNRTUiDT7Df+YI1t/8FevqUwS6OpHNDdj+v08wfFCJ99Yt/I8eI3ksKCEbGm59ej5sQ4314CkqQSg6QeDyYYSPi3A9foVsaEHseEbgwj4sH6ThutOFHDS8vvQgWUjIfdzYNp9PC3Zg9DiITtXGU0EVUIwPsP3yYwx/XIP31k0Cj58iOZpwzlyGff9N/Hs2YpmxmYDLgNTRgHdHFaZfzcVx4DZBYx+ytY3g43v4Lx3GlrsRX8sAasiS3AXj0XcFqRaUYC/BJ3dxL8/G9Kd8PFceI3mGkNofj6vzFsHBHj1YNO7Sf59w6EHUk/T01zcgeQ1jNlpXiX3ndWTJOqVDrakO1I5jLJw7g7332qeZPZ6GSyETgb0VDP+3L7DXnMd/+xaipY/A0W1Y52zFd/cqjlnLsB15hCz1Erh9BfsXMzGn78DX0IzkMyC+rCfQeBv32tXYd32jc0megksDzfhPH8byX18grDlDoKMN2dFF4M64Oh8/RfJO4lLIiqIMIbU8xrO9CtOv5uE4eJugqR/Z/BL/9av4jh3G+kUWzmvNKK/Fk41wqYfrW+bxWVE1Zq9T35X6tlwy3Mf2i48x/mUd3tu3CDQ0I9uf4PhyOfbaW/h3V2H5cisBjwGp7TGebesx/Wo+jkN3dD0trQTr7+O/eEjnUtvg9FxqvIMrLwvTn4vwXHuCHOjGU1CMUHqSwMWDCB8W437WqW+bn8yl4XsT9PTXNyAOdSG2NyN2NuBcMA9L8XFE8/Brs18j76HXHB7FTsLxkHVZn5JXdwtVsaWS7v6M8L2DlsOqgLHhIBXFOew9e4RvTt1g2DVEVDHR/fg45+ubiCrT5+BRRQtRzUYspCOqTrWTywr0cLEih7R5GZSsLOXk7XrkmI+Ys5nze4op27ias+ev8ORRI3LYgzh0nwMbs6k6eQNJdhAxP6Bu+ypWFi+jbNM+uqwG4hE3wsvTbK/IonL3Fk4cOkdHbwdqyE7E+4yzu8opWp7Pidv1BIODPDi6itJVBew8doQ7F+/g0cx03j9AU08fYVn/2gypdozNJ7jX3IgoCqiiEU2xEzQ+4vi2ZaysqqDuyCmePX5C+/NzXH/2iLYbp3nc8IAnj87RYjKjGm6wc3UhpSX5bDlwDkfQQlwz8/DgMlbuuIiacBAK6i9/6XktaQWb6fVYiE0zQKqqFfHeUewLSnAeOoWn9hZiQEB6dhHH0mLs63fhrr5IoLMTJWxHdT/DXbkB27xyXBcfo8TsiPdOYJ+/EtuidbjOPUIOTzHQiCbCihnrk4Ns3ltDr93+rUtaO/cexBHxEZ1qV49oRZW68NXsxJa+GkfOWmyLVuN52IEaHcJ/aA+2+aU4d15GirhQzA9xZVdiX7oWe8YqHBtPEHQb8Ndtxza/EOexO8iqa4qt5SbUsAmx4QKO+WXYc9ZjT1uJ6/Q9xI57OHMq9Wvpq7BvPErQYXs9Z4ksoHif41mzAdu8CtxXGpEj+otZjTtQ7M14T55GdDunCb61AFae1qbzHx/n0263E3+rvComVNWM3H4d59IRPVdi33iMoM+NMnAbZ1YFtozN+Fr70KIG/Edrsc8vx569FvviSjxNnUidd3BmFWNbvh1/vymZlmCyPSwoUiueNZuxZVRiX7Iae0E1fnM/gRN12BeM1Lkaz8PWZHD7t+i5KWmj2u3Y5hfhPH53Ghvp0BQnCc8NlvzxN5ScaJj2Y2pqLnXi27sTW3qlzqXFlXjqO1Gjg/gP7MY2rxTn7is6l4wPcC2txJ61FnvGShybT+p67k/qeeIesjY9l4L15ydy6ewDJEOTzs+ROjcdJ+iczCUzangA/5H9Y+2ZWYnnaSdS+22cOaXY0tbjvvIEJTZdgLLOpSc1afznp4V0OezE38p51m0ktV7TbZSbtNHmE4gBN0rfLZxLy7Et2oKvvR8tOoz/0CQ9m7t0PZcWY1uxA/+geWouSRYUsQXP6s3YFiW5VLgd36CA5n+Op6JK70fXm/R30tvouekEoteFGrOjIhC4cQLvk1bU0HTtZCYRttBzf9+YwyPaINHBrow/8NfSY8jjdumm8P7jB9mWHg45AV9yp5WNkDiWy4aQFfl7J3TSl7ROFq3mUkMrIENYQE3mWyDuhYQHonZiIStKYBhFFgA/RG0oQQOyJEDCq+uZcCXz8Bj0pH34Ie6GuIOIkswvIVqT5b0QsqIGTcRjyf/HnCSiNtSAkUjYRUwxje0qS9YZ18bl8AkYUGUBEj5dz5iDWMhKRHOQ0AQiYQexkEAs5CAq6zNnkLxXVN8qqSkC6vA9qkqWc+JZC1HNiqbakfvOUpBRzK2eNqSAcVo7qeFk8GnMgZpIvgBGgiUTLlTs+hLCaA4L/YtVDVvH5bvw6F+hEev0OYyCRjTNCXEX4Sl32xlRgiaicYGuK9upqtpKh20Y0Ted7ibU0WBHj66TZmYsD49nLHfKaP4Oz1hOFdE49vvYG3ZDjcZ3jP1ejVj1bbbj7q0lHNMnwRvfbpFxOWoCyb/FHKjSFL8VTURkM723NrM4azEnbjbrQdFv+2U5Id+OZ6xNxJHcLZ6xQNGAvhQwoT1V87jnHMnvMt39zKiM2CNZXjKhRhyv22hy/pRp9Rxno+j0STFV1Y5mrqeuaiHZq/cwbLcSfqfByDSWu+mtueSdmktv0PN1Lnl0LkmWKeqcgg8B0yQbuVFVk75le+T/U83sjONSz82NLFq6mFO3n6Fq7zBLMZ2Ngm/DpTE9vzOX5Mn9aJpcaG/ifPLvb84npu+mDTrbeXR2Iys3nkRKuIh5u7h9IJeFy8p42j1ARLW8Ib1GCu8b3pOjJSzEYt3c3ruX203P0cLCPyAJTUTDTkxPD3Ho1FEsfhdh2UREMvDi2ErmrCjlblsPsam+pn5yMBGJCFieHWflgs/JWFHIva4hotPFbPwDQBWNeIzNdPe1IskCoe+SWfjnDtGM4u1hqKsBk9P4D82XN0EVjXgMzXT3tyEpKS5NCVkg5nzKsa25fDFrPpuP30SN2ggFBrH2NtBv6iesWv8Bx5mfN94Th0eHJk8TmPsPAz3Qe8KWfdFMWLGgBKabTfnpQpXMaMnjMN433X8MaLJVn7n7CfS1nyxEMxHVRkROOTtvgiZbiaW49K2QA3r6hNAon0yEVBvR1MzOzxLvlcOjiqYUCYOm13ddiCa097Jt9Gd5P3VPIYUU3neooglNMv0kxrcUfny8Vw5PCimkkEIKKaSQwndByuH5uUIeOR/r73Bv0YzynZccTKPnpb378uXYb1M7K3SMtEf4jWeb/UQhjpw/9z2WsiXzxC3J8rseQvq2un4/zo+cs/dTXrJXRfPrXEouqYcmHa+hST/WQdEppPDdkXJ4fpYwILv7kb0/crCiZEGd6hwo3yCya3D6k6S/RXe/owuroQWXa4iRNXViLh1R+9Q7c0QTin8Qp7kNu62HgG/4R2tbVbaSiLogljz/LeogKpv+NnFIAePY/ZM6RBXzNG1twCN0YLN04fMO/Uj66TEQsfBIW+j/xqdMrPgOEE0ovn5splYEaw9B/3fhsgHFM4Ds0XmkiAYUzxDKd6rrW+D9YTmvBI1EFSsoFkJB4xttp4lmUK3Ev9XJN5FQrKBaSbyhrBzUzxRE1e8/kiNLdHdjMbThsPcjBfXlIMndg2DpxB80J2MLTaiBIXzuYUKyJTVupPCTQsrh+blBtKKpbbgyM7FVP9BPPB93TtVbf91Om/l45F8TirsbseMZktecPB3bhBqyIj2owfLJKvzDjnc64TqkCgSMd9mU8Rmz0tM59uA5mmbDY3jKi8eXuXvzLLdv3GDYPog2acZCU6yIticcKV/Ahx/8htx9V5Bl26Qz2b4/VMlC0NzE47vnePDwJs2PLnPnziW6Df2E3ja52/eAJpkJ2FrpaLrG/dvnuHH1Eh39nSjKxCBLVbQQknq4s6+Q2X/5FV8UbmfYZXv7ZIbv0B6qq51X9ee5ffc6zxq+4d7NszzrateT/X3H9lcVG+rAdTYUL+DjGWkcutVELPYOuzNFM2p0CN+2YixZhxFFP1qiA/fynXgevJw6Yd+UyS+nuTY+v1DIinRnD5ZPK/Abne/E+bAq4B+6xYb0T5mdkcHJhy9QFTuoZgaNLdwzduHym6Y94yksW9B8fTzqf0mbcxh12uzAJqLiIM0DLzjX9YIO1zARaepZv7BkwuXo5EJnM9eGOvFLFhKKGXNDHbmLZ/DXhaU09vcRj7lxvzxC7pJZlO3/BjUs6IdBiy0c376eM4+biYXeMk9SCin8DZByeH52sKLShXNmOsKG2yiR5InMqqBnK43aUTWLPiBEbKiyaTRviH6ejlnPHBy1j/1dsujJvMJ2PZeMakYJO1D6r2FbUIjX4kdDz0uiRgSkxjrM/5aPzzKSZC+ZLynqJCpP/7Ua0gRcnVeoXlXOC5eDmGQmHrdwb0c6v/r337J8VSGVFdt5OthDOGQjFrYTDzsg4tCzTEs2kJ6xdfEf+LL8OKJsJyQaCWl2iDqIh+3EkjMPqmwlHnEQjzggbCc8TaK7ydBUG96uK+zbsIzZf/wf/MvvPqVg3UbutHSSiDqJh2xENDvEHERkMyHVPnq0ykheKjVoIqLZSUQcJCJO4m+9I8RELOZg8M5m/vI//pV5y5dTXrqGqw3NKBE7sZCdeNiu66FaUEQLhAe5vf1rfj2rjF6nnZhiQlMEiDpJhPV8UWrQiCJaiIUdSZ0cb73lW1VsaNYnnK9ZRdZXv+X//uV/sbhgJSfvNqBpThJhOxHVpuukWdBkAaIOwpJRH9gjSRupNhIRB/GIk0RI0HcXiRZQO7myfz27T90nEp/qiJrpoJ+W7ttQhHlWDaIWQKMV19wq3Hdb9GMdIslcOqJZ5/YI50ecd21SPwgm+1E0WTZk0ctFBcSHNZj/vQifzfUa5yNv4HxYE3C0XWBH2WpavA5ikomoMszzngbyrp7in85f5o5DgCn4GZJMeN0dHG64yW9PHmLhszYUyTKFc2Qiopjo7HxE1t3rpF09xx9u3+Ol10Rs0kyPJpkJuruoe3SNWXeu8fsLZynr6iQqm1ElG/gfsa1iHbdedhANWQmHBOytp1ifX8Qzh4u4bCSsORl4uIUlWeX0OixTZ4BPIYW/A1IOz88OJhRlCPHpY/0ICNmMqpmRXlzBsagM24JS3LdaUcwNONfuxtfVjxr3EPzmIK5zd1CCPfh2bcc2Jx97RR1Bmw158BHuwu3YS4qxzijF09iL3HUN+6yFGP7nTzF/VIhtSTV+kwFVMyNbWwjUNyEH9XgJVbGjdp9jVXEOl14NEJtmMA1pAq6uq+xevYYWj5O4bCYeN3N7Wzofz68iQBSQIGZDaLvEzrIcivKzKFizgSf9Q0RDDpBfUJ31F+asOYmoOIirJoYf7ic/P5eCFVmsO3YVWXUStj2gdl0xRXmLqdh3BIPT+nYv5oABVXMBVq6v+Yg/F9UgEgPMvLy8g4OnT3Ottpj58wq4191C+42tlG09gts7TNOJUsrrzhPUbHTd3EVpbhYFpUWcbWwhqr7NEQkmYjE7g7eq+PCDBTx1+4EQJByI1kZObsqnuCiP/OICzja2ENFsEBni3q4F/GHeavqcduJhG2L3JdaVLfv/2Xvv7yjOfF/3H7pn3bPP7H3P2nNmxzOeZI/H9ng89mBjwGQkJHVUbkmgAEIIEJJAgMggogCRsyREEiigHDtHdUudqjpKz/2hW6AEiGCDcdVaz7JcVL/1qTd0ffpNX1IVCai37EFrNxMRn3BhVz5pKQmkF23iXv8wkfns9OzWxjf59GCsVfLRwiTaR8OAHf39g+yqrub6qS2s/WE11RfrMXXXsD5vA491emwN28nYUEqvcwTXk2MUpSlIUyexvfYaXp+ZgM8EgW4u7C1m5/Fbr2h49AiCDl/nPdyP2/ALVkQ6GEnYiFVTjPl7GZaCY/g8I/gHbmJPTce8KB1rXjVus5VAaAD3qV1YFqRiXp6P814XYsSMr/kMtpU5WJZn4bjUjOA3IQh6/MYW3A33Y/G94nXe33mcrAw5dW1Dz90FPRQwY3tyhvL1hbSP2hn36wn5hujStnF34C7qS3VctJrmNDwBn54RRxfNuiccbTpH2sNWvHMaHh1Bn5Z+XSdmnwXcT/jyxDE2DvUxIczoKfXqcY300WHogwkbLQ/P8auLt7AFTIR9VnA3sr1gI9daYoYnKNrwDV6jYmMi9UYvhPQIHgPjgV5OFaVQUNvAxFy7sktIvAMkw/Mh4tbHenMCBgSvCWH0DrYvVFiyynHk52D4tRrXQCuOVXIsexsRw93YV+fhuH4Hd00Vpk+zcWzegeXTFZizT+PpPI3h/12D49ItxoqyMSyuxito8VysxvT3FByXm/F2PMLnit/fb0Kcsu19QLQhPjlM0polHH3Q/9z5Hc8Mz3paRiZ7eAzcKFvNJ58t5ciFk9y8dQOLy0jY1cGdszvZvS2X7//w76zZdhJ3xA1CM9vihscvjjAu3CXvy//mvxbIudJ0G6PTApFOjuUu5JOvk9m7JY2P//N/sWrnFQKibX77lvhM4OvhZM7nfKoqw+RxAwaubV7CZ18v5+iF01RkrmHz8XNcKfuB//o2B/PIELXZf+L3yjJ6Wk+w/M+fosgvoXj1R/zTZyto1NpAfPkcjGjUytC1Er786C+UHDrC9ZuX6NMPEBa1dN/az96qEpT/+IjPEgoZ8LkgOsj17ZOGxwEMUav5hv/1n99wqO4sfRY94+N6mo+l88mfFlC6dQOr//IrPpJtw+R2Pic0yAy8esYDJrqPpPDRt2u4q3cCdnovFLLgzx+z8Wgtp7cqURbvpflSIX/44wIudRvQ1yTw6y9Xcbf/HhuXfMq3yeupzv2ef/6Pj6iq74WQBcQuzle/juHRPeu5DJkQ3EZEunAsV2BM2ou37RLWr5OwnXiEGOhn7Pg+HIWbMH+0FuvuRgRPM9Zl32MqPId3oBO/14zgbMD2mQqLpgLHOg36Xytxdg3Hdih/Wue1T+u8v+0giWuWcvzREBPPMY/PDE8BbS4bUV+sN4igGY/5ASkXznHpOYZH8OgIeI0QNnC2sRbFCwyP3xMb/iJkxdpXz+8uXabermV8DpMvevWMByzgGWDzjVqWtbYRESZ7eBoom2J4AoIZwfyQk7uyqD5Zx6CpH9FnJBo00XdlKyrVdoxhG+F3/Z0oIeGRDM+Hj2hDfHIM4+/WYJFtwp5ajC23GveIA9/NSswFNXhu1mDO3I7XOchoYQb6jzOwr9uCLakY55UmPA/PYP1hDz5c+C7swrRgB17GEPrqsKzMZNTqJcCLwjZoEfwWYJRxQf/cUCNzGx4jt7Yn8Pv//hhldirrt+yh3zLEwKWN/GPRQjTrslj8+39j+abDuKI+CLWwPflzFhceRwyOEPX38/DcVlSL/8gnXyyj6lQjbusNMhf+B79dmMKW0g0UF2k4dK0Rv9dIwGdiImInIrxgEvLzDM/WVXz2j3T6vbbY5N3wIDe2L+NPy4pwjOm5VPQVf8us5G5NDr/57R9QFxSzrTiL4soq2nVawoKBUMAGITOB52yHH43aGLq+hb/9x3+wTKEgp6CE+o5uXF3HSF7+FYkZeaQu+D2fLtPQ7R0DtNyqWM4nS/MZdI1AxEh/4yGKVV/z8UefkVdxFr2thZN5f+WfP/6Oos0lbC7KZHtNLRankaDfQDRsZyLwgknIcxoeG4NXi/nidws43z0IOCBsQXs9nz9/vpSbgxasZ5X8fomCe9cP8vXHv2GRKo+yknUUlWzkamsXkYAZAjMNz5Th0ReV0SxMiLTjWLGJkVtPCDDGaJECS/V1fE1nsPyQhTVjI+Zfr8Ky9Sp+dIwdqsCq2YJ9y37GOgYQO2sw/nYNFsUmbKnF2HXxeUsAACAASURBVNftxW3SPRvumlnnBSvgYlzQPbfOz2V4BI+OiGBk1PwA+cU6rtkt4NchzHx2tw7BY4CgjnN3alE3txEQTPFJznpCwVhdEj1a/B4944IJw2ATi86fZ5e+H0Tj9Pz0x9IM+Ezg7udIfR0LGpswCkaiXl1syHiG4RF9RkRXL/fPbqYov4BrTzoJCCbCIROmR/vIXZ1H26j96XNJSLxLJMPzoeO3IOgvYfkmlZE7PUyuqhEEE+LYYxzKTEwp+dj23UbEzOj2PEyqw/jcltjwTdSMt7EG8zc78WLHe7Ic41cVeHEiDN3EujoJx+VW/KZu/GNza4gNaZ0iJ1PG2XkNaU0xPBMGLhUv4U8LNFiiHmAUxB6Opv2B36zcyJD2Hus+/zXfFx5gJOBgzHiNdUs+4q+qSvTmQfweHaJvGNtAA1uWfsS//Pu33NM+oDLlL3yRsRfXmAH/WGzuQkC0IPTUUrAulbOP+56rc9Lw1KT/kY+SSjF6PICBSyVL+UyxBbfXQkgwQ3iYW+XL+N23adxvuca6L/+Jz9MqaL1WxseffUvNvW7Cgg7BoycgmIh4+2k8mEXWjqNYx2xzzCvSEx230n+pgD/932+5obcAHoha6Dywml99sohbg/2cVn/KHxam0+W243U+4kT+N/zHV0ru9fbGTakWt72V2oLl/Ov/86/suXOf21Ur+c9vM3mi1xPyahG9BkTBQsR+n30lcsrq7iAK5rm/B+KGp/PAGv7Pl8to1LkAGwMX1vPxgkSadXoImoiGLOhvFvHxn76hpukup1L/xG/+lsC95gskfP0xGYduExb0+MZ0sQngXuOsHp6AECuj/HVp1LW8oIxmETM89kXrsNfU4x+8gfUbFY7Gu7gKsjCuPYzP24nt8yWYiy7in7AguHQIQ7ew/ZCAce1J/M5rmL9JZeReH4JnONaOnvMijw1pnSA7U8H5eQ1pPTM8oleHe2yIJ/0NfF97igPaITxjWgKCFaH7NOvXpVHX2k9UNOB3D+N09bLz+nF+aLzPkHMYr9dI1NdL/f5MsqqOYXfbiYoGBnvr+e/DR0jrasM+NoTDpY3p7DrFunVpnG/tJxowER7tpfTSMf73+SvcGRnE4RzC7dbN2cMTFG14+y9RkreG20YvRGIrBqMhEwPXt6OWb0UbshGW3h8S7wGS4fng0SOGDHhv7Mf8uQzTFzIsecfwug2IIRPeU6UYV5cwNmxBDFoQRx8ykqHB+EkSxgX5uO634+u9hiP3BL6oBd/NY9g0x/FFrIiBQdyHtmD6fQLmFVsY02nn/LUbEG2IHUdITvjhlYe0ImED94+sQ6XZjm7MQMhnIBIyMdxUTfryBSSnpVCQk0vV0Qvo+i5QKFvB0sUL+H7ht2SUVNLv6OTsBhUpSYnIkn6g/PQ13H4H3qHzFMpWsnrVMhITVdQ9aiMUdYPzAkt+9xuS996G8HNWmPiMjPv6uL4zBfnWQ9g8TsajBu4dXU/GtoOMeUwEfLFf2Pa2k+St/TuJKhkFOUoKK2tw+Qw01RSwavFiVq9cwfqyfei8DsDKvcpF/OpPybRZLHMMg8RikBnuVqNOzuTO4ADhgJGgaGJs6Aql8kWsXLuKwsJcNpTsZ9hyj73rk1m+eAELF35LUmoWd/V9PKzZiGLlKmRJS8irqEbrGiE4ep/9RXJWLl3C6hVrqDp7jbHQGNBF2Yr/y+9lu/AIz4kc7dUTEY0MXdpIQlY+bWY741ELhqbdpOZsoNOoIyoaCAhm/Ob77Mn5nqWrV1BUmE5WbgldDhuGu7uRL1vCmtXLUWZt4JFRR1gwzzA8ZoIBJ4ycZ/FH/4ZsX/3zy2gWRsRoL66iIkx/SMT0STLW7efxhUbxN9di+XYFpqWZmBNLcZ5owu9+hCNJiemvSswr8nA29iBOmPBe24v5s3g7yj+Bz2tAnCNPJoe01iYs5cSjIZ4X+X624dETFYe48vgan9We4L9qj/OHulq29/YQCo2Co47vf/vvyPc3wLgFp72F9Iu1/P7Mcf779AkW1tfzxGkBrDRt/55//rOMDqsNAgPsbzjLr44d44vLZ/msrpbtffE07edY+H//DeXBOzBuwaq/yxcnjvKfdWf424VTfN9QT4fTSFSYy/BY8Q1dZ88WGbeGR5gQdAheAxPBQeo2y8mtucH4vMtIQuLHRTI8vwj0CKJp7o0IBROiYHy2OZvfGF+tNeUaryG2MsujQ/BN+durRxCek+5MvAbCopngC7q2J1dpla/Lp9M7FpvT4o7HmJqxkikgmIkIRkSvnlBgamwlPSHRHIt6PyP9WDqxzd2Ck5+P/5voNxOwPOTMXiWrk7K426t96Uqlpxom5234TYQF4xz3nKJTMCD6DEQC5mfmwasn5Deif7CXDMVSSvacZ1SwPzevRJ+R8Iw4SaJvyrOJ5mn59UzDzHQMhOM6nuXNs3uExvppvlBIwpoEjt9oISA+p4fnaR7OTiMsmqZ9ZvLcM52mWN6I5tnxsXwWGB/g8v5NVNbcJDLhJGR5yJlqJWuSNNzre3kZzUKMb8jp1cfruT5W5wVD7FzAPNu0+43xOv+CdvSiOv+CPAsFzFjba9m+vpBu/9i0eVyiV0/YF9vfRhTMBMwPOL1HwZpkDff7ddO2GAj6DIS9sVAtIb8R3f09pMuXUrr3ImOCLZaGV0/UZ3g6x0cULFPSzOHBwLM0Q/H0ppWv6ADxHuUFG7j6+AmRoIlw2I67p5ZN6Wrumh1M+HUEAyMYH5STlJBJu9lARFqlJfGeIBmeXxJe/dMv+2nn5ojNNfs63XP+nuPa5/CyWGjBgJmx4SsULv2CRQmJ1NQ3x4yId474YZPpPWWuc/rZ5573eb8J0dZC/YX9NHT1EJ3PqqmZul5BpzBDZ9Cnx/Coltorl7C5LS9cvj9nPLX5PLtXP8e9n/N5n4HgWB9Pbh7kwt0HCMJ89jSaqWv+OievnSQgWBAHL7E5ZyV//XopVReaGB93ELA9pv78ARq7e4kGXmP1z2R99eln1+OnvKRuv8U6HwqYGR24SP4PX7A4cS3HGx7HzI1XNx2/CdH6mNvnD3Cnu5folDlV4pTrJuuS/tFpaq9cxu62Pq1LoucFafb0Tut5nZlmRDBgaNqHOulb/rY4jfreXsajIzhbD6NY+x3p22rxBS0E/GYm7Hep2LaOIw0PmJAijku8R0iGR+L9watHcA9hHX5Id3sDevPAvF4qbwctgs/IRNQJwXezjDYYsEPUTsj34p11fyr8Hj2R8AiELT991G2vHsHZRX/nHbp7HuN0Dse+g56W0Rvu5Py+4NUjuAexDj2ku73xBXVe+0rPPr+6NP80Ra8Ot6WVrvY7DAx2xOf0GPBa2+nteYjNpYvNOfPqEUd7MVn6CcSN2zvPYwmJOJLhkXi/iA9vRAOWuUNISPxy8BoIByxEpw7/fYh49YREy3tf50WfkUjAMmvYMhIwE/JP7+kMSWElJN5DJMMjISEhISEh8cHzkxien6tZksaef5q8+jnk88+1DktISEhIxHi7hsdrJBqKTW70u2PdneOhWAyjV15N8Yr4PTpCAUssVpL72aZtot9MNGhGfJUoxl4D4aDtpXFw3iaBeegM+Iyzx8S9RsbDtreuU/SZiARmj8E/06nF74mtVBoP2xgPvmJ3vHsynlUs/tTTFUmTu+OGTQhzbr73FvEbZm+W6DXG4iRN2WE4IJgZD9mYCL1C8MqXpPkUwRR71hfVz7l0zokeMWyL7bD9pjrdutjqpNBLtL0Ws3WKPiPROeqbhISExNvirRke0W9GNN3kwJbdtFuHiAQs+MxN7M1NYHXiasrP3MTv+5G+0LwGooEBmk/v4ciZG3gjFgIePSHBgPHhCfbsPI4laCY0j7SCog33wDUqcxazWq7iasfQj2zW9ITEuM6qEy/QqcXjHMAzZXM/0W8mYLzC1hwlZx/FNiJ7G5oCghW/qYmzNWW0Gy1E/XPptBANmTE9PkFh8mLWqNI486DjaXDOlz1zOGTG3HqCouRFJKVncrN7KLZEOTiM+8hWrBtO4fPY44Ecfwy0+EcGpm+W6DcjGG5iVxXgfDiAGDAT9fbz8HQxK1cuI2vLQcxuA8FXmUg9M01xyqqkgB5fwynsxbX4nmum5tA5ZxswIfracRasx378PoJonqdJmqFTWYCzeRAxYsLXdgVHyVl8obe40maWTgshUY/u8SkO1NQxFrQQ/NHamoSExC+Zt2J4RMECiOC8ROaiNG6atICX4cubSCjYhdHagdnUh9/znBeFNzZkMNcS1qe4tQREGzAWI2Ih4BnG7zEQjY4BVurLNGRvPo4bB9GgA/Bib6gkJWEzwxHrHPFctAheE0y4nqXp0+N39qHrOkvh6r9RdauTiXgU8fHoaPz+TqKCDr/bQDRqh6gzdj4U65XwT00zaiXg1cZ0RkZi58YdhLxa/G4dobhOW30lKYmlc+jUIvotEB3gbKmMs0+MwBjjgj4WxNLdROU6FWeaY7vOhkQbRB2AA8ZdT+8lxkM7wCgE4r1gc+n0Ghj393FuWzp5h2vx+8zxSN/PdCYnbEaHFyaGOb09nXUHzmMf6cRmne/Qp57ouIWuc1vIy1lPU287IyNaRK8RET2jhTL0n27BK7gQ/bGt70WcBBglEDXHVoJE7YhBQ3wL/1gEa8GjQwzZCOAiwEg8arUBccKGODFCABdi2IggWBAnBhjJzWSkzUQQV2yfFZ8FwXEJ0z8twHapFzFkJODR4jS20XajnBRFCT123av1ZPlnpBk0xGKdhRwEGcN/qQrj38rxTlgJRBxx7a7Ydf65dOpjnx93xPIDG6JXi+AxI/IE22cLMK6/ghC2vaLhmaLzSh8BzHhvHsb8zS58eAnijPXIuLWIM3W6Z5TR+GRMKcO8dAZFC37DTdYpl7HvSjPR6CvGzJKQkJCYB29seIKCGb/pNofKiijOWcPCf2Rxf/g+149uJHHRZ3y+IoWdFfto1/cRnOPXv+g1EglaiAYtRIPWaSsApt1HtGJuPc3esjw2bVzHyZu3cfudjIcGabm0h7LiDBK+XkjerjrCOLG2nqayOJeshMWslG3HOD5HADufmainlcsHt7KpMIfjN+rxCHZCfhPjYgeHND+wt76TiZAF0dlN/YmNlGzKp7yqknajiYi/i5bzZ7l4eitFG9ZT2/SIkGglPBZLs6Qwix0nzmJxWRkPD9JyeQ+b8zXsPnYc49gI0bARQ8spKjflkpmwmFWK8lk6Rb+ZgLWZ8/uz+e7T37JUmc3WzVu409uP19jE8UoN2/fs4YleR8ivx9BVx/m6gxzec5SLp7aw79hRjGMjBMy3OFRWyObNRdx40kUoYCM02vJU586T57C6jITDTsx3y1CpNtLrMhMRDESC03WuTt3FoPk2R7ao+cffP+UHZQ4HDtdi8Ojn2fuhJxI1032+nPKd+3FE3fFYO3rEkA5vfR2uU7fxi2YEvxnR04qrvBJb6kZGLt9H8AwxVnuMsdYuxKAd/1Ajrovn8btN+JrPYU8txl68F7fJgujvZKzmPM5DlVjVpbjudiDYW3FtL0T/q79iWFSELauS0bYuhIAFwd3K6K4TuLVDTzegCwUchI3nyM/dTq9N+2qGx2tEGHuWpuA3xHa+vncWe9pGLH9NwPj9bnwTdjx1+7BnlWDTlDH6ZADB0YarbKbOXsTxYdynDmBTF+HYey7eE2ZACPUzVnOC0XvtsQ32XuXLYKpO3TCBcRPeO6ewfl+K42gVtqwdjPUOIYaMuOv2PtPZ2oMQsCK6WnCVVWJTFmE/cBnfqIVAZAD3yfno1BOdsKK9vBWlppR+p5WotFmdhITEW+aNDI/oMxHyPuSgZiWZG3dxem8uKxZmc1fXQuvNg+QrvmWBIpezp2rpNfYTmDY0pCckGBnprWNrjorMTBWZqckUVVTRZ7POitIcEKyMDlzj+N7N7NiaytplaVzt7WOwqQz1GiUHju+lYPVKCqovMmK9yMa1q9hcfYjqgmQS5NsxRGf2nBiJjvfTuLuYdZp17NyRh2p5AoeuNxMM2Qh7WtiXtSRmeIJmgu4BWq9WsaO8mKLUFaRvPM1otIn1X/6d1es3U7tPw8qVadw1OTBeW0+SXE7VgYPUP7yHL2Si78Z+ihQZlFcUk5uygs3VlzAYYzpLqw+xZ30yiYryWTpFn4mAo517l8qRLfwL6k2VnDlZwxPtID5bKw1niklY8Bd21fdC1MSt8jUslMlJXbWIVStXospUUPfkERcLsynYXMyO7Spkq7K5Z3JguLaOtXJFXOddXGNmYJBzBSlsPnaZQNBGOGDCNXCSgsRVlO6N6Vyr3smw8zG3jpeyZvnXJBds49KVq5jdOgKvaHjKKvZgEkcITdYvtw4hZEWMmhHcBsTxPkY3bMGcsAlH0UZMn6UzcvM+zvVZmDJOIODCvXsblqz9eIZuY/s+F1tRJba1SkyrD+L13MX8r0swplbizMvA8EUpbmMH7jN7MP1uIebMvTj3nsTd1xufK2OM9QhNeeEG/BZ8Q6dZl/Mahide1ybTFAMm/N1nsPxdgW3rcRzJaRi/34V3woGv6RSOogrsCjXG73biNs3UeRqPqQ9P3WEs36/HXlSG5ZsULCVX8IetiB49YtT2rNfllb8QJnUaEMMmfA+PYvzXBGw7D+FQqTGu3o1XcOC7F9cpV2NcUIFHcOI9swHjIg2OimOMNjUjhI14zhycv06/DUbr2aBQcfxuC5G3OYwmISEh4XlDwxMQ7fhbq1mesp4erxf8tylMyKXeNAy4uH80k9SD14Exwj79rMmPQb+B0aEb1OzczI7KzezYvoH9x4+jdZgJT5u7oScYMuG4f5jcdDlZ2Ql8/cfl1DZd5/j2NPKONAJjNO/bSMnOWlqub2L1+gNMEMTTvJ8MZRnamUNFfit4mticvJjvliWQl6cgYckqDt5+QDBkJ+ydNDxdTIQthFytXNqRQ1KqAvmSb1maVI4hfI/KhBxu6ozAAAfTv2V34yBjzdWkpiVRevAELX0dTIj9XKtQ8Ne//UDu+lRSli1l66FaHpzbRELBQSYI4n64jwzV9tk6PdpY0L5wN0dyl3HssQEYJeLXE/BbIdrH0byl7GvohrCBa1Vqso7VcHlzJjuqazh6sJiT5w+hXvgta9UKstMTWZuQxh2jFef93TGdh07Q0tuG121hYqKdmsx8Tt96QDBiYVzU03YijxX5h2BSp7IMPR7wd7CzRMHeu33ASCxKs1tHIGB/Nmw3Z8V7geGZUUYB912s36zB8Kkaa4IG0x8VOO504287iVm1GXfnI+xZGpxNffhvlKP/1UrMa9dh/kqGObkaj/Metq8KcRktBG2XMf8xj1GrkQC9OFJScDQbY8M1wuz6+bSez2F4YpvyOSFiiUejnkeD88bm7Xj2F2FMrUFExN9wEPPi3fgw4DlYjmlxNpbv1qL/l2xGneYZOscIjvfhzE1H95tkrMl5mD9Owlp2Hn/INud8p9fS6dEjho14G49i/kcFXnyIuguYF6kZ1Zrx1kzqTEL//2kY81jx1e/DvDwdW1Utnp4uAsFeXOvmr1PwmIAujmfIqDh5CyFolQyPhITEW+WNDY/QeYA1q9Jpdtow3yplyedJNFi1EDRwY4+SlKpzEJwreJyeoN+Is/8SuzflsmFDLhvyM9m+dz+DdgvhqT08XjOEH1OVvIytZx8zMXaL7AWLOdZ0m7PlajJ3XyYc6aRyxUJydp+j41Ypq9IqGcXG7dIkfkjYjD46Y0jLFzM8paqVlJ9/QGwei52wX0/AZ2Yi2MGBrMXsbxoAHOgaylj7g4aBiI+2agXLk7ahD91jd0oxrWM2sF8nd9Vyjrf1xObOTNgYulHM539P5nbHI67vUaEuOYaAD8YdMG6huzafFemVjGHj1ua1LE0sxTBTpyc27BfydHEg93sqb7TDhD0e/8jCROAJ+7MWc+DuIIybubpbTdbJY1wszGDX3sPsry7k+PmDZCfJuTlggIkRiFgJenQEgw6YsDJ4o5jPvkrkQksv0E1NRiaHLt8lELEyHjDQWbue5ek7puk04gL7fbbkr6XiWgtETAjemIm1tpzkwMlj6ByWGcb1WdnPz/BYCIzdxbpYhu30YwKMxnogBDNiuIORvGJsxVuxZFbji4zgPbsF4/db8YpjsTkj43aEkVtYv9zMqN2IOHgW88f5jJp1iP4e7ClrsF/uIIDthfGRZhkev5GwZ4An13ZTc+UGo17rPMIu6GKGJ2jAc2gjxpXV+LAymqXCuGAPXs91zP8txzk8gv/OLgz/lsaoTT9Dp5NAuA9nXhrmvLMIuGPPGTTO3aPjNRD2DNB+dRc1V2/OX+ek4bldg2Xpfnx48F3ZjXFRMe6h61h+K8epdeJvqMLw7+mMWrQEoiMEseA5twX9v2cw1vEI16as+en06BA8Zoi2sl8lZ9eFRgIhaR6PhITE2+XN5vD4jIS93VwsTWLhssVk5MlQLttAs20IggbqD2aSvu/CcwxPjNhkWlecURi3z+4Z8BqIBvQ0VqexdPEC5LnJJHyn4FLLE5xPashY+Q9Wp69BsUrFjoOXcY/dZ2fqIhatXUFaqoLcjN0YIpYZRkJPKGzCcn8XaStXkJS4CnnuVjqtWlw9dZSql/DVX/7I3xcupuzERUz9jRSv/ZJlKUnI5GvIzdqLZfwhZYu+Y8mqlaT8sJj1e88zFrbQc7mSrJRVqBTLycjbSqvFis98iTLVKlatXM1alYaLjzoQ7XeoUC9i8doVpKkV5GXuwRidqTOmNSKa6L6ykeXfLyIlOY3LnV3Yu89Tql4c0/n9EiqOn+Hc/kKKzp7kyuY89h2q4fC+Is53dtN3Jp/VS1eRkpxAXnkNI0ETPZcrnurMzNtGi84A41bu7lGSuf0I3oCdsGjGr79FuWq6TtOEE+wPqdykZPfN1pjh8egYjzqw3sjln3/9Zw49GIDwXHNJ5ml4PHqEsAnvzb2YP5dj/kqJOXknbu0gIg58V6swfroCe+0TxKgVYewRIxmZGD9RYVqQhb2mEb9wF9vCbYxaDYhD57F8VcyoeZhA2IznzBaMv0vA/I91OO89QQiY5pzoO8vwCCaY0HOj5O/8j09kPLFY54hs/hxEE8JQPbYlazB8Lce0NAvzmsP4An041iZg+Iscc6Ia45+LGbNrZ+l0tfQg6K9iWyTH+IUS05IinE1t8WX8M+7ljem8XvwV/+NTOZ0WKxPi/IYcxbAJX+tJTP+yDNM3KkyfqHBcaUcUu3AkJmD4iyKuswS3T4fnzB4sC5RYvkvBnFKF22pB0F2en06PjkDIQWTgDGnqTG509zP+oYSOkJCQeG9440nLos9EYLSb/o5GtKYeRm2DeN3aWOwVRw92++Db2bTNa0Ic60PX00jPQAt2ywAel5aQoMehfUBP9wPsjmHc9kECggmPtZWeJ3cw2wcYswwSDDtivTiTK5UYhaid8YAeWzx2U3f3Y1yjOnwjXQx1NjHQ/5iBrkYGtV34fSbGzI/oeXIHnakXt12H313P9jVZnG66SX9PC2NeI2G/AZexhb4njXS238FoHSDgNxMSTbgtbfS0N9DZ8QCzdZCgOFtnKDKXzni0Y88ght67dD65h9UxhHeazjsMaTtx2fsYGRlgzNaDyzGAy97D2JiBiH8IfU8Tne136BvowOfTM2pqoXdSp22QoN9IQLAi6M6Tn5zKue4+CBoJ+I1TdA4yZh3A59UjuodxWrtxxeMciT4TfssDzh9IZdXKLB7qzYzP+YKNGZ6uunJ2VB/FRxCE5+0jZEAM6vH1N+NpbsLzpBW/S4vgNSB4BvENPsHvjpsNwYTg6sH7uAnPo/t4tX0IvmH8xj78bh3C2CB+Q2/s73gMI1/HfTyPHuCzDs0Zw8jv0RONesB5haK8cnpsWiKCCZf2CjvWLUeRsweTxz69R/KF6BEEI35zG57H9/BZB/FbBhD8JgR7B97HTXiHu/CbBmJDbHPoFEMm/Ma2WH60NOOzDM7ZQxXwGXENX6Fy3TIUudWvptOrRxgbwNf7CE/zXby9nQgBE6LPOFunV4df34bncROe5tgzCX4TYsA4L52C1wTRIa6Uy8kqrcEVcjzHAEtISEi8Pm9nWbrfRCRgISwYCQqGp13RAb9xeoyVN0T0GQnHY7mEhMlN+GKxlyKimZBgJBi/X0Awx2O8mBmPDvPk8l62FeSweXMBWzbns6kwj+qa05g9VsYD5mcxYjy6pzF8IvHzYX/shRqMpxkWjIQCVgTXTbauXM99mxbC1qfxfkR/POZMwEJYMCB6tAgePUHBFD//LDZQcIbO9kvV03QWF+ZRfawWs9tMyGcgHIhdH/TqEOfQGfAbCfqe/Tfoj+eT99lnw4Jxtk7/s3KLBCz0XNtOdkkJQw4rYf9UnVPLODYsOfksAdGC80ktZVsKuNbey0Tgeb/SY8vS+y5tZe1335BXXsGjweGn+TzX9WLAhBg0IwaMU6JZGxADJoSpw2Z+Y+y6oDk+8Vj/bMWSVz999ZLPEL/W9JwXsYGwd4DOG3tZn76M79ZspN9pYFw00netgg0VO+kxG4kKr1HHhfjzCEYEwTD9nGiMLZOfU2f8nGh6iXY9Ib+BvmvlbKiootfyGjq9hmd5ObX3ay6dU/NdMCDE6/x8dIYFI/q7+0jKzeXR4BDR1904UUJCQuIF/AJiaekJiUMM3j/L6UO7OXF8LyeP7+X44T1cunEdu8c0z3kNM/DqEdw99DXfxeoafvEeQq+gc+DedJ3HDu/h0o0br6/zdfAaCXkGGX5yFa3NGIuCPJ/PubWIghUmXEwEDC/coTfgNzBmekjD2WpOnDpCt0H7/gWI9OoJeYcYbK7l8OG93Lh7lzGP/tm+RBMjRPz6WI/Ru9Y6B/6fic6gV4ulv4G24UEIGt9bnRISEj9vfgGGJ7ZyKBy0Ac7YpN0JZ4ywhcAbhS8wEAlb3poR3l+ZMwAAIABJREFU8bv1P5LO18BrIBK0vmCl1Rviju0xxERsc8TITxTC45XLxKMnFLTHyiQsTaT9cfJYR1CwMC4a38s6ICEh8WHwizA8EhISEhISEr9sftTgoYLXQDTsgHEH48+ZzyH6jESCplcL7jkHfo+OYMBCZEbw0JBoJRzvzg/4TUSfO69EQkJCQkJC4kPl7RkerwHB1UVf+wPso1oCPgMB7yD9d2upO3OEu09a8XsN09IRfXo89g6GOltw+/RvMFygJ+Abxtr/gIGBTvzxCbhB0YJz8DaDxkGCfj1O4yP6B3qJBI0/QgRoCQkJCQkJifeVt2N4vAbCoREihrNkLsngtnEIxh3YHh0keflScopyOHK1Eb93epysUNCIvvkIG1PK0E04QJjy714DIcFEWDDFJ7NqESfPiSZCU1b0BAQLTAxxdUs2uVtP4sFORLTjG7jMxkIVtzoHmAhbsLYcIzU1i3u64dik2vegACQkJCQkJCR+fN7c8HgNhAQddmMn2ub9qJdm02jsxWNt4+y2JFaW1uD3mQgJhllphIJG9I+PsU1dTtdoNyZdJ16vgYDXQNA/hGXoMcMDLYx6jIT9RjyOLgxDzQwPPMbhHCbgMxIUTPicvTgMTdSsT2V9xWk8jILQTs06JcWnbxIOWwh4TUyEBrlYLkdTeoxRaa8PCQkJCQmJXwxvaHgMhIJauuqKSfhhJYnL/s6XX2XxYLCBmtJk/vaX3/GHv32DLGkdt3u7CAanBwQMBU2YO45TuDiR7A0Klny7gKLj9QTG9fReqaYgU0VmRgJb953B7nVivH+AktxkMlQryd64g26HHdF+nR0Za1i9ail//8OX5O4+TwgvlsYKUjNy6LDan25+Fww5CA+cIV2dwY3uASak3VwlJCQkJCR+EbxZLC3BiqirJXVVIhc7DWC9QO7KHBpMgxA2cWtfKso956ct5xV9sWGpoE9PKGjG9uQgSQvk3NYNYzxfzIqUCgz+egr+8T3K9evYtknGP/74Hae7dDD6gOPVJWzZpGThn5dzsrmJGwfSUW04gjBh4XZFHvnlZwhj4+H+DWwqPopzfITQpGavGaJtHEhVsPNcPWLYGttoUEJCQkJCQuKD5g2DhzrwN1exVLEJbcgLutOk/5BBg3kIQkZu7VOj2HMeQpb4Z/T4XAOMWHsYdQ3HhrQeHWNb+i4cONFfryQjdTe64WOs/mE1VcdruHH5FI1N9bjEPm5uyyBz4w6uXawg6evV1DZe48jWdApqmwEzlzemkVd+lggW7u/fSuX2M7ixE3yq2QT0cFojp+zoNXwhyfBISEhISEj8EngjwyP6LQRN1yhas4wNhw5waHMCX36UGIuWHjJwZcdaVpXXQigWPDQSGaX7ZCr/53//TxJ2XwXs6B4eJD9hC0YcDF8oJXHNNvTBZvZlrqGk+hT3Gi/woK2daLCTferFKIp3UX+9guV//Jqj9x/w+FQBifJsTl7cQdInX5BeVksYF0+OFZGTX4k54CIyqd1ni0dIV3H4djNhaSM5CQkJCQmJXwRvPGk5KJox3D9IoUbJ7tNHuHrqKtqRIcKCnt67xzh75/7T2E3BgA1T8xFKNmRzrKGZcMjMyHADt85cwRk04+i8zLnay7jCdvzaK+wszCQ3J52t+0/hEBzY209RUSCnqGorJw6foXuoj8hoC+d2aVhfWkjtuYs8aLyHPzSGOFRLnlLJlY5BJsImBI+e6IQNy60dKLM20GkzM/46MZAkJCQkJCQkfna8lWXpoWA8wnfEDlELIe9kOAc7BE3PYuO4tQQD9ti1QSN+t5aA38xExILo1hIQLRD/WxSsPIsWbkV0awkGbLHPjo/AuI2wXx+LtDwxGgvBELESDZoQPDqiYRNtNRtRlO7A5DQSES2I5gY2pC+n6sxdIlGr1LsjISEhISHxC+GDDS0h+kxEPH1cOxqL3D0eMDJ45wBbT11EEKbvByQhISEhISHxYfPBGh7BE1sRFhZMz7R7DYTFnzDquISEhISEhMR7wcsNz0AvHtfQz7hHZPo8HWkYS0JCQkJC4pfHSw2P0ahDr+1E9OkJ+Q0EJSQkJCQkPlj0Eh8oLzU84XAIg0GLXtuDUd/72hh0Pei13W+UxoeGfrgbo+7d65iXVu37WX5SvZLy5MdAP/zLzj+9tvsXWYd0w91oBzslPlBeanhcLhdDQ4M8edJBa9sT2l6LdtqfdNDV1UNrW/trpvHh0dXVQ1t7LH/etZYX0drWTkdHF52dXe9Z+U3Wq+73TJeUJz93fi5t88egta2djs4uOt679v4jP3drO719/bhGxyQ+UF5qeHp7e9FoNGRnZ5OTk/NaZGZmsmPHDtrb20lPT3/tdD4UNBoNeXl5dHd3s3HjRjQazTvX9CLUajXnz5/nxo0bqFSqd65nkszMTHbu3ElbW5tUr6bkSVVVFW1tbaSlpb1zPT83NBoN69evp6enh8LCwve+bf4YqNVqLl++zNWrV1Gr1e9cz09V7tnZ2XR3d7/slSgdP+PjpYanr68PpVKJTCZDoVC8FklJSZSWltLa2kpiYuJrp/OhIJfLUalUdHZ2kp2d/UZ5+1OwevVqTp8+zeXLl1m1atU71zNJUlISW7ZsoaWlRapXU/Jk69attLS0kJCQ8M71/NyQy+WkpqbS1dVFRkbGe982fwxWr17NuXPnuHDhAqtXr37nen6qcpfJZHR0dPwU713peEfHvAxPamoqSqUStVr9WshkMrZu3UprayvJycmvnc6HgkqlIi0tjc7OTnJzc98ob38KEhMTqa2t5cqVKyQkJLxzPZPIZDK2bdtGS0uLVK+m5ElZWRktLS0kJSW9cz0/N1QqFRkZGXR1dZGdnf3et80fg8TEROrq6rh48SKJiYnvXM9PVe5KpVIyPB/4IRmed9S4JMPz5kiGZ+48kQzP6yMZHsnwSMeHe0iG5x01LsnwvDmS4Zk7TyTD8/pIhkcyPNLx4R6S4XlHjUsyPG+OZHjmzhPJ8Lw+kuGRDI90fLiHZHjeUeOSDM+bIxmeufNEMjyvj2R4JMMjHR/uIRmed9S4JMPz5kiGZ+48kQzP6yMZHsnwSMeHe0iGZy5SVShkySQlpaD8kRrXh2V4lMiSk0hOkaNK/el0zd/wqJCnJJGUIkOlmloOCpKTkkhKSiJFrnrn+fy28uSFhidVhUKWQlL8uZ+SnIJCqSb1pfeIlXVSUhLJMgUqdeo7f+a3yc/S8KSqkL/F76ufpeFJVaNUyOL1ORm58tXLXTI8H/4hGZ5ZqFAq0snftI3KHVvITVWjesG1suQkUhSqebwopjeu98vwpKKQJZMsU6Ce4wX2YsOjQqXSUFJeyfbSIjKUyhfk19tlXoZHpUKZmkrB5kp2bCkiPVWJUhUrA5Uqhy07d7Jz505KC7NRypNJSpahVL3HL/HUVJRyGcnJMpRzlNWLDU+8bhdvY2f8uZ+yfTOZahkyxYuMnwq5LIMNWyvYuXMn20vyyUhVTDORPwdUSgXJyckolKmz2u37aHietc25y0SpSKegpIzKylJy1C/6vpof75vheVF5TaKUq8jILqJy5052Vm6nMEeNUjX/HzGS4fllHJLhmdawlCgUSaxZlUPdYzugZX+6GtmMTaqUKjVqlZKUFBmbqw5QsSENmSKWP0rljOue07jmZXhUymf3VapQq1NRq1Tx/1dO0R27ZvLFM7eG2OeUSiXKyX9TqlCrVciSEli3ZTd7theiVspmfWG+yPCoVDIUiko6/VE8gzcpWpNI0nP0xXhmiKadn5oHKtVTjVOvn6tevczwKOVy1JpSHrkAfxcV61JJSZEjS0mh/FgzYrye95zfQHpuEbt3laNJTUKhmiv/53qeyTyeW7Ny5jPH01TG04vVOcW0c0/TUiqflWXcSMpT1pKeX0r17rhO5ew8eb7hkZOUsI5zzZY5WrqPlkt7SE+Vx9Kc49nlKYnkbTmNMRj/RHcdBelrSE6ZmhfPnmH65m4x/XM/7/Pr7cy6Pav+P6eMJtNSTrmfSq1GKU9BkZ7Dzup9bMhORjYj/+ZteH6ktjk9b1SkJCWyfusedpflo1LI52gLcpIS8rnc4WRifJDdKjlrZfIZ+R2vf5N1b2p9Vc42BfM1PK9WXqpXLC/ltPKqek55xe4pQ6bUcOa+LV6X/VyuUpKQrJjWBqe2v5n5KBmeX8YhGZ6nLyY5SnU6Gk0GqpQCzj4wEIoMsi9NyVq5ksxsDRqNBo0mm1SljJSUDHadbsApiDTVrEepVCGXpaBKz4pdl52FWpGCXDm79+flhicVlUKOXKkmSxO7b1a6CplMRmp6BpqcHLIz0+ONVklqehY5ublkZqQhk6WgnqlBoSI1NYNsTTbpqWlkZGaj0WjISFUhS1GyofwYg2MBhuqr0aTJUc74Unm54amg3S3i6L1OsUxNhkZDZroahUyBQqlAmZoZzzsN2RlpKBXyWecz09Uo5UpUKiUyuYL0rPj1meko5ClzmseXGx4VcrmM/F1XMXpDBEULjQc3IUtORpmaweVeH3jNXD9Vxfay3dw3uHD13mBLXgqyFDmymfkvl6NSpZKRmUW2JpvMzGw0mhwy4/82TbMsBZU6DU1OLpqsTNSpsS9bdVo6Gk0umuxMFLIUFOqMp3mQrpIhkytRq9PI0mSTmZFOWlrm03xTyORkrS/nvnEMV+81SnOTkSte1fCsp+6RBXBy83A5paWlbCrfzbU+L4zr2bcxm+S1ydPrXpoSmUyOPCWZfdc7iUxEaL95mIrNBajla1GmZ09pG3JkCiWpaRlkazRkZWWRrdGg0cTq4qznjb+I5HIZ6sl0srNQxdtOliYHjSabtLRYu1GnppKl0ZCbk41KOaOM0pTPyigrm6zsDFLV6fE0M1ApUlClFVL3SI9vZIAjWxTIFLPb5osNz+y2mZkW24k+LT2DnDnbZs6UtjnjGRWqeF7NbJtKZMlKNu44wbA7yMDNKrLSFKhmvfBjZXqxzUog0MPu9AwysrLJzkpDkaIgPTv27GqlCnVaBtnZ2aSnqVCqUsnMziY7K4NU1ez2/mLDE2tX6oyZ5aWOl1dWvLyU08trrnx7YXnJUKUVcv6xAZ9jgCOlClIUs78HlHIZ2RvK6PKCoH/AqUOVbN6gIVWtRqVSk5GlQZOZjkoVz+ucbDJSU2eVu2R4PvxDMjzq2K8SlbqAM/d6CY5D2G7HaDHj9/WwS51GYU09o/FftZGQh/snd1BWeQHX01zy0XCohMy8Mu4OuWOnwm7u124lI1UR6y14BcOjUspRqdRUnX+IOxJLztXXQOX6tahKqukbFRnrqCNDKSclOZ3aFgt+t5bDpWkoC3Zwf9jzVMO901tQK1LIzD+B1u+ip7UHmyvIeDjAUNMJSgp30umZfI5xtHdPkJWUguIVDU+L3Y1jxITJKABRbN2NlKerkOWUcXMgnlMTEVzaR1Tnq0lO30Rdq5FQdBwAt/4Ru3PSSUleS1F1HUNjsfMhZx9nduYgVypnmZ6XGh6VCrkslaMPtFg6HvHwUS/24ZtkrFGx/1o3EYCJcYLOAfpHhKel6R9uYFOqisq6B1Pyv56qDXJWrcnhZEMfbmEMhzMAeLm5ax2FVacZGpt4qrm2IoOUzPVcG/Ah2h6zZX06a1YmsePsA/wBL001G0lOy+PsQx0T8bwfuFNDYVYSSfLtPDDa0A/2MTA0BtEQI0NNVK4r4kqP+1mt0zexKVWJfMov5fkYnnPNFiYmRrh+sIySkhI2llVxpcfF2GADGzLkJCvU7LrQjCf+7M6+25RpFBTtvsJo/N6RsJ3LuwrJWF/BvWF37BmiXlqu7kUtSyEj/wTDfg82u4vIBIz2XKU0R8OJKc/b33iEwmwlyclJZJfs5oHWG0s8NMbdk5tRKWVUN+oJ+s2c2lnA6hUJ5Jcfx+gNoK8/gEqloOr8wyk669lRJGfVmlxqmwYYcWnpaDPDRBTRNcjxzfkcuNrz7MtNHOLQBg0ymXzehkellKNUp7H74iO88fuO9N6mInctqtIDDI6JONvOkq6QkZKSydl2G77RQQ6WqFEVVfFQ64s/4yhNJ0tRyVPILjyF3u+iu6UH+2iI8VCAgYZjlBTtosc3KTbKUOMxMtdOb5uTZXr+kRFf2M5AvwuYwO/o4tD6deypa8Hh6GNPxhoKDt3A7fHSdGITa+XltFsddNcfJTUpZVqPx8sMj1KehKa0moe6yWdxcedECUqVnH1NRoI+EycqC1i9Yg0Flacw+wLobu9HpVKy68KUfOu5xY5COavX5HHm3gAO52R5RRCdgxwvyefAtd5n5SUMcnCDBtmU4T2VSo5CtYH6odiX2MR4CKepi/4RN62nK0hTZ3Kt34df10B+ahpbjz7E6+ujujB7RjqS4fklHJLhUStJTlaz/cRDwoCj+z5Xmx5hFSaIejrYkZFH+eGzXL9+mQt1t+g1+5kIajmzfTd3Bp1MEEXbdpEd26u4NzSGYO3h6rk6rtf3EBz3cPvQZhRrp3+hvNjwqEhJUbC1pgH/hEDnneucq71Bn1XEo79Brjqfy12jIAyyO3stCTn70QXAN3Cdgoz13DH4nmlo6CU07uZa9QayNMewAAgW7t67Q6ctCONWzmyr5ExjPwHANfyQ03tLSZMppk1+fLnhKafZGgQEeh7Xc/tOPyFAV3+EwsKtnLt2ncuXLnGzoQcR6L2yn9IDDUwAxo77XDp/gctX66gqziVz436M4jimznvUnb7Igw4bUe8g+wszkaXIp937ZYZHpZQhy9pBl91D16UKMisvYB+zcqJQTUHFUXrsQcZFJ623jnPqajOuKAQdfVw9sZNdNQ14xwU67lzj3Jmb9NlEPIbr5K3J5fQDMwC2/mauXDnF3j2nMHgjmDqmaPb0sXNdDpV1XYzj41J5NitTCrjZ74dQP5WaDI40DRENWmm6coELFx8yEgnTV78XdcJWHo1EAZHulnoa+0aAEA+O72Pf0XpcUQg4+rl1Zhc5KtW0uQrzGdI6c98wZ1s3P75IvkzO5poGhAk/HY2xZ++3BxgdvElZYRkN/VYi0QjDreepLNvJXZ0AARuPbl/hTocZCNB8tpK8wpqn9e1B4zVq9u3hQuMgoYCFO5cvcOFS/Hlv7UOtKOK+yY/f0s3Vs3XcaOwjFB3j8u4icrZfws8EnXU7SFotZ9eVIcBPXdk6Sg/fnKXTrbtGzupczsSH7Wx997jaMkgUMN0/x45tJxjyjDMhOmirr6FYk/F0uOPlhkdFcoqCbSeaEPDzpCF+X0cA9/BVctSFXOv1gK+XqqxEEvMOYQyDu/cK+Zn53DUJ+M1dXIk/Yzg6xuWqQrJzT2Lj/2fvPb/i+tY7z3+iV3evedHLnpmeZS93e3r5umd6gttuz3W73U7X9/a91/bvpyyBRC4qkJNACQQIEAKEcgBJIAmEkJBQQhGEECKJnEORY1HhpM+8qEICivQDpEKl813reUFxzj7PfnY4n7PP3vsApn5evn7JxyEbSP3cSjnFnVdtWIHRtnLyzzq3zTngKXzbB4CxtYKHpdWMSTDT9pjT5woYnJ7h0ZkI0otqsSLR+yqHoycKGbVYqLx1HN+Ahe1qJeAx6APRRSXxbmCWmT57Xp68bEGQxrmXfYSY9AeYUKgtPIW/t46zpR3ANIUpBzmRW8asYqLGEbfWYQsTnQ+J9jpI4Tuj3f+mNzx8344E9L4pJDMtn44pGXl2mA/PcpcoLz06fSTn75QxZAHL0EfuF+ZQWj/DdNNdjscnUW5UwNpMzvEkbr4bRx54SUK0dsF8NRV4vg+pwKPX4RsUzdWKITC1k3kogB93hlDwbhBRaOVciAFff3/CY8/wvLaVwQkLiq2HqweDyLzbgISF4pT9eMTnMWgBy6SRpvoGWjtGARgsv8lBre+CVQMrAo9ei29QNDnlRsBCf0cz9XWtjM4CjJIfG8Chi2WYRCvPz0dxKPcFFlni1YUI/BJvMmgFy8RCH/qe55IQe4U+wFiei8ZjP4nXPiAySdGRaGJTChgHGu4cxc/Xe9ET5NpGeKrHrUx2lHFo/x72G47yfgzknhfER/pywCuCc7ef09pmxAq0PbtC0rliJmWYGeqlsaGBitLrxAX5EZdXBUiMD3TSUNtIz5B9ls27nET0moXguBrw6AL8iD33gAkRhJkR2genkGUr1XdT8fQ4wI2qCcShelLDduATlEmzFcarctAG+nPhzfz4tzFmBjCSGxNH3ps+FEa5naRlx+79xM753L/Q57fn4wg9fIb2Geh5nElE0nm6rND3OB3/yBTKe61gnaCj6SMfG3uxAsLAG1KDEikfEbEMVpKg3YvmSBGTSNTeyiRMe4JGK4y+v0Z44D4C1vFKyz7CM8bzvDNkZGaSnnmOe2+7gVkeXD7J1Vc9gJn+dkfeLQAj5EZ5En+jHLPNTNEJTzwTC5mWZNqeXeDAnp34RyZRPwFix1PSU2846ts1Qg5sY0dIChX9NrBO0D4vv7buF6RmXqfPDOZF9bb/+VUiDZE87pawtj7gcGwczwZkZlvvEx0WxuU3xiX8HOBqdBz5bweQ5SHyjvqyW5NB86zAaMM9YvaF8bBTQBqqJi1yL94aw6L6vALw6LX4Bh/keuUgYKZvwXWHuB7jz+GrLzGLZp6ejeTI9TfYZIHn58LwTy5gxAbm8QF7Hjvto57dT66QcCiXAaD/1RX89x3gRH4dEhMUHork8MkipoDa24fw8/NZZg5PHHerjdhsHZwP9WeXh4aijzNgaufiyWyqe41UlN6hoKKV9rZuOt8XUVjyipGxbi5E69AsmsezEvDoA/0xZNxlbF5e2hx56X12iQhDNM96JCwt9zgcd4jnRgVTczFRYeH2PnZe3MYtAP1cjYrjZqURWR7kxlEfdgdm0mIWGKkvJsYjnNIuAXHwPWkRzuUVFGQfcdKGxVI5CmNVV9Du9+DkzVpMo7Vczn/Eh+YeejoaKLt1kffDZprunSPM33cBOKrA831IBZ4FwNNGRpw/u/aGc69mGNFcT1ZMMiW1A0z2t1PX0sHYrIg4VU+GxkD2/XpE2cq9lP14HLuB0Qbi7BidjU00NX2ktqaWN/cuEBvmvw7gGQAkRrs7aG5qpKG+jtrqCq6m6PDTJlE9NEX72xeUve3BPFlLms4b/9TbDDr5UMeLgmwSEq4xgEj9nWx0u/xJuVKBjUnuHo3hSHoBY8p84Fn4fnu9wCN0PuPCrcf0j47R0fqRlt5xFERqCrLRefgTf+ke9Q0faWnvxCRB27PLpOa9RARMw/20Njby8WM9NbX1lFw5Zp9QPe+11srAo8PfP5zc562I0izG7h56e7qYtCiM1D/mcIA3+R8mEUcaOR13AF1UJk2zMP7eATyvjc7xf/+Ks0cPcbO8H4UB8hIM+PgHcuxmFSzp8yH8fUIoeNvN+EA99+/WYBMHuXksGM/wVMr7bKDM0t/SQlNzI/W1tbx/UUDywRQqx8yMND4kbr834YdvMYxAzc0sokJS+DgLY9XXCdesD3iKqgZRlB4uhO3lx+07+OGHPRw+9wwz8L74NLmvuwGR0a75eS/nfLwfqQXvsNgsPMjU4JdaxLQo0/b0Avv37MQ/Mpn6CTA3l5J2Ip8+oKvsClH+HhyIyeBtvw3kWfpbmj/n90k+Jy7l02cG0TRKZ2MTjY56+7r4DGEaH1JyK5gVjDzIK2NcMvH2+gm8fUO4+tbo7GfVS84cOcztygGsliaygwLwDzxFzZSFobr7xHmH87DDhjj0YX3AEzQHPPOvW0vt+3Iun9DipztB3eg0reVlvKzqY3asmpRALzQn7zAigGAapbOx0ZHHWspuZ3E8MY8hBGpuZ6HdFcDJ3HcIjFN4OIpjmUVMKFBXcAhfX58lVuYtAp4QB/A0zIC5m4tJoVypaKenr5e2pnpe5D3mQ309La3NtL0vJFSndVrNtBbgGRVBmBml41Ne6nh19zShAb6kXa9kVhigJO85E5KJ8pwkvP3CuPZuCBAZ6Wr/HLeqF2QfOUzBuwGs5kZOGwIICMygdtrCYO094nwiKO20IQxWrwA8GkIOJlA9BuM1t4gJ3ENYWh7t0xM0t7TT8qyUR6V1NDZUMzDURv6pGHz9dU7lrgKP+0sFnrlXWvn2V1qDDa94Wl7NpAyMv+dCygWaZ0AcrOXugzI6x0UQurgQ5sOJm2+wAt01xY7h/WmE8Q6eF92luKSEkgd3yE6KQx+o+8mvtE5ce44JkbbXz7h3t5j7JSXcvXGWGIOBAI2GrHt1TEkSgs1Gc0kmOo0vgeHHKe+fRRhrp2yeDxlHo4mKvcUYCo1FZ9HtCiAttwoJE/cTIohOvkifCJOdb8k/l7SOV1qnqBoWAQuN757x5EUzViQaSy+QW9YKmKl985DSt12A/ZXWkeNZ3H/4gHvFxZQ8LsNog5H3Nzl+IouOWRhpquLBnSLulZTwoPgax6MXDmWvBjwGrT/auAxqh2XMbSVEBvhwwNuX02W9YOnnakow16qmUMabORO3n4Dwo7wbBnG0hQfXMzh97Tkzikjrq/nxzyTYO5Y77waBYW4lBePrryHqxFX6zEv7rPHzIu7MPfsIhllisq6Y2CBfvDRh5Jd3ojBG1YMSiu/do6SkhGvZ8egD0qmbsTHe/Ig4Tx/CjxYyjkL9rSzCDNG8HQZxtJWnt7OI+smvtOIoemcfGWmueEJpaSkPHpVR2z0FNiNXT0STePUpswi0vnr6Ke9FN84Q5udNRnE1giRQmq3DJzie8gEbmI1UPi3hee0AYOXVjVSi4m4wAvS9yiVa641PYDj5FV0oyhjvHtyn+N59SkpKyM2KRx8ST4XRgm2kjWd35uptIacT49D6emM4nMWHYZHZWQF58APZhwLZ76Ml9cZLZz+vZxDsHUvxhyFEoYUzBg3+ukwaZgVGPz4k1tuXW7WTYB2jpiyH+Mj1vNKyX7fl5fzrZhNt0BMQGEh2yUemRRFRsNI/Qd/jAAAgAElEQVRw7xTaAD8CI5KoHLRiG2nl2Z0iRx4LOHU4iujDhUwgU1+QjXaXhlM3PiAzTdGRUGJSrmKUYKKjnLwzzm1zYZmCseUNJQ/fMyrBVMsTjui9iM5+zIQCsvE9WSlJPPpoAmy8zY9Hr9UsuSpz2VdaukB0kUm8G7RiHZ6fl0Kyjsfay+tINrUjkr28jNVkxWnY76sjLf8VZgSaXy4sryDvOO7VDCHamjmt1xCgy+KjWWC0/gGx3n7crpsCyygfnjmX12fgOU7NJEzV3eZQkAf7dYk8aR4HRaTubgbHLz9jSgBzXznpUT5ODwoq8HwfUoEnyDFpOfgIheUt2BQQR4bo7OpgZPgDWaEhnCupYkqQYbaPdx8+0D9o5G56IIaTN+mesCApIu9upBEbl071gO1T7EZaX5F+MMJpafVaJi3rDUFceVyDaS4xcYSy61mEaXX2FRKxqVQPWrGONXI6PgJNoBZdoD8Hk89SO9+HlpekRIQQEXuDHvM01bdOo9sTwInLr5kyD3E3IZKA6FRed05hk8BYXcwhvwC0Pwl4TlLePUhPfxd9/RZAZqixjBMGLeEJp6nptyADw63lVHZO0lN+nbjjJ3jaMv7Jz6meai4nhhPo70vylQf0zyqO/1hoen6TQ8EGpyW0ywOPgUD/QI5kFdJvMlN5IwldoAaNRktUchFD5nFe5KaTX9bNZG8Np+O8OGCIIa+iF4sgYx2qIj04iAul8+M/TNm1k2i9osh/1cGsuYvrx4PRBOrQBgZwIuch/eYlfNbpCDBEcvfDEDbrKPcuJaAJCESn1RASfYRH9YPMnWUbbeZaSixaTSpvB8fprblP7AFfwo/k02uepiovA21AGDfe2v20DH8gI8RA4E+YtBzge5D8562YzVbkee1ckSaounMWQ4AfGn0QOU/q+DSNWxjm2bUMDD5enLxdzsTUBPeyQ/Dz8yUqad5kY9lEdekFgnWBhB/Op9dspuXJZaJ0/gQGagiJPsqjhqFF+T2C1s+HmBPnqTMKn/wZbn5BWnQ4Oq0O/wAt2cVV2GxW6h9dxBAYYF/pFxS8yM8hnuWmovWK5nZFJ5MTtWQFaQjQpVM1PEHP+7sc9PIjqeg9FquAIhspSIxFq9HO2zZgLZOWg8l5uvi6pwjTadEGBhJ8KI2aISvW0Xoyj4URqNXZ22bKBeoHxU95HGoqIzksmMjD+fSZp3iXl4l2j4a0nHKmzEbuHA0n4OBJKrqmESSFnvKbhO3zxHvBppHe7PeM4tbrNkame2lpnQBgduQjOUej8fcJIDz2PE0zFkaqbxEWGUZOxQAWUyfXEqPRLrG/z2qTlnWB/sSmXqRhaF5eGstI/VReOs7e/4DNZqW29AJ6TYBjFWwIuc/qP20FgW2IpzmpaA/EUPC2k8nxGjINGgJ0p3g/MkFPVRExXn4k363GYhVA6uP6oVC8D3jjNy8Gvt5e6KKOUTFgZqDyBrEh3vgeCOPqk2bM5gnuZwWjSStgxGym63U+0ZoAp9f2KvB8H1KBJ2juKUGLPiiM6JgYosLDCQsPJyomihDHqoyomBhiIsMICg4hIiqGiLAgdEEhREbFEBMTQ2RYKLrAQEIioomJiSEmJprwEANarY6gRbsPr3VZum7uujExxESF232c2+/CoCc0wu6TwWD41GHrtMv4EBJGVEw0kWGhBBmCCJlbLhsSjN4QTFhEFDExMURHhhOyxBD3yjsthxAZHUVERDhhYZH2eIQGo9fa99aY8yc81EBweBQxUeH2J8WQCIefMUSFh6DTah37cOgJd8Q1JiaKYP3S+4WsOMJjCCI0LJKYmGjCgoMI+rQvSAiRMTFEhYcRHh5FdFQkocEG9IYggsMiPl0zRKdFZ3COv86xzDU6JoqwkLmboN3niOV8NugIDoskJjqS4CCDowztGwgGhS6MgTZQiyEoxL68NzKcYIOBoODPZWeY52d0dCShS8RkpZ2WDfPKeqFFEWzQo9cHrVD3DISERRAdHU14qL0e25cnO9KLjiLEoCVQa1+WHhUTQ2R4KMFBhk/5NSzKr84x+rl0vbUvaw4y2OtvTEwM4SFB6AxBBAcv30Z0jjzOxccQFEJE9Od4GhxpxTjq/+K2uZZl6frV2makvW3qP7VNAzptIKHz8xhsb5vBIeFExUQTERZib5thEUTHRC1om5HRB4k/kc6Z06c5vchOnUjgYFQ4EVERhDriGx0Z9nlkOTiEyOgYIsND7H1PeBQx0RH2ZdtL9IVrWZau02qXyItzeYUtKi99UOgScQsm3FFeIZ/6k2iiIsM+lVd0dBTRh49zKjPbKf+nT2eQEBtBRGQUURFhBAcZ7O0/PJLo6ChCg3Xog+3beUSEhSy5UaYKPN+HVOCZX+n1erRa7YIN0wyODkyn1aKdtzGWffNBAzqdFq3283twveNvrVa75E16bcDzuePUOdLS6px3tNXrtGiX2JhvaR/0DqAwfNoTRqdduAmZ/XhnX1YHnvmb7jmnM+ePbm7Tw0+b7uk++zk/H/PiqtXqlt0xddVVWo74LTx/Lt+GT5udzd8Icb4vy8Vfr9eh1S4qj1V8NjjOWby0fukYGBZslvap7AyGJf1cHJPVvqWln3fNz7bQZ4N+6bwb5tf/T+WrWyIN+/mL28CyZb5K25lrm4s3K3Tyc14eP5ft540c7WWln+evc9tcy8aDy133c3tYqm0als6j4XOdXLJtagPw8g/lwtOuJftoaaCC1FAvfAN0n8p2YWztdXNhu3PefG9+e19948Fl8vIlykuvJ9Dfh8AjufSJS4aAitx4Av38FmzRsKDNGZauj/PLXQUe95cKPC6wrfdpiZVN/Xjot2Pqx0M3Zlvx0xJBQQb0hhAOHkshOzvbyTJSE4gMdt6nar221T4tERQURJBBT1B4HKkZp5eIQSYJseH2jSk3UO4q8Li/VOBxganAszmmAs/SMVGBZ/22NYHH/lFXvXaJj7762z+Ku9R31dZrWxJ4goIIMujQLJV/f/9VvgG3tnJXgcf9pQKPC0wFns0xFXiWjokKPOu3rQo8X9O2LPB84XJXgcf9pQKPixqXCjwbNxV4lo6JCjzrNxV4VOBR5b5SgcdFjUsFno2bCjxLx0QFnvWbCjwq8KhyX6nA46LGpQLPxk0FnqVjogLP+k0FHhV4VLmvVgWepqYmAgMD8ff3R6PRrMu8vb05fvw479+/58CBA+tOx10sICAArVZLXV0dYWFhG4rt1zAPDw/y8/O5f/8++/btc7k/c+bt7U1iYiJVVVVqvZoXk6SkJKqqqti/f7/L/fnWLCAgAL1eT0NDA8HBwVu+bX4J8/DwoKCggLt37+Lh4eFyf75Wufv7+1NbW/s17ruqXKRVgaetrY3U1FROnDhBamrquiwpKYmrV69SV1dHYmLiutNxF0tJSSEtLY3GxkaysrI2FNuvYfHx8ZSWlvLixQvi4+Nd7s+cJSUlkZOTQ21trVqv5sUkNzeX2tpajh8/7nJ/vjVLSUkhPT2dpqYmMjIytnzb/BIWHx/PkydPKCsr21Lt/UuX+4kTJ2hsbPwa911VLtKqwNPX10dnZyfd3d0btp6enk1Jx13sW4pHT0/PlvV3q/qlxuTbte89flu5vX8p6+rqore392vcd1W5SKsCj9FoZHJykunp6XWbxWKhsbGRtLQ0LBbLhtJyBzOZTExOTpKYmIjRaMRkMrncp9XKr7i4mLy8vC1VfhaLhfr6erVeLRGTkydPqjFZh5lMJsbHx0lMTGR4eHjLt80vYRaLhcLCQm7duvVd1aGpqSkGBgZQFGW126Kqb1SrAs/g4CA2mw1RFNdtAHV1dWi1WoANpeUOJssyVqsVLy8vRkZGUBTF5T6tVn5XrlwhPT19S5UfwIcPH9DpdFvKL1fHpLq6Gr1er8ZkHSbLMiaTCS8vLyYmJrZ82/wSBnDu3DlOnz79XdUhQRAwGo0q8Lix1gQ8FosFm822bgOor68nJCQEYENpuYOJoojZbEaj0TA8PIwkSS73abXyy83NJSsra0uVH0BNTQ2hoaFbyi9Xx+TDhw+EhYWpMVmHiaLIzMwMGo2G8fHxLd82v4QBXLp0iXPnzn1XdchqtarA4+ZSgccFpgLP5vmlAo9zTFTgWb+pwKMCjwo87isVeFxgKvBsnl8q8DjHRAWe9ZsKPCrwqMDjvlKBxwWmAs/m+aUCj3NMVOBZv6nAowKPCjzuKxV4XGAq8GyeXyrwOMdEBZ71mwo8KvCowOO+UoHHBaYCz+b5pQKPc0xU4Fm/qcCjAo8KPO4rFXhcYCrwbJ5fKvA4x0QFnvWbCjwq8KjA477aMPBI845VJGHZBrQ68IgLrquIn9OS5/0uiwuvISkACsIy6YjCSpVcwH66+Ok3QZAXnC8tc64gLvDK6f9z/xaXOHctwCNISzc6RVouL+Jc4Da9I4C1Ao9zPL+kwRqAR5AWh3BeXXE/g7UBz0pt6nu2nwI8c210qTZus9kQlQVBdnnefkodWhV4hIX97JJtai3HbCFTgcf9tSHgkRQwDbZT8bSU0vJaRmblJRs2rAY8EiDQ/e45hbduUVRSybBFRhFFZGCio4Li2/kUl9UxLShIjg5alCVmRvpoa+7DJIqIggjY6K56yZ38PB5XdyEAkrhUBReQERnpaKerbxyrKCKKCiiT1Dy6z63bt3n8sgUzIC2CJkGSUSzjVD+7Td7tB9R0TgDypwYtihK2KSMf61qZsIhO0LUa8IiiyMxoL++elVBUVERRURF3CgspKnlE67AVcfENShARhWk6G+poG5jAJoqb2rnAWoBnYTw324fl/FoJeARBRLSM0fDmKUWFhRQUFPLw1UembMIqIPztGqwOPDIw1lbO3dv53Htez7T4uU1977ZW4BFFEZt5jPb6diasS7RxBawjzTwtzuPm/df0Tdq+GeiBVYBHFEEWaH9XQv6tO7yo7UNe8NC5xmO2mKnA4/5aN/CIkoIw1kFWwF/wv/7rf8G/+Lc/Y1dyMSOzMtKikR5YCXhEZMVCXWkmu3+zn2MJ8QTt3Uf46SImAWtvFUeDvIk+fhjfvZ4cuv4aQQZZBqRJroX/iG/sTUYAFOipvILHL34k4sghQsPCuPq0GVFWEBZ1SJIC8ngNsT/+A/G3GxABlCHuZESyc5uWhITjeG/bR8aTBiTlM8zYBAnEGV7mJhKg0xF3MJidvod52zcLkoQd3qw8OeHDr7bFUD8LLBqVWRl4BAA6n2byw9/+HUGHU0hJSSYxIZ6k9Gze9ViQZAl5XqOUFUBsI9VnH/E36xBgQaOVpc/wIUiyfRSGtd/kYHXgkQBprJqDP/6ShIKPiKw2urY5HfNKwCMqIHbcx/PHPYQcSiDx+HEyb7xgzCq67Q0eVgYeUVYwdVVwWO9FzPFD+Ozx5Eh+BaKCUxv5Hm1NwOMYNay4HMSuPUf4aFnYxgVJhslOLhzVEnQwmhB/L/zirzNsVpCXGQXfSgYrAY+ArCi0P89F5+/D4fiD7NodyM0PRlDkn3DM1jMVeNxf6wQeEZBofpDEz3//5yQWlHI9aR9/8Hu/4FrNIAoLhy9hBeCRFDC1kuy3m9DcWvtFB0rw/SGAp8OjPEvxQZv42H5e9SW2bY+kclwGoZ3zEb78+b//Qw6k3GMSYLaNxAPb0F+oAMBSeZ69e4/yfsIK0tzTlYCsyEz0POfg9l/xf//sP5P0qB0FkLoe4vWjJ1frZwHoepjEHs94ms2AaD9XAibaiwna6cP9XoBJLgQfwHD2NVZHzEaq8tjx93/Kb/cm0LioM5zrVFcDno5H6fgGJ9Oz+I2MLKIoImPGblpbW2nr7GHcAkidZAR6k1T4EQDzuJG2llZaW9oYmrSgKBKiDNLsBN1tzbS09jBpFlGk1Z86YSXgscdzvKeMg9v+gf/rZ39K8uMOJFwPPDJgfH4a35TCBSEUbFaXd65fMibLA48ETHHv2H70Kc/t9aTyPD/siKFq3DavjXy/tirwCDKKOEJJ9hF+8Uf/nr/zSabVNr+NiyhIfCw8jJd/Or0AU6/RbPPmSpXRUf9cn8/V6tBywCOICpL5I8kHdpD+dBKAitOh7AzNZVQBeY3HuDqPS5kKPO6v9QGPKIM8xcOkHfzuX4fSZgNbUwH/+B//ZwKv1mBTFt7sYJVXWpZZJicmmbUJyIDQdR//nXpetTeQEehL6v0W+5wDoZ6Efbu4VGkG41uy826RczQYw7ECRgHGKwndsZ+sSqPD+TI02/dzrW4KFEfHJQjIkkBn1X3O3rpJutaP5MIGBEA0TzMxOW3PH9BeksS+A8dpmQc8INPxMB1Pb0dHh0xN/kE0+jP0KaBMVZEVHkvKyWMEBCbTYGL9wBNywgl4JGx0v7qM3sMHTaAW7x2/xiv+Hiapj2y9H6nFTYz1vedUbAh+foFo/HfjG3KYsrYpRJORa0nB+Pt447Pbh+isewxZ5VXncMAKwCMIKJJAx7v7nLt9k5OBfpwo+miPp0uBRwAk3l4KxSfkKPl37nKn6BVGq+QYiXN9B/ulYrIs8IiApZFEL29OOSAf6weO7dnNlbdT9tq1BfLgSlsVeCQFZbyRq/n55GXHE6BJWfhQI8igTFAUryMo5SEmAMa4HrGXQxffY/sK7WIz6tBywCMqYG67i//OIJ4M2Puq4dqraHeHUjECKGs7xtV5XMpU4HF/rQt4BEkB2yj5UX/P7/4ylI/jIHc+wfO//Q4BF9cBPDYBSXJMo5zt5WzQj3ilPsA8VU/sPh2nK3oAUIR64vf8SMq9Hod3Np6fjkR75LYdeKzdpPv9wO74ByhAV3ECf/Xz/0LWm5nPGVJkRMGGfW5yP6cNviQV1Ntv0KL944H2pN4Qsvs3xBfV22FrXhtouhbPDv1F7FglUXM7Fg+vNPpmzTzLOUTarbcMVN1E45u47hGe7udn2fXLX6KPPc7xhGMcPnKUnLI2ZMskFcXXeFo3Yo9A0y32/xDE6/4WzgcHkl36jpK0GIKTHiI4YlRdms+Tmg5enjvCzvAzDMmA0MbxgD2k3mlaFU5g9VdaggLQR5bO9zNAuhJ4BEDu52zgr/mHH4JISksmMeYwydkP6LMKyMLWf7Ww3pgsCzwyMPqWiD06zlX12Wuv5QOHd24j/WE/S02+/95sbXN47E8hvWWn8fFNXtjGRQVEI1fD9ARfKne0wTGuR+7GkPIMi/KNAw9gqsxh1+4jVJrsxw7V5+D9zxoed4mAuIZjtmbbU4HH/bXOER4FhHEK4v4Hv/OrcJomQep4hMd//Tf4nf+wDuCxzwGRp7vIjf4n/jEwifoZYLaW2H2BZL3pBkAWP3J874+kPxhweDfDk4zwz8CjwMzwW4557cfLU8/xhEj2/ejDrdoRxoxdtLS00NbVx4TJhiABYieZOp/PwCPYVxmZ258T6/lXeKeUMKGAaBqlq6ON1tZW+kfGqL+eyC79efrtXlFbEEeAJoPXTwrxPxDN4+Ye6goS2b0zjBe900iisGAYey3A0/XsNB4793O24DGPHz3g3v37VDQbsVkFRNssLaXn8NUEovHZyS9/FcDzjhbOBwdw8kEbfdUPifL5gV2+WhKuPGd0BpCHOB/0j/zX3+4nOMiA3qBl5//4a3RZL7DIrDinBdYwaVkExA4ytD5bA3hsAoJgYqCriVajyVFf6on7cTdXqyZx19EMWAV4xt8RtVfL2cpeACRbLfG7t5H1ZAgVeNYKPPaR3vZHGcsAzyC5EXqCL7zGXiLj5EXtJuzkS/cAnqpr7Nl9iIppB8x8zCHgx0Ce9cqAsKZjXJ3HpUwFHvfXxl5pJe/kd/9MS6MVZmqu8Ld/8AeE32pA+InAI0rATD/Z+u14x2XSPHd/krrJ0nqSdLvRPspiquLgbk9yqycdBywEHkWcoqvpI+2dffQNjDDech+9dzSPa2q5kRaGl5c3+iOZVPVZHRN9FwKPAsy0vSRixy+JufKYCUe9n2x6xLFIDT4+3hy5/IDqJ+cJ9DpGgxlApPJyDProHN6U5qD19SM4JAjf3b/hv/zJXxCb+4IJm4w8b6XY2ufwJNE5NzFoTrYBco+FcGB/NA+ahhlvuIPfbgNP2po4H+xPUmGT/TjLGC21D4gP8OKHX3lx82k52VEH0J95ytDIEP19RiZnLVitq89ngW8QeAQRwTRCU107w2YbsgyS1MCJfXu4+GaC7xJ4HGV0KsCTlKIW+6DlVAXRu/aTVzf9+bXvd2wbAx7Bsa3FDKVpBgzH7trnFmLkgsGDYzdqv0q72Iw6tCzwyGDpLyVoZwAlnfZl58aK8/jui+XDJCALazjG9XlcylTgcX+tc9KygIJIx5NM/uY//IxdITHo9vwlv/efPHnUPgkoTg1oWeARJBRlnIcpwfhF5zLouK4kyoCNslN+eIZeZBzoLIrnN56JtM6KKLICzPDoZDD+cTcdIzxjXAnby4GUUkDg2akA9sflMzx/OwjHK625zj89YD8Jt+oQAWW6lQyNF3E57+37CykyoiggiBLz28Bs33NCtv3ApXfjILRweP8eDt3+uCBu/S/P4LU/ft2vtNpL09gfcIj6MUBxPBHJwEglwZ4HyKwYBUTeXgjlz/9iH0+7Wjij9+VkQSXVjx9QXDn32m+ci4Y9JFyrpPz6UX677wgfZwFGeZSfS2nDIKIkrbhCB9YKPO2c9N/P8dv1rgceUQZzD5mBHiQU1dknpfc9Itj/KOUDs9/MEuH1xGT5ScsiYOVJqg/7I64yCbTeOsJvDpygwyIt2Pvqe7WfAjxtD0+y/8Dxz6u0BAFRFAGF9tIU9u4J44MJTI032fVDIPfbnPvGrWiwwqRlQUa29ZHu+1sOXmsAZsk/6IXn8QeYAVkQEcWVj1lu3yJXmwo87q91L0sXBBFsM7y5YuDnP/tf+N/+5Fck3qvHIihONzpYHngEBeThauI8/4Ff7Q4g2KBHE+CHNuwgZe0ClvFerhzzwdt3H9s0sdz70IeiyI6loTO8OH+YyBPFjAHIMGV8SZzXfnz2bsP/YBrV/RZQRATBhiAIn2/sIiB2cyEqiIx79hGkqQ/X2f2rv2N3QBBBOh3+PgcITzpP87iMIguO80UUSaDpySVCfLexx8eX4Iy7DJsk+94cggjI9L2+QrAhjcZ1Lkvven6OoKgUmsb5DDyCAKKJ15cPsnvPDry8AolMiMXgFcqjumZy48I4U9pMX90TYkI07Pf1x9/Lh4Np+bRO2ZAsw9xKMODp4YmXpye6uGyqjNMLlq0v1wGuDXi6OB8ZRMb91ecFbVbHvOKydBlmjM9J0QXi530Af91hbr7txCqvDHjfssEqy9JFGfNoJxcPe+Hl48E27SEe1A5s6eXCX9N+CvB0lp0nKDiDFgugyPS/LyLrwm36TCCbxyg9H4W/9y62eevJuleDRXTeHmMrGqy8D4+kwFDDU47qtuPp7YVn7FnaRmZBHKb4Qhp33hlBgaGPC49pHZ5d06pQV5kKPO6vDW08KEgyimhjanyEkckZRHnpvV1gpREeGzbzLJMTIxgH+ujp6bFbXz8TJiuSAuLsOH3dnfSPzqCwsNMwm6aZnpnF6uiIZGTM48N0d3UzOmMDRVrhZm7FND3FzKw9fxbTNGNjwwz09dp96O6mzziMySIs7KgECRSRiaEeOnsGmLY6b7hoNZuYmprBskynutpOyxbzDFPTM1isi84XJCRhllFjD11dfUzMWrCYZjDNmjFNTzE9a0NBxjQ+SHd3N93dfUzMCiiyiCgpyLYZBnu76OruY9Isruk1Bqx1p2XLgnh+jY555Z2W7fVhZmSQnq4ueozj9jr6Ddx0NhKT1TYelBQQZsfo7e6if8zk1Ka+Z/spOy1b5rdxQcA8PcbQ8BizVvvCDkUwMdjbSbdxDGGVeXJbyWC1nZbtcx1nxwfo6upl1GRfEWmzmRkfHmRsymxfvbn4mC3+ylQFHvfXhj8tIYj2TfAUWV72iR5WmbQsCEiygqLMs3npiZLs+M0ZXgRRQlrw1CAgyfbj5VWfJgRESfrcEQki8iI/5CWuOXes3Wd5yY5MEEQkaelz1/RpiRXO/xRzRUES7ceJwvy82Fe9KfOOWe7ctXaAa/20xIJ4fmGDtXxL63N9UNx4ZGd+TNbyaYmV2tT3bD/p0xKL2qjT32voG7eiwVq+pfW5z5bn7XEmSvK8neCXOmbrmgo87i/146EuMPXjoZvnl/rxUOeYqB8PXb+pHw9VPx6qAo/7SgUeF5gKPJvnlwo8zjFRgWf9pgKPCjwq8LivVOBxganAs3l+qcDjHBMVeNZvKvCowKMCj/tKBR4XmAo8m+eXCjzOMVGBZ/2mAo8KPCrwuK9U4HGBqcCzeX6pwOMcExV41m8q8KjAowKP+0oFHheYCjyb55cKPM4xUYFn/aYCjwo8KvC4r9YEPHMdwXoNoK6ujsDAQIANpeUOJssyVqsVLy8vRkZGUBTF5T6tVn6XL18mPT19S5Uf2G/uOp1uS/nl6phUV1ej1+vVmKzDZFnGZDLh5eXFxMTElm+bX8IAzp07x+nTp7+rOiQIggo8bq5VgcdoNDI6Osr4+Pi6bWZmhsbGRs6dO8fMzMyG0nIHm5ycZHR0lMzMTPr7+5mcnHS5T6uVX2lpKXfu3NlS5TczM0NDQ4NarxbFpL6+nvPnz6sxWYdNTk4yPDxMVlYWRqNxy7fNL2EzMzPcv3+f4uLi76oOjY2N0d/frwKPG2tV4BkYGGBkZISxsbENWWtrK7dv395wOu5io6Oj5OXlMTAw4HJf1mKvXr3iyZMnLvdjsbW0tKj1apE1NzdTUFDgcj++VRsZGSEvL4/BwUGX++Iqe/HiBWVlZS7342va6Ogo/f39X+O+q8pFWtMrrc1QU1MTWq12U9JyBymKgre3N9PT0652ZU3KyckhIyPD1W44qaGh4dMrLVV21dXVfXqlpeqnSxRFDhw4gNlsdrUrLtPFixc5c+aMq9346jSww44AACAASURBVBocHFRHeNxYawIeSZI2fKGmpibmJlKqAkmS0Gq1TE5OutqVNenGjRtbsgP8+PEj4eHhrnZjS6m+vp6IiAhXu/HNymazERgYiMlkcrUrLtPVq1e5ePGiq934qlIURQUeN5cKPC6SCjybIxV4nKUCz8akAo8KPKrcUyrwuEgq8GyOVOBxlgo8G5MKPCrwqHJPqcDjIqnAszlSgcdZKvBsTCrwqMCjyj2lAo+LpALP5kgFHmepwLMxqcCjAo8q95QKPC6SCjybIxV4nKUCz8akAo8KPKrcUyrwuEgq8GyOVOBxlgo8G5MKPCrwqHJPqcDjIqnAszlSgcdZKvBsTCrwqMCjyj21KcAjDj4jLCCa4oblb96rAY9obuN8ZBABPt54ecRwr9Gx4aEiUHblIAF+HnhqE3ndPbXgvLbHV7lw5QUzjr8VWwcXwnR4e3gQlHKNrilxBc9tPDt7koKXXcyv4ovTXCiFia4yjnr54OPrh8aQTt2M/RozvWUc9jiAt58f8ddfYZaXv/JKwCPNdJF7VI+fJpBAf288Pb3QBGrw0kVw6WX3Cvn5clob8Fh5eiadgldfz8dVgUex8exSNP6+nnjqkinvWbpU3UmrAo9i4+nFKHtM9MmU97p/TH6K1go80+2POZNyg94l748yLY/PEKLZwx7vCG68WdjHbHWtDXhmeZyVRtHbpXcnlqe6uHTEm/3evujj8zAKK3SIW0Aq8Li/Ngw8ttFOsv3+M//Tz/6a8+Wjyx63IvCIQ5zV/TO/1F3EODRE7Z1E9nkfokUU6XmYim9wBs1Dg7w+G84P+rOMKAA2Op/fZvef/AF7EooxAUgmipMD2OaXTsvgIBWXYwk8ksfIEu1MEceouHSE//aznxH/sGsuN85pLtZkOf6/+gcM518zNDREQaIf/scKMU33k+K3DV3qA4aGesiN03Do2geEZeKx4giPLDA9NszQ0DC1RUns3BHJm4EhBodHMbuoLa4GPIo4RsXFQ/zlz/6YhNKtAjwyrUVJ+IZm0jo0yMvsMH4MOs/YV/PONVoZeGRa7iTiG5pF29AgL7JC+THkAuNf1cOtrbUAz0hzFdG//k/81Z6jdC7x/5n62xj8InjUNkBrWTY/7o6kYmilh6+tpdWAR7GN8OpMNH/xx/8nKWVLAc80d5O0hGY+YXCokwzdPgwX3rKVkUcFHvfXhoBnuuc9R7f/Gf/Hv/t9fufPt5P7bvlbyYrAI4zwovgOFb2ODsb8nvBdWh719XIj8gAJNxodF6wgbJcfRZ0KjL0hXKfB6ze/RZdy3w4ns7VE7vTk1Nth+/FDZWh2hvDIaHO6ZF9VLr77ffD49TZOPmoHQBl+6ZzmYo00cefOQ7os9j+nqq/g45NCw4d7eG4P4ZXjpKFn2ezzOUnXMi18ra+0hssv4O93gg67h3RXVVJy8zppaSfIuf2Yp4/u8aZxxH6wqZP7eUU0TQDIVBee4UhcNIeOXKZ+fDn0WptWA57eqhx893vj8ettpD/u2NC1fopWBp5hLhj2cfxms/3PyTeE7vLnbodzfXAnrQw8Q5zX7yPxVqv9z4nXhOwKoLhzY/XDnbQq8My2kXY4FK8ffmCvNp0up/ujyMszIejibjv6ECNZgV6cuNf6Rf3eTK0MPAod5Zfx8fRm3693cPp5j/MRk68I33mAYnvXyuDLbLy8EmmzfDmfNyoVeNxfGwKe3pd5pCSkc/9KHP/u5//ElbfrHOFZpJY7R9ilSWFgpIlEHx3Z5X1z/yHFYzvZz6fAPEr3xARvLx8mOP4O0wCWJmJ3bSO2xDFi01bA9l/9PReqnL+JYxobxDjbx7UoLSlFTY4fR5zTXFESdxI88T9RiqnnIbt/fYC7Rvt/ugqi+NsfA6lc5tF5rcAz8Oocfr5JtEgAAs8zNfy/f+NNTulLPjRUkOi3j4QCBxAOPSXgH7150G/hQ0EGgTEnqXj3lrKcFEKOXaJnA58GWg145uKZG6Eltbh5/Rf6iVoReMz1HNqv5VzlgOOHJpL3befci6mlj3cTrQg8s3XEeWo5XzUXk0aS9u3g/Mtv45tuX0OrAo8wSffwBN1vLqPVpNLu9FAzwc2DQYReKHe8xpql4OBeorPefTOvtVYDnunRQQbN3VwO1ZL+sN3pCLH+Fvv3HObdrP3v8dYb6HfoeT3y5XzeqFTgcX9tCHhkyT5EO/E0gd//899yeROAZ+j1GXb+9kcuVo+C0ETsPj3n3s99wLSJhD3bSX0wN4Qq8+J0FIZPcGLh9bUj/LA9lPzrheQm6fm7//4LchuWG0gd5LTBj5S782/Qi9NcTiKVF3X8Znc45cMK0M+lWH/2aU5wu7CYFM2v+dvtwVQvwzPrAx6Rl9kadoflOJ4ch8jW+ZJ6r8V+8MhLwr0ieVH7jqN7/gnPhEs8evyY0uI0/vnnf8mp5xMrXmslrW0Oj5Esvd9nf76CVgSeqQ9E7dVzsWbI/rfykWO7t5P+aHM+iLtVtSLwTFYTuUfPpTrHKKjcwJFd2zn1ZOjrObjFtdY5PP3Ps/HzT1kCeEbJDdcTmvPe8fc0+dF7MaS+2NKvdOZrbXN4ekgP9ONUqfOIrvD+Grv3JFDjeIs33nQdn38OpKx/68KECjzur02ZtDxYcpjf2wTgaXqQjteOfyKjrNneMUhtJPsGkFk2N2TaQornTi68nptkaeO5E5xI1N/LJTnhFA9LrxPmG8OD2mbuX0kmOjqaY1nXaRqdq9D9ZDsBz+c0ZwBmeii6mPjp3JYJADNPTmnYeUBDSfN8LBrh8flMUtMvcf/mKTR+J2heJnTrAx4bZVlRBCfecwBPL1l6P9LuO4bKx98Q5XeQBy9KCfX8JzSHTpJx6hTpp7I4n5vPu+71T05dG/D0cXorAY/QQqJPAKdf9jp+aCLZYyeXK2a/mn+u0IrAY2vmuHcA2a/mRk0bSfLYxZW33++XwRdrrcDTU7Yc8ExTdCyY0NMvsN/vZ7kds5fD5z+4yQjPnLo4tQzwSG138dsTxRvHM9ZE83WCdoVQuf5nri8uFXjcX1sEeBRGKgsI9grh4YL3LjPcPriH8My39j+7ivDYHszz4bn5BouBZ4zC1ARuVNv/Et6fwyPgBM0j4zRXv+TRo0eUVdQy/Ol+twbgsU3QWPXi07mjFokP+aloQlJps847bbqBU7EnqHK8o35/KRTvI3cwLdN21g88kRgS7jpWkPWT4e9BUnGnIzulBO4J4nn9e+J995L28vOcKtlmZSObC3yTwMM0N6N2EZFdZf+zvZB920N5NfrtTB5dj1aewzNFfuQuIs9U2/9sK2DfjjDejG186wl30caBR+HDtUh89OeYABAbid7jxdnyAedEtqg2CjxY6zi080cuV9uD05J3mF2682zledsq8Li/NgV4Bu6E8y//6K/Ifj287DErAo+lhWO7/jv/qD3JvQcl3Cm4TeG9h3SMK/S+yUXn68+lm9dJCNcQmlXK53lvNh6n6vCOzsc+K0PifUE8P+4J4+b1M0QGHiDzwUoTBXtJ897N0Vsf5/22OM2FUrqK2f2Xf4k+/SYlJcUU3Mrnflkl47YxbiX5s1eXSv614wQEhPGwafkZemsFnr5np9i96xCNDuB5lKLFO+bW51d4l6LZ632E/Bt5nEsM4B/+v908HpFoLsli7zZfzt3K53bGIfwj0ng/sv6b2tqAp4dUr90cm5tT9BW02rL0nldX0foGcOnmdeLDAgjLfoJ7T1lefVl698sraH01XL55nWOhAYSfebrsasLvUWsFnq5Haezec5QWB/CYBhopf1fPtAiznS85pPEk+UouZ1IiORB1js5vaPX/2oCnnUSP3SQWO/pYZZbmdy9p6DcBEs8vHiQg5DA38q+i9dVw/tnXW8ywHqnA4/7aFOAxdZZz9vodGozLD4uvCDymAZ4WXuBURiYZp05xMi2VU2cuUTtor3gDVQWcSo7n5K3Xi0ZMJHprXvLsbdu8m5iF94U5JMfHc+tV6ypDyDPUPHtMVfv8mcVLpflZ1v4a8q9mk5GRwalTp0g7kcTZvBIGBUAZoORMBkkpJ3nRtnLvtlbgMfXV8fhRJeOKw7cPL3n2tn3eDWqMp/kXSD6eyM0Xr6h4UkXvlOOp6mke6SnJpJ68zIcVymYtWhvwOOLZ8fUWOa9l48G+d7dIT44nveAN7v0yy661bDzYV3mL9OQE0gvLXbbVwVbVmvfh6a3h8eMqJhzxm2wv5+6DV4w5Oo7ZrjdcSj9Kwvk7dHxj8+TXBjxTVD99THWXow9Tpql8cJs3bXOZtfHubiYJyWnceNO1bCpbRSrwuL/UnZZdJHWn5c2RutOys9SdljcmdadldadlVe4pFXhcJBV4Nkcq8DhLBZ6NSQUeFXhUuadU4HGRVODZHKnA4ywVeDYmFXhU4FHlnlKBx0VSgWdzpAKPs1Tg2ZhU4FGBR5V7SgUeF0kFns2RCjzOUoFnY1KBRwUeVe4pFXhcJBV4Nkcq8DhLBZ6NSQUeFXhUuadU4HGRVODZHKnA4ywVeDYmFXhU4FHlnvqqwBMaGrrhdNxFkiQRGBioAs8G9fHjRxWkF6m+vl6FwA3IZrOh0WhU4FGBR5WbSR3hcZHUEZ7NkTrC4yx1hGdjUkd4VOBR5Z5aFXj6+/vp7+/HaDSu2wYHB2ltbeXJkycMDg5uKC13sYGBAUpLS+np6XG5L2spv6qqKsrLy7dU+Q0ODtLS0qLWKzUmm2r9/f2UlpbS19fncl9cYYODg1RWVvL27dvvqg4NDAzQ19e32i1R1TesNY3wmEwmzGbzuk2SJBoaGjh48CCSJG0oLXcwq9XKzMwMYWFhDA4OYrPZXO7TauWXn5/P+fPnt1T5SZJEbW0tsbGxW8ovV8ekpqaGuLg4NSbrMKvVytTUFGFhYYyOjm75tvklTJIkcnNzuXLlyndVh2ZnZxkYGFBHeNxYawIeq9WKIAjrNrAPswcFBQFsKC13MEmSsFgs+Pv7Mzw8jCzLLvdptfLLyckhMzNzS5UfQE1NDcHBwVvKL1fH5MOHD4SEhKgxWYdJksTMzAz+/v6Mj49v+bb5JQzg4sWLnD179ruqQzabDaPRqAKPG2tNwGOxWLDZbOs2sAPPXCe8kbTcwURRxGw2o9FoGB4eRpIkl/u0Wvnl5uaSlZW1pcoP7MAzNxne1f5sBQM78MzNl3O1P9+aiaLIzMwMGo2G8fHxLd82v4QBXLp0iXPnzn1XdchqtarA4+ZSgccFpgLP5vmlAo9zTFTgWb+pwKMCjwo87isVeFxgKvBsnl8q8DjHRAWe9ZsKPCrwqMDjvlKBxwWmAs/m+aUCj3NMVOBZv6nAowKPCjzuKxV4XGAq8GyeXyrwOMdEBZ71mwo8KvCowOO+UoHHBaYCz+b5pQKPc0xU4Fm/qcCjAo8KPO6rDQOPuKBuKAjLNKDVgUdceGFJ+PQ/ed7PsigsOE9SFl93YTqisFIlF7CfLq2S5trOFZw2pJaXjtkagEeUF6c1F5fl/HHkWxE3vSOA1YFHWFgRkL5CBwVrAZ6F9UH5VK+W+/3bNlgb8MwvrcVt6nu2nwI8gr2jQFwurYVBdnnefkodWhV4hIXtZ8m+ci3HbCFTgcf9tSHgkRSwjXXw8tEdiooeUts1ioTs1AHAasAjATbaXpVyPecqebdfMjAroYgiMjDa/Jz83MvkP6hiwiYjSyI2m4AkS0wbu2is72ZGFBEFEbDS9voR1y9foriiFRsgiUtVcBEZgcHmRtq6R7GKy6W5tnNFUcQ83sXz4gKuX79GzrWbPHvfhVUUnRr6asAjiiIzw528KrnNjbwb3LiRx43r18gruEvToAVx8Q1KEBGFKVqqq2jqGce2xDU32gGuBDyiBMijvL17i5ycXO49bsAESCvC5ub4tTLwSICV1pcP7fWq4BVGs4gsLvG7RUKRvp2b0koxWQ14FGC4sYy8nMvcfPieSUFGUqEHm23twCNKElbTEE3vmxmzOvcTkgJmYz338y9x5dZTusasIH8bo0WwCvCIEkhWml4VcOXqdR5VdiGxCGjWcswWMxV43F/rBh5RkrGNtHLG8Ff83u/8K/71v/o3/Okvoyk3TqPI0oKKDSsBj4gsm3l/N5Xtv/HmRGoKkfs9CE6/xbgC5q43xOl9OJyWRKCHB9GXn2OTQVYA2wiXDL/B+2A+IwAKdLw+x55f7CA2OZGo8FDOP2xAkBWnDklWQBiqJPK3f8Ox2w0IYB/ZWZSmsgQsLXUuyHQ8SufX/+RD8ql0UlIzKXjejFWSnABwZeCxp9b55BT//Le/IDwxk8zMU5xMSyX9zEWqey1IkrTgCV0BENtI8d7D0fxaBFjQaOeXhyh9HjqS13iDh+WBRxBkFGmAG0lB7NgZTGraSfx37CHtQS2i4gy/m90xLw88IrI8y7s7yWz7rTcpqSlEeO4jJKOIGaxUF51Y9HshYyLf/I0fVgYeSVaYbnvBQZ0PR9IS0Xh4cDD3FYKy2mjo92FrAh5BAhRenNWwbfchPlpYMPIqSDLKeCvZcYGEHTtKtM4Hr0NXMJrkNbc5V9eh5YFHQFFkmh9fJDBAQ1LKMfbs8ie3sg8U+Sccs/VMBR731zqBRwQkGooO8cf/8vcIyX3B67un+Jv//d9iuFbn1HnCCsAjKWBqJSXAg6j8BsdFS/H/wZ/HgyM8SfJGn/wMAKkuhx3bIigfk8HWQlbwAf78D/8DXin3mAQwtRDvuY3gK1X267y/xN49h6kct8KnjkZAVmTGup4Q8c+/4P/54z8j+VE7MqBYmp3SXAg8S58rAcgiL64eJPJW87zoKdis1iU71dWAp+NROr4hJ+hd/JpMFkERGO5po6G+no/NbQybFJA6ydB6k1TYCIBppIePdfXU1zfQN2ZGQUZSQJwZofVjLXX17YyZBJQ1DLXD8sAjKiB0PsBnpy95zVYAeh4ls8cjnqZFN4Iv0TEvCzySAjPNJPnv42CBPSYMlOC7Xc+LpgbStZ4Lf//Bj/vtJqfXm9+awUrAIwGTFB32ICjtJQDW6kts2x5F5dj8NvL92qrAI8gowhBFpw7yd3/0h/y9TzKttvn1XERBov5WHF6aDPoBZirQbffiUmU/sLVHOebq0HLAI4gK4mw9iZ7byXw+DcC7cxHsDL7CsAyysLZjXJ3HpUwFHvfX+oBHEJFlCx8fn0WjPUmTGZTeR2z/j7+D5koNtp8CPDYbNquZmZkZrIL9FZa1vQi/nQbK2xs4pfEj7UGrfR6P0MDxfTu5WDELg++4eKeYG8dDMRwrYBRgopKwHfvJfGu0O298RsB2D3Jrpz7fyAQBWRLoqi7lSnERGXo/kgvrEQFbb4VTmguAZ4Vzkce5EbOLgCNnyLtxnYL775lm6ca9ZuAJTqZ78dQmbHSUnUPr4YchKBj/3b/G49AdpsVesvX+pN1rYrizgrSYUAJ1QRh0+/AxHORR0wS26V4uHTOg0QQQ6OFHZPodBsz2V4erdYArzuExm5g2zSI4Ro+aio6xzyeZNuvSI2Sb2TGv+EprXr1SAHNrIT7bNTzunMFmMTv9/qjL7N7AIwHmjxz38ubU4/b/v70zfWojzRP0f7G7E3tM9H6Y3djpnd2Z7ojq3dnZ6I6a6TNiq7unq+yqcvngMDfiPmwwvgBfuLAN+L6ryjYu2+Wzykf5BGyMKR8c5jDGYA4JgUDozuvZDxK2QSDJCCNQvU/E7wNJKvXTq8xXT77vLzPRAM35mE2Ry/ii1uzeu+bAZwhl+BUeRUU1tVJ57jxnD5WQmrqNp2+KvaSCZuLcxkyyt1/F/bx1E5X5kRQeqsfJ3B9Jg6mFR9bA3n6e5KU53Oh391UDDV+SHpHLPSOgBbZOqD/jZCGEJ/wJuoYHALmfI1kf8LfvLeZC0yAa6ltMablwuSRkxTOUMfqcnWkfk7Tze5zmRtZFZ7Dn/ksANKmRjZGL2Haxy/PGErf35JNefMYtPK5udqV9xpLC87hUlfazG/jt+79izz3rG5/IPb3lLijsZU9mElu/aUQCT6Hw+G1qivxG0fTkr1UAzPfI+csfiMwupby8nJLVm9h7qpYRVK8C3kCEp+v2AZb96QNS8osoKlzH6jVrOXK9DcVu5sGVM1S3DgPgbDlD3CdZVPW0cjAnjb1X6/luxxqyt36H05Pz0zsXuNP4nFt71rF45X4MKiA9Y0vyEkpOu6fkfHXC4Ed4JAnFIzu2thukL1lA6eU21An7wbvomH3X8LyxX5k7KEtZiK78W8yqe5pvsuXvuu7oXQf4EB4VGLxPXkQGB35wPxVacTyiaOlnlF/pZaoi+x9TBDal5d7XX97cTWLS5+OFR9ZA7ufLlZnkHLnnme4e4sSqCLJKb+KYB1OH4EN4AGvdVyyLKKbO6l7X0PgVCR+n8P0LGZADWGduThsL4Ql/ghIeWQE0I5VrPuHv/tPPyDhcjWOSIUvwf5WWAiimdg6t+JBPs8totQO2J6xbnsbumhcAqHIzJdGLqLjiGcHBwvWdea+FRwXH8CNKdfHERmdQsnUNMYt1nHlsQN/VypMnT2hq62TI4rmiSu5kV0bia+GRFa9tao4Rup81+32t4jDT0/2CAY9b2Z6dRPdJBtUGQPXuVP3W8NzcQ0xkIl9+W0111S1u3LjJww4DLpeMZDfTcL6CuOQUdPFL+NOfU7jd2cbBnBTKLnfQ33Cddcmfsjhex/q9l+kdlEAxcCB7Ib9ZEENWZjrpGWksW/AB2fuqcCiaz9oV8HeVljvn0eYr5EX+jrRdNxjVpioWn9mO2d9VWgogD7WwP+cvLFqxk3aLBqo05fJQd7oz0SY+hcdUz+qodPZ7TiIU1xM2RXzGnusDCOEJtGhZAlQ6ru2cQnj0HF+VSc7BatzfiImvV0eQV14dHsLzwwmiItZzz+yRmeZjpC5K4+ZLFZACWifUn3GyEMIT/kxfeGQZJAs39yXzi5/+nJx9dZ5XqF51K+BbeGQFtJEXlKcuImXzITqdnk0p3ezJiKHkVLN7lGW0jtURsRx/POJZYYKcyMO0P35Ee5eeQdMoo+2XyEhYw40njXxdsYrk5GRyNu3lhx6nu+jZj/AMAQy18tX2PJ+vlQHJ2MmD+g7Mqvvsb+jZN6xcmsUdPV5DuAFNaX1fTlJ2Cc8dE74QVw9HC7OISyzi9gsz1rZLJEdmcf1ZCwdzdGw92+JpOyvdbbfZnq3j0z8t58TVu+xdHU/WwTuMWMwMGU3YJcUtJU7/HaAv4VGBkebrZH/2FzZ8XeMexp+Fy3DBt/DICqgjnezQfUJKyVG6XAAKigLqyHOv5XO9tiLQNplSeCRAfsGu1BhKz7a6i91H7rJqaTxfN1rm/XTeTERQwiNJSLIKWLlWnkXWhvPu2kKtjwOZMWw62eB3NHUuBPgQHhWcfdfIWZrMpQ73fHvf3QMkLl/PYzPukwkVHL7WeYd1fcGEEJ7wZ5rCI6Gh0XfvKH/86V/zn//H+yQWFLN+7RpO3+vCpahIgdbwSCqog1zckk7SmhP0AyguHA4XGhJVe9JYnr0Pg6rScqqIBfGlPLcrqKoKWLhWlkPyuq/dIzyaia/yo4jefBFNs3B5WxLxxd8wOKHwV5FcuGRAfk65LoZNpxrGCc/YNo24p7T8vVYBlL675EXHcqLRhKqqtF/fT0b+Ufpk7xGvQISn4+oOYnTraRwCNM8ZkQoY68iNiaPirgGwcWdPJr98P4rrnW3sy0yi7Js66i9f4HRVu7u2iEEOZ0dTUllP3anNLIhYww8mFVy9XPjiEJee9COryrjva7IOcMqrtBQVZfgppYnLKTzxCBlQnA4cDu9i7XfRMU8pPJIKipHzG9NIXn8SA4DswuGU0SZb7nDgnAOd7ky0ydRFyzLg4maFjpgVhzCqCk0n1rEgcQddTkXcj8f1dsLz7EoZMbGbX1+l5XTidLrQ0Oi8XkZ0RA51wxKmJ8dZsiiDK8/NzIdRNPBRtCypqFIfu1I+puDoDyjqMMdWxRFfeg0nIDmcuPys8y6v3AwmhPCEP9MsWlZAsVB1NJ9f/Z9f8dvf/Zr/+79/wc9+9nNWVz55q6JlSQN14BHFCR/yUaSOrIx0dMmJpOau4WaHC5e5n8qtOuITIvkso5hrTf3uSxslBU2zUn1kE2vLvmVI09AUsBpr2ZScQHzEItKKdtNocE0+2iBraHI3R9flsee7FiRNQ5a9t6lONi0zyWs1VPoaTrMmJom4xCQy1u7jfs8I2iT33vAnPJqm0VV1mLx15bSaNLSxqRZJQpNt3D9eTHTUYmJjUllTupH81AKuN7RRuWE1B79vp7/lNoV5aSxPSCIpNoHCnWfptEioriEubF9JbPRyYqNjyNl4mCcDVlQ/9+2BqYVH0WD40QmiF/6ZqJRMMtPSSIqPZWXJAVpNKmqIrtKSNFAM9RTGfciCqJRX+1V6wRaqHtSxJXkBC6JfL09dsZabzxyo8+gGcVO1ia/L0mVZxTncw7HNScTFR7E4cxM3nxrm9OXCsxmBCo+mqby4c4S8/L20OzQ0TaX3h3PsOnialxZQnWZufbEeXfwSFiXmcPBaMy5F83liMVcCfN+HR1FhsK2akuwlRMfFEb/hKF0mB0gDXDy4nbMP+kGDwfbx67wYcszpe10J4Ql/gqjhcWK3WjBbLFgtFiyesE1yZg9+angcdqwWM0ODRgwGAwaDHsOAkVGbE1kFxTnKgL4fo9mOpo3vNBx2Gzb76/wUTcVlGUbfr8dsl9E0X1MVTuw2G/YJOU/cZmCvlVFVmdHBAfR6PYNmO5o2edFuIHdadjrs2Gx271EHSUGVnZiHDPT3D2BxupCcdux2B3abDZvDhYqKY9SEXq9Hrx/A4nTnJisaqmzHNKCnX2/E6lKCvizd5XLhtNsYHR1hcMDg/v70egYGTdj8TJXNRMfss4Zn0v1qkFGrHat1kv3NHvpOdybaxN+NBxUVFIf7mBo0O9zHPBaK/gAAE31JREFU1BzIfS7E29xpeeIx6rCaMZlGsDvdd2HWZAemgX70Q6PufmweyM7YPuT7TssSqgaO0UH69QbMDtkzHerAbBpixOrwsU7oP9+U36cQnrAnqKJlSXZPLb0ZsuQ9LA6BXKU1fjuqorwaJXr1Por3SIQkyxPuPOy+MkdVVRQ/l1u7OzjFK2fvbQb6WgnFk7/i40wmoGdpSTLKFCMvkiS/eh9ZlpEVGUmSPPmMbwN3O0jjPpsyyXJ/HaDvq7RklAnfnzLJdzXTAYFcpeW9X0nS+PaZuL/N54DAHi3h65j6McdbPVpCksft59KEY/bVcar4njKeawGBPEvr9bH1Zj/yug+aep25GkJ4wh/x8NAQhHh46MzlJR4e6t0m4uGh0w/x8FDx8FAhPOGLEJ4QhBCemctLCI93mwjhmX4I4RHCI4QnfBHCE4IQwjNzeQnh8W4TITzTDyE8QniE8IQvQnhCEEJ4Zi4vITzebSKEZ/ohhEcIjxCe8EUITwhCCM/M5SWEx7tNhPBMP4TwCOERwhO+COEJQQjhmbm8hPB4t4kQnumHEB4hPEJ4whchPCEIITwzl5cQHu82EcIz/RDCI4RHCE/4EpDwjHUE0w2AhoYG0tLSAILaVjiEqqo4nU7i4uIwGo1omhbynPx9f0ePHqWsrGxOfX/g/nFPT0+fU3mFuk0ePnxIRkaGaJNphKqq2Gw24uLiGB4envPH5rsIgAMHDrw6wQl1PrMVkiQJ4Qlz/ApPX18ffX19nrv2Ti+MRiOtra1cvHgRo9EY1LbCIQwGA/39/Zw9e5bu7m4MBkPIc/L3/d29e5dbt27Nqe/PaDTS0tIi9ivRJjMWBoOBvr4+zp49S09Pz5w/Nt9FGI1GqquruXPnzo9qH+rv76enp2c2fncFIcKv8PT392OxWLDb7UFFW1sbFRUVQW8nXMJqtVJaWorRaAx5LoHEd999x+nTp0Oex8RoaWlh586dIc9jLsXTp0/ZtWtXyPOYrzE6OkppaSkmkynkuYQqLl68yLlz50Kex2yGzWajr69PjPCEMQFNac3EDtDS0kJWVlbQ2wkXNE0jOTkZs9kc6lQC4s0anrlEc3Mz2dnZoU5jTtHY2EhOTk6o05i3SJJEUlISNpst1KmEjDdreH5MzNTvnWBuEpDwKIoS9Bu1tLQwVkgpAEVRSE9PZ2RkJNSpBERlZSX79u0LdRpeNDc3k5eXF+o05hSNjY3k5+eHOo15i8vlIi0tDavVGupUQsaXX37J4cOHQ53GrKJpmhCeMEcIT4gQwjMzCOHxRghPcAjhEcIjCE+E8IQIITwzgxAeb4TwBIcQHiE8gvBECE+IEMIzMwjh8UYIT3AI4RHCIwhPhPCECCE8M4MQHm+E8ASHEB4hPILwRAhPiBDCMzMI4fFGCE9wCOERwiMIT4TwhAghPDODEB5vhPAEhxAeITyC8CR44ZFtGHq66DYMo/rYTiDCYzd009zUSMszPfIby1VLP61NDbR1DU3y/k4sI7Zx720f6OFpQwPPB/x3WLLNitXmGrfMNtBBY2Mz3Ua7r2zpbmmisbEV/bA0yf9djJjMSFMcO76ER1Ps9HW00NT8lNb253R3d9L2tJnGp230mHzl9O7wLzwag53tNDU10dk7Omt5BSI8qqWPlqYG2ron2X/CkECERxkdaxPTLGU1fwhceBSsplEmO/oBkMx0tjbQ1N6Lc579hgYqPJLVitU+ZQtg0T+jsfEpL4ecM5neO0EIT/gTlPBII71UrlnMP/zkr/gP//BrVn9dj22Kfd+38Gj0P71E1pLlZGWkE/dJLKUX6nACjHZzoDCR1Cwdy5alcPBW27hX3t6Vw6qSi4zdvs/cdZ3cjz8jSZdM6qqN3Hg64OPTGdifEcvOb9sZ28VHOmoozIggNT2VpfFrud3lLSSqq58z2wuIWZJMamoqcambeGgYLyJNlYVEJWyhfQpX9CU8irWLr7fmk5WzgvTYT/nDHz5Cl5NDWt56jt8Lza3PfQuPlYeXdhG3MIb0jCyil6RztsUwK3n5Ex5lpIt96xNIzdSxdFkqh6s6ZiWvUOJPeJThF+xb+7pNjlSHf5u8DYEKz4sbZWSlbqdjst9HycTlfQWkpCewPCqBdUduYZUnWW+OEpDwKC/ZnRLLvu9fTPpvU+tN1qZFkJKeyrLEIu7O4onQdBDCE/4EITwqzecL+V9//R6Z5QfZvnIBf/PfP+VS++Q7tU/hcXXzecxHLK+oAUB6doq4JVnUWW08OpyDrugCKjByu4KFURtpdwHaIJcr1vLrn/4XYrZfxg4g6dmbuZSEbdcAGL5VQbSunGcu77En53AT+9OX8ou/e4/Pb3R7lho4mhtF0ZkuAKrKMlm29gyWCa/tv7Wd33+go8YMIHFyfSzZ5TdwvPo4N4n74B/514hNPJti2CvQKa3huiPokrfRPWG5qsgoiv8DU5ZlFF9DbwHiU3j6rxHx/xZQUTsMQNPptUSn7qR/Bt7XH76Fx8Xd3RmkbPwWDTDdKGNh9GY6php2CxN8C4+Tml3ppG68DMDQ9R0sXL6F53J4t8nb4F94HPxw/jCfvvff+H3853RNskbvzXISk0voANBfI2ZRCuefTexJ5i7+hMc++JjdSZ/w3v/8Rypq+r1XUHvYnxnJlovu/10rSSWq+BKhGZ8ODCE84U8QwqNhGeymqaEbp2rhalksf//LJG51T35Q+xQexUZP5wsGHZ5fyOEaspdlcqe7g0PZiWy/5DkDVRrZGBXDiUYVBu6yaXs523N0ZG+96JYS2yPylsaz/7FnmN50l4xlKZx77vB6y+4HpynaXk5RQgI7vmt3Lxy6Q87SFC53ufMYbfma9Mg8HgyPf61jsJfnvYOvptHu7MolteicOwe5i5PF61lTnEdKxg7apjirC1R4+qoPkJy0lTYFwMWjcycoLlhLTt5KKg6d4sjuUiqrPF3u8EPK1m6lxgCqvY/jG3NISY4jMbqAsw16n+/jD5/CYx3i+YveV53ZQM1eYmM30T4LZ7Q+hUd9SUVKHGWXO91/S08ojoyhsmHuD68Hg0/hUbsp18VRfsVzVu56TFFULCcbXZOv/yPEr/BYWtm9p5wdRXkkp5fz3EvsHVzdnk3O1suek6ARjq2MYdOJJubLT6lv4dHouHeSoh3lrI9LYNd17xEetf8amUvTudHn/nvo8ZekRa+hYQ47nxCe8GdGipYf7IngJ//u3/PplgtM9fSZwIuW7Xy3NZ6owpNYRlvYEJvJ/gdjZxCtbI1eTMX3RlAVFFRqD60je9M5RgFcLyiJWYju0EMALPf28cffvc++Ou8fOFVRACOHV6Sy7Xyre+HTb1geUcg9q/vzjr74hvRPdXz/cuoDwN52leRli/mivh9QqD9XwuYDV+is+4b0lDFR8WZ6wqNQtSeBf/pwFY/0o9jsnZTpYig51+JeeeAWGYtTufFykEuf55O19yoKYG0/S1bqOh7op198HnDRsuUln+sWUnDsAcGXuvvHp/BYHrMmOoNDD8dk7ylbohaz+8bgLGQWOnwKz+gjVkdlcPixZ8pRa2Zz5GL23BS1PGP4FR5NQdZAf+8wKbptdHgJzxAnVmWx4osHnr+tnF4Txcryuz7rHOcS/kZ43P1nH/uyUqi48tzr/9KjSqIiN/LQ49GmthOkLErnTnDnXe8UITzhz4wIT++jy+zIX8L7v1zCN82Td5yBCY+d6n06/hKRQ/WAAvJT1i/PYH/9a+EpiVpM+bWx+hCJ23sKyBoTHjR6G8+TvjiGvOz1bNuQw6KPIjn91IEiy0iShCQrqK/25z72ZiWz7cIE4bG9Fp60T3Vc65KRZQlJkpAV9dVZmuPZTVZG/J7cw/U4AFPzFVZmbabO4MJce5DE+M00Oyfv4qYnPBK3d2eRUjQ2zdbLnsxktl/y1DUZq8hLKOBm3R0KlvyZj1MLKC4uprg4g3/9ze/Zft3op/2nJiDhGe3g0Io/s3jVF/RNXcc4o/gTntXRGRx69Fp4NkcuZlcQ7TAf8Cc8BVGZHH7yWng2RS5m980fR0F3IARaw/Py1l6SJxWewQnCY+HUmihWlNeEjfC46aIiLZmKqwEIT+sJdJ+mc2eS2a+5ghCe8Gf6wqNauFIWz29jt9IHYKpi8d//FYlHn0y6Hb/Co9q4UJJEZEo+Vf2ecSK1m51pia+nJLRmNkdH82X92OSJa4LwyNisI/S2NVFTVUdX82VWJq/jekMTldtziYmJJb1oF4/0Yzt073jhMd4iJyKTqy89U1rtp8iJXcftuhpKV+uIj41l9f5vGQFszd+Su/iPFFXWYPFsrvX8Zj5ZsIyMzHQSln7Ir/7pn1l3/A6jkxw/053SurW7gJySS7i74pfsytBRfvmZe2Xzfdbo1nL1zhVWxEdReqaKutpaause8+xlHybr9C3En/CopjZ2JH+IbvMRumbxIdO+p7S6KE9JpOKaZ8hdaWRjVDTHH3lPcYYTvqe0XlCWksjO7z1VYXIDG6OWc+JxeE/zvQ2BCk/3lMJj58q2HHK3X/NMaZk5kR/DxmONYTKlNcaLKYVH7blKZkQ2tzznGqbGr0iPKuDxHK5bFsIT/gQxwqPQ9M16fv6T/4qu4hhfbk/nvb/5GZuvdE66Hd/C4+TJyVIy8vYz/hokF9e2xpBcdAkAR+0+Pl5WSJNdffX/W7tXkbnxrEd4THyVn8jqk80AdJxeQ9TKI+idCg7bKGazmVGrDflVB9XLnswkSsemtOilPP4jNl1wn4bU7clhcf5JRmQJq8WM2WzGYndiNz5hW2o6+6snlBIrEk6nndHRUdqv7SR2eSGPLK5JO7mAhadqP0mJJa+E5+aufDI3nfeM8BjYmxrJuuNPAbA8+orIjxK509nJvqxlZB2q92zFRv29B/Tapn8g+xQeaYgzG3JZe6Bq1jt030XLTq5sjkbnKdC11exmYUQxLfPtGuG3xHfRsoPLm6LQbboKgLVqFwsjN9Aa5m3yNgQsPDf3kJRcOonwQPvFjUTHbnL3Z6bbJCxK4nTL/LjnFgQuPOWpSZRPMqWF8oKtyz+i9Kp7xL9qRwbL1p5lLt/ZSAhP+BPclJZtgBOrP+Rv/+O/4d/+5OfEbL6I0TH5oK1P4RltZPXi3/DH6Fw2Fhexdk0B6zdv536Pxmj3D2xbsZycvCyiddkcvt76xo+qi1u78snYMCY8oG8+R+qyWPKyEknOXs33bcOTvycAvezOSOTz8y2vlnTdP0N+ShS5K3OJyiymqt273qP1dAH/8s9/JnfDRgoL11OQt4J9F+6PO5gNdw+SlFBCW5BXafVV7SMxYQutY8KzM4+MjWPCo/Ci+hAJEUnk5axgXWEG0R9mcNMIw+23WRW5lMxVeRTo4skoOUb7yPQH1H0Jj6PpBJ/85l9YvrKY4sJCVuevoOTAKbpnYaTH32Xp5q56Pl8R7dl/cjh6q/3dJxVi/F2Wbu6q5/PcaHLysonW5fLFj6BN3obAhWc3iUmfv7oSc6jlBsdOXWXA6b4dwvEtaWTkppOUlk7h0VuYZ2madyYIVHjKUhIpu+K5qEQb4fapw3zvKWt4XlPJypQosvNyicraTO1zX31x6BHCE/4EXcOj2Uw8b2mksbUbq49SH9+XpVvp6WzmYf0Damtrqb13j9r6R+g9c0XyUAd1NVU8aJ94bxcN65CevgHzuLnx4edPqamqpt3g7xdXYqivB6N5/HD+cNcjqmvu0aKf/CJK2+BLmpse86C2ltraWu7VVNP4XD/uBmSybYienoEpbzgWqPBI1je3o2Ed7J/weVX62p9QU1VNa5+BIb0Jq+dNbf3t1N2t4V5dEyNBVhD7Eh7ZYuRZawP1dffd7XG3mvqmdkZDfZWWB2noGfdrqqh/5uueTOFDIDcelAY9bdLx42iTtyFQ4ZGsQ/T0Ghm7vs1heknrs27sY8ea00jD/dtUP+5gvk2iBiY8LgZ7exi0eFpAc9LzrJnuN24yONT5A1U1tbQNzP0pUyE84Y94tESIEI+WmBnEoyW8EY+WCA7xaAnxaAlBeCKEJ0QI4ZkZhPB4I4QnOITwCOERhCdCeEKEEJ6ZQQiPN0J4gkMIjxAeQXgihCdECOGZGYTweCOEJziE8AjhEYQnQnhChBCemUEIjzdCeIJDCI8QHkF4IoQnRAjhmRmE8HgjhCc4hPAI4RGEJ0J4QoQQnplBCI83QniCQwiPEB5BeBKQ8Khq8E+AaWlpITs7O+jthAuqqqLT6TCbzaFOJSCOHz/O7t27Q52GF83NzeTk5IQ6jTlFY2Mjubm5oU5j3iJJEsnJydhss/iMlDnG0aNHOXjwYKjTmHWE8IQ3foWnr68Pm82G0+kMKpqbmykqKgp6O+ESdrudgoICjEZjyHMJJM6cOcORI0dCnsfEaGpqori4OOR5zKVoaGhgw4YNIc9jvobFYmHVqlUMDw+HPJdQRWVlJceOHQt5HrMZDoeD3t5eITxhjF/hMZlMGAwGBgYGggqDwYBerw96O+EU86k9DAbDjOwH7yKv+dSOok3mR/zY22+uHu/v+jMPDQ3Nxu+uIET4FR6BQCAQCASC+Y4QHoFAIBAIBGGPEB6BQCAQCARhjxAegUAgEAgEYY8QHoFAIBAIBGGPEB6BQCAQCARhjxAegUAgEAgEYY8QHoFAIBAIBGHP/wdkanuvDdRmsQAAAABJRU5ErkJggg==)The implementiation details written as a pseudo-code are as given below: Pseudo-code for calculating elapsed time```0. Initializelast_store_Seen = 0last_date_recorded = np.datetime64() 1. Read current store number: csn2. Read current SchoolHoliday value: sh_value3. Read current Date: c_dateBegin Is csn == last_store_seen if NO: last_store_seen = csn after = 0 is sh_value == True if Yes, last_date_recorded = c_date if No---last_date_recorded = np.datetime64() if YES: is sh_value == True if Yes, last_date_recorded = c_date after = 0 if False, after = c_date - last_date_recorded``` ###Code # 13.0 We are NOT using this function. But worth examining. # The source code of the following function is here: # https://github.com/fastai/fastai/blob/master/fastai/tabular/core.py#L54 # Usage: https://docs.fast.ai/tabular.core.html#add_elapsed_times # # We are NOT using this function, but it is worth trying. # Other useful functions are at above link. def add_elapsed_times(df, field_names, date_field, base_field): "Add in `df` for each event in `field_names` the elapsed time according to `date_field` grouped by `base_field`" field_names = list((field_names)) #Make sure date_field is a date and base_field a bool df[field_names] = df[field_names].astype('bool') make_date(df, date_field) work_df = df[field_names + [date_field, base_field]] work_df = work_df.sort_values([base_field, date_field]) work_df = _get_elapsed(work_df, field_names, date_field, base_field, 'After') work_df = work_df.sort_values([base_field, date_field], ascending=[True, False]) work_df = _get_elapsed(work_df, field_names, date_field, base_field, 'Before') for a in ['After' + f for f in field_names] + ['Before' + f for f in field_names]: work_df[a] = work_df[a].fillna(0).astype(int) for a,s in zip([True, False], ['_bw', '_fw']): work_df = work_df.set_index(date_field) tmp = (work_df[[base_field] + field_names].sort_index(ascending=a) .groupby(base_field).rolling(7, min_periods=1).sum()) tmp.drop(base_field,1,inplace=True) tmp.reset_index(inplace=True) work_df.reset_index(inplace=True) work_df = work_df.merge(tmp, 'left', [date_field, base_field], suffixes=['', s]) work_df.drop(field_names,1,inplace=True) return df.merge(work_df, 'left', [date_field, base_field]) ###Output _____no_output_____ ###Markdown Our `get_event_elapsed()` function ###Code # 13.1 See StackOverflow # https://stackoverflow.com/a/18215499/3282777 def get_event_elapsed(base_fld, event_fld, dt_fld, df): """ Example: base_fld = 'Store' For every store fld = 'SchoolHoliday' when this event happens, switch on your stop-watch The stop-watch adds a day for each passing day, till next this event happens. At that time reset stop-watch This is 'After-field' dt_fld=Date field How many days, hence, the next event will happen To calculate this, put data in descending order date-wise and apply the algorithm, as if for 'After-field' So for a given 'Store', next 'SchoolHoliday' has come After how many days since the last """ # 13.2 Initialise all variables day1 = np.timedelta64(1, 'D') # See expt below last_store_seen = 0 # This store does not exist last_date_recorded = np.datetime64() # Nat: Not a time (same as None) after = 0 # Initial value in 'after' field res = [] # Collection of all values # as we move forward in time for csn,sh_value,c_date in zip(df[base_fld].values,df[event_fld].values,df[dt_fld].values): # Get current store if csn != last_store_seen: after = 0 last_store_seen = csn if sh_value: last_date_recorded = c_date else: last_date_recorded = np.datetime64() else: if sh_value: last_date_recorded = c_date after =0 else: """ StackOverFlow: https://stackoverflow.com/a/18215499/3282777 In the absence of division by day1 we get the following: numpy.timedelta64(1,'D'), numpy.timedelta64(2,'D'), numpy.timedelta64(3,'D'), numpy.timedelta64(4,'D'), """ after = (c_date - last_date_recorded).astype('timedelta64[D]') / day1 res.append(after) return(res) ###Output _____no_output_____ ###Markdown Simple experiments ###Code # 14.0 Here is print(np.timedelta64(1, 'D')) # 1 days print(type(np.timedelta64(1, 'D'))) # It is a timedelta type print(np.datetime64()) # NaT # 14.1 Create a date-range from 1st March to 16th March dr = pd.date_range(start = '03/01/2021', end = '03/16/2021').to_list() # 14.1.1 Create a data-frame xy = pd.DataFrame( { "event" : [1,0,1,1,0,1, 0,0,0,0,1,1, 0,0,1,0] * 2, "date_fld" : dr * 2, "base_fld" : [1]* 16 + [2]* 16 } ) # 14.1.2 xy.shape # (32, 3) xy.head() xy.tail() # 14.1.3 Shuffle the DataFrame rows xy = xy.sample(frac = 1) xy.head() # 14.2 Sort our dataset on ['base_fld','date_fld'] # dates in ascending order xy = xy.sort_values(['base_fld','date_fld']) # 14.3 Then apply our function # get_event_elapsed(grfld, event_fld, dt_fld, df) # 14.4 xy['after_event']= get_event_elapsed('base_fld','event', 'date_fld', xy ) xy # 14.4 Sort database with dates in descending order xy = xy.sort_values(['base_fld','date_fld'], ascending = [True,False]) # 14.5 Now apply # get_event_elapsed(grfld, event_fld, dt_fld, df) xy['before_event']= get_event_elapsed('base_fld','event', 'date_fld', xy ) xy # 15.0 Function on Kaggle # See https://colab.research.google.com/github/duchaba2/fastai_san_ramon_biztech/blob/master/smbt_rossman_data_clean.ipynb#scrollTo=qdOUyEHcR8Ks def get_elapsed(fld, pre): day1 = np.timedelta64(1, 'D') last_date = np.datetime64() last_store = 0 res = [] for s,v,d in zip(xy.base_fld.values,xy[fld].values, xy.date_fld.values): if s != last_store: last_date = np.datetime64() last_store = s if v: last_date = d res.append(((d-last_date).astype('timedelta64[D]') / day1)) xy[pre+fld] = res # 15.1 Apply the get_elapsed function # Compare results. They are the same. fld = 'event' xy = xy.sort_values(['base_fld', 'date_fld']) get_elapsed(fld, 'After') xy = xy.sort_values(['base_fld', 'date_fld'], ascending=[True, False]) get_elapsed(fld, 'Before') xy ###Output _____no_output_____ ###Markdown Now with real dataExperiment finished. We apply above function to events of 'SchoolHoliday', 'Promo', 'StateHoliday' ###Code # 15.1 # get_event_elapsed(base_fld, event_fld, dt_fld, df) fld = 'SchoolHoliday' joined = joined.sort_values(['Store', 'Date']) joined['after_event_sh'] = get_event_elapsed('Store', fld, 'Date', joined) joined = joined.sort_values(['Store', 'Date'], ascending=[True, False]) joined['before_event_sh'] = get_event_elapsed('Store', fld, 'Date', joined) # 15.1.1 Check joined.shape # (1017209, 78) # 15.2 fld = 'StateHoliday' joined = joined.sort_values(['Store', 'Date']) joined['after_event_st'] = get_event_elapsed('Store', fld, 'Date', joined) joined = joined.sort_values(['Store', 'Date'], ascending=[True, False]) joined['before_event_st'] = get_event_elapsed('Store', fld, 'Date', joined) # 15.2.1 Check joined.shape # (1017209, 80) # 15.3 fld = 'Promo' joined = joined.sort_values(['Store', 'Date']) joined['after_event_pr'] = get_event_elapsed('Store', fld, 'Date', joined) joined = joined.sort_values(['Store', 'Date'], ascending=[True, False]) joined['before_event_pr'] = get_event_elapsed('Store', fld, 'Date', joined) # 15.3.1 Check joined.shape # (1017209, 82) ###Output _____no_output_____ ###Markdown We're going to set the active index to Date. ###Code # 16.0 joined = joined.set_index("Date") joined.shape # (1017209, 81) joined.head() ###Output _____no_output_____ ###Markdown Save data to disk--IISave processed data to disk file `joined_p` ###Code # 16.1 Save data to disk as 'joined_p' # StackOverflow: https://stackoverflow.com/a/17098736/3282777 path = "/content/drive/MyDrive/Colab_data_files/" joined.to_pickle(path +"joined_p") # 16.2 Check saved files # joined_p size: 512020944 !ls -la $path ###Output total 1349928 -rw------- 1 root root 2841873 Dec 27 10:04 bioresponse_train.csv.zip -rw------- 1 root root 69468154 Feb 17 00:53 cats_dogs.tar.gz -rw------- 1 root root 469951247 Mar 19 05:59 joined -rw------- 1 root root 512020944 Mar 19 06:00 joined_p -rw------- 1 root root 18111235 Mar 19 05:59 joined_test -rw------- 1 root root 20995 May 2 2016 LCDataDictionary.xlsx -rw------- 1 root root 76166 Mar 13 12:21 metadata.tsv drwx------ 2 root root 4096 Feb 17 07:15 model -rw------- 1 root root 2038945 Oct 30 2019 pos.zip drwx------ 2 root root 4096 Mar 15 13:04 rossmannStoreSales -rw------- 1 root root 303835737 Feb 21 04:15 talinkigData_out.csv.zip drwx------ 2 root root 4096 Feb 21 04:46 talkingData -rw------- 1 root root 3861202 Mar 13 12:21 vectors.tsv -rw------- 1 root root 84199 Dec 27 06:30 winequality-red.csv ###Markdown Read processed data--IIFile is `joined_p` ###Code # 16.3 Read saved files path = "/content/drive/MyDrive/Colab_data_files/" joined = pd.read_pickle(path +"joined_p") joined_test =pd.read_pickle(path +"joined_test") # 16.4 Check joined.shape # (1017209, 83) #joined_test.shape # (41088, 77) ###Output _____no_output_____ ###Markdown Rolling summaries Simple experiment--IRolling average of prices ###Code # 17.0 # https://benalexkeen.com/resampling-time-series-data-with-pandas/ stocks_nyse_path = "/content/drive/MyDrive/Colab_data_files/rossmannStoreSales/" close_px = pd.read_csv( stocks_nyse_path+"stock_px_2.csv", parse_dates= True, index_col = 0 # Make first column as index column ) # 17.0.1 # Date wise prices for just four tickers close_px.head() #17.1 Pandas rolling window. # Moving averages: # Summarise last 250 points # and bring them forward _=close_px.AAPL.plot() _=close_px.AAPL.rolling(250).mean().plot() # 17.2 # Refer: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html # rolling( # window, # Size of the moving window. # # This is the number of observations # # used for calculating the statistic. # # Each window will be a fixed size. # min_periods=None, # center=False, # win_type=None, # on=None, # axis=0, closed=None) # 17.3 # To understand rolling forward, let us do one # simple experiment. Just average last two points # and create a new column: close_px['avg2'] = close_px['AAPL'].rolling(2).mean() close_px['sum2'] = close_px['AAPL'].rolling(2).sum() close_px[['AAPL', 'avg2','sum2']].head(10) ###Output _____no_output_____ ###Markdown Simple Experiment--IIGroup based rolling summaries. I have daily data for two Stores. For each store, I want moving separate moving average of last two days: ###Code # 18.0 Create a date-range from 1st March to 16th March dr = pd.date_range(start = '03/01/2021', end = '03/16/2021').to_list() # 18.0.1 Create a data-frame xy = pd.DataFrame( { "SchoolHoliday" : [1,0,1,1,0,1, 0,0,0,0,1,1, 0,0,1,0] * 2, "StateHoliday" : [0,0,0,1,0,1, 1,0,1,0,1,1, 0,1,0,1] * 2, "Promo" : [1,1,0,0,1,0,0,1,1,1,0,0,1,0,0,1] * 2, "date_fld" : dr * 2, "Store" : [1]* 16 + [2]* 16, "price" : np.random.normal(loc = 0.24, scale=1, size = (32,) ) } ) # 18.0.2 Shuffle the DataFrame rows xy = xy.sample(frac = 1) xy.head() ###Output _____no_output_____ ###Markdown To create a rolling window, I must put date field as Index ###Code # 18.0.3 df = xy.set_index('date_fld') df.shape df.head() ###Output _____no_output_____ ###Markdown Next I perform grouping and perform moving averages. For each group, a separate bag/basket is created and moving average taken within that group. ###Code # 18.0.4 Here is moving avg and # an explanation of code # Just consider these two columns # Sort index date wise # Create separate bags for each group # Within each bag create rolling windows # Take mean within each window mov_avg = df[['Store','price']]. \ sort_index(). \ groupby("Store"). \ rolling(2, min_periods=1). \ mean() # 18.0.5 Check if moving avg is taken: mov_avg.head() # 18.0.6 And our data for Store 1, # sorted by date-index df.loc[df['Store'] == 1, ['Store', 'price']].sort_index().head() ###Output _____no_output_____ ###Markdown Simple Experiment--IIIGroup by store and take sum of multiple fields ###Code # 19.0 Create a date-range from 1st March to 16th March dr = pd.date_range(start = '03/01/2021', end = '03/16/2021').to_list() # 19.0.1 Create a data-frame xy = pd.DataFrame( { "SchoolHoliday" : [1,0,1,1,0,1, 0,0,0,0,1,1, 0,0,1,0] * 2, "StateHoliday" : [0,0,0,1,0,1, 1,0,1,0,1,1, 0,1,0,1] * 2, "Promo" : [1,1,0,0,1,0,0,1,1,1,0,0,1,0,0,1] * 2, "date_fld" : dr * 2, "Store" : [1]* 16 + [2]* 16, "price" : np.random.normal(loc = 0.24, scale=1, size = (32,) ) } ) # 19.0.2 Shuffle the DataFrame rows xy = xy.sample(frac = 1) xy.head(3) # 19.0.3 Set date-index df = xy.set_index('date_fld') df.shape df.head(3) ###Output _____no_output_____ ###Markdown We will now total up holidays in every two-day periods. ###Code # 19.0.4 columns = ['SchoolHoliday', 'StateHoliday', 'Promo'] # 19.0.5 bwd_xy = df[['Store'] +columns].\ sort_index().\ groupby("Store").\ rolling(2, min_periods=1).\ sum() ###Output _____no_output_____ ###Markdown Note that summation is done, in each bag of 'Store', not only of holidays but also of 'Store'. This is the reason, you observe under Store column, values 1,2. These are not store numbers but moving-summation of values in 'Store' column. Try moving summation of three values and check. ###Code # 19.0.6 Our data has multiple indexes bwd_xy.head() # 19.1 Extract data for Ist index # https://stackoverflow.com/a/18835121/3282777 xx = bwd_xy.iloc[bwd_xy.index.get_level_values('Store') == 1] xx.head() # 19.2 We will drop 'Store' column xx = xx.drop(columns = ['Store']) xx.head() # 19.3 To assist checking of moving summation, # we will create side-by-side columns of # actual vs moving summations: # 19.3.1 Sort data and drop columns not needed sk = df.loc[df['Store'] == 1, :].sort_index().drop(columns = ['Store', 'price']) # 19.3.2 Begin adding columns to sk from xx sk['schoolholiday'] = xx['SchoolHoliday'].values sk['promo'] = xx['Promo'].values sk['stateholiday'] = xx['StateHoliday'].values # 19.3.4 Now check sk[['SchoolHoliday', 'schoolholiday', 'Promo', 'promo','StateHoliday', 'stateholiday']] ###Output _____no_output_____ ###Markdown Next moving-summation on real data We'll now use window functions in pandas to calculate rolling quantities. Here we're sorting by date (`sort_index()`) and counting the number of events of interest (`sum()`) defined in columns in the following week (`rolling()`), grouped by `Store` (groupby()). We do the same in the opposite direction. ###Code # 20.0 Do rolling store by store columns = ['SchoolHoliday', 'StateHoliday', 'Promo'] #20.1 Weekly summation bwd = joined[['Store']+columns].\ sort_index().\ groupby("Store").\ rolling(7, min_periods=1).\ sum() #20.2 Weekly summation # in opposite direction fwd = joined[['Store']+columns]. \ sort_index(ascending=False). \ groupby("Store"). \ rolling(7, min_periods=1).\ sum() # 20.3 bwd.shape # (1017209, 4) bwd.head() # 20.3.1 fwd.shape #(1017209, 4) fwd.head() ###Output _____no_output_____ ###Markdown Next we will drop the Store indices grouped together in the window function. ###Code # 20.3.2 fwd.drop('Store',1,inplace=True) fwd.reset_index(inplace=True) # 20.3.3 bwd.drop('Store',1,inplace=True) bwd.reset_index(inplace=True) ###Output _____no_output_____ ###Markdown Now we'll merge these values onto the 'joined' ###Code # 21 joined.shape # (1017209, 81) print() # 21.1 # Columns ['SchoolHoliday', 'StateHoliday', 'Promo'] in fwd and # bwd are now renamed as ['SchoolHoliday_bw', 'StateHoliday_bw', 'Promo_bw'] # and ['SchoolHoliday_fwd', 'StateHoliday_fwd', 'Promo_fwd'] as these # contain moving summations: # 21.1.1 joined = joined.merge(bwd, 'left', ['Date', 'Store'], suffixes=['', '_bw']) # 21.1.2 joined.shape # (1017209, 85) print() # 21.1.3 joined = joined.merge(fwd, 'left', ['Date', 'Store'], suffixes=['', '_fw']) # 21.1.4 joined.shape # (1017209, 88) print() ###Output _____no_output_____ ###Markdown And Save again--IIIFile created `joined_fp` ###Code # 22.0 Save data to disk as 'joined_fp' # StackOverflow: https://stackoverflow.com/a/17098736/3282777 path = "/content/drive/MyDrive/Colab_data_files/" joined.to_pickle(path +"joined_fp") # 22.1 Check saved files. # joined_fp Size: 574901643 !ls -la $path ###Output total 1911355 -rw------- 1 root root 2841873 Dec 27 10:04 bioresponse_train.csv.zip -rw------- 1 root root 69468154 Feb 17 00:53 cats_dogs.tar.gz -rw------- 1 root root 469951247 Mar 19 05:59 joined -rw------- 1 root root 574901643 Mar 19 06:01 joined_fp -rw------- 1 root root 512020944 Mar 19 06:00 joined_p -rw------- 1 root root 18111235 Mar 19 05:59 joined_test -rw------- 1 root root 20995 May 2 2016 LCDataDictionary.xlsx -rw------- 1 root root 76166 Mar 13 12:21 metadata.tsv drwx------ 2 root root 4096 Feb 17 07:15 model -rw------- 1 root root 2038945 Oct 30 2019 pos.zip drwx------ 2 root root 4096 Mar 15 13:04 rossmannStoreSales -rw------- 1 root root 303835737 Feb 21 04:15 talinkigData_out.csv.zip drwx------ 2 root root 4096 Feb 21 04:46 talkingData -rw------- 1 root root 3861202 Mar 13 12:21 vectors.tsv -rw------- 1 root root 84199 Dec 27 06:30 winequality-red.csv ###Markdown Read data--IIIRead from `joined_fp` ###Code # 22.2 Read saved files: del joined path = "/content/drive/MyDrive/Colab_data_files/" joined = pd.read_pickle(path +"joined_fp") # 22.3 Check joined.shape # (1017209, 90) #joined_test.shape # (41088, 77) ###Output _____no_output_____ ###Markdown Cleaning up and saving Some data-scientists also removed all instances where the store had zero sale / was closed. We speculate that this may have cost them a higher standing in the Kaggle competition. One reason for this may be the case is that a little exploratory data analysis reveals that there are often periods where stores are closed, typically for refurbishment. Before and after these periods, there are naturally spikes in sales that one might expect. By ommitting this data from their training, the authors gave up the ability to leverage information about these periods to predict this otherwise volatile behavior. ###Code # 23.0 joined = joined[joined.Sales!=0] # 23.1 joined.reset_index(inplace=True) #joined_test.reset_index(inplace=True) joined.shape # (844338, 91) ###Output _____no_output_____ ###Markdown Save this data also--IVFile created `joined_fp` ###Code # 24.0 Save data to disk as 'joined_fp' # StackOverflow: https://stackoverflow.com/a/17098736/3282777 path = "/content/drive/MyDrive/Colab_data_files/" joined.to_pickle(path +"joined_fp") # 24.1 Check saved files. # joined_fp Size: 471530522 !ls -la $path ###Output total 1810407 -rw------- 1 root root 2841873 Dec 27 10:04 bioresponse_train.csv.zip -rw------- 1 root root 69468154 Feb 17 00:53 cats_dogs.tar.gz -rw------- 1 root root 469951247 Mar 19 05:59 joined -rw------- 1 root root 471530522 Mar 19 06:02 joined_fp -rw------- 1 root root 512020944 Mar 19 06:00 joined_p -rw------- 1 root root 18111235 Mar 19 05:59 joined_test -rw------- 1 root root 20995 May 2 2016 LCDataDictionary.xlsx -rw------- 1 root root 76166 Mar 13 12:21 metadata.tsv drwx------ 2 root root 4096 Feb 17 07:15 model -rw------- 1 root root 2038945 Oct 30 2019 pos.zip drwx------ 2 root root 4096 Mar 15 13:04 rossmannStoreSales -rw------- 1 root root 303835737 Feb 21 04:15 talinkigData_out.csv.zip drwx------ 2 root root 4096 Feb 21 04:46 talkingData -rw------- 1 root root 3861202 Mar 13 12:21 vectors.tsv -rw------- 1 root root 84199 Dec 27 06:30 winequality-red.csv ###Markdown Read processed data--IVRead finally processed and saved data from disk. File is `joined_fp` ###Code # 24.2 Read saved files: # del joined_fp path = "/content/drive/MyDrive/Colab_data_files/" joined = pd.read_pickle(path +"joined_fp") # 24.3 Check saved files. # joined_fp Size: 471530522 !ls -la $path # 24.4 Check joined.shape # (844338, 91) #joined_test.shape # (41088, 77) ###Output _____no_output_____ ###Markdown Modeling using fastai ###Code ###Output _____no_output_____
_360-in-525/2018/04/jp/360-in-525-04_02.ipynb
###Markdown 02. Numbers, Strings, Booleans and Sets [Mathematical Statistical and Computational Foundations for Data Scientists](https://lamastex.github.io/scalable-data-science/360-in-525/2018/04/)&copy;2018 Raazesh Sainudiin. [Attribution 4.0 International (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/) Numbers and Arithmetic OperationsWe will start by showing you some of the basic numeric capabilities of SageMath.A worksheet cell is the area enclosed by a gray rectangle. You may type any expression you want to evaluate into a worksheet cell. We have already put some expressions into this worksheet.When you are in a cell you can evaluate the expression in it by pressing or just by clicking the evaluate button below the cell. To start with, we are going to be using SAGE like a hand-held calculator. Let's perform the basic arithmetic operations of addition, subtraction, multiplication, division, exponentiation, and remainder over the three standard number systems: Integers denoted by $\mathbb{Z}$, Rational Numbers denoted by $\mathbb{Q}$ and Real Numbers denoted by $\mathbb{R}$. Let us recall the real number line and the basics of number systems next. ###Code def showURL(url, ht=500): """Return an IFrame of the url to show in notebook with height ht""" from IPython.display import IFrame return IFrame(url, width='95%', height=ht) showURL('https://en.wikipedia.org/wiki/Number',400) ###Output _____no_output_____ ###Markdown The most basic numbers are called natural numbers and they are denoted by $\mathbb{N} :=\{0, 1,2,3,\ldots\}$. See [https://en.wikipedia.org/wiki/Natural_number](https://en.wikipedia.org/wiki/Natural_number).> The natural numbers are the basis from which many other number sets may be built by extension: the integers, by including (if not yet in) the neutral element 0 and an additive inverse (−n) for each nonzero natural number n; the rational numbers, by including a multiplicative inverse (1/n) for each nonzero integer n (and also the product of these inverses by integers); the real numbers by including with the rationals the limits of (converging) Cauchy sequences of rationals; the complex numbers, by including with the real numbers the unresolved square root of minus one (and also the sums and products thereof); and so on. These chains of extensions make the natural numbers canonically embedded (identified) in the other number systems. ###Code showURL("https://en.wikipedia.org/wiki/Natural_number#Notation",300) ###Output _____no_output_____ ###Markdown Let us get our fingers dirty with some numerical operations in SageMath. Note that anything after a '' symbol is a comment - comments are ignored by SAGE but help programmers to know what's going on. Example 1: Integer ArithmeticTry evaluating the cell containing 1+2 below by placing the cursor in the cell and pressing . ###Code 1+2 # one is being added to 2 ###Output _____no_output_____ ###Markdown Now, modify the above expression and evaluate it again. Try 3+4, for instance. ###Code 3-4 # subtracting 4 from 3 ###Output _____no_output_____ ###Markdown The multiplication operator is `*`, the division operator is `/`. ###Code 2*6 # multiplying 2 by 6 15/5 # dividing 15 by 5 type(1) ###Output _____no_output_____ ###Markdown The exponentiation operator is `^`. ###Code 2^3 # exponentiating 2 by 3, i.e., raising 2 to the third power ###Output _____no_output_____ ###Markdown However, Python's exponentiation operator `**` also works. ###Code 2**3 ###Output _____no_output_____ ###Markdown Being able to finding the remainder after a division is surprisingly useful in computer programming. ###Code 11%3 # remainder after 11 is divided by 3; i.e., 11=3*3+2 ###Output _____no_output_____ ###Markdown Another way of referring to this is 11 modulus 3, which evaluates to 2. Here `%` is the modulus operator. You tryTry typing in and evaluating some expressions of your own. You can get new cells above or below an existing cell by clicking 'Insert' in the menu above and 'Insert Cell Above' or 'Insert Cell below'. You can also place the cursor at an existing cell and click `+` icon above to get a new cell below. What happens if you put space between the characters in your expression, like:`1 + 2` instead of `1+2`?. Example 2: Operator Precedence for Evaluating Arithmetic ExpressionsSometimes we want to perform more than one arithmetic operation with some given integers. Suppose, we want to - "divide 12 by 4 then add the product of 2 and 3 and finally subtract 1." Perhaps this can be achieved by evaluating the expression "12/4+2*3-1"?But could that also be interpreted as - "divide 12 by the sum of 4 and 2 and multiply the result by the difference of 3 and 1"?In programming, there are rules for the order in which arithmetic operations are carried out. This is called the order of precedence.The basic arithmetic operations are: +, -, *, %, /, ^. The order in which operations are evaluated are as follows:- ^ Exponents are evaluated right to left- *, %, / Then multiplication, remainder and division operations are evaluated left to right- +, - Finally, addition and subtraction are evaluated left to rightWhen operators are at the same level in the list above, what matters is the evaluation order (right to left, or left to right). Operator precedence can be forced using parenthesis. ###Code showURL("https://en.wikipedia.org/wiki/Order_of_operations", 300) (12/4) + (2*3) - 1 # divide 12 by 4 then add the product of 2 and 3 and finally subtract 1 12/4+2*3-1 # due to operator precedence this expression evaluates identically to the parenthesized expression above ###Output _____no_output_____ ###Markdown Operator precedence can be forced using nested parentheses. When our expression has nested parenthesis, i.e., one pair of parentheses inside another pair, the expression inside the inner-most pair of parentheses is evaluated first. ###Code (12/(4+2)) * (3-1) # divide 12 by the sum of 4 and 2 and multiply the result by the difference of 3 and 1 ###Output _____no_output_____ ###Markdown You tryTry writing an expression which will subtract 3 from 5 and then raise the result to the power of 3. Find out for yourself what we mean by the precedence for exponentiation (^) being from right to left: - What do you think the expression `3^3^2` would evaluate to? - Is it the same as `(3^3)^2`, i.e., `27` squared, or - `3^(3^2)`, i.e., `3` raised to the power `9`? Try typing in the different expressions to find out: Find an expression which will add the squares of four numbers together and then divide that sum of squares by 4. Find what the precedence is for the modulus operator `%` that we discussed above: try looking at the difference between the results for `10%2^2` and `10%2*2` (or `10^2+2`). Can you see how SageMath is interpreting your expressions? Note that when you have two operators at the same precedence level (like `%` and `*`), then what matters is the order - left to right or right to left. You will see this when you evaluate `10%2*2`. Does putting spaces in your expression make any difference? Using parenthesis or white spaces can improve readability a lot! So be generous with them. ###Code 10^2+2^8-4 10^2 + 2^8 -4 (((10^2) + (2^8)) - 4) ###Output _____no_output_____ ###Markdown The lesson to learn is that it is always good to use the parentheses: you will make it clear to someone reading your code what you mean to happen as well as making sure that the computer actually does what you mean it to!Try this 10 minutes-long videos to get some practice if you are really rusty with order of operations:* [Khan Academy Order of operations - https://www.youtube.com/watch?v=ClYdw4d4OmA](https://www.youtube.com/watch?v=ClYdw4d4OmA) Example 3: Rational ArithmeticSo far we have been dealing with integers. Integers are a type in SAGE. Algebraically speaking, integers, rational numbers and real numbers form a *ring*. This is something you will learn in detail in a maths course in Group Theory or Abstract Algebra, but let's take a quick peek at the definition of a ring. ###Code showURL("https://en.wikipedia.org/wiki/Ring_(mathematics)#Definition_and_illustration",400) type(1) # find the data type of 1 ###Output _____no_output_____ ###Markdown The output above tells us that `1` is of type `sage.rings.integer.Integer`. ###Code showURL("https://en.wikipedia.org/wiki/Integer",400) ###Output _____no_output_____ ###Markdown However, life with only integers denoted by $\mathbb{Z} := \{\ldots,-3,-2,-1,0,1,2,3,\ldots\}$ is a bit limited. What about values like $1/2$ or $\frac{1}{2}$?This brings us to the rational numbers denoted by $\mathbb{Q}$. ###Code showURL("https://en.wikipedia.org/wiki/Rational_number",400) type(1/2) # data type of 1/2 is a sage.rings.rational.Rational ###Output _____no_output_____ ###Markdown Try evaluating the cell containing `1/2 + 2` below. ###Code 1/2 + 2 # add one half to 2 or four halves to obtain the rational number 5/2 or five halves ###Output _____no_output_____ ###Markdown SageMath seems to have done rational arithmetic for us when evaluating the above expression. Next, modify the expression in the cell below and evaluate it again. Try `1/3+2/4`, for instance. ###Code 1/2 + 1/3 ###Output _____no_output_____ ###Markdown You can do arithmetic with rationals just as we did with integers. ###Code 3/4 - 1/4 # subtracting 3/4 from 1/4 1/2 * 1/2 # multiplying 1/2 by 1/2 (2/5) / (1/5) # dividing 2/5 by 1/5 (1/2)^3 # exponentiating 1/2 by 3, i.e., raising 1/2 to the third power ###Output _____no_output_____ ###Markdown You tryWrite an expression which evaluates to `1` using the rationals `1/3` and `1/12`, some integers, and some of the arithmetical operators - there are lots of different expressions you can choose, just try a few. What does SageMath do with something like `1/1/5`? Can you see how this is being interpreted? What should we do if we really want to evaluate `1` divided by `1/5`? ###Code 1/1/5 ###Output _____no_output_____ ###Markdown Try adding some rationals and some integers together - what type is the result? Example 4: Real Arithmetic (multi-precision floating-point arithmetic)Recall that real numbers denoted by $\mathbb{R}$ include natural numbers ($\mathbb{N}$), integers ($\mathbb{Z}$), rational numbers ($\mathbb{Q}$) and various types of irrational numbers like:- the square root of 2 or $\sqrt{2}$- [Pi](https://en.wikipedia.org/wiki/Pi) or $\pi$ and - Euler's number $e$ and - [Euler–Mascheroni constant](https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant) $\gamma$. Real numbers can be thought of as all the numbers in the real line between negative infinity and positive infinity. Real numbers are represented in decimal format, for e.g. 234.4677878. ###Code showURL("https://en.wikipedia.org/wiki/Real_number#Definition",400) ###Output _____no_output_____ ###Markdown We can do arithmetic with real numbers, actually with [http://www.mpfr.org/](http://www.mpfr.org/)'s multiprecision [floating-point numbers](http://en.wikipedia.org/wiki/Floating_point), and can combine them with integer and rational types in SageMath. *Technical note:* Computers can be made to exactly compute in integer and rational arithmetic. But, because computers with finite memory (all computers today!) cannot represent the [uncountably infinitely many real numbers](http://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument), they can only mimic or approximate arithmetic over real numbers using finitely many computer-representable floating-point numbers.See [SageMath Quick Start on Numerical Analysis](http://doc.sagemath.org/html/en/prep/Quickstarts/NumAnalysis.html) to understand SageMath's multiprecision real arithmetic.For now, let's compare the results of evaluating the expressions below to the equivalent expressions using rational numbers above. ###Code type(0.5) # data type of 0.2 is a sage.rings.real_mpfr.RealLiteral RR # Real Field with the default 53 bits of precision RR(0.5) # RR(0.5) is the same as 0.5 in SageMath 0.5 + 2 # one half as 0.5 is being added to 2 to obtain the real number 2.500..0 in SageMath 0.75 - 0.25 # subtracting 0.75 from 0.25 is the same as subtracting 0.75 from 1/4 0.5 * 0.5 # multiplying 0.5 by 0.5 is the same as 1/2 * 1/2 (2 / 5.0) / 0.2 # dividing 2/5. by 0.2 is the same as (2/5) / (1/5) 0.5^3.0 # exponentiating 0.5 by 3.0 is the same as (1/2)^3 ###Output _____no_output_____ ###Markdown You tryFind the type of `1/2`. Try a few different ways of getting the same result as typing `((((1/5) / (1/10)) * (0.1 * 2/5) + 4/100))*5/(3/5)` - this exact expression has already been put in for you in the cell below you could try something just using floating point numbers. Then see how important the parentheses are around rationals when you have an expression like this - try taking some of the parenthesis out and just play with complex expressions like these to get familiar. ###Code ((((1/5) / (1/10)) * (0.1 * 2/5) + 4/100))*5/(3/5) ((((1/5) / (1/10)) * (1/10 * 2/5) + 4/100))*5/(3/5) ###Output _____no_output_____ ###Markdown Example 5: Variables and assignments of numbers and expressionsLoosely speaking one can think of a *variable* as a way of referring to a memory location used by a computer program. A variable is a symbolic name for this physical location. This memory location contains values, like numbers, text or more complicated types and crucially *what is contained in a variable can change* based on operations we do to it.In SageMath, the symbol `=` is the *assignment operator*. You can assign a numerical value to a *variable* in SageMath using the assignment operator. This is a good way to store values you want to use or modify later. (If you have programmed before using a a language like C or C++ or Java, you'll see that SageMath is a bit different because in SageMath you don't have to say what type of value is going to be assigned to the variable.)Feel free to take a deeper dive into the computer science concept of assignment. ###Code a = 1 # assign 1 to a variable named a a # disclose a - you need to explicitly do this! ###Output _____no_output_____ ###Markdown Just typing the name of a variable to get the value works in the SageMath Notebook, but if you are writing a program and you want to output the value of a variable, you'll probably want to use something like the print command. ###Code print(a) b = 2 c = 3 print a, b, c # print out the values of a and b and c x=2^(1/2) x type(x) # x is a sage symbolic expression ###Output _____no_output_____ ###Markdown Many of the commands in SageMath/Python are "methods" of objects.That is, we access them by typing:- the name of the mathematical object,- a dot/period,- the name of the method, and- parentheses (possibly with an argument).This is a huge advantage, once you get familiar with it, because it allows you to do only the things that are possible, and all such things. See [SageMath programming guide for more details on this](http://doc.sagemath.org/html/en/prep/Programming.htmlmethods-and-dot-notation).Let's try to hit the Tab button after the `.` following `x` below to view all available methods for `x` which is currently `sqrt(2)`. ###Code x. # hit the Tab button after the '.' following 'x' help(x.n) # we can use ? after a method to get breif help x.n(digits=10) # this gives a numerical approximation for x s = 1; t = 2; u = 3; print s + t + u f=(5-3)^(6/2)+3*(7-2) # assign the expression to f f # disclose f type(f) ###Output _____no_output_____ ###Markdown You tryTry assigning some values to some variables - you choose what values and you choose what variable names to use. See if you can print out the values you have assigned. You can reassign different values to variable names. Using SageMath you can also change the type of the values assigned to the variable (not all programming languages allow you to do this). ###Code a = 1 print "Right now, a =", a, "and is of type", type(a) # using , and strings in double quotes print can be more flexible a = 1/3 # reassign 1/3 to the variable a print "Now, a =", a, "and is of type", type(a) # note the change in type ###Output Right now, a = 1 and is of type <type 'sage.rings.integer.Integer'> Now, a = 1/3 and is of type <type 'sage.rings.rational.Rational'> ###Markdown You tryAssign the value `2` to a variable named `x`.On the next line down in the same cell, assign the value `3` to a variable named `y`.Then (on a third line) put in an expression which will evaluate `x + y` ###Code x=2 y = 3 x+y ###Output _____no_output_____ ###Markdown Now try reassigning a different value to x and re-evaluating x + y ###Code x=4 x+y ###Output _____no_output_____ ###Markdown Example 6: StringsVariables can be strings (an not just numbers). Anything you put inside quote marks will be treated as a string by SageMath/Python.Strings as `str` and `unicode` are built-in [sequence types](https://docs.python.org/2/library/stdtypes.htmlsequence-types-str-unicode-list-tuple-bytearray-buffer-xrange) for storing strings of bytes and unicode-encoded characters and and operating over them. ###Code myStr = "this is a string" # assign a string to the variable myStr myStr # disclose myStr type(myStr) # check the type for myStr ###Output _____no_output_____ ###Markdown You can also create a string by enclosing them in single quotes or three consecutive single quotes. In SageMath/Python a character (represented by the `char` type in languages like C/C++/Scala) is just a string made up of one character. ###Code myStr = 'this is a string' # assign a string to the variable myStr using single quotes myStr # disclose myStr ###Output _____no_output_____ ###Markdown You can assign values to more than one variable on the same line, by separating the assignment expressions with a semicolon `;`. However, it is usually best not to do this because it will make your code easier to read (it is hard to spot the other assignments on a single line after the first one). ###Code myStr = '''this is a string''' # assign a string to the variable myStr using three consecutive single quotes myStr # disclose myStr ###Output _____no_output_____ ###Markdown Using triple single quotes is especially useful if your string has single or double quotes within it. Triple quotes are often used to create `DocString` to document code in Pyhton/SageMath. ###Code myStrContainingQuotes = '''this string has "a double quoted sub-string" and some escaped characters: \,', - all OK!''' myStrContainingQuotes ###Output _____no_output_____ ###Markdown Str and unicode StringsIn Python/SageMath, we need to be extremely careful with strings.The type 'str' is actually a sequence of bytes while the unicode string of type `unicode` is a sequence of unicode characters (some of which can be more than a byte in size). See [this](http://pgbovine.net/unicode-python.htm) for an nice clarification of ASCII and unicode (utf-8) encoded strings. So, it is a good habit to convert strings from natural languages that are meant for processing into unicode strings using the `decode(utf-8)` method right away. ###Code x = 'hi猫' # this is hi (each letter is encoded by one byte) followed by the Chinese character for cat (3 bytes) type(x) # x is of type str = sequence of bytes in Python2 / SageMath len(x) # this is a sequence of five hexadecimal numbers each requiring a byte to represent ###Output _____no_output_____ ###Markdown Disclosing `x` below only shows the hexa-decimal numbers `68` `69` `e7` `8c` `ab`, but only `h` for `68` and `i` for `69` from [ASCII table](http://www.asciitable.com/), are displayed as characters here,while `\xe7\x8c\xab` are shown as hexadecimal numbers with prefix `\x` instead of the Chinese character for cat: 猫 ###Code x print(x) # printing a string displays the desired if the display is unicode-compatible ###Output hi猫 ###Markdown Generally it is safe safe to convert strings from natural languages to unicode in Python/SageMath. ###Code y = x.decode('utf-8') # this decodes or converts the sequence of bytes to a sequence of unicode characters type(y) # the type of y now is unicode len(y) # now we have a sequence of just 3 unicode characters as we want ###Output _____no_output_____ ###Markdown Disclosing `y` shows the two ASCII character `h` and `i` and the Chinese cat character 猫 is specified by the corresponding entry in [utf-8 table](https://en.wikipedia.org/wiki/UTF-8). ###Code y # output prepended by u shows it is a unicode sequence as opposed to a str which is a byte sequence print y ###Output hi猫 ###Markdown When programmatically processing sequences of unicode characters it is much safer to work with `repr` for the canonical string representation of the object. ###Code ?repr # gives the canonical string representation of the object print repr(y) print repr(y).decode('unicode_escape') ###Output u'hi猫' ###Markdown Pride and Prejudice as unicodeWe will explore frequencies of strings for the most downloaded book at [Project Gutenberg](http://www.gutenberg.org/ebooks/search/?sort_order=downloads) that publishes public domain books online.Currently, books published before 1923 are in the *public domain* - meaning anyone has the right to copy or use the text in any way. Pride and Prejudice by Jane Austin had the most number of downloads and it's available from - [http://www.gutenberg.org/ebooks/1342](http://www.gutenberg.org/ebooks/1342).A quick exploration allows us to see the utf-encoded text [here](http://www.gutenberg.org/files/1342/1342-0.txt).For now, we will just show how to download the most popular book from the project and display it's contents for processing down the road. ###Code # this downloads the unicode text of the book from the right url we found at the Gutenberg Project # and assigns it to a variable named prideAndPrejudiceRaw from urllib import * prideAndPrejudiceRaw = urlopen('http://www.gutenberg.org/files/1342/1342-0.txt').read().decode('utf-8') prideAndPrejudiceRaw[0:1000] # just showing the first 1000 raw characters of the downloaded book as unicode type(prideAndPrejudiceRaw) # this is a sequence of utf-8-encoded characters len(prideAndPrejudiceRaw) # the length of the unicode string is about 700 thousand unicode characters ###Output _____no_output_____ ###Markdown Next we will show how trivial it is to "read" all the chapters into SageMath/Python using these steps:- we use regular expressions via the `re` library to substitue all occurences of white-space characters like one or more consecutive end-of-line, tabs, white space characters, etc with a single white space, - we split by 'Chapter ' into multiple chapters in a list- print the first 100 character in each of the first 10 Chapters(don't worry about the details now - we will revist these in detail later) ###Code import re # make a list of chapters chapterList = re.sub('\\s+', ' ',prideAndPrejudiceRaw).split('Chapter ')[1:10] for chapter in chapterList: print repr(chapter[0:100]).decode('unicode_escape'), '\n'; ###Output u'1 It is a truth universally acknowledged, that a single man in possession of a good fortune, must be' u'2 Mr. Bennet was among the earliest of those who waited on Mr. Bingley. He had always intended to vi' u'3 Not all that Mrs. Bennet, however, with the assistance of her five daughters, could ask on the sub' u'4 When Jane and Elizabeth were alone, the former, who had been cautious in her praise of Mr. Bingley' u'5 Within a short walk of Longbourn lived a family with whom the Bennets were particularly intimate. ' u'6 The ladies of Longbourn soon waited on those of Netherfield. The visit was soon returned in due fo' u"7 Mr. Bennet's property consisted almost entirely in an estate of two thousand a year, which, unfort" u"8 At five o'clock the two ladies retired to dress, and at half-past six Elizabeth was summoned to di" u"9 Elizabeth passed the chief of the night in her sister's room, and in the morning had the pleasure " ###Markdown As we learn more we will return to this popular book's unicode. Assignment Gotcha!Let's examine the three assignments in the cell below.The first assignment of `x=3` is standard: Python/SageMath chooses a memory location for `x` and saves the integer value `3` in it. The second assignment of `y=x` is more interesting and *Pythonic*: Instead of finding another location for the variable `y` and copying the value of `3` in it, Python/SageMath differs from the ways of C/C++. Since both variables will have the same value after the assignment, Python/SageMath lets `y` point to the memory location of `x`.Finally, after the third assignment of `y=2`, `x` will be NOT be changed to `2` as because the behavior is not that of a C-pointer. Since `x` and `y` will not share the same value anymore, `y` gets its own memory location, containing `2` and `x` sticks to the originally assigned value `3`. ###Code x=3 print(x) # x is 3 y=x print(x,y) # x is 3 and y is y=2 print(x,y) ###Output 3 (3, 3) (3, 2) ###Markdown As every instance (object or variable) has an identity or `id()`, i.e. an integer which is unique within the script or program, we can use `id()` to understand the above behavior of Python/SageMath assignments.So, let's have a look at our previous example and see how the identities change with the assignments. ###Code x = 3 print('x and its id() are:') print(x,id(x)) y = x print('\ny and its id() are:') print(y,id(y)) y = 2 print('\nx, y and their id()s are:') print(x,y,id(x),id(y)) ###Output x and its id() are: (3, 139843823135168) y and its id() are: (3, 139843823135168) x, y and their id()s are: (3, 2, 139843823135168, 139843814033952) ###Markdown Example 6: Truth statements and Boolean valuesConsider statements like "Today is Friday" or "2 is greater than 1" or " 1 equals 1": statements which are either true or not true (i.e., false). SageMath has two values, True and False which you'll meet in this situation. These value are called Booleans values, or values of the type Boolean.In SageMath, we can express statements like "2 is greater than 1" or " 1 equals 1" with relational operators, also known as value comparison operators. Have a look at the list below.- `<` Less than- `>` Greater than- `<=` Less than or equal to- `>=` Greater than or equal to- `==` Equal to. - `!=` Not equal toLets try some really simple truth statements. ###Code 1 < 1 # 1 is less than 1 ###Output _____no_output_____ ###Markdown Let us evaluate the following statement. ###Code 1 <= 1 # 1 is less than or equal to 1 ###Output _____no_output_____ ###Markdown We can use these operators on variables as well as on values. Again, try assigning different values to `x` and `y`, or try using different operators, if you want to. ###Code x = 1 # assign the value 1 to x y = 2 # assign the value 2 to y x == y # evaluate the truth statement "x is equal to y" ###Output _____no_output_____ ###Markdown Note that when we check if something equals something else, we use `==`, a double equals sign. This is because `=`, a single equals sign, is the assignment operator we talked about above. Therefore, to test if `x` equals `y` we can't write `x = y` because this would assign `y to x`, instead we use the equality operator `==` and write `x == y`.We can also assign a Boolean value to a variable. ###Code # Using the same x and y as above myBoolean = (x == y) # assign the result of x == y to the variable myBoolean myBoolean # disclose myBoolean type(myBoolean) # check the type of myBoolean ###Output _____no_output_____ ###Markdown If we want to check if two things are not equal we use `!=`. As we would expect, it gives us the opposite of testing for equality: ###Code x != y # evaluate the truth statement "x is not equal to y" print(x,y) # Let's print x and y to make sure the above statement makes sense ###Output (1, 2) ###Markdown You tryTry assigning some values to two variables - you choose what values and you choose what variable names to use. Try some truth statements to check if they are equal, or one is less than the other. You tryTry some strings (we looked at strings briefly in Example 5 above). Can you check if two strings are equal? Can you check if one string is less than (`<`) another string. How do you think that Sage is ordering strings (try comparing "fred" and "freddy", for example)? ###Code 'raazb' <= 'raaza' x = [1] y = x y[0] = 5 print x print(x,id(x),y,id(y)) ###Output [5] ([5], 139843849399112, [5], 139843849399112) ###Markdown Example 7: Mathematical constantsSage has reserved words that are defined as common mathematical constants. For example, `pi` and `e` behave as you expect. Numerical approximations can be obtained using the `.n()` method, as before. ###Code print pi, "~", pi.n() # print a numerical approximation of the mathematical constant pi print e, "~", e.n() # print a numerical approximation of the mathematical constant e print I, "~", I.n() # print a numerical approximation of the imaginary number sqrt(-1) (i).n(digits=200) # print the first 1000 digits of pi/e e^(i*pi)+1 # Euler's identity symbolically - see https://en.wikipedia.org/wiki/Euler%27s_identity ###Output _____no_output_____ ###Markdown Example 8: SageMath number types and Python number typesWe showed how you can find the type of a number value and we demonstrated that by default, SageMath makes 'real' numbers like 3.1 into Sage real literals (`sage.rings.real_mpfr.RealLiteral`). If you were just using Python (the programming language underlying most of SageMath) then a value like 3.1 would be a floating point number or float type. Python has some interesting extra operators that you can use with Python floating point numbers, which also work with the Sage rings integer type but not with Sage real literals. ###Code X = 3.1 # convert to default Sage real literal 3.1 type(X) X = float(3.1) # convert the default Sage real literal 3.1 to a float 3.1 type(X) ###Output _____no_output_____ ###Markdown Floor Division (`//`) - The division of operands where the result is the quotient in which the digits after the decimal point are removed - the result is floored, i.e., rounded towards negative infinity: examples: 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0 ###Code 3 // 2 # floor division 3.3 // 2.0 # this will give error - floor division is undefined for Sage real literals float(3.5) // float(2.0) ###Output _____no_output_____ ###Markdown Similarly, we have the light-weight Python integer type `int` that we may want instead of SageMath integer type for non-mathematical operations. ###Code type(3) # the default Sage rings integer type X = int(3) # conversion to a plain Python integer type type(X) 3/2 # see the result you get when dividing one default Sage rings integer type by another ###Output _____no_output_____ ###Markdown One of the differences of SageMath rings integers to plain Python integers is that result of dividing one SageMath rings integer by another is a rational. This probably seems very sensible, but it is not what happens at the moment with Python integers. ###Code int(7)/int(2) # division using python integers is "floor division" ###Output _____no_output_____ ###Markdown We showed the `.n()` method. If X is some Sage real literal and we use `X.n(20)` we will be asking for 20 bits of precision, which is about how many bits in the computer's memory will be allocated to hold the number. If we ask for `X.n(digits=20)` will be asking for 20 digits of precision, which is not the same thing. Also note that 20 digits of precision does not mean showing the number to 20 decimal places, it means all the digits including those in front of the decimal point. ###Code help(n) # always ask for help when you need it - or lookup in help menu above X=3.55555555 X.n(digits = 3) X.n(3) # this will use 3 bits of precision round(X,3) ?round # this opens a window with help information that can be closed ###Output _____no_output_____ ###Markdown If you want to actually round a number to a specific number of decimal places, you can also use the round(...) function.For deeper dive see documents on [Python Numeric Types](https://docs.python.org/2/library/stdtypes.htmlnumeric-types-int-float-long-complex) and [SageMath Numeric Types]() SetsSet theory is at the very foundation in modern mathematics and is necessary to understand the mathematical notions of probability and statistics. We will take a practical mathemtical tour of the essential concepts from set theory that a data scientist needs to understand and build probabilistic models from the data using statistical principles. ###Code showURL("https://en.wikipedia.org/wiki/Set_(mathematics)",500) ###Output _____no_output_____ ###Markdown Essentials of Set Theory for Probability and StatisticsLet us learn or recall elementary set theory. Sets are perhaps the most fundamental concept in mathematics. Definitions**Set** *is a collection of distinct elements*. We write a set by enclosing its elements with curly brackets. Let us see some example next.- The collection of $\star$ and $\circ$ is $\{\star,\circ\}$.- We can name the set $\{\star,\circ\}$ by the letter $A$ and write $$A=\{\star,\circ\}.$$- Question: Is $\{\star,\star,\circ\}$ a set?- A set of letters and numbers that I like is $\{b,d,6,p,q,9\}$.- The set of first five Greek alphabets is $\{\alpha,\beta,\gamma,\delta,\epsilon\}$.The set that contains no elements is the **empty set**. It is denoted by $$\boxed{\emptyset = \{\}} \ .$$We say an element belongs to or does not belong to a set with the binary operators $$\boxed{\in \ \text{or} \ \notin} \ .$$ For example,- $\star \in \{\star,\circ\}$ but the element $\otimes \notin \{\star,\circ\}$- $b \in \{b,d,6,p,q,9\}$ but $8 \notin \{b,d,6,p,q,9\}$- Question: Is $9 \in \{3,4,1,5,2,8,6,7\}$?We say a set $C$ is a **subset** of a set $D$ and write$$\boxed{C \subset D}$$if every element of $C$ is also an element of $D$. For example,- $\{\star\} \subset \{\star,\circ\}$- Question: Is $\{6,9\}\subset \{b,d,6,p,q,9\}$? Set OperationsWe can add distinct new elements to an existing set by **union** operation denoted by $\cup$ symbol. For example- $\{\circ, \bullet\} \cup \{\star\} = \{\circ,\bullet,\star\}$- Question: $\{\circ, \bullet\} \cup \{\bullet\} = \quad$?More formally, we write the union of two sets $A$ and $B$ as $$\boxed{A \cup B = \{x: x \in A \ \text{or} \ x \in B \}} \ .$$The symbols above are read as *$A$ union $B$ is equal to the set of all $x$ such that $x$ belongs to $A$ or $x$ belongs to $B$* and simply means that $A$ union $B$ or $A \cup B$ is the set of elements that belong to $A$ or $B$.Similarly, the **intersection** of two sets $A$ and $B$ written as $$\boxed{A \cap B = \{x: x \in A \ \text{and} \ x \in B \}} $$ means $A$ intersection $B$ is the set of elements that belong to both $A$ and $B$.For example- $\{\circ, \bullet\} \cap \{\circ\} = \{\circ\}$- $\{\circ, \bullet\} \cap \{\bullet\} = \{\bullet\}$- $\{\circ\} \cap \{a,b,c,d\}=\emptyset$The **set difference** of two sets $A$ and $B$ written as $$\boxed{A \setminus B = \{x: x \in A \ \text{and} \ x \notin B \}} $$ means $A \setminus B$ is the set of elements that belong to $A$ and not belong to $B$.For example- $\{\circ, \bullet\} \setminus \{\circ\} = \{\bullet\}$- $\{\circ, \bullet\} \setminus \{\bullet\} = \{\circ\}$- $\{a,b,c,d\} \setminus \{a,b,c,d\}=\emptyset$The equality of two sets $A$ and $B$ is defined in terms of subsets as follows: $$\boxed{A = B \quad \text{if and only if} \quad A \subset B \ \text{and} \ B \subset A} \ .$$Two sets $A$ anb $B$ are said to be **disjoint** if $$\boxed{ A \cap B = \emptyset} \ .$$Given a **universal set** $\Omega$, we define the **complement** of a subset $A$ of the universal set by $$\boxed{A^c = \Omega \setminus A = \{x: x \in \Omega \ \text{and} \ x \notin A\}} \ .$$ An Interactive Venn DiagramLet us gain more intuition by seeing the unions and intersections of sets interactively. The following interact is from [interact/misc](https://wiki.sagemath.org/interact/miscAnInteractiveVennDiagram) page of Sage Wiki. ###Code # ignore this code for now and focus on the interact in the output cell def f(s, braces=True): t = ', '.join(sorted(list(s))) if braces: return '{' + t + '}' return t def g(s): return set(str(s).replace(',',' ').split()) @interact def _(X='1,2,3,a', Y='2,a,3,4,apple', Z='a,b,10,apple'): S = [g(X), g(Y), g(Z)] X,Y,Z = S XY = X & Y XZ = X & Z YZ = Y & Z XYZ = XY & Z pretty_print(html('<center>')) pretty_print(html("$X \cap Y$ = %s"%f(XY))) pretty_print(html("$X \cap Z$ = %s"%f(XZ))) pretty_print(html("$Y \cap Z$ = %s"%f(YZ))) pretty_print(html("$X \cap Y \cap Z$ = %s"%f(XYZ))) pretty_print(html('</center>')) centers = [(cos(n*2*pi/3), sin(n*2*pi/3)) for n in [0,1,2]] scale = 1.7 clr = ['yellow', 'blue', 'green'] G = Graphics() for i in range(len(S)): G += circle(centers[i], scale, rgbcolor=clr[i], fill=True, alpha=0.3) for i in range(len(S)): G += circle(centers[i], scale, rgbcolor='black') # Plot what is in one but neither other for i in range(len(S)): Z = set(S[i]) for j in range(1,len(S)): Z = Z.difference(S[(i+j)%3]) G += text(f(Z,braces=False), (1.5*centers[i][0],1.7*centers[i][1]), rgbcolor='black') # Plot pairs of intersections for i in range(len(S)): Z = (set(S[i]) & S[(i+1)%3]) - set(XYZ) C = (1.3*cos(i*2*pi/3 + pi/3), 1.3*sin(i*2*pi/3 + pi/3)) G += text(f(Z,braces=False), C, rgbcolor='black') # Plot intersection of all three G += text(f(XYZ,braces=False), (0,0), rgbcolor='black') # Show it G.show(aspect_ratio=1, axes=False) ###Output _____no_output_____ ###Markdown Create and manipulate sets in SageMath. Example 0: Lists before SetsA `list` is a sequential collection that we will revisit in detail soon. For now, we just need to know that we can create a list by using delimiter `,` between items and by wrapping with left and right square brackets: `[` and `]`. For example, the following is a list of 4 integers: ###Code [1,2,3,4] myList = [1,2,3,4] # we can assign the list to a variable myList print(myList) # print myList type(myList) # and ask for its type ###Output [1, 2, 3, 4] ###Markdown List is one of the most primitive data structures and has a long history in a popular computer programming language called LISP - originally created as a practical mathematical notation for computer programs.For now, we just use lists to create sets. Example 1: Making setsIn SageMath, you do have to specifically say that you want a set when you make it. ###Code X = set([1, 2, 3, 4]) # make the set X={1,2,3,4} from the List [1,2,3,4] X # disclose X type(X) # what is the type of X ###Output _____no_output_____ ###Markdown This is a specialized datatype in Python and more details can be found in Python docs: [https://docs.python.org/2/library/datatypes.html](https://docs.python.org/2/library/datatypes.html) ###Code 4 in X # 'is 4 in X?' 5 in X # 'is 5 in X?' Y = set([1, 2]) # make the set Y={1,2} Y # disclose Y 4 not in Y # 'is 4 not in Y?' 1 not in Y # 'is 1 not in Y?' ###Output _____no_output_____ ###Markdown We can add new elements to a set. ###Code X.add(5) # add 5 to the set X X ###Output _____no_output_____ ###Markdown But remember from the mathematical exposition above that sets contain distinct elements. ###Code X.add(1) # try adding another 1 to the set X X ###Output _____no_output_____ ###Markdown You tryTry making the set $Z=\{4,5,6,7\}$ next. The instructions are in the two cells below. ###Code # Write in the expression to make set Z ={4, 5, 6, 7} # (press ENTER at the end of this line to get a new line) Z = set([4,5,6,7]) #([4],[5],[6,7])) # Check if 4 is in Z 4 in Z # (press ENTER at the end of this line to get a new line) ###Output _____no_output_____ ###Markdown Make a set with the value 2/5 (as a rational) in it. Try adding 0.4 (as a floating point number) to the set. Does SageMath do what you expect? Example 2: SubsetsIn lectures we talked about subsets of sets.Recall that `Y` is a subset of `X` if each element in `Y` is also in `X`. ###Code print "X is", X print "Y is", Y print "Is Y a subset of X?" Y <= X # 'is Y a subset of X?' ###Output X is set([1, 2, 3, 4]) Y is set([1, 2]) Is Y a subset of X? ###Markdown If you have time: We say Y is a proper subset of X if all the elements in Y are also in X but there is at least one element in X that it is not in Y. If X is a (proper) subset of Y, then we also say that Y is a (proper) superset of X. ###Code X < X # 'is X a proper subset of itself?' X > Y # 'is X a proper superset of Y?' X > X # 'is X a proper superset of itself?' X >= Y # 'is X a superset of Y?' is the same as 'is Y a subset of X?' ###Output _____no_output_____ ###Markdown Example 3: More set operationsNow let's have a look at the other set operations we talked about above: intersection, union, and difference.Recall that the intersection of X and Y is the set of elements that are in both X and Y. ###Code X & Y # '&' is the intersection operator ###Output _____no_output_____ ###Markdown The union of X and Y is the set of elements that are in either X or Y. ###Code X | Y # '|' is the union operator ###Output _____no_output_____ ###Markdown The set difference between X and Y is the set of elements in X that are not in Y. ###Code X - Y # '-' is the set difference operator ###Output _____no_output_____ ###Markdown You tryTry some more work with sets of strings below. ###Code fruit = set(['orange', 'banana', 'apple']) fruit colours = set(['red', 'green', 'blue', 'orange']) colours ###Output _____no_output_____ ###Markdown Fruit and colours are different to us as people, but to the computer, the string 'orange' is just the string 'orange' whether it is in a set called fruit or a set called colours. ###Code print "fruit intersection colours is", fruit & colours print "fruit union colours is", fruit | colours print "fruit - colours is", fruit - colours print "colours - fruit is", colours - fruit ###Output fruit intersection colours is set(['orange']) fruit union colours is set(['blue', 'green', 'apple', 'orange', 'banana', 'red']) fruit - colours is set(['banana', 'apple']) colours - fruit is set(['blue', 'green', 'red']) ###Markdown Try a few other simple subset examples - make up your own sets and try some intersections, unions, and set difference operations. The best way to try new possible operations on a set such as X we just created is to type a period after X and hit `` key. THis will bring up all the possible methods you can call on the set X. ###Code mySet = set([1,2,3,4,5,6,7,8,9]) mySet. # try placing the cursor after the dot and hit <TAB> key ?mySet.add # you can get help on a method by prepending a question mark ###Output _____no_output_____ ###Markdown Infact, there are two ways to make sets in SageMath. We have so far used [the python set](https://docs.python.org/2/library/sets.html) to make a set. However we can use the SageMath `Set` to maka sets too. SageMath `Set` is more mathematically consisitent. If you are interested in the SageMath `Set` go to the source and work through the [SageMath reference on Sets](http://doc.sagemath.org/html/en/reference/sets/sage/sets/set.html). But, first let us appreciate the difference between Python `set` and SageMath `Set`! ###Code X = set([1, 2, 3, 4]) # make the set X={1,2,3,4} with python set X # disclose X type(X) # this is the set in python anotherX = Set([1, 2, 3, 4]) # make the set anotherX={1,2,3,4} in SAGE Set anotherX. type(anotherX) # this is the set in SAGE and is more mathy ###Output _____no_output_____ ###Markdown Example 4Python also provides something called a [frozenset](https://docs.python.org/2/library/stdtypes.htmlfrozenset), which you can't change like an ordinary set. ###Code aFrozenSet = frozenset([2/5, 0.2, 1/7, 0.1]) aFrozenSet #aFrozenSet.add(0.3) ###Output _____no_output_____
Finding_Best_Biryani_Point_In__Bangalore.ipynb
###Markdown Table of contents* [Introduction: Business Problem](introduction)* [Data](data)* [Methodology](methodology)* [Analysis](analysis)* [Results and Discussion](results)* [Conclusion](conclusion) Introduction: Business Problem In this project, I am trying to find best reataurant to eat chicken biryani for a person who came to Banglore for the first time and staying in a Hotel within 5 km range from his location. This project is also targeting the people those want to know the best biryani point in their areas.As there may be many restaurants within 5 km range so it's difficult to say which one is serving best biryani.To solve this problem I will use the magic of Data Science. Data To solve this problem I required following data about restaurants within 5 km range from the user's location :* wheather the restaurant serves biryani or not.* rating of restaurant from online plateforms.* coordinate's location of restaurant to showing the path on map to the restaurant from user's location.* user's coordinates location.* travel time to restaurants from user's location.* travel distance betweent restaurant and user's location.Following data sources will be needed to extract/generate the required information:* **geopy libray** to get coordinate's location of User.* **foursqaue API** to explorer user's location to get list of nearby restaurants.* **zomato API** to get ratings of restaurants. (I am using zomato api for ratings because zomato is more used here in Hyderabad than foursquare)* **bing map API** to get driving path locations.**Note*** I will only select first 100 restaurants with in 5 km range for this project.* I will use manual searching for getting whether a restaurant serves biryani or not because these restaurants's food menu data is not available in zomato api, foursquare api and uber eat api so I have no option. ###Code # installing required libraries !pip install geopy # Installing geopy library, this library helps in getting Latitude and Longitude of a given address. !pip install folium # map visualizing library. #avoiding warnigs pd.options.mode.chained_assignment = None # avoiding setting with copy warning import warnings warnings.simplefilter(action='ignore', category=FutureWarning) #importing required libraries import pandas as pd import numpy as np import requests import folium from geopy.geocoders import Nominatim # Nominatim converts an address into latitude and longitude values. #Getting Location's Coordinates of Bangalore City....... address = 'Bangalore' geolocator = Nominatim(user_agent='Bangalore_explorer') Bng_location = geolocator.geocode(address) Bng_latitude = Bng_location.latitude Bng_longitude = Bng_location.longitude print('latitide=',Bng_latitude,' longitude=',Bng_longitude) #Getting Hotel location where user stay... # I am considering that for this project, user stay in The Park Bangalore Hotel_address = 'The Park Bangalore' B_location = geolocator.geocode(Hotel_address) B_lat = B_location.latitude B_long = B_location.longitude print('latitude=',B_lat,' longitude=',B_long) # defining forsquare credentials to get list of 100 restaurants near by user's location. LIMIT = 100 # no. of restaurants. radius = 6000 # defing range 6 KM, I am considering range+1. CLIENT_ID = 'enter your id' # my Foursquare ID CLIENT_SECRET = 'enter your id' # my Foursquare Secret VERSION = '20180605' # Foursquare API version url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format( CLIENT_ID, CLIENT_SECRET, VERSION, H_lat, H_long, radius, LIMIT) url # API calling to get data in Json format result = requests.get(url).json() result # function that extracts the category of the venue def get_category_type(row): try: categories_list = row['categories'] except: categories_list = row['venue.categories'] if len(categories_list) == 0: return None else: return categories_list[0]['name'] from pandas.io.json import json_normalize # tranform JSON file into a pandas dataframe restaurants = result['response']['groups'][0]['items'] nearby_restaurants = json_normalize(restaurants) # flatten JSON # filter columns filtered_columns = ['venue.name','venue.categories', 'venue.location.lat', 'venue.location.lng'] nearby_restaurants = nearby_restaurants.loc[:, filtered_columns] # filter the category for each row nearby_restaurants['venue.categories'] = nearby_restaurants.apply(get_category_type, axis=1) # clean columns nearby_restaurants.columns = [col.split(".")[-1] for col in nearby_restaurants.columns] nearby_restaurants.head() # getting ratings of restaurants from zomato rating=[] #list to store rating zomato_key = {'user-key':'enter your key'} # zomato api key count = 1 # counter print('Processing restaurant no: ') for name,lat,lng in zip(nearby_restaurants['name'],nearby_restaurants['lat'],nearby_restaurants['lng']): print(count,end=" ") url = ('https://developers.zomato.com/api/v2.1/search?q={}&start=0&count=1&lat={}&lon={}').format(name,lat,lng) result = requests.get(url, headers = zomato_key) if(result.status_code == 200): try: result = result.json() rating.append(result['restaurants'][0]['restaurant']['user_rating']['aggregate_rating']) except: rating.append('NA') else: rating.append('NA') count+=1 print('\n restaurants ratings are : ') print(rating) # adding ratings nearby_restaurants['zomato rating'] = rating nearby_restaurants.head() # checking restaurants who have no ratings nearby_restaurants[nearby_restaurants['zomato rating']=='NA'].index # droping the restaurants from list nearby_restaurants.drop([19, 45, 66],axis=0,inplace=True) nearby_restaurants.head() # getting travel distance and travel time from datetime import datetime start_time = datetime.now(tz=None) time=[] # time unit: minutes distance=[] # distance unit: km key = 'enter your key' # Bing Map Api Key. count = 1 # counter. print('Processing restaurant no: ') for name,lat,lng in zip(nearby_restaurants['name'],nearby_restaurants['lat'],nearby_restaurants['lng']): url = 'https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins={},{}&destinations={},{}&travelMode=driving&startTime={}&key={}'.format( H_lat, H_long, lat, lng, start_time, key) print(count,end=" ") result = requests.get(url).json() time.append(result['resourceSets'][0]['resources'][0]['results'][0]['travelDuration']) distance.append(result['resourceSets'][0]['resources'][0]['results'][0]['travelDistance']) count+=1 print('\n time list : ') print(time) print('\n distance list') print(distance) # adding time, distance and serving biryani data to our dataframe nearby_restaurants['travel time minutes'] = time nearby_restaurants['travel distance km'] = distance serving_biryani = [1,0,0,1,1,0,1,0,0,1,1,0,0,1, 1,0,0,1,1,0,1,0,1,0,0,0,1,1, 0,1,1,0,0,1,0,0,0,0,0,0,0,0, 0,1,0,1,0,0,0,0,0,0,0,0,0,1, 0,0,1,1,1,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,1,1,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,] # menually generated list from online searching -> 1: yes, 0: no nearby_restaurants['serves biryani'] = serving_biryani nearby_restaurants.head() # getting those restaurants who serves biryani biryani_points = nearby_restaurants[nearby_restaurants['serves biryani']==1].reset_index(drop=True) biryani_points.head() biryani_points.shape ###Output _____no_output_____ ###Markdown There are 27 restaurants who serves biryani near by user's location Our Data aquisition and data preprocessing has completed now next some visulizations. Bangalore City Map ###Code import folium Bng_map = folium.Map( location=[Bng_latitude,Bng_longitude], zoom_start=12) Bng_map ###Output _____no_output_____ ###Markdown Get user's location on map ###Code Bng_map = folium.Map(location=[B_lat,B_long],zoom_start=20) folium.Marker(location=[B_lat,B_long],tooltip='The Park Bangalore').add_to(Bng_map) Bng_map ###Output _____no_output_____ ###Markdown Showing all restaurants on map those serve biryani ###Code Bng_map = folium.Map(location=[B_lat,B_long],zoom_start=13) folium.Marker(location=[B_lat,B_long],tooltip='The Park Bangalore').add_to(Bng_map) for name,lat,lng in zip(biryani_points['name'],biryani_points['lat'],biryani_points['lng']): folium.CircleMarker( location=[lat,lng], tooltip=name, color='blue', radius=6, fill=True, fill_color='red', fill_opacity=0.8).add_to(Bng_map) Bng_map ###Output _____no_output_____ ###Markdown Methodology To find the best biryani serving restaurant near the user's location, First I have to check those restaurants with highest rating so need to sort our data in descending order according to rating to get highest rating restaurants on top of the list then I will consider only those restaurants having high value rating then after I will sort restaurants list according to travel time in ascending order to get a restaurant where user can reach in short time and for result I will select the first restaurant in the list after doing all anaysis.To solve this problem I don't require any machine learning algorithm. ###Code biryani_points['zomato rating'] = biryani_points['zomato rating'].astype(float) # Sorting data Frame according to zomato ratings in descending order. biryani_points.sort_values(by='zomato rating',ascending=False,inplace=True) biryani_points.reset_index(drop=True,inplace=True) biryani_points.head() # Getting list of highest rating restaurants. top_points = biryani_points[biryani_points['zomato rating']==biryani_points['zomato rating'][0]] top_points ###Output _____no_output_____ ###Markdown Next step is for the situation if I get more than one restaurant with rating 4.7 so there is need to choose one and for this I am choosing that restaurant where user can reach in short time. ###Code # sorting the dataframe according to travel time in ascending order.. top_points.sort_values(by=['travel time minutes'],inplace=True) # sorting list according to time. top_points.reset_index(drop=True, inplace=True) top_points = top_points[top_points['travel distance km']<=5].reset_index(drop=True) # considering only restaurants those are in 5 km range. top_points ###Output _____no_output_____ ###Markdown Let's do some analysis now.. Analysis **Doing some additional analysis on fetched data..** **Let's check how many different catagories of restaurants are near by the user's location** ###Code len(nearby_restaurants['categories'].unique()) ###Output _____no_output_____ ###Markdown There are 47 different catagories of restaurants. **Let's check how many restaurants are there in each catagory..** ###Code category = nearby_restaurants['categories'].unique().tolist() category[0:10] import seaborn as sns import matplotlib.pyplot as plt plt.figure(figsize=(10,20)) ax = sns.countplot(y='categories', data=nearby_restaurants) y_count=0.1 for p in ax.patches: ax.annotate(str(p.get_width()), (p.get_width()+0.05,y_count),color='blue') y_count+=1 plt.title('No. of restaurants in each category',size=15) plt.show() ###Output _____no_output_____ ###Markdown Mostly there are one or two restaurant in each catagory except Indian Restaurants, South Indian, cafe and Bakery. **Let's check different catagories of restaurants those serve biryani** ###Code biryani_points.categories.unique() plt.figure(figsize=(10,10)) ax = sns.countplot(y='categories', data=biryani_points) y_count=0.1 for p in ax.patches: ax.annotate(str(p.get_width()), (p.get_width()+0.05,y_count),color='blue') y_count+=1 plt.title('No. of restaurants in each category those sereve biryani',size=15) plt.show() ###Output _____no_output_____ ###Markdown **Let's look out on ratings** ###Code nearby_restaurants['zomato rating'] = nearby_restaurants['zomato rating'].astype(float) plt.figure(figsize=(20,10)) ax = sns.countplot(x='zomato rating', data=nearby_restaurants) for p in ax.patches: ax.annotate(str(p.get_height()), (p.get_x()+0.3,p.get_height()+0.1),color='blue') plt.title('No. restaurants in each uniue rating value', size=15) plt.show() ###Output _____no_output_____ ###Markdown Mostly restaurants have ratings between 4 and 4.6. There is only one restaurant with rating of 4.8 **Let's checkout those restaurant's ratings who serve biryani** ###Code plt.figure(figsize=(15,10)) ax = sns.countplot(x='zomato rating', data=biryani_points) for p in ax.patches: ax.annotate(str(p.get_height()), (p.get_x()+0.3,p.get_height()+0.1),color='blue') plt.title('No. of restaurants in each unique rating value those serve biryani', size=15) plt.show() ###Output _____no_output_____ ###Markdown There is only one restaurant with rating of 4.6... Results and Discussion In methodology section I have already computed the list of highest rating restaurants those serves biryani so for the result it's better to select the restaurant having highest rating as well as less time is require to travel from user's location to restaurant. ###Code print('best biryani points with in 5 km is ',top_points.iloc[0]['name']) print('Distance =',top_points.iloc[0]['travel distance km'],'KM') print('Travel Time =',round(top_points.iloc[0]['travel time minutes']),'Minutes') # getting coordinate's location of best biryani point BP_lat = top_points.iloc[0]['lat'] BP_lng = top_points.iloc[0]['lng'] print('latitude =',BP_lat,' longitude =',BP_lng) # generating url to fectch path data from user's location to retaurant'S location bing_key = 'enter your key' url='http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0={},{}&wp.1={},{}&optmz=distance&routeAttributes=routePath&key={}'.format(H_lat, H_long, BP_lat, BP_lng, bing_key) print(url) # fetching data result = requests.get(url).json() result # getting coordinate points to draw path on map.. points = result['resourceSets'][0]['resources'][0]['routePath']['line']['coordinates'] points # drwaing path on map Bng_map = folium.Map(location=[(B_lat+BP_lat)/2,(B_long+BP_lng)/2],zoom_start=16) folium.Marker(location=[B_lat,B_long],icon=folium.Icon(color='green',icon='fas fa-h-square'),tooltip='The Park Bangalore').add_to(Bng_map) folium.Marker(location=[BP_lat,BP_lng],icon=folium.Icon(color='red',icon='fas fa-h-square'),tooltip=top_points.iloc[0]['name']).add_to(Bng_map) distance = top_points.iloc[0]['travel distance km'] time = round(top_points.iloc[0]['travel time minutes']) folium.PolyLine(points,tooltip='distance = '+str(distance)+' KM and time = '+str(time)+' Minutes').add_to(Bng_map) Bng_map ###Output _____no_output_____
notebooks/Telco-customer-churn-ICP4D.ipynb
###Markdown Predicting Telco Customer Churn using SparkML on IBM Cloud Pak for Data (ICP4D) We'll use this notebook to create a machine learning model to predict customer churn. In this notebook we will build the prediction model using the SparkML library.This notebook walks you through these steps:- Load and Visualize data set.- Build a predictive model with SparkML API- Save the model in the ML repository 1.0 Install required packagesThere are a couple of Python packages we will use in this notebook. First we make sure the Watson Machine Learning client v3 is removed (its not installed by default) and then install/upgrade the v4 version of the client (this package is installed by default on CP4D).WML Client: https://wml-api-pyclient-dev-v4.mybluemix.net/repository ###Code !pip uninstall watson-machine-learning-client -y !pip install --user watson-machine-learning-client-v4==1.0.103 --upgrade | tail -n 1 !pip install --user pyspark==2.3.3 --upgrade|tail -n 1 !pip install --user scikit-learn==0.20.3 --upgrade|tail -n 1 import pandas as pd import numpy as np import json import os # Import the Project Library to read/write project assets from project_lib import Project project = Project.access() import warnings warnings.filterwarnings("ignore") ###Output _____no_output_____ ###Markdown 2.0 Load and Clean dataWe'll load our data as a pandas data frame.**>*** Highlight the cell below by clicking it.* Click the `10/01` "Find data" icon in the upper right of the notebook.* If you are using Virtualized data, begin by choosing the `Files` tab. Then choose your virtualized data (i.e. MYSCHEMA.BILLINGPRODUCTCUSTOMERS), click `Insert to code` and choose `Insert Pandas DataFrame`.* If you are using this notebook without virtualized data, add the locally uploaded file `Telco-Customer-Churn.csv` by choosing the `Files` tab. Then choose the `Telco-Customer-Churn.csv`. Click `Insert to code` and choose `Insert Pandas DataFrame`.* The code to bring the data into the notebook environment and create a Pandas DataFrame will be added to the cell below.* Run the cell ###Code # Place cursor below and insert the Pandas DataFrame for the Telco churn data ###Output _____no_output_____ ###Markdown We'll use the Pandas naming convention df for our DataFrame. Make sure that the cell below uses the name for the dataframe used above. For the locally uploaded file it should look like df_data_1 or df_data_2 or df_data_x. For the virtualized data case it should look like data_df_1 or data_df_2 or data_df_x.**>** ###Code # for virtualized data # df = data_df_1 # for local upload df = df_data_1 ###Output _____no_output_____ ###Markdown 2.1 Drop CustomerID feature (column) ###Code df = df.drop('customerID', axis=1) df.head(5) ###Output _____no_output_____ ###Markdown 2.2 Examine the data types of the features ###Code df.info() # Statistics for the columns (features). Set it to all, since default is to describe just the numeric features. df.describe(include = 'all') ###Output _____no_output_____ ###Markdown We see that Tenure ranges from 0 (new customer) to 6 years, Monthly charges range from $18 to $118, etc 2.3 Check for need to Convert TotalCharges column to numeric if it is detected as objectIf the above `df.info` shows the "TotalCharges" columnn as an object, we'll need to convert it to numeric. If you have already done this during a previous exercise for "Data Visualization with Data Refinery", you can skip to step `2.4`. ###Code totalCharges = df.columns.get_loc("TotalCharges") new_col = pd.to_numeric(df.iloc[:, totalCharges], errors='coerce') df.iloc[:, totalCharges] = pd.Series(new_col) # Statistics for the columns (features). Set it to all, since default is to describe just the numeric features. df.describe(include = 'all') ###Output _____no_output_____ ###Markdown We now see statistics for the `TotalCharges` feature. 2.4 Any NaN values should be removed to create a more accurate model. ###Code # Check if we have any NaN values and see which features have missing values that should be addressed print(df.isnull().values.any()) df.isnull().sum() ###Output _____no_output_____ ###Markdown We should see that the `TotalCharges` column has missing values. There are various ways we can address this issue:- Drop records with missing values - Fill in the missing value with one of the following strategies: Zero, Mean of the values for the column, Random value, etc). ###Code # Handle missing values for nan_column (TotalCharges) from sklearn.impute import SimpleImputer # Find the column number for TotalCharges (starting at 0). total_charges_idx = df.columns.get_loc("TotalCharges") imputer = SimpleImputer(missing_values=np.nan, strategy='mean') df.iloc[:, total_charges_idx] = imputer.fit_transform(df.iloc[:, total_charges_idx].values.reshape(-1, 1)) df.iloc[:, total_charges_idx] = pd.Series(df.iloc[:, total_charges_idx]) # Validate that we have addressed any NaN values print(df.isnull().values.any()) df.isnull().sum() ###Output _____no_output_____ ###Markdown 2.5 Categorize FeaturesWe will categorize some of the columns / features based on wether they are categorical values or continuous (i.e numerical) values. We will use this in later sections to build visualizations. ###Code columns_idx = np.s_[0:] # Slice of first row(header) with all columns. first_record_idx = np.s_[0] # Index of first record string_fields = [type(fld) is str for fld in df.iloc[first_record_idx, columns_idx]] # All string fields all_features = [x for x in df.columns if x != 'Churn'] categorical_columns = list(np.array(df.columns)[columns_idx][string_fields]) categorical_features = [x for x in categorical_columns if x != 'Churn'] continuous_features = [x for x in all_features if x not in categorical_features] #print('All Features: ', all_features) #print('\nCategorical Features: ', categorical_features) #print('\nContinuous Features: ', continuous_features) #print('\nAll Categorical Columns: ', categorical_columns) ###Output _____no_output_____ ###Markdown 2.6 Visualize dataData visualization can be used to find patterns, detect outliers, understand distribution and more. We can use graphs such as:- Histograms, boxplots, etc: To find distribution / spread of our continuous variables.- Bar charts: To show frequency in categorical values. ###Code import seaborn as sns import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder %matplotlib inline sns.set(style="darkgrid") sns.set_palette("hls", 3) ###Output _____no_output_____ ###Markdown First, we get a high level view of the distribution of `Churn`. What percentage of customer in our dataset are churning vs not churning. ###Code print(df.groupby(['Churn']).size()) churn_plot = sns.countplot(data=df, x='Churn', order=df.Churn.value_counts().index) plt.ylabel('Count') for p in churn_plot.patches: height = p.get_height() churn_plot.text(p.get_x()+p.get_width()/2., height + 1,'{0:.0%}'.format(height/float(len(df))),ha="center") plt.show() ###Output _____no_output_____ ###Markdown We can get use frequency counts charts to get an understanding of the categorical features relative to `Churn` - We can see that for the `gender` feature. We have relatively equal rates of churn by `gender`- We can see that for the `InternetService` feature. We have higher churn for those that have "Fiber optic" service versus those with "DSL" ###Code # Categorical feature count plots f, ((ax1, ax2, ax3), (ax4, ax5, ax6), (ax7, ax8, ax9), (ax10, ax11, ax12), (ax13, ax14, ax15)) = plt.subplots(5, 3, figsize=(20, 20)) ax = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10, ax11, ax12, ax13, ax14, ax15 ] for i in range(len(categorical_features)): sns.countplot(x = categorical_features[i], hue="Churn", data=df, ax=ax[i]) ###Output _____no_output_____ ###Markdown We can get use histrogram charts to get an understanding of the distribution of our continuous / numerical features relative to Churn.- We can see that for the `MonthlyCharges` feature, customers that churn tend to pay higher monthly fees than those that stay.- We can see that for the `tenure` feature, customers that churn tend to be relatively new customers. ###Code # Continuous feature histograms. fig, ax = plt.subplots(2, 2, figsize=(28, 8)) df[df.Churn == 'No'][continuous_features].hist(bins=20, color="blue", alpha=0.5, ax=ax) df[df.Churn == 'Yes'][continuous_features].hist(bins=20, color="orange", alpha=0.5, ax=ax) # Or use displots #sns.set_palette("hls", 3) #f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(25, 25)) #ax = [ax1, ax2, ax3, ax4] #for i in range(len(continuous_features)): # sns.distplot(df[continuous_features[i]], bins=20, hist=True, ax=ax[i]) # Create Grid for pairwise relationships gr = sns.PairGrid(df, height=5, hue="Churn") gr = gr.map_diag(plt.hist) gr = gr.map_offdiag(plt.scatter) gr = gr.add_legend() # Plot boxplots of numerical columns. More variation in the boxplot implies higher significance. f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(25, 25)) ax = [ax1, ax2, ax3, ax4] for i in range(len(continuous_features)): sns.boxplot(x = 'Churn', y = continuous_features[i], data=df, ax=ax[i]) ###Output _____no_output_____ ###Markdown 3.0 Create a modelNow we can create our machine learning model. You could use the insights / intuition gained from the data visualization steps above to what kind of model to create or which features to use. We will create a simple classification model. ###Code from pyspark.sql import SparkSession import pandas as pd import json spark = SparkSession.builder.getOrCreate() df_data = spark.createDataFrame(df) df_data.head() ###Output _____no_output_____ ###Markdown 3.1 Split the data into training and test sets ###Code spark_df = df_data (train_data, test_data) = spark_df.randomSplit([0.8, 0.2], 24) print("Number of records for training: " + str(train_data.count())) print("Number of records for evaluation: " + str(test_data.count())) ###Output _____no_output_____ ###Markdown 3.2 Examine the Spark DataFrame SchemaLook at the data types to determine requirements for feature engineering ###Code spark_df.printSchema() ###Output _____no_output_____ ###Markdown 3.3 Use StringIndexer to encode a string column of labels to a column of label indicesWe are using the Pipeline package to build the development steps as pipeline. We are using StringIndexer to handle categorical / string features from the dataset. StringIndexer encodes a string column of labels to a column of label indicesWe then use VectorAssembler to asemble these features into a vector. Pipelines API requires that input variables are passed in a vector ###Code from pyspark.ml.classification import RandomForestClassifier from pyspark.ml.feature import StringIndexer, IndexToString, VectorAssembler from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml import Pipeline, Model si_gender = StringIndexer(inputCol = 'gender', outputCol = 'gender_IX') si_Partner = StringIndexer(inputCol = 'Partner', outputCol = 'Partner_IX') si_Dependents = StringIndexer(inputCol = 'Dependents', outputCol = 'Dependents_IX') si_PhoneService = StringIndexer(inputCol = 'PhoneService', outputCol = 'PhoneService_IX') si_MultipleLines = StringIndexer(inputCol = 'MultipleLines', outputCol = 'MultipleLines_IX') si_InternetService = StringIndexer(inputCol = 'InternetService', outputCol = 'InternetService_IX') si_OnlineSecurity = StringIndexer(inputCol = 'OnlineSecurity', outputCol = 'OnlineSecurity_IX') si_OnlineBackup = StringIndexer(inputCol = 'OnlineBackup', outputCol = 'OnlineBackup_IX') si_DeviceProtection = StringIndexer(inputCol = 'DeviceProtection', outputCol = 'DeviceProtection_IX') si_TechSupport = StringIndexer(inputCol = 'TechSupport', outputCol = 'TechSupport_IX') si_StreamingTV = StringIndexer(inputCol = 'StreamingTV', outputCol = 'StreamingTV_IX') si_StreamingMovies = StringIndexer(inputCol = 'StreamingMovies', outputCol = 'StreamingMovies_IX') si_Contract = StringIndexer(inputCol = 'Contract', outputCol = 'Contract_IX') si_PaperlessBilling = StringIndexer(inputCol = 'PaperlessBilling', outputCol = 'PaperlessBilling_IX') si_PaymentMethod = StringIndexer(inputCol = 'PaymentMethod', outputCol = 'PaymentMethod_IX') si_Label = StringIndexer(inputCol="Churn", outputCol="label").fit(spark_df) label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=si_Label.labels) ###Output _____no_output_____ ###Markdown 3.4 Create a single vector ###Code va_features = VectorAssembler(inputCols=['gender_IX', 'SeniorCitizen', 'Partner_IX', 'Dependents_IX', 'PhoneService_IX', 'MultipleLines_IX', 'InternetService_IX', \ 'OnlineSecurity_IX', 'OnlineBackup_IX', 'DeviceProtection_IX', 'TechSupport_IX', 'StreamingTV_IX', 'StreamingMovies_IX', \ 'Contract_IX', 'PaperlessBilling_IX', 'PaymentMethod_IX', 'TotalCharges', 'MonthlyCharges'], outputCol="features") ###Output _____no_output_____ ###Markdown 3.5 Create a pipeline, and fit a model using RandomForestClassifier Assemble all the stages into a pipeline. We don't expect a clean linear regression, so we'll use RandomForestClassifier to find the best decision tree for the data. ###Code classifier = RandomForestClassifier(featuresCol="features") pipeline = Pipeline(stages=[si_gender, si_Partner, si_Dependents, si_PhoneService, si_MultipleLines, si_InternetService, si_OnlineSecurity, si_OnlineBackup, si_DeviceProtection, \ si_TechSupport, si_StreamingTV, si_StreamingMovies, si_Contract, si_PaperlessBilling, si_PaymentMethod, si_Label, va_features, \ classifier, label_converter]) model = pipeline.fit(train_data) predictions = model.transform(test_data) evaluatorDT = BinaryClassificationEvaluator(rawPredictionCol="prediction") area_under_curve = evaluatorDT.evaluate(predictions) evaluatorDT = BinaryClassificationEvaluator(rawPredictionCol="prediction", metricName='areaUnderROC') area_under_curve = evaluatorDT.evaluate(predictions) evaluatorDT = BinaryClassificationEvaluator(rawPredictionCol="prediction", metricName='areaUnderPR') area_under_PR = evaluatorDT.evaluate(predictions) print("areaUnderROC = %g" % area_under_curve) ###Output _____no_output_____ ###Markdown 4.0 Save the model and test dataNow the model can be saved for future deployment. The model will be saved using the Watson Machine Learning client, to a deployment space.**>****>** ###Code MODEL_NAME = "INSERT-YOUR-MODEL-NAME-HERE" DEPLOYMENT_SPACE_NAME = 'INSERT-YOUR-DEPLOYMENT-SPACE-NAME-HERE' ###Output _____no_output_____ ###Markdown 4.1 Save the model to ICP4D local Watson Machine LearningReplace the `username` and `password` values of `*****` with your Cloud Pak for Data `username` and `password`. The value for `url` should match the `url` for your Cloud Pak for Data cluster. ###Code from watson_machine_learning_client import WatsonMachineLearningAPIClient wml_credentials = { "url": "******", "username": "*****", "password" : "*****", "instance_id": "wml_local", "version" : "2.5.0" } client = WatsonMachineLearningAPIClient(wml_credentials) client.spaces.list() ###Output _____no_output_____ ###Markdown Use the desired space as the `default_space`The deployment space ID will be looked up based on the name specified above. If you do not receive a space GUID as an output to the next cell, do not proceed until you have created a deployment space. ###Code # Be sure to update the name of the space with the one you want to use. client.spaces.list() all_spaces = client.spaces.get_details()['resources'] space_id = None for space in all_spaces: if space['entity']['name'] == DEPLOYMENT_SPACE_NAME: space_id = space["metadata"]["guid"] print("\nDeployment Space GUID: ", space_id) if space_id is None: print("WARNING: Your space does not exist. Create a deployment space before proceeding to the next cell.") #space_id = client.spaces.store(meta_props={client.spaces.ConfigurationMetaNames.NAME: space_name})["metadata"]["guid"] ###Output _____no_output_____ ###Markdown **client.set.default_space("6b39c537-f707-4078-9dc7-ce70b70ab22f") >>** ###Code # Now set the default space to the GUID for your deployment space. If this is successful, you will see a 'SUCCESS' message. client.set.default_space(space_id) ###Output _____no_output_____ ###Markdown Save the Model ###Code # Store our model model_props = {client.repository.ModelMetaNames.NAME: MODEL_NAME, client.repository.ModelMetaNames.RUNTIME_UID : "spark-mllib_2.3", client.repository.ModelMetaNames.TYPE : "mllib_2.3"} published_model = client.repository.store_model(model=model, pipeline=pipeline, meta_props=model_props, training_data=train_data) print(json.dumps(published_model, indent=3)) # Use this cell to do any cleanup of previously created models and deployments client.repository.list_models() client.deployments.list() # client.repository.delete('GUID of stored model') # client.deployments.delete('GUID of deployed model') ###Output _____no_output_____ ###Markdown 5.0 Save Test DataWe will save the test data we used to evaluate the model to our project. ###Code write_score_CSV=test_data.toPandas().drop(['Churn'], axis=1) write_score_CSV.to_csv('/project_data/data_asset/TelcoCustomerSparkMLBatchScore.csv', sep=',', index=False) #project.save_data('TelcoCustomerSparkMLBatchScore.csv', write_score_CSV.to_csv()) write_eval_CSV=test_data.toPandas() write_eval_CSV.to_csv('/project_data/data_asset/TelcoCustomerSparkMLEval.csv', sep=',', index=False) #project.save_data('TelcoCustomerSparkMLEval.csv', write_eval_CSV.to_csv()) ###Output _____no_output_____ ###Markdown Telco Customer Churn for ICP4D We'll use this notebook to create a machine learning model to predict customer churn. 1.0 Install required packages ###Code !pip install --user watson-machine-learning-client --upgrade | tail -n 1 ###Output _____no_output_____ ###Markdown 2.0 Load and Clean dataWe'll load our data as a pandas data frame.* Highlight the cell below by clicking it.* Click the `10/01` "Find data" icon in the upper right of the notebook.* If you are using the [ICP4D Learning Path] and have the [Virtualized data], begin by choosing the `Remote` tab. Then choose your virtualized data (i.e. User.billingProductCustomers), click `Insert to code` and choose `Insert Pandas DataFrame`.* If you are using this code pattern outside of the [ICP4D Learning Path], add the locally uploaded file `Telco-Customer-Churn.csv` by choosing the 'Local` tab. Then choose the `Telco-Customer-Churn.csv`, click `Insert to code` and choose `Insert Pandas DataFrame`.* The code to bring the data into the notebook environment and create a Pandas DataFrame will be added to the cell below.* Run the cell ###Code # Place cursor below and insert the Pandas DataFrame for the Telco churn data ###Output _____no_output_____ ###Markdown We'll use the Pandas naming convention `df` for our DataFrame. Make sure that the cell below uses the name for the dataframe used above, i.e df1, df2,... dfX for the remote data using Data Virtualization, or df_data1, df_data2, ... if using local data. ###Code # df = df1 df = df_data_1 ###Output _____no_output_____ ###Markdown 2.1 Drop CustomerID feature (column) ###Code df = df.drop('customerID', axis=1) df.head(5) ###Output _____no_output_____ ###Markdown 2.2 Examine the data types of the features ###Code df.info() ###Output _____no_output_____ ###Markdown 2.3 Convert TotalCharges column to numeric as it is detected as object ###Code new_col = pd.to_numeric(df.iloc[:, 18], errors='coerce') new_col ###Output _____no_output_____ ###Markdown 2.4 Modify our dataframe to reflect the new datatype ###Code df.iloc[:, 18] = pd.Series(new_col) df ###Output _____no_output_____ ###Markdown 2.5 Any NaN values should be removed to create a more accurate model. Prior examination shows NaN values for `TotalCharges` ###Code # Check if we have any NaN values df.isnull().values.any() ###Output _____no_output_____ ###Markdown Set `nan_column` to the column number for TotalCharges (starting at 0). ###Code nan_column = df.columns.get_loc("TotalCharges") print(nan_column) # Handle missing values for nan_column (TotalCharges) from sklearn.preprocessing import Imputer imp = Imputer(missing_values="NaN", strategy="mean") df.iloc[:, nan_column] = imp.fit_transform(df.iloc[:, nan_column].values.reshape(-1, 1)) df.iloc[:, nan_column] = pd.Series(df.iloc[:, nan_column]) # Check if we have any NaN values df.isnull().values.any() ###Output _____no_output_____ ###Markdown 2.6 Visualize data ###Code import json import os import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn import preprocessing, svm from itertools import combinations from sklearn.preprocessing import PolynomialFeatures, LabelEncoder, StandardScaler import sklearn.feature_selection from sklearn.model_selection import train_test_split from collections import defaultdict from sklearn import metrics # Plot Tenure Frequency count sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="tenure", hue="Churn", data=df) # Plot Tenure Frequency count sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="Contract", hue="Churn", data=df) # Plot Tenure Frequency count sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="TechSupport", hue="Churn", data=df) # Create Grid for pairwise relationships gr = sns.PairGrid(df, size=5, hue="Churn") gr = gr.map_diag(plt.hist) gr = gr.map_offdiag(plt.scatter) gr = gr.add_legend() totalCharge = df.columns.get_loc("TotalCharges") print(nan_column) # Set up plot size fig, ax = plt.subplots(figsize=(6,6)) # Attributes destribution a = sns.boxplot(orient="v", palette="hls", data=df.iloc[:, totalCharge], fliersize=14) # Total Charges data distribution histogram = sns.distplot(df.iloc[:, totalCharge], hist=True) plt.show() tenure = df.columns.get_loc("tenure") print(tenure) # Tenure data distribution histogram = sns.distplot(df.iloc[:, tenure], hist=True) plt.show() monthly = df.columns.get_loc("MonthlyCharges") print(monthly) # Monthly Charges data distribution histogram = sns.distplot(df.iloc[:, monthly], hist=True) plt.show() ###Output _____no_output_____ ###Markdown Understand Data Distribution¶ 3.0 Create a model ###Code from pyspark.sql import SparkSession import pandas as pd import json spark = SparkSession.builder.getOrCreate() df_data = spark.createDataFrame(df) df_data.head() ###Output _____no_output_____ ###Markdown 3.1 Split the data into training and test sets ###Code spark_df = df_data (train_data, test_data) = spark_df.randomSplit([0.8, 0.2], 24) print("Number of records for training: " + str(train_data.count())) print("Number of records for evaluation: " + str(test_data.count())) ###Output _____no_output_____ ###Markdown 3.2 Examine the Spark DataFrame SchemaLook at the data types to determine requirements for feature engineering ###Code spark_df.printSchema() ###Output _____no_output_____ ###Markdown 3.3 Use StringIndexer to encode a string column of labels to a column of label indices ###Code from pyspark.ml.classification import RandomForestClassifier from pyspark.ml.feature import StringIndexer, IndexToString, VectorAssembler from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml import Pipeline, Model si_gender = StringIndexer(inputCol = 'gender', outputCol = 'gender_IX') si_Partner = StringIndexer(inputCol = 'Partner', outputCol = 'Partner_IX') si_Dependents = StringIndexer(inputCol = 'Dependents', outputCol = 'Dependents_IX') si_PhoneService = StringIndexer(inputCol = 'PhoneService', outputCol = 'PhoneService_IX') si_MultipleLines = StringIndexer(inputCol = 'MultipleLines', outputCol = 'MultipleLines_IX') si_InternetService = StringIndexer(inputCol = 'InternetService', outputCol = 'InternetService_IX') si_OnlineSecurity = StringIndexer(inputCol = 'OnlineSecurity', outputCol = 'OnlineSecurity_IX') si_OnlineBackup = StringIndexer(inputCol = 'OnlineBackup', outputCol = 'OnlineBackup_IX') si_DeviceProtection = StringIndexer(inputCol = 'DeviceProtection', outputCol = 'DeviceProtection_IX') si_TechSupport = StringIndexer(inputCol = 'TechSupport', outputCol = 'TechSupport_IX') si_StreamingTV = StringIndexer(inputCol = 'StreamingTV', outputCol = 'StreamingTV_IX') si_StreamingMovies = StringIndexer(inputCol = 'StreamingMovies', outputCol = 'StreamingMovies_IX') si_Contract = StringIndexer(inputCol = 'Contract', outputCol = 'Contract_IX') si_PaperlessBilling = StringIndexer(inputCol = 'PaperlessBilling', outputCol = 'PaperlessBilling_IX') si_PaymentMethod = StringIndexer(inputCol = 'PaymentMethod', outputCol = 'PaymentMethod_IX') si_Label = StringIndexer(inputCol="Churn", outputCol="label").fit(spark_df) label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=si_Label.labels) ###Output _____no_output_____ ###Markdown 3.4 Create a single vector ###Code va_features = VectorAssembler(inputCols=['gender_IX', 'SeniorCitizen', 'Partner_IX', 'Dependents_IX', 'PhoneService_IX', 'MultipleLines_IX', 'InternetService_IX', \ 'OnlineSecurity_IX', 'OnlineBackup_IX', 'DeviceProtection_IX', 'TechSupport_IX', 'StreamingTV_IX', 'StreamingMovies_IX', \ 'Contract_IX', 'PaperlessBilling_IX', 'PaymentMethod_IX', 'TotalCharges', 'MonthlyCharges'], outputCol="features") ###Output _____no_output_____ ###Markdown 3.5 Create a pipeline, and fit a model using RandomForestClassifier Assemble all the stages into a pipeline. We don't expect a clean linear regression, so we'll use RandomForestClassifier to find the best decision tree for the data. ###Code classifier = RandomForestClassifier(featuresCol="features") pipeline = Pipeline(stages=[si_gender, si_Partner, si_Dependents, si_PhoneService, si_MultipleLines, si_InternetService, si_OnlineSecurity, si_OnlineBackup, si_DeviceProtection, \ si_TechSupport, si_StreamingTV, si_StreamingMovies, si_Contract, si_PaperlessBilling, si_PaymentMethod, si_Label, va_features, \ classifier, label_converter]) model = pipeline.fit(train_data) predictions = model.transform(test_data) evaluatorDT = BinaryClassificationEvaluator(rawPredictionCol="prediction") area_under_curve = evaluatorDT.evaluate(predictions) #default evaluation is areaUnderROC print("areaUnderROC = %g" % area_under_curve) ###Output _____no_output_____ ###Markdown 4.0 Save the model and test data Add a unique name for MODEL_NAME. ###Code MODEL_NAME = "myname model" ###Output _____no_output_____ ###Markdown 4.1 Save the model to ICP4D local Watson Machine Learning ###Code from dsx_ml.ml import save save(name=MODEL_NAME, model=model, test_data=test_data, algorithm_type='Classification', description='This is a SparkML Model to Classify Telco Customer Churn Risk') ###Output _____no_output_____ ###Markdown 4.2 Write the test data without label to a .csv so that we can later use it for batch scoring ###Code write_score_CSV=test_data.toPandas().drop(['Churn'], axis=1) write_score_CSV.to_csv('../datasets/TelcoCustomerSparkMLBatchScore.csv', sep=',', index=False) ###Output _____no_output_____ ###Markdown 4.3 Write the test data to a .csv so that we can later use it for evaluation ###Code write_eval_CSV=test_data.toPandas() write_eval_CSV.to_csv('../datasets/TelcoCustomerSparkMLEval.csv', sep=',', index=False) ###Output _____no_output_____ ###Markdown Telco Customer Churn para ICP4D Usaremos este 'notebook' para crear un modelo de 'machine learning' para predecir el 'CHURN' en los clientes. 1.0 Instalar las paqueterías requeridas ###Code !pip install --user watson-machine-learning-client --upgrade | tail -n 1 !pip install --user pyspark==2.3.3 --upgrade|tail -n 1 ###Output _____no_output_____ ###Markdown 2.0 Cargar y limpiar los datos.Cargamos nuestros datos como un marco de datos (Data Frame) de pandas.* Resalta la celda inferior dándole clic.* Da clic en el ícono `01/00` "Find and add data" en la parte superior derecha de la 'Notebook'.* Si estás usando 'Virtualized data', comienza seleccionando la pestaña 'Files'. Ahora, selecciona tus datos virtualizados (ej. MYSCHEMA.BILLINGPRODUCTCUSTOMERS), da clic en 'Insert to code' y selecciona 'Insert Pandas DataFrame'.* Si estás usando esta 'Notebook' sin datos virtualizados, agrega localmente el archivo: `Telco-Customer-Churn.csv` Seleccionando la pestaña 'Files'. Después, selecciona el archivo: 'Telco-Customer-Churn.csv'. Da clic en 'Insert to code' y selecciona 'Insert Pandas DataFrame'.* El códico para traer los datos a este ambiente de 'Notebook' y crear el marco de datos de Pandas (Pandas DataFrame) será agregado el la celda inferior.* Correr la celda. ###Code # Coloca el cursor debajo e inserta el marco de datos de pandas(Pandas DataFrame) para los datos de la Telco. import pandas as pd ###Output _____no_output_____ ###Markdown Usaremos la convención de nombramiento de Pandas 'df' para nuestro marco de datos (DataFrame). Asegúrate de que la celda inferior use el mismo nombre para el marco de datos(DataFrame) usado en la celda superior. Para el archivo cargado de forma local, debe verse como: 'df_data_1' o 'df_data_2' o 'df_data_x'. Para el caso de los datos virtualizados, debe verse como: data_df_1 o data_df_2 o data_df_x. ###Code # Para datos virtualizados: # df = data_df_1 # Para carga local: df = df_data_1 ###Output _____no_output_____ ###Markdown 2.1 Desplegar la característica 'CustomerID' (columna) ###Code df = df.drop('customerID', axis=1) df.head(5) ###Output _____no_output_____ ###Markdown 2.2 Examinar los tipos de datos de las características (columnas). ###Code df.info() ###Output _____no_output_____ ###Markdown 2.3 Verificar la necesidad de convertir la columna 'TotalCharges' a numérico si es detectado como objetoSi el 'df.info' superior, muestra la columnda "TotalCharges" c omo un objeto, necesitamos convertirlo a numérico. Si ya lo has hecho durante el ejericio previo para "Visualización de datos con refinería de datos", puedes saltar este paso `2.5`. ###Code totalCharges = df.columns.get_loc("TotalCharges") print(totalCharges) new_col = pd.to_numeric(df.iloc[:, totalCharges], errors='coerce') new_col ###Output _____no_output_____ ###Markdown 2.4 Modificamos nuestro marco de datos 'Data Frame' para reflejar el nuevo tipo de dato ###Code df.iloc[:, totalCharges] = pd.Series(new_col) df ###Output _____no_output_____ ###Markdown 2.5 Los valores NaN deben ser removidos para crear un modelo más certero. ###Code # Revisar si tenemos valores 'NaN' ('Not a Number'). df.isnull().values.any() ###Output _____no_output_____ ###Markdown Configura la columna 'nan_column' al numero de columna de 'TotalCharges' (comenzando en 0). ###Code nan_column = df.columns.get_loc("TotalCharges") print(nan_column) # Maneja los valores faltantes para la columna 'nan_column' de 'TotalCharges' from sklearn.preprocessing import Imputer imp = Imputer(missing_values="NaN", strategy="mean") df.iloc[:, nan_column] = imp.fit_transform(df.iloc[:, nan_column].values.reshape(-1, 1)) df.iloc[:, nan_column] = pd.Series(df.iloc[:, nan_column]) # Verificar si tenemos valores 'NaN'. df.isnull().values.any() ###Output _____no_output_____ ###Markdown 2.6 Visualizar lod datos ###Code import json import os import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn import preprocessing, svm from itertools import combinations from sklearn.preprocessing import PolynomialFeatures, LabelEncoder, StandardScaler import sklearn.feature_selection from sklearn.model_selection import train_test_split from collections import defaultdict from sklearn import metrics # Conteo de frecuencia en la permanencia de la trama (plot tenure). sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="tenure", hue="Churn", data=df) # Conteo de frecuencia en la permanencia de la trama (plot tenure). sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="Contract", hue="Churn", data=df) # Conteo de frecuencia en la permanencia de la trama (plot tenure). sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="TechSupport", hue="Churn", data=df) # Crear la cuadrícula para relaciones en pares. gr = sns.PairGrid(df, size=5, hue="Churn") gr = gr.map_diag(plt.hist) gr = gr.map_offdiag(plt.scatter) gr = gr.add_legend() # Configurar el tamaño de la trama. fig, ax = plt.subplots(figsize=(6,6)) # Distribución de atributos a = sns.boxplot(orient="v", palette="hls", data=df.iloc[:, totalCharges], fliersize=14) # Distribución de datos de cargas totales. histogram = sns.distplot(df.iloc[:, totalCharges], hist=True) plt.show() tenure = df.columns.get_loc("tenure") print(tenure) # Distribución de permanencia de datos (Tenure). histogram = sns.distplot(df.iloc[:, tenure], hist=True) plt.show() monthly = df.columns.get_loc("MonthlyCharges") print(monthly) # Distribución de datos de cargos mensuales. histogram = sns.distplot(df.iloc[:, monthly], hist=True) plt.show() ###Output _____no_output_____ ###Markdown Entender la distribución de datos 3.0 Crear un modelo ###Code from pyspark.sql import SparkSession import pandas as pd import json spark = SparkSession.builder.getOrCreate() df_data = spark.createDataFrame(df) df_data.head() ###Output _____no_output_____ ###Markdown 3.1 Dividir los datos en conjuntos de entrenamiento y de prueba. ###Code spark_df = df_data (train_data, test_data) = spark_df.randomSplit([0.8, 0.2], 24) print("Número de registros para entrenamiento: " + str(train_data.count())) print("Número de registros para evaluación: " + str(test_data.count())) ###Output _____no_output_____ ###Markdown 3.2 Examinar el esquema de marco de datos (DataFrame Schema) de 'Spark'.Observa los tipos de datos para determinar los requerimientos para la ingeniería de características. ###Code spark_df.printSchema() ###Output _____no_output_____ ###Markdown 3.3 Usar 'StringIndexer' para codificar una columna de etiquetas 'string' a una columna de etiquetas índice. ###Code from pyspark.ml.classification import RandomForestClassifier from pyspark.ml.feature import StringIndexer, IndexToString, VectorAssembler from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml import Pipeline, Model si_gender = StringIndexer(inputCol = 'gender', outputCol = 'gender_IX') si_Partner = StringIndexer(inputCol = 'Partner', outputCol = 'Partner_IX') si_Dependents = StringIndexer(inputCol = 'Dependents', outputCol = 'Dependents_IX') si_PhoneService = StringIndexer(inputCol = 'PhoneService', outputCol = 'PhoneService_IX') si_MultipleLines = StringIndexer(inputCol = 'MultipleLines', outputCol = 'MultipleLines_IX') si_InternetService = StringIndexer(inputCol = 'InternetService', outputCol = 'InternetService_IX') si_OnlineSecurity = StringIndexer(inputCol = 'OnlineSecurity', outputCol = 'OnlineSecurity_IX') si_OnlineBackup = StringIndexer(inputCol = 'OnlineBackup', outputCol = 'OnlineBackup_IX') si_DeviceProtection = StringIndexer(inputCol = 'DeviceProtection', outputCol = 'DeviceProtection_IX') si_TechSupport = StringIndexer(inputCol = 'TechSupport', outputCol = 'TechSupport_IX') si_StreamingTV = StringIndexer(inputCol = 'StreamingTV', outputCol = 'StreamingTV_IX') si_StreamingMovies = StringIndexer(inputCol = 'StreamingMovies', outputCol = 'StreamingMovies_IX') si_Contract = StringIndexer(inputCol = 'Contract', outputCol = 'Contract_IX') si_PaperlessBilling = StringIndexer(inputCol = 'PaperlessBilling', outputCol = 'PaperlessBilling_IX') si_PaymentMethod = StringIndexer(inputCol = 'PaymentMethod', outputCol = 'PaymentMethod_IX') si_Label = StringIndexer(inputCol="Churn", outputCol="label").fit(spark_df) label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=si_Label.labels) ###Output _____no_output_____ ###Markdown 3.4 Crear un vector. ###Code va_features = VectorAssembler(inputCols=['gender_IX', 'SeniorCitizen', 'Partner_IX', 'Dependents_IX', 'PhoneService_IX', 'MultipleLines_IX', 'InternetService_IX', \ 'OnlineSecurity_IX', 'OnlineBackup_IX', 'DeviceProtection_IX', 'TechSupport_IX', 'StreamingTV_IX', 'StreamingMovies_IX', \ 'Contract_IX', 'PaperlessBilling_IX', 'PaymentMethod_IX', 'TotalCharges', 'MonthlyCharges'], outputCol="features") ###Output _____no_output_____ ###Markdown 3.5 Crear una 'pipeline', y ajustar un modelo usando 'RandomForestClassifier'. Montar todas las etapas a una 'pipeline'. No esperamos una regresión lineal limpia, así que usaremos 'RandomForestClassifier' para encontrar el mejor árbol de decisión para nuestros datos. ###Code classifier = RandomForestClassifier(featuresCol="features") pipeline = Pipeline(stages=[si_gender, si_Partner, si_Dependents, si_PhoneService, si_MultipleLines, si_InternetService, si_OnlineSecurity, si_OnlineBackup, si_DeviceProtection, \ si_TechSupport, si_StreamingTV, si_StreamingMovies, si_Contract, si_PaperlessBilling, si_PaymentMethod, si_Label, va_features, \ classifier, label_converter]) model = pipeline.fit(train_data) predictions = model.transform(test_data) evaluatorDT = BinaryClassificationEvaluator(rawPredictionCol="prediction") area_under_curve = evaluatorDT.evaluate(predictions) #La evauación predeterminada es 'areaUnderROC' print("areaUnderROC = %g" % area_under_curve) ###Output _____no_output_____ ###Markdown 4.0 Guardar el modelo y probar los datos. Agrega un nombre único para el NOMBRE_DEL_MODELO. ###Code NOMBRE_DEL_MODELO = "mi-modelo mi-fecha" ###Output _____no_output_____ ###Markdown 4.1 Guardar el modelo en 'ICP4D local Watson Machine Learning'.Reemplaza el nombre de usuario ('username') y contraseña ('password') Con tus credenciales de 'Watson Machine Learning'.El URL debe ser el mismo de tu 'Data Cluster'. ###Code from watson_machine_learning_client import WatsonMachineLearningAPIClient wml_credentials = { "url": "https://zen-cpd-zen.apps.os-workshop-nov22.vz-cpd-nov22.com", "username": "*****", "password" : "*****", "instance_id": "wml_local", "version" : "2.5.0" } client = WatsonMachineLearningAPIClient(wml_credentials) client.spaces.list() ###Output _____no_output_____ ###Markdown Usar el espacio deseado como 'default_space'Poner el 'GUID' del espacio deseado como un parámetro debajo. ###Code client.set.default_space('<GUID>') # Guardar el modelo model_props = {client.repository.ModelMetaNames.NAME: MODEL_NAME, client.repository.ModelMetaNames.RUNTIME_UID : "spark-mllib_2.3", client.repository.ModelMetaNames.TYPE : "mllib_2.3"} published_model = client.repository.store_model(model=model, pipeline=pipeline, meta_props=model_props, training_data=train_data) # Usar esta celda para cualquier limpieza de modelos y despliegues previos. client.repository.list_models() client.deployments.list() # client.repository.delete('GUID del modelo guardado') # client.deployments.delete('GUID del modelo desplegado') ###Output _____no_output_____ ###Markdown 4.2 Escribe los datos de prueba sin ninguna etiqueta a un .csv, para usarlo después como puntuación por lotes. ###Code write_score_CSV=test_data.toPandas().drop(['Churn'], axis=1) write_score_CSV.to_csv('/project_data/data_asset/TelcoCustomerSparkMLBatchScore.csv', sep=',', index=False) ###Output _____no_output_____ ###Markdown 4.3 Escribe los datos de prueba a un .csv para usarlos posteriormente para la evaluación. ###Code write_eval_CSV=test_data.toPandas() write_eval_CSV.to_csv('/project_data/data_asset/TelcoCustomerSparkMLEval.csv', sep=',', index=False) ###Output _____no_output_____ ###Markdown Telco Customer Churn for ICP4D We'll use this notebook to create a machine learning model to predict customer churn. 1.0 Install required packages ###Code !pip install --user watson-machine-learning-client --upgrade | tail -n 1 !pip install --user pyspark==2.3.3 --upgrade|tail -n 1 ###Output _____no_output_____ ###Markdown 2.0 Load and Clean dataWe'll load our data as a pandas data frame.* Highlight the cell below by clicking it.* Click the `10/01` "Find data" icon in the upper right of the notebook.* If you are using Virtualized data, begin by choosing the `Files` tab. Then choose your virtualized data (i.e. MYSCHEMA.BILLINGPRODUCTCUSTOMERS), click `Insert to code` and choose `Insert Pandas DataFrame`.* If you are using this notebook without virtualized data, add the locally uploaded file `Telco-Customer-Churn.csv` by choosing the `Files` tab. Then choose the `Telco-Customer-Churn.csv`. Click `Insert to code` and choose `Insert Pandas DataFrame`.* The code to bring the data into the notebook environment and create a Pandas DataFrame will be added to the cell below.* Run the cell ###Code # Place cursor below and insert the Pandas DataFrame for the Telco churn data import pandas as pd ###Output _____no_output_____ ###Markdown We'll use the Pandas naming convention df for our DataFrame. Make sure that the cell below uses the name for the dataframe used above. For the locally uploaded file it should look like df_data_1 or df_data_2 or df_data_x. For the virtualized data case it should look like data_df_1 or data_df_2 or data_df_x. ###Code # for virtualized data # df = data_df_1 # for local upload df = df_data_1 ###Output _____no_output_____ ###Markdown 2.1 Drop CustomerID feature (column) ###Code df = df.drop('customerID', axis=1) df.head(5) ###Output _____no_output_____ ###Markdown 2.2 Examine the data types of the features ###Code df.info() ###Output _____no_output_____ ###Markdown 2.3 Check for need to convert TotalCharges column to numeric if it is detected as objectIf the above `df.info` shows the "TotalCharges" columnn as an object, we'll need to convert it to numeric. If you have already done this during a previous exercise for "Data Visualization with Data Refinery", you can skip to step `2.5`. ###Code totalCharges = df.columns.get_loc("TotalCharges") print(totalCharges) new_col = pd.to_numeric(df.iloc[:, totalCharges], errors='coerce') new_col ###Output _____no_output_____ ###Markdown 2.4 Modify our dataframe to reflect the new datatype ###Code df.iloc[:, totalCharges] = pd.Series(new_col) df ###Output _____no_output_____ ###Markdown 2.5 Any NaN values should be removed to create a more accurate model. ###Code # Check if we have any NaN values df.isnull().values.any() ###Output _____no_output_____ ###Markdown Set `nan_column` to the column number for TotalCharges (starting at 0). ###Code nan_column = df.columns.get_loc("TotalCharges") print(nan_column) # Handle missing values for nan_column (TotalCharges) from sklearn.preprocessing import Imputer imp = Imputer(missing_values="NaN", strategy="mean") df.iloc[:, nan_column] = imp.fit_transform(df.iloc[:, nan_column].values.reshape(-1, 1)) df.iloc[:, nan_column] = pd.Series(df.iloc[:, nan_column]) # Check if we have any NaN values df.isnull().values.any() ###Output _____no_output_____ ###Markdown 2.6 Visualize data ###Code import json import os import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn import preprocessing, svm from itertools import combinations from sklearn.preprocessing import PolynomialFeatures, LabelEncoder, StandardScaler import sklearn.feature_selection from sklearn.model_selection import train_test_split from collections import defaultdict from sklearn import metrics # Plot Tenure Frequency count sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="tenure", hue="Churn", data=df) # Plot Tenure Frequency count sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="Contract", hue="Churn", data=df) # Plot Tenure Frequency count sns.set(style="darkgrid") sns.set_palette("hls", 3) fig, ax = plt.subplots(figsize=(20,10)) ax = sns.countplot(x="TechSupport", hue="Churn", data=df) # Create Grid for pairwise relationships gr = sns.PairGrid(df, size=5, hue="Churn") gr = gr.map_diag(plt.hist) gr = gr.map_offdiag(plt.scatter) gr = gr.add_legend() # Set up plot size fig, ax = plt.subplots(figsize=(6,6)) # Attributes destribution a = sns.boxplot(orient="v", palette="hls", data=df.iloc[:, totalCharges], fliersize=14) # Total Charges data distribution histogram = sns.distplot(df.iloc[:, totalCharges], hist=True) plt.show() tenure = df.columns.get_loc("tenure") print(tenure) # Tenure data distribution histogram = sns.distplot(df.iloc[:, tenure], hist=True) plt.show() monthly = df.columns.get_loc("MonthlyCharges") print(monthly) # Monthly Charges data distribution histogram = sns.distplot(df.iloc[:, monthly], hist=True) plt.show() ###Output _____no_output_____ ###Markdown Understand Data Distribution 3.0 Create a model ###Code from pyspark.sql import SparkSession import pandas as pd import json spark = SparkSession.builder.getOrCreate() df_data = spark.createDataFrame(df) df_data.head() ###Output _____no_output_____ ###Markdown 3.1 Split the data into training and test sets ###Code spark_df = df_data (train_data, test_data) = spark_df.randomSplit([0.8, 0.2], 24) print("Number of records for training: " + str(train_data.count())) print("Number of records for evaluation: " + str(test_data.count())) ###Output _____no_output_____ ###Markdown 3.2 Examine the Spark DataFrame SchemaLook at the data types to determine requirements for feature engineering ###Code spark_df.printSchema() ###Output _____no_output_____ ###Markdown 3.3 Use StringIndexer to encode a string column of labels to a column of label indices ###Code from pyspark.ml.classification import RandomForestClassifier from pyspark.ml.feature import StringIndexer, IndexToString, VectorAssembler from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml import Pipeline, Model si_gender = StringIndexer(inputCol = 'gender', outputCol = 'gender_IX') si_Partner = StringIndexer(inputCol = 'Partner', outputCol = 'Partner_IX') si_Dependents = StringIndexer(inputCol = 'Dependents', outputCol = 'Dependents_IX') si_PhoneService = StringIndexer(inputCol = 'PhoneService', outputCol = 'PhoneService_IX') si_MultipleLines = StringIndexer(inputCol = 'MultipleLines', outputCol = 'MultipleLines_IX') si_InternetService = StringIndexer(inputCol = 'InternetService', outputCol = 'InternetService_IX') si_OnlineSecurity = StringIndexer(inputCol = 'OnlineSecurity', outputCol = 'OnlineSecurity_IX') si_OnlineBackup = StringIndexer(inputCol = 'OnlineBackup', outputCol = 'OnlineBackup_IX') si_DeviceProtection = StringIndexer(inputCol = 'DeviceProtection', outputCol = 'DeviceProtection_IX') si_TechSupport = StringIndexer(inputCol = 'TechSupport', outputCol = 'TechSupport_IX') si_StreamingTV = StringIndexer(inputCol = 'StreamingTV', outputCol = 'StreamingTV_IX') si_StreamingMovies = StringIndexer(inputCol = 'StreamingMovies', outputCol = 'StreamingMovies_IX') si_Contract = StringIndexer(inputCol = 'Contract', outputCol = 'Contract_IX') si_PaperlessBilling = StringIndexer(inputCol = 'PaperlessBilling', outputCol = 'PaperlessBilling_IX') si_PaymentMethod = StringIndexer(inputCol = 'PaymentMethod', outputCol = 'PaymentMethod_IX') si_Label = StringIndexer(inputCol="Churn", outputCol="label").fit(spark_df) label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=si_Label.labels) ###Output _____no_output_____ ###Markdown 3.4 Create a single vector ###Code va_features = VectorAssembler(inputCols=['gender_IX', 'SeniorCitizen', 'Partner_IX', 'Dependents_IX', 'PhoneService_IX', 'MultipleLines_IX', 'InternetService_IX', \ 'OnlineSecurity_IX', 'OnlineBackup_IX', 'DeviceProtection_IX', 'TechSupport_IX', 'StreamingTV_IX', 'StreamingMovies_IX', \ 'Contract_IX', 'PaperlessBilling_IX', 'PaymentMethod_IX', 'TotalCharges', 'MonthlyCharges'], outputCol="features") ###Output _____no_output_____ ###Markdown 3.5 Create a pipeline, and fit a model using RandomForestClassifier Assemble all the stages into a pipeline. We don't expect a clean linear regression, so we'll use RandomForestClassifier to find the best decision tree for the data. ###Code classifier = RandomForestClassifier(featuresCol="features") pipeline = Pipeline(stages=[si_gender, si_Partner, si_Dependents, si_PhoneService, si_MultipleLines, si_InternetService, si_OnlineSecurity, si_OnlineBackup, si_DeviceProtection, \ si_TechSupport, si_StreamingTV, si_StreamingMovies, si_Contract, si_PaperlessBilling, si_PaymentMethod, si_Label, va_features, \ classifier, label_converter]) model = pipeline.fit(train_data) predictions = model.transform(test_data) evaluatorDT = BinaryClassificationEvaluator(rawPredictionCol="prediction") area_under_curve = evaluatorDT.evaluate(predictions) #default evaluation is areaUnderROC print("areaUnderROC = %g" % area_under_curve) ###Output _____no_output_____ ###Markdown 4.0 Save the model and test data Add a unique name for MODEL_NAME. ###Code MODEL_NAME = "my-model my-date" ###Output _____no_output_____ ###Markdown 4.1 Save the model to ICP4D local Watson Machine LearningReplace the `username` and `password` values of `*****` with your Cloud Pak for Data `username` and `password`.The value for `url` should match the `url` for your Cloud Pak for Data cluster. ###Code from watson_machine_learning_client import WatsonMachineLearningAPIClient wml_credentials = { "url": "https://zen-cpd-zen.apps.os-workshop-nov22.vz-cpd-nov22.com", "username": "*****", "password" : "*****", "instance_id": "wml_local", "version" : "2.5.0" } client = WatsonMachineLearningAPIClient(wml_credentials) client.spaces.list() ###Output _____no_output_____ ###Markdown Use the desired space as the `default_space`Put the `GUID` of the desired space as the parameter below ###Code client.set.default_space('<GUID>') # Store our model model_props = {client.repository.ModelMetaNames.NAME: MODEL_NAME, client.repository.ModelMetaNames.RUNTIME_UID : "spark-mllib_2.3", client.repository.ModelMetaNames.TYPE : "mllib_2.3"} published_model = client.repository.store_model(model=model, pipeline=pipeline, meta_props=model_props, training_data=train_data) # Use this cell to do any cleanup of previously created models and deployments client.repository.list_models() client.deployments.list() # client.repository.delete('GUID of stored model') # client.deployments.delete('GUID of deployed model') ###Output _____no_output_____ ###Markdown 4.2 Write the test data without label to a .csv so that we can later use it for batch scoring ###Code write_score_CSV=test_data.toPandas().drop(['Churn'], axis=1) write_score_CSV.to_csv('/project_data/data_asset/TelcoCustomerSparkMLBatchScore.csv', sep=',', index=False) ###Output _____no_output_____ ###Markdown 4.3 Write the test data to a .csv so that we can later use it for evaluation ###Code write_eval_CSV=test_data.toPandas() write_eval_CSV.to_csv('/project_data/data_asset/TelcoCustomerSparkMLEval.csv', sep=',', index=False) ###Output _____no_output_____
remote_sensing/python/Local_Jupyter_NoteBooks/Acre per Crop Group - Mike Brady - Douglas.ipynb
###Markdown Acre per Crop Group - Mike Brady - Douglas ###Code # import warnings # warnings.filterwarnings("ignore") import csv import numpy as np import pandas as pd # import geopandas as gpd from IPython.display import Image # from shapely.geometry import Point, Polygon from math import factorial import scipy import scipy.signal import os, os.path from datetime import date import datetime import time from statsmodels.sandbox.regression.predstd import wls_prediction_std from sklearn.linear_model import LinearRegression from patsy import cr # from pprint import pprint import matplotlib.pyplot as plt import seaborn as sb import sys # to move files from one directory to another import shutil sys.path.append('/Users/hn/Documents/00_GitHub/Ag/remote_sensing/python/') import remote_sensing_core as rc import remote_sensing_plot_core as rcp start_time = time.time() ###Output _____no_output_____ ###Markdown crop_type vs crop_group ###Code data_dir = "/Users/hn/Documents/01_research_data/remote_sensing/01_Data_part_not_filtered/" shapeFile_2016 = pd.read_csv(data_dir + f_names[0], low_memory = False) shapeFile_2017 = pd.read_csv(data_dir + f_names[1], low_memory = False) shapeFile_2018 = pd.read_csv(data_dir + f_names[1], low_memory = False) shapeFile_2016.head(5) ###Output _____no_output_____ ###Markdown Find Acreage per crop group and croup type in Douglas ###Code data_dir = "/Users/hn/Documents/01_research_data/remote_sensing/" + \ "01_NDVI_TS/70_Cloud/00_Eastern_WA_withYear/2Years/Douglas_MikeBrady/" param_dir = "/Users/hn/Documents/00_GitHub/Ag/remote_sensing/parameters/" given_county = "Douglas" SG_win_size = 7 SG_poly_Order = 3 years = [2016, 2017, 2018] file_names = ["Douglas_2016_regular_EVI_SG_win7_Order3.csv", "Douglas_2017_regular_EVI_SG_win7_Order3.csv", "Douglas_2018_regular_EVI_SG_win7_Order3.csv"] double_crop_potential = pd.read_csv(param_dir + "double_crop_potential_plants.csv") irrigated_only = True NASS_out = False only_annuals = True small_fields_out = False Last_survey_year = False remove_columns = ["RtCrpTy", "SOS", "EOS", "human_system_start_time", "Shp_Lng", "Shap_Ar", "TRS", "doy", "IntlSrD"] for file in file_names: print (file) original_data_tble = pd.read_csv(data_dir + file, low_memory = False) data_tble = original_data_tble.copy() if irrigated_only == True: data_tble = rc.filter_out_nonIrrigated(data_tble) irrigated_name = "onlyIrrigated" else: irrigated_name = "irrigatedAndNonIrr" if NASS_out == True: data_tble = rc.filter_out_NASS(data_tble) NASS_out_name = "NASSOut" else: NASS_out_name = "allSurvySources" if only_annuals == True: data_tble = data_tble[data_tble.CropTyp.isin(double_crop_potential['Crop_Type'])] only_annuals_name = "onlyAnnuals" else: only_annuals_name = "AnnualsAndPerenials" if small_fields_out == True: data_tble = data_tble[data_tble.Acres > 3] small_fields_name = "bigFields" else: small_fields_name = "bigAndSmallFields" proper_year = file.split("_")[1] proper_year = proper_year.split(".")[0] if Last_survey_year == True: data_tble = data_tble[data_tble['LstSrvD'].str.contains(proper_year)] Last_survey_year_name = "correctLstSrvD" else: Last_survey_year_name = "wrongLstSrvD" CropGrp_acreage = data_tble.groupby(["county", "CropGrp", "season_count"]).Acres.sum().reset_index() CropType_acreage = data_tble.groupby(["county", "CropTyp", "season_count"]).Acres.sum().reset_index() # Saving path out_dir = data_dir + "/acreage_tables/" out_dir = data_dir os.makedirs(out_dir, exist_ok=True) CropGrp_acreage_name = out_dir + proper_year + "_" + \ "Douglas_CropGrp_doubleAcr_" + \ irrigated_name + "_" + \ NASS_out_name + "_" + \ only_annuals_name + "_" + \ small_fields_name + "_" + \ Last_survey_year_name + "_" + \ ".csv" CropType_acreage_name = out_dir + proper_year + "_" + \ "Douglas_CropType_doubleAcr_" + \ irrigated_name + "_" + \ NASS_out_name + "_" + \ only_annuals_name + "_" + \ small_fields_name + "_" + \ Last_survey_year_name + \ ".csv" CropGrp_acreage.to_csv(CropGrp_acreage_name, index = False) CropType_acreage.to_csv(CropType_acreage_name, index = False) ###Output Douglas_2016_regular_EVI_SG_win7_Order3.csv Douglas_2017_regular_EVI_SG_win7_Order3.csv Douglas_2018_regular_EVI_SG_win7_Order3.csv ###Markdown print (data_tble.DataSrc.unique())print (data_tble.Irrigtn.unique())print (data_tble.CropTyp.unique())print (data_tble.season_count.unique())print (data_tble.LstSrvD.unique())print (data_tble.image_year.unique())print (data_tble.SF_year.unique()) ###Code data_tble.head(2) CropGrp_acreage ###Output _____no_output_____
Recommender.ipynb
###Markdown A Recommendation System from RedditIn this report, I aim to build a recommendation system for Reddit users (refered to as Redditors) using only their Reddit username. MotivationIn the age of the internet consumers have an abundance of choice. From movies to songs to every concievable product, it seems like we have access to more choice than we can every hope to exercise. To make the traversal of this infromation more manageable, many companies build recommendation systems to help their users find more meaningful content or products, with great success. Platforms like Netflix and YouTube would simply not exist if they could not match users with personalized content given their vast content libraries.However, the value we gain from these recommendation engines come at a cost. These websites collect a tremendous amount of data from us. Google and Facebook particularly track our every movement, not just on the internet but, since the proliferation of smartphones, in the physical world as well. In addition, this is a huge barrier to entry for startups since the information that sites like Amazon and Facebook have about their customers allows them to provide better suggestions than new platforms.This is why I set out to see if I could build a recommendation system for users who I have not collected any prior information from. I plan to explore how we can leverage existing, public data about a user to suggest interesting items they may find interesting. I wish to deploy this into a site that encourages a community to share interests and ideas together rather than with a corporation that is trying to sell them something. The ProductsFirst of all, I had to select which products I wanted to suggest. Netflix suggests movies, YouTube suggests videos and Spotify suggests songs, but Amazon suggests all of these things and a whole lot more. However, Amazon's product discovery algorithm is mainly built on items that someone has already purchased. As a result, a user only gets recommendations based on products they are familiar with. This is to Amazon's advantage, since these products likely have a very high conversion rate. However, it does not lend itself well to finding novel products that are based on our interests rather than our purchase history. Reddit as a window to the soulReddit is one of the most visited sites on the internet. It is a meta forum where users can post links to interesting items for every topic imaginable and discuss them with millions of other people. One of the strongest reasons why Reddit appeals to so many is because of its anonymity. It is one of the few forums where you can sign up without an email address, and is a far cry from something like Facebook where you have profile pictures and family information. Therefore, redditors can be open and expressive about their interests. Indeed, their personalities are associated with their Reddit usernames rather than their real names. This may lead to trolling but that is outside the scope of this exercise. The true value of Reddit for this tool is that redditors comment on different topics, and we can access these topics. This means that by accessing the topics where they comment (known as subreddits), we can see which topics they are interested in. A clear limitation of this is that certain redditors only browse subreddits without commenting on them (colloquially known as 'lurking'). There is no way to access this information. Indeed, I do not even think that reddit makes the subreddits that a user is subscribed to public. Therefore, we have to use the comments and get the subreddits from them. Collaborative FilteringThere are a variety of ways that recommender systems can work. In order to harness the power of the social fabric of Reddit, I will use 'Collaborative Filtering'. Collaborative Filtering is a way to utilize user inputs to suggest products to similar users. Usually, it is done in the manner that if User 1 likes X,Y and Z and User 2 likes X and Y, there is a high probability that User 2 likes Z. This is the way that Amazon does it. However, we do not have access to the users purchase history and, like mentioned above, we want to suggest novel products that are independent of our target user's purchase history. Therefore, we extend the same concept to subreddits rather than products. In our case, we postulate that if User X and User Y comment on similar topics, they have similar tastes and therefore we can recommend the products that User X likes to User Y. Getting DataFor Collaborative Filtering to work, however, we need a seed dataset of products to suggest to our users. This is where most platforms fail in their recommender systems. Without this critical mass of data, there would be nothing to suggest. However, upon research, I found a particular subreddit that provided me with a workaround; r/randomactsofamazon. R/RandomActsOfAmazon is an offshoot of an idea that the Reddit community has had for a long time, the act of randomly gifting something to another redditor. It originated with R/RandonActsOfPizza where, like the title would suggest, redditors would gift each other pizza delivered to their doorstep. R/RandomActsOfAmazon takes this concept further and allows redditors to post wishlists of things they want from Amazon. These redditors then hope that some stranger might like them and buy them a gift from their wishlist. This data is perfect for me as this contains the products that a particular redditor wants/thinks are cool. After contacting the moderators for r/randomactsofamazon, I was referred to http://n8fq.org/temp/links.sql This is an sql dump of the entire database of active users on r/randomactsofamazon. It is a public site that is used to power functionality for r/randomactsofamazon and I was given permission to use it. I was able to parse this sql dump into a database and convert it into a csv file in another script (see github repo). I will use this csv file for my recommendation engine. I will also encourage users to gift their 'Reddit Twin' (i.e. the redditor in my database who is thier closest match) something from their wishlist. However, since I do not have informed consent for every reddit user in my database, I will not disclose the reddit id of their twin. Amazon holds the address of the wishlist owner secret to allow for safe, anonymous gifting. Now, lets get to the good stuff. Lets import our dependecies. In this case, we need pandas to manipulate our data and PRAW, the Python Reddit API Wrapper.Find out more about PRAW at https://praw.readthedocs.io/en/latest/ ###Code import pandas as pd import praw ###Output _____no_output_____ ###Markdown We instantiate our Reddit instance. We have registered this script with Reddit and obtained a key (client secret). The account details are mine. ###Code reddit = praw.Reddit(client_id = 'tOwGdbmWXETjEA', client_secret = 'FPfgf52wvSG0TN-y_wlTRavGlpU', username = 'amazonrecommender', password = 'amazon', user_agent='test') getsubs('abhi91') ###Output _____no_output_____ ###Markdown Lets import the data. We will have 3 columns, the username a raw link and a processed link that I have cleaned up and added tracking information to. This will allow me to monitor the traffic being sent to Amazon when the site is published. We will use 'New Url' in this program. ###Code df = pd.DataFrame.from_csv('newlist.csv') df.head() ###Output _____no_output_____ ###Markdown We now write a function that allows us to utilize PRAW to get the subreddits that a redditor has commented in. To keep in touch with the redditors current interests, we will only identify the most recent 500 comments. Note that we are using a set so that we have unique subreddits and these are not in any order. Also we need to normalize these by removing the most popular subreddits as well as randomactsofamazon. This will ensure that the subreddits that influence unique tastes are given higher weight. ###Code defaultsubs = set(['announcements','funny','AskReddit','todayilearned','science','pics','IAmA','randomactsofamazon']) def normalizesubs(usersubs): normalizedsubs = usersubs - defaultsubs return (normalizedsubs) def getsubs(username): subs = set() redditor = reddit.redditor(str(username)) for comment in redditor.comments.new(limit=500): subs.add(str(comment.subreddit)) #normalize subs by removing most popular subs. subs=normalizesubs(subs) return(subs) ###Output _____no_output_____ ###Markdown In order to give our user a good experience, we need to minimize loading times for our recommendations. The most time consuming part of this whole script is extracting all the comments from a user. We can minimize this time by pulling a list of subreddits that our database of redditors have commented in as of today (12/10/2017). While this will mean that our recommendation engine is not dynamic with the changing interests of our database redditors, it significantly cuts down on loading time. We can update this list of subreddits at regular intervals in the future. We will append this list of subreddits to our dataframe. ###Code #takes a long time. Just import redditproducts.csv and the code in that cell subslist = [] for index,rows in df.iterrows(): user = rows['User'] print('Trying for user number: ',index,' username: ',user) try: subslist.append(getsubs(user)) except : #if there is an error, the user has deleted their reddit account. Store Null and continue with the loop subslist.append('Null') print('user not there') continue df['Subs']=subslist ###Output Trying for user number: 0 username: Ali-Sama Trying for user number: 1 username: Rysona Trying for user number: 2 username: G0ATLY Trying for user number: 3 username: dancemasterv Trying for user number: 4 username: chunkopunk Trying for user number: 5 username: Browntizzle Trying for user number: 6 username: rockinDS24 Trying for user number: 7 username: rsgamg Trying for user number: 8 username: 82364 Trying for user number: 9 username: RyanOver9000 Trying for user number: 10 username: L_Cranston_Shadow Trying for user number: 11 username: neuromorph Trying for user number: 12 username: havechanged Trying for user number: 13 username: TAPorter Trying for user number: 14 username: cj151695 Trying for user number: 15 username: NibbleFish Trying for user number: 16 username: ninja_nicci Trying for user number: 17 username: ShiroiMana Trying for user number: 18 username: mitsimac Trying for user number: 19 username: FirstLadyOfBeer Trying for user number: 20 username: imscreamingrightnow Trying for user number: 21 username: whiteandyellow Trying for user number: 22 username: Balaguru_BR5 Trying for user number: 23 username: kanooka Trying for user number: 24 username: ScarlettMaeBottom Trying for user number: 25 username: Jacewoop23 Trying for user number: 26 username: t-minus5tosexy Trying for user number: 27 username: MagicMistoffelees Trying for user number: 28 username: Allybama Trying for user number: 29 username: PapaRomeoAlpha Trying for user number: 30 username: spilledbeans Trying for user number: 31 username: nddragoon Trying for user number: 32 username: ProbableErorr Trying for user number: 33 username: lcarosella Trying for user number: 34 username: theregoesmyeye user not there Trying for user number: 35 username: discojaxx Trying for user number: 36 username: Rayn_the_hunter Trying for user number: 37 username: Envy_The_Jealous Trying for user number: 38 username: TrocheeCity Trying for user number: 39 username: Bucket4Life Trying for user number: 40 username: ruphuselderbeer Trying for user number: 41 username: Enovara Trying for user number: 42 username: SEQU0IA Trying for user number: 43 username: LittleMizPixie Trying for user number: 44 username: spacesleep Trying for user number: 45 username: EriSeguchi Trying for user number: 46 username: kurosaba Trying for user number: 47 username: Sp3cia1K Trying for user number: 48 username: MMAPhreak21 Trying for user number: 49 username: SailoLee Trying for user number: 50 username: Sieberella Trying for user number: 51 username: GrtNPwrfulOz Trying for user number: 52 username: kirklazaurs87 Trying for user number: 53 username: rarelyserious Trying for user number: 54 username: giggidywarlock user not there Trying for user number: 56 username: TwistedEnigma Trying for user number: 57 username: watsoned Trying for user number: 58 username: SukiTheGoat Trying for user number: 59 username: MCubb Trying for user number: 60 username: neongreenpurple Trying for user number: 61 username: mewfasa Trying for user number: 62 username: mattidallama Trying for user number: 63 username: burke_no_sleeps Trying for user number: 64 username: Headcall Trying for user number: 65 username: paradoxikal Trying for user number: 66 username: MKandtheforce Trying for user number: 67 username: SirRipo Trying for user number: 68 username: Rubenick Trying for user number: 69 username: wee-pixie user not there Trying for user number: 70 username: saratonin84 Trying for user number: 71 username: EdenSB Trying for user number: 72 username: Girfex Trying for user number: 73 username: windurr Trying for user number: 74 username: s2xtreme4u Trying for user number: 75 username: dragonflyjen Trying for user number: 76 username: HeadlessBob17 Trying for user number: 77 username: krispykremedonuts Trying for user number: 78 username: legotech Trying for user number: 79 username: Akeleie Trying for user number: 80 username: glanmiregirl Trying for user number: 81 username: BuffHagen user not there Trying for user number: 82 username: thatbossguy Trying for user number: 83 username: Matronix Trying for user number: 84 username: GhostOfTheNet Trying for user number: 85 username: Brenhines Trying for user number: 86 username: teatimeoclock Trying for user number: 87 username: kayleighh Trying for user number: 88 username: xX_Justin_Xx Trying for user number: 89 username: Ajs1004 Trying for user number: 90 username: RCJhawk Trying for user number: 91 username: ItsACharlieDay Trying for user number: 92 username: OfMonstersAndSuicide Trying for user number: 93 username: angelninja Trying for user number: 94 username: Roehok Trying for user number: 95 username: cupcakegiraffe Trying for user number: 96 username: Kibure Trying for user number: 97 username: LeftMySoulAtHome Trying for user number: 98 username: paintnwood Trying for user number: 99 username: lobstahfi Trying for user number: 100 username: origami_rock Trying for user number: 101 username: natalietoday Trying for user number: 102 username: OverlyApologeticGuy Trying for user number: 103 username: Chaela Trying for user number: 104 username: bethydolla Trying for user number: 105 username: Ereshkigal234 Trying for user number: 106 username: drzedwordhunter Trying for user number: 107 username: hannaHananaB Trying for user number: 108 username: ebooksgirl Trying for user number: 109 username: 0hfuck Trying for user number: 111 username: homeallday Trying for user number: 112 username: 3dmesh Trying for user number: 113 username: theCaitiff Trying for user number: 114 username: Coffin_Nail Trying for user number: 115 username: SphynxKitty Trying for user number: 116 username: sylvar Trying for user number: 117 username: Candroth Trying for user number: 118 username: OptomisticOcelot Trying for user number: 119 username: cthylla Trying for user number: 120 username: effeduphealer Trying for user number: 121 username: Liies Trying for user number: 122 username: ichosethis Trying for user number: 123 username: EmergencyPizza Trying for user number: 124 username: aimeenew Trying for user number: 125 username: stutterbutt Trying for user number: 126 username: ApeOver Trying for user number: 127 username: timelady84 Trying for user number: 128 username: trisarahdactyl Trying for user number: 129 username: KittenAnne Trying for user number: 130 username: Nemesis0320 Trying for user number: 131 username: travelersoul Trying for user number: 132 username: draconorge Trying for user number: 133 username: MsRocky Trying for user number: 134 username: DiscoKittie Trying for user number: 135 username: angel92591 Trying for user number: 136 username: R3bel_R3bel Trying for user number: 137 username: Dee_Doubleyew_TTT Trying for user number: 138 username: Junigole Trying for user number: 139 username: hellooolady Trying for user number: 140 username: titchard Trying for user number: 141 username: Shercock_Holmes Trying for user number: 142 username: book_worm526 Trying for user number: 143 username: themusicliveson Trying for user number: 144 username: writerlib Trying for user number: 145 username: Janiichan Trying for user number: 146 username: UnBornPorn Trying for user number: 147 username: nijoli Trying for user number: 148 username: DoodlesAndSuch Trying for user number: 149 username: imsamsam Trying for user number: 150 username: Sneekyninja Trying for user number: 151 username: browneyedgirl79 Trying for user number: 152 username: MoonPrisimPower Trying for user number: 153 username: DrUsual Trying for user number: 154 username: ink1026 Trying for user number: 155 username: dapamico Trying for user number: 156 username: melumebelle Trying for user number: 157 username: earthsick Trying for user number: 158 username: MisterJimJim ###Markdown If you are running the script, run the cell below to avoid waiting a bunch for the code above. ###Code #If you are running this script, please just use this as the Dataframe df=pd.DataFrame.from_csv('redditproducts.csv') # If you are running the script then run this cell. My functions import ast newlist = [] for i in range(len(df)): try: print(i) newlist.append(ast.literal_eval(df['Subs'][i])) print(type(newlist[i])) except: print(i,'Null Subs, user does not exist') newlist.append('Null') df['Subs']=newlist ###Output 0 <class 'set'> 1 <class 'set'> 2 <class 'set'> 3 <class 'set'> 4 <class 'set'> 5 <class 'set'> 6 <class 'set'> 7 <class 'set'> 8 <class 'set'> 9 <class 'set'> 10 <class 'set'> 11 <class 'set'> 12 <class 'set'> 13 <class 'set'> 14 <class 'set'> 15 <class 'set'> 16 <class 'set'> 17 <class 'set'> 18 <class 'set'> 19 <class 'set'> 20 <class 'set'> 21 <class 'set'> 22 <class 'set'> 23 <class 'set'> 24 <class 'set'> 25 <class 'set'> 26 <class 'set'> 27 <class 'set'> 28 <class 'set'> 29 <class 'set'> 30 <class 'set'> 31 <class 'set'> 32 <class 'set'> 33 <class 'set'> 34 34 Null Subs, user does not exist 35 <class 'set'> 36 <class 'set'> 37 <class 'set'> 38 <class 'set'> 39 <class 'set'> 40 <class 'set'> 41 <class 'set'> 42 <class 'set'> 43 <class 'set'> 44 <class 'set'> 45 <class 'set'> 46 <class 'set'> 47 <class 'set'> 48 <class 'set'> 49 <class 'set'> 50 <class 'set'> 51 <class 'set'> 52 <class 'set'> 53 <class 'set'> 54 54 Null Subs, user does not exist 55 55 Null Subs, user does not exist 56 <class 'set'> 57 <class 'set'> 58 <class 'set'> 59 <class 'set'> 60 <class 'set'> 61 <class 'set'> 62 <class 'set'> 63 <class 'set'> 64 <class 'set'> 65 <class 'set'> 66 <class 'set'> 67 <class 'set'> 68 <class 'set'> 69 69 Null Subs, user does not exist 70 <class 'set'> 71 <class 'set'> 72 <class 'set'> 73 <class 'set'> 74 <class 'set'> 75 <class 'set'> 76 <class 'set'> 77 <class 'set'> 78 <class 'set'> 79 <class 'set'> 80 <class 'set'> 81 81 Null Subs, user does not exist 82 <class 'set'> 83 <class 'set'> 84 <class 'set'> 85 <class 'set'> 86 <class 'set'> 87 <class 'set'> 88 <class 'set'> 89 <class 'set'> 90 <class 'set'> 91 <class 'set'> 92 <class 'set'> 93 <class 'set'> 94 <class 'set'> 95 <class 'set'> 96 <class 'set'> 97 <class 'set'> 98 <class 'set'> 99 <class 'set'> 100 <class 'set'> 101 <class 'set'> 102 <class 'set'> 103 <class 'set'> 104 <class 'set'> 105 <class 'set'> 106 <class 'set'> 107 <class 'set'> 108 <class 'set'> 109 <class 'set'> 110 110 Null Subs, user does not exist 111 <class 'set'> 112 <class 'set'> 113 <class 'set'> 114 <class 'set'> 115 <class 'set'> 116 <class 'set'> 117 <class 'set'> 118 <class 'set'> 119 <class 'set'> 120 <class 'set'> 121 <class 'set'> 122 <class 'set'> 123 <class 'set'> 124 <class 'set'> 125 <class 'set'> 126 <class 'set'> 127 <class 'set'> 128 <class 'set'> 129 <class 'set'> 130 <class 'set'> 131 <class 'set'> 132 <class 'set'> 133 <class 'set'> 134 <class 'set'> 135 <class 'set'> 136 <class 'set'> 137 <class 'set'> 138 <class 'set'> 139 <class 'set'> 140 <class 'set'> 141 <class 'set'> 142 <class 'set'> 143 143 Null Subs, user does not exist 144 <class 'set'> 145 <class 'set'> 146 <class 'set'> 147 <class 'set'> 148 <class 'set'> 149 <class 'set'> 150 <class 'set'> 151 <class 'set'> 152 <class 'set'> 153 <class 'set'> 154 <class 'set'> 155 <class 'set'> 156 <class 'set'> 157 <class 'set'> 158 <class 'set'> 159 <class 'set'> 160 <class 'set'> 161 <class 'set'> 162 <class 'set'> 163 <class 'set'> 164 <class 'set'> 165 <class 'set'> 166 <class 'set'> 167 167 Null Subs, user does not exist 168 <class 'set'> 169 <class 'set'> 170 <class 'set'> 171 <class 'set'> 172 <class 'set'> 173 <class 'set'> 174 <class 'set'> 175 <class 'set'> 176 <class 'set'> 177 <class 'set'> 178 <class 'set'> 179 <class 'set'> 180 <class 'set'> 181 <class 'set'> 182 <class 'set'> 183 <class 'set'> 184 <class 'set'> 185 <class 'set'> 186 <class 'set'> 187 <class 'set'> 188 <class 'set'> 189 <class 'set'> 190 <class 'set'> 191 <class 'set'> 192 <class 'set'> 193 <class 'set'> 194 <class 'set'> 195 <class 'set'> 196 <class 'set'> 197 <class 'set'> 198 <class 'set'> 199 <class 'set'> 200 <class 'set'> 201 <class 'set'> 202 <class 'set'> 203 <class 'set'> 204 <class 'set'> 205 <class 'set'> 206 <class 'set'> 207 <class 'set'> 208 <class 'set'> 209 <class 'set'> 210 <class 'set'> 211 <class 'set'> 212 <class 'set'> 213 <class 'set'> 214 <class 'set'> 215 <class 'set'> 216 <class 'set'> 217 <class 'set'> 218 <class 'set'> 219 <class 'set'> 220 <class 'set'> 221 <class 'set'> 222 <class 'set'> 223 <class 'set'> 224 <class 'set'> 225 <class 'set'> 226 <class 'set'> 227 <class 'set'> 228 <class 'set'> 229 <class 'set'> 230 <class 'set'> 231 <class 'set'> 232 <class 'set'> 233 <class 'set'> 234 <class 'set'> 235 <class 'set'> 236 <class 'set'> 237 <class 'set'> 238 <class 'set'> 239 <class 'set'> 240 <class 'set'> 241 <class 'set'> 242 <class 'set'> 243 <class 'set'> 244 <class 'set'> 245 245 Null Subs, user does not exist 246 <class 'set'> 247 247 Null Subs, user does not exist 248 <class 'set'> 249 <class 'set'> 250 <class 'set'> 251 <class 'set'> 252 <class 'set'> 253 <class 'set'> 254 <class 'set'> 255 <class 'set'> 256 <class 'set'> 257 <class 'set'> 258 <class 'set'> 259 <class 'set'> 260 <class 'set'> 261 <class 'set'> 262 <class 'set'> 263 <class 'set'> 264 <class 'set'> 265 <class 'set'> 266 <class 'set'> 267 <class 'set'> 268 <class 'set'> 269 <class 'set'> 270 <class 'set'> 271 <class 'set'> 272 <class 'set'> 273 <class 'set'> 274 <class 'set'> 275 <class 'set'> 276 <class 'set'> 277 <class 'set'> 278 <class 'set'> 279 <class 'set'> 280 <class 'set'> 281 <class 'set'> 282 282 Null Subs, user does not exist 283 <class 'set'> 284 <class 'set'> 285 <class 'set'> 286 <class 'set'> 287 <class 'set'> 288 <class 'set'> 289 <class 'set'> 290 <class 'set'> 291 <class 'set'> 292 <class 'set'> 293 <class 'set'> 294 <class 'set'> 295 <class 'set'> 296 <class 'set'> 297 <class 'set'> 298 <class 'set'> 299 <class 'set'> 300 <class 'set'> 301 <class 'set'> 302 <class 'set'> 303 <class 'set'> 304 <class 'set'> 305 <class 'set'> 306 <class 'set'> 307 <class 'set'> 308 <class 'set'> 309 <class 'set'> 310 <class 'set'> 311 <class 'set'> 312 <class 'set'> 313 <class 'set'> 314 <class 'set'> 315 <class 'set'> 316 <class 'set'> 317 <class 'set'> 318 <class 'set'> 319 <class 'set'> 320 <class 'set'> 321 <class 'set'> 322 <class 'set'> 323 <class 'set'> 324 <class 'set'> 325 <class 'set'> 326 <class 'set'> 327 <class 'set'> 328 <class 'set'> 329 <class 'set'> 330 <class 'set'> 331 <class 'set'> 332 <class 'set'> 333 <class 'set'> 334 <class 'set'> 335 <class 'set'> 336 <class 'set'> 337 <class 'set'> 338 <class 'set'> 339 <class 'set'> 340 <class 'set'> 341 <class 'set'> 342 <class 'set'> 343 <class 'set'> 344 <class 'set'> 345 <class 'set'> 346 <class 'set'> 347 <class 'set'> 348 <class 'set'> 349 <class 'set'> 350 <class 'set'> 351 <class 'set'> 352 <class 'set'> 353 <class 'set'> 354 <class 'set'> 355 <class 'set'> 356 <class 'set'> 357 <class 'set'> 358 <class 'set'> 359 <class 'set'> 360 <class 'set'> 361 <class 'set'> 362 <class 'set'> 363 <class 'set'> 364 <class 'set'> 365 <class 'set'> 366 <class 'set'> 367 <class 'set'> 368 <class 'set'> 369 <class 'set'> 370 <class 'set'> 371 <class 'set'> 372 <class 'set'> 373 <class 'set'> 374 <class 'set'> 375 <class 'set'> 376 <class 'set'> 377 <class 'set'> 378 <class 'set'> 379 <class 'set'> 380 <class 'set'> 381 <class 'set'> 382 <class 'set'> 383 <class 'set'> 384 <class 'set'> 385 <class 'set'> 386 <class 'set'> 387 <class 'set'> 388 <class 'set'> 389 <class 'set'> 390 <class 'set'> 391 <class 'set'> 392 <class 'set'> 393 <class 'set'> 394 <class 'set'> 395 <class 'set'> 396 <class 'set'> 397 <class 'set'> 398 <class 'set'> 399 <class 'set'> 400 <class 'set'> 401 <class 'set'> 402 <class 'set'> 403 <class 'set'> 404 <class 'set'> 405 405 Null Subs, user does not exist 406 <class 'set'> 407 <class 'set'> 408 <class 'set'> 409 <class 'set'> 410 <class 'set'> 411 <class 'set'> 412 <class 'set'> 413 <class 'set'> 414 <class 'set'> 415 <class 'set'> 416 <class 'set'> 417 <class 'set'> 418 418 Null Subs, user does not exist 419 <class 'set'> 420 <class 'set'> 421 <class 'set'> 422 <class 'set'> 423 <class 'set'> 424 <class 'set'> 425 <class 'set'> 426 <class 'set'> 427 <class 'set'> 428 <class 'set'> 429 <class 'set'> 430 <class 'set'> 431 <class 'set'> 432 <class 'set'> 433 <class 'set'> 434 <class 'set'> 435 <class 'set'> 436 <class 'set'> 437 <class 'set'> 438 <class 'set'> 439 <class 'set'> 440 <class 'set'> 441 <class 'set'> 442 <class 'set'> 443 <class 'set'> 444 <class 'set'> 445 <class 'set'> 446 <class 'set'> 447 <class 'set'> 448 <class 'set'> 449 <class 'set'> 450 <class 'set'> 451 <class 'set'> 452 <class 'set'> 453 <class 'set'> 454 <class 'set'> 455 <class 'set'> 456 <class 'set'> 457 <class 'set'> 458 <class 'set'> 459 <class 'set'> 460 <class 'set'> 461 <class 'set'> 462 <class 'set'> 463 <class 'set'> 464 464 Null Subs, user does not exist 465 <class 'set'> 466 <class 'set'> 467 <class 'set'> 468 <class 'set'> 469 <class 'set'> 470 <class 'set'> 471 <class 'set'> 472 <class 'set'> 473 <class 'set'> 474 <class 'set'> 475 <class 'set'> 476 <class 'set'> 477 <class 'set'> 478 <class 'set'> 479 <class 'set'> 480 <class 'set'> 481 481 Null Subs, user does not exist 482 <class 'set'> 483 <class 'set'> 484 <class 'set'> 485 <class 'set'> 486 <class 'set'> 487 <class 'set'> 488 <class 'set'> 489 <class 'set'> 490 <class 'set'> 491 <class 'set'> 492 <class 'set'> 493 <class 'set'> 494 <class 'set'> 495 <class 'set'> 496 <class 'set'> 497 497 Null Subs, user does not exist 498 <class 'set'> 499 <class 'set'> 500 <class 'set'> 501 <class 'set'> 502 <class 'set'> 503 <class 'set'> 504 <class 'set'> 505 <class 'set'> 506 <class 'set'> 507 <class 'set'> 508 <class 'set'> 509 <class 'set'> 510 <class 'set'> 511 <class 'set'> 512 <class 'set'> 513 <class 'set'> 514 <class 'set'> 515 <class 'set'> 516 <class 'set'> 517 <class 'set'> 518 <class 'set'> 519 <class 'set'> 520 <class 'set'> 521 <class 'set'> 522 <class 'set'> 523 <class 'set'> 524 <class 'set'> 525 <class 'set'> 526 <class 'set'> 527 <class 'set'> 528 <class 'set'> 529 <class 'set'> 530 <class 'set'> 531 <class 'set'> 532 <class 'set'> 533 <class 'set'> 534 <class 'set'> 535 <class 'set'> 536 <class 'set'> 537 <class 'set'> 538 <class 'set'> 539 <class 'set'> 540 <class 'set'> 541 541 Null Subs, user does not exist 542 <class 'set'> 543 <class 'set'> 544 <class 'set'> 545 <class 'set'> 546 <class 'set'> 547 <class 'set'> 548 <class 'set'> 549 <class 'set'> 550 <class 'set'> 551 <class 'set'> 552 <class 'set'> 553 <class 'set'> 554 <class 'set'> 555 <class 'set'> 556 <class 'set'> 557 <class 'set'> 558 558 Null Subs, user does not exist 559 <class 'set'> 560 <class 'set'> 561 <class 'set'> 562 <class 'set'> 563 <class 'set'> 564 <class 'set'> 565 <class 'set'> 566 <class 'set'> 567 <class 'set'> 568 <class 'set'> 569 <class 'set'> 570 <class 'set'> 571 <class 'set'> 572 <class 'set'> 573 <class 'set'> 574 <class 'set'> 575 <class 'set'> 576 <class 'set'> 577 <class 'set'> 578 <class 'set'> 579 <class 'set'> 580 <class 'set'> 581 <class 'set'> 582 <class 'set'> 583 <class 'set'> 584 <class 'set'> 585 <class 'set'> 586 <class 'set'> 587 587 Null Subs, user does not exist 588 <class 'set'> 589 <class 'set'> 590 <class 'set'> 591 <class 'set'> 592 592 Null Subs, user does not exist 593 <class 'set'> 594 <class 'set'> 595 595 Null Subs, user does not exist 596 <class 'set'> 597 <class 'set'> 598 <class 'set'> 599 <class 'set'> 600 <class 'set'> 601 <class 'set'> 602 <class 'set'> 603 <class 'set'> 604 <class 'set'> 605 <class 'set'> 606 <class 'set'> 607 <class 'set'> 608 <class 'set'> 609 <class 'set'> 610 <class 'set'> 611 <class 'set'> 612 <class 'set'> 613 <class 'set'> 614 <class 'set'> 615 <class 'set'> 616 <class 'set'> 617 <class 'set'> 618 <class 'set'> 619 <class 'set'> 620 <class 'set'> 621 <class 'set'> 622 <class 'set'> 623 <class 'set'> 624 <class 'set'> 625 <class 'set'> 626 <class 'set'> 627 <class 'set'> 628 <class 'set'> 629 <class 'set'> 630 <class 'set'> 631 <class 'set'> 632 <class 'set'> 633 <class 'set'> 634 <class 'set'> 635 <class 'set'> 636 <class 'set'> 637 <class 'set'> 638 <class 'set'> 639 639 Null Subs, user does not exist 640 <class 'set'> 641 <class 'set'> 642 <class 'set'> 643 <class 'set'> 644 <class 'set'> 645 <class 'set'> 646 <class 'set'> 647 <class 'set'> 648 <class 'set'> 649 <class 'set'> 650 <class 'set'> 651 <class 'set'> ###Markdown We will use jaccard similarity to find similar subreddits. Jaccard similarity is computed by taking the intersections and dividing by the union of two sets. The function will take 4 arguments, the username, dbsubs, usersubs and the url. We wll return a list that has the username of the potential match, the similarity score and the recommendation link. We also have to check if the usersubs field is a set, since if we return a 'Null' string if the user doesn't exist when populating the list of subs. ###Code def jaccardsimilarity(username,dbsubs,usersubs,link): temp = [] temp.append(username) if type(dbsubs)==set: intersection = dbsubs.intersection(usersubs) temp.append(intersection) score = (len(intersection)/len(dbsubs.union(usersubs))) temp.append(score) temp.append(link) return temp else: score = 0 temp.append('Not Active User') temp.append(score) return temp ###Output _____no_output_____ ###Markdown Now we put it all together. We check to see if its a valid usersanme. Then we iterate through our dataframe. We create a temporary list and run it through our jaccard similarity function. We then sort it by the jaccard similarity cost (in descending order) and prune out all but the top 5 results. Then we just loop through the list and print our results. ###Code def main(username): cesc = [] try: usersubs = getsubs(username) except: print("Not a valid username.") return for i in range(len(df)-1): try: cesc.append(jaccardsimilarity(df['User'][i],df['Subs'][i],usersubs,df['New Url'][i])) except: continue # Sort the list by the 3rd item, the Jaccard similarity score sortedlist = sorted(cesc,key=itemgetter(2),reverse=True) # Return the top 5 results sortedlist = sortedlist[:5] print("Your reddit twins are:") for i in sortedlist: print('http://www.reddit.com/u/'+str(i[0])) print('Similarity Score:',i[2]) print('The Subreddits you share are: ',i[1]) print('And here is some stuff they like. Check it out you may like it as well! ' ,i[3] ) # Just call main with your username as a string to run the recommender username = 'abhi91' main(username) df.to_csv('redditproducts.csv') ###Output _____no_output_____ ###Markdown ** The main idea behind the generation of the Recommendation system is to recommend posts using both Collaborative and Content Based Filtering Methods. For Collaborative based filtering we will find out all the categories and find the cosine similarity using user-user collaborative filtering.**``` **DATA PREPROCESSING** UPLOADING DATASETS AND STORING THEM IN DATAFRAMES ###Code import pandas as pd from google.colab import files import io # upload posts.csv, users.csva and views .csv files to proceed uploaded = files.upload() # creating a user data_frame users_df = pd.read_csv('users.csv') users_df.head() # creating posts data frame posts_df = pd.read_csv('posts.csv') posts_df.head() # creating a views data frame views_df = pd.read_csv('views.csv') views_df.head() ###Output _____no_output_____ ###Markdown DETAILS OF THE DATAFRAMES ###Code users_df.describe() views_df.describe() posts_df.describe() ###Output _____no_output_____ ###Markdown NULL VALUE IMPUTATION ###Code users_df.isnull().any() views_df.isnull().any() posts_df.isnull().any() ###Output _____no_output_____ ###Markdown **we have got null values in the category column of the posts dataset** **as its a categorical variable i have to fill the null values considering the title and post_type** **counting total number of null values in posts_df** ###Code posts_df['category'].isna().sum() ###Output _____no_output_____ ###Markdown **finding title and post_type for all 28 null values** ###Code # using pd.isna() function to find null values posts_df[posts_df['category'].isna()] ###Output _____no_output_____ ###Markdown **As we can see most of the null values are for the post_types project we will create a new category called project and assign it to the null values and when ever a user leaves the category field empty we will assign the category field same as the post_type as default** ###Code posts_df[posts_df['category'].isna()]='project' ###Output _____no_output_____ ###Markdown **As we have imputed the null values lets check again** ###Code posts_df.isna().any() ###Output _____no_output_____ ###Markdown **Now lets see how many unique categories are present in the dataset** ###Code posts_df['category'].unique() ###Output _____no_output_____ ###Markdown PREPARING MORE DETAILED DATASET **As we can see some of the categories are combination of multiple categoris we will add more rows to the posts_df by splitting the categories and making one category for each row** ###Code # creating a dictionary whcih will store actual categories as key and splitted # categories as its value categories = {} # filling the dictionary for i in posts_df['category']: categories.update({i:[]}) for j in list(i.split("|")): categories[i].append(j) print(categories) ###Output {'Plant Biotechnology': ['Plant Biotechnology'], 'Artificial Intelligence|Machine Learning|Information Technology': ['Artificial Intelligence', 'Machine Learning', 'Information Technology'], 'Operating Systems': ['Operating Systems'], 'Drawings': ['Drawings'], 'Competition Laws': ['Competition Laws'], 'Eco System': ['Eco System'], 'Economic Policies': ['Economic Policies'], 'Graphic|Graphic Design': ['Graphic', 'Graphic Design'], 'Painting': ['Painting'], 'Pen and ink': ['Pen and ink'], 'Computer Technology|Information Technology': ['Computer Technology', 'Information Technology'], 'Drawings|Painting': ['Drawings', 'Painting'], 'Graphic Design|Visual Arts|Illustration|Graphic': ['Graphic Design', 'Visual Arts', 'Illustration', 'Graphic'], 'Drawings|Calligraphy': ['Drawings', 'Calligraphy'], 'Photography': ['Photography'], 'Empowerment': ['Empowerment'], 'project': ['project'], 'Video editing': ['Video editing'], 'Inorganic Chemistry': ['Inorganic Chemistry'], 'Programming languages': ['Programming languages'], 'Conceptual|Graphic Design': ['Conceptual', 'Graphic Design'], 'HR Management': ['HR Management'], 'Human Resources|HR Management': ['Human Resources', 'HR Management'], 'Mass Media|International Relations': ['Mass Media', 'International Relations'], 'Sculptures|Artistic design': ['Sculptures', 'Artistic design'], 'Fashion Design|Ceramics|Artistic design': ['Fashion Design', 'Ceramics', 'Artistic design'], 'Craft|Artistic design': ['Craft', 'Artistic design'], 'Fashion Design|Visual Arts|Conceptual|Artistic design': ['Fashion Design', 'Visual Arts', 'Conceptual', 'Artistic design'], 'Photography|Fashion Design|Visual Arts|Graphic Design|Artistic design': ['Photography', 'Fashion Design', 'Visual Arts', 'Graphic Design', 'Artistic design'], 'Fashion Design|Visual Arts|Graphic Design|Artistic design|Graphic|Illustration': ['Fashion Design', 'Visual Arts', 'Graphic Design', 'Artistic design', 'Graphic', 'Illustration'], 'Mathematics|Linear Algebra': ['Mathematics', 'Linear Algebra'], 'Electronics & electrical Technology|Electrical Machines': ['Electronics & electrical Technology', 'Electrical Machines'], 'Auditing|Internal Audit': ['Auditing', 'Internal Audit'], 'E Commerce|E Transactions': ['E Commerce', 'E Transactions'], 'Computer Technology|Computation': ['Computer Technology', 'Computation'], 'Auditing|Internal Financial Control': ['Auditing', 'Internal Financial Control'], 'Taxation|Custom Laws': ['Taxation', 'Custom Laws'], 'Auditing|Audit Evidence': ['Auditing', 'Audit Evidence'], 'Taxation|GST': ['Taxation', 'GST'], 'Taxation|Direct Tax': ['Taxation', 'Direct Tax'], 'Auditing|Secratarial Audit': ['Auditing', 'Secratarial Audit'], 'Banking|Banking Companies': ['Banking', 'Banking Companies'], 'Banking|Banking Technology': ['Banking', 'Banking Technology'], 'Auditing|Audit Remark': ['Auditing', 'Audit Remark'], 'Auditing|Cost Audit': ['Auditing', 'Cost Audit'], 'Auditing|Statuary Audit': ['Auditing', 'Statuary Audit'], 'Computer Technology|Programming languages': ['Computer Technology', 'Programming languages'], 'Legal Studies|Legal System': ['Legal Studies', 'Legal System'], 'Sports Coaching|Sports Law': ['Sports Coaching', 'Sports Law'], 'Economics|Economics Sociology': ['Economics', 'Economics Sociology'], 'Economics|Revenue Concept': ['Economics', 'Revenue Concept'], 'Human Rights|Rights and Duties': ['Human Rights', 'Rights and Duties'], 'Sociology|Sociology of Religion': ['Sociology', 'Sociology of Religion'], 'Sociology|Sociology in India': ['Sociology', 'Sociology in India'], 'Political Science|International Politics': ['Political Science', 'International Politics'], 'Political Science|Colonialism In India': ['Political Science', 'Colonialism In India'], 'Legal Studies|Labor Law': ['Legal Studies', 'Labor Law'], 'Computer Technology|Design and Analysis of Algorithms|Programming languages': ['Computer Technology', 'Design and Analysis of Algorithms', 'Programming languages'], 'Computer Technology|Computer Application|Programming languages|Information Technology': ['Computer Technology', 'Computer Application', 'Programming languages', 'Information Technology'], 'Graphics|Computer Creation': ['Graphics', 'Computer Creation'], 'E Commerce|Other Online Platforms': ['E Commerce', 'Other Online Platforms'], 'Drawing': ['Drawing'], 'Drawings|Artistic design': ['Drawings', 'Artistic design'], 'Drawings|Artistic design|Illustration': ['Drawings', 'Artistic design', 'Illustration'], 'E Commerce|Shopping Platform|Other Online Platforms': ['E Commerce', 'Shopping Platform', 'Other Online Platforms'], 'Computer Technology|Hardware|Information Technology': ['Computer Technology', 'Hardware', 'Information Technology'], 'Computer Technology|Computation|Computer Application': ['Computer Technology', 'Computation', 'Computer Application'], 'Business|Business Skills': ['Business', 'Business Skills'], 'Computer Technology|Computer Application|Hardware|Information Technology': ['Computer Technology', 'Computer Application', 'Hardware', 'Information Technology'], 'Computer Technology|Computer Application': ['Computer Technology', 'Computer Application'], 'Computer Technology|Mobile Applications': ['Computer Technology', 'Mobile Applications'], 'Computer Technology|Computer Application|Operating Systems': ['Computer Technology', 'Computer Application', 'Operating Systems'], 'Computer Technology|Information Technology|Computer Application': ['Computer Technology', 'Information Technology', 'Computer Application'], 'Computer Technology|Computer Application|Information Technology': ['Computer Technology', 'Computer Application', 'Information Technology'], 'Communication|Basics of Communiaction': ['Communication', 'Basics of Communiaction'], 'Drawings|Painting|Visual Arts|Graphic Design|Prints|Illustration': ['Drawings', 'Painting', 'Visual Arts', 'Graphic Design', 'Prints', 'Illustration'], 'Drawings|Visual Arts|Painting|Graphic Design|Artistic design|Illustration': ['Drawings', 'Visual Arts', 'Painting', 'Graphic Design', 'Artistic design', 'Illustration'], 'Computer Technology|Artificial Intelligence': ['Computer Technology', 'Artificial Intelligence'], 'Marketing|Advertising': ['Marketing', 'Advertising'], 'Political Science|Political Thought': ['Political Science', 'Political Thought'], 'Accounting|Fundamental Of Accounting': ['Accounting', 'Fundamental Of Accounting'], 'Mixed Media': ['Mixed Media'], 'Management|Team Mangememnt': ['Management', 'Team Mangememnt'], 'Business|Corporate Social Responsibilities': ['Business', 'Corporate Social Responsibilities'], 'Philosophy|Applied Ethics': ['Philosophy', 'Applied Ethics'], 'Human Resources|Performance In Organization|Organizational Behaviour|HR Management': ['Human Resources', 'Performance In Organization', 'Organizational Behaviour', 'HR Management'], 'Fashion Desigining|Fashion Textile|Fashion Manufacturing|Fashion Techniques|Garment Production|Garment Technology': ['Fashion Desigining', 'Fashion Textile', 'Fashion Manufacturing', 'Fashion Techniques', 'Garment Production', 'Garment Technology'], 'Marketing|Promotion And Distribution Decisions': ['Marketing', 'Promotion And Distribution Decisions'], 'Biotechnology|Genetic Engineering': ['Biotechnology', 'Genetic Engineering'], 'Physiology|Neurology': ['Physiology', 'Neurology'], 'Mass Media|Indian Government': ['Mass Media', 'Indian Government'], 'Physiology|Osteology': ['Physiology', 'Osteology'], 'Physiology|Cardiology': ['Physiology', 'Cardiology'], 'Zoology|Ecology': ['Zoology', 'Ecology'], 'Computer Technology|Cloud Computing': ['Computer Technology', 'Cloud Computing'], 'Physiology|Radiology': ['Physiology', 'Radiology'], 'Computer Technology|Operating Systems': ['Computer Technology', 'Operating Systems'], 'Biotechnology|Molecular Biology': ['Biotechnology', 'Molecular Biology'], 'Physiology|Gastroenterology|Cardiology': ['Physiology', 'Gastroenterology', 'Cardiology'], 'Philosophy|Logic': ['Philosophy', 'Logic'], 'Watercolours': ['Watercolours'], 'Drawings|Watercolours': ['Drawings', 'Watercolours'], 'Mixed Media|Conceptual': ['Mixed Media', 'Conceptual'], 'Drawings|Painting|Watercolours': ['Drawings', 'Painting', 'Watercolours'], 'Visual Arts': ['Visual Arts'], 'Conceptual': ['Conceptual'], 'Tapestry': ['Tapestry'], 'Calligraphy': ['Calligraphy'], 'Human Resources|Performance In Organization': ['Human Resources', 'Performance In Organization'], 'Computer Technology|Robotics|Data Science|Information Technology|Artificial Intelligence': ['Computer Technology', 'Robotics', 'Data Science', 'Information Technology', 'Artificial Intelligence'], 'Philosophy|Public Philosophy': ['Philosophy', 'Public Philosophy'], 'Digital Marketing': ['Digital Marketing'], 'Mass Media|Videography': ['Mass Media', 'Videography'], 'Drawings|Painting|Visual Arts|Artistic design|Watercolours|Acrylics': ['Drawings', 'Painting', 'Visual Arts', 'Artistic design', 'Watercolours', 'Acrylics'], 'Biotechnology|Plant Biotechnology': ['Biotechnology', 'Plant Biotechnology'], 'Sports Coaching|Sports Event': ['Sports Coaching', 'Sports Event'], 'Political Science|Government and Politics': ['Political Science', 'Government and Politics'], 'Geography|Physical Geography': ['Geography', 'Physical Geography'], 'Computer Technology|Data Science': ['Computer Technology', 'Data Science'], 'Computer Technology|Machine Learning': ['Computer Technology', 'Machine Learning'], 'Graphic Design': ['Graphic Design'], 'Graphic Design|Visual Arts': ['Graphic Design', 'Visual Arts'], 'Education': ['Education'], 'Business|Business Organisation': ['Business', 'Business Organisation'], 'Zoology|Environmental Biology': ['Zoology', 'Environmental Biology'], 'Human Rights|Fundamental Rights': ['Human Rights', 'Fundamental Rights'], 'Computer Technology|Design and Analysis of Algorithms': ['Computer Technology', 'Design and Analysis of Algorithms'], 'Marketing|Marketing Management': ['Marketing', 'Marketing Management'], 'Accounting|Partnership Accounting|Corporate Accounting|Accounting Theory And Practices': ['Accounting', 'Partnership Accounting', 'Corporate Accounting', 'Accounting Theory And Practices'], 'Legal Studies|Income Tax Laws': ['Legal Studies', 'Income Tax Laws'], 'Graphics|Articulation|Computer Creation': ['Graphics', 'Articulation', 'Computer Creation'], 'Archeology|Human Prehistory': ['Archeology', 'Human Prehistory'], 'Business|Start Ups|Entreperneurship|Business Strategies|Venture Capitalist|Business Planning': ['Business', 'Start Ups', 'Entreperneurship', 'Business Strategies', 'Venture Capitalist', 'Business Planning'], 'Geography|Indian Geography': ['Geography', 'Indian Geography'], 'E Commerce|Shopping Platform|Other Online Platforms|Digital India': ['E Commerce', 'Shopping Platform', 'Other Online Platforms', 'Digital India'], 'Business|Bio-entrepreneurship': ['Business', 'Bio-entrepreneurship'], 'Literature|Stories': ['Literature', 'Stories'], 'History|Indian History': ['History', 'Indian History'], 'ViDEO': ['ViDEO'], 'Management|Business Management': ['Management', 'Business Management'], 'Visual Arts|Photography': ['Visual Arts', 'Photography'], 'Social Work|Health Education': ['Social Work', 'Health Education'], 'Social Work|Social Tech': ['Social Work', 'Social Tech'], 'Social Work|Humanities': ['Social Work', 'Humanities'], 'Photography|Visual Arts': ['Photography', 'Visual Arts'], 'Accounting|Financial Accounting': ['Accounting', 'Financial Accounting'], 'Psycholgy|Social Psychology': ['Psycholgy', 'Social Psychology'], 'Photography|Conceptual': ['Photography', 'Conceptual'], 'Physics|Instrumentation': ['Physics', 'Instrumentation'], 'Craft work': ['Craft work'], 'Social Work|Social Interventions|Substance Abuse': ['Social Work', 'Social Interventions', 'Substance Abuse'], 'Economics|Indian Economy': ['Economics', 'Indian Economy'], 'Social Work|Substance Abuse|Social Interventions|Humanities': ['Social Work', 'Substance Abuse', 'Social Interventions', 'Humanities'], 'Social Work|Social Interventions|Substance Abuse|Health Education': ['Social Work', 'Social Interventions', 'Substance Abuse', 'Health Education'], 'Social Work|Humanities|Social Interventions': ['Social Work', 'Humanities', 'Social Interventions'], 'Finance|Financial Analysis': ['Finance', 'Financial Analysis'], 'Architecture': ['Architecture'], 'Photography|Architecture|Painting': ['Photography', 'Architecture', 'Painting'], 'Computer Technology|Cloud Computing|Artificial Intelligence|Information Technology|Programming languages': ['Computer Technology', 'Cloud Computing', 'Artificial Intelligence', 'Information Technology', 'Programming languages'], 'Computer Technology|Design and Analysis of Algorithms|Web designing|Database Management|Artificial Intelligence': ['Computer Technology', 'Design and Analysis of Algorithms', 'Web designing', 'Database Management', 'Artificial Intelligence'], 'Literature|Movements in Literature': ['Literature', 'Movements in Literature'], 'Physics|Atomic Physics|Energy Physics|Quantum Mecahnics|Instrumentation': ['Physics', 'Atomic Physics', 'Energy Physics', 'Quantum Mecahnics', 'Instrumentation'], 'Business|Business Strategies|Venture Capitalist': ['Business', 'Business Strategies', 'Venture Capitalist'], 'Photography|Architecture|Illustration': ['Photography', 'Architecture', 'Illustration'], 'Photography|Architecture': ['Photography', 'Architecture'], 'Human Rights|Fundamental Rights|Protection & Enforcement': ['Human Rights', 'Fundamental Rights', 'Protection & Enforcement'], 'Environment Studies|Pollution|Environmental Biology': ['Environment Studies', 'Pollution', 'Environmental Biology'], 'Photography|Conceptual|Illustration': ['Photography', 'Conceptual', 'Illustration'], 'Physics|Quantum Mecahnics|Industrial Instrumentation|Atomic Physics|Nuclear & Particle Physics|Energy Physics': ['Physics', 'Quantum Mecahnics', 'Industrial Instrumentation', 'Atomic Physics', 'Nuclear & Particle Physics', 'Energy Physics'], 'Biotechnology|Environmental Biotechnology': ['Biotechnology', 'Environmental Biotechnology'], 'Legal Studies|Alternate Dispute Resolution|International Treaties|International Agreement': ['Legal Studies', 'Alternate Dispute Resolution', 'International Treaties', 'International Agreement'], 'Marketing|Principles Of Marketing|Marketing Research Methadology|Marketing Management|International Marketing': ['Marketing', 'Principles Of Marketing', 'Marketing Research Methadology', 'Marketing Management', 'International Marketing'], 'Sculptures': ['Sculptures'], 'Psycholgy|Child Development': ['Psycholgy', 'Child Development'], 'Economics|Economic Policies|Break even Point|Foreign Economy': ['Economics', 'Economic Policies', 'Break even Point', 'Foreign Economy'], 'Psycholgy|Psychological Growth': ['Psycholgy', 'Psychological Growth'], 'Management|Business Management|Technology Mangement|Managerial Activity|Creative And Lateral Management': ['Management', 'Business Management', 'Technology Mangement', 'Managerial Activity', 'Creative And Lateral Management'], 'Business': ['Business'], 'Business|Business Strategies|Business Enviorment|New Venture Planning|Foreign Business|Business Organisation': ['Business', 'Business Strategies', 'Business Enviorment', 'New Venture Planning', 'Foreign Business', 'Business Organisation'], 'Marketing|Principles Of Marketing|International Marketing|Promotion And Distribution Decisions': ['Marketing', 'Principles Of Marketing', 'International Marketing', 'Promotion And Distribution Decisions'], 'Social Work|NGO': ['Social Work', 'NGO'], 'Fine Arts|Painting': ['Fine Arts', 'Painting'], 'Legal Studies|Legal System|Legal Tradition|Nationality Law|Government Law': ['Legal Studies', 'Legal System', 'Legal Tradition', 'Nationality Law', 'Government Law'], 'Business|Entreperneurship|Venture Capitalist|Business Enviorment|Start Ups|Business Planning|New Venture Planning': ['Business', 'Entreperneurship', 'Venture Capitalist', 'Business Enviorment', 'Start Ups', 'Business Planning', 'New Venture Planning'], 'Legal Studies|Company Law|Legal System|Banking Law': ['Legal Studies', 'Company Law', 'Legal System', 'Banking Law'], 'Computer Technology|Web designing|Artificial Intelligence|Computer Application|Machine Learning|Frontend Development': ['Computer Technology', 'Web designing', 'Artificial Intelligence', 'Computer Application', 'Machine Learning', 'Frontend Development'], 'Music': ['Music'], 'Sculptures|Wood Crafts|Craft|Wood carving': ['Sculptures', 'Wood Crafts', 'Craft', 'Wood carving'], 'Fashion Design': ['Fashion Design'], 'Painting|Craft|Artistic design': ['Painting', 'Craft', 'Artistic design'], '2D Composition|Watercolours|Painting': ['2D Composition', 'Watercolours', 'Painting'], 'Painting|Watercolours|2D Composition': ['Painting', 'Watercolours', '2D Composition'], 'Visual Arts|Craft|Conceptual': ['Visual Arts', 'Craft', 'Conceptual'], 'Painting|Visual Arts|Craft|Conceptual': ['Painting', 'Visual Arts', 'Craft', 'Conceptual'], 'Painting|Craft|Mixed Media|2D Composition': ['Painting', 'Craft', 'Mixed Media', '2D Composition'], 'Visual Arts|Craft|Mixed Media|Conceptual|Mosaic painting': ['Visual Arts', 'Craft', 'Mixed Media', 'Conceptual', 'Mosaic painting'], 'Craft|Drawings|Conceptual|2D Composition': ['Craft', 'Drawings', 'Conceptual', '2D Composition'], 'Craft|Mixed Media|Conceptual|Mosaic painting|2D Composition': ['Craft', 'Mixed Media', 'Conceptual', 'Mosaic painting', '2D Composition'], 'Video': ['Video'], 'Fashion Desigining|Fashion Illustration|Pattern Cutting|Fashion Communication': ['Fashion Desigining', 'Fashion Illustration', 'Pattern Cutting', 'Fashion Communication'], 'Biotechnology|Animal Biotechnology': ['Biotechnology', 'Animal Biotechnology'], 'Fashion Desigining|Pattern & Culture|Fashion Trends|Fashion Portfoilio': ['Fashion Desigining', 'Pattern & Culture', 'Fashion Trends', 'Fashion Portfoilio'], 'Sketch Video': ['Sketch Video'], 'Fashion Desigining|Pattern & Culture|Fashion Textile|Fashion Trends': ['Fashion Desigining', 'Pattern & Culture', 'Fashion Textile', 'Fashion Trends'], 'Test': ['Test'], 'Professionalism': ['Professionalism'], 'Art': ['Art'], 'Science;Technology': ['Science;Technology'], 'Art; Science': ['Art; Science'], 'Fashion Design|Illustration|Watercolours|Drawings': ['Fashion Design', 'Illustration', 'Watercolours', 'Drawings'], 'Drawings|Fashion Design|Illustration|Watercolours': ['Drawings', 'Fashion Design', 'Illustration', 'Watercolours'], 'Fashion Design|Illustration|Watercolours': ['Fashion Design', 'Illustration', 'Watercolours'], 'Drawings|Fashion Design|Mixed Media|Conceptual|Illustration|Pen and ink|Watercolours': ['Drawings', 'Fashion Design', 'Mixed Media', 'Conceptual', 'Illustration', 'Pen and ink', 'Watercolours'], 'Fashion Design|Illustration|Conceptual|Watercolours|Pen and ink': ['Fashion Design', 'Illustration', 'Conceptual', 'Watercolours', 'Pen and ink'], 'Artistic design|Logo Design|Graphic|Illustration': ['Artistic design', 'Logo Design', 'Graphic', 'Illustration'], 'Visual Arts|Graphic Design|Artistic design|Graphic|Illustration': ['Visual Arts', 'Graphic Design', 'Artistic design', 'Graphic', 'Illustration'], 'Learning': ['Learning'], 'Photography|Architecture|Visual Arts|Graphic Design': ['Photography', 'Architecture', 'Visual Arts', 'Graphic Design'], 'Photography|Architecture|Visual Arts|Graphic Design|Artistic design|Graphic|Logo Design': ['Photography', 'Architecture', 'Visual Arts', 'Graphic Design', 'Artistic design', 'Graphic', 'Logo Design'], 'Visual Arts|Graphic Design|2D Composition|Logo Design': ['Visual Arts', 'Graphic Design', '2D Composition', 'Logo Design'], 'Artistic design': ['Artistic design'], 'Literature|Stories|Fictions|Movements in Literature': ['Literature', 'Stories', 'Fictions', 'Movements in Literature'], 'Technology': ['Technology'], 'Computer Technology|Computation|Computer Application|Cloud Computing': ['Computer Technology', 'Computation', 'Computer Application', 'Cloud Computing'], 'Visual Arts|Calligraphy|Pen and ink': ['Visual Arts', 'Calligraphy', 'Pen and ink'], 'Mixed Media|Calligraphy|Pen and ink': ['Mixed Media', 'Calligraphy', 'Pen and ink'], 'Typography|Pen and ink': ['Typography', 'Pen and ink'], 'Typography|Calligraphy|Pen and ink': ['Typography', 'Calligraphy', 'Pen and ink'], 'Calligraphy|Typography|Pen and ink': ['Calligraphy', 'Typography', 'Pen and ink'], 'Calligraphy|Pen and ink': ['Calligraphy', 'Pen and ink'], 'Mass Media|Media And Society': ['Mass Media', 'Media And Society'], 'Science; Technology': ['Science; Technology']} ###Markdown **Now lets update posts_df** ###Code # we will prepare a list which will store all the new rows and # column values for now updated_data = [] for i in categories: # create a dummy dataframe which will store row values for the current # category dummy = posts_df[posts_df['category']==i] id = dummy['_id'].values[0] title = dummy['title'].values[0] post_type = dummy[' post_type'].values[0] for j in categories[i]: # now we will create a dictionary which will store the row values of the # main category and will be assigned to all of its splitted category dict1 = {} dict1.update({'_id':id}) dict1.update({'title':title}) dict1.update({'category':j}) dict1.update({' post_type':post_type}) updated_data.append(dict1) posts_df_updated = pd.DataFrame(updated_data) ###Output _____no_output_____ ###Markdown **now lets check updated posts_df** ###Code posts_df_updated.loc[:, ['_id', 'category', ' post_type']].head() posts_df.loc[:, ['_id', 'category', ' post_type']].head() posts_df_updated.describe() ###Output _____no_output_____ ###Markdown **As we can see we have successfully created our posts dataframe now we will merge the dataframes** MERGING OF THE DATAFRAMES **We will merge views_df and posts_df_updated dataframes as they conatin all the columns and data that we will need for our recommendation system** ###Code views_df.columns posts_df_updated.columns ###Output _____no_output_____ ###Markdown **As we know for merging we need a common column and post_id is the column in the both dataframes but we have to rename one of them to perform the merge operation****We will change rename _id to post id in the posts_df_updated column** ###Code # using pd.rename function to rename _id to post_id posts_df_updated.rename(columns={'_id':'post_id'}, inplace=True) posts_df_updated.columns # using pd.merge function to merge two dataframes main_df = pd.merge(views_df, posts_df_updated) main_df.columns main_df.head(10) main_df.tail(20) main_df.describe() ###Output _____no_output_____ ###Markdown **Now the merging is done and we have our actuall dataframe to work on now lets move to the nect step which is filtering using Collaborative Filtering** **Collaborative Filtering** **So we are using user-user collaberative filtering. And we are using cosine similarity to determine the similarity between users. For that we need to build a matrix. categories will be the columns and user_ids will be the rows. And we are using K near neighbour model to determine the similar users.** CONSTRUCTING THE MATRIX **We will create a sparse matrix of mXn. All the unique categories will be the column values and user_ids will be the row value. And the cell values will be the number times a user has viwed a category. The higher the cell value the higher the users interest for that particular category** **Lets find all the unique user_ids and categories** ###Code users = list(main_df['user_id'].unique()) len(users) categories = list(main_df['category'].unique()) len(categories) ###Output _____no_output_____ ###Markdown **Our matrix size will be of size 88X234** ###Code # craeting the matrix user_mat = [[] for i in range(len(users))] for i in range(len(users)): for j in range(len(categories)): # finding how many rows present with current user_id and current # category value = len(main_df[ (main_df['user_id']==users[i])& (main_df['category']==categories[j]) ]) user_mat[i].append(value) for i in user_mat[0]: print(i, end=" ") ###Output 4 3 3 3 2 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 2 0 0 0 0 1 2 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ###Markdown **Now we will convert the list to a actual sparse matrix using scipy.sparse library** ###Code # importing csr_matrix from scipy.sparse from scipy.sparse import csr_matrix # for creating a sparse matrix user_mat = csr_matrix(user_mat) user_mat ###Output _____no_output_____ ###Markdown **As we have made our matrix lets train the model.** TRAINING THE MODEL **So we are using K nearest neighbour model. And the similarity constraint we are using is cosine similarity.** **Importing the model** ###Code # importing NearestNeighbors from sklearn.neighbors from sklearn.neighbors import NearestNeighbors # setting the parameters model_knn = NearestNeighbors( metric='cosine', algorithm='brute', n_neighbors=15) # fitting the model model_knn.fit(user_mat) ###Output _____no_output_____ ###Markdown CREATING A FUNCTION FOR RECOMMENDATION **We have trained our model. Now lets make a function which will take users_id as input and recommend categories that the user would like** ###Code # creating a function which will recommend us posts with argument as # user_id and other default arguments def recommender(user_id, data=user_mat, model=model_knn): model.fit(data) index = users.index(user_id) current_user = main_df[main_df['user_id']==user_id] distances, indices = model.kneighbors(data[index], 15) recomendation = [] for i in indices[0]: user = main_df[main_df['user_id']==users[i]] for i in user['category'].unique(): if i not in current_user['category'].unique(): recomendation.append(i) print(recomendation) print(indices) ###Output _____no_output_____ ###Markdown **What we did above there is first we found out 15 similar users for our current user and we recomended those posts to the user which he/she hasnot viewed yet but similar users have.Now lets test our function for a user** **Lets see what the system recomendation for the first user. But before that lets see the users categories that he has already viewed** ###Code main_df[main_df['user_id']==users[0]]['category'].unique() ###Output _____no_output_____ ###Markdown **These are the categories the user has viewed now lets see the recomendations for our user** ###Code recommender(users[0]) ###Output ['Fashion Portfoilio', 'Fashion Design', 'Watercolours', 'Drawings', 'Sketch Video', 'Political Science', 'Colonialism In India', 'Legal Studies', 'Labor Law', 'Banking', 'Banking Companies', 'Professionalism', 'Fashion Portfoilio', 'Painting', 'Craft', 'Technology', 'Drawings', 'Business', 'Learning', 'Literature', 'Stories', 'Fictions', 'Movements in Literature', 'Fashion Portfoilio', 'Business Strategies', 'Business Enviorment', 'New Venture Planning', 'Foreign Business', 'Business Organisation', 'Fashion Design', 'Watercolours', 'Conceptual', 'Pen and ink', 'Mixed Media', '2D Composition', 'Communication', 'Basics of Communiaction', 'Sketch Video', 'Professionalism', 'Biotechnology', 'Molecular Biology', 'Fine Arts', 'Painting', 'Management', 'Business Management', 'Technology Mangement', 'Managerial Activity', 'Creative And Lateral Management', 'Economics', 'Economic Policies', 'Break even Point', 'Foreign Economy', 'Computer Technology', 'Operating Systems', 'Fashion Manufacturing', 'Fashion Techniques', 'Garment Production', 'Garment Technology', 'Digital Marketing', 'Learning', 'Fashion Design', 'Watercolours', 'Drawings', 'Conceptual', 'Pen and ink', 'Mixed Media', 'Political Science', 'Colonialism In India', 'Legal Studies', 'Labor Law', 'Banking', 'Banking Companies', 'Auditing', 'Statuary Audit', 'Legal System', 'Sports Coaching', 'Sports Law', 'Taxation', 'Custom Laws', 'Economics', 'Revenue Concept', 'Human Rights', 'Rights and Duties', 'Sociology', 'Sociology of Religion', 'Sociology in India', 'International Politics', 'Mass Media', 'Videography', 'Biotechnology', 'Plant Biotechnology', 'Painting', 'Technology', 'Digital Marketing', 'Business', 'Learning', 'Literature', 'Stories', 'Fictions', 'Movements in Literature', 'Business Strategies', 'Business Enviorment', 'New Venture Planning', 'Foreign Business', 'Business Organisation', 'Conceptual', 'Fashion Design', 'Watercolours', 'Drawings', 'Pen and ink', 'Mixed Media', '2D Composition', 'Sketch Video', 'Professionalism', 'Philosophy', 'Public Philosophy', 'Test', 'Applied Ethics', 'Entreperneurship', 'Venture Capitalist', 'Start Ups', 'Business Planning', 'Painting', 'Prints', 'Biotechnology', 'Animal Biotechnology', 'Craft', 'Mosaic painting', 'Social Work', 'Humanities', 'Social Interventions', 'Sculptures', 'Marketing', 'Principles Of Marketing', 'Marketing Research Methadology', 'Marketing Management', 'International Marketing', 'Music', 'Fine Arts', 'Promotion And Distribution Decisions', 'Video', 'Legal Studies', 'Legal System', 'Legal Tradition', 'Nationality Law', 'Government Law', 'Plant Biotechnology', 'Management', 'Business Management', 'Technology Mangement', 'Managerial Activity', 'Creative And Lateral Management', 'Human Rights', 'Fundamental Rights', 'Protection & Enforcement', 'NGO', 'Graphics', 'Articulation', 'Computer Creation', 'Psycholgy', 'Psychological Growth', 'Physics', 'Quantum Mecahnics', 'Industrial Instrumentation', 'Atomic Physics', 'Nuclear & Particle Physics', 'Energy Physics', 'Substance Abuse', 'Environmental Biotechnology', 'Computer Technology', 'Design and Analysis of Algorithms', 'Web designing', 'Database Management', 'Artificial Intelligence', 'Health Education', 'Social Psychology', 'Economics', 'Indian Economy', 'Instrumentation', 'Craft work', 'Acrylics', 'Accounting', 'Financial Accounting', 'ViDEO', 'Archeology', 'Human Prehistory', 'Mass Media', 'Videography', 'Sports Coaching', 'Sports Event', 'Machine Learning', 'Information Technology', 'Partnership Accounting', 'Corporate Accounting', 'Accounting Theory And Practices', 'Zoology', 'Environmental Biology', 'Physiology', 'Osteology', 'Education', 'Fashion Manufacturing', 'Fashion Techniques', 'Garment Production', 'Garment Technology', 'Political Science', 'Government and Politics', 'Gastroenterology', 'Cardiology', 'Logic', 'Human Resources', 'Performance In Organization', 'Robotics', 'Data Science', 'International Relations', 'Tapestry', 'Technology', 'Competition Laws', 'Digital Marketing', 'Fashion Portfoilio', 'Fashion Design', 'Conceptual', 'Painting', 'Craft', 'Biotechnology', 'Animal Biotechnology', 'Mixed Media', 'Mosaic painting', '2D Composition', 'Drawings', 'Sculptures', 'Wood Crafts', 'Wood carving', 'Watercolours', 'Ceramics', 'Music', 'Fine Arts', 'Legal Studies', 'Company Law', 'Legal System', 'Banking Law', 'Computer Technology', 'Web designing', 'Artificial Intelligence', 'Computer Application', 'Machine Learning', 'Frontend Development', 'Social Work', 'NGO', 'Graphics', 'Articulation', 'Computer Creation', 'Physics', 'Quantum Mecahnics', 'Industrial Instrumentation', 'Atomic Physics', 'Nuclear & Particle Physics', 'Energy Physics', 'Psycholgy', 'Child Development', 'Alternate Dispute Resolution', 'International Treaties', 'International Agreement', 'Economics', 'Economic Policies', 'Break even Point', 'Foreign Economy', 'Environment Studies', 'Pollution', 'Environmental Biology', 'Business', 'Business Organisation', 'Acrylics', 'ViDEO', 'E Commerce', 'Shopping Platform', 'Other Online Platforms', 'Digital India', 'Bio-entrepreneurship', 'History', 'Indian History', 'Income Tax Laws', 'Mass Media', 'Videography', 'Marketing', 'Marketing Management', 'Design and Analysis of Algorithms', 'Zoology', 'Education', 'Plant Biotechnology', 'Robotics', 'Data Science', 'Information Technology', 'Physiology', 'Radiology', 'Fashion Design', 'Watercolours', 'Drawings', 'Conceptual', 'Pen and ink', 'Mixed Media', 'Painting', 'Craft', 'Mosaic painting', '2D Composition', 'Sculptures', 'Wood Crafts', 'Wood carving', 'Ceramics', 'Fine Arts', 'Fashion Manufacturing', 'Fashion Techniques', 'Garment Production', 'Garment Technology', 'Technology', 'Fashion Design', 'Watercolours', 'Drawings', 'Conceptual', 'Pen and ink', 'Mixed Media', 'Computer Technology', 'Cloud Computing', 'Human Rights', 'Fundamental Rights', 'Biotechnology', 'Plant Biotechnology', 'Mass Media', 'Indian Government', 'Fashion Design', 'Watercolours', 'Drawings', 'Conceptual', 'Pen and ink', 'Mixed Media', 'Physiology', 'Radiology', 'Drawings', 'Painting', 'Watercolours', 'Acrylics', 'Human Resources', 'Performance In Organization', 'Organizational Behaviour', 'HR Management'] [[ 0 1 2 32 3 42 8 15 16 73 37 4 6 75 70]] ###Markdown **NOTE: We are suggesting what are the new categories the user would like we can also modify the recommend function to suggest Posts also.** **Looks like the system is suggesting posts of users interest and also some new categories for the user.****The List below suggests the similar users to the current user.** **So This ends our Collaborative Filtering. Lets move on to Content based filtering** CONTENT BASED FILTERING **Now for content based filtering we will prepare item profiles for each category and user profile for each user.** PREPARING ITEM-PROFILES **We have got 234 unique categories. Each category will have its own item-profile. These item-profiles are vectors of length equal to number of posts we have and it will contain binary values depending upon whether the category is present in a post or not.** ###Code main_df['post_id'].describe() ###Output _____no_output_____ ###Markdown **We will have 234 vectors, each of length 231 containing 0s and 1s** ###Code import numpy as np # Lets create a list which will contain all the posts posts = list(main_df['post_id'].unique()) # Create a dictionary which will store each category as key and their item-profile vector as value item_profiles = {} # filling item_profiles for i in categories: item_profiles.update({i:[]}) for j in posts: item_profiles[i].append(1) if i in list(main_df[main_df['post_id']==j]['category'].unique()) else item_profiles[i].append(0) # converting lists to vectors or arrays for i in item_profiles: item_profiles[i] = np.array(item_profiles[i]) for i in item_profiles: print(i, item_profiles[i]) ###Output Visual Arts [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 1 0 0 1 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0] Graphic Design [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0] Artistic design [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0] Graphic [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Illustration [1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0] Science; Technology [0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Computer Technology [0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 1 0 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0] Computation [0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Computer Application [0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Cloud Computing [0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Technology [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Calligraphy [0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0] Typography [0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Pen and ink [0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Mixed Media [0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Mass Media [0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0] Media And Society [0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Competition Laws [0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Drawings [0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0] Marketing [0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Advertising [0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Promotion And Distribution Decisions [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Digital Marketing [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Business [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Learning [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Photography [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0] Architecture [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Logo Design [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Literature [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Stories [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fictions [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Movements in Literature [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Art; Science [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fashion Desigining [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Pattern & Culture [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fashion Trends [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fashion Portfoilio [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Video editing [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Business Strategies [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Business Enviorment [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] New Venture Planning [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Foreign Business [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Business Organisation [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Conceptual [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0] Fashion Design [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Watercolours [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0] Operating Systems [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 2D Composition [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Science;Technology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Information Technology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0] Hardware [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Drawing [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Communication [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Basics of Communiaction [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Sketch Video [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Political Science [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0] Colonialism In India [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Legal Studies [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Labor Law [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Banking [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Banking Companies [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Auditing [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Statuary Audit [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Legal System [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Sports Coaching [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Sports Law [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Taxation [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Custom Laws [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Economics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Revenue Concept [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Human Rights [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Rights and Duties [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Sociology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Sociology of Religion [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Sociology in India [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] International Politics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Internal Financial Control [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Internal Audit [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Audit Evidence [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] GST [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Direct Tax [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Secratarial Audit [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Banking Technology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Audit Remark [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Cost Audit [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Economics Sociology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Professionalism [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fashion Textile [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fashion Illustration [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Pattern Cutting [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fashion Communication [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Programming languages [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Art [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Philosophy [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0] Public Philosophy [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Test [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Applied Ethics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Painting [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0] Craft [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Entreperneurship [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Venture Capitalist [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Start Ups [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Business Planning [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Prints [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Biotechnology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Animal Biotechnology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Mosaic painting [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Social Work [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Humanities [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Social Interventions [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Business Skills [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Inorganic Chemistry [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Sculptures [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Principles Of Marketing [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Marketing Research Methadology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Marketing Management [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] International Marketing [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Molecular Biology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Wood Crafts [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Wood carving [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Ceramics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Music [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fine Arts [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Electronics & electrical Technology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Electrical Machines [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] HR Management [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Mathematics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Linear Algebra [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Human Resources [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0] Video [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Legal Tradition [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Nationality Law [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Government Law [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Company Law [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Banking Law [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Web designing [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Artificial Intelligence [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0] Machine Learning [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Frontend Development [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Plant Biotechnology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Management [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Business Management [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Technology Mangement [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Managerial Activity [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Creative And Lateral Management [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fundamental Rights [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Protection & Enforcement [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] NGO [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Eco System [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Graphics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Articulation [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Computer Creation [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Psycholgy [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Psychological Growth [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Physics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Quantum Mecahnics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Industrial Instrumentation [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Atomic Physics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Nuclear & Particle Physics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Energy Physics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Substance Abuse [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Zoology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Ecology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Physiology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0] Cardiology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0] Child Development [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Political Thought [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Alternate Dispute Resolution [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] International Treaties [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] International Agreement [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Geography [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Physical Geography [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Genetic Engineering [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Economic Policies [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Break even Point [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Foreign Economy [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Corporate Social Responsibilities [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Environment Studies [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Pollution [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Environmental Biology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Team Mangememnt [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Environmental Biotechnology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Indian Geography [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Design and Analysis of Algorithms [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Database Management [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Instrumentation [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Finance [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Financial Analysis [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Health Education [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Social Psychology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Indian Economy [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Craft work [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Acrylics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Accounting [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Financial Accounting [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ViDEO [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Performance In Organization [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0] Organizational Behaviour [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Social Tech [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Radiology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] E Commerce [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Shopping Platform [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Other Online Platforms [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Digital India [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Bio-entrepreneurship [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] History [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Indian History [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Archeology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Human Prehistory [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Income Tax Laws [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Videography [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Sports Event [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Partnership Accounting [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Corporate Accounting [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Accounting Theory And Practices [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] E Transactions [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Mobile Applications [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Osteology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Education [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fashion Manufacturing [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fashion Techniques [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Garment Production [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Garment Technology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Fundamental Of Accounting [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Indian Government [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Data Science [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0] Government and Politics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0] Gastroenterology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0] Logic [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0] Robotics [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0] Neurology [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0] Empowerment [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0] International Relations [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0] Tapestry [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1] ###Markdown PREPARING THE USER-PROFILE **We will prepare the user profile from the item profiles that we have already prepared. Lets say a user has viewed posts which have n different categories and let I1,I2....In be their item-profiles. User profile for a user will be equal to the weghited average of the profiles. For the weight calculation we will divide the number of times a category has appeared in all the posts the user have viewed by the total number of pots the user has viewed.** ###Code # we will create a dictionary user_id as key and user_profile as value user_profiles = {} # Filling the user_profiles for i in users: user_profiles.update({i:[]}) # finding the current user current_user = main_df[main_df['user_id']==i] # listing all the categories the user has viewed current_user_categories = list(current_user['category'].unique()) # Listing all the posts the user has viewed current_user_post = list(current_user['post_id'].unique()) # Now we will find the weights for each category in the current_user_categories # create a dictionary category as key and their weight as value category_weight = {} # create a dummy vector which will store the final vector for the user profile of length equal to posts result_vector = np.array([0 for i in range(len(posts))]) for j in current_user_categories: category_weight.update({j:0}) # Now count how many times j has appeared for k in list(current_user['category']): if j==k: category_weight[j]+=1 # Now divide it with the length of the current_user_post category_weight[j] = category_weight[j]/len(current_user_post) # Now we have calculated our weights, Now we will calculate user-profile result_vector = result_vector+ (category_weight[j]*item_profiles[j]) user_profiles[i] = result_vector/len(current_user_post) for i in user_profiles: if i in users[0:5]: print(i, user_profiles[i]) print() ###Output 5df49b32cc709107827fb3c7 [0.12396694 0. 0. 0. 0.00826446 0.00826446 0. 0.00826446 0.00826446 0. 0. 0. 0. 0. 0. 0. 0. 0.04132231 0. 0.15702479 0. 0.00826446 0.09090909 0.02479339 0.03305785 0. 0. 0.02479339 0.01652893 0.01652893 0.01652893 0.01652893 0. 0.05785124 0.07438017 0. 0.00826446 0. 0. 0. 0. 0. 0.08264463 0.01652893 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.04132231 0.04132231 0. 0.00826446 0. 0. 0. 0.02479339 0.00826446 0. 0.07438017 0. 0. 0.03305785 0. 0. 0. 0. 0.09917355 0. 0.09917355 0. 0. 0.03305785 0.03305785 0. 0. 0.02479339 0.02479339 0. 0. 0. 0. 0.03305785 0.02479339 0.12396694 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.01652893 0.03305785 0. 0. 0. 0. 0.03305785 0. 0.04958678 0.03305785 0.04958678 0. 0. 0. 0. 0. 0.01652893 0. 0. 0. 0. 0. 0.05785124 0.04958678 0. 0. 0. 0. 0.04958678 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.05785124 0. 0. 0. 0. 0. 0. 0. 0.02479339 0. 0. 0. 0.04132231 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.02479339 0. 0. 0.02479339 0. 0. 0. 0. 0. 0. 0.09917355 0. 0. 0.00826446 0. 0. 0. 0.01652893 0. 0. ] 5ec3ba5374f7660d73aa1201 [0.0625 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.0078125 0. 0. 0. 0. 0. 0.01171875 0. 0.0703125 0. 0.00390625 0.0390625 0.01171875 0.03125 0. 0. 0.01171875 0.03125 0.0390625 0.03125 0.0390625 0. 0.03125 0.03125 0. 0.00390625 0. 0. 0. 0. 0.00390625 0.046875 0.0390625 0.0078125 0.0078125 0.0078125 0. 0.00390625 0. 0. 0. 0. 0. 0. 0.00390625 0. 0. 0. 0. 0. 0. 0.00390625 0. 0. 0. 0.00390625 0.03125 0.0234375 0. 0. 0. 0. 0. 0.01171875 0. 0. 0.046875 0. 0. 0.01171875 0.0078125 0. 0. 0. 0.05078125 0.0078125 0.05078125 0. 0. 0.01171875 0.01171875 0. 0. 0.01171875 0.01171875 0. 0.0078125 0.0078125 0.0078125 0.01171875 0.01953125 0.0703125 0. 0. 0. 0. 0. 0. 0. 0. 0.00390625 0.00390625 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.00390625 0.00390625 0. 0. 0. 0. 0. 0. 0.0078125 0.0234375 0. 0. 0. 0. 0.015625 0. 0.03125 0.015625 0.0234375 0. 0. 0. 0. 0. 0.0078125 0. 0. 0. 0. 0. 0.0390625 0.01953125 0. 0. 0. 0. 0.01953125 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.00390625 0. 0. 0. 0. 0. 0.015625 0. 0.0234375 0. 0. 0. 0. 0. 0. 0. 0.01953125 0. 0. 0. 0.03515625 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.015625 0. 0. 0.015625 0. 0. 0.01171875 0. 0. 0.00390625 0. 0. 0.0078125 0.05859375 0. 0. 0.0078125 0. 0. 0. 0.0078125 0. 0. ] 5ec2204374f7660d73aa100f [5. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 4. 0. 0. 2. 1. 0. 0. 0. 1. 1. 1. 1. 1. 0. 2. 2. 0. 0. 0. 0. 0. 0. 0. 3. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 3. 0. 0. 1. 0. 0. 0. 0. 3. 0. 4. 0. 0. 1. 1. 0. 0. 1. 1. 0. 0. 0. 0. 1. 1. 5. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 1. 0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 2. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 2. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 4. 0. 0. 0. 0. 0. 0. 0. 0. 0.] 5d7c994d5720533e15c3b1e9 [0.02444444 0. 0.00111111 0.00111111 0.00222222 0.00222222 0.00222222 0.00333333 0.00222222 0. 0. 0.00444444 0.00111111 0. 0. 0. 0.00222222 0.00777778 0.00111111 0.02555556 0.00444444 0.00111111 0.01444444 0.00444444 0.00888889 0. 0.00777778 0.00777778 0.01666667 0.02111111 0.02222222 0.02777778 0.00222222 0.01888889 0.01444444 0.00111111 0.00111111 0.00111111 0.00111111 0. 0.00222222 0.00111111 0.01777778 0.02111111 0. 0. 0. 0. 0. 0. 0. 0.00111111 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.00111111 0.00111111 0.01 0.00333333 0.00111111 0.00111111 0. 0. 0. 0.00666667 0. 0.00444444 0.02333333 0.00111111 0.00555556 0.00555556 0.00888889 0. 0.00222222 0. 0.02222222 0.00666667 0.02 0. 0.00444444 0.01111111 0.01 0. 0.00222222 0.00444444 0.00444444 0. 0.00555556 0.00777778 0.00777778 0.00888889 0.01 0.03 0. 0.00444444 0. 0. 0. 0. 0. 0. 0. 0. 0.00111111 0. 0.00555556 0. 0. 0. 0.00111111 0. 0. 0. 0.00111111 0. 0. 0. 0. 0. 0. 0. 0. 0.00111111 0.00444444 0.00222222 0. 0.00111111 0.00222222 0.01222222 0.00111111 0. 0.00333333 0.00111111 0.00666667 0.00222222 0.01111111 0.00444444 0.00777778 0.00333333 0. 0. 0.00111111 0. 0.00555556 0. 0.00111111 0. 0. 0. 0.02111111 0.00777778 0. 0.00222222 0. 0. 0.00777778 0. 0. 0.00111111 0. 0. 0.00222222 0. 0. 0. 0.00333333 0.00222222 0. 0. 0. 0. 0.00222222 0.00444444 0.00888889 0. 0.01 0. 0. 0.00111111 0.00111111 0.00222222 0.00111111 0.00222222 0.00888889 0. 0. 0. 0.01555556 0.00111111 0.00111111 0. 0.00111111 0.00111111 0.00111111 0.00111111 0.00111111 0. 0.00111111 0.01111111 0. 0. 0.01 0.00111111 0. 0.00444444 0. 0.00111111 0. 0. 0. 0.00444444 0.02777778 0. 0.00111111 0.00444444 0. 0. 0. 0.00222222 0.00333333 0. ] 5de50d768eab6401affbb135 [0.11 0. 0.02 0.01 0.02 0.02 0.02 0.03 0.02 0.01 0. 0.02 0.01 0. 0. 0. 0. 0.03 0. 0.07 0. 0. 0.02 0.02 0. 0. 0. 0.03 0.11 0.13 0.15 0.18 0.01 0.08 0.03 0.02 0. 0.01 0.01 0. 0. 0. 0.1 0.13 0. 0. 0. 0. 0. 0. 0. 0. 0.01 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.01 0. 0. 0. 0. 0.02 0. 0. 0.09 0.01 0.03 0.01 0.04 0. 0. 0. 0.07 0.02 0.09 0. 0.01 0.03 0.04 0. 0.01 0.02 0.02 0. 0.03 0.03 0.03 0.03 0.05 0.14 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.01 0.01 0. 0.02 0. 0. 0. 0. 0. 0. 0.01 0. 0. 0. 0. 0. 0. 0. 0. 0.01 0. 0. 0. 0. 0. 0.07 0.01 0. 0. 0.01 0. 0. 0.05 0. 0.03 0. 0. 0. 0.02 0. 0.02 0. 0. 0. 0. 0. 0.08 0.01 0. 0. 0. 0. 0.01 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.01 0.02 0. 0.01 0.03 0.05 0. 0.02 0. 0. 0.01 0.01 0.02 0.01 0. 0.04 0. 0. 0. 0.09 0.01 0.01 0. 0.01 0.01 0.01 0.01 0.01 0. 0.01 0.05 0. 0. 0. 0.02 0. 0.01 0.02 0.01 0. 0. 0. 0.03 0.11 0. 0.01 0.02 0. 0. 0.01 0. 0.02 0. ] ###Markdown **So we have successfully Calculated the user_profile and item_profile.** CREATING A FUNCTION FOR RECOMMENDATION **In this Section we will find the cosine similarity between a user and the categoroies, the higher the cosine value the higher will be the similarity** ###Code # to find the cosine similarity we need to import cosine_similarity function from sklearn.metrics.pairwise import cosine_similarity # we will create a function which will take user_id as argument and will provide recomendation # all other arguments will be set to some default values. def recommender1(user_id, user_profiles = user_profiles, item_profiles=item_profiles): # calculate the cosine similiraity between the item-profile of all categories and the users user-profile # create a dictionary category as key and cosine value as the value similarity = {} for i in item_profiles: similarity.update({i:cosine_similarity(user_profiles[user_id].reshape(1, -1), item_profiles[i].reshape(1, -1))}) # as we have found the similarity now we will sort it and show the user the posts of the top categories and which the user # hasnot viewed yet sorted_similarity = sorted(similarity.items(), key=lambda x: x[1], reverse=True) # now we will filter those posts that the user hasnot viewed user_posts = list(main_df[main_df['user_id']==user_id]['post_id'].unique()) # create recomendation list recommendations = [] # displaying users viewed posts and categories print("posts user has viewed:{}".format(user_posts)) print("users viewed categories:{}".format(list(main_df[main_df['user_id']==user_id]['category'].unique()))) for i in sorted_similarity: category_posts = list(main_df[main_df['category']==i[0]]['post_id'].unique()) for j in category_posts: if j not in user_posts: recommendations.append([i[0], j]) # we will recommend top 20 posts to the user if len(recommendations)==20: break for i in recommendations: print(i) recommender1(users[30]) ###Output posts user has viewed:['5ea7cd9610426255a7aa9bd2'] users viewed categories:['Business'] ['Business', '5ea80a7e10426255a7aa9be2'] ['Business', '5eadc2f710426255a7aa9ee4'] ['Business', '5e4d359cf5561b1994c8e424'] ['Business', '5e6eff8aed32a005135d6bb8'] ['Business', '5e830dc8a3258347b42f23fb'] ['Business', '5e978c7ca3258347b42f2b09'] ['Business', '5e9028cea3258347b42f2736'] ['Business', '5e8e13dca3258347b42f26f2'] ['Business Strategies', '5ea80a7e10426255a7aa9be2'] ['Business Strategies', '5e978c7ca3258347b42f2b09'] ['Business Strategies', '5e8e13dca3258347b42f26f2'] ['Venture Capitalist', '5eadc2f710426255a7aa9ee4'] ['Venture Capitalist', '5e978c7ca3258347b42f2b09'] ['Venture Capitalist', '5e8e13dca3258347b42f26f2'] ['Business Enviorment', '5ea80a7e10426255a7aa9be2'] ['Business Enviorment', '5eadc2f710426255a7aa9ee4'] ['New Venture Planning', '5ea80a7e10426255a7aa9be2'] ['New Venture Planning', '5eadc2f710426255a7aa9ee4'] ['Business Organisation', '5ea80a7e10426255a7aa9be2'] ['Business Organisation', '5e830dc8a3258347b42f23fb'] ###Markdown NEW ###Code # 功能性函数 # searchCode() 用于搜寻股票代码 def searchCode(): isDone = False print('+--------------输入想要查找的板块名--------------+') while isDone == False: user_input = str(input('搜索板块名:')) if user_input == 'quit': print('用户已取消操作!') break try: print(user_input + '代码是:' + name_dict[user_input]) isDone = True except KeyError: print('板块不存在!') # 重启UI (待议) user_interface(SELECTED_DATA) # printAllBankuai() def printAllBankuai(): print('----------------以下是所有板块代码----------------') element_list = [(k, codename_dict[k]) for k in sorted(codename_dict.keys())] counter = 0 while counter < len(element_list): print(element_list[counter][0] + ' - ' + element_list[counter][1]) counter += 1 print('-----------------------------------------------') # 重启UI user_interface(SELECTED_DATA) def showAllSelected(): print(SELECTED_DATA) if SELECTED_DATA[0]['name'] != '数据不存在': SELECTED_DATA.show() else: print('没有分析完成的数据!') user_interface(SELECTED_DATA) # 用于加载SFrame (也许需要写一个return 待议) def parseSFrame(): fileName = input('输入文件名:') filePath = './SelectedData/' + fileName + '/' SELECTED_DATA = tc.SFrame(data=filePath) user_interface(SELECTED_DATA) def user_interface(xuangu): choice = greetings() if choice == 'a': xuangu = inputCode(xuangu) return xuangu elif choice == 's': searchCode() elif choice == 'l': printAllBankuai() elif choice == 'x': showAllSelected() elif choice == 'j': parseSFrame() else: user_interface(SELECTED_DATA) return xuangu ###Output _____no_output_____
wordnet.ipynb
###Markdown Sample usage for wordnet WordNet Interface WordNet is just another NLTK corpus reader, and can be imported like this: ###Code from nltk.corpus import wordnet as wn wn.synsets('dog') wn.synsets('dog', pos=wn.VERB) wn.synset('dog.n.01') print(wn.synset('dog.n.01').definition()) len(wn.synset('dog.n.01').examples()) print(wn.synset('dog.n.01').examples()[0]) wn.synset('dog.n.01').lemmas() [str(lemma.name()) for lemma in wn.synset('dog.n.01').lemmas()] wn.lemma('dog.n.01.dog').synset() sorted(wn.langs()) wn.synsets(b'\xe7\x8a\xac'.decode('utf-8'), lang='jpn') wn.synset('dog.n.01').lemma_names('ita') wn.lemmas('cane', lang='ita') sorted(wn.synset('dog.n.01').lemmas('dan')) sorted(wn.synset("dog.n.01").lemmas("por")) dog_lemma = wn.lemma(b'dog.n.01.c\xc3\xa3o'.decode('utf-8'), lang='por') dog_lemma dog_lemma.lang() len(list(wn.all_lemma_names(pos='n', lang='jpn'))) dog = wn.synset('dog.n.01') dog.hypernyms() dog.hyponyms() dog.member_holonyms() dog.root_hypernyms() wn.synset('dog.n.01').lowest_common_hypernyms(wn.synset('cat.n.01')) good = wn.synset('good.a.01') good.antonyms() good.lemmas()[0].antonyms() wn.synset_from_pos_and_offset('n', 4543158) eat = wn.lemma('eat.v.03.eat') eat print(eat.key()) eat.count() wn.lemma_from_key(eat.key()) wn.lemma_from_key(eat.key()).synset() wn.lemma_from_key('feebleminded%5:00:00:retarded:00') for lemma in wn.synset('eat.v.03').lemmas(): print(lemma, lemma.count()) for lemma in wn.lemmas('eat', 'v'): print(lemma, lemma.count()) ###Output Lemma('eat.v.01.eat') 61 Lemma('eat.v.02.eat') 13 Lemma('feed.v.06.eat') 4 Lemma('eat.v.04.eat') 0 Lemma('consume.v.05.eat') 0 Lemma('corrode.v.01.eat') 0
Moon Data/Moon_Classification_Exercise.ipynb
###Markdown Moon Data ClassificationIn this notebook, you'll be tasked with building and deploying a **custom model** in SageMaker. Specifically, you'll define and train a custom, PyTorch neural network to create a binary classifier for data that is separated into two classes; the data looks like two moon shapes when it is displayed, and is often referred to as **moon data**.The notebook will be broken down into a few steps:* Generating the moon data* Loading it into an S3 bucket* Defining a PyTorch binary classifier* Completing a training script* Training and deploying the custom model* Evaluating its performanceBeing able to train and deploy custom models is a really useful skill to have. Especially in applications that may not be easily solved by traditional algorithms like a LinearLearner.--- Load in required libraries, below. ###Code # data import pandas as pd import numpy as np from sklearn.datasets import make_moons from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt %matplotlib inline ###Output _____no_output_____ ###Markdown Generating Moon DataBelow, I have written code to generate some moon data, using sklearn's [make_moons](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html) and [train_test_split](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html).I'm specifying the number of data points and a noise parameter to use for generation. Then, displaying the resulting data. ###Code # set data params np.random.seed(0) num_pts = 600 noise_val = 0.25 # generate data # X = 2D points, Y = class labels (0 or 1) X, Y = make_moons(num_pts, noise=noise_val) # Split into test and training data X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=1) # plot # points are colored by class, Y_train # 0 labels = purple, 1 = yellow plt.figure(figsize=(8,5)) plt.scatter(X_train[:,0], X_train[:,1], c=Y_train) plt.title('Moon Data') plt.show() ###Output _____no_output_____ ###Markdown SageMaker ResourcesThe below cell stores the SageMaker session and role (for creating estimators and models), and creates a default S3 bucket. After creating this bucket, you can upload any locally stored data to S3. ###Code # sagemaker import boto3 import sagemaker from sagemaker import get_execution_role # SageMaker session and role sagemaker_session = sagemaker.Session() role = sagemaker.get_execution_role() # default S3 bucket bucket = sagemaker_session.default_bucket() ###Output _____no_output_____ ###Markdown EXERCISE: Create csv filesDefine a function that takes in x (features) and y (labels) and saves them to one `.csv` file at the path `data_dir/filename`. SageMaker expects `.csv` files to be in a certain format, according to the [documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html):> Amazon SageMaker requires that a CSV file doesn't have a header record and that the target variable is in the first column.It may be useful to use pandas to merge your features and labels into one DataFrame and then convert that into a `.csv` file. When you create a `.csv` file, make sure to set `header=False`, and `index=False` so you don't include anything extraneous, like column names, in the `.csv` file. ###Code import os def make_csv(x, y, filename, data_dir): '''Merges features and labels and converts them into one csv file with labels in the first column. :param x: Data features :param y: Data labels :param file_name: Name of csv file, ex. 'train.csv' :param data_dir: The directory where files will be saved ''' # make data dir, if it does not exist if not os.path.exists(data_dir): os.makedirs(data_dir) # your code here pd.concat([pd.DataFrame(y), pd.DataFrame(x)], axis = 1).to_csv(os.path.join(data_dir, filename), header = False, index = False) # nothing is returned, but a print statement indicates that the function has run print('Path created: '+str(data_dir)+'/'+str(filename)) ###Output _____no_output_____ ###Markdown The next cell runs the above function to create a `train.csv` file in a specified directory. ###Code data_dir = 'data_moon' # the folder we will use for storing data name = 'train.csv' # create 'train.csv' make_csv(X_train, Y_train, name, data_dir) ###Output Path created: data_moon/train.csv ###Markdown Upload Data to S3Upload locally-stored `train.csv` file to S3 by using `sagemaker_session.upload_data`. This function needs to know: where the data is saved locally, and where to upload in S3 (a bucket and prefix). ###Code # specify where to upload in S3 prefix = 'moon-data' # upload to S3 input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix) print(input_data) ###Output s3://sagemaker-us-east-1-441543649966/moon-data ###Markdown Check that you've uploaded the data, by printing the contents of the default bucket. ###Code # iterate through S3 objects and print contents for obj in boto3.resource('s3').Bucket(bucket).objects.all(): print(obj.key) ###Output _____no_output_____ ###Markdown --- ModelingNow that you've uploaded your training data, it's time to define and train a model!In this notebook, you'll define and train a **custom PyTorch model**; a neural network that performs binary classification. EXERCISE: Define a model in `model.py`To implement a custom classifier, the first thing you'll do is define a neural network. You've been give some starting code in the directory `source`, where you can find the file, `model.py`. You'll need to complete the class `SimpleNet`; specifying the layers of the neural network and its feedforward behavior. It may be helpful to review the [code for a 3-layer MLP](https://github.com/udacity/deep-learning-v2-pytorch/blob/master/convolutional-neural-networks/mnist-mlp/mnist_mlp_solution.ipynb).This model should be designed to: * Accept a number of `input_dim` features* Create some linear, hidden layers of a desired size* Return **a single output value** that indicates the class scoreThe returned output value should be a [sigmoid-activated](https://pytorch.org/docs/stable/nn.htmlsigmoid) class score; a value between 0-1 that can be rounded to get a predicted, class label.Below, you can use !pygmentize to display the code in the `model.py` file. Read through the code; all of your tasks are marked with TODO comments. You should navigate to the file, and complete the tasks to define a `SimpleNet`. ###Code !pygmentize source/model.py ###Output import torch import torch.nn as nn import torch.nn.functional as F ## TODO: Complete this classifier class SimpleNet(nn.Module): ## TODO: Define the init function def __init__(self, input_dim, hidden_dim, output_dim): '''Defines layers of a neural network.  :param input_dim: Number of input features  :param hidden_dim: Size of hidden layer(s)  :param output_dim: Number of outputs  ''' super(SimpleNet, self).__init__() # define all layers, here # fully connected layers self.fc_in = nn.Linear(input_dim, hidden_dim) self.fc_hidden = nn.Linear(hidden_dim, hidden_dim) self.fc_out = nn.Linear(hidden_dim, output_dim) # dropout layer self.drop = nn.Dropout(0.5) # Sigmoid layer for classification self.sig = nn.Sigmoid() ## TODO: Define the feedforward behavior of the network def forward(self, x): '''Feedforward behavior of the net.  :param x: A batch of input features  :return: A single, sigmoid activated value  ''' # your code, here # 10 hidden layers with a dropout layer between each x = F.relu(self.fc_in(x)) x = self.drop(x) for i in range(9): x = F.relu(self.fc_hidden(x)) x = self.drop(x) # last hidden layer with sigmoid activation for output x = self.fc_out(x) x = self.sig(x) return x ###Markdown Training ScriptTo implement a custom classifier, you'll also need to complete a `train.py` script. You can find this in the `source` directory.A typical training script:* Loads training data from a specified directory* Parses any training & model hyperparameters (ex. nodes in a neural network, training epochs, etc.)* Instantiates a model of your design, with any specified hyperparams* Trains that model* Finally, saves the model so that it can be hosted/deployed, later EXERCISE: Complete the `train.py` scriptMuch of the training script code is provided for you. Almost all of your work will be done in the if __name__ == '__main__': section. To complete the `train.py` file, you will:* Define any additional model training hyperparameters using `parser.add_argument`* Define a model in the if __name__ == '__main__': section* Train the model in that same sectionBelow, you can use !pygmentize to display an existing train.py file. Read through the code; all of your tasks are marked with TODO comments. ###Code !pygmentize source/train.py ###Output from __future__ import print_function # future proof import argparse import sys import os import json import pandas as pd # pytorch import torch import torch.nn as nn import torch.optim as optim import torch.utils.data # import model from model import SimpleNet def model_fn(model_dir): print("Loading model.") # First, load the parameters used to create the model. model_info = {} model_info_path = os.path.join(model_dir, 'model_info.pth') with open(model_info_path, 'rb') as f: model_info = torch.load(f) print("model_info: {}".format(model_info)) # Determine the device and construct the model. device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = SimpleNet(model_info['input_dim'], model_info['hidden_dim'], model_info['output_dim']) # Load the stored model parameters. model_path = os.path.join(model_dir, 'model.pth') with open(model_path, 'rb') as f: model.load_state_dict(torch.load(f)) return model.to(device) # Load the training data from a csv file def _get_train_loader(batch_size, data_dir): print("Get data loader.") # read in csv file train_data = pd.read_csv(os.path.join(data_dir, "train.csv"), header=None, names=None) # labels are first column train_y = torch.from_numpy(train_data[[0]].values).float().squeeze() # features are the rest train_x = torch.from_numpy(train_data.drop([0], axis=1).values).float() # create dataset train_ds = torch.utils.data.TensorDataset(train_x, train_y) return torch.utils.data.DataLoader(train_ds, batch_size=batch_size) # Provided train function def train(model, train_loader, epochs, optimizer, criterion, device): """  This is the training method that is called by the PyTorch training script. The parameters  passed are as follows:  model - The PyTorch model that we wish to train.  train_loader - The PyTorch DataLoader that should be used during training.  epochs - The total number of epochs to train for.  optimizer - The optimizer to use during training.  criterion - The loss function used for training.   device - Where the model and data should be loaded (gpu or cpu).  """ for epoch in range(1, epochs + 1): model.train() total_loss = 0 for batch_idx, (data, target) in enumerate(train_loader, 1): # prep data data, target = data.to(device), target.to(device) optimizer.zero_grad() # zero accumulated gradients # get output of SimpleNet output = model(data) # calculate loss and perform backprop loss = criterion(output, target) loss.backward() optimizer.step() total_loss += loss.item() # print loss stats print("Epoch: {}, Loss: {}".format(epoch, total_loss / len(train_loader))) # save after all epochs save_model(model, args.model_dir) # Provided model saving functions def save_model(model, model_dir): print("Saving the model.") path = os.path.join(model_dir, 'model.pth') # save state dictionary torch.save(model.cpu().state_dict(), path) def save_model_params(model, model_dir): model_info_path = os.path.join(args.model_dir, 'model_info.pth') with open(model_info_path, 'wb') as f: model_info = { 'input_dim': args.input_dim, 'hidden_dim': args.hidden_dim, 'output_dim': args.output_dim } torch.save(model_info, f) ## TODO: Complete the main code if __name__ == '__main__': # All of the model parameters and training parameters are sent as arguments # when this script is executed, during a training job # Here we set up an argument parser to easily access the parameters parser = argparse.ArgumentParser() # SageMaker parameters, like the directories for training data and saving models; set automatically # Do not need to change parser.add_argument('--hosts', type=list, default=json.loads(os.environ['SM_HOSTS'])) parser.add_argument('--current-host', type=str, default=os.environ['SM_CURRENT_HOST']) parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR']) parser.add_argument('--data-dir', type=str, default=os.environ['SM_CHANNEL_TRAIN']) # Training Parameters, given parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--lr', type=float, default=0.001, metavar='LR', help='learning rate (default: 0.001)') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') ## TODO: Add args for the three model parameters: input_dim, hidden_dim, output_dim # Model parameters parser.add_argument('--input_dim', type=int, default=2, metavar='IN', help='dimention of the input layer (default: 2)') parser.add_argument('--hidden_dim', type=int, default=10, metavar='H', help='dimension of the hidden layers (default: 10)') parser.add_argument('--output_dim', type=int, default=1, metavar='OUT', help='dimension of the output layer (default: 1)') args = parser.parse_args() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # set the seed for generating random numbers torch.manual_seed(args.seed) if torch.cuda.is_available(): torch.cuda.manual_seed(args.seed) # get train loader train_loader = _get_train_loader(args.batch_size, args.data_dir) # data_dir from above.. ## TODO: Build the model by passing in the input params # To get params from the parser, call args.argument_name, ex. args.epochs or ards.hidden_dim # Don't forget to move your model .to(device) to move to GPU , if appropriate model = SimpleNet(args.input_dim, args.hidden_dim, args.output_dim).to(device) # Given: save the parameters used to construct the model save_model_params(model, args.model_dir) ## TODO: Define an optimizer and loss function for training optimizer = optim.Adam(model.parameters(), lr = args.lr) criterion = nn.BCELoss() # Trains the model (given line of code, which calls the above training function) # This function *also* saves the model state dictionary train(model, train_loader, args.epochs, optimizer, criterion, device) ###Markdown EXERCISE: Create a PyTorch EstimatorYou've had some practice instantiating built-in models in SageMaker. All estimators require some constructor arguments to be passed in. When a custom model is constructed in SageMaker, an **entry point** must be specified. The entry_point is the training script that will be executed when the model is trained; the `train.py` function you specified above! See if you can complete this task, instantiating a PyTorch estimator, using only the [PyTorch estimator documentation](https://sagemaker.readthedocs.io/en/stable/sagemaker.pytorch.html) as a resource. It is suggested that you use the **latest version** of PyTorch as the optional `framework_version` parameter. Instance TypesIt is suggested that you use instances that are available in the free tier of usage: `'ml.c4.xlarge'` for training and `'ml.t2.medium'` for deployment. ###Code # import a PyTorch wrapper from sagemaker.pytorch import PyTorch # specify an output path output_path = f's3://{bucket}/{prefix}' # instantiate a pytorch estimator estimator = PyTorch(entry_point = 'train.py', source_dir = 'source', instance_count = 1, instance_type = 'ml.c4.xlarge', framework_version = '1.5.0', py_version = 'py3', role = role, output_path = output_path, sagemaker_session = sagemaker_session, hyperparameters = { 'input_dim':2, 'hidden_dim':60, 'output_dim':1, 'epochs':120 }) ###Output _____no_output_____ ###Markdown Train the EstimatorAfter instantiating your estimator, train it with a call to `.fit()`. The `train.py` file explicitly loads in `.csv` data, so you do not need to convert the input data to any other format. ###Code %%time # train the estimator on S3 training data estimator.fit({'train': input_data}) ###Output 2021-01-26 16:44:49 Starting - Starting the training job... 2021-01-26 16:45:15 Starting - Launching requested ML instancesProfilerReport-1611679488: InProgress ......... 2021-01-26 16:46:36 Starting - Preparing the instances for training...... 2021-01-26 16:47:43 Downloading - Downloading input data... 2021-01-26 16:48:18 Training - Downloading the training image..bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell 2021-01-26 16:48:30,719 sagemaker-containers INFO Imported framework sagemaker_pytorch_container.training 2021-01-26 16:48:30,722 sagemaker-containers INFO No GPUs detected (normal if no gpus installed) 2021-01-26 16:48:30,733 sagemaker_pytorch_container.training INFO Block until all host DNS lookups succeed. 2021-01-26 16:48:33,759 sagemaker_pytorch_container.training INFO Invoking user training script. 2021-01-26 16:48:34,129 sagemaker-containers INFO Module default_user_module_name does not provide a setup.py.  Generating setup.py 2021-01-26 16:48:34,129 sagemaker-containers INFO Generating setup.cfg 2021-01-26 16:48:34,129 sagemaker-containers INFO Generating MANIFEST.in 2021-01-26 16:48:34,130 sagemaker-containers INFO Installing module with the following command: /opt/conda/bin/python -m pip install .  Processing /tmp/tmpgn0zntx9/module_dir Building wheels for collected packages: default-user-module-name Building wheel for default-user-module-name (setup.py): started Building wheel for default-user-module-name (setup.py): finished with status 'done' Created wheel for default-user-module-name: filename=default_user_module_name-1.0.0-py2.py3-none-any.whl size=14392 sha256=2405983a036a282f0e65a0115903bb2638f63c7b1e1a151b77c350b4a3a832fe Stored in directory: /tmp/pip-ephem-wheel-cache-6pxsf5pl/wheels/a7/81/b0/38f5507e99f8d74e89f0cb47bd7b8ec5d44a81abaa31568828 Successfully built default-user-module-name Installing collected packages: default-user-module-name Successfully installed default-user-module-name-1.0.0 WARNING: You are using pip version 20.1; however, version 21.0 is available. You should consider upgrading via the '/opt/conda/bin/python -m pip install --upgrade pip' command. 2021-01-26 16:48:36,473 sagemaker-containers INFO No GPUs detected (normal if no gpus installed) 2021-01-26 16:48:36,487 sagemaker-containers INFO No GPUs detected (normal if no gpus installed) 2021-01-26 16:48:36,501 sagemaker-containers INFO No GPUs detected (normal if no gpus installed) 2021-01-26 16:48:36,513 sagemaker-containers INFO Invoking user script  Training Env:  { "additional_framework_parameters": {}, "channel_input_dirs": { "train": "/opt/ml/input/data/train" }, "current_host": "algo-1", "framework_module": "sagemaker_pytorch_container.training:main", "hosts": [ "algo-1" ], "hyperparameters": { "input_dim": 2, "hidden_dim": 60, "epochs": 120, "output_dim": 1 }, "input_config_dir": "/opt/ml/input/config", "input_data_config": { "train": { "TrainingInputMode": "File", "S3DistributionType": "FullyReplicated", "RecordWrapperType": "None" } }, "input_dir": "/opt/ml/input", "is_master": true, "job_name": "pytorch-training-2021-01-26-16-44-48-828", "log_level": 20, "master_hostname": "algo-1", "model_dir": "/opt/ml/model", "module_dir": "s3://sagemaker-us-east-1-441543649966/pytorch-training-2021-01-26-16-44-48-828/source/sourcedir.tar.gz", "module_name": "train", "network_interface_name": "eth0", "num_cpus": 4, "num_gpus": 0, "output_data_dir": "/opt/ml/output/data", "output_dir": "/opt/ml/output", "output_intermediate_dir": "/opt/ml/output/intermediate", "resource_config": { "current_host": "algo-1", "hosts": [ "algo-1" ], "network_interface_name": "eth0" }, "user_entry_point": "train.py" }  Environment variables:  SM_HOSTS=["algo-1"] SM_NETWORK_INTERFACE_NAME=eth0 SM_HPS={"epochs":120,"hidden_dim":60,"input_dim":2,"output_dim":1} SM_USER_ENTRY_POINT=train.py SM_FRAMEWORK_PARAMS={} SM_RESOURCE_CONFIG={"current_host":"algo-1","hosts":["algo-1"],"network_interface_name":"eth0"} SM_INPUT_DATA_CONFIG={"train":{"RecordWrapperType":"None","S3DistributionType":"FullyReplicated","TrainingInputMode":"File"}} SM_OUTPUT_DATA_DIR=/opt/ml/output/data SM_CHANNELS=["train"] SM_CURRENT_HOST=algo-1 SM_MODULE_NAME=train SM_LOG_LEVEL=20 SM_FRAMEWORK_MODULE=sagemaker_pytorch_container.training:main SM_INPUT_DIR=/opt/ml/input SM_INPUT_CONFIG_DIR=/opt/ml/input/config SM_OUTPUT_DIR=/opt/ml/output SM_NUM_CPUS=4 SM_NUM_GPUS=0 SM_MODEL_DIR=/opt/ml/model SM_MODULE_DIR=s3://sagemaker-us-east-1-441543649966/pytorch-training-2021-01-26-16-44-48-828/source/sourcedir.tar.gz SM_TRAINING_ENV={"additional_framework_parameters":{},"channel_input_dirs":{"train":"/opt/ml/input/data/train"},"current_host":"algo-1","framework_module":"sagemaker_pytorch_container.training:main","hosts":["algo-1"],"hyperparameters":{"epochs":120,"hidden_dim":60,"input_dim":2,"output_dim":1},"input_config_dir":"/opt/ml/input/config","input_data_config":{"train":{"RecordWrapperType":"None","S3DistributionType":"FullyReplicated","TrainingInputMode":"File"}},"input_dir":"/opt/ml/input","is_master":true,"job_name":"pytorch-training-2021-01-26-16-44-48-828","log_level":20,"master_hostname":"algo-1","model_dir":"/opt/ml/model","module_dir":"s3://sagemaker-us-east-1-441543649966/pytorch-training-2021-01-26-16-44-48-828/source/sourcedir.tar.gz","module_name":"train","network_interface_name":"eth0","num_cpus":4,"num_gpus":0,"output_data_dir":"/opt/ml/output/data","output_dir":"/opt/ml/output","output_intermediate_dir":"/opt/ml/output/intermediate","resource_config":{"current_host":"algo-1","hosts":["algo-1"],"network_interface_name":"eth0"},"user_entry_point":"train.py"} SM_USER_ARGS=["--epochs","120","--hidden_dim","60","--input_dim","2","--output_dim","1"] SM_OUTPUT_INTERMEDIATE_DIR=/opt/ml/output/intermediate SM_CHANNEL_TRAIN=/opt/ml/input/data/train SM_HP_INPUT_DIM=2 SM_HP_HIDDEN_DIM=60 SM_HP_EPOCHS=120 SM_HP_OUTPUT_DIM=1 PYTHONPATH=/opt/ml/code:/opt/conda/bin:/opt/conda/lib/python36.zip:/opt/conda/lib/python3.6:/opt/conda/lib/python3.6/lib-dynload:/opt/conda/lib/python3.6/site-packages  Invoking script with the following command:  /opt/conda/bin/python train.py --epochs 120 --hidden_dim 60 --input_dim 2 --output_dim 1  Get data loader. 2021-01-26 16:48:45 Uploading - Uploading generated training model[2021-01-26 16:48:39.823 algo-1:44 INFO json_config.py:90] Creating hook from json_config at /opt/ml/input/config/debughookconfig.json. [2021-01-26 16:48:39.824 algo-1:44 INFO hook.py:183] tensorboard_dir has not been set for the hook. SMDebug will not be exporting tensorboard summaries. [2021-01-26 16:48:39.824 algo-1:44 INFO hook.py:228] Saving to /opt/ml/output/tensors [2021-01-26 16:48:39.824 algo-1:44 INFO hook.py:364] Monitoring the collections: losses [2021-01-26 16:48:39.825 algo-1:44 INFO hook.py:422] Hook is writing from the hook with pid: 44  Epoch: 1, Loss: 0.6908036097884178 Epoch: 2, Loss: 0.6920408830046654 Epoch: 3, Loss: 0.6916394382715225 Epoch: 4, Loss: 0.6889793649315834 Epoch: 5, Loss: 0.6905276104807854 Epoch: 6, Loss: 0.6898483708500862 Epoch: 7, Loss: 0.6898057237267494 Epoch: 8, Loss: 0.6885049715638161 Epoch: 9, Loss: 0.6897438317537308 Epoch: 10, Loss: 0.6871912851929665 Epoch: 11, Loss: 0.687233991920948 Epoch: 12, Loss: 0.6891267746686935 Epoch: 13, Loss: 0.6894926726818085 Epoch: 14, Loss: 0.6889978349208832 Epoch: 15, Loss: 0.6883935779333115 Epoch: 16, Loss: 0.6878218278288841 Epoch: 17, Loss: 0.689660519361496 Epoch: 18, Loss: 0.6870928555727005 Epoch: 19, Loss: 0.6890536695718765 Epoch: 20, Loss: 0.6882910281419754 Epoch: 21, Loss: 0.6862850710749626 Epoch: 22, Loss: 0.6871005520224571 Epoch: 23, Loss: 0.6741482466459274 Epoch: 24, Loss: 0.6890128701925278 Epoch: 25, Loss: 0.6810644268989563 Epoch: 26, Loss: 0.6463201493024826 Epoch: 27, Loss: 0.6406928300857544 Epoch: 28, Loss: 0.6542286574840546 Epoch: 29, Loss: 0.6180807203054428 Epoch: 30, Loss: 0.5901653580367565 Epoch: 31, Loss: 0.6235450878739357 Epoch: 32, Loss: 0.6167617067694664 Epoch: 33, Loss: 0.5810073465108871 Epoch: 34, Loss: 0.608798049390316 Epoch: 35, Loss: 0.6098298355937004 Epoch: 36, Loss: 0.5668461881577969 Epoch: 37, Loss: 0.5835252404212952 Epoch: 38, Loss: 0.5514932535588741 Epoch: 39, Loss: 0.5606307163834572 Epoch: 40, Loss: 0.5231835693120956 Epoch: 41, Loss: 0.5834812261164188 Epoch: 42, Loss: 0.5068818517029285 Epoch: 43, Loss: 0.7984053269028664 Epoch: 44, Loss: 0.48848166689276695 Epoch: 45, Loss: 0.5412987396121025 Epoch: 46, Loss: 0.5111497864127159 Epoch: 47, Loss: 0.4768614359200001 Epoch: 48, Loss: 0.5140528008341789 Epoch: 49, Loss: 0.504484087228775 Epoch: 50, Loss: 0.6039571538567543 Epoch: 51, Loss: 0.49702345952391624 Epoch: 52, Loss: 0.4821183569729328 Epoch: 53, Loss: 0.5134796462953091 Epoch: 54, Loss: 0.46601760387420654 Epoch: 55, Loss: 0.505382813513279 Epoch: 56, Loss: 0.4410233795642853 Epoch: 57, Loss: 0.3817650377750397 Epoch: 58, Loss: 0.7113528028130531 Epoch: 59, Loss: 0.4524150863289833 Epoch: 60, Loss: 0.4655093811452389 Epoch: 61, Loss: 0.5338554568588734 Epoch: 62, Loss: 0.5649877600371838 Epoch: 63, Loss: 0.4654165916144848 Epoch: 64, Loss: 0.4766323193907738 Epoch: 65, Loss: 0.4723433740437031 Epoch: 66, Loss: 0.4797331467270851 Epoch: 67, Loss: 0.45389315858483315 Epoch: 68, Loss: 0.41504909470677376 Epoch: 69, Loss: 0.4974297136068344 Epoch: 70, Loss: 0.454141091555357 Epoch: 71, Loss: 0.42979762703180313 Epoch: 72, Loss: 0.43634628877043724 Epoch: 73, Loss: 0.4146912060678005 Epoch: 74, Loss: 0.40102680772542953 Epoch: 75, Loss: 0.5323594473302364 Epoch: 76, Loss: 0.3965425118803978 Epoch: 77, Loss: 0.4876905754208565 Epoch: 78, Loss: 0.4221675172448158 Epoch: 79, Loss: 0.46357808634638786 Epoch: 80, Loss: 0.39132950082421303 Epoch: 81, Loss: 0.42814962938427925 Epoch: 82, Loss: 0.36541498079895973 Epoch: 83, Loss: 0.3650229908525944 Epoch: 84, Loss: 0.3982105515897274 Epoch: 85, Loss: 0.3611805643886328 Epoch: 86, Loss: 0.6417031362652779 Epoch: 87, Loss: 0.45397766679525375 Epoch: 88, Loss: 0.4329790249466896 Epoch: 89, Loss: 0.4360342025756836 Epoch: 90, Loss: 0.45970072597265244 Epoch: 91, Loss: 0.472491517663002 Epoch: 92, Loss: 0.44455286487936974 Epoch: 93, Loss: 0.4621676504611969 Epoch: 94, Loss: 0.4056120291352272 Epoch: 95, Loss: 0.40046630054712296 Epoch: 96, Loss: 0.42284689098596573 Epoch: 97, Loss: 0.5503215827047825 Epoch: 98, Loss: 0.39570067822933197 Epoch: 99, Loss: 0.4493889883160591 Epoch: 100, Loss: 0.4556043781340122 Epoch: 101, Loss: 0.409470584243536 Epoch: 102, Loss: 0.4194321744143963 Epoch: 103, Loss: 0.4418772980570793 Epoch: 104, Loss: 0.3437572540715337 Epoch: 105, Loss: 0.3976924791932106 Epoch: 106, Loss: 0.41119642555713654 Epoch: 107, Loss: 0.3896511495113373 Epoch: 108, Loss: 0.3996008113026619 Epoch: 109, Loss: 0.41742073372006416 Epoch: 110, Loss: 0.3967522978782654 Epoch: 111, Loss: 0.4652267098426819 Epoch: 112, Loss: 0.3771080747246742 Epoch: 113, Loss: 0.3720633387565613 Epoch: 114, Loss: 0.3181770369410515 Epoch: 115, Loss: 0.41743091493844986 Epoch: 116, Loss: 0.38632725179195404 Epoch: 117, Loss: 0.39293285086750984 Epoch: 118, Loss: 0.32474648021161556 Epoch: 119, Loss: 0.3757524713873863 Epoch: 120, Loss: 0.4377058632671833 Saving the model. [2021-01-26 16:48:44.380 algo-1:44 INFO utils.py:25] The end of training job file will not be written for jobs running under SageMaker. 2021-01-26 16:48:44,572 sagemaker-containers INFO Reporting training SUCCESS ###Markdown Create a Trained ModelPyTorch models do not automatically come with `.predict()` functions attached (as many Scikit-learn models do, for example) and you may have noticed that you've been give a `predict.py` file. This file is responsible for loading a trained model and applying it to passed in, numpy data. When you created a PyTorch estimator, you specified where the training script, `train.py` was located. > How can we tell a PyTorch model where the `predict.py` file is?Before you can deploy this custom PyTorch model, you have to take one more step: creating a `PyTorchModel`. In earlier exercises you could see that a call to `.deploy()` created both a **model** and an **endpoint**, but for PyTorch models, these steps have to be separate. EXERCISE: Instantiate a `PyTorchModel`You can create a `PyTorchModel` (different that a PyTorch estimator) from your trained, estimator attributes. This model is responsible for knowing how to execute a specific `predict.py` script. And this model is what you'll deploy to create an endpoint. Model ParametersTo instantiate a `PyTorchModel`, ([documentation, here](https://sagemaker.readthedocs.io/en/stable/sagemaker.pytorch.htmlsagemaker.pytorch.model.PyTorchModel)) you pass in the same arguments as your PyTorch estimator, with a few additions/modifications:* **model_data**: The trained `model.tar.gz` file created by your estimator, which can be accessed as `estimator.model_data`.* **entry_point**: This time, this is the path to the Python script SageMaker runs for **prediction** rather than training, `predict.py`. ###Code %%time # importing PyTorchModel from sagemaker.pytorch import PyTorchModel # Create a model from the trained estimator data # And point to the prediction script model = PyTorchModel(model_data = estimator.model_data, entry_point = 'predict.py', source_dir = 'source', role = role, framework_version = '1.5.0', py_version = 'py3') ###Output CPU times: user 10.7 ms, sys: 3.89 ms, total: 14.5 ms Wall time: 91.1 ms ###Markdown EXERCISE: Deploy the trained modelDeploy your model to create a predictor. We'll use this to make predictions on our test data and evaluate the model. ###Code %%time # deploy and create a predictor predictor = model.deploy(initial_instance_count = 1, instance_type = 'ml.t2.medium') ###Output -----------------------!CPU times: user 563 ms, sys: 41.1 ms, total: 605 ms Wall time: 11min 35s ###Markdown --- Evaluating Your ModelOnce your model is deployed, you can see how it performs when applied to the test data.The provided function below, takes in a deployed predictor, some test features and labels, and returns a dictionary of metrics; calculating false negatives and positives as well as recall, precision, and accuracy. ###Code # code to evaluate the endpoint on test data # returns a variety of model metrics def evaluate(predictor, test_features, test_labels, verbose=True): """ Evaluate a model on a test set given the prediction endpoint. Return binary classification metrics. :param predictor: A prediction endpoint :param test_features: Test features :param test_labels: Class labels for test data :param verbose: If True, prints a table of all performance metrics :return: A dictionary of performance metrics. """ # rounding and squeezing array test_preds = np.squeeze(np.round(predictor.predict(test_features))) # calculate true positives, false positives, true negatives, false negatives tp = np.logical_and(test_labels, test_preds).sum() fp = np.logical_and(1-test_labels, test_preds).sum() tn = np.logical_and(1-test_labels, 1-test_preds).sum() fn = np.logical_and(test_labels, 1-test_preds).sum() # calculate binary classification metrics recall = tp / (tp + fn) precision = tp / (tp + fp) accuracy = (tp + tn) / (tp + fp + tn + fn) # print metrics if verbose: print(pd.crosstab(test_labels, test_preds, rownames=['actuals'], colnames=['predictions'])) print("\n{:<11} {:.3f}".format('Recall:', recall)) print("{:<11} {:.3f}".format('Precision:', precision)) print("{:<11} {:.3f}".format('Accuracy:', accuracy)) print() return {'TP': tp, 'FP': fp, 'FN': fn, 'TN': tn, 'Precision': precision, 'Recall': recall, 'Accuracy': accuracy} ###Output _____no_output_____ ###Markdown Test ResultsThe cell below runs the `evaluate` function. The code assumes that you have a defined `predictor` and `X_test` and `Y_test` from previously-run cells. ###Code # get metrics for custom predictor metrics = evaluate(predictor, X_test, Y_test, True) ###Output predictions 0.0 1.0 actuals 0 64 7 1 10 69 Recall: 0.873 Precision: 0.908 Accuracy: 0.887 ###Markdown Delete the EndpointFinally, I've add a convenience function to delete prediction endpoints after we're done with them. And if you're done evaluating the model, you should delete your model endpoint! ###Code # Accepts a predictor endpoint as input # And deletes the endpoint by name def delete_endpoint(predictor): try: boto3.client('sagemaker').delete_endpoint(EndpointName=predictor.endpoint) print('Deleted {}'.format(predictor.endpoint)) except: print('Already deleted: {}'.format(predictor.endpoint)) # delete the predictor endpoint delete_endpoint(predictor) ###Output The endpoint attribute has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details. The endpoint attribute has been renamed in sagemaker>=2. See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
jwst_validation_notebooks/flat_field/jwst_flat_field_miri_test/jwst_flat_field_miri_test.ipynb
###Markdown Testing flat_field step with MIRI simulated data SummaryThis notebook processes an image through calwebb_image2 and calwebb_image3 (calwebb_detector1 is optional) and examines the output table of the source_catalog step. The steps are as follow:1) Set up data path and directory and image file name.2) Modify header information of input simulations (if needed).3) Run input data through calwebb_detector1.4) Run output of calwebb_detector1 through the flat_field step in calwebb_image2.5) Get flat field reference file. 6) Compare the flat field reference file with the rate/cal image ratio and check that they are the same.The pipeline documentation can be found here: https://jwst-pipeline.readthedocs.io/en/latest/The pipeline code is available on GitHub: https://github.com/spacetelescope/jwstAuthor: T. Temim Set up import statements ###Code import pytest import numpy as np from glob import glob import json import jwst from astropy.io import fits, ascii from astropy.coordinates import Angle from astropy.table import Table, vstack, unique from astropy.stats import sigma_clip from jwst.pipeline import Detector1Pipeline, Image2Pipeline, Image3Pipeline from jwst.associations import asn_from_list import matplotlib.pyplot as plt import random from jwst import associations from jwst.datamodels import RampModel from astropy.io import fits import numpy as np from jwst.associations.lib.rules_level3_base import DMS_Level3_Base from jwst.pipeline import calwebb_image3 from jwst.pipeline import calwebb_image2 from jwst.pipeline import calwebb_detector1 from astropy.io import fits from jwst.datamodels import ImageModel from jwst import datamodels from astropy.utils.data import get_pkg_data_filename from ci_watson.artifactory_helpers import get_bigdata from astropy import table import crds import os os.environ['CRDS_PATH']='$HOME/crds_cache' os.environ['CRDS_SERVER_URL'] = 'https://jwst-crds.stsci.edu' os.environ['CRDS_CONTEXT']='jwst_0619.pmap' os.environ['TEST_BIGDATA']='https://bytesalad.stsci.edu/artifactory/' #export CRDS_SERVER_URL=https://jwst-crds.stsci.edu #export CRDS_PATH=$HOME/crds_cache #export CRDS_CONTEXT='jwst_0619.pmap' #export TEST_BIGDATA=https://bytesalad.stsci.edu/artifactory/ ###Output _____no_output_____ ###Markdown Print pipeline version number ###Code jwst.__version__ ###Output _____no_output_____ ###Markdown Read in data from artifactory ###Code input_file = get_bigdata('jwst_validation_notebooks', 'validation_data', 'source_catalog', 'source_catalog_miri_test', 'det_image_seq1_MIRIMAGE_F560Wexp1_rate.fits') ###Output _____no_output_____ ###Markdown Read in input image as JWST data model ###Code from jwst import datamodels with datamodels.open(input_file) as im: # raises exception if myimage.fits is not an image file pass ###Output _____no_output_____ ###Markdown Modify header information of input simulations (if needed) ###Code print(im.meta.wcsinfo.wcsaxes) im.meta.wcsinfo.wcsaxes=2 print(im.meta.wcsinfo.wcsaxes) del im.meta.wcsinfo.cdelt3 del im.meta.wcsinfo.crpix3 del im.meta.wcsinfo.crval3 del im.meta.wcsinfo.ctype3 del im.meta.wcsinfo.cunit3 del im.meta.wcsinfo.pc3_1 del im.meta.wcsinfo.pc3_2 #del im.meta.wcsinfo.cdelt4 #del im.meta.wcsinfo.crpix4 #del im.meta.wcsinfo.crval4 #del im.meta.wcsinfo.ctype4 #del im.meta.wcsinfo.cunit4 ###Output _____no_output_____ ###Markdown Run input data through calwebb_detector1 (not done here) ###Code #det1 = calwebb_detector1.Detector1Pipeline() #det1.save_results = True #det1.run(im) ###Output _____no_output_____ ###Markdown Run output of calwebb_detector1 through calwebb_image2 ###Code input_file = input_file.replace('rateint.fits', 'rate.fits') im2 = calwebb_image2.Image2Pipeline() #im2.background.skip = True im2.assign_wcs.skip = True im2.flat_field.skip = False im2.photom.skip=True im2.resample.skip = True im2.save_results = True im2.run(im) input_file = input_file.replace('rate.fits', 'cal.fits') with datamodels.open(input_file) as im_cal: # raises exception if myimage.fits is not an image file pass ###Output _____no_output_____ ###Markdown Calculate the rate/cal image ratio ###Code ratio_im=im.data/im_cal.data ###Output _____no_output_____ ###Markdown Get flat_field reference file ###Code flatreffile = im_cal.meta.ref_file.flat.name print('Flat reference file', flatreffile) # find location of file basename = crds.core.config.pop_crds_uri(flatreffile) path = crds.locate_file(basename, "jwst") # open reference file with datamodels.open(path) as flat_im: # raises exception if myimage.fits is not an image file pass ###Output _____no_output_____ ###Markdown Compare flat field reference file with the rate/cal image ratio and check that they are equal ###Code check_flat=ratio_im/flat_im.data print('Minimum and maximum values in the check_flat image are:', np.nanmin(check_flat), 'and', np.nanmax(check_flat)) ###Output _____no_output_____ ###Markdown JWST Pipeline Validation Testing notebook: flat_field step with MIRI ImagingInstruments Affected: NIRCam, NIRSpec, NIRISS, MIRI, FGS Introduction This test is designed to test the flat_field step in the calwebb_image2 pipeline. This step retrieves the correct flat field reference file and divides the data by the reference file. The SCI extension of the reference file is divided into the SCI array of the science image. The DQ plane of the reference file is combined with the DQ plane of the science file. Error calculation: The VAR_POISSON and VAR_RNOISE variance arrays of the science exposure are divided by the square of the flat-field value for each pixel. A flat-field variance array, VAR_FLAT, is created from the science exposure and flat-field reference file data using the following formula:var_flat = SCI array ^ 2 / flat SCI array ^ 2 * flat err array ^2The total ERR array in the science exposure is updated as the square root of the quadratic sum of VAR_POISSON, VAR_RNOISE, and VAR_FLAT.Description of the steps applied: - If the science data have been taken using a subarray and the flat-field reference file is a full-frame image, extract the corresponding subarray region from the flat-field data.- Find pixels that have a value of NaN or zero in the FLAT reference file SCI array and set their DQ values to “NO_FLAT_FIELD.”- Reset the values of pixels in the flat that have DQ=”NO_FLAT_FIELD” to 1.0, so that they have no effect when applied to the science data.- Apply the flat by dividing it into the science exposure SCI array.- Propagate the FLAT reference file DQ values into the science exposure DQ array using a bitwise OR operation. DocumentationFor more information on the pipeline step visit the links below. The pipeline documentation can be found here: https://jwst-pipeline.readthedocs.io/en/latest/The pipeline code is available on GitHub: https://github.com/spacetelescope/jwst Test DescriptionThis notebook processes an image through calwebb_image2 (calwebb_detector1 is optional) and examines the output of the flat_field step. The steps are as follow:1) Retrieve data.2) Run output of calwebb_detector1 through the flat_field step in calwebb_image2. Visualize the sci arrays of the data before and after the flat_field step is applied. 3) Get flat field reference file. Look at the sci array of the flat_field reference file.4) Compare the flat field reference file with the rate/cal image ratio and check that they are the same.5) Look at the ERR arrays of the science data before and after the step is run, and compare to the flat_field reference file ERR array to be sure there is no unexpected pattern seen. Check that a new extension (var_flat) has been added to the output data.6) Check that the DQ flags were applied as expected. Data used The data used in this test is a simulated MIRI image created using MIRISim. The documentation for MIRISim can be found here: https://wiki.miricle.org/bin/view/Public/MIRISim_Public ###Code # Create a temporary directory to hold notebook output, and change the working directory to that directory. from tempfile import TemporaryDirectory import os data_dir = TemporaryDirectory() os.chdir(data_dir.name) print(data_dir) import os if 'CRDS_CACHE_TYPE' in os.environ: if os.environ['CRDS_CACHE_TYPE'] == 'local': os.environ['CRDS_PATH'] = os.path.join(os.environ['HOME'], 'crds', 'cache') elif os.path.isdir(os.environ['CRDS_CACHE_TYPE']): os.environ['CRDS_PATH'] = os.environ['CRDS_CACHE_TYPE'] print('CRDS cache location: {}'.format(os.environ['CRDS_PATH'])) ###Output _____no_output_____ ###Markdown Set up import statementsSoftware imports:- astropy allows various data formats to be read in and written out as well as visualization tools for plotting- numpy provides the framework to work with arrays and standard calculations- matplotlib is a set of plotting software- jwst is all of the jwst calibration pipeline software being tested- download_file, move and get_bigdata are used in downloading the data to be used. ###Code from astropy.io import fits, ascii from astropy.utils.data import download_file from astropy.visualization import SqrtStretch from astropy.visualization.mpl_normalize import ImageNormalize import numpy as np import matplotlib import matplotlib.pyplot as plt from shutil import move import jwst from jwst.pipeline import Detector1Pipeline, Image2Pipeline from jwst.flatfield import FlatFieldStep from jwst.datamodels import RampModel, ImageModel, dqflags from jwst.pipeline import calwebb_image2 from ci_watson.artifactory_helpers import get_bigdata import crds import os ###Output _____no_output_____ ###Markdown Print pipeline version number ###Code jwst.__version__ ###Output _____no_output_____ ###Markdown Read in data from artifactory (or Box) ###Code #input_file = get_bigdata('jwst_validation_notebooks', # 'validation_data', # 'flat_field', # 'flat_field_miri_test', # 'car007_seq1_MIRIMAGE_F770Wexp1_b771_rate.fits') from astropy.utils.data import download_file from pathlib import Path from shutil import move from os.path import splitext def get_box_files(file_list): for box_url,file_name in file_list: if 'https' not in box_url: box_url = 'https://stsci.box.com/shared/static/' + box_url downloaded_file = download_file(box_url) if Path(file_name).suffix == '': ext = splitext(box_url)[1] file_name += ext move(downloaded_file, file_name) #print(file_name) file_list=[('https://stsci.box.com/shared/static/kzef4nvyzzpfy4x4o108x344qg5epaf0.fits', 'car007_seq1_MIRIMAGE_F770Wexp1_b771_rate.fits')] get_box_files(file_list) filename = file_list[0][1] print(filename) # Read in data from Box #file_url = 'https://stsci.box.com/shared/static/kzef4nvyzzpfy4x4o108x344qg5epaf0.fits' #filename = 'car007_seq1_MIRIMAGE_F770Wexp1_b771_rate.fits' #input_file = download_file(file_url) #print(input_file) #ext = os.path.splitext(file_url)[1] #new_input_file = input_file + ext #move(input_file, new_input_file) ###Output _____no_output_____ ###Markdown Read in input image as JWST data model ###Code #im = ImageModel(new_input_file) #im.save(filename) im = ImageModel(filename) im.info() # Make sure image was read into the model correctly and has the expected extensions ###Output _____no_output_____ ###Markdown Display the rate (slope) file that is output of calwebb_detector1 ###Code plt.figure(figsize=(20,20)) plt.imshow(im.data, cmap='Greys', origin='lower', vmin=-2,vmax=10) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Run output of calwebb_detector1 through the flat field step ###Code im2 = FlatFieldStep() im2.save_results = True flatfile = im2.run(im) # Read output of calwebb_image2 into a data model im_cal = ImageModel(flatfile) print(im_cal.meta.filename) ###Output _____no_output_____ ###Markdown Display the calibrated data that is output of calwebb_image2 ###Code plt.figure(figsize=(20,20)) plt.imshow(im_cal.data, cmap='Greys', origin='lower', vmin=-2,vmax=10)#, norm=norm) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Calculate the rate/cal image ratio ###Code ratio_im = im.data / im_cal.data print('Minimum and maximum values in the ratio image are:', np.nanmin(ratio_im), 'and', np.nanmax(ratio_im)) ###Output _____no_output_____ ###Markdown Display ratio imageThe ratio of the images calculated above should be comparable to the flat field reference file science extension. ###Code plt.figure(figsize=(20,20)) # mask out DO_NOT_USE values of 1 masked_ratio = np.ma.masked_where((im_cal.dq & dqflags.pixel['DO_NOT_USE'] > 0), ratio_im) cmap = matplotlib.cm.get_cmap("Greys").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='white') # color to mark all DO_NOT_USE pixels plt.imshow(masked_ratio, cmap=cmap, origin='lower', vmin=0,vmax=1.5) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Get flat_field reference file ###Code flatreffile = im_cal.meta.ref_file.flat.name print('Flat reference file', flatreffile) # find location of file basename = crds.core.config.pop_crds_uri(flatreffile) path = crds.locate_file(basename, "jwst") # open reference file flat_im = ImageModel(path) print(flat_im.meta.filename) print('Minimum and maximum values in the ratio image are:', np.nanmin(flat_im.data), 'and', np.nanmax(flat_im.data)) ###Output _____no_output_____ ###Markdown Display flat field reference file data ###Code plt.figure(figsize=(20,20)) plt.imshow(flat_im.data, cmap='Greys', origin='lower', vmin=0,vmax=1.5) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Compare flat field reference file with the rate/cal image ratio and check that they are equalSince the step sets any flat field values to 1 where the DQ array lists the pixel as DO_NOT_USE, only a masked version of the images should be compared to the flat. Find regions where dq values are not marked as DO_NOT_USE and compare the good regions. ###Code # Do a check on any specific pixel in the imager. The rate file divided by the flat file should equal the value # in the flat_fielded output file. xval = 600 yval = 600 print('Rate image pixel value', im.data[yval, xval]) print('Cal image pixel value', im_cal.data[yval, xval]) print('Flat pixel value', flat_im.data[yval, xval]) print('DQ value for flat file:', flat_im.dq[yval, xval]) div_val = im.data[yval, xval] / flat_im.data[yval, xval] print('The rate file pixel divided by the flat file pixel is: ', div_val) try: assert im_cal.data[yval,xval] == im.data[yval, xval] / flat_im.data[yval, xval] except: print('Cal pixel does not equal rate divided by flat. There is a problem here.') # mask out bad pixels, i.e. pixels marked as DO_NOT_USE in the reference file dq array badpixels = np.where(flat_im.dq & dqflags.pixel['DO_NOT_USE'] > 0) # Set bad pixels in images to nan so they are not part of calculations good_im = im.data good_im[badpixels] = np.nan good_cal = im_cal.data good_cal[badpixels] = np.nan good_flat = flat_im.data good_flat[badpixels] = np.nan # Get the ratio of the masked images, and then divide by the masked flat image test_ratio = good_im / good_cal check_flat = test_ratio / good_flat print('Minimum and maximum values in the ratio image are:', np.nanmin(test_ratio), 'and', np.nanmax(test_ratio)) ###Output _____no_output_____ ###Markdown View the ratio image divided by the flat field ((rate / flat_fielded image) / flat field reference file)The values of this image should be around 1.0. The flat fielded science image results from dividing the rate image by the flat field reference file image. So the ratio of the rate image divided by the flat_fielded image should equal the flat field reference file, meaning that ratio should equal 1.0. ###Code plt.figure(figsize=(20,20)) plt.imshow(check_flat, cmap='Greys', origin='lower', vmin=0.5,vmax=1.5) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Check that min and max values of ratio image divided by the flat are 1.0 ###Code print('**************** Passing criteria check: Be sure that both of these values are near 1.0 *******') print('Minimum and maximum values in the check_flat image are:', np.nanmin(check_flat), 'and', np.nanmax(check_flat)) try: np.testing.assert_allclose(np.nanmin(check_flat), 1.0, rtol = 0.05) except AssertionError: print("AssertionError: The minimum value is not within 5% of 1.0") try: np.testing.assert_allclose(np.nanmax(check_flat), 1.0, rtol = 0.05) except AssertionError: print("AssertionError: The maximum value is not within 5% of 1.0") ###Output _____no_output_____ ###Markdown Check ERR arraysThere should be a new ERR array (var_flat) attached. Check that var_flat extension was added to data after flat field step was run ###Code # Look at extensions of the rate file uncal_filename = str(im.meta.filename) hdu = fits.open(uncal_filename) hdu.info() hdu.close() # Look at the extensions of cal file and check that a new extension 'var_flat' was added filename = str(im_cal.meta.filename) hdu = fits.open(filename) hdu.info() hdu.close() try: assert(im_cal.var_flat.shape == im_cal.data.shape) except AssertionError: print('AssertionError: var_flat array is not the same shape as the data array') ###Output _____no_output_____ ###Markdown Look at error arrays before and after flat field step to see if there are any unexplained changes ###Code # ERR array of rate image print('Min val: ', np.nanmin(im.err), ' Max val: ', np.nanmax(im.err)) plt.figure(figsize=(20,20)) plt.imshow(im.err, cmap='Greys', origin='lower', vmin=0,vmax=.5) plt.colorbar() plt.show() # ERR array of flat_fielded image print('Min val: ', np.nanmin(im_cal.err), ' Max val: ', np.nanmax(im_cal.err)) plt.figure(figsize=(20,20)) plt.imshow(im_cal.err, cmap='Greys', origin='lower', vmin=0,vmax=.5) plt.colorbar() plt.show() # ERR array of flat reference file image print('Min val: ', np.nanmin(im.err), ' Max val: ', np.nanmax(im.err)) plt.figure(figsize=(20,20)) plt.imshow(flat_im.err, cmap='Greys', origin='lower', vmin=0,vmax=.002) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Check DQ flagging Any pixel flagged as NON_SCIENCE should also be flagged as DO_NOT_USE. Check if this is in place in both the input reference file and for the output science file of the calwebb_image2 pipeline. If there are no assert errors, the test below passes. ###Code # Check if the output cal file is flagged properly # Test that all pixels flagged with NON_SCIENCE are also flagged as DO_NOT_USE nonsciencearray = (im_cal.dq & dqflags.pixel['NON_SCIENCE'] > 0) badarray = (im_cal.dq & dqflags.pixel['DO_NOT_USE'] > 0) try: assert nonsciencearray.all() == badarray.all() except AssertionError: print('AssertionError: The NON_SCIENCE pixels are not equal to the DO_NOT_USE pixels in the flat_fielded file.') # Test if the input reference file had the flags all set the same way nonsciencearray = (flat_im.dq & dqflags.pixel['NON_SCIENCE'] > 0) badarray = (flat_im.dq & dqflags.pixel['DO_NOT_USE'] > 0) try: assert nonsciencearray.all() == badarray.all() except AssertionError: print('AssertionError: The NON_SCIENCE pixels are not equal to the DO_NOT_USE pixels in the input file.') # Look at DQ planes of rate and cal files and make sure flat field reference file was added to the rate file. rate_dq = im.dq cal_dq = im_cal.dq flat_dq = flat_im.dq try: assert cal_dq.all() == rate_dq.all() & flat_dq.all() except AssertionError: print('AssertionError: The dq plane of the reference file was not added to the input dq plane properly.') ###Output _____no_output_____ ###Markdown Look at the dq planes to see how they change.The dq planes shown below show the rate file before the flat field step, the reference file dq plane, and the dq plane after the flat field step is applied.The regions marked with white have been set as 'DO_NOT_USE' in the dq plane. The images below should show that the 4QPM regions are marked as DO_NOT_USE by the flat field step. The rate image dq plane does not remove the 4QPM, but the flat field dq plane and the cal dq plane should both have the 4QPM regions marked as DO_NOT_USE. ###Code # Look at the dq plane of the rate image plt.figure(figsize=(20,20)) # call out DO_NOT_USE values of 1 masked_array = np.ma.masked_where((rate_dq & dqflags.pixel['DO_NOT_USE'] > 0), rate_dq) cmap = matplotlib.cm.get_cmap("rainbow").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='white') plt.imshow(masked_array, cmap=cmap, origin='lower', vmin=0,vmax=200) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Take a look at the dq plane of the flat field reference file.The dq definitions in the flat field file are as follows (from the dq_def extention) Value DQ Name 1 DO_NOT_USE 2 NON_SCIENCE 4 UNRELIABLE_FLAT 8 CDP_PARTIAL_DATA 16 CDP_LOW_QUAL 32 CDP_UNRELIABLE_ERROR 64 NO_FLAT_FIELD 128 DIFF_PATTERN If the pixel has an odd numbered value, it has been combined with the value 'DO_NOT_USE', and is not applied in the division of the science data by the flat. These 'bad' pixels are flagged in the following image by being shown in white. The purple pixels have values of zero, which indicate they are good science pixels. ###Code # Look at the dq plane of the flat_field image plt.figure(figsize=(20,20)) # call out DO_NOT_USE values of 1 masked_flat = np.ma.masked_where((flat_dq & dqflags.pixel['DO_NOT_USE'] > 0), flat_dq) cmap = matplotlib.cm.get_cmap("rainbow").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='white') plt.imshow(masked_flat, cmap=cmap, origin='lower', vmin=0,vmax=5) plt.colorbar() plt.show() # Look at the dq plane of the cal image plt.figure(figsize=(20,20)) # call out DO_NOT_USE values of 1 masked_cal = np.ma.masked_where((cal_dq & dqflags.pixel['DO_NOT_USE'] > 0), cal_dq) cmap = matplotlib.cm.get_cmap("rainbow").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='white') plt.imshow(masked_cal, cmap=cmap, origin='lower', vmin=0,vmax=200) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Take a look at what portion of the flat fielded image will be masked out in combined (image3 pipeline) dataTake the masked NaN region shown above and apply it to the flat fielded image to see what portion of the image will be masked out once calwebb_image3 is run and the DO_NOT_USE pixels are masked out. ###Code # Look at the dq plane of the cal image plt.figure(figsize=(20,20)) # call out DO_NOT_USE values of 1 masked_cal = np.ma.masked_where((cal_dq & dqflags.pixel['DO_NOT_USE'] > 0), im_cal.data) cmap = matplotlib.cm.get_cmap("Greys").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='blue') # Mark the DO_NOT_USE pixel color that will be masked out plt.imshow(masked_cal, cmap=cmap, origin='lower', vmin=-2,vmax=10) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Testing flat_field step with MIRI simulated data SummaryThis notebook processes an image through calwebb_image2 and calwebb_image3 (calwebb_detector1 is optional) and examines the output table of the source_catalog step. The steps are as follow:1) Set up data path and directory and image file name.2) Modify header information of input simulations (if needed).3) Run input data through calwebb_detector1.4) Run output of calwebb_detector1 through the flat_field step in calwebb_image2.5) Get flat field reference file. 6) Compare the flat field reference file with the rate/cal image ratio and check that they are the same.The pipeline documentation can be found here: https://jwst-pipeline.readthedocs.io/en/latest/The pipeline code is available on GitHub: https://github.com/spacetelescope/jwstAuthor: T. Temim ###Code # Create a temporary directory to hold notebook output, and change the working directory to that directory. from tempfile import TemporaryDirectory import os data_dir = TemporaryDirectory() os.chdir(data_dir.name) ###Output _____no_output_____ ###Markdown Set up import statements ###Code import pytest import numpy as np from glob import glob import json import jwst from astropy.io import fits, ascii from astropy.coordinates import Angle from astropy.table import Table, vstack, unique from astropy.stats import sigma_clip from jwst.pipeline import Detector1Pipeline, Image2Pipeline, Image3Pipeline from jwst.associations import asn_from_list import matplotlib.pyplot as plt import random from jwst import associations from jwst.datamodels import RampModel from astropy.io import fits import numpy as np from jwst.associations.lib.rules_level3_base import DMS_Level3_Base from jwst.pipeline import calwebb_image3 from jwst.pipeline import calwebb_image2 from jwst.pipeline import calwebb_detector1 from astropy.io import fits from jwst.datamodels import ImageModel from jwst import datamodels from astropy.utils.data import get_pkg_data_filename from ci_watson.artifactory_helpers import get_bigdata from astropy import table import crds import os os.environ['CRDS_SERVER_URL'] = 'https://jwst-crds.stsci.edu' os.environ['CRDS_CONTEXT']='jwst_0619.pmap' os.environ['TEST_BIGDATA']='https://bytesalad.stsci.edu/artifactory/' ###Output _____no_output_____ ###Markdown Print pipeline version number ###Code jwst.__version__ ###Output _____no_output_____ ###Markdown Read in data from artifactory ###Code input_file = get_bigdata('jwst_validation_notebooks', 'validation_data', 'source_catalog', 'source_catalog_miri_test', 'det_image_seq1_MIRIMAGE_F560Wexp1_rate.fits') ###Output _____no_output_____ ###Markdown Read in input image as JWST data model ###Code from jwst import datamodels im = ImageModel(input_file) ###Output _____no_output_____ ###Markdown Modify header information of input simulations (if needed) ###Code print(im.meta.wcsinfo.wcsaxes) im.meta.wcsinfo.wcsaxes=2 print(im.meta.wcsinfo.wcsaxes) del im.meta.wcsinfo.cdelt3 del im.meta.wcsinfo.crpix3 del im.meta.wcsinfo.crval3 del im.meta.wcsinfo.ctype3 del im.meta.wcsinfo.cunit3 del im.meta.wcsinfo.pc3_1 del im.meta.wcsinfo.pc3_2 #del im.meta.wcsinfo.cdelt4 #del im.meta.wcsinfo.crpix4 #del im.meta.wcsinfo.crval4 #del im.meta.wcsinfo.ctype4 #del im.meta.wcsinfo.cunit4 ###Output _____no_output_____ ###Markdown Run input data through calwebb_detector1 (not done here) ###Code #det1 = calwebb_detector1.Detector1Pipeline() #det1.save_results = True #det1.run(im) ###Output _____no_output_____ ###Markdown Run output of calwebb_detector1 through calwebb_image2 ###Code input_file = input_file.replace('rateint.fits', 'rate.fits') im2 = calwebb_image2.Image2Pipeline() #im2.background.skip = True im2.assign_wcs.skip = True im2.flat_field.skip = False im2.photom.skip=True im2.resample.skip = True im2.save_results = True im2.run(im) input_file = input_file.replace('rate.fits', 'cal.fits') im_cal = ImageModel(input_file) ###Output _____no_output_____ ###Markdown Calculate the rate/cal image ratio ###Code ratio_im=im.data/im_cal.data ###Output _____no_output_____ ###Markdown Get flat_field reference file ###Code flatreffile = im_cal.meta.ref_file.flat.name print('Flat reference file', flatreffile) # find location of file basename = crds.core.config.pop_crds_uri(flatreffile) path = crds.locate_file(basename, "jwst") # open reference file flat_im = ImageModel(path) ###Output _____no_output_____ ###Markdown Compare flat field reference file with the rate/cal image ratio and check that they are equal ###Code check_flat=ratio_im/flat_im.data print('Minimum and maximum values in the check_flat image are:', np.nanmin(check_flat), 'and', np.nanmax(check_flat)) ###Output _____no_output_____ ###Markdown JWST Pipeline Validation Testing notebook: flat_field step with MIRI ImagingInstruments Affected: NIRCam, NIRSpec, NIRISS, MIRI, FGS Introduction and summary of test being runThis notebook processes an image through calwebb_image2 (calwebb_detector1 is optional) and examines the output of the flat_field step. The steps are as follow:1) Set up data path and directory and image file name.2) Modify header information of input simulations (if needed).3) Run input data through calwebb_detector1. (Can be done prior to running this notebook.)4) Run output of calwebb_detector1 through the flat_field step in calwebb_image2.5) Get flat field reference file. 6) Compare the flat field reference file with the rate/cal image ratio and check that they are the same. DocumentationThe pipeline documentation can be found here: https://jwst-pipeline.readthedocs.io/en/latest/The pipeline code is available on GitHub: https://github.com/spacetelescope/jwst Data used The data used in this test is a simulated MIRI image created using MIRISim. The documentation for MIRISim can be found here: https://wiki.miricle.org/bin/view/Public/MIRISim_PublicAuthor: T. Temim ###Code # Create a temporary directory to hold notebook output, and change the working directory to that directory. from tempfile import TemporaryDirectory import os data_dir = TemporaryDirectory() os.chdir(data_dir.name) print(data_dir) ###Output _____no_output_____ ###Markdown Set up import statements ###Code from astropy.io import fits, ascii import pytest import numpy as np import jwst from jwst.pipeline import Detector1Pipeline, Image2Pipeline from jwst.datamodels import RampModel, ImageModel, dqflags from jwst.pipeline import calwebb_image2 from ci_watson.artifactory_helpers import get_bigdata import crds import os # Specify CRDS locations and pmap os.environ['CRDS_SERVER_URL'] = 'https://jwst-crds.stsci.edu' os.environ['CRDS_CONTEXT']='jwst_0619.pmap' os.environ['TEST_BIGDATA']='https://bytesalad.stsci.edu/artifactory/' ###Output _____no_output_____ ###Markdown Print pipeline version number ###Code jwst.__version__ ###Output _____no_output_____ ###Markdown Read in data from artifactory ###Code input_file = get_bigdata('jwst_validation_notebooks', 'validation_data', 'source_catalog', 'source_catalog_miri_test', 'det_image_seq1_MIRIMAGE_F560Wexp1_rate.fits') # Put in new simulation once we're sure MIRISim and the pipeline are using the same input flats. #input_file = get_bigdata('jwst_validation_notebooks', # 'validation_data', # 'flat_field', # 'flat_field_miri_test', # 'starfield_50star4ptdither_seq1_MIRIMAGE_F1130Wexp1_rate.fits') ###Output _____no_output_____ ###Markdown Read in input image as JWST data model ###Code im = ImageModel(input_file) ###Output _____no_output_____ ###Markdown Modify header information of input simulations (if needed) ###Code print(im.meta.wcsinfo.wcsaxes) im.meta.wcsinfo.wcsaxes=2 print(im.meta.wcsinfo.wcsaxes) del im.meta.wcsinfo.cdelt3 del im.meta.wcsinfo.crpix3 del im.meta.wcsinfo.crval3 del im.meta.wcsinfo.ctype3 del im.meta.wcsinfo.cunit3 del im.meta.wcsinfo.pc3_1 del im.meta.wcsinfo.pc3_2 ###Output _____no_output_____ ###Markdown Run input data through calwebb_detector1 (not done here) ###Code #det1 = calwebb_detector1.Detector1Pipeline() #det1.save_results = True #det1.run(im) ###Output _____no_output_____ ###Markdown Run output of calwebb_detector1 through calwebb_image2 ###Code #input_file = input_file.replace('rateint.fits', 'rate.fits') im2 = calwebb_image2.Image2Pipeline() #im2.background.skip = True im2.assign_wcs.skip = True im2.flat_field.skip = False im2.photom.skip=True im2.resample.skip = True im2.save_results = True im2.run(im) input_file = input_file.replace('rate.fits', 'cal.fits') im_cal = ImageModel(input_file) ###Output _____no_output_____ ###Markdown Calculate the rate/cal image ratio ###Code ratio_im=im.data/im_cal.data ###Output _____no_output_____ ###Markdown Get flat_field reference file ###Code flatreffile = im_cal.meta.ref_file.flat.name print('Flat reference file', flatreffile) # find location of file basename = crds.core.config.pop_crds_uri(flatreffile) path = crds.locate_file(basename, "jwst") # open reference file flat_im = ImageModel(path) ###Output _____no_output_____ ###Markdown Compare flat field reference file with the rate/cal image ratio and check that they are equal ###Code check_flat=ratio_im/flat_im.data print('Minimum and maximum values in the check_flat image are:', np.nanmin(check_flat), 'and', np.nanmax(check_flat)) ###Output _____no_output_____ ###Markdown Both values above should equal to 1.0 Check DQ flagging Any pixel flagged as NON_SCIENCE should also be flagged as DO_NOT_USE. Check if this is in place in both the input reference file and for the output science file of the calwebb_image2 pipeline. If there are no assert errors, the test below passes. ###Code # Check if the output cal file is flagged properly # Test that all pixels flagged with NON_SCIENCE are also flagged as DO_NOT_USE nonsciencearray = (im_cal.dq & dqflags.pixel['NON_SCIENCE'] > 0) badarray = (im_cal.dq & dqflags.pixel['DO_NOT_USE'] > 0) assert nonsciencearray.all() == badarray.all() # Test if the input reference file had the flags all set the same way nonsciencearray = (flat_im.dq & dqflags.pixel['NON_SCIENCE'] > 0) badarray = (flat_im.dq & dqflags.pixel['DO_NOT_USE'] > 0) assert nonsciencearray.all() == badarray.all() ###Output _____no_output_____ ###Markdown JWST Pipeline Validation Testing notebook: flat_field step with MIRI ImagingInstruments Affected: NIRCam, NIRSpec, NIRISS, MIRI, FGS Introduction This test is designed to test the flat_field step in the calwebb_image2 pipeline. This step retrieves the correct flat field reference file and divides the data by the reference file. The SCI extension of the reference file is divided into the SCI array of the science image. The DQ plane of the reference file is combined with the DQ plane of the science file. Error calculation: The VAR_POISSON and VAR_RNOISE variance arrays of the science exposure are divided by the square of the flat-field value for each pixel. A flat-field variance array, VAR_FLAT, is created from the science exposure and flat-field reference file data using the following formula:var_flat = SCI array ^ 2 / flat SCI array ^ 2 * flat err array ^2The total ERR array in the science exposure is updated as the square root of the quadratic sum of VAR_POISSON, VAR_RNOISE, and VAR_FLAT.Description of the steps applied: - If the science data have been taken using a subarray and the flat-field reference file is a full-frame image, extract the corresponding subarray region from the flat-field data.- Find pixels that have a value of NaN or zero in the FLAT reference file SCI array and set their DQ values to “NO_FLAT_FIELD.”- Reset the values of pixels in the flat that have DQ=”NO_FLAT_FIELD” to 1.0, so that they have no effect when applied to the science data.- Apply the flat by dividing it into the science exposure SCI array.- Propagate the FLAT reference file DQ values into the science exposure DQ array using a bitwise OR operation. DocumentationFor more information on the pipeline step visit the links below. The pipeline documentation can be found here: https://jwst-pipeline.readthedocs.io/en/latest/The pipeline code is available on GitHub: https://github.com/spacetelescope/jwst Test DescriptionThis notebook processes an image through calwebb_image2 (calwebb_detector1 is optional) and examines the output of the flat_field step. The steps are as follow:1) Retrieve data.2) Run output of calwebb_detector1 through the flat_field step in calwebb_image2. Visualize the sci arrays of the data before and after the flat_field step is applied. 3) Get flat field reference file. Look at the sci array of the flat_field reference file.4) Compare the flat field reference file with the rate/cal image ratio and check that they are the same.5) Look at the ERR arrays of the science data before and after the step is run, and compare to the flat_field reference file ERR array to be sure there is no unexpected pattern seen. Check that a new extension (var_flat) has been added to the output data.6) Check that the DQ flags were applied as expected. Data used The data used in this test is a simulated MIRI image created using MIRISim. The documentation for MIRISim can be found here: https://wiki.miricle.org/bin/view/Public/MIRISim_Public ###Code # Create a temporary directory to hold notebook output, and change the working directory to that directory. from tempfile import TemporaryDirectory import os data_dir = TemporaryDirectory() os.chdir(data_dir.name) print(data_dir) ###Output _____no_output_____ ###Markdown Set up import statementsSoftware imports:- astropy allows various data formats to be read in and written out as well as visualization tools for plotting- numpy provides the framework to work with arrays and standard calculations- matplotlib is a set of plotting software- jwst is all of the jwst calibration pipeline software being tested- download_file, move and get_bigdata are used in downloading the data to be used. ###Code from astropy.io import fits, ascii from astropy.utils.data import download_file from astropy.visualization import SqrtStretch from astropy.visualization.mpl_normalize import ImageNormalize import numpy as np import matplotlib import matplotlib.pyplot as plt from shutil import move import jwst from jwst.pipeline import Detector1Pipeline, Image2Pipeline from jwst.flatfield import FlatFieldStep from jwst.datamodels import RampModel, ImageModel, dqflags from jwst.pipeline import calwebb_image2 from ci_watson.artifactory_helpers import get_bigdata import crds import os ###Output _____no_output_____ ###Markdown Print pipeline version number ###Code jwst.__version__ ###Output _____no_output_____ ###Markdown Read in data from artifactory (or Box) ###Code #input_file = get_bigdata('jwst_validation_notebooks', # 'validation_data', # 'flat_field', # 'flat_field_miri_test', # 'car007_seq1_MIRIMAGE_F770Wexp1_b771_rate.fits') from astropy.utils.data import download_file from pathlib import Path from shutil import move from os.path import splitext def get_box_files(file_list): for box_url,file_name in file_list: if 'https' not in box_url: box_url = 'https://stsci.box.com/shared/static/' + box_url downloaded_file = download_file(box_url) if Path(file_name).suffix == '': ext = splitext(box_url)[1] file_name += ext move(downloaded_file, file_name) #print(file_name) file_list=[('https://stsci.box.com/shared/static/kzef4nvyzzpfy4x4o108x344qg5epaf0.fits', 'car007_seq1_MIRIMAGE_F770Wexp1_b771_rate.fits')] get_box_files(file_list) filename = file_list[0][1] print(filename) # Read in data from Box #file_url = 'https://stsci.box.com/shared/static/kzef4nvyzzpfy4x4o108x344qg5epaf0.fits' #filename = 'car007_seq1_MIRIMAGE_F770Wexp1_b771_rate.fits' #input_file = download_file(file_url) #print(input_file) #ext = os.path.splitext(file_url)[1] #new_input_file = input_file + ext #move(input_file, new_input_file) ###Output _____no_output_____ ###Markdown Read in input image as JWST data model ###Code #im = ImageModel(new_input_file) #im.save(filename) im = ImageModel(filename) im.info() # Make sure image was read into the model correctly and has the expected extensions ###Output _____no_output_____ ###Markdown Display the rate (slope) file that is output of calwebb_detector1 ###Code plt.figure(figsize=(20,20)) plt.imshow(im.data, cmap='Greys', origin='lower', vmin=-2,vmax=10) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Run output of calwebb_detector1 through the flat field step ###Code im2 = FlatFieldStep() im2.save_results = True flatfile = im2.run(im) # Read output of calwebb_image2 into a data model im_cal = ImageModel(flatfile) print(im_cal.meta.filename) ###Output _____no_output_____ ###Markdown Display the calibrated data that is output of calwebb_image2 ###Code plt.figure(figsize=(20,20)) plt.imshow(im_cal.data, cmap='Greys', origin='lower', vmin=-2,vmax=10)#, norm=norm) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Calculate the rate/cal image ratio ###Code ratio_im = im.data / im_cal.data print('Minimum and maximum values in the ratio image are:', np.nanmin(ratio_im), 'and', np.nanmax(ratio_im)) ###Output _____no_output_____ ###Markdown Display ratio imageThe ratio of the images calculated above should be comparable to the flat field reference file science extension. ###Code plt.figure(figsize=(20,20)) # mask out DO_NOT_USE values of 1 masked_ratio = np.ma.masked_where((im_cal.dq & dqflags.pixel['DO_NOT_USE'] > 0), ratio_im) cmap = matplotlib.cm.get_cmap("Greys").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='white') # color to mark all DO_NOT_USE pixels plt.imshow(masked_ratio, cmap=cmap, origin='lower', vmin=0,vmax=1.5) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Get flat_field reference file ###Code flatreffile = im_cal.meta.ref_file.flat.name print('Flat reference file', flatreffile) # find location of file basename = crds.core.config.pop_crds_uri(flatreffile) path = crds.locate_file(basename, "jwst") # open reference file flat_im = ImageModel(path) print(flat_im.meta.filename) print('Minimum and maximum values in the ratio image are:', np.nanmin(flat_im.data), 'and', np.nanmax(flat_im.data)) ###Output _____no_output_____ ###Markdown Display flat field reference file data ###Code plt.figure(figsize=(20,20)) plt.imshow(flat_im.data, cmap='Greys', origin='lower', vmin=0,vmax=1.5) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Compare flat field reference file with the rate/cal image ratio and check that they are equalSince the step sets any flat field values to 1 where the DQ array lists the pixel as DO_NOT_USE, only a masked version of the images should be compared to the flat. Find regions where dq values are not marked as DO_NOT_USE and compare the good regions. ###Code # Do a check on any specific pixel in the imager. The rate file divided by the flat file should equal the value # in the flat_fielded output file. xval = 600 yval = 600 print('Rate image pixel value', im.data[yval, xval]) print('Cal image pixel value', im_cal.data[yval, xval]) print('Flat pixel value', flat_im.data[yval, xval]) print('DQ value for flat file:', flat_im.dq[yval, xval]) div_val = im.data[yval, xval] / flat_im.data[yval, xval] print('The rate file pixel divided by the flat file pixel is: ', div_val) try: assert im_cal.data[yval,xval] == im.data[yval, xval] / flat_im.data[yval, xval] except: print('Cal pixel does not equal rate divided by flat. There is a problem here.') # mask out bad pixels, i.e. pixels marked as DO_NOT_USE in the reference file dq array badpixels = np.where(flat_im.dq & dqflags.pixel['DO_NOT_USE'] > 0) # Set bad pixels in images to nan so they are not part of calculations good_im = im.data good_im[badpixels] = np.nan good_cal = im_cal.data good_cal[badpixels] = np.nan good_flat = flat_im.data good_flat[badpixels] = np.nan # Get the ratio of the masked images, and then divide by the masked flat image test_ratio = good_im / good_cal check_flat = test_ratio / good_flat print('Minimum and maximum values in the ratio image are:', np.nanmin(test_ratio), 'and', np.nanmax(test_ratio)) ###Output _____no_output_____ ###Markdown View the ratio image divided by the flat field ((rate / flat_fielded image) / flat field reference file)The values of this image should be around 1.0. The flat fielded science image results from dividing the rate image by the flat field reference file image. So the ratio of the rate image divided by the flat_fielded image should equal the flat field reference file, meaning that ratio should equal 1.0. ###Code plt.figure(figsize=(20,20)) plt.imshow(check_flat, cmap='Greys', origin='lower', vmin=0.5,vmax=1.5) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Check that min and max values of ratio image divided by the flat are 1.0 ###Code print('**************** Passing criteria check: Be sure that both of these values are near 1.0 *******') print('Minimum and maximum values in the check_flat image are:', np.nanmin(check_flat), 'and', np.nanmax(check_flat)) try: np.testing.assert_allclose(np.nanmin(check_flat), 1.0, rtol = 0.05) except AssertionError: print("AssertionError: The minimum value is not within 5% of 1.0") try: np.testing.assert_allclose(np.nanmax(check_flat), 1.0, rtol = 0.05) except AssertionError: print("AssertionError: The maximum value is not within 5% of 1.0") ###Output _____no_output_____ ###Markdown Check ERR arraysThere should be a new ERR array (var_flat) attached. Check that var_flat extension was added to data after flat field step was run ###Code # Look at extensions of the rate file uncal_filename = str(im.meta.filename) hdu = fits.open(uncal_filename) hdu.info() hdu.close() # Look at the extensions of cal file and check that a new extension 'var_flat' was added filename = str(im_cal.meta.filename) hdu = fits.open(filename) hdu.info() hdu.close() try: assert(im_cal.var_flat.shape == im_cal.data.shape) except AssertionError: print('AssertionError: var_flat array is not the same shape as the data array') ###Output _____no_output_____ ###Markdown Look at error arrays before and after flat field step to see if there are any unexplained changes ###Code # ERR array of rate image print('Min val: ', np.nanmin(im.err), ' Max val: ', np.nanmax(im.err)) plt.figure(figsize=(20,20)) plt.imshow(im.err, cmap='Greys', origin='lower', vmin=0,vmax=.5) plt.colorbar() plt.show() # ERR array of flat_fielded image print('Min val: ', np.nanmin(im_cal.err), ' Max val: ', np.nanmax(im_cal.err)) plt.figure(figsize=(20,20)) plt.imshow(im_cal.err, cmap='Greys', origin='lower', vmin=0,vmax=.5) plt.colorbar() plt.show() # ERR array of flat reference file image print('Min val: ', np.nanmin(im.err), ' Max val: ', np.nanmax(im.err)) plt.figure(figsize=(20,20)) plt.imshow(flat_im.err, cmap='Greys', origin='lower', vmin=0,vmax=.002) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Check DQ flagging Any pixel flagged as NON_SCIENCE should also be flagged as DO_NOT_USE. Check if this is in place in both the input reference file and for the output science file of the calwebb_image2 pipeline. If there are no assert errors, the test below passes. ###Code # Check if the output cal file is flagged properly # Test that all pixels flagged with NON_SCIENCE are also flagged as DO_NOT_USE nonsciencearray = (im_cal.dq & dqflags.pixel['NON_SCIENCE'] > 0) badarray = (im_cal.dq & dqflags.pixel['DO_NOT_USE'] > 0) try: assert nonsciencearray.all() == badarray.all() except AssertionError: print('AssertionError: The NON_SCIENCE pixels are not equal to the DO_NOT_USE pixels in the flat_fielded file.') # Test if the input reference file had the flags all set the same way nonsciencearray = (flat_im.dq & dqflags.pixel['NON_SCIENCE'] > 0) badarray = (flat_im.dq & dqflags.pixel['DO_NOT_USE'] > 0) try: assert nonsciencearray.all() == badarray.all() except AssertionError: print('AssertionError: The NON_SCIENCE pixels are not equal to the DO_NOT_USE pixels in the input file.') # Look at DQ planes of rate and cal files and make sure flat field reference file was added to the rate file. rate_dq = im.dq cal_dq = im_cal.dq flat_dq = flat_im.dq try: assert cal_dq.all() == rate_dq.all() & flat_dq.all() except AssertionError: print('AssertionError: The dq plane of the reference file was not added to the input dq plane properly.') ###Output _____no_output_____ ###Markdown Look at the dq planes to see how they change.The dq planes shown below show the rate file before the flat field step, the reference file dq plane, and the dq plane after the flat field step is applied.The regions marked with white have been set as 'DO_NOT_USE' in the dq plane. The images below should show that the 4QPM regions are marked as DO_NOT_USE by the flat field step. The rate image dq plane does not remove the 4QPM, but the flat field dq plane and the cal dq plane should both have the 4QPM regions marked as DO_NOT_USE. ###Code # Look at the dq plane of the rate image plt.figure(figsize=(20,20)) # call out DO_NOT_USE values of 1 masked_array = np.ma.masked_where((rate_dq & dqflags.pixel['DO_NOT_USE'] > 0), rate_dq) cmap = matplotlib.cm.get_cmap("rainbow").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='white') plt.imshow(masked_array, cmap=cmap, origin='lower', vmin=0,vmax=200) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Take a look at the dq plane of the flat field reference file.The dq definitions in the flat field file are as follows (from the dq_def extention) Value DQ Name 1 DO_NOT_USE 2 NON_SCIENCE 4 UNRELIABLE_FLAT 8 CDP_PARTIAL_DATA 16 CDP_LOW_QUAL 32 CDP_UNRELIABLE_ERROR 64 NO_FLAT_FIELD 128 DIFF_PATTERN If the pixel has an odd numbered value, it has been combined with the value 'DO_NOT_USE', and is not applied in the division of the science data by the flat. These 'bad' pixels are flagged in the following image by being shown in white. The purple pixels have values of zero, which indicate they are good science pixels. ###Code # Look at the dq plane of the flat_field image plt.figure(figsize=(20,20)) # call out DO_NOT_USE values of 1 masked_flat = np.ma.masked_where((flat_dq & dqflags.pixel['DO_NOT_USE'] > 0), flat_dq) cmap = matplotlib.cm.get_cmap("rainbow").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='white') plt.imshow(masked_flat, cmap=cmap, origin='lower', vmin=0,vmax=5) plt.colorbar() plt.show() # Look at the dq plane of the cal image plt.figure(figsize=(20,20)) # call out DO_NOT_USE values of 1 masked_cal = np.ma.masked_where((cal_dq & dqflags.pixel['DO_NOT_USE'] > 0), cal_dq) cmap = matplotlib.cm.get_cmap("rainbow").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='white') plt.imshow(masked_cal, cmap=cmap, origin='lower', vmin=0,vmax=200) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Take a look at what portion of the flat fielded image will be masked out in combined (image3 pipeline) dataTake the masked NaN region shown above and apply it to the flat fielded image to see what portion of the image will be masked out once calwebb_image3 is run and the DO_NOT_USE pixels are masked out. ###Code # Look at the dq plane of the cal image plt.figure(figsize=(20,20)) # call out DO_NOT_USE values of 1 masked_cal = np.ma.masked_where((cal_dq & dqflags.pixel['DO_NOT_USE'] > 0), im_cal.data) cmap = matplotlib.cm.get_cmap("Greys").copy() # Can be any colormap that you want after the cm cmap.set_bad(color='blue') # Mark the DO_NOT_USE pixel color that will be masked out plt.imshow(masked_cal, cmap=cmap, origin='lower', vmin=-2,vmax=10) plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Testing flat_field step with MIRI simulated data SummaryThis notebook processes an image through calwebb_image2 and calwebb_image3 (calwebb_detector1 is optional) and examines the output table of the source_catalog step. The steps are as follow:1) Set up data path and directory and image file name.2) Modify header information of input simulations (if needed).3) Run input data through calwebb_detector1.4) Run output of calwebb_detector1 through the flat_field step in calwebb_image2.5) Get flat field reference file. 6) Compare the flat field reference file with the rate/cal image ratio and check that they are the same.The pipeline documentation can be found here: https://jwst-pipeline.readthedocs.io/en/latest/The pipeline code is available on GitHub: https://github.com/spacetelescope/jwstAuthor: T. Temim Set up import statements ###Code import pytest import numpy as np from glob import glob import json import jwst from astropy.io import fits, ascii from astropy.coordinates import Angle from astropy.table import Table, vstack, unique from astropy.stats import sigma_clip from jwst.pipeline import Detector1Pipeline, Image2Pipeline, Image3Pipeline from jwst.associations import asn_from_list import matplotlib.pyplot as plt import random from jwst import associations from jwst.datamodels import RampModel from astropy.io import fits import numpy as np from jwst.associations.lib.rules_level3_base import DMS_Level3_Base from jwst.pipeline import calwebb_image3 from jwst.pipeline import calwebb_image2 from jwst.pipeline import calwebb_detector1 from astropy.io import fits from jwst.datamodels import ImageModel from jwst import datamodels from astropy.utils.data import get_pkg_data_filename from ci_watson.artifactory_helpers import get_bigdata from astropy import table import crds import os os.environ['CRDS_SERVER_URL'] = 'https://jwst-crds.stsci.edu' os.environ['CRDS_CONTEXT']='jwst_0619.pmap' os.environ['TEST_BIGDATA']='https://bytesalad.stsci.edu/artifactory/' ###Output _____no_output_____ ###Markdown Print pipeline version number ###Code jwst.__version__ ###Output _____no_output_____ ###Markdown Read in data from artifactory ###Code input_file = get_bigdata('jwst_validation_notebooks', 'validation_data', 'source_catalog', 'source_catalog_miri_test', 'det_image_seq1_MIRIMAGE_F560Wexp1_rate.fits') ###Output _____no_output_____ ###Markdown Read in input image as JWST data model ###Code from jwst import datamodels im = ImageModel(input_file) ###Output _____no_output_____ ###Markdown Modify header information of input simulations (if needed) ###Code print(im.meta.wcsinfo.wcsaxes) im.meta.wcsinfo.wcsaxes=2 print(im.meta.wcsinfo.wcsaxes) del im.meta.wcsinfo.cdelt3 del im.meta.wcsinfo.crpix3 del im.meta.wcsinfo.crval3 del im.meta.wcsinfo.ctype3 del im.meta.wcsinfo.cunit3 del im.meta.wcsinfo.pc3_1 del im.meta.wcsinfo.pc3_2 #del im.meta.wcsinfo.cdelt4 #del im.meta.wcsinfo.crpix4 #del im.meta.wcsinfo.crval4 #del im.meta.wcsinfo.ctype4 #del im.meta.wcsinfo.cunit4 ###Output _____no_output_____ ###Markdown Run input data through calwebb_detector1 (not done here) ###Code #det1 = calwebb_detector1.Detector1Pipeline() #det1.save_results = True #det1.run(im) ###Output _____no_output_____ ###Markdown Run output of calwebb_detector1 through calwebb_image2 ###Code input_file = input_file.replace('rateint.fits', 'rate.fits') im2 = calwebb_image2.Image2Pipeline() #im2.background.skip = True im2.assign_wcs.skip = True im2.flat_field.skip = False im2.photom.skip=True im2.resample.skip = True im2.save_results = True im2.run(im) input_file = input_file.replace('rate.fits', 'cal.fits') im_cal = ImageModel(input_file) ###Output _____no_output_____ ###Markdown Calculate the rate/cal image ratio ###Code ratio_im=im.data/im_cal.data ###Output _____no_output_____ ###Markdown Get flat_field reference file ###Code flatreffile = im_cal.meta.ref_file.flat.name print('Flat reference file', flatreffile) # find location of file basename = crds.core.config.pop_crds_uri(flatreffile) path = crds.locate_file(basename, "jwst") # open reference file flat_im = ImageModel(path) ###Output _____no_output_____ ###Markdown Compare flat field reference file with the rate/cal image ratio and check that they are equal ###Code check_flat=ratio_im/flat_im.data print('Minimum and maximum values in the check_flat image are:', np.nanmin(check_flat), 'and', np.nanmax(check_flat)) ###Output _____no_output_____
tracking_performance/Survivor_Incomer_Mistrack.ipynb
###Markdown Flood Fill the Slides of the Representative Movie:+ **SURVIVORS**: Mark those cells which are correctly tracked to it's root at frame 0 (cyan)+ **INCOMERS**: Separate those cells which are incomers into the FOV during the movie (gold) - tree founder cell must be initiated near FOV boundary *(use 50 px)* - tree founder cell must be successfully tracked for certain time period *(use 50 frames)*+ **MISTRACKS**: Highlight those cells which were mistracked in their tree due to breakage (red) ###Code import h5py import numpy as np import scipy as sp import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap from skimage import io from skimage.segmentation import flood_fill ###Output _____no_output_____ ###Markdown Let's nominate which file we want to process: ###Code hdf5_file = "../example_segment_classif_tracked_movie.hdf5" ###Output _____no_output_____ ###Markdown Set the thresholds use to categorise which cells will be considered incomers:At this moment, only those tracks which are within **50px distance** to any FOV edge upon appearance will be considered *incomers* if they:+ live at least for **50 frames**, or+ have divided in the meantimeChange appropriately if needed. ###Code time_threshold = 50 dist_threshold = 50 ###Output _____no_output_____ ###Markdown Process the tracks & assign the survivor (cyan), incomer (yellow) or mistrack (red) label to each tracklet: ###Code survivor, incomer, mistrack = [], [], [] with h5py.File(hdf5_file, 'r') as f: ID_list = [item[0] for item in f["tracks"]["obj_type_1"]["LBEPR"]] # Shorlist all cells which are parents to 2 children: set of such list should be 1/2 of its length: parents = list(set([item[3] for item in f["tracks"]["obj_type_1"]["LBEPR"] if item[3] != 0])) # Survivors = founders: for cell in f["tracks"]["obj_type_1"]["LBEPR"]: if cell[1] == 0: survivor.append(cell[0]) # Survivors = progeny: for cell in f["tracks"]["obj_type_1"]["LBEPR"]: if cell[4] in survivor: survivor.append(cell[0]) # Incomers = founders: for cell in f["tracks"]["obj_type_1"]["LBEPR"]: if cell[0] not in survivor: # Must be a founder: if cell[4] == 0: # Look at cell coordinates at its frame of appearance: cell_map = f["tracks"]["obj_type_1"]["map"][ID_list.index(cell[0])] trk_init = f["tracks"]["obj_type_1"]["tracks"][cell_map[0]] coo_init = f["objects"]["obj_type_1"]["coords"][trk_init] # CONDITION #1: distance threshold: x (index=2) or y (index=1) close to FOV borders? if not (dist_threshold < coo_init[2] < 1600 - dist_threshold and dist_threshold < coo_init[1] < 1200 - dist_threshold): # CONDITION #2: time threshold: is the track alive for at least XYZ frames? if cell[2] - cell[1] + 1 > time_threshold: incomer.append(cell[0]) else: # If it doesn't live long enough, it could have divided: is it a parent? if cell[0] in parents: incomer.append(cell[0]) else: mistrack.append(cell[0]) else: mistrack.append(cell[0]) # Incomers = progeny: for cell in f["tracks"]["obj_type_1"]["LBEPR"]: if cell[4] in incomer: incomer.append(cell[0]) # All other cells must be tracking errors: for cell in f["tracks"]["obj_type_1"]["LBEPR"]: if not (cell[0] in survivor or cell[0] in incomer): if not cell[0] in mistrack: mistrack.append(cell[0]) ###Output _____no_output_____ ###Markdown Allocate colomap labels to cells, then to the respective coordinated of their objects:+ Survivor = 1+ Incomer = 2+ Mistrack = 3 ###Code object_vector = [] with h5py.File(hdf5_file, 'r') as f: object_vector = [0 for _ in range(len(f["objects"]["obj_type_1"]["coords"]))] for e, item in enumerate(ID_list): if item in survivor: index = 2 elif item in incomer: index = 3 elif item in mistrack: index = 4 else: raise ValueError cell_map = f["tracks"]["obj_type_1"]["map"][e] for trk in f["tracks"]["obj_type_1"]["tracks"][cell_map[0]:cell_map[1]]: if trk > 0: object_vector[trk] = index else: object_vector[trk] = 1 ###Output _____no_output_____ ###Markdown Define the custom colormap: ###Code viridis = cm.get_cmap('viridis', 256) newcolors = viridis(np.linspace(0, 1, 256)) newcolors[0:1, :] = np.array([0/256, 0/256, 0/256, 1]) newcolors[1:2, :] = np.array([150/256, 150/256, 150/256, 1]) newcolors[2:3, :] = np.array([0/256, 255/256, 255/256, 1]) # survivor: cyan newcolors[3:4, :] = np.array([255/256, 255/256, 0/256, 1]) # incomer: yellow newcolors[4:5, :] = np.array([255/256, 0/256, 0/256, 1]) # mistrack: red newcmp = ListedColormap(newcolors[:5]) ###Output _____no_output_____ ###Markdown Fill each object in the frame: ###Code dr = "" # specify your saving directory, otherwise images are saved to where this notebook is stored frames = range(0, 800 + 1, 100) with h5py.File(hdf5_file, 'r') as f: for frame in frames: _ = plt.figure(figsize=(24, 18)) img = f["segmentation"]["images"][frame] # Process the image: label individual objects & store their slices: lbl_image = sp.ndimage.label(img)[0] found_objects = sp.ndimage.find_objects(input=lbl_image) # Map the coordinates: mp = f["objects"]["obj_type_1"]["map"][frame] coords_list = f["objects"]["obj_type_1"]["coords"][mp[0]:mp[1]] fill_list = object_vector[mp[0]:mp[1]] # Check whether number of detected objects matches found objects in labeled array: if len(coords_list) != len(found_objects): raise ValueError # Iterate: for e, (obj, lab, slc) in enumerate(zip(coords_list, fill_list, found_objects)): if not (slc[0].start <= obj[1] <= slc[0].stop and slc[1].start <= obj[2] <= slc[1].stop): raise Exception("Warning") # Check if the pixel at the centre of your cell in non-zero: seed_point = img[int(obj[1])][int(obj[2])] if seed_point != 0: flood_fill(image=img, seed_point=(int(obj[1]), int(obj[2])), new_value=lab, in_place=True) else: idx = list(lbl_image[slc[0].start][slc[1].start:slc[1].stop]).index(e+1) seed_point = img[slc[0].start][slc[1].start+idx] if seed_point != 0: flood_fill(image=img, seed_point=(slc[0].start, slc[1].start+idx), new_value=lab, in_place=True) else: print ("Disaster!") # Colormap will normalise its range: include corner pixels with different colors: img[0][0] = 1 img[0][1599] = 2 img[1199][0] = 3 img[1199][1599] = 4 plt.axis("off") plt.imshow(img, cmap=newcmp) #plt.imsave(fname=dr+f"frm_{frame}.tiff", arr=img, cmap=newcmp) ###Output _____no_output_____
DAY 401 ~ 500/DAY424_[BaekJoon] 무한 문자열 (Python).ipynb
###Markdown 2021년 7월 14일 수요일 BaekJoon - 무한 문자열 (Python) 문제 : https://www.acmicpc.net/problem/12871 블로그 : https://somjang.tistory.com/entry/BaekJoon-12871%EB%B2%88-%EB%AC%B4%ED%95%9C-%EB%AC%B8%EC%9E%90%EC%97%B4-Python Solution ###Code import math def get_least_common_multiple(string_s_len, string_t_len): return string_s_len * string_t_len // math.gcd(string_s_len, string_t_len) def infinity_string(string_s, string_t): is_infinity_string = 0 string_s_len = len(string_s) string_t_len = len(string_t) standard_len = get_least_common_multiple(string_s_len, string_t_len) s_multiply_num = standard_len // string_s_len t_multiply_num = standard_len // string_t_len if string_s * s_multiply_num == string_t * t_multiply_num: is_infinity_string = 1 return is_infinity_string if __name__ == "__main__": string_s = input() string_t = input() print(infinity_string(string_s, string_t)) ###Output _____no_output_____
REST/Udemy-Django-Python/Django REST Course - 08 Intro To Viewsets.ipynb
###Markdown ___ ___ What Is A ViewSet?This is the other framwork view. APIView was the other.Just like APIViews, they allow us to write the logic for our endpoints. However - instead of defining functions that map to HTTP methods, Viewsets accept functions that map to common API object actions.- list- create- retrieve- update- partial update- destroyThese Viewsets take care of a lot of the common logic for you.Additional benefits:- perfect for standard database operations- fastest way to make a database interface When To Use ViewSetsMost of the time it comes down to personal preference. Here are some examples for when you need to use Viewsets over APIViews:1. need a simple CRUD (**C**reate **R**ead **U**pdate **D**elete) interface to your DB2. need quick and simple API to manage pre-defined objects3. need little to no customization on the logic4. you are working with standard data structures Create A Simple ViewsetThis section will create the "Hello Viewset".1. Load up your `views.py` file in the **profiles_api** app folder.2. Add the following import above the APIView import: `from rest_framework import viewsets` This is the base module for all the different viewsets that Django REST framework offers. 3. Below your APIView code, create a new class that inherits from: `viewsets.ViewSet` ###Code class HelloViewSet(viewsets.ViewSet): """Test API ViewSet.""" def list(self, request): # typically a HTTP GET to the root of an endpoint """Return a hello message.""" a_viewset = [ 'Uses actions (list, create, retrieve, update, partial_update)', 'Automatically maps to URLs using Routers', 'Provides more functionality with less code.' ] return Response({'message': 'Hello!', 'a_viewset': a_viewset}) ###Output _____no_output_____ ###Markdown The functions within this new class are actions you would take on an object - not HTTP calls. Add A URL RouterJust like with APIView, we need to map (or register) our ViewSet to a URL so we can use it in the browser. Django REST has a special Router class that can be used to automatically set up the different routes for our URL to our ViewSet.This is one of the advantages for using a ViewSet over an APIView.Now it's time to add a router to your HelloViewSet.1. Go to your `url.py` file in the profiles_api folder - **not** the one in the profiles_project folder.2. Add/update the following imports at the top: - update `from django.urls import path` to `from django.urls import path, include` - `from rest_framework.routers import DefaultRouter`3. Create your router under the imports & assign it a URL ###Code router = DefaultRouter() # register a new URL that points to our HelloViewSet # input 1 - string is the URL you would like to use # input 2 - name of the viewset we want to assign/register to the router # input 3 - base name (used for retrieving URLs in Router) router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset') ###Output _____no_output_____ ###Markdown 4. In the urlpatterns, create a new url with a blank string for the RegEx `path('', include(router.urls))` That way the router creates the URLs for you. Testing Our ViewsetEnsure the development server is up and running. It's possible you may have to restart to get latest changes.Go to your browser and the root API URL: `http://127.0.0.1:8000/api/`It should look a little different than last time:It used to say there was no page linked to this URL!If you click the link next to it, you will find the Hello-Viewset you just created.`http://127.0.0.1:8080/api/hello-viewset/` Commit To GitIn your **git bash** program ...1. go to project directory: `cd workspace/PROJECTNAME` (in this example **profiles-rest-api**)2. Call `git add .`3. Call `git commit -am "Added our first viewset and router."` Add Create, Retrieve, Update, Partial Update, And Destroy FunctionsIt's time to complete our ViewSet.1. Locate the `views.py` file in the profiles_api app folder.2. Go to bottom where you added the **HelloViewSet** class. You will now add a serializer class to this class the same way we added it to the **HelloAPIView** class.**NOTE:** ViewSets and APIViews can use the same serializer!3. Below the docstring, add the following: `serializer_class = serializers.HelloSerializer`4. Add the functions to the class. ###Code # CREATE - takes care of the HTTP POST function # creates new objects in the system def create(self, request): """Create a new hello message.""" serializer = self.serializer_class(data=request.data) if serializer.is_valid(): name = serializer.data.get('name') message = f'Hello {name}!' return Response({'message': message}) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) # RETRIEVE - gets a specific object by it's ID def retrieve(self, request, pk=None): """Handles getting an object by it's ID.""" return Response({'http_method': 'GET'}) # UPDATE - corresponds to the HTTP PUT def update(self, request, pk=None): """Handles updating an object.""" return Response({'http_method': 'PUT'}) # PARTIAL_UPDATE - corresponds to HTTP PATCH method def partial_update(self, request, pk=None): """Handles updating part of an object.""" return Response({'http_method': 'PATCH'}) # DESTROY - corresponds to HTTP DELETE method def destroy(self, request, pk=None): """Handles removing an object.""" return Response({'http_method': 'DELETE'}) ###Output _____no_output_____
01_Understanding and Visualizing Data with Python/Week_1 introduction to the field of statistics/01_introduction_jupyter.ipynb
###Markdown What is Jupyter Notebooks?Jupyter is a web-based interactive development environment that supports multiple programming languages, however most commonly used with the Python programming language.The interactive environment that Jupyter provides enables students, scientists, and researchers to create reproducible analysis and formulate a story within a single document.Lets take a look at an example of a completed Jupyter Notebook: [Example Notebook](http://nbviewer.jupyter.org/github/cossatot/lanf_earthquake_likelihood/blob/master/notebooks/lanf_manuscript_notebook.ipynb) Jupyter Notebook Features* File Browser* Markdown Cells & Syntax* Kernels, Variables, & Environment* Command vs. Edit Mode & Shortcuts What is Markdown?Markdown is a markup language that uses plain text formatting syntax. This means that we can modify the formatting our text with the use of various symbols on our keyboard as indicators.Some examples include:* Headers* Text modifications such as italics and bold* Ordered and Unordered lists* Links* Tables* Images* Etc.Now I'll showcase some examples of how this formatting is done: Headers: H1 H2 H3 H4 H5 H6 Text modifications:Emphasis, aka italics, with *asterisks* or _underscores_.Strong emphasis, aka bold, with **asterisks** or __underscores__.Combined emphasis with **asterisks and _underscores_**.Strikethrough uses two tildes. ~~Scratch this.~~ Lists:1. First ordered list item2. Another item * Unordered sub-list. 1. Actual numbers don't matter, just that it's a number 1. Ordered sub-list4. And another item.* Unordered list can use asterisks- Or minuses+ Or pluses Links:http://www.umich.edu[The University of Michigan's Homepage](www.http://umich.edu/)To look into more examples of Markdown syntax and features such as tables, images, etc. head to the following link: [Markdown Reference](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) Kernels, Variables, and EnvironmentA notebook kernel is a “computational engine” that executes the code contained in a Notebook document. There are kernels for various programming languages, however we are solely using the python kernel which executes python code.When a notebook is opened, the associated kernel is automatically launched for our convenience. ###Code ### This is python print("This is a python code cell") ###Output _____no_output_____ ###Markdown A kernel is the back-end of our notebook which not only executes our python code, but stores our initialized variables. ###Code ### For example, lets initialize variable x x = 1738 print("x has been set to " + str(x)) ### Print x print(x) ###Output _____no_output_____ ###Markdown Issues arrise when we restart our kernel and attempt to run code with variables that have not been reinitialized.If the kernel is reset, make sure to rerun code where variables are intialized. ###Code ## We can also run code that accepts input name = input("What is your name? ") print("The name you entered is " + name) ###Output _____no_output_____ ###Markdown It is important to note that Jupyter Notebooks have in-line cell execution. This means that a prior executing cell must complete its operations prior to another cell being executed. A cell still being executing is indicated by the [*] on the left-hand side of the cell. ###Code print("This won't print until all prior cells have finished executing.") ###Output _____no_output_____
Day 4/Hypothesis_Testing_tutorial1.ipynb
###Markdown Hypothesis TestingHypothesis testing is a critical tool in inferential statistics, for determing what the value of a population parameter could be.Statistical hypothesis testing reflects **the scientific method, adapted to the setting of research involving data analysis**. In this framework, a researcher makes a precise statement about the population of interest, then aims to falsify the statement. In statistical hypothesis testing, the statement in question is the **null hypothesis**. If we reject the null hypothesis, we have falsified it (to some degree of confidence). According to the scientific method, falsifying a hypothesis should require an overwhelming amount of evidence against it. If the data we observe are ambiguous, or are only weakly contradictory to the null hypothesis, we do not reject the null hypothesis.Basis of hypothesis testing has two attributes:**Null Hypothesis: $H_0$****Alternative Hypothesis: $H_a$**Various cases which are generally used in hypothesis testing are:* One Population Proportion* Difference in Population Proportions* One Population Mean* Difference in Population MeansThe equation to compute the ***test statistic*** is:$$test\ statistic = \frac{Best\ Estimate - Hypothesized\ Estimate}{Standard\ Error\ of\ Estimate}$$After computing this _test statistic_, we ask ourselves, "How likely is it to see this value of the test statistic under the Null hypothesis?" i.e. we compute a probability value.Depending on that probability, we either **reject or fail to reject the null hypothesis**. Note, we **do not accept the alternate hypothesis** because we can never ovserve all the data in the universe. Type-I and Type-II errorsThe framework of formal hypothesis testing defines two distinct types of errors. A **type I error (false positive)** occurs when the null hypothesis is true but is incorrectly rejected. A **type II error** occurs when the null hypothesis is not rejected when it actually is false. Most traditional methods for statistical inference aim to strictly control the probability of a type I error, usually at 5%. While we also wish to minimize the probability of a type II error, this is a secondary priority to controlling the type I error.Now let us see some widely used hypothesis testing types:- **T-test (Student test)**- **Z-test****t-test**: The t test (also called Student’s T Test) compares two averages (means) and tells you if they are different from each other. The t test also tells you how significant the differences are.There are two types of t-test:- **One sampled t-test**- **Two sampled t-test****One sample t-test**: The One Sample t Test determines whether the sample mean is statistically different from a known or hypothesized population mean. Let's create some dummy age data for the population of voters in the entire country (Senegal) and a sample of voters in Dakar and test the whether the average age of voters Dakar differs from the population: ###Code %matplotlib inline import statsmodels.api as sm import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import pandas as pd np.random.seed(6) population_ages1 = stats.poisson.rvs(loc=18, mu=35, size=150000) population_ages2 = stats.poisson.rvs(loc=18, mu=10, size=100000) population_ages = np.concatenate((population_ages1, population_ages2)) Dakar_ages1 = stats.poisson.rvs(loc=18, mu=30, size=30) Dakar_ages2 = stats.poisson.rvs(loc=18, mu=10, size=20) Dakar_ages = np.concatenate((Dakar_ages1, Dakar_ages2)) print( population_ages.mean() ) print( Dakar_ages.mean() ) population_ages ###Output _____no_output_____ ###Markdown Let's conduct a t-test at a 95% confidence level and see if it correctly rejects the null hypothesis that the sample comes from the same distribution as the population. To conduct a one sample t-test, we can the _**stats.ttest_1samp()**_ function: ###Code stats.ttest_1samp(a= Dakar_ages, # Sample data popmean= population_ages.mean()) # Pop mean ###Output _____no_output_____ ###Markdown As the p value = 0.013 < 0.05, we can reject the null hypothesis **Two-Sample T-Test**A two-sample t-test investigates whether the means of two independent data samples differ from one another. In a two-sample test, the null hypothesis is that the means of both groups are the same. Unlike the one sample-test where we test against a known population parameter, the two sample test only involves sample means. You can conduct a two-sample t-test by passing with the _**stats.ttest_ind()**_ function. Difference in Population meanLet's generate a sample of voter age data for Kaolack and test it against the sample we made earlier: ###Code np.random.seed(12) Kaolack_ages1 = stats.poisson.rvs(loc=18, mu=33, size=30) Kaolack_ages2 = stats.poisson.rvs(loc=18, mu=13, size=20) Kaolack_ages = np.concatenate((Kaolack_ages1, Kaolack_ages2)) print( Kaolack_ages.mean() ) stats.ttest_ind(a= Dakar_ages, b= Kaolack_ages, equal_var=False) ###Output _____no_output_____ ###Markdown If we were using a 95% confidence level we would fail to reject the null hypothesis, since the p-value is greater than the corresponding significance level of 5%. Difference in Population Proportions Research QuestionIs there a significant difference between the population proportions of parents of black children and parents of Hispanic children who report that their child has had some swimming lessons? **Parameter of Interest**: p1 - p2, where p1 = black and p2 = hispanic **Null Hypothesis:** p1 - p2 = 0 **Alternative Hypthosis:** p1 - p2 $\neq$ = 0 **Data**: 247 Parents of Black Children. 36.8% of parents report that their child has had some swimming lessons. 308 Parents of Hispanic Children. 38.9% of parents report that their child has had some swimming lessons. Use of `ttest_ind()` from `statsmodels`Difference in population proportion needs t-test. Also, the population follow a binomial distribution here. We can just pass on the two population quantities with the appropriate binomial distribution parameters to the t-test function.The function returns three values: (a) test statisic, (b) p-value of the t-test, and (c) degrees of freedom used in the t-test. ###Code n1 = 247 p1 = .37 n2 = 308 p2 = .39 population1 = np.random.binomial(1, p1, n1) population2 = np.random.binomial(1, p2, n2) sm.stats.ttest_ind(population1, population2) ###Output _____no_output_____ ###Markdown Conclusion of the hypothesis testSince the p-value = 0.68 > 0.05, we cannot reject the Null hypothesis in this case i.e. the difference in the population proportions are not statistically significant. But what happens if we could survey much higher number of people?We do not chnage the proportions, just the number of survey participants in the two population. The slight difference in the proportion could become statistically significant in this situation. There is no guarantee that when you run the code, you will get a p-value < 0.05 all the time as the samples are randomly generated each itme. But if you run it a few times, you will notice some p-values < 0.05 for sure. ###Code n1 = 5000 p1 = .37 n2 = 5000 p2 = .39 population1 = np.random.binomial(1, p1, n1) population2 = np.random.binomial(1, p2, n2) sm.stats.ttest_ind(population1, population2) ###Output _____no_output_____ ###Markdown The p-value is less than 0.05, we reject the null hypothesis Z-testA z-test is a statistical test used to determine whether two population means are different when the variances are known and the sample size is large. The test statistic is assumed to have a normal distribution, and nuisance parameters such as standard deviation should be known in order for an accurate z-test to be performed. One sampled z-testThe one sampled z-test is used to test wether the mean of the population is greater than, less than or not equal to a specific value. One Population Mean Research Question Let's say a cartwheeling competition was organized for some adults. The data looks like following,(80.57, 98.96, 85.28, 83.83, 69.94, 89.59, 91.09, 66.25, 91.21, 82.7 , 73.54, 81.99, 54.01, 82.89, 75.88, 98.32, 107.2 , 85.53, 79.08, 84.3 , 89.32, 86.35, 78.98, 92.26, 87.01)Is the average cartwheel distance (in inches) for adults more than 80 inches?**Population**: All adults **Parameter of Interest**: $\mu$, population mean cartwheel distance.**Null Hypothesis:** $\mu$ = 80 **Alternative Hypthosis**: $\mu$ > 80**Data**:25 adult participants. $\mu = 83.84$$\sigma = 10.72$ ###Code cwdata = np.array([80.57, 98.96, 85.28, 83.83, 69.94, 89.59, 91.09, 66.25, 91.21, 82.7 , 73.54, 81.99, 54.01, 82.89, 75.88, 98.32, 107.2 , 85.53, 79.08, 84.3 , 89.32, 86.35, 78.98, 92.26, 87.01]) n = len(cwdata) mean = cwdata.mean() sd = cwdata.std() (n, mean, sd) sm.stats.ztest(cwdata, value = 80, alternative = "larger") ###Output _____no_output_____ ###Markdown Conclusion of the hypothesis testSince the p-value (0.0394) is lower than the standard confidence level 0.05, we can reject the Null hypothesis that the mean cartwheel distance for adults (a population quantity) is equal to 80 inches. Difference in Population Means Research Question Considering adults in the [NHANES data](https://www.cdc.gov/nchs/nhanes/index.htm), do males have a significantly higher mean [Body Mass Index](https://www.cdc.gov/healthyweight/assessing/bmi/index.html) than females?**Population**: Adults in the NHANES data. **Parameter of Interest**: $\mu_1 - \mu_2$, Body Mass Index. **Null Hypothesis:** $\mu_1 = \mu_2$ **Alternative Hypthosis:** $\mu_1 \neq \mu_2$**Data:**2976 Females $\mu_1 = 29.94$ $\sigma_1 = 7.75$ 2759 Male Adults $\mu_2 = 28.78$ $\sigma_2 = 6.25$ $\mu_1 - \mu_2 = 1.16$ ###Code url = "https://raw.githubusercontent.com/kshedden/statswpy/master/NHANES/merged/nhanes_2015_2016.csv" da = pd.read_csv(url) da.head() females = da[da["RIAGENDR"] == 2] male = da[da["RIAGENDR"] == 1] n1 = len(females) mu1 = females["BMXBMI"].mean() sd1 = females["BMXBMI"].std() (n1, mu1, sd1) n2 = len(male) mu2 = male["BMXBMI"].mean() sd2 = male["BMXBMI"].std() (n2, mu2, sd2) sm.stats.ztest(females["BMXBMI"].dropna(), male["BMXBMI"].dropna(),alternative='two-sided') ###Output _____no_output_____
courses/machine_learning/deepdive2/structured/solutions/2_automl_tables_babyweight.ipynb
###Markdown LAB 2: AutoML Tables Babyweight Training.**Learning Objectives**1. Setup AutoML Tables1. Create and import AutoML Tables dataset from BigQuery1. Analyze AutoML Tables dataset1. Train AutoML Tables model1. Check evaluation metrics1. Deploy model1. Make batch predictions1. Make online predictions Introduction In this notebook, we will use AutoML Tables to train a model to predict the weight of a baby before it is born. We will use the AutoML Tables UI to create a training dataset from BigQuery and will then train, evaluate, and predict with a Auto ML Tables model.In this lab, we will setup AutoML Tables, create and import an AutoML Tables dataset from BigQuery, analyze AutoML Tables dataset, train an AutoML Tables model, check evaluation metrics of trained model, deploy trained model, and then finally make both batch and online predictions using the trained model.Each learning objective will correspond to a series of steps to complete in this student lab notebook. Verify tables existRun the following cells to verify that we previously created the dataset and data tables. If not, go back to lab [1b_prepare_data_babyweight](../solutions/1b_prepare_data_babyweight.ipynb) to create them. ###Code !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_augmented_data LIMIT 0 ###Output _____no_output_____ ###Markdown LAB 2: AutoML Tables Babyweight Training.**Learning Objectives**1. Setup AutoML Tables1. Create and import AutoML Tables dataset from BigQuery1. Analyze AutoML Tables dataset1. Train AutoML Tables model1. Check evaluation metrics1. Deploy model1. Make batch predictions1. Make online predictions Introduction In this notebook, we will use AutoML Tables to train a model to predict the weight of a baby before it is born. We will use the AutoML Tables UI to create a training dataset from BigQuery and will then train, evaluate, and predict with a Auto ML Tables model.In this lab, we will setup AutoML Tables, create and import an AutoML Tables dataset from BigQuery, analyze AutoML Tables dataset, train an AutoML Tables model, check evaluation metrics of trained model, deploy trained model, and then finally make both batch and online predictions using the trained model.Each learning objective will correspond to a series of steps to complete in this student lab notebook. Verify tables existRun the following cells to verify that we previously created the dataset and data tables. If not, go back to lab [1b_prepare_data_babyweight](../solutions/1b_prepare_data_babyweight.ipynb) to create them. ###Code %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_augmented_data LIMIT 0 ###Output _____no_output_____ ###Markdown LAB 2: AutoML Tables Babyweight Training.**Learning Objectives**1. Setup AutoML Tables1. Create and import AutoML Tables dataset from BigQuery1. Analyze AutoML Tables dataset1. Train AutoML Tables model1. Check evaluation metrics1. Deploy model1. Make batch predictions1. Make online predictions Introduction In this notebook, we will use AutoML Tables to train a model to predict the weight of a baby before it is born. We will use the AutoML Tables UI to create a training dataset from BigQuery and will then train, evaluate, and predict with a Auto ML Tables model.In this lab, we will setup AutoML Tables, create and import an AutoML Tables dataset from BigQuery, analyze AutoML Tables dataset, train an AutoML Tables model, check evaluation metrics of trained model, deploy trained model, and then finally make both batch and online predictions using the trained model.Each learning objective will correspond to a series of steps to complete in this student lab notebook. Verify tables existRun the following cells to verify that we previously created the dataset and data tables. If not, go back to lab [1b_prepare_data_babyweight](../solutions/1b_prepare_data_babyweight.ipynb) to create them. ###Code !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_augmented_data LIMIT 0 ###Output _____no_output_____ ###Markdown LAB 2: AutoML Tables Babyweight Training.**Learning Objectives**1. Setup AutoML Tables1. Create and import AutoML Tables dataset from BigQuery1. Analyze AutoML Tables dataset1. Train AutoML Tables model1. Check evaluation metrics1. Deploy model1. Make batch predictions1. Make online predictions Introduction In this notebook, we will use AutoML Tables to train a model to predict the weight of a baby before it is born. We will use the AutoML Tables UI to create a training dataset from BigQuery and will then train, evaluate, and predict with a Auto ML Tables model.In this lab, we will setup AutoML Tables, create and import an AutoML Tables dataset from BigQuery, analyze AutoML Tables dataset, train an AutoML Tables model, check evaluation metrics of trained model, deploy trained model, and then finally make both batch and online predictions using the trained model.Each learning objective will correspond to a series of steps to complete in this student lab notebook. Verify tables existRun the following cells to verify that we previously created the dataset and data tables. If not, go back to lab [1b_prepare_data_babyweight](../solutions/1b_prepare_data_babyweight.ipynb) to create them. ###Code %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_augmented_data LIMIT 0 ###Output _____no_output_____ ###Markdown LAB 2: AutoML Tables Babyweight Training.**Learning Objectives**1. Setup AutoML Tables1. Create and import AutoML Tables dataset from BigQuery1. Analyze AutoML Tables dataset1. Train AutoML Tables model1. Check evaluation metrics1. Deploy model1. Make batch predictions1. Make online predictions Introduction In this notebook, we will use AutoML Tables to train a model to predict the weight of a baby before it is born. We will use the AutoML Tables UI to create a training dataset from BigQuery and will then train, evaluate, and predict with a Auto ML Tables model.In this lab, we will setup AutoML Tables, create and import an AutoML Tables dataset from BigQuery, analyze AutoML Tables dataset, train an AutoML Tables model, check evaluation metrics of trained model, deploy trained model, and then finally make both batch and online predictions using the trained model.Each learning objective will correspond to a series of steps to complete in this student lab notebook. Verify tables existRun the following cells to verify that we previously created the dataset and data tables. If not, go back to lab [1b_prepare_data_babyweight](../solutions/1b_prepare_data_babyweight.ipynb) to create them. ###Code !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_augmented_data LIMIT 0 ###Output _____no_output_____ ###Markdown LAB 2: AutoML Tables Babyweight Training.**Learning Objectives**1. Setup AutoML Tables1. Create and import AutoML Tables dataset from BigQuery1. Analyze AutoML Tables dataset1. Train AutoML Tables model1. Check evaluation metrics1. Deploy model1. Make batch predictions1. Make online predictions Introduction In this notebook, we will use AutoML Tables to train a model to predict the weight of a baby before it is born. We will use the AutoML Tables UI to create a training dataset from BigQuery and will then train, evaluate, and predict with a Auto ML Tables model.In this lab, we will setup AutoML Tables, create and import an AutoML Tables dataset from BigQuery, analyze AutoML Tables dataset, train an AutoML Tables model, check evaluation metrics of trained model, deploy trained model, and then finally make both batch and online predictions using the trained model.Each learning objective will correspond to a series of steps to complete in this student lab notebook. Verify tables existRun the following cells to verify that we previously created the dataset and data tables. If not, go back to lab [1b_prepare_data_babyweight](../solutions/1b_prepare_data_babyweight.ipynb) to create them. ###Code !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_augmented_data LIMIT 0 ###Output _____no_output_____
Lecture_4.ipynb
###Markdown ![alt text](./image_files/pageheader_rose2_babies.jpg) Data Science in Medicine using Python Author: Dr Gusztav Belteki 1. Review of homework: slicing and dicing in PythonSubsetting and indexing pandas DataFrames ###Code a = 42; b = 'Hello World' dir() import os import pandas as pd filenames = ['CsvLogBase_2020-11-02_134238.904_slow_Measurement.csv.zip', ] data = {} for file in filenames: path = os.path.join('data', file,) data[file] = pd.read_csv(path) data data_all = pd.concat(data) data_all import os import pandas as pd path = os.path.join('data', 'CsvLogBase_2020-11-02_134238.904_slow_Measurement.csv.zip',) data = pd.read_csv(path) data data.info() data.head(5) # Select the third row only selection = data selection.loc[0] # Select the "MVe [L/min]" column only" selection = data['5001|MVe [L/min]'] selection data.columns # Select the "MVe [L/min]" and "MVi [L/min]" columns only columns_to_keep = ['5001|MVe [L/min]', '5001|MVi [L/min]'] selection = data[columns_to_keep] selection # Select the 'MVe [L/min]' value from the third row selection = data.iloc[2]['5001|MVe [L/min]'] selection type(selection) ###Output _____no_output_____ ###Markdown End-to-end analysis of tabular (two-dimensional data) using pandas ###Code pd.read_csv? ###Output _____no_output_____ ###Markdown You can also look it up on the internetm ###Code import os import pandas as pd path = os.path.join('data', 'CsvLogBase_2020-11-02_134238.904_slow_Measurement.csv.zip',) data = pd.read_csv(path) data len(data) data.shape data.ndim data.info() round(data.describe(), 2) data.head() data.tail() ###Output _____no_output_____ ###Markdown What is the problem with these data - Indexed by numbers only (uninformative, it should be indexed by date and time)- Date and time are in separate columnns- Date and time formats are not appropriate- Column names are too long and difficult to read- Lots of `na` values - half of every row is empty- Some columns have barely any informative values- Some values are not meaningful (e.g. tidal volume should be mL/kg not mL)*We will deal with all these issues* ###Code data.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 689436 entries, 0 to 689435 Data columns (total 47 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Time [ms] 689436 non-null int64 1 Date 689436 non-null object 2 Time 689436 non-null object 3 Rel.Time [s] 689436 non-null int64 4 5001|MVe [L/min] 344633 non-null float64 5 5001|MVi [L/min] 344633 non-null float64 6 5001|Cdyn [L/bar] 344073 non-null float64 7 5001|R [mbar/L/s] 342099 non-null float64 8 5001|MVespon [L/min] 344633 non-null float64 9 5001|Rpat [mbar/L/s] 341398 non-null float64 10 5001|MVemand [L/min] 344633 non-null float64 11 5001|FlowDev [L/min] 344677 non-null float64 12 5001|VTmand [mL] 344567 non-null float64 13 5001|r2 [no unit] 344538 non-null float64 14 5001|VTispon [mL] 344634 non-null float64 15 5001|Pmin [mbar] 344677 non-null float64 16 5001|Pmean [mbar] 344677 non-null float64 17 5001|PEEP [mbar] 344677 non-null float64 18 5001|RRmand [1/min] 344677 non-null float64 19 5001|PIP [mbar] 344677 non-null float64 20 5001|VTmand [L] 344567 non-null float64 21 5001|VTspon [L] 344634 non-null float64 22 5001|VTemand [mL] 344567 non-null float64 23 5001|VTespon [mL] 344634 non-null float64 24 5001|VTimand [mL] 344571 non-null float64 25 5001|VT [mL] 344567 non-null float64 26 5001|% leak [%] 344633 non-null float64 27 5001|RRspon [1/min] 256267 non-null float64 28 5001|% MVspon [%] 344633 non-null float64 29 5001|MV [L/min] 344633 non-null float64 30 5001|RRtrig [1/min] 344633 non-null float64 31 5001|RR [1/min] 344633 non-null float64 32 5001|I (I:E) [no unit] 344672 non-null float64 33 5001|E (I:E) [no unit] 344672 non-null float64 34 5001|FiO2 [%] 344677 non-null float64 35 5001|VTspon [mL] 344633 non-null float64 36 5001|E [mbar/L] 340217 non-null float64 37 5001|TC [s] 344051 non-null float64 38 5001|TCe [s] 344566 non-null float64 39 5001|C20/Cdyn [no unit] 339993 non-null float64 40 5001|VTe [mL] 344566 non-null float64 41 5001|VTi [mL] 344570 non-null float64 42 5001|EIP [mbar] 344676 non-null float64 43 5001|MVleak [L/min] 344632 non-null float64 44 5001|Tispon [s] 10015 non-null float64 45 5001|I:Espon (I-Part) [no unit] 9071 non-null float64 46 5001|I:Espon (E-Part) [no unit] 9071 non-null float64 dtypes: float64(43), int64(2), object(2) memory usage: 247.2+ MB ###Markdown 1. Convert the `date` and `time` columns to appropriate format Let us time how long the import takes ###Code # Let us time how long the import takes %%time path = os.path.join('data', 'CsvLogBase_2020-11-02_134238.904_slow_Measurement.csv.zip') data = pd.read_csv(path) data pd.read_csv? ###Output _____no_output_____ ###Markdown This takes much longer ###Code %%time path = os.path.join('data', 'CsvLogBase_2020-11-02_134238.904_slow_Measurement.csv.zip') lst = ['Date', 'Time'] data = pd.read_csv(path, parse_dates = lst) data data.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 689436 entries, 0 to 689435 Data columns (total 47 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Time [ms] 689436 non-null int64 1 Date 689436 non-null datetime64[ns] 2 Time 689436 non-null datetime64[ns] 3 Rel.Time [s] 689436 non-null int64 4 5001|MVe [L/min] 344633 non-null float64 5 5001|MVi [L/min] 344633 non-null float64 6 5001|Cdyn [L/bar] 344073 non-null float64 7 5001|R [mbar/L/s] 342099 non-null float64 8 5001|MVespon [L/min] 344633 non-null float64 9 5001|Rpat [mbar/L/s] 341398 non-null float64 10 5001|MVemand [L/min] 344633 non-null float64 11 5001|FlowDev [L/min] 344677 non-null float64 12 5001|VTmand [mL] 344567 non-null float64 13 5001|r2 [no unit] 344538 non-null float64 14 5001|VTispon [mL] 344634 non-null float64 15 5001|Pmin [mbar] 344677 non-null float64 16 5001|Pmean [mbar] 344677 non-null float64 17 5001|PEEP [mbar] 344677 non-null float64 18 5001|RRmand [1/min] 344677 non-null float64 19 5001|PIP [mbar] 344677 non-null float64 20 5001|VTmand [L] 344567 non-null float64 21 5001|VTspon [L] 344634 non-null float64 22 5001|VTemand [mL] 344567 non-null float64 23 5001|VTespon [mL] 344634 non-null float64 24 5001|VTimand [mL] 344571 non-null float64 25 5001|VT [mL] 344567 non-null float64 26 5001|% leak [%] 344633 non-null float64 27 5001|RRspon [1/min] 256267 non-null float64 28 5001|% MVspon [%] 344633 non-null float64 29 5001|MV [L/min] 344633 non-null float64 30 5001|RRtrig [1/min] 344633 non-null float64 31 5001|RR [1/min] 344633 non-null float64 32 5001|I (I:E) [no unit] 344672 non-null float64 33 5001|E (I:E) [no unit] 344672 non-null float64 34 5001|FiO2 [%] 344677 non-null float64 35 5001|VTspon [mL] 344633 non-null float64 36 5001|E [mbar/L] 340217 non-null float64 37 5001|TC [s] 344051 non-null float64 38 5001|TCe [s] 344566 non-null float64 39 5001|C20/Cdyn [no unit] 339993 non-null float64 40 5001|VTe [mL] 344566 non-null float64 41 5001|VTi [mL] 344570 non-null float64 42 5001|EIP [mbar] 344676 non-null float64 43 5001|MVleak [L/min] 344632 non-null float64 44 5001|Tispon [s] 10015 non-null float64 45 5001|I:Espon (I-Part) [no unit] 9071 non-null float64 46 5001|I:Espon (E-Part) [no unit] 9071 non-null float64 dtypes: datetime64[ns](2), float64(43), int64(2) memory usage: 247.2 MB ###Markdown There must be a better way !!!Google: **"How to combine date and time columns in pandas"** ###Code %%time path = os.path.join('data', 'CsvLogBase_2020-11-02_134238.904_slow_Measurement.csv.zip') data = pd.read_csv(path, parse_dates = [['Date', 'Time']]) data data.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 689436 entries, 0 to 689435 Data columns (total 46 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Date_Time 689436 non-null datetime64[ns] 1 Time [ms] 689436 non-null int64 2 Rel.Time [s] 689436 non-null int64 3 5001|MVe [L/min] 344633 non-null float64 4 5001|MVi [L/min] 344633 non-null float64 5 5001|Cdyn [L/bar] 344073 non-null float64 6 5001|R [mbar/L/s] 342099 non-null float64 7 5001|MVespon [L/min] 344633 non-null float64 8 5001|Rpat [mbar/L/s] 341398 non-null float64 9 5001|MVemand [L/min] 344633 non-null float64 10 5001|FlowDev [L/min] 344677 non-null float64 11 5001|VTmand [mL] 344567 non-null float64 12 5001|r2 [no unit] 344538 non-null float64 13 5001|VTispon [mL] 344634 non-null float64 14 5001|Pmin [mbar] 344677 non-null float64 15 5001|Pmean [mbar] 344677 non-null float64 16 5001|PEEP [mbar] 344677 non-null float64 17 5001|RRmand [1/min] 344677 non-null float64 18 5001|PIP [mbar] 344677 non-null float64 19 5001|VTmand [L] 344567 non-null float64 20 5001|VTspon [L] 344634 non-null float64 21 5001|VTemand [mL] 344567 non-null float64 22 5001|VTespon [mL] 344634 non-null float64 23 5001|VTimand [mL] 344571 non-null float64 24 5001|VT [mL] 344567 non-null float64 25 5001|% leak [%] 344633 non-null float64 26 5001|RRspon [1/min] 256267 non-null float64 27 5001|% MVspon [%] 344633 non-null float64 28 5001|MV [L/min] 344633 non-null float64 29 5001|RRtrig [1/min] 344633 non-null float64 30 5001|RR [1/min] 344633 non-null float64 31 5001|I (I:E) [no unit] 344672 non-null float64 32 5001|E (I:E) [no unit] 344672 non-null float64 33 5001|FiO2 [%] 344677 non-null float64 34 5001|VTspon [mL] 344633 non-null float64 35 5001|E [mbar/L] 340217 non-null float64 36 5001|TC [s] 344051 non-null float64 37 5001|TCe [s] 344566 non-null float64 38 5001|C20/Cdyn [no unit] 339993 non-null float64 39 5001|VTe [mL] 344566 non-null float64 40 5001|VTi [mL] 344570 non-null float64 41 5001|EIP [mbar] 344676 non-null float64 42 5001|MVleak [L/min] 344632 non-null float64 43 5001|Tispon [s] 10015 non-null float64 44 5001|I:Espon (I-Part) [no unit] 9071 non-null float64 45 5001|I:Espon (E-Part) [no unit] 9071 non-null float64 dtypes: datetime64[ns](1), float64(43), int64(2) memory usage: 242.0 MB ###Markdown 2. Set the `Date_Time` column as index ###Code data.head() data.index list(data.index)[:15] data = data.set_index('Date_Time') # Do not use inplace modifications data data.index ###Output _____no_output_____ ###Markdown 3. Change the clumsy column names ###Code data_columns = ['Time [ms]', 'Rel.Time [s]', 'MVe [L/min]', 'MVi [L/min]', 'Cdyn [L/bar]', 'R [mbar/L/s]', 'MVespon [L/min]', 'Rpat [mbar/L/s]', 'MVemand [L/min]', 'FlowDev [L/min]', 'VTmand [mL]', 'r2 [no unit]', 'VTispon [mL]', 'Pmin [mbar]', 'Pmean [mbar]', 'PEEP [mbar]', 'RRmand [1/min]', 'PIP [mbar]', 'VTmand [L]', 'VTspon [L]', 'VTemand [mL]', 'VTespon [mL]', 'VTimand [mL]', 'VT [mL]', '% leak [%]', 'RRspon [1/min]', '% MVspon [%]', 'MV [L/min]', 'RRtrig [1/min]', 'RR [1/min]', 'I (I:E) [no unit]', 'E (I:E) [no unit]', 'FiO2 [%]', 'VTspon [mL]', 'E [mbar/L]', 'TC [s]', 'TCe [s]', 'C20/Cdyn [no unit]', 'VTe [mL]', 'VTi [mL]', 'EIP [mbar]', 'MVleak [L/min]', 'Tispon [s]', 'I:Espon (I-Part) [no unit]', 'I:Espon (E-Part) [no unit]'] data.columns ###Output _____no_output_____ ###Markdown We could just replace it with `data.columns = ['...', '...', '...']` but that is error prone ###Code # Welcome to list comprehensions new_columns_1 = [item for item in data.columns] print(new_columns_1) new_columns_2 = [item[5:] for item in data.columns] print(new_columns_2) new_columns_3 = [item[5:] for item in data.columns if item.startswith('5001')] print(new_columns_3) # The expression to the right of `=` is evaluated firs (before assignment) new_columns_3 = ['Time [ms]', 'Rel.Time [s]'] + new_columns_3 print(new_columns_3) data.columns = new_columns_3 data.columns data.head() ###Output _____no_output_____ ###Markdown 4. Combine consecutive columns as they contain complementary data ###Code data.info() data.head(10) # This is called a `hack` # During `mean() na values are excluded by default data = data.resample('1S').mean() data.head(10) data.info() ###Output <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 344677 entries, 2020-11-02 13:42:39 to 2020-11-06 13:27:15 Freq: S Data columns (total 45 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Time [ms] 344677 non-null float64 1 Rel.Time [s] 344677 non-null float64 2 MVe [L/min] 344519 non-null float64 3 MVi [L/min] 344519 non-null float64 4 Cdyn [L/bar] 343959 non-null float64 5 R [mbar/L/s] 341986 non-null float64 6 MVespon [L/min] 344519 non-null float64 7 Rpat [mbar/L/s] 341285 non-null float64 8 MVemand [L/min] 344519 non-null float64 9 FlowDev [L/min] 344563 non-null float64 10 VTmand [mL] 344453 non-null float64 11 r2 [no unit] 344424 non-null float64 12 VTispon [mL] 344520 non-null float64 13 Pmin [mbar] 344563 non-null float64 14 Pmean [mbar] 344563 non-null float64 15 PEEP [mbar] 344563 non-null float64 16 RRmand [1/min] 344563 non-null float64 17 PIP [mbar] 344563 non-null float64 18 VTmand [L] 344453 non-null float64 19 VTspon [L] 344520 non-null float64 20 VTemand [mL] 344453 non-null float64 21 VTespon [mL] 344520 non-null float64 22 VTimand [mL] 344457 non-null float64 23 VT [mL] 344453 non-null float64 24 % leak [%] 344519 non-null float64 25 RRspon [1/min] 256176 non-null float64 26 % MVspon [%] 344519 non-null float64 27 MV [L/min] 344519 non-null float64 28 RRtrig [1/min] 344519 non-null float64 29 RR [1/min] 344519 non-null float64 30 I (I:E) [no unit] 344558 non-null float64 31 E (I:E) [no unit] 344558 non-null float64 32 FiO2 [%] 344563 non-null float64 33 VTspon [mL] 343318 non-null float64 34 E [mbar/L] 338973 non-null float64 35 TC [s] 342758 non-null float64 36 TCe [s] 343260 non-null float64 37 C20/Cdyn [no unit] 338726 non-null float64 38 VTe [mL] 343260 non-null float64 39 VTi [mL] 343265 non-null float64 40 EIP [mbar] 343361 non-null float64 41 MVleak [L/min] 343318 non-null float64 42 Tispon [s] 10011 non-null float64 43 I:Espon (I-Part) [no unit] 9056 non-null float64 44 I:Espon (E-Part) [no unit] 9056 non-null float64 dtypes: float64(45) memory usage: 121.0 MB ###Markdown Please recognise that these are already aggregate data !!! The numbers in the same colum do not necessary belong to the same observation (e.g. ventilator inflations) 5. Remove na values ###Code data.info() data.shape # Some columns are almost completely empty and hopeless - drop them columns_to_drop = ['Tispon [s]', 'I:Espon (I-Part) [no unit]', 'I:Espon (E-Part) [no unit]'] data = data.drop(columns_to_drop, axis = 1) data.info() data.isnull().sum() # How many data points are missing ? data.isnull().sum() # How many percent of data is missing data.isnull().sum() / len(data) * 100 ###Output _____no_output_____ ###Markdown A lot of things are happening here, for example vectorized computation, broadcasting We will speak about them during the next session. 6. Now let us save the processed data A. export them as `csv` files ###Code %%time path = os.path.join('results', 'data_processed') data.to_csv(path) ###Output CPU times: user 10.5 s, sys: 228 ms, total: 10.7 s Wall time: 10.8 s ###Markdown B. export az Excel file This will run for a long time ###Code %%time path = os.path.join('data', 'data_processed.xlsx') data.to_excel(path, sheet_name = 'processed_data') ###Output _____no_output_____ ###Markdown C. export them as serialised binary data - `pickle` ###Code %%time import pickle path = os.path.join('results', 'data_processed.pickle') filehandle = open(path, 'wb') pickle.dump(data, filehandle) filehandle.close() %%time import pickle path = os.path.join('results', 'data_processed.pickle') filehandle = open(os.path.join(path), 'rb') data_processed = pickle.load(filehandle) filehandle.close() data_processed ###Output CPU times: user 29.6 ms, sys: 62.9 ms, total: 92.5 ms Wall time: 93.3 ms ###Markdown To be continued... 6. Homework 1. Further explorative analysis on data ###Code # Select all data during the 1 minute period at 2020-11-03 13:00 selection = data selection # Select all data between 2020-11-03 13:00 and and 15:00 selection = data selection # Select all data between 2020-11-03 13:00 and and 15:00 and limit it to # "MVe [L/min]" and "MVi [L/min]" columns only selection = data selection ###Output _____no_output_____ ###Markdown Lecture 4 use SQL Review Python ###Code demo_str = 'this is my string' for word_item in demo_str.split(): print(word_item) print(' {} + {} is {} '.format(1,2,1+2)) ###Output 1 + 2 is 3 ###Markdown Install or import libs ###Code !pip install psycopg2 import pandas import configparser import psycopg2 ###Output /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) ###Markdown Establish connection ###Code config = configparser.ConfigParser() config.read('config.ini') host = config['myaws']['host'] db=config['myaws']['db'] user=config['myaws']['user'] pwd=config['myaws']['pwd'] conn = psycopg2.connect( host = host, user = user, password = pwd, dbname=db ) ###Output _____no_output_____ ###Markdown Regression Metrics ###Code %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_boston data = load_boston() from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) from sklearn.linear_model import LinearRegression clf = LinearRegression() clf.fit(X_train, y_train) predicted = clf.predict(X_test) expected = y_test import sklearn.metrics as sm print(clf.coef_) # RMSE as the same units as the quantity estimated, can normalize if needed print("RMSE: %s" % np.sqrt(sm.mean_squared_error(expected, predicted))) # proportion of variance which is explained by the model print("R^2: %s" % sm.r2_score(expected, predicted)) # MedAE median absolute error is robust to outliers print("MedAE: %s" % sm.median_absolute_error(expected, predicted)) # using normalized data (general model fit is the same, but coefficients are # more easily compared) print("Using normalized data") from sklearn.preprocessing import normalize #normalize using default (l2) normalization data.data = normalize(data.data) X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) clf = LinearRegression() clf.fit(X_train, y_train) predicted = clf.predict(X_test) expected = y_test import sklearn.metrics as sm print(clf.coef_) # RMSE as the same units as the quantity estimated, can normalize if needed print("RMSE: %s" % np.sqrt(sm.mean_squared_error(expected, predicted))) # proportion of variance which is explained by the model print("R^2: %s" % sm.r2_score(expected, predicted)) # MedAE median absolute error is robust to outliers print("MedAE: %s" % sm.median_absolute_error(expected, predicted)) ###Output _____no_output_____ ###Markdown Classification metrics ###Code from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_breast_cancer from sklearn import metrics, neighbors, svm, calibration, tree cancer = load_breast_cancer() #print(cancer.DESCR) X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, random_state=0, test_size=0.25) def test_model(model): model.fit(X_train, y_train) y_predict = model.predict(X_test) print("%s: %f" % (str(model), metrics.accuracy_score(y_test, y_predict))) print(metrics.classification_report(y_test, y_predict)) y_predict_proba = model.predict_proba(X_test) fpr, tpr, _ = metrics.roc_curve(y_test, y_predict_proba[:,1]) roc_auc = metrics.auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show() test_model(LogisticRegression()) test_model(neighbors.KNeighborsClassifier(n_neighbors=1)) test_model(neighbors.KNeighborsClassifier(n_neighbors=16)) test_model(svm.SVC(kernel='linear',probability=True)) test_model(calibration.CalibratedClassifierCV(svm.LinearSVC())) test_model(tree.DecisionTreeClassifier()) ###Output /usr/local/lib/python3.6/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning. FutureWarning) ###Markdown Tuning for Bias / Variance ###Code # find the best KNeighborsClassifier from sklearn.model_selection import validation_curve nneighbors = np.arange(1,51) train_scores, validation_scores = validation_curve( neighbors.KNeighborsClassifier(), cancer.data, cancer.target, param_name='n_neighbors', param_range=nneighbors, cv=5) # Plot the mean train error and validation error across folds plt.figure(figsize=(6, 4)) plt.plot(nneighbors, validation_scores.mean(axis=1), lw=2, label='cross-validation') plt.plot(nneighbors, train_scores.mean(axis=1), lw=2, label='training') plt.legend(loc='best') plt.xlabel('number of neighbors') plt.ylabel('explained variance') plt.title('Validation curve') plt.tight_layout() test_model(neighbors.KNeighborsClassifier(n_neighbors=np.argmax(np.mean(validation_scores, axis=1))+1)) ###Output KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=None, n_neighbors=13, p=2, weights='uniform'): 0.958042 precision recall f1-score support 0 0.96 0.92 0.94 53 1 0.96 0.98 0.97 90 accuracy 0.96 143 macro avg 0.96 0.95 0.95 143 weighted avg 0.96 0.96 0.96 143 ###Markdown Electronic Medical Records ###Code #download 100patients.zip from google drive !pip install -U -q PyDrive from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # 1. Authenticate and create the PyDrive client. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) # 2. Download actual file file_patients = drive.CreateFile({'id': '1BKA073MRD3WLuHutN-sZug9vtPVgW0Lg'}) file_patients.GetContentFile('100-patients.zip') !ls !unzip 100-patients.zip import pandas as pd df_patients = pd.read_table('PatientCorePopulatedTable.txt') df_patients.set_index('PatientID') df_labs = pd.read_table('LabsCorePopulatedTable.txt') df_admcore = pd.read_table('AdmissionsCorePopulatedTable.txt') df_admdiag = pd.read_table('AdmissionsDiagnosesCorePopulatedTable.txt') tables = [df_patients, df_labs, df_admcore, df_admdiag] #print(df_patients) for df in tables: print(df.info()) print(df.head()) myloid = df_admdiag[df_admdiag['PrimaryDiagnosisCode'].str.startswith("C92")] print(myloid) print(df_admdiag[df_admdiag['PrimaryDiagnosisDescription'].str.contains("leukemia")]) print(myloid.merge(df_patients,on='PatientID')) ###Output PatientID ... PrimaryDiagnosisDescription 2 80AC01B2-BD55-4BE0-A59A-4024104CF4E9 ... Chronic myeloid leukemia, BCR/ABL-positive 25 0681FA35-A794-4684-97BD-00B88370DB41 ... Acute myelomonocytic leukemia, in remission 58 1A40AF35-C6D4-4D46-B475-A15D84E8A9D5 ... Acute myeloblastic leukemia 102 1A8791E3-A61C-455A-8DEE-763EB90C9B2C ... Acute myelomonocytic leukemia, not having achi... 140 8D389A8C-A6D8-4447-9DDE-1A28AB4EC667 ... Chronic myeloid leukemia, BCR/ABL-positive, in... [5 rows x 4 columns] PatientID ... PrimaryDiagnosisDescription 2 80AC01B2-BD55-4BE0-A59A-4024104CF4E9 ... Chronic myeloid leukemia, BCR/ABL-positive 4 6A57AC0C-57F3-4C19-98A1-51135EFBC4FF ... Acute lymphoblastic leukemia not having achiev... 25 0681FA35-A794-4684-97BD-00B88370DB41 ... Acute myelomonocytic leukemia, in remission 58 1A40AF35-C6D4-4D46-B475-A15D84E8A9D5 ... Acute myeloblastic leukemia 97 F0B53A2C-98CA-415D-B928-E3FD0E52B22A ... Acute erythroid leukemia, in relapse 102 1A8791E3-A61C-455A-8DEE-763EB90C9B2C ... Acute myelomonocytic leukemia, not having achi... 126 FFCDECD6-4048-4DCB-B910-1218160005B3 ... Hairy cell leukemia, in relapse 133 69CC25ED-A54A-4BAF-97E3-774BB3C9DED1 ... Adult T-cell lymphoma/leukemia (HTLV-1-associa... 138 69B5D2A0-12FD-46EF-A5FF-B29C4BAFBE49 ... Acute erythroid leukemia 140 8D389A8C-A6D8-4447-9DDE-1A28AB4EC667 ... Chronic myeloid leukemia, BCR/ABL-positive, in... 194 B2EB15FA-5431-4804-9309-4215BDC778C0 ... Chronic lymphocytic leukemia of B-cell type 232 98F593D2-8894-49BB-93B9-5A0E2CF85E2E ... Mast cell leukemia, in relapse 241 7A7332AD-88B1-4848-9356-E5260E477C59 ... Acute lymphoblastic leukemia [ALL] 251 03A481F5-B32A-4A91-BD42-43EB78FEBA77 ... Acute megakaryoblastic leukemia, in relapse 274 6623F5D6-D581-4268-9F9B-21612FBBF7B5 ... Mast cell leukemia, in relapse 311 B39DC5AC-E003-4E6A-91B6-FC07625A1285 ... Acute monoblastic/monocytic leukemia, in remis... [16 rows x 4 columns] PatientID ... PatientPopulationPercentageBelowPoverty 0 80AC01B2-BD55-4BE0-A59A-4024104CF4E9 ... 19.74 1 0681FA35-A794-4684-97BD-00B88370DB41 ... 19.16 2 1A40AF35-C6D4-4D46-B475-A15D84E8A9D5 ... 11.25 3 1A8791E3-A61C-455A-8DEE-763EB90C9B2C ... 13.97 4 8D389A8C-A6D8-4447-9DDE-1A28AB4EC667 ... 4.34 [5 rows x 10 columns]
vui/vui_notebook.ipynb
###Markdown Artificial Intelligence Nanodegree Voice User Interfaces Project: Speech Recognition with Neural Networks---In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with **'(IMPLEMENTATION)'** in the header indicate that the following blocks of code will require additional functionality which you must provide. Please be sure to read the instructions carefully! > **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.The rubric contains _optional_ "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.--- Introduction In this notebook, you will build a deep neural network that functions as part of an end-to-end automatic speech recognition (ASR) pipeline! Your completed pipeline will accept raw audio as input and return a predicted transcription of the spoken language. The full pipeline is summarized in the figure below.- **STEP 1** is a pre-processing step that converts raw audio to one of two feature representations that are commonly used for ASR. - **STEP 2** is an acoustic model which accepts audio features as input and returns a probability distribution over all potential transcriptions. After learning about the basic types of neural networks that are often used for acoustic modeling, you will engage in your own investigations, to design your own acoustic model!- **STEP 3** in the pipeline takes the output from the acoustic model and returns a predicted transcription. Feel free to use the links below to navigate the notebook:- [The Data](thedata)- [**STEP 1**](step1): Acoustic Features for Speech Recognition- [**STEP 2**](step2): Deep Neural Networks for Acoustic Modeling - [Model 0](model0): RNN - [Model 1](model1): RNN + TimeDistributed Dense - [Model 2](model2): CNN + RNN + TimeDistributed Dense - [Model 3](model3): Deeper RNN + TimeDistributed Dense - [Model 4](model4): Bidirectional RNN + TimeDistributed Dense - [Models 5+](model5) - [Compare the Models](compare) - [Final Model](final)- [**STEP 3**](step3): Obtain Predictions The DataWe begin by investigating the dataset that will be used to train and evaluate your pipeline. [LibriSpeech](http://www.danielpovey.com/files/2015_icassp_librispeech.pdf) is a large corpus of English-read speech, designed for training and evaluating models for ASR. The dataset contains 1000 hours of speech derived from audiobooks. We will work with a small subset in this project, since larger-scale data would take a long while to train. However, after completing this project, if you are interested in exploring further, you are encouraged to work with more of the data that is provided [online](http://www.openslr.org/12/).In the code cells below, you will use the `vis_train_features` module to visualize a training example. The supplied argument `index=0` tells the module to extract the first example in the training set. (You are welcome to change `index=0` to point to a different training example, if you like, but please **DO NOT** amend any other code in the cell.) The returned variables are:- `vis_text` - transcribed text (label) for the training example.- `vis_raw_audio` - raw audio waveform for the training example.- `vis_mfcc_feature` - mel-frequency cepstral coefficients (MFCCs) for the training example.- `vis_spectrogram_feature` - spectrogram for the training example. - `vis_audio_path` - the file path to the training example. ###Code from data_generator import vis_train_features # extract label and audio features for a single training example vis_text, vis_raw_audio, vis_mfcc_feature, vis_spectrogram_feature, vis_audio_path = vis_train_features() ###Output There are 2136 total training examples. ###Markdown The following code cell visualizes the audio waveform for your chosen example, along with the corresponding transcript. You also have the option to play the audio in the notebook! ###Code from IPython.display import Markdown, display from data_generator import vis_train_features, plot_raw_audio from IPython.display import Audio %matplotlib inline # plot audio signal plot_raw_audio(vis_raw_audio) # print length of audio signal display(Markdown('**Shape of Audio Signal** : ' + str(vis_raw_audio.shape))) # print transcript corresponding to audio clip display(Markdown('**Transcript** : ' + str(vis_text))) # play the audio file Audio(vis_audio_path) ###Output _____no_output_____ ###Markdown STEP 1: Acoustic Features for Speech RecognitionFor this project, you won't use the raw audio waveform as input to your model. Instead, we provide code that first performs a pre-processing step to convert the raw audio to a feature representation that has historically proven successful for ASR models. Your acoustic model will accept the feature representation as input.In this project, you will explore two possible feature representations. _After completing the project_, if you'd like to read more about deep learning architectures that can accept raw audio input, you are encouraged to explore this [research paper](https://pdfs.semanticscholar.org/a566/cd4a8623d661a4931814d9dffc72ecbf63c4.pdf). SpectrogramsThe first option for an audio feature representation is the [spectrogram](https://www.youtube.com/watch?v=_FatxGN3vAM). In order to complete this project, you will **not** need to dig deeply into the details of how a spectrogram is calculated; but, if you are curious, the code for calculating the spectrogram was borrowed from [this repository](https://github.com/baidu-research/ba-dls-deepspeech). The implementation appears in the `utils.py` file in your repository.The code that we give you returns the spectrogram as a 2D tensor, where the first (_vertical_) dimension indexes time, and the second (_horizontal_) dimension indexes frequency. To speed the convergence of your algorithm, we have also normalized the spectrogram. (You can see this quickly in the visualization below by noting that the mean value hovers around zero, and most entries in the tensor assume values close to zero.) ###Code from data_generator import plot_spectrogram_feature # plot normalized spectrogram plot_spectrogram_feature(vis_spectrogram_feature) # print shape of spectrogram display(Markdown('**Shape of Spectrogram** : ' + str(vis_spectrogram_feature.shape))) ###Output _____no_output_____ ###Markdown Mel-Frequency Cepstral Coefficients (MFCCs)The second option for an audio feature representation is [MFCCs](https://en.wikipedia.org/wiki/Mel-frequency_cepstrum). You do **not** need to dig deeply into the details of how MFCCs are calculated, but if you would like more information, you are welcome to peruse the [documentation](https://github.com/jameslyons/python_speech_features) of the `python_speech_features` Python package. Just as with the spectrogram features, the MFCCs are normalized in the supplied code.The main idea behind MFCC features is the same as spectrogram features: at each time window, the MFCC feature yields a feature vector that characterizes the sound within the window. Note that the MFCC feature is much lower-dimensional than the spectrogram feature, which could help an acoustic model to avoid overfitting to the training dataset. ###Code from data_generator import plot_mfcc_feature # plot normalized MFCC plot_mfcc_feature(vis_mfcc_feature) # print shape of MFCC display(Markdown('**Shape of MFCC** : ' + str(vis_mfcc_feature.shape))) ###Output _____no_output_____ ###Markdown When you construct your pipeline, you will be able to choose to use either spectrogram or MFCC features. If you would like to see different implementations that make use of MFCCs and/or spectrograms, please check out the links below:- This [repository](https://github.com/baidu-research/ba-dls-deepspeech) uses spectrograms.- This [repository](https://github.com/mozilla/DeepSpeech) uses MFCCs.- This [repository](https://github.com/buriburisuri/speech-to-text-wavenet) also uses MFCCs.- This [repository](https://github.com/pannous/tensorflow-speech-recognition/blob/master/speech_data.py) experiments with raw audio, spectrograms, and MFCCs as features. STEP 2: Deep Neural Networks for Acoustic ModelingIn this section, you will experiment with various neural network architectures for acoustic modeling. You will begin by training five relatively simple architectures. **Model 0** is provided for you. You will write code to implement **Models 1**, **2**, **3**, and **4**. If you would like to experiment further, you are welcome to create and train more models under the **Models 5+** heading. All models will be specified in the `sample_models.py` file. After importing the `sample_models` module, you will train your architectures in the notebook.After experimenting with the five simple architectures, you will have the opportunity to compare their performance. Based on your findings, you will construct a deeper architecture that is designed to outperform all of the shallow models.For your convenience, we have designed the notebook so that each model can be specified and trained on separate occasions. That is, say you decide to take a break from the notebook after training **Model 1**. Then, you need not re-execute all prior code cells in the notebook before training **Model 2**. You need only re-execute the code cell below, that is marked with **`RUN THIS CODE CELL IF YOU ARE RESUMING THE NOTEBOOK AFTER A BREAK`**, before transitioning to the code cells corresponding to **Model 2**. ###Code ##################################################################### # RUN THIS CODE CELL IF YOU ARE RESUMING THE NOTEBOOK AFTER A BREAK # ##################################################################### # allocate 50% of GPU memory (if you like, feel free to change this) from keras.backend.tensorflow_backend import set_session import tensorflow as tf config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.5 set_session(tf.Session(config=config)) # watch for any changes in the sample_models module, and reload it automatically %load_ext autoreload %autoreload 2 # import NN architectures for speech recognition from sample_models import * # import function for training acoustic model from train_utils import train_model ###Output Using TensorFlow backend. ###Markdown Model 0: RNNGiven their effectiveness in modeling sequential data, the first acoustic model you will use is an RNN. As shown in the figure below, the RNN we supply to you will take the time sequence of audio features as input.At each time step, the speaker pronounces one of 28 possible characters, including each of the 26 letters in the English alphabet, along with a space character (" "), and an apostrophe (').The output of the RNN at each time step is a vector of probabilities with 29 entries, where the $i$-th entry encodes the probability that the $i$-th character is spoken in the time sequence. (The extra 29th character is an empty "character" used to pad training examples within batches containing uneven lengths.) If you would like to peek under the hood at how characters are mapped to indices in the probability vector, look at the `char_map.py` file in the repository. The figure below shows an equivalent, rolled depiction of the RNN that shows the output layer in greater detail. The model has already been specified for you in Keras. To import it, you need only run the code cell below. ###Code from sample_models import * model_0 = simple_rnn_model(input_dim=161) # change to 13 if you would like to use MFCC features ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= the_input (InputLayer) (None, None, 161) 0 _________________________________________________________________ rnn (GRU) (None, None, 29) 16617 _________________________________________________________________ softmax (Activation) (None, None, 29) 0 ================================================================= Total params: 16,617 Trainable params: 16,617 Non-trainable params: 0 _________________________________________________________________ None ###Markdown As explored in the lesson, you will train the acoustic model with the [CTC loss](http://www.cs.toronto.edu/~graves/icml_2006.pdf) criterion. Custom loss functions take a bit of hacking in Keras, and so we have implemented the CTC loss function for you, so that you can focus on trying out as many deep learning architectures as possible :). If you'd like to peek at the implementation details, look at the `add_ctc_loss` function within the `train_utils.py` file in the repository.To train your architecture, you will use the `train_model` function within the `train_utils` module; it has already been imported in one of the above code cells. The `train_model` function takes three **required** arguments:- `input_to_softmax` - a Keras model instance.- `pickle_path` - the name of the pickle file where the loss history will be saved.- `save_model_path` - the name of the HDF5 file where the model will be saved.If we have already supplied values for `input_to_softmax`, `pickle_path`, and `save_model_path`, please **DO NOT** modify these values. There are several **optional** arguments that allow you to have more control over the training process. You are welcome to, but not required to, supply your own values for these arguments.- `minibatch_size` - the size of the minibatches that are generated while training the model (default: `20`).- `spectrogram` - Boolean value dictating whether spectrogram (`True`) or MFCC (`False`) features are used for training (default: `True`).- `mfcc_dim` - the size of the feature dimension to use when generating MFCC features (default: `13`).- `optimizer` - the Keras optimizer used to train the model (default: `SGD(lr=0.02, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)`). - `epochs` - the number of epochs to use to train the model (default: `20`). If you choose to modify this parameter, make sure that it is *at least* 20.- `verbose` - controls the verbosity of the training output in the `model.fit_generator` method (default: `1`).- `sort_by_duration` - Boolean value dictating whether the training and validation sets are sorted by (increasing) duration before the start of the first epoch (default: `False`).The `train_model` function defaults to using spectrogram features; if you choose to use these features, note that the acoustic model in `simple_rnn_model` should have `input_dim=161`. Otherwise, if you choose to use MFCC features, the acoustic model should have `input_dim=13`.We have chosen to use `GRU` units in the supplied RNN. If you would like to experiment with `LSTM` or `SimpleRNN` cells, feel free to do so here. If you change the `GRU` units to `SimpleRNN` cells in `simple_rnn_model`, you may notice that the loss quickly becomes undefined (`nan`) - you are strongly encouraged to check this for yourself! This is due to the [exploding gradients problem](http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/). We have already implemented [gradient clipping](https://arxiv.org/pdf/1211.5063.pdf) in your optimizer to help you avoid this issue.__IMPORTANT NOTE:__ If you notice that your gradient has exploded in any of the models below, feel free to explore more with gradient clipping (the `clipnorm` argument in your optimizer) or swap out any `SimpleRNN` cells for `LSTM` or `GRU` cells. You can also try restarting the kernel to restart the training process. ###Code from train_utils import train_model train_model(input_to_softmax=model_0, pickle_path='model_0.pickle', save_model_path='model_0.h5', spectrogram=True) # change to False if you would like to use MFCC features ###Output Epoch 1/20 106/106 [==============================] - 201s 2s/step - loss: 832.3758 - val_loss: 727.4456 Epoch 2/20 106/106 [==============================] - 201s 2s/step - loss: 752.5418 - val_loss: 721.4544 Epoch 3/20 106/106 [==============================] - 200s 2s/step - loss: 751.8712 - val_loss: 730.7420 Epoch 4/20 106/106 [==============================] - 197s 2s/step - loss: 751.5974 - val_loss: 734.5410 Epoch 5/20 106/106 [==============================] - 196s 2s/step - loss: 752.5842 - val_loss: 717.3582 Epoch 6/20 106/106 [==============================] - 197s 2s/step - loss: 751.0046 - val_loss: 726.0532 Epoch 7/20 106/106 [==============================] - 197s 2s/step - loss: 752.4638 - val_loss: 726.9816 Epoch 8/20 106/106 [==============================] - 198s 2s/step - loss: 752.5248 - val_loss: 728.5321 Epoch 9/20 106/106 [==============================] - 197s 2s/step - loss: 751.4070 - val_loss: 725.8266 Epoch 10/20 106/106 [==============================] - 197s 2s/step - loss: 751.6268 - val_loss: 723.0809 Epoch 11/20 106/106 [==============================] - 196s 2s/step - loss: 751.6480 - val_loss: 725.8229 Epoch 12/20 106/106 [==============================] - 196s 2s/step - loss: 751.9354 - val_loss: 724.9918 Epoch 13/20 106/106 [==============================] - 196s 2s/step - loss: 751.0907 - val_loss: 724.6436 Epoch 14/20 106/106 [==============================] - 198s 2s/step - loss: 751.4871 - val_loss: 726.7535 Epoch 15/20 106/106 [==============================] - 196s 2s/step - loss: 751.1905 - val_loss: 722.4764 Epoch 16/20 106/106 [==============================] - 198s 2s/step - loss: 750.6781 - val_loss: 723.2440 Epoch 17/20 106/106 [==============================] - 197s 2s/step - loss: 750.9423 - val_loss: 729.6451 Epoch 18/20 106/106 [==============================] - 198s 2s/step - loss: 750.6979 - val_loss: 724.0448 Epoch 19/20 106/106 [==============================] - 198s 2s/step - loss: 751.4984 - val_loss: 731.4728 Epoch 20/20 106/106 [==============================] - 197s 2s/step - loss: 751.4527 - val_loss: 724.0936 ###Markdown (IMPLEMENTATION) Model 1: RNN + TimeDistributed DenseRead about the [TimeDistributed](https://keras.io/layers/wrappers/) wrapper and the [BatchNormalization](https://keras.io/layers/normalization/) layer in the Keras documentation. For your next architecture, you will add [batch normalization](https://arxiv.org/pdf/1510.01378.pdf) to the recurrent layer to reduce training times. The `TimeDistributed` layer will be used to find more complex patterns in the dataset. The unrolled snapshot of the architecture is depicted below.The next figure shows an equivalent, rolled depiction of the RNN that shows the (`TimeDistrbuted`) dense and output layers in greater detail. Use your research to complete the `rnn_model` function within the `sample_models.py` file. The function should specify an architecture that satisfies the following requirements:- The first layer of the neural network should be an RNN (`SimpleRNN`, `LSTM`, or `GRU`) that takes the time sequence of audio features as input. We have added `GRU` units for you, but feel free to change `GRU` to `SimpleRNN` or `LSTM`, if you like!- Whereas the architecture in `simple_rnn_model` treated the RNN output as the final layer of the model, you will use the output of your RNN as a hidden layer. Use `TimeDistributed` to apply a `Dense` layer to each of the time steps in the RNN output. Ensure that each `Dense` layer has `output_dim` units.Use the code cell below to load your model into the `model_1` variable. Use a value for `input_dim` that matches your chosen audio features, and feel free to change the values for `units` and `activation` to tweak the behavior of your recurrent layer. ###Code model_1 = rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features units=200, activation='relu') ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= the_input (InputLayer) (None, None, 161) 0 _________________________________________________________________ rnn (GRU) (None, None, 200) 217200 _________________________________________________________________ bn_rnn (BatchNormalization) (None, None, 200) 800 _________________________________________________________________ time_distributed_1 (TimeDist (None, None, 29) 5829 _________________________________________________________________ softmax (Activation) (None, None, 29) 0 ================================================================= Total params: 223,829 Trainable params: 223,429 Non-trainable params: 400 _________________________________________________________________ None ###Markdown Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_1.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_1.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ###Code train_model(input_to_softmax=model_1, pickle_path='model_1.pickle', save_model_path='model_1.h5', spectrogram=True) # change to False if you would like to use MFCC features ###Output Epoch 1/20 106/106 [==============================] - 200s 2s/step - loss: 271.5375 - val_loss: 215.2374 Epoch 2/20 106/106 [==============================] - 201s 2s/step - loss: 226.0123 - val_loss: 226.9614 Epoch 3/20 106/106 [==============================] - 198s 2s/step - loss: 225.5427 - val_loss: 214.1131 Epoch 4/20 106/106 [==============================] - 198s 2s/step - loss: 224.8475 - val_loss: 218.0052 Epoch 5/20 106/106 [==============================] - 198s 2s/step - loss: 224.4640 - val_loss: 215.0090 Epoch 6/20 106/106 [==============================] - 197s 2s/step - loss: 224.8359 - val_loss: 210.9995 Epoch 7/20 106/106 [==============================] - 199s 2s/step - loss: 224.5322 - val_loss: 214.6766 Epoch 8/20 106/106 [==============================] - 198s 2s/step - loss: 224.6650 - val_loss: 213.1127 Epoch 10/20 106/106 [==============================] - 198s 2s/step - loss: 224.3817 - val_loss: 213.9965 Epoch 11/20 106/106 [==============================] - 198s 2s/step - loss: 224.4028 - val_loss: 214.6676 Epoch 12/20 106/106 [==============================] - 198s 2s/step - loss: 224.6196 - val_loss: 213.3244 Epoch 13/20 106/106 [==============================] - 198s 2s/step - loss: 224.3800 - val_loss: 212.8022 Epoch 14/20 106/106 [==============================] - 197s 2s/step - loss: 224.2215 - val_loss: 216.0779 Epoch 15/20 106/106 [==============================] - 197s 2s/step - loss: 224.4581 - val_loss: 212.5886 Epoch 16/20 106/106 [==============================] - 198s 2s/step - loss: 224.1820 - val_loss: 213.6726 Epoch 17/20 106/106 [==============================] - 198s 2s/step - loss: 224.1731 - val_loss: 212.3718 Epoch 18/20 106/106 [==============================] - 198s 2s/step - loss: 224.1342 - val_loss: 214.6201 Epoch 19/20 106/106 [==============================] - 198s 2s/step - loss: 224.1194 - val_loss: 211.2834 Epoch 20/20 106/106 [==============================] - 200s 2s/step - loss: 224.0086 - val_loss: 214.5752 ###Markdown (IMPLEMENTATION) Model 2: CNN + RNN + TimeDistributed DenseThe architecture in `cnn_rnn_model` adds an additional level of complexity, by introducing a [1D convolution layer](https://keras.io/layers/convolutional/conv1d). This layer incorporates many arguments that can be (optionally) tuned when calling the `cnn_rnn_model` module. We provide sample starting parameters, which you might find useful if you choose to use spectrogram audio features. If you instead want to use MFCC features, these arguments will have to be tuned. Note that the current architecture only supports values of `'same'` or `'valid'` for the `conv_border_mode` argument.When tuning the parameters, be careful not to choose settings that make the convolutional layer overly small. If the temporal length of the CNN layer is shorter than the length of the transcribed text label, your code will throw an error.Before running the code cell below, you must modify the `cnn_rnn_model` function in `sample_models.py`. Please add batch normalization to the recurrent layer, and provide the same `TimeDistributed` layer as before. ###Code model_2 = cnn_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=2, conv_border_mode='valid', units=200) ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= the_input (InputLayer) (None, None, 161) 0 _________________________________________________________________ conv1d (Conv1D) (None, None, 200) 354400 _________________________________________________________________ bn_conv_1d (BatchNormalizati (None, None, 200) 800 _________________________________________________________________ rnn (SimpleRNN) (None, None, 200) 80200 _________________________________________________________________ bn_rnn (BatchNormalization) (None, None, 200) 800 _________________________________________________________________ time_distributed_2 (TimeDist (None, None, 29) 5829 _________________________________________________________________ softmax (Activation) (None, None, 29) 0 ================================================================= Total params: 442,029 Trainable params: 441,229 Non-trainable params: 800 _________________________________________________________________ None ###Markdown Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_2.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_2.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ###Code train_model(input_to_softmax=model_2, pickle_path='model_2.pickle', save_model_path='model_2.h5', spectrogram=True) # change to False if you would like to use MFCC features ###Output Epoch 1/20 106/106 [==============================] - 108s 1s/step - loss: 233.9037 - val_loss: 215.3739 Epoch 2/20 106/106 [==============================] - 55s 515ms/step - loss: 170.1712 - val_loss: 158.1822 Epoch 3/20 106/106 [==============================] - 56s 530ms/step - loss: 149.2637 - val_loss: 145.9997 Epoch 4/20 106/106 [==============================] - 56s 531ms/step - loss: 137.3644 - val_loss: 140.9082 Epoch 5/20 106/106 [==============================] - 56s 526ms/step - loss: 129.7414 - val_loss: 136.5908 Epoch 6/20 106/106 [==============================] - 55s 516ms/step - loss: 123.1647 - val_loss: 136.4024 Epoch 7/20 106/106 [==============================] - 56s 526ms/step - loss: 117.8127 - val_loss: 135.9587 Epoch 8/20 106/106 [==============================] - 55s 515ms/step - loss: 113.5190 - val_loss: 134.1884 Epoch 9/20 106/106 [==============================] - 54s 509ms/step - loss: 109.6732 - val_loss: 130.6733 Epoch 10/20 106/106 [==============================] - 56s 527ms/step - loss: 106.3541 - val_loss: 132.0268 Epoch 11/20 106/106 [==============================] - 56s 528ms/step - loss: 102.8600 - val_loss: 131.0430 Epoch 12/20 106/106 [==============================] - 56s 525ms/step - loss: 99.7022 - val_loss: 133.5133 Epoch 13/20 106/106 [==============================] - 54s 509ms/step - loss: 96.6316 - val_loss: 133.0950 Epoch 14/20 106/106 [==============================] - 54s 506ms/step - loss: 93.8300 - val_loss: 134.7976 Epoch 15/20 106/106 [==============================] - 55s 522ms/step - loss: 91.0680 - val_loss: 134.6847 Epoch 16/20 106/106 [==============================] - 56s 525ms/step - loss: 88.4579 - val_loss: 134.0580 Epoch 17/20 106/106 [==============================] - 56s 527ms/step - loss: 86.0148 - val_loss: 140.3218 Epoch 18/20 106/106 [==============================] - 54s 512ms/step - loss: 83.5431 - val_loss: 139.2986 Epoch 19/20 106/106 [==============================] - 55s 521ms/step - loss: 81.8140 - val_loss: 139.4966 Epoch 20/20 106/106 [==============================] - 55s 523ms/step - loss: 79.2393 - val_loss: 141.2783 ###Markdown (IMPLEMENTATION) Model 3: Deeper RNN + TimeDistributed DenseReview the code in `rnn_model`, which makes use of a single recurrent layer. Now, specify an architecture in `deep_rnn_model` that utilizes a variable number `recur_layers` of recurrent layers. The figure below shows the architecture that should be returned if `recur_layers=2`. In the figure, the output sequence of the first recurrent layer is used as input for the next recurrent layer.Feel free to change the supplied values of `units` to whatever you think performs best. You can change the value of `recur_layers`, as long as your final value is greater than 1. (As a quick check that you have implemented the additional functionality in `deep_rnn_model` correctly, make sure that the architecture that you specify here is identical to `rnn_model` if `recur_layers=1`.) ###Code model_3 = deep_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features units=200, recur_layers=2) ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= the_input (InputLayer) (None, None, 161) 0 _________________________________________________________________ gru_1 (GRU) (None, None, 200) 217200 _________________________________________________________________ bn_rnn (BatchNormalization) (None, None, 200) 800 _________________________________________________________________ gru_2 (GRU) (None, None, 200) 240600 _________________________________________________________________ batch_normalization_1 (Batch (None, None, 200) 800 _________________________________________________________________ time_distributed_3 (TimeDist (None, None, 29) 5829 _________________________________________________________________ softmax (Activation) (None, None, 29) 0 ================================================================= Total params: 465,229 Trainable params: 464,429 Non-trainable params: 800 _________________________________________________________________ None ###Markdown Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_3.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_3.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ###Code train_model(input_to_softmax=model_3, pickle_path='model_3.pickle', save_model_path='model_3.h5', spectrogram=True) # change to False if you would like to use MFCC features ###Output Epoch 1/20 106/106 [==============================] - 329s 3s/step - loss: 279.0108 - val_loss: 229.9250 Epoch 2/20 106/106 [==============================] - 332s 3s/step - loss: 225.0682 - val_loss: 209.1276 Epoch 3/20 106/106 [==============================] - 333s 3s/step - loss: 215.4607 - val_loss: 206.2111 Epoch 4/20 106/106 [==============================] - 333s 3s/step - loss: 189.7864 - val_loss: 173.4158 Epoch 5/20 106/106 [==============================] - 336s 3s/step - loss: 160.5668 - val_loss: 165.4435 Epoch 6/20 106/106 [==============================] - 335s 3s/step - loss: 146.8373 - val_loss: 149.6192 Epoch 7/20 106/106 [==============================] - 333s 3s/step - loss: 137.9485 - val_loss: 141.9723 Epoch 8/20 106/106 [==============================] - 332s 3s/step - loss: 132.0306 - val_loss: 137.8731 Epoch 9/20 106/106 [==============================] - 334s 3s/step - loss: 127.4622 - val_loss: 134.9801 Epoch 10/20 106/106 [==============================] - 333s 3s/step - loss: 123.9866 - val_loss: 134.0194 Epoch 11/20 106/106 [==============================] - 335s 3s/step - loss: 120.6518 - val_loss: 137.8118 Epoch 12/20 106/106 [==============================] - 335s 3s/step - loss: 118.9663 - val_loss: 133.7554 Epoch 13/20 106/106 [==============================] - 332s 3s/step - loss: 116.0514 - val_loss: 128.0993 Epoch 14/20 106/106 [==============================] - 332s 3s/step - loss: 114.8396 - val_loss: 130.3831 Epoch 15/20 106/106 [==============================] - 333s 3s/step - loss: 112.8482 - val_loss: 133.6612 Epoch 16/20 106/106 [==============================] - 333s 3s/step - loss: 111.7261 - val_loss: 128.3950 Epoch 17/20 106/106 [==============================] - 331s 3s/step - loss: 110.4110 - val_loss: 125.9611 Epoch 18/20 106/106 [==============================] - 334s 3s/step - loss: 109.5875 - val_loss: 124.4582 Epoch 19/20 106/106 [==============================] - 333s 3s/step - loss: 107.5200 - val_loss: 125.6245 Epoch 20/20 106/106 [==============================] - 332s 3s/step - loss: 106.9535 - val_loss: 124.7905 ###Markdown (IMPLEMENTATION) Model 4: Bidirectional RNN + TimeDistributed DenseRead about the [Bidirectional](https://keras.io/layers/wrappers/) wrapper in the Keras documentation. For your next architecture, you will specify an architecture that uses a single bidirectional RNN layer, before a (`TimeDistributed`) dense layer. The added value of a bidirectional RNN is described well in [this paper](http://www.cs.toronto.edu/~hinton/absps/DRNN_speech.pdf).> One shortcoming of conventional RNNs is that they are only able to make use of previous context. In speech recognition, where whole utterances are transcribed at once, there is no reason not to exploit future context as well. Bidirectional RNNs (BRNNs) do this by processing the data in both directions with two separate hidden layers which are then fed forwards to the same output layer.Before running the code cell below, you must complete the `bidirectional_rnn_model` function in `sample_models.py`. Feel free to use `SimpleRNN`, `LSTM`, or `GRU` units. When specifying the `Bidirectional` wrapper, use `merge_mode='concat'`. ###Code model_4 = bidirectional_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features units=200) ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= the_input (InputLayer) (None, None, 161) 0 _________________________________________________________________ bidirectional_1 (Bidirection (None, None, 400) 434400 _________________________________________________________________ time_distributed_4 (TimeDist (None, None, 29) 11629 _________________________________________________________________ softmax (Activation) (None, None, 29) 0 ================================================================= Total params: 446,029 Trainable params: 446,029 Non-trainable params: 0 _________________________________________________________________ None ###Markdown Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_4.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_4.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ###Code train_model(input_to_softmax=model_4, pickle_path='model_4.pickle', save_model_path='model_4.h5', spectrogram=True) # change to False if you would like to use MFCC features ###Output Epoch 1/20 106/106 [==============================] - 314s 3s/step - loss: 295.9663 - val_loss: 224.9329 Epoch 2/20 106/106 [==============================] - 317s 3s/step - loss: 225.4940 - val_loss: 204.5446 Epoch 3/20 106/106 [==============================] - 317s 3s/step - loss: 211.6394 - val_loss: 197.9675 Epoch 4/20 106/106 [==============================] - 317s 3s/step - loss: 199.5537 - val_loss: 190.3478 Epoch 5/20 106/106 [==============================] - 319s 3s/step - loss: 188.7032 - val_loss: 178.1398 Epoch 6/20 106/106 [==============================] - 316s 3s/step - loss: 178.7231 - val_loss: 170.9624 Epoch 7/20 106/106 [==============================] - 317s 3s/step - loss: 169.6119 - val_loss: 164.3558 Epoch 8/20 106/106 [==============================] - 318s 3s/step - loss: 161.0897 - val_loss: 157.8137 Epoch 9/20 106/106 [==============================] - 317s 3s/step - loss: 153.9279 - val_loss: 154.1404 Epoch 10/20 106/106 [==============================] - 318s 3s/step - loss: 147.2670 - val_loss: 148.8880 Epoch 11/20 106/106 [==============================] - 315s 3s/step - loss: 141.3428 - val_loss: 146.4738 Epoch 12/20 106/106 [==============================] - 317s 3s/step - loss: 136.2316 - val_loss: 143.0241 Epoch 13/20 106/106 [==============================] - 318s 3s/step - loss: 131.6063 - val_loss: 142.2228 Epoch 14/20 106/106 [==============================] - 319s 3s/step - loss: 127.2795 - val_loss: 140.0253 Epoch 15/20 106/106 [==============================] - 318s 3s/step - loss: 122.9308 - val_loss: 139.7404 Epoch 16/20 106/106 [==============================] - 317s 3s/step - loss: 119.3044 - val_loss: 137.9344 Epoch 17/20 106/106 [==============================] - 317s 3s/step - loss: 115.4683 - val_loss: 136.4806 Epoch 18/20 106/106 [==============================] - 318s 3s/step - loss: 112.4107 - val_loss: 137.9953 Epoch 19/20 106/106 [==============================] - 317s 3s/step - loss: 108.9697 - val_loss: 140.7246 Epoch 20/20 106/106 [==============================] - 315s 3s/step - loss: 106.0100 - val_loss: 136.1279 ###Markdown (OPTIONAL IMPLEMENTATION) Models 5+If you would like to try out more architectures than the ones above, please use the code cell below. Please continue to follow the same convention for saving the models; for the $i$-th sample model, please save the loss at **`model_i.pickle`** and saving the trained model at **`model_i.h5`**. ###Code ## (Optional) TODO: Try out some more models! ### Feel free to use as many code cells as needed. ###Output _____no_output_____ ###Markdown Compare the ModelsExecute the code cell below to evaluate the performance of the drafted deep learning models. The training and validation loss are plotted for each model. ###Code from glob import glob import numpy as np import _pickle as pickle import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline sns.set_style(style='white') # obtain the paths for the saved model history all_pickles = sorted(glob("results/*.pickle")) # extract the name of each model model_names = [item[8:-7] for item in all_pickles] # extract the loss history for each model valid_loss = [pickle.load( open( i, "rb" ) )['val_loss'] for i in all_pickles] train_loss = [pickle.load( open( i, "rb" ) )['loss'] for i in all_pickles] # save the number of epochs used to train each model num_epochs = [len(valid_loss[i]) for i in range(len(valid_loss))] fig = plt.figure(figsize=(16,5)) # plot the training loss vs. epoch for each model ax1 = fig.add_subplot(121) for i in range(len(all_pickles)): ax1.plot(np.linspace(1, num_epochs[i], num_epochs[i]), train_loss[i], label=model_names[i]) # clean up the plot ax1.legend() ax1.set_xlim([1, max(num_epochs)]) plt.xlabel('Epoch') plt.ylabel('Training Loss') # plot the validation loss vs. epoch for each model ax2 = fig.add_subplot(122) for i in range(len(all_pickles)): ax2.plot(np.linspace(1, num_epochs[i], num_epochs[i]), valid_loss[i], label=model_names[i]) # clean up the plot ax2.legend() ax2.set_xlim([1, max(num_epochs)]) plt.xlabel('Epoch') plt.ylabel('Validation Loss') plt.show() ###Output _____no_output_____ ###Markdown __Question 1:__ Use the plot above to analyze the performance of each of the attempted architectures. Which performs best? Provide an explanation regarding why you think some models perform better than others. __Answer:__ Looking at the graphs we have interesting results. We can see that all models are behaving in the similar way: at the beginning of the training, each model starts by decreasing loss dramaticly and suddenly at the mid of 3rd-5nd epoch it keeps its loss value without decreasing. If we take into account all plots, the best model is 2nd model (CNN). That's why we provide the most information to the RNN part of the network.We can also observe that Models 2, 3 and 4 perform much better than the previous two models. It can partially attributed to the huge number of parameters at about 500k. Below an analysis of each model:- Modelo 0: is a highly simplistic model with a simple GRE recurrent layer. It is not able to capture all the complexities in the data.- Model 1: tries to introduce some complexity by making use of a Batch Normalization layer and a Time Distributed Layer, to correctly capture the variance of the data. And the TimeDistributed layer allows the model to convey the transitions between the temporal slices.- Model 2: had the fastest training times among all the other models. It also seems to overfit a bit as its training loss is less than the validation loss. The fact that this model uses a SimpleRNN layer instead of the GRU layer the other models use might explain this characteristic.- Model 3: seems to be the best performance amongst all the models. Its is consistent on the training as well as the validation sets. This might be due to the addition of an extra RNN layer.- Model 4: introduces a bidirectional RNN layer, which surprisingly does not perform as well as Model 3. One reason for this might be the absence of a Batch Normalization layer. (IMPLEMENTATION) Final ModelNow that you've tried out many sample models, use what you've learned to draft your own architecture! While your final acoustic model should not be identical to any of the architectures explored above, you are welcome to merely combine the explored layers above into a deeper architecture. It is **NOT** necessary to include new layer types that were not explored in the notebook.However, if you would like some ideas for even more layer types, check out these ideas for some additional, optional extensions to your model:- If you notice your model is overfitting to the training dataset, consider adding **dropout**! To add dropout to [recurrent layers](https://faroit.github.io/keras-docs/1.0.2/layers/recurrent/), pay special attention to the `dropout_W` and `dropout_U` arguments. This [paper](http://arxiv.org/abs/1512.05287) may also provide some interesting theoretical background.- If you choose to include a convolutional layer in your model, you may get better results by working with **dilated convolutions**. If you choose to use dilated convolutions, make sure that you are able to accurately calculate the length of the acoustic model's output in the `model.output_length` lambda function. You can read more about dilated convolutions in Google's [WaveNet paper](https://arxiv.org/abs/1609.03499). For an example of a speech-to-text system that makes use of dilated convolutions, check out this GitHub [repository](https://github.com/buriburisuri/speech-to-text-wavenet). You can work with dilated convolutions [in Keras](https://keras.io/layers/convolutional/) by paying special attention to the `padding` argument when you specify a convolutional layer.- If your model makes use of convolutional layers, why not also experiment with adding **max pooling**? Check out [this paper](https://arxiv.org/pdf/1701.02720.pdf) for example architecture that makes use of max pooling in an acoustic model.- So far, you have experimented with a single bidirectional RNN layer. Consider stacking the bidirectional layers, to produce a [deep bidirectional RNN](https://www.cs.toronto.edu/~graves/asru_2013.pdf)!All models that you specify in this repository should have `output_length` defined as an attribute. This attribute is a lambda function that maps the (temporal) length of the input acoustic features to the (temporal) length of the output softmax layer. This function is used in the computation of CTC loss; to see this, look at the `add_ctc_loss` function in `train_utils.py`. To see where the `output_length` attribute is defined for the models in the code, take a look at the `sample_models.py` file. You will notice this line of code within most models:```model.output_length = lambda x: x```The acoustic model that incorporates a convolutional layer (`cnn_rnn_model`) has a line that is a bit different:```model.output_length = lambda x: cnn_output_length( x, kernel_size, conv_border_mode, conv_stride)```In the case of models that use purely recurrent layers, the lambda function is the identity function, as the recurrent layers do not modify the (temporal) length of their input tensors. However, convolutional layers are more complicated and require a specialized function (`cnn_output_length` in `sample_models.py`) to determine the temporal length of their output.You will have to add the `output_length` attribute to your final model before running the code cell below. Feel free to use the `cnn_output_length` function, if it suits your model. ###Code # specify the model model_end = final_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=1, conv_border_mode='valid', units=200) ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= the_input (InputLayer) (None, None, 161) 0 _________________________________________________________________ conv_layer_1 (Conv1D) (None, None, 200) 354400 _________________________________________________________________ dropout_2 (Dropout) (None, None, 200) 0 _________________________________________________________________ conv_bn (BatchNormalization) (None, None, 200) 800 _________________________________________________________________ gru_5 (GRU) (None, None, 200) 240600 _________________________________________________________________ rnn_bn_gru_1 (BatchNormaliza (None, None, 200) 800 _________________________________________________________________ time_distributed_5 (TimeDist (None, None, 29) 5829 _________________________________________________________________ softmax (Activation) (None, None, 29) 0 ================================================================= Total params: 602,429 Trainable params: 601,629 Non-trainable params: 800 _________________________________________________________________ None ###Markdown Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/how-can-i-save-a-keras-model) in the HDF5 file `model_end.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_end.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ###Code train_model(input_to_softmax=model_end, pickle_path='model_end.pickle', save_model_path='model_end.h5', spectrogram=True) # change to False if you would like to use MFCC features ###Output Epoch 1/20 106/106 [==============================] - 206s 2s/step - loss: 280.3741 - val_loss: 257.9122 Epoch 2/20 106/106 [==============================] - 204s 2s/step - loss: 228.0922 - val_loss: 210.8335 Epoch 3/20 106/106 [==============================] - 203s 2s/step - loss: 207.2466 - val_loss: 189.8217 Epoch 4/20 106/106 [==============================] - 202s 2s/step - loss: 180.3884 - val_loss: 164.4573 Epoch 5/20 106/106 [==============================] - 203s 2s/step - loss: 161.0185 - val_loss: 151.6160 Epoch 6/20 106/106 [==============================] - 203s 2s/step - loss: 151.1197 - val_loss: 143.7066 Epoch 7/20 106/106 [==============================] - 202s 2s/step - loss: 145.1533 - val_loss: 141.4320 Epoch 8/20 106/106 [==============================] - 202s 2s/step - loss: 139.7824 - val_loss: 136.8355 Epoch 9/20 106/106 [==============================] - 203s 2s/step - loss: 135.2198 - val_loss: 133.1196 Epoch 10/20 106/106 [==============================] - 202s 2s/step - loss: 131.9494 - val_loss: 130.0909 Epoch 11/20 106/106 [==============================] - 203s 2s/step - loss: 129.7081 - val_loss: 128.2077 Epoch 12/20 106/106 [==============================] - 202s 2s/step - loss: 126.8082 - val_loss: 128.6146 Epoch 13/20 106/106 [==============================] - 203s 2s/step - loss: 124.7251 - val_loss: 127.4304 Epoch 14/20 106/106 [==============================] - 201s 2s/step - loss: 122.6122 - val_loss: 125.9810 Epoch 15/20 106/106 [==============================] - 202s 2s/step - loss: 121.3722 - val_loss: 122.8291 Epoch 16/20 106/106 [==============================] - 202s 2s/step - loss: 122.1733 - val_loss: 131.9557 Epoch 17/20 106/106 [==============================] - 202s 2s/step - loss: 120.6360 - val_loss: 125.1846 Epoch 18/20 106/106 [==============================] - 203s 2s/step - loss: 119.4076 - val_loss: 122.5974 Epoch 19/20 106/106 [==============================] - 203s 2s/step - loss: 117.3383 - val_loss: 120.0489 Epoch 20/20 106/106 [==============================] - 202s 2s/step - loss: 115.8139 - val_loss: 118.6194 ###Markdown __Question 2:__ Describe your final model architecture and your reasoning at each step. __Answer:__ I tried to incorporate all the best features of the preview models:- A CNN layer to gain more information from the data (Based on the performance of Model 3). - Use of Dropout and Batch Normalization layers to prevent over-fitting. - Use the GRU RNN and not tweaked standard parameters as I think that the "GRU" with the added complexity performs better than the "SimpleRNN" without too much increase in processing time. - Use a TimeDistributed Dense layer followed by softmax activation in order to compute the logits.And, the further improvements are:- More training data (this usually improves Deep Learning Models)- More convolutional layers (to gain more information from the data)- Incorporate a language model (as mentioned at the end of this notebook) STEP 3: Obtain PredictionsWe have written a function for you to decode the predictions of your acoustic model. To use the function, please execute the code cell below. ###Code import numpy as np from data_generator import AudioGenerator from keras import backend as K from utils import int_sequence_to_text from IPython.display import Audio def get_predictions(index, partition, input_to_softmax, model_path): """ Print a model's decoded predictions Params: index (int): The example you would like to visualize partition (str): One of 'train' or 'validation' input_to_softmax (Model): The acoustic model model_path (str): Path to saved acoustic model's weights """ # load the train and test data data_gen = AudioGenerator() data_gen.load_train_data() data_gen.load_validation_data() # obtain the true transcription and the audio features if partition == 'validation': transcr = data_gen.valid_texts[index] audio_path = data_gen.valid_audio_paths[index] data_point = data_gen.normalize(data_gen.featurize(audio_path)) elif partition == 'train': transcr = data_gen.train_texts[index] audio_path = data_gen.train_audio_paths[index] data_point = data_gen.normalize(data_gen.featurize(audio_path)) else: raise Exception('Invalid partition! Must be "train" or "validation"') # obtain and decode the acoustic model's predictions input_to_softmax.load_weights(model_path) prediction = input_to_softmax.predict(np.expand_dims(data_point, axis=0)) output_length = [input_to_softmax.output_length(data_point.shape[0])] pred_ints = (K.eval(K.ctc_decode( prediction, output_length)[0][0])+1).flatten().tolist() # play the audio file, and display the true and predicted transcriptions print('-'*80) Audio(audio_path) print('True transcription:\n' + '\n' + transcr) print('-'*80) print('Predicted transcription:\n' + '\n' + ''.join(int_sequence_to_text(pred_ints))) print('-'*80) ###Output _____no_output_____ ###Markdown Use the code cell below to obtain the transcription predicted by your final model for the first example in the training dataset. ###Code get_predictions(index=0, partition='train', input_to_softmax=final_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=1, conv_border_mode='valid', units=200), model_path='results/model_end.h5') ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= the_input (InputLayer) (None, None, 161) 0 _________________________________________________________________ conv_layer_1 (Conv1D) (None, None, 200) 354400 _________________________________________________________________ dropout_4 (Dropout) (None, None, 200) 0 _________________________________________________________________ conv_bn (BatchNormalization) (None, None, 200) 800 _________________________________________________________________ gru_9 (GRU) (None, None, 200) 240600 _________________________________________________________________ rnn_bn_gru_1 (BatchNormaliza (None, None, 200) 800 _________________________________________________________________ time_distributed_7 (TimeDist (None, None, 29) 5829 _________________________________________________________________ softmax (Activation) (None, None, 29) 0 ================================================================= Total params: 602,429 Trainable params: 601,629 Non-trainable params: 800 _________________________________________________________________ None -------------------------------------------------------------------------------- True transcription: the last two days of the voyage bartley found almost intolerable -------------------------------------------------------------------------------- Predicted transcription: thelistodas of thef w by fond on motintor be -------------------------------------------------------------------------------- ###Markdown Use the next code cell to visualize the model's prediction for the first example in the validation dataset. ###Code get_predictions(index=0, partition='validation', input_to_softmax=final_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=1, conv_border_mode='valid', units=200), model_path='results/model_end.h5') ###Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= the_input (InputLayer) (None, None, 161) 0 _________________________________________________________________ conv_layer_1 (Conv1D) (None, None, 200) 354400 _________________________________________________________________ dropout_5 (Dropout) (None, None, 200) 0 _________________________________________________________________ conv_bn (BatchNormalization) (None, None, 200) 800 _________________________________________________________________ gru_11 (GRU) (None, None, 200) 240600 _________________________________________________________________ rnn_bn_gru_1 (BatchNormaliza (None, None, 200) 800 _________________________________________________________________ time_distributed_8 (TimeDist (None, None, 29) 5829 _________________________________________________________________ softmax (Activation) (None, None, 29) 0 ================================================================= Total params: 602,429 Trainable params: 601,629 Non-trainable params: 800 _________________________________________________________________ None -------------------------------------------------------------------------------- True transcription: out in the woods stood a nice little fir tree -------------------------------------------------------------------------------- Predicted transcription: ito nho wo stote nyst ni forcrmy --------------------------------------------------------------------------------
ReadNumPy.ipynb
###Markdown Reading NumPy Arrays NumPy provides various ways of reading arrays from files, whether they are written as ASCII text ("plain text") or in a specialized binary format. Related functions provide the ability to write arrays out to files. We'll examine a few of those functions here. (For a NumPy array refresher, consult the NumPy Array Tip Sheet.)First, let's look in our current working directory to see what data files we might have to work with. Jupyter notebooks provide a capability for executing commands in the shell, or command line, external to the notebook, by beginning a command with the "!" character (exclamation point, or "bang"). The Linux command "ls" lists the contents in the current directory. We can execute this command from within the notebook by entering and evaluating the expression ```!ls```. (You could also list the contents of the directory with the ```%ls``` magic function, but since we'll be issuing a few additional commands below that don't have magic function equivalents, we might as well use the "!" notation for all of them.) Step 1.Execute the expression in the code cell below and evaluate the results. You will see the name of a data file (with .txt suffix). ###Code !ls ###Output data.txt jn.py __pycache__ readNumpy.png gradebook.db logo.npy ReadNumPy.ipynb ###Markdown Notice that there is a data file named ```data.txt```. Using the ```head``` command in Linux, we can print out the first 10 lines of the file to see what it consists of. Step 2.Execute the expression in the code cell below and evaluate the results. ###Code !head data.txt ###Output 52 119 53 119 54 119 55 119 56 119 57 119 58 119 59 119 60 119 61 119 ###Markdown It looks like the file contains a pair of integers on each row, which is something that we could read into a NumPy array. Before doing so, we might want to figure out how many lines are in the file (since if it is a ridiculously large number, we might want to think twice about reading it all in). The ```wc -l``` command in Linux ("wc -l" is short for "word count -lines", i.e., it returns the number of lines in a file). Step 3.Execute the expression in the code cell below, to see how many lines it has. ###Code !wc -l data.txt ###Output 3569 data.txt ###Markdown The file is not too big, so let's go ahead and read it in.First, you'll need to ```import numpy as np``` in order to access that module. Then you will want to use the ```np.loadtxt``` function in order to read in the data that is stored in the plain text file ```data.txt```.```np.loadtxt``` requires at least one argument, which is the name of the file that you want to read in. The filename is passed as a Python string, for example, "data.txt". Step 4.The code cell below reads in the contents of the data file and assign it to the variable ```data```. ###Code import numpy as np data = np.loadtxt('data.txt') ###Output _____no_output_____ ###Markdown Step 5.Let's examine some basic attributes of the data array. The code cell below prints both the ```shape``` and the ```dtype``` attributes of the array ```data```. ###Code print( data.shape ) print( data.dtype ) ###Output (3569, 2) float64 ###Markdown By default, the ```dtype``` of arrays read in via ```np.loadtxt``` is ```float64``` (floating point numbers). When we peeked at the data file above using the ```head``` command, it looked like the data might contain all integer (int) values. We can refine our call to ```np.loadtxt``` to tell it to read in the data as ```dtype=int``` instead, by supplying that as an additional option to the function call. Step 6.In the code cell below, enter and evaluate a revised version of the call to ```np.loadtxt```, supplying an additional option to read in the data as integers, and assign the result to the variable ```data```. Verify afterwards that the ```dtype``` of ```data``` is now int64 (64-bit integers, or int). ###Code # YOUR CODE HERE data = np.loadtxt('data.txt', dtype=int) print(data.dtype) ###Output int64 ###Markdown Self-CheckRun the cell below to test the correctness of your code above before submitting for grading. ###Code # Run this self-test cell to check your code; do not add code or delete code in this cell from jn import testType try: print(testType(data)) except Exception as e: print("Error!\n" + str(e)) ###Output Correct! ###Markdown Even though we have read the data in, we don't really know anything about it other than its type and its shape (3569 rows by 2 columns). Step 7.In the code cell below -- recalling that the `axis` parameter can be passed to methods and functions, in order to operate over a specified dimension of an array (for example: `axis=0`, `axis=1` )-- do the following:* write an expression to compute the minimum value in each column, using the ```min``` method of an array, and assign the result to the variable ```minvals```, which should be an array containing two elements (one for each column)* write an expression to compute the maximum value in each column, using the ```max``` method of an array, and assign the result to the variable ```maxvals```, which should be an array containing two elements (one for each column)* print the values of ```minvals``` and ```maxvals``` so you can examine the range of the data ###Code # YOUR CODE HERE minvals = np.min() maxvals = np.max() print(minvals) print(maxvals) ###Output _____no_output_____ ###Markdown Self-CheckRun the cell below to test the correctness of your code in the cell above. ###Code # Run this self-test cell to check your code; do not add code or delete code in this cell from jn import testMinvals, testMaxvals try: print(testMinvals(minvals)) except Exception as e: print("Error!\n" + str(e)) try: print(testMaxvals(maxvals)) except Exception as e: print("Error!\n" + str(e)) ###Output Error! name 'minvals' is not defined Error! name 'maxvals' is not defined ###Markdown Sometimes it is useful to plot some new data you are working with, to get a sense of what it looks like. Since the array consists of two columns, it might be helpful to plot one column against the other, i.e., treat one column as "x" data and the other as associated "y" data. Step 8.In the code cell below, fill in the missing code (denoted as ```___```) so that you can plot the first column of the array on the x-axis, and the second column of the array on the y-axis. (Recall that we are plotting columns, which is why we first slice over all rows in the first index with ```:``` ; recall also how we start counting when we are indexing into an array or list.) The code below also specifies a square figure size, since we know from our examination above about ```minvals``` and ```maxvals``` that the range of the data is the same in each dimension. ###Code import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=(8,8)) plt.plot(data[:,___minvals], data[:,___maxvals]) ###Output _____no_output_____ ###Markdown That plot is not particularly informative. It looks like the data points are criss-crossing back and forth across the plane, making it hard to discern a pattern. In such a case, a scatter plot is sometimes useful. Step 9.In the code cell below, fill in the missing code to make a scatter plot of the two columns in the data. (A few extra plotting options have been added to improve the resulting figure.) Note: a self-check will not accompany this exercise. ###Code # FILL IN THE MISSING CODE BELOW plt.figure(figsize=(8,8)) plt.scatter(data[:,___], data[:,___], s=3, c='r') ###Output _____no_output_____ ###Markdown Aha! That's what the data represents! (Your plot should reveal the Cornell logo. If it doesn't go back and fix your plotting commands above until it does.)For what it's worth, the file ```data.txt``` was generated by processing a low-resolution jpeg image of the Cornell logo. Images are built up out of raster data, which are essentially one or more two-dimensional arrays describing the intensity of pixels in the image. Several image processing packages are available to convert images to numpy arrays. We noted above that we can read and write files either from plain text files or binary files. What are "binary files"? They are files in which data are packed in as a sequence of bytes (1 byte = 8 bits), rather than encoded as text characters. The data are packed in some specified format, which means that they can hold data, images, computer programs, etc. But in order to unpack a binary file, you need to know what the format is, i.e., how the data were packed in the first place.NumPy provides the functions ```loadtxt``` and ```savetxt``` for loading (reading) and saving (writing) arrays encoded in plain text files. Similarly, it provides the functions ```load``` and ```save``` for reading and writing arrays in a specific binary format, the so-called NumPy ```.npy``` format. The advantage of saving files to binary format is that the data are stored to full precision, along with information about their dtype, and binary files can be smaller than a text file encoding the same data. The disadvantage of using binary files is that they are less portable to other programming environments; while NumPy knows how to load a .npy file that has been saved, that might not be the case for other libraries or languages. Step 10.The code cell below uses ```np.save``` to save the ```data``` array to a new file named ```logo.npy```.Consult the online documentation for more information on how to use `np.save`. ###Code np.save('logo.npy', data) ###Output _____no_output_____ ###Markdown Just because the new file ```logo.npy``` is in binary format doesn't mean we can't look at it, although the results of such a process are not especially meaningful. Step 11.Use the ```head``` command used in Step 2 to look at the first few lines of ```logo.npy```. You should notice that there is some legible metadata encoded with text characters at the top of the file, describing, for example, the shape of the array and its dtype ('<i8' is equivalent to 'int64'). All of the illegible stuff that follows is due to the fact that the binary data describing the array values are being interpreted as text and/or control characters rather than the 64-bit integers (int64) that they actually are. ###Code # YOUR CODE HERE !head logo.npy ###Output �NUMPYv{'descr': '<i8', 'fortran_order': False, 'shape': (3569, 2), } 4w5w6w7w8w9w:w;w<w=w>w?w@wAwBwCwDw/v0v1v2v3v4v5v6v7v8v9v:v;v<v=v>v?v@vAvBvCvDvEvFvGvHvIv+u,u-u.u/u0u1uGuHuIuJuKuLuMu(t)t*t+t,tKtLtMtNtOtPt%s&s's(s)s9s:s;sOsPsQsRs#r$r%r&r4r5r6r9r:r;r@rArBrErFrGrQrRrSrTrUr!q"q#q$q4q5q6q:q;q@qAqBqCqEqFqTqUqVqWqp p!p"p5p6p:p;p@pApBpCpEpFpLpMpVpWpXpYpoo o(o)o5o6o:o;o@oAoBoCoEoFoKoLoMoXoYoZonnn(n)n5n6n:n;n@nCnDnEnFnKnLnQnRnSnZn[n\nmmm(m)m*m5m6m:m;m@mAmCmDmEmFmKmLmQmRmSm[m\m]mlll)l*l5l6l7l8l9l:l;l@lAlClDlElFlJlKlLlQlRlWl]l^l_lkk k!k)k*k+k6k7k8k9k:k?k@kAkDkEkFkJkKkQkRkVkWkXk^k_k`kjjj j!j)j*j+j.jDjEjFjJjKjQjRjUjVjWj`jajiii i!i"i*i+i,i-i.iIiJiKiQiRiTiUiViaibihhhh!h"h#h*h+h,h-hKhQhRhShThUh[h\h]hbhchdhgggggg"g#g&g'g5g6g7g8g9g:g;g<g=g>g?g@gAgBgPgRgSgTg[g\g]g^gcgdgegfffff"f#f$f%f&f'f1f2f3f4f5f6f7f8f9f?f@fAfBfCfDfEfFfGfPfQfRfSfZf[f\f]f^f_fdfefffeeeeee#e$e%e&e.e/e0e1e2eFeGeHeIeJeReYeZe[e^e_eeefegeddddddd#d$d+d,d-d.dIdJdKdLdXdYdZd[d\d]dfdgdhdccccccc)c*c+c,cLcMcNcOcWcXcYc\c]cgchcbbbbbbb b'b(b)bNbObPbWbXbYbcbhbibaaaaaaaa%a&a'aPaQaRaYaZa[abacadaiaja ````````$`%`&`R`S`T`Z`[`a`b`c`d`e`j`k` _ ______"_#_$_T_U___`_a_b_d_e_f_k_l_ ^ ^^^^!^"^#^U^V^^^_^`^a^b^c^d^e^f^k^l^ ] ]]]]]]]]]] ]!]V]W]X]]]^]_]`]a]b]c]d]e]l]m] \ \\\\\\\\\\\\\ \X\Y\^\a\b\c\d\m\n\ [ [[[[[[[[[[Y[Z[b[m[n[ Z ZZZZZZZZ[Z`ZaZbZnZoZY YYYYYYY Y!Y"Y#Y$Y%Y&Y'Y(Y)Y*Y+Y,Y-Y.Y/Y0Y1Y2Y3Y4Y5Y6Y7Y8Y9Y:Y;Y<Y=Y>Y?Y@YAYBYCYDYEYFYGYHYIYJYKYLYMYNYOYPYQYRYSYTYUYVYWYXY[Y\YaYgYhYiYjYoYX XXXXXX X!X"X#X$X%X&X'X(X)X*X+X,X-X.X/X0X1X2X3X4X5X6X7X8X9X:X;X<X=X>X?X@XAXBXCXDXEXFXGXHXIXJXKXLXMXNXOXPXQXRXSXTXUXVXWXXX\X]XgXhXiXjXkXoXpXWW WWWWW W!W"W#W$W%W&W'W(W)W*W+W,W-W.W/W0W1W2W3W4W5W6W7W8W9W:W;W<W=W>W?W@WAWBWCWDWEWFWGWHWIWJWKWLWMWNWOWPWQWRWSWTWUWVWWWXW]WdWgWhWjWkWlWpWVV V VVVVV V!V"VVVWVXV]V^VcVdVgVhVkVpVqVUU U U UUUUUU U!U"UBUCUDUEUFUGUHUIUJUKULUMUNUOUPUVUWUXU^U_UdUeUgUhUqUTT T TTTTTTTT T!T"T*T+T,T-T.T/T0T1T2T3T4T5T6T7TBTCTDTETFTGTHTITJTKTLTMTNTOTPTVTWTXT_T`TdTeTfTgThTqTrTSS S S S SSSSSSSSS S!S"S*S+S,S-S.S/S0S1S2S3S4S5S6S7SBSCSOSPSVSWSXS`SeSfSgSrSRR R R RRRRR R!R"R*R+R6R7RBRCRORPRVRWRXR`RaRrRsRQ QQQQQQQ Q!Q"Q*Q+Q6Q7QBQCQGQHQIQJQOQPQVQWQXQaQmQnQrQsQPPPPPP P!P"P*P+P,P-P.P/P0P1P2P3P4P5P6P7PBPCPFPGPHPIPJPKPOPPPVPWPXPaPbPjPkPlPmPnPoPsPtPOOOOO O!O"O*O+O,O-O.O/O0O1O2O3O4O5O6O7OBOCOEOFOGOJOKOLOMOOOPOVOWOXObOhOiOjOkOlOmOsOtONN N!N"N*N+N6N7NBNCNDNENFNLNMNNNONPNVNWNXNbNcNgNhNiNjNtNMM M M M M MMM M!M"M*M+M6M7MBMCMDMMMNMOMPMVMWMXMcMhMtMuMLLL L L L L LLLL L!L"L*L+L6L7LBLCLOLPLVLWLXLcLdLoLpLtLuLKKK K KKKKK K!K"K*K+K6K7KBKCKNKOKPKVKWKXKdKoKpKtKuKJJJJJJJJ J!J"J*J+J,J5J6J7JCJDJEJMJNJOJVJWJXJdJeJpJqJuJIIIIIII I!I"I+I,I-I.I4I5I6ICIDIEIFILIMINIVIWIXIdIeIlImInIoIpIqIuIvIHHHH H HHHHH H!H"H-H.H/H2H3H4H5HEHFHGHHHJHKHLHMHVHWHXHeHiHjHkHlHmHnHoHpHqHuHvHGG G G G G GGGG G!G"G.G/G0G1G2G3GFGGGHGIGJGKGVGWGXGeGiGjGkGlGpGqGuGvGF F F F F FFF F!F"F0F1F2FHFIFJFVFWFXFeFfFqFrFvFEEE E!E"EVEWEXEeEfEvEDDD D!D"DVDWDXDfDvDCCCC C!C"C#C$C%C&C'C(C)C*C+C,C-C.C/C0C1C2C3C4C5C6C7C8C9C:C;C<C=C>C?C@CACBCCCDCECFCGCHCICJCKCLCMCNCOCPCQCRCSCTCUCVCWCXCfCvCwCBBBBB B BBB B!B"B#B$B%B&B'B(B)B*B+B,B-B.B/B0B1B2B3B4B5B6B7B8B9B:B;B<B=B>B?B@BABBBCBDBEBFBGBHBIBJBKBLBMBNBOBPBQBRBSBTBUBVBWBXBfBrBvBwBAAAA A AAA A!A"A#A$A%A&A'A(A)A*A+A,A-A.A/A0A1A2A3A4A5A6A7A8A9A:A;A<A=A>A?A@AAABACADAEAFAGAHAIAJAKALAMANAOAPAQARASATAUAVAWAXAfAgApAqArAvAwA@@@@ @ @@@ @!@"@;@<@=@V@W@X@f@g@o@p@q@r@v@w@????? ? ??? ?!?"?;?<?=?V?W?X?f?g?k?l?m?n?o?p?v?w?>>>> > ###Markdown If you're interested, you could read the data in the logo file back in with a call to ```np.load('logo.npy')```. Since the binary file stores information about the dtype of the data in the array, you don't need to pass in a dtype option to ```np.load``` in the manner that we did with ```np.loadtxt```.Even though the visual representation of the logo.npy file is mostly gibberish, the size of the file is perfectly predictable. Let's revisit our original ```!ls``` command, along with an additional option to get more information about the file.Evaluate the code cell below. ###Code !ls -l ###Output total 416 -rw-r--r-- 1 codio codio 21989 May 14 2021 data.txt -rw-r--r-- 1 codio codio 36864 Mar 15 2019 gradebook.db -rw-r--r-- 1 codio codio 1521 May 14 2021 jn.py -rw-r--r-- 1 codio codio 57232 Nov 21 09:30 logo.npy drwxr-xr-x 1 codio codio 144 Oct 9 23:52 __pycache__ -rw-r--r-- 1 codio codio 184402 Nov 21 09:30 ReadNumPy.ipynb -rw-r--r-- 1 codio codio 111420 Jun 3 2020 readNumpy.png ###Markdown We can see that the listing for logo.npy indicates its file size is 57232 bytes. The metadata header at the top of the file (describing the dtype, shape, ordering, etc.) takes up 128 bytes. That means the binary gibberish that follows takes up 57232-128 = 57104 bytes. Let's think about the data that we packed into the file. There are 3569 rows and 2 columns per row, and each element in the array is a 64-bit integer. Since 8 bits = 1 byte, that means each element of the array requires 8 bytes to specify. So the total amount of memory required to store the array is:3569 rows x 2 columns per row x 8 bytes per element, or3569 * 2 * 8which equals 57104 (as can be verified by executing the cell below): ###Code 3569 * 2 * 8 ###Output _____no_output_____
P2-Traffic Sign Classification/TrafficSignRecognition.ipynb
###Markdown Self-Driving Car Engineer Nanodegree Deep Learning Project: Build a Traffic Sign Recognition ClassifierIn this notebook, a template is provided for you to implement your functionality in stages which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission, if necessary. Sections that begin with **'Implementation'** in the header indicate where you should begin your implementation for your project. Note that some sections of implementation are optional, and will be marked with **'Optional'** in the header.In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode. --- Step 1: Dataset ExplorationVisualize the German Traffic Signs Dataset. This is open ended, some suggestions include: plotting traffic signs images, plotting the count of each sign, etc. Be creative!The pickled data is a dictionary with 4 key/value pairs:- features -> the images pixel values, (width, height, channels)- labels -> the label of the traffic sign- sizes -> the original width and height of the image, (width, height)- coords -> coordinates of a bounding box around the sign in the image, (x1, y1, x2, y2). Based the original image (not the resized version). ###Code #imports import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gs import seaborn as sns # import cPickle as pickle import pickle as pickle import cv2 import numpy as np import math sns.set_style("whitegrid") % matplotlib inline training_file = 'train.p' with open(training_file, mode='rb') as f: train = pickle.load(f) testing_file = 'test.p' with open(testing_file, mode='rb') as f: test = pickle.load(f) X_train, y_train = train['features'], train['labels'] X_test, y_test = test['features'], test['labels'] # To start off let's do a basic data summary. n_train = X_train.shape[0] n_test = X_test.shape[0] image_shape = X_train.shape[1:3] n_classes = len(np.unique(y_train)) print("Number of training examples =", n_train) print("Number of testing examples =", n_test) print("Image data shape =", image_shape) print("Number of classes =", n_classes) ###Output Number of training examples = 39209 Number of testing examples = 12630 Image data shape = (32, 32) Number of classes = 43 ###Markdown Data Exploration ###Code # count of each sign plt.figure(figsize=(6,2)) plt.xlim(0,1000) plt.xticks(np.arange(0, 1000, 100)) sns.distplot(np.bincount(y_train), kde=False, bins=20) ###Output _____no_output_____ ###Markdown There are 13 classes of sign with less than 100 testing data points. The remaining 30 classes have betwen 100 and 800 testing data points, meaning the classes are not well balanced. We can generate more test data by transforming the existing pictures, such as rotating, blurring or sharpening, zooming in or out, or random disturbances in the pixel position.Let's have a look at the sign images, to have an idea of how they are: ###Code def print_images(dataset, imgs_row, title=""): imgs_col = int(len(dataset)/imgs_row) # set grid plt.figure(figsize=(imgs_row, imgs_col)) grid = gs.GridSpec(imgs_col,imgs_row) grid.update(wspace=0.01, hspace=0.01) # create title plt.gcf().suptitle(title, fontsize=14) # plot images for idx, img in enumerate(dataset[:imgs_row*imgs_col]): ax = plt.subplot(grid[idx]) ax.imshow(img) ax.axes.get_xaxis().set_ticks([]) ax.axes.get_yaxis().set_ticks([]) # get random indices indices = np.random.permutation(X_train.shape[0]) print_images(X_train[indices[:36]], 12, "Random Training Images") ###Output _____no_output_____ ###Markdown The images from both sets are generally ok, but they should be preprocessed before classifying. Most of them are centered, with 1 to 3 pixels margin on each side, but some are very clear while others are dark, blurry or colorless. All of the samples have 3 distinct channels, meaning none of them seem to be grayscale.As these images are already centered and cropped, I will ignore for now the size of the original image and the coordinates of the bounding box around the traffic sign. Generating extra training data Build a jittered dataset by adding transformed versions of the original training set. Distortions are stochastic and applied to each preprocessed image during training, using random but bounded values for translation, rotation and scaling. These values are drawn from a uniform distribution in a specified range:* translation 1 pixel to any side* zooming/scaling, maintaining center, from -7% to 7%* +5 to -5 degrees for rotation. ###Code # image transform functions def scale(img): """ Scale to [.937, .969, 1.06]. Maintain center.""" n = np.random.choice([-2,1,2]) rdn = int(math.floor(-n/2)) # zoom in if n > 0: img = cv2.resize(img[n:32-n, n:32-n], (32,32)) # zoom out elif n < 0: img = cv2.resize(img, (32+n, 32+n)) img = np.lib.pad(img, ((rdn,rdn), (rdn,rdn),(0,0)), 'edge') return img def translate(img): """ Translate -1 or +1 pixel in any direction """ w,h = np.random.randint(-1,2), np.random.randint(-1,2) M = np.float32([[1, 0, w], [0, 1, h]]) return cv2.warpAffine(img, M, (32,32)) def rotate(img): """ Rotate -5 to +5 degrees """ rot = np.random.randint(-5,6) M = cv2.getRotationMatrix2D((16,16), rot, 1) return cv2.warpAffine(img, M, (32,32)) def show(img): plt.figure(figsize=(3,3)) ax = plt.imshow(img) ax.axes.get_xaxis().set_ticks([]) ax.axes.get_yaxis().set_ticks([]) img = X_train[10] # visualize transformations indices = np.random.permutation(X_train.shape[0]) images = X_train[indices][:3] to_print = [] for img in images: to_print.append(img) for fn in [scale, translate, rotate]: to_print.append(fn(img)) print_images(to_print, 4, "Transformations: Original, Scaled, Translated, Rotated") ###Output _____no_output_____ ###Markdown The transformations are subtle and hard to notice by visual inspection, but as shown later, they are essential for improving the overall score for the CNN model (note: experiment with more agressive transformations). Importing external data ###Code import os images = [] labels = [] for img in os.listdir('./'): if img[-3:] == 'jpg': images.append(cv2.resize(plt.imread(img), (32,32))) labels.append(int(img[:2])) X_new = np.array(images) y_new = np.array(labels) X_new.shape, y_new.shape # visualize print_images(X_new, 4, "New images, downloaded from the web") ###Output _____no_output_____ ###Markdown Preprocessing images ###Code def process_image(img, yuv=True, histeq=True, adapthisteq=True, edge=True): """ Steps to enhance image prior to classification """ # convert to YUV space, isolate Y channel if yuv: img = cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB)[:, :, 0] # preprocess Y with global histogram equalization (histeq) if histeq: img = cv2.equalizeHist(img) # preprocess Y with local histogram equalization (adapthisteq) if adapthisteq: clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(4,4)) img = clahe.apply(img) # edge detection - substract blurred image from original image if edge: gaussian_filter = cv2.GaussianBlur(img, ksize=(5,5), sigmaX=3) img = cv2.addWeighted(img, 1.5, gaussian_filter, -0.5, gamma=1) return img #.reshape(32, 32, 1) def normalize(image_data): """ Normalize the image data with Min-Max scaling to a pre-defined range """ x_min, x_max = 0, 255 a, b = .01, .99 return a + (image_data - x_min)*(b-a)/(x_max-x_min) # visualize preprocessing indices = np.random.permutation(X_train.shape[0]) images = X_train[indices][:3] to_print = [] for img in images: to_print.append(img) to_print.append(process_image(img, histeq=False, adapthisteq=False, edge=False)) to_print.append(process_image(img, adapthisteq=False, edge=False)) to_print.append(process_image(img, edge=False)) to_print.append(process_image(img)) print_images(to_print, 5, "Preprocessing: Original, YUV, Histeq, AdaptHisteq, EdgeSharpening") ###Output _____no_output_____ ###Markdown Pipeline ###Code # Adding new data: for each image, generate 3 more, one for each distortion X_train = np.vstack((X_train, np.array([translate(img) for img in X_train]), np.array([rotate(img) for img in X_train]), np.array([scale(img) for img in X_train]))) y_train = np.concatenate((y_train, y_train, y_train, y_train)) # Preprocess and normalize X_train = normalize(np.array([process_image(img) for img in X_train]).reshape(-1,32,32,1)) X_test = normalize(np.array([process_image(img) for img in X_test]).reshape(-1,32,32,1)) X_new = normalize(np.array([process_image(img) for img in X_new]).reshape(-1,32,32,1)) # save data np.save('variables', np.array([X_train, X_test, X_new, y_train, y_test, y_new])) # additional imports import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gs import seaborn as sns import tensorflow as tf from time import time sns.set_style("whitegrid") % matplotlib inline ###Output _____no_output_____ ###Markdown ---- Step 2: Design and Test a Model ArchitectureDesign and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).There are various aspects to consider when thinking about this problem:- Your model can be derived from a deep feedforward net or a deep convolutional network.- Play around preprocessing techniques (normalization, rgb to grayscale, etc)- Number of examples per label (some have more than others).- Generate fake data.Here is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these. ImplementationUse the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow. Load files ###Code X_train, X_test, X_new, y_train, y_test, y_new = np.load('variables.npy') X_train.shape, X_test.shape, X_new.shape, y_train.shape, y_test.shape, y_new.shape ###Output _____no_output_____ ###Markdown Split Validation Set ###Code from sklearn.model_selection import train_test_split X_train, X_validate, y_train, y_validate= train_test_split(X_train, y_train, test_size=0.05, stratify=y_train, random_state=42) # validation set was reduced to 5% for the final round # it is only being used to know when to stop training nn ###Output _____no_output_____ ###Markdown Convolutional Neural Network - Model ###Code # width of each layer layer_width = { 'layer_1': 100, 'layer_2': 150, 'layer_3': 250, 'fc_1': 300 } # fixed parameters n_input = int(32*32) n_classes = len(np.unique(y_train)) init_mean = 0 init_std = 0.03 # initial weight roughly between [-0.06, 0.06] fc_input = 1000 # weights and biases weights = { 'layer_1': tf.Variable( tf.truncated_normal([7,7,X_train.shape[3],layer_width['layer_1']], mean=init_mean, stddev=init_std), trainable=True), 'layer_2': tf.Variable( tf.truncated_normal([4,4,layer_width['layer_1'], layer_width['layer_2']], mean=init_mean, stddev=init_std), trainable=True), 'layer_3': tf.Variable( tf.truncated_normal([4,4,layer_width['layer_2'], layer_width['layer_3']], mean=init_mean, stddev=init_std), trainable=True), 'fc_1': tf.Variable( tf.truncated_normal([fc_input,layer_width['fc_1']], mean=init_mean, stddev=init_std), trainable=True), 'out': tf.Variable( tf.truncated_normal([layer_width['fc_1'], n_classes], mean=init_mean, stddev=init_std), trainable=True) } biases = { 'layer_1': tf.Variable( tf.truncated_normal([layer_width['layer_1']], mean=init_mean, stddev=init_std), trainable=True), 'layer_2': tf.Variable( tf.truncated_normal([layer_width['layer_2']], mean=init_mean, stddev=init_std), trainable=True), 'layer_3': tf.Variable( tf.truncated_normal([layer_width['layer_3']], mean=init_mean, stddev=init_std), trainable=True), 'fc_1': tf.Variable( tf.truncated_normal([layer_width['fc_1']], mean=init_mean, stddev=init_std), trainable=True), 'out': tf.Variable( tf.truncated_normal([n_classes], mean=init_mean, stddev=init_std), trainable=True) } # conv2d, bias, and relu activaton def conv2d(x, W, b, strides=1): x = tf.nn.conv2d(x, W, strides = [1, strides, strides, 1], padding='VALID') x = tf.nn.bias_add(x,b) # x = tf.nn.relu(x) x = tf.tanh(x) return x # max pool def maxpool2d(x,k=2): x= tf.nn.max_pool(x, ksize=[1,k,k,1], strides=[1,k,k,1], padding='SAME') return x # create neural net def conv_net(x, weights, biases): # Layer 1 conv1 = conv2d(x, weights['layer_1'], biases['layer_1']) conv1 = maxpool2d(conv1, k=2) # Layer 2 conv2 = conv2d(conv1, weights['layer_2'], biases['layer_2']) conv2 = maxpool2d(conv2, k=2) #adapted to remove conv3 # Layer 3 conv3 = conv2d(conv2, weights['layer_3'], biases['layer_3']) # Fully connected layer 1 - fc + relu conv3_reshaped = tf.reshape(conv3, [-1, fc_input]) fc1 = tf.add(tf.matmul(conv3_reshaped, weights['fc_1']), biases['fc_1']) # fc1 = tf.nn.relu(fc1) fc1 = tf.tanh(fc1) # Output layer - class prediction out = tf.add(tf.matmul(fc1, weights['out']), biases['out']) return out # learning parameters batch_size = 64 training_epochs = 300 decay = .01 ###Output _____no_output_____ ###Markdown Convolutional Neural Network - Implementation ###Code # graph input # instead of batch_size, use None to allow for variable input x = tf.placeholder(tf.float32, shape=(None, X_train.shape[1], X_train.shape[2], X_train.shape[3])) y = tf.placeholder(tf.int32, shape=(None)) global_step = tf.Variable(0, trainable=False) learning_rate = tf.train.exponential_decay(5e-2, global_step, decay_steps=X_train.shape[0]/batch_size, decay_rate=.96, staircase=True) logits = conv_net(x, weights, biases) # loss, optimizer, and variables initialization cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( logits, y, name='xentropy') loss = tf.reduce_mean(cross_entropy, name='xentropy_mean') # optimizer tf.scalar_summary(loss.op.name, loss) optimizer = tf.train.GradientDescentOptimizer(learning_rate) train_op = optimizer.minimize(loss, global_step=global_step) #evaluation function eval_correct = tf.reduce_sum(tf.cast(tf.nn.in_top_k(logits, y, 1),tf.float32)) #init init = tf.initialize_all_variables() # launch graph t0 = time() sess = tf.Session() sess.run(init) # create session variables feed_dict={ x: None, y: None } num_samples = 4000 # sample train and validation set np.random.seed(42) indices_train = np.random.permutation(y_train.shape[0])[:num_samples] #indices_validate = np.random.permutation(y_validate.shape[0])[:num_samples] # init scores scores_train = [] scores_validate = [] losses = [] epochs = [] # training cycle for epoch in range(1, training_epochs+1): # set size of batch total_batch = int(X_train.shape[0]/batch_size)+1 # loop over batches for i in range(total_batch): feed_dict[x] = X_train[i*batch_size:(i+1)*batch_size] feed_dict[y] = y_train[i*batch_size:(i+1)*batch_size] _, loss_value = sess.run([train_op, loss], feed_dict) # update last loss value losses.append(loss_value) # test model in training set feed_dict[x] = X_train[indices_train] feed_dict[y] = y_train[indices_train] true_count = sess.run(eval_correct, feed_dict) scores_train.append(true_count / num_samples) # test model in validation set true_count = 0 total_batch_validation = int(y_validate.shape[0]/num_samples)+1 # loop over batches for i in range(total_batch_validation): feed_dict[x] = X_validate[i*num_samples:(i+1)*num_samples] feed_dict[y] = y_validate[i*num_samples:(i+1)*num_samples] true_count += sess.run(eval_correct, feed_dict) scores_validate.append(true_count / y_validate.shape[0]) print("Epoch: {:0>4}, Cost: {:.8f}, Acc@Training: {:.3f}, Acc@Validate: {:.3f}".format( (epoch), losses[-1], scores_train[-1], scores_validate[-1])) if epoch>1: #if scores_train[-1] >= 1: if (scores_validate[-1] < scores_validate[-2]) or (scores_validate[-1] > .998): break print("Optimization Finished! Time to complete: {:.2f}".format(time()-t0)) # create epochs epochs = np.arange(1,len(scores_train)+1,1) # set figure and axis fig, ax1 = plt.subplots() fig.set_size_inches((8,4)) # plot ax1.plot(epochs, scores_train,'b-', label='training score') ax1.plot(epochs, scores_validate, 'r-', label='validation score') plt.legend() ax2 = ax1.twinx() ax2.plot(epochs, losses, 'g--', label='loss'); # test model in testing set true_count = 0 batch_size = 1000 total_batch = int(y_test.shape[0]/batch_size)+1 # loop over batches for i in range(total_batch): t0= time() feed_dict[x] = X_test[i*batch_size:(i+1)*batch_size] feed_dict[y] = y_test[i*batch_size:(i+1)*batch_size] true_count += sess.run(eval_correct, feed_dict) score = true_count / y_test.shape[0] print("Acc@Test: {:.3f}".format(score)) # Non-transformed images: .936 # Transformed images, with 80% training set: .958 # Transformed images, with full training set: .960 # Transformed images, with full training set, tanh as non linear function: .970 # get probability distribution for new images softmax_pred = tf.nn.top_k(tf.nn.softmax(logits), 5) feed_dict[x] = X_new feed_dict[y] = y_new classes = sess.run(softmax_pred, feed_dict) for i in range(len(classes.values)): print(zip(classes.values[i], classes.indices[i])) print y_new ###Output [(0.99999487, 1), (1.8382967e-06, 0), (1.0728776e-06, 2), (9.9029455e-07, 6), (9.6554697e-07, 5)] [(0.99998009, 9), (1.3907021e-05, 41), (2.5391014e-06, 16), (1.5097144e-06, 23), (5.3574547e-07, 35)] [(0.99151868, 4), (0.0063370462, 0), (0.0021262243, 1), (6.1533524e-06, 18), (5.3878402e-06, 14)] [(0.99995756, 11), (1.5105596e-05, 18), (1.1499011e-05, 40), (7.2709777e-06, 30), (3.691787e-06, 42)] [(0.99819225, 18), (0.0015140012, 26), (0.00019332254, 11), (4.0405677e-05, 27), (3.9706778e-05, 37)] [(0.99579155, 28), (0.002493473, 35), (0.00069932808, 36), (0.0001690522, 19), (0.00016574388, 32)] [(0.93736994, 14), (0.033448607, 5), (0.020408753, 1), (0.0033263753, 8), (0.0018562834, 4)] [(0.99999404, 13), (1.7098735e-06, 12), (1.3186822e-06, 15), (1.2444472e-06, 35), (3.6900687e-07, 39)] [ 1 9 4 11 18 28 14 13]
CLT_vs_PJ.ipynb
###Markdown CLT vs PJ ###Code import pandas as pd import DescontosBeneficiosCLT as CLT import DescontosPJ as PJ ###Output _____no_output_____ ###Markdown Introdução Este documento visa apresentar um comparativo entre os valores líquidos recebidos entre as modalidades de contratação CLT e PJ. Auxiliando profissionais (principalmente na área de TI) a avaliar propostas de trabalho em diferente modalidades. Auxiliando também na compreensão dos direitos e deveres associados a cada uma das modalidades de contratação.Para os cálculos apresentados serão apresentados resultados para os diferentes métodos de pagamento do Imposto de Renda sobre Pessoa Física (pagamento simplificado e completo). Os resultados apresentados são estimativas e podem variar por diversos fatores: numero de hora trabalhadas (PJ), abatimentos nos cálculos do IR, reajustes, .... \* *É permitido a livre divulgação, modificação e utilização deste documento e deste repositório de acordo com os termos de [licença](files/LICENSE) MIT. Caso queira contribuir com melhorias e correções, faça-o através do repositório no Github.* Parâmetros Apenas as variáveis abaixo (dentro da seção "Parâmetros") precisam ser alteradas. Não há necessidade de alterar nenhum outro campo dentro de outras seções deste documento. Informações referentes à modalidade **CLT**: ###Code salario_mensal_bruto = 7500 # Salário bruto recebido mensalmente na modalidade CLT PLR = 2*salario_mensal_bruto # Valor da PLR ou Bonus anual recebidos na modalidade CLT VA_VR = 860.00 # Valor mensal de Vale Alimentação e Vale Refeição somados ###Output _____no_output_____ ###Markdown Informações referentes à modalidade **PJ**. Normalmente, para a modalidade PJ o contrato estipula o pagamento por horas trabalhadas, dessa forma é solicitado que seja informado o salário/hora.Na modalidade PJ, férias normalmente não são remuneradas, dessa forma deve-se informar o número de dias de férias no ano para que não seja considerado nenhum faturamento no período de férias. Deve-se considerar também custos relacionados como contratação de Contados, custo de aluguel de escritório (físico ou virtual), contratação de plano de saúde (para que a comparação fique justa com a proposta CLT que oferece plano de saúde), ... ###Code salario_PJ_hora = 133 # Salário/hora (R$/h) na modalidade PJ horas_mes = 170 # Número de horas trabalhadas no mês dias_ferias = 30 # Número de dias corridos de férias por ano (não remunerados na modalidade PJ) contador = 150.00 # Custos mensais com contador outros_custos = 200.00 # Outros custos mensais para operação da empresa e.g.: aluguel de escritório, custos com equipamentos, ... seguro_saude = 500.00 # Custo mensal do Plano de saúde de saúde que precisa serm contratado a parte. ###Output _____no_output_____ ###Markdown Informações complementares ###Code numero_dependentes = 0 # Número de dependentes para abatimento no IR - será utilizado tanto para cálculo CLT quanto PJ ###Output _____no_output_____ ###Markdown Cálculos CLT Cálculo dos descontos e benefícios na modalidade CLT INSS (mensal) ###Code INSS_mensal = CLT.INSS(salario_mensal_bruto) print(f"Valor mensal do INSS: R$ {INSS_mensal:,.2f}") ###Output Valor mensal do INSS: R$ 751.99 ###Markdown Imposto de Renda mensal sobre o salário (mensal) ###Code salario_base = salario_mensal_bruto - INSS_mensal # Salário Base para cálculo do IR, com os devidos descontos IR_mensal_simplificado = CLT.IR_Mensal_Simplificado(salario_mensal_bruto) # Opção de IR sobre salário com cálculo simplificado IR_mensal_completo = CLT.IR_Mensal(salario_base, numero_dependentes) # Opção de IR sobre salário com cálculo completo print(f"IR Simplificado sobre o salário: R$ {IR_mensal_simplificado:,.2f}") print(f"IR Completo sobre o salário: R$ {IR_mensal_completo:,.2f}") ###Output IR Simplificado sobre o salário: R$ 780.64 IR Completo sobre o salário: R$ 986.34 ###Markdown FGTS Para uma comparação justa com a modalidade PJ, o rendimento do FGTS não será considerado. Além disso, é importante salientar que o valor recebido via FGTS não é totalmente líquido, tendo sua utilização e resgate condicionados à ocasiões estabelecidas pela legislação.Os cálculos abaixo também não consideram os optantes pela modalidade de Saque-Aniversário, dado que nesta modalidade sim há o resgate parcial de forma líquida deste benefício. ###Code numero_meses = 1 # número de meses a considerar incluir_multa = False # Incluir o valor de 40% de Multa de demissão sem justa causa? incluir_rendimento = False # Incluir o cálculo do rendimento de juros do FGTS? FGTS_mensal = CLT.FGTS(salario_mensal_bruto, numero_meses, incluir_multa, incluir_rendimento) print(f"Valor mensal do FGTS: R$ {FGTS_mensal:,.2f}") ###Output Valor mensal do FGTS: R$ 600.00 ###Markdown Salário de Férias Neste cálculo é considerado o salário de férias no valor de 1+1/3 salário. E em seguida já é realizado o cálculo dos devidos descontos. ###Code salario_ferias = CLT.Salario_Ferias_Bruto(salario_mensal_bruto) INSS_ferias = CLT.INSS(salario_ferias) # Desconto de INSS no salário de férias salario_base_ferias = salario_ferias - INSS_ferias # Salário de Férias Base para cálculo do IR, com os devidos descontos IR_ferias_completo = CLT.IR_Mensal(salario_base_ferias, numero_dependentes) # Opção de IR sobre ferias com cálculo completo IR_ferias_simplificado = CLT.IR_Mensal_Simplificado(salario_ferias) # Opção de IR sobre ferias com cálculo simplificado print(f"Valor do salário de férias bruto: R$ {salario_ferias:,.2f}") print(f"INSS sobre o salário de férias: R$ {INSS_ferias:,.2f}") print(f"IR Simplificado sobre o salário de férias: R$ {IR_ferias_simplificado:,.2f}") print(f"IR Completo sobre o salário de férias: R$ {IR_ferias_completo:,.2f}") ###Output Valor do salário de férias bruto: R$ 10,000.00 INSS sobre o salário de férias: R$ 751.99 IR Simplificado sobre o salário de férias: R$ 1,330.64 IR Completo sobre o salário de férias: R$ 1,673.84 ###Markdown 13º Salário ###Code salario_13_bruto = salario_mensal_bruto INSS_13o = CLT.INSS(salario_13_bruto) # Desconto de INSS no 13º salário salario_base_13o = salario_13_bruto - INSS_13o # 13o Salário Base para cálculo do IR, com os devidos descontos IR_13o_completo = CLT.IR_Mensal(salario_base_13o, numero_dependentes) # Opção de IR sobre 13º com cálculo completo IR_13o_simplificado = CLT.IR_Mensal_Simplificado(salario_13_bruto) # Opção de IR sobre 13º com cálculo simplificado print(f"Valor bruto do 13º salário: R$ {salario_13_bruto:,.2f}") print(f"INSS sobre o 13º salário: R$ {INSS_13o:,.2f}") print(f"IR Simplificado sobre o 13º salário: R$ {IR_13o_simplificado:,.2f}") print(f"IR Completo sobre o 13º salário: R$ {IR_13o_completo:,.2f}") ###Output Valor bruto do 13º salário: R$ 7,500.00 INSS sobre o 13º salário: R$ 751.99 IR Simplificado sobre o 13º salário: R$ 780.64 IR Completo sobre o 13º salário: R$ 986.34 ###Markdown PLR / Bônus Cálculo dos descontos aplicados sobre a PLR ###Code IR_PLR = CLT.IR_PLR(PLR) print(f"IR Completo sobre o PLR anual: R$ {IR_PLR:,.2f}") ###Output IR Completo sobre o PLR anual: R$ 1,142.49 ###Markdown Resumo dos Cálculos Anuais Para o cálculo anual serão considerados os sálarios de 11 meses de trabalho mais 1 mês de férias. Os valores podem variar dentro do primeiro ano de contratação, dado que neste período o funcinário não possui o benefício das férias. ###Code # 11 meses de trabalho (1 mês de férias) salario_anual_liq_simp = (salario_mensal_bruto - INSS_mensal - IR_mensal_simplificado) * 11 # Salário líquido anual com IR Simplificado salario_anual_liq_comp = (salario_mensal_bruto - INSS_mensal - IR_mensal_completo) * 11 # Salário líquido anual com IR Completo salario_13_liq_simp = salario_13_bruto - INSS_13o - IR_13o_simplificado # 13º Salário Líquido com desconto de IR Simplificado salario_13_liq_comp = salario_13_bruto - INSS_13o - IR_13o_completo # 13º Salário Líquido com desconto de IR Completo salario_ferias_liq_simp = salario_ferias - INSS_ferias - IR_ferias_simplificado # Salário de Férias Líquido com desconto de IR Simplificado salario_ferias_liq_comp = salario_ferias - INSS_ferias - IR_ferias_completo # Salário de Férias Líquido com desconto de IR Completo PLR_liquido = PLR - IR_PLR # Valor da PLR líquido no ano # Salario + benefícios Brutos CLT_bruto_anual = salario_mensal_bruto*12 + salario_ferias + PLR + FGTS_mensal*(13+1/3) + VA_VR*12 # Salario + benefícios Líquidos CLT_liquido_anual_simp = salario_anual_liq_simp + salario_13_liq_simp + salario_ferias_liq_simp + PLR_liquido + FGTS_mensal*(13+1/3) + VA_VR*12 CLT_liquido_anual_comp = salario_anual_liq_comp + salario_13_liq_comp + salario_ferias_liq_comp + PLR_liquido + FGTS_mensal*(13+1/3) + VA_VR*12 print(f"Salário mensal bruto: R$ {salario_mensal_bruto:,.2f}") # Sálario mensal Bruto print(f"Salário anual bruto: R$ {CLT_bruto_anual:,.2f}") # Salario anual Bruto print(f"Salário anual líquido + benefícios (IR Simplificado): R$ {CLT_liquido_anual_simp:,.2f}") # Salario Líquido + benefícios print(f"Salário anual líquido + benefícios (IR Completo): R$ {CLT_liquido_anual_comp:,.2f}") # Salario Líquido + benefícios # Agregando os resultados dos cálculos para CLT Simplificado resultado_CLT_Simp = [] # Montar variável com resultados CLT Simplificado resultado_CLT_Simp.append(f'R$ {salario_mensal_bruto:,.2f} /mês') # Ref resultado_CLT_Simp.append(salario_mensal_bruto) # Salário Mensal resultado_CLT_Simp.append(salario_mensal_bruto-INSS_mensal-IR_mensal_simplificado) # Salário Mensal Líquido resultado_CLT_Simp.append((salario_mensal_bruto-INSS_mensal-IR_mensal_simplificado)*12) # Salário Anual Líquido resultado_CLT_Simp.append(CLT_liquido_anual_simp) # Liquido + Benefícios (Anual) # Agregando os resultados dos cálculos para CLT Completo resultado_CLT_Comp = [] # Montar variável com resultados CLT Completo resultado_CLT_Comp.append(f'R$ {salario_mensal_bruto:,.2f} /mês') # Ref resultado_CLT_Comp.append(salario_mensal_bruto) # Salário Mensal resultado_CLT_Comp.append(salario_mensal_bruto-INSS_mensal-IR_mensal_completo) # Salário Mensal Líquido resultado_CLT_Comp.append((salario_mensal_bruto-INSS_mensal-IR_mensal_completo)*12) # Salário Anual Líquido resultado_CLT_Comp.append(CLT_liquido_anual_comp) # Liquido + Benefícios (Anual) ###Output _____no_output_____ ###Markdown PJ SIMPLES NACIONAL (ANEXO III) Nesta seção serão considerados apenas os cálculos para empresas que se enquadram no Anexo III do Simples Nacional.Para que prestadores de serviço possam se enquadrar nessa modalidade é necessário que o fator R (cálculado abaixo) esteja dentro do limite estabelecido. Faturamento mensal e anual PJ ###Code receita_mensal_PJ = salario_PJ_hora * horas_mes # Faturamento mensal PJ meses_ferias = dias_ferias / 30 # Converte o numero de dias de férias para mêses para auxiliar no cálculo anual. Está aproximado o valor de 30 dias em um mês. receita_anual_PJ = receita_mensal_PJ * (12 - meses_ferias) # Cáculo da receita anual descontado os dias de férias não remuneradas print(f"Faturamento mensal PJ: R$ {receita_mensal_PJ:,.2f}") # Faturamento mensal PJ print(f"Faturamento mensal PJ: R$ {receita_anual_PJ:,.2f}") # Faturamento anual PJ ###Output Faturamento mensal PJ: R$ 22,610.00 Faturamento mensal PJ: R$ 248,710.00 ###Markdown Cálculo do Pro-Labore Para enquadramento de prestadores de serviço no Anexo III do Simples Nacional, a empresa deve possuir um Fator R acima de **0.28** (ou **28%**).O fator R é calculado dividindo o Pro-Labore pela receita bruta.O Pró-Labore é a remunueração dos sócios da empresa\*, neste documento estamos considerando um sócio único (uma única pessoa trabalhando dentro da modalidade PJ). Há incidência de Imposto de Renda sobre a remuneração do Pró-Labore, dessa forma, é desejável mantê-lo próximo ao limite permitido. Para os cálculos a seguir será considerado um Fator R de 30% (como margem de segurança).\* *Além do Pró-Labore, os demais rendimentos líquidos da empresa serão repassados ao sócios como **dividendos**, dado que por enquanto ainda não há incidência de Imposto sobre dividendos.* ###Code pro_labore = PJ.ProLabore_FatorR(receita_mensal_PJ, 0.30) # Cálculo do valor mensal do Pro-labore, utilizando fator R de 30% print(f"Valor do Pro-Labore mensal: R$ {pro_labore:,.2f}") # Pro-Labore mensal ###Output Valor do Pro-Labore mensal: R$ 6,783.00 ###Markdown Recolhimento de imposto DAS. A DAS é uma via única de recolhimento de imposto para PJ.O valor anual da DAS durante os primeiros 12 meses de atividade da empresa pode vir acima do valor calculado a seguir, devido ao cálculo proporcionalizado durante os 12 primeiros meses. Neste caso é possivel solicitar a restituição de pagamento a maior junto à Receita Federal. ###Code imposto_DAS_anual = PJ.DAS_SimplesNacionalIII(receita_anual_PJ) # Cálculo do imposto a ser recolhido via DAS print(f"Imposto DAS anual: R$ {imposto_DAS_anual:,.2f}") # Pro-Labore mensal ###Output Imposto DAS anual: R$ 18,495.52 ###Markdown Impostos Pessoa Física -- Pro-Labore Além da incidência de impostos sobre a Pessoa Jurídica, há tambéma incidência sobre a Pessoa Física, sobre o valor do Pró-Labore. ###Code ### INSS sobre pro-labore 11% INSS_prolabore_mensal = pro_labore * 0.11 # INSS sobre Pró-labore 11% print(f"Valor mensal do INSS: R$ {INSS_prolabore_mensal:,.2f}") ## IRRF sobre pro-labore prolabore_base = pro_labore - INSS_prolabore_mensal IR_prolabore_mensal_simplificado = CLT.IR_Mensal_Simplificado(prolabore_base) # Opção de IR sobre pró-labore com cálculo simplificado IR_prolabore_mensal_completo = CLT.IR_Mensal(prolabore_base, numero_dependentes) # Opção de IR sobre pró-labore com cálculo completo print(f"IR Simplificado sobre o pró-labore: R$ {IR_prolabore_mensal_simplificado:,.2f}") print(f"IR Completo sobre o pró-labore: R$ {IR_prolabore_mensal_completo:,.2f}") rendimento_liquido_anual_PJ_simpl = receita_anual_PJ - imposto_DAS_anual - contador - outros_custos - seguro_saude - (INSS_prolabore_mensal + IR_prolabore_mensal_simplificado) * (12 - meses_ferias) rendimento_liquido_anual_PJ_compl = receita_anual_PJ - imposto_DAS_anual - contador - outros_custos - seguro_saude - (INSS_prolabore_mensal + IR_prolabore_mensal_completo) * (12 - meses_ferias) print(f"Rendimento líquido anual para PJ (com IR simplificado sobre Pró-Labore): R$ {rendimento_liquido_anual_PJ_simpl:,.2f}") print(f"Rendimento líquido anual para PJ (com IR completo sobre Pró-Labore): R$ {rendimento_liquido_anual_PJ_compl:,.2f}") # Agregando os resultados dos cálculos para PJ Simplificado resultado_PJ_Simp = [] # Montar variável com resultados PJ Simplificado resultado_PJ_Simp.append(f'R$ {salario_PJ_hora:,.2f} /hora') # Ref resultado_PJ_Simp.append(receita_mensal_PJ) # Salário Mensal resultado_PJ_Simp.append(receita_mensal_PJ-INSS_prolabore_mensal-IR_prolabore_mensal_simplificado-imposto_DAS_anual/12) # Salário Mensal Líquido resultado_PJ_Simp.append(rendimento_liquido_anual_PJ_simpl) # Salário Anual Líquido resultado_PJ_Simp.append(rendimento_liquido_anual_PJ_simpl) # Liquido + Benefícios (Anual) # Agregando os resultados dos cálculos para PJ Completo resultado_PJ_Comp = [] # Montar variável com resultados PJ Completo resultado_PJ_Comp.append(f'R$ {salario_PJ_hora:,.2f} /hora') # Ref resultado_PJ_Comp.append(receita_mensal_PJ) # Salário Mensal resultado_PJ_Comp.append(receita_mensal_PJ-INSS_prolabore_mensal-IR_prolabore_mensal_completo-imposto_DAS_anual/12) # Salário Mensal Líquido resultado_PJ_Comp.append(rendimento_liquido_anual_PJ_compl) # Salário Anual Líquido resultado_PJ_Comp.append(rendimento_liquido_anual_PJ_compl) # Liquido + Benefícios (Anual) ###Output _____no_output_____ ###Markdown Resultado A tabela apresenta o resultado comparativo entre as opções de contratação CLT e PJ. Para cada uma das modalidades são consideradas as diferentes formas de tributação (Simplificada e Completa). O resultado aparecerá ordenado pelo valor Líquido + Benefícios (Anual) de forma decescente.Reforçando que os resultados apresentados são uma estimativa e podem variar na remuneração real. ###Code # Parâmetros, opções e formatação da tabela table_columns = ["Ref", "Salário Mensal", "Salário Líquido Mensal","Salário Líquido Anual","Líquido + Benefícios (Anual)"] table_index = ['CLT (Simplificado)', 'CLT (Completo)', 'PJ (Simplificado)', 'PJ (Completo)'] pd.options.display.max_columns = None pd.options.display.float_format = 'R$ {:,.2f}'.format # Format float numbers in dataTable df = pd.DataFrame([resultado_CLT_Simp, resultado_CLT_Comp, resultado_PJ_Simp, resultado_PJ_Comp], columns=table_columns, index=table_index) # Novas colunas calculadas df['Diferença Anual'] = df['Líquido + Benefícios (Anual)'] - df['Líquido + Benefícios (Anual)'].max() # Diferença para o maior valor df['Equivalente Mensal Líquido'] = df['Líquido + Benefícios (Anual)']/12 # Define column Equivalente Mensal df = df.sort_values(by='Líquido + Benefícios (Anual)', ascending=False) display(df) ###Output _____no_output_____ ###Markdown CLT vs PJ ###Code import pandas as pd import DescontosBeneficiosCLT as CLT import DescontosPJ as PJ ###Output _____no_output_____ ###Markdown Introdução Este documento visa apresentar um comparativo entre os valores líquidos recebidos entre as modalidades de contratação CLT e PJ. Auxiliando profissionais (principalmente na área de TI) a avaliar propostas de trabalho em diferente modalidades. Auxiliando também na compreensão dos direitos e deveres associados a cada uma das modalidades de contratação.Para os cálculos apresentados serão apresentados resultados para os diferentes métodos de pagamento do Imposto de Renda sobre Pessoa Física (pagamento simplificado e completo). Os resultados apresentados são estimativas e podem variar por diversos fatores: numero de hora trabalhadas (PJ), abatimentos nos cálculos do IR, reajustes, .... \* *É permitido a livre divulgação, modificação e utilização deste documento e deste repositório de acordo com os termos de [licença](files/LICENSE) MIT. Caso queira contribuir com melhorias e correções, faça-o através do repositório no Github.* Parâmetros Apenas as variáveis abaixo (dentro da seção "Parâmetros") precisam ser alteradas. Não há necessidade de alterar nenhum outro campo dentro de outras seções deste documento. Informações referentes à modalidade **CLT**: ###Code salario_mensal_bruto = 10000 # Salário bruto recebido mensalmente na modalidade CLT PLR = 2*salario_mensal_bruto # Valor da PLR ou Bonus anual recebidos na modalidade CLT VA_VR = 1500.00 # Valor mensal de Vale Alimentação e Vale Refeição somados ###Output _____no_output_____ ###Markdown Informações referentes à modalidade **PJ**. Normalmente, para a modalidade PJ o contrato estipula o pagamento por horas trabalhadas, dessa forma é solicitado que seja informado o salário/hora.Na modalidade PJ, férias normalmente não são remuneradas, dessa forma deve-se informar o número de dias de férias no ano para que não seja considerado nenhum faturamento no período de férias. Deve-se considerar também custos relacionados como contratação de Contados, custo de aluguel de escritório (físico ou virtual), contratação de plano de saúde (para que a comparação fique justa com a proposta CLT que oferece plano de saúde), ... ###Code salario_PJ_hora = 100.00 # Salário/hora (R$/h) na modalidade PJ horas_mes = 170 # Número de horas trabalhadas no mês dias_ferias = 30 # Número de dias corridos de férias por ano (não remunerados na modalidade PJ) contador = 100.00 # Custos mensais com contador outros_custos = 0.00 # Outros custos mensais para operação da empresa e.g.: aluguel de escritório, custos com equipamentos, ... seguro_saude = 0.00 # Custo mensal do Plano de saúde de saúde que precisa serm contratado a parte. ###Output _____no_output_____ ###Markdown Informações complementares ###Code numero_dependentes = 1 # Número de dependentes para abatimento no IR - será utilizado tanto para cálculo CLT quanto PJ ###Output _____no_output_____ ###Markdown Cálculos CLT Cálculo dos descontos e benefícios na modalidade CLT INSS (mensal) ###Code INSS_mensal = CLT.INSS(salario_mensal_bruto) print(f"Valor mensal do INSS: R$ {INSS_mensal:,.2f}") ###Output Valor mensal do INSS: R$ 751.99 ###Markdown Imposto de Renda mensal sobre o salário (mensal) ###Code salario_base = salario_mensal_bruto - INSS_mensal # Salário Base para cálculo do IR, com os devidos descontos IR_mensal_simplificado = CLT.IR_Mensal_Simplificado(salario_mensal_bruto) # Opção de IR sobre salário com cálculo simplificado IR_mensal_completo = CLT.IR_Mensal(salario_base, numero_dependentes) # Opção de IR sobre salário com cálculo completo print(f"IR Simplificado sobre o salário: R$ {IR_mensal_simplificado:,.2f}") print(f"IR Completo sobre o salário: R$ {IR_mensal_completo:,.2f}") ###Output IR Simplificado sobre o salário: R$ 1,330.64 IR Completo sobre o salário: R$ 1,621.71 ###Markdown FGTS Para uma comparação justa com a modalidade PJ, o rendimento do FGTS não será considerado. Além disso, é importante salientar que o valor recebido via FGTS não é totalmente líquido, tendo sua utilização e resgate condicionados à ocasiões estabelecidas pela legislação.Os cálculos abaixo também não consideram os optantes pela modalidade de Saque-Aniversário, dado que nesta modalidade sim há o resgate parcial de forma líquida deste benefício. ###Code numero_meses = 1 # número de meses a considerar incluir_multa = False # Incluir o valor de 40% de Multa de demissão sem justa causa? incluir_rendimento = False # Incluir o cálculo do rendimento de juros do FGTS? FGTS_mensal = CLT.FGTS(salario_mensal_bruto, numero_meses, incluir_multa, incluir_rendimento) print(f"Valor mensal do FGTS: R$ {FGTS_mensal:,.2f}") ###Output Valor mensal do FGTS: R$ 800.00 ###Markdown Salário de Férias Neste cálculo é considerado o salário de férias no valor de 1+1/3 salário. E em seguida já é realizado o cálculo dos devidos descontos. ###Code salario_ferias = CLT.Salario_Ferias_Bruto(salario_mensal_bruto) INSS_ferias = CLT.INSS(salario_ferias) # Desconto de INSS no salário de férias salario_base_ferias = salario_ferias - INSS_ferias # Salário de Férias Base para cálculo do IR, com os devidos descontos IR_ferias_completo = CLT.IR_Mensal(salario_base_ferias, numero_dependentes) # Opção de IR sobre ferias com cálculo completo IR_ferias_simplificado = CLT.IR_Mensal_Simplificado(salario_ferias) # Opção de IR sobre ferias com cálculo simplificado print(f"Valor do salário de férias bruto: R$ {salario_ferias:,.2f}") print(f"INSS sobre o salário de férias: R$ {INSS_ferias:,.2f}") print(f"IR Simplificado sobre o salário de férias: R$ {IR_ferias_simplificado:,.2f}") print(f"IR Completo sobre o salário de férias: R$ {IR_ferias_completo:,.2f}") ###Output Valor do salário de férias bruto: R$ 13,333.33 INSS sobre o salário de férias: R$ 751.99 IR Simplificado sobre o salário de férias: R$ 2,063.97 IR Completo sobre o salário de férias: R$ 2,538.37 ###Markdown 13º Salário ###Code salario_13_bruto = salario_mensal_bruto INSS_13o = CLT.INSS(salario_13_bruto) # Desconto de INSS no 13º salário salario_base_13o = salario_13_bruto - INSS_13o # 13o Salário Base para cálculo do IR, com os devidos descontos IR_13o_completo = CLT.IR_Mensal(salario_base_13o, numero_dependentes) # Opção de IR sobre 13º com cálculo completo IR_13o_simplificado = CLT.IR_Mensal_Simplificado(salario_13_bruto) # Opção de IR sobre 13º com cálculo simplificado print(f"Valor bruto do 13º salário: R$ {salario_13_bruto:,.2f}") print(f"INSS sobre o 13º salário: R$ {INSS_13o:,.2f}") print(f"IR Simplificado sobre o 13º salário: R$ {IR_13o_simplificado:,.2f}") print(f"IR Completo sobre o 13º salário: R$ {IR_13o_completo:,.2f}") ###Output Valor bruto do 13º salário: R$ 10,000.00 INSS sobre o 13º salário: R$ 751.99 IR Simplificado sobre o 13º salário: R$ 1,330.64 IR Completo sobre o 13º salário: R$ 1,621.71 ###Markdown PLR / Bônus Cálculo dos descontos aplicados sobre a PLR ###Code IR_PLR = CLT.IR_PLR(PLR) print(f"IR Completo sobre o PLR anual: R$ {IR_PLR:,.2f}") ###Output IR Completo sobre o PLR anual: R$ 2,448.47 ###Markdown Resumo dos Cálculos Anuais Para o cálculo anual serão considerados os sálarios de 11 meses de trabalho mais 1 mês de férias. Os valores podem variar dentro do primeiro ano de contratação, dado que neste período o funcinário não possui o benefício das férias. ###Code # 11 meses de trabalho (1 mês de férias) salario_anual_liq_simp = (salario_mensal_bruto - INSS_mensal - IR_mensal_simplificado) * 11 # Salário líquido anual com IR Simplificado salario_anual_liq_comp = (salario_mensal_bruto - INSS_mensal - IR_mensal_completo) * 11 # Salário líquido anual com IR Completo salario_13_liq_simp = salario_13_bruto - INSS_13o - IR_13o_simplificado # 13º Salário Líquido com desconto de IR Simplificado salario_13_liq_comp = salario_13_bruto - INSS_13o - IR_13o_completo # 13º Salário Líquido com desconto de IR Completo salario_ferias_liq_simp = salario_ferias - INSS_ferias - IR_ferias_simplificado # Salário de Férias Líquido com desconto de IR Simplificado salario_ferias_liq_comp = salario_ferias - INSS_ferias - IR_ferias_completo # Salário de Férias Líquido com desconto de IR Completo PLR_liquido = PLR - IR_PLR # Valor da PLR líquido no ano # Salario + benefícios Brutos CLT_bruto_anual = salario_mensal_bruto*12 + salario_ferias + PLR + FGTS_mensal*(13+1/3) + VA_VR*12 # Salario + benefícios Líquidos CLT_liquido_anual_simp = salario_anual_liq_simp + salario_13_liq_simp + salario_ferias_liq_simp + PLR_liquido + FGTS_mensal*(13+1/3) + VA_VR*12 CLT_liquido_anual_comp = salario_anual_liq_comp + salario_13_liq_comp + salario_ferias_liq_comp + PLR_liquido + FGTS_mensal*(13+1/3) + VA_VR*12 print(f"Salário mensal bruto: R$ {salario_mensal_bruto:,.2f}") # Sálario mensal Bruto print(f"Salário anual bruto: R$ {CLT_bruto_anual:,.2f}") # Salario anual Bruto print(f"Salário anual líquido + benefícios (IR Simplificado): R$ {CLT_liquido_anual_simp:,.2f}") # Salario Líquido + benefícios print(f"Salário anual líquido + benefícios (IR Completo): R$ {CLT_liquido_anual_comp:,.2f}") # Salario Líquido + benefícios # Agregando os resultados dos cálculos para CLT Simplificado resultado_CLT_Simp = [] # Montar variável com resultados CLT Simplificado resultado_CLT_Simp.append(f'R$ {salario_mensal_bruto:,.2f} /mês') # Ref resultado_CLT_Simp.append(salario_mensal_bruto) # Salário Mensal resultado_CLT_Simp.append(salario_mensal_bruto-INSS_mensal-IR_mensal_simplificado) # Salário Mensal Líquido resultado_CLT_Simp.append((salario_mensal_bruto-INSS_mensal-IR_mensal_simplificado)*12) # Salário Anual Líquido resultado_CLT_Simp.append(CLT_liquido_anual_simp) # Liquido + Benefícios (Anual) # Agregando os resultados dos cálculos para CLT Completo resultado_CLT_Comp = [] # Montar variável com resultados CLT Completo resultado_CLT_Comp.append(f'R$ {salario_mensal_bruto:,.2f} /mês') # Ref resultado_CLT_Comp.append(salario_mensal_bruto) # Salário Mensal resultado_CLT_Comp.append(salario_mensal_bruto-INSS_mensal-IR_mensal_completo) # Salário Mensal Líquido resultado_CLT_Comp.append((salario_mensal_bruto-INSS_mensal-IR_mensal_completo)*12) # Salário Anual Líquido resultado_CLT_Comp.append(CLT_liquido_anual_comp) # Liquido + Benefícios (Anual) ###Output _____no_output_____ ###Markdown PJ SIMPLES NACIONAL (ANEXO III) Nesta seção serão considerados apenas os cálculos para empresas que se enquadram no Anexo III do Simples Nacional.Para que prestadores de serviço possam se enquadrar nessa modalidade é necessário que o fator R (cálculado abaixo) esteja dentro do limite estabelecido. Faturamento mensal e anual PJ ###Code receita_mensal_PJ = salario_PJ_hora * horas_mes # Faturamento mensal PJ meses_ferias = dias_ferias / 30 # Converte o numero de dias de férias para mêses para auxiliar no cálculo anual. Está aproximado o valor de 30 dias em um mês. receita_anual_PJ = receita_mensal_PJ * (12 - meses_ferias) # Cáculo da receita anual descontado os dias de férias não remuneradas print(f"Faturamento mensal PJ: R$ {receita_mensal_PJ:,.2f}") # Faturamento mensal PJ print(f"Faturamento mensal PJ: R$ {receita_anual_PJ:,.2f}") # Faturamento anual PJ ###Output Faturamento mensal PJ: R$ 17,000.00 Faturamento mensal PJ: R$ 187,000.00 ###Markdown Cálculo do Pro-Labore Para enquadramento de prestadores de serviço no Anexo III do Simples Nacional, a empresa deve possuir um Fator R acima de **0.28** (ou **28%**).O fator R é calculado dividindo o Pro-Labore pela receita bruta.O Pró-Labore é a remunueração dos sócios da empresa\*, neste documento estamos considerando um sócio único (uma única pessoa trabalhando dentro da modalidade PJ). Há incidência de Imposto de Renda sobre a remuneração do Pró-Labore, dessa forma, é desejável mantê-lo próximo ao limite permitido. Para os cálculos a seguir será considerado um Fator R de 30% (como margem de segurança).\* *Além do Pró-Labore, os demais rendimentos líquidos da empresa serão repassados ao sócios como **dividendos**, dado que por enquanto ainda não há incidência de Imposto sobre dividendos.* ###Code pro_labore = PJ.ProLabore_FatorR(receita_mensal_PJ, 0.30) # Cálculo do valor mensal do Pro-labore, utilizando fator R de 30% print(f"Valor do Pro-Labore mensal: R$ {pro_labore:,.2f}") # Pro-Labore mensal ###Output Valor do Pro-Labore mensal: R$ 5,100.00 ###Markdown Recolhimento de imposto DAS. A DAS é uma via única de recolhimento de imposto para PJ.O valor anual da DAS durante os primeiros 12 meses de atividade da empresa pode vir acima do valor calculado a seguir, devido ao cálculo proporcionalizado durante os 12 primeiros meses. Neste caso é possivel solicitar a restituição de pagamento a maior junto à Receita Federal. ###Code imposto_DAS_anual = PJ.DAS_SimplesNacionalIII(receita_anual_PJ) # Cálculo do imposto a ser recolhido via DAS print(f"Imposto DAS anual: R$ {imposto_DAS_anual:,.2f}") # Pro-Labore mensal ###Output Imposto DAS anual: R$ 11,584.00 ###Markdown Impostos Pessoa Física -- Pro-Labore Além da incidência de impostos sobre a Pessoa Jurídica, há tambéma incidência sobre a Pessoa Física, sobre o valor do Pró-Labore. ###Code ### INSS sobre pro-labore 11% INSS_prolabore_mensal = pro_labore * 0.11 # INSS sobre Pró-labore 11% print(f"Valor mensal do INSS: R$ {INSS_prolabore_mensal:,.2f}") ## IRRF sobre pro-labore prolabore_base = pro_labore - INSS_prolabore_mensal IR_prolabore_mensal_simplificado = CLT.IR_Mensal_Simplificado(prolabore_base) # Opção de IR sobre pró-labore com cálculo simplificado IR_prolabore_mensal_completo = CLT.IR_Mensal(prolabore_base, numero_dependentes) # Opção de IR sobre pró-labore com cálculo completo print(f"IR Simplificado sobre o pró-labore: R$ {IR_prolabore_mensal_simplificado:,.2f}") print(f"IR Completo sobre o pró-labore: R$ {IR_prolabore_mensal_completo:,.2f}") rendimento_liquido_anual_PJ_simpl = receita_anual_PJ - imposto_DAS_anual - contador - outros_custos - seguro_saude - (INSS_prolabore_mensal + IR_prolabore_mensal_simplificado) * (12 - meses_ferias) rendimento_liquido_anual_PJ_compl = receita_anual_PJ - imposto_DAS_anual - contador - outros_custos - seguro_saude - (INSS_prolabore_mensal + IR_prolabore_mensal_completo) * (12 - meses_ferias) print(f"Rendimento líquido anual para PJ (com IR simplificado sobre Pró-Labore): R$ {rendimento_liquido_anual_PJ_simpl:,.2f}") print(f"Rendimento líquido anual para PJ (com IR completo sobre Pró-Labore): R$ {rendimento_liquido_anual_PJ_compl:,.2f}") # Agregando os resultados dos cálculos para PJ Simplificado resultado_PJ_Simp = [] # Montar variável com resultados PJ Simplificado resultado_PJ_Simp.append(f'R$ {salario_PJ_hora:,.2f} /hora') # Ref resultado_PJ_Simp.append(receita_mensal_PJ) # Salário Mensal resultado_PJ_Simp.append(receita_mensal_PJ-INSS_prolabore_mensal-IR_prolabore_mensal_simplificado-imposto_DAS_anual/12) # Salário Mensal Líquido resultado_PJ_Simp.append(rendimento_liquido_anual_PJ_simpl) # Salário Anual Líquido resultado_PJ_Simp.append(rendimento_liquido_anual_PJ_simpl) # Liquido + Benefícios (Anual) # Agregando os resultados dos cálculos para PJ Completo resultado_PJ_Comp = [] # Montar variável com resultados PJ Completo resultado_PJ_Comp.append(f'R$ {salario_PJ_hora:,.2f} /hora') # Ref resultado_PJ_Comp.append(receita_mensal_PJ) # Salário Mensal resultado_PJ_Comp.append(receita_mensal_PJ-INSS_prolabore_mensal-IR_prolabore_mensal_completo-imposto_DAS_anual/12) # Salário Mensal Líquido resultado_PJ_Comp.append(rendimento_liquido_anual_PJ_compl) # Salário Anual Líquido resultado_PJ_Comp.append(rendimento_liquido_anual_PJ_compl) # Liquido + Benefícios (Anual) ###Output _____no_output_____ ###Markdown Resultado A tabela apresenta o resultado comparativo entre as opções de contratação CLT e PJ. Para cada uma das modalidades são consideradas as diferentes formas de tributação (Simplificada e Completa). O resultado aparecerá ordenado pelo valor Líquido + Benefícios (Anual) de forma decescente.Reforçando que os resultados apresentados são uma estimativa e podem variar na remuneração real. ###Code # Parâmetros, opções e formatação da tabela table_columns = ["Ref", "Salário Mensal", "Salário Líquido Mensal","Salário Líquido Anual","Líquido + Benefícios (Anual)"] table_index = ['CLT (Simplificado)', 'CLT (Completo)', 'PJ (Simplificado)', 'PJ (Completo)'] pd.options.display.max_columns = None pd.options.display.float_format = 'R$ {:,.2f}'.format # Format float numbers in dataTable df = pd.DataFrame([resultado_CLT_Simp, resultado_CLT_Comp, resultado_PJ_Simp, resultado_PJ_Comp], columns=table_columns, index=table_index) # Novas colunas calculadas df['Diferença Anual'] = df['Líquido + Benefícios (Anual)'] - df['Líquido + Benefícios (Anual)'].max() # Diferença para o maior valor df['Equivalente Mensal Líquido'] = df['Líquido + Benefícios (Anual)']/12 # Define column Equivalente Mensal df = df.sort_values(by='Líquido + Benefícios (Anual)', ascending=False) display(df) ###Output _____no_output_____
Day03/deep_learning_COMPLETE.ipynb
###Markdown TensorFlow & Keras - Basics of Deep Learning Most importantly... resourceshttps://www.tensorflow.org/api_docshttps://keras.io/https://www.tensorflow.org/tutorials/https://www.google.com TF overview* "End-to-end machine learning platform" - Not the only one! Check out PyTorch, Theano, Cognitive Toolkit. * Integrates with high-level APIs like Keras* Plays nice with Pandas* Makes deep learning *fast* and *easy* * *"easy" Tasks for TensorFlow:* Regression - Predict house prices - Predict drug metabolic rates - Predict stock trends * *this is super hard * Classification - Cat or dog? - Malignant or benign cancer from images ![](media/dr.png) Google AI Blog: Diabetic Retinopathy* Dimensionality reduction - Visualize high-dimensional data in 2 or 3-D space - Compress representations for successive ML* Generative models - Create new molecules with desirable properties - Artificially enhance image resolution ![](media/molecular_gan.png) Kadurin et al., 2017* Reinforcement learning - Can't beat your friends at chess? Make your computer do it* Much more... - Generic math - Probabilistic programming with TFP - Automatic differentiation - ... Let's Regress Imports! ###Code import numpy as np import pandas as pd ###Output _____no_output_____ ###Markdown Name a more iconic duo, I'll wait New imports -- TF and Keras ###Code import keras import tensorflow as tf ###Output Using TensorFlow backend. ###Markdown Check our versions for good measure -- these programs may have very different behavior version-to-version ###Code print(keras.__version__) print(tf.__version__) ###Output 2.2.4 1.13.1 ###Markdown Loading in housing data as with SKLearn ###Code data = pd.read_csv('kc_house_data.csv') data data["yr_built"].unique() column_selection = ["bedrooms","bathrooms","sqft_living","sqft_lot", "floors","condition","grade","sqft_above", "sqft_basement","sqft_living15","sqft_lot15", "lat", "long","yr_built","yr_renovated","waterfront"] selected_feature = np.array(data[column_selection]) price = np.array(data["price"]) selected_feature_train = selected_feature[:20000] price_train = price[:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] def score(y,y_pred): return np.mean(np.abs(y-y_pred)/y) model = keras.Sequential() input_len = len(column_selection) model.add(keras.layers.Dense(50, input_dim=input_len, activation='relu')) model.add(keras.layers.Dense(50, activation='relu')) model.add(keras.layers.Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128) preds = model.predict(selected_feature_test) score(preds, price_test) ###Output _____no_output_____ ###Markdown Like SKLearn, it's easy to train and evaluate simple models. ... but we should try to do better Practical Deep Learning -- What you need to know Train, Validation, Test: * Optimize parameters with Train (weights, biases) * Optimize hyperparameters with Validation (layer width & depth, activation functions, etc.) * Optimize NOTHING with Test ###Code # Split out a validation set for hyperparameter optimization selected_feature_train = selected_feature[:18000] price_train = price[:18000] selected_feature_val = selected_feature[18000:20000] price_val = price[18000:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] ###Output _____no_output_____ ###Markdown Try a hyperparameter optimization: Try three activation functions to use for dense layers in the neural network above. Save the model that achieves the best validation loss Hint: [activation functions](http://letmegooglethat.com/?q=keras+activation+functions) Hint: `model.fit` has argument "`validation_data`" which takes a tuple of features and targets Hint: Use `model.save("filename.h5")` to save a model locally. If you want to use it later, just call `keras.models.load_model("filename.h5")` ###Code # For easy looping, define neural network model as a function def nn_model(optimizer='adam', activation='relu', layers=[20,20], loss='mean_squared_error'): model = keras.Sequential() model.add(keras.layers.Dense(50, input_dim=input_len, activation=activ)) model.add(keras.layers.Dense(50, activation=activ)) model.add(keras.layers.Dense(1)) model.compile(loss='mean_absolute_error', optimizer='adam') return model best_score = 1000.0 # bad # loop over chosen activation functions, train, evaluate on validation for activ in ['sigmoid', 'tanh', 'relu']: model = nn_model(activation=activ) history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) if model_score < best_score: best_score = model_score best_activ = activ best_model = model best_train = history print(f"BEST ACTIVATION FUNCTION {best_activ} WITH SCORE {best_score}") best_model.save("awesome_model.h5") ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 61us/step - loss: 532974.1758 - val_loss: 557914.6710 Epoch 2/50 18000/18000 [==============================] - 0s 15us/step - loss: 532967.3181 - val_loss: 557908.9735 Epoch 3/50 18000/18000 [==============================] - 0s 13us/step - loss: 532962.1269 - val_loss: 557903.9525 Epoch 4/50 18000/18000 [==============================] - 0s 14us/step - loss: 532957.2894 - val_loss: 557899.4930 Epoch 5/50 18000/18000 [==============================] - 0s 13us/step - loss: 532952.5633 - val_loss: 557894.6470 Epoch 6/50 18000/18000 [==============================] - 0s 9us/step - loss: 532947.9042 - val_loss: 557889.8510 Epoch 7/50 18000/18000 [==============================] - 0s 11us/step - loss: 532943.2878 - val_loss: 557885.5170 Epoch 8/50 18000/18000 [==============================] - 0s 10us/step - loss: 532938.6823 - val_loss: 557880.8320 Epoch 9/50 18000/18000 [==============================] - 0s 10us/step - loss: 532934.1124 - val_loss: 557876.0225 Epoch 10/50 18000/18000 [==============================] - 0s 10us/step - loss: 532929.5258 - val_loss: 557871.6970 Epoch 11/50 18000/18000 [==============================] - 0s 14us/step - loss: 532924.9893 - val_loss: 557867.0405 Epoch 12/50 18000/18000 [==============================] - 0s 12us/step - loss: 532920.4284 - val_loss: 557862.6110 Epoch 13/50 18000/18000 [==============================] - 0s 12us/step - loss: 532915.8835 - val_loss: 557857.9335 Epoch 14/50 18000/18000 [==============================] - 0s 12us/step - loss: 532911.3458 - val_loss: 557853.6650 Epoch 15/50 18000/18000 [==============================] - 0s 14us/step - loss: 532906.8151 - val_loss: 557848.8690 Epoch 16/50 18000/18000 [==============================] - 0s 12us/step - loss: 532902.2797 - val_loss: 557844.4835 Epoch 17/50 18000/18000 [==============================] - 0s 10us/step - loss: 532897.7445 - val_loss: 557839.8085 Epoch 18/50 18000/18000 [==============================] - 0s 10us/step - loss: 532893.2282 - val_loss: 557835.5010 Epoch 19/50 18000/18000 [==============================] - 0s 10us/step - loss: 532888.7034 - val_loss: 557830.8360 Epoch 20/50 18000/18000 [==============================] - 0s 10us/step - loss: 532884.1843 - val_loss: 557826.4430 Epoch 21/50 18000/18000 [==============================] - 0s 12us/step - loss: 532879.6504 - val_loss: 557821.7920 Epoch 22/50 18000/18000 [==============================] - 0s 14us/step - loss: 532875.1483 - val_loss: 557817.4790 Epoch 23/50 18000/18000 [==============================] - 0s 13us/step - loss: 532870.6122 - val_loss: 557812.8160 Epoch 24/50 18000/18000 [==============================] - 0s 11us/step - loss: 532866.1056 - val_loss: 557808.3360 Epoch 25/50 18000/18000 [==============================] - 0s 10us/step - loss: 532861.5706 - val_loss: 557803.7380 Epoch 26/50 18000/18000 [==============================] - 0s 11us/step - loss: 532857.0776 - val_loss: 557799.1610 Epoch 27/50 18000/18000 [==============================] - 0s 10us/step - loss: 532852.5495 - val_loss: 557794.6775 Epoch 28/50 18000/18000 [==============================] - 0s 14us/step - loss: 532848.0404 - val_loss: 557789.9945 Epoch 29/50 18000/18000 [==============================] - 0s 15us/step - loss: 532843.5083 - val_loss: 557785.6990 Epoch 30/50 18000/18000 [==============================] - 0s 14us/step - loss: 532839.0229 - val_loss: 557781.0485 Epoch 31/50 18000/18000 [==============================] - 0s 12us/step - loss: 532834.4841 - val_loss: 557776.6410 Epoch 32/50 18000/18000 [==============================] - 0s 12us/step - loss: 532829.9850 - val_loss: 557771.9805 Epoch 33/50 18000/18000 [==============================] - 0s 12us/step - loss: 532825.4563 - val_loss: 557767.6930 Epoch 34/50 18000/18000 [==============================] - 0s 12us/step - loss: 532820.7999 - val_loss: 557762.6110 Epoch 35/50 18000/18000 [==============================] - 0s 10us/step - loss: 532815.6766 - val_loss: 557757.6930 Epoch 36/50 18000/18000 [==============================] - 0s 10us/step - loss: 532810.8327 - val_loss: 557752.8360 Epoch 37/50 18000/18000 [==============================] - 0s 9us/step - loss: 532806.0533 - val_loss: 557747.9525 Epoch 38/50 18000/18000 [==============================] - 0s 9us/step - loss: 532801.3039 - val_loss: 557743.0485 Epoch 39/50 18000/18000 [==============================] - 0s 9us/step - loss: 532796.0384 - val_loss: 557737.7920 Epoch 40/50 18000/18000 [==============================] - 0s 9us/step - loss: 532790.9252 - val_loss: 557732.8320 Epoch 41/50 18000/18000 [==============================] - 0s 9us/step - loss: 532785.9397 - val_loss: 557727.7980 Epoch 42/50 18000/18000 [==============================] - 0s 13us/step - loss: 532781.0243 - val_loss: 557722.8730 Epoch 43/50 18000/18000 [==============================] - 0s 15us/step - loss: 532776.1177 - val_loss: 557717.9525 Epoch 44/50 18000/18000 [==============================] - 0s 14us/step - loss: 532771.2528 - val_loss: 557713.3645 Epoch 45/50 18000/18000 [==============================] - 0s 11us/step - loss: 532766.3882 - val_loss: 557708.4470 Epoch 46/50 18000/18000 [==============================] - 0s 11us/step - loss: 532761.5342 - val_loss: 557703.6650 Epoch 47/50 18000/18000 [==============================] - 0s 14us/step - loss: 532756.7074 - val_loss: 557698.6670 Epoch 48/50 18000/18000 [==============================] - 0s 11us/step - loss: 532751.8659 - val_loss: 557693.7030 Epoch 49/50 18000/18000 [==============================] - 0s 14us/step - loss: 532746.5045 - val_loss: 557688.0105 Epoch 50/50 18000/18000 [==============================] - 0s 13us/step - loss: 532741.2496 - val_loss: 557683.0085 Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 66us/step - loss: 532968.8535 - val_loss: 557907.8785 Epoch 2/50 18000/18000 [==============================] - 0s 11us/step - loss: 532959.6811 - val_loss: 557900.1345 Epoch 3/50 18000/18000 [==============================] - 0s 12us/step - loss: 532952.1103 - val_loss: 557892.8225 Epoch 4/50 18000/18000 [==============================] - 0s 11us/step - loss: 532944.7126 - val_loss: 557885.5415 Epoch 5/50 18000/18000 [==============================] - 0s 11us/step - loss: 532937.3764 - val_loss: 557877.9805 Epoch 6/50 18000/18000 [==============================] - 0s 12us/step - loss: 532930.0783 - val_loss: 557870.8360 Epoch 7/50 18000/18000 [==============================] - 0s 12us/step - loss: 532922.8012 - val_loss: 557863.6790 Epoch 8/50 18000/18000 [==============================] - 0s 12us/step - loss: 532915.5595 - val_loss: 557856.4430 Epoch 9/50 18000/18000 [==============================] - 0s 12us/step - loss: 532908.3144 - val_loss: 557849.0125 Epoch 10/50 18000/18000 [==============================] - 0s 12us/step - loss: 532901.0774 - val_loss: 557841.7920 Epoch 11/50 18000/18000 [==============================] - 0s 12us/step - loss: 532893.8619 - val_loss: 557834.6450 Epoch 12/50 18000/18000 [==============================] - 0s 12us/step - loss: 532886.6362 - val_loss: 557827.5335 Epoch 13/50 18000/18000 [==============================] - 0s 11us/step - loss: 532879.4228 - val_loss: 557820.0150 Epoch 14/50 18000/18000 [==============================] - 0s 11us/step - loss: 532872.2118 - val_loss: 557812.9090 Epoch 15/50 18000/18000 [==============================] - 0s 10us/step - loss: 532864.9957 - val_loss: 557805.7820 Epoch 16/50 18000/18000 [==============================] - 0s 11us/step - loss: 532857.7976 - val_loss: 557798.6210 Epoch 17/50 18000/18000 [==============================] - 0s 16us/step - loss: 532850.5966 - val_loss: 557791.5170 Epoch 18/50 18000/18000 [==============================] - 0s 13us/step - loss: 532843.3934 - val_loss: 557783.9945 Epoch 19/50 18000/18000 [==============================] - 0s 14us/step - loss: 532836.1900 - val_loss: 557776.8790 Epoch 20/50 18000/18000 [==============================] - 0s 15us/step - loss: 532828.9844 - val_loss: 557769.7820 ###Markdown Visualize your training: ###Code import matplotlib.pyplot as plt # plot loss during training def plot_loss(hist): %matplotlib inline plt.title('Training Curve') plt.plot(hist.history['loss'], label='train') plt.plot(hist.history['val_loss'], label='validation') plt.xlabel("Epochs") plt.ylabel("Mean squared error") plt.legend() plt.show() plot_loss(best_train) ###Output _____no_output_____ ###Markdown In the future, try better validation schemes like [k-fold cross validation](https://chrisalbon.com/deep_learning/keras/k-fold_cross-validating_neural_networks/), though 80/20 or 90/10 train/val like this works in a pinch Standardize your features:* Typically assumes normally distributed feature, shifting mean to 0 and standard deviation to 1* In theory does not matter for neural networks* In practice tends to matter for neural networks* Scale if using: - Logistic regression - Support vector machines - Perceptrons - Neural networks - Principle component analysis* Don't bother if using: - "Forest" methods - Naive Bayes ###Code from sklearn.preprocessing import StandardScaler # Instantiate StandardScaler in_scaler = StandardScaler() # Fit scaler to the training set and perform the transformation selected_feature_train = in_scaler.fit_transform(selected_feature_train) # Use the fitted scaler to transform validation and test features selected_feature_val = in_scaler.transform(selected_feature_val) selected_feature_test = in_scaler.transform(selected_feature_test) # Check appropriate scaling print(np.mean(selected_feature_train[:,0])) print(np.std(selected_feature_train[:,0])) print(np.mean(selected_feature_val[:,0])) print(np.std(selected_feature_val[:,0])) print(np.mean(selected_feature_test[:,0])) print(np.std(selected_feature_test[:,0])) model = nn_model() model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=200, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(model_score) plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/200 18000/18000 [==============================] - 1s 69us/step - loss: 416644724774.2293 - val_loss: 456240251273.2160 Epoch 2/200 18000/18000 [==============================] - 0s 14us/step - loss: 416219411047.3102 - val_loss: 455230525276.1600 Epoch 3/200 18000/18000 [==============================] - 0s 16us/step - loss: 414539373463.3245 - val_loss: 452292457267.2000 Epoch 4/200 18000/18000 [==============================] - 0s 14us/step - loss: 410731792826.3680 - val_loss: 446517339226.1120 Epoch 5/200 18000/18000 [==============================] - 0s 12us/step - loss: 403953550943.1182 - val_loss: 437057174896.6400 Epoch 6/200 18000/18000 [==============================] - 0s 11us/step - loss: 393657770544.6969 - val_loss: 423509280423.9360 Epoch 7/200 18000/18000 [==============================] - 0s 11us/step - loss: 379580761156.2667 - val_loss: 405581878001.6640 Epoch 8/200 18000/18000 [==============================] - 0s 11us/step - loss: 361658841912.6613 - val_loss: 383390637883.3920 Epoch 9/200 18000/18000 [==============================] - 0s 12us/step - loss: 340165479570.5458 - val_loss: 357764951965.6960 Epoch 10/200 18000/18000 [==============================] - 0s 10us/step - loss: 315699842136.2916 - val_loss: 329091613720.5760 Epoch 11/200 18000/18000 [==============================] - 0s 10us/step - loss: 289117304433.3227 - val_loss: 298578878136.3200 Epoch 12/200 18000/18000 [==============================] - 0s 11us/step - loss: 261380564058.1120 - val_loss: 267361173110.7840 Epoch 13/200 18000/18000 [==============================] - 0s 11us/step - loss: 233512805422.4213 - val_loss: 236796970795.0080 Epoch 14/200 18000/18000 [==============================] - 0s 11us/step - loss: 206621634811.2213 - val_loss: 207759685582.8480 Epoch 15/200 18000/18000 [==============================] - 0s 11us/step - loss: 181544216108.1458 - val_loss: 181255742947.3280 Epoch 16/200 18000/18000 [==============================] - 0s 12us/step - loss: 159017826516.9920 - val_loss: 158054828081.1520 Epoch 17/200 18000/18000 [==============================] - 0s 11us/step - loss: 139581889431.3244 - val_loss: 138607148466.1760 Epoch 18/200 18000/18000 [==============================] - 0s 12us/step - loss: 123407551306.8658 - val_loss: 122830300577.7920 Epoch 19/200 18000/18000 [==============================] - 0s 11us/step - loss: 110414201050.4533 - val_loss: 110407385219.0720 Epoch 20/200 18000/18000 [==============================] - 0s 11us/step - loss: 100342549796.1813 - val_loss: 101138505334.7840 Epoch 21/200 18000/18000 [==============================] - 0s 11us/step - loss: 92746195562.9511 - val_loss: 94260454621.1840 Epoch 22/200 18000/18000 [==============================] - 0s 12us/step - loss: 87142331467.5484 - val_loss: 89257073442.8160 Epoch 23/200 18000/18000 [==============================] - 0s 10us/step - loss: 83029246782.1227 - val_loss: 85649517051.9040 Epoch 24/200 18000/18000 [==============================] - 0s 10us/step - loss: 79974571289.2587 - val_loss: 82916333518.8480 Epoch 25/200 18000/18000 [==============================] - 0s 10us/step - loss: 77613710038.3573 - val_loss: 80772310892.5440 Epoch 26/200 18000/18000 [==============================] - 0s 10us/step - loss: 75758766536.9315 - val_loss: 79040771063.8080 Epoch 27/200 18000/18000 [==============================] - 0s 16us/step - loss: 74215229277.9805 - val_loss: 77595545501.6960 Epoch 28/200 18000/18000 [==============================] - 0s 16us/step - loss: 72905572177.2373 - val_loss: 76338272731.1360 Epoch 29/200 18000/18000 [==============================] - 0s 15us/step - loss: 71745211261.8382 - val_loss: 75183492169.7280 Epoch 30/200 18000/18000 [==============================] - 0s 12us/step - loss: 70697890440.0782 - val_loss: 74151740702.7200 Epoch 31/200 18000/18000 [==============================] - 0s 15us/step - loss: 69729018285.6249 - val_loss: 73179619459.0720 Epoch 32/200 18000/18000 [==============================] - 0s 16us/step - loss: 68816311542.6702 - val_loss: 72256881098.7520 Epoch 33/200 18000/18000 [==============================] - 0s 16us/step - loss: 67936579977.2160 - val_loss: 71377126752.2560 Epoch 34/200 18000/18000 [==============================] - 0s 13us/step - loss: 67097538195.9111 - val_loss: 70526461837.3120 Epoch 35/200 18000/18000 [==============================] - 0s 10us/step - loss: 66280199538.4604 - val_loss: 69706505519.1040 Epoch 36/200 18000/18000 [==============================] - 0s 9us/step - loss: 65474546091.8044 - val_loss: 68888741609.4720 Epoch 37/200 18000/18000 [==============================] - 0s 14us/step - loss: 64683688744.2773 - val_loss: 68096607354.8800 Epoch 38/200 18000/18000 [==============================] - 0s 15us/step - loss: 63904897171.4560 - val_loss: 67312825925.6320 Epoch 39/200 18000/18000 [==============================] - 0s 15us/step - loss: 63130683200.8533 - val_loss: 66542651277.3120 Epoch 40/200 18000/18000 [==============================] - 0s 15us/step - loss: 62353993003.4631 - val_loss: 65772004278.2720 Epoch 41/200 18000/18000 [==============================] - 0s 13us/step - loss: 61587946799.1040 - val_loss: 65005461667.8400 Epoch 42/200 18000/18000 [==============================] - 0s 13us/step - loss: 60821804999.5662 - val_loss: 64246054682.6240 Epoch 43/200 18000/18000 [==============================] - 0s 15us/step - loss: 60059479146.4960 - val_loss: 63493657821.1840 Epoch 44/200 18000/18000 [==============================] - 0s 13us/step - loss: 59302580489.7849 - val_loss: 62744275124.2240 Epoch 45/200 18000/18000 [==============================] - 0s 11us/step - loss: 58543664973.5964 - val_loss: 61995190353.9200 Epoch 46/200 18000/18000 [==============================] - 0s 14us/step - loss: 57782123597.3689 - val_loss: 61241564889.0880 Epoch 47/200 18000/18000 [==============================] - 0s 14us/step - loss: 57033753307.8187 - val_loss: 60478097522.6880 Epoch 48/200 18000/18000 [==============================] - 0s 16us/step - loss: 56258215957.8453 - val_loss: 59734967582.7200 Epoch 49/200 18000/18000 [==============================] - 0s 15us/step - loss: 55499806911.1467 - val_loss: 58974680743.9360 Epoch 50/200 18000/18000 [==============================] - 0s 12us/step - loss: 54732866202.2827 - val_loss: 58233620856.8320 Epoch 51/200 18000/18000 [==============================] - 0s 12us/step - loss: 53979515737.4293 - val_loss: 57494574628.8640 Epoch 52/200 18000/18000 [==============================] - 0s 12us/step - loss: 53222918094.8480 - val_loss: 56758398943.2320 Epoch 53/200 18000/18000 [==============================] - 0s 14us/step - loss: 52461172330.0409 - val_loss: 56031989923.8400 Epoch 54/200 18000/18000 [==============================] - 0s 11us/step - loss: 51707750733.1413 - val_loss: 55297092943.8720 Epoch 55/200 18000/18000 [==============================] - 0s 12us/step - loss: 50952434705.2942 - val_loss: 54574977581.0560 Epoch 56/200 18000/18000 [==============================] - 0s 12us/step - loss: 50216374794.4676 - val_loss: 53872021700.6080 Epoch 57/200 18000/18000 [==============================] - 0s 12us/step - loss: 49466069960.4764 - val_loss: 53165771784.1920 Epoch 58/200 18000/18000 [==============================] - 0s 12us/step - loss: 48736365170.2329 - val_loss: 52481645215.7440 Epoch 59/200 18000/18000 [==============================] - 0s 12us/step - loss: 48015811634.0622 - val_loss: 51818096754.6880 Epoch 60/200 18000/18000 [==============================] - 0s 12us/step - loss: 47307462479.4169 - val_loss: 51166277468.1600 Epoch 61/200 18000/18000 [==============================] - 0s 12us/step - loss: 46607229739.9182 - val_loss: 50528075153.4080 Epoch 62/200 18000/18000 [==============================] - 0s 11us/step - loss: 45922461060.6649 - val_loss: 49895826849.7920 Epoch 63/200 18000/18000 [==============================] - 0s 10us/step - loss: 45252787397.5182 - val_loss: 49297462722.5600 Epoch 64/200 18000/18000 [==============================] - 0s 10us/step - loss: 44604951643.9324 - val_loss: 48700301737.9840 ###Markdown In the future, consider standardizing outputs as well Regularize:* Heavily parameterized models like neural networks are prone to overfitting* Popular off-the-shelf tools exist to regularize models and prevent overfitting: - L2 regularization (weight decay) - Dropout - Batch normalization These tools come as standard Keras/TF layers!`model.add(keras.layers.Dropout(rate)``model.add(keras.layers.ActivityRegularization(l1=0.0, l2=0.0)``model.add(keras.layers.BatchNormalization())` Early stopping and model checkpointing: It's unlikely the last iteration is the best, and who knows how long until the thing is converged. Just grab the best validation error. ###Code # Set callback functions to early stop training and save the # best model so far from keras.callbacks import EarlyStopping, ModelCheckpoint callbacks = [EarlyStopping(monitor='val_loss', patience=2), ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)] model = nn_model(layers=[20,20,20]) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=400, callbacks=callbacks, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(f"Model score: {model_score}") plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/400 18000/18000 [==============================] - 1s 74us/step - loss: 416642251358.2080 - val_loss: 456230491127.8080 Epoch 00001: val_loss improved from inf to 456230491127.80798, saving model to best_model.h5 Epoch 2/400 18000/18000 [==============================] - 0s 12us/step - loss: 416175593648.5831 - val_loss: 455115510906.8800 Epoch 00002: val_loss improved from 456230491127.80798 to 455115510906.88000, saving model to best_model.h5 Epoch 3/400 18000/18000 [==============================] - 0s 11us/step - loss: 414236468168.4764 - val_loss: 451725259702.2720 Epoch 00003: val_loss improved from 455115510906.88000 to 451725259702.27197, saving model to best_model.h5 Epoch 4/400 18000/18000 [==============================] - 0s 12us/step - loss: 409652313427.5129 - val_loss: 444793102532.6080 Epoch 00004: val_loss improved from 451725259702.27197 to 444793102532.60797, saving model to best_model.h5 Epoch 5/400 18000/18000 [==============================] - 0s 11us/step - loss: 401502478940.3876 - val_loss: 433555929300.9920 Epoch 00005: val_loss improved from 444793102532.60797 to 433555929300.99200, saving model to best_model.h5 Epoch 6/400 18000/18000 [==============================] - 0s 14us/step - loss: 389127931691.0080 - val_loss: 417407007195.1360 Epoch 00006: val_loss improved from 433555929300.99200 to 417407007195.13599, saving model to best_model.h5 Epoch 7/400 18000/18000 [==============================] - 0s 14us/step - loss: 372354871401.5858 - val_loss: 396453596364.8000 Epoch 00007: val_loss improved from 417407007195.13599 to 396453596364.79999, saving model to best_model.h5 Epoch 8/400 18000/18000 [==============================] - 0s 11us/step - loss: 351261101246.2365 - val_loss: 370822052315.1360 Epoch 00008: val_loss improved from 396453596364.79999 to 370822052315.13599, saving model to best_model.h5 Epoch 9/400 18000/18000 [==============================] - 0s 13us/step - loss: 326316790761.2444 - val_loss: 341345543389.1840 Epoch 00009: val_loss improved from 370822052315.13599 to 341345543389.18402, saving model to best_model.h5 Epoch 10/400 18000/18000 [==============================] - 0s 15us/step - loss: 298425331511.7511 - val_loss: 309198200242.1760 Epoch 00010: val_loss improved from 341345543389.18402 to 309198200242.17603, saving model to best_model.h5 Epoch 11/400 18000/18000 [==============================] - 0s 14us/step - loss: 268705647005.2409 - val_loss: 275747260858.3680 Epoch 00011: val_loss improved from 309198200242.17603 to 275747260858.36798, saving model to best_model.h5 Epoch 12/400 18000/18000 [==============================] - 0s 11us/step - loss: 238421556796.5298 - val_loss: 242600971730.9440 Epoch 00012: val_loss improved from 275747260858.36798 to 242600971730.94400, saving model to best_model.h5 Epoch 13/400 18000/18000 [==============================] - 0s 11us/step - loss: 208827929067.5200 - val_loss: 210544567123.9680 Epoch 00013: val_loss improved from 242600971730.94400 to 210544567123.96799, saving model to best_model.h5 Epoch 14/400 18000/18000 [==============================] - 0s 11us/step - loss: 181250766609.5218 - val_loss: 181239822417.9200 Epoch 00014: val_loss improved from 210544567123.96799 to 181239822417.92001, saving model to best_model.h5 Epoch 15/400 18000/18000 [==============================] - 0s 11us/step - loss: 156734730928.1280 - val_loss: 155991138369.5360 Epoch 00015: val_loss improved from 181239822417.92001 to 155991138369.53601, saving model to best_model.h5 Epoch 16/400 18000/18000 [==============================] - ETA: 0s - loss: 138017311735.09 - 0s 11us/step - loss: 135798981525.5040 - val_loss: 134988053086.2080 Epoch 00016: val_loss improved from 155991138369.53601 to 134988053086.20799, saving model to best_model.h5 Epoch 17/400 18000/18000 [==============================] - 0s 15us/step - loss: 118836078000.3556 - val_loss: 118353070260.2240 Epoch 00017: val_loss improved from 134988053086.20799 to 118353070260.22400, saving model to best_model.h5 Epoch 18/400 18000/18000 [==============================] - 0s 12us/step - loss: 105603678346.3538 - val_loss: 105883129348.0960 Epoch 00018: val_loss improved from 118353070260.22400 to 105883129348.09599, saving model to best_model.h5 Epoch 19/400 18000/18000 [==============================] - 0s 10us/step - loss: 95745313909.4187 - val_loss: 96829833609.2160 Epoch 00019: val_loss improved from 105883129348.09599 to 96829833609.21600, saving model to best_model.h5 Epoch 20/400 18000/18000 [==============================] - 0s 11us/step - loss: 88618352621.7956 - val_loss: 90346775052.2880 Epoch 00020: val_loss improved from 96829833609.21600 to 90346775052.28799, saving model to best_model.h5 Epoch 21/400 18000/18000 [==============================] - 0s 10us/step - loss: 83567574355.5129 - val_loss: 85874045485.0560 Epoch 00021: val_loss improved from 90346775052.28799 to 85874045485.05600, saving model to best_model.h5 Epoch 22/400 18000/18000 [==============================] - 0s 10us/step - loss: 79998094813.8667 - val_loss: 82761349857.2800 Epoch 00022: val_loss improved from 85874045485.05600 to 82761349857.28000, saving model to best_model.h5 Epoch 23/400 18000/18000 [==============================] - 0s 12us/step - loss: 77425343874.8444 - val_loss: 80483269541.8880 Epoch 00023: val_loss improved from 82761349857.28000 to 80483269541.88800, saving model to best_model.h5 Epoch 24/400 18000/18000 [==============================] - 0s 11us/step - loss: 75462087511.6089 - val_loss: 78729282191.3600 Epoch 00024: val_loss improved from 80483269541.88800 to 78729282191.36000, saving model to best_model.h5 Epoch 25/400 18000/18000 [==============================] - 0s 10us/step - loss: 73870388468.8498 - val_loss: 77273078038.5280 Epoch 00025: val_loss improved from 78729282191.36000 to 77273078038.52800, saving model to best_model.h5 Epoch 26/400 18000/18000 [==============================] - 0s 10us/step - loss: 72516323071.3173 - val_loss: 75994380828.6720 Epoch 00026: val_loss improved from 77273078038.52800 to 75994380828.67200, saving model to best_model.h5 Epoch 27/400 18000/18000 [==============================] - 0s 11us/step - loss: 71323900251.7049 - val_loss: 74852082581.5040 Epoch 00027: val_loss improved from 75994380828.67200 to 74852082581.50400, saving model to best_model.h5 Epoch 28/400 18000/18000 [==============================] - 0s 11us/step - loss: 70227146804.7929 - val_loss: 73817158909.9520 Epoch 00028: val_loss improved from 74852082581.50400 to 73817158909.95200, saving model to best_model.h5 Epoch 29/400 18000/18000 [==============================] - 0s 11us/step - loss: 69211586836.7076 - val_loss: 72820976910.3360 Epoch 00029: val_loss improved from 73817158909.95200 to 72820976910.33600, saving model to best_model.h5 Epoch 30/400 18000/18000 [==============================] - 0s 10us/step - loss: 68253316495.5876 - val_loss: 71868724150.2720 Epoch 00030: val_loss improved from 72820976910.33600 to 71868724150.27200, saving model to best_model.h5 Epoch 31/400 18000/18000 [==============================] - 0s 11us/step - loss: 67342146957.7671 - val_loss: 70966434824.1920 Epoch 00031: val_loss improved from 71868724150.27200 to 70966434824.19200, saving model to best_model.h5 Epoch 32/400 18000/18000 [==============================] - 0s 10us/step - loss: 66443596828.2169 - val_loss: 70082538242.0480 Epoch 00032: val_loss improved from 70966434824.19200 to 70082538242.04800, saving model to best_model.h5 Epoch 33/400 18000/18000 [==============================] - 0s 11us/step - loss: 65572032122.4249 - val_loss: 69227643109.3760 Epoch 00033: val_loss improved from 70082538242.04800 to 69227643109.37601, saving model to best_model.h5 Epoch 34/400 18000/18000 [==============================] - 0s 10us/step - loss: 64735541992.5618 - val_loss: 68379734900.7360 Epoch 00034: val_loss improved from 69227643109.37601 to 68379734900.73600, saving model to best_model.h5 Epoch 35/400 18000/18000 [==============================] - 0s 10us/step - loss: 63888829455.4738 - val_loss: 67542714089.4720 ###Markdown TensorFlow & Keras - Basics of Deep Learning Most importantly... resourceshttps://www.tensorflow.org/api_docshttps://keras.io/https://www.tensorflow.org/tutorials/https://www.google.com TF overview* "End-to-end machine learning platform" - Not the only one! Check out PyTorch, Theano, Cognitive Toolkit. * Integrates with high-level APIs like Keras* Plays nice with Pandas* Makes deep learning *fast* and *easy* * *"easy" Tasks for TensorFlow:* Regression - Predict house prices - Predict drug metabolic rates - Predict stock trends * *this is super hard * Classification - Cat or dog? - Malignant or benign cancer from images ![](media/dr.png) Google AI Blog: Diabetic Retinopathy* Dimensionality reduction - Visualize high-dimensional data in 2 or 3-D space - Compress representations for successive ML* Generative models - Create new molecules with desirable properties - Artificially enhance image resolution ![](media/molecular_gan.png) Kadurin et al., 2017* Reinforcement learning - Can't beat your friends at chess? Make your computer do it* Much more... - Generic math - Probabilistic programming with TFP - Automatic differentiation - ... Let's Regress Imports! ###Code import numpy as np import pandas as pd ###Output _____no_output_____ ###Markdown Name a more iconic duo, I'll wait New imports -- TF and Keras ###Code import keras import tensorflow as tf ###Output Using TensorFlow backend. ###Markdown Check our versions for good measure -- these programs may have very different behavior version-to-version ###Code print(keras.__version__) print(tf.__version__) ###Output 2.2.4 1.13.1 ###Markdown Loading in housing data as with SKLearn ###Code data = pd.read_csv('kc_house_data.csv') data data["yr_built"].unique() column_selection = ["bedrooms","bathrooms","sqft_living","sqft_lot", "floors","condition","grade","sqft_above", "sqft_basement","sqft_living15","sqft_lot15", "lat", "long","yr_built","yr_renovated","waterfront"] selected_feature = np.array(data[column_selection]) price = np.array(data["price"]) selected_feature_train = selected_feature[:20000] price_train = price[:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] def score(y,y_pred): return np.mean(np.abs(y-y_pred)/y) model = keras.Sequential() input_len = len(column_selection) model.add(keras.layers.Dense(50, input_dim=input_len, activation='relu')) model.add(keras.layers.Dense(50, activation='relu')) model.add(keras.layers.Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128) preds = model.predict(selected_feature_test) score(preds, price_test) ###Output _____no_output_____ ###Markdown Like SKLearn, it's easy to train and evaluate simple models. ... but we should try to do better Practical Deep Learning -- What you need to know Train, Validation, Test: * Optimize parameters with Train (weights, biases) * Optimize hyperparameters with Validation (layer width & depth, activation functions, etc.) * Optimize NOTHING with Test ###Code # Split out a validation set for hyperparameter optimization selected_feature_train = selected_feature[:18000] price_train = price[:18000] selected_feature_val = selected_feature[18000:20000] price_val = price[18000:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] ###Output _____no_output_____ ###Markdown Try a hyperparameter optimization: Try three activation functions to use for dense layers in the neural network above. Save the model that achieves the best validation loss Hint: [activation functions](http://letmegooglethat.com/?q=keras+activation+functions) Hint: `model.fit` has argument "`validation_data`" which takes a tuple of features and targets Hint: Use `model.save("filename.h5")` to save a model locally. If you want to use it later, just call `keras.models.load_model("filename.h5")` ###Code # For easy looping, define neural network model as a function def nn_model(optimizer='adam', activation='relu', layers=[20,20], loss='mean_squared_error'): model = keras.Sequential() model.add(keras.layers.Dense(50, input_dim=input_len, activation=activ)) model.add(keras.layers.Dense(50, activation=activ)) model.add(keras.layers.Dense(1)) model.compile(loss='mean_absolute_error', optimizer='adam') return model best_score = 1000.0 # bad # loop over chosen activation functions, train, evaluate on validation for activ in ['sigmoid', 'tanh', 'relu']: model = nn_model(activation=activ) history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) if model_score < best_score: best_score = model_score best_activ = activ best_model = model best_train = history print(f"BEST ACTIVATION FUNCTION {best_activ} WITH SCORE {best_score}") best_model.save("awesome_model.h5") ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 61us/step - loss: 532974.1758 - val_loss: 557914.6710 Epoch 2/50 18000/18000 [==============================] - 0s 15us/step - loss: 532967.3181 - val_loss: 557908.9735 Epoch 3/50 18000/18000 [==============================] - 0s 13us/step - loss: 532962.1269 - val_loss: 557903.9525 Epoch 4/50 18000/18000 [==============================] - 0s 14us/step - loss: 532957.2894 - val_loss: 557899.4930 Epoch 5/50 18000/18000 [==============================] - 0s 13us/step - loss: 532952.5633 - val_loss: 557894.6470 Epoch 6/50 18000/18000 [==============================] - 0s 9us/step - loss: 532947.9042 - val_loss: 557889.8510 Epoch 7/50 18000/18000 [==============================] - 0s 11us/step - loss: 532943.2878 - val_loss: 557885.5170 Epoch 8/50 18000/18000 [==============================] - 0s 10us/step - loss: 532938.6823 - val_loss: 557880.8320 Epoch 9/50 18000/18000 [==============================] - 0s 10us/step - loss: 532934.1124 - val_loss: 557876.0225 Epoch 10/50 18000/18000 [==============================] - 0s 10us/step - loss: 532929.5258 - val_loss: 557871.6970 Epoch 11/50 18000/18000 [==============================] - 0s 14us/step - loss: 532924.9893 - val_loss: 557867.0405 Epoch 12/50 18000/18000 [==============================] - 0s 12us/step - loss: 532920.4284 - val_loss: 557862.6110 Epoch 13/50 18000/18000 [==============================] - 0s 12us/step - loss: 532915.8835 - val_loss: 557857.9335 Epoch 14/50 18000/18000 [==============================] - 0s 12us/step - loss: 532911.3458 - val_loss: 557853.6650 Epoch 15/50 18000/18000 [==============================] - 0s 14us/step - loss: 532906.8151 - val_loss: 557848.8690 Epoch 16/50 18000/18000 [==============================] - 0s 12us/step - loss: 532902.2797 - val_loss: 557844.4835 Epoch 17/50 18000/18000 [==============================] - 0s 10us/step - loss: 532897.7445 - val_loss: 557839.8085 Epoch 18/50 18000/18000 [==============================] - 0s 10us/step - loss: 532893.2282 - val_loss: 557835.5010 Epoch 19/50 18000/18000 [==============================] - 0s 10us/step - loss: 532888.7034 - val_loss: 557830.8360 Epoch 20/50 18000/18000 [==============================] - 0s 10us/step - loss: 532884.1843 - val_loss: 557826.4430 Epoch 21/50 18000/18000 [==============================] - 0s 12us/step - loss: 532879.6504 - val_loss: 557821.7920 Epoch 22/50 18000/18000 [==============================] - 0s 14us/step - loss: 532875.1483 - val_loss: 557817.4790 Epoch 23/50 18000/18000 [==============================] - 0s 13us/step - loss: 532870.6122 - val_loss: 557812.8160 Epoch 24/50 18000/18000 [==============================] - 0s 11us/step - loss: 532866.1056 - val_loss: 557808.3360 Epoch 25/50 18000/18000 [==============================] - 0s 10us/step - loss: 532861.5706 - val_loss: 557803.7380 Epoch 26/50 18000/18000 [==============================] - 0s 11us/step - loss: 532857.0776 - val_loss: 557799.1610 Epoch 27/50 18000/18000 [==============================] - 0s 10us/step - loss: 532852.5495 - val_loss: 557794.6775 Epoch 28/50 18000/18000 [==============================] - 0s 14us/step - loss: 532848.0404 - val_loss: 557789.9945 Epoch 29/50 18000/18000 [==============================] - 0s 15us/step - loss: 532843.5083 - val_loss: 557785.6990 Epoch 30/50 18000/18000 [==============================] - 0s 14us/step - loss: 532839.0229 - val_loss: 557781.0485 Epoch 31/50 18000/18000 [==============================] - 0s 12us/step - loss: 532834.4841 - val_loss: 557776.6410 Epoch 32/50 18000/18000 [==============================] - 0s 12us/step - loss: 532829.9850 - val_loss: 557771.9805 Epoch 33/50 18000/18000 [==============================] - 0s 12us/step - loss: 532825.4563 - val_loss: 557767.6930 Epoch 34/50 18000/18000 [==============================] - 0s 12us/step - loss: 532820.7999 - val_loss: 557762.6110 Epoch 35/50 18000/18000 [==============================] - 0s 10us/step - loss: 532815.6766 - val_loss: 557757.6930 Epoch 36/50 18000/18000 [==============================] - 0s 10us/step - loss: 532810.8327 - val_loss: 557752.8360 Epoch 37/50 18000/18000 [==============================] - 0s 9us/step - loss: 532806.0533 - val_loss: 557747.9525 Epoch 38/50 18000/18000 [==============================] - 0s 9us/step - loss: 532801.3039 - val_loss: 557743.0485 Epoch 39/50 18000/18000 [==============================] - 0s 9us/step - loss: 532796.0384 - val_loss: 557737.7920 Epoch 40/50 18000/18000 [==============================] - 0s 9us/step - loss: 532790.9252 - val_loss: 557732.8320 Epoch 41/50 18000/18000 [==============================] - 0s 9us/step - loss: 532785.9397 - val_loss: 557727.7980 Epoch 42/50 18000/18000 [==============================] - 0s 13us/step - loss: 532781.0243 - val_loss: 557722.8730 Epoch 43/50 18000/18000 [==============================] - 0s 15us/step - loss: 532776.1177 - val_loss: 557717.9525 Epoch 44/50 18000/18000 [==============================] - 0s 14us/step - loss: 532771.2528 - val_loss: 557713.3645 Epoch 45/50 18000/18000 [==============================] - 0s 11us/step - loss: 532766.3882 - val_loss: 557708.4470 Epoch 46/50 18000/18000 [==============================] - 0s 11us/step - loss: 532761.5342 - val_loss: 557703.6650 Epoch 47/50 18000/18000 [==============================] - 0s 14us/step - loss: 532756.7074 - val_loss: 557698.6670 Epoch 48/50 18000/18000 [==============================] - 0s 11us/step - loss: 532751.8659 - val_loss: 557693.7030 Epoch 49/50 18000/18000 [==============================] - 0s 14us/step - loss: 532746.5045 - val_loss: 557688.0105 Epoch 50/50 18000/18000 [==============================] - 0s 13us/step - loss: 532741.2496 - val_loss: 557683.0085 Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 66us/step - loss: 532968.8535 - val_loss: 557907.8785 Epoch 2/50 18000/18000 [==============================] - 0s 11us/step - loss: 532959.6811 - val_loss: 557900.1345 Epoch 3/50 18000/18000 [==============================] - 0s 12us/step - loss: 532952.1103 - val_loss: 557892.8225 Epoch 4/50 18000/18000 [==============================] - 0s 11us/step - loss: 532944.7126 - val_loss: 557885.5415 Epoch 5/50 18000/18000 [==============================] - 0s 11us/step - loss: 532937.3764 - val_loss: 557877.9805 Epoch 6/50 18000/18000 [==============================] - 0s 12us/step - loss: 532930.0783 - val_loss: 557870.8360 Epoch 7/50 18000/18000 [==============================] - 0s 12us/step - loss: 532922.8012 - val_loss: 557863.6790 Epoch 8/50 18000/18000 [==============================] - 0s 12us/step - loss: 532915.5595 - val_loss: 557856.4430 Epoch 9/50 18000/18000 [==============================] - 0s 12us/step - loss: 532908.3144 - val_loss: 557849.0125 Epoch 10/50 18000/18000 [==============================] - 0s 12us/step - loss: 532901.0774 - val_loss: 557841.7920 Epoch 11/50 18000/18000 [==============================] - 0s 12us/step - loss: 532893.8619 - val_loss: 557834.6450 Epoch 12/50 18000/18000 [==============================] - 0s 12us/step - loss: 532886.6362 - val_loss: 557827.5335 Epoch 13/50 18000/18000 [==============================] - 0s 11us/step - loss: 532879.4228 - val_loss: 557820.0150 Epoch 14/50 18000/18000 [==============================] - 0s 11us/step - loss: 532872.2118 - val_loss: 557812.9090 Epoch 15/50 18000/18000 [==============================] - 0s 10us/step - loss: 532864.9957 - val_loss: 557805.7820 Epoch 16/50 18000/18000 [==============================] - 0s 11us/step - loss: 532857.7976 - val_loss: 557798.6210 Epoch 17/50 18000/18000 [==============================] - 0s 16us/step - loss: 532850.5966 - val_loss: 557791.5170 Epoch 18/50 18000/18000 [==============================] - 0s 13us/step - loss: 532843.3934 - val_loss: 557783.9945 Epoch 19/50 18000/18000 [==============================] - 0s 14us/step - loss: 532836.1900 - val_loss: 557776.8790 Epoch 20/50 18000/18000 [==============================] - 0s 15us/step - loss: 532828.9844 - val_loss: 557769.7820 Epoch 21/50 18000/18000 [==============================] - 0s 12us/step - loss: 532821.7987 - val_loss: 557762.6210 Epoch 22/50 18000/18000 [==============================] - 0s 12us/step - loss: 532814.5922 - val_loss: 557755.5335 Epoch 23/50 18000/18000 [==============================] - 0s 12us/step - loss: 532807.4018 - val_loss: 557747.9945 Epoch 24/50 18000/18000 [==============================] - 0s 12us/step - loss: 532800.2038 - val_loss: 557740.9595 Epoch 25/50 18000/18000 [==============================] - 0s 9us/step - loss: 532793.0068 - val_loss: 557733.7920 Epoch 26/50 18000/18000 [==============================] - 0s 9us/step - loss: 532785.8116 - val_loss: 557726.6450 Epoch 27/50 18000/18000 [==============================] - 0s 9us/step - loss: 532778.6256 - val_loss: 557719.5335 Epoch 28/50 18000/18000 [==============================] - 0s 9us/step - loss: 532771.4330 - val_loss: 557712.0170 Epoch 29/50 18000/18000 [==============================] - 0s 9us/step - loss: 532764.2351 - val_loss: 557704.9855 Epoch 30/50 18000/18000 [==============================] - 0s 9us/step - loss: 532757.0397 - val_loss: 557697.7920 Epoch 31/50 18000/18000 [==============================] - 0s 10us/step - loss: 532749.8561 - val_loss: 557690.6450 Epoch 32/50 18000/18000 [==============================] - 0s 9us/step - loss: 532742.6587 - val_loss: 557683.5700 Epoch 33/50 18000/18000 [==============================] - 0s 9us/step - loss: 532735.4679 - val_loss: 557676.3360 Epoch 34/50 18000/18000 [==============================] - 0s 9us/step - loss: 532728.2726 - val_loss: 557668.9955 Epoch 35/50 18000/18000 [==============================] - 0s 9us/step - loss: 532721.0774 - val_loss: 557661.7980 Epoch 36/50 18000/18000 [==============================] - 0s 12us/step - loss: 532713.8920 - val_loss: 557654.6670 Epoch 37/50 18000/18000 [==============================] - 0s 12us/step - loss: 532706.6927 - val_loss: 557647.6650 Epoch 38/50 18000/18000 [==============================] - 0s 13us/step - loss: 532699.5059 - val_loss: 557640.4430 Epoch 39/50 18000/18000 [==============================] - 0s 12us/step - loss: 532692.3229 - val_loss: 557633.0485 Epoch 40/50 18000/18000 [==============================] - 0s 13us/step - loss: 532685.1196 - val_loss: 557625.8125 Epoch 41/50 18000/18000 [==============================] - 0s 12us/step - loss: 532677.9398 - val_loss: 557618.7840 Epoch 42/50 18000/18000 [==============================] - 0s 11us/step - loss: 532670.7418 - val_loss: 557611.6650 Epoch 43/50 18000/18000 [==============================] - 0s 12us/step - loss: 532663.5602 - val_loss: 557604.4430 Epoch 44/50 18000/18000 [==============================] - 0s 11us/step - loss: 532656.3681 - val_loss: 557597.0485 Epoch 45/50 18000/18000 [==============================] - 0s 12us/step - loss: 532649.1709 - val_loss: 557589.8230 Epoch 46/50 18000/18000 [==============================] - 0s 13us/step - loss: 532641.9852 - val_loss: 557582.8240 Epoch 47/50 18000/18000 [==============================] - 0s 13us/step - loss: 532634.7951 - val_loss: 557575.6850 Epoch 48/50 18000/18000 [==============================] - 0s 12us/step - loss: 532627.6101 - val_loss: 557568.4755 Epoch 49/50 18000/18000 [==============================] - 0s 12us/step - loss: 532620.4128 - val_loss: 557561.1510 Epoch 50/50 18000/18000 [==============================] - 0s 12us/step - loss: 532613.2224 - val_loss: 557553.9335 Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 69us/step - loss: 460302.7814 - val_loss: 389935.7043 Epoch 2/50 18000/18000 [==============================] - 0s 13us/step - loss: 288842.3789 - val_loss: 218617.1030 Epoch 3/50 18000/18000 [==============================] - 0s 12us/step - loss: 174847.2772 - val_loss: 176664.5083 Epoch 4/50 18000/18000 [==============================] - 0s 11us/step - loss: 165716.2985 - val_loss: 173251.2797 Epoch 5/50 18000/18000 [==============================] - 0s 12us/step - loss: 163249.9868 - val_loss: 172159.8714 Epoch 6/50 18000/18000 [==============================] - 0s 12us/step - loss: 161611.9619 - val_loss: 170750.6835 Epoch 7/50 18000/18000 [==============================] - 0s 12us/step - loss: 160407.1660 - val_loss: 169810.5179 Epoch 8/50 18000/18000 [==============================] - 0s 12us/step - loss: 159345.5089 - val_loss: 169291.1629 Epoch 9/50 18000/18000 [==============================] - 0s 12us/step - loss: 158630.9237 - val_loss: 169034.1908 Epoch 10/50 18000/18000 [==============================] - 0s 12us/step - loss: 158230.8990 - val_loss: 168649.8141 Epoch 11/50 18000/18000 [==============================] - 0s 12us/step - loss: 158015.7605 - val_loss: 169410.4244 Epoch 12/50 18000/18000 [==============================] - 0s 11us/step - loss: 157256.5905 - val_loss: 167973.3121 Epoch 13/50 18000/18000 [==============================] - 0s 12us/step - loss: 156975.5700 - val_loss: 167988.3602 Epoch 14/50 18000/18000 [==============================] - 0s 11us/step - loss: 156917.9833 - val_loss: 167261.6631 Epoch 15/50 18000/18000 [==============================] - 0s 11us/step - loss: 156874.7785 - val_loss: 169002.1360 Epoch 16/50 18000/18000 [==============================] - 0s 10us/step - loss: 156387.4673 - val_loss: 167151.6112 Epoch 17/50 18000/18000 [==============================] - 0s 10us/step - loss: 156141.9905 - val_loss: 168106.7525 Epoch 18/50 18000/18000 [==============================] - 0s 10us/step - loss: 155940.2835 - val_loss: 167468.5219 Epoch 19/50 18000/18000 [==============================] - 0s 10us/step - loss: 155684.3832 - val_loss: 167765.7778 Epoch 20/50 18000/18000 [==============================] - 0s 10us/step - loss: 155719.0916 - val_loss: 167466.6630 Epoch 21/50 18000/18000 [==============================] - 0s 10us/step - loss: 155545.2087 - val_loss: 166713.0641 Epoch 22/50 18000/18000 [==============================] - 0s 9us/step - loss: 155303.3075 - val_loss: 166852.0119 Epoch 23/50 18000/18000 [==============================] - 0s 11us/step - loss: 155179.0475 - val_loss: 166528.6830 Epoch 24/50 18000/18000 [==============================] - 0s 10us/step - loss: 155039.3024 - val_loss: 167060.9409 Epoch 25/50 18000/18000 [==============================] - 0s 10us/step - loss: 155022.6373 - val_loss: 166782.4909 Epoch 26/50 18000/18000 [==============================] - 0s 10us/step - loss: 154666.9540 - val_loss: 166420.0279 Epoch 27/50 18000/18000 [==============================] - 0s 10us/step - loss: 155009.4956 - val_loss: 166587.0267 Epoch 28/50 18000/18000 [==============================] - 0s 10us/step - loss: 154355.8122 - val_loss: 166219.7179 Epoch 29/50 18000/18000 [==============================] - 0s 10us/step - loss: 154413.5130 - val_loss: 166502.0960 Epoch 30/50 18000/18000 [==============================] - 0s 10us/step - loss: 154332.8766 - val_loss: 165990.8961 Epoch 31/50 18000/18000 [==============================] - 0s 10us/step - loss: 154091.2003 - val_loss: 167065.7801 Epoch 32/50 18000/18000 [==============================] - 0s 9us/step - loss: 154115.9829 - val_loss: 167038.7180 Epoch 33/50 18000/18000 [==============================] - 0s 10us/step - loss: 153895.3677 - val_loss: 166218.6487 Epoch 34/50 18000/18000 [==============================] - 0s 10us/step - loss: 154062.3794 - val_loss: 166869.0389 Epoch 35/50 18000/18000 [==============================] - 0s 10us/step - loss: 153830.0327 - val_loss: 165967.7117 Epoch 36/50 18000/18000 [==============================] - 0s 10us/step - loss: 153554.7361 - val_loss: 165572.1533 Epoch 37/50 18000/18000 [==============================] - 0s 10us/step - loss: 153472.7553 - val_loss: 165612.7610 Epoch 38/50 18000/18000 [==============================] - 0s 10us/step - loss: 153322.2003 - val_loss: 165850.4700 Epoch 39/50 18000/18000 [==============================] - 0s 10us/step - loss: 153419.3344 - val_loss: 166075.8007 Epoch 40/50 18000/18000 [==============================] - ETA: 0s - loss: 153015.61 - 0s 10us/step - loss: 153535.5968 - val_loss: 165214.1501 Epoch 41/50 18000/18000 [==============================] - 0s 10us/step - loss: 153215.4091 - val_loss: 165272.4703 Epoch 42/50 18000/18000 [==============================] - 0s 10us/step - loss: 153143.2716 - val_loss: 165429.7129 Epoch 43/50 18000/18000 [==============================] - 0s 10us/step - loss: 152930.2451 - val_loss: 164992.4201 Epoch 44/50 18000/18000 [==============================] - 0s 11us/step - loss: 153128.0189 - val_loss: 165270.4543 Epoch 45/50 18000/18000 [==============================] - 0s 9us/step - loss: 152793.8060 - val_loss: 166957.1629 Epoch 46/50 18000/18000 [==============================] - 0s 9us/step - loss: 152620.9163 - val_loss: 166043.3472 Epoch 47/50 18000/18000 [==============================] - 0s 9us/step - loss: 152873.9664 - val_loss: 165305.3497 Epoch 48/50 18000/18000 [==============================] - 0s 10us/step - loss: 152703.1435 - val_loss: 165293.5600 Epoch 49/50 18000/18000 [==============================] - 0s 9us/step - loss: 152441.4831 - val_loss: 164842.7197 Epoch 50/50 18000/18000 [==============================] - 0s 9us/step - loss: 152284.0022 - val_loss: 164795.3660 BEST ACTIVATION FUNCTION relu WITH SCORE 0.6314101076795888 ###Markdown Visualize your training: ###Code import matplotlib.pyplot as plt # plot loss during training def plot_loss(hist): %matplotlib inline plt.title('Training Curve') plt.plot(hist.history['loss'], label='train') plt.plot(hist.history['val_loss'], label='validation') plt.xlabel("Epochs") plt.ylabel("Mean squared error") plt.legend() plt.show() plot_loss(best_train) ###Output _____no_output_____ ###Markdown In the future, try better validation schemes like [k-fold cross validation](https://chrisalbon.com/deep_learning/keras/k-fold_cross-validating_neural_networks/), though 80/20 or 90/10 train/val like this works in a pinch Standardize your features:* Typically assumes normally distributed feature, shifting mean to 0 and standard deviation to 1* In theory does not matter for neural networks* In practice tends to matter for neural networks* Scale if using: - Logistic regression - Support vector machines - Perceptrons - Neural networks - Principle component analysis* Don't bother if using: - "Forest" methods - Naive Bayes ###Code from sklearn.preprocessing import StandardScaler # Instantiate StandardScaler in_scaler = StandardScaler() # Fit scaler to the training set and perform the transformation selected_feature_train = in_scaler.fit_transform(selected_feature_train) # Use the fitted scaler to transform validation and test features selected_feature_val = in_scaler.transform(selected_feature_val) selected_feature_test = in_scaler.transform(selected_feature_test) # Check appropriate scaling print(np.mean(selected_feature_train[:,0])) print(np.std(selected_feature_train[:,0])) print(np.mean(selected_feature_val[:,0])) print(np.std(selected_feature_val[:,0])) print(np.mean(selected_feature_test[:,0])) print(np.std(selected_feature_test[:,0])) model = nn_model() model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=200, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(model_score) plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/200 18000/18000 [==============================] - 1s 69us/step - loss: 416644724774.2293 - val_loss: 456240251273.2160 Epoch 2/200 18000/18000 [==============================] - 0s 14us/step - loss: 416219411047.3102 - val_loss: 455230525276.1600 Epoch 3/200 18000/18000 [==============================] - 0s 16us/step - loss: 414539373463.3245 - val_loss: 452292457267.2000 Epoch 4/200 18000/18000 [==============================] - 0s 14us/step - loss: 410731792826.3680 - val_loss: 446517339226.1120 Epoch 5/200 18000/18000 [==============================] - 0s 12us/step - loss: 403953550943.1182 - val_loss: 437057174896.6400 Epoch 6/200 18000/18000 [==============================] - 0s 11us/step - loss: 393657770544.6969 - val_loss: 423509280423.9360 Epoch 7/200 18000/18000 [==============================] - 0s 11us/step - loss: 379580761156.2667 - val_loss: 405581878001.6640 Epoch 8/200 18000/18000 [==============================] - 0s 11us/step - loss: 361658841912.6613 - val_loss: 383390637883.3920 Epoch 9/200 18000/18000 [==============================] - 0s 12us/step - loss: 340165479570.5458 - val_loss: 357764951965.6960 Epoch 10/200 18000/18000 [==============================] - 0s 10us/step - loss: 315699842136.2916 - val_loss: 329091613720.5760 Epoch 11/200 18000/18000 [==============================] - 0s 10us/step - loss: 289117304433.3227 - val_loss: 298578878136.3200 Epoch 12/200 18000/18000 [==============================] - 0s 11us/step - loss: 261380564058.1120 - val_loss: 267361173110.7840 Epoch 13/200 18000/18000 [==============================] - 0s 11us/step - loss: 233512805422.4213 - val_loss: 236796970795.0080 Epoch 14/200 18000/18000 [==============================] - 0s 11us/step - loss: 206621634811.2213 - val_loss: 207759685582.8480 Epoch 15/200 18000/18000 [==============================] - 0s 11us/step - loss: 181544216108.1458 - val_loss: 181255742947.3280 Epoch 16/200 18000/18000 [==============================] - 0s 12us/step - loss: 159017826516.9920 - val_loss: 158054828081.1520 Epoch 17/200 18000/18000 [==============================] - 0s 11us/step - loss: 139581889431.3244 - val_loss: 138607148466.1760 Epoch 18/200 18000/18000 [==============================] - 0s 12us/step - loss: 123407551306.8658 - val_loss: 122830300577.7920 Epoch 19/200 18000/18000 [==============================] - 0s 11us/step - loss: 110414201050.4533 - val_loss: 110407385219.0720 Epoch 20/200 18000/18000 [==============================] - 0s 11us/step - loss: 100342549796.1813 - val_loss: 101138505334.7840 Epoch 21/200 18000/18000 [==============================] - 0s 11us/step - loss: 92746195562.9511 - val_loss: 94260454621.1840 Epoch 22/200 18000/18000 [==============================] - 0s 12us/step - loss: 87142331467.5484 - val_loss: 89257073442.8160 Epoch 23/200 18000/18000 [==============================] - 0s 10us/step - loss: 83029246782.1227 - val_loss: 85649517051.9040 Epoch 24/200 18000/18000 [==============================] - 0s 10us/step - loss: 79974571289.2587 - val_loss: 82916333518.8480 Epoch 25/200 18000/18000 [==============================] - 0s 10us/step - loss: 77613710038.3573 - val_loss: 80772310892.5440 Epoch 26/200 18000/18000 [==============================] - 0s 10us/step - loss: 75758766536.9315 - val_loss: 79040771063.8080 Epoch 27/200 18000/18000 [==============================] - 0s 16us/step - loss: 74215229277.9805 - val_loss: 77595545501.6960 Epoch 28/200 18000/18000 [==============================] - 0s 16us/step - loss: 72905572177.2373 - val_loss: 76338272731.1360 Epoch 29/200 18000/18000 [==============================] - 0s 15us/step - loss: 71745211261.8382 - val_loss: 75183492169.7280 Epoch 30/200 18000/18000 [==============================] - 0s 12us/step - loss: 70697890440.0782 - val_loss: 74151740702.7200 Epoch 31/200 18000/18000 [==============================] - 0s 15us/step - loss: 69729018285.6249 - val_loss: 73179619459.0720 Epoch 32/200 18000/18000 [==============================] - 0s 16us/step - loss: 68816311542.6702 - val_loss: 72256881098.7520 Epoch 33/200 18000/18000 [==============================] - 0s 16us/step - loss: 67936579977.2160 - val_loss: 71377126752.2560 Epoch 34/200 18000/18000 [==============================] - 0s 13us/step - loss: 67097538195.9111 - val_loss: 70526461837.3120 Epoch 35/200 18000/18000 [==============================] - 0s 10us/step - loss: 66280199538.4604 - val_loss: 69706505519.1040 Epoch 36/200 18000/18000 [==============================] - 0s 9us/step - loss: 65474546091.8044 - val_loss: 68888741609.4720 Epoch 37/200 18000/18000 [==============================] - 0s 14us/step - loss: 64683688744.2773 - val_loss: 68096607354.8800 Epoch 38/200 18000/18000 [==============================] - 0s 15us/step - loss: 63904897171.4560 - val_loss: 67312825925.6320 Epoch 39/200 18000/18000 [==============================] - 0s 15us/step - loss: 63130683200.8533 - val_loss: 66542651277.3120 Epoch 40/200 18000/18000 [==============================] - 0s 15us/step - loss: 62353993003.4631 - val_loss: 65772004278.2720 Epoch 41/200 18000/18000 [==============================] - 0s 13us/step - loss: 61587946799.1040 - val_loss: 65005461667.8400 Epoch 42/200 18000/18000 [==============================] - 0s 13us/step - loss: 60821804999.5662 - val_loss: 64246054682.6240 Epoch 43/200 18000/18000 [==============================] - 0s 15us/step - loss: 60059479146.4960 - val_loss: 63493657821.1840 Epoch 44/200 18000/18000 [==============================] - 0s 13us/step - loss: 59302580489.7849 - val_loss: 62744275124.2240 Epoch 45/200 18000/18000 [==============================] - 0s 11us/step - loss: 58543664973.5964 - val_loss: 61995190353.9200 Epoch 46/200 18000/18000 [==============================] - 0s 14us/step - loss: 57782123597.3689 - val_loss: 61241564889.0880 Epoch 47/200 18000/18000 [==============================] - 0s 14us/step - loss: 57033753307.8187 - val_loss: 60478097522.6880 Epoch 48/200 18000/18000 [==============================] - 0s 16us/step - loss: 56258215957.8453 - val_loss: 59734967582.7200 Epoch 49/200 18000/18000 [==============================] - 0s 15us/step - loss: 55499806911.1467 - val_loss: 58974680743.9360 Epoch 50/200 18000/18000 [==============================] - 0s 12us/step - loss: 54732866202.2827 - val_loss: 58233620856.8320 Epoch 51/200 18000/18000 [==============================] - 0s 12us/step - loss: 53979515737.4293 - val_loss: 57494574628.8640 Epoch 52/200 18000/18000 [==============================] - 0s 12us/step - loss: 53222918094.8480 - val_loss: 56758398943.2320 Epoch 53/200 18000/18000 [==============================] - 0s 14us/step - loss: 52461172330.0409 - val_loss: 56031989923.8400 Epoch 54/200 18000/18000 [==============================] - 0s 11us/step - loss: 51707750733.1413 - val_loss: 55297092943.8720 Epoch 55/200 18000/18000 [==============================] - 0s 12us/step - loss: 50952434705.2942 - val_loss: 54574977581.0560 Epoch 56/200 18000/18000 [==============================] - 0s 12us/step - loss: 50216374794.4676 - val_loss: 53872021700.6080 Epoch 57/200 18000/18000 [==============================] - 0s 12us/step - loss: 49466069960.4764 - val_loss: 53165771784.1920 Epoch 58/200 18000/18000 [==============================] - 0s 12us/step - loss: 48736365170.2329 - val_loss: 52481645215.7440 Epoch 59/200 18000/18000 [==============================] - 0s 12us/step - loss: 48015811634.0622 - val_loss: 51818096754.6880 Epoch 60/200 18000/18000 [==============================] - 0s 12us/step - loss: 47307462479.4169 - val_loss: 51166277468.1600 Epoch 61/200 18000/18000 [==============================] - 0s 12us/step - loss: 46607229739.9182 - val_loss: 50528075153.4080 Epoch 62/200 18000/18000 [==============================] - 0s 11us/step - loss: 45922461060.6649 - val_loss: 49895826849.7920 Epoch 63/200 18000/18000 [==============================] - 0s 10us/step - loss: 45252787397.5182 - val_loss: 49297462722.5600 Epoch 64/200 18000/18000 [==============================] - 0s 10us/step - loss: 44604951643.9324 - val_loss: 48700301737.9840 Epoch 65/200 18000/18000 [==============================] - 0s 10us/step - loss: 43967003383.1253 - val_loss: 48120822792.1920 Epoch 66/200 18000/18000 [==============================] - ETA: 0s - loss: 43677351207.822 - 0s 10us/step - loss: 43358731547.0791 - val_loss: 47560437465.0880 Epoch 67/200 18000/18000 [==============================] - 0s 10us/step - loss: 42763919989.8738 - val_loss: 47031392337.9200 Epoch 68/200 18000/18000 [==============================] - 0s 12us/step - loss: 42186531049.0169 - val_loss: 46524311076.8640 Epoch 69/200 18000/18000 [==============================] - 0s 12us/step - loss: 41641749632.3413 - val_loss: 46035936804.8640 Epoch 70/200 18000/18000 [==============================] - 0s 12us/step - loss: 41131274274.5884 - val_loss: 45590292496.3840 Epoch 71/200 18000/18000 [==============================] - 0s 13us/step - loss: 40640540990.5778 - val_loss: 45200045047.8080 Epoch 72/200 18000/18000 [==============================] - 0s 13us/step - loss: 40185976102.0018 - val_loss: 44812461441.0240 Epoch 73/200 18000/18000 [==============================] - 0s 10us/step - loss: 39770515632.5831 - val_loss: 44455844544.5120 Epoch 74/200 18000/18000 [==============================] - 0s 11us/step - loss: 39383302529.9342 - val_loss: 44143539847.1680 Epoch 75/200 18000/18000 [==============================] - 0s 11us/step - loss: 39036987379.2569 - val_loss: 43853232668.6720 Epoch 76/200 18000/18000 [==============================] - 0s 13us/step - loss: 38714754087.1396 - val_loss: 43603367395.3280 Epoch 77/200 18000/18000 [==============================] - 0s 13us/step - loss: 38427186877.7813 - val_loss: 43368991490.0480 Epoch 78/200 18000/18000 [==============================] - 0s 12us/step - loss: 38160408874.5529 - val_loss: 43161227362.3040 Epoch 79/200 18000/18000 [==============================] - 0s 11us/step - loss: 37924018501.8596 - val_loss: 42971564965.8880 Epoch 80/200 18000/18000 [==============================] - 0s 10us/step - loss: 37706286556.0462 - val_loss: 42789223038.9760 Epoch 81/200 18000/18000 [==============================] - 0s 12us/step - loss: 37521690509.3120 - val_loss: 42630109265.9200 Epoch 82/200 18000/18000 [==============================] - 0s 11us/step - loss: 37323107128.6613 - val_loss: 42519357882.3680 Epoch 83/200 18000/18000 [==============================] - 0s 15us/step - loss: 37151890132.5369 - val_loss: 42389031780.3520 Epoch 84/200 18000/18000 [==============================] - 0s 16us/step - loss: 36994491953.6071 - val_loss: 42256742350.8480 Epoch 85/200 18000/18000 [==============================] - 0s 13us/step - loss: 36835559378.4889 - val_loss: 42120880259.0720 Epoch 86/200 18000/18000 [==============================] - 0s 10us/step - loss: 36704747214.1653 - val_loss: 42013906468.8640 Epoch 87/200 18000/18000 [==============================] - 0s 10us/step - loss: 36570395162.8516 - val_loss: 41910531948.5440 Epoch 88/200 18000/18000 [==============================] - 0s 11us/step - loss: 36440781664.7111 - val_loss: 41807704260.6080 Epoch 89/200 18000/18000 [==============================] - 0s 13us/step - loss: 36317897958.2862 - val_loss: 41708020006.9120 Epoch 90/200 18000/18000 [==============================] - 0s 14us/step - loss: 36208089410.2187 - val_loss: 41619933167.6160 Epoch 91/200 18000/18000 [==============================] - 0s 11us/step - loss: 36095894862.0516 - val_loss: 41511169458.1760 Epoch 92/200 18000/18000 [==============================] - 0s 12us/step - loss: 35994212051.6267 - val_loss: 41430843686.9120 Epoch 93/200 18000/18000 [==============================] - 0s 11us/step - loss: 35886885553.9484 - val_loss: 41361790697.4720 Epoch 94/200 18000/18000 [==============================] - 0s 11us/step - loss: 35793174910.2933 - val_loss: 41256490467.3280 Epoch 95/200 18000/18000 [==============================] - 0s 12us/step - loss: 35695162993.3227 - val_loss: 41184487899.1360 Epoch 96/200 18000/18000 [==============================] - 0s 12us/step - loss: 35602815862.5564 - val_loss: 41073298571.2640 Epoch 97/200 18000/18000 [==============================] - 0s 12us/step - loss: 35513192074.8089 - val_loss: 40987678146.5600 Epoch 98/200 18000/18000 [==============================] - 0s 11us/step - loss: 35420576619.6338 - val_loss: 40920484282.3680 Epoch 99/200 18000/18000 [==============================] - 0s 11us/step - loss: 35349878811.3067 - val_loss: 40858422837.2480 Epoch 100/200 18000/18000 [==============================] - 0s 12us/step - loss: 35263009479.7938 - val_loss: 40782295302.1440 Epoch 101/200 18000/18000 [==============================] - 0s 12us/step - loss: 35188018318.9049 - val_loss: 40695475666.9440 Epoch 102/200 18000/18000 [==============================] - 0s 12us/step - loss: 35094649547.4347 - val_loss: 40589422854.1440 Epoch 103/200 18000/18000 [==============================] - 0s 12us/step - loss: 35030873797.0631 - val_loss: 40532539834.3680 Epoch 104/200 18000/18000 [==============================] - 0s 12us/step - loss: 34941361824.6542 - val_loss: 40445707354.1120 Epoch 105/200 18000/18000 [==============================] - 0s 12us/step - loss: 34875362002.7164 - val_loss: 40372683702.2720 Epoch 106/200 18000/18000 [==============================] - 0s 12us/step - loss: 34801925383.0542 - val_loss: 40293627822.0800 Epoch 107/200 18000/18000 [==============================] - 0s 12us/step - loss: 34740944914.2044 - val_loss: 40232055275.5200 Epoch 108/200 18000/18000 [==============================] - 0s 12us/step - loss: 34671356710.4569 - val_loss: 40199075725.3120 Epoch 109/200 18000/18000 [==============================] - 0s 12us/step - loss: 34603361945.3724 - val_loss: 40129020493.8240 Epoch 110/200 18000/18000 [==============================] - 0s 12us/step - loss: 34540628758.9831 - val_loss: 40064682721.2800 Epoch 111/200 18000/18000 [==============================] - 0s 12us/step - loss: 34478302221.6533 - val_loss: 39999905398.7840 Epoch 112/200 18000/18000 [==============================] - 0s 12us/step - loss: 34424151026.3467 - val_loss: 39946603134.9760 Epoch 113/200 18000/18000 [==============================] - 0s 11us/step - loss: 34350522548.2240 - val_loss: 39869459628.0320 Epoch 114/200 18000/18000 [==============================] - 0s 11us/step - loss: 34293735635.1716 - val_loss: 39808236847.1040 Epoch 115/200 18000/18000 [==============================] - 0s 11us/step - loss: 34235366901.5324 - val_loss: 39718557646.8480 Epoch 116/200 18000/18000 [==============================] - 0s 11us/step - loss: 34184416892.2453 - val_loss: 39678572363.7760 Epoch 117/200 18000/18000 [==============================] - 0s 12us/step - loss: 34140378854.7413 - val_loss: 39588100669.4400 Epoch 118/200 18000/18000 [==============================] - 0s 13us/step - loss: 34081494005.9876 - val_loss: 39570870108.1600 Epoch 119/200 18000/18000 [==============================] - 0s 12us/step - loss: 34034455769.5431 - val_loss: 39493161254.9120 Epoch 120/200 18000/18000 [==============================] - 0s 12us/step - loss: 33986731443.9964 - val_loss: 39435902451.7120 Epoch 121/200 18000/18000 [==============================] - 0s 12us/step - loss: 33928106806.8409 - val_loss: 39386770636.8000 Epoch 122/200 18000/18000 [==============================] - 0s 13us/step - loss: 33890774086.0871 - val_loss: 39336803696.6400 Epoch 123/200 18000/18000 [==============================] - 0s 12us/step - loss: 33837027029.4471 - val_loss: 39311237513.2160 Epoch 124/200 18000/18000 [==============================] - 0s 12us/step - loss: 33790312047.5022 - val_loss: 39268650778.6240 Epoch 125/200 18000/18000 [==============================] - 0s 11us/step - loss: 33744856614.6844 - val_loss: 39220975042.5600 Epoch 126/200 18000/18000 [==============================] - 0s 10us/step - loss: 33708920902.9973 - val_loss: 39168369328.1280 Epoch 127/200 18000/18000 [==============================] - 0s 10us/step - loss: 33664118831.3316 - val_loss: 39107614572.5440 Epoch 128/200 18000/18000 [==============================] - 0s 11us/step - loss: 33618047434.7520 - val_loss: 39077930663.9360 Epoch 129/200 18000/18000 [==============================] - 0s 13us/step - loss: 33579016670.7769 - val_loss: 39000030150.6560 Epoch 130/200 18000/18000 [==============================] - 0s 12us/step - loss: 33535163312.8107 - val_loss: 38973689102.3360 Epoch 131/200 18000/18000 [==============================] - 0s 12us/step - loss: 33492335205.4898 - val_loss: 38930244927.4880 Epoch 132/200 18000/18000 [==============================] - 0s 12us/step - loss: 33455017304.9742 - val_loss: 38909504585.7280 Epoch 133/200 18000/18000 [==============================] - 0s 12us/step - loss: 33410613950.6916 - val_loss: 38849598160.8960 Epoch 134/200 18000/18000 [==============================] - 0s 12us/step - loss: 33375177029.8596 - val_loss: 38805699493.8880 Epoch 135/200 18000/18000 [==============================] - 0s 13us/step - loss: 33335135123.6836 - val_loss: 38765521666.0480 Epoch 136/200 18000/18000 [==============================] - 0s 13us/step - loss: 33302001097.8418 - val_loss: 38731508088.8320 Epoch 137/200 18000/18000 [==============================] - 0s 13us/step - loss: 33272129013.5324 - val_loss: 38691386785.7920 Epoch 138/200 18000/18000 [==============================] - 0s 12us/step - loss: 33235998062.8196 - val_loss: 38653477912.5760 Epoch 139/200 18000/18000 [==============================] - 0s 13us/step - loss: 33192606025.5004 - val_loss: 38581751644.1600 Epoch 140/200 18000/18000 [==============================] - 0s 12us/step - loss: 33160514983.2533 - val_loss: 38569467052.0320 Epoch 141/200 18000/18000 [==============================] - 0s 11us/step - loss: 33130229130.1262 - val_loss: 38560806535.1680 Epoch 142/200 18000/18000 [==============================] - 0s 13us/step - loss: 33097339705.5716 - val_loss: 38533460557.8240 Epoch 143/200 18000/18000 [==============================] - 0s 12us/step - loss: 33071230875.8756 - val_loss: 38499154231.2960 Epoch 144/200 18000/18000 [==============================] - 0s 12us/step - loss: 33035680088.0640 - val_loss: 38425215172.6080 Epoch 145/200 18000/18000 [==============================] - 0s 12us/step - loss: 33002553438.6631 - val_loss: 38392848777.2160 Epoch 146/200 18000/18000 [==============================] - 0s 12us/step - loss: 32988974998.4142 - val_loss: 38361419939.8400 Epoch 147/200 18000/18000 [==============================] - 0s 12us/step - loss: 32941554934.6702 - val_loss: 38362186940.4160 Epoch 148/200 18000/18000 [==============================] - 0s 13us/step - loss: 32918950730.8658 - val_loss: 38352234151.9360 Epoch 149/200 18000/18000 [==============================] - 0s 12us/step - loss: 32880421586.7164 - val_loss: 38287552675.8400 Epoch 150/200 18000/18000 [==============================] - 0s 12us/step - loss: 32854975978.6098 - val_loss: 38253683376.1280 Epoch 151/200 18000/18000 [==============================] - 0s 13us/step - loss: 32840697178.7947 - val_loss: 38210115403.7760 Epoch 152/200 18000/18000 [==============================] - 0s 13us/step - loss: 32803013911.4382 - val_loss: 38197209858.0480 Epoch 153/200 18000/18000 [==============================] - 0s 13us/step - loss: 32776528858.6809 - val_loss: 38171726905.3440 Epoch 154/200 18000/18000 [==============================] - 0s 14us/step - loss: 32748213445.5182 - val_loss: 38138094190.5920 Epoch 155/200 18000/18000 [==============================] - 0s 13us/step - loss: 32722838243.1004 - val_loss: 38122217734.1440 Epoch 156/200 18000/18000 [==============================] - 0s 13us/step - loss: 32695236014.5351 - val_loss: 38068723449.8560 Epoch 157/200 18000/18000 [==============================] - 0s 13us/step - loss: 32670382154.6382 - val_loss: 38065923162.1120 Epoch 158/200 18000/18000 [==============================] - 0s 13us/step - loss: 32645579341.8240 - val_loss: 37994074636.2880 Epoch 159/200 18000/18000 [==============================] - 0s 13us/step - loss: 32624472003.9253 - val_loss: 37982525947.9040 Epoch 160/200 18000/18000 [==============================] - 0s 12us/step - loss: 32597628986.2542 - val_loss: 37980290088.9600 Epoch 161/200 18000/18000 [==============================] - 0s 12us/step - loss: 32567088693.2480 - val_loss: 37934505525.2480 Epoch 162/200 18000/18000 [==============================] - 0s 13us/step - loss: 32546711400.9031 - val_loss: 37949333405.6960 Epoch 163/200 18000/18000 [==============================] - 0s 13us/step - loss: 32516446144.2844 - val_loss: 37929517776.8960 Epoch 164/200 18000/18000 [==============================] - 0s 13us/step - loss: 32502933589.5609 - val_loss: 37870684536.8320 Epoch 165/200 18000/18000 [==============================] - 0s 12us/step - loss: 32481144615.3671 - val_loss: 37861278351.3600 Epoch 166/200 18000/18000 [==============================] - 0s 13us/step - loss: 32453420915.8258 - val_loss: 37832754200.5760 Epoch 167/200 18000/18000 [==============================] - 0s 14us/step - loss: 32430444946.3182 - val_loss: 37816830328.8320 Epoch 168/200 18000/18000 [==============================] - 0s 13us/step - loss: 32408308675.0151 - val_loss: 37782546350.0800 Epoch 169/200 18000/18000 [==============================] - 0s 13us/step - loss: 32385081331.2569 - val_loss: 37786984120.3200 Epoch 170/200 18000/18000 [==============================] - 0s 13us/step - loss: 32365805653.5609 - val_loss: 37741922549.7600 Epoch 171/200 18000/18000 [==============================] - 0s 13us/step - loss: 32349541994.0409 - val_loss: 37729805271.0400 Epoch 172/200 18000/18000 [==============================] - 0s 13us/step - loss: 32322018574.3360 - val_loss: 37718481600.5120 Epoch 173/200 18000/18000 [==============================] - 0s 14us/step - loss: 32296829794.5316 - val_loss: 37701888802.8160 Epoch 174/200 18000/18000 [==============================] - 0s 15us/step - loss: 32277643309.5111 - val_loss: 37663694651.3920 Epoch 175/200 18000/18000 [==============================] - 0s 13us/step - loss: 32269726715.4489 - val_loss: 37674866638.8480 Epoch 176/200 18000/18000 [==============================] - 0s 13us/step - loss: 32233154066.6596 - val_loss: 37626876854.2720 Epoch 177/200 18000/18000 [==============================] - 0s 13us/step - loss: 32213190499.4418 - val_loss: 37591130505.2160 Epoch 178/200 18000/18000 [==============================] - 0s 13us/step - loss: 32196344607.1751 - val_loss: 37617813454.8480 Epoch 179/200 18000/18000 [==============================] - 0s 13us/step - loss: 32168589903.6444 - val_loss: 37551676588.0320 Epoch 180/200 18000/18000 [==============================] - 0s 13us/step - loss: 32146972701.1271 - val_loss: 37532002385.9200 Epoch 181/200 18000/18000 [==============================] - 0s 13us/step - loss: 32130249115.4204 - val_loss: 37544678719.4880 Epoch 182/200 18000/18000 [==============================] - 0s 13us/step - loss: 32112177372.2738 - val_loss: 37497368084.4800 Epoch 183/200 18000/18000 [==============================] - 0s 13us/step - loss: 32091575828.4800 - val_loss: 37469483335.6800 Epoch 184/200 18000/18000 [==============================] - 0s 13us/step - loss: 32067664347.1360 - val_loss: 37462552870.9120 Epoch 185/200 18000/18000 [==============================] - 0s 15us/step - loss: 32044462150.9973 - val_loss: 37429701935.1040 Epoch 186/200 18000/18000 [==============================] - 0s 15us/step - loss: 32034467963.7902 - val_loss: 37426921144.3200 Epoch 187/200 18000/18000 [==============================] - 0s 14us/step - loss: 32019949296.7538 - val_loss: 37409924055.0400 Epoch 188/200 18000/18000 [==============================] - 0s 14us/step - loss: 31997113823.6871 - val_loss: 37370300858.3680 Epoch 189/200 18000/18000 [==============================] - 0s 13us/step - loss: 31977750718.2364 - val_loss: 37362002427.9040 Epoch 190/200 18000/18000 [==============================] - 0s 13us/step - loss: 31954116509.6960 - val_loss: 37339767603.2000 Epoch 191/200 18000/18000 [==============================] - 0s 13us/step - loss: 31939885838.7911 - val_loss: 37316951769.0880 Epoch 192/200 18000/18000 [==============================] - 0s 13us/step - loss: 31924599555.8684 - val_loss: 37286352683.0080 Epoch 193/200 18000/18000 [==============================] - 0s 13us/step - loss: 31895322201.6569 - val_loss: 37303470850.0480 Epoch 194/200 18000/18000 [==============================] - 0s 13us/step - loss: 31877078220.8000 - val_loss: 37286238158.8480 Epoch 195/200 18000/18000 [==============================] - 0s 13us/step - loss: 31859688972.2880 - val_loss: 37263179186.1760 Epoch 196/200 18000/18000 [==============================] - 0s 12us/step - loss: 31845225469.2693 - val_loss: 37228672647.1680 Epoch 197/200 18000/18000 [==============================] - 0s 13us/step - loss: 31821257150.0089 - val_loss: 37222641401.8560 Epoch 198/200 18000/18000 [==============================] - 0s 12us/step - loss: 31811658725.6036 - val_loss: 37176441765.8880 Epoch 199/200 18000/18000 [==============================] - 0s 12us/step - loss: 31781443567.6160 - val_loss: 37216355942.4000 Epoch 200/200 18000/18000 [==============================] - 0s 13us/step - loss: 31768730311.7938 - val_loss: 37173094449.1520 0.6651870143377775 ###Markdown In the future, consider standardizing outputs as well Regularize:* Heavily parameterized models like neural networks are prone to overfitting* Popular off-the-shelf tools exist to regularize models and prevent overfitting: - L2 regularization (weight decay) - Dropout - Batch normalization These tools come as standard Keras/TF layers!`model.add(keras.layers.Dropout(rate)``model.add(keras.layers.ActivityRegularization(l1=0.0, l2=0.0)``model.add(keras.layers.BatchNormalization())` Early stopping and model checkpointing: It's unlikely the last iteration is the best, and who knows how long until the thing is converged. Just grab the best validation error. ###Code # Set callback functions to early stop training and save the # best model so far from keras.callbacks import EarlyStopping, ModelCheckpoint callbacks = [EarlyStopping(monitor='val_loss', patience=2), ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)] model = nn_model(layers=[20,20,20]) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=400, callbacks=callbacks, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(f"Model score: {model_score}") plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/400 18000/18000 [==============================] - 1s 74us/step - loss: 416642251358.2080 - val_loss: 456230491127.8080 Epoch 00001: val_loss improved from inf to 456230491127.80798, saving model to best_model.h5 Epoch 2/400 18000/18000 [==============================] - 0s 12us/step - loss: 416175593648.5831 - val_loss: 455115510906.8800 Epoch 00002: val_loss improved from 456230491127.80798 to 455115510906.88000, saving model to best_model.h5 Epoch 3/400 18000/18000 [==============================] - 0s 11us/step - loss: 414236468168.4764 - val_loss: 451725259702.2720 Epoch 00003: val_loss improved from 455115510906.88000 to 451725259702.27197, saving model to best_model.h5 Epoch 4/400 18000/18000 [==============================] - 0s 12us/step - loss: 409652313427.5129 - val_loss: 444793102532.6080 Epoch 00004: val_loss improved from 451725259702.27197 to 444793102532.60797, saving model to best_model.h5 Epoch 5/400 18000/18000 [==============================] - 0s 11us/step - loss: 401502478940.3876 - val_loss: 433555929300.9920 Epoch 00005: val_loss improved from 444793102532.60797 to 433555929300.99200, saving model to best_model.h5 Epoch 6/400 18000/18000 [==============================] - 0s 14us/step - loss: 389127931691.0080 - val_loss: 417407007195.1360 Epoch 00006: val_loss improved from 433555929300.99200 to 417407007195.13599, saving model to best_model.h5 Epoch 7/400 18000/18000 [==============================] - 0s 14us/step - loss: 372354871401.5858 - val_loss: 396453596364.8000 Epoch 00007: val_loss improved from 417407007195.13599 to 396453596364.79999, saving model to best_model.h5 Epoch 8/400 18000/18000 [==============================] - 0s 11us/step - loss: 351261101246.2365 - val_loss: 370822052315.1360 Epoch 00008: val_loss improved from 396453596364.79999 to 370822052315.13599, saving model to best_model.h5 Epoch 9/400 18000/18000 [==============================] - 0s 13us/step - loss: 326316790761.2444 - val_loss: 341345543389.1840 Epoch 00009: val_loss improved from 370822052315.13599 to 341345543389.18402, saving model to best_model.h5 Epoch 10/400 18000/18000 [==============================] - 0s 15us/step - loss: 298425331511.7511 - val_loss: 309198200242.1760 Epoch 00010: val_loss improved from 341345543389.18402 to 309198200242.17603, saving model to best_model.h5 Epoch 11/400 18000/18000 [==============================] - 0s 14us/step - loss: 268705647005.2409 - val_loss: 275747260858.3680 Epoch 00011: val_loss improved from 309198200242.17603 to 275747260858.36798, saving model to best_model.h5 Epoch 12/400 18000/18000 [==============================] - 0s 11us/step - loss: 238421556796.5298 - val_loss: 242600971730.9440 Epoch 00012: val_loss improved from 275747260858.36798 to 242600971730.94400, saving model to best_model.h5 Epoch 13/400 18000/18000 [==============================] - 0s 11us/step - loss: 208827929067.5200 - val_loss: 210544567123.9680 Epoch 00013: val_loss improved from 242600971730.94400 to 210544567123.96799, saving model to best_model.h5 Epoch 14/400 18000/18000 [==============================] - 0s 11us/step - loss: 181250766609.5218 - val_loss: 181239822417.9200 Epoch 00014: val_loss improved from 210544567123.96799 to 181239822417.92001, saving model to best_model.h5 Epoch 15/400 18000/18000 [==============================] - 0s 11us/step - loss: 156734730928.1280 - val_loss: 155991138369.5360 Epoch 00015: val_loss improved from 181239822417.92001 to 155991138369.53601, saving model to best_model.h5 Epoch 16/400 18000/18000 [==============================] - ETA: 0s - loss: 138017311735.09 - 0s 11us/step - loss: 135798981525.5040 - val_loss: 134988053086.2080 Epoch 00016: val_loss improved from 155991138369.53601 to 134988053086.20799, saving model to best_model.h5 Epoch 17/400 18000/18000 [==============================] - 0s 15us/step - loss: 118836078000.3556 - val_loss: 118353070260.2240 Epoch 00017: val_loss improved from 134988053086.20799 to 118353070260.22400, saving model to best_model.h5 Epoch 18/400 18000/18000 [==============================] - 0s 12us/step - loss: 105603678346.3538 - val_loss: 105883129348.0960 Epoch 00018: val_loss improved from 118353070260.22400 to 105883129348.09599, saving model to best_model.h5 Epoch 19/400 18000/18000 [==============================] - 0s 10us/step - loss: 95745313909.4187 - val_loss: 96829833609.2160 Epoch 00019: val_loss improved from 105883129348.09599 to 96829833609.21600, saving model to best_model.h5 Epoch 20/400 18000/18000 [==============================] - 0s 11us/step - loss: 88618352621.7956 - val_loss: 90346775052.2880 Epoch 00020: val_loss improved from 96829833609.21600 to 90346775052.28799, saving model to best_model.h5 Epoch 21/400 18000/18000 [==============================] - 0s 10us/step - loss: 83567574355.5129 - val_loss: 85874045485.0560 Epoch 00021: val_loss improved from 90346775052.28799 to 85874045485.05600, saving model to best_model.h5 Epoch 22/400 18000/18000 [==============================] - 0s 10us/step - loss: 79998094813.8667 - val_loss: 82761349857.2800 Epoch 00022: val_loss improved from 85874045485.05600 to 82761349857.28000, saving model to best_model.h5 Epoch 23/400 18000/18000 [==============================] - 0s 12us/step - loss: 77425343874.8444 - val_loss: 80483269541.8880 Epoch 00023: val_loss improved from 82761349857.28000 to 80483269541.88800, saving model to best_model.h5 Epoch 24/400 18000/18000 [==============================] - 0s 11us/step - loss: 75462087511.6089 - val_loss: 78729282191.3600 Epoch 00024: val_loss improved from 80483269541.88800 to 78729282191.36000, saving model to best_model.h5 Epoch 25/400 18000/18000 [==============================] - 0s 10us/step - loss: 73870388468.8498 - val_loss: 77273078038.5280 Epoch 00025: val_loss improved from 78729282191.36000 to 77273078038.52800, saving model to best_model.h5 Epoch 26/400 18000/18000 [==============================] - 0s 10us/step - loss: 72516323071.3173 - val_loss: 75994380828.6720 Epoch 00026: val_loss improved from 77273078038.52800 to 75994380828.67200, saving model to best_model.h5 Epoch 27/400 18000/18000 [==============================] - 0s 11us/step - loss: 71323900251.7049 - val_loss: 74852082581.5040 Epoch 00027: val_loss improved from 75994380828.67200 to 74852082581.50400, saving model to best_model.h5 Epoch 28/400 18000/18000 [==============================] - 0s 11us/step - loss: 70227146804.7929 - val_loss: 73817158909.9520 Epoch 00028: val_loss improved from 74852082581.50400 to 73817158909.95200, saving model to best_model.h5 Epoch 29/400 18000/18000 [==============================] - 0s 11us/step - loss: 69211586836.7076 - val_loss: 72820976910.3360 Epoch 00029: val_loss improved from 73817158909.95200 to 72820976910.33600, saving model to best_model.h5 Epoch 30/400 18000/18000 [==============================] - 0s 10us/step - loss: 68253316495.5876 - val_loss: 71868724150.2720 Epoch 00030: val_loss improved from 72820976910.33600 to 71868724150.27200, saving model to best_model.h5 Epoch 31/400 18000/18000 [==============================] - 0s 11us/step - loss: 67342146957.7671 - val_loss: 70966434824.1920 Epoch 00031: val_loss improved from 71868724150.27200 to 70966434824.19200, saving model to best_model.h5 Epoch 32/400 18000/18000 [==============================] - 0s 10us/step - loss: 66443596828.2169 - val_loss: 70082538242.0480 Epoch 00032: val_loss improved from 70966434824.19200 to 70082538242.04800, saving model to best_model.h5 Epoch 33/400 18000/18000 [==============================] - 0s 11us/step - loss: 65572032122.4249 - val_loss: 69227643109.3760 Epoch 00033: val_loss improved from 70082538242.04800 to 69227643109.37601, saving model to best_model.h5 Epoch 34/400 18000/18000 [==============================] - 0s 10us/step - loss: 64735541992.5618 - val_loss: 68379734900.7360 Epoch 00034: val_loss improved from 69227643109.37601 to 68379734900.73600, saving model to best_model.h5 Epoch 35/400 18000/18000 [==============================] - 0s 10us/step - loss: 63888829455.4738 - val_loss: 67542714089.4720 Epoch 00035: val_loss improved from 68379734900.73600 to 67542714089.47200, saving model to best_model.h5 Epoch 36/400 18000/18000 [==============================] - 0s 11us/step - loss: 63058047835.2498 - val_loss: 66706866110.4640 Epoch 00036: val_loss improved from 67542714089.47200 to 66706866110.46400, saving model to best_model.h5 Epoch 37/400 18000/18000 [==============================] - 0s 11us/step - loss: 62235788523.7476 - val_loss: 65874906316.8000 Epoch 00037: val_loss improved from 66706866110.46400 to 65874906316.80000, saving model to best_model.h5 Epoch 38/400 18000/18000 [==============================] - 0s 9us/step - loss: 61422055413.0773 - val_loss: 65048028676.0960 Epoch 00038: val_loss improved from 65874906316.80000 to 65048028676.09600, saving model to best_model.h5 Epoch 39/400 18000/18000 [==============================] - 0s 10us/step - loss: 60599847682.0480 - val_loss: 64214742892.5440 Epoch 00039: val_loss improved from 65048028676.09600 to 64214742892.54400, saving model to best_model.h5 Epoch 40/400 18000/18000 [==============================] - 0s 9us/step - loss: 59780959221.9876 - val_loss: 63386770505.7280 Epoch 00040: val_loss improved from 64214742892.54400 to 63386770505.72800, saving model to best_model.h5 Epoch 41/400 18000/18000 [==============================] - 0s 11us/step - loss: 58964683500.2027 - val_loss: 62554961117.1840 Epoch 00041: val_loss improved from 63386770505.72800 to 62554961117.18400, saving model to best_model.h5 Epoch 42/400 18000/18000 [==============================] - 0s 9us/step - loss: 58138298537.3013 - val_loss: 61735717634.0480 Epoch 00042: val_loss improved from 62554961117.18400 to 61735717634.04800, saving model to best_model.h5 Epoch 43/400 18000/18000 [==============================] - 0s 9us/step - loss: 57323855722.7236 - val_loss: 60914490802.1760 Epoch 00043: val_loss improved from 61735717634.04800 to 60914490802.17600, saving model to best_model.h5 Epoch 44/400 18000/18000 [==============================] - 0s 10us/step - loss: 56503696352.1422 - val_loss: 60096960069.6320 Epoch 00044: val_loss improved from 60914490802.17600 to 60096960069.63200, saving model to best_model.h5 Epoch 45/400 18000/18000 [==============================] - 0s 9us/step - loss: 55668120533.2196 - val_loss: 59280067788.8000 Epoch 00045: val_loss improved from 60096960069.63200 to 59280067788.80000, saving model to best_model.h5 Epoch 46/400 18000/18000 [==============================] - 0s 10us/step - loss: 54842026473.6996 - val_loss: 58457415778.3040 Epoch 00046: val_loss improved from 59280067788.80000 to 58457415778.30400, saving model to best_model.h5 Epoch 47/400 18000/18000 [==============================] - 0s 9us/step - loss: 54010812614.4284 - val_loss: 57647501213.6960 Epoch 00047: val_loss improved from 58457415778.30400 to 57647501213.69600, saving model to best_model.h5 Epoch 48/400 18000/18000 [==============================] - 0s 10us/step - loss: 53177819831.4098 - val_loss: 56829615800.3200 Epoch 00048: val_loss improved from 57647501213.69600 to 56829615800.32000, saving model to best_model.h5 Epoch 49/400 18000/18000 [==============================] - 0s 9us/step - loss: 52360600900.9493 - val_loss: 56027553169.4080 Epoch 00049: val_loss improved from 56829615800.32000 to 56027553169.40800, saving model to best_model.h5 Epoch 50/400 18000/18000 [==============================] - 0s 9us/step - loss: 51520948746.4676 - val_loss: 55215088926.7200 Epoch 00050: val_loss improved from 56027553169.40800 to 55215088926.72000, saving model to best_model.h5 Epoch 51/400 18000/18000 [==============================] - 0s 9us/step - loss: 50697004821.1627 - val_loss: 54416942628.8640 Epoch 00051: val_loss improved from 55215088926.72000 to 54416942628.86400, saving model to best_model.h5 Epoch 52/400 18000/18000 [==============================] - 0s 9us/step - loss: 49875405404.3876 - val_loss: 53624083316.7360 Epoch 00052: val_loss improved from 54416942628.86400 to 53624083316.73600, saving model to best_model.h5 Epoch 53/400 18000/18000 [==============================] - 0s 9us/step - loss: 49051193566.0942 - val_loss: 52843989532.6720 Epoch 00053: val_loss improved from 53624083316.73600 to 52843989532.67200, saving model to best_model.h5 Epoch 54/400 18000/18000 [==============================] - 0s 10us/step - loss: 48227908357.6889 - val_loss: 52055709745.1520 Epoch 00054: val_loss improved from 52843989532.67200 to 52055709745.15200, saving model to best_model.h5 Epoch 55/400 18000/18000 [==============================] - 0s 9us/step - loss: 47403340121.8844 - val_loss: 51286491725.8240 Epoch 00055: val_loss improved from 52055709745.15200 to 51286491725.82400, saving model to best_model.h5 Epoch 56/400 18000/18000 [==============================] - 0s 9us/step - loss: 46613951727.3885 - val_loss: 50534507249.6640 Epoch 00056: val_loss improved from 51286491725.82400 to 50534507249.66400, saving model to best_model.h5 Epoch 57/400 18000/18000 [==============================] - 0s 9us/step - loss: 45824541298.2329 - val_loss: 49813665021.9520 Epoch 00057: val_loss improved from 50534507249.66400 to 49813665021.95200, saving model to best_model.h5 Epoch 58/400 18000/18000 [==============================] - 0s 10us/step - loss: 45071834655.4027 - val_loss: 49112425070.5920 Epoch 00058: val_loss improved from 49813665021.95200 to 49112425070.59200, saving model to best_model.h5 Epoch 59/400 18000/18000 [==============================] - 0s 10us/step - loss: 44345352439.5804 - val_loss: 48432106635.2640 Epoch 00059: val_loss improved from 49112425070.59200 to 48432106635.26400, saving model to best_model.h5 Epoch 60/400 18000/18000 [==============================] - 0s 11us/step - loss: 43661941178.3680 - val_loss: 47821221199.8720 Epoch 00060: val_loss improved from 48432106635.26400 to 47821221199.87200, saving model to best_model.h5 Epoch 61/400 18000/18000 [==============================] - 0s 11us/step - loss: 43024287771.3067 - val_loss: 47246677344.2560 Epoch 00061: val_loss improved from 47821221199.87200 to 47246677344.25600, saving model to best_model.h5 Epoch 62/400 18000/18000 [==============================] - 0s 11us/step - loss: 42434092837.5467 - val_loss: 46741821325.3120 Epoch 00062: val_loss improved from 47246677344.25600 to 46741821325.31200, saving model to best_model.h5 Epoch 63/400 18000/18000 [==============================] - 0s 11us/step - loss: 41892284414.1796 - val_loss: 46289688592.3840 Epoch 00063: val_loss improved from 46741821325.31200 to 46289688592.38400, saving model to best_model.h5 Epoch 64/400 18000/18000 [==============================] - 0s 11us/step - loss: 41396230582.7271 - val_loss: 45897796452.3520 Epoch 00064: val_loss improved from 46289688592.38400 to 45897796452.35200, saving model to best_model.h5 Epoch 65/400 18000/18000 [==============================] - 0s 11us/step - loss: 40957934294.3573 - val_loss: 45518593884.1600 Epoch 00065: val_loss improved from 45897796452.35200 to 45518593884.16000, saving model to best_model.h5 Epoch 66/400 18000/18000 [==============================] - 0s 11us/step - loss: 40559064143.1893 - val_loss: 45203121700.8640 Epoch 00066: val_loss improved from 45518593884.16000 to 45203121700.86400, saving model to best_model.h5 Epoch 67/400 18000/18000 [==============================] - 0s 11us/step - loss: 40185660833.7920 - val_loss: 44915859357.6960 Epoch 00067: val_loss improved from 45203121700.86400 to 44915859357.69600, saving model to best_model.h5 Epoch 68/400 18000/18000 [==============================] - 0s 11us/step - loss: 39866041088.2276 - val_loss: 44656491364.3520 Epoch 00068: val_loss improved from 44915859357.69600 to 44656491364.35200, saving model to best_model.h5 Epoch 69/400 18000/18000 [==============================] - 0s 11us/step - loss: 39548505059.7831 - val_loss: 44428516720.6400 Epoch 00069: val_loss improved from 44656491364.35200 to 44428516720.64000, saving model to best_model.h5 Epoch 70/400 18000/18000 [==============================] - 0s 13us/step - loss: 39269333139.4560 - val_loss: 44217486540.8000 Epoch 00070: val_loss improved from 44428516720.64000 to 44217486540.80000, saving model to best_model.h5 Epoch 71/400 18000/18000 [==============================] - 0s 12us/step - loss: 39018746580.5369 - val_loss: 44027694514.1760 Epoch 00071: val_loss improved from 44217486540.80000 to 44027694514.17600, saving model to best_model.h5 Epoch 72/400 18000/18000 [==============================] - 0s 12us/step - loss: 38775277986.7022 - val_loss: 43818001956.8640 Epoch 00072: val_loss improved from 44027694514.17600 to 43818001956.86400, saving model to best_model.h5 Epoch 73/400 18000/18000 [==============================] - 0s 11us/step - loss: 38536078988.6293 - val_loss: 43646061936.6400 Epoch 00073: val_loss improved from 43818001956.86400 to 43646061936.64000, saving model to best_model.h5 Epoch 74/400 18000/18000 [==============================] - 0s 12us/step - loss: 38323034567.1111 - val_loss: 43454754029.5680 Epoch 00074: val_loss improved from 43646061936.64000 to 43454754029.56800, saving model to best_model.h5 Epoch 75/400 18000/18000 [==============================] - 0s 14us/step - loss: 38116566543.0187 - val_loss: 43281596088.3200 Epoch 00075: val_loss improved from 43454754029.56800 to 43281596088.32000, saving model to best_model.h5 Epoch 76/400 18000/18000 [==============================] - 0s 13us/step - loss: 37925072677.5467 - val_loss: 43158784114.6880 Epoch 00076: val_loss improved from 43281596088.32000 to 43158784114.68800, saving model to best_model.h5 Epoch 77/400 18000/18000 [==============================] - 0s 14us/step - loss: 37730638750.6062 - val_loss: 43000789401.6000 Epoch 00077: val_loss improved from 43158784114.68800 to 43000789401.60000, saving model to best_model.h5 Epoch 78/400 18000/18000 [==============================] - 0s 14us/step - loss: 37545695324.8427 - val_loss: 42832945938.4320 Epoch 00078: val_loss improved from 43000789401.60000 to 42832945938.43200, saving model to best_model.h5 Epoch 79/400 18000/18000 [==============================] - 0s 14us/step - loss: 37369545315.6693 - val_loss: 42689178435.5840 Epoch 00079: val_loss improved from 42832945938.43200 to 42689178435.58400, saving model to best_model.h5 Epoch 80/400 18000/18000 [==============================] - 0s 14us/step - loss: 37213279251.1147 - val_loss: 42551691640.8320 Epoch 00080: val_loss improved from 42689178435.58400 to 42551691640.83200, saving model to best_model.h5 Epoch 81/400 18000/18000 [==============================] - 0s 14us/step - loss: 37043436697.8276 - val_loss: 42367208062.9760 Epoch 00081: val_loss improved from 42551691640.83200 to 42367208062.97600, saving model to best_model.h5 Epoch 82/400 18000/18000 [==============================] - 0s 14us/step - loss: 36883514381.6533 - val_loss: 42236606906.3680 Epoch 00082: val_loss improved from 42367208062.97600 to 42236606906.36800, saving model to best_model.h5 Epoch 83/400 18000/18000 [==============================] - 0s 16us/step - loss: 36728396828.2169 - val_loss: 42110056824.8320 Epoch 00083: val_loss improved from 42236606906.36800 to 42110056824.83200, saving model to best_model.h5 Epoch 84/400 18000/18000 [==============================] - 0s 15us/step - loss: 36585878292.2524 - val_loss: 41972454588.4160 Epoch 00084: val_loss improved from 42110056824.83200 to 41972454588.41600, saving model to best_model.h5 Epoch 85/400 18000/18000 [==============================] - 0s 14us/step - loss: 36449368939.6338 - val_loss: 41817125093.3760 Epoch 00085: val_loss improved from 41972454588.41600 to 41817125093.37600, saving model to best_model.h5 Epoch 86/400 18000/18000 [==============================] - 0s 13us/step - loss: 36307057457.3796 - val_loss: 41719629086.7200 Epoch 00086: val_loss improved from 41817125093.37600 to 41719629086.72000, saving model to best_model.h5 Epoch 87/400 18000/18000 [==============================] - 0s 14us/step - loss: 36177432406.6987 - val_loss: 41587646824.4480 Epoch 00087: val_loss improved from 41719629086.72000 to 41587646824.44800, saving model to best_model.h5 Epoch 88/400 18000/18000 [==============================] - 0s 13us/step - loss: 36051885424.6400 - val_loss: 41470138187.7760 Epoch 00088: val_loss improved from 41587646824.44800 to 41470138187.77600, saving model to best_model.h5 Epoch 89/400 18000/18000 [==============================] - 0s 12us/step - loss: 35921624032.1422 - val_loss: 41352127283.2000 Epoch 00089: val_loss improved from 41470138187.77600 to 41352127283.20000, saving model to best_model.h5 Epoch 90/400 18000/18000 [==============================] - 0s 12us/step - loss: 35803357944.9458 - val_loss: 41223586906.1120 Epoch 00090: val_loss improved from 41352127283.20000 to 41223586906.11200, saving model to best_model.h5 Epoch 91/400 18000/18000 [==============================] - 0s 12us/step - loss: 35698335460.0107 - val_loss: 41139544326.1440 Epoch 00091: val_loss improved from 41223586906.11200 to 41139544326.14400, saving model to best_model.h5 Epoch 92/400 18000/18000 [==============================] - 0s 13us/step - loss: 35580043815.5947 - val_loss: 40976475979.7760 Epoch 00092: val_loss improved from 41139544326.14400 to 40976475979.77600, saving model to best_model.h5 Epoch 93/400 18000/18000 [==============================] - 0s 12us/step - loss: 35472793399.7511 - val_loss: 40878393982.9760 Epoch 00093: val_loss improved from 40976475979.77600 to 40878393982.97600, saving model to best_model.h5 Epoch 94/400 18000/18000 [==============================] - 0s 14us/step - loss: 35391152721.4649 - val_loss: 40774588203.0080 Epoch 00094: val_loss improved from 40878393982.97600 to 40774588203.00800, saving model to best_model.h5 Epoch 95/400 18000/18000 [==============================] - 0s 13us/step - loss: 35303738239.6587 - val_loss: 40658617303.0400 Epoch 00095: val_loss improved from 40774588203.00800 to 40658617303.04000, saving model to best_model.h5 Epoch 96/400 18000/18000 [==============================] - 0s 13us/step - loss: 35182854244.1245 - val_loss: 40588689539.0720 Epoch 00096: val_loss improved from 40658617303.04000 to 40588689539.07200, saving model to best_model.h5 Epoch 97/400 18000/18000 [==============================] - 0s 12us/step - loss: 35105872498.2329 - val_loss: 40501942091.7760 Epoch 00097: val_loss improved from 40588689539.07200 to 40501942091.77600, saving model to best_model.h5 Epoch 98/400 18000/18000 [==============================] - 0s 12us/step - loss: 35005353741.8809 - val_loss: 40411219787.7760 Epoch 00098: val_loss improved from 40501942091.77600 to 40411219787.77600, saving model to best_model.h5 Epoch 99/400 18000/18000 [==============================] - 0s 12us/step - loss: 34931741385.6142 - val_loss: 40335295021.0560 Epoch 00099: val_loss improved from 40411219787.77600 to 40335295021.05600, saving model to best_model.h5 Epoch 100/400 18000/18000 [==============================] - 0s 12us/step - loss: 34849365062.0871 - val_loss: 40204030836.7360 Epoch 00100: val_loss improved from 40335295021.05600 to 40204030836.73600, saving model to best_model.h5 Epoch 101/400 18000/18000 [==============================] - 0s 12us/step - loss: 34763294721.8204 - val_loss: 40149693136.8960 Epoch 00101: val_loss improved from 40204030836.73600 to 40149693136.89600, saving model to best_model.h5 Epoch 102/400 18000/18000 [==============================] - 0s 13us/step - loss: 34689906591.5164 - val_loss: 40099296378.8800 Epoch 00102: val_loss improved from 40149693136.89600 to 40099296378.88000, saving model to best_model.h5 Epoch 103/400 18000/18000 [==============================] - 0s 12us/step - loss: 34619039079.5378 - val_loss: 40023661019.1360 Epoch 00103: val_loss improved from 40099296378.88000 to 40023661019.13600, saving model to best_model.h5 Epoch 104/400 18000/18000 [==============================] - 0s 12us/step - loss: 34541981688.7182 - val_loss: 39974522781.6960 Epoch 00104: val_loss improved from 40023661019.13600 to 39974522781.69600, saving model to best_model.h5 Epoch 105/400 18000/18000 [==============================] - 0s 12us/step - loss: 34475419067.2782 - val_loss: 39880520302.5920 Epoch 00105: val_loss improved from 39974522781.69600 to 39880520302.59200, saving model to best_model.h5 Epoch 106/400 18000/18000 [==============================] - 0s 12us/step - loss: 34409279844.8071 - val_loss: 39797475049.4720 Epoch 00106: val_loss improved from 39880520302.59200 to 39797475049.47200, saving model to best_model.h5 Epoch 107/400 18000/18000 [==============================] - 0s 11us/step - loss: 34347008436.9067 - val_loss: 39678428577.7920 Epoch 00107: val_loss improved from 39797475049.47200 to 39678428577.79200, saving model to best_model.h5 Epoch 108/400 18000/18000 [==============================] - 0s 11us/step - loss: 34287083181.3973 - val_loss: 39658844979.2000 Epoch 00108: val_loss improved from 39678428577.79200 to 39658844979.20000, saving model to best_model.h5 Epoch 109/400 18000/18000 [==============================] - 0s 11us/step - loss: 34224641645.6818 - val_loss: 39636056375.2960 Epoch 00109: val_loss improved from 39658844979.20000 to 39636056375.29600, saving model to best_model.h5 Epoch 110/400 18000/18000 [==============================] - 0s 11us/step - loss: 34163118793.6142 - val_loss: 39521863106.5600 Epoch 00110: val_loss improved from 39636056375.29600 to 39521863106.56000, saving model to best_model.h5 Epoch 111/400 18000/18000 [==============================] - 0s 11us/step - loss: 34101883917.6533 - val_loss: 39476215676.9280 Epoch 00111: val_loss improved from 39521863106.56000 to 39476215676.92800, saving model to best_model.h5 Epoch 112/400 18000/18000 [==============================] - 0s 11us/step - loss: 34054626374.0871 - val_loss: 39423951536.1280 Epoch 00112: val_loss improved from 39476215676.92800 to 39423951536.12800, saving model to best_model.h5 Epoch 113/400 18000/18000 [==============================] - 0s 11us/step - loss: 33996209076.4516 - val_loss: 39335197966.3360 Epoch 00113: val_loss improved from 39423951536.12800 to 39335197966.33600, saving model to best_model.h5 Epoch 114/400 18000/18000 [==============================] - 0s 11us/step - loss: 33945380321.5076 - val_loss: 39317181071.3600 Epoch 00114: val_loss improved from 39335197966.33600 to 39317181071.36000, saving model to best_model.h5 Epoch 115/400 18000/18000 [==============================] - 0s 13us/step - loss: 33895051136.5689 - val_loss: 39271611039.7440 Epoch 00115: val_loss improved from 39317181071.36000 to 39271611039.74400, saving model to best_model.h5 Epoch 116/400 18000/18000 [==============================] - 0s 12us/step - loss: 33847080067.0720 - val_loss: 39208574779.3920 Epoch 00116: val_loss improved from 39271611039.74400 to 39208574779.39200, saving model to best_model.h5 Epoch 117/400 18000/18000 [==============================] - 0s 11us/step - loss: 33808622234.2827 - val_loss: 39153998528.5120 Epoch 00117: val_loss improved from 39208574779.39200 to 39153998528.51200, saving model to best_model.h5 Epoch 118/400 18000/18000 [==============================] - 0s 12us/step - loss: 33750373105.6640 - val_loss: 39077553963.0080 Epoch 00118: val_loss improved from 39153998528.51200 to 39077553963.00800, saving model to best_model.h5 Epoch 119/400 18000/18000 [==============================] - 0s 15us/step - loss: 33713382945.2231 - val_loss: 39070849368.0640 Epoch 00119: val_loss improved from 39077553963.00800 to 39070849368.06400, saving model to best_model.h5 Epoch 120/400 18000/18000 [==============================] - 0s 14us/step - loss: 33671119437.8240 - val_loss: 39037835870.2080 Epoch 00120: val_loss improved from 39070849368.06400 to 39037835870.20800, saving model to best_model.h5 Epoch 121/400 18000/18000 [==============================] - 0s 14us/step - loss: 33622327783.8791 - val_loss: 38955241504.7680 Epoch 00121: val_loss improved from 39037835870.20800 to 38955241504.76800, saving model to best_model.h5 Epoch 122/400 18000/18000 [==============================] - 0s 14us/step - loss: 33578996141.6249 - val_loss: 38900926939.1360 Epoch 00122: val_loss improved from 38955241504.76800 to 38900926939.13600, saving model to best_model.h5 Epoch 123/400 18000/18000 [==============================] - 0s 14us/step - loss: 33536964597.0773 - val_loss: 38876731932.6720 Epoch 00123: val_loss improved from 38900926939.13600 to 38876731932.67200, saving model to best_model.h5 Epoch 124/400 18000/18000 [==============================] - 0s 14us/step - loss: 33500475932.6720 - val_loss: 38860265717.7600 Epoch 00124: val_loss improved from 38876731932.67200 to 38860265717.76000, saving model to best_model.h5 Epoch 125/400 18000/18000 [==============================] - 0s 14us/step - loss: 33464907260.8142 - val_loss: 38826009624.5760 Epoch 00125: val_loss improved from 38860265717.76000 to 38826009624.57600, saving model to best_model.h5 Epoch 126/400 18000/18000 [==============================] - 0s 14us/step - loss: 33434713070.7058 - val_loss: 38759668842.4960 Epoch 00126: val_loss improved from 38826009624.57600 to 38759668842.49600, saving model to best_model.h5 Epoch 127/400 18000/18000 [==============================] - 0s 13us/step - loss: 33394509862.2293 - val_loss: 38714550321.1520 Epoch 00127: val_loss improved from 38759668842.49600 to 38714550321.15200, saving model to best_model.h5 Epoch 128/400 18000/18000 [==============================] - 0s 14us/step - loss: 33357455727.7298 - val_loss: 38705615634.4320 Epoch 00128: val_loss improved from 38714550321.15200 to 38705615634.43200, saving model to best_model.h5 Epoch 129/400 18000/18000 [==============================] - 0s 14us/step - loss: 33322727991.9787 - val_loss: 38642503909.3760 Epoch 00129: val_loss improved from 38705615634.43200 to 38642503909.37600, saving model to best_model.h5 Epoch 130/400 18000/18000 [==============================] - 0s 13us/step - loss: 33286661217.3938 - val_loss: 38597904498.6880 Epoch 00130: val_loss improved from 38642503909.37600 to 38597904498.68800, saving model to best_model.h5 Epoch 131/400 18000/18000 [==============================] - 0s 14us/step - loss: 33252904674.1902 - val_loss: 38588660449.2800 Epoch 00131: val_loss improved from 38597904498.68800 to 38588660449.28000, saving model to best_model.h5 Epoch 132/400 18000/18000 [==============================] - 0s 14us/step - loss: 33224918514.8018 - val_loss: 38529613234.1760 Epoch 00132: val_loss improved from 38588660449.28000 to 38529613234.17600, saving model to best_model.h5 Epoch 133/400 18000/18000 [==============================] - 0s 14us/step - loss: 33190210593.6782 - val_loss: 38498867806.2080 Epoch 00133: val_loss improved from 38529613234.17600 to 38498867806.20800, saving model to best_model.h5 Epoch 134/400 18000/18000 [==============================] - 0s 14us/step - loss: 33166816781.1982 - val_loss: 38446092615.6800 Epoch 00134: val_loss improved from 38498867806.20800 to 38446092615.68000, saving model to best_model.h5 Epoch 135/400 18000/18000 [==============================] - 0s 13us/step - loss: 33130609457.3796 - val_loss: 38429994188.8000 Epoch 00135: val_loss improved from 38446092615.68000 to 38429994188.80000, saving model to best_model.h5 Epoch 136/400 18000/18000 [==============================] - 0s 14us/step - loss: 33119490135.3813 - val_loss: 38455079927.8080 Epoch 00136: val_loss did not improve from 38429994188.80000 Epoch 137/400 18000/18000 [==============================] - 0s 15us/step - loss: 33075230091.9467 - val_loss: 38360250580.9920 Epoch 00137: val_loss improved from 38429994188.80000 to 38360250580.99200, saving model to best_model.h5 Epoch 138/400 18000/18000 [==============================] - 0s 16us/step - loss: 33050356289.0809 - val_loss: 38310647627.7760 Epoch 00138: val_loss improved from 38360250580.99200 to 38310647627.77600, saving model to best_model.h5 Epoch 139/400 18000/18000 [==============================] - 0s 14us/step - loss: 33017948624.2133 - val_loss: 38306381004.8000 Epoch 00139: val_loss improved from 38310647627.77600 to 38306381004.80000, saving model to best_model.h5 Epoch 140/400 18000/18000 [==============================] - 0s 14us/step - loss: 32989488866.1902 - val_loss: 38296360091.6480 Epoch 00140: val_loss improved from 38306381004.80000 to 38296360091.64800, saving model to best_model.h5 Epoch 141/400 18000/18000 [==============================] - 0s 13us/step - loss: 32979157902.2222 - val_loss: 38283316002.8160 Epoch 00141: val_loss improved from 38296360091.64800 to 38283316002.81600, saving model to best_model.h5 Epoch 142/400 18000/18000 [==============================] - 0s 14us/step - loss: 32936257102.7342 - val_loss: 38207856377.8560 Epoch 00142: val_loss improved from 38283316002.81600 to 38207856377.85600, saving model to best_model.h5 Epoch 143/400 18000/18000 [==============================] - 0s 13us/step - loss: 32926904334.5636 - val_loss: 38199855087.6160 Epoch 00143: val_loss improved from 38207856377.85600 to 38199855087.61600, saving model to best_model.h5 Epoch 144/400 18000/18000 [==============================] - 0s 14us/step - loss: 32887741881.4578 - val_loss: 38198765125.6320 Epoch 00144: val_loss improved from 38199855087.61600 to 38198765125.63200, saving model to best_model.h5 Epoch 145/400 18000/18000 [==============================] - 0s 13us/step - loss: 32866151701.6178 - val_loss: 38168843452.4160 Epoch 00145: val_loss improved from 38198765125.63200 to 38168843452.41600, saving model to best_model.h5 Epoch 146/400 18000/18000 [==============================] - 0s 13us/step - loss: 32844073466.0836 - val_loss: 38104048435.2000 Epoch 00146: val_loss improved from 38168843452.41600 to 38104048435.20000, saving model to best_model.h5 Epoch 147/400 18000/18000 [==============================] - 0s 14us/step - loss: 32823448882.7449 - val_loss: 38084934664.1920 Epoch 00147: val_loss improved from 38104048435.20000 to 38084934664.19200, saving model to best_model.h5 Epoch 148/400 18000/18000 [==============================] - 0s 14us/step - loss: 32799449681.4649 - val_loss: 38072868339.7120 Epoch 00148: val_loss improved from 38084934664.19200 to 38072868339.71200, saving model to best_model.h5 Epoch 149/400 18000/18000 [==============================] - 0s 13us/step - loss: 32772458883.7547 - val_loss: 38065437343.7440 Epoch 00149: val_loss improved from 38072868339.71200 to 38065437343.74400, saving model to best_model.h5 Epoch 150/400 18000/18000 [==============================] - 0s 13us/step - loss: 32751987806.6631 - val_loss: 38008082759.6800 Epoch 00150: val_loss improved from 38065437343.74400 to 38008082759.68000, saving model to best_model.h5 Epoch 151/400 18000/18000 [==============================] - 0s 14us/step - loss: 32732362072.9742 - val_loss: 37986270773.2480 Epoch 00151: val_loss improved from 38008082759.68000 to 37986270773.24800, saving model to best_model.h5 Epoch 152/400 18000/18000 [==============================] - 0s 13us/step - loss: 32714497126.8551 - val_loss: 37978890764.2880 Epoch 00152: val_loss improved from 37986270773.24800 to 37978890764.28800, saving model to best_model.h5 Epoch 153/400 18000/18000 [==============================] - 0s 14us/step - loss: 32686127815.7938 - val_loss: 37992514650.1120 Epoch 00153: val_loss did not improve from 37978890764.28800 Epoch 154/400 18000/18000 [==============================] - 0s 14us/step - loss: 32670563933.2978 - val_loss: 37929588064.2560 Epoch 00154: val_loss improved from 37978890764.28800 to 37929588064.25600, saving model to best_model.h5 Epoch 155/400 18000/18000 [==============================] - 0s 13us/step - loss: 32643100182.3004 - val_loss: 37923952721.9200 Epoch 00155: val_loss improved from 37929588064.25600 to 37923952721.92000, saving model to best_model.h5 Epoch 156/400 18000/18000 [==============================] - 0s 16us/step - loss: 32639153899.2924 - val_loss: 37904727080.9600 Epoch 00156: val_loss improved from 37923952721.92000 to 37904727080.96000, saving model to best_model.h5 Epoch 157/400 18000/18000 [==============================] - 0s 14us/step - loss: 32613794944.3413 - val_loss: 37936861806.5920 Epoch 00157: val_loss did not improve from 37904727080.96000 Epoch 158/400 18000/18000 [==============================] - 0s 15us/step - loss: 32586484540.3022 - val_loss: 37883475689.4720 Epoch 00158: val_loss improved from 37904727080.96000 to 37883475689.47200, saving model to best_model.h5 Epoch 159/400 18000/18000 [==============================] - 0s 13us/step - loss: 32579593554.6027 - val_loss: 37853698523.1360 Epoch 00159: val_loss improved from 37883475689.47200 to 37853698523.13600, saving model to best_model.h5 Epoch 160/400 18000/18000 [==============================] - 0s 14us/step - loss: 32548355480.6898 - val_loss: 37833799860.2240 Epoch 00160: val_loss improved from 37853698523.13600 to 37833799860.22400, saving model to best_model.h5 Epoch 161/400 18000/18000 [==============================] - 0s 13us/step - loss: 32538943182.1653 - val_loss: 37796682727.4240 Epoch 00161: val_loss improved from 37833799860.22400 to 37796682727.42400, saving model to best_model.h5 Epoch 162/400 18000/18000 [==============================] - 0s 13us/step - loss: 32507544910.0516 - val_loss: 37774902165.5040 Epoch 00162: val_loss improved from 37796682727.42400 to 37774902165.50400, saving model to best_model.h5 Epoch 163/400 18000/18000 [==============================] - 0s 13us/step - loss: 32493366933.7316 - val_loss: 37761643053.0560 Epoch 00163: val_loss improved from 37774902165.50400 to 37761643053.05600, saving model to best_model.h5 Epoch 164/400 18000/18000 [==============================] - 0s 12us/step - loss: 32475281315.1573 - val_loss: 37785489571.8400 Epoch 00164: val_loss did not improve from 37761643053.05600 Epoch 165/400 18000/18000 [==============================] - 0s 13us/step - loss: 32457725282.0764 - val_loss: 37763269394.4320 Epoch 00165: val_loss did not improve from 37761643053.05600 Model score: 0.6731525788821355 ###Markdown TensorFlow & Keras - Basics of Deep Learning Most importantly... resourceshttps://www.tensorflow.org/api_docshttps://keras.io/https://www.tensorflow.org/tutorials/https://www.google.com TF overview* "End-to-end machine learning platform" - Not the only one! Check out PyTorch, Theano, Cognitive Toolkit. * Integrates with high-level APIs like Keras* Plays nice with Pandas* Makes deep learning *fast* and *easy* * *"easy" Tasks for TensorFlow:* Regression - Predict house prices - Predict drug metabolic rates - Predict stock trends * *this is super hard * Classification - Cat or dog? - Malignant or benign cancer from images ![](media/dr.png) Google AI Blog: Diabetic Retinopathy* Dimensionality reduction - Visualize high-dimensional data in 2 or 3-D space - Compress representations for successive ML* Generative models - Create new molecules with desirable properties - Artificially enhance image resolution ![](media/molecular_gan.png) Kadurin et al., 2017* Reinforcement learning - Can't beat your friends at chess? Make your computer do it* Much more... - Generic math - Probabilistic programming with TFP - Automatic differentiation - ... Let's Regress Imports! ###Code import numpy as np import pandas as pd ###Output _____no_output_____ ###Markdown Name a more iconic duo, I'll wait New imports -- TF and Keras ###Code import keras import tensorflow as tf ###Output Using TensorFlow backend. ###Markdown Check our versions for good measure -- these programs may have very different behavior version-to-version ###Code print(keras.__version__) print(tf.__version__) ###Output 2.2.4 1.13.1 ###Markdown Loading in housing data as with SKLearn ###Code data = pd.read_csv('kc_house_data.csv') data data["yr_built"].unique() column_selection = ["bedrooms","bathrooms","sqft_living","sqft_lot", "floors","condition","grade","sqft_above", "sqft_basement","sqft_living15","sqft_lot15", "lat", "long","yr_built","yr_renovated","waterfront"] selected_feature = np.array(data[column_selection]) price = np.array(data["price"]) selected_feature_train = selected_feature[:20000] price_train = price[:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] def score(y,y_pred): return np.mean(np.abs(y-y_pred)/y) model = keras.Sequential() input_len = len(column_selection) model.add(keras.layers.Dense(50, input_dim=input_len, activation='relu')) model.add(keras.layers.Dense(50, activation='relu')) model.add(keras.layers.Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128) preds = model.predict(selected_feature_test) score(preds, price_test) ###Output _____no_output_____ ###Markdown Like SKLearn, it's easy to train and evaluate simple models. ... but we should try to do better Practical Deep Learning -- What you need to know Train, Validation, Test: * Optimize parameters with Train (weights, biases) * Optimize hyperparameters with Validation (layer width & depth, activation functions, etc.) * Optimize NOTHING with Test ###Code # Split out a validation set for hyperparameter optimization selected_feature_train = selected_feature[:18000] price_train = price[:18000] selected_feature_val = selected_feature[18000:20000] price_val = price[18000:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] ###Output _____no_output_____ ###Markdown Try a hyperparameter optimization: Try three activation functions to use for dense layers in the neural network above. Save the model that achieves the best validation loss Hint: [activation functions](http://letmegooglethat.com/?q=keras+activation+functions) Hint: `model.fit` has argument "`validation_data`" which takes a tuple of features and targets Hint: Use `model.save("filename.h5")` to save a model locally. If you want to use it later, just call `keras.models.load_model("filename.h5")` ###Code # For easy looping, define neural network model as a function def nn_model(optimizer='adam', activation='relu', layers=[20,20], loss='mean_squared_error'): model = keras.Sequential() model.add(keras.layers.Dense(50, input_dim=input_len, activation=activ)) model.add(keras.layers.Dense(50, activation=activ)) model.add(keras.layers.Dense(1)) model.compile(loss='mean_absolute_error', optimizer='adam') return model best_score = 1000.0 # bad # loop over chosen activation functions, train, evaluate on validation for activ in ['sigmoid', 'tanh', 'relu']: model = nn_model(activation=activ) history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) if model_score < best_score: best_score = model_score best_activ = activ best_model = model best_train = history print(f"BEST ACTIVATION FUNCTION {best_activ} WITH SCORE {best_score}") best_model.save("awesome_model.h5") ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 61us/step - loss: 532974.1758 - val_loss: 557914.6710 Epoch 2/50 18000/18000 [==============================] - 0s 15us/step - loss: 532967.3181 - val_loss: 557908.9735 Epoch 3/50 18000/18000 [==============================] - 0s 13us/step - loss: 532962.1269 - val_loss: 557903.9525 Epoch 4/50 18000/18000 [==============================] - 0s 14us/step - loss: 532957.2894 - val_loss: 557899.4930 Epoch 5/50 18000/18000 [==============================] - 0s 13us/step - loss: 532952.5633 - val_loss: 557894.6470 Epoch 6/50 18000/18000 [==============================] - 0s 9us/step - loss: 532947.9042 - val_loss: 557889.8510 Epoch 7/50 18000/18000 [==============================] - 0s 11us/step - loss: 532943.2878 - val_loss: 557885.5170 Epoch 8/50 18000/18000 [==============================] - 0s 10us/step - loss: 532938.6823 - val_loss: 557880.8320 Epoch 9/50 18000/18000 [==============================] - 0s 10us/step - loss: 532934.1124 - val_loss: 557876.0225 Epoch 10/50 18000/18000 [==============================] - 0s 10us/step - loss: 532929.5258 - val_loss: 557871.6970 Epoch 11/50 18000/18000 [==============================] - 0s 14us/step - loss: 532924.9893 - val_loss: 557867.0405 Epoch 12/50 18000/18000 [==============================] - 0s 12us/step - loss: 532920.4284 - val_loss: 557862.6110 Epoch 13/50 18000/18000 [==============================] - 0s 12us/step - loss: 532915.8835 - val_loss: 557857.9335 Epoch 14/50 18000/18000 [==============================] - 0s 12us/step - loss: 532911.3458 - val_loss: 557853.6650 Epoch 15/50 18000/18000 [==============================] - 0s 14us/step - loss: 532906.8151 - val_loss: 557848.8690 Epoch 16/50 18000/18000 [==============================] - 0s 12us/step - loss: 532902.2797 - val_loss: 557844.4835 Epoch 17/50 18000/18000 [==============================] - 0s 10us/step - loss: 532897.7445 - val_loss: 557839.8085 Epoch 18/50 18000/18000 [==============================] - 0s 10us/step - loss: 532893.2282 - val_loss: 557835.5010 Epoch 19/50 18000/18000 [==============================] - 0s 10us/step - loss: 532888.7034 - val_loss: 557830.8360 Epoch 20/50 18000/18000 [==============================] - 0s 10us/step - loss: 532884.1843 - val_loss: 557826.4430 Epoch 21/50 18000/18000 [==============================] - 0s 12us/step - loss: 532879.6504 - val_loss: 557821.7920 Epoch 22/50 18000/18000 [==============================] - 0s 14us/step - loss: 532875.1483 - val_loss: 557817.4790 Epoch 23/50 18000/18000 [==============================] - 0s 13us/step - loss: 532870.6122 - val_loss: 557812.8160 Epoch 24/50 18000/18000 [==============================] - 0s 11us/step - loss: 532866.1056 - val_loss: 557808.3360 Epoch 25/50 18000/18000 [==============================] - 0s 10us/step - loss: 532861.5706 - val_loss: 557803.7380 Epoch 26/50 18000/18000 [==============================] - 0s 11us/step - loss: 532857.0776 - val_loss: 557799.1610 Epoch 27/50 18000/18000 [==============================] - 0s 10us/step - loss: 532852.5495 - val_loss: 557794.6775 Epoch 28/50 18000/18000 [==============================] - 0s 14us/step - loss: 532848.0404 - val_loss: 557789.9945 Epoch 29/50 18000/18000 [==============================] - 0s 15us/step - loss: 532843.5083 - val_loss: 557785.6990 Epoch 30/50 18000/18000 [==============================] - 0s 14us/step - loss: 532839.0229 - val_loss: 557781.0485 Epoch 31/50 18000/18000 [==============================] - 0s 12us/step - loss: 532834.4841 - val_loss: 557776.6410 Epoch 32/50 18000/18000 [==============================] - 0s 12us/step - loss: 532829.9850 - val_loss: 557771.9805 Epoch 33/50 18000/18000 [==============================] - 0s 12us/step - loss: 532825.4563 - val_loss: 557767.6930 Epoch 34/50 18000/18000 [==============================] - 0s 12us/step - loss: 532820.7999 - val_loss: 557762.6110 Epoch 35/50 18000/18000 [==============================] - 0s 10us/step - loss: 532815.6766 - val_loss: 557757.6930 Epoch 36/50 18000/18000 [==============================] - 0s 10us/step - loss: 532810.8327 - val_loss: 557752.8360 Epoch 37/50 18000/18000 [==============================] - 0s 9us/step - loss: 532806.0533 - val_loss: 557747.9525 Epoch 38/50 18000/18000 [==============================] - 0s 9us/step - loss: 532801.3039 - val_loss: 557743.0485 Epoch 39/50 18000/18000 [==============================] - 0s 9us/step - loss: 532796.0384 - val_loss: 557737.7920 Epoch 40/50 18000/18000 [==============================] - 0s 9us/step - loss: 532790.9252 - val_loss: 557732.8320 Epoch 41/50 18000/18000 [==============================] - 0s 9us/step - loss: 532785.9397 - val_loss: 557727.7980 Epoch 42/50 18000/18000 [==============================] - 0s 13us/step - loss: 532781.0243 - val_loss: 557722.8730 Epoch 43/50 18000/18000 [==============================] - 0s 15us/step - loss: 532776.1177 - val_loss: 557717.9525 Epoch 44/50 18000/18000 [==============================] - 0s 14us/step - loss: 532771.2528 - val_loss: 557713.3645 Epoch 45/50 18000/18000 [==============================] - 0s 11us/step - loss: 532766.3882 - val_loss: 557708.4470 Epoch 46/50 18000/18000 [==============================] - 0s 11us/step - loss: 532761.5342 - val_loss: 557703.6650 Epoch 47/50 18000/18000 [==============================] - 0s 14us/step - loss: 532756.7074 - val_loss: 557698.6670 Epoch 48/50 18000/18000 [==============================] - 0s 11us/step - loss: 532751.8659 - val_loss: 557693.7030 Epoch 49/50 18000/18000 [==============================] - 0s 14us/step - loss: 532746.5045 - val_loss: 557688.0105 Epoch 50/50 18000/18000 [==============================] - 0s 13us/step - loss: 532741.2496 - val_loss: 557683.0085 Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 66us/step - loss: 532968.8535 - val_loss: 557907.8785 Epoch 2/50 18000/18000 [==============================] - 0s 11us/step - loss: 532959.6811 - val_loss: 557900.1345 Epoch 3/50 18000/18000 [==============================] - 0s 12us/step - loss: 532952.1103 - val_loss: 557892.8225 Epoch 4/50 18000/18000 [==============================] - 0s 11us/step - loss: 532944.7126 - val_loss: 557885.5415 Epoch 5/50 18000/18000 [==============================] - 0s 11us/step - loss: 532937.3764 - val_loss: 557877.9805 Epoch 6/50 18000/18000 [==============================] - 0s 12us/step - loss: 532930.0783 - val_loss: 557870.8360 Epoch 7/50 18000/18000 [==============================] - 0s 12us/step - loss: 532922.8012 - val_loss: 557863.6790 Epoch 8/50 18000/18000 [==============================] - 0s 12us/step - loss: 532915.5595 - val_loss: 557856.4430 Epoch 9/50 18000/18000 [==============================] - 0s 12us/step - loss: 532908.3144 - val_loss: 557849.0125 Epoch 10/50 18000/18000 [==============================] - 0s 12us/step - loss: 532901.0774 - val_loss: 557841.7920 Epoch 11/50 18000/18000 [==============================] - 0s 12us/step - loss: 532893.8619 - val_loss: 557834.6450 Epoch 12/50 18000/18000 [==============================] - 0s 12us/step - loss: 532886.6362 - val_loss: 557827.5335 Epoch 13/50 18000/18000 [==============================] - 0s 11us/step - loss: 532879.4228 - val_loss: 557820.0150 Epoch 14/50 18000/18000 [==============================] - 0s 11us/step - loss: 532872.2118 - val_loss: 557812.9090 Epoch 15/50 18000/18000 [==============================] - 0s 10us/step - loss: 532864.9957 - val_loss: 557805.7820 Epoch 16/50 18000/18000 [==============================] - 0s 11us/step - loss: 532857.7976 - val_loss: 557798.6210 Epoch 17/50 18000/18000 [==============================] - 0s 16us/step - loss: 532850.5966 - val_loss: 557791.5170 Epoch 18/50 18000/18000 [==============================] - 0s 13us/step - loss: 532843.3934 - val_loss: 557783.9945 Epoch 19/50 18000/18000 [==============================] - 0s 14us/step - loss: 532836.1900 - val_loss: 557776.8790 Epoch 20/50 18000/18000 [==============================] - 0s 15us/step - loss: 532828.9844 - val_loss: 557769.7820 Epoch 21/50 18000/18000 [==============================] - 0s 12us/step - loss: 532821.7987 - val_loss: 557762.6210 Epoch 22/50 18000/18000 [==============================] - 0s 12us/step - loss: 532814.5922 - val_loss: 557755.5335 Epoch 23/50 18000/18000 [==============================] - 0s 12us/step - loss: 532807.4018 - val_loss: 557747.9945 Epoch 24/50 18000/18000 [==============================] - 0s 12us/step - loss: 532800.2038 - val_loss: 557740.9595 Epoch 25/50 18000/18000 [==============================] - 0s 9us/step - loss: 532793.0068 - val_loss: 557733.7920 Epoch 26/50 18000/18000 [==============================] - 0s 9us/step - loss: 532785.8116 - val_loss: 557726.6450 Epoch 27/50 18000/18000 [==============================] - 0s 9us/step - loss: 532778.6256 - val_loss: 557719.5335 Epoch 28/50 18000/18000 [==============================] - 0s 9us/step - loss: 532771.4330 - val_loss: 557712.0170 Epoch 29/50 18000/18000 [==============================] - 0s 9us/step - loss: 532764.2351 - val_loss: 557704.9855 Epoch 30/50 18000/18000 [==============================] - 0s 9us/step - loss: 532757.0397 - val_loss: 557697.7920 Epoch 31/50 18000/18000 [==============================] - 0s 10us/step - loss: 532749.8561 - val_loss: 557690.6450 Epoch 32/50 18000/18000 [==============================] - 0s 9us/step - loss: 532742.6587 - val_loss: 557683.5700 Epoch 33/50 18000/18000 [==============================] - 0s 9us/step - loss: 532735.4679 - val_loss: 557676.3360 Epoch 34/50 18000/18000 [==============================] - 0s 9us/step - loss: 532728.2726 - val_loss: 557668.9955 Epoch 35/50 18000/18000 [==============================] - 0s 9us/step - loss: 532721.0774 - val_loss: 557661.7980 Epoch 36/50 18000/18000 [==============================] - 0s 12us/step - loss: 532713.8920 - val_loss: 557654.6670 Epoch 37/50 18000/18000 [==============================] - 0s 12us/step - loss: 532706.6927 - val_loss: 557647.6650 Epoch 38/50 18000/18000 [==============================] - 0s 13us/step - loss: 532699.5059 - val_loss: 557640.4430 Epoch 39/50 18000/18000 [==============================] - 0s 12us/step - loss: 532692.3229 - val_loss: 557633.0485 Epoch 40/50 18000/18000 [==============================] - 0s 13us/step - loss: 532685.1196 - val_loss: 557625.8125 Epoch 41/50 18000/18000 [==============================] - 0s 12us/step - loss: 532677.9398 - val_loss: 557618.7840 Epoch 42/50 18000/18000 [==============================] - 0s 11us/step - loss: 532670.7418 - val_loss: 557611.6650 Epoch 43/50 18000/18000 [==============================] - 0s 12us/step - loss: 532663.5602 - val_loss: 557604.4430 Epoch 44/50 18000/18000 [==============================] - 0s 11us/step - loss: 532656.3681 - val_loss: 557597.0485 Epoch 45/50 18000/18000 [==============================] - 0s 12us/step - loss: 532649.1709 - val_loss: 557589.8230 Epoch 46/50 18000/18000 [==============================] - 0s 13us/step - loss: 532641.9852 - val_loss: 557582.8240 Epoch 47/50 18000/18000 [==============================] - 0s 13us/step - loss: 532634.7951 - val_loss: 557575.6850 Epoch 48/50 18000/18000 [==============================] - 0s 12us/step - loss: 532627.6101 - val_loss: 557568.4755 Epoch 49/50 18000/18000 [==============================] - 0s 12us/step - loss: 532620.4128 - val_loss: 557561.1510 Epoch 50/50 18000/18000 [==============================] - 0s 12us/step - loss: 532613.2224 - val_loss: 557553.9335 Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 69us/step - loss: 460302.7814 - val_loss: 389935.7043 Epoch 2/50 18000/18000 [==============================] - 0s 13us/step - loss: 288842.3789 - val_loss: 218617.1030 Epoch 3/50 18000/18000 [==============================] - 0s 12us/step - loss: 174847.2772 - val_loss: 176664.5083 Epoch 4/50 18000/18000 [==============================] - 0s 11us/step - loss: 165716.2985 - val_loss: 173251.2797 Epoch 5/50 18000/18000 [==============================] - 0s 12us/step - loss: 163249.9868 - val_loss: 172159.8714 Epoch 6/50 18000/18000 [==============================] - 0s 12us/step - loss: 161611.9619 - val_loss: 170750.6835 Epoch 7/50 18000/18000 [==============================] - 0s 12us/step - loss: 160407.1660 - val_loss: 169810.5179 Epoch 8/50 18000/18000 [==============================] - 0s 12us/step - loss: 159345.5089 - val_loss: 169291.1629 Epoch 9/50 18000/18000 [==============================] - 0s 12us/step - loss: 158630.9237 - val_loss: 169034.1908 Epoch 10/50 18000/18000 [==============================] - 0s 12us/step - loss: 158230.8990 - val_loss: 168649.8141 Epoch 11/50 18000/18000 [==============================] - 0s 12us/step - loss: 158015.7605 - val_loss: 169410.4244 Epoch 12/50 18000/18000 [==============================] - 0s 11us/step - loss: 157256.5905 - val_loss: 167973.3121 Epoch 13/50 18000/18000 [==============================] - 0s 12us/step - loss: 156975.5700 - val_loss: 167988.3602 Epoch 14/50 18000/18000 [==============================] - 0s 11us/step - loss: 156917.9833 - val_loss: 167261.6631 Epoch 15/50 18000/18000 [==============================] - 0s 11us/step - loss: 156874.7785 - val_loss: 169002.1360 Epoch 16/50 18000/18000 [==============================] - 0s 10us/step - loss: 156387.4673 - val_loss: 167151.6112 Epoch 17/50 18000/18000 [==============================] - 0s 10us/step - loss: 156141.9905 - val_loss: 168106.7525 Epoch 18/50 18000/18000 [==============================] - 0s 10us/step - loss: 155940.2835 - val_loss: 167468.5219 Epoch 19/50 18000/18000 [==============================] - 0s 10us/step - loss: 155684.3832 - val_loss: 167765.7778 Epoch 20/50 18000/18000 [==============================] - 0s 10us/step - loss: 155719.0916 - val_loss: 167466.6630 Epoch 21/50 18000/18000 [==============================] - 0s 10us/step - loss: 155545.2087 - val_loss: 166713.0641 Epoch 22/50 18000/18000 [==============================] - 0s 9us/step - loss: 155303.3075 - val_loss: 166852.0119 Epoch 23/50 18000/18000 [==============================] - 0s 11us/step - loss: 155179.0475 - val_loss: 166528.6830 Epoch 24/50 18000/18000 [==============================] - 0s 10us/step - loss: 155039.3024 - val_loss: 167060.9409 Epoch 25/50 18000/18000 [==============================] - 0s 10us/step - loss: 155022.6373 - val_loss: 166782.4909 Epoch 26/50 18000/18000 [==============================] - 0s 10us/step - loss: 154666.9540 - val_loss: 166420.0279 Epoch 27/50 18000/18000 [==============================] - 0s 10us/step - loss: 155009.4956 - val_loss: 166587.0267 Epoch 28/50 18000/18000 [==============================] - 0s 10us/step - loss: 154355.8122 - val_loss: 166219.7179 Epoch 29/50 18000/18000 [==============================] - 0s 10us/step - loss: 154413.5130 - val_loss: 166502.0960 Epoch 30/50 18000/18000 [==============================] - 0s 10us/step - loss: 154332.8766 - val_loss: 165990.8961 Epoch 31/50 18000/18000 [==============================] - 0s 10us/step - loss: 154091.2003 - val_loss: 167065.7801 Epoch 32/50 18000/18000 [==============================] - 0s 9us/step - loss: 154115.9829 - val_loss: 167038.7180 Epoch 33/50 18000/18000 [==============================] - 0s 10us/step - loss: 153895.3677 - val_loss: 166218.6487 Epoch 34/50 18000/18000 [==============================] - 0s 10us/step - loss: 154062.3794 - val_loss: 166869.0389 Epoch 35/50 18000/18000 [==============================] - 0s 10us/step - loss: 153830.0327 - val_loss: 165967.7117 Epoch 36/50 18000/18000 [==============================] - 0s 10us/step - loss: 153554.7361 - val_loss: 165572.1533 Epoch 37/50 18000/18000 [==============================] - 0s 10us/step - loss: 153472.7553 - val_loss: 165612.7610 Epoch 38/50 18000/18000 [==============================] - 0s 10us/step - loss: 153322.2003 - val_loss: 165850.4700 Epoch 39/50 18000/18000 [==============================] - 0s 10us/step - loss: 153419.3344 - val_loss: 166075.8007 Epoch 40/50 18000/18000 [==============================] - ETA: 0s - loss: 153015.61 - 0s 10us/step - loss: 153535.5968 - val_loss: 165214.1501 Epoch 41/50 18000/18000 [==============================] - 0s 10us/step - loss: 153215.4091 - val_loss: 165272.4703 Epoch 42/50 18000/18000 [==============================] - 0s 10us/step - loss: 153143.2716 - val_loss: 165429.7129 Epoch 43/50 18000/18000 [==============================] - 0s 10us/step - loss: 152930.2451 - val_loss: 164992.4201 Epoch 44/50 18000/18000 [==============================] - 0s 11us/step - loss: 153128.0189 - val_loss: 165270.4543 Epoch 45/50 18000/18000 [==============================] - 0s 9us/step - loss: 152793.8060 - val_loss: 166957.1629 Epoch 46/50 18000/18000 [==============================] - 0s 9us/step - loss: 152620.9163 - val_loss: 166043.3472 Epoch 47/50 18000/18000 [==============================] - 0s 9us/step - loss: 152873.9664 - val_loss: 165305.3497 Epoch 48/50 18000/18000 [==============================] - 0s 10us/step - loss: 152703.1435 - val_loss: 165293.5600 Epoch 49/50 18000/18000 [==============================] - 0s 9us/step - loss: 152441.4831 - val_loss: 164842.7197 Epoch 50/50 18000/18000 [==============================] - 0s 9us/step - loss: 152284.0022 - val_loss: 164795.3660 BEST ACTIVATION FUNCTION relu WITH SCORE 0.6314101076795888 ###Markdown Visualize your training: ###Code import matplotlib.pyplot as plt # plot loss during training def plot_loss(hist): %matplotlib inline plt.title('Training Curve') plt.plot(hist.history['loss'], label='train') plt.plot(hist.history['val_loss'], label='validation') plt.xlabel("Epochs") plt.ylabel("Mean squared error") plt.legend() plt.show() plot_loss(best_train) ###Output _____no_output_____ ###Markdown In the future, try better validation schemes like [k-fold cross validation](https://chrisalbon.com/deep_learning/keras/k-fold_cross-validating_neural_networks/), though 80/20 or 90/10 train/val like this works in a pinch Standardize your features:* Typically assumes normally distributed feature, shifting mean to 0 and standard deviation to 1* In theory does not matter for neural networks* In practice tends to matter for neural networks* Scale if using: - Logistic regression - Support vector machines - Perceptrons - Neural networks - Principle component analysis* Don't bother if using: - "Forest" methods - Naive Bayes ###Code from sklearn.preprocessing import StandardScaler # Instantiate StandardScaler in_scaler = StandardScaler() # Fit scaler to the training set and perform the transformation selected_feature_train = in_scaler.fit_transform(selected_feature_train) # Use the fitted scaler to transform validation and test features selected_feature_val = in_scaler.transform(selected_feature_val) selected_feature_test = in_scaler.transform(selected_feature_test) # Check appropriate scaling print(np.mean(selected_feature_train[:,0])) print(np.std(selected_feature_train[:,0])) print(np.mean(selected_feature_val[:,0])) print(np.std(selected_feature_val[:,0])) print(np.mean(selected_feature_test[:,0])) print(np.std(selected_feature_test[:,0])) model = nn_model() model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=200, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(model_score) plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/200 18000/18000 [==============================] - 1s 69us/step - loss: 416644724774.2293 - val_loss: 456240251273.2160 Epoch 2/200 18000/18000 [==============================] - 0s 14us/step - loss: 416219411047.3102 - val_loss: 455230525276.1600 Epoch 3/200 18000/18000 [==============================] - 0s 16us/step - loss: 414539373463.3245 - val_loss: 452292457267.2000 Epoch 4/200 18000/18000 [==============================] - 0s 14us/step - loss: 410731792826.3680 - val_loss: 446517339226.1120 Epoch 5/200 18000/18000 [==============================] - 0s 12us/step - loss: 403953550943.1182 - val_loss: 437057174896.6400 Epoch 6/200 18000/18000 [==============================] - 0s 11us/step - loss: 393657770544.6969 - val_loss: 423509280423.9360 Epoch 7/200 18000/18000 [==============================] - 0s 11us/step - loss: 379580761156.2667 - val_loss: 405581878001.6640 Epoch 8/200 18000/18000 [==============================] - 0s 11us/step - loss: 361658841912.6613 - val_loss: 383390637883.3920 Epoch 9/200 18000/18000 [==============================] - 0s 12us/step - loss: 340165479570.5458 - val_loss: 357764951965.6960 Epoch 10/200 18000/18000 [==============================] - 0s 10us/step - loss: 315699842136.2916 - val_loss: 329091613720.5760 Epoch 11/200 18000/18000 [==============================] - 0s 10us/step - loss: 289117304433.3227 - val_loss: 298578878136.3200 Epoch 12/200 18000/18000 [==============================] - 0s 11us/step - loss: 261380564058.1120 - val_loss: 267361173110.7840 Epoch 13/200 18000/18000 [==============================] - 0s 11us/step - loss: 233512805422.4213 - val_loss: 236796970795.0080 Epoch 14/200 18000/18000 [==============================] - 0s 11us/step - loss: 206621634811.2213 - val_loss: 207759685582.8480 Epoch 15/200 18000/18000 [==============================] - 0s 11us/step - loss: 181544216108.1458 - val_loss: 181255742947.3280 Epoch 16/200 18000/18000 [==============================] - 0s 12us/step - loss: 159017826516.9920 - val_loss: 158054828081.1520 Epoch 17/200 18000/18000 [==============================] - 0s 11us/step - loss: 139581889431.3244 - val_loss: 138607148466.1760 Epoch 18/200 18000/18000 [==============================] - 0s 12us/step - loss: 123407551306.8658 - val_loss: 122830300577.7920 Epoch 19/200 18000/18000 [==============================] - 0s 11us/step - loss: 110414201050.4533 - val_loss: 110407385219.0720 Epoch 20/200 18000/18000 [==============================] - 0s 11us/step - loss: 100342549796.1813 - val_loss: 101138505334.7840 Epoch 21/200 18000/18000 [==============================] - 0s 11us/step - loss: 92746195562.9511 - val_loss: 94260454621.1840 Epoch 22/200 18000/18000 [==============================] - 0s 12us/step - loss: 87142331467.5484 - val_loss: 89257073442.8160 Epoch 23/200 18000/18000 [==============================] - 0s 10us/step - loss: 83029246782.1227 - val_loss: 85649517051.9040 Epoch 24/200 18000/18000 [==============================] - 0s 10us/step - loss: 79974571289.2587 - val_loss: 82916333518.8480 Epoch 25/200 18000/18000 [==============================] - 0s 10us/step - loss: 77613710038.3573 - val_loss: 80772310892.5440 Epoch 26/200 18000/18000 [==============================] - 0s 10us/step - loss: 75758766536.9315 - val_loss: 79040771063.8080 Epoch 27/200 18000/18000 [==============================] - 0s 16us/step - loss: 74215229277.9805 - val_loss: 77595545501.6960 Epoch 28/200 18000/18000 [==============================] - 0s 16us/step - loss: 72905572177.2373 - val_loss: 76338272731.1360 Epoch 29/200 18000/18000 [==============================] - 0s 15us/step - loss: 71745211261.8382 - val_loss: 75183492169.7280 Epoch 30/200 18000/18000 [==============================] - 0s 12us/step - loss: 70697890440.0782 - val_loss: 74151740702.7200 Epoch 31/200 18000/18000 [==============================] - 0s 15us/step - loss: 69729018285.6249 - val_loss: 73179619459.0720 Epoch 32/200 18000/18000 [==============================] - 0s 16us/step - loss: 68816311542.6702 - val_loss: 72256881098.7520 Epoch 33/200 18000/18000 [==============================] - 0s 16us/step - loss: 67936579977.2160 - val_loss: 71377126752.2560 Epoch 34/200 18000/18000 [==============================] - 0s 13us/step - loss: 67097538195.9111 - val_loss: 70526461837.3120 Epoch 35/200 18000/18000 [==============================] - 0s 10us/step - loss: 66280199538.4604 - val_loss: 69706505519.1040 Epoch 36/200 18000/18000 [==============================] - 0s 9us/step - loss: 65474546091.8044 - val_loss: 68888741609.4720 Epoch 37/200 18000/18000 [==============================] - 0s 14us/step - loss: 64683688744.2773 - val_loss: 68096607354.8800 Epoch 38/200 18000/18000 [==============================] - 0s 15us/step - loss: 63904897171.4560 - val_loss: 67312825925.6320 Epoch 39/200 18000/18000 [==============================] - 0s 15us/step - loss: 63130683200.8533 - val_loss: 66542651277.3120 Epoch 40/200 18000/18000 [==============================] - 0s 15us/step - loss: 62353993003.4631 - val_loss: 65772004278.2720 Epoch 41/200 18000/18000 [==============================] - 0s 13us/step - loss: 61587946799.1040 - val_loss: 65005461667.8400 Epoch 42/200 18000/18000 [==============================] - 0s 13us/step - loss: 60821804999.5662 - val_loss: 64246054682.6240 Epoch 43/200 18000/18000 [==============================] - 0s 15us/step - loss: 60059479146.4960 - val_loss: 63493657821.1840 Epoch 44/200 18000/18000 [==============================] - 0s 13us/step - loss: 59302580489.7849 - val_loss: 62744275124.2240 Epoch 45/200 18000/18000 [==============================] - 0s 11us/step - loss: 58543664973.5964 - val_loss: 61995190353.9200 Epoch 46/200 18000/18000 [==============================] - 0s 14us/step - loss: 57782123597.3689 - val_loss: 61241564889.0880 Epoch 47/200 18000/18000 [==============================] - 0s 14us/step - loss: 57033753307.8187 - val_loss: 60478097522.6880 Epoch 48/200 18000/18000 [==============================] - 0s 16us/step - loss: 56258215957.8453 - val_loss: 59734967582.7200 Epoch 49/200 18000/18000 [==============================] - 0s 15us/step - loss: 55499806911.1467 - val_loss: 58974680743.9360 Epoch 50/200 18000/18000 [==============================] - 0s 12us/step - loss: 54732866202.2827 - val_loss: 58233620856.8320 Epoch 51/200 18000/18000 [==============================] - 0s 12us/step - loss: 53979515737.4293 - val_loss: 57494574628.8640 Epoch 52/200 18000/18000 [==============================] - 0s 12us/step - loss: 53222918094.8480 - val_loss: 56758398943.2320 Epoch 53/200 18000/18000 [==============================] - 0s 14us/step - loss: 52461172330.0409 - val_loss: 56031989923.8400 Epoch 54/200 18000/18000 [==============================] - 0s 11us/step - loss: 51707750733.1413 - val_loss: 55297092943.8720 Epoch 55/200 18000/18000 [==============================] - 0s 12us/step - loss: 50952434705.2942 - val_loss: 54574977581.0560 Epoch 56/200 18000/18000 [==============================] - 0s 12us/step - loss: 50216374794.4676 - val_loss: 53872021700.6080 Epoch 57/200 18000/18000 [==============================] - 0s 12us/step - loss: 49466069960.4764 - val_loss: 53165771784.1920 Epoch 58/200 18000/18000 [==============================] - 0s 12us/step - loss: 48736365170.2329 - val_loss: 52481645215.7440 Epoch 59/200 18000/18000 [==============================] - 0s 12us/step - loss: 48015811634.0622 - val_loss: 51818096754.6880 Epoch 60/200 18000/18000 [==============================] - 0s 12us/step - loss: 47307462479.4169 - val_loss: 51166277468.1600 Epoch 61/200 18000/18000 [==============================] - 0s 12us/step - loss: 46607229739.9182 - val_loss: 50528075153.4080 Epoch 62/200 18000/18000 [==============================] - 0s 11us/step - loss: 45922461060.6649 - val_loss: 49895826849.7920 Epoch 63/200 18000/18000 [==============================] - 0s 10us/step - loss: 45252787397.5182 - val_loss: 49297462722.5600 Epoch 64/200 18000/18000 [==============================] - 0s 10us/step - loss: 44604951643.9324 - val_loss: 48700301737.9840 Epoch 65/200 18000/18000 [==============================] - 0s 10us/step - loss: 43967003383.1253 - val_loss: 48120822792.1920 Epoch 66/200 18000/18000 [==============================] - ETA: 0s - loss: 43677351207.822 - 0s 10us/step - loss: 43358731547.0791 - val_loss: 47560437465.0880 Epoch 67/200 18000/18000 [==============================] - 0s 10us/step - loss: 42763919989.8738 - val_loss: 47031392337.9200 Epoch 68/200 18000/18000 [==============================] - 0s 12us/step - loss: 42186531049.0169 - val_loss: 46524311076.8640 Epoch 69/200 18000/18000 [==============================] - 0s 12us/step - loss: 41641749632.3413 - val_loss: 46035936804.8640 Epoch 70/200 18000/18000 [==============================] - 0s 12us/step - loss: 41131274274.5884 - val_loss: 45590292496.3840 Epoch 71/200 18000/18000 [==============================] - 0s 13us/step - loss: 40640540990.5778 - val_loss: 45200045047.8080 Epoch 72/200 18000/18000 [==============================] - 0s 13us/step - loss: 40185976102.0018 - val_loss: 44812461441.0240 Epoch 73/200 18000/18000 [==============================] - 0s 10us/step - loss: 39770515632.5831 - val_loss: 44455844544.5120 Epoch 74/200 18000/18000 [==============================] - 0s 11us/step - loss: 39383302529.9342 - val_loss: 44143539847.1680 Epoch 75/200 18000/18000 [==============================] - 0s 11us/step - loss: 39036987379.2569 - val_loss: 43853232668.6720 Epoch 76/200 18000/18000 [==============================] - 0s 13us/step - loss: 38714754087.1396 - val_loss: 43603367395.3280 Epoch 77/200 18000/18000 [==============================] - 0s 13us/step - loss: 38427186877.7813 - val_loss: 43368991490.0480 Epoch 78/200 18000/18000 [==============================] - 0s 12us/step - loss: 38160408874.5529 - val_loss: 43161227362.3040 Epoch 79/200 18000/18000 [==============================] - 0s 11us/step - loss: 37924018501.8596 - val_loss: 42971564965.8880 Epoch 80/200 18000/18000 [==============================] - 0s 10us/step - loss: 37706286556.0462 - val_loss: 42789223038.9760 Epoch 81/200 18000/18000 [==============================] - 0s 12us/step - loss: 37521690509.3120 - val_loss: 42630109265.9200 Epoch 82/200 18000/18000 [==============================] - 0s 11us/step - loss: 37323107128.6613 - val_loss: 42519357882.3680 Epoch 83/200 18000/18000 [==============================] - 0s 15us/step - loss: 37151890132.5369 - val_loss: 42389031780.3520 Epoch 84/200 18000/18000 [==============================] - 0s 16us/step - loss: 36994491953.6071 - val_loss: 42256742350.8480 Epoch 85/200 18000/18000 [==============================] - 0s 13us/step - loss: 36835559378.4889 - val_loss: 42120880259.0720 Epoch 86/200 18000/18000 [==============================] - 0s 10us/step - loss: 36704747214.1653 - val_loss: 42013906468.8640 Epoch 87/200 18000/18000 [==============================] - 0s 10us/step - loss: 36570395162.8516 - val_loss: 41910531948.5440 Epoch 88/200 18000/18000 [==============================] - 0s 11us/step - loss: 36440781664.7111 - val_loss: 41807704260.6080 Epoch 89/200 18000/18000 [==============================] - 0s 13us/step - loss: 36317897958.2862 - val_loss: 41708020006.9120 Epoch 90/200 18000/18000 [==============================] - 0s 14us/step - loss: 36208089410.2187 - val_loss: 41619933167.6160 Epoch 91/200 18000/18000 [==============================] - 0s 11us/step - loss: 36095894862.0516 - val_loss: 41511169458.1760 Epoch 92/200 18000/18000 [==============================] - 0s 12us/step - loss: 35994212051.6267 - val_loss: 41430843686.9120 Epoch 93/200 18000/18000 [==============================] - 0s 11us/step - loss: 35886885553.9484 - val_loss: 41361790697.4720 Epoch 94/200 18000/18000 [==============================] - 0s 11us/step - loss: 35793174910.2933 - val_loss: 41256490467.3280 Epoch 95/200 18000/18000 [==============================] - 0s 12us/step - loss: 35695162993.3227 - val_loss: 41184487899.1360 Epoch 96/200 18000/18000 [==============================] - 0s 12us/step - loss: 35602815862.5564 - val_loss: 41073298571.2640 Epoch 97/200 18000/18000 [==============================] - 0s 12us/step - loss: 35513192074.8089 - val_loss: 40987678146.5600 Epoch 98/200 18000/18000 [==============================] - 0s 11us/step - loss: 35420576619.6338 - val_loss: 40920484282.3680 Epoch 99/200 18000/18000 [==============================] - 0s 11us/step - loss: 35349878811.3067 - val_loss: 40858422837.2480 Epoch 100/200 18000/18000 [==============================] - 0s 12us/step - loss: 35263009479.7938 - val_loss: 40782295302.1440 Epoch 101/200 18000/18000 [==============================] - 0s 12us/step - loss: 35188018318.9049 - val_loss: 40695475666.9440 Epoch 102/200 18000/18000 [==============================] - 0s 12us/step - loss: 35094649547.4347 - val_loss: 40589422854.1440 Epoch 103/200 18000/18000 [==============================] - 0s 12us/step - loss: 35030873797.0631 - val_loss: 40532539834.3680 Epoch 104/200 18000/18000 [==============================] - 0s 12us/step - loss: 34941361824.6542 - val_loss: 40445707354.1120 Epoch 105/200 18000/18000 [==============================] - 0s 12us/step - loss: 34875362002.7164 - val_loss: 40372683702.2720 Epoch 106/200 18000/18000 [==============================] - 0s 12us/step - loss: 34801925383.0542 - val_loss: 40293627822.0800 Epoch 107/200 18000/18000 [==============================] - 0s 12us/step - loss: 34740944914.2044 - val_loss: 40232055275.5200 Epoch 108/200 18000/18000 [==============================] - 0s 12us/step - loss: 34671356710.4569 - val_loss: 40199075725.3120 Epoch 109/200 18000/18000 [==============================] - 0s 12us/step - loss: 34603361945.3724 - val_loss: 40129020493.8240 Epoch 110/200 18000/18000 [==============================] - 0s 12us/step - loss: 34540628758.9831 - val_loss: 40064682721.2800 Epoch 111/200 18000/18000 [==============================] - 0s 12us/step - loss: 34478302221.6533 - val_loss: 39999905398.7840 Epoch 112/200 18000/18000 [==============================] - 0s 12us/step - loss: 34424151026.3467 - val_loss: 39946603134.9760 Epoch 113/200 18000/18000 [==============================] - 0s 11us/step - loss: 34350522548.2240 - val_loss: 39869459628.0320 Epoch 114/200 18000/18000 [==============================] - 0s 11us/step - loss: 34293735635.1716 - val_loss: 39808236847.1040 Epoch 115/200 18000/18000 [==============================] - 0s 11us/step - loss: 34235366901.5324 - val_loss: 39718557646.8480 Epoch 116/200 18000/18000 [==============================] - 0s 11us/step - loss: 34184416892.2453 - val_loss: 39678572363.7760 Epoch 117/200 18000/18000 [==============================] - 0s 12us/step - loss: 34140378854.7413 - val_loss: 39588100669.4400 Epoch 118/200 18000/18000 [==============================] - 0s 13us/step - loss: 34081494005.9876 - val_loss: 39570870108.1600 Epoch 119/200 18000/18000 [==============================] - 0s 12us/step - loss: 34034455769.5431 - val_loss: 39493161254.9120 Epoch 120/200 18000/18000 [==============================] - 0s 12us/step - loss: 33986731443.9964 - val_loss: 39435902451.7120 Epoch 121/200 18000/18000 [==============================] - 0s 12us/step - loss: 33928106806.8409 - val_loss: 39386770636.8000 Epoch 122/200 18000/18000 [==============================] - 0s 13us/step - loss: 33890774086.0871 - val_loss: 39336803696.6400 Epoch 123/200 18000/18000 [==============================] - 0s 12us/step - loss: 33837027029.4471 - val_loss: 39311237513.2160 Epoch 124/200 18000/18000 [==============================] - 0s 12us/step - loss: 33790312047.5022 - val_loss: 39268650778.6240 Epoch 125/200 18000/18000 [==============================] - 0s 11us/step - loss: 33744856614.6844 - val_loss: 39220975042.5600 Epoch 126/200 18000/18000 [==============================] - 0s 10us/step - loss: 33708920902.9973 - val_loss: 39168369328.1280 Epoch 127/200 18000/18000 [==============================] - 0s 10us/step - loss: 33664118831.3316 - val_loss: 39107614572.5440 Epoch 128/200 18000/18000 [==============================] - 0s 11us/step - loss: 33618047434.7520 - val_loss: 39077930663.9360 Epoch 129/200 18000/18000 [==============================] - 0s 13us/step - loss: 33579016670.7769 - val_loss: 39000030150.6560 Epoch 130/200 18000/18000 [==============================] - 0s 12us/step - loss: 33535163312.8107 - val_loss: 38973689102.3360 Epoch 131/200 18000/18000 [==============================] - 0s 12us/step - loss: 33492335205.4898 - val_loss: 38930244927.4880 Epoch 132/200 18000/18000 [==============================] - 0s 12us/step - loss: 33455017304.9742 - val_loss: 38909504585.7280 Epoch 133/200 18000/18000 [==============================] - 0s 12us/step - loss: 33410613950.6916 - val_loss: 38849598160.8960 Epoch 134/200 18000/18000 [==============================] - 0s 12us/step - loss: 33375177029.8596 - val_loss: 38805699493.8880 Epoch 135/200 18000/18000 [==============================] - 0s 13us/step - loss: 33335135123.6836 - val_loss: 38765521666.0480 Epoch 136/200 18000/18000 [==============================] - 0s 13us/step - loss: 33302001097.8418 - val_loss: 38731508088.8320 Epoch 137/200 18000/18000 [==============================] - 0s 13us/step - loss: 33272129013.5324 - val_loss: 38691386785.7920 Epoch 138/200 18000/18000 [==============================] - 0s 12us/step - loss: 33235998062.8196 - val_loss: 38653477912.5760 Epoch 139/200 18000/18000 [==============================] - 0s 13us/step - loss: 33192606025.5004 - val_loss: 38581751644.1600 Epoch 140/200 18000/18000 [==============================] - 0s 12us/step - loss: 33160514983.2533 - val_loss: 38569467052.0320 Epoch 141/200 18000/18000 [==============================] - 0s 11us/step - loss: 33130229130.1262 - val_loss: 38560806535.1680 Epoch 142/200 18000/18000 [==============================] - 0s 13us/step - loss: 33097339705.5716 - val_loss: 38533460557.8240 Epoch 143/200 18000/18000 [==============================] - 0s 12us/step - loss: 33071230875.8756 - val_loss: 38499154231.2960 Epoch 144/200 18000/18000 [==============================] - 0s 12us/step - loss: 33035680088.0640 - val_loss: 38425215172.6080 Epoch 145/200 18000/18000 [==============================] - 0s 12us/step - loss: 33002553438.6631 - val_loss: 38392848777.2160 Epoch 146/200 18000/18000 [==============================] - 0s 12us/step - loss: 32988974998.4142 - val_loss: 38361419939.8400 Epoch 147/200 18000/18000 [==============================] - 0s 12us/step - loss: 32941554934.6702 - val_loss: 38362186940.4160 Epoch 148/200 18000/18000 [==============================] - 0s 13us/step - loss: 32918950730.8658 - val_loss: 38352234151.9360 Epoch 149/200 18000/18000 [==============================] - 0s 12us/step - loss: 32880421586.7164 - val_loss: 38287552675.8400 Epoch 150/200 18000/18000 [==============================] - 0s 12us/step - loss: 32854975978.6098 - val_loss: 38253683376.1280 Epoch 151/200 18000/18000 [==============================] - 0s 13us/step - loss: 32840697178.7947 - val_loss: 38210115403.7760 Epoch 152/200 18000/18000 [==============================] - 0s 13us/step - loss: 32803013911.4382 - val_loss: 38197209858.0480 Epoch 153/200 18000/18000 [==============================] - 0s 13us/step - loss: 32776528858.6809 - val_loss: 38171726905.3440 Epoch 154/200 18000/18000 [==============================] - 0s 14us/step - loss: 32748213445.5182 - val_loss: 38138094190.5920 Epoch 155/200 18000/18000 [==============================] - 0s 13us/step - loss: 32722838243.1004 - val_loss: 38122217734.1440 Epoch 156/200 18000/18000 [==============================] - 0s 13us/step - loss: 32695236014.5351 - val_loss: 38068723449.8560 Epoch 157/200 18000/18000 [==============================] - 0s 13us/step - loss: 32670382154.6382 - val_loss: 38065923162.1120 Epoch 158/200 18000/18000 [==============================] - 0s 13us/step - loss: 32645579341.8240 - val_loss: 37994074636.2880 Epoch 159/200 18000/18000 [==============================] - 0s 13us/step - loss: 32624472003.9253 - val_loss: 37982525947.9040 Epoch 160/200 18000/18000 [==============================] - 0s 12us/step - loss: 32597628986.2542 - val_loss: 37980290088.9600 Epoch 161/200 18000/18000 [==============================] - 0s 12us/step - loss: 32567088693.2480 - val_loss: 37934505525.2480 Epoch 162/200 18000/18000 [==============================] - 0s 13us/step - loss: 32546711400.9031 - val_loss: 37949333405.6960 Epoch 163/200 18000/18000 [==============================] - 0s 13us/step - loss: 32516446144.2844 - val_loss: 37929517776.8960 Epoch 164/200 18000/18000 [==============================] - 0s 13us/step - loss: 32502933589.5609 - val_loss: 37870684536.8320 Epoch 165/200 18000/18000 [==============================] - 0s 12us/step - loss: 32481144615.3671 - val_loss: 37861278351.3600 Epoch 166/200 18000/18000 [==============================] - 0s 13us/step - loss: 32453420915.8258 - val_loss: 37832754200.5760 Epoch 167/200 18000/18000 [==============================] - 0s 14us/step - loss: 32430444946.3182 - val_loss: 37816830328.8320 Epoch 168/200 18000/18000 [==============================] - 0s 13us/step - loss: 32408308675.0151 - val_loss: 37782546350.0800 Epoch 169/200 18000/18000 [==============================] - 0s 13us/step - loss: 32385081331.2569 - val_loss: 37786984120.3200 Epoch 170/200 18000/18000 [==============================] - 0s 13us/step - loss: 32365805653.5609 - val_loss: 37741922549.7600 Epoch 171/200 18000/18000 [==============================] - 0s 13us/step - loss: 32349541994.0409 - val_loss: 37729805271.0400 Epoch 172/200 18000/18000 [==============================] - 0s 13us/step - loss: 32322018574.3360 - val_loss: 37718481600.5120 Epoch 173/200 18000/18000 [==============================] - 0s 14us/step - loss: 32296829794.5316 - val_loss: 37701888802.8160 Epoch 174/200 18000/18000 [==============================] - 0s 15us/step - loss: 32277643309.5111 - val_loss: 37663694651.3920 Epoch 175/200 18000/18000 [==============================] - 0s 13us/step - loss: 32269726715.4489 - val_loss: 37674866638.8480 Epoch 176/200 18000/18000 [==============================] - 0s 13us/step - loss: 32233154066.6596 - val_loss: 37626876854.2720 Epoch 177/200 18000/18000 [==============================] - 0s 13us/step - loss: 32213190499.4418 - val_loss: 37591130505.2160 Epoch 178/200 18000/18000 [==============================] - 0s 13us/step - loss: 32196344607.1751 - val_loss: 37617813454.8480 Epoch 179/200 18000/18000 [==============================] - 0s 13us/step - loss: 32168589903.6444 - val_loss: 37551676588.0320 Epoch 180/200 18000/18000 [==============================] - 0s 13us/step - loss: 32146972701.1271 - val_loss: 37532002385.9200 Epoch 181/200 18000/18000 [==============================] - 0s 13us/step - loss: 32130249115.4204 - val_loss: 37544678719.4880 Epoch 182/200 18000/18000 [==============================] - 0s 13us/step - loss: 32112177372.2738 - val_loss: 37497368084.4800 Epoch 183/200 18000/18000 [==============================] - 0s 13us/step - loss: 32091575828.4800 - val_loss: 37469483335.6800 Epoch 184/200 18000/18000 [==============================] - 0s 13us/step - loss: 32067664347.1360 - val_loss: 37462552870.9120 Epoch 185/200 18000/18000 [==============================] - 0s 15us/step - loss: 32044462150.9973 - val_loss: 37429701935.1040 Epoch 186/200 18000/18000 [==============================] - 0s 15us/step - loss: 32034467963.7902 - val_loss: 37426921144.3200 Epoch 187/200 18000/18000 [==============================] - 0s 14us/step - loss: 32019949296.7538 - val_loss: 37409924055.0400 Epoch 188/200 18000/18000 [==============================] - 0s 14us/step - loss: 31997113823.6871 - val_loss: 37370300858.3680 Epoch 189/200 18000/18000 [==============================] - 0s 13us/step - loss: 31977750718.2364 - val_loss: 37362002427.9040 Epoch 190/200 18000/18000 [==============================] - 0s 13us/step - loss: 31954116509.6960 - val_loss: 37339767603.2000 Epoch 191/200 18000/18000 [==============================] - 0s 13us/step - loss: 31939885838.7911 - val_loss: 37316951769.0880 Epoch 192/200 18000/18000 [==============================] - 0s 13us/step - loss: 31924599555.8684 - val_loss: 37286352683.0080 Epoch 193/200 18000/18000 [==============================] - 0s 13us/step - loss: 31895322201.6569 - val_loss: 37303470850.0480 Epoch 194/200 18000/18000 [==============================] - 0s 13us/step - loss: 31877078220.8000 - val_loss: 37286238158.8480 Epoch 195/200 18000/18000 [==============================] - 0s 13us/step - loss: 31859688972.2880 - val_loss: 37263179186.1760 Epoch 196/200 18000/18000 [==============================] - 0s 12us/step - loss: 31845225469.2693 - val_loss: 37228672647.1680 Epoch 197/200 18000/18000 [==============================] - 0s 13us/step - loss: 31821257150.0089 - val_loss: 37222641401.8560 Epoch 198/200 18000/18000 [==============================] - 0s 12us/step - loss: 31811658725.6036 - val_loss: 37176441765.8880 Epoch 199/200 18000/18000 [==============================] - 0s 12us/step - loss: 31781443567.6160 - val_loss: 37216355942.4000 Epoch 200/200 18000/18000 [==============================] - 0s 13us/step - loss: 31768730311.7938 - val_loss: 37173094449.1520 0.6651870143377775 ###Markdown In the future, consider standardizing outputs as well Regularize:* Heavily parameterized models like neural networks are prone to overfitting* Popular off-the-shelf tools exist to regularize models and prevent overfitting: - L2 regularization (weight decay) - Dropout - Batch normalization These tools come as standard Keras/TF layers!`model.add(keras.layers.Dropout(rate)``model.add(keras.layers.ActivityRegularization(l1=0.0, l2=0.0)``model.add(keras.layers.BatchNormalization())` Early stopping and model checkpointing: It's unlikely the last iteration is the best, and who knows how long until the thing is converged. Just grab the best validation error. ###Code # Set callback functions to early stop training and save the # best model so far from keras.callbacks import EarlyStopping, ModelCheckpoint callbacks = [EarlyStopping(monitor='val_loss', patience=2), ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)] model = nn_model(layers=[20,20,20]) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=400, callbacks=callbacks, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(f"Model score: {model_score}") plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/400 18000/18000 [==============================] - 1s 74us/step - loss: 416642251358.2080 - val_loss: 456230491127.8080 Epoch 00001: val_loss improved from inf to 456230491127.80798, saving model to best_model.h5 Epoch 2/400 18000/18000 [==============================] - 0s 12us/step - loss: 416175593648.5831 - val_loss: 455115510906.8800 Epoch 00002: val_loss improved from 456230491127.80798 to 455115510906.88000, saving model to best_model.h5 Epoch 3/400 18000/18000 [==============================] - 0s 11us/step - loss: 414236468168.4764 - val_loss: 451725259702.2720 Epoch 00003: val_loss improved from 455115510906.88000 to 451725259702.27197, saving model to best_model.h5 Epoch 4/400 18000/18000 [==============================] - 0s 12us/step - loss: 409652313427.5129 - val_loss: 444793102532.6080 Epoch 00004: val_loss improved from 451725259702.27197 to 444793102532.60797, saving model to best_model.h5 Epoch 5/400 18000/18000 [==============================] - 0s 11us/step - loss: 401502478940.3876 - val_loss: 433555929300.9920 Epoch 00005: val_loss improved from 444793102532.60797 to 433555929300.99200, saving model to best_model.h5 Epoch 6/400 18000/18000 [==============================] - 0s 14us/step - loss: 389127931691.0080 - val_loss: 417407007195.1360 Epoch 00006: val_loss improved from 433555929300.99200 to 417407007195.13599, saving model to best_model.h5 Epoch 7/400 18000/18000 [==============================] - 0s 14us/step - loss: 372354871401.5858 - val_loss: 396453596364.8000 Epoch 00007: val_loss improved from 417407007195.13599 to 396453596364.79999, saving model to best_model.h5 Epoch 8/400 18000/18000 [==============================] - 0s 11us/step - loss: 351261101246.2365 - val_loss: 370822052315.1360 Epoch 00008: val_loss improved from 396453596364.79999 to 370822052315.13599, saving model to best_model.h5 Epoch 9/400 18000/18000 [==============================] - 0s 13us/step - loss: 326316790761.2444 - val_loss: 341345543389.1840 Epoch 00009: val_loss improved from 370822052315.13599 to 341345543389.18402, saving model to best_model.h5 Epoch 10/400 18000/18000 [==============================] - 0s 15us/step - loss: 298425331511.7511 - val_loss: 309198200242.1760 Epoch 00010: val_loss improved from 341345543389.18402 to 309198200242.17603, saving model to best_model.h5 Epoch 11/400 18000/18000 [==============================] - 0s 14us/step - loss: 268705647005.2409 - val_loss: 275747260858.3680 Epoch 00011: val_loss improved from 309198200242.17603 to 275747260858.36798, saving model to best_model.h5 Epoch 12/400 18000/18000 [==============================] - 0s 11us/step - loss: 238421556796.5298 - val_loss: 242600971730.9440 Epoch 00012: val_loss improved from 275747260858.36798 to 242600971730.94400, saving model to best_model.h5 Epoch 13/400 18000/18000 [==============================] - 0s 11us/step - loss: 208827929067.5200 - val_loss: 210544567123.9680 Epoch 00013: val_loss improved from 242600971730.94400 to 210544567123.96799, saving model to best_model.h5 Epoch 14/400 18000/18000 [==============================] - 0s 11us/step - loss: 181250766609.5218 - val_loss: 181239822417.9200 Epoch 00014: val_loss improved from 210544567123.96799 to 181239822417.92001, saving model to best_model.h5 Epoch 15/400 18000/18000 [==============================] - 0s 11us/step - loss: 156734730928.1280 - val_loss: 155991138369.5360 Epoch 00015: val_loss improved from 181239822417.92001 to 155991138369.53601, saving model to best_model.h5 Epoch 16/400 18000/18000 [==============================] - ETA: 0s - loss: 138017311735.09 - 0s 11us/step - loss: 135798981525.5040 - val_loss: 134988053086.2080 Epoch 00016: val_loss improved from 155991138369.53601 to 134988053086.20799, saving model to best_model.h5 Epoch 17/400 18000/18000 [==============================] - 0s 15us/step - loss: 118836078000.3556 - val_loss: 118353070260.2240 Epoch 00017: val_loss improved from 134988053086.20799 to 118353070260.22400, saving model to best_model.h5 Epoch 18/400 18000/18000 [==============================] - 0s 12us/step - loss: 105603678346.3538 - val_loss: 105883129348.0960 Epoch 00018: val_loss improved from 118353070260.22400 to 105883129348.09599, saving model to best_model.h5 Epoch 19/400 18000/18000 [==============================] - 0s 10us/step - loss: 95745313909.4187 - val_loss: 96829833609.2160 Epoch 00019: val_loss improved from 105883129348.09599 to 96829833609.21600, saving model to best_model.h5 Epoch 20/400 18000/18000 [==============================] - 0s 11us/step - loss: 88618352621.7956 - val_loss: 90346775052.2880 Epoch 00020: val_loss improved from 96829833609.21600 to 90346775052.28799, saving model to best_model.h5 Epoch 21/400 18000/18000 [==============================] - 0s 10us/step - loss: 83567574355.5129 - val_loss: 85874045485.0560 Epoch 00021: val_loss improved from 90346775052.28799 to 85874045485.05600, saving model to best_model.h5 Epoch 22/400 18000/18000 [==============================] - 0s 10us/step - loss: 79998094813.8667 - val_loss: 82761349857.2800 Epoch 00022: val_loss improved from 85874045485.05600 to 82761349857.28000, saving model to best_model.h5 Epoch 23/400 18000/18000 [==============================] - 0s 12us/step - loss: 77425343874.8444 - val_loss: 80483269541.8880 Epoch 00023: val_loss improved from 82761349857.28000 to 80483269541.88800, saving model to best_model.h5 Epoch 24/400 18000/18000 [==============================] - 0s 11us/step - loss: 75462087511.6089 - val_loss: 78729282191.3600 Epoch 00024: val_loss improved from 80483269541.88800 to 78729282191.36000, saving model to best_model.h5 Epoch 25/400 18000/18000 [==============================] - 0s 10us/step - loss: 73870388468.8498 - val_loss: 77273078038.5280 Epoch 00025: val_loss improved from 78729282191.36000 to 77273078038.52800, saving model to best_model.h5 Epoch 26/400 18000/18000 [==============================] - 0s 10us/step - loss: 72516323071.3173 - val_loss: 75994380828.6720 Epoch 00026: val_loss improved from 77273078038.52800 to 75994380828.67200, saving model to best_model.h5 Epoch 27/400 18000/18000 [==============================] - 0s 11us/step - loss: 71323900251.7049 - val_loss: 74852082581.5040 Epoch 00027: val_loss improved from 75994380828.67200 to 74852082581.50400, saving model to best_model.h5 Epoch 28/400 18000/18000 [==============================] - 0s 11us/step - loss: 70227146804.7929 - val_loss: 73817158909.9520 Epoch 00028: val_loss improved from 74852082581.50400 to 73817158909.95200, saving model to best_model.h5 Epoch 29/400 18000/18000 [==============================] - 0s 11us/step - loss: 69211586836.7076 - val_loss: 72820976910.3360 Epoch 00029: val_loss improved from 73817158909.95200 to 72820976910.33600, saving model to best_model.h5 Epoch 30/400 18000/18000 [==============================] - 0s 10us/step - loss: 68253316495.5876 - val_loss: 71868724150.2720 Epoch 00030: val_loss improved from 72820976910.33600 to 71868724150.27200, saving model to best_model.h5 Epoch 31/400 18000/18000 [==============================] - 0s 11us/step - loss: 67342146957.7671 - val_loss: 70966434824.1920 Epoch 00031: val_loss improved from 71868724150.27200 to 70966434824.19200, saving model to best_model.h5 Epoch 32/400 18000/18000 [==============================] - 0s 10us/step - loss: 66443596828.2169 - val_loss: 70082538242.0480 Epoch 00032: val_loss improved from 70966434824.19200 to 70082538242.04800, saving model to best_model.h5 Epoch 33/400 18000/18000 [==============================] - 0s 11us/step - loss: 65572032122.4249 - val_loss: 69227643109.3760 Epoch 00033: val_loss improved from 70082538242.04800 to 69227643109.37601, saving model to best_model.h5 Epoch 34/400 18000/18000 [==============================] - 0s 10us/step - loss: 64735541992.5618 - val_loss: 68379734900.7360 Epoch 00034: val_loss improved from 69227643109.37601 to 68379734900.73600, saving model to best_model.h5 Epoch 35/400 18000/18000 [==============================] - 0s 10us/step - loss: 63888829455.4738 - val_loss: 67542714089.4720 Epoch 00035: val_loss improved from 68379734900.73600 to 67542714089.47200, saving model to best_model.h5 Epoch 36/400 18000/18000 [==============================] - 0s 11us/step - loss: 63058047835.2498 - val_loss: 66706866110.4640 Epoch 00036: val_loss improved from 67542714089.47200 to 66706866110.46400, saving model to best_model.h5 Epoch 37/400 18000/18000 [==============================] - 0s 11us/step - loss: 62235788523.7476 - val_loss: 65874906316.8000 Epoch 00037: val_loss improved from 66706866110.46400 to 65874906316.80000, saving model to best_model.h5 Epoch 38/400 18000/18000 [==============================] - 0s 9us/step - loss: 61422055413.0773 - val_loss: 65048028676.0960 Epoch 00038: val_loss improved from 65874906316.80000 to 65048028676.09600, saving model to best_model.h5 Epoch 39/400 18000/18000 [==============================] - 0s 10us/step - loss: 60599847682.0480 - val_loss: 64214742892.5440 Epoch 00039: val_loss improved from 65048028676.09600 to 64214742892.54400, saving model to best_model.h5 Epoch 40/400 18000/18000 [==============================] - 0s 9us/step - loss: 59780959221.9876 - val_loss: 63386770505.7280 Epoch 00040: val_loss improved from 64214742892.54400 to 63386770505.72800, saving model to best_model.h5 Epoch 41/400 18000/18000 [==============================] - 0s 11us/step - loss: 58964683500.2027 - val_loss: 62554961117.1840 Epoch 00041: val_loss improved from 63386770505.72800 to 62554961117.18400, saving model to best_model.h5 Epoch 42/400 18000/18000 [==============================] - 0s 9us/step - loss: 58138298537.3013 - val_loss: 61735717634.0480 Epoch 00042: val_loss improved from 62554961117.18400 to 61735717634.04800, saving model to best_model.h5 Epoch 43/400 18000/18000 [==============================] - 0s 9us/step - loss: 57323855722.7236 - val_loss: 60914490802.1760 Epoch 00043: val_loss improved from 61735717634.04800 to 60914490802.17600, saving model to best_model.h5 Epoch 44/400 18000/18000 [==============================] - 0s 10us/step - loss: 56503696352.1422 - val_loss: 60096960069.6320 Epoch 00044: val_loss improved from 60914490802.17600 to 60096960069.63200, saving model to best_model.h5 Epoch 45/400 18000/18000 [==============================] - 0s 9us/step - loss: 55668120533.2196 - val_loss: 59280067788.8000 Epoch 00045: val_loss improved from 60096960069.63200 to 59280067788.80000, saving model to best_model.h5 Epoch 46/400 18000/18000 [==============================] - 0s 10us/step - loss: 54842026473.6996 - val_loss: 58457415778.3040 Epoch 00046: val_loss improved from 59280067788.80000 to 58457415778.30400, saving model to best_model.h5 Epoch 47/400 18000/18000 [==============================] - 0s 9us/step - loss: 54010812614.4284 - val_loss: 57647501213.6960 Epoch 00047: val_loss improved from 58457415778.30400 to 57647501213.69600, saving model to best_model.h5 Epoch 48/400 18000/18000 [==============================] - 0s 10us/step - loss: 53177819831.4098 - val_loss: 56829615800.3200 Epoch 00048: val_loss improved from 57647501213.69600 to 56829615800.32000, saving model to best_model.h5 Epoch 49/400 18000/18000 [==============================] - 0s 9us/step - loss: 52360600900.9493 - val_loss: 56027553169.4080 Epoch 00049: val_loss improved from 56829615800.32000 to 56027553169.40800, saving model to best_model.h5 Epoch 50/400 18000/18000 [==============================] - 0s 9us/step - loss: 51520948746.4676 - val_loss: 55215088926.7200 Epoch 00050: val_loss improved from 56027553169.40800 to 55215088926.72000, saving model to best_model.h5 Epoch 51/400 18000/18000 [==============================] - 0s 9us/step - loss: 50697004821.1627 - val_loss: 54416942628.8640 Epoch 00051: val_loss improved from 55215088926.72000 to 54416942628.86400, saving model to best_model.h5 Epoch 52/400 18000/18000 [==============================] - 0s 9us/step - loss: 49875405404.3876 - val_loss: 53624083316.7360 Epoch 00052: val_loss improved from 54416942628.86400 to 53624083316.73600, saving model to best_model.h5 Epoch 53/400 18000/18000 [==============================] - 0s 9us/step - loss: 49051193566.0942 - val_loss: 52843989532.6720 Epoch 00053: val_loss improved from 53624083316.73600 to 52843989532.67200, saving model to best_model.h5 Epoch 54/400 18000/18000 [==============================] - 0s 10us/step - loss: 48227908357.6889 - val_loss: 52055709745.1520 Epoch 00054: val_loss improved from 52843989532.67200 to 52055709745.15200, saving model to best_model.h5 Epoch 55/400 18000/18000 [==============================] - 0s 9us/step - loss: 47403340121.8844 - val_loss: 51286491725.8240 Epoch 00055: val_loss improved from 52055709745.15200 to 51286491725.82400, saving model to best_model.h5 Epoch 56/400 18000/18000 [==============================] - 0s 9us/step - loss: 46613951727.3885 - val_loss: 50534507249.6640 Epoch 00056: val_loss improved from 51286491725.82400 to 50534507249.66400, saving model to best_model.h5 Epoch 57/400 18000/18000 [==============================] - 0s 9us/step - loss: 45824541298.2329 - val_loss: 49813665021.9520 Epoch 00057: val_loss improved from 50534507249.66400 to 49813665021.95200, saving model to best_model.h5 Epoch 58/400 18000/18000 [==============================] - 0s 10us/step - loss: 45071834655.4027 - val_loss: 49112425070.5920 Epoch 00058: val_loss improved from 49813665021.95200 to 49112425070.59200, saving model to best_model.h5 Epoch 59/400 18000/18000 [==============================] - 0s 10us/step - loss: 44345352439.5804 - val_loss: 48432106635.2640 Epoch 00059: val_loss improved from 49112425070.59200 to 48432106635.26400, saving model to best_model.h5 Epoch 60/400 18000/18000 [==============================] - 0s 11us/step - loss: 43661941178.3680 - val_loss: 47821221199.8720 Epoch 00060: val_loss improved from 48432106635.26400 to 47821221199.87200, saving model to best_model.h5 Epoch 61/400 18000/18000 [==============================] - 0s 11us/step - loss: 43024287771.3067 - val_loss: 47246677344.2560 Epoch 00061: val_loss improved from 47821221199.87200 to 47246677344.25600, saving model to best_model.h5 Epoch 62/400 18000/18000 [==============================] - 0s 11us/step - loss: 42434092837.5467 - val_loss: 46741821325.3120 Epoch 00062: val_loss improved from 47246677344.25600 to 46741821325.31200, saving model to best_model.h5 Epoch 63/400 18000/18000 [==============================] - 0s 11us/step - loss: 41892284414.1796 - val_loss: 46289688592.3840 Epoch 00063: val_loss improved from 46741821325.31200 to 46289688592.38400, saving model to best_model.h5 Epoch 64/400 18000/18000 [==============================] - 0s 11us/step - loss: 41396230582.7271 - val_loss: 45897796452.3520 Epoch 00064: val_loss improved from 46289688592.38400 to 45897796452.35200, saving model to best_model.h5 Epoch 65/400 18000/18000 [==============================] - 0s 11us/step - loss: 40957934294.3573 - val_loss: 45518593884.1600 Epoch 00065: val_loss improved from 45897796452.35200 to 45518593884.16000, saving model to best_model.h5 Epoch 66/400 18000/18000 [==============================] - 0s 11us/step - loss: 40559064143.1893 - val_loss: 45203121700.8640 Epoch 00066: val_loss improved from 45518593884.16000 to 45203121700.86400, saving model to best_model.h5 Epoch 67/400 18000/18000 [==============================] - 0s 11us/step - loss: 40185660833.7920 - val_loss: 44915859357.6960 Epoch 00067: val_loss improved from 45203121700.86400 to 44915859357.69600, saving model to best_model.h5 Epoch 68/400 18000/18000 [==============================] - 0s 11us/step - loss: 39866041088.2276 - val_loss: 44656491364.3520 Epoch 00068: val_loss improved from 44915859357.69600 to 44656491364.35200, saving model to best_model.h5 Epoch 69/400 18000/18000 [==============================] - 0s 11us/step - loss: 39548505059.7831 - val_loss: 44428516720.6400 Epoch 00069: val_loss improved from 44656491364.35200 to 44428516720.64000, saving model to best_model.h5 Epoch 70/400 18000/18000 [==============================] - 0s 13us/step - loss: 39269333139.4560 - val_loss: 44217486540.8000 Epoch 00070: val_loss improved from 44428516720.64000 to 44217486540.80000, saving model to best_model.h5 Epoch 71/400 18000/18000 [==============================] - 0s 12us/step - loss: 39018746580.5369 - val_loss: 44027694514.1760 Epoch 00071: val_loss improved from 44217486540.80000 to 44027694514.17600, saving model to best_model.h5 Epoch 72/400 18000/18000 [==============================] - 0s 12us/step - loss: 38775277986.7022 - val_loss: 43818001956.8640 Epoch 00072: val_loss improved from 44027694514.17600 to 43818001956.86400, saving model to best_model.h5 Epoch 73/400 18000/18000 [==============================] - 0s 11us/step - loss: 38536078988.6293 - val_loss: 43646061936.6400 Epoch 00073: val_loss improved from 43818001956.86400 to 43646061936.64000, saving model to best_model.h5 Epoch 74/400 18000/18000 [==============================] - 0s 12us/step - loss: 38323034567.1111 - val_loss: 43454754029.5680 Epoch 00074: val_loss improved from 43646061936.64000 to 43454754029.56800, saving model to best_model.h5 Epoch 75/400 18000/18000 [==============================] - 0s 14us/step - loss: 38116566543.0187 - val_loss: 43281596088.3200 Epoch 00075: val_loss improved from 43454754029.56800 to 43281596088.32000, saving model to best_model.h5 Epoch 76/400 18000/18000 [==============================] - 0s 13us/step - loss: 37925072677.5467 - val_loss: 43158784114.6880 Epoch 00076: val_loss improved from 43281596088.32000 to 43158784114.68800, saving model to best_model.h5 Epoch 77/400 18000/18000 [==============================] - 0s 14us/step - loss: 37730638750.6062 - val_loss: 43000789401.6000 Epoch 00077: val_loss improved from 43158784114.68800 to 43000789401.60000, saving model to best_model.h5 Epoch 78/400 18000/18000 [==============================] - 0s 14us/step - loss: 37545695324.8427 - val_loss: 42832945938.4320 Epoch 00078: val_loss improved from 43000789401.60000 to 42832945938.43200, saving model to best_model.h5 Epoch 79/400 18000/18000 [==============================] - 0s 14us/step - loss: 37369545315.6693 - val_loss: 42689178435.5840 Epoch 00079: val_loss improved from 42832945938.43200 to 42689178435.58400, saving model to best_model.h5 Epoch 80/400 18000/18000 [==============================] - 0s 14us/step - loss: 37213279251.1147 - val_loss: 42551691640.8320 Epoch 00080: val_loss improved from 42689178435.58400 to 42551691640.83200, saving model to best_model.h5 Epoch 81/400 18000/18000 [==============================] - 0s 14us/step - loss: 37043436697.8276 - val_loss: 42367208062.9760 Epoch 00081: val_loss improved from 42551691640.83200 to 42367208062.97600, saving model to best_model.h5 Epoch 82/400 18000/18000 [==============================] - 0s 14us/step - loss: 36883514381.6533 - val_loss: 42236606906.3680 Epoch 00082: val_loss improved from 42367208062.97600 to 42236606906.36800, saving model to best_model.h5 Epoch 83/400 18000/18000 [==============================] - 0s 16us/step - loss: 36728396828.2169 - val_loss: 42110056824.8320 Epoch 00083: val_loss improved from 42236606906.36800 to 42110056824.83200, saving model to best_model.h5 Epoch 84/400 18000/18000 [==============================] - 0s 15us/step - loss: 36585878292.2524 - val_loss: 41972454588.4160 Epoch 00084: val_loss improved from 42110056824.83200 to 41972454588.41600, saving model to best_model.h5 Epoch 85/400 18000/18000 [==============================] - 0s 14us/step - loss: 36449368939.6338 - val_loss: 41817125093.3760 Epoch 00085: val_loss improved from 41972454588.41600 to 41817125093.37600, saving model to best_model.h5 Epoch 86/400 18000/18000 [==============================] - 0s 13us/step - loss: 36307057457.3796 - val_loss: 41719629086.7200 Epoch 00086: val_loss improved from 41817125093.37600 to 41719629086.72000, saving model to best_model.h5 Epoch 87/400 18000/18000 [==============================] - 0s 14us/step - loss: 36177432406.6987 - val_loss: 41587646824.4480 Epoch 00087: val_loss improved from 41719629086.72000 to 41587646824.44800, saving model to best_model.h5 Epoch 88/400 18000/18000 [==============================] - 0s 13us/step - loss: 36051885424.6400 - val_loss: 41470138187.7760 Epoch 00088: val_loss improved from 41587646824.44800 to 41470138187.77600, saving model to best_model.h5 Epoch 89/400 18000/18000 [==============================] - 0s 12us/step - loss: 35921624032.1422 - val_loss: 41352127283.2000 Epoch 00089: val_loss improved from 41470138187.77600 to 41352127283.20000, saving model to best_model.h5 Epoch 90/400 18000/18000 [==============================] - 0s 12us/step - loss: 35803357944.9458 - val_loss: 41223586906.1120 Epoch 00090: val_loss improved from 41352127283.20000 to 41223586906.11200, saving model to best_model.h5 Epoch 91/400 18000/18000 [==============================] - 0s 12us/step - loss: 35698335460.0107 - val_loss: 41139544326.1440 Epoch 00091: val_loss improved from 41223586906.11200 to 41139544326.14400, saving model to best_model.h5 Epoch 92/400 18000/18000 [==============================] - 0s 13us/step - loss: 35580043815.5947 - val_loss: 40976475979.7760 Epoch 00092: val_loss improved from 41139544326.14400 to 40976475979.77600, saving model to best_model.h5 Epoch 93/400 18000/18000 [==============================] - 0s 12us/step - loss: 35472793399.7511 - val_loss: 40878393982.9760 Epoch 00093: val_loss improved from 40976475979.77600 to 40878393982.97600, saving model to best_model.h5 Epoch 94/400 18000/18000 [==============================] - 0s 14us/step - loss: 35391152721.4649 - val_loss: 40774588203.0080 Epoch 00094: val_loss improved from 40878393982.97600 to 40774588203.00800, saving model to best_model.h5 Epoch 95/400 18000/18000 [==============================] - 0s 13us/step - loss: 35303738239.6587 - val_loss: 40658617303.0400 Epoch 00095: val_loss improved from 40774588203.00800 to 40658617303.04000, saving model to best_model.h5 Epoch 96/400 18000/18000 [==============================] - 0s 13us/step - loss: 35182854244.1245 - val_loss: 40588689539.0720 Epoch 00096: val_loss improved from 40658617303.04000 to 40588689539.07200, saving model to best_model.h5 Epoch 97/400 18000/18000 [==============================] - 0s 12us/step - loss: 35105872498.2329 - val_loss: 40501942091.7760 Epoch 00097: val_loss improved from 40588689539.07200 to 40501942091.77600, saving model to best_model.h5 Epoch 98/400 18000/18000 [==============================] - 0s 12us/step - loss: 35005353741.8809 - val_loss: 40411219787.7760 Epoch 00098: val_loss improved from 40501942091.77600 to 40411219787.77600, saving model to best_model.h5 Epoch 99/400 18000/18000 [==============================] - 0s 12us/step - loss: 34931741385.6142 - val_loss: 40335295021.0560 Epoch 00099: val_loss improved from 40411219787.77600 to 40335295021.05600, saving model to best_model.h5 Epoch 100/400 18000/18000 [==============================] - 0s 12us/step - loss: 34849365062.0871 - val_loss: 40204030836.7360 Epoch 00100: val_loss improved from 40335295021.05600 to 40204030836.73600, saving model to best_model.h5 Epoch 101/400 18000/18000 [==============================] - 0s 12us/step - loss: 34763294721.8204 - val_loss: 40149693136.8960 Epoch 00101: val_loss improved from 40204030836.73600 to 40149693136.89600, saving model to best_model.h5 Epoch 102/400 18000/18000 [==============================] - 0s 13us/step - loss: 34689906591.5164 - val_loss: 40099296378.8800 Epoch 00102: val_loss improved from 40149693136.89600 to 40099296378.88000, saving model to best_model.h5 Epoch 103/400 18000/18000 [==============================] - 0s 12us/step - loss: 34619039079.5378 - val_loss: 40023661019.1360 Epoch 00103: val_loss improved from 40099296378.88000 to 40023661019.13600, saving model to best_model.h5 Epoch 104/400 18000/18000 [==============================] - 0s 12us/step - loss: 34541981688.7182 - val_loss: 39974522781.6960 Epoch 00104: val_loss improved from 40023661019.13600 to 39974522781.69600, saving model to best_model.h5 Epoch 105/400 18000/18000 [==============================] - 0s 12us/step - loss: 34475419067.2782 - val_loss: 39880520302.5920 Epoch 00105: val_loss improved from 39974522781.69600 to 39880520302.59200, saving model to best_model.h5 Epoch 106/400 18000/18000 [==============================] - 0s 12us/step - loss: 34409279844.8071 - val_loss: 39797475049.4720 Epoch 00106: val_loss improved from 39880520302.59200 to 39797475049.47200, saving model to best_model.h5 Epoch 107/400 18000/18000 [==============================] - 0s 11us/step - loss: 34347008436.9067 - val_loss: 39678428577.7920 Epoch 00107: val_loss improved from 39797475049.47200 to 39678428577.79200, saving model to best_model.h5 Epoch 108/400 18000/18000 [==============================] - 0s 11us/step - loss: 34287083181.3973 - val_loss: 39658844979.2000 Epoch 00108: val_loss improved from 39678428577.79200 to 39658844979.20000, saving model to best_model.h5 Epoch 109/400 18000/18000 [==============================] - 0s 11us/step - loss: 34224641645.6818 - val_loss: 39636056375.2960 Epoch 00109: val_loss improved from 39658844979.20000 to 39636056375.29600, saving model to best_model.h5 Epoch 110/400 18000/18000 [==============================] - 0s 11us/step - loss: 34163118793.6142 - val_loss: 39521863106.5600 Epoch 00110: val_loss improved from 39636056375.29600 to 39521863106.56000, saving model to best_model.h5 Epoch 111/400 18000/18000 [==============================] - 0s 11us/step - loss: 34101883917.6533 - val_loss: 39476215676.9280 Epoch 00111: val_loss improved from 39521863106.56000 to 39476215676.92800, saving model to best_model.h5 Epoch 112/400 18000/18000 [==============================] - 0s 11us/step - loss: 34054626374.0871 - val_loss: 39423951536.1280 Epoch 00112: val_loss improved from 39476215676.92800 to 39423951536.12800, saving model to best_model.h5 Epoch 113/400 18000/18000 [==============================] - 0s 11us/step - loss: 33996209076.4516 - val_loss: 39335197966.3360 Epoch 00113: val_loss improved from 39423951536.12800 to 39335197966.33600, saving model to best_model.h5 Epoch 114/400 18000/18000 [==============================] - 0s 11us/step - loss: 33945380321.5076 - val_loss: 39317181071.3600 Epoch 00114: val_loss improved from 39335197966.33600 to 39317181071.36000, saving model to best_model.h5 Epoch 115/400 18000/18000 [==============================] - 0s 13us/step - loss: 33895051136.5689 - val_loss: 39271611039.7440 Epoch 00115: val_loss improved from 39317181071.36000 to 39271611039.74400, saving model to best_model.h5 Epoch 116/400 18000/18000 [==============================] - 0s 12us/step - loss: 33847080067.0720 - val_loss: 39208574779.3920 Epoch 00116: val_loss improved from 39271611039.74400 to 39208574779.39200, saving model to best_model.h5 Epoch 117/400 18000/18000 [==============================] - 0s 11us/step - loss: 33808622234.2827 - val_loss: 39153998528.5120 Epoch 00117: val_loss improved from 39208574779.39200 to 39153998528.51200, saving model to best_model.h5 Epoch 118/400 18000/18000 [==============================] - 0s 12us/step - loss: 33750373105.6640 - val_loss: 39077553963.0080 Epoch 00118: val_loss improved from 39153998528.51200 to 39077553963.00800, saving model to best_model.h5 Epoch 119/400 18000/18000 [==============================] - 0s 15us/step - loss: 33713382945.2231 - val_loss: 39070849368.0640 Epoch 00119: val_loss improved from 39077553963.00800 to 39070849368.06400, saving model to best_model.h5 Epoch 120/400 18000/18000 [==============================] - 0s 14us/step - loss: 33671119437.8240 - val_loss: 39037835870.2080 Epoch 00120: val_loss improved from 39070849368.06400 to 39037835870.20800, saving model to best_model.h5 Epoch 121/400 18000/18000 [==============================] - 0s 14us/step - loss: 33622327783.8791 - val_loss: 38955241504.7680 Epoch 00121: val_loss improved from 39037835870.20800 to 38955241504.76800, saving model to best_model.h5 Epoch 122/400 18000/18000 [==============================] - 0s 14us/step - loss: 33578996141.6249 - val_loss: 38900926939.1360 Epoch 00122: val_loss improved from 38955241504.76800 to 38900926939.13600, saving model to best_model.h5 Epoch 123/400 18000/18000 [==============================] - 0s 14us/step - loss: 33536964597.0773 - val_loss: 38876731932.6720 Epoch 00123: val_loss improved from 38900926939.13600 to 38876731932.67200, saving model to best_model.h5 Epoch 124/400 18000/18000 [==============================] - 0s 14us/step - loss: 33500475932.6720 - val_loss: 38860265717.7600 Epoch 00124: val_loss improved from 38876731932.67200 to 38860265717.76000, saving model to best_model.h5 Epoch 125/400 18000/18000 [==============================] - 0s 14us/step - loss: 33464907260.8142 - val_loss: 38826009624.5760 Epoch 00125: val_loss improved from 38860265717.76000 to 38826009624.57600, saving model to best_model.h5 Epoch 126/400 18000/18000 [==============================] - 0s 14us/step - loss: 33434713070.7058 - val_loss: 38759668842.4960 Epoch 00126: val_loss improved from 38826009624.57600 to 38759668842.49600, saving model to best_model.h5 Epoch 127/400 18000/18000 [==============================] - 0s 13us/step - loss: 33394509862.2293 - val_loss: 38714550321.1520 Epoch 00127: val_loss improved from 38759668842.49600 to 38714550321.15200, saving model to best_model.h5 Epoch 128/400 18000/18000 [==============================] - 0s 14us/step - loss: 33357455727.7298 - val_loss: 38705615634.4320 Epoch 00128: val_loss improved from 38714550321.15200 to 38705615634.43200, saving model to best_model.h5 Epoch 129/400 18000/18000 [==============================] - 0s 14us/step - loss: 33322727991.9787 - val_loss: 38642503909.3760 Epoch 00129: val_loss improved from 38705615634.43200 to 38642503909.37600, saving model to best_model.h5 Epoch 130/400 18000/18000 [==============================] - 0s 13us/step - loss: 33286661217.3938 - val_loss: 38597904498.6880 Epoch 00130: val_loss improved from 38642503909.37600 to 38597904498.68800, saving model to best_model.h5 Epoch 131/400 18000/18000 [==============================] - 0s 14us/step - loss: 33252904674.1902 - val_loss: 38588660449.2800 Epoch 00131: val_loss improved from 38597904498.68800 to 38588660449.28000, saving model to best_model.h5 Epoch 132/400 18000/18000 [==============================] - 0s 14us/step - loss: 33224918514.8018 - val_loss: 38529613234.1760 Epoch 00132: val_loss improved from 38588660449.28000 to 38529613234.17600, saving model to best_model.h5 Epoch 133/400 18000/18000 [==============================] - 0s 14us/step - loss: 33190210593.6782 - val_loss: 38498867806.2080 Epoch 00133: val_loss improved from 38529613234.17600 to 38498867806.20800, saving model to best_model.h5 Epoch 134/400 18000/18000 [==============================] - 0s 14us/step - loss: 33166816781.1982 - val_loss: 38446092615.6800 Epoch 00134: val_loss improved from 38498867806.20800 to 38446092615.68000, saving model to best_model.h5 Epoch 135/400 18000/18000 [==============================] - 0s 13us/step - loss: 33130609457.3796 - val_loss: 38429994188.8000 Epoch 00135: val_loss improved from 38446092615.68000 to 38429994188.80000, saving model to best_model.h5 Epoch 136/400 18000/18000 [==============================] - 0s 14us/step - loss: 33119490135.3813 - val_loss: 38455079927.8080 Epoch 00136: val_loss did not improve from 38429994188.80000 Epoch 137/400 18000/18000 [==============================] - 0s 15us/step - loss: 33075230091.9467 - val_loss: 38360250580.9920 Epoch 00137: val_loss improved from 38429994188.80000 to 38360250580.99200, saving model to best_model.h5 Epoch 138/400 18000/18000 [==============================] - 0s 16us/step - loss: 33050356289.0809 - val_loss: 38310647627.7760 Epoch 00138: val_loss improved from 38360250580.99200 to 38310647627.77600, saving model to best_model.h5 Epoch 139/400 18000/18000 [==============================] - 0s 14us/step - loss: 33017948624.2133 - val_loss: 38306381004.8000 Epoch 00139: val_loss improved from 38310647627.77600 to 38306381004.80000, saving model to best_model.h5 Epoch 140/400 18000/18000 [==============================] - 0s 14us/step - loss: 32989488866.1902 - val_loss: 38296360091.6480 Epoch 00140: val_loss improved from 38306381004.80000 to 38296360091.64800, saving model to best_model.h5 Epoch 141/400 18000/18000 [==============================] - 0s 13us/step - loss: 32979157902.2222 - val_loss: 38283316002.8160 Epoch 00141: val_loss improved from 38296360091.64800 to 38283316002.81600, saving model to best_model.h5 Epoch 142/400 18000/18000 [==============================] - 0s 14us/step - loss: 32936257102.7342 - val_loss: 38207856377.8560 Epoch 00142: val_loss improved from 38283316002.81600 to 38207856377.85600, saving model to best_model.h5 Epoch 143/400 18000/18000 [==============================] - 0s 13us/step - loss: 32926904334.5636 - val_loss: 38199855087.6160 Epoch 00143: val_loss improved from 38207856377.85600 to 38199855087.61600, saving model to best_model.h5 Epoch 144/400 18000/18000 [==============================] - 0s 14us/step - loss: 32887741881.4578 - val_loss: 38198765125.6320 Epoch 00144: val_loss improved from 38199855087.61600 to 38198765125.63200, saving model to best_model.h5 Epoch 145/400 18000/18000 [==============================] - 0s 13us/step - loss: 32866151701.6178 - val_loss: 38168843452.4160 Epoch 00145: val_loss improved from 38198765125.63200 to 38168843452.41600, saving model to best_model.h5 Epoch 146/400 18000/18000 [==============================] - 0s 13us/step - loss: 32844073466.0836 - val_loss: 38104048435.2000 Epoch 00146: val_loss improved from 38168843452.41600 to 38104048435.20000, saving model to best_model.h5 Epoch 147/400 18000/18000 [==============================] - 0s 14us/step - loss: 32823448882.7449 - val_loss: 38084934664.1920 Epoch 00147: val_loss improved from 38104048435.20000 to 38084934664.19200, saving model to best_model.h5 Epoch 148/400 18000/18000 [==============================] - 0s 14us/step - loss: 32799449681.4649 - val_loss: 38072868339.7120 Epoch 00148: val_loss improved from 38084934664.19200 to 38072868339.71200, saving model to best_model.h5 Epoch 149/400 18000/18000 [==============================] - 0s 13us/step - loss: 32772458883.7547 - val_loss: 38065437343.7440 Epoch 00149: val_loss improved from 38072868339.71200 to 38065437343.74400, saving model to best_model.h5 Epoch 150/400 18000/18000 [==============================] - 0s 13us/step - loss: 32751987806.6631 - val_loss: 38008082759.6800 Epoch 00150: val_loss improved from 38065437343.74400 to 38008082759.68000, saving model to best_model.h5 Epoch 151/400 18000/18000 [==============================] - 0s 14us/step - loss: 32732362072.9742 - val_loss: 37986270773.2480 Epoch 00151: val_loss improved from 38008082759.68000 to 37986270773.24800, saving model to best_model.h5 Epoch 152/400 18000/18000 [==============================] - 0s 13us/step - loss: 32714497126.8551 - val_loss: 37978890764.2880 Epoch 00152: val_loss improved from 37986270773.24800 to 37978890764.28800, saving model to best_model.h5 Epoch 153/400 18000/18000 [==============================] - 0s 14us/step - loss: 32686127815.7938 - val_loss: 37992514650.1120 Epoch 00153: val_loss did not improve from 37978890764.28800 Epoch 154/400 18000/18000 [==============================] - 0s 14us/step - loss: 32670563933.2978 - val_loss: 37929588064.2560 Epoch 00154: val_loss improved from 37978890764.28800 to 37929588064.25600, saving model to best_model.h5 Epoch 155/400 18000/18000 [==============================] - 0s 13us/step - loss: 32643100182.3004 - val_loss: 37923952721.9200 Epoch 00155: val_loss improved from 37929588064.25600 to 37923952721.92000, saving model to best_model.h5 Epoch 156/400 18000/18000 [==============================] - 0s 16us/step - loss: 32639153899.2924 - val_loss: 37904727080.9600 Epoch 00156: val_loss improved from 37923952721.92000 to 37904727080.96000, saving model to best_model.h5 Epoch 157/400 18000/18000 [==============================] - 0s 14us/step - loss: 32613794944.3413 - val_loss: 37936861806.5920 Epoch 00157: val_loss did not improve from 37904727080.96000 Epoch 158/400 18000/18000 [==============================] - 0s 15us/step - loss: 32586484540.3022 - val_loss: 37883475689.4720 Epoch 00158: val_loss improved from 37904727080.96000 to 37883475689.47200, saving model to best_model.h5 Epoch 159/400 18000/18000 [==============================] - 0s 13us/step - loss: 32579593554.6027 - val_loss: 37853698523.1360 Epoch 00159: val_loss improved from 37883475689.47200 to 37853698523.13600, saving model to best_model.h5 Epoch 160/400 18000/18000 [==============================] - 0s 14us/step - loss: 32548355480.6898 - val_loss: 37833799860.2240 Epoch 00160: val_loss improved from 37853698523.13600 to 37833799860.22400, saving model to best_model.h5 Epoch 161/400 18000/18000 [==============================] - 0s 13us/step - loss: 32538943182.1653 - val_loss: 37796682727.4240 Epoch 00161: val_loss improved from 37833799860.22400 to 37796682727.42400, saving model to best_model.h5 Epoch 162/400 18000/18000 [==============================] - 0s 13us/step - loss: 32507544910.0516 - val_loss: 37774902165.5040 Epoch 00162: val_loss improved from 37796682727.42400 to 37774902165.50400, saving model to best_model.h5 Epoch 163/400 18000/18000 [==============================] - 0s 13us/step - loss: 32493366933.7316 - val_loss: 37761643053.0560 Epoch 00163: val_loss improved from 37774902165.50400 to 37761643053.05600, saving model to best_model.h5 Epoch 164/400 18000/18000 [==============================] - 0s 12us/step - loss: 32475281315.1573 - val_loss: 37785489571.8400 Epoch 00164: val_loss did not improve from 37761643053.05600 Epoch 165/400 18000/18000 [==============================] - 0s 13us/step - loss: 32457725282.0764 - val_loss: 37763269394.4320 Epoch 00165: val_loss did not improve from 37761643053.05600 Model score: 0.6731525788821355 ###Markdown TensorFlow & Keras - Basics of Deep Learning Most importantly... resourceshttps://www.tensorflow.org/api_docshttps://keras.io/https://www.tensorflow.org/tutorials/https://www.google.com TF overview* "End-to-end machine learning platform" - Not the only one! Check out PyTorch, Theano, Cognitive Toolkit. * Integrates with high-level APIs like Keras* Plays nice with Pandas* Makes deep learning *fast* and *easy* * *"easy" Tasks for TensorFlow:* Regression - Predict house prices - Predict drug metabolic rates - Predict stock trends * *this is super hard * Classification - Cat or dog? - Malignant or benign cancer from images ![](media/dr.png) Google AI Blog: Diabetic Retinopathy* Dimensionality reduction - Visualize high-dimensional data in 2 or 3-D space - Compress representations for successive ML* Generative models - Create new molecules with desirable properties - Artificially enhance image resolution ![](media/molecular_gan.png) Kadurin et al., 2017* Reinforcement learning - Can't beat your friends at chess? Make your computer do it* Much more... - Generic math - Probabilistic programming with TFP - Automatic differentiation - ... Let's Regress Imports! ###Code import numpy as np import pandas as pd ###Output _____no_output_____ ###Markdown Name a more iconic duo, I'll wait New imports -- TF and Keras ###Code import keras import tensorflow as tf ###Output C:\Anaconda\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Using TensorFlow backend. ###Markdown Check our versions for good measure -- these programs may have very different behavior version-to-version ###Code print(keras.__version__) print(tf.__version__) ###Output 2.2.4 1.12.0 ###Markdown Loading in housing data as with SKLearn ###Code data = pd.read_csv('kc_house_data.csv') data data["yr_built"].unique() column_selection = ["bedrooms","bathrooms","sqft_living","sqft_lot", "floors","condition","grade","sqft_above", "sqft_basement","sqft_living15","sqft_lot15", "lat", "long","yr_built","yr_renovated","waterfront"] selected_feature = np.array(data[column_selection]) price = np.array(data["price"]) selected_feature_train = selected_feature[:20000] price_train = price[:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] def score(y,y_pred): return np.mean(np.abs(y-y_pred)/y) model = keras.Sequential() input_len = len(column_selection) model.add(keras.layers.Dense(50, input_dim=input_len, activation='relu')) model.add(keras.layers.Dense(50, activation='relu')) model.add(keras.layers.Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128) preds = model.predict(selected_feature_test) score(preds, price_test) ###Output _____no_output_____ ###Markdown Like SKLearn, it's easy to train and evaluate simple models. ... but we should try to do better Practical Deep Learning -- What you need to know Train, Validation, Test: * Optimize parameters with Train (weights, biases) * Optimize hyperparameters with Validation (layer width & depth, activation functions, etc.) * Optimize NOTHING with Test ###Code # Split out a validation set for hyperparameter optimization selected_feature_train = selected_feature[:18000] price_train = price[:18000] selected_feature_val = selected_feature[18000:20000] price_val = price[18000:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] ###Output _____no_output_____ ###Markdown Try a hyperparameter optimization: Try three activation functions to use for dense layers in the neural network above. Save the model that achieves the best validation loss Hint: [activation functions](http://letmegooglethat.com/?q=keras+activation+functions) Hint: `model.fit` has argument "`validation_data`" which takes a tuple of features and targets Hint: Use `model.save("filename.h5")` to save a model locally. If you want to use it later, just call `keras.models.load_model("filename.h5")` ###Code # For easy looping, define neural network model as a function def nn_model(optimizer='adam', activation='relu', layers=[20,20], loss='mean_squared_error'): model = keras.Sequential() model.add(keras.layers.Dense(50, input_dim=input_len, activation=activ)) model.add(keras.layers.Dense(50, activation=activ)) model.add(keras.layers.Dense(1)) model.compile(loss='mean_absolute_error', optimizer='adam') return model best_score = 1000.0 # bad # loop over chosen activation functions, train, evaluate on validation for activ in ['sigmoid', 'tanh', 'relu']: model = nn_model(activation=activ) history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) if model_score < best_score: best_score = model_score best_activ = activ best_model = model best_train = history print(f"BEST ACTIVATION FUNCTION {best_activ} WITH SCORE {best_score}") best_model.save("awesome_model.h5") ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 31us/step - loss: 532974.0115 - val_loss: 557914.0565 Epoch 2/50 18000/18000 [==============================] - 0s 10us/step - loss: 532966.4315 - val_loss: 557907.7440 Epoch 3/50 18000/18000 [==============================] - 0s 10us/step - loss: 532960.4552 - val_loss: 557902.0385 Epoch 4/50 18000/18000 [==============================] - 0s 10us/step - loss: 532954.8337 - val_loss: 557896.6045 Epoch 5/50 18000/18000 [==============================] - 0s 10us/step - loss: 532949.3721 - val_loss: 557891.0965 Epoch 6/50 18000/18000 [==============================] - 0s 11us/step - loss: 532943.7817 - val_loss: 557885.2920 Epoch 7/50 18000/18000 [==============================] - 0s 10us/step - loss: 532938.0435 - val_loss: 557879.6830 Epoch 8/50 18000/18000 [==============================] - 0s 10us/step - loss: 532932.4725 - val_loss: 557874.1570 Epoch 9/50 18000/18000 [==============================] - 0s 10us/step - loss: 532926.9642 - val_loss: 557868.6770 Epoch 10/50 18000/18000 [==============================] - 0s 10us/step - loss: 532921.4915 - val_loss: 557863.1610 Epoch 11/50 18000/18000 [==============================] - 0s 10us/step - loss: 532916.0389 - val_loss: 557857.7420 Epoch 12/50 18000/18000 [==============================] - 0s 10us/step - loss: 532910.6117 - val_loss: 557852.3100 Epoch 13/50 18000/18000 [==============================] - 0s 10us/step - loss: 532905.1918 - val_loss: 557846.8370 Epoch 14/50 18000/18000 [==============================] - 0s 10us/step - loss: 532899.7812 - val_loss: 557841.6045 Epoch 15/50 18000/18000 [==============================] - 0s 10us/step - loss: 532894.3781 - val_loss: 557836.1210 Epoch 16/50 18000/18000 [==============================] - 0s 10us/step - loss: 532888.9848 - val_loss: 557830.7190 Epoch 17/50 18000/18000 [==============================] - 0s 10us/step - loss: 532883.5964 - val_loss: 557825.3100 Epoch 18/50 18000/18000 [==============================] - 0s 10us/step - loss: 532878.2143 - val_loss: 557819.8590 Epoch 19/50 18000/18000 [==============================] - 0s 10us/step - loss: 532872.8313 - val_loss: 557814.6165 Epoch 20/50 18000/18000 [==============================] - 0s 10us/step - loss: 532867.4610 - val_loss: 557809.1750 Epoch 21/50 18000/18000 [==============================] - 0s 11us/step - loss: 532862.0847 - val_loss: 557803.7820 Epoch 22/50 18000/18000 [==============================] - 0s 11us/step - loss: 532856.7184 - val_loss: 557798.3910 Epoch 23/50 18000/18000 [==============================] - 0s 10us/step - loss: 532851.3425 - val_loss: 557793.0965 Epoch 24/50 18000/18000 [==============================] - 0s 10us/step - loss: 532845.9747 - val_loss: 557787.7190 Epoch 25/50 18000/18000 [==============================] - 0s 10us/step - loss: 532840.6135 - val_loss: 557782.3140 Epoch 26/50 18000/18000 [==============================] - 0s 10us/step - loss: 532835.2472 - val_loss: 557776.8650 Epoch 27/50 18000/18000 [==============================] - 0s 10us/step - loss: 532829.8720 - val_loss: 557771.6770 Epoch 28/50 18000/18000 [==============================] - 0s 11us/step - loss: 532824.5156 - val_loss: 557766.2240 Epoch 29/50 18000/18000 [==============================] - 0s 10us/step - loss: 532819.1571 - val_loss: 557760.8125 Epoch 30/50 18000/18000 [==============================] - 0s 10us/step - loss: 532813.7879 - val_loss: 557755.6125 Epoch 31/50 18000/18000 [==============================] - 0s 10us/step - loss: 532808.4271 - val_loss: 557750.1610 Epoch 32/50 18000/18000 [==============================] - 0s 10us/step - loss: 532803.0678 - val_loss: 557744.7680 Epoch 33/50 18000/18000 [==============================] - 0s 11us/step - loss: 532797.7111 - val_loss: 557739.3910 Epoch 34/50 18000/18000 [==============================] - 0s 10us/step - loss: 532792.3457 - val_loss: 557734.0965 Epoch 35/50 18000/18000 [==============================] - 0s 10us/step - loss: 532786.9829 - val_loss: 557728.7420 Epoch 36/50 18000/18000 [==============================] - 0s 10us/step - loss: 532781.6269 - val_loss: 557723.3160 Epoch 37/50 18000/18000 [==============================] - 0s 10us/step - loss: 532776.2653 - val_loss: 557717.8690 Epoch 38/50 18000/18000 [==============================] - 0s 10us/step - loss: 532770.9041 - val_loss: 557712.6810 Epoch 39/50 18000/18000 [==============================] - 0s 10us/step - loss: 532765.5489 - val_loss: 557707.2920 Epoch 40/50 18000/18000 [==============================] - 0s 11us/step - loss: 532760.1891 - val_loss: 557701.8570 Epoch 41/50 18000/18000 [==============================] - 0s 10us/step - loss: 532754.8321 - val_loss: 557696.6165 Epoch 42/50 18000/18000 [==============================] - 0s 10us/step - loss: 532749.4747 - val_loss: 557691.1790 Epoch 43/50 18000/18000 [==============================] - 0s 11us/step - loss: 532744.1129 - val_loss: 557685.7840 Epoch 44/50 18000/18000 [==============================] - 0s 11us/step - loss: 532738.7598 - val_loss: 557680.6045 Epoch 45/50 18000/18000 [==============================] - 0s 10us/step - loss: 532733.3988 - val_loss: 557675.1570 Epoch 46/50 18000/18000 [==============================] - 0s 10us/step - loss: 532728.0400 - val_loss: 557669.7480 Epoch 47/50 18000/18000 [==============================] - ETA: 0s - loss: 532702.63 - 0s 10us/step - loss: 532722.6843 - val_loss: 557664.3870 Epoch 48/50 18000/18000 [==============================] - 0s 10us/step - loss: 532717.3249 - val_loss: 557659.0945 Epoch 49/50 18000/18000 [==============================] - 0s 10us/step - loss: 532711.9656 - val_loss: 557653.7170 Epoch 50/50 18000/18000 [==============================] - 0s 10us/step - loss: 532706.6133 - val_loss: 557648.3140 Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 0s 24us/step - loss: 532970.1318 - val_loss: 557909.2725 Epoch 2/50 18000/18000 [==============================] - 0s 10us/step - loss: 532960.9386 - val_loss: 557901.5785 Epoch 3/50 18000/18000 [==============================] - 0s 10us/step - loss: 532953.3493 - val_loss: 557894.0385 Epoch 4/50 18000/18000 [==============================] - 0s 10us/step - loss: 532945.9204 - val_loss: 557886.6870 Epoch 5/50 18000/18000 [==============================] - 0s 10us/step - loss: 532938.5780 - val_loss: 557879.3140 Epoch 6/50 18000/18000 [==============================] - 0s 10us/step - loss: 532931.2692 - val_loss: 557872.0885 Epoch 7/50 18000/18000 [==============================] - 0s 10us/step - loss: 532923.9883 - val_loss: 557864.7460 Epoch 8/50 18000/18000 [==============================] - 0s 10us/step - loss: 532916.7349 - val_loss: 557857.6045 Epoch 9/50 18000/18000 [==============================] - 0s 10us/step - loss: 532909.4831 - val_loss: 557850.2620 Epoch 10/50 18000/18000 [==============================] - 0s 10us/step - loss: 532902.2473 - val_loss: 557843.0885 Epoch 11/50 18000/18000 [==============================] - 0s 10us/step - loss: 532895.0113 - val_loss: 557835.7840 Epoch 12/50 18000/18000 [==============================] - 0s 11us/step - loss: 532887.7956 - val_loss: 557828.6510 Epoch 13/50 18000/18000 [==============================] - 0s 10us/step - loss: 532880.5834 - val_loss: 557821.3265 Epoch 14/50 18000/18000 [==============================] - 0s 10us/step - loss: 532873.3627 - val_loss: 557814.1610 Epoch 15/50 18000/18000 [==============================] - 0s 10us/step - loss: 532866.1591 - val_loss: 557806.8590 Epoch 16/50 18000/18000 [==============================] - 0s 10us/step - loss: 532858.9509 - val_loss: 557799.7420 Epoch 17/50 18000/18000 [==============================] - 0s 10us/step - loss: 532851.7448 - val_loss: 557792.6145 Epoch 18/50 18000/18000 [==============================] - 0s 11us/step - loss: 532844.5419 - val_loss: 557785.3140 Epoch 19/50 18000/18000 [==============================] - 0s 12us/step - loss: 532837.3457 - val_loss: 557778.1610 Epoch 20/50 ###Markdown Visualize your training: ###Code import matplotlib.pyplot as plt # plot loss during training def plot_loss(hist): %matplotlib inline plt.title('Training Curve') plt.plot(hist.history['loss'], label='train') plt.plot(hist.history['val_loss'], label='validation') plt.xlabel("Epochs") plt.ylabel("Mean squared error") plt.legend() plt.show() plot_loss(best_train) ###Output _____no_output_____ ###Markdown In the future, try better validation schemes like [k-fold cross validation](https://chrisalbon.com/deep_learning/keras/k-fold_cross-validating_neural_networks/), though 80/20 or 90/10 train/val like this works in a pinch Standardize your features:* Typically assumes normally distributed feature, shifting mean to 0 and standard deviation to 1* In theory does not matter for neural networks* In practice tends to matter for neural networks* Scale if using: - Logistic regression - Support vector machines - Perceptrons - Neural networks - Principle component analysis* Don't bother if using: - "Forest" methods - Naive Bayes ###Code from sklearn.preprocessing import StandardScaler # Instantiate StandardScaler in_scaler = StandardScaler() # Fit scaler to the training set and perform the transformation selected_feature_train = in_scaler.fit_transform(selected_feature_train) # Use the fitted scaler to transform validation and test features selected_feature_val = in_scaler.transform(selected_feature_val) selected_feature_test = in_scaler.transform(selected_feature_test) # Check appropriate scaling print(np.mean(selected_feature_train[:,0])) print(np.std(selected_feature_train[:,0])) print(np.mean(selected_feature_val[:,0])) print(np.std(selected_feature_val[:,0])) print(np.mean(selected_feature_test[:,0])) print(np.std(selected_feature_test[:,0])) model = nn_model() model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=200, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(model_score) plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/200 18000/18000 [==============================] - 1s 30us/step - loss: 416643360664.2347 - val_loss: 456226459090.9440 Epoch 2/200 18000/18000 [==============================] - 0s 10us/step - loss: 416175119983.5022 - val_loss: 455096928829.4401 Epoch 3/200 18000/18000 [==============================] - 0s 10us/step - loss: 414325133541.3760 - val_loss: 451825760731.1359 Epoch 4/200 18000/18000 [==============================] - 0s 10us/step - loss: 410124513735.1111 - val_loss: 445473112981.5040 Epoch 5/200 18000/18000 [==============================] - 0s 11us/step - loss: 402882324099.5271 - val_loss: 435331354329.0880 Epoch 6/200 18000/18000 [==============================] - 0s 10us/step - loss: 391998989372.9849 - val_loss: 420808691810.3040 Epoch 7/200 18000/18000 [==============================] - 0s 10us/step - loss: 377252354399.3458 - val_loss: 401978543308.8000 Epoch 8/200 18000/18000 [==============================] - 0s 10us/step - loss: 358771684627.7974 - val_loss: 379162710769.6640 Epoch 9/200 18000/18000 [==============================] - 0s 10us/step - loss: 336863679101.1555 - val_loss: 352851277381.6320 Epoch 10/200 18000/18000 [==============================] - 0s 10us/step - loss: 312167480018.7164 - val_loss: 323778086699.0080 Epoch 11/200 18000/18000 [==============================] - 0s 10us/step - loss: 285482632231.1395 - val_loss: 292908206391.2960 Epoch 12/200 18000/18000 [==============================] - 0s 10us/step - loss: 257900540650.3822 - val_loss: 261877699706.8800 Epoch 13/200 18000/18000 [==============================] - 0s 11us/step - loss: 230439534956.0889 - val_loss: 231827165806.5920 Epoch 14/200 18000/18000 [==============================] - 0s 10us/step - loss: 204230289755.7049 - val_loss: 203510794944.5120 Epoch 15/200 18000/18000 [==============================] - 0s 11us/step - loss: 180171257282.5600 - val_loss: 178228993720.3200 Epoch 16/200 18000/18000 [==============================] - 0s 10us/step - loss: 158859801220.4373 - val_loss: 156422493044.7360 Epoch 17/200 18000/18000 [==============================] - 0s 10us/step - loss: 140660142425.8845 - val_loss: 138249369092.0960 Epoch 18/200 18000/18000 [==============================] - 0s 10us/step - loss: 125589164647.3102 - val_loss: 123814903939.0720 Epoch 19/200 18000/18000 [==============================] - 0s 10us/step - loss: 113501671595.1218 - val_loss: 112468381204.4800 Epoch 20/200 18000/18000 [==============================] - 0s 11us/step - loss: 104093540628.7076 - val_loss: 103961095700.4800 Epoch 21/200 18000/18000 [==============================] - 0s 10us/step - loss: 96870897294.4498 - val_loss: 97507325378.5600 Epoch 22/200 18000/18000 [==============================] - 0s 10us/step - loss: 91388252200.0498 - val_loss: 92750705197.0560 Epoch 23/200 18000/18000 [==============================] - 0s 10us/step - loss: 87164592739.6693 - val_loss: 89085560487.9360 Epoch 24/200 18000/18000 [==============================] - 0s 10us/step - loss: 83875793644.2027 - val_loss: 86196380237.8240 Epoch 25/200 18000/18000 [==============================] - 0s 10us/step - loss: 81264161499.8187 - val_loss: 83851038294.0160 Epoch 26/200 18000/18000 [==============================] - 0s 10us/step - loss: 79161698010.9084 - val_loss: 81938899927.0400 Epoch 27/200 18000/18000 [==============================] - 0s 11us/step - loss: 77409837128.8178 - val_loss: 80284049276.9280 Epoch 28/200 18000/18000 [==============================] - 0s 10us/step - loss: 75907892911.2178 - val_loss: 78857053732.8640 Epoch 29/200 18000/18000 [==============================] - 0s 10us/step - loss: 74593363758.6489 - val_loss: 77589748056.0640 Epoch 30/200 18000/18000 [==============================] - 0s 11us/step - loss: 73434448862.3218 - val_loss: 76440567676.9280 Epoch 31/200 18000/18000 [==============================] - 0s 11us/step - loss: 72388591382.9831 - val_loss: 75392780075.0080 Epoch 32/200 18000/18000 [==============================] - 0s 10us/step - loss: 71415718102.8124 - val_loss: 74433648132.0960 Epoch 33/200 18000/18000 [==============================] - 0s 10us/step - loss: 70519953901.3404 - val_loss: 73519545221.1200 Epoch 34/200 18000/18000 [==============================] - 0s 10us/step - loss: 69664263299.9822 - val_loss: 72658094981.1200 Epoch 35/200 18000/18000 [==============================] - 0s 10us/step - loss: 68847307299.9538 - val_loss: 71832857411.5840 Epoch 36/200 18000/18000 [==============================] - 0s 11us/step - loss: 68061245123.2427 - val_loss: 71055667036.1600 Epoch 37/200 18000/18000 [==============================] - 0s 10us/step - loss: 67297847898.5671 - val_loss: 70295621206.0160 Epoch 38/200 18000/18000 [==============================] - 0s 11us/step - loss: 66548314690.9013 - val_loss: 69544804155.3920 Epoch 39/200 18000/18000 [==============================] - 0s 11us/step - loss: 65802287433.5004 - val_loss: 68800373522.4320 Epoch 40/200 18000/18000 [==============================] - 0s 10us/step - loss: 65073398211.4702 - val_loss: 68096687341.5680 Epoch 41/200 18000/18000 [==============================] - 0s 11us/step - loss: 64344636143.8436 - val_loss: 67376283156.4800 Epoch 42/200 18000/18000 [==============================] - 0s 10us/step - loss: 63622377439.2320 - val_loss: 66666608525.3120 Epoch 43/200 18000/18000 [==============================] - 0s 11us/step - loss: 62916118846.5778 - val_loss: 65980831694.8480 Epoch 44/200 18000/18000 [==============================] - 0s 10us/step - loss: 62203820987.7333 - val_loss: 65282057994.2400 Epoch 45/200 18000/18000 [==============================] - 0s 10us/step - loss: 61489272316.8142 - val_loss: 64595847544.8320 Epoch 46/200 18000/18000 [==============================] - 0s 10us/step - loss: 60776852852.2809 - val_loss: 63896474681.3440 Epoch 47/200 18000/18000 [==============================] - 0s 10us/step - loss: 60063808156.1031 - val_loss: 63218145755.1360 Epoch 48/200 18000/18000 [==============================] - 0s 10us/step - loss: 59352234663.0258 - val_loss: 62518026076.1600 Epoch 49/200 18000/18000 [==============================] - 0s 10us/step - loss: 58663435479.7227 - val_loss: 61840687693.8240 Epoch 50/200 18000/18000 [==============================] - 0s 11us/step - loss: 57947576693.1911 - val_loss: 61149969186.8160 Epoch 51/200 18000/18000 [==============================] - 0s 10us/step - loss: 57228263868.1884 - val_loss: 60470712958.9760 Epoch 52/200 18000/18000 [==============================] - 0s 11us/step - loss: 56526551886.5067 - val_loss: 59785181331.4560 Epoch 53/200 18000/18000 [==============================] - 0s 11us/step - loss: 55830205206.0729 - val_loss: 59109734776.8320 Epoch 54/200 18000/18000 [==============================] - 0s 11us/step - loss: 55112070769.3227 - val_loss: 58437222498.3040 Epoch 55/200 18000/18000 [==============================] - 0s 10us/step - loss: 54415164367.7582 - val_loss: 57758560747.5200 Epoch 56/200 18000/18000 [==============================] - 0s 10us/step - loss: 53715308016.0711 - val_loss: 57083334983.6800 Epoch 57/200 18000/18000 [==============================] - 0s 11us/step - loss: 53020278285.1982 - val_loss: 56407620288.5120 Epoch 58/200 18000/18000 [==============================] - 0s 10us/step - loss: 52327839163.2782 - val_loss: 55744691372.0320 Epoch 59/200 18000/18000 [==============================] - 0s 11us/step - loss: 51637411170.0764 - val_loss: 55092800323.5840 Epoch 60/200 18000/18000 [==============================] - 0s 10us/step - loss: 50955147171.1573 - val_loss: 54431102533.6320 Epoch 61/200 18000/18000 [==============================] - 0s 10us/step - loss: 50270661181.4400 - val_loss: 53798340689.9200 Epoch 62/200 18000/18000 [==============================] - 0s 10us/step - loss: 49606753452.0320 - val_loss: 53170362187.7760 Epoch 63/200 18000/18000 [==============================] - 0s 11us/step - loss: 48940280002.7876 - val_loss: 52562962939.9040 Epoch 64/200 18000/18000 [==============================] - 0s 10us/step - loss: 48294432174.5351 - val_loss: 51942451609.6000 ###Markdown In the future, consider standardizing outputs as well Regularize:* Heavily parameterized models like neural networks are prone to overfitting* Popular off-the-shelf tools exist to regularize models and prevent overfitting: - L2 regularization (weight decay) - Dropout - Batch normalization These tools come as standard Keras/TF layers!`model.add(keras.layers.Dropout(rate)``model.add(keras.layers.ActivityRegularization(l1=0.0, l2=0.0)``model.add(keras.layers.BatchNormalization())` Early stopping and model checkpointing: It's unlikely the last iteration is the best, and who knows how long until the thing is converged. Just grab the best validation error. ###Code # Set callback functions to early stop training and save the # best model so far from keras.callbacks import EarlyStopping, ModelCheckpoint callbacks = [EarlyStopping(monitor='val_loss', patience=2), ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)] model = nn_model(layers=[20,20,20]) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=400, callbacks=callbacks, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(f"Model score: {model_score}") plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/400 18000/18000 [==============================] - 1s 33us/step - loss: 416651544421.2622 - val_loss: 456259511517.1840 Epoch 00001: val_loss improved from inf to 456259511517.18402, saving model to best_model.h5 Epoch 2/400 18000/18000 [==============================] - 0s 11us/step - loss: 416275351615.7155 - val_loss: 455326677860.3519 Epoch 00002: val_loss improved from 456259511517.18402 to 455326677860.35199, saving model to best_model.h5 Epoch 3/400 18000/18000 [==============================] - 0s 11us/step - loss: 414689964880.3271 - val_loss: 452503833411.5840 Epoch 00003: val_loss improved from 455326677860.35199 to 452503833411.58398, saving model to best_model.h5 Epoch 4/400 18000/18000 [==============================] - 0s 11us/step - loss: 411070708609.4791 - val_loss: 446986228334.5920 Epoch 00004: val_loss improved from 452503833411.58398 to 446986228334.59198, saving model to best_model.h5 Epoch 5/400 18000/18000 [==============================] - 0s 11us/step - loss: 404691041299.1147 - val_loss: 438088345845.7600 Epoch 00005: val_loss improved from 446986228334.59198 to 438088345845.76001, saving model to best_model.h5 Epoch 6/400 18000/18000 [==============================] - 0s 11us/step - loss: 395193707134.9760 - val_loss: 425492854865.9200 Epoch 00006: val_loss improved from 438088345845.76001 to 425492854865.91998, saving model to best_model.h5 Epoch 7/400 18000/18000 [==============================] - 0s 11us/step - loss: 382342614191.6729 - val_loss: 409169559552.0000 Epoch 00007: val_loss improved from 425492854865.91998 to 409169559552.00000, saving model to best_model.h5 Epoch 8/400 18000/18000 [==============================] - 0s 11us/step - loss: 366015355493.4897 - val_loss: 388959393808.3840 Epoch 00008: val_loss improved from 409169559552.00000 to 388959393808.38397, saving model to best_model.h5 Epoch 9/400 18000/18000 [==============================] - 0s 10us/step - loss: 346449591664.6400 - val_loss: 365161711403.0080 Epoch 00009: val_loss improved from 388959393808.38397 to 365161711403.00800, saving model to best_model.h5 Epoch 10/400 18000/18000 [==============================] - 0s 11us/step - loss: 324079842798.2507 - val_loss: 338854563807.2320 Epoch 00010: val_loss improved from 365161711403.00800 to 338854563807.23199, saving model to best_model.h5 Epoch 11/400 18000/18000 [==============================] - 0s 10us/step - loss: 299622456215.3245 - val_loss: 310327667064.8320 Epoch 00011: val_loss improved from 338854563807.23199 to 310327667064.83197, saving model to best_model.h5 Epoch 12/400 18000/18000 [==============================] - 0s 10us/step - loss: 273810197810.7449 - val_loss: 281015086219.2640 Epoch 00012: val_loss improved from 310327667064.83197 to 281015086219.26398, saving model to best_model.h5 Epoch 13/400 18000/18000 [==============================] - 0s 10us/step - loss: 247658309455.4169 - val_loss: 251876329390.0800 Epoch 00013: val_loss improved from 281015086219.26398 to 251876329390.07999, saving model to best_model.h5 Epoch 14/400 18000/18000 [==============================] - 0s 10us/step - loss: 221969782145.0240 - val_loss: 223936291012.6080 Epoch 00014: val_loss improved from 251876329390.07999 to 223936291012.60800, saving model to best_model.h5 Epoch 15/400 18000/18000 [==============================] - 0s 11us/step - loss: 197645427277.8240 - val_loss: 197799311704.0640 Epoch 00015: val_loss improved from 223936291012.60800 to 197799311704.06400, saving model to best_model.h5 Epoch 16/400 18000/18000 [==============================] - 0s 11us/step - loss: 175316568695.6942 - val_loss: 174281057501.1840 Epoch 00016: val_loss improved from 197799311704.06400 to 174281057501.18399, saving model to best_model.h5 Epoch 17/400 18000/18000 [==============================] - 0s 11us/step - loss: 155461359821.7102 - val_loss: 153989718999.0400 Epoch 00017: val_loss improved from 174281057501.18399 to 153989718999.04001, saving model to best_model.h5 Epoch 18/400 18000/18000 [==============================] - 0s 11us/step - loss: 138388227504.3556 - val_loss: 136791897604.0960 Epoch 00018: val_loss improved from 153989718999.04001 to 136791897604.09599, saving model to best_model.h5 Epoch 19/400 18000/18000 [==============================] - 0s 10us/step - loss: 124003460943.4169 - val_loss: 122836608352.2560 Epoch 00019: val_loss improved from 136791897604.09599 to 122836608352.25600, saving model to best_model.h5 Epoch 20/400 18000/18000 [==============================] - 0s 11us/step - loss: 112310590883.6124 - val_loss: 111870702845.9520 Epoch 00020: val_loss improved from 122836608352.25600 to 111870702845.95200, saving model to best_model.h5 Epoch 21/400 18000/18000 [==============================] - 0s 10us/step - loss: 103110011839.3742 - val_loss: 103343601876.9920 Epoch 00021: val_loss improved from 111870702845.95200 to 103343601876.99200, saving model to best_model.h5 Epoch 22/400 18000/18000 [==============================] - 0s 10us/step - loss: 95954258588.1031 - val_loss: 96986140246.0160 Epoch 00022: val_loss improved from 103343601876.99200 to 96986140246.01601, saving model to best_model.h5 Epoch 23/400 18000/18000 [==============================] - 0s 10us/step - loss: 90434397033.8133 - val_loss: 92076851200.0000 Epoch 00023: val_loss improved from 96986140246.01601 to 92076851200.00000, saving model to best_model.h5 Epoch 24/400 18000/18000 [==============================] - 0s 10us/step - loss: 86121230106.6240 - val_loss: 88317148004.3520 Epoch 00024: val_loss improved from 92076851200.00000 to 88317148004.35201, saving model to best_model.h5 Epoch 25/400 18000/18000 [==============================] - 0s 10us/step - loss: 82706072520.4764 - val_loss: 85273224019.9680 Epoch 00025: val_loss improved from 88317148004.35201 to 85273224019.96800, saving model to best_model.h5 Epoch 26/400 18000/18000 [==============================] - 0s 11us/step - loss: 79954325493.0773 - val_loss: 82783483854.8480 Epoch 00026: val_loss improved from 85273224019.96800 to 82783483854.84801, saving model to best_model.h5 Epoch 27/400 18000/18000 [==============================] - 0s 10us/step - loss: 77693653308.7573 - val_loss: 80722644697.0880 Epoch 00027: val_loss improved from 82783483854.84801 to 80722644697.08800, saving model to best_model.h5 Epoch 28/400 18000/18000 [==============================] - 0s 10us/step - loss: 75807112531.5129 - val_loss: 78950488080.3840 Epoch 00028: val_loss improved from 80722644697.08800 to 78950488080.38400, saving model to best_model.h5 Epoch 29/400 18000/18000 [==============================] - 0s 10us/step - loss: 74205346216.1635 - val_loss: 77438394302.4640 Epoch 00029: val_loss improved from 78950488080.38400 to 77438394302.46400, saving model to best_model.h5 Epoch 30/400 18000/18000 [==============================] - 0s 10us/step - loss: 72839366013.3831 - val_loss: 76100882530.3040 Epoch 00030: val_loss improved from 77438394302.46400 to 76100882530.30400, saving model to best_model.h5 Epoch 31/400 18000/18000 [==============================] - 0s 11us/step - loss: 71630325263.0187 - val_loss: 74927345205.2480 Epoch 00031: val_loss improved from 76100882530.30400 to 74927345205.24800, saving model to best_model.h5 Epoch 32/400 18000/18000 [==============================] - 0s 11us/step - loss: 70559261884.4160 - val_loss: 73853330030.5920 Epoch 00032: val_loss improved from 74927345205.24800 to 73853330030.59200, saving model to best_model.h5 Epoch 33/400 18000/18000 [==============================] - 0s 10us/step - loss: 69578067993.4862 - val_loss: 72866725036.0320 Epoch 00033: val_loss improved from 73853330030.59200 to 72866725036.03200, saving model to best_model.h5 Epoch 34/400 18000/18000 [==============================] - 0s 11us/step - loss: 68685977328.7538 - val_loss: 71949478526.9760 Epoch 00034: val_loss improved from 72866725036.03200 to 71949478526.97600, saving model to best_model.h5 Epoch 35/400 18000/18000 [==============================] - 0s 11us/step - loss: 67829586387.8542 - val_loss: 71087979429.8880 ###Markdown TensorFlow & Keras - Basics of Deep Learning Most importantly... resourceshttps://www.tensorflow.org/api_docshttps://keras.io/https://www.tensorflow.org/tutorials/https://www.google.com TF overview* "End-to-end machine learning platform" - Not the only one! Check out PyTorch, Theano, Cognitive Toolkit. * Integrates with high-level APIs like Keras* Plays nice with Pandas* Makes deep learning *fast* and *easy* * *"easy" Tasks for TensorFlow:* Regression - Predict house prices - Predict drug metabolic rates - Predict stock trends * *this is super hard * Classification - Cat or dog? - Malignant or benign cancer from images ![](media/dr.png) Google AI Blog: Diabetic Retinopathy* Dimensionality reduction - Visualize high-dimensional data in 2 or 3-D space - Compress representations for successive ML* Generative models - Create new molecules with desirable properties - Artificially enhance image resolution ![](media/molecular_gan.png) Kadurin et al., 2017* Reinforcement learning - Can't beat your friends at chess? Make your computer do it* Much more... - Generic math - Probabilistic programming with TFP - Automatic differentiation - ... Let's Regress Imports! ###Code import numpy as np import pandas as pd ###Output _____no_output_____ ###Markdown Name a more iconic duo, I'll wait New imports -- TF and Keras ###Code import keras import tensorflow as tf ###Output Using TensorFlow backend. ###Markdown Check our versions for good measure -- these programs may have very different behavior version-to-version ###Code print(keras.__version__) print(tf.__version__) ###Output 2.2.4 1.13.1 ###Markdown Loading in housing data as with SKLearn ###Code data = pd.read_csv('kc_house_data.csv') data data["yr_built"].unique() column_selection = ["bedrooms","bathrooms","sqft_living","sqft_lot", "floors","condition","grade","sqft_above", "sqft_basement","sqft_living15","sqft_lot15", "lat", "long","yr_built","yr_renovated","waterfront"] selected_feature = np.array(data[column_selection]) price = np.array(data["price"]) selected_feature_train = selected_feature[:20000] price_train = price[:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] def score(y,y_pred): return np.mean(np.abs(y-y_pred)/y) model = keras.Sequential() input_len = len(column_selection) model.add(keras.layers.Dense(50, input_dim=input_len, activation='relu')) model.add(keras.layers.Dense(50, activation='relu')) model.add(keras.layers.Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128) preds = model.predict(selected_feature_test) score(preds, price_test) ###Output _____no_output_____ ###Markdown Like SKLearn, it's easy to train and evaluate simple models. ... but we should try to do better Practical Deep Learning -- What you need to know Train, Validation, Test: * Optimize parameters with Train (weights, biases) * Optimize hyperparameters with Validation (layer width & depth, activation functions, etc.) * Optimize NOTHING with Test ###Code # Split out a validation set for hyperparameter optimization selected_feature_train = selected_feature[:18000] price_train = price[:18000] selected_feature_val = selected_feature[18000:20000] price_val = price[18000:20000] selected_feature_test = selected_feature[20000:] price_test = price[20000:] ###Output _____no_output_____ ###Markdown Try a hyperparameter optimization: Try three activation functions to use for dense layers in the neural network above. Save the model that achieves the best validation loss Hint: [activation functions](http://letmegooglethat.com/?q=keras+activation+functions) Hint: `model.fit` has argument "`validation_data`" which takes a tuple of features and targets Hint: Use `model.save("filename.h5")` to save a model locally. If you want to use it later, just call `keras.models.load_model("filename.h5")` ###Code # For easy looping, define neural network model as a function def nn_model(optimizer='adam', activation='relu', layers=[20,20], loss='mean_squared_error'): model = keras.Sequential() model.add(keras.layers.Dense(50, input_dim=input_len, activation=activ)) model.add(keras.layers.Dense(50, activation=activ)) model.add(keras.layers.Dense(1)) model.compile(loss='mean_absolute_error', optimizer='adam') return model best_score = 1000.0 # bad # loop over chosen activation functions, train, evaluate on validation for activ in ['sigmoid', 'tanh', 'relu']: model = nn_model(activation=activ) history = model.fit(selected_feature_train, price_train, epochs=50, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) if model_score < best_score: best_score = model_score best_activ = activ best_model = model best_train = history print(f"BEST ACTIVATION FUNCTION {best_activ} WITH SCORE {best_score}") best_model.save("awesome_model.h5") ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 61us/step - loss: 532974.1758 - val_loss: 557914.6710 Epoch 2/50 18000/18000 [==============================] - 0s 15us/step - loss: 532967.3181 - val_loss: 557908.9735 Epoch 3/50 18000/18000 [==============================] - 0s 13us/step - loss: 532962.1269 - val_loss: 557903.9525 Epoch 4/50 18000/18000 [==============================] - 0s 14us/step - loss: 532957.2894 - val_loss: 557899.4930 Epoch 5/50 18000/18000 [==============================] - 0s 13us/step - loss: 532952.5633 - val_loss: 557894.6470 Epoch 6/50 18000/18000 [==============================] - 0s 9us/step - loss: 532947.9042 - val_loss: 557889.8510 Epoch 7/50 18000/18000 [==============================] - 0s 11us/step - loss: 532943.2878 - val_loss: 557885.5170 Epoch 8/50 18000/18000 [==============================] - 0s 10us/step - loss: 532938.6823 - val_loss: 557880.8320 Epoch 9/50 18000/18000 [==============================] - 0s 10us/step - loss: 532934.1124 - val_loss: 557876.0225 Epoch 10/50 18000/18000 [==============================] - 0s 10us/step - loss: 532929.5258 - val_loss: 557871.6970 Epoch 11/50 18000/18000 [==============================] - 0s 14us/step - loss: 532924.9893 - val_loss: 557867.0405 Epoch 12/50 18000/18000 [==============================] - 0s 12us/step - loss: 532920.4284 - val_loss: 557862.6110 Epoch 13/50 18000/18000 [==============================] - 0s 12us/step - loss: 532915.8835 - val_loss: 557857.9335 Epoch 14/50 18000/18000 [==============================] - 0s 12us/step - loss: 532911.3458 - val_loss: 557853.6650 Epoch 15/50 18000/18000 [==============================] - 0s 14us/step - loss: 532906.8151 - val_loss: 557848.8690 Epoch 16/50 18000/18000 [==============================] - 0s 12us/step - loss: 532902.2797 - val_loss: 557844.4835 Epoch 17/50 18000/18000 [==============================] - 0s 10us/step - loss: 532897.7445 - val_loss: 557839.8085 Epoch 18/50 18000/18000 [==============================] - 0s 10us/step - loss: 532893.2282 - val_loss: 557835.5010 Epoch 19/50 18000/18000 [==============================] - 0s 10us/step - loss: 532888.7034 - val_loss: 557830.8360 Epoch 20/50 18000/18000 [==============================] - 0s 10us/step - loss: 532884.1843 - val_loss: 557826.4430 Epoch 21/50 18000/18000 [==============================] - 0s 12us/step - loss: 532879.6504 - val_loss: 557821.7920 Epoch 22/50 18000/18000 [==============================] - 0s 14us/step - loss: 532875.1483 - val_loss: 557817.4790 Epoch 23/50 18000/18000 [==============================] - 0s 13us/step - loss: 532870.6122 - val_loss: 557812.8160 Epoch 24/50 18000/18000 [==============================] - 0s 11us/step - loss: 532866.1056 - val_loss: 557808.3360 Epoch 25/50 18000/18000 [==============================] - 0s 10us/step - loss: 532861.5706 - val_loss: 557803.7380 Epoch 26/50 18000/18000 [==============================] - 0s 11us/step - loss: 532857.0776 - val_loss: 557799.1610 Epoch 27/50 18000/18000 [==============================] - 0s 10us/step - loss: 532852.5495 - val_loss: 557794.6775 Epoch 28/50 18000/18000 [==============================] - 0s 14us/step - loss: 532848.0404 - val_loss: 557789.9945 Epoch 29/50 18000/18000 [==============================] - 0s 15us/step - loss: 532843.5083 - val_loss: 557785.6990 Epoch 30/50 18000/18000 [==============================] - 0s 14us/step - loss: 532839.0229 - val_loss: 557781.0485 Epoch 31/50 18000/18000 [==============================] - 0s 12us/step - loss: 532834.4841 - val_loss: 557776.6410 Epoch 32/50 18000/18000 [==============================] - 0s 12us/step - loss: 532829.9850 - val_loss: 557771.9805 Epoch 33/50 18000/18000 [==============================] - 0s 12us/step - loss: 532825.4563 - val_loss: 557767.6930 Epoch 34/50 18000/18000 [==============================] - 0s 12us/step - loss: 532820.7999 - val_loss: 557762.6110 Epoch 35/50 18000/18000 [==============================] - 0s 10us/step - loss: 532815.6766 - val_loss: 557757.6930 Epoch 36/50 18000/18000 [==============================] - 0s 10us/step - loss: 532810.8327 - val_loss: 557752.8360 Epoch 37/50 18000/18000 [==============================] - 0s 9us/step - loss: 532806.0533 - val_loss: 557747.9525 Epoch 38/50 18000/18000 [==============================] - 0s 9us/step - loss: 532801.3039 - val_loss: 557743.0485 Epoch 39/50 18000/18000 [==============================] - 0s 9us/step - loss: 532796.0384 - val_loss: 557737.7920 Epoch 40/50 18000/18000 [==============================] - 0s 9us/step - loss: 532790.9252 - val_loss: 557732.8320 Epoch 41/50 18000/18000 [==============================] - 0s 9us/step - loss: 532785.9397 - val_loss: 557727.7980 Epoch 42/50 18000/18000 [==============================] - 0s 13us/step - loss: 532781.0243 - val_loss: 557722.8730 Epoch 43/50 18000/18000 [==============================] - 0s 15us/step - loss: 532776.1177 - val_loss: 557717.9525 Epoch 44/50 18000/18000 [==============================] - 0s 14us/step - loss: 532771.2528 - val_loss: 557713.3645 Epoch 45/50 18000/18000 [==============================] - 0s 11us/step - loss: 532766.3882 - val_loss: 557708.4470 Epoch 46/50 18000/18000 [==============================] - 0s 11us/step - loss: 532761.5342 - val_loss: 557703.6650 Epoch 47/50 18000/18000 [==============================] - 0s 14us/step - loss: 532756.7074 - val_loss: 557698.6670 Epoch 48/50 18000/18000 [==============================] - 0s 11us/step - loss: 532751.8659 - val_loss: 557693.7030 Epoch 49/50 18000/18000 [==============================] - 0s 14us/step - loss: 532746.5045 - val_loss: 557688.0105 Epoch 50/50 18000/18000 [==============================] - 0s 13us/step - loss: 532741.2496 - val_loss: 557683.0085 Train on 18000 samples, validate on 2000 samples Epoch 1/50 18000/18000 [==============================] - 1s 66us/step - loss: 532968.8535 - val_loss: 557907.8785 Epoch 2/50 18000/18000 [==============================] - 0s 11us/step - loss: 532959.6811 - val_loss: 557900.1345 Epoch 3/50 18000/18000 [==============================] - 0s 12us/step - loss: 532952.1103 - val_loss: 557892.8225 Epoch 4/50 18000/18000 [==============================] - 0s 11us/step - loss: 532944.7126 - val_loss: 557885.5415 Epoch 5/50 18000/18000 [==============================] - 0s 11us/step - loss: 532937.3764 - val_loss: 557877.9805 Epoch 6/50 18000/18000 [==============================] - 0s 12us/step - loss: 532930.0783 - val_loss: 557870.8360 Epoch 7/50 18000/18000 [==============================] - 0s 12us/step - loss: 532922.8012 - val_loss: 557863.6790 Epoch 8/50 18000/18000 [==============================] - 0s 12us/step - loss: 532915.5595 - val_loss: 557856.4430 Epoch 9/50 18000/18000 [==============================] - 0s 12us/step - loss: 532908.3144 - val_loss: 557849.0125 Epoch 10/50 18000/18000 [==============================] - 0s 12us/step - loss: 532901.0774 - val_loss: 557841.7920 Epoch 11/50 18000/18000 [==============================] - 0s 12us/step - loss: 532893.8619 - val_loss: 557834.6450 Epoch 12/50 18000/18000 [==============================] - 0s 12us/step - loss: 532886.6362 - val_loss: 557827.5335 Epoch 13/50 18000/18000 [==============================] - 0s 11us/step - loss: 532879.4228 - val_loss: 557820.0150 Epoch 14/50 18000/18000 [==============================] - 0s 11us/step - loss: 532872.2118 - val_loss: 557812.9090 Epoch 15/50 18000/18000 [==============================] - 0s 10us/step - loss: 532864.9957 - val_loss: 557805.7820 Epoch 16/50 18000/18000 [==============================] - 0s 11us/step - loss: 532857.7976 - val_loss: 557798.6210 Epoch 17/50 18000/18000 [==============================] - 0s 16us/step - loss: 532850.5966 - val_loss: 557791.5170 Epoch 18/50 18000/18000 [==============================] - 0s 13us/step - loss: 532843.3934 - val_loss: 557783.9945 Epoch 19/50 18000/18000 [==============================] - 0s 14us/step - loss: 532836.1900 - val_loss: 557776.8790 Epoch 20/50 18000/18000 [==============================] - 0s 15us/step - loss: 532828.9844 - val_loss: 557769.7820 ###Markdown Visualize your training: ###Code import matplotlib.pyplot as plt # plot loss during training def plot_loss(hist): %matplotlib inline plt.title('Training Curve') plt.plot(hist.history['loss'], label='train') plt.plot(hist.history['val_loss'], label='validation') plt.xlabel("Epochs") plt.ylabel("Mean squared error") plt.legend() plt.show() plot_loss(best_train) ###Output _____no_output_____ ###Markdown In the future, try better validation schemes like [k-fold cross validation](https://chrisalbon.com/deep_learning/keras/k-fold_cross-validating_neural_networks/), though 80/20 or 90/10 train/val like this works in a pinch Standardize your features:* Typically assumes normally distributed feature, shifting mean to 0 and standard deviation to 1* In theory does not matter for neural networks* In practice tends to matter for neural networks* Scale if using: - Logistic regression - Support vector machines - Perceptrons - Neural networks - Principle component analysis* Don't bother if using: - "Forest" methods - Naive Bayes ###Code from sklearn.preprocessing import StandardScaler # Instantiate StandardScaler in_scaler = StandardScaler() # Fit scaler to the training set and perform the transformation selected_feature_train = in_scaler.fit_transform(selected_feature_train) # Use the fitted scaler to transform validation and test features selected_feature_val = in_scaler.transform(selected_feature_val) selected_feature_test = in_scaler.transform(selected_feature_test) # Check appropriate scaling print(np.mean(selected_feature_train[:,0])) print(np.std(selected_feature_train[:,0])) print(np.mean(selected_feature_val[:,0])) print(np.std(selected_feature_val[:,0])) print(np.mean(selected_feature_test[:,0])) print(np.std(selected_feature_test[:,0])) model = nn_model() model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=200, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(model_score) plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/200 18000/18000 [==============================] - 1s 69us/step - loss: 416644724774.2293 - val_loss: 456240251273.2160 Epoch 2/200 18000/18000 [==============================] - 0s 14us/step - loss: 416219411047.3102 - val_loss: 455230525276.1600 Epoch 3/200 18000/18000 [==============================] - 0s 16us/step - loss: 414539373463.3245 - val_loss: 452292457267.2000 Epoch 4/200 18000/18000 [==============================] - 0s 14us/step - loss: 410731792826.3680 - val_loss: 446517339226.1120 Epoch 5/200 18000/18000 [==============================] - 0s 12us/step - loss: 403953550943.1182 - val_loss: 437057174896.6400 Epoch 6/200 18000/18000 [==============================] - 0s 11us/step - loss: 393657770544.6969 - val_loss: 423509280423.9360 Epoch 7/200 18000/18000 [==============================] - 0s 11us/step - loss: 379580761156.2667 - val_loss: 405581878001.6640 Epoch 8/200 18000/18000 [==============================] - 0s 11us/step - loss: 361658841912.6613 - val_loss: 383390637883.3920 Epoch 9/200 18000/18000 [==============================] - 0s 12us/step - loss: 340165479570.5458 - val_loss: 357764951965.6960 Epoch 10/200 18000/18000 [==============================] - 0s 10us/step - loss: 315699842136.2916 - val_loss: 329091613720.5760 Epoch 11/200 18000/18000 [==============================] - 0s 10us/step - loss: 289117304433.3227 - val_loss: 298578878136.3200 Epoch 12/200 18000/18000 [==============================] - 0s 11us/step - loss: 261380564058.1120 - val_loss: 267361173110.7840 Epoch 13/200 18000/18000 [==============================] - 0s 11us/step - loss: 233512805422.4213 - val_loss: 236796970795.0080 Epoch 14/200 18000/18000 [==============================] - 0s 11us/step - loss: 206621634811.2213 - val_loss: 207759685582.8480 Epoch 15/200 18000/18000 [==============================] - 0s 11us/step - loss: 181544216108.1458 - val_loss: 181255742947.3280 Epoch 16/200 18000/18000 [==============================] - 0s 12us/step - loss: 159017826516.9920 - val_loss: 158054828081.1520 Epoch 17/200 18000/18000 [==============================] - 0s 11us/step - loss: 139581889431.3244 - val_loss: 138607148466.1760 Epoch 18/200 18000/18000 [==============================] - 0s 12us/step - loss: 123407551306.8658 - val_loss: 122830300577.7920 Epoch 19/200 18000/18000 [==============================] - 0s 11us/step - loss: 110414201050.4533 - val_loss: 110407385219.0720 Epoch 20/200 18000/18000 [==============================] - 0s 11us/step - loss: 100342549796.1813 - val_loss: 101138505334.7840 Epoch 21/200 18000/18000 [==============================] - 0s 11us/step - loss: 92746195562.9511 - val_loss: 94260454621.1840 Epoch 22/200 18000/18000 [==============================] - 0s 12us/step - loss: 87142331467.5484 - val_loss: 89257073442.8160 Epoch 23/200 18000/18000 [==============================] - 0s 10us/step - loss: 83029246782.1227 - val_loss: 85649517051.9040 Epoch 24/200 18000/18000 [==============================] - 0s 10us/step - loss: 79974571289.2587 - val_loss: 82916333518.8480 Epoch 25/200 18000/18000 [==============================] - 0s 10us/step - loss: 77613710038.3573 - val_loss: 80772310892.5440 Epoch 26/200 18000/18000 [==============================] - 0s 10us/step - loss: 75758766536.9315 - val_loss: 79040771063.8080 Epoch 27/200 18000/18000 [==============================] - 0s 16us/step - loss: 74215229277.9805 - val_loss: 77595545501.6960 Epoch 28/200 18000/18000 [==============================] - 0s 16us/step - loss: 72905572177.2373 - val_loss: 76338272731.1360 Epoch 29/200 18000/18000 [==============================] - 0s 15us/step - loss: 71745211261.8382 - val_loss: 75183492169.7280 Epoch 30/200 18000/18000 [==============================] - 0s 12us/step - loss: 70697890440.0782 - val_loss: 74151740702.7200 Epoch 31/200 18000/18000 [==============================] - 0s 15us/step - loss: 69729018285.6249 - val_loss: 73179619459.0720 Epoch 32/200 18000/18000 [==============================] - 0s 16us/step - loss: 68816311542.6702 - val_loss: 72256881098.7520 Epoch 33/200 18000/18000 [==============================] - 0s 16us/step - loss: 67936579977.2160 - val_loss: 71377126752.2560 Epoch 34/200 18000/18000 [==============================] - 0s 13us/step - loss: 67097538195.9111 - val_loss: 70526461837.3120 Epoch 35/200 18000/18000 [==============================] - 0s 10us/step - loss: 66280199538.4604 - val_loss: 69706505519.1040 Epoch 36/200 18000/18000 [==============================] - 0s 9us/step - loss: 65474546091.8044 - val_loss: 68888741609.4720 Epoch 37/200 18000/18000 [==============================] - 0s 14us/step - loss: 64683688744.2773 - val_loss: 68096607354.8800 Epoch 38/200 18000/18000 [==============================] - 0s 15us/step - loss: 63904897171.4560 - val_loss: 67312825925.6320 Epoch 39/200 18000/18000 [==============================] - 0s 15us/step - loss: 63130683200.8533 - val_loss: 66542651277.3120 Epoch 40/200 18000/18000 [==============================] - 0s 15us/step - loss: 62353993003.4631 - val_loss: 65772004278.2720 Epoch 41/200 18000/18000 [==============================] - 0s 13us/step - loss: 61587946799.1040 - val_loss: 65005461667.8400 Epoch 42/200 18000/18000 [==============================] - 0s 13us/step - loss: 60821804999.5662 - val_loss: 64246054682.6240 Epoch 43/200 18000/18000 [==============================] - 0s 15us/step - loss: 60059479146.4960 - val_loss: 63493657821.1840 Epoch 44/200 18000/18000 [==============================] - 0s 13us/step - loss: 59302580489.7849 - val_loss: 62744275124.2240 Epoch 45/200 18000/18000 [==============================] - 0s 11us/step - loss: 58543664973.5964 - val_loss: 61995190353.9200 Epoch 46/200 18000/18000 [==============================] - 0s 14us/step - loss: 57782123597.3689 - val_loss: 61241564889.0880 Epoch 47/200 18000/18000 [==============================] - 0s 14us/step - loss: 57033753307.8187 - val_loss: 60478097522.6880 Epoch 48/200 18000/18000 [==============================] - 0s 16us/step - loss: 56258215957.8453 - val_loss: 59734967582.7200 Epoch 49/200 18000/18000 [==============================] - 0s 15us/step - loss: 55499806911.1467 - val_loss: 58974680743.9360 Epoch 50/200 18000/18000 [==============================] - 0s 12us/step - loss: 54732866202.2827 - val_loss: 58233620856.8320 Epoch 51/200 18000/18000 [==============================] - 0s 12us/step - loss: 53979515737.4293 - val_loss: 57494574628.8640 Epoch 52/200 18000/18000 [==============================] - 0s 12us/step - loss: 53222918094.8480 - val_loss: 56758398943.2320 Epoch 53/200 18000/18000 [==============================] - 0s 14us/step - loss: 52461172330.0409 - val_loss: 56031989923.8400 Epoch 54/200 18000/18000 [==============================] - 0s 11us/step - loss: 51707750733.1413 - val_loss: 55297092943.8720 Epoch 55/200 18000/18000 [==============================] - 0s 12us/step - loss: 50952434705.2942 - val_loss: 54574977581.0560 Epoch 56/200 18000/18000 [==============================] - 0s 12us/step - loss: 50216374794.4676 - val_loss: 53872021700.6080 Epoch 57/200 18000/18000 [==============================] - 0s 12us/step - loss: 49466069960.4764 - val_loss: 53165771784.1920 Epoch 58/200 18000/18000 [==============================] - 0s 12us/step - loss: 48736365170.2329 - val_loss: 52481645215.7440 Epoch 59/200 18000/18000 [==============================] - 0s 12us/step - loss: 48015811634.0622 - val_loss: 51818096754.6880 Epoch 60/200 18000/18000 [==============================] - 0s 12us/step - loss: 47307462479.4169 - val_loss: 51166277468.1600 Epoch 61/200 18000/18000 [==============================] - 0s 12us/step - loss: 46607229739.9182 - val_loss: 50528075153.4080 Epoch 62/200 18000/18000 [==============================] - 0s 11us/step - loss: 45922461060.6649 - val_loss: 49895826849.7920 Epoch 63/200 18000/18000 [==============================] - 0s 10us/step - loss: 45252787397.5182 - val_loss: 49297462722.5600 Epoch 64/200 18000/18000 [==============================] - 0s 10us/step - loss: 44604951643.9324 - val_loss: 48700301737.9840 ###Markdown In the future, consider standardizing outputs as well Regularize:* Heavily parameterized models like neural networks are prone to overfitting* Popular off-the-shelf tools exist to regularize models and prevent overfitting: - L2 regularization (weight decay) - Dropout - Batch normalization These tools come as standard Keras/TF layers!`model.add(keras.layers.Dropout(rate)``model.add(keras.layers.ActivityRegularization(l1=0.0, l2=0.0)``model.add(keras.layers.BatchNormalization())` Early stopping and model checkpointing: It's unlikely the last iteration is the best, and who knows how long until the thing is converged. Just grab the best validation error. ###Code # Set callback functions to early stop training and save the # best model so far from keras.callbacks import EarlyStopping, ModelCheckpoint callbacks = [EarlyStopping(monitor='val_loss', patience=2), ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)] model = nn_model(layers=[20,20,20]) model.compile(loss='mean_squared_error', optimizer='adam') history = model.fit(selected_feature_train, price_train, epochs=400, callbacks=callbacks, batch_size=128, validation_data=(selected_feature_val, price_val)) model_score = score(model.predict(selected_feature_val), price_val) print(f"Model score: {model_score}") plot_loss(history) ###Output Train on 18000 samples, validate on 2000 samples Epoch 1/400 18000/18000 [==============================] - 1s 74us/step - loss: 416642251358.2080 - val_loss: 456230491127.8080 Epoch 00001: val_loss improved from inf to 456230491127.80798, saving model to best_model.h5 Epoch 2/400 18000/18000 [==============================] - 0s 12us/step - loss: 416175593648.5831 - val_loss: 455115510906.8800 Epoch 00002: val_loss improved from 456230491127.80798 to 455115510906.88000, saving model to best_model.h5 Epoch 3/400 18000/18000 [==============================] - 0s 11us/step - loss: 414236468168.4764 - val_loss: 451725259702.2720 Epoch 00003: val_loss improved from 455115510906.88000 to 451725259702.27197, saving model to best_model.h5 Epoch 4/400 18000/18000 [==============================] - 0s 12us/step - loss: 409652313427.5129 - val_loss: 444793102532.6080 Epoch 00004: val_loss improved from 451725259702.27197 to 444793102532.60797, saving model to best_model.h5 Epoch 5/400 18000/18000 [==============================] - 0s 11us/step - loss: 401502478940.3876 - val_loss: 433555929300.9920 Epoch 00005: val_loss improved from 444793102532.60797 to 433555929300.99200, saving model to best_model.h5 Epoch 6/400 18000/18000 [==============================] - 0s 14us/step - loss: 389127931691.0080 - val_loss: 417407007195.1360 Epoch 00006: val_loss improved from 433555929300.99200 to 417407007195.13599, saving model to best_model.h5 Epoch 7/400 18000/18000 [==============================] - 0s 14us/step - loss: 372354871401.5858 - val_loss: 396453596364.8000 Epoch 00007: val_loss improved from 417407007195.13599 to 396453596364.79999, saving model to best_model.h5 Epoch 8/400 18000/18000 [==============================] - 0s 11us/step - loss: 351261101246.2365 - val_loss: 370822052315.1360 Epoch 00008: val_loss improved from 396453596364.79999 to 370822052315.13599, saving model to best_model.h5 Epoch 9/400 18000/18000 [==============================] - 0s 13us/step - loss: 326316790761.2444 - val_loss: 341345543389.1840 Epoch 00009: val_loss improved from 370822052315.13599 to 341345543389.18402, saving model to best_model.h5 Epoch 10/400 18000/18000 [==============================] - 0s 15us/step - loss: 298425331511.7511 - val_loss: 309198200242.1760 Epoch 00010: val_loss improved from 341345543389.18402 to 309198200242.17603, saving model to best_model.h5 Epoch 11/400 18000/18000 [==============================] - 0s 14us/step - loss: 268705647005.2409 - val_loss: 275747260858.3680 Epoch 00011: val_loss improved from 309198200242.17603 to 275747260858.36798, saving model to best_model.h5 Epoch 12/400 18000/18000 [==============================] - 0s 11us/step - loss: 238421556796.5298 - val_loss: 242600971730.9440 Epoch 00012: val_loss improved from 275747260858.36798 to 242600971730.94400, saving model to best_model.h5 Epoch 13/400 18000/18000 [==============================] - 0s 11us/step - loss: 208827929067.5200 - val_loss: 210544567123.9680 Epoch 00013: val_loss improved from 242600971730.94400 to 210544567123.96799, saving model to best_model.h5 Epoch 14/400 18000/18000 [==============================] - 0s 11us/step - loss: 181250766609.5218 - val_loss: 181239822417.9200 Epoch 00014: val_loss improved from 210544567123.96799 to 181239822417.92001, saving model to best_model.h5 Epoch 15/400 18000/18000 [==============================] - 0s 11us/step - loss: 156734730928.1280 - val_loss: 155991138369.5360 Epoch 00015: val_loss improved from 181239822417.92001 to 155991138369.53601, saving model to best_model.h5 Epoch 16/400 18000/18000 [==============================] - ETA: 0s - loss: 138017311735.09 - 0s 11us/step - loss: 135798981525.5040 - val_loss: 134988053086.2080 Epoch 00016: val_loss improved from 155991138369.53601 to 134988053086.20799, saving model to best_model.h5 Epoch 17/400 18000/18000 [==============================] - 0s 15us/step - loss: 118836078000.3556 - val_loss: 118353070260.2240 Epoch 00017: val_loss improved from 134988053086.20799 to 118353070260.22400, saving model to best_model.h5 Epoch 18/400 18000/18000 [==============================] - 0s 12us/step - loss: 105603678346.3538 - val_loss: 105883129348.0960 Epoch 00018: val_loss improved from 118353070260.22400 to 105883129348.09599, saving model to best_model.h5 Epoch 19/400 18000/18000 [==============================] - 0s 10us/step - loss: 95745313909.4187 - val_loss: 96829833609.2160 Epoch 00019: val_loss improved from 105883129348.09599 to 96829833609.21600, saving model to best_model.h5 Epoch 20/400 18000/18000 [==============================] - 0s 11us/step - loss: 88618352621.7956 - val_loss: 90346775052.2880 Epoch 00020: val_loss improved from 96829833609.21600 to 90346775052.28799, saving model to best_model.h5 Epoch 21/400 18000/18000 [==============================] - 0s 10us/step - loss: 83567574355.5129 - val_loss: 85874045485.0560 Epoch 00021: val_loss improved from 90346775052.28799 to 85874045485.05600, saving model to best_model.h5 Epoch 22/400 18000/18000 [==============================] - 0s 10us/step - loss: 79998094813.8667 - val_loss: 82761349857.2800 Epoch 00022: val_loss improved from 85874045485.05600 to 82761349857.28000, saving model to best_model.h5 Epoch 23/400 18000/18000 [==============================] - 0s 12us/step - loss: 77425343874.8444 - val_loss: 80483269541.8880 Epoch 00023: val_loss improved from 82761349857.28000 to 80483269541.88800, saving model to best_model.h5 Epoch 24/400 18000/18000 [==============================] - 0s 11us/step - loss: 75462087511.6089 - val_loss: 78729282191.3600 Epoch 00024: val_loss improved from 80483269541.88800 to 78729282191.36000, saving model to best_model.h5 Epoch 25/400 18000/18000 [==============================] - 0s 10us/step - loss: 73870388468.8498 - val_loss: 77273078038.5280 Epoch 00025: val_loss improved from 78729282191.36000 to 77273078038.52800, saving model to best_model.h5 Epoch 26/400 18000/18000 [==============================] - 0s 10us/step - loss: 72516323071.3173 - val_loss: 75994380828.6720 Epoch 00026: val_loss improved from 77273078038.52800 to 75994380828.67200, saving model to best_model.h5 Epoch 27/400 18000/18000 [==============================] - 0s 11us/step - loss: 71323900251.7049 - val_loss: 74852082581.5040 Epoch 00027: val_loss improved from 75994380828.67200 to 74852082581.50400, saving model to best_model.h5 Epoch 28/400 18000/18000 [==============================] - 0s 11us/step - loss: 70227146804.7929 - val_loss: 73817158909.9520 Epoch 00028: val_loss improved from 74852082581.50400 to 73817158909.95200, saving model to best_model.h5 Epoch 29/400 18000/18000 [==============================] - 0s 11us/step - loss: 69211586836.7076 - val_loss: 72820976910.3360 Epoch 00029: val_loss improved from 73817158909.95200 to 72820976910.33600, saving model to best_model.h5 Epoch 30/400 18000/18000 [==============================] - 0s 10us/step - loss: 68253316495.5876 - val_loss: 71868724150.2720 Epoch 00030: val_loss improved from 72820976910.33600 to 71868724150.27200, saving model to best_model.h5 Epoch 31/400 18000/18000 [==============================] - 0s 11us/step - loss: 67342146957.7671 - val_loss: 70966434824.1920 Epoch 00031: val_loss improved from 71868724150.27200 to 70966434824.19200, saving model to best_model.h5 Epoch 32/400 18000/18000 [==============================] - 0s 10us/step - loss: 66443596828.2169 - val_loss: 70082538242.0480 Epoch 00032: val_loss improved from 70966434824.19200 to 70082538242.04800, saving model to best_model.h5 Epoch 33/400 18000/18000 [==============================] - 0s 11us/step - loss: 65572032122.4249 - val_loss: 69227643109.3760 Epoch 00033: val_loss improved from 70082538242.04800 to 69227643109.37601, saving model to best_model.h5 Epoch 34/400 18000/18000 [==============================] - 0s 10us/step - loss: 64735541992.5618 - val_loss: 68379734900.7360 Epoch 00034: val_loss improved from 69227643109.37601 to 68379734900.73600, saving model to best_model.h5 Epoch 35/400 18000/18000 [==============================] - 0s 10us/step - loss: 63888829455.4738 - val_loss: 67542714089.4720
Preparation/generate_sample_strict_QC_nopsm.ipynb
###Markdown Make sample- define a sample that passes strict QC and has data ###Code import os import numpy as np import pandas as pd # Paths root_p = '/home/surchs/sim_big/PROJECT/abide_hps/' # Pheno abide1_p = os.path.join(root_p, 'pheno', 'abide_1_complete.csv') # Data ct_p = os.path.join(root_p, 'ct') fc_p = os.path.join(root_p, 'fc') # File templates ct_t = '{}+{:07}_{}+{}_native_rms_rsl_tlaplace_30mm_left.txt' fc_t = 'fmri_{:07}_session_1_run1.nii.gz' # Out_path sample_p = os.path.join(root_p, 'pheno', 'strict_abide1_nopsm.csv') pheno = pd.read_csv(abide1_p) ###Output _____no_output_____ ###Markdown Define sampleCriteria:- `anat_qc` > 1- `fc_qc` > _'Fail'_- in psm sample- data available for both ct and fc ###Code sub_ind = [row['ct_available'] and row['fc_available'] and row['Ratings'] > 2 and row['status']=='OK' for rid, row in pheno.iterrows()] np.sum(sub_ind) sample = pheno[sub_ind] sample['DX_GROUP'].value_counts() ###Output _____no_output_____ ###Markdown This seems like a good starting sample. I'd say we go with this ###Code # Store it sample.to_csv(sample_p, index=False) ###Output _____no_output_____
workshops/workshop1.ipynb
###Markdown Data Dawgs Workshop 2: Introduction to PythonPresentation by Maanasa Ghantasala and Jonathan Waring**Important Note**: A lot of this presentation borrows heavily from Jake VanderPlas' ["Whirlwind Tour of Python"](https://github.com/jakevdp/WhirlwindTourOfPython) which is under the Creative Commons license. **2nd Important Note**: It seems as though most people had at least some sort of experience with a programming language before. Therefore, we will not be painstakingly explaining every tiny detail of programming, but rather focus on Python specifics. If you feel that you need more help understanding what's going on in the code, PLEASE LET US KNOW. Just raise your hand and Maanasa or Jonathan will come over to help you! Part 1: Introduction Conceived in the late 1980s as a teaching and scripting language, Python has since become an essential tool for many programmers, engineers, researchers, and data scientists across academia and industry. Python has emerged over the last couple decades as a first-class tool for scientific computing tasks, including the analysis and visualization of large datasets. This is surprising given the fact that Python was not originally designed for data analysis or scientific computing. The appeal of Python is in its simplicity and beauty, as well as the convenience of the large ecosystem of domain-specific tools that have been built on top of it. For example, most of the Python code in scientific computing and data science is built around a group of mature and useful packages:* [NumPy](http://www.numpy.org/) provides efficient storage and computation for multi-dimensional data arrays.* [SciPy](https://scipy.org/) contains a wide array of numerical tools such as numerical integration and interpolation.* [Pandas](http://pandas.pydata.org/) provides a DataFrame object along with a powerful set of methods to manipulate, filter, group, and transform data.* [Matplotlib](https://matplotlib.org/) provides a useful interface for creation of publication-quality plots and figures.* [Scikit-Learn](http://scikit-learn.org) provides a uniform toolkit for applying common machine learning algorithms to data.* [IPython/Jupyter](https://jupyter.org/) provides an enhanced terminal and an interactive notebook environment that is useful for exploratory analysis, as well as creation of interactive, executable documents. For example, this tutorial was composed entirely in Jupyter notebooks.The above list is just a sample of all the third party libraries out there. Always remember that if there is a scientific or data analysis task you want to perform, chances are someone has written a package in Python that will do it for you. However, in order to tap into the power of this data science ecosystem, one must first have a familiarity with the Python language itself. The Zen of Python Those who use Python are often quick to point out how "intuitive", "beautiful", or "fun" Python is. If you really want to dig into the programming philosophy that drives much of the coding practice of Python power-users, a nice little Easter egg exists in the Python interpreter: simply close your eyes, meditate for a few minutes, and import this: ###Code import this ###Output The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ###Markdown Part 2: How to Run Python CodePython is a flexible language, and there are several ways to use it depending on your particular task. One thing that distinguishes Python from other programming languages is that it is **interpreted** rather than **compiled**. This means that it is executed line by line, which allows programming to be interactive in a way that is not directly possible with compiled languages like Fortran, C, or Java. This section will describe four primary ways you can run Python code: * the Python interpreter * the IPython interpreter * via Self-contained Scripts * or in the Jupyter notebook (which is what we're using right now!) The Python InterpreterThe most basic way to execute Python code is line by line within the **Python interpreter**. The Python interpreter can be started by installing the Python language and typing python at the command prompt (look for the Terminal on Mac OS X and Unix/Linux systems, or the Command Prompt application in Windows) The IPython InterpreterIf you spend much time with the basic Python interpreter, you'll find that it lacks many of the features of a full-fledged interactive development environment. An alternative interpreter called **IPython** (for Interactive Python) is bundled with the Anaconda distribution, and includes a host of convenient enhancements to the basic Python interpreter. It can be started by typing ipython at the command prompt. The main aesthetic difference between the Python interpreter and the enhanced IPython interpreter lies in the command prompt: Python uses >>> by default, while IPython uses numbered commands (e.g. In [1]:). Regardless, we can execute code line by line just as we did before. Self-contained Python scriptsRunning Python snippets line by line is useful in some cases, but for more complicated programs it is more convenient to save code to file, and execute it all at once. By convention, Python scripts are saved in files with a .py extension. For example, let's create a script called test.py which contains the following: ###Code # Imagine this is a file called test.py print("Running test.py") x = 5 print("Result is", 3 * x) ###Output Running test.py Result is 15 ###Markdown To run this file, we make sure it is in the current directory and type python filename at the command prompt (i.e. python test.py). You would see the above output after running this command. The Jupyter notebookA useful hybrid of the interactive terminal and the self-contained script is the **Jupyter notebook**, a document format that allows executable code, formatted text, graphics, and even interactive features to be combined into a single document. Though the notebook began as a Python-only format, it has since been made compatible with a large number of programming languages, and is now an essential part of the [Jupyter Project](https://jupyter.org/). The notebook is useful both as a development environment, and as a means of sharing work via rich computational and data-driven narratives that mix together code, figures, data, and text. Part 3: Basic Python Syntax Python was originally developed as a teaching language, but its ease of use and clean syntax have led it to be embraced by beginners and experts alike. The cleanliness of Python's syntax has led some to call it "executable pseudocode", and it is often much easier to read and understand a Python script than to read a similar script written in, say, C or Java. Syntax refers to the structure of the language (i.e., what constitutes a correctly-formed program). For the time being, we'll not focus on the semantics – the meaning of the words and symbols within the syntax – but will return to this at a later point.Let's look at the following example (**don't worry about trying to understand how the code works right now**): ###Code # set the midpoint midpoint = 5 # make two empty lists lower = []; upper = [] # split the numbers into lower and upper for i in range(10): if (i < midpoint): lower.append(i) else: upper.append(i) print("lower:", lower) print("upper:", upper) ###Output lower: [0, 1, 2, 3, 4] upper: [5, 6, 7, 8, 9] ###Markdown The above code is a bit useless, but it compactly illustrates several of the important aspects of Python syntax. Let's walk through it and discuss some of the syntactical features of Python. Comments are Marked by ''The first line of code in the above example starts with a comment. ###Code #set the midpoint ###Output _____no_output_____ ###Markdown Comments in Python are indicated by a pound sign (), and anything on the line following the pound sign is ignored by the interpreter (notice that running the above code block doesn't do anything). This means, for example, that you can have stand-alone comments like the one just shown, as well as inline comments that follow a statement. For example: ###Code x += 2 # shorthand for x = x + 2 ###Output _____no_output_____ ###Markdown To create multiline comments, use the following: ###Code ''' This is a multiline comment. This is the second line of my comment. This is stil a part of the comment. ''' x = 4 ###Output _____no_output_____ ###Markdown End-of-Line Terminates a Statement The next line in the script is: ###Code midpoint = 5 ###Output _____no_output_____ ###Markdown This is an assignment operation, where we've created a variable named midpoint and assigned it the value 5. Notice that the end of this statement is simply marked by the end of the line. This is in contrast to languages like Java and C++, where every statement must end with a semicolon (;).In Python, if you'd like a statement to continue to the next line, it is possible to use the "\" marker to indicate this ###Code x = 1 + 2 + 3 + 4 +\ 5 + 6 + 7 + 8 ###Output _____no_output_____ ###Markdown It is also possible to continue expressions on the next line within parentheses, without using the "\" marker: ###Code x = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8) ###Output _____no_output_____ ###Markdown Semicolon Can Optionally Terminate a StatementSometimes it can be useful to put multiple statements on a single line. The next portion of the script is: ###Code lower = []; upper = [] ###Output _____no_output_____ ###Markdown This shows the example of how the semicolon (;) familiar in C++/Java, can be used optionally in Python to put two statements on a single line. Functionally, this is entirely equivalent to writing: ###Code lower = [] upper = [] ###Output _____no_output_____ ###Markdown Using a semicolon to put multiple statements on a single line is generally discouraged by most Python style guides, though occasionally it proves convenient. Identation: Whitespace Matters!Next, we get to the main block of code: ###Code for i in range(10): if i < midpoint: lower.append(i) else: upper.append(i) ###Output _____no_output_____ ###Markdown This is a compound control-flow statement including a loop and a conditional – we'll look at these types of statements in a moment. For now, consider that this demonstrates what is perhaps the most controversial feature of Python's syntax: whitespace is meaningful!In programming languages, a block of code is a set of statements that should be treated as a unit. In C, for example, code blocks are denoted by curly braces:> `// C++ Code for(int i=0; i < 100; i++){ // curly braces indicate code block total += i;}`In Python, code blocks are denoted by indentation: ###Code total = 0 for i in range(100): # indentation indicates code block total += i ###Output _____no_output_____ ###Markdown In Python, indented code blocks are always preceded by a colon (:) on the previous line.The use of indentation helps to enforce the uniform, readable style that many find appealing in Python code. Python's use of meaningful whitespace often is surprising to programmers who are accustomed to other languages, but in practice it can lead to much more consistent and readable code than languages that do not enforce indentation of code blocks. Finally, you should be aware that the amount of whitespace used for indenting code blocks is up to the user, as long as it is consistent throughout the script. Whitespaces Within Lines Does Not Matter While the mantra of **meaningful whitespace** holds true for whitespace **before** lines (which indicate a code block), white space **within** lines of Python code does not matter. For example, all three of these expressions are equivalent: ###Code x=1+2 x = 1 + 2 x = 1 + 2 ###Output _____no_output_____ ###Markdown Abusing this flexibility can lead to issues with code readibility. However, using whitespace effectively can lead to much more readable code, especially in cases where operators follow each other – compare the following two expressions for exponentiating by a negative number: ###Code x=10**-2 # compared to x = 10 ** -2 ###Output _____no_output_____ ###Markdown I find the second version with spaces much more easily readable at a single glance. Parentheses Are for Grouping or CallingIn the previous code snippet, we see two uses of parentheses. First, they can be used in the typical way to group statements or mathematical operations: ###Code 2 * (3 + 4) ###Output _____no_output_____ ###Markdown They can also be used to indicate that a function is being called. In the next snippet, the print() function is used to display the contents of a variable. The function call is indicated by a pair of opening and closing parentheses, with the arguments to the function contained within: ###Code print('first value:', 1) print('second value:', 2) ###Output second value: 2 ###Markdown Some functions can be called with no arguments at all, in which case the opening and closing parentheses still must be used to indicate a function evaluation. An example of this is the sort method of lists: ###Code L = [4,2,3,1] L.sort() print(L) ###Output [1, 2, 3, 4] ###Markdown The "()" after sort indicates that the function should be executed, and is required even if no arguments are necessary. Finishing Up on Syntax and Learning MoreThis has been a very brief exploration of the essential features of Python syntax; its purpose is to give you a good frame of reference for when you're reading the code in later sections. Several times we've mentioned Python "style guides", which can help teams to write code in a consistent style. The most widely used style guide in Python is known as PEP8, and can be found at https://www.python.org/dev/peps/pep-0008/. As you begin to write more Python code, it would be useful to read through this! The style suggestions contain the wisdom of many Python gurus, and most suggestions go beyond simple pedantry: they are experience-based recommendations that can help avoid subtle mistakes and bugs in your code. Part 4: Basic Python Semantics: Variables and ObjectsThis section will begin to cover the basic semantics of the Python language. As opposed to the syntax covered in the previous section, the semantics of a language involve the meaning of the statements. As with our discussion of syntax, here we'll preview a few of the essential semantic constructions in Python to give you a better frame of reference for understanding the code in the following sections.This section will cover the semantics of variables and objects, which are the main ways you store, reference, and operate on data within a Python script. Python Variables are PointersAssigning variables in Python is as easy as putting a variable name to the left of the equals (=) sign (note that as opposed to other langugages, such as Java and C++, you don't have to assign it a type): ###Code # assign 4 to the variable x x = 4 ###Output _____no_output_____ ###Markdown This may seem straightforward, but if you have the wrong mental model of what this operation does, the way Python works may seem confusing. We'll briefly dig into that here.In many programming languages, variables are best thought of as containers or buckets into which you put data. So in Java, for example, when you write > `\\Java Codeint x = 4;`you are essentially defining a "memory bucket" named x, and putting the value 4 into it. In Python, by contrast, variables are best thought of not as containers but as pointers. So in Python, when you write>` Python Codex = 4` you are essentially defining a pointer named x that points to some other bucket containing the value 4. Note one consequence of this: because Python variables just point to various objects, there is no need to "declare" the variable, or even require the variable to always point to information of the same type! This is the sense in which people say Python is **dynamically-typed**: variable names can point to objects of any type. So in Python, you can do things like this: ###Code x = 1 # x is an integer x = 'hello' # now x is a string x = [1, 2, 3] # now x is a list ###Output _____no_output_____ ###Markdown While users of **statically-typed** languages might miss the type-safety that comes with variable type declarations like those found in Java or C, this dynamic typing is one of the pieces that makes Python so quick to write and easy to read.There is a consequence of this "variable as pointer" approach that you need to be aware of. If we have two variable names pointing to the same mutable object, then changing one will change the other as well! For example, let's create and modify a list: ###Code x = [1, 2, 3] y = x ###Output _____no_output_____ ###Markdown We've created two variables x and y which both point to the same object. Because of this, if we modify the list via one of its names, we'll see that the "other" list will be modified as well: ###Code print(y) x.append(4) # append 4 to the list pointed to by x print(y) # y's list is modified as well! ###Output [1, 2, 3, 4] ###Markdown This behavior might seem confusing if you're wrongly thinking of variables as buckets that contain data. But if you're correctly thinking of variables as pointers to objects, then this behavior makes sense.Note also that if we use "=" to assign another value to x, this will not affect the value of y – assignment is simply a change of what object the variable points to: ###Code x = 'something else' print(y) # y is unchanged ###Output [1, 2, 3, 4] ###Markdown Again, this makes perfect sense if you think of x and y as pointers, and the "=" operator as an operation that changes what the name points to.You might wonder whether this pointer idea makes arithmetic operations in Python difficult to track, but Python is set up so that this is not an issue. Numbers, strings, and other simple types are immutable: you can't change their value – you can only change what values the variables point to. So, for example, it's perfectly safe to do operations like the following: ###Code x = 10 y = x x += 5 # add 5 to x's value, and assign it to x print("x =", x) print("y =", y) ###Output x = 15 y = 10 ###Markdown When we call x += 5, we are not modifying the value of the 10 object pointed to by x; we are rather changing the variable x so that it points to a new integer object with value 15. For this reason, the value of y is not affected by the operation. Everything Is an Object Python is an **object-oriented** programming language, and in Python everything is an object.Let's flesh-out what this means. Earlier we saw that variables are simply pointers, and the variable names themselves have no attached type information. This leads some to claim erroneously that Python is a type-free language. But this is not the case! Consider the following: ###Code x = 4 type(x) x = 'hello' type(x) x = 3.14159 type(x) ###Output _____no_output_____ ###Markdown Python has types; however, the types are linked not to the variable names but to the objects themselves.In object-oriented programming languages like Python, an object is an entity that contains data along with associated metadata and/or functionality. In Python everything is an object, which means every entity has some metadata (called attributes) and associated functionality (called methods). These attributes and methods are accessed via the dot syntax.For example, before we saw that lists have an append method, which adds an item to the list, and is accessed via the dot (".") syntax: ###Code L = [1, 2, 3] L.append(100) print(L) ###Output [1, 2, 3, 100] ###Markdown While it might be expected for compound objects like lists to have attributes and methods, what is sometimes unexpected is that in Python even simple types have attached attributes and methods. For example, numerical types have a real and imag attribute that returns the real and imaginary part of the value, if viewed as a complex number: ###Code x = 4.5 print(x.real, "+", x.imag, 'i') ###Output 4.5 + 0.0 i ###Markdown Methods are like attributes, except they are functions that you can call using opening and closing parentheses. For example, floating point numbers have a method called is_integer that checks whether the value is an integer: ###Code x = 4.5 x.is_integer() x = 4.0 x.is_integer() ###Output _____no_output_____ ###Markdown Part 5: Basic Python Semantics: Operators In the previous section, we began to look at the semantics of Python variables and objects. Here we'll dig into the semantics of the various operators included in the language. By the end of this section, you'll have the basic tools to begin comparing and operating on data in Python. Arithmetic Operations Python implements seven basic binary arithmetic operators, two of which can double as unary operators. They are summarized in the following table:| Operator | Name | Description ||----------|----------------|------------------------------------------------|| a + b | Addition | Sum of a and b || a - b | Subtraction | Difference of a and b || a * b | Multiplication | Product of a and b || a / b | True Division | Quotient of a and b || a // b | Floor Division | Quotient of a and b, removing fractional parts || a % b | Modulus | Integer remainder after division of a by b || a \*\* b | Exponentiation | a raised to the power of b || -a | Negation | The negative of a || +a | Unary Plus | a unchanged (rarely used) |These operators can be used and combined in intuitive ways, using standard parentheses to group operations. For example: ###Code # addition, subtraction, multiplication (4 + 8) * (6.5 - 3) ###Output _____no_output_____ ###Markdown Floor division is true division with fractional parts truncated: ###Code # True division print(11 / 2) # Floor division print(11 // 2) ###Output 5 ###Markdown The floor division operator was added in Python 3; you should be aware if working in Python 2 that the standard division operator (/) acts like floor division for integers and like true division for floating-point numbers. Assignment OperationsWe've seen that variables can be assigned with the "=" operator, and the values stored for later use. For example: ###Code a = 24 print(a) ###Output 24 ###Markdown We can use these variables in expressions with any of the operators mentioned earlier. For example, to add 2 to a we write ###Code a + 2 ###Output _____no_output_____ ###Markdown We might want to update the variable $a$ with this new value; in this case, we could combine the addition and the assignment and write a = a + 2. Because this type of combined operation and assignment is so common, Python includes built-in update operators for all of the arithmetic operations: ###Code a += 2 # equivalent to a = a + 2 (you can do this with any of the arithmetic operators) print(a) ###Output 26 ###Markdown Comparison OperationsAnother type of operation which can be very useful is comparison of different values. For this, Python implements standard comparison operators, which return Boolean values True (1) and False (0). The comparison operations are listed in the following table:| Operation | Description ||-----------|------------------------------|| a == b | a equal to b || a < b | a less than b || a <= b | a less than or equal to b || a != b | a not equal to b || a > b | a greater than b || a >= b | a greater than or equal to b |These comparison operators can be combined with the arithmetic operators to express a virtually limitless range of tests for the numbers. For example, we can check if a number is odd by checking that the modulus with 2 returns 1: ###Code # 25 is odd 25 % 2 == 1 # 66 is odd 66 % 2 == 1 ###Output _____no_output_____ ###Markdown We can string-together multiple comparisons to check more complicated relationships: ###Code # check if a is between 15 and 30 a = 25 15 < a < 30 ###Output _____no_output_____ ###Markdown Boolean OperationsWhen working with Boolean values, Python provides operators to combine the values using the standard concepts of "and", "or", and "not". Predictably, these operators are expressed using the words and, or, and not: ###Code x = 4 (x < 6) and (x > 2) (x > 10) or (x % 2 == 0) not (x < 6) ###Output _____no_output_____ ###Markdown These sorts of Boolean operations will become extremely useful when we begin discussing control flow statements such as conditionals and loops. Identity and Membership OperatorsLike and, or, and not, Python also contains prose-like operators to check for identity and membership. They are the following:| Operation | Description ||------------|------------------------------------------|| a is b | True if a and b are identical objects || a is not b | True if a and b are not identical objects|| a in b | True if a is a member of b || a not in b | True if a is not a member of b | Identity Operators: "is" and "is not"The identity operators, "is" and "is not" check for object identity. Object identity is different than equality, as we can see here: ###Code a = [1, 2, 3] b = [1, 2, 3] a == b a is b a is not b ###Output _____no_output_____ ###Markdown What do identical objects look like? Here is an example: ###Code a = [1, 2, 3] b = a a is b ###Output _____no_output_____ ###Markdown The difference between the two cases here is that in the first, a and b point to different objects, while in the second they point to the same object. As we saw in the previous section, Python variables are pointers. The "is" operator checks whether the two variables are pointing to the same container (object), rather than referring to what the container contains. With this in mind, in most cases that a beginner is tempted to use "is" what they really mean is ==. Membership operatorsMembership operators check for membership within compound objects. So, for example, we can write: ###Code 1 in [1, 2, 3] 2 not in [1, 2, 3] ###Output _____no_output_____ ###Markdown These membership operations are an example of what makes Python so easy to use compared to lower-level languages such as C. In C, membership would generally be determined by manually constructing a loop over the list and checking for equality of each value. In Python, you just type what you want to know, in a manner reminiscent of straightforward English prose. Part 6: Built-In-Types: Simple ValuesWhen discussing Python variables and objects, we mentioned the fact that all Python objects have type information attached. Here we'll briefly walk through the built-in simple types offered by Python. We say "simple types" to contrast with several compound types, which will be discussed in the following section.Python's simple types are summarized in the following table:| Type | Example | Description ||-----------|------------|-------------------------------------------------------------|| int | x = 1 | integers (i.e. whole numbers) || float | x = 1.0 | floating-point numbers (i.e. real numbers) || complex | x = 1 + 2j | Complex numbers (i.e. numbers with real and imaginary part) || bool | x = True | Boolean: True/False values || str | x = 'abc' | String: characters or text || None Type | x = None | Special object indicating nulls | IntegersThe most basic numerical type is the integer. Any number without a decimal point is an integer: ###Code x = 1 type(x) ###Output _____no_output_____ ###Markdown **Aside**: Python integers are actually quite a bit more sophisticated than integers in languages like Java. Java integers are fixed-precision, and usually overflow at some value (often near $2^{31}$ or $2^{63}$, depending on your system). Python integers are variable-precision, so you can do computations that would overflow in other languages: ###Code 2 ** 200 ###Output _____no_output_____ ###Markdown Floating-Point NumbersThe floating-point type can store fractional numbers. They can be defined either in standard decimal notation, or in exponential notation: ###Code x = 0.000005 y = 5e-6 print(x == y) x = 1400000.00 y = 1.4e6 print(x == y) ###Output True ###Markdown In the exponential notation, the e or E can be read "...times ten to the...", so that 1.4e6 is interpreted as ~$1.4 \times 10^6$.An integer can be explicitly converted to a float with the float constructor: ###Code float(1) ###Output _____no_output_____ ###Markdown **Aside**: One thing to be aware of with floating point arithmetic is that its precision is limited, which can cause equality tests to be unstable. For example: ###Code 0.1 + 0.2 == 0.3 ###Output _____no_output_____ ###Markdown Why is this the case? It turns out that it is not a behavior unique to Python, but is due to the fixed-precision format of the binary floating-point storage used by most, if not all, scientific computing platforms. All programming languages using floating-point numbers store them in a fixed number of bits, and this leads some numbers to be represented only approximately. We can see this by printing the three values to high precision: ###Code print("0.1 = {0:.17f}".format(0.1)) print("0.2 = {0:.17f}".format(0.2)) print("0.3 = {0:.17f}".format(0.3)) ###Output 0.1 = 0.10000000000000001 0.2 = 0.20000000000000001 0.3 = 0.29999999999999999 ###Markdown Complex NumbersComplex numbers are numbers with real and imaginary (floating-point) parts. We've seen integers and real numbers before; we can use these to construct a complex number: ###Code complex(1,2) ###Output _____no_output_____ ###Markdown Complex numbers have a variety of interesting attributes and methods, which we'll briefly demonstrate here: ###Code c = 3 + 4j c.real # real part c.imag # imaginary part c.conjugate() # complex conjugate abs(c) # magnitude, i.e. sqrt(c.real ** 2 + c.imag ** 2) ###Output _____no_output_____ ###Markdown String TypeStrings in Python are created with single or double quotes: ###Code message = "what do you like?" response = 'spam' ###Output _____no_output_____ ###Markdown Python has many extremely useful string functions and methods; here are a few of them: ###Code #length of string (number of characters) len(response) # Make upper-case. See also str.lower() response.upper() # Capitalize. See also str.title() message.capitalize() # concatenation with + message + response # multiplication is multiple concatenation 5 * response # Access individual characters (zero-based indexing) message[0] ###Output _____no_output_____ ###Markdown None TypePython includes a special type, the NoneType, which has only a single possible value: None. For example: ###Code type(None) ###Output _____no_output_____ ###Markdown You'll see None used in many places, but perhaps most commonly it is used as the default return value of a function. For example, the print() function in Python 3 does not return anything, but we can still catch its value: ###Code return_value = print('abc') print(return_value) ###Output None ###Markdown Likewise, any function in Python with no return value is, in reality, returning None. Boolean TypeThe Boolean type is a simple type with two possible values: True and False, and is returned by comparison operators discussed previously: ###Code result = (4 < 5) result type(result) ###Output _____no_output_____ ###Markdown Keep in mind that the Boolean values are case-sensitive: unlike some other languages, True and False must be capitalized!Booleans can also be constructed using the bool() object constructor: values of any other type can be converted to Boolean via predictable rules. For example, any numeric type is False if equal to zero, and True otherwise: ###Code bool(2017) bool(0) bool(3.1415) bool(None) bool("") bool("abc") ###Output _____no_output_____ ###Markdown Part 7: Built-In Data StructuresWe have seen Python's simple types: int, float, complex, bool, str, and so on. Python also has several built-in compound types, which act as containers for other types. These compound types are:| Type Name | Example | Description ||-----------|------------------------|---------------------------------------|| list | [1, 2, 3] | Ordered collection || tuple | (1, 2, 3) | Immutable ordered collection || dict | {'a':1, 'b':2, 'c': 3} | Unordered (key,value) mapping || set | {1, 2, 3} | Unordered collection of unique values |As you can see, round, square, and curly brackets have distinct meanings when it comes to the type of collection produced. We'll take a quick tour of these data structures here. ListsLists are the basic **ordered** and **mutable** data collection type in Python. They can be defined with comma-separated values between square brackets; for example, here is a list of the first several prime numbers: ###Code L = [2, 3, 5, 7] ###Output _____no_output_____ ###Markdown Lists have a number of useful properties and methods available to them. Here we'll take a quick look at some of the more common and useful ones: ###Code # Length of a list len(L) # Append a value to the end L.append(11) print(L) # Addition concatenates lists L + [13, 17, 19] # sort() method sorts in-place L = [2, 5, 1, 6, 3, 4] L.sort() print(L) ###Output [1, 2, 3, 4, 5, 6] ###Markdown In addition, there are many more built-in list methods; they are well-covered in Python's [online documentation](https://docs.python.org/3/tutorial/datastructures.html).While we've been demonstrating lists containing values of a single type, one of the powerful features of Python's compound objects is that they can contain objects of any type, or even a mix of types. For example: ###Code L = [1, 'two', 3.14, [0, 3, 5]] ###Output _____no_output_____ ###Markdown This flexibility is a consequence of Python's dynamic type system. Creating such a mixed sequence in a statically-typed language like Java can be much more of a headache! We see that lists can even contain other lists as elements. Such type flexibility is an essential piece of what makes Python code relatively quick and easy to write.So far we've been considering manipulations of lists as a whole; another essential piece is the accessing of individual elements. This is done in Python via indexing and slicing, which we'll explore next. List indexing and slicingPython provides access to elements in compound types through indexing for single elements, and slicing for multiple elements. As we'll see, both are indicated by a square-bracket syntax. Suppose we return to our list of the first several primes: ###Code L = [2, 3, 5, 7, 11] ###Output _____no_output_____ ###Markdown Python uses zero-based indexing, so we can access the first and second element in using the following syntax: ###Code L[0] L[1] ###Output _____no_output_____ ###Markdown Elements at the end of the list can be accessed with negative numbers, starting from -1: ###Code L[-1] L[-2] ###Output _____no_output_____ ###Markdown Where **indexing** is a means of fetching a single value from the list, **slicing** is a means of accessing multiple values in sub-lists. It uses a colon to indicate the start point (inclusive) and end point (non-inclusive) of the sub-array. For example, to get the first three elements of the list, we can write: ###Code L[0:3] ###Output _____no_output_____ ###Markdown If we leave out the first index, 0 is assumed, so we can equivalently write: ###Code L[:3] ###Output _____no_output_____ ###Markdown Similarly, if we leave out the last index, it defaults to the length of the list. Thus, the last three elements can be accessed as follows: ###Code L[-3:] ###Output _____no_output_____ ###Markdown Finally, it is possible to specify a third integer that represents the step size; for example, to select every second element of the list, we can write: ###Code L[::2] # equivalent to L[0:len(L):2] ###Output _____no_output_____ ###Markdown A particularly useful version of this is to specify a negative step, which will reverse the array: ###Code L[::-1] ###Output _____no_output_____ ###Markdown Both indexing and slicing can be used to set elements as well as access them. The syntax is as you would expect: ###Code L[0] = 100 print(L) L[1:3] = [55, 56] print(L) ###Output [100, 55, 56, 7, 11] ###Markdown A very similar slicing syntax is also used in many data science-oriented packages, including NumPy and Pandas (mentioned in the introduction).Now that we have seen Python lists and how to access elements in ordered compound types, let's take a look at the other three standard compound data types mentioned earlier. TuplesTuples are in many ways similar to lists, but they are defined with parentheses rather than square brackets: ###Code t = (1, 2, 3) ###Output _____no_output_____ ###Markdown They can also be defined without any brackets at all: ###Code t = 1, 2, 3 print(t) ###Output (1, 2, 3) ###Markdown Like the lists discussed before, tuples have a length, and individual elements can be extracted using square-bracket indexing: ###Code len(t) t[0] ###Output _____no_output_____ ###Markdown The main distinguishing feature of tuples is that they are **immutable**: this means that once they are created, their size and contents cannot be changed: ###Code t[1] = 4 t.append(4) ###Output _____no_output_____ ###Markdown Tuples are often used in a Python program; a particularly common case is in functions that have multiple return values. For example, the as_integer_ratio() method of floating-point objects returns a numerator and a denominator; this dual return value comes in the form of a tuple: ###Code x = 0.125 x.as_integer_ratio() ###Output _____no_output_____ ###Markdown These multiple return values can be individually assigned as follows: ###Code numerator, denominator = x.as_integer_ratio() print(numerator / denominator) ###Output 0.125 ###Markdown The indexing and slicing logic covered earlier for lists works for tuples as well, along with a host of other methods. Refer to the online [Python documentation](https://docs.python.org/3/tutorial/datastructures.html) for a more complete list of these. DictionariesDictionaries are extremely flexible mappings of keys to values, and form the basis of much of Python's internal implementation. They can be created via a comma-separated list of key:value pairs within curly braces: ###Code numbers = {'one':1, 'two':2, 'three':3} ###Output _____no_output_____ ###Markdown Items are accessed and set via the indexing syntax used for lists and tuples, except here the index is not a zero-based order but valid key in the dictionary: ###Code # Access a value via the key numbers['two'] ###Output _____no_output_____ ###Markdown New items can be added to the dictionary using indexing as well: ###Code # Set a new key:value pair numbers['ninety'] = 90 print(numbers) ###Output {'one': 1, 'two': 2, 'three': 3, 'ninety': 90} ###Markdown Keep in mind that dictionaries do not maintain any sense of order for the input parameters; this is by design. This lack of ordering allows dictionaries to be implemented very efficiently, so that random element access is very fast, regardless of the size of the dictionary (if you're curious how this works, read about the concept of a hash table). The [Python documentation](https://docs.python.org/3/tutorial/datastructures.html) has a complete list of the methods available for dictionaries. SetsThe fourth basic collection is the set, which contains unordered collections of unique items. They are defined much like lists and tuples, except they use the curly brackets of dictionaries: ###Code primes = {2, 3, 5, 7} odds = {1, 3, 5, 7, 9} ###Output _____no_output_____ ###Markdown If you're familiar with the mathematics of sets, you'll be familiar with operations like the union, intersection, difference, symmetric difference, and others. Python's sets have all of these operations built-in, via methods or operators. For each, we'll show the two equivalent methods: ###Code # union: items appearing in either primes | odds # with an operator primes.union(odds) # equivalently with a method # intersection: items appearing in both primes & odds # with an operator primes.intersection(odds) # equivalently with a method # difference: items in primes but not in odds primes - odds # with an operator primes.difference(odds) # equivalently with a method # symmetric difference: items appearing in only one set primes ^ odds # with an operator primes.symmetric_difference(odds) # equivalently with a method ###Output _____no_output_____ ###Markdown Many more set methods and operations are available. You've probably already guessed what I'll say next: refer to Python's [online documentation](https://docs.python.org/3/tutorial/datastructures.html) for a complete reference. Part 8: Control FlowControl flow is where the rubber really meets the road in programming. Without it, a program is simply a list of statements that are sequentially executed. With control flow, you can execute certain code blocks conditionally and/or repeatedly: these basic building blocks can be combined to create surprisingly sophisticated programs!Here we'll cover **conditional statements** (including "if", "elif", and "else") and **loop statements** (including "for" and "while" and the accompanying "break", "continue", and "pass"). Conditional Statements: if-elif-else:Conditional statements, often referred to as if-then statements, allow the programmer to execute certain pieces of code depending on some Boolean condition. A basic example of a Python conditional statement is this: ###Code x = -15 if x == 0: print(x, "is zero") elif x > 0: print(x, "is positive") elif x < 0: print(x, "is negative") else: print(x, "is unlike anything I've ever seen...") ###Output -15 is negative ###Markdown Note especially the use of colons (:) and whitespace to denote separate blocks of code.Python adopts the if and else often used in other languages; its more unique keyword is elif, a contraction of "else if". In these conditional clauses, elif and else blocks are optional; additionally, you can optinally include as few or as many elif statements as you would like. for loopLoops in Python are a way to repeatedly execute some code statement. So, for example, if we'd like to print each of the items in a list, we can use a for loop: ###Code for N in [2,3,5,7]: print(N, end=' ') # print all on same line ###Output 2 3 5 7 ###Markdown Notice the simplicity of the for loop: we specify the variable we want to use, the sequence we want to loop over, and use the "in" operator to link them together in an intuitive and readable way. More precisely, the object to the right of the "in" can be any Python **iterator**.For example, one of the most commonly-used iterators in Python is the range object, which generates a sequence of numbers: ###Code for i in range(10): print(i, end=' ') ###Output 0 1 2 3 4 5 6 7 8 9 ###Markdown Note that the range starts at zero by default, and that by convention the top of the range is not included in the output. Range objects can also have more complicated values: ###Code # range from 5 to 10 list(range(5, 10)) # range from 0 to 10 by 2 list(range(0, 10, 2)) ###Output _____no_output_____ ###Markdown while loopsThe other type of loop in Python is a while loop, which iterates until some condition is met: ###Code i = 0 while i < 10: print(i, end=' ') i += 1 ###Output 0 1 2 3 4 5 6 7 8 9 ###Markdown The argument of the while loop is evaluated as a boolean statement, and the loop is executed until the statement evaluates to False. break and continue: Fine-Tuning Your LoopsThere are two useful statements that can be used within loops to fine-tune how they are executed:* The break statement breaks-out of the loop entirely* The continue statement skips the remainder of the current loop, and goes to the next iterationThese can be used in both for and while loops.Here is an example of using continue to print a string of odd numbers. In this case, the result could be accomplished just as well with an if-else statement, but sometimes the continue statement can be a more convenient way to express the idea you have in mind: ###Code for n in range(20): # if the remainder of n / 2 is 0, skip the rest of the loop if n % 2 == 0: continue print(n, end=' ') ###Output 1 3 5 7 9 11 13 15 17 19 ###Markdown Here is an example of a break statement used for a less trivial task. This loop will fill a list with all Fibonacci numbers up to a certain value: ###Code a, b = 0, 1 amax = 100 L = [] while True: (a, b) = (b, a + b) if a > amax: break L.append(a) print(L) ###Output [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ###Markdown Notice that we use a while True loop, which will loop forever unless we have a break statement! Part 9: Defining and Using FunctionsSo far, our scripts have been simple, single-use code blocks. One way to organize our Python code and to make it more readable and reusable is to factor-out useful pieces into reusable functions. Here we'll cover two ways of creating functions: the def statement, useful for any type of function, and the lambda statement, useful for creating short anonymous functions. Using FunctionsFunctions are groups of code that have a name, and can be called using parentheses. We've seen functions before. For example, print in Python 3 is a function: ###Code print('abc') ###Output abc ###Markdown Here print is the function name, and 'abc' is the function's argument.In addition to arguments, there are keyword arguments that are specified by name. One available keyword argument for the print() function (in Python 3) is sep, which tells what character or characters should be used to separate multiple items: ###Code print(1, 2, 3) print(1, 2, 3, sep='--') ###Output 1--2--3 ###Markdown When non-keyword arguments are used together with keyword arguments, the keyword arguments must come at the end. Defining FunctionsFunctions become even more useful when we begin to define our own, organizing functionality to be used in multiple places. In Python, functions are defined with the def statement. For example, we can encapsulate a version of our Fibonacci sequence code from the previous section as follows: ###Code def fibonacci(N): L = [] a, b = 0, 1 while len(L) < N: a, b = b, a + b L.append(a) return L ###Output _____no_output_____ ###Markdown Now we have a function named fibonacci which takes a single argument N, does something with this argument, and returns a value; in this case, a list of the first N Fibonacci numbers: ###Code fibonacci(10) ###Output _____no_output_____ ###Markdown If you're familiar with strongly-typed languages like Java, you'll immediately notice that there is no type information associated with the function inputs or outputs. Python functions can return any Python object, simple or compound, which means constructs that may be difficult in other languages are straightforward in Python.For example, multiple return values are simply put in a tuple, which is indicated by commas: ###Code def real_imag_conj(val): return val.real, val.imag, val.conjugate() r, i, c = real_imag_conj(3 + 4j) print(r, i, c) ###Output 3.0 4.0 (3-4j) ###Markdown Default Argument ValuesOften when defining a function, there are certain values that we want the function to use most of the time, but we'd also like to give the user some flexibility. In this case, we can use default values for arguments. Consider the fibonacci function from before. What if we would like the user to be able to play with the starting values? We could do that as follows: ###Code def fibonacci(N, a=0, b=1): L = [] while len(L) < N: a, b = b, a + b L.append(a) return L ###Output _____no_output_____ ###Markdown With a single argument, the result of the function call is identical to before: ###Code fibonacci(10) ###Output _____no_output_____ ###Markdown But now we can use the function to explore new things, such as the effect of new starting values: ###Code fibonacci(10, 0, 2) ###Output _____no_output_____ ###Markdown The values can also be specified by name if desired, in which case the order of the named values does not matter: ###Code fibonacci(10, b=3, a=1) ###Output _____no_output_____ ###Markdown \*args and **kwargs: Flexible ArgumentsSometimes you might wish to write a function in which you don't initially know how many arguments the user will pass. In this case, you can use the special form \*args and \*\*kwargs to catch all arguments that are passed. Here is an example: ###Code def catch_all(*args, **kwargs): print("args =", args) print("kwargs = ", kwargs) catch_all(1, 2, 3, a=4, b=5) catch_all('a', keyword=2) ###Output args = ('a',) kwargs = {'keyword': 2} ###Markdown Here it is not the names args and kwargs that are important, but the \* characters preceding them. args and kwargs are just the variable names often used by convention, short for "arguments" and "keyword arguments". The operative difference is the asterisk characters: a single \* before a variable means "expand this as a sequence", while a double \*\* before a variable means "expand this as a dictionary". In fact, this syntax can be used not only with the function definition, but with the function call as well! ###Code inputs = (1, 2, 3) keywords = {'pi': 3.14} catch_all(*inputs, **keywords) ###Output args = (1, 2, 3) kwargs = {'pi': 3.14} ###Markdown Anonymous (lambda) FunctionsEarlier we quickly covered the most common way of defining functions, the def statement. You'll likely come across another way of defining short, one-off functions with the lambda statement. It looks something like this: ###Code add = lambda x, y: x + y add(1, 2) ###Output _____no_output_____ ###Markdown This lambda function is roughly equivalent to ###Code def add(x, y): return x + y ###Output _____no_output_____ ###Markdown So why would you ever want to use such a thing? Primarily, it comes down to the fact that everything is an object in Python, even functions themselves! That means that functions can be passed as arguments to functions.As an example of this, suppose we have some data stored in a list of dictionaries: ###Code data = [{'first':'Guido', 'last':'Van Rossum', 'YOB':1956}, {'first':'Grace', 'last':'Hopper', 'YOB':1906}, {'first':'Alan', 'last':'Turing', 'YOB':1912}] ###Output _____no_output_____ ###Markdown Now suppose we want to sort this data. Python has a sorted function that does this: ###Code sorted([2,4,3,5,1,6]) ###Output _____no_output_____ ###Markdown But dictionaries are not orderable: we need a way to tell the function how to sort our data. We can do this by specifying the key function, a function which given an item returns the sorting key for that item: ###Code # sort alphabetically by first name sorted(data, key=lambda item: item['first']) # sort by year of birth sorted(data, key=lambda item: item['YOB']) ###Output _____no_output_____ ###Markdown While these key functions could certainly be created by the normal, def syntax, the lambda syntax is convenient for such short one-off functions like these. Part 10: Errors and ExceptionsNo matter your skill as a programmer, you will eventually make a coding mistake. Such mistakes come in three basic flavors:* Syntax errors: Errors where the code is not valid Python (generally easy to fix)* Runtime errors: Errors where syntactically valid code fails to execute, perhaps due to invalid user input (sometimes easy to fix)* Semantic errors: Errors in logic: code executes without a problem, but the result is not what you expect (often very difficult to track-down and fix)Here we're going to focus on how to deal cleanly with runtime errors. As we'll see, Python handles runtime errors via its exception handling framework. Runtime ErrorsIf you've done any coding in Python, you've likely come across runtime errors. They can happen in a lot of ways.For example, if you try to reference an undefined variable: ###Code print(Q) ###Output _____no_output_____ ###Markdown Or if you try an operation that's not defined: ###Code 1 + 'abc' ###Output _____no_output_____ ###Markdown Or you might be trying to compute a mathematically ill-defined result: ###Code 2 / 0 ###Output _____no_output_____ ###Markdown Or maybe you're trying to access a sequence element that doesn't exist: ###Code L = [1, 2, 3] L[1000] ###Output _____no_output_____ ###Markdown Note that in each case, Python is kind enough to not simply indicate that an error happened, but to spit out a meaningful exception that includes information about what exactly went wrong, along with the exact line of code where the error happened. Having access to meaningful errors like this is immensely useful when trying to trace the root of problems in your code. Catching Exceptions: try and exceptThe main tool Python gives you for handling runtime exceptions is the try...except clause. Its basic structure is this: ###Code try: print("this gets executed first") except: print("this gets executed only if there is an error") ###Output this gets executed first ###Markdown Note that the second block here did not get executed: this is because the first block did not return an error. Let's put a problematic statement in the try block and see what happens: ###Code try: print("let's try something:") x = 1 / 0 # ZeroDivisionError except: print("something bad happened!") ###Output let's try something: something bad happened! ###Markdown Here we see that when the error was raised in the try statement (in this case, a ZeroDivisionError), the error was caught, and the except statement was executed.One way this is often used is to check user input within a function or another piece of code. For example, we might wish to have a function that catches zero-division and returns some other value, perhaps a suitably large number like $10^{100}$: ###Code def safe_divide(a, b): try: return a / b except: return 1E100 safe_divide(1, 2) safe_divide(2, 0) ###Output _____no_output_____ ###Markdown There is a subtle problem with this code, though: what happens when another type of exception comes up? For example, this is probably not what we intended: ###Code safe_divide (1, '2') # Notice that 2 is a string in this case ###Output _____no_output_____ ###Markdown Dividing an integer and a string raises a TypeError, which our over-zealous code caught and assumed was a ZeroDivisionError! For this reason, it's nearly always a better idea to catch exceptions explicitly: ###Code def safe_divide(a, b): try: return a / b except ZeroDivisionError: return 1E100 safe_divide(1, 0) safe_divide(1, '2') ###Output _____no_output_____ ###Markdown We're now catching zero-division errors only, and letting all other errors pass through un-modified. Raising Exceptions: raiseWe've seen how valuable it is to have informative exceptions when using parts of the Python language. It's equally valuable to make use of informative exceptions within the code you write, so that users of your code (foremost yourself!) can figure out what caused their errors.The way you raise your own exceptions is with the raise statement. For example: ###Code raise RuntimeError("my error message") ###Output _____no_output_____ ###Markdown As an example of where this might be useful, let's return to our fibonacci function that we defined previously: ###Code def fibonacci(N): L = [] a, b = 0, 1 while len(L) < N: a, b = b, a + b L.append(a) return L ###Output _____no_output_____ ###Markdown One potential problem here is that the input value could be negative. This will not currently cause any error in our function, but we might want to let the user know that a negative N is not supported. Errors stemming from invalid parameter values, by convention, lead to a ValueError being raised: ###Code def fibonacci(N): if N < 0: raise ValueError("N must be non-negative") L = [] a, b = 0, 1 while len(L) < N: a, b = b, a + b L.append(a) return L fibonacci(10) fibonacci(-10) ###Output _____no_output_____ ###Markdown Now the user knows exactly why the input is invalid, and could even use a try...except block to handle it! ###Code N = -10 try: print("trying this...") print(fibonacci(N)) except ValueError: print("Bad value: need to do something else") ###Output trying this... Bad value: need to do something else ###Markdown Diving Deeper into ExceptionsBriefly, I want to mention here some other concepts you might run into. I'll not go into detail on these concepts and how and why to use them, but instead simply show you the syntax so you can explore more on your own. Accessing the error messageSometimes in a try...except statement, you would like to be able to work with the error message itself. This can be done with the as keyword: ###Code try: x = 1 / 0 except ZeroDivisionError as err: print("Error class is: ", type(err)) print("Error message is:", err) ###Output Error class is: <class 'ZeroDivisionError'> Error message is: division by zero ###Markdown With this pattern, you can further customize the exception handling of your function. Defining custom exceptionsIn addition to built-in exceptions, it is possible to define custom exceptions through class inheritance. For instance, if you want a special kind of ValueError, you can do this: ###Code class MySpecialError(ValueError): pass raise MySpecialError("here's the message") ###Output _____no_output_____ ###Markdown This would allow you to use a try...except block that only catches this type of error: ###Code try: print("do something") raise MySpecialError("[informative error message here]") except MySpecialError: print("do something else") ###Output do something do something else ###Markdown You might find this useful as you develop more customized code. try...except...else...finallyIn addition to try and except, you can use the else and finally keywords to further tune your code's handling of exceptions. The basic structure is this: ###Code try: print("try something here") except: print("this happens only if it fails") else: print("this happens only if it succeeds") finally: print("this happens no matter what") ###Output try something here this happens only if it succeeds this happens no matter what
nbs/01-02-partitionnement-k-moyennes/01-02-A2.ipynb
###Markdown **420-A58-SF - Algorithmes d'apprentissage non supervisé - Été 2021 - Spécialisation technique en Intelligence Artificielle**MIT License - Copyright (c) 2021 Mikaël Swawola![Travaux Pratiques - partitionnement-k-moyennes (sklearn)](static/01-02-A2-banner.png)**Objectif:** cet atelier a pour objectif la mise en oeuvre du partitionnement K-moyennes à l'aide de la librairie scikit-learn ###Code %reload_ext autoreload %autoreload 2 %matplotlib inline ###Output _____no_output_____ ###Markdown 1 - Lecture et visualisation des données ###Code import pandas as pd import seaborn as sns; sns.set() import matplotlib.pyplot as plt # Chargement des données blobs = pd.read_csv('../../data/blobs.csv') # Configuration de la visualisation sns.set(style="darkgrid") sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5}) plt.rcParams['figure.figsize']=(12,8) _ = sns.scatterplot(x="x0", y="x1", data=blobs) plt.xlabel('x0') plt.ylabel('x1') ###Output _____no_output_____ ###Markdown 2 - Mise en oeuvre du partitionnement K-moyennes avec scikit-learn **Exercice 1-1 - Initialiser la variable K, représentant le nombre de clusters estimé à partir de la visualisation précédente** ###Code # Compléter cette cellule ~ 1 ligne de code ###Output _____no_output_____ ###Markdown **Exercice 1-2 - À l'aide de scikit-learn, effectuer le partitionnement K-moyennes** [class sklearn.cluster.KMeans(n_clusters=8, *, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='deprecated', verbose=0, random_state=None, copy_x=True, n_jobs='deprecated', algorithm='auto')](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html) ###Code # Compléter cette cellule ~ 3-5 lignes de code ###Output _____no_output_____ ###Markdown **Exercice 1-3 - Afficher les centroïdes et les "labels" (ou indices, c) de chaque observation** ###Code # Compléter cette cellule ~ 2-4 lignes de code ###Output _____no_output_____
results/plot.ipynb
###Markdown Visualize Results Imports ###Code %matplotlib inline import numpy as np import matplotlib.pyplot as plt import os from fnmatch import fnmatch from tensorboard.backend.event_processing.event_accumulator import EventAccumulator ###Output _____no_output_____ ###Markdown Load Data ###Code def get_sorted_summary_paths(path): paths = [] for path, subdirs, files in os.walk(path): for name in files: if fnmatch(name, "*.0"): paths.append(os.path.join(path, name)) return paths summary_paths = get_sorted_summary_paths("./poc_summaries/") summaries = [EventAccumulator(path) for path in summary_paths] for i in range(len(summaries)): summaries[i].Reload() ###Output _____no_output_____ ###Markdown Available data keys ###Code print(summaries[0].scalars.Keys()) ###Output ['episode/success_percent', 'episode/success_mean', 'episode/reward_mean', 'episode/length_mean', 'losses/loss', 'losses/policy_loss', 'losses/value_loss', 'losses/entropy', 'training/sequence_length', 'training/value_mean', 'training/advantage_mean'] ###Markdown Convert data to a numpy array ###Code mean_rewards = [] for summary in summaries: _, t, v = zip(*summary.Scalars("episode/reward_mean")) mean_rewards.append(v) mean_rewards = np.asarray(mean_rewards, dtype=np.float32) ###Output _____no_output_____ ###Markdown Prepare data ###Code mean = np.mean(mean_rewards, axis=0) std = np.std(mean_rewards, axis=0) ###Output _____no_output_____ ###Markdown Plot data ###Code plt.rcParams.update({'font.size': 12}) plt.rcParams['figure.facecolor'] = "white" plt.rcParams['axes.facecolor'] = "white" fig, ax = plt.subplots() fig.set_size_inches(7, 5.5) ax.plot(t, mean) ax.fill_between(t, mean + std, mean - std, alpha=0.3) ax.set_ylabel("Mean Reward") ax.set_ylim([-2.5,1.5]) ax.set_xlabel("PPO Update") ax.set_xlim([0,t[-1]]) ax.set_title("Training Performance across 10 Runs") #plt.savefig("poc.svg") plt.show() ###Output _____no_output_____
Cleaning employee exit surveys/Cleaning employee exit surveys.ipynb
###Markdown Analysing employees' reasons for quittingIn this project we will examine the following questions* Are employees who only worked for the institutes for a short period of time resigning due to some kind of dissatisfaction? What about employees who have been there longer?* Are younger employees resigning due to some kind of dissatisfaction? Is it the same for older employees?In order to do this, we will first need to clean the data to get into a format that makes analysis easier. Exploration and observation of dataframes ###Code # setting up notebook import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use('ggplot') # read in survey data dete_survey = pd.read_csv('dete_survey.csv') tafe_survey = pd.read_csv('tafe_survey.csv') ###Output _____no_output_____ ###Markdown Let's first take a look at the data sets. We'll start with dete ###Code dete_survey.info() dete_survey.head() dete_survey.columns # view each separately dete_survey['SeparationType'].value_counts() dete_survey['DETE Start Date'].value_counts() dete_survey['Region'].value_counts() dete_survey['Interpersonal conflicts'].value_counts() dete_survey['Business Unit'].value_counts() dete_survey['Career Aspirations'].value_counts() dete_survey['Worklife balance'].value_counts() dete_survey.isnull().sum() tafe_survey.info() tafe_survey.head() tafe_survey.isnull().sum() tafe_survey.columns # view each separately print(tafe_survey['Reason for ceasing employment'].value_counts()) print(' ') print(tafe_survey['Contributing Factors. Career Move - Private Sector '].value_counts()) print(' ') print(tafe_survey['InstituteViews. Topic:10. Staff morale was positive within the Institute'].value_counts()) print(' ') print(tafe_survey['WorkUnitViews. Topic:17. I was encouraged to use my initiative in the course of my work'].value_counts()) ###Output Resignation 340 Contract Expired 127 Retrenchment/ Redundancy 104 Retirement 82 Transfer 25 Termination 23 Name: Reason for ceasing employment, dtype: int64 - 336 Career Move - Private Sector 101 Name: Contributing Factors. Career Move - Private Sector , dtype: int64 Neutral 154 Agree 146 Disagree 139 Strongly Disagree 109 Strongly Agree 47 Not Applicable 7 Name: InstituteViews. Topic:10. Staff morale was positive within the Institute, dtype: int64 Agree 253 Strongly Agree 198 Neutral 86 Disagree 40 Strongly Disagree 27 Not Applicable 6 Name: WorkUnitViews. Topic:17. I was encouraged to use my initiative in the course of my work, dtype: int64 ###Markdown Observations:* Some columns could be melted. * In `dete_survey`, NaN values are conveyed at 'Not Stated'* Many unnecessary columns (unrelated to our question)* In each dataframe same column but different name (must rename) Change NA values and drop unnecessary columns We will read in the `dete_survey` dataframe again, this time specifying the `na values` and 'Not Stated.After that, let's drop the columns that will not be relevant to our analysis. ###Code # read in replacing Not Stated as NaN dete_survey = pd.read_csv('dete_survey.csv', na_values='Not Stated') # dropping unused columns dete_survey_updated = dete_survey.drop(dete_survey.columns[28:49], axis=1) tafe_survey_updated = tafe_survey.drop(tafe_survey.columns[17:66], axis=1) ###Output _____no_output_____ ###Markdown Standardise column names In order to merge the two dataframes we will need to clean the column names and rename some columns. To save time, we'll create a function that cleans the column names. ###Code # function to clean columns names def clean_columns(df): df.columns = df.columns.str.lower().str.strip().str.replace(' ', '_') return df.columns clean_columns(dete_survey_updated) dete_survey_updated.columns # Rename column names of tafe survey tafe_survey_updated_2 = tafe_survey_updated.copy() tafe_survey_updated_2.columns tafe_survey_updated_2 = tafe_survey_updated_2.rename(columns={'Record ID': 'id', 'CESSATION YEAR': 'cease_date', 'Reason for ceasing employment': 'separationtype', 'Gender. What is your Gender?': 'gender', 'CurrentAge. Current Age': 'age', 'Employment Type. Employment Type': 'employment_status', 'Classification. Classification': 'position', 'LengthofServiceOverall. Overall Length of Service at Institute (in years)': 'institute_service', 'LengthofServiceCurrent. Length of Service at current workplace (in years)': 'role_service' }) tafe_survey_updated.columns = tafe_survey_updated_2.columns ###Output _____no_output_____ ###Markdown Filter the data Next, as we are analysing employees who voluntary chose to leave the institute, we only want to examine columns containing the string `'Resignation'`. ###Code print(dete_survey_updated['separationtype'].value_counts()) print('\n') print(tafe_survey_updated['separationtype'].value_counts()) # select resignation type columns dete_resignations = dete_survey_updated[(dete_survey_updated['separationtype'] == 'Resignation-Other reasons') | (dete_survey_updated['separationtype'] == 'Resignation-Other employer') | (dete_survey_updated['separationtype'] == 'Resignation-Move overseas/interstate')] dete_resignations = dete_resignations.copy() tafe_resignations = tafe_survey_updated.loc[tafe_survey_updated['separationtype'] == 'Resignation'] tafe_resignations = tafe_resignations.copy() print(dete_resignations.head()) print('\n') print(tafe_resignations.head()) ###Output id separationtype cease_date dete_start_date \ 3 4 Resignation-Other reasons 05/2012 2005.0 5 6 Resignation-Other reasons 05/2012 1994.0 8 9 Resignation-Other reasons 07/2012 2009.0 9 10 Resignation-Other employer 2012 1997.0 11 12 Resignation-Move overseas/interstate 2012 2009.0 role_start_date position classification region \ 3 2006.0 Teacher Primary Central Queensland 5 1997.0 Guidance Officer NaN Central Office 8 2009.0 Teacher Secondary North Queensland 9 2008.0 Teacher Aide NaN NaN 11 2009.0 Teacher Secondary Far North Queensland business_unit employment_status ... work_life_balance \ 3 NaN Permanent Full-time ... False 5 Education Queensland Permanent Full-time ... False 8 NaN Permanent Full-time ... False 9 NaN Permanent Part-time ... False 11 NaN Permanent Full-time ... False workload none_of_the_above gender age aboriginal torres_strait \ 3 False False Female 36-40 NaN NaN 5 False False Female 41-45 NaN NaN 8 False False Female 31-35 NaN NaN 9 False False Female 46-50 NaN NaN 11 False False Male 31-35 NaN NaN south_sea disability nesb 3 NaN NaN NaN 5 NaN NaN NaN 8 NaN NaN NaN 9 NaN NaN NaN 11 NaN NaN NaN [5 rows x 35 columns] id Institute \ 3 6.341399e+17 Mount Isa Institute of TAFE 4 6.341466e+17 Southern Queensland Institute of TAFE 5 6.341475e+17 Southern Queensland Institute of TAFE 6 6.341520e+17 Barrier Reef Institute of TAFE 7 6.341537e+17 Southern Queensland Institute of TAFE WorkArea cease_date separationtype \ 3 Non-Delivery (corporate) 2010.0 Resignation 4 Delivery (teaching) 2010.0 Resignation 5 Delivery (teaching) 2010.0 Resignation 6 Non-Delivery (corporate) 2010.0 Resignation 7 Delivery (teaching) 2010.0 Resignation Contributing Factors. Career Move - Public Sector \ 3 - 4 - 5 - 6 - 7 - Contributing Factors. Career Move - Private Sector \ 3 - 4 Career Move - Private Sector 5 - 6 Career Move - Private Sector 7 - Contributing Factors. Career Move - Self-employment \ 3 - 4 - 5 - 6 - 7 - Contributing Factors. Ill Health Contributing Factors. Maternity/Family \ 3 - - 4 - - 5 - - 6 - Maternity/Family 7 - - ... Contributing Factors. Study Contributing Factors. Travel \ 3 ... - Travel 4 ... - - 5 ... - - 6 ... - - 7 ... - - Contributing Factors. Other Contributing Factors. NONE gender \ 3 - - NaN 4 - - Male 5 Other - Female 6 Other - Male 7 Other - Male age employment_status position \ 3 NaN NaN NaN 4 41 45 Permanent Full-time Teacher (including LVT) 5 56 or older Contract/casual Teacher (including LVT) 6 20 or younger Temporary Full-time Administration (AO) 7 46 50 Permanent Full-time Teacher (including LVT) institute_service role_service 3 NaN NaN 4 3-4 3-4 5 7-10 7-10 6 3-4 3-4 7 3-4 3-4 [5 rows x 23 columns] ###Markdown Data verification Now we must check the dates are in a reasonable range. Let's use the following criteria:* No start dates before 1940 (this would be unlikely)* No cease dates after current date ###Code dete_resignations['cease_date'].value_counts() dete_resignations['cease_date'] = dete_resignations['cease_date'].str.extract(r'([2][0][0-9]{2})').astype('float') dete_resignations['dete_start_date'].value_counts(dropna=False).sort_values(ascending=False) dete_resignations['cease_date'].value_counts().sort_values(ascending=False) tafe_resignations['cease_date'].value_counts().sort_values(ascending=False) ###Output _____no_output_____ ###Markdown Create column specifying service lengthIn order to answer our question if employees who worked for a shorter time period resigned due to dissatisfaction, we need a column to indicate the length of time they worked. ###Code # creating institute_service column for dete dete_resignations['institute_service'] = dete_resignations['cease_date'] - dete_resignations['dete_start_date'] tafe_resignations.head() print(dete_resignations.columns) print('\n') print(tafe_resignations.columns) ###Output Index(['id', 'separationtype', 'cease_date', 'dete_start_date', 'role_start_date', 'position', 'classification', 'region', 'business_unit', 'employment_status', 'career_move_to_public_sector', 'career_move_to_private_sector', 'interpersonal_conflicts', 'job_dissatisfaction', 'dissatisfaction_with_the_department', 'physical_work_environment', 'lack_of_recognition', 'lack_of_job_security', 'work_location', 'employment_conditions', 'maternity/family', 'relocation', 'study/travel', 'ill_health', 'traumatic_incident', 'work_life_balance', 'workload', 'none_of_the_above', 'gender', 'age', 'aboriginal', 'torres_strait', 'south_sea', 'disability', 'nesb', 'institute_service'], dtype='object') Index(['id', 'Institute', 'WorkArea', 'cease_date', 'separationtype', 'Contributing Factors. Career Move - Public Sector ', 'Contributing Factors. Career Move - Private Sector ', 'Contributing Factors. Career Move - Self-employment', 'Contributing Factors. Ill Health', 'Contributing Factors. Maternity/Family', 'Contributing Factors. Dissatisfaction', 'Contributing Factors. Job Dissatisfaction', 'Contributing Factors. Interpersonal Conflict', 'Contributing Factors. Study', 'Contributing Factors. Travel', 'Contributing Factors. Other', 'Contributing Factors. NONE', 'gender', 'age', 'employment_status', 'position', 'institute_service', 'role_service'], dtype='object') ###Markdown Identify dissatified employeesNow, let's make a new column `dissatisfied` with a boolean value. ###Code tafe_resignations['Contributing Factors. Dissatisfaction'].value_counts(dropna=False) tafe_resignations['Contributing Factors. Job Dissatisfaction'].value_counts(dropna=False) # converting values to boolean def update_value(x): if pd.isnull(x): return np.nan elif x == '-': return False else: return True # apply function to tafe survey tafe_resignations[['Contributing Factors. Job Dissatisfaction', 'Contributing Factors. Dissatisfaction']] = tafe_resignations[['Contributing Factors. Job Dissatisfaction', 'Contributing Factors. Dissatisfaction']].applymap(update_value) tafe_resignations['Contributing Factors. Dissatisfaction'].value_counts(dropna=False) tafe_resignations['Contributing Factors. Job Dissatisfaction'].value_counts(dropna=False) dete_resignations['job_dissatisfaction'].value_counts() tafe_resignations['dissatisfied'] = tafe_resignations[['Contributing Factors. Dissatisfaction', 'Contributing Factors. Job Dissatisfaction'] ].any(axis=1, skipna=False) dete_resignations.columns dete_resignations['dissatisfied'] = dete_resignations[['job_dissatisfaction', 'dissatisfaction_with_the_department', 'physical_work_environment', 'lack_of_recognition', 'lack_of_job_security', 'work_location', 'employment_conditions', 'work_life_balance', 'workload'] ].any(axis=1, skipna=False) dete_resignations['dissatisfied'].value_counts(dropna=False) dete_resignations_up = dete_resignations.copy() tafe_resignations_up = tafe_resignations.copy() ###Output _____no_output_____ ###Markdown Combining dataframesFirst, we will create an additional column specifying the institute name to use as a reference point. Then, let's join the the two dataframes, dropping any unneeded columns. ###Code dete_resignations_up['institute'] = 'DETE' tafe_resignations_up['institute'] = 'TAFE' # combine dataframes combined = pd.concat([dete_resignations_up, tafe_resignations_up], ignore_index=True) combined_updated = combined.dropna(thresh=500, axis=1) combined_updated['institute_service'] = combined_updated['institute_service'].astype(str) combined_updated['institute_service'] = combined_updated['institute_service'].str.extract('(\d+)').astype(float) combined_updated = combined_updated.copy() ###Output _____no_output_____ ###Markdown Categorise experience levelTo make comparison easier, we will categorise the `institute_service` column based on career stage. Let's use the following categories:* New: less than 3 years experience* Experienced: 3 to 6 years experience* Established: 7 to 10 years experience* Veteran: More than 10 years experience ###Code # create function to categorise experience level def categorize(val): if val < 3: return 'New' elif 3 <= val <= 6: return 'Experienced' elif 7 <= val <= 10: return 'Established' elif 11 <= val: return 'Veteran' elif pd.isnull(val): return np.nan combined_updated['service_cat'] = combined_updated['institute_service'].apply(categorize) combined_updated['service_cat'].value_counts(dropna=False) ###Output _____no_output_____ ###Markdown Fill missing valuesAs the `dissatisfied` column contains few `na` values, we will fill them with the most common value, `False`. ###Code combined_updated['dissatisfied'].value_counts(dropna=False) combined_updated['dissatisfied'] = combined_updated['dissatisfied'].fillna('False') combined_updated['dissatisfied'] = combined_updated['dissatisfied'].astype(bool) ###Output _____no_output_____ ###Markdown Visualisation of results ###Code # pivot table for experience levels pivot_tbl = combined_updated.pivot_table(values='dissatisfied', index='service_cat' ) pivot_tbl.plot(kind='barh', legend=False) plt.title('''Pct employees leave due to dissatisfaction (by career stage)''') plt.show() ###Output _____no_output_____
RPA in Data Science Life Cycle - Ganesh Ram - Livewire Dissertation.ipynb
###Markdown Robotic Process Automation in Data Science Life Cycle - Ganesh Ram Gururajan - Livewire Dissertation ###Code # Salaries.csv imported ###Output _____no_output_____ ###Markdown Package import preparation ###Code # Importing Packages import pandas as pd import numpy as np import seaborn as sns ###Output _____no_output_____ ###Markdown Import statement Give Location and target as "location*target" ###Code process = "E:/GPRS/GNS3 IOS/Refactored_Py_DS_ML_Bootcamp-master/04-Pandas-Exercises/Salaries.csv*TotalPay" #Storing Location of file in a string location = process.split('*')[0] location target = process.split('*')[1] target #Finding the extension of the file ext = location.split('.')[1] # Importing Data Accoring to the extension if ext == 'csv': data = pd.read_csv(location) print('--reading csv file--') else: data = pd.read_excel(location) print('--reading excel file--') print('The shape of the given data is {}'.format(data.shape)) data.head() if len(data[target].value_counts().index) < 10: ml_needed = 'Classification' else: ml_needed = 'Regression' print('According to the target column specified {} is need to be performed'.format(ml_needed)) sns.heatmap(data.isnull()) ###Output _____no_output_____ ###Markdown Data Cleaning ###Code #Storing column names as key and percentage of missing data as corresponding values in a dictionary missing_dict = {} no_of_rows = data.shape[0] for column in data.columns: count = data[column].describe()['count'] missing_ratio = (no_of_rows - count)/no_of_rows missing_dict[column] = round(missing_ratio,10) print('--Priting a dictionary with missing values--') print(missing_dict) # Removing columns with 35% or more missing data highly_missing_features = [] for (column,miss) in missing_dict.items(): if miss>=0.35: highly_missing_features.append(column) print('--Highly Missing features--') print(highly_missing_features) data.drop(highly_missing_features,axis=1,inplace=True) data.head() print('--printing data types of features--') print(data.dtypes) #Obtaining Numerical Columns num_cols = list(data._get_numeric_data().columns) # Obtaining Categorical columns from removing numerical columns from all columns cat_cols = list(set(data.columns) - set(num_cols)) cat_cols # Finding columns with all rows of unique values or only one unique value unique_or_no_change_cat_cols = [] for column in cat_cols: no_of_values = len(data[column].value_counts().index) if no_of_values == no_of_rows or no_of_values == 1: unique_or_no_change_cat_cols.append(column) print('--Removing unique or no change columns--') unique_or_no_change_cat_cols data.drop(unique_or_no_change_cat_cols,axis=1,inplace=True) data.head() ###Output _____no_output_____ ###Markdown Imputation ###Code # To find columns to be imputed from missing dictionary columns_to_be_imputed = [] for (column,ratio) in missing_dict.items(): if ratio <0.35 and ratio > 0.1: columns_to_be_imputed.append(column) print('--columns to be imputed--') columns_to_be_imputed def mean_impute(col): if pd.isnull(col): return data[column].mean() else: return col def mode_impute(col): if pd.isnull(col): return data[column].mode() else: return col for column in columns_to_be_imputed: if data[column].dtypes == 'float64': data[column] = data[column].apply(mean_impute) if data[column].dtypes == 'O': data[column] = data[column].apply(mode_impute) data = data.dropna() sns.heatmap(data.isnull()) ###Output _____no_output_____ ###Markdown Dummies ###Code new_num_cols = data._get_numeric_data() new_cat_cols = list(set(data.columns) - set(new_num_cols)) print('--Encoding newly derived categorical columns--') new_cat_cols def get_dummy(col): return categories.index(col) for column in new_cat_cols: categories = list(data[column].value_counts().index) data[column] = data[column].apply(get_dummy) ###Output _____no_output_____ ###Markdown Train test split ###Code X = data.drop(target,axis=1) y = data[target] from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.25,random_state=100) ###Output _____no_output_____ ###Markdown Machine Learning ###Code if ml_needed == 'Classification': from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from xgboost import XGBClassifier from sklearn.metrics import accuracy_score dt = DecisionTreeClassifier() rf = RandomForestClassifier() ada = AdaBoostClassifier() xgb = XGBClassifier() if ml_needed == 'Regression': from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor, AdaBoostRegressor from xgboost import XGBRegressor from sklearn.metrics import mean_absolute_error dt = DecisionTreeRegressor() rf = RandomForestRegressor() ada = AdaBoostRegressor() xgb = XGBRegressor() ###Output _____no_output_____ ###Markdown Fit Function ###Code dt.fit(X_train,y_train) rf.fit(X_train,y_train) ada.fit(X_train,y_train) xgb.fit(X_train,y_train) ###Output C:\Users\LIVEWIRE\Anaconda3\lib\site-packages\sklearn\ensemble\forest.py:245: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22. "10 in version 0.20 to 100 in 0.22.", FutureWarning) C:\Users\LIVEWIRE\Anaconda3\lib\site-packages\xgboost\core.py:587: FutureWarning: Series.base is deprecated and will be removed in a future version if getattr(data, 'base', None) is not None and \ ###Markdown Prediction ###Code pred1 = dt.predict(X_test) pred2 = rf.predict(X_test) pred3 = ada.predict(X_test) pred4 = xgb.predict(X_test) algorithms_order = ['DecisionTree','RandomForest','AdaBoost','XGBoost'] ###Output _____no_output_____ ###Markdown Conclusion ###Code if ml_needed == 'Classification': acc1 = accuracy_score(y_test,pred1) acc2 = accuracy_score(y_test,pred2) acc3 = accuracy_score(y_test,pred3) acc4 = accuracy_score(y_test,pred4) ml_metrics = [acc1,acc2,acc3,acc4] highes_accuracy = max(ml_metrics) best_algorithm = algorithms_order[ml_metrics.index(highest_accuracy)] print('The Best Algorithm is {} with highest accuracy of {}'.format(best_algorithm,highes_accuracy)) if ml_needed == 'Regression': mae1 = mean_absolute_error(y_test,pred1) mae2 = mean_absolute_error(y_test,pred2) mae3 = mean_absolute_error(y_test,pred3) mae4 = mean_absolute_error(y_test,pred4) ml_metrics = [mae1,mae2,mae3,mae4] min_mae = min(ml_metrics) best_algorithm = algorithms_order[ml_metrics.index(min_mae)] print('The Best Algorithm is {} with minimum absolute error of {}'.format(best_algorithm,min_mae)) ###Output The Best Algorithm is RandomForest with minimum absolute error of 160.65304056447886
unit-12_classification/Classification_Binary_Digit_Image.ipynb
###Markdown From video Predict the digit in an image. This is an example of binary classification problem. Predicting if the number in the image is a 3.https://youtu.be/pXdum128xww ###Code from sklearn.datasets import fetch_openml # Get the image datasets from online mnist = fetch_openml('mnist_784') ###Output _____no_output_____ ###Markdown Explore the dataset ###Code mnist %matplotlib inline import matplotlib import matplotlib.pyplot as plt X,Y = mnist['data'], mnist['target'] # Pick one of the image to look at random_digit = X[4000] some_random_digit = random_digit.reshape(28,28) # reshape the actual image plt.imshow(some_random_digit, cmap=matplotlib.cm.binary, interpolation="nearest") # Pick one of the image to look at random_digit = X[3600] some_random_digit = random_digit.reshape(28,28) # reshape the actual image plt.imshow(some_random_digit, cmap=matplotlib.cm.binary, interpolation="nearest") # Pick one of the image to look at random_digit = X[50000] some_random_digit = random_digit.reshape(28,28) # reshape the actual image plt.imshow(some_random_digit, cmap=matplotlib.cm.binary, interpolation="nearest") ###Output _____no_output_____ ###Markdown Splitting Dataset into training and testing ###Code # Take first 6000 as training, then the next 1000 as testing x_train, x_test = X[:6000], X[6000:7000] y_train, y_test = Y[:6000], Y[6000:7000] # Shuffle the data to make it more efficient import numpy as np shuffle_index = np.random.permutation(6000) x_train, y_train = x_train[shuffle_index], y_train[shuffle_index] y_train # Create predictor # convert the dataset to integer type for using == y_train = y_train.astype(np.int8) y_test = y_train.astype(np.int8) # The Y label has the actual digit. Here, we are going to make prediction of True/False of a digit. # Let's try to set the training and testing label to True/False for predicting 3. If digit is 3, True. y_train_2 = (y_train == 3) y_test_2 = (y_test == 3) y_test_2 from sklearn.linear_model import LogisticRegression clf = LogisticRegression(tol=0.1) # tolerance 0.1 clf.fit(x_train, y_train_2) y_pred = clf.predict([random_digit]) y_pred # random_digit was assigned earlier, and it has a 3. So prediction True is Correct, True Positive. ###Output _____no_output_____ ###Markdown Use cross_val_score() to calculate accuracy ###Code from sklearn.model_selection import cross_val_score a = cross_val_score(clf, x_train, y_train_2, cv=3, scoring='accuracy') # Use the mean to calculate accuracy a.mean() ###Output _____no_output_____ ###Markdown Use SVC as the classifer to do the same ###Code from sklearn import svm clf = svm.SVC() clf.fit(x_train, y_train_2) y_pred = clf.predict([random_digit]) y_pred # Prediction of True is correct for 3. from sklearn.model_selection import cross_val_score a = cross_val_score(clf, x_train, y_train_2, cv=3, scoring='accuracy') a.mean() ###Output _____no_output_____
Classification_solution.ipynb
###Markdown Deep learning programming II: ClassificationFelix Wiewel, Institute of Signal Processing and System Theory, University of Stuttgart, 24.04.2020 IntroductionA common problem that arises in machine learning is the classifiaction of images. The goal of this exercise is to introduce you to the practical implementation of a complete pipeline for solving a classification task with neural networks in Tensorflow. For this we will make extended use of Keras, a specification of a high-level API for implementing powerful classes and functions to create and train neural networks. Tensorflow already comes with an implementation of the Keras specification so there is no need to install Keras if you have already installed Tensorflow. Usign Keras instead of low level tensorflow code to implement your neural networks and their training algorithms comes with some advantages but also some disadvantages. Since Keras makes it very easy to build and train neural networks, even people without strong programming skills can quickly develop solutions for given problems using neural networks. Keras essantially provides an abstract interface to the user and takes care of the low-level implementation details. This, however, comes with a cost. Since many technical details are hidden from the user, it is sometimes quite difficult to modify and change certain parts of your model/training algorithm. To a certain extend Keras provides you with ways to implement custom network architectures, custom layers and custom training algorithms but sometimes having to write code that is compliant with the Keras specification is more difficult than implementing it in low-level Tensorflow code. But for most standard applications, e.g. simple image classification like in this exercise, Keras is flexible enough and can save you a lot of time and frustation. GPU supportIn order to speed up calculations with Tensorflow, we need to change the runtime type of this notebook to GPU. For this click on "Runtime" in the top left menu and select "Change runtime type". Then choose "GPU" in the drop down list under "Hardware accelerator". This will enable Tensorflow to execute calculations on a GPU provided by Google Colab. Mathematical BackgroundIn classification we are interested in learning a function that maps an input $\mathbf{x}\in\mathbb{R}^{M}$ to one out of possibly many classes. In order to characterize such a mapping, we need a mathematical expression to uniquely identify different classes. This is typically done by assigning each class an integer value. So in the case of classifying images in the three classes Dog, Cat, Bird one could assign these classes with the one-hot vectors $\left[1,0,0\right]^{T},\left[0,1,0\right]^{T},\left[0,0,1\right]^{T}$. Using one-hot vectors to represent labels of indivudual classes is very useful for training neural networks. It closely matches the mathematical model that we will be using for interpreting the networks output where each of its elements describes a probability. In classification using neural networks we are interested in learning the function$\mathbf{y}=f_{\boldsymbol{\theta}}(\mathbf{x})$,where $f$ is a neural network with parameters $\boldsymbol{\theta}$ that maps our possibly high-dimensional input $\mathbf{x}\in\mathbb{R}^{M}$ to an output $\mathbf{y}\in\lbrace0,1\rbrace^{k}$ that represents one out of $k$ possible classes. Similar to the regression exercise, we will use a probabilistic view on this problem in order to derive a suitable cost function we can use to train our model. This time however, we will not introduce uncertainty through assuming some sort of noise acting on the prediction of the model as we did in the previous exercise. Instead we will treat both $\mathbf{x}$ and $\mathbf{y}$ as random variables with probability distribution functions (pdfs) $p(\mathbf{x})$ and $p(\mathbf{y})$. We already know that $\mathbf{y}$ can be one out of $k$ classes, i.e. $p(\mathbf{y})$ is a cateorical distribution. Instead of trying to learn a deterministic function that maps an input $\mathbf{x}$ to an output $\mathbf{y}$ we can instead learn a function that takes $\mathbf{x}$ as an input and outputs a pdf over our $k$ different classes, i.e. $p(\mathbf{y}\vert\mathbf{x})$. In order to then classify an input we typically assign it with the class label that is most likely. In this way we can easily interprete the output of the model and also incorporate prior information into our decision. Using this probabilistic perspective on the classification problem we are interested in learning the conditional distribution$p(\mathbf{y}\vert\mathbf{x})=\prod_{n=1}^{k}\mu_{n}(\mathbf{x})^{y_{n}}$,where $y_{n}\in\lbrace0,1\rbrace$, $\sum_{n=1}^{k}y_{n}=1$, $0\leq\mu_{n}(\mathbf{x})\leq1$ and $\sum_{n=1}^{k}\mu_{n}(\mathbf{x})=1$. In other words, we want to learn the parameters of a neural network $\boldsymbol{\theta}$ that, given an input $\mathbf{x}$, outputs $\mu_{n}(\mathbf{x})$ for $1\leq n\leq k$ satisfying the constraints $0\leq\mu_{n}(\mathbf{x})\leq1$ and $\sum_{n=1}^{k}\mu_{n}(\mathbf{x})=1$. Practically, we can realize this by designing a neural network that accepts $\mathbf{x}$ as an input and has an output layer with $k$ neurons and a softmax activation function. In order to derive a cost function for learning the parameters $\boldsymbol{\theta}$ of the neural network, we will again use the log likelihood$\mathcal{L}(\mathbf{x},\mathbf{y},\boldsymbol{\theta})=\ln{p(\mathbf{y}\vert\mathbf{x},\boldsymbol{\theta})}=\ln{\prod_{n=1}^{k}\mu_{n}(\mathbf{x})^{y_{n}}}=\sum_{n=1}^{k}y_{n}\ln{\mu_{n}(\mathbf{x})}$,where $\mu_{n}(\mathbf{x})$ depends on the parameters $\boldsymbol{\theta}$ of the neural network. The log likelihood measures how likely $\mathbf{y}$ is given $\mathbf{x}$ and the parameters $\boldsymbol{\theta}$. Maximizing the expected log likelihood over the complete data set yields the optimal parameters$\boldsymbol{\theta}^{\star}=\arg\max_{\boldsymbol{\theta}}\mathbb{E}\left[\mathcal{L}(\mathbf{x},\mathbf{y},\boldsymbol{\theta})\right]=\arg\min_{\boldsymbol{\theta}}-\mathbb{E}\left[\sum_{n=1}^{k}y_{n}\ln{\mu_{n}(\mathbf{x})}\right]\approx\arg\min_{\boldsymbol{\theta}}-\dfrac{1}{N}\sum_{i=1}^{N}\sum_{n=1}^{k}y_{n,i}\ln{\mu_{n}(\mathbf{x}_{i})}$,where we have reformulated the maximization as a minimization of the negative objective function and approximated the expectation with a sum. As you probably already noticed, the last term is the cross entropy loss that you are familiar with from the lecture. We can now again use SGD or some variant of it in order to minimize the cost function and obtain find some good parameters for our neural network. But keep in mind that while $\boldsymbol{\theta}^{\star}$ are the globally optimal parameters, we are usually only able to find locally optimal parameters due to the non-convex cost function that we are minimizing. Data setIn this exercise we will use common data sets like the MNIST or FashionMNIST data sets. Those and some other data sets are provided through simple functions in the Keras implementation of Tensorflow. For an overview of available data sets and how to use them click [here](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/datasets). The MNIST data set is a simple and very popular data set for handwritten digit classification. It contains $70000$ images with $28\times 28$ pixels that are split into $60000$ training and $10000$ test samples. Since the task is to classify a handwritten digit, the labels $y$ for each image are from the set $\lbrace0,\ldots,9\rbrace$. The FashionMNIST data set is very similar to MNIST it also has approximately the same number of images with exactly the same dimensions as MNIST. It was provided by Zalando research and contains $10$ classes of different fashion objects. ImplementationWe can simply import all required packages and load some data set using Keras. ###Code import tensorflow as tf import tensorflow.keras as k import numpy as np import matplotlib.pyplot as plt # Define constants batch_size = 128 epochs = 20 learning_rate = 0.001 (x_train_mnist, y_train_mnist), (x_test_mnist, y_test_mnist) = tf.keras.datasets.mnist.load_data() x_train_mnist = np.expand_dims(x_train_mnist, axis=-1).astype(np.float32) x_test_mnist = np.expand_dims(x_test_mnist, axis=-1).astype(np.float32) ###Output _____no_output_____ ###Markdown We can also plot some examples in order to get an impresion of what the data looks like. ###Code plt_img = np.zeros((280, 280)) for i in range(10): for j in range(10): plt_img[i*28:(i+1)*28, j*28:(j+1)*28] = np.squeeze(x_train_mnist[i*10+j]) plt.imshow(plt_img, cmap="gray") plt.axis("off") plt.show() ###Output _____no_output_____ ###Markdown Similar to the previous exercises we again derive a class for our model from the Keras Model class. ###Code class MyModel(k.Model): def __init__(self): super(MyModel, self).__init__() self.conv0 = k.layers.Conv2D(8, 3, 2, activation="relu") self.conv1 = k.layers.Conv2D(16, 3, 2, activation="relu") self.flatten = k.layers.Flatten() self.dense0 = k.layers.Dense(128, activation="relu") self.dense1 = k.layers.Dense(64, activation="relu") self.dense2 = k.layers.Dense(10, activation="softmax") def call(self, inputs, training=False): output = self.conv0(inputs) output = self.conv1(output) output = self.flatten(output) output = self.dense0(output) output = self.dense1(output) output = self.dense2(output) return output ###Output _____no_output_____ ###Markdown We can now instanciate an object of this class and compile it using the the cross-entropy loss function. ###Code mdl = MyModel() opt = tf.keras.optimizers.RMSprop(learning_rate) mdl.compile(loss="sparse_categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) ###Output _____no_output_____ ###Markdown Now we are ready to train the model and log the metrics for plotting. ###Code history_no_dropout = mdl.fit(x_train_mnist, y_train_mnist, batch_size, epochs, validation_split=0.1) ###Output Epoch 1/20 422/422 [==============================] - 1s 2ms/step - loss: 0.5560 - accuracy: 0.8834 - val_loss: 0.1328 - val_accuracy: 0.9612 Epoch 2/20 422/422 [==============================] - 1s 2ms/step - loss: 0.1062 - accuracy: 0.9674 - val_loss: 0.0837 - val_accuracy: 0.9743 Epoch 3/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0671 - accuracy: 0.9789 - val_loss: 0.0800 - val_accuracy: 0.9760 Epoch 4/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0462 - accuracy: 0.9854 - val_loss: 0.0754 - val_accuracy: 0.9803 Epoch 5/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0364 - accuracy: 0.9887 - val_loss: 0.0839 - val_accuracy: 0.9788 Epoch 6/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0276 - accuracy: 0.9913 - val_loss: 0.0745 - val_accuracy: 0.9817 Epoch 7/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0214 - accuracy: 0.9933 - val_loss: 0.0898 - val_accuracy: 0.9815 Epoch 8/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0185 - accuracy: 0.9940 - val_loss: 0.1065 - val_accuracy: 0.9793 Epoch 9/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0159 - accuracy: 0.9953 - val_loss: 0.0880 - val_accuracy: 0.9818 Epoch 10/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0138 - accuracy: 0.9957 - val_loss: 0.1057 - val_accuracy: 0.9822 Epoch 11/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0136 - accuracy: 0.9956 - val_loss: 0.1042 - val_accuracy: 0.9832 Epoch 12/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0107 - accuracy: 0.9967 - val_loss: 0.1228 - val_accuracy: 0.9815 Epoch 13/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0113 - accuracy: 0.9966 - val_loss: 0.1637 - val_accuracy: 0.9767 Epoch 14/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0106 - accuracy: 0.9970 - val_loss: 0.1178 - val_accuracy: 0.9832 Epoch 15/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0096 - accuracy: 0.9971 - val_loss: 0.1158 - val_accuracy: 0.9833 Epoch 16/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0083 - accuracy: 0.9977 - val_loss: 0.1251 - val_accuracy: 0.9832 Epoch 17/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0084 - accuracy: 0.9976 - val_loss: 0.1597 - val_accuracy: 0.9833 Epoch 18/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0090 - accuracy: 0.9976 - val_loss: 0.1518 - val_accuracy: 0.9832 Epoch 19/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0091 - accuracy: 0.9978 - val_loss: 0.1664 - val_accuracy: 0.9823 Epoch 20/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0094 - accuracy: 0.9975 - val_loss: 0.1777 - val_accuracy: 0.9817 ###Markdown Visualizing the training process in a plot is possible by using the history object that contains a history dictionary. This is returned from the fit function and contains all the metrics logged over the training proces. ###Code plt.plot(history_no_dropout.history["loss"]) plt.plot(history_no_dropout.history["val_loss"]) plt.legend(["loss", "val_loss"]) plt.xticks(range(epochs)) plt.xlabel("epochs") plt.title("Training process") plt.show() ###Output _____no_output_____ ###Markdown As you can see, the model is clearly overfitting. The loss on the training data is decreasing further and further with every epoch, while the loss on the validation data rises at the same time. We can avoid this by using dropout, which is a strong regularization that you should be familiar with from the lecture. For this we define a new model that has an additional dropout layer with a drop probability of $0.25$ before the first fully connected layer. Otherwise this model is the same as the model above. ###Code class MyDropoutModel(k.Model): def __init__(self): super(MyDropoutModel, self).__init__() self.conv0 = k.layers.Conv2D(8, 3, 2, activation="relu") self.conv1 = k.layers.Conv2D(16, 3, 2, activation="relu") self.flatten = k.layers.Flatten() self.dropout = k.layers.Dropout(0.25) self.dense0 = k.layers.Dense(128, activation="relu") self.dense1 = k.layers.Dense(64, activation="relu") self.dense2 = k.layers.Dense(10, activation="softmax") def call(self, inputs, training=False): output = self.conv0(inputs) output = self.conv1(output) output = self.flatten(output) output = self.dropout(output, training) output = self.dense0(output) output = self.dense1(output) output = self.dense2(output) return output ###Output _____no_output_____ ###Markdown We can now create an instance of this model, train it and visualize the training process. ###Code dropout_mdl = MyDropoutModel() dropout_opt = tf.keras.optimizers.RMSprop(learning_rate) dropout_mdl.compile(loss="sparse_categorical_crossentropy", optimizer=dropout_opt, metrics=["accuracy"]) history_dropout = dropout_mdl.fit(x_train_mnist, y_train_mnist, batch_size, epochs, validation_split=0.1) plt.plot(history_no_dropout.history["loss"]) plt.plot(history_no_dropout.history["val_loss"]) plt.plot(history_dropout.history["loss"]) plt.plot(history_dropout.history["val_loss"]) plt.legend(["loss", "val_loss", "loss w. dropout", "val_loss w. dropout"]) plt.xticks(range(epochs)) plt.xlabel("epochs") plt.title("Training process") plt.show() ###Output Epoch 1/20 422/422 [==============================] - 1s 2ms/step - loss: 0.5024 - accuracy: 0.8541 - val_loss: 0.1272 - val_accuracy: 0.9628 Epoch 2/20 422/422 [==============================] - 1s 2ms/step - loss: 0.1537 - accuracy: 0.9527 - val_loss: 0.0838 - val_accuracy: 0.9757 Epoch 3/20 422/422 [==============================] - 1s 2ms/step - loss: 0.1077 - accuracy: 0.9662 - val_loss: 0.0741 - val_accuracy: 0.9795 Epoch 4/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0853 - accuracy: 0.9733 - val_loss: 0.0716 - val_accuracy: 0.9790 Epoch 5/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0746 - accuracy: 0.9768 - val_loss: 0.0650 - val_accuracy: 0.9837 Epoch 6/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0642 - accuracy: 0.9804 - val_loss: 0.0618 - val_accuracy: 0.9832 Epoch 7/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0575 - accuracy: 0.9815 - val_loss: 0.0643 - val_accuracy: 0.9833 Epoch 8/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0524 - accuracy: 0.9840 - val_loss: 0.0544 - val_accuracy: 0.9835 Epoch 9/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0494 - accuracy: 0.9845 - val_loss: 0.0505 - val_accuracy: 0.9863 Epoch 10/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0477 - accuracy: 0.9847 - val_loss: 0.0507 - val_accuracy: 0.9862 Epoch 11/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0432 - accuracy: 0.9861 - val_loss: 0.0567 - val_accuracy: 0.9842 Epoch 12/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0391 - accuracy: 0.9873 - val_loss: 0.0568 - val_accuracy: 0.9865 Epoch 13/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0391 - accuracy: 0.9876 - val_loss: 0.0542 - val_accuracy: 0.9865 Epoch 14/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0372 - accuracy: 0.9885 - val_loss: 0.0615 - val_accuracy: 0.9858 Epoch 15/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0367 - accuracy: 0.9883 - val_loss: 0.0563 - val_accuracy: 0.9870 Epoch 16/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0340 - accuracy: 0.9891 - val_loss: 0.0549 - val_accuracy: 0.9862 Epoch 17/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0346 - accuracy: 0.9890 - val_loss: 0.0520 - val_accuracy: 0.9888 Epoch 18/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0319 - accuracy: 0.9896 - val_loss: 0.0542 - val_accuracy: 0.9880 Epoch 19/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0318 - accuracy: 0.9900 - val_loss: 0.0469 - val_accuracy: 0.9880 Epoch 20/20 422/422 [==============================] - 1s 2ms/step - loss: 0.0321 - accuracy: 0.9900 - val_loss: 0.0556 - val_accuracy: 0.9880 ###Markdown While the model without dropout can reach a much lower loss on the training data, it generalizes very poorly to the unseen validation data. The model with dropout however generalizes quite good to the validation data and achieves a similar loss on both the data used during training and unseen data. This demonstrates that using dropout can be a good way to regularize your networks and prevent overfitting. Although dropout helps to prevent overfitting very well, it introduces another hyperparameter, the drop probability, that needs to be optimized. Common values for this hyperparameter are on the interval $\left[0.2,0.5\right]$. Transfer LearningIn many applications there is only a limited amount of annotated data available. In order to still train a neural network that generalizes well on such a data set, one can use transfer learning. In transfer learning the goal is to transfer knowledge from a source domain or task to a target domain or task. The hope is that this transfer will be positive, i.e. the performance on the target domain or task increases compared to only training on the target data set. A requirement for succesfull transfer learning is that the source and target have something in common, e.g. similar features. There is a broad literature on transfer learning methods but in this exercise we will restrict ourselves to the most basic approach, fine tuning. Fine tuning can be implemented by using a part of a neural network, which was trained on the source domain or task, as a feature extractor. A common approach is to use neral network pretrained on the ImageNet data set as a feature extractor. In this exercise, we will also use a neural network pretrained on ImageNet in order to fine tune it for the [Caltech 101](http://www.vision.caltech.edu/Image_Datasets/Caltech101/) data set. For a guide on transfer learning using fine tuning with Keras click [here](https://www.tensorflow.org/beta/tutorials/images/transfer_learning).In order to do this we first need to download an extract the data set. Note that there is a wide collection of data sets available through the [tensorflow_datasets](https://www.tensorflow.org/datasets) package including Caltech101. But for demonstration purposses we manually download and load the images using Keras. ###Code !wget -N http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz !tar -xzf 101_ObjectCategories.tar.gz ###Output --2020-04-24 15:27:12-- http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz Resolving www.vision.caltech.edu (www.vision.caltech.edu)... 34.208.54.77 Connecting to www.vision.caltech.edu (www.vision.caltech.edu)|34.208.54.77|:80... connected. HTTP request sent, awaiting response... 304 Not Modified File ‘101_ObjectCategories.tar.gz’ not modified on server. Omitting download. ###Markdown In order to feed our model with the data, we will use the ImageDataGenerator class provided by Keras. This class can be used for reading files from a structured directory, create the labels based on the structure of the directory and apply data augmentation techniques. The ImageDataGenerator already supports a lot of techniques for data augmentation. In our example, we use a random rotation, width shift, height shift, shearing, zomming and horizontal flipping. All of those operations are applied randomly to individual images. More information on the available transformations for data augmentation and how to use them see the [documentation](https://www.tensorflow.org/versions/r2.2/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator__init__). ###Code N_samples_Caltech101 = 9247 val_split = 0.1 datagen = k.preprocessing.image.ImageDataGenerator(validation_split=val_split, preprocessing_function=k.applications.mobilenet_v2.preprocess_input, rotation_range=20, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.1, zoom_range=0.1, horizontal_flip=True) ###Output _____no_output_____ ###Markdown Now that we have the data set we can load the pretrained model. Keras provides a range of pretrained models called "applications", click [here](https://www.tensorflow.org/api_docs/python/tf/keras/applications) for a link to its documentation. We will use the MobileNetV2 architecture without it's output layer, since we want to modify it in order to apply the model to the Caltech 101 data set. ###Code base_model = k.applications.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights='imagenet') base_model.summary() ###Output Model: "mobilenetv2_1.00_224" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_1 (InputLayer) [(None, 224, 224, 3) 0 __________________________________________________________________________________________________ Conv1_pad (ZeroPadding2D) (None, 225, 225, 3) 0 input_1[0][0] __________________________________________________________________________________________________ Conv1 (Conv2D) (None, 112, 112, 32) 864 Conv1_pad[0][0] __________________________________________________________________________________________________ bn_Conv1 (BatchNormalization) (None, 112, 112, 32) 128 Conv1[0][0] __________________________________________________________________________________________________ Conv1_relu (ReLU) (None, 112, 112, 32) 0 bn_Conv1[0][0] __________________________________________________________________________________________________ expanded_conv_depthwise (Depthw (None, 112, 112, 32) 288 Conv1_relu[0][0] __________________________________________________________________________________________________ expanded_conv_depthwise_BN (Bat (None, 112, 112, 32) 128 expanded_conv_depthwise[0][0] __________________________________________________________________________________________________ expanded_conv_depthwise_relu (R (None, 112, 112, 32) 0 expanded_conv_depthwise_BN[0][0] __________________________________________________________________________________________________ expanded_conv_project (Conv2D) (None, 112, 112, 16) 512 expanded_conv_depthwise_relu[0][0 __________________________________________________________________________________________________ expanded_conv_project_BN (Batch (None, 112, 112, 16) 64 expanded_conv_project[0][0] __________________________________________________________________________________________________ block_1_expand (Conv2D) (None, 112, 112, 96) 1536 expanded_conv_project_BN[0][0] __________________________________________________________________________________________________ block_1_expand_BN (BatchNormali (None, 112, 112, 96) 384 block_1_expand[0][0] __________________________________________________________________________________________________ block_1_expand_relu (ReLU) (None, 112, 112, 96) 0 block_1_expand_BN[0][0] __________________________________________________________________________________________________ block_1_pad (ZeroPadding2D) (None, 113, 113, 96) 0 block_1_expand_relu[0][0] __________________________________________________________________________________________________ block_1_depthwise (DepthwiseCon (None, 56, 56, 96) 864 block_1_pad[0][0] __________________________________________________________________________________________________ block_1_depthwise_BN (BatchNorm (None, 56, 56, 96) 384 block_1_depthwise[0][0] __________________________________________________________________________________________________ block_1_depthwise_relu (ReLU) (None, 56, 56, 96) 0 block_1_depthwise_BN[0][0] __________________________________________________________________________________________________ block_1_project (Conv2D) (None, 56, 56, 24) 2304 block_1_depthwise_relu[0][0] __________________________________________________________________________________________________ block_1_project_BN (BatchNormal (None, 56, 56, 24) 96 block_1_project[0][0] __________________________________________________________________________________________________ block_2_expand (Conv2D) (None, 56, 56, 144) 3456 block_1_project_BN[0][0] __________________________________________________________________________________________________ block_2_expand_BN (BatchNormali (None, 56, 56, 144) 576 block_2_expand[0][0] __________________________________________________________________________________________________ block_2_expand_relu (ReLU) (None, 56, 56, 144) 0 block_2_expand_BN[0][0] __________________________________________________________________________________________________ block_2_depthwise (DepthwiseCon (None, 56, 56, 144) 1296 block_2_expand_relu[0][0] __________________________________________________________________________________________________ block_2_depthwise_BN (BatchNorm (None, 56, 56, 144) 576 block_2_depthwise[0][0] __________________________________________________________________________________________________ block_2_depthwise_relu (ReLU) (None, 56, 56, 144) 0 block_2_depthwise_BN[0][0] __________________________________________________________________________________________________ block_2_project (Conv2D) (None, 56, 56, 24) 3456 block_2_depthwise_relu[0][0] __________________________________________________________________________________________________ block_2_project_BN (BatchNormal (None, 56, 56, 24) 96 block_2_project[0][0] __________________________________________________________________________________________________ block_2_add (Add) (None, 56, 56, 24) 0 block_1_project_BN[0][0] block_2_project_BN[0][0] __________________________________________________________________________________________________ block_3_expand (Conv2D) (None, 56, 56, 144) 3456 block_2_add[0][0] __________________________________________________________________________________________________ block_3_expand_BN (BatchNormali (None, 56, 56, 144) 576 block_3_expand[0][0] __________________________________________________________________________________________________ block_3_expand_relu (ReLU) (None, 56, 56, 144) 0 block_3_expand_BN[0][0] __________________________________________________________________________________________________ block_3_pad (ZeroPadding2D) (None, 57, 57, 144) 0 block_3_expand_relu[0][0] __________________________________________________________________________________________________ block_3_depthwise (DepthwiseCon (None, 28, 28, 144) 1296 block_3_pad[0][0] __________________________________________________________________________________________________ block_3_depthwise_BN (BatchNorm (None, 28, 28, 144) 576 block_3_depthwise[0][0] __________________________________________________________________________________________________ block_3_depthwise_relu (ReLU) (None, 28, 28, 144) 0 block_3_depthwise_BN[0][0] __________________________________________________________________________________________________ block_3_project (Conv2D) (None, 28, 28, 32) 4608 block_3_depthwise_relu[0][0] __________________________________________________________________________________________________ block_3_project_BN (BatchNormal (None, 28, 28, 32) 128 block_3_project[0][0] __________________________________________________________________________________________________ block_4_expand (Conv2D) (None, 28, 28, 192) 6144 block_3_project_BN[0][0] __________________________________________________________________________________________________ block_4_expand_BN (BatchNormali (None, 28, 28, 192) 768 block_4_expand[0][0] __________________________________________________________________________________________________ block_4_expand_relu (ReLU) (None, 28, 28, 192) 0 block_4_expand_BN[0][0] __________________________________________________________________________________________________ block_4_depthwise (DepthwiseCon (None, 28, 28, 192) 1728 block_4_expand_relu[0][0] __________________________________________________________________________________________________ block_4_depthwise_BN (BatchNorm (None, 28, 28, 192) 768 block_4_depthwise[0][0] __________________________________________________________________________________________________ block_4_depthwise_relu (ReLU) (None, 28, 28, 192) 0 block_4_depthwise_BN[0][0] __________________________________________________________________________________________________ block_4_project (Conv2D) (None, 28, 28, 32) 6144 block_4_depthwise_relu[0][0] __________________________________________________________________________________________________ block_4_project_BN (BatchNormal (None, 28, 28, 32) 128 block_4_project[0][0] __________________________________________________________________________________________________ block_4_add (Add) (None, 28, 28, 32) 0 block_3_project_BN[0][0] block_4_project_BN[0][0] __________________________________________________________________________________________________ block_5_expand (Conv2D) (None, 28, 28, 192) 6144 block_4_add[0][0] __________________________________________________________________________________________________ block_5_expand_BN (BatchNormali (None, 28, 28, 192) 768 block_5_expand[0][0] __________________________________________________________________________________________________ block_5_expand_relu (ReLU) (None, 28, 28, 192) 0 block_5_expand_BN[0][0] __________________________________________________________________________________________________ block_5_depthwise (DepthwiseCon (None, 28, 28, 192) 1728 block_5_expand_relu[0][0] __________________________________________________________________________________________________ block_5_depthwise_BN (BatchNorm (None, 28, 28, 192) 768 block_5_depthwise[0][0] __________________________________________________________________________________________________ block_5_depthwise_relu (ReLU) (None, 28, 28, 192) 0 block_5_depthwise_BN[0][0] __________________________________________________________________________________________________ block_5_project (Conv2D) (None, 28, 28, 32) 6144 block_5_depthwise_relu[0][0] __________________________________________________________________________________________________ block_5_project_BN (BatchNormal (None, 28, 28, 32) 128 block_5_project[0][0] __________________________________________________________________________________________________ block_5_add (Add) (None, 28, 28, 32) 0 block_4_add[0][0] block_5_project_BN[0][0] __________________________________________________________________________________________________ block_6_expand (Conv2D) (None, 28, 28, 192) 6144 block_5_add[0][0] __________________________________________________________________________________________________ block_6_expand_BN (BatchNormali (None, 28, 28, 192) 768 block_6_expand[0][0] __________________________________________________________________________________________________ block_6_expand_relu (ReLU) (None, 28, 28, 192) 0 block_6_expand_BN[0][0] __________________________________________________________________________________________________ block_6_pad (ZeroPadding2D) (None, 29, 29, 192) 0 block_6_expand_relu[0][0] __________________________________________________________________________________________________ block_6_depthwise (DepthwiseCon (None, 14, 14, 192) 1728 block_6_pad[0][0] __________________________________________________________________________________________________ block_6_depthwise_BN (BatchNorm (None, 14, 14, 192) 768 block_6_depthwise[0][0] __________________________________________________________________________________________________ block_6_depthwise_relu (ReLU) (None, 14, 14, 192) 0 block_6_depthwise_BN[0][0] __________________________________________________________________________________________________ block_6_project (Conv2D) (None, 14, 14, 64) 12288 block_6_depthwise_relu[0][0] __________________________________________________________________________________________________ block_6_project_BN (BatchNormal (None, 14, 14, 64) 256 block_6_project[0][0] __________________________________________________________________________________________________ block_7_expand (Conv2D) (None, 14, 14, 384) 24576 block_6_project_BN[0][0] __________________________________________________________________________________________________ block_7_expand_BN (BatchNormali (None, 14, 14, 384) 1536 block_7_expand[0][0] __________________________________________________________________________________________________ block_7_expand_relu (ReLU) (None, 14, 14, 384) 0 block_7_expand_BN[0][0] __________________________________________________________________________________________________ block_7_depthwise (DepthwiseCon (None, 14, 14, 384) 3456 block_7_expand_relu[0][0] __________________________________________________________________________________________________ block_7_depthwise_BN (BatchNorm (None, 14, 14, 384) 1536 block_7_depthwise[0][0] __________________________________________________________________________________________________ block_7_depthwise_relu (ReLU) (None, 14, 14, 384) 0 block_7_depthwise_BN[0][0] __________________________________________________________________________________________________ block_7_project (Conv2D) (None, 14, 14, 64) 24576 block_7_depthwise_relu[0][0] __________________________________________________________________________________________________ block_7_project_BN (BatchNormal (None, 14, 14, 64) 256 block_7_project[0][0] __________________________________________________________________________________________________ block_7_add (Add) (None, 14, 14, 64) 0 block_6_project_BN[0][0] block_7_project_BN[0][0] __________________________________________________________________________________________________ block_8_expand (Conv2D) (None, 14, 14, 384) 24576 block_7_add[0][0] __________________________________________________________________________________________________ block_8_expand_BN (BatchNormali (None, 14, 14, 384) 1536 block_8_expand[0][0] __________________________________________________________________________________________________ block_8_expand_relu (ReLU) (None, 14, 14, 384) 0 block_8_expand_BN[0][0] __________________________________________________________________________________________________ block_8_depthwise (DepthwiseCon (None, 14, 14, 384) 3456 block_8_expand_relu[0][0] __________________________________________________________________________________________________ block_8_depthwise_BN (BatchNorm (None, 14, 14, 384) 1536 block_8_depthwise[0][0] __________________________________________________________________________________________________ block_8_depthwise_relu (ReLU) (None, 14, 14, 384) 0 block_8_depthwise_BN[0][0] __________________________________________________________________________________________________ block_8_project (Conv2D) (None, 14, 14, 64) 24576 block_8_depthwise_relu[0][0] __________________________________________________________________________________________________ block_8_project_BN (BatchNormal (None, 14, 14, 64) 256 block_8_project[0][0] __________________________________________________________________________________________________ block_8_add (Add) (None, 14, 14, 64) 0 block_7_add[0][0] block_8_project_BN[0][0] __________________________________________________________________________________________________ block_9_expand (Conv2D) (None, 14, 14, 384) 24576 block_8_add[0][0] __________________________________________________________________________________________________ block_9_expand_BN (BatchNormali (None, 14, 14, 384) 1536 block_9_expand[0][0] __________________________________________________________________________________________________ block_9_expand_relu (ReLU) (None, 14, 14, 384) 0 block_9_expand_BN[0][0] __________________________________________________________________________________________________ block_9_depthwise (DepthwiseCon (None, 14, 14, 384) 3456 block_9_expand_relu[0][0] __________________________________________________________________________________________________ block_9_depthwise_BN (BatchNorm (None, 14, 14, 384) 1536 block_9_depthwise[0][0] __________________________________________________________________________________________________ block_9_depthwise_relu (ReLU) (None, 14, 14, 384) 0 block_9_depthwise_BN[0][0] __________________________________________________________________________________________________ block_9_project (Conv2D) (None, 14, 14, 64) 24576 block_9_depthwise_relu[0][0] __________________________________________________________________________________________________ block_9_project_BN (BatchNormal (None, 14, 14, 64) 256 block_9_project[0][0] __________________________________________________________________________________________________ block_9_add (Add) (None, 14, 14, 64) 0 block_8_add[0][0] block_9_project_BN[0][0] __________________________________________________________________________________________________ block_10_expand (Conv2D) (None, 14, 14, 384) 24576 block_9_add[0][0] __________________________________________________________________________________________________ block_10_expand_BN (BatchNormal (None, 14, 14, 384) 1536 block_10_expand[0][0] __________________________________________________________________________________________________ block_10_expand_relu (ReLU) (None, 14, 14, 384) 0 block_10_expand_BN[0][0] __________________________________________________________________________________________________ block_10_depthwise (DepthwiseCo (None, 14, 14, 384) 3456 block_10_expand_relu[0][0] __________________________________________________________________________________________________ block_10_depthwise_BN (BatchNor (None, 14, 14, 384) 1536 block_10_depthwise[0][0] __________________________________________________________________________________________________ block_10_depthwise_relu (ReLU) (None, 14, 14, 384) 0 block_10_depthwise_BN[0][0] __________________________________________________________________________________________________ block_10_project (Conv2D) (None, 14, 14, 96) 36864 block_10_depthwise_relu[0][0] __________________________________________________________________________________________________ block_10_project_BN (BatchNorma (None, 14, 14, 96) 384 block_10_project[0][0] __________________________________________________________________________________________________ block_11_expand (Conv2D) (None, 14, 14, 576) 55296 block_10_project_BN[0][0] __________________________________________________________________________________________________ block_11_expand_BN (BatchNormal (None, 14, 14, 576) 2304 block_11_expand[0][0] __________________________________________________________________________________________________ block_11_expand_relu (ReLU) (None, 14, 14, 576) 0 block_11_expand_BN[0][0] __________________________________________________________________________________________________ block_11_depthwise (DepthwiseCo (None, 14, 14, 576) 5184 block_11_expand_relu[0][0] __________________________________________________________________________________________________ block_11_depthwise_BN (BatchNor (None, 14, 14, 576) 2304 block_11_depthwise[0][0] __________________________________________________________________________________________________ block_11_depthwise_relu (ReLU) (None, 14, 14, 576) 0 block_11_depthwise_BN[0][0] __________________________________________________________________________________________________ block_11_project (Conv2D) (None, 14, 14, 96) 55296 block_11_depthwise_relu[0][0] __________________________________________________________________________________________________ block_11_project_BN (BatchNorma (None, 14, 14, 96) 384 block_11_project[0][0] __________________________________________________________________________________________________ block_11_add (Add) (None, 14, 14, 96) 0 block_10_project_BN[0][0] block_11_project_BN[0][0] __________________________________________________________________________________________________ block_12_expand (Conv2D) (None, 14, 14, 576) 55296 block_11_add[0][0] __________________________________________________________________________________________________ block_12_expand_BN (BatchNormal (None, 14, 14, 576) 2304 block_12_expand[0][0] __________________________________________________________________________________________________ block_12_expand_relu (ReLU) (None, 14, 14, 576) 0 block_12_expand_BN[0][0] __________________________________________________________________________________________________ block_12_depthwise (DepthwiseCo (None, 14, 14, 576) 5184 block_12_expand_relu[0][0] __________________________________________________________________________________________________ block_12_depthwise_BN (BatchNor (None, 14, 14, 576) 2304 block_12_depthwise[0][0] __________________________________________________________________________________________________ block_12_depthwise_relu (ReLU) (None, 14, 14, 576) 0 block_12_depthwise_BN[0][0] __________________________________________________________________________________________________ block_12_project (Conv2D) (None, 14, 14, 96) 55296 block_12_depthwise_relu[0][0] __________________________________________________________________________________________________ block_12_project_BN (BatchNorma (None, 14, 14, 96) 384 block_12_project[0][0] __________________________________________________________________________________________________ block_12_add (Add) (None, 14, 14, 96) 0 block_11_add[0][0] block_12_project_BN[0][0] __________________________________________________________________________________________________ block_13_expand (Conv2D) (None, 14, 14, 576) 55296 block_12_add[0][0] __________________________________________________________________________________________________ block_13_expand_BN (BatchNormal (None, 14, 14, 576) 2304 block_13_expand[0][0] __________________________________________________________________________________________________ block_13_expand_relu (ReLU) (None, 14, 14, 576) 0 block_13_expand_BN[0][0] __________________________________________________________________________________________________ block_13_pad (ZeroPadding2D) (None, 15, 15, 576) 0 block_13_expand_relu[0][0] __________________________________________________________________________________________________ block_13_depthwise (DepthwiseCo (None, 7, 7, 576) 5184 block_13_pad[0][0] __________________________________________________________________________________________________ block_13_depthwise_BN (BatchNor (None, 7, 7, 576) 2304 block_13_depthwise[0][0] __________________________________________________________________________________________________ block_13_depthwise_relu (ReLU) (None, 7, 7, 576) 0 block_13_depthwise_BN[0][0] __________________________________________________________________________________________________ block_13_project (Conv2D) (None, 7, 7, 160) 92160 block_13_depthwise_relu[0][0] __________________________________________________________________________________________________ block_13_project_BN (BatchNorma (None, 7, 7, 160) 640 block_13_project[0][0] __________________________________________________________________________________________________ block_14_expand (Conv2D) (None, 7, 7, 960) 153600 block_13_project_BN[0][0] __________________________________________________________________________________________________ block_14_expand_BN (BatchNormal (None, 7, 7, 960) 3840 block_14_expand[0][0] __________________________________________________________________________________________________ block_14_expand_relu (ReLU) (None, 7, 7, 960) 0 block_14_expand_BN[0][0] __________________________________________________________________________________________________ block_14_depthwise (DepthwiseCo (None, 7, 7, 960) 8640 block_14_expand_relu[0][0] __________________________________________________________________________________________________ block_14_depthwise_BN (BatchNor (None, 7, 7, 960) 3840 block_14_depthwise[0][0] __________________________________________________________________________________________________ block_14_depthwise_relu (ReLU) (None, 7, 7, 960) 0 block_14_depthwise_BN[0][0] __________________________________________________________________________________________________ block_14_project (Conv2D) (None, 7, 7, 160) 153600 block_14_depthwise_relu[0][0] __________________________________________________________________________________________________ block_14_project_BN (BatchNorma (None, 7, 7, 160) 640 block_14_project[0][0] __________________________________________________________________________________________________ block_14_add (Add) (None, 7, 7, 160) 0 block_13_project_BN[0][0] block_14_project_BN[0][0] __________________________________________________________________________________________________ block_15_expand (Conv2D) (None, 7, 7, 960) 153600 block_14_add[0][0] __________________________________________________________________________________________________ block_15_expand_BN (BatchNormal (None, 7, 7, 960) 3840 block_15_expand[0][0] __________________________________________________________________________________________________ block_15_expand_relu (ReLU) (None, 7, 7, 960) 0 block_15_expand_BN[0][0] __________________________________________________________________________________________________ block_15_depthwise (DepthwiseCo (None, 7, 7, 960) 8640 block_15_expand_relu[0][0] __________________________________________________________________________________________________ block_15_depthwise_BN (BatchNor (None, 7, 7, 960) 3840 block_15_depthwise[0][0] __________________________________________________________________________________________________ block_15_depthwise_relu (ReLU) (None, 7, 7, 960) 0 block_15_depthwise_BN[0][0] __________________________________________________________________________________________________ block_15_project (Conv2D) (None, 7, 7, 160) 153600 block_15_depthwise_relu[0][0] __________________________________________________________________________________________________ block_15_project_BN (BatchNorma (None, 7, 7, 160) 640 block_15_project[0][0] __________________________________________________________________________________________________ block_15_add (Add) (None, 7, 7, 160) 0 block_14_add[0][0] block_15_project_BN[0][0] __________________________________________________________________________________________________ block_16_expand (Conv2D) (None, 7, 7, 960) 153600 block_15_add[0][0] __________________________________________________________________________________________________ block_16_expand_BN (BatchNormal (None, 7, 7, 960) 3840 block_16_expand[0][0] __________________________________________________________________________________________________ block_16_expand_relu (ReLU) (None, 7, 7, 960) 0 block_16_expand_BN[0][0] __________________________________________________________________________________________________ block_16_depthwise (DepthwiseCo (None, 7, 7, 960) 8640 block_16_expand_relu[0][0] __________________________________________________________________________________________________ block_16_depthwise_BN (BatchNor (None, 7, 7, 960) 3840 block_16_depthwise[0][0] __________________________________________________________________________________________________ block_16_depthwise_relu (ReLU) (None, 7, 7, 960) 0 block_16_depthwise_BN[0][0] __________________________________________________________________________________________________ block_16_project (Conv2D) (None, 7, 7, 320) 307200 block_16_depthwise_relu[0][0] __________________________________________________________________________________________________ block_16_project_BN (BatchNorma (None, 7, 7, 320) 1280 block_16_project[0][0] __________________________________________________________________________________________________ Conv_1 (Conv2D) (None, 7, 7, 1280) 409600 block_16_project_BN[0][0] __________________________________________________________________________________________________ Conv_1_bn (BatchNormalization) (None, 7, 7, 1280) 5120 Conv_1[0][0] __________________________________________________________________________________________________ out_relu (ReLU) (None, 7, 7, 1280) 0 Conv_1_bn[0][0] ================================================================================================== Total params: 2,257,984 Trainable params: 2,223,872 Non-trainable params: 34,112 __________________________________________________________________________________________________ ###Markdown With the pretrained model we can build our actual model that adds an output layer to the MobileNetV2. ###Code class MyTransferModel(k.Model): def __init__(self, pretrained_model): super(MyTransferModel, self).__init__() self.pretrained_model = pretrained_model self.glbl_avg_pool = k.layers.GlobalAveragePooling2D() self.dropout = k.layers.Dropout(0.25) self.dense = k.layers.Dense(102, activation="softmax") def call(self, inputs, training=False): output = self.pretrained_model(inputs) output = self.glbl_avg_pool(output) output = self.dropout(output) output = self.dense(output) return output ###Output _____no_output_____ ###Markdown Now we just need to instantiate our model for transfer learning and fine tune it. But instead of directly training all layers we will just train the last layer first. If you do not do this and directly train the complete model, the random initialization of the last layer can cause gradients with very big magnitude that will be propageted into the MobileNetV2 layers and cause them to "forget" what they have learned on ImageNet. This is undesireable since we want to transfer that knowledge over into our model in order to achieve better performance on the Caltech 101 data set. ###Code tf_batch_size = 32 tf_epochs = 10 tf_learning_rate = 0.001 tf_mdl = MyTransferModel(base_model) tf_opt = k.optimizers.RMSprop(tf_learning_rate) base_model.trainable = False tf_mdl.compile(loss="sparse_categorical_crossentropy", optimizer=tf_opt, metrics=["accuracy"]) tf_mdl.build((tf_batch_size, 224, 224, 3)) tf_mdl.summary() train_gen = datagen.flow_from_directory("101_ObjectCategories", target_size=(224, 224), class_mode="sparse", batch_size=tf_batch_size, subset="training") val_gen = datagen.flow_from_directory("101_ObjectCategories", target_size=(224, 224), class_mode="sparse", batch_size=tf_batch_size, subset="validation") tf_history_0 = tf_mdl.fit(train_gen, validation_data=val_gen, steps_per_epoch=int((1.0-val_split)*N_samples_Caltech101/tf_batch_size), validation_steps=int(val_split*N_samples_Caltech101/tf_batch_size), epochs=tf_epochs) ###Output Model: "my_transfer_model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= mobilenetv2_1.00_224 (Model) (None, 7, 7, 1280) 2257984 _________________________________________________________________ global_average_pooling2d (Gl multiple 0 _________________________________________________________________ dropout_1 (Dropout) multiple 0 _________________________________________________________________ dense_6 (Dense) multiple 130662 ================================================================= Total params: 2,388,646 Trainable params: 130,662 Non-trainable params: 2,257,984 _________________________________________________________________ Found 8278 images belonging to 102 classes. Found 866 images belonging to 102 classes. Epoch 1/10 260/260 [==============================] - 63s 243ms/step - loss: 1.3355 - accuracy: 0.6999 - val_loss: 0.4454 - val_accuracy: 0.8707 Epoch 2/10 260/260 [==============================] - 63s 244ms/step - loss: 0.3653 - accuracy: 0.8934 - val_loss: 0.4732 - val_accuracy: 0.8926 Epoch 3/10 260/260 [==============================] - 63s 243ms/step - loss: 0.2790 - accuracy: 0.9146 - val_loss: 0.3368 - val_accuracy: 0.8995 Epoch 4/10 260/260 [==============================] - 64s 245ms/step - loss: 0.2226 - accuracy: 0.9325 - val_loss: 0.3785 - val_accuracy: 0.8949 Epoch 5/10 260/260 [==============================] - 64s 245ms/step - loss: 0.2067 - accuracy: 0.9406 - val_loss: 0.3367 - val_accuracy: 0.9145 Epoch 6/10 260/260 [==============================] - 64s 244ms/step - loss: 0.1856 - accuracy: 0.9422 - val_loss: 0.3387 - val_accuracy: 0.9053 Epoch 7/10 260/260 [==============================] - 64s 244ms/step - loss: 0.1687 - accuracy: 0.9508 - val_loss: 0.3004 - val_accuracy: 0.9169 Epoch 8/10 260/260 [==============================] - 63s 241ms/step - loss: 0.1599 - accuracy: 0.9542 - val_loss: 0.3013 - val_accuracy: 0.9192 Epoch 9/10 260/260 [==============================] - 63s 242ms/step - loss: 0.1434 - accuracy: 0.9555 - val_loss: 0.3728 - val_accuracy: 0.9122 Epoch 10/10 260/260 [==============================] - 62s 239ms/step - loss: 0.1357 - accuracy: 0.9586 - val_loss: 0.3274 - val_accuracy: 0.9134 ###Markdown Now that we have trained the outputlayer of our model on the Caltech 101 data set, we can make the last layers of the MobileNetV2 model trainable and continue to fine tune it with a low learning rate. For this we need to recompile our model in order for the change of the MobileNetV2 parameters to trainable to have an effect. ###Code tf_learning_rate = 0.00001 tf_opt = k.optimizers.RMSprop(tf_learning_rate) base_model.trainable = True tf_mdl.compile(loss="sparse_categorical_crossentropy", optimizer=tf_opt, metrics=["accuracy"]) tf_mdl.build((tf_batch_size, 224, 224, 3)) tf_mdl.summary() tf_history_1 = tf_mdl.fit(train_gen, validation_data=val_gen, steps_per_epoch=int((1.0-val_split)*N_samples_Caltech101/tf_batch_size), validation_steps=int(val_split*N_samples_Caltech101/tf_batch_size), epochs=tf_epochs) ###Output Model: "my_transfer_model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= mobilenetv2_1.00_224 (Model) (None, 7, 7, 1280) 2257984 _________________________________________________________________ global_average_pooling2d (Gl multiple 0 _________________________________________________________________ dropout_1 (Dropout) multiple 0 _________________________________________________________________ dense_6 (Dense) multiple 130662 ================================================================= Total params: 2,388,646 Trainable params: 2,354,534 Non-trainable params: 34,112 _________________________________________________________________ Epoch 1/10 260/260 [==============================] - 64s 246ms/step - loss: 0.4107 - accuracy: 0.8862 - val_loss: 0.3158 - val_accuracy: 0.9203 Epoch 2/10 260/260 [==============================] - 63s 241ms/step - loss: 0.2256 - accuracy: 0.9342 - val_loss: 0.3229 - val_accuracy: 0.9145 Epoch 3/10 260/260 [==============================] - 63s 241ms/step - loss: 0.1694 - accuracy: 0.9483 - val_loss: 0.3285 - val_accuracy: 0.9180 Epoch 4/10 260/260 [==============================] - 63s 242ms/step - loss: 0.1426 - accuracy: 0.9542 - val_loss: 0.2743 - val_accuracy: 0.9169 Epoch 5/10 260/260 [==============================] - 63s 243ms/step - loss: 0.1198 - accuracy: 0.9591 - val_loss: 0.2728 - val_accuracy: 0.9192 Epoch 6/10 260/260 [==============================] - 64s 244ms/step - loss: 0.1091 - accuracy: 0.9638 - val_loss: 0.2651 - val_accuracy: 0.9342 Epoch 7/10 260/260 [==============================] - 63s 242ms/step - loss: 0.0996 - accuracy: 0.9670 - val_loss: 0.2382 - val_accuracy: 0.9249 Epoch 8/10 260/260 [==============================] - 63s 242ms/step - loss: 0.0959 - accuracy: 0.9681 - val_loss: 0.2475 - val_accuracy: 0.9307 Epoch 9/10 260/260 [==============================] - 63s 242ms/step - loss: 0.0838 - accuracy: 0.9721 - val_loss: 0.2783 - val_accuracy: 0.9238 Epoch 10/10 260/260 [==============================] - 63s 241ms/step - loss: 0.0815 - accuracy: 0.9739 - val_loss: 0.2763 - val_accuracy: 0.9284 ###Markdown As you can see from the increasing gap between training and validation loss and accuracy, overfitting is becoming a bigger problem now. This is due to the much higher number of trainable parameters if we not only train the output layer on the rather small Caltech 101 data set. But still we can improve the performance of our model. We can visualize this if we plot the accuracy over the training process. ###Code plt.plot(tf_history_0.history["accuracy"]+tf_history_1.history["accuracy"]) plt.plot(tf_history_0.history["val_accuracy"]+tf_history_1.history["val_accuracy"]) plt.xticks(range(len(tf_history_0.history["accuracy"]+tf_history_1.history["accuracy"]))) plt.axvline(9, color="green") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend(["Acc", "Val. Acc", "Start fine tuning"]) plt.show() ###Output _____no_output_____ ###Markdown Overall the resulting performance of the model is quite close to published results on the Caltach 101, e.g. this [paper](https://arxiv.org/abs/1406.4729v1), while the definintion and training of the model only required very little code.In order to evaluate if transfer learning actually makes a difference, we can simply train the MobileNetV2 on the Caltech 101 data set. As we already discussed, training such a high capacity model on such a small data set leads to heavy overfitting. ###Code tf_batch_size = 32 tf_epochs = 5 tf_learning_rate = 0.001 base_model = k.applications.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights=None) tf_mdl = MyTransferModel(base_model) tf_opt = k.optimizers.RMSprop(tf_learning_rate) tf_mdl.compile(loss="sparse_categorical_crossentropy", optimizer=tf_opt, metrics=["accuracy"]) tf_mdl.build((tf_batch_size, 224, 224, 3)) tf_mdl.summary() tf_history_2 = tf_mdl.fit(train_gen, validation_data=val_gen, steps_per_epoch=int((1.0-val_split)*N_samples_Caltech101/tf_batch_size), validation_steps=int(val_split*N_samples_Caltech101/tf_batch_size), epochs=tf_epochs) ###Output Model: "my_transfer_model_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= mobilenetv2_1.00_224 (Model) (None, 7, 7, 1280) 2257984 _________________________________________________________________ global_average_pooling2d_1 ( multiple 0 _________________________________________________________________ dropout_2 (Dropout) multiple 0 _________________________________________________________________ dense_7 (Dense) multiple 130662 ================================================================= Total params: 2,388,646 Trainable params: 2,354,534 Non-trainable params: 34,112 _________________________________________________________________ Epoch 1/10 260/260 [==============================] - 64s 245ms/step - loss: 3.7655 - accuracy: 0.2298 - val_loss: 4.4664 - val_accuracy: 0.0508 Epoch 2/10 260/260 [==============================] - 62s 240ms/step - loss: 3.0558 - accuracy: 0.3278 - val_loss: 5.0592 - val_accuracy: 0.0462 Epoch 3/10 260/260 [==============================] - 63s 242ms/step - loss: 2.7501 - accuracy: 0.3697 - val_loss: 5.4238 - val_accuracy: 0.0520 Epoch 4/10 260/260 [==============================] - 63s 242ms/step - loss: 2.4769 - accuracy: 0.4159 - val_loss: 5.9812 - val_accuracy: 0.0554 Epoch 5/10 28/260 [==>...........................] - ETA: 50s - loss: 2.3722 - accuracy: 0.4453 ###Markdown As you can see, training MobileNetV2 from scratch does not only suffer from severe overfitting but is also rather slow when compared with fine tuning. So overall it is recommended to use pretrained models and transfer learning if you want to train a high capacity neural network on a small data set, as it is often the case in practical applications. By doing this you can benefit from not only the architecture search of many experts but also save time and computational resources since a part of your model has already be pretrained by someone else. But you should always keep in mind that transfer learning is only a suitable method if there is a realistic chance of a positive transfer, i.e. the data set and task the model was pretrained on has to have something in common with your data set and task. Otherwise transfer learning can not only slow down the convergence speed but also hurt the final performance of your model. Catastrophic ForgettingDespite many advances in better architectures and training algorithms for training, neural networks still suffer from a long known phenomenon called "catastrophic forgetting". In order to understand what this phenomenon is we can compare human learning with the way neural networks learn. Humans can quickly learn from few examples and most importantly, they can learn to solve tasks in a sequential way. This means one can learn a language, e.g. english, and after a certain period of time learn a second language, e.g. chinese, without having to repeatedly refresh everthing that was learned on the first language. Neural networks are currently not capable of learning on a sequence of different tasks. In order to demonstrate this, we will train a neural network first on MNIST and then on the FashionMNIST data set. We want to be able to uniquely identify any class from both data sets. Since both data sets contain $10$ classes and use the labels $\lbrace0,\ldots,9\rbrace$ for them, we need to choose different labels for the FashionMNIST data set. We do this by loading the data set and shifting the labels by $10$ so that we get labels $\lbrace10,\ldots,19\rbrace$. ###Code (x_train_fmnist, y_train_fmnist), (x_test_fmnist, y_test_fmnist) = tf.keras.datasets.fashion_mnist.load_data() x_train_fmnist = np.expand_dims(x_train_fmnist, axis=-1).astype(np.float32) y_train_fmnist = y_train_fmnist + 10 x_test_fmnist = np.expand_dims(x_test_fmnist, axis=-1).astype(np.float32) y_test_fmnist = y_test_fmnist + 10 ###Output _____no_output_____ ###Markdown We also plot some examples of this data set and varify if the labels were shifted correctly. ###Code plt_img = np.zeros((280, 280)) for i in range(10): for j in range(10): plt_img[i*28:(i+1)*28, j*28:(j+1)*28] = np.squeeze(x_train_fmnist[i*10+j]) plt.imshow(plt_img, cmap="gray") plt.axis("off") plt.show() print("Labels") print("MNIST: "+str(np.unique(y_test_mnist))) print("FashionMNIST: "+str(np.unique(y_test_fmnist))) ###Output _____no_output_____ ###Markdown Now the data is prepared we need to define a new model that can classify images into $20$ different classes. This is necessary since the models we used up to this point only have $10$ neurons in their output layers and therefore are only capable of classifying into $10$ different categories. ###Code class MyExtendedModel(k.Model): def __init__(self): super(MyExtendedModel, self).__init__() self.conv0 = k.layers.Conv2D(8, 3, 2, activation="relu") self.conv1 = k.layers.Conv2D(16, 3, 2, activation="relu") self.flatten = k.layers.Flatten() self.dropout = k.layers.Dropout(0.25) self.dense0 = k.layers.Dense(128, activation="relu") self.dense1 = k.layers.Dense(64, activation="relu") self.dense2 = k.layers.Dense(20, activation="softmax") def call(self, inputs, training=False): output = self.conv0(inputs) output = self.conv1(output) output = self.flatten(output) output = self.dropout(output, training) output = self.dense0(output) output = self.dense1(output) output = self.dense2(output) return output ###Output _____no_output_____ ###Markdown With this model we are almost redy to start training on a sequence of tasks, i.e. we will first train on the MNIST data set in order to learn the classes $0$ up to $9$ and after that train on the FshionMNIST data set in order to learn the remaining classes from $10$ to $19$. During this process we want to evaluate the model separately on MNIST and FashionMNIST validation data. Since this is not a standard procedure, we need to implement a Callback class. Callbacks in Keras are used to implement actions that are executed at different points during the training process, e.g. at the beginning of the training, after a batch is processed or at the end of each epoch. See the [documentation](https://www.tensorflow.org/versions/r2.2/api_docs/python/tf/keras/callbacks) for an overview of all provided callbacks and the [guide](https://www.tensorflow.org/beta/guide/keras/custom_callbackan_overview_of_callback_methods) on writing custom callbacks. While there are predefined callbacks, e.g. for logging metrics into a tensorboard log file, there is unfortunately no callback that we could use to evaluate our model simultaneously on two different validation data sets. The only option we have is to implement our own callback. ###Code class MyCallback(tf.keras.callbacks.Callback): # Get the two different data sets and create lists for storing results def __init__(self, x_0, y_0, x_1, y_1, batch_size): super(MyCallback, self).__init__() self.x_0 = x_0 self.y_0 = y_0 self.x_1 = x_1 self.y_1 = y_1 self.loss_0 = [] self.acc_0 = [] self.loss_1 = [] self.acc_1 = [] self.batch_size = batch_size def on_epoch_end(self, epoch, logs=None): # Evaluate the model on both data sets and store results print("\nStarting callback...") print("+----------------------+") print("| Data set 0 |") print("+----------------------+") metrics_0 = self.model.evaluate(self.x_0, self.y_0, self.batch_size) self.loss_0.append(metrics_0[0]) self.acc_0.append(metrics_0[1]) print("+----------------------+") print("| Data set 1 |") print("+----------------------+") metrics_1 = self.model.evaluate(self.x_1, self.y_1, self.batch_size) self.loss_1.append(metrics_1[0]) self.acc_1.append(metrics_1[1]) print("Callback completed...") ###Output _____no_output_____ ###Markdown This callback will accept two data sets on its initialization that can be used during training to evaluate on. For this we override the on_epoch_end function to evaluate on both data sets, print the results and store them for later use. We now train our neural network first on MNIST in order to learn the classes $\lbrace0,\ldots,9\rbrace$ and then on FashionMNIST in order to learn the classes $\lbrace10,\ldots,19\rbrace$ while simultaneously evaluating the model on both, the MNIST and FashionMNIST test sets. If our neural network would be capable of learning continually, we would expect to see the loss on MNIST decrease as we train on it and remain low as we continue with the training on FashionMNIST. Similarly we would expect the accuracy to rise on MNIST as we train on it and remain stable even if we continue to train on FashionMNIST. ###Code extended_mdl = MyExtendedModel() extended_opt = tf.keras.optimizers.RMSprop(learning_rate) extended_mdl.compile(loss="sparse_categorical_crossentropy", optimizer=extended_opt, metrics=["accuracy"]) my_cb = MyCallback(x_test_mnist, y_test_mnist, x_test_fmnist, y_test_fmnist, batch_size) extended_mdl.fit(x_train_mnist, y_train_mnist, batch_size, epochs, callbacks=[my_cb]) extended_mdl.fit(x_train_fmnist, y_train_fmnist, batch_size, epochs, callbacks=[my_cb]) ###Output Epoch 1/20 465/469 [============================>.] - ETA: 0s - loss: 0.5914 - accuracy: 0.8643 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.1235 - accuracy: 0.9595 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 14.8833 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.5879 - accuracy: 0.8650 Epoch 2/20 461/469 [============================>.] - ETA: 0s - loss: 0.1416 - accuracy: 0.9561 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0833 - accuracy: 0.9737 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 14.4861 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.1416 - accuracy: 0.9561 Epoch 3/20 462/469 [============================>.] - ETA: 0s - loss: 0.1004 - accuracy: 0.9681 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0720 - accuracy: 0.9757 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 15.2568 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.1009 - accuracy: 0.9681 Epoch 4/20 456/469 [============================>.] - ETA: 0s - loss: 0.0876 - accuracy: 0.9728 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0674 - accuracy: 0.9777 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 14.6159 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.0873 - accuracy: 0.9728 Epoch 5/20 453/469 [===========================>..] - ETA: 0s - loss: 0.0763 - accuracy: 0.9758 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0646 - accuracy: 0.9786 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 20.7221 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.0762 - accuracy: 0.9760 Epoch 6/20 466/469 [============================>.] - ETA: 0s - loss: 0.0658 - accuracy: 0.9789 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0662 - accuracy: 0.9809 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 17.9167 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.0658 - accuracy: 0.9789 Epoch 7/20 460/469 [============================>.] - ETA: 0s - loss: 0.0587 - accuracy: 0.9812 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0582 - accuracy: 0.9822 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 21.5782 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0584 - accuracy: 0.9812 Epoch 8/20 469/469 [==============================] - ETA: 0s - loss: 0.0568 - accuracy: 0.9819 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0523 - accuracy: 0.9842 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 18.8078 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0568 - accuracy: 0.9819 Epoch 9/20 468/469 [============================>.] - ETA: 0s - loss: 0.0518 - accuracy: 0.9830 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0476 - accuracy: 0.9856 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 18.5827 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0518 - accuracy: 0.9830 Epoch 10/20 461/469 [============================>.] - ETA: 0s - loss: 0.0503 - accuracy: 0.9845 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0556 - accuracy: 0.9843 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 24.6296 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0503 - accuracy: 0.9845 Epoch 11/20 448/469 [===========================>..] - ETA: 0s - loss: 0.0477 - accuracy: 0.9851 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0520 - accuracy: 0.9856 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 19.0023 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0481 - accuracy: 0.9849 Epoch 12/20 459/469 [============================>.] - ETA: 0s - loss: 0.0462 - accuracy: 0.9860 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0578 - accuracy: 0.9847 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 23.5102 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.0459 - accuracy: 0.9862 Epoch 13/20 462/469 [============================>.] - ETA: 0s - loss: 0.0438 - accuracy: 0.9861 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0571 - accuracy: 0.9850 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 26.4608 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0436 - accuracy: 0.9862 Epoch 14/20 447/469 [===========================>..] - ETA: 0s - loss: 0.0404 - accuracy: 0.9873 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0511 - accuracy: 0.9859 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 26.3339 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0406 - accuracy: 0.9873 Epoch 15/20 451/469 [===========================>..] - ETA: 0s - loss: 0.0397 - accuracy: 0.9869 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0521 - accuracy: 0.9851 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 24.0854 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.0398 - accuracy: 0.9869 Epoch 16/20 469/469 [==============================] - ETA: 0s - loss: 0.0382 - accuracy: 0.9885 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0561 - accuracy: 0.9848 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 20.9028 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.0382 - accuracy: 0.9885 Epoch 17/20 456/469 [============================>.] - ETA: 0s - loss: 0.0367 - accuracy: 0.9884 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0568 - accuracy: 0.9847 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 21.9710 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0373 - accuracy: 0.9883 Epoch 18/20 469/469 [==============================] - ETA: 0s - loss: 0.0372 - accuracy: 0.9884 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0493 - accuracy: 0.9859 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 24.4688 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0372 - accuracy: 0.9884 Epoch 19/20 462/469 [============================>.] - ETA: 0s - loss: 0.0360 - accuracy: 0.9891 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0542 - accuracy: 0.9858 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 27.9090 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.0363 - accuracy: 0.9890 Epoch 20/20 468/469 [============================>.] - ETA: 0s - loss: 0.0351 - accuracy: 0.9890 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.0499 - accuracy: 0.9865 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 23.9937 - accuracy: 0.0000e+00 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.0352 - accuracy: 0.9890 Epoch 1/20 466/469 [============================>.] - ETA: 0s - loss: 0.8005 - accuracy: 0.7543 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 28.9105 - accuracy: 0.0011 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.4612 - accuracy: 0.8338 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.7984 - accuracy: 0.7546 Epoch 2/20 446/469 [===========================>..] - ETA: 0s - loss: 0.4429 - accuracy: 0.8406 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 32.9707 - accuracy: 0.0000e+00 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.3895 - accuracy: 0.8615 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.4423 - accuracy: 0.8409 Epoch 3/20 461/469 [============================>.] - ETA: 0s - loss: 0.3900 - accuracy: 0.8575 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 44.7675 - accuracy: 0.0000e+00 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.3715 - accuracy: 0.8666 Callback completed... 469/469 [==============================] - 1s 3ms/step - loss: 0.3896 - accuracy: 0.8576 Epoch 4/20 461/469 [============================>.] - ETA: 0s - loss: 0.3594 - accuracy: 0.8680 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 42.1162 - accuracy: 0.0000e+00 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.3536 - accuracy: 0.8714 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.3590 - accuracy: 0.8680 Epoch 5/20 467/469 [============================>.] - ETA: 0s - loss: 0.3380 - accuracy: 0.8748 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 40.2410 - accuracy: 0.0000e+00 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.3418 - accuracy: 0.8742 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.3380 - accuracy: 0.8748 Epoch 6/20 460/469 [============================>.] - ETA: 0s - loss: 0.3212 - accuracy: 0.8814 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 48.1656 - accuracy: 0.0000e+00 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.3375 - accuracy: 0.8784 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.3209 - accuracy: 0.8816 Epoch 7/20 464/469 [============================>.] - ETA: 0s - loss: 0.3071 - accuracy: 0.8873 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 45.3209 - accuracy: 0.0000e+00 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.3367 - accuracy: 0.8753 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.3071 - accuracy: 0.8872 Epoch 8/20 446/469 [===========================>..] - ETA: 0s - loss: 0.2978 - accuracy: 0.8896 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 51.7852 - accuracy: 0.0000e+00 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.3357 - accuracy: 0.8799 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.2973 - accuracy: 0.8899 Epoch 9/20 468/469 [============================>.] - ETA: 0s - loss: 0.2900 - accuracy: 0.8927 Starting callback... +----------------------+ | Data set 0 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 49.1386 - accuracy: 0.0000e+00 +----------------------+ | Data set 1 | +----------------------+ 79/79 [==============================] - 0s 1ms/step - loss: 0.3143 - accuracy: 0.8867 Callback completed... 469/469 [==============================] - 1s 2ms/step - loss: 0.2902 - accuracy: 0.8926 Epoch 10/20 465/469 [============================>.] - ETA: 0s - loss: 0.2807 - accuracy: 0.8944 Starting callback... +----------------------+ | Data set 0 | +----------------------+ ###Markdown If we now plot the loss on the test sets during the sequential training process on MNIST and FashionMNIST, we can clearly see what catastrophic forgetting means. ###Code plt.subplot(2, 1, 1) plt.plot(my_cb.loss_0) plt.plot(my_cb.loss_1) plt.legend(["MNIST", "FashionMNIST"]) plt.title("Loss") plt.subplot(2, 1, 2) plt.plot(my_cb.acc_0) plt.plot(my_cb.acc_1) plt.legend(["MNIST", "FashionMNIST"]) plt.title("Accuracy") plt.xlabel("Epochs") plt.tight_layout() plt.show() ###Output _____no_output_____
_notebooks/2020-05-26-set-zeroes.ipynb
###Markdown "Set Matrix Zeroes"> "[[Leetcode]](https://leetcode.com/problems/set-matrix-zeroes/)[Arrays][Matrix]"- toc: true - badges: true- comments: true- categories: [Problem Solving,Leetcode]- comments: true- author: Teja Kummarikuntla Problem StatementGiven a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1:```Input: [ [1,1,1], [1,0,1], [1,1,1]]Output: [ [1,0,1], [0,0,0], [1,0,1]]``` Example 2:```Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5]]Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0]]``` Follow up:- A straight forward solution using O(mn) space is probably a bad idea.- A simple improvement uses O(m + n) space, but still not the best solution.- Could you devise a constant space solution?[[URL]](https://leetcode.com/problems/set-matrix-zeroes/) Approach 1 ###Code #collapse-hide from typing import List class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ temp = [] matrixCopy = [] for row in matrix: for element in row: temp.append(element) matrixCopy.append(temp) temp = [] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrixCopy[i][j] == 0: for k in range(len(matrix[0])): matrix[i][k] = 0 for k in range(len(matrix)): matrix[k][j] = 0 return matrix sol = Solution() sol.setZeroes([ [1,1,1], [1,0,1], [1,1,1] ]) ###Output _____no_output_____ ###Markdown ![](Images/Problem_solving/setZeroes/Approach1_sub.png) **Worst case performance in Time: $O(m*n)$** **Worst case performance in Space:** $O(m*n)$ **Is Inplace?** : ```False``` Approach 2 1. Traverse the original matrix and look for 0 entities2. if found, record the i, j values using auxilary variables3. Using sets for recording i, j vlues would be benifiting as we overcome duplicate row, column values ahead.4. Finally, re iterate over the original matrix, for every cell make a check `if i in rows or j in columns`, update the values to 0. ###Code #collapse-hide class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ rows = set() columns = set() for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: rows.add(i) columns.add(j) for i in range(len(matrix)): for j in range(len(matrix[0])): if i in rows or j in columns: matrix[i][j] = 0 return matrix sol = Solution() sol.setZeroes([ [1,1,1], [1,0,1], [1,1,1] ]) ###Output _____no_output_____ ###Markdown ![](Images/Problem_solving/setZeroes/Approach2_sub.png) **Worst case performance in Time: $O(m*n)$** **Worst case performance in Space:** $O(m+n)$ **Is Inplace?** : ```False``` Approach 3 ###Code #collapse-hide class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ rowFlag, colFlag = False, False for i in range(len(matrix)): for j in range(len(matrix[0])): if i == 0 and matrix[i][j] == 0: rowFlag = True if j ==0 and matrix[i][j] == 0: colFlag = True if matrix[i][j] == 0: matrix[0][j] = 0 matrix[i][0] = 0 for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 if rowFlag == True: for i in range(len(matrix[0])): matrix[0][i] = 0 if colFlag == True: for i in range(len(matrix)): matrix[j][0] = 0 return matrix sol = Solution() sol.setZeroes([ [1,1,1], [1,0,1], [1,1,1] ]) ###Output _____no_output_____
Notebooks/.ipynb_checkpoints/7. K-Means Clustering and Principal Component Analysis-checkpoint.ipynb
###Markdown Programming Exercise 7 - K-means Clustering and Principal Component Analysis ###Code # import libraries import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy.io import loadmat from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from scipy import linalg pd.set_option('display.notebook_repr_html', False) pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', 150) pd.set_option('display.max_seq_items', None) # matplotlib inline %matplotlib inline import seaborn as sns sns.set_context('notebook') sns.set_style('white') ###Output _____no_output_____ ###Markdown K-means in example dataset ###Code data1 = loadmat('data/ex7data2.mat') data1.keys() X1 = data1['X'] print('X1', X1.shape) km1 = KMeans(3) km1.fit(X1) plt.scatter(X1[:, 0], X1[:, 1], s=40, c=km1.labels_, cmap=plt.cm.prism) plt.title('K-Means Clustering Results with K=3') plt.scatter(km1.cluster_centers_[:, 0], km1.cluster_centers_[:, 1], marker='+', s=100, c='k', linewidth=2) ###Output _____no_output_____ ###Markdown Image Compression Using K-Means Clustering ###Code img = plt.imread('data/bird_small.png') img_shape = img.shape img_shape A = img/255 AA = A.reshape(128*128, 3) km2 = KMeans(16) km2.fit(AA) B = km2.cluster_centers_[km2.labels_].reshape(img_shape[0], img.shape[1], 3) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 9)) ax1.imshow(img) ax1.set_title('Original') ax2.imshow(B*255) ax2.set_title('Compressed, with 16 colors') for ax in fig.axes: ax.axis('off') ###Output _____no_output_____ ###Markdown PCA on example dataset Using scipy insted of scikit-learn ###Code data2 = loadmat('data/ex7data1.mat') data2.keys() X2 = data2['X'] print('X2:', X2.shape) # Standardizing the data scaler = StandardScaler() scaler.fit(X2) U, S, V = linalg.svd(scaler.transform(X2).T) print(U) print(S) plt.scatter(X2[:,0], X2[:,1], s=30, edgecolors='b', facecolors='None', linewidth=1) #set aspect ratio to 'equal' in order to show orthogonality of principal components in the plot plt.gca().set_aspect('equal') plt.quiver(scaler.mean_[0], scaler.mean_[1], U[0,0], U[0,1], scale=S[1], color='r') plt.quiver(scaler.mean_[0], scaler.mean_[1], U[1,0], U[1,1], scale=S[1], color='r') ###Output _____no_output_____
Downloader Example.ipynb
###Markdown Downloader exampleThe `Downloader` class is responsible for fetching, pre-process and caching data from a given GitHub repository. ###Code from os import getenv from dotenv import load_dotenv from hub_downloader import Downloader # for reloading the Downloader after code change %reload_ext autoreload %autoreload 1 %aimport hub_downloader # loading environment variables from .env file load_dotenv(); owner = 'pandas-dev' repo = 'pandas' downloader = Downloader(owner, repo, getenv('GITHUB_OAUTH_TOKEN'), verbose=True) downloader.get_commit_activity() total_contributions, weekly_contributions = downloader.get_contributors_statistic() total_contributions weekly_contributions downloader.get_stargazers() downloader.get_issues() downloader.get_code_frequency_statistic() ###Output _____no_output_____
SDSC-2016-Joyce-modified/bigdata0_spark/3_house_price_join.ipynb
###Markdown Create a local file ###Code %%file inflation.txt Downtown 2.1 Hilltop 4.5 !cat inflation.txt ###Output _____no_output_____ ###Markdown Copy the file to the distributed file system HDFS ###Code !hdfs dfs -copyFromLocal inflation.txt /data/ ###Output _____no_output_____ ###Markdown Verify that the file is replicated 3 times Load house prices ###Code text_RDD = sc.textFile("/data/houses.txt") def mapper_parse_lines(line): """Parse line into (neighborhoood, price) pair""" words = line.split() return (words[1], float(words[2])) house_prices_RDD = text_RDD.map(mapper_parse_lines) house_prices_RDD.collect() ###Output _____no_output_____ ###Markdown Load inflation ###Code inflation_text_RDD = sc.textFile("/data/inflation.txt") def mapper_parse__inflation_lines(line): """Parse line into (neighborhoood, inflation) pair""" words = line.split() return (words[0], float(words[1])) inflation_RDD = inflation_text_RDD.map(mapper_parse__inflation_lines) inflation_RDD.collect() ###Output _____no_output_____ ###Markdown join ###Code house_prices_RDD.join(inflation_RDD).collect() def mapper_multiply_price_inflation(pair): inflation_ratio = 1 + pair[1][1]/100. return (pair[0], pair[1][0]*inflation_ratio) house_prices_nextyear_RDD = house_prices_RDD.join( inflation_RDD).map(mapper_multiply_price_inflation) house_prices_nextyear_RDD.collect() ###Output _____no_output_____ ###Markdown reduce ###Code def reducer_sum(a,b): return a+b total_nextyear = house_prices_nextyear_RDD.reduceByKey(reducer_sum) total_nextyear.collect() ###Output _____no_output_____ ###Markdown ExcerciseList neighborhood and house price only for the neighborhoods where inflation is low (less than 4%)(Advanced: for each of those neighborhoods, find the more expensive house) Print DAG ###Code print(total_nextyear.toDebugString()) ###Output _____no_output_____
02_Python_Code/02_Modeling/02_Decision_Tree_&_Random_Forest_Classification/2020_1125_Decision_Tree_&_Random_Forest_Classification.ipynb
###Markdown Classifying Pulsars from the High Time Resolution Universe Survey (HTRU2) - Decision Tree & Random Forest Classification Overview & Citation In this code notebook, we attempt to classify pulsars from the High Time Resolution Universe Survey, South (HTRU2) dataset using decision tree and random forest classification. The dataset was retrieved from the UC Irvine Machine Learning Repository at the following link: https://archive.ics.uci.edu/ml/datasets/HTRU2.The dataset was donated to the UCI Repository by Dr. Robert Lyon of The University of Manchester, United Kingdom. The two papers requested for citation in the description are listed below:* R. J. Lyon, B. W. Stappers, S. Cooper, J. M. Brooke, J. D. Knowles, Fifty Years of Pulsar Candidate Selection: From simple filters to a new principled real-time classification approach, Monthly Notices of the Royal Astronomical Society 459 (1), 1104-1123, DOI: 10.1093/mnras/stw656* R. J. Lyon, HTRU2, DOI: 10.6084/m9.figshare.3080389.v1. Import the Relevant Libraries ###Code # Data Manipulation import pandas as pd import numpy as np # Modeling & Evaluation from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix,classification_report ###Output _____no_output_____ ###Markdown Import & Check the Data ###Code df = pd.read_csv('2020_1125_Pulsar_Data.csv') pulsar_data = df.copy() pulsar_data.head() ###Output _____no_output_____ ###Markdown Train Test Split The following train test split will be used for both the decision tree and random forest classifications below: ###Code X = pulsar_data.drop('Class',axis=1) y = pulsar_data['Class'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) ###Output _____no_output_____ ###Markdown Decision Tree Classification Build and Test the Model ###Code tree = DecisionTreeClassifier() tree.fit(X_train,y_train) y_pred = tree.predict(X_test) ###Output _____no_output_____ ###Markdown Model Evaluation ###Code confusion = confusion_matrix(y_test,y_pred) print(f'CONFUSION MATRIX:\n\n{confusion[0][0]}\t{confusion[0][1]}\n{confusion[1][0]}\t{confusion[1][1]}') print(f'CLASSIFICATION REPORT:\n\n{classification_report(y_test,y_pred)}') ###Output CLASSIFICATION REPORT: precision recall f1-score support 0 0.99 0.98 0.98 4070 1 0.84 0.86 0.85 405 accuracy 0.97 4475 macro avg 0.91 0.92 0.92 4475 weighted avg 0.97 0.97 0.97 4475 ###Markdown The dataset contains a total of 1,639 actual pulsars out of 16,259 instances in the dataset (approximately 10%). This means that we have an unbalanced classification problem, and accuracy is not a good metric. Therefore, the most important metrics for predicting a pulsar with this model are:* Precision = 0.84* Recall = 0.86* F1-Score = 0.85Let's save this data to a .csv file for future comparison with the other classification models: ###Code with open("2020_1125_Decision_Tree_Results.csv","w") as file: file.write('Model,Accuracy,Precision,Recall,F1-Score\n') file.write('Decision_Tree,0.97,0.84,0.86,0.85\n') ###Output _____no_output_____ ###Markdown Random Forest Classification Build and Test the Model ###Code forest = RandomForestClassifier(n_estimators=100) forest.fit(X_train,y_train) y_pred = forest.predict(X_test) ###Output _____no_output_____ ###Markdown Model Evaluation ###Code confusion = confusion_matrix(y_test,y_pred) print(f'CONFUSION MATRIX:\n\n{confusion[0][0]}\t{confusion[0][1]}\n{confusion[1][0]}\t{confusion[1][1]}') print(f'CLASSIFICATION REPORT:\n\n{classification_report(y_test,y_pred)}') ###Output CLASSIFICATION REPORT: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.94 4475 weighted avg 0.98 0.98 0.98 4475 ###Markdown We see that the random forest classifier has performed significantly better than the decision tree classifier in terms of precision and f1-score. Let's see if we can improve the performance of our random forest by experimenting with the number of estimators in the random forest. Improving Performance ###Code # Test the data with random forest classifiers of variable n_estimators. # Please note that this may take a few minutes to run. for i in range(100,1600,100): forest_loop = RandomForestClassifier(n_estimators=i) forest_loop.fit(X_train,y_train) y_pred_loop = forest_loop.predict(X_test) print(f'CLASSIFICATION REPORT FOR {i} ESTIMATORS:\n\n{classification_report(y_test,y_pred_loop)}\n\n') ###Output CLASSIFICATION REPORT FOR 100 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.94 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 200 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.93 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.93 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 300 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.94 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 400 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.82 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.93 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 500 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.93 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 600 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.94 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 700 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.94 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 800 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.93 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 900 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.93 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 1000 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.84 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.92 0.94 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 1100 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.94 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 1200 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.94 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 1300 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.93 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 1400 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.94 4475 weighted avg 0.98 0.98 0.98 4475 CLASSIFICATION REPORT FOR 1500 ESTIMATORS: precision recall f1-score support 0 0.98 0.99 0.99 4070 1 0.94 0.83 0.88 405 accuracy 0.98 4475 macro avg 0.96 0.91 0.93 4475 weighted avg 0.98 0.98 0.98 4475 ###Markdown The best random forest model used 1000 estimators and yielded the following metrics:* Accuracy = 0.98* Precision = 0.94* Recall = 0.84* F1-Score = 0.88Let's save this in a .csv file for future reference: ###Code with open("2020_1125_Random_Forest_Results.csv","w") as file: file.write('Model,Accuracy,Precision,Recall,F1-Score\n') file.write('Random_Forest,0.98,0.94,0.84,0.88\n') ###Output _____no_output_____
notebooks/building_production_ml_systems/labs/2_hyperparameter_tuning.ipynb
###Markdown Hyperparameter tuning**Learning Objectives**1. Learn how to use `cloudml-hypertune` to report the results for Cloud hyperparameter tuning trial runs2. Learn how to configure the `.yaml` file for submitting a Cloud hyperparameter tuning job3. Submit a hyperparameter tuning job to Cloud AI Platform IntroductionLet's see if we can improve upon that by tuning our hyperparameters.Hyperparameters are parameters that are set *prior* to training a model, as opposed to parameters which are learned *during* training. These include learning rate and batch size, but also model design parameters such as type of activation function and number of hidden units.Here are the four most common ways to finding the ideal hyperparameters:1. Manual2. Grid Search3. Random Search4. Bayesian Optimzation**1. Manual**Traditionally, hyperparameter tuning is a manual trial and error process. A data scientist has some intution about suitable hyperparameters which they use as a starting point, then they observe the result and use that information to try a new set of hyperparameters to try to beat the existing performance. Pros- Educational, builds up your intuition as a data scientist- Inexpensive because only one trial is conducted at a timeCons- Requires alot of time and patience**2. Grid Search**On the other extreme we can use grid search. Define a discrete set of values to try for each hyperparameter then try every possible combination. Pros- Can run hundreds of trials in parallel using the cloud- Gauranteed to find the best solution within the search spaceCons- Expensive**3. Random Search**Alternatively define a range for each hyperparamter (e.g. 0-256) and sample uniformly at random from that range. Pros- Can run hundreds of trials in parallel using the cloud- Requires less trials than Grid Search to find a good solutionCons- Expensive (but less so than Grid Search)**4. Bayesian Optimization**Unlike Grid Search and Random Search, Bayesian Optimization takes into account information from past trials to select parameters for future trials. The details of how this is done is beyond the scope of this notebook, but if you're interested you can read how it works here [here](https://cloud.google.com/blog/products/gcp/hyperparameter-tuning-cloud-machine-learning-engine-using-bayesian-optimization). Pros- Picks values intelligenty based on results from past trials- Less expensive because requires fewer trials to get a good resultCons- Requires sequential trials for best results, takes longer**AI Platform HyperTune**AI Platform HyperTune, powered by [Google Vizier](https://ai.google/research/pubs/pub46180), uses Bayesian Optimization by default, but [also supports](https://cloud.google.com/ml-engine/docs/tensorflow/hyperparameter-tuning-overviewsearch_algorithms) Grid Search and Random Search. When tuning just a few hyperparameters (say less than 4), Grid Search and Random Search work well, but when tunining several hyperparameters and the search space is large Bayesian Optimization is best. ###Code # Change below if necessary PROJECT = !gcloud config get-value project # noqa: E999 PROJECT = PROJECT[0] BUCKET = PROJECT REGION = "us-central1" %env PROJECT=$PROJECT %env BUCKET=$BUCKET %env REGION=$REGION %env TFVERSION=2.5 %%bash gcloud config set project $PROJECT gcloud config set ai_platform/region $REGION ###Output _____no_output_____ ###Markdown Make code compatible with AI Platform Training ServiceIn order to make our code compatible with AI Platform Training Service we need to make the following changes:1. Upload data to Google Cloud Storage 2. Move code into a trainer Python package4. Submit training job with `gcloud` to train on AI Platform Upload data to Google Cloud Storage (GCS)Cloud services don't have access to our local files, so we need to upload them to a location the Cloud servers can read from. In this case we'll use GCS.To do this run the notebook [0_export_data_from_bq_to_gcs.ipynb](./0_export_data_from_bq_to_gcs.ipynb), which will export the taxifare data from BigQuery directly into a GCS bucket. If all ran smoothly, you should be able to list the data bucket by running the following command: ###Code !gsutil ls gs://$BUCKET/taxifare/data ###Output _____no_output_____ ###Markdown Move code into python packageIn the [previous lab](./1_training_at_scale.ipynb), we moved our code into a python package for training on Cloud AI Platform. Let's just check that the files are there. You should see the following files in the `taxifare/trainer` directory: - `__init__.py` - `model.py` - `task.py` ###Code !ls -la taxifare/trainer ###Output _____no_output_____ ###Markdown To use hyperparameter tuning in your training job you must perform the following steps: 1. Specify the hyperparameter tuning configuration for your training job by including a HyperparameterSpec in your TrainingInput object. 2. Include the following code in your training application: - Parse the command-line arguments representing the hyperparameters you want to tune, and use the values to set the hyperparameters for your training trial.Add your hyperparameter metric to the summary for your graph. - To submit a hyperparameter tuning job, we must modify `model.py` and `task.py` to expose any variables we want to tune as command line arguments. Modify model.py Exercise.Complete the TODOs in the `train_and_evaluate` functin below. - Define the hyperparameter tuning metric `hp_metric` - Set up cloudml-hypertune to report the results of each trial by calling its helper function, `report_hyperparameter_tuning_metric` ###Code %%writefile ./taxifare/trainer/model.py import datetime import logging import os import shutil import hypertune import numpy as np import tensorflow as tf from tensorflow import feature_column as fc from tensorflow.keras import activations, callbacks, layers, models logging.info(tf.version.VERSION) CSV_COLUMNS = [ "fare_amount", "pickup_datetime", "pickup_longitude", "pickup_latitude", "dropoff_longitude", "dropoff_latitude", "passenger_count", "key", ] LABEL_COLUMN = "fare_amount" DEFAULTS = [[0.0], ["na"], [0.0], [0.0], [0.0], [0.0], [0.0], ["na"]] DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] def features_and_labels(row_data): for unwanted_col in ["key"]: row_data.pop(unwanted_col) label = row_data.pop(LABEL_COLUMN) return row_data, label def load_dataset(pattern, batch_size, num_repeat): dataset = tf.data.experimental.make_csv_dataset( file_pattern=pattern, batch_size=batch_size, column_names=CSV_COLUMNS, column_defaults=DEFAULTS, num_epochs=num_repeat, shuffle_buffer_size=1000000, ) return dataset.map(features_and_labels) def create_train_dataset(pattern, batch_size): dataset = load_dataset(pattern, batch_size, num_repeat=None) return dataset.prefetch(1) def create_eval_dataset(pattern, batch_size): dataset = load_dataset(pattern, batch_size, num_repeat=1) return dataset.prefetch(1) def parse_datetime(s): if not isinstance(s, str): s = s.numpy().decode("utf-8") return datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S %Z") def euclidean(params): lon1, lat1, lon2, lat2 = params londiff = lon2 - lon1 latdiff = lat2 - lat1 return tf.sqrt(londiff * londiff + latdiff * latdiff) def get_dayofweek(s): ts = parse_datetime(s) return DAYS[ts.weekday()] @tf.function def dayofweek(ts_in): return tf.map_fn( lambda s: tf.py_function(get_dayofweek, inp=[s], Tout=tf.string), ts_in ) @tf.function def fare_thresh(x): return 60 * activations.relu(x) def transform(inputs, NUMERIC_COLS, STRING_COLS, nbuckets): # Pass-through columns transformed = inputs.copy() del transformed["pickup_datetime"] feature_columns = { colname: fc.numeric_column(colname) for colname in NUMERIC_COLS } # Scaling longitude from range [-70, -78] to [0, 1] for lon_col in ["pickup_longitude", "dropoff_longitude"]: transformed[lon_col] = layers.Lambda( lambda x: (x + 78) / 8.0, name=f"scale_{lon_col}" )(inputs[lon_col]) # Scaling latitude from range [37, 45] to [0, 1] for lat_col in ["pickup_latitude", "dropoff_latitude"]: transformed[lat_col] = layers.Lambda( lambda x: (x - 37) / 8.0, name=f"scale_{lat_col}" )(inputs[lat_col]) # Adding Euclidean dist (no need to be accurate: NN will calibrate it) transformed["euclidean"] = layers.Lambda(euclidean, name="euclidean")( [ inputs["pickup_longitude"], inputs["pickup_latitude"], inputs["dropoff_longitude"], inputs["dropoff_latitude"], ] ) feature_columns["euclidean"] = fc.numeric_column("euclidean") # hour of day from timestamp of form '2010-02-08 09:17:00+00:00' transformed["hourofday"] = layers.Lambda( lambda x: tf.strings.to_number( tf.strings.substr(x, 11, 2), out_type=tf.dtypes.int32 ), name="hourofday", )(inputs["pickup_datetime"]) feature_columns["hourofday"] = fc.indicator_column( fc.categorical_column_with_identity("hourofday", num_buckets=24) ) latbuckets = np.linspace(0, 1, nbuckets).tolist() lonbuckets = np.linspace(0, 1, nbuckets).tolist() b_plat = fc.bucketized_column( feature_columns["pickup_latitude"], latbuckets ) b_dlat = fc.bucketized_column( feature_columns["dropoff_latitude"], latbuckets ) b_plon = fc.bucketized_column( feature_columns["pickup_longitude"], lonbuckets ) b_dlon = fc.bucketized_column( feature_columns["dropoff_longitude"], lonbuckets ) ploc = fc.crossed_column([b_plat, b_plon], nbuckets * nbuckets) dloc = fc.crossed_column([b_dlat, b_dlon], nbuckets * nbuckets) pd_pair = fc.crossed_column([ploc, dloc], nbuckets ** 4) feature_columns["pickup_and_dropoff"] = fc.embedding_column(pd_pair, 100) return transformed, feature_columns def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) def build_dnn_model(nbuckets, nnsize, lr): # input layer is all float except for pickup_datetime which is a string STRING_COLS = ["pickup_datetime"] NUMERIC_COLS = {CSV_COLUMNS} - {LABEL_COLUMN, "key"} - {STRING_COLS} inputs = { colname: layers.Input(name=colname, shape=(), dtype="float32") for colname in NUMERIC_COLS } inputs.update( { colname: layers.Input(name=colname, shape=(), dtype="string") for colname in STRING_COLS } ) # transforms transformed, feature_columns = transform( inputs, NUMERIC_COLS, STRING_COLS, nbuckets=nbuckets ) dnn_inputs = layers.DenseFeatures(feature_columns.values())(transformed) x = dnn_inputs for layer, nodes in enumerate(nnsize): x = layers.Dense(nodes, activation="relu", name=f"h{layer}")(x) output = layers.Dense(1, name="fare")(x) model = models.Model(inputs, output) lr_optimizer = tf.keras.optimizers.Adam(learning_rate=lr) model.compile(optimizer=lr_optimizer, loss="mse", metrics=[rmse, "mse"]) return model def train_and_evaluate(hparams): batch_size = hparams["batch_size"] eval_data_path = hparams["eval_data_path"] nnsize = hparams["nnsize"] nbuckets = hparams["nbuckets"] lr = hparams["lr"] num_evals = hparams["num_evals"] num_examples_to_train_on = hparams["num_examples_to_train_on"] output_dir = hparams["output_dir"] train_data_path = hparams["train_data_path"] if tf.io.gfile.exists(output_dir): tf.io.gfile.rmtree(output_dir) timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") savedmodel_dir = os.path.join(output_dir, "savedmodel") model_export_path = os.path.join(savedmodel_dir, timestamp) checkpoint_path = os.path.join(output_dir, "checkpoints") tensorboard_path = os.path.join(output_dir, "tensorboard") dnn_model = build_dnn_model(nbuckets, nnsize, lr) logging.info(dnn_model.summary()) trainds = create_train_dataset(train_data_path, batch_size) evalds = create_eval_dataset(eval_data_path, batch_size) steps_per_epoch = num_examples_to_train_on // (batch_size * num_evals) checkpoint_cb = callbacks.ModelCheckpoint( checkpoint_path, save_weights_only=True, verbose=1 ) tensorboard_cb = callbacks.TensorBoard(tensorboard_path, histogram_freq=1) history = dnn_model.fit( trainds, validation_data=evalds, epochs=num_evals, steps_per_epoch=max(1, steps_per_epoch), verbose=2, # 0=silent, 1=progress bar, 2=one line per epoch callbacks=[checkpoint_cb, tensorboard_cb], ) # Exporting the model with default serving function. tf.saved_model.save(dnn_model, model_export_path) # TODO 1 hp_metric = # TODO: Your code goes here # TODO 1 hpt = # TODO: Your code goes here # TODO: Your code goes here return history ###Output _____no_output_____ ###Markdown Modify task.py ###Code %%writefile taxifare/trainer/task.py import argparse import json import os from trainer import model if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--batch_size", help="Batch size for training steps", type=int, default=32, ) parser.add_argument( "--eval_data_path", help="GCS location pattern of eval files", required=True, ) parser.add_argument( "--nnsize", help="Hidden layer sizes (provide space-separated sizes)", nargs="+", type=int, default=[32, 8], ) parser.add_argument( "--nbuckets", help="Number of buckets to divide lat and lon with", type=int, default=10, ) parser.add_argument( "--lr", help="learning rate for optimizer", type=float, default=0.001 ) parser.add_argument( "--num_evals", help="Number of times to evaluate model on eval data training.", type=int, default=5, ) parser.add_argument( "--num_examples_to_train_on", help="Number of examples to train on.", type=int, default=100, ) parser.add_argument( "--output_dir", help="GCS location to write checkpoints and export models", required=True, ) parser.add_argument( "--train_data_path", help="GCS location pattern of train files containing eval URLs", required=True, ) parser.add_argument( "--job-dir", help="this model ignores this field, but it is required by gcloud", default="junk", ) args, _ = parser.parse_known_args() hparams = args.__dict__ hparams["output_dir"] = os.path.join( hparams["output_dir"], json.loads(os.environ.get("TF_CONFIG", "{}")) .get("task", {}) .get("trial", ""), ) print("output_dir", hparams["output_dir"]) model.train_and_evaluate(hparams) ###Output _____no_output_____ ###Markdown Create config.yaml fileSpecify the hyperparameter tuning configuration for your training jobCreate a HyperparameterSpec object to hold the hyperparameter tuning configuration for your training job, and add the HyperparameterSpec as the hyperparameters object in your TrainingInput object.In your HyperparameterSpec, set the hyperparameterMetricTag to a value representing your chosen metric. If you don't specify a hyperparameterMetricTag, AI Platform Training looks for a metric with the name training/hptuning/metric. The following example shows how to create a configuration for a metric named metric1: Exercise.Complete the TODOs below. - Specify the hypertuning cofiguration for the learning rate, the batch size and the number of buckets using one of the available [hyperparameter types](https://cloud.google.com/ai-platform/training/docs/hyperparameter-tuning-overviewhyperparameter_types). - Specify the hyperparameter tuning metric tag - Set the maximum number of parallel trial and the max number of trials ###Code %%writefile hptuning_config.yaml trainingInput: scaleTier: BASIC hyperparameters: goal: MINIMIZE maxTrials: # TODO: Your code goes here maxParallelTrials: # TODO: Your code goes here hyperparameterMetricTag: # TODO: Your code goes here enableTrialEarlyStopping: True params: - parameterName: lr # TODO: Your code goes here - parameterName: nbuckets # TODO: Your code goes here - parameterName: batch_size # TODO: Your code goes here ###Output _____no_output_____ ###Markdown Report your hyperparameter metric to AI Platform TrainingThe way to report your hyperparameter metric to the AI Platform Training service depends on whether you are using TensorFlow for training or not. It also depends on whether you are using a runtime version or a custom container for training.We recommend that your training code reports your hyperparameter metric to AI Platform Training frequently in order to take advantage of early stopping.TensorFlow with a runtime versionIf you use an AI Platform Training runtime version and train with TensorFlow, then you can report your hyperparameter metric to AI Platform Training by writing the metric to a TensorFlow summary. ###Code %%bash # Output directory and jobID OUTDIR=gs://${BUCKET}/taxifare/trained_model_$(date -u +%y%m%d_%H%M%S) JOBID=taxifare_$(date -u +%y%m%d_%H%M%S) echo ${OUTDIR} ${REGION} ${JOBID} gsutil -m rm -rf ${OUTDIR} # Model and training hyperparameters BATCH_SIZE=15 NUM_EXAMPLES_TO_TRAIN_ON=100 NUM_EVALS=10 NBUCKETS=10 LR=0.001 NNSIZE="32 8" # GCS paths GCS_PROJECT_PATH=gs://$BUCKET/taxifare DATA_PATH=$GCS_PROJECT_PATH/data TRAIN_DATA_PATH=$DATA_PATH/taxi-train* EVAL_DATA_PATH=$DATA_PATH/taxi-valid* # TODO gcloud ai-platform jobs submit training $JOBID \ # TODO: Your code goes here -- \ --eval_data_path $EVAL_DATA_PATH \ --output_dir $OUTDIR \ --train_data_path $TRAIN_DATA_PATH \ --batch_size $BATCH_SIZE \ --num_examples_to_train_on $NUM_EXAMPLES_TO_TRAIN_ON \ --num_evals $NUM_EVALS \ --nbuckets $NBUCKETS \ --lr $LR \ --nnsize $NNSIZE ###Output _____no_output_____ ###Markdown Hyper-parameter tuning**Learning Objectives**1. Learn how to use `cloudml-hypertune` to report the results for Cloud hyperparameter tuning trial runs2. Learn how to configure the `.yaml` file for submitting a Cloud hyperparameter tuning job3. Submit a hyperparameter tuning job to Cloud AI Platform IntroductionLet's see if we can improve upon that by tuning our hyperparameters.Hyperparameters are parameters that are set *prior* to training a model, as opposed to parameters which are learned *during* training. These include learning rate and batch size, but also model design parameters such as type of activation function and number of hidden units.Here are the four most common ways to finding the ideal hyperparameters:1. Manual2. Grid Search3. Random Search4. Bayesian Optimzation**1. Manual**Traditionally, hyperparameter tuning is a manual trial and error process. A data scientist has some intution about suitable hyperparameters which they use as a starting point, then they observe the result and use that information to try a new set of hyperparameters to try to beat the existing performance. Pros- Educational, builds up your intuition as a data scientist- Inexpensive because only one trial is conducted at a timeCons- Requires alot of time and patience**2. Grid Search**On the other extreme we can use grid search. Define a discrete set of values to try for each hyperparameter then try every possible combination. Pros- Can run hundreds of trials in parallel using the cloud- Gauranteed to find the best solution within the search spaceCons- Expensive**3. Random Search**Alternatively define a range for each hyperparamter (e.g. 0-256) and sample uniformly at random from that range. Pros- Can run hundreds of trials in parallel using the cloud- Requires less trials than Grid Search to find a good solutionCons- Expensive (but less so than Grid Search)**4. Bayesian Optimization**Unlike Grid Search and Random Search, Bayesian Optimization takes into account information from past trials to select parameters for future trials. The details of how this is done is beyond the scope of this notebook, but if you're interested you can read how it works here [here](https://cloud.google.com/blog/products/gcp/hyperparameter-tuning-cloud-machine-learning-engine-using-bayesian-optimization). Pros- Picks values intelligenty based on results from past trials- Less expensive because requires fewer trials to get a good resultCons- Requires sequential trials for best results, takes longer**AI Platform HyperTune**AI Platform HyperTune, powered by [Google Vizier](https://ai.google/research/pubs/pub46180), uses Bayesian Optimization by default, but [also supports](https://cloud.google.com/ml-engine/docs/tensorflow/hyperparameter-tuning-overviewsearch_algorithms) Grid Search and Random Search. When tuning just a few hyperparameters (say less than 4), Grid Search and Random Search work well, but when tunining several hyperparameters and the search space is large Bayesian Optimization is best. ###Code BUCKET = "qwiklabs-gcp-04-8722038efd75" PROJECT = "qwiklabs-gcp-04-8722038efd75" REGION = "us-west1" TFVERSION = "2.1" # TF version for AI Platform to use import os os.environ["PROJECT"] = PROJECT os.environ["BUCKET"] = BUCKET os.environ["REGION"] = REGION os.environ["TFVERSION"] = TFVERSION ###Output _____no_output_____ ###Markdown Make code compatible with AI Platform Training ServiceIn order to make our code compatible with AI Platform Training Service we need to make the following changes:1. Upload data to Google Cloud Storage 2. Move code into a trainer Python package4. Submit training job with `gcloud` to train on AI Platform Upload data to Google Cloud Storage (GCS)Cloud services don't have access to our local files, so we need to upload them to a location the Cloud servers can read from. In this case we'll use GCS.To do this run the notebook [0_export_data_from_bq_to_gcs.ipynb](./0_export_data_from_bq_to_gcs.ipynb), which will export the taxifare data from BigQuery directly into a GCS bucket. If all ran smoothly, you should be able to list the data bucket by running the following command: ###Code !gsutil ls gs://$BUCKET/taxifare/data ###Output gs://qwiklabs-gcp-04-8722038efd75/taxifare/data/taxi-train-000000000000.csv gs://qwiklabs-gcp-04-8722038efd75/taxifare/data/taxi-valid-000000000000.csv ###Markdown Move code into python packageIn the [previous lab](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/building_production_ml_systems/labs/1_training_at_scale.ipynb), we moved our code into a python package for training on Cloud AI Platform. Let's just check that the files are there. You should see the following files in the `taxifare/trainer` directory: - `__init__.py` - `model.py` - `task.py` ###Code !ls -la taxifare/trainer ###Output total 24 drwxr-xr-x 3 jupyter jupyter 4096 Dec 4 17:11 . drwxr-xr-x 4 jupyter jupyter 4096 Dec 7 14:31 .. -rw-r--r-- 1 jupyter jupyter 0 Nov 29 03:14 __init__.py drwxr-xr-x 2 jupyter jupyter 4096 Dec 7 13:29 __pycache__ -rw-r--r-- 1 jupyter jupyter 7887 Dec 7 15:36 model.py -rw-r--r-- 1 jupyter jupyter 2026 Dec 7 15:36 task.py ###Markdown To use hyperparameter tuning in your training job you must perform the following steps: 1. Specify the hyperparameter tuning configuration for your training job by including a HyperparameterSpec in your TrainingInput object. 2. Include the following code in your training application: - Parse the command-line arguments representing the hyperparameters you want to tune, and use the values to set the hyperparameters for your training trial.Add your hyperparameter metric to the summary for your graph. - To submit a hyperparameter tuning job, we must modify `model.py` and `task.py` to expose any variables we want to tune as command line arguments. Modify model.py Exercise.Complete the TODOs in the `train_and_evaluate` functin below. - Define the hyperparameter tuning metric `hp_metric` - Set up cloudml-hypertune to report the results of each trial by calling its helper function, `report_hyperparameter_tuning_metric` ###Code %%writefile ./taxifare/trainer/model.py import datetime import hypertune import logging import os import shutil import numpy as np import tensorflow as tf from tensorflow.keras import activations from tensorflow.keras import callbacks from tensorflow.keras import layers from tensorflow.keras import models from tensorflow import feature_column as fc logging.info(tf.version.VERSION) CSV_COLUMNS = [ 'fare_amount', 'pickup_datetime', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count', 'key', ] LABEL_COLUMN = 'fare_amount' DEFAULTS = [[0.0], ['na'], [0.0], [0.0], [0.0], [0.0], [0.0], ['na']] DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] def features_and_labels(row_data): for unwanted_col in ['key']: row_data.pop(unwanted_col) label = row_data.pop(LABEL_COLUMN) return row_data, label def load_dataset(pattern, batch_size, num_repeat): dataset = tf.data.experimental.make_csv_dataset( file_pattern=pattern, batch_size=batch_size, column_names=CSV_COLUMNS, column_defaults=DEFAULTS, num_epochs=num_repeat, ) return dataset.map(features_and_labels) def create_train_dataset(pattern, batch_size): dataset = load_dataset(pattern, batch_size, num_repeat=None) return dataset.prefetch(1) def create_eval_dataset(pattern, batch_size): dataset = load_dataset(pattern, batch_size, num_repeat=1) return dataset.prefetch(1) def parse_datetime(s): if type(s) is not str: s = s.numpy().decode('utf-8') return datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S %Z") def euclidean(params): lon1, lat1, lon2, lat2 = params londiff = lon2 - lon1 latdiff = lat2 - lat1 return tf.sqrt(londiff*londiff + latdiff*latdiff) def get_dayofweek(s): ts = parse_datetime(s) return DAYS[ts.weekday()] @tf.function def dayofweek(ts_in): return tf.map_fn( lambda s: tf.py_function(get_dayofweek, inp=[s], Tout=tf.string), ts_in ) @tf.function def fare_thresh(x): return 60 * activations.relu(x) def transform(inputs, NUMERIC_COLS, STRING_COLS, nbuckets): # Pass-through columns transformed = inputs.copy() del transformed['pickup_datetime'] feature_columns = { colname: fc.numeric_column(colname) for colname in NUMERIC_COLS } # Scaling longitude from range [-70, -78] to [0, 1] for lon_col in ['pickup_longitude', 'dropoff_longitude']: transformed[lon_col] = layers.Lambda( lambda x: (x + 78)/8.0, name='scale_{}'.format(lon_col) )(inputs[lon_col]) # Scaling latitude from range [37, 45] to [0, 1] for lat_col in ['pickup_latitude', 'dropoff_latitude']: transformed[lat_col] = layers.Lambda( lambda x: (x - 37)/8.0, name='scale_{}'.format(lat_col) )(inputs[lat_col]) # Adding Euclidean dist (no need to be accurate: NN will calibrate it) transformed['euclidean'] = layers.Lambda(euclidean, name='euclidean')([ inputs['pickup_longitude'], inputs['pickup_latitude'], inputs['dropoff_longitude'], inputs['dropoff_latitude'] ]) feature_columns['euclidean'] = fc.numeric_column('euclidean') # hour of day from timestamp of form '2010-02-08 09:17:00+00:00' transformed['hourofday'] = layers.Lambda( lambda x: tf.strings.to_number( tf.strings.substr(x, 11, 2), out_type=tf.dtypes.int32), name='hourofday' )(inputs['pickup_datetime']) feature_columns['hourofday'] = fc.indicator_column( fc.categorical_column_with_identity( 'hourofday', num_buckets=24)) latbuckets = np.linspace(0, 1, nbuckets).tolist() lonbuckets = np.linspace(0, 1, nbuckets).tolist() b_plat = fc.bucketized_column( feature_columns['pickup_latitude'], latbuckets) b_dlat = fc.bucketized_column( feature_columns['dropoff_latitude'], latbuckets) b_plon = fc.bucketized_column( feature_columns['pickup_longitude'], lonbuckets) b_dlon = fc.bucketized_column( feature_columns['dropoff_longitude'], lonbuckets) ploc = fc.crossed_column( [b_plat, b_plon], nbuckets * nbuckets) dloc = fc.crossed_column( [b_dlat, b_dlon], nbuckets * nbuckets) pd_pair = fc.crossed_column([ploc, dloc], nbuckets ** 4) feature_columns['pickup_and_dropoff'] = fc.embedding_column( pd_pair, 100) return transformed, feature_columns def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) def build_dnn_model(nbuckets, nnsize, lr): # input layer is all float except for pickup_datetime which is a string STRING_COLS = ['pickup_datetime'] NUMERIC_COLS = ( set(CSV_COLUMNS) - set([LABEL_COLUMN, 'key']) - set(STRING_COLS) ) inputs = { colname: layers.Input(name=colname, shape=(), dtype='float32') for colname in NUMERIC_COLS } inputs.update({ colname: layers.Input(name=colname, shape=(), dtype='string') for colname in STRING_COLS }) # transforms transformed, feature_columns = transform( inputs, NUMERIC_COLS, STRING_COLS, nbuckets=nbuckets) dnn_inputs = layers.DenseFeatures(feature_columns.values())(transformed) x = dnn_inputs for layer, nodes in enumerate(nnsize): x = layers.Dense(nodes, activation='relu', name='h{}'.format(layer))(x) output = layers.Dense(1, name='fare')(x) model = models.Model(inputs, output) lr_optimizer = tf.keras.optimizers.Adam(learning_rate=lr) model.compile(optimizer=lr_optimizer, loss='mse', metrics=[rmse, 'mse']) return model def train_and_evaluate(hparams): batch_size = hparams['batch_size'] eval_data_path = hparams['eval_data_path'] nnsize = hparams['nnsize'] nbuckets = hparams['nbuckets'] lr = hparams['lr'] num_evals = hparams['num_evals'] num_examples_to_train_on = hparams['num_examples_to_train_on'] output_dir = hparams['output_dir'] train_data_path = hparams['train_data_path'] if tf.io.gfile.exists(output_dir): tf.io.gfile.rmtree(output_dir) timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S') savedmodel_dir = os.path.join(output_dir, 'savedmodel') model_export_path = os.path.join(savedmodel_dir, timestamp) checkpoint_path = os.path.join(output_dir, 'checkpoints') tensorboard_path = os.path.join(output_dir, 'tensorboard') dnn_model = build_dnn_model(nbuckets, nnsize, lr) logging.info(dnn_model.summary()) trainds = create_train_dataset(train_data_path, batch_size) evalds = create_eval_dataset(eval_data_path, batch_size) steps_per_epoch = num_examples_to_train_on // (batch_size * num_evals) checkpoint_cb = callbacks.ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1) tensorboard_cb = callbacks.TensorBoard(tensorboard_path, histogram_freq=1) history = dnn_model.fit( trainds, validation_data=evalds, epochs=num_evals, steps_per_epoch=max(1, steps_per_epoch), verbose=2, # 0=silent, 1=progress bar, 2=one line per epoch callbacks=[checkpoint_cb, tensorboard_cb] ) # Exporting the model with default serving function. tf.saved_model.save(dnn_model, model_export_path) # TODO 1 hp_metric = history.history['val_rmse'][num_evals-1] # TODO 1 hpt = hypertune.HyperTune() hpt.report_hyperparameter_tuning_metric( hyperparameter_metric_tag='rmse', metric_value=hp_metric, global_step=num_evals ) return history ###Output Overwriting ./taxifare/trainer/model.py ###Markdown Modify task.py ###Code %%writefile taxifare/trainer/task.py import argparse import json import os from trainer import model if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( "--batch_size", help = "Batch size for training steps", type = int, default = 32 ) parser.add_argument( "--eval_data_path", help = "GCS location pattern of eval files", required = True ) parser.add_argument( "--nnsize", help = "Hidden layer sizes (provide space-separated sizes)", nargs = "+", type = int, default=[32, 8] ) parser.add_argument( "--nbuckets", help = "Number of buckets to divide lat and lon with", type = int, default = 10 ) parser.add_argument( "--lr", help = "learning rate for optimizer", type = float, default = 0.001 ) parser.add_argument( "--num_evals", help = "Number of times to evaluate model on eval data training.", type = int, default = 5 ) parser.add_argument( "--num_examples_to_train_on", help = "Number of examples to train on.", type = int, default = 100 ) parser.add_argument( "--output_dir", help = "GCS location to write checkpoints and export models", required = True ) parser.add_argument( "--train_data_path", help = "GCS location pattern of train files containing eval URLs", required = True ) parser.add_argument( "--job-dir", help = "this model ignores this field, but it is required by gcloud", default = "junk" ) args, _ = parser.parse_known_args() hparams = args.__dict__ hparams["output_dir"] = os.path.join( hparams["output_dir"], json.loads( os.environ.get("TF_CONFIG", "{}") ).get("task", {}).get("trial", "") ) print("output_dir", hparams["output_dir"]) model.train_and_evaluate(hparams) ###Output Overwriting taxifare/trainer/task.py ###Markdown Create config.yaml fileSpecify the hyperparameter tuning configuration for your training jobCreate a HyperparameterSpec object to hold the hyperparameter tuning configuration for your training job, and add the HyperparameterSpec as the hyperparameters object in your TrainingInput object.In your HyperparameterSpec, set the hyperparameterMetricTag to a value representing your chosen metric. If you don't specify a hyperparameterMetricTag, AI Platform Training looks for a metric with the name training/hptuning/metric. The following example shows how to create a configuration for a metric named metric1: Exercise.Complete the TODOs below. - Specify the hypertuning cofiguration for the learning rate, the batch size and the number of buckets using one of the available [hyperparameter types](https://cloud.google.com/ai-platform/training/docs/hyperparameter-tuning-overviewhyperparameter_types). - Specify the hyperparameter tuning metric tag - Set the maximum number of parallel trial and the max number of trials ###Code %%writefile hptuning_config.yaml trainingInput: scaleTier: BASIC hyperparameters: goal: MINIMIZE maxTrials: 10 maxParallelTrials: 2 hyperparameterMetricTag: rmse enableTrialEarlyStopping: True params: - parameterName: lr type: DOUBLE minValue: 0.0001 maxValue: 0.1 scaleType: UNIT_LOG_SCALE - parameterName: nbuckets type: INTEGER minValue: 10 maxValue: 25 scaleType: UNIT_LINEAR_SCALE - parameterName: batch_size type: DISCRETE discreteValues: - 15 - 30 - 50 ###Output Overwriting hptuning_config.yaml ###Markdown Report your hyperparameter metric to AI Platform TrainingThe way to report your hyperparameter metric to the AI Platform Training service depends on whether you are using TensorFlow for training or not. It also depends on whether you are using a runtime version or a custom container for training.We recommend that your training code reports your hyperparameter metric to AI Platform Training frequently in order to take advantage of early stopping.TensorFlow with a runtime versionIf you use an AI Platform Training runtime version and train with TensorFlow, then you can report your hyperparameter metric to AI Platform Training by writing the metric to a TensorFlow summary. Use one of the following functions. ###Code %%bash # Output directory and jobID OUTDIR=gs://${BUCKET}/taxifare/trained_model_$(date -u +%y%m%d_%H%M%S) JOBID=taxifare_$(date -u +%y%m%d_%H%M%S) echo ${OUTDIR} ${REGION} ${JOBID} gsutil -m rm -rf ${OUTDIR} # Model and training hyperparameters BATCH_SIZE=15 NUM_EXAMPLES_TO_TRAIN_ON=100 NUM_EVALS=10 NBUCKETS=10 LR=0.001 NNSIZE="32 8" # GCS paths GCS_PROJECT_PATH=gs://$BUCKET/taxifare DATA_PATH=$GCS_PROJECT_PATH/data TRAIN_DATA_PATH=$DATA_PATH/taxi-train* EVAL_DATA_PATH=$DATA_PATH/taxi-valid* # TODO gcloud ai-platform jobs submit training $JOBID \ --module-name=trainer.task \ --package-path=taxifare/trainer \ --staging-bucket=gs://${BUCKET} \ --config=hptuning_config.yaml \ --python-version=3.7 \ --runtime-version=${TFVERSION} \ --region=${REGION} \ -- \ --eval_data_path $EVAL_DATA_PATH \ --output_dir $OUTDIR \ --train_data_path $TRAIN_DATA_PATH \ --batch_size $BATCH_SIZE \ --num_examples_to_train_on $NUM_EXAMPLES_TO_TRAIN_ON \ --num_evals $NUM_EVALS \ --nbuckets $NBUCKETS \ --lr $LR \ --nnsize $NNSIZE ###Output gs://qwiklabs-gcp-04-8722038efd75/taxifare/trained_model_201207_154503 us-west1 taxifare_201207_154503 jobId: taxifare_201207_154503 state: QUEUED ###Markdown Hyperparameter tuning**Learning Objectives**1. Learn how to use `cloudml-hypertune` to report the results for Cloud hyperparameter tuning trial runs2. Learn how to configure the `.yaml` file for submitting a Cloud hyperparameter tuning job3. Submit a hyperparameter tuning job to Cloud AI Platform IntroductionLet's see if we can improve upon that by tuning our hyperparameters.Hyperparameters are parameters that are set *prior* to training a model, as opposed to parameters which are learned *during* training. These include learning rate and batch size, but also model design parameters such as type of activation function and number of hidden units.Here are the four most common ways to finding the ideal hyperparameters:1. Manual2. Grid Search3. Random Search4. Bayesian Optimzation**1. Manual**Traditionally, hyperparameter tuning is a manual trial and error process. A data scientist has some intution about suitable hyperparameters which they use as a starting point, then they observe the result and use that information to try a new set of hyperparameters to try to beat the existing performance. Pros- Educational, builds up your intuition as a data scientist- Inexpensive because only one trial is conducted at a timeCons- Requires alot of time and patience**2. Grid Search**On the other extreme we can use grid search. Define a discrete set of values to try for each hyperparameter then try every possible combination. Pros- Can run hundreds of trials in parallel using the cloud- Gauranteed to find the best solution within the search spaceCons- Expensive**3. Random Search**Alternatively define a range for each hyperparamter (e.g. 0-256) and sample uniformly at random from that range. Pros- Can run hundreds of trials in parallel using the cloud- Requires less trials than Grid Search to find a good solutionCons- Expensive (but less so than Grid Search)**4. Bayesian Optimization**Unlike Grid Search and Random Search, Bayesian Optimization takes into account information from past trials to select parameters for future trials. The details of how this is done is beyond the scope of this notebook, but if you're interested you can read how it works here [here](https://cloud.google.com/blog/products/gcp/hyperparameter-tuning-cloud-machine-learning-engine-using-bayesian-optimization). Pros- Picks values intelligenty based on results from past trials- Less expensive because requires fewer trials to get a good resultCons- Requires sequential trials for best results, takes longer**AI Platform HyperTune**AI Platform HyperTune, powered by [Google Vizier](https://ai.google/research/pubs/pub46180), uses Bayesian Optimization by default, but [also supports](https://cloud.google.com/ml-engine/docs/tensorflow/hyperparameter-tuning-overviewsearch_algorithms) Grid Search and Random Search. When tuning just a few hyperparameters (say less than 4), Grid Search and Random Search work well, but when tunining several hyperparameters and the search space is large Bayesian Optimization is best. ###Code # Change below if necessary PROJECT = !gcloud config get-value project # noqa: E999 PROJECT = PROJECT[0] BUCKET = PROJECT REGION = "us-central1" %env PROJECT=$PROJECT %env BUCKET=$BUCKET %env REGION=$REGION %env TFVERSION=2.5 %%bash gcloud config set project $PROJECT gcloud config set ai_platform/region $REGION ###Output _____no_output_____ ###Markdown Make code compatible with AI Platform Training ServiceIn order to make our code compatible with AI Platform Training Service we need to make the following changes:1. Upload data to Google Cloud Storage 2. Move code into a trainer Python package4. Submit training job with `gcloud` to train on AI Platform Upload data to Google Cloud Storage (GCS)Cloud services don't have access to our local files, so we need to upload them to a location the Cloud servers can read from. In this case we'll use GCS.To do this run the notebook [0_export_data_from_bq_to_gcs.ipynb](./0_export_data_from_bq_to_gcs.ipynb), which will export the taxifare data from BigQuery directly into a GCS bucket. If all ran smoothly, you should be able to list the data bucket by running the following command: ###Code !gsutil ls gs://$BUCKET/taxifare/data ###Output _____no_output_____ ###Markdown Move code into python packageIn the [previous lab](./1_training_at_scale.ipynb), we moved our code into a python package for training on Cloud AI Platform. Let's just check that the files are there. You should see the following files in the `taxifare/trainer` directory: - `__init__.py` - `model.py` - `task.py` ###Code !ls -la taxifare/trainer ###Output _____no_output_____ ###Markdown To use hyperparameter tuning in your training job you must perform the following steps: 1. Specify the hyperparameter tuning configuration for your training job by including a HyperparameterSpec in your TrainingInput object. 2. Include the following code in your training application: - Parse the command-line arguments representing the hyperparameters you want to tune, and use the values to set the hyperparameters for your training trial.Add your hyperparameter metric to the summary for your graph. - To submit a hyperparameter tuning job, we must modify `model.py` and `task.py` to expose any variables we want to tune as command line arguments. Modify model.py Exercise.Complete the TODOs in the `train_and_evaluate` functin below. - Define the hyperparameter tuning metric `hp_metric` - Set up cloudml-hypertune to report the results of each trial by calling its helper function, `report_hyperparameter_tuning_metric` ###Code %%writefile ./taxifare/trainer/model.py """Data prep, train and evaluate DNN model.""" import datetime import logging import os import hypertune import numpy as np import tensorflow as tf from tensorflow import feature_column as fc from tensorflow.keras import activations, callbacks, layers, models logging.info(tf.version.VERSION) CSV_COLUMNS = [ "fare_amount", "pickup_datetime", "pickup_longitude", "pickup_latitude", "dropoff_longitude", "dropoff_latitude", "passenger_count", "key", ] # inputs are all float except for pickup_datetime which is a string STRING_COLS = ["pickup_datetime"] LABEL_COLUMN = "fare_amount" DEFAULTS = [[0.0], ["na"], [0.0], [0.0], [0.0], [0.0], [0.0], ["na"]] DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] def features_and_labels(row_data): for unwanted_col in ["key"]: row_data.pop(unwanted_col) label = row_data.pop(LABEL_COLUMN) return row_data, label def load_dataset(pattern, batch_size, num_repeat): dataset = tf.data.experimental.make_csv_dataset( file_pattern=pattern, batch_size=batch_size, column_names=CSV_COLUMNS, column_defaults=DEFAULTS, num_epochs=num_repeat, shuffle_buffer_size=1000000, ) return dataset.map(features_and_labels) def create_train_dataset(pattern, batch_size): dataset = load_dataset(pattern, batch_size, num_repeat=None) return dataset.prefetch(1) def create_eval_dataset(pattern, batch_size): dataset = load_dataset(pattern, batch_size, num_repeat=1) return dataset.prefetch(1) def parse_datetime(s): if not isinstance(s, str): s = s.numpy().decode("utf-8") return datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S %Z") def euclidean(params): lon1, lat1, lon2, lat2 = params londiff = lon2 - lon1 latdiff = lat2 - lat1 return tf.sqrt(londiff * londiff + latdiff * latdiff) def get_dayofweek(s): ts = parse_datetime(s) return DAYS[ts.weekday()] @tf.function def dayofweek(ts_in): return tf.map_fn( lambda s: tf.py_function(get_dayofweek, inp=[s], Tout=tf.string), ts_in ) @tf.function def fare_thresh(x): return 60 * activations.relu(x) def transform(inputs, numeric_cols, nbuckets): # Pass-through columns transformed = inputs.copy() del transformed["pickup_datetime"] feature_columns = { colname: fc.numeric_column(colname) for colname in numeric_cols } # Scaling longitude from range [-70, -78] to [0, 1] for lon_col in ["pickup_longitude", "dropoff_longitude"]: transformed[lon_col] = layers.Lambda( lambda x: (x + 78) / 8.0, name=f"scale_{lon_col}" )(inputs[lon_col]) # Scaling latitude from range [37, 45] to [0, 1] for lat_col in ["pickup_latitude", "dropoff_latitude"]: transformed[lat_col] = layers.Lambda( lambda x: (x - 37) / 8.0, name=f"scale_{lat_col}" )(inputs[lat_col]) # Adding Euclidean dist (no need to be accurate: NN will calibrate it) transformed["euclidean"] = layers.Lambda(euclidean, name="euclidean")( [ inputs["pickup_longitude"], inputs["pickup_latitude"], inputs["dropoff_longitude"], inputs["dropoff_latitude"], ] ) feature_columns["euclidean"] = fc.numeric_column("euclidean") # hour of day from timestamp of form '2010-02-08 09:17:00+00:00' transformed["hourofday"] = layers.Lambda( lambda x: tf.strings.to_number( tf.strings.substr(x, 11, 2), out_type=tf.dtypes.int32 ), name="hourofday", )(inputs["pickup_datetime"]) feature_columns["hourofday"] = fc.indicator_column( fc.categorical_column_with_identity("hourofday", num_buckets=24) ) latbuckets = np.linspace(0, 1, nbuckets).tolist() lonbuckets = np.linspace(0, 1, nbuckets).tolist() b_plat = fc.bucketized_column( feature_columns["pickup_latitude"], latbuckets ) b_dlat = fc.bucketized_column( feature_columns["dropoff_latitude"], latbuckets ) b_plon = fc.bucketized_column( feature_columns["pickup_longitude"], lonbuckets ) b_dlon = fc.bucketized_column( feature_columns["dropoff_longitude"], lonbuckets ) ploc = fc.crossed_column([b_plat, b_plon], nbuckets * nbuckets) dloc = fc.crossed_column([b_dlat, b_dlon], nbuckets * nbuckets) pd_pair = fc.crossed_column([ploc, dloc], nbuckets ** 4) feature_columns["pickup_and_dropoff"] = fc.embedding_column(pd_pair, 100) return transformed, feature_columns def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) def build_dnn_model(nbuckets, nnsize, lr, string_cols): numeric_cols = set(CSV_COLUMNS) - {LABEL_COLUMN, "key"} - set(string_cols) inputs = { colname: layers.Input(name=colname, shape=(), dtype="float32") for colname in numeric_cols } inputs.update( { colname: layers.Input(name=colname, shape=(), dtype="string") for colname in string_cols } ) # transforms transformed, feature_columns = transform(inputs, numeric_cols, nbuckets) dnn_inputs = layers.DenseFeatures(feature_columns.values())(transformed) x = dnn_inputs for layer, nodes in enumerate(nnsize): x = layers.Dense(nodes, activation="relu", name=f"h{layer}")(x) output = layers.Dense(1, name="fare")(x) model = models.Model(inputs, output) lr_optimizer = tf.keras.optimizers.Adam(learning_rate=lr) model.compile(optimizer=lr_optimizer, loss="mse", metrics=[rmse, "mse"]) return model def train_and_evaluate(hparams): batch_size = hparams["batch_size"] nbuckets = hparams["nbuckets"] lr = hparams["lr"] nnsize = hparams["nnsize"] eval_data_path = hparams["eval_data_path"] num_evals = hparams["num_evals"] num_examples_to_train_on = hparams["num_examples_to_train_on"] output_dir = hparams["output_dir"] train_data_path = hparams["train_data_path"] timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") savedmodel_dir = os.path.join(output_dir, "savedmodel") model_export_path = os.path.join(savedmodel_dir, timestamp) checkpoint_path = os.path.join(output_dir, "checkpoints") tensorboard_path = os.path.join(output_dir, "tensorboard") if tf.io.gfile.exists(output_dir): tf.io.gfile.rmtree(output_dir) model = build_dnn_model(nbuckets, nnsize, lr, STRING_COLS) logging.info(model.summary()) trainds = create_train_dataset(train_data_path, batch_size) evalds = create_eval_dataset(eval_data_path, batch_size) steps_per_epoch = num_examples_to_train_on // (batch_size * num_evals) checkpoint_cb = callbacks.ModelCheckpoint( checkpoint_path, save_weights_only=True, verbose=1 ) tensorboard_cb = callbacks.TensorBoard(tensorboard_path, histogram_freq=1) history = model.fit( trainds, validation_data=evalds, epochs=num_evals, steps_per_epoch=max(1, steps_per_epoch), verbose=2, # 0=silent, 1=progress bar, 2=one line per epoch callbacks=[checkpoint_cb, tensorboard_cb], ) # Exporting the model with default serving function. model.save(model_export_path) # TODO 1 hp_metric = # TODO: Your code goes here # TODO 1 hpt = # TODO: Your code goes here # TODO: Your code goes here return history ###Output _____no_output_____ ###Markdown Modify task.py ###Code %%writefile taxifare/trainer/task.py """Argument definitions for model training code in `trainer.model`.""" import argparse import json import os from trainer import model if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--batch_size", help="Batch size for training steps", type=int, default=32, ) parser.add_argument( "--eval_data_path", help="GCS location pattern of eval files", required=True, ) parser.add_argument( "--nnsize", help="Hidden layer sizes (provide space-separated sizes)", nargs="+", type=int, default=[32, 8], ) parser.add_argument( "--nbuckets", help="Number of buckets to divide lat and lon with", type=int, default=10, ) parser.add_argument( "--lr", help="learning rate for optimizer", type=float, default=0.001 ) parser.add_argument( "--num_evals", help="Number of times to evaluate model on eval data training.", type=int, default=5, ) parser.add_argument( "--num_examples_to_train_on", help="Number of examples to train on.", type=int, default=100, ) parser.add_argument( "--output_dir", help="GCS location to write checkpoints and export models", required=True, ) parser.add_argument( "--train_data_path", help="GCS location pattern of train files containing eval URLs", required=True, ) parser.add_argument( "--job-dir", help="this model ignores this field, but it is required by gcloud", default="junk", ) args, _ = parser.parse_known_args() hparams = args.__dict__ hparams["output_dir"] = os.path.join( hparams["output_dir"], json.loads(os.environ.get("TF_CONFIG", "{}")) .get("task", {}) .get("trial", ""), ) print("output_dir", hparams["output_dir"]) model.train_and_evaluate(hparams) ###Output _____no_output_____ ###Markdown Create config.yaml fileSpecify the hyperparameter tuning configuration for your training jobCreate a HyperparameterSpec object to hold the hyperparameter tuning configuration for your training job, and add the HyperparameterSpec as the hyperparameters object in your TrainingInput object.In your HyperparameterSpec, set the hyperparameterMetricTag to a value representing your chosen metric. If you don't specify a hyperparameterMetricTag, AI Platform Training looks for a metric with the name training/hptuning/metric. The following example shows how to create a configuration for a metric named metric1: Exercise.Complete the TODOs below. - Specify the hypertuning cofiguration for the learning rate, the batch size and the number of buckets using one of the available [hyperparameter types](https://cloud.google.com/ai-platform/training/docs/hyperparameter-tuning-overviewhyperparameter_types). - Specify the hyperparameter tuning metric tag - Set the maximum number of parallel trial and the max number of trials ###Code %%writefile hptuning_config.yaml trainingInput: scaleTier: BASIC hyperparameters: goal: MINIMIZE maxTrials: # TODO: Your code goes here maxParallelTrials: # TODO: Your code goes here hyperparameterMetricTag: # TODO: Your code goes here enableTrialEarlyStopping: True params: - parameterName: lr # TODO: Your code goes here - parameterName: nbuckets # TODO: Your code goes here - parameterName: batch_size # TODO: Your code goes here ###Output _____no_output_____ ###Markdown Report your hyperparameter metric to AI Platform TrainingThe way to report your hyperparameter metric to the AI Platform Training service depends on whether you are using TensorFlow for training or not. It also depends on whether you are using a runtime version or a custom container for training.We recommend that your training code reports your hyperparameter metric to AI Platform Training frequently in order to take advantage of early stopping.TensorFlow with a runtime versionIf you use an AI Platform Training runtime version and train with TensorFlow, then you can report your hyperparameter metric to AI Platform Training by writing the metric to a TensorFlow summary. ###Code %%bash # Output directory and jobID OUTDIR=gs://${BUCKET}/taxifare/trained_model_$(date -u +%y%m%d_%H%M%S) JOBID=taxifare_$(date -u +%y%m%d_%H%M%S) echo ${OUTDIR} ${REGION} ${JOBID} gsutil -m rm -rf ${OUTDIR} # Model and training hyperparameters BATCH_SIZE=15 NUM_EXAMPLES_TO_TRAIN_ON=100 NUM_EVALS=10 NBUCKETS=10 LR=0.001 NNSIZE="32 8" # GCS paths GCS_PROJECT_PATH=gs://$BUCKET/taxifare DATA_PATH=$GCS_PROJECT_PATH/data TRAIN_DATA_PATH=$DATA_PATH/taxi-train* EVAL_DATA_PATH=$DATA_PATH/taxi-valid* # TODO gcloud ai-platform jobs submit training $JOBID \ # TODO: Your code goes here -- \ --eval_data_path $EVAL_DATA_PATH \ --output_dir $OUTDIR \ --train_data_path $TRAIN_DATA_PATH \ --batch_size $BATCH_SIZE \ --num_examples_to_train_on $NUM_EXAMPLES_TO_TRAIN_ON \ --num_evals $NUM_EVALS \ --nbuckets $NBUCKETS \ --lr $LR \ --nnsize $NNSIZE ###Output _____no_output_____
notebooks/03-visualize-cost-and-usage.ipynb
###Markdown Load and cleanup dataWe load user activity data and cloud cost data for the duration of the semesterinto pandas dataframes. We make sure our timezones are right, and that we fill inNaNs where we have missing data. ###Code semester_start = pd.Timestamp('2018-08-15').tz_localize('US/Pacific') semester_end = pd.Timestamp('2018-12-15').tz_localize('US/Pacific') # Log data for user activity path_usage = '../data/processed/fall-2018/user-activity.jsonl' datahub = pd.read_json(path_usage, lines=True) # Index by timestamp datahub = datahub.set_index('timestamp') # Our timestamps are in UTC datahub = datahub.tz_localize('UTC') # But we want them in US/Pacific, since that's how our billing data is setup datahub = datahub.tz_convert('US/Pacific') # Only between start and end of semester datahub = datahub[datahub.index > semester_start][datahub.index < semester_end] # Cost per day, in PST cost = pd.read_json('../data/processed/fall-2018/cloud-costs.jsonl', lines=True) cost = cost.set_index('start_time') cost = cost.drop(columns=['end_time']) # Pandas' read_json reads dates in as UTC, but since our *actual* dates for cloud costs are in PST, we convert back cost = cost.tz_localize('UTC') cost = cost.tz_convert('US/Pacific') # Only between start and end of semester cost = cost[cost.index > semester_start][cost.index < semester_end] # We only use indexing timestamps to make the tz_localize easier. # after that, we drop it to make everything else easier cost = cost.reset_index() # Fill in any missing data before beginning of date missing_dates = pd.date_range(semester_start, cost.start_time.min(), name='start_time') missing_dates_cost = pd.DataFrame(missing_dates, np.full(len(missing_dates), np.nan), columns={'start_time', 'cost'}) cost = cost.append(missing_dates_cost) ###Output _____no_output_____ ###Markdown MetricsWe munge our raw data into specific metrics we care about Daily Active userWe count someone as a 'daily active user' if they start / stop their notebook serverat least once. Due to anonimization techniques applied earlier, this might slightlyunder count users ###Code # Unique daily users - we count anyone who has logged in at least once a day # We want a dataframe with no index so we can use it easily with Altair daily_active_users = pd.DataFrame(datahub['user'].resample('D').nunique()).reset_index() alt.Chart(daily_active_users, width=900).mark_line().encode( x='timestamp', y='user' ) ###Output _____no_output_____ ###Markdown Daily cloud costs ###Code alt.Chart(cost, width=900).mark_line().encode( x='start_time', y=alt.Y('cost', axis=alt.Axis(format="$.0f", title="Cost per user")) ) ###Output _____no_output_____ ###Markdown Daily cloud costs per **active** userThis is cost per day for *active* users - those who used the cluster. This is only a fraction of your total users, so be careful using this for estimates. ###Code # Combine into a single dataframe based on day total = pd.merge(daily_active_users, cost, how='outer', left_on='timestamp', right_on='start_time').drop(columns=['start_time']) # Calculate daily cost per user total['cost_per_user'] = total['cost'] / total['user'] alt.Chart(total, width=900).mark_line().encode( x='timestamp', y=alt.Y('cost_per_user', axis=alt.Axis(format="$.2f", title="Cost per user")) ) ###Output _____no_output_____ ###Markdown 1. session length - general stats on how long sessions are. means,percentiles, etc.2. User 'profile' - how many 'kinds' of users do we have? Some whojust pop in once? Some who pop in a few times a week for a fixedamount of time? some who are there all the time? what kinda userclusters do we have?3. Who are those people using it 400 times in a semester?4. are there user corelations? Can we spot 'groups' of users withsimilar behavior? What kinda behavior is it? etc ###Code import pandas as pd import numpy as np from datetime import datetime import altair as alt from IPython import display # Set the altair theme def my_theme(*args, **kwargs): return {'config': {'axis': {'labelFontSize': 20, 'titleFontSize': 20}}} alt.themes.register('my-chart', my_theme) alt.themes.enable('my-chart') ###Output _____no_output_____ ###Markdown Params and functions ###Code semester_start = pd.Timestamp('2018-08-15').tz_localize('US/Pacific') semester_end = pd.Timestamp('2018-12-15').tz_localize('US/Pacific') def convert_tz(series): series = series.dt.tz_localize('UTC') return series.dt.tz_convert('US/Pacific') ###Output _____no_output_____ ###Markdown Load data User session data ###Code # Log data for user activity path_sessions = '../data/features/fall-2018/user-sessions.jsonl' sessions = pd.read_json(path_sessions, convert_dates=['start', 'stop']) for col in ['start', 'stop']: sessions[col] = convert_tz(sessions[col]) # Only between start and end of semester sessions = sessions[sessions['start'] > semester_start][sessions['start'] < semester_end] ###Output _____no_output_____ ###Markdown Cost per day ###Code cost = pd.read_json('../data/processed/fall-2018/cloud-costs.jsonl', lines=True) cost['start_time'] = convert_tz(cost['start_time']) cost = cost.drop(columns=['end_time']).set_index('start_time') # Only between start and end of semester cost = cost[cost.index > semester_start][cost.index < semester_end] # We only use indexing timestamps to make the tz_localize easier. # after that, we drop it to make everything else easier cost = cost.reset_index() # Fill in any missing data before beginning of date missing_dates = pd.date_range(semester_start, cost.start_time.min(), name='start_time') missing_dates_cost = pd.DataFrame(missing_dates, np.full(len(missing_dates), np.nan), columns={'start_time', 'cost'}) cost = cost.append(missing_dates_cost) ###Output /home/choldgraf/anaconda/envs/dev/lib/python3.6/site-packages/pandas/core/frame.py:6201: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version of pandas will change to not sort by default. To accept the future behavior, pass 'sort=True'. To retain the current behavior and silence the warning, pass sort=False sort=sort) ###Markdown Viz and analysis Daily Active userWe count someone as a 'daily active user' if they start / stop their notebook serverat least once. Due to anonimization techniques applied earlier, this might slightlyunder count users ###Code # Unique daily users - we count anyone who has logged in at least once a day # We want a dataframe with no index so we can use it easily with Altair daily_active_users = pd.DataFrame(sessions.set_index('start')['user'].resample('D').nunique()).reset_index() alt.Chart(daily_active_users, width=900).mark_line().encode( x='start', y='user' ) # Mean daily active users mean_daily_active_users = daily_active_users['user'].mean() display.HTML(f'<h3>Mean daily active users: <b>{mean_daily_active_users: .2f}</b></h3>') ###Output _____no_output_____ ###Markdown Daily cloud costs ###Code alt.Chart(cost, width=900).mark_line().encode( x='start_time', y=alt.Y('cost', axis=alt.Axis(format="$.2f")) ) # Mean daily active users mean_cost = cost['cost'].mean() display.HTML(f'<h3>Mean daily cloud cost: <b>${mean_cost: .2f}</b></h3>') ###Output _____no_output_____ ###Markdown Daily cloud costs per **active** userThis is cost per day for *active* users - those who used the cluster. This is only a fraction of your total users, so be careful using this for estimates. ###Code # Combine into a single dataframe based on day total = pd.merge(daily_active_users, cost, how='outer', left_on='start', right_on='start_time').drop(columns=['start_time']) # Calculate daily cost per user total['cost_per_active_user'] = total['cost'] / total['user'] alt.Chart(total, width=900).mark_line().encode( x='start', y=alt.Y('cost_per_active_user', axis=alt.Axis(format="$.2f"), title="Cost per active user") ) ###Output _____no_output_____ ###Markdown Total UsersOne way to count the 'number of users on the JupyterHub' is to look at everyone who has ever started a notebook. Since anyone with a Berkeley.edu account can log in, this is not the most accurate count of people who *use* the hub - but it's useful nonetheless. ###Code user_starts_count = sessions.groupby('user').count()['start'].to_frame() display.HTML(f'<h4>Users who used JupyterHub at least once: <b>{user_starts_count.shape[0]}</b></h4>') ###Output _____no_output_____ ###Markdown Some basic stats about number of times users started their servers ###Code user_starts_count.describe() ###Output _____no_output_____ ###Markdown We can calculate cost per day per user from this user count ###Code total['cost_per_user'] = total['cost'] / user_starts_count.count()['start'] alt.Chart(total, width=900, title='Daily cost per user').mark_line().encode( x='start', y=alt.Y('cost_per_user', axis=alt.Axis(format="$.2f"), title="Cost per user") ) ###Output _____no_output_____ ###Markdown We can also figure out how much they cost per month. ###Code monthly = cost.copy().set_index('start_time').resample('M').sum() monthly['cost_per_user'] = monthly['cost'] / user_starts_count.count()['start'] monthly = monthly.reset_index() alt.Chart(monthly, width=900, title='Monthly cost per user').mark_bar().encode( x='month(start_time):O', y=alt.Y('cost_per_user', axis=alt.Axis(format="$.2f"), title="Cost per user") ) ###Output _____no_output_____ ###Markdown Realistic user countA lot of people might log in a few times to the JupyterHub to check it out, and then never really come back. We should avoid counting those as 'users' when doing our cost analysis. We can cut off outliers at the 99th percentile and plot a histogram to see how most people use the hub ###Code outlier_cutoff = user_starts_count.quantile(0.99) alt.Chart(user_starts_count[user_starts_count['start'] < outlier_cutoff['start']], width=900).mark_bar().encode( alt.X('start', bin=alt.BinParams(maxbins=100)), y='count()' ) ###Output _____no_output_____ ###Markdown There's a lot of users who use the hub <5 times, and many who use it 5-10 times. We pick an arbitrary cut off of 'ten notebook server starts' to count as a 'real' user and not someone just trying out the hub. ###Code users_with_more_than_ten_starts = user_starts_count[user_starts_count['start'] > 10] display.HTML(f'<h4>Users who used the hub more than 10 times: <b>{users_with_more_than_ten_starts.count()["start"]}') ###Output _____no_output_____ ###Markdown We can use this to plot a daily and monthly cost per user ###Code total['cost_per_realistic_user'] = total['cost'] / users_with_more_than_ten_starts.count()['start'] alt.Chart(total, width=900, title='Daily cost per user (with >10 server starts)').mark_line().encode( x='start', y=alt.Y('cost_per_realistic_user', axis=alt.Axis(format="$.2f"), title="Cost per realistic user") ) realistic_monthly = cost.copy().set_index('start_time').resample('M').sum() realistic_monthly['cost_per_realistic_user'] = realistic_monthly['cost'] / users_with_more_than_ten_starts.count()['start'] realistic_monthly = realistic_monthly.reset_index() alt.Chart(realistic_monthly, width=900, title='Monthly cost per user (with >10 starts)').mark_bar().encode( x='month(start_time):O', y='cost_per_realistic_user' ) ###Output _____no_output_____ ###Markdown Session length ###Code length_counts = sessions.groupby('length_hours').count().reset_index() alt.Chart(length_counts, width=300).mark_bar().encode( x='length_hours', y=alt.Y('start', title="Count") ) ###Output _____no_output_____
Milestone-4 - ARIMA Analysis.ipynb
###Markdown Load Data ###Code # World Confirmed Cases confirmed_df = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv") # World Death Cases death_df = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv") ###Output _____no_output_____ ###Markdown DataFrame Cleaning ###Code # Get a list of columns, this serves to know which ones to clean list(confirmed_df.columns)[0:5] # Get a list of columns, this serves to know which ones to clean list(death_df.columns)[0:5] confirmed_df.sample(3) # Drop Unused columns for confirmed (Only keep columns needed, in this case Province_State and latest numbers confirmed_df.drop(columns=['Province/State','Lat','Long'], inplace=True) # Drop Unused columns for confirmed (Only keep columns needed, in this case Province_State and latest numbers death_df.drop(columns=['Province/State','Lat','Long'], inplace=True) confirmed_df.sample(3) death_df.sample(3) # Create grouped dataframes for entire world world_confirmed_grouped_df = confirmed_df.groupby('Country/Region').sum() world_death_grouped_df = death_df.groupby('Country/Region').sum() world_confirmed_grouped_df.sample(2) world_death_grouped_df.sample(2) # Add the option to run analysis for the whole world (treat it as another region) # Entire world numbers, returns Series with total daily numbers, create dataframe to # add at end of current data all_confirmed_df = pd.DataFrame(world_confirmed_grouped_df.sum(), columns=["World"]) all_death_df = pd.DataFrame(world_death_grouped_df.sum(), columns=["World"]) # Transpose so Series becomes row in df. Rename column to match all_confirmed_df.T.index.rename('Country/Region', inplace=True) all_death_df.T.index.rename('Country/Region', inplace=True) all_confirmed_df.T # Concatenate dataframes world_confirmed_df = pd.concat([all_confirmed_df.T,world_confirmed_grouped_df]) world_death_df = pd.concat([all_death_df.T,world_death_grouped_df]) world_confirmed_df.head() ###Output _____no_output_____ ###Markdown Functions ###Code def get_country_data(country_name, df): """Given a country name, return the Series with information""" results = None if(country_name in df.index): results = df.loc[country_name] # Convert index to DateTime results.index = pd.to_datetime(results.index) return results # Display confirmed cases of Canada (sample) series = get_country_data("Canada", world_confirmed_df ) series.plot() plt.show() # Display confirmed cases of Canada (sample) series = get_country_data("Canada", world_confirmed_df) series.plot() plt.show() ###Output _____no_output_____ ###Markdown Arima modeling ###Code # Autocorrelation test autocorrelation_plot(series) plt.show() ###Output _____no_output_____ ###Markdown Positive correlation in the first 80 to 90 lags, let's choose 10 for the AR parameter. Higher number makes ARIMA calcualtion longer ###Code # Calculate arima for Canada model = ARIMA(series.values,order=(10,1,0), dates=series.index, freq='D') model_fit = model.fit(disp=0) print(model_fit.summary()) # plot residual errors residuals = pd.DataFrame(model_fit.resid) residuals.plot() plt.show() residuals.plot(kind='kde') plt.show() print(residuals.describe()) ###Output _____no_output_____ ###Markdown Split train, test and predict, evaluate prediction ###Code def calculate_mse(series,train_size=65, arima_order=(10,1,0)): """Given a series, calculate the mse given the arima_order""" # Split train, test and predict X = series.values # Split train/test in rouhgly 65%/35% up_to = int(len(X) * 0.65) train, test = X[0:up_to], X[up_to:len(X)] # initial historical (train) data history = [x for x in train] # To keep track of predictions predictions = [] for t in tqdm(range(len(test))): model = ARIMA(history, order=(10,1,0)) model_fit = model.fit(disp=0) yhat = model_fit.forecast()[0] predictions.append(yhat) actual = test[t] # Append real value to history history.append(actual) # Uncomment if print desired #print(f'Prediction={yhat}, Expected={actual}') # Calculate MSE error = mean_squared_error(test, predictions) print('Test MSE: %.3f' % error) # plot plt.plot(test) plt.plot(predictions, color='red') plt.show() # Calculate MSE for Canada (series) calculate_mse(series) series = get_country_data("World", df) series def plot_country_forecast(country_name, df=world_confirmed_df): """Given a country, predict future cases""" series = get_country_data(country_name, df) model = ARIMA(series.values,order=(10,1,0), dates=series.index, freq='D') fig2, ax = plt.subplots(figsize=(12,8)) ax = series.loc['2020-01-22':].plot(ax=ax, label="Confirmed") model_fit = model.fit(disp=0) model_fit.plot_predict('2020-09-26','2020-12-31', dynamic=True, ax=ax, plot_insample=False) plt.show() # Forecast plot_country_forecast("Mexico") # Forecast US plot_country_forecast("US") # Forecast US death plot_country_forecast("US",df=world_death_df) # Forecast World plot_country_forecast("World") # Forecast Death plot_country_forecast("World",world_death_df) ###Output _____no_output_____
ScrapingMars.ipynb
###Markdown Basic Setup ###Code #Dependicies import time from splinter import Browser from bs4 import BeautifulSoup as bs import pandas as pd import requests from config import path #setup chromedriver executable_path = {"executable_path":f"{path}"} browser=Browser("chrome", **executable_path, headless=True) ###Output _____no_output_____ ###Markdown Scraping Mars News Site ###Code #Mars news URL to be scraped mars_news_page='https://mars.nasa.gov/news/' browser.visit(mars_news_page) #wait a moment for the page to be redirected time.sleep(1) html=browser.html news_soup=bs(html,'html.parser') #print(html) #Retrieve Title and teaser paragraph news_title=news_soup.find_all('div',class_='content_title')[1].text news_p=news_soup.find_all('div',class_="article_teaser_body")[0].text print(news_title) print('-----------------------------') print(news_p) ###Output NASA's Perseverance Rover Is Midway to Mars ----------------------------- Sometimes half measures can be a good thing – especially on a journey this long. The agency's latest rover only has about 146 million miles left to reach its destination. ###Markdown Scrap JPL Featured Mars Space Images ###Code #JPL image URL to be scraped jpl_url='https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars' browser.visit(jpl_url) html=browser.html image_soup=bs(html,'html.parser') #Retrieve Image URL relative_img_path=image_soup.find_all('img')[3]['src'] featured_image=f"https://www.jpl.nasa.gov{relative_img_path}" print(featured_image) ###Output https://www.jpl.nasa.gov/spaceimages/images/wallpaper/PIA24189-640x350.jpg ###Markdown Scrap Mars Facts ###Code facts_url='https://space-facts.com/mars/' tables = pd.read_html(facts_url) tables mars_facts_df=tables[0] mars_facts_df.columns =['Description','Value'] mars_facts_df mars_fact_html=mars_facts_df.to_html() mars_fact_html.replace('\n','') print(mars_fact_html) ###Output <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Description</th> <th>Value</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>Equatorial Diameter:</td> <td>6,792 km</td> </tr> <tr> <th>1</th> <td>Polar Diameter:</td> <td>6,752 km</td> </tr> <tr> <th>2</th> <td>Mass:</td> <td>6.39 × 10^23 kg (0.11 Earths)</td> </tr> <tr> <th>3</th> <td>Moons:</td> <td>2 (Phobos &amp; Deimos)</td> </tr> <tr> <th>4</th> <td>Orbit Distance:</td> <td>227,943,824 km (1.38 AU)</td> </tr> <tr> <th>5</th> <td>Orbit Period:</td> <td>687 days (1.9 years)</td> </tr> <tr> <th>6</th> <td>Surface Temperature:</td> <td>-87 to -5 °C</td> </tr> <tr> <th>7</th> <td>First Record:</td> <td>2nd millennium BC</td> </tr> <tr> <th>8</th> <td>Recorded By:</td> <td>Egyptian astronomers</td> </tr> </tbody> </table> ###Markdown Scraping Mars Hemisphere Images ###Code hemi_url='https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' browser.visit(hemi_url) html=browser.html hemi_soup=bs(html,'html.parser') hemi_url=[] items = hemi_soup.find_all('div', class_='item') for i in items: hemisphere = i.find('div',class_='description') title = hemisphere.h3.text hemisphere_link=hemisphere.a['href'] browser.visit(f'https://astrogeology.usgs.gov{hemisphere_link}') time.sleep(1) image_html=browser.html image_soup=bs(image_html,'html.parser') image_url=image_soup.find('div',class_='downloads').find('li').a['href'] hemi_url.append({'title':title,'img_url':image_url}) print(hemi_url) ###Output [{'title': 'Cerberus Hemisphere Enhanced', 'img_url': 'https://astropedia.astrogeology.usgs.gov/download/Mars/Viking/cerberus_enhanced.tif/full.jpg'}, {'title': 'Schiaparelli Hemisphere Enhanced', 'img_url': 'https://astropedia.astrogeology.usgs.gov/download/Mars/Viking/schiaparelli_enhanced.tif/full.jpg'}, {'title': 'Syrtis Major Hemisphere Enhanced', 'img_url': 'https://astropedia.astrogeology.usgs.gov/download/Mars/Viking/syrtis_major_enhanced.tif/full.jpg'}, {'title': 'Valles Marineris Hemisphere Enhanced', 'img_url': 'https://astropedia.astrogeology.usgs.gov/download/Mars/Viking/valles_marineris_enhanced.tif/full.jpg'}] ###Markdown Putting it all together ###Code mars_dict={ "news_title":news_title, "news_p":news_p, "featured_image":featured_image, "fact_table":str(mars_fact_html), "hemisphere_images":hemi_url } mars_dict browser.quit() ###Output _____no_output_____
Results Analysis-Public.ipynb
###Markdown Meta Class 1 ###Code #test_acc_df = pd.DataFrame(data = [[i,j,k] for i,j,k in zip(pickle_logs_names,test_acc_allmc,mc)],columns = ['Experiment','Test Accuracy','Meta Class']) #test_acc_mc0 = test_acc_df[test_acc_df['Meta Class'] == 0] #test_acc_mc1 = test_acc_df[test_acc_df['Meta Class'] == 1] #test_acc_mc2 = test_acc_df[test_acc_df['Meta Class'] == 2] #test_acc_mc3 = test_acc_df[test_acc_df['Meta Class'] == 3] #test_acc_mc4 = test_acc_df[test_acc_df['Meta Class'] == 4] #test_acc_mc5 = test_acc_df[test_acc_df['Meta Class'] == 5] test_acc_mc1['Network'] = [f.split('-')[0] for f in test_acc_mc1['Experiment']] test_acc_mc1['SR'] = [f.split('-')[2] for f in test_acc_mc1['Experiment']] test_acc_mc1['Representation'] = [f.split('-')[3] for f in test_acc_mc1['Experiment']] AttRNN1D_df = test_acc_mc1[test_acc_mc1['Network']=='AttRNN1D'] AttRNN2D_df = test_acc_mc1[test_acc_mc1['Network']=='AttRNN2D'] AttRNN2D_MFCC_df = AttRNN2D_df[AttRNN2D_df['Representation']=='MFCC'] AttRNN2D_MFCC_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_MFCC_df['Experiment']] AttRNN2D_MFCC_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_MFCC_df['Experiment']] AttRNN2D_MFCC_df['Frames'] = AttRNN2D_MFCC_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') AttRNN2D_MS_df = AttRNN2D_df[AttRNN2D_df['Representation']=='MS'] AttRNN2D_MS_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_MS_df['Experiment']] AttRNN2D_MS_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_MS_df['Experiment']] AttRNN2D_MS_df['Frames'] = AttRNN2D_MS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') AttRNN2D_PS_df = AttRNN2D_df[AttRNN2D_df['Representation']=='PS'] AttRNN2D_PS_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_PS_df['Experiment']] AttRNN2D_PS_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_PS_df['Experiment']] AttRNN2D_PS_df['Frames'] = AttRNN2D_PS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') CNN1D_df = test_acc_mc1[test_acc_mc1['Network']=='CNN1D'] malley_df = test_acc_mc1[test_acc_mc1['Network']=='malley'] malley_MFCC_df = malley_df[malley_df['Representation']=='MFCC'] malley_MFCC_df['Freq Res'] = [f.split('-')[4] for f in malley_MFCC_df['Experiment']] malley_MFCC_df['Time Res'] = [f.split('-')[5] for f in malley_MFCC_df['Experiment']] malley_MFCC_df['Frames'] = malley_MFCC_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') malley_MS_df = malley_df[malley_df['Representation']=='MS'] malley_MS_df['Freq Res'] = [f.split('-')[4] for f in malley_MS_df['Experiment']] malley_MS_df['Time Res'] = [f.split('-')[5] for f in malley_MS_df['Experiment']] malley_MS_df['Frames'] = malley_MS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') malley_PS_df = malley_df[malley_df['Representation']=='PS'] malley_PS_df['Freq Res'] = [f.split('-')[4] for f in malley_PS_df['Experiment']] malley_PS_df['Time Res'] = [f.split('-')[5] for f in malley_PS_df['Experiment']] malley_PS_df['Frames'] = malley_PS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') labels1 = ['{}'.format(f) for f in AttRNN1D_df['SR']] labels2 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_MFCC_df['SR'],AttRNN2D_MFCC_df['Freq Res'],AttRNN2D_MFCC_df['Frames'])] labels3 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_MS_df['SR'],AttRNN2D_MS_df['Freq Res'],AttRNN2D_MS_df['Frames'])] labels4 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_PS_df['SR'],AttRNN2D_PS_df['Freq Res'],AttRNN2D_PS_df['Frames'])] labels5 = ['{}'.format(f) for f in CNN1D_df['SR']] labels6 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_MFCC_df['SR'],malley_MFCC_df['Freq Res'],malley_MFCC_df['Frames'])] labels7 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_MS_df['SR'],malley_MS_df['Freq Res'],malley_MS_df['Frames'])] labels8 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_PS_df['SR'],malley_PS_df['Freq Res'],malley_PS_df['Frames'])] fig, ax = plt.subplots(1,1,figsize = (16,6)) rects1 = ax.bar(rects1_x,AttRNN1D_df['Test Accuracy'],label = 'WF AttRNN1D',color = '#33D7FC') rects2 = ax.bar(rects2_x,AttRNN2D_MFCC_df['Test Accuracy'],label = 'MFCC AttRNN2D',color = '#FC5533') rects3 = ax.bar(rects3_x,AttRNN2D_MS_df['Test Accuracy'],label = 'MS AttRNN2D',color = '#FD8066') rects4 = ax.bar(rects4_x,AttRNN2D_PS_df['Test Accuracy'],label = 'PS AttRNN2D',color = '#FEAA99') rects5 = ax.bar(rects5_x,CNN1D_df['Test Accuracy'],label = 'WF CNN1D',color = '#FC3364') rects6 = ax.bar(rects6_x,malley_MFCC_df['Test Accuracy'],label = "MFCC O\'Malley",color = '#C62CF3') rects7 = ax.bar(rects7_x,malley_MS_df['Test Accuracy'],label = "MS O\'Malley",color = '#D461F6') rects8 = ax.bar(rects8_x,malley_PS_df['Test Accuracy'],label = "PS O\'Malley",color = '#E395F9') ax.set(ylim = [0.7,1],xlim = [-1,44]) ax.legend(loc = 'lower right') ax.set_xlabel('Input') ax.set_ylabel('Test Accuracy') fig = ax.set_xticks(x) fig = ax.set_xticklabels(labels1+labels2+labels3+labels4+labels5+labels6+labels7+labels8,rotation = 90) ax.set_title('Accuracy for Meta-Class 1 Classifiers') plt.tight_layout() plt.savefig('./MC1_Accuracy.eps') fig, ax = plt.subplots(1,1,figsize = (16,6)) rects1 = ax.bar(rects1_x,AttRNN1D_df['Map3'],label = 'WF AttRNN1D',color = '#33D7FC') rects2 = ax.bar(rects2_x,AttRNN2D_MFCC_df['Map3'],label = 'MFCC AttRNN2D',color = '#FC5533') rects3 = ax.bar(rects3_x,AttRNN2D_MS_df['Map3'],label = 'MS AttRNN2D',color = '#FD8066') rects4 = ax.bar(rects4_x,AttRNN2D_PS_df['Map3'],label = 'PS AttRNN2D',color = '#FEAA99') rects5 = ax.bar(rects5_x,CNN1D_df['Map3'],label = 'WF CNN1D',color = '#FC3364') rects6 = ax.bar(rects6_x,malley_MFCC_df['Map3'],label = "MFCC O\'Malley",color = '#C62CF3') rects7 = ax.bar(rects7_x,malley_MS_df['Map3'],label = "MS O\'Malley",color = '#D461F6') rects8 = ax.bar(rects8_x,malley_PS_df['Map3'],label = "PS O\'Malley",color = '#E395F9') ax.set(ylim = [0.7,1],xlim = [-1,44]) ax.legend(loc = 'lower right') ax.set_xlabel('Input') ax.set_ylabel('Test Accuracy') fig = ax.set_xticks(x) fig = ax.set_xticklabels(labels1+labels2+labels3+labels4+labels5+labels6+labels7+labels8,rotation = 90) ax.set_title('MAP@3 for Meta-Class 1 Classifiers') plt.tight_layout() plt.savefig('./MC1_Map3.eps') ###Output _____no_output_____ ###Markdown Meta Class 2 ###Code #test_acc_df = pd.DataFrame(data = [[i,j,k] for i,j,k in zip(pickle_logs_names,test_acc_allmc,mc)],columns = ['Experiment','Test Accuracy','Meta Class']) #test_acc_mc0 = test_acc_df[test_acc_df['Meta Class'] == 0] #test_acc_mc1 = test_acc_df[test_acc_df['Meta Class'] == 1] #test_acc_mc2 = test_acc_df[test_acc_df['Meta Class'] == 2] #test_acc_mc3 = test_acc_df[test_acc_df['Meta Class'] == 3] #test_acc_mc4 = test_acc_df[test_acc_df['Meta Class'] == 4] #test_acc_mc5 = test_acc_df[test_acc_df['Meta Class'] == 5] test_acc_mc2['Network'] = [f.split('-')[0] for f in test_acc_mc2['Experiment']] test_acc_mc2['SR'] = [f.split('-')[2] for f in test_acc_mc2['Experiment']] test_acc_mc2['Representation'] = [f.split('-')[3] for f in test_acc_mc2['Experiment']] AttRNN1D_df = test_acc_mc2[test_acc_mc2['Network']=='AttRNN1D'] AttRNN2D_df = test_acc_mc2[test_acc_mc2['Network']=='AttRNN2D'] AttRNN2D_MFCC_df = AttRNN2D_df[AttRNN2D_df['Representation']=='MFCC'] AttRNN2D_MFCC_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_MFCC_df['Experiment']] AttRNN2D_MFCC_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_MFCC_df['Experiment']] AttRNN2D_MFCC_df['Frames'] = AttRNN2D_MFCC_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') AttRNN2D_MS_df = AttRNN2D_df[AttRNN2D_df['Representation']=='MS'] AttRNN2D_MS_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_MS_df['Experiment']] AttRNN2D_MS_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_MS_df['Experiment']] AttRNN2D_MS_df['Frames'] = AttRNN2D_MS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') AttRNN2D_PS_df = AttRNN2D_df[AttRNN2D_df['Representation']=='PS'] AttRNN2D_PS_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_PS_df['Experiment']] AttRNN2D_PS_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_PS_df['Experiment']] AttRNN2D_PS_df['Frames'] = AttRNN2D_PS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') CNN1D_df = test_acc_mc2[test_acc_mc2['Network']=='CNN1D'] malley_df = test_acc_mc2[test_acc_mc2['Network']=='malley'] malley_MFCC_df = malley_df[malley_df['Representation']=='MFCC'] malley_MFCC_df['Freq Res'] = [f.split('-')[4] for f in malley_MFCC_df['Experiment']] malley_MFCC_df['Time Res'] = [f.split('-')[5] for f in malley_MFCC_df['Experiment']] malley_MFCC_df['Frames'] = malley_MFCC_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') malley_MS_df = malley_df[malley_df['Representation']=='MS'] malley_MS_df['Freq Res'] = [f.split('-')[4] for f in malley_MS_df['Experiment']] malley_MS_df['Time Res'] = [f.split('-')[5] for f in malley_MS_df['Experiment']] malley_MS_df['Frames'] = malley_MS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') malley_PS_df = malley_df[malley_df['Representation']=='PS'] malley_PS_df['Freq Res'] = [f.split('-')[4] for f in malley_PS_df['Experiment']] malley_PS_df['Time Res'] = [f.split('-')[5] for f in malley_PS_df['Experiment']] malley_PS_df['Frames'] = malley_PS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') labels1 = ['{}'.format(f) for f in AttRNN1D_df['SR']] labels2 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_MFCC_df['SR'],AttRNN2D_MFCC_df['Freq Res'],AttRNN2D_MFCC_df['Frames'])] labels3 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_MS_df['SR'],AttRNN2D_MS_df['Freq Res'],AttRNN2D_MS_df['Frames'])] labels4 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_PS_df['SR'],AttRNN2D_PS_df['Freq Res'],AttRNN2D_PS_df['Frames'])] labels5 = ['{}'.format(f) for f in CNN1D_df['SR']] labels6 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_MFCC_df['SR'],malley_MFCC_df['Freq Res'],malley_MFCC_df['Frames'])] labels7 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_MS_df['SR'],malley_MS_df['Freq Res'],malley_MS_df['Frames'])] labels8 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_PS_df['SR'],malley_PS_df['Freq Res'],malley_PS_df['Frames'])] fig, ax = plt.subplots(1,1,figsize = (16,6)) rects1 = ax.bar(rects1_x,AttRNN1D_df['Test Accuracy'],label = 'WF AttRNN1D',color = '#33D7FC') rects2 = ax.bar(rects2_x,AttRNN2D_MFCC_df['Test Accuracy'],label = 'MFCC AttRNN2D',color = '#FC5533') rects3 = ax.bar(rects3_x,AttRNN2D_MS_df['Test Accuracy'],label = 'MS AttRNN2D',color = '#FD8066') rects4 = ax.bar(rects4_x,AttRNN2D_PS_df['Test Accuracy'],label = 'PS AttRNN2D',color = '#FEAA99') rects5 = ax.bar(rects5_x,CNN1D_df['Test Accuracy'],label = 'WF CNN1D',color = '#FC3364') rects6 = ax.bar(rects6_x,malley_MFCC_df['Test Accuracy'],label = "MFCC O\'Malley",color = '#C62CF3') rects7 = ax.bar(rects7_x,malley_MS_df['Test Accuracy'],label = "MS O\'Malley",color = '#D461F6') rects8 = ax.bar(rects8_x,malley_PS_df['Test Accuracy'],label = "PS O\'Malley",color = '#E395F9') ax.set(ylim = [0.4,0.95],xlim = [-1,44]) ax.legend(loc = 'lower right') ax.set_xlabel('Input') ax.set_ylabel('Test Accuracy') fig = ax.set_xticks(x) fig = ax.set_xticklabels(labels1+labels2+labels3+labels4+labels5+labels6+labels7+labels8,rotation = 90) ax.set_title('Accuracy for Meta-Class 2 Classifiers') plt.tight_layout() plt.savefig('./MC2_Accuracy.eps') fig, ax = plt.subplots(1,1,figsize = (16,6)) rects1 = ax.bar(rects1_x,AttRNN1D_df['Map3'],label = 'WF AttRNN1D',color = '#33D7FC') rects2 = ax.bar(rects2_x,AttRNN2D_MFCC_df['Map3'],label = 'MFCC AttRNN2D',color = '#FC5533') rects3 = ax.bar(rects3_x,AttRNN2D_MS_df['Map3'],label = 'MS AttRNN2D',color = '#FD8066') rects4 = ax.bar(rects4_x,AttRNN2D_PS_df['Map3'],label = 'PS AttRNN2D',color = '#FEAA99') rects5 = ax.bar(rects5_x,CNN1D_df['Map3'],label = 'WF CNN1D',color = '#FC3364') rects6 = ax.bar(rects6_x,malley_MFCC_df['Map3'],label = "MFCC O\'Malley",color = '#C62CF3') rects7 = ax.bar(rects7_x,malley_MS_df['Map3'],label = "MS O\'Malley",color = '#D461F6') rects8 = ax.bar(rects8_x,malley_PS_df['Map3'],label = "PS O\'Malley",color = '#E395F9') ax.set(ylim = [0.4,0.95],xlim = [-1,44]) ax.legend(loc = 'lower right') ax.set_xlabel('Input') ax.set_ylabel('Test Accuracy') fig = ax.set_xticks(x) fig = ax.set_xticklabels(labels1+labels2+labels3+labels4+labels5+labels6+labels7+labels8,rotation = 90) ax.set_title('MAP@3 Score for Meta-Class 2 Classifiers') plt.tight_layout() plt.savefig('./MC2_MAP3.eps') ###Output _____no_output_____ ###Markdown Meta Class 3 ###Code #test_acc_df = pd.DataFrame(data = [[i,j,k] for i,j,k in zip(pickle_logs_names,test_acc_allmc,mc)],columns = ['Experiment','Test Accuracy','Meta Class']) #test_acc_mc0 = test_acc_df[test_acc_df['Meta Class'] == 0] #test_acc_mc1 = test_acc_df[test_acc_df['Meta Class'] == 1] #test_acc_mc2 = test_acc_df[test_acc_df['Meta Class'] == 2] #test_acc_mc3 = test_acc_df[test_acc_df['Meta Class'] == 3] #test_acc_mc4 = test_acc_df[test_acc_df['Meta Class'] == 4] #test_acc_mc5 = test_acc_df[test_acc_df['Meta Class'] == 5] test_acc_mc3['Network'] = [f.split('-')[0] for f in test_acc_mc3['Experiment']] test_acc_mc3['SR'] = [f.split('-')[2] for f in test_acc_mc3['Experiment']] test_acc_mc3['Representation'] = [f.split('-')[3] for f in test_acc_mc3['Experiment']] AttRNN1D_df = test_acc_mc3[test_acc_mc3['Network']=='AttRNN1D'] AttRNN2D_df = test_acc_mc3[test_acc_mc3['Network']=='AttRNN2D'] AttRNN2D_MFCC_df = AttRNN2D_df[AttRNN2D_df['Representation']=='MFCC'] AttRNN2D_MFCC_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_MFCC_df['Experiment']] AttRNN2D_MFCC_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_MFCC_df['Experiment']] AttRNN2D_MFCC_df['Frames'] = AttRNN2D_MFCC_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') AttRNN2D_MS_df = AttRNN2D_df[AttRNN2D_df['Representation']=='MS'] AttRNN2D_MS_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_MS_df['Experiment']] AttRNN2D_MS_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_MS_df['Experiment']] AttRNN2D_MS_df['Frames'] = AttRNN2D_MS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') AttRNN2D_PS_df = AttRNN2D_df[AttRNN2D_df['Representation']=='PS'] AttRNN2D_PS_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_PS_df['Experiment']] AttRNN2D_PS_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_PS_df['Experiment']] AttRNN2D_PS_df['Frames'] = AttRNN2D_PS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') CNN1D_df = test_acc_mc3[test_acc_mc3['Network']=='CNN1D'] malley_df = test_acc_mc3[test_acc_mc3['Network']=='malley'] malley_MFCC_df = malley_df[malley_df['Representation']=='MFCC'] malley_MFCC_df['Freq Res'] = [f.split('-')[4] for f in malley_MFCC_df['Experiment']] malley_MFCC_df['Time Res'] = [f.split('-')[5] for f in malley_MFCC_df['Experiment']] malley_MFCC_df['Frames'] = malley_MFCC_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') malley_MS_df = malley_df[malley_df['Representation']=='MS'] malley_MS_df['Freq Res'] = [f.split('-')[4] for f in malley_MS_df['Experiment']] malley_MS_df['Time Res'] = [f.split('-')[5] for f in malley_MS_df['Experiment']] malley_MS_df['Frames'] = malley_MS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') malley_PS_df = malley_df[malley_df['Representation']=='PS'] malley_PS_df['Freq Res'] = [f.split('-')[4] for f in malley_PS_df['Experiment']] malley_PS_df['Time Res'] = [f.split('-')[5] for f in malley_PS_df['Experiment']] malley_PS_df['Frames'] = malley_PS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') labels1 = ['{}'.format(f) for f in AttRNN1D_df['SR']] labels2 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_MFCC_df['SR'],AttRNN2D_MFCC_df['Freq Res'],AttRNN2D_MFCC_df['Frames'])] labels3 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_MS_df['SR'],AttRNN2D_MS_df['Freq Res'],AttRNN2D_MS_df['Frames'])] labels4 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_PS_df['SR'],AttRNN2D_PS_df['Freq Res'],AttRNN2D_PS_df['Frames'])] labels5 = ['{}'.format(f) for f in CNN1D_df['SR']] labels6 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_MFCC_df['SR'],malley_MFCC_df['Freq Res'],malley_MFCC_df['Frames'])] labels7 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_MS_df['SR'],malley_MS_df['Freq Res'],malley_MS_df['Frames'])] labels8 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_PS_df['SR'],malley_PS_df['Freq Res'],malley_PS_df['Frames'])] fig, ax = plt.subplots(1,1,figsize = (16,6)) rects1 = ax.bar(rects1_x,AttRNN1D_df['Test Accuracy'],label = 'WF AttRNN1D',color = '#33D7FC') rects2 = ax.bar(rects2_x,AttRNN2D_MFCC_df['Test Accuracy'],label = 'MFCC AttRNN2D',color = '#FC5533') rects3 = ax.bar(rects3_x,AttRNN2D_MS_df['Test Accuracy'],label = 'MS AttRNN2D',color = '#FD8066') rects4 = ax.bar(rects4_x,AttRNN2D_PS_df['Test Accuracy'],label = 'PS AttRNN2D',color = '#FEAA99') rects5 = ax.bar(rects5_x,CNN1D_df['Test Accuracy'],label = 'WF CNN1D',color = '#FC3364') rects6 = ax.bar(rects6_x,malley_MFCC_df['Test Accuracy'],label = "MFCC O\'Malley",color = '#C62CF3') rects7 = ax.bar(rects7_x,malley_MS_df['Test Accuracy'],label = "MS O\'Malley",color = '#D461F6') rects8 = ax.bar(rects8_x,malley_PS_df['Test Accuracy'],label = "PS O\'Malley",color = '#E395F9') ax.set(ylim = [0.6,0.95],xlim = [-1,44]) ax.legend(loc = 'lower right') ax.set_xlabel('Input') ax.set_ylabel('Test Accuracy') fig = ax.set_xticks(x) fig = ax.set_xticklabels(labels1+labels2+labels3+labels4+labels5+labels6+labels7+labels8,rotation = 90) ax.set_title('Accuracy for Meta-Class 3 Classifiers') plt.tight_layout() plt.savefig('./MC3_Accuracy.eps') fig, ax = plt.subplots(1,1,figsize = (16,6)) rects1 = ax.bar(rects1_x,AttRNN1D_df['Map3'],label = 'WF AttRNN1D',color = '#33D7FC') rects2 = ax.bar(rects2_x,AttRNN2D_MFCC_df['Map3'],label = 'MFCC AttRNN2D',color = '#FC5533') rects3 = ax.bar(rects3_x,AttRNN2D_MS_df['Map3'],label = 'MS AttRNN2D',color = '#FD8066') rects4 = ax.bar(rects4_x,AttRNN2D_PS_df['Map3'],label = 'PS AttRNN2D',color = '#FEAA99') rects5 = ax.bar(rects5_x,CNN1D_df['Map3'],label = 'WF CNN1D',color = '#FC3364') rects6 = ax.bar(rects6_x,malley_MFCC_df['Map3'],label = "MFCC O\'Malley",color = '#C62CF3') rects7 = ax.bar(rects7_x,malley_MS_df['Map3'],label = "MS O\'Malley",color = '#D461F6') rects8 = ax.bar(rects8_x,malley_PS_df['Map3'],label = "PS O\'Malley",color = '#E395F9') ax.set(ylim = [0.6,0.95],xlim = [-1,44]) ax.legend(loc = 'lower right') ax.set_xlabel('Input') ax.set_ylabel('Test Accuracy') fig = ax.set_xticks(x) fig = ax.set_xticklabels(labels1+labels2+labels3+labels4+labels5+labels6+labels7+labels8,rotation = 90) ax.set_title('MAP@3 Score for Meta-Class 3 Classifiers') plt.tight_layout() plt.savefig('./MC3_MAP3.eps') ###Output _____no_output_____ ###Markdown Meta Class 5 ###Code #test_acc_df = pd.DataFrame(data = [[i,j,k] for i,j,k in zip(pickle_logs_names,test_acc_allmc,mc)],columns = ['Experiment','Test Accuracy','Meta Class']) #test_acc_mc0 = test_acc_df[test_acc_df['Meta Class'] == 0] #test_acc_mc1 = test_acc_df[test_acc_df['Meta Class'] == 1] #test_acc_mc2 = test_acc_df[test_acc_df['Meta Class'] == 2] #test_acc_mc3 = test_acc_df[test_acc_df['Meta Class'] == 3] #test_acc_mc4 = test_acc_df[test_acc_df['Meta Class'] == 4] #test_acc_mc5 = test_acc_df[test_acc_df['Meta Class'] == 5] test_acc_mc5['Network'] = [f.split('-')[0] for f in test_acc_mc5['Experiment']] test_acc_mc5['SR'] = [f.split('-')[2] for f in test_acc_mc5['Experiment']] test_acc_mc5['Representation'] = [f.split('-')[3] for f in test_acc_mc5['Experiment']] AttRNN1D_df = test_acc_mc5[test_acc_mc5['Network']=='AttRNN1D'] AttRNN2D_df = test_acc_mc5[test_acc_mc5['Network']=='AttRNN2D'] AttRNN2D_MFCC_df = AttRNN2D_df[AttRNN2D_df['Representation']=='MFCC'] AttRNN2D_MFCC_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_MFCC_df['Experiment']] AttRNN2D_MFCC_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_MFCC_df['Experiment']] AttRNN2D_MFCC_df['Frames'] = AttRNN2D_MFCC_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') AttRNN2D_MS_df = AttRNN2D_df[AttRNN2D_df['Representation']=='MS'] AttRNN2D_MS_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_MS_df['Experiment']] AttRNN2D_MS_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_MS_df['Experiment']] AttRNN2D_MS_df['Frames'] = AttRNN2D_MS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') AttRNN2D_PS_df = AttRNN2D_df[AttRNN2D_df['Representation']=='PS'] AttRNN2D_PS_df['Freq Res'] = [f.split('-')[4] for f in AttRNN2D_PS_df['Experiment']] AttRNN2D_PS_df['Time Res'] = [f.split('-')[5] for f in AttRNN2D_PS_df['Experiment']] AttRNN2D_PS_df['Frames'] = AttRNN2D_PS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') CNN1D_df = test_acc_mc5[test_acc_mc5['Network']=='CNN1D'] malley_df = test_acc_mc5[test_acc_mc5['Network']=='malley'] malley_MFCC_df = malley_df[malley_df['Representation']=='MFCC'] malley_MFCC_df['Freq Res'] = [f.split('-')[4] for f in malley_MFCC_df['Experiment']] malley_MFCC_df['Time Res'] = [f.split('-')[5] for f in malley_MFCC_df['Experiment']] malley_MFCC_df['Frames'] = malley_MFCC_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') malley_MS_df = malley_df[malley_df['Representation']=='MS'] malley_MS_df['Freq Res'] = [f.split('-')[4] for f in malley_MS_df['Experiment']] malley_MS_df['Time Res'] = [f.split('-')[5] for f in malley_MS_df['Experiment']] malley_MS_df['Frames'] = malley_MS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') malley_PS_df = malley_df[malley_df['Representation']=='PS'] malley_PS_df['Freq Res'] = [f.split('-')[4] for f in malley_PS_df['Experiment']] malley_PS_df['Time Res'] = [f.split('-')[5] for f in malley_PS_df['Experiment']] malley_PS_df['Frames'] = malley_PS_df['Time Res'].apply(lambda x: '125' if x == 'HL512' else '250') labels1 = ['{}'.format(f) for f in AttRNN1D_df['SR']] labels2 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_MFCC_df['SR'],AttRNN2D_MFCC_df['Freq Res'],AttRNN2D_MFCC_df['Frames'])] labels3 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_MS_df['SR'],AttRNN2D_MS_df['Freq Res'],AttRNN2D_MS_df['Frames'])] labels4 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(AttRNN2D_PS_df['SR'],AttRNN2D_PS_df['Freq Res'],AttRNN2D_PS_df['Frames'])] labels5 = ['{}'.format(f) for f in CNN1D_df['SR']] labels6 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_MFCC_df['SR'],malley_MFCC_df['Freq Res'],malley_MFCC_df['Frames'])] labels7 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_MS_df['SR'],malley_MS_df['Freq Res'],malley_MS_df['Frames'])] labels8 = ['{}-({},{})'.format(f,j,k) for f,j,k in zip(malley_PS_df['SR'],malley_PS_df['Freq Res'],malley_PS_df['Frames'])] fig, ax = plt.subplots(1,1,figsize = (16,6)) rects1 = ax.bar(rects1_x,AttRNN1D_df['Test Accuracy'],label = 'WF AttRNN1D',color = '#33D7FC') rects2 = ax.bar(rects2_x,AttRNN2D_MFCC_df['Test Accuracy'],label = 'MFCC AttRNN2D',color = '#FC5533') rects3 = ax.bar(rects3_x,AttRNN2D_MS_df['Test Accuracy'],label = 'MS AttRNN2D',color = '#FD8066') rects4 = ax.bar(rects4_x,AttRNN2D_PS_df['Test Accuracy'],label = 'PS AttRNN2D',color = '#FEAA99') rects5 = ax.bar(rects5_x,CNN1D_df['Test Accuracy'],label = 'WF CNN1D',color = '#FC3364') rects6 = ax.bar(rects6_x,malley_MFCC_df['Test Accuracy'],label = "MFCC O\'Malley",color = '#C62CF3') rects7 = ax.bar(rects7_x,malley_MS_df['Test Accuracy'],label = "MS O\'Malley",color = '#D461F6') rects8 = ax.bar(rects8_x,malley_PS_df['Test Accuracy'],label = "PS O\'Malley",color = '#E395F9') ax.set(ylim = [0.55,1],xlim = [-1,44]) ax.legend(loc = 'lower right') ax.set_xlabel('Input') ax.set_ylabel('Test Accuracy') fig = ax.set_xticks(x) fig = ax.set_xticklabels(labels1+labels2+labels3+labels4+labels5+labels6+labels7+labels8,rotation = 90) ax.set_title('Accuracy for Meta-Class 5 Classifiers') plt.tight_layout() plt.savefig('./MC5_Accuracy.eps') fig, ax = plt.subplots(1,1,figsize = (16,6)) rects1 = ax.bar(rects1_x,AttRNN1D_df['Map3'],label = 'WF AttRNN1D',color = '#33D7FC') rects2 = ax.bar(rects2_x,AttRNN2D_MFCC_df['Map3'],label = 'MFCC AttRNN2D',color = '#FC5533') rects3 = ax.bar(rects3_x,AttRNN2D_MS_df['Map3'],label = 'MS AttRNN2D',color = '#FD8066') rects4 = ax.bar(rects4_x,AttRNN2D_PS_df['Map3'],label = 'PS AttRNN2D',color = '#FEAA99') rects5 = ax.bar(rects5_x,CNN1D_df['Map3'],label = 'WF CNN1D',color = '#FC3364') rects6 = ax.bar(rects6_x,malley_MFCC_df['Map3'],label = "MFCC O\'Malley",color = '#C62CF3') rects7 = ax.bar(rects7_x,malley_MS_df['Map3'],label = "MS O\'Malley",color = '#D461F6') rects8 = ax.bar(rects8_x,malley_PS_df['Map3'],label = "PS O\'Malley",color = '#E395F9') ax.set(ylim = [0.55,1],xlim = [-1,44]) ax.legend(loc = 'lower right') ax.set_xlabel('Input') ax.set_ylabel('Test Accuracy') fig = ax.set_xticks(x) fig = ax.set_xticklabels(labels1+labels2+labels3+labels4+labels5+labels6+labels7+labels8,rotation = 90) ax.set_title('MAP@3 Score for Meta-Class 5 Classifiers') plt.tight_layout() plt.savefig('./MC5_MAP3.eps') ###Output _____no_output_____
2_Estatistica-para-Ciencia-de-Dados/4_Medidas-de-posicao-e-dispersao.ipynb
###Markdown Estatística para Machine Learning 4. Medidas de posição e dispersão Base de dados ###Code import numpy as np import statistics from scipy import stats import math dados = np.array([150, 151, 152, 152, 153, 154, 155, 155, 155, 155, 156, 156, 156, 157, 158, 158, 160, 160, 160, 160, 160, 161, 161, 161, 161, 162, 163, 163, 164, 164, 164, 165, 166, 167, 168, 168, 169, 170, 172, 173]) ###Output _____no_output_____ ###Markdown Média aritmética simples ###Code dados.sum() / len(dados) dados.mean() statistics.mean(dados) ###Output _____no_output_____ ###Markdown Moda ###Code statistics.mode(dados) stats.mode(dados) ###Output _____no_output_____ ###Markdown Mediana ###Code dados_impar = [150, 151, 152, 152, 153, 154, 155, 155, 155] ###Output _____no_output_____ ###Markdown Cálculo manual (ímpar) ###Code posicao = len(dados_impar) / 2 posicao posicao = math.ceil(posicao) posicao dados_impar[posicao - 1] ###Output _____no_output_____ ###Markdown Cálculo manual (par) ###Code posicao = len(dados) // 2 posicao dados[posicao - 1], dados[posicao] mediana = (dados[posicao - 1] + dados[posicao]) / 2 mediana ###Output _____no_output_____ ###Markdown Bibliotecas ###Code np.median(dados_impar) np.median(dados) statistics.median(dados_impar) statistics.median(dados) ###Output _____no_output_____ ###Markdown Média aritmética ponderada ###Code notas = np.array([9, 8, 7, 3]) pesos = np.array([1, 2, 3, 4]) (9 * 1 + 8 * 2 + 7 * 3 + 3 * 4) / (1 + 2 + 3 + 4) media_ponderada = (notas * pesos).sum() / pesos.sum() media_ponderada np.average(notas, weights=pesos) ###Output _____no_output_____ ###Markdown Média aritmética, moda e mediana com distribuição de frequência (dados agrupados) ###Code dados = {'inferior': [150, 154, 158, 162, 166, 170], 'superior': [154, 158, 162, 166, 170, 174], 'fi': [5, 9, 11, 7, 5, 3]} import pandas as pd dataset = pd.DataFrame(dados) dataset dataset['xi'] = (dataset['superior'] + dataset['inferior']) / 2 dataset dataset['fi.xi'] = dataset['fi'] * dataset['xi'] dataset dataset['Fi'] = 0 dataset frequencia_acumulada = [] somatorio = 0 for linha in dataset.iterrows(): #print(linha[1]) #print(linha[1][2]) somatorio += linha[1][2] frequencia_acumulada.append(somatorio) frequencia_acumulada dataset['Fi'] = frequencia_acumulada dataset ###Output _____no_output_____ ###Markdown Média ###Code dataset['fi'].sum(), dataset['fi.xi'].sum() dataset['fi.xi'].sum() / dataset['fi'].sum() ###Output _____no_output_____ ###Markdown Moda ###Code dataset['fi'].max() dataset[dataset['fi'] == dataset['fi'].max()] dataset[dataset['fi'] == dataset['fi'].max()]['xi'].values[0] ###Output _____no_output_____ ###Markdown Mediana ###Code dataset fi_2 = dataset['fi'].sum() / 2 fi_2 limite_inferior, frequencia_classe, id_frequencia_anterior = 0, 0, 0 for linha in dataset.iterrows(): #print(linha) limite_inferior = linha[1][0] frequencia_classe = linha[1][2] id_frequencia_anterior = linha[0] if linha[1][5] >= fi_2: id_frequencia_anterior -= 1 break limite_inferior, frequencia_classe, id_frequencia_anterior Fi_anterior = dataset.iloc[[id_frequencia_anterior]]['Fi'].values[0] Fi_anterior mediana = limite_inferior + ((fi_2 - Fi_anterior) * 4) / frequencia_classe mediana ###Output _____no_output_____ ###Markdown Função completa ###Code def get_estatisticas(dataframe): media = dataset['fi.xi'].sum() / dataset['fi'].sum() moda = dataset[dataset['fi'] == dataset['fi'].max()]['xi'].values[0] fi_2 = dataset['fi'].sum() / 2 limite_inferior, frequencia_classe, id_frequencia_anterior = 0, 0, 0 for i, linha in enumerate(dataset.iterrows()): limite_inferior = linha[1][0] frequencia_classe = linha[1][2] id_frequencia_anterior = linha[0] if linha[1][5] >= fi_2: id_frequencia_anterior -= 1 break Fi_anterior = dataset.iloc[[id_frequencia_anterior]]['Fi'].values[0] mediana = limite_inferior + ((fi_2 - Fi_anterior) * 4) / frequencia_classe get_estatisticas(dataset) ###Output _____no_output_____ ###Markdown Média geométrica, harmônica e quadrática Média geométrica ###Code from scipy.stats.mstats import gmean gmean(dados) ###Output _____no_output_____ ###Markdown Média harmônica ###Code from scipy.stats.mstats import hmean hmean(dados) ###Output _____no_output_____ ###Markdown Média quadrática ###Code def quadratic_mean(dados): return math.sqrt(sum(n * n for n in dados) / len(dados)) quadratic_mean(dados) ###Output _____no_output_____ ###Markdown Quartis ###Code dados_impar = [150, 151, 152, 152, 153, 154, 155, 155, 155] ###Output _____no_output_____ ###Markdown Cálculo manual ###Code np.median(dados_impar) posicao_mediana = math.floor(len(dados_impar) / 2) posicao_mediana esquerda = dados_impar[0:posicao_mediana] esquerda np.median(esquerda) direita = dados_impar[posicao_mediana + 1:] direita np.median(direita) ###Output _____no_output_____ ###Markdown Bibliotecas Numpy ###Code np.quantile(dados_impar, 0.5) np.quantile(dados_impar, 0.75) np.quantile(dados_impar, 0.25) esquerda2 = dados_impar[0:posicao_mediana + 1] esquerda2 np.median(esquerda2) np.quantile(dados, 0.25), np.quantile(dados, 0.50), np.quantile(dados, 0.75) ###Output _____no_output_____ ###Markdown Scipy ###Code stats.scoreatpercentile(dados, 25), stats.scoreatpercentile(dados, 50), stats.scoreatpercentile(dados, 75) ###Output _____no_output_____ ###Markdown Pandas ###Code import pandas as pd dataset = pd.DataFrame(dados) dataset.head() dataset.quantile([0.25, 0.5, 0.75]) dataset.describe() ###Output _____no_output_____ ###Markdown Quartis com distribuição de frequência ###Code dataset def get_quartil(dataframe, q1 = True): if q1 == True: fi_4 = dataset['fi'].sum() / 4 else: fi_4 = (3 * dataset['fi'].sum()) / 4 limite_inferior, frequencia_classe, id_frequencia_anterior = 0, 0, 0 for linha in dataset.iterrows(): limite_inferior = linha[1][0] frequencia_classe = linha[1][2] id_frequencia_anterior = linha[0] if linha[1][5] >= fi_4: id_frequencia_anterior -= 1 break Fi_anterior = dataset.iloc[[id_frequencia_anterior]]['Fi'].values[0] q = limite_inferior + ((fi_4 - Fi_anterior) * 4) / frequencia_classe return q get_quartil(dados), get_quartil(dados, q1 = False) ###Output _____no_output_____ ###Markdown Percentis ###Code np.median(dados) np.quantile(dados, 0.5) np.percentile(dados, 50) np.percentile(dados, 5), np.percentile(dados, 10), np.percentile(dados, 90) stats.scoreatpercentile(dados, 5), stats.scoreatpercentile(dados, 10), stats.scoreatpercentile(dados, 90) import pandas as pd dataset = pd.DataFrame(dados) dataset.head() dataset.quantile([0.05, 0.10, 0.90]) ###Output _____no_output_____ ###Markdown Exercício ###Code dataset = pd.read_csv('census.csv') dataset.head() dataset['age'].mean() stats.hmean(dataset['age']) from scipy.stats.mstats import gmean gmean(dataset['age']) quadratic_mean(dataset['age']) dataset['age'].median() statistics.mode(dataset['age']) ###Output _____no_output_____ ###Markdown Medidas de dispersão Amplitude total e diferença interquartil ###Code dados dados.max() - dados.min() q1 = np.quantile(dados, 0.25) q3 = np.quantile(dados, 0.75) q1, q3 diferenca_interquartil = q3 - q1 diferenca_interquartil inferior = q1 - (1.5 * diferenca_interquartil) inferior superior = q3 + (1.5 * diferenca_interquartil) superior ###Output _____no_output_____ ###Markdown Variância, desvio padrão e coeficiente de variação ###Code dados_impar = np.array([150, 151, 152, 152, 153, 154, 155, 155, 155]) ###Output _____no_output_____ ###Markdown Cálculo Manual ###Code media = dados_impar.sum() / len(dados_impar) media desvio = abs(dados_impar - media) desvio desvio = desvio ** 2 desvio soma_desvio = desvio.sum() soma_desvio v = soma_desvio / len(dados_impar) v dp = math.sqrt(v) dp cv = (dp / media) * 100 cv def get_variancia_desvio_padrao_coeficiente(dataset): media = dataset.sum() / len(dataset) desvio = abs(dados_impar - media) desvio = desvio ** 2 soma_desvio = desvio.sum() variancia = soma_desvio / len(dados_impar) dp = math.sqrt(variancia) return variancia, dp, (dp / media) * 100 get_variancia_desvio_padrao_coeficiente(dados_impar) ###Output _____no_output_____
NY Taxi Fare.ipynb
###Markdown Competition: https://www.kaggle.com/c/nyc-taxi-trip-duration/overview My learnings: Encoding time as sin and cos functions: https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/ and https://www.kaggle.com/avanwyk/encoding-cyclical-features-for-deep-learning (very good resource) datetime formats in python: http://strftime.org/ ###Code import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import OneHotEncoder from datetime import datetime from sklearn.neighbors import DistanceMetric from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV from sklearn.neural_network import MLPRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error import seaborn as sns from datetime import datetime import warnings warnings.filterwarnings('ignore') # This method creates a subset of the dataset and writes it to train_subset.csv # This is done as the entire data set is too vast original_dataset_csv = "../Datasets/train.csv" subset_dataset_csv = "../Datasets/train_subset.csv" def create_subset_of_dataset(): df = pd.read_csv(original_dataset_csv) print(f"Original shape of dataset: {df.shape}") sample_size = int(df.shape[0] * 0.1) df_subset = df.sample(n=sample_size) print(f"Shape of subset dataset: {df_subset.shape}") df_subset.to_csv(subset_dataset_csv) #print("Now, open the csv file and delete the first (unnamed) column!") create_subset_of_dataset() df = pd.read_csv(subset_dataset_csv) df.head() # Drop the column C0 as it corresponds to the row number from the original csv file df = df.drop(['Unnamed: 0'], axis=1) # Drop the column store_and_fwd_flag as we hypothesize that it will not affect the trip duration df = df.drop(['store_and_fwd_flag'], axis=1) df.describe() print(f"Number of null values in the dataset: {df.isnull().any().sum()}") def one_hot_encoding(column): ohe_enc = OneHotEncoder(sparse=False) ohe_enc.fit(column) result = ohe_enc.transform(column) return result def encode_cyclic_values(data, max_val, col_name): encoded_data = pd.DataFrame() # Sine transformation encoded_data[col_name + '_sin'] = np.sin(2* np.pi * data / max_val) # Cos transformation encoded_data[col_name + '_cos'] = np.cos(2 * np.pi * data / max_val) return encoded_data def label_encode_bearing(bearing_values): # North is between -45.0 and 45.0. Label: 1 bearing_values[np.logical_and(bearing_values>=-45.0, bearing_values<45.0)] = 1.0 # East is between 45.0 and 135.0 Label: 2 bearing_values[np.logical_and(bearing_values>=45.0, bearing_values<135.0)] = 2.0 # South is between -135.0 to -180.0 and 135.0 to 180.0 Label: 3 bearing_values[np.logical_and(bearing_values<-135.0, bearing_values>=-180.0)] = 3.0 bearing_values[np.logical_and(bearing_values>=135.0, bearing_values<=180.0)] = 3.0 # West is between -45.0 and -135.0 Label: 4 bearing_values[np.logical_and(bearing_values<-45.0, bearing_values>=-135.0)] = 4.0 return bearing_values def preprocess_datetime_values(column): # Split the datetime value into date and time components date_time_values = pd.DataFrame() # Split the datetime column into 2 columns: date and time temp = column.str.split(' ') date_time_values['date'] = temp.str[0] date_time_values['time'] = temp.str[1] # Extract the year value from the dates date_time_values['year'] = date_time_values['date'].str.split('-').str[0] # Get day# of the year from the dates and perform sin, cos transformations dates = pd.to_datetime(date_time_values['date']) date_time_values['day_number'] = pd.to_numeric(dates.dt.strftime('%j')) encoded_dates = encode_cyclic_values(date_time_values['day_number'], 366, 'day_number') date_time_values['day_number_sin'] = encoded_dates['day_number_sin'] date_time_values['day_number_cos'] = encoded_dates['day_number_cos'] # Convert time into seconds past midnight and perform sin, cos transformations temp = date_time_values['time'].str.split(':') date_time_values['hour'] = pd.to_numeric(temp.str[0]) date_time_values['minute'] = pd.to_numeric(temp.str[1]) date_time_values['second'] = pd.to_numeric(temp.str[2]) date_time_values['seconds_past_midnight'] = (date_time_values['hour']*3600) + ((date_time_values['minute']*60)) + (date_time_values['second']) encoded_times = encode_cyclic_values(date_time_values['seconds_past_midnight'], 86400, 'time') date_time_values['time_sin'] = encoded_times['time_sin'] date_time_values['time_cos'] = encoded_times['time_cos'] return date_time_values def haversine(pickup_lat, pickup_long, dropoff_lat, dropoff_long): radius_of_earth = 6378.1 # In km lat_delta = dropoff_lat - pickup_lat lon_delta = dropoff_long - pickup_long d = np.sin(lat_delta*0.5)**2 + np.cos(pickup_lat) * np.cos(dropoff_lat) * np.sin(lon_delta*0.5)**2 haversine_values = 2 * radius_of_earth * np.arcsin(np.sqrt(d)) haversine_values = np.reshape(haversine_values, (haversine_values.shape[0],1)) return haversine_values # Get latitude dist with long_delta = 0. Then get lon dist with lat_delta = 0. # Then add both values to get the the manhattan distance wrt to lat & long coordinates. # Reference: https://stackoverflow.com/questions/32923363/manhattan-distance-for-two-geolocations def manhattan_distance(pickup_lat, pickup_long, dropoff_lat, dropoff_long): lat_distance = haversine(pickup_lat, pickup_long, dropoff_lat, pickup_long) long_distance = haversine(pickup_lat, pickup_long, pickup_lat, dropoff_long) man_dist = lat_distance + long_distance return man_dist def bearing(pickup_lat, pickup_long, dropoff_lat, dropoff_long): radius_of_earth = 6378.1 # In km lon_delta = dropoff_long - pickup_long y = np.sin(lon_delta) * np.cos(dropoff_lat) x = np.cos(pickup_lat) * np.sin(dropoff_lat) - np.sin(pickup_lat) * np.cos(dropoff_lat) * np.cos(lon_delta) bearing_values = np.degrees(np.arctan2(y, x)) bearing_values = np.reshape(bearing_values, (bearing_values.shape[0],1)) label_enc_bearing_values = label_encode_bearing(bearing_values) ohe_enc_bearing_values = one_hot_encoding(label_enc_bearing_values) return ohe_enc_bearing_values def preprocess_geospatial_values(data): # Columns after converting df to np array: # 0: pickup_latitude, 1: pickup_longitude, 2: dropoff_latitude, 3: dropoff_longitude data_radians = np.radians(data) # Haversine formula to calculate the distance between the 2 coordinates enc_geospatial_data = haversine(data_radians[:,0], data_radians[:,1], data_radians[:,2], data_radians[:,3]) # Manhattan distance between the pickup and dropoff coordinates man_dist = manhattan_distance(data_radians[:,0], data_radians[:,1], data_radians[:,2], data_radians[:,3]) enc_geospatial_data = np.append(enc_geospatial_data, man_dist, axis=1) # Calculate the bearing (i.e direction) between the coordinates. Then, perform O-H-E. bearing_values = bearing(data_radians[:,0], data_radians[:,1], data_radians[:,2], data_radians[:,3]) enc_geospatial_data = np.append(enc_geospatial_data, bearing_values, axis=1) # Calculate the center-points of the latitudes and longitudes (in degrees) latitude_centers = data[:,2] - data[:,0] longitude_centers = data[:,3] - data[:,1] latitude_centers = np.reshape(latitude_centers, (latitude_centers.shape[0],1)) longitude_centers = np.reshape(longitude_centers, (longitude_centers.shape[0],1)) enc_geospatial_data = np.append(enc_geospatial_data, latitude_centers, axis=1) enc_geospatial_data = np.append(enc_geospatial_data, longitude_centers,axis=1) return enc_geospatial_data def remove_spurious_data(raw_data): # Decided on a threshold time of 20000 seconds for a trip after analysing the dataset threshold_of_trip_time = 20000 # Remove records with null values from the dataset print(f"Number of null values in the dataset: {raw_data.isnull().any().sum()}") raw_data = raw_data[raw_data.notnull()] # Remove records with trip times greater than the given threshold raw_data = raw_data[raw_data.trip_duration < 20000] return raw_data def preprocess_data(raw_data): # Add the id column without any pre-processing clean_data = np.array(raw_data['id']) clean_data = np.reshape(clean_data, (clean_data.shape[0],1)) # One-hot-encode the vendor_id column vendor_id_raw = np.array(raw_data['vendor_id']) vendor_id_raw = np.reshape(vendor_id_raw, (vendor_id_raw.shape[0],1)) vendor_id_clean = one_hot_encoding(vendor_id_raw) clean_data = np.append(clean_data, vendor_id_clean, axis=1) # For pickup_datetime column, split the datetime field and: # i. Retain year as a seperate feature # ii. Combine month and date to get day# and perform sine & cos encoding on it # iii. Convert time to seconds_past_midnight and perform sine & cos encoding on it pickup_datetime_split = preprocess_datetime_values(raw_data['pickup_datetime']) # Add year column after O-H-E year_values = np.array(pickup_datetime_split['year']) year_values = np.reshape(year_values, (year_values.shape[0],1)) year_values_OHE = one_hot_encoding(year_values) clean_data = np.append(clean_data, year_values_OHE, axis=1) # Add day_number_sin column day_number_sin = np.array(pickup_datetime_split['day_number_sin']) day_number_sin = np.reshape(day_number_sin, (day_number_sin.shape[0],1)) clean_data = np.append(clean_data, day_number_sin, axis=1) # Add day_number_cos column day_number_cos = np.array(pickup_datetime_split['day_number_cos']) day_number_cos = np.reshape(day_number_cos, (day_number_cos.shape[0],1)) clean_data = np.append(clean_data, day_number_cos, axis=1) # Add time_sin column pickup_time_sine = np.array(pickup_datetime_split['time_sin']) pickup_time_sine = np.reshape(pickup_time_sine, (pickup_time_sine.shape[0],1)) clean_data = np.append(clean_data, pickup_time_sine,axis=1) # Add time_cos column pickup_time_cos = np.array(pickup_datetime_split['time_cos']) pickup_time_cos = np.reshape(pickup_time_cos, (pickup_time_cos.shape[0],1)) clean_data = np.append(clean_data, pickup_time_cos, axis=1) # For dropoff_datetime column, split the datetime field and # perform the same actions as performed on pickup_datetime dropoff_datetime_split = preprocess_datetime_values(raw_data['dropoff_datetime']) # Add year column after O-H-E year_values = np.array(dropoff_datetime_split['year']) year_values = np.reshape(year_values, (year_values.shape[0],1)) year_values_OHE = one_hot_encoding(year_values) clean_data = np.append(clean_data, year_values_OHE, axis=1) # Add day_number_sin column day_number_sin = np.array(dropoff_datetime_split['day_number_sin']) day_number_sin = np.reshape(day_number_sin, (day_number_sin.shape[0],1)) clean_data = np.append(clean_data, day_number_sin, axis=1) # Add day_number_cos column day_number_cos = np.array(dropoff_datetime_split['day_number_cos']) day_number_cos = np.reshape(day_number_cos, (day_number_cos.shape[0],1)) clean_data = np.append(clean_data, day_number_cos, axis=1) # Add time_sin column dropoff_time_sine = np.array(dropoff_datetime_split['time_sin']) dropoff_time_sine = np.reshape(dropoff_time_sine, (dropoff_time_sine.shape[0],1)) clean_data = np.append(clean_data, dropoff_time_sine,axis=1) # Add time_cos column dropoff_time_cos = np.array(dropoff_datetime_split['time_cos']) dropoff_time_cos = np.reshape(dropoff_time_cos, (dropoff_time_cos.shape[0],1)) clean_data = np.append(clean_data, dropoff_time_cos, axis=1) # Add passenger_count column without any preprocessing passenger_count = np.array(raw_data['passenger_count']) passenger_count = np.reshape(passenger_count, (passenger_count.shape[0],1)) clean_data = np.append(clean_data, passenger_count, axis=1) # To encode geo-spatial data, the following techniques have been used: # i. Haversine formula: https://plus.maths.org/content/lost-lovely-haversine # ii. Manhattan distance: https://xlinux.nist.gov/dads/HTML/manhattanDistance.html # iii. Bearing: https://www.igismap.com/formula-to-find-bearing-or-heading-angle-between-two-points-latitude-longitude/ # iv. Center lat and long b/w pickup and dropoff points # Reference: https://mlwhiz.com/blog/2017/09/14/kaggle_tricks/ raw_geospatial_data = np.array(raw_data[['pickup_latitude', 'pickup_longitude', 'dropoff_latitude', 'dropoff_longitude']]) encoded_geospatial_data = preprocess_geospatial_values(raw_geospatial_data) clean_data = np.append(clean_data, encoded_geospatial_data, axis=1) # Add the trip_duration column as it is, without any preprocessing. This is the label. labels_column = np.array(raw_data['trip_duration']) labels_column = np.reshape(labels_column, (labels_column.shape[0],1)) clean_data = np.append(clean_data, labels_column, axis=1) return clean_data # Distribution of trip durations duration = [df['trip_duration'].values] f, axes = plt.subplots(1,2, figsize=(16,4), sharex=True) sns.despine(left=True) sns.distplot(duration, ax=axes[0]) sns.boxplot(duration, ax=axes[1]) # The data has been preprocessed print(df.shape) df2 = remove_spurious_data(df) print(df2.shape) clean_data = preprocess_data(df2) print(clean_data[0]) print(np.unique(clean_data[:,3])) # Split into data and labels data = clean_data[:,:-1] labels = clean_data[:,-1] # Split the data into train and validation datasets X_train, X_val, y_train, y_val = train_test_split(data, labels, test_size=0.2, random_state=42) # Use cross validation to find a model that gives the least error (using mean absolute error) # Linear Regression on the model lin_reg_cv_score = cross_val_score(LinearRegression(), data[:,1:], labels, scoring="neg_mean_squared_error", cv=10, n_jobs=-1) print(f"Mean absolute error with Linear Regression is: {lin_reg_cv_score}\n") # MLP on the model mlp_cv_score = cross_val_score(MLPRegressor(), data[:,1:], labels, scoring='neg_mean_squared_error', cv=10, n_jobs=-1) print(f"Mean absolute error for MLP is: {mlp_cv_score}\n") # Decision Tree Regressor tree_reg_cv_score = cross_val_score(DecisionTreeRegressor(), data[:,1:], labels, scoring="neg_mean_squared_error", cv=10, n_jobs=-1) print(f"Mean absolute error with Decision Tree Regressor is: {tree_reg_cv_score}\n") # Random Forest Regressor forest_reg_cv_score = cross_val_score(RandomForestRegressor(), data[:,1:], labels, scoring="neg_mean_squared_error", cv=10, n_jobs=-1) print(f"Mean absolute error with Random Forest Regressor is: {forest_reg_cv_score}") plt.plot(lin_reg_cv_score, 'y') plt.plot(mlp_cv_score, 'r') plt.plot(tree_reg_cv_score, 'g') plt.plot(forest_reg_cv_score, 'c') ###Output _____no_output_____ ###Markdown As seen from the above error graph, MLP (red) and Random Forest Regressor (cyan) give the least error (RMSE). Comparing the errors between them: ###Code # Compare error plt.plot(mlp_cv_score) plt.plot(forest_reg_cv_score) forest_count = 0; mlp_count = 0 for forest,mlp in zip(mlp_cv_score, forest_reg_cv_score): if forest > mlp: mlp_count += 1 else: forest_count += 1 print(f"Number of times Random Forest gave lesser error than MLP: {forest_count}") print(f"Number of times MLP gave lesser error than Random Forest: {mlp_count}") ###Output Number of times Random Forest gave lesser error than MLP: 6 Number of times MLP gave lesser error than Random Forest: 4 ###Markdown We see that RF performs better than MLP, but only just. Hence, let's choose both models and see the results of making an ensemble out of them. ###Code # Since Random Forest Regressor gives the lowest error among all models, we will use # GridSearchCV to tune the hyper-parameters for RF Regressor and minimize the error print(datetime.now()) rf_parameters = {'n_estimators':[10,50,100,200,500,750], 'criterion':['mse','mae'], 'max_depth':[20,50,100,None], 'min_samples_leaf':[2,5,10,20]} rf_gsc = GridSearchCV(RandomForestRegressor(), param_grid=rf_parameters, scoring="neg_mean_squared_error", cv=5, n_jobs=-1) grid_search_result = rf_gsc.fit(X_train[:1000,1:],y_train[:1000]) print(f"The best set of hyper-parameters are: {grid_search_result.best_params_}") print(datetime.now()) ###Output 2019-06-20 23:00:08.266957
3 convolutional-neural-networks/2 conv-visualization/1 custom_filters.ipynb
###Markdown Creating a Filter, Edge Detection Import resources and display image ###Code import matplotlib.pyplot as plt import matplotlib.image as mpimg import cv2 import numpy as np %matplotlib inline # Read in the image image = mpimg.imread('data/curved_lane.jpg') plt.imshow(image) ###Output _____no_output_____ ###Markdown Convert the image to grayscale ###Code # Convert to grayscale for filtering gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) plt.imshow(gray, cmap='gray') ###Output _____no_output_____ ###Markdown TODO: Create a custom kernelBelow, you've been given one common type of edge detection filter: a Sobel operator.The Sobel filter is very commonly used in edge detection and in finding patterns in intensity in an image. Applying a Sobel filter to an image is a way of **taking (an approximation) of the derivative of the image** in the x or y direction, separately. The operators look as follows.**It's up to you to create a Sobel x operator and apply it to the given image.**For a challenge, see if you can put the image through a series of filters: first one that blurs the image (takes an average of pixels), and then one that detects the edges. ###Code # Create a custom kernel # 3x3 array for edge detection sobel_y = np.array([[ -1, -2, -1], [ 0, 0, 0], [ 1, 2, 1]]) # Filter the image using filter2D, which has inputs: (grayscale image, bit-depth, kernel) filtered_image = cv2.filter2D(gray, -1, sobel_y) plt.imshow(filtered_image, cmap='gray') ###Output _____no_output_____
notebook/Unit1-2-Control_Flow.ipynb
###Markdown Control Flow * if, while,for, * break continue* Indentation* Coding StylesIn the programs we have seen till now, there has always been `a series of statements` faithfully executed by Python in `exact top-down order`.What if you wanted to change `the flow of how it works?` For example, you want the program to take some decisions and do differentthings depending on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of the day?As you might have guessed, this is achieved using` control flow statements`. There are **three** control flow statements in **Python(<=3.9)** * if , for , while>[Python >=3.10: **match** Statements](https://docs.python.org/3/tutorial/controlflow.htmlmatch-statements)>```python>match status:> case 400:> return "Bad request"> case 404:> return "Not found"> case 418:> return "I'm a teapot"> case _:> return "Something's wrong with the Internet>``` 1 Branching Programs: `if`Branching programs are more interesting. The simplest branching statement is a conditional. As shown in the boxed-in part of the folloewing Figure![if-else](./img/if-else.jpg)The conditional statement has three parts:* `a test`, an expression that evaluates to either True or False;* `a block of code` that is executed if the test evaluates to `True`; * `an optional block of code` that is executed if the test evaluates to `False`.After a conditional statement is executed, execution resumes at the code following the statement.In Python, a conditional statement has the form* The colon (:) ends the `if expression/else` ```pythonif Boolean expression: block of codeelse: block of code```or ```pythonif Boolean expression: block of code``` ###Code x=25 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') ###Output _____no_output_____ ###Markdown Indentation Most other programming languages use some sort of **bracketing symbols** to delineate blocks of code, e.g.,* C encloses blocks in braces, { }.```cppif(boolean_expression){ // block of code int i=1; double f=2 }else{ block of code}``` Python is `unusual` in using indentation this way: * Indentation is semantically meaningful in Python: delineate blocks of code An advantage of the Python approach is that it ensures that the * **visual structure** of a program is an **accurate** representation of the **semantic structure** of that program.![block](./img/python-block.jpg) **1 Improper indent: `Syntax` error** ###Code x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) ###Output _____no_output_____ ###Markdown **2 Improper indentation: `Semantic` error** ###Code x=10 if x > 20:rongy x =11/x x +=10 # x add 10 only >20 print(x) x=10 if x > 20: x=12/34 x+=23 print(x) ###Output _____no_output_____ ###Markdown Nested conditionalsWhen either the true block or the false block of a conditional contains `another` conditional, the conditional statements are said to be **nested**. In the code below, there are nested conditionals in both branches of the top-level `if` statement ###Code #x=2*3*7 #x=2*7 x=3*7 # the conditional statements are nested. if x % 2 == 0: if x % 3 == 0: print('Divisible by 2 and 3') else: print('Divisible by 2 and not by 3') elif x % 3 == 0: # elif : else if print('Divisible by 3 and not by 2') ###Output _____no_output_____ ###Markdown **NOTE:** The `elif` in the above code stands for `else if`. It is often convenient to use `a compound Boolean expression` in the test of a conditional, for example, ###Code x=1 y=10 z=87 if x < y and x < z: # compound Boolean expressions print('x is least') elif y < z: print('y is least') else: print('z is least') ###Output _____no_output_____ ###Markdown 2 The while loop**Conditional Iteration:The while loop**When we want a program to do the same thing many times, we can use iterationA generic iteration (also called looping) mechanism is shown in the boxed-in part of the following. ![while](./img/while.jpg)Like a conditional statement, it begins with a test. If the test evaluates to True, the program executes the loop body once, and then goes back to reevaluate the test. This process is repeated until the test evaluates to False, after which control passes to the code following the iteration statement.```pythoninitial value !!!while Boolean expression: block of code``` ###Code n = 5 while n > 0: n -= 1 print(n) str1="Python" while str1: print() ###Output _____no_output_____ ###Markdown Line Continuation. ```pythonprint(str(x) + '*' + str(x) + ' = ' + str(ans))```* Python's `implicit` line joining inside `parentheses(), brackets[] and braces{}`.* `\` continuation. A Implicit line joining * inside `parentheses(), brackets[] and braces{}` ###Code a =( '1' + '2' + '3' + '4' + '5' + '6' ) a a=['1' + '2' + '3' + '4' + '5' + '6' ] a a={'1' + '2' + '3' + '4' + '5' + '6' } a ###Output _____no_output_____ ###Markdown B “\” continuation ###Code a = '1' + '2' + '3' + '4' + '5' +'6' a a = '1' + '2' + '3' + \ '4' + '5' + '6' a ###Output _____no_output_____ ###Markdown C Syntax error caused by Implicit line continuation **without end*** [Problem and Solution:报没有错误语句的“SyntaxError"](https://gitee.com/thermalogic/home/blob/B2021/guide/doc/Problem_Solution.md%E6%8A%A5%E6%B2%A1%E6%9C%89%E9%94%99%E8%AF%AF%E8%AF%AD%E5%8F%A5%E7%9A%84syntaxerror) ###Code multilines=((1+2)+2+1+2++2+1+2++2+1+2++ nextline=3+4 ###Output _____no_output_____ ###Markdown 3 For LoopsPython provides a language mechanism, the for loop,that can be used to simplify programs containing this kind of iteration: Each iterates over a sequence of integers.The general form of a for statement is :```pythonfor variable in sequence: code block``` 3.1 Iterate over characters of a stringThe `for` statement can be used in conjunction with the in operator to conveniently `iterate over characters of a string`. For example, ###Code for s in "abcgdg": s=4*s print(s) ###Output _____no_output_____ ###Markdown sums the digits in the string denoted by the literal `'12345678`' and prints the total ###Code total = 0 for char in '123456789': total = total + int(char) print(total) ###Output _____no_output_____ ###Markdown 3.2 Range typehttps://docs.python.org/3/library/stdtypes.htmlrangesThe range type represents `an immutable sequence of numbers` and is commonly used for looping a specific number of times in `for loops.`The `range` type may takes one,two or three integer arguments: ```pythonrange(stop)range(start, stop)range(start, stop[, step])```* start: The value of the start parameter (or 0 if the parameter was not supplied)* stop: The value of the stop parameter* step: The value of the step parameter (or 1 if the parameter was not supplied) * If `start` is omitted it defaults to 0, * If `step` is omitted it defaults to 1.```python range(4)-> range(0, 4)->range(0, 4,1) ->[0, 1, 2,3]``````python range(4,10)-> range(4,10,1)->[4 5 6 7 8 9] ``` ###Code print("range(4)") for i in range(4): print(i) print("\nrange(4,10)") for i in range(4,10): print(i) ###Output _____no_output_____ ###Markdown **`range(start,stop,step)`*** It produces the progression `start, start + step, start + 2*step`, etc.```pythonrange(5,40,10) -> [5,15,25,35]```* If step is `negative`, the last element is the smallest integer `start + i*step` greater than stop.```pythonrange(40,5,-10)-> [40,30,20,10]``` ###Code print("range(5,40,10)") for i in range(5,40,10): print(i) print("\nrange(40,5,-10)") for i in range(40,5,-10): print(i) ###Output _____no_output_____ ###Markdown 4 `break` and `continue` ![c-b](./img/continue-break.jpg) 4.1 The `break`The `break` statement is used to **break out** of a `loop` statement * stop the execution of a looping statement, * even if the loop condition has not become False * or the sequence of items has not been completely iterated over. **stop the execution of a looping statement even if the loop condition has not become False** ###Code n = 5 while n > 0: n -= 1 if n == 2: break print(n) ###Output _____no_output_____ ###Markdown **stop the sequence of items has not been completely iterated over** ###Code for n in range(5,1,-1): n -= 1 if n == 2: break print(n) ###Output _____no_output_____ ###Markdown 4.2 The `continue` The `continue` statement is used to tell Python to * **skip** the **rest** of the statements in the current loop block and to continue to the **next iteration** of the loop. ###Code n = 5 while n > 0: n -= 1 if n == 2: continue print(n) print('Loop ended') for n in range(5,1,-1): n -= 1 if n == 2: continue print(n) ###Output _____no_output_____ ###Markdown 5 pass StatementThe `pass` statement is a null operation; nothing happens when it executes. It is used as a **placeholder** when a statement is required **syntactically**. * **your code will eventually go, but has not been written yet** * **no code needs to be executed****your code will eventually go, but has not been written yet** ###Code x=25 if x % 2 == 0: print('Even') print(x) print(x%2) else: pass #print('Odd') ###Output _____no_output_____ ###Markdown >**the placeholder in C/C++** > >* empty block`{}` or empty line `;`>>```cpp>if (/* some condition */)>{ > }>else>{ > }>> >if (/* some condition */)> ;>else> ;>``` 6 Coding StylesPython Developer's Guide,Coding Styleshttps://www.python.org/dev/**PEP**:Python Enhancement Proposals 6.1 The Zen of Python ,PEP20 (Python Enhancement Proposals)https://www.python.org/dev/peps/pep-0020/ ###Code # Easter Egg import this ###Output _____no_output_____ ###Markdown Control Flow * if, while, for, * break continue* Indentation* Coding StylesIn the programs we have seen till now, there has always been `a series of statements` faithfully executed by Python in `exact top-down order`.What if you wanted to change `the flow of how it works?` For example, you want the program to take some decisions and do differentthings depending on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of the day?As you might have guessed, this is achieved using` control flow statements`. There are **three** control flow statements in **Python(<=3.9)** * if , for , while>[Python >=3.10: **match** Statements](https://docs.python.org/3/tutorial/controlflow.htmlmatch-statements)>```python>match status:> case 400:> return "Bad request"> case 404:> return "Not found"> case 418:> return "I'm a teapot"> case _:> return "Something's wrong with the Internet>``` 1 Branching Programs: `if`Branching programs are more interesting. The simplest branching statement is a conditional. As shown in the boxed-in part of the folloewing Figure![if-else](./img/if-else.jpg)The conditional statement has three parts:* `a test`, an expression that evaluates to either True or False;* `a block of code` that is executed if the test evaluates to `True`; * `an optional block of code` that is executed if the test evaluates to `False`.After a conditional statement is executed, execution resumes at the code following the statement.In Python, a conditional statement has the form* The colon (:) ends the `if expression/else` ```pythonif Boolean expression: block of codeelse: block of code```or ```pythonif Boolean expression: block of code``` ###Code x=25 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') print(x) ###Output _____no_output_____ ###Markdown Indentation Most other programming languages use some sort of **bracketing symbols** to delineate blocks of code, e.g.,* C encloses blocks in braces, { }.```cppif(boolean_expression){ // block of code int i=1; double f=2 }else{ block of code}``` Python is `unusual` in using indentation this way: * Indentation is semantically meaningful in Python: delineate blocks of code An advantage of the Python approach is that it ensures that the * **visual structure** of a program is an **accurate** representation of the **semantic structure** of that program.![block](./img/python-block.jpg) **1 Improper indent: `Syntax` error** ###Code x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) ###Output _____no_output_____ ###Markdown **2 Improper indentation: `Semantic` error** ###Code x=10 if x > 20: x =11/x x +=10 # x add 10 only >20 print(x) x=10 if x > 20: x=12/34 x+=23 print(x) ###Output _____no_output_____ ###Markdown Nested conditionalsWhen either the true block or the false block of a conditional contains `another` conditional, the conditional statements are said to be **nested**. In the code below, there are nested conditionals in both branches of the top-level `if` statement ###Code #x=2*3*7 #x=2*7 x=3*7 # the conditional statements are nested. if x % 2 == 0: if x % 3 == 0: print('Divisible by 2 and 3') else: print('Divisible by 2 and not by 3') elif x % 3 == 0: # elif : else if print('Divisible by 3 and not by 2') ###Output _____no_output_____ ###Markdown **NOTE:** The `elif` in the above code stands for `else if`. It is often convenient to use `a compound Boolean expression` in the test of a conditional, for example, ###Code x=1 y=10 z=87 if x < y and x < z: # compound Boolean expressions print('x is least') elif y < z: print('y is least') else: print('z is least') ###Output _____no_output_____ ###Markdown 2 The while loop**Conditional Iteration:The while loop**When we want a program to do the same thing many times, we can use iterationA generic iteration (also called looping) mechanism is shown in the boxed-in part of the following. ![while](./img/while.jpg)Like a conditional statement, it begins with a test. If the test evaluates to True, the program executes the loop body once, and then goes back to reevaluate the test. This process is repeated until the test evaluates to False, after which control passes to the code following the iteration statement.```pythoninitial value !!!while Boolean expression: block of code``` ###Code n = 5 while n > 0: n -= 1 print(n) str1="Python" while str1: print() ###Output _____no_output_____ ###Markdown Line Continuation. ```pythonprint('n' = ,n)```* Python's `implicit` line joining inside `parentheses(), brackets[] and braces{}`.* `\` continuation. A Implicit line joining * inside `parentheses(), brackets[] and braces{}` ###Code a =( '1' + '2' + '3' + '4' + '5' + '6' ) a a=['1' + '2' + '3' + '4' + '5' + '6' ] a a={'1' + '2' + '3' + '4' + '5' + '6' } a ###Output _____no_output_____ ###Markdown B “\” continuation ###Code a = '1' + '2' + '3' + '4' + '5' +'6' a a = '1' + '2' + '3' + \ '4' + '5' + '6' a ###Output _____no_output_____ ###Markdown C Syntax error caused by Implicit line continuation **without end*** [Problem and Solution:报没有错误语句的“SyntaxError"](https://gitee.com/thermalogic/sees/blob/B2022/guide/doc/Problem_Solution.md%E6%8A%A5%E6%B2%A1%E6%9C%89%E9%94%99%E8%AF%AF%E8%AF%AD%E5%8F%A5%E7%9A%84syntaxerror) ###Code multilines=((1+2)+2+1+2++2+1+2++2+1+2++ nextline=3+4 ###Output _____no_output_____ ###Markdown 3 For LoopsPython provides a language mechanism, the for loop,that can be used to simplify programs containing this kind of iteration:Each iterates over a **sequence**.The general form of a for statement is :```pythonfor variable in sequence: code block``` 3.1 Iterate over characters of a stringThe `for` statement can be used in conjunction with the in operator to conveniently `iterate over characters of a string`.For example, ###Code for s in "abcgdg": s=4*s print(s) ###Output aaaa bbbb cccc gggg dddd gggg ###Markdown sums the digits in the string denoted by the literal `'12345678`' and prints the total ###Code total = 0 for char in '123456789': total = total + int(char) print(total) ###Output 45 ###Markdown 3.2 Range typehttps://docs.python.org/3/library/stdtypes.htmlrangesThe range type represents `an immutable sequence of numbers` and is commonly used for looping a specific number of times in `for loops.`The `range` type may takes one,two or three integer arguments: ```pythonrange(stop)range(start, stop)range(start, stop[, step])```* start: The value of the start parameter (or 0 if the parameter was not supplied)* stop: The value of the stop parameter* step: The value of the step parameter (or 1 if the parameter was not supplied) * If `start` is omitted it defaults to 0, * If `step` is omitted it defaults to 1.```python range(4)-> range(0, 4)->range(0, 4,1) ->[0, 1, 2,3]``````python range(4,10)-> range(4,10,1)->[4 5 6 7 8 9] ``` ###Code print("range(4)") for i in range(4): print(i) print("\nrange(4,10)") for i in range(4,10): print(i) ###Output range(4,10) 4 5 6 7 8 9 ###Markdown **`range(start,stop,step)`*** It produces the progression `start, start + step, start + 2*step`, etc.```pythonrange(5,40,10) -> [5,15,25,35]```* If step is `negative`, the last element is the smallest integer `start + i*step` greater than stop.```pythonrange(40,5,-10)-> [40,30,20,10]``` ###Code print("range(5,40,10)") for i in range(5,40,10): print(i) print("\nrange(40,5,-10)") for i in range(40,5,-10): print(i) ###Output range(40,5,-10) 40 30 20 10 ###Markdown 4 `break` and `continue` ![c-b](./img/continue-break.jpg) 4.1 The `break`The `break` statement is used to **break out** of a `loop` statement * stop the execution of a looping statement, * even if the loop condition has not become False * or the sequence of items has not been completely iterated over. **stop the execution of a looping statement even if the loop condition has not become False** ###Code n = 5 while n > 0: n -= 1 if n == 2: break print(n) ###Output 4 3 ###Markdown **stop the sequence of items has not been completely iterated over** ###Code for n in range(5,1,-1): n -= 1 if n == 2: break print(n) ###Output 4 3 ###Markdown 4.2 The `continue` The `continue` statement is used to tell Python to * **skip** the **rest** of the statements in the current loop block and to continue to the **next iteration** of the loop. ###Code n = 5 while n > 0: n -= 1 if n == 2: continue print(n) print('Loop ended') for n in range(5,1,-1): n -= 1 if n == 2: continue print(n) ###Output 4 3 1 ###Markdown 5 pass StatementThe `pass` statement is a null operation; nothing happens when it executes. It is used as a **placeholder** when a statement is required **syntactically**. * **your code will eventually go, but has not been written yet** * **no code needs to be executed****your code will eventually go, but has not been written yet** ###Code x=25 if x % 2 == 0: print('Even') print(x) print(x%2) else: pass #print('Odd') ###Output _____no_output_____ ###Markdown >**the placeholder in C/C++** > >* empty block`{}` or empty line `;`>>```cpp>if (/* some condition */)>{ > }>else>{ > }>> >if (/* some condition */)> ;>else> ;>``` 6 Coding StylesPython Developer's Guide,Coding Styleshttps://www.python.org/dev/**PEP**:Python Enhancement Proposals 6.1 The Zen of Python ,PEP20 (Python Enhancement Proposals)https://www.python.org/dev/peps/pep-0020/ ###Code # Easter Egg import this ###Output The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ###Markdown Control Flow * if, while, for, * break continue* Indentation* Coding StylesIn the programs we have seen till now, there has always been `a series of statements` faithfully executed by Python in `exact top-down order`.What if you wanted to change `the flow of how it works?` For example, you want the program to take some decisions and do differentthings depending on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of the day?As you might have guessed, this is achieved using` control flow statements`. There are **three** control flow statements in **Python(<=3.9)** * if , for , while>[Python >=3.10: **match** Statements](https://docs.python.org/3/tutorial/controlflow.htmlmatch-statements)>```python>match status:> case 400:> return "Bad request"> case 404:> return "Not found"> case 418:> return "I'm a teapot"> case _:> return "Something's wrong with the Internet>``` 1 Branching Programs: `if`Branching programs are more interesting. The simplest branching statement is a conditional. As shown in the boxed-in part of the folloewing Figure![if-else](./img/if-else.jpg)The conditional statement has three parts:* `a test`, an expression that evaluates to either True or False;* `a block of code` that is executed if the test evaluates to `True`; * `an optional block of code` that is executed if the test evaluates to `False`.After a conditional statement is executed, execution resumes at the code following the statement.In Python, a conditional statement has the form* The colon (:) ends the `if expression/else` ```pythonif Boolean expression: block of codeelse: block of code```or ```pythonif Boolean expression: block of code``` ###Code x=25 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') print(x) ###Output _____no_output_____ ###Markdown Indentation Most other programming languages use some sort of **bracketing symbols** to delineate blocks of code, e.g.,* C encloses blocks in braces, { }.```cppif(boolean_expression){ // block of code int i=1; double f=2 }else{ block of code}``` Python is `unusual` in using indentation this way: * Indentation is semantically meaningful in Python: delineate blocks of code An advantage of the Python approach is that it ensures that the * **visual structure** of a program is an **accurate** representation of the **semantic structure** of that program.![block](./img/python-block.jpg) **1 Improper indent: `Syntax` error** ###Code x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) ###Output _____no_output_____ ###Markdown **2 Improper indentation: `Semantic` error** ###Code x=10 if x > 20: x =11/x x +=10 # x add 10 only >20 print(x) x=10 if x > 20: x=12/34 x+=23 print(x) ###Output _____no_output_____ ###Markdown Nested conditionalsWhen either the true block or the false block of a conditional contains `another` conditional, the conditional statements are said to be **nested**. In the code below, there are nested conditionals in both branches of the top-level `if` statement ###Code #x=2*3*7 #x=2*7 x=3*7 # the conditional statements are nested. if x % 2 == 0: if x % 3 == 0: print('Divisible by 2 and 3') else: print('Divisible by 2 and not by 3') elif x % 3 == 0: # elif : else if print('Divisible by 3 and not by 2') ###Output _____no_output_____ ###Markdown **NOTE:** The `elif` in the above code stands for `else if`. It is often convenient to use `a compound Boolean expression` in the test of a conditional, for example, ###Code x=1 y=10 z=87 if x < y and x < z: # compound Boolean expressions print('x is least') elif y < z: print('y is least') else: print('z is least') ###Output _____no_output_____ ###Markdown 2 The while loop**Conditional Iteration:The while loop**When we want a program to do the same thing many times, we can use iterationA generic iteration (also called looping) mechanism is shown in the boxed-in part of the following. ![while](./img/while.jpg)Like a conditional statement, it begins with a test. If the test evaluates to True, the program executes the loop body once, and then goes back to reevaluate the test. This process is repeated until the test evaluates to False, after which control passes to the code following the iteration statement.```pythoninitial value !!!while Boolean expression: block of code``` ###Code n = 5 while n > 0: n -= 1 print(n) str1="Python" while str1: print() ###Output _____no_output_____ ###Markdown Line Continuation. ```pythonprint('n' = ,n)```* Python's `implicit` line joining inside `parentheses(), brackets[] and braces{}`.* `\` continuation. A Implicit line joining * inside `parentheses(), brackets[] and braces{}` ###Code a =( '1' + '2' + '3' + '4' + '5' + '6' ) a a=['1' + '2' + '3' + '4' + '5' + '6' ] a a={'1' + '2' + '3' + '4' + '5' + '6' } a ###Output _____no_output_____ ###Markdown B “\” continuation ###Code a = '1' + '2' + '3' + '4' + '5' +'6' a a = '1' + '2' + '3' + \ '4' + '5' + '6' a ###Output _____no_output_____ ###Markdown C Syntax error caused by Implicit line continuation **without end*** [Problem and Solution:报没有错误语句的“SyntaxError"](https://gitee.com/thermalogic/sees/blob/B2022/guide/doc/Problem_Solution.md%E6%8A%A5%E6%B2%A1%E6%9C%89%E9%94%99%E8%AF%AF%E8%AF%AD%E5%8F%A5%E7%9A%84syntaxerror) ###Code multilines=((1+2)+2+1+2++2+1+2++2+1+2++ nextline=3+4 ###Output _____no_output_____ ###Markdown 3 For LoopsPython provides a language mechanism, the for loop,that can be used to simplify programs containing this kind of iteration:Each iterates over a **sequence**.The general form of a for statement is :```pythonfor variable in sequence: code block``` 3.1 Iterate over characters of a stringThe `for` statement can be used in conjunction with the in operator to conveniently `iterate over characters of a string`.For example, ###Code for s in "abcgdg": s=4*s print(s) ###Output _____no_output_____ ###Markdown sums the digits in the string denoted by the literal `'12345678`' and prints the total ###Code total = 0 for char in '123456789': total = total + int(char) print(total) ###Output _____no_output_____ ###Markdown 3.2 Range typehttps://docs.python.org/3/library/stdtypes.htmlrangesThe range type represents `an immutable sequence of numbers` and is commonly used for looping a specific number of times in `for loops.`The `range` type may takes one,two or three integer arguments: ```pythonrange(stop)range(start, stop)range(start, stop[, step])```* start: The value of the start parameter (or 0 if the parameter was not supplied)* stop: The value of the stop parameter* step: The value of the step parameter (or 1 if the parameter was not supplied) * If `start` is omitted it defaults to 0, * If `step` is omitted it defaults to 1.```python range(4)-> range(0, 4)->range(0, 4,1) ->[0, 1, 2,3]``````python range(4,10)-> range(4,10,1)->[4 5 6 7 8 9] ``` ###Code print("range(4)") for i in range(4): print(i) print("\nrange(4,10)") for i in range(4,10): print(i) ###Output _____no_output_____ ###Markdown **`range(start,stop,step)`*** It produces the progression `start, start + step, start + 2*step`, etc.```pythonrange(5,40,10) -> [5,15,25,35]```* If step is `negative`, the last element is the smallest integer `start + i*step` greater than stop.```pythonrange(40,5,-10)-> [40,30,20,10]``` ###Code print("range(5,40,10)") for i in range(5,40,10): print(i) print("\nrange(40,5,-10)") for i in range(40,5,-10): print(i) ###Output _____no_output_____ ###Markdown 4 `break` and `continue` ![c-b](./img/continue-break.jpg) 4.1 The `break`The `break` statement is used to **break out** of a `loop` statement * stop the execution of a looping statement, * even if the loop condition has not become False * or the sequence of items has not been completely iterated over. **stop the execution of a looping statement even if the loop condition has not become False** ###Code n = 5 while n > 0: n -= 1 if n == 2: break print(n) ###Output _____no_output_____ ###Markdown **stop the sequence of items has not been completely iterated over** ###Code for n in range(5,1,-1): n -= 1 if n == 2: break print(n) ###Output _____no_output_____ ###Markdown 4.2 The `continue` The `continue` statement is used to tell Python to * **skip** the **rest** of the statements in the current loop block and to continue to the **next iteration** of the loop. ###Code n = 5 while n > 0: n -= 1 if n == 2: continue print(n) print('Loop ended') for n in range(5,1,-1): n -= 1 if n == 2: continue print(n) ###Output _____no_output_____ ###Markdown 5 pass StatementThe `pass` statement is a null operation; nothing happens when it executes. It is used as a **placeholder** when a statement is required **syntactically**. * **your code will eventually go, but has not been written yet** * **no code needs to be executed****your code will eventually go, but has not been written yet** ###Code x=25 if x % 2 == 0: print('Even') print(x) print(x%2) else: pass #print('Odd') ###Output _____no_output_____ ###Markdown >**The placeholder in C/C++**>>* empty block`{}` or >* empty line `;`>>```cpp>if (/* some condition */)>{ > }>else>{ > }>> >if (/* some condition */)> ;>else> ;>``` 6 Coding StylesPython Developer's Guide,Coding Styleshttps://www.python.org/dev/**PEP**:Python Enhancement Proposals 6.1 The Zen of Python ,PEP20 (Python Enhancement Proposals)https://www.python.org/dev/peps/pep-0020/ ###Code # Easter Egg import this ###Output _____no_output_____ ###Markdown Control Flow * if, while,for,break continue* Indentation* Coding StylesIn the programs we have seen till now, there has always been `a series of statements` faithfully executed by Python in `exact top-down order`.What if you wanted to change `the flow of how it works?` For example, you want the program to take some decisions and do differentthings depending on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of the day?As you might have guessed, this is achieved using` control flow statements`. There are three control flow statements in Python - `if , for and while` . 1 Branching Programs: `if`Branching programs are more interesting. The simplest branching statement is a conditional. As shown in the boxed-in part of the folloewing Figure 2.3, a conditional statement has three parts:* `a test`, i.e., an expression that evaluates to either True or False;* `a block of code` that is executed if the test evaluates to `True`; * `an optional block of code` that is executed if the test evaluates to `False`.![if-else](./img/if-else.jpg)After a conditional statement is executed, execution resumes at the code following the statement.In Python, a conditional statement has the form```pythonif Boolean expression: block of codeelse: block of code```or ```pythonif Boolean expression: block of code``` ###Code x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') ###Output _____no_output_____ ###Markdown Indentation Python is unusual in using indentation this way: * Indentation is semantically meaningful in Python: delineate blocks of code Most other programming languages use some sort of **bracketing symbols** to delineate blocks of code, e.g.,C encloses blocks in braces, { }. An advantage of the Python approach is that it ensures that the **visual structure** of a program is an **accurate** representation of the semantic structure of that program.* **The example C++ code with GCC** http://nbviewer.jupyter.org/github/PySEE/home/blob/S2019/notebook/Unit8-2-GCC_DLL.ipynb ###Code if(boolean_expression) { // block of code } else { block of code } %%file ./code/gcc/cppdemo.cpp #include <iostream> using namespace std; int main() { int x = 12; if( x % 2==0 ) { cout << "Even" <<endl; cout <<x<<endl; cout <<x%2<<endl; } else { cout << "Odd" << endl; }; return 0; } ###Output _____no_output_____ ###Markdown The braces specify what statements are executed in the `if` case. It is considered good style to indent your code to agree with the brace structure, `but it is not required`. In addition, the `semicolons` are used to indicate the end of a statement, independent of the locations of the line breaks in the file. So, the following code fragment has the same meaning as the previous one, although it is `much harder to read and understand`. ###Code %%file ./code/gcc/cppdemo.cpp #include <iostream> using namespace std; int main() { int x = 12; if( x % 2==0 ) { cout << "Even" <<endl; cout <<x<<endl; cout <<x%2<<endl; } else { cout << "Odd" << endl; }; return 0; } !g++ -o ./code/gcc/cppdemo ./code/gcc/cppdemo.cpp !.\code\gcc\cppdemo ###Output _____no_output_____ ###Markdown In Python, on the other hand, there are no braces for grouping or semicolons for termination. **Indentation indicates grouping** and **line breaks indicate statement termination**. So, in Python, we would write the previous example as ###Code x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') x=12 # the following program that prints “Even” if the value of the variable x is even # and “Odd” otherwise: if x % 2 == 0: print('Even') print(x) print(x%2) else: print('Odd') ###Output _____no_output_____ ###Markdown Nested conditionalsWhen either the true block or the false block of a conditional contains `another` conditional, the conditional statements are said to be **nested**. In the code below, there are nested conditionals in both branches of the top-level `if` statement ###Code #x=2*3*7 #x=2*7 x=3*7 # the conditional statements are nested. if x % 2 == 0: if x % 3 == 0: print('Divisible by 2 and 3') else: print('Divisible by 2 and not by 3') elif x % 3 == 0: # elif : else if print('Divisible by 3 and not by 2') ###Output _____no_output_____ ###Markdown **NOTE:** The `elif` in the above code stands for `else if`. It is often convenient to use `a compound Boolean expression` in the test of a conditional, for example, ###Code x=1 y=10 z=87 if x < y and x < z: # compound Boolean expressions print('x is least') elif y < z: print('y is least') else: print('z is least') ###Output _____no_output_____ ###Markdown 2 Conditional Iteration:The while loopWhen we want a program to do the same thing many times, we can use iterationA generic iteration (also called looping) mechanism is shown in the boxed-in part of the following. ![while](./img/while.jpg)Like a conditional statement, it begins with a test. If the test evaluates to True, the program executes the loop body once, and then goes back to reevaluate the test. This process is repeated until the test evaluates to False, after which control passes to the code following the iteration statement.```pythoninitial value !!!while Boolean expression: block of code``` ###Code # Square an integer, the hard way X**2 x = 3 ans = 0 itersLeft = x # initial value :X while (itersLeft != 0): ans = ans + x # x**2 to repetitive + itersLeft = itersLeft - 1 print(str(x) + '*' + str(x) + ' = ' + str(ans)) ###Output 3*3 = 9 ###Markdown It is sometimes convenient to exit a loop without testing the loop condition. Executing a `break` statement terminates the loop in which it is contained, and transfers control to the code immediately following the loop.For example, the code of `Find a positive integer that is divisible by both 11 and 12` ###Code #Find a positive integer that is divisible by both 11 and 12 x = 1 while True: if x%11 == 0 and x%12 == 0: break x = x + 1 print(x, 'is divisible by 11 and 12') ###Output _____no_output_____ ###Markdown Loop Logic,Error and TestingThe `while` loop is typically the **condition-control** loopThe careful design and testing is needed.* initialized control variable* update the control variable with loop* test the continuation conditionIf the continuation contidition is already available for examination at **loop entry**,check it and provide test data that prodece 0,1,and at least 5 iterations. Example: Exhaustive EnumerationThe following code * prints `the integer cube root`, if it exists, of an integer. * If the input is not a perfect cube, it prints a message to that effect ###Code #Find the cube root of a perfect cube #x=19 x=8 #x=-8 ans = 0 # !!! while ans**3 < abs(x): ans = ans + 1 # +1 Exhaustive Enumeration if ans**3 != abs(x): print(x, 'is not a perfect cube') else: if x < 0: ans = -ans print('Cube root of', x,'is', ans) ###Output Cube root of 8 is 2 ###Markdown The algorithmic technique used in this program is a variant of guess and check called exhaustive enumeration. * We enumerate **all possibilities** until we get to the right answer or exhaust the space of possibilities. At first blush, this may seem like an incredibly stupid way to solve a problem.Surprisingly, however, exhaustive enumeration algorithms are often `the most practical way` to solve a problem. They are typically easy to implement and easy to understand. And, in many cases, they run fast enough for all practical purposes.**Modern computers are amazingly fast.** Now, let’s insert some errors and see what happens1: change initialized control variable: ans =16. ###Code x=-8 ans =16 # error: initialized control variable while ans**3 < abs(x): ans = ans + 1 # if ans**3 != abs(x): print(x, 'is not a perfect cube') else: if x < 0: ans = -ans print('Cube root of', x,'is', ans) !python ./code/python/ch3_cube_root.py ###Output -8 is not a perfect cube ###Markdown 2 replace the statement `ans = ans + 1` by `ans = ans`if one forget to update the control variable,the result is an infinite loop.To halt a loop thar appears to be hung,type **Ctrl+c** (hold down the control key and the c key simultaneously). This will return you to the user prompt in the shell. ###Code %%file ./code/python/cube_root.py # running use IDEL: tired of waiting x=8 ans = 0 while ans**3 < abs(x): ans = ans # replace the statement ans = ans + 1 by ans = ans # ans = ans + 1 if ans**3 != abs(x): print(x, 'is not a perfect cube') else: if x < 0: ans = -ans print('Cube root of', x,'is', ans) ###Output Overwriting ./code/python/cube_root.py ###Markdown Try finding the cube root of 8(running use IDEL),After you get **tired of waiting**, enter “control+c” (hold down the control key and the c key simultaneously). This will return you to the user prompt in the shell.![cube_root](./img/cube_root.jpg) 3 replace the continuation condition statement `ans**3 ###Code x=8 ans = 0 while ans**2 < abs(x): ans = ans + 1 if ans**3 != abs(x): print(x, 'is not a perfect cube') else: if x < 0: ans = -ans print('Cube root of', x,'is', ans) ###Output 8 is not a perfect cube ###Markdown Debug while loopIf a while loop seems not to be terminating or to be terminated incorrectlyInsert print statements to test the control variable and the continuation condition ###Code x=8 ans = 0 while ans**2 < abs(x): print('the control variable:',ans) print('the continuation condition:', abs(x) - ans**2) ans = ans + 2 if ans**3 != abs(x): print(x, 'is not a perfect cube') else: if x < 0: ans = -ans print('Cube root of', x,'is', ans) ###Output the control variable: 0 the continuation condition: 8 the control variable: 2 the continuation condition: 4 8 is not a perfect cube ###Markdown Line Continuation. ``` print('the continuation condition:', abs(x) - ans**3)```* Python's `implicit` line joining inside `parentheses, brackets and braces`.* `\` continuation. Implicit line joining inside parentheses, brackets and braces ###Code a = ('1' + '2' + '3' + '4' + '5' + '6' ) a a=['1' + '2' + '3' + '4' + '5' + '6' ] a a={'1' + '2' + '3' + '4' + '5' + '6' } a ###Output _____no_output_____ ###Markdown `\` continuation ###Code a = '1' + '2' + '3' + '4' + '5' +'6' a a = '1' + '2' + '3' + \ '4' + '5' + '6' a ###Output _____no_output_____ ###Markdown 3 For LoopsPython provides a language mechanism, the for loop,that can be used to simplify programs containing this kind of iteration: Each iterates over a sequence of integers.The general form of a for statement is :```pythonfor variable in sequence: code block```The process continues until the `sequence is exhausted` or a break statement is executed within the code block.The sequence of values bound to variable is most commonly generated using the sequence type Range, which returns a sequence containing an arithmetic progression. 3.1 Range typehttps://docs.python.org/3/library/stdtypes.htmlrangesThe range type represents `an immutable sequence of numbers` and is commonly used for looping a specific number of times in `for loops.`The `range` type may takes one,two or three integer arguments: ```pythonrange(stop)range(start, stop)range(start, stop[, step])```* start: The value of the start parameter (or 0 if the parameter was not supplied)* stop: The value of the stop parameter* step: The value of the step parameter (or 1 if the parameter was not supplied)```pythonrange(start,stop,step)```* It produces the progression `start, start + step, start + 2*step`, etc.```pythonrange(5,40,10) -> [5,15,25,35]```* If step is `negative`, the last element is the smallest integer `start + i*step` greater than stop.```pythonrange(40,5,-10)-> [40,30,20,10]``` ###Code print("range(5,40,10)") for i in range(5,40,10): print(i,end=" ") print("\nrange(40,5,-10)") for i in range(40,5,-10): print(i,end=" ") ###Output range(5,40,10) 5 15 25 35 range(40,5,-10) 40 30 20 10 ###Markdown If the first argument `start` is omitted it defaults to 0, If the last argument (the `step` size) is omitted it defaults to 1.```python range(4)-> range(0, 4)->range(0, 4,1) ->[0, 1, 2,3]``````python range(4,10)-> range(4,10,1)->[4 5 6 7 8 9] ``` ###Code print("range(4)") for i in range(4): print(i,end=" ") print("\nrange(4,10)") for i in range(4,10): print(i,end=" ") ###Output range(4) 0 1 2 3 range(4,10) 4 5 6 7 8 9 ###Markdown It raises the question of whether changing **the value of x inside the loop** affects the number of iterations. It does not. The arguments to the `range` function in the line with for are evaluated just before the `first iteration of the loo`p, and not reevaluated for subsequent iterations.To see how this works, consider ###Code x = 4 for j in range(x): print('j: ',j) for i in range(x): # inner loop print('\t i: ',i) x=2 # evaluated each time ###Output _____no_output_____ ###Markdown because the `range` function in the outer loop is evaluated only once, but the `range` function in the **inner loop** is `evaluated each time` the inner for statement is reached ###Code x = 4 for j in range(x): print('j: ',j) for i in range(x): # inner loop print(i) x=2 # change x=2 ###Output _____no_output_____ ###Markdown 3.2 Iterate over characters of a stringThe `for` statement can be used in conjunction with the in operator to conveniently `iterate over characters of a string`. For example, ###Code total = 0 for char in '123456789': total = total + int(char) print(total) ###Output _____no_output_____ ###Markdown sums the digits in the string denoted by the literal `'12345678`' and prints the total 4 `break` and `continue` Statements 4.1 The `break` StatementThe break statement is used to break out of a loop statement i.e. stop the execution of a looping statement, even if the loop condition has not become False or the sequence of items has not been completely iterated over.An important note is that if you break out of a for or while loop, any corresponding loop else block is not executed.This is exemplified by the following loop, which searches for `prime` numbers: ###Code while True: s = input('Enter something : ') if s == 'quit': break print('Length of the string is', len(s)) print('Done') ###Output _____no_output_____ ###Markdown 4.2 The `continue` StatementThe `continue` statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop. ###Code for num in range(2, 10): if num % 2 == 0: print("Found an even number", num) continue # skip the rest of the statements in the current loop block print("Found a number", num) while True: s = input('Enter something : ') if s == 'quit': break if len(s) < 3: print('Too small') continue # skip the rest of the statements in the current loop block print('Input is of sufficient length') # Do other kinds of processing here... ###Output _____no_output_____ ###Markdown 5 Python Developer's Guide,Coding Styleshttps://www.python.org/dev/**PEP**:Python Enhancement Proposals 5.1 The Zen of Python ,PEP20 (Python Enhancement Proposals)https://www.python.org/dev/peps/pep-0020/ ###Code # Easter Egg import this ###Output _____no_output_____ ###Markdown 5.2 Coding convention: PEP8()PEP 8 -- Style Guide for Python Code: https://www.python.org/dev/peps/pep-0008/The recommended styles are:* Use 4 spaces for indentation. Don't use tab.* Lines shall not exceed 79 characters.* Use blank lines to separate functions and classes.* Use a space before and after an operator.​ Packages about pep8​* `pycodestyle` :the tool to check your Python code against some of the style conventions in PEP 8.​* `autopep8` : the tool that automatically formats Python code to conform to the PEP 8 style guide​**Installation**​```bash>python -m pip install autopep8```​pycodestyle is installed when you install autopep8 pycodestyle : usage and outputShow **first** occurrence of each error```bash>pycodestyle --first sourcecodefile``` ###Code %%file ./code/python/demo_pep8.py total=0 for char in '123456789': total=total + int(char) print(total) !pycodestyle --first ./code/python/demo_pep8.py ###Output _____no_output_____ ###Markdown You can also make `pycodestyle` show the **source code** for each error, and even the relevant text from PEP 8: ###Code !pycodestyle --show-source --show-pep8 ./code/python/demo_pep8.py ###Output _____no_output_____ ###Markdown you can display **how often** each error was found: ###Code !pycodestyle --statistics ./code/python/ch3_cube_root.py ###Output _____no_output_____ ###Markdown autopep8 usageTo **modify** the source code file **in place** (with aggressive level 2): ###Code !autopep8 --in-place --aggressive --aggressive ./code/python/demo_pep8.py ###Output _____no_output_____ ###Markdown The modified code by autopep8 ###Code %load ./code/python/demo_pep8.py ###Output _____no_output_____ ###Markdown >**LINE** magics: `%load`>> https://ipython.readthedocs.io/en/stable/interactive/magics.html>>Load code into the current frontend.>>Usage:>>```python>%load [options] source>```>where source can be a filename, URL, input history range, macro, or element in the user namespace ###Code !pycodestyle --first ./code/python/demo_pep8.py !pycodestyle --statistics ./code/python/demo_pep8.py ###Output _____no_output_____ ###Markdown Using pep8 within Visual Studio Codepep8 is unenabled by default within Visual Studio Codeyou may setting ```json // Whether to lint Python files using pep8 "python.linting.pep8Enabled": true,```![autopep8](./img/vscode-pep8.jpg) Using pep8 within Jupyter NotebookJupyter notebook extensions:* https://github.com/ipython-contrib/jupyter_contrib_nbextensions This repository contains a collection of extensions that add functionality to the Jupyter notebook.* Install the python package```bash>python -m pip install jupyter_contrib_nbextensions```* Install javascript and css files```bash>jupyter contrib nbextension install --user``` ###Code total = 0 for char in '123456789': total = total + int(char) print(total) ###Output _____no_output_____
band_and_point_spec/systematic_study_of_0_lambda_valued_potentials.ipynb
###Markdown Monodromy Matrices and Scaled PotentialsGiven a real-valued $K$-periodic potential $(v(0),\dots,v(K-1))$, the corresponding monodromy matrix reads\begin{equation} M = \begin{pmatrix} -v(K-1)&-1\\1&0\end{pmatrix} \begin{pmatrix} -v(K-2)&-1\\1&0\end{pmatrix}\cdots\begin{pmatrix} -v(0)&-1\\1&0\end{pmatrix}\end{equation}If $v$ is a potential over the alphabet $\Sigma_\lambda = \{0,\lambda\}$ with $\lambda \in \mathbb{R}$, then the corresponding matrix entries of $M$ are polynomials in $\lambda$.The location of the zeros of the entry $M_{2,1}$ is linked to the invertibility of the corresponding one-sided periodic Schrödinger operator $H_+$. More precisely, if $|\mathrm{tr}(M) | > 2$ and $M_{2,1} \neq 0$, then $H_+$ is invertible.This notepad will systematically determine all potentials up to length $9$ over the alphabet $\Sigma_0$ and calculate the corresponding monodromy matrices, the zeros of the entry $M_{2,1}$ and the trace of $M$. See the section "Systematic Studies of $\{0, \lambda\}$-Valued Potentials" for details. In particular, all polynomial roots are given by closed-form algebraic expressions. Data GenerationRun the cell below with `Kmin = 1` and `Kmax = 9` in order to generate all data for the proofs in the section "Systematic Studies of $\{0, \lambda\}$-Valued Potentials".The cell will produce a dictionary `pots`, where the keys are given by stringified potentials and the corresponding values consist of the symbolic monodromy matrix (`key='mon'`), the zeros of the matrix entry (`key='sol'`) and the value of the trace (`key='trace'`). Rendering of OutputAfter all results have been calculated. Run the cell that renders "Human Readable Output". Interactive Data AnalysisIn order to access and further analyse the values in the dictionary for the potential `v = [0,1,1]` use the syntax```pythonv = [0,1,1]pots[str(v)]```More examples follow below in the analysis section. JSON ExportIt is possible to export the files in JSON, see the corresponding section at the end of this notebook. ###Code # Run this cell once at startup ############################### l = var('l') def mon(v): ########################## # Calculate the general monodromy matrix with scaling l # # Example: # v = [1,1,0]; mon(v).expand() # > [ l 1] # > [l^2 - 1 l] # ########################## M = identity_matrix(2) for vv in v: M = matrix(2,2,[ - l*vv, -1, 1, 0])*M return M def analyse_v(v): ########################## # calculate monodromy, zeros and check trace. # return a dictionary containing symbolic elements # # Example: # v = [1,1,0]; analyse_v(v) ########################## data = {} #monodromy M = mon(v).expand() data['mon'] = M #zeros sols = solve(M[1][0] == 0, l) sol = list(map(lambda s: s.rhs(), sols)) sol.sort() data['sol'] = sol #trace data['trace'] = list(map(lambda s: M.trace().subs(l=s), sol)) return data #######Data Creation###### # input Kmin = 1 Kmax = 8 #maximal period length, not larger than 9 to guarantee algebraic roots sigma = [0,1] # alphabet pots = {} #empty dictionary for K in range(Kmin,Kmax + 1): v_list = Tuples(sigma,K).list() for v in v_list: pots[str(v)] = deepcopy(analyse_v(v)) ###Output _____no_output_____ ###Markdown Human Readable OutputThe cell below outputs all potentials, their corresponding monodromy matrices, the zeros of the entry M_{1,2}, and the corresponding value of the trace of M. For an interactive data analysis and further documentation, see the cells below. ###Code for k in range(1,9): show("Period Length K = ", k) v_list = Tuples(sigma,k).list() for v in v_list: # skip the following potentials for readability # they are treated separately at the the Section # "Skipped potentials" of this notebook if (v == [1,1,1,1,1,1,1] or v == [1,1,1,1,1,1,0]): continue show((str(v), pots[str(v)])) ###Output _____no_output_____ ###Markdown Skipped PotentialsThe following cell analyses the previously skipped potentials`v = [1,1,1,1,1,1,0]`and `v = [1,1,1,1,1,1,1]`Both potentials lead to the monodromy matrix entry $M_{1,2}$.$$M_{1,2} = l^6 - 5l^4 + 6l^2 - 1$$The algebraic roots produced with SageMath don't fully simplify with some remaining expressions that appear to have a non-vanishing imaginary part. The following calculations show that the imaginary parts add up, so that roots are only taken of positive real numbers.Note that$$9 \cdot \left(\frac{7}{18} i \, \sqrt{3} + \frac{7}{54}\right)^{\frac{1}{3}} =3 \, \sqrt{7} {\left(\cos\left(\frac{1}{3} \, \arctan\left(3 \, \sqrt{3}\right)\right) + i \, \sin\left(\frac{1}{3} \, \arctan\left(3 \, \sqrt{3}\right)\right)\right)}$$and $$\frac{7}{{\left(\frac{7}{18} i \, \sqrt{3} + \frac{7}{54}\right)}^{\frac{1}{3}}} = \left(\cos\left(\frac{1}{3} \, \arctan\left(3 \, \sqrt{3}\right)\right) - i \, \sin\left(\frac{1}{3} \, \arctan\left(3 \, \sqrt{3}\right)\right)\right)$$This shows that$$\mathrm{Im} \left( 9 \cdot \left(\frac{7}{18} i \, \sqrt{3} + \frac{7}{54}\right)^{\frac{1}{3}} +\frac{7}{{\left(\frac{7}{18} i \, \sqrt{3} + \frac{7}{54}\right)}^{\frac{1}{3}}} \right) = 0$$and$$\mathrm{Re} \left( 9 \cdot \left(\frac{7}{18} i \, \sqrt{3} + \frac{7}{54}\right)^{\frac{1}{3}} +\frac{7}{{\left(\frac{7}{18} i \, \sqrt{3} + \frac{7}{54}\right)}^{\frac{1}{3}}} \right) > 0$$ ###Code # Run this cell in order to analyse the roots of # the monodromy matrices for v = [1,1,1,1,1,1,0] # and v = [1,1,1,1,1,1,1] v = [1,1,1,1,1,1,0] print("Monodromy Matrix M for v = [1,1,1,1,1,1,0]") show(pots[str(v)]['mon']) v = [1,1,1,1,1,1,1] print("Monodromy Matrix M for v = [1,1,1,1,1,1,1]") show(pots[str(v)]['mon']) print("Zeros of M_{2,1}") for s in pots[str(v)]['sol']: show(s) ###Output _____no_output_____ ###Markdown Result FilteringThe dictionary `pots` contains all possible periodic potentials. In order to filter the results we need to do 3 things1. create a suitable list of potentials2. decide whether we want to filter out candidates that don't fulfill the trace condition3. decide whether we want to allow irrational scaling factors Interpretation of Results Example 1```pythonv_list = Tuples(sigma,2).list()for v in v_list: print([v, [s for s in pots[str(v)]['sol']], [s if s in QQ else s.n() for s in pots[str(v)]['trace']]])```gives as first line of output```[[0, 0], [r1], [-2]]```This means that the entry $M_{2,1}$ of monodromy matrix for the potential $v = (0,0)$ is zero for all scalings (`r1` corresponds to $\mathbb{R}$) and that the value of the trace of $M$ is always $-2$.The line```[[1, 0], [0], [-2]]```means that the entry $M_{2,1}$ of monodromy matrix for the potential $v = (1,0)$ is zero for the scaling `l = 1` and that the value of the trace of $M$ is, in this case, $-2$. Example 2Similarly to Example 1, we can look at potentials with period $K = 5$. A line like```[[1, 0, 1, 1, 0], [-1/2*sqrt(2), 1/2*sqrt(2)], [2.12132034355964, -2.12132034355964]]```means that the entry $M_{2,1}$ of monodromy matrix for the potential $v = (1, 0, 1, 1, 0)$ is zero for the tuple of $\left( -\frac{\sqrt{2}}{2}, \frac{\sqrt{2}}{2}\right)$ and that the corresponding values of the trace of $M$ are $(2.12\dots, -2.12\dots)$. Example 3Only list potentials such that $M_{2,1}$ has at least one rational zero.```pythonv_list = Tuples(sigma,9).list()for v in v_list: isRational = [s in QQ for s in pots[str(v)]['sol']] if True in isRational: print([v, [s for s in pots[str(v)]['sol']], [s if s in QQ else s.n() for s in pots[str(v)]['trace']]])``` Example 4Only list potentials such that $M_{2,1}$ has at least one rational zero and have absolute trace larger than 2.```pythonv_list = Tuples(sigma,9).list()for v in v_list: isRational = [s in QQ for s in pots[str(v)]['sol']] if True in isRational: isTraceGt2 = [abs(s.n()) > 2 for s in pots[str(v)]['trace']] if True in isTraceGt2: print([v, [s for s in pots[str(v)]['sol']], [s if s in QQ else s.n() for s in pots[str(v)]['trace']]])``` ###Code # example code, modify as indicated above v_list = Tuples(sigma,5).list() for v in v_list: print([v, [s.full_simplify() for s in pots[str(v)]['sol']], [s if s in QQ else s.n() for s in pots[str(v)]['trace']]]) ###Output _____no_output_____ ###Markdown JSON OutputExport the `pots` dictionary in JSON file format.You can read the input using a simple Python program```python!/bin/python3import jsonwith open('pots_export.json') as json_file: data = json.load(json_file) for key in data: print(key)```or an online JSON reader like https://jsonformatter.org/json-reader . ###Code # run this cell to in order to save pots into json file import json def jsonify_dict(input_dict): ########################## # create json object from dictionary, # stringify everything for serialization ########################## json_object ={} for key in input_dict: dictionary = {} dictionary['mon'] = str(input_dict[key]['mon']) dictionary['sol'] = str(input_dict[key]['sol']) dictionary['trace'] = str(input_dict[key]['trace']) json_object[str(key)] = deepcopy(dictionary) return json_object json_dict = jsonify_dict(pots) with open('pots_export.json', 'w') as outfile: json.dump(json_dict,outfile) ###Output _____no_output_____
Human_Activity_Recognition (1) (1).ipynb
###Markdown Human Activity Recognition Problem statement:In this project you will design a robust activity recogonition system based on the smartphones.As you know mobile devices have accelerometer as the sensor which collects the activities.These activities can be classified using K-nearest neighbour. Attribute Information:For each record in the dataset it is provided:- Triaxial acceleration from the accelerometer (total acceleration) and the estimated body acceleration.- Triaxial Angular velocity from the gyroscope.- A 561-feature vector with time and frequency domain variables.- Its activity label.- An identifier of the subject who carried out the experiment. step-1....Import requied libraries ###Code # import the standard libraries import pandas as pd #Data processing and I/O operation import numpy as np #Linear Algebra import matplotlib.pyplot as plt %matplotlib inline #Import the machine libraries from sklearn.utils import shuffle from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score, confusion_matrix, classification_report ###Output _____no_output_____ ###Markdown step-2... Import the Dataset ###Code train = shuffle(pd.read_csv('train.csv')) test = shuffle(pd.read_csv('test.csv')) ###Output _____no_output_____ ###Markdown STep-3... Inspection of data ###Code train.head(10) ## shows top 10 rows train.tail(1) ## Shows last row train.shape ### size of trian data set test.shape ## size of test data set ###Output _____no_output_____ ###Markdown Step-4...Data Exploration Check for missing values ###Code print('Any missing value in training set:', train.isnull().values.any()) print('Any missing value in training set:', test.isnull().values.any()) ###Output Any missing value in training set: False Any missing value in training set: False ###Markdown Exploring the Dataset ###Code train_outcome = pd.crosstab(index = train['Activity'], columns='Count') train_outcome ###Output _____no_output_____ ###Markdown Exploratory Data Analysis ###Code temp = train['Activity'].value_counts() ### Gives value counts temp df = pd.DataFrame({'labels':temp.index, 'values':temp.values}) df.head(2) labels=df['labels'] sizes = df['values'] colors = ['yellowgreen', 'lightskyblue', 'gold', 'lightpink', 'cyan', 'lightcoral'] patches, texts = plt.pie(sizes, colors=colors, labels = labels, shadow=True, startangle=90, pctdistance=1.1, labeldistance=1.2) plt.legend(patches, labels, loc='right') plt.axis('equal') plt.tight_layout() plt.show() ###Output _____no_output_____ ###Markdown Data Processing ###Code X_train = pd.DataFrame(train.drop(['Activity', 'subject'], axis=1)) Y_train_label = train.Activity.values.astype(object) X_test = pd.DataFrame(test.drop(['Activity', 'subject'], axis=1)) Y_test_label = test.Activity.values.astype(object) ## Import necessaray library from sklearn import preprocessing ## Instantiating the object encoder = preprocessing.LabelEncoder() ### It will do lable encoder ## Fit on train data encoder.fit(Y_train_label) y_train = encoder.transform(Y_train_label) y_train encoder.fit(Y_test_label) ## Transforming on test data y_test = encoder.transform(Y_test_label) y_test num_cols = X_train._get_numeric_data().columns num_cols.size ###Output _____no_output_____ ###Markdown Step-5.... Model Building ###Code from sklearn.preprocessing import StandardScaler scaler = StandardScaler() x_train = scaler.fit_transform(X_train) x_test = scaler.fit_transform(X_test) ## Instantiating the object knn = KNeighborsClassifier(n_neighbors=24) ## fit on train data knn.fit(x_train,y_train) ## Predictions on test data y_pred = knn.predict(x_test) print((accuracy_score(y_test, y_pred)*100), '%') ## Applying the range method scores = [] ### creating Empty list for i in range(1,50): knn=KNeighborsClassifier(n_neighbors=i, n_jobs=-1) knn.fit(x_train, y_train) y_pred = knn.predict(x_test) scores.append(accuracy_score(y_test, y_pred)) plt.xlabel('Number of Neighbors') plt.ylabel('Accuracy Score') xticks = range(1,50) plt.plot(xticks, scores, color='red', linestyle='solid', marker='o', markersize=5, markerfacecolor='blue') plt.show() scores = np.array(scores) print('Optimal number of neighbors is:', scores.argmax()) print('Accuracy Score:' +str(scores.max()*100),'%') ###Output Optimal number of neighbors is: 19 Accuracy Score:90.29521547336275 % ###Markdown Step-6.......Conclusion ###Code knn = KNeighborsClassifier(n_neighbors=19) knn.fit(x_train, y_train) y_pred = knn.predict(x_test) y_pred_label = list(encoder.inverse_transform(y_pred)) y_pred_label print(confusion_matrix(Y_test_label, y_pred_label)) print(classification_report(Y_test_label, y_pred_label)) ###Output precision recall f1-score support LAYING 0.99 0.96 0.97 537 SITTING 0.92 0.79 0.85 491 STANDING 0.83 0.96 0.89 532 WALKING 0.85 0.97 0.91 496 WALKING_DOWNSTAIRS 0.96 0.78 0.86 420 WALKING_UPSTAIRS 0.89 0.92 0.90 471 accuracy 0.90 2947 macro avg 0.91 0.90 0.90 2947 weighted avg 0.91 0.90 0.90 2947
_posts/python/scientific/heatmap/heatmaps.ipynb
###Markdown New to Plotly?Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).You can set up Plotly to work in [online](https://plot.ly/python/getting-started/initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/python/getting-started/start-plotting-online).We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started! Version CheckPlotly's python package is updated frequently. Run pip install plotly --upgrade to use the latest version. ###Code import plotly plotly.__version__ ###Output _____no_output_____ ###Markdown Basic Heatmap ###Code import plotly.plotly as py import plotly.graph_objs as go trace = go.Heatmap(z=[[1, 20, 30], [20, 1, 60], [30, 60, 1]]) data=[trace] py.iplot(data, filename='basic-heatmap') ###Output _____no_output_____ ###Markdown Heatmap with Categorical Axis Labels ###Code import plotly.plotly as py import plotly.graph_objs as go trace = go.Heatmap(z=[[1, 20, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, -10, 20]], x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], y=['Morning', 'Afternoon', 'Evening']) data=[trace] py.iplot(data, filename='labelled-heatmap') ###Output _____no_output_____ ###Markdown Heatmap with Unequal Block Sizes ###Code import numpy as np import plotly.plotly as py def spiral(th): a = 1.120529 b = 0.306349 r = a*np.exp(-b*th) return (r*np.cos(th), r*np.sin(th)) nspiral = 2 # number of spiral loops th = np.linspace(-np.pi/13,2*np.pi*nspiral,1000); # angle (x,y) = spiral(th) # shift the spiral north so that it is centered yshift = (1.6 - (max(y)-min(y)))/2 s = dict(x= -x+x[0], y= y-y[0]+yshift, line =dict(color='white',width=3)) # Build the rectangles as a heatmap # specify the edges of the heatmap squares phi = ( 1+np.sqrt(5) )/2. xe = [0, 1, 1+(1/(phi**4)), 1+(1/(phi**3)), phi] ye = [0, 1/(phi**3),1/phi**3+1/phi**4,1/(phi**2),1] z = [ [13,3,3,5], [13,2,1,5], [13,10,11,12], [13,8,8,8] ] hm = dict(x = np.sort(xe), y = np.sort(ye)+yshift, z = z, type = 'heatmap', colorscale = 'Viridis') axis_template = dict(range = [0,1.6], autorange = False, showgrid = False, zeroline = False, linecolor = 'black', showticklabels = False, ticks = '' ) layout = dict( margin = dict(t=200,r=200,b=200,l=200), xaxis = axis_template, yaxis = axis_template, showlegend = False, width = 700, height = 700, autosize = False ) figure = dict(data=[s, hm],layout=layout) py.iplot(figure, filename='golden spiral', height=750) ###Output _____no_output_____ ###Markdown Heatmap with Datetime Axis ###Code import datetime import numpy as np import plotly.plotly as py import plotly.graph_objs as go programmers = ['Alex','Nicole','Sara','Etienne','Chelsea','Jody','Marianne'] base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(0, 180)] z = [] for prgmr in programmers: new_row = [] for date in date_list: new_row.append( np.random.poisson() ) z.append(list(new_row)) data = [ go.Heatmap( z=z, x=date_list, y=programmers, colorscale='Viridis', ) ] layout = go.Layout( title='GitHub commits per day', xaxis = dict(ticks='', nticks=36), yaxis = dict(ticks='' ) ) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='datetime-heatmap') ###Output _____no_output_____ ###Markdown ReferenceSee https://plot.ly/python/reference/heatmap for more information and chart attribute options! ###Code from IPython.display import display, HTML display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700rel="stylesheet" type="text/css" />')) display(HTML('<link rel="stylesheet" type="text/csshref="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">')) ! pip install git+https://github.com/plotly/publisher.git --upgrade import publisher publisher.publish( 'heatmaps.ipynb', ' python/heatmaps/', 'Heatmaps | plotly', 'How to make Heatmaps in Python with Plotly.', title = 'Python Heatmaps | plotly', name = 'Heatmaps', has_thumbnail='true', thumbnail='thumbnail/heatmap.jpg', language='python', page_type='example_index', display_as='scientific',order=3, ipynb= '~notebook_demo/33', redirect_from='python/heatmap/') ###Output _____no_output_____ ###Markdown New to Plotly?Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).You can set up Plotly to work in [online](https://plot.ly/python/getting-started/initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/python/getting-started/start-plotting-online).We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started! Version CheckPlotly's python package is updated frequently. Run pip install plotly --upgrade to use the latest version. ###Code import plotly plotly.__version__ ###Output _____no_output_____ ###Markdown Basic Heatmap ###Code import plotly.plotly as py import plotly.graph_objs as go trace = go.Heatmap(z=[[1, 20, 30], [20, 1, 60], [30, 60, 1]]) data=[trace] py.iplot(data, filename='basic-heatmap') ###Output _____no_output_____ ###Markdown Heatmap with Categorical Axis Labels ###Code import plotly.plotly as py import plotly.graph_objs as go trace = go.Heatmap(z=[[1, 20, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, -10, 20]], x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], y=['Morning', 'Afternoon', 'Evening']) data=[trace] py.iplot(data, filename='labelled-heatmap') ###Output _____no_output_____ ###Markdown Heatmap with Unequal Block Sizes ###Code import numpy as np import plotly.plotly as py def spiral(th): a = 1.120529 b = 0.306349 r = a*np.exp(-b*th) return (r*np.cos(th), r*np.sin(th)) nspiral = 2 # number of spiral loops th = np.linspace(-np.pi/13,2*np.pi*nspiral,1000); # angle (x,y) = spiral(th) # shift the spiral north so that it is centered yshift = (1.6 - (max(y)-min(y)))/2 s = dict(x= -x+x[0], y= y-y[0]+yshift, line =dict(color='white',width=3)) # Build the rectangles as a heatmap # specify the edges of the heatmap squares phi = ( 1+np.sqrt(5) )/2. xe = [0, 1, 1+(1/(phi**4)), 1+(1/(phi**3)), phi] ye = [0, 1/(phi**3),1/phi**3+1/phi**4,1/(phi**2),1] z = [ [13,3,3,5], [13,2,1,5], [13,10,11,12], [13,8,8,8] ] hm = dict(x = np.sort(xe), y = np.sort(ye)+yshift, z = z, type = 'heatmap', colorscale = 'Viridis') axis_template = dict(range = [0,1.6], autorange = False, showgrid = False, zeroline = False, linecolor = 'black', showticklabels = False, ticks = '' ) layout = dict( margin = dict(t=200,r=200,b=200,l=200), xaxis = axis_template, yaxis = axis_template, showlegend = False, width = 700, height = 700, autosize = False ) figure = dict(data=[s, hm],layout=layout) py.iplot(figure, filename='golden spiral', height=750) ###Output _____no_output_____ ###Markdown Heatmap with Datetime Axis ###Code import datetime import numpy as np import plotly.plotly as py import plotly.graph_objs as go programmers = ['Alex','Nicole','Sara','Etienne','Chelsea','Jody','Marianne'] base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(0, 180)] z = [] for prgmr in programmers: new_row = [] for date in date_list: new_row.append( np.random.poisson() ) z.append(list(new_row)) data = [ go.Heatmap( z=z, x=date_list, y=programmers, colorscale='Viridis', ) ] layout = go.Layout( title='GitHub commits per day', xaxis = dict(ticks='', nticks=36), yaxis = dict(ticks='' ) ) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='datetime-heatmap') ###Output _____no_output_____ ###Markdown Dash Example ###Code from IPython.display import IFrame IFrame(src= "https://dash-simple-apps.plotly.host/dash-heatmapplot/", width="120%", height="650px", frameBorder="0") ###Output _____no_output_____ ###Markdown Find the dash app source code [here](https://github.com/plotly/simple-example-chart-apps/tree/master/heatmap) ReferenceSee https://plot.ly/python/reference/heatmap for more information and chart attribute options! ###Code from IPython.display import display, HTML display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700rel="stylesheet" type="text/css" />')) display(HTML('<link rel="stylesheet" type="text/csshref="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">')) ! pip install git+https://github.com/plotly/publisher.git --upgrade import publisher publisher.publish( 'heatmaps.ipynb', ' python/heatmaps/', 'Heatmaps | plotly', 'How to make Heatmaps in Python with Plotly.', title = 'Python Heatmaps | plotly', name = 'Heatmaps', has_thumbnail='true', thumbnail='thumbnail/heatmap.jpg', language='python', page_type='example_index', display_as='scientific',order=3, ipynb= '~notebook_demo/33', redirect_from='python/heatmap/') ###Output _____no_output_____
Macmulti/exercicios_com_repeticoes_encaixadas.ipynb
###Markdown Exercícios com Repetições Encaixadas Exercício 1Dados $n$ e $n$ seqüências de números inteiros não-nulos, cada qual seguida por um $0$, calcular a soma dos números pares de cada seqüência. ###Code def main(): n = int(input('Numero de seqûencias: ')) for i in range(1, n+1): soma = 0 num = -1 # gambiarra, hehehe while num != 0: num = int(input('Digite um número, 0 para canelar: ')) if num % 2 == 0: soma += num print(f'A soma dos números pares da {i}ª sequencia é {soma}') main() ###Output _____no_output_____ ###Markdown Exercício 2Dado um número inteiro positivo $n$, determinar todos os inteiros entre $1$ e $n$ que são comprimento da hipotenusa de um triângulo retângulo com catetos inteiros. ###Code def main(): n = int(input('Digite um número: ')) total = 0 for hipotenusa in range(1, n+1): for cateto_op in range(1, hipotenusa): for cateto_ad in range(1, cateto_op): if hipotenusa ** 2 == cateto_op ** 2 + cateto_ad**2: total += 1 print(hipotenusa, cateto_op, cateto_ad) print(f'{total} triângulos nesse intervalo') main() ###Output _____no_output_____ ###Markdown Exercício 3Dados dois naturais $m$ e $n$ determinar, entre todos os pares de números naturais $(x,y)$ tais que $x \leq m$ e $y \leq n$, um par para o qual o valor da expressão $xy - x^2 + y$ seja máximo e calcular também esse máximo. ###Code def main(): m = int(input('Digite um valor para o m: ')) n = int(input('Digite um valor para o n: ')) f_max = 0 x_max = 0 y_max = 0 for x in range(1, m+1): for y in range(1, n+1): if (x*y - x**2 + y) > f_max: x_max = x y_max = y f_max = x*y - x**2 + y print(f'({x_max},{y_max}) é o ponto de máximo no intervalo. F max = {f_max}') main() ###Output _____no_output_____ ###Markdown Exercício 4Dados $n$ números inteiros positivos, calcular a soma dos que são primos. ###Code def isprimo(n): for cand in range(2, n): if n % cand == 0: return False return True def main(): n = int(input('Quantos números deseja inserir? ')) # BASIC feelings soma = 0 for i in range(1, n+1): num = int(input(f'Digite o {i}º número: ')) if isprimo(num): soma += num print(f'A soma dos números primos da sua sequência é {soma}') main() ###Output _____no_output_____ ###Markdown Exercício 5Sabe-se que um número da forma $n^3$ é igual a soma de $n$ ímpares consecutivos. * Exemplo $m = 4$: * $1^3 = 1$ * $2^3 = 3 + 5$ * $3^3= 7 + 9 + 11$ * $4^3= 13 + 15 + 17 + 19$Dado $m$, determine os ímpares consecutivos cuja soma é igual a $n^3$ para $n$ assumindo valores de $1$ a $m$. ###Code def main(): m = int(input('Digite um valor para m: ')) init = 1 for i in range(1, m+1): print(f'{i}**3 = {init}', end='') for n in range(1, i): print(f' + {init + 2 * n}', end='') init += 2 * i print('') main() ###Output _____no_output_____ ###Markdown Exercício 6Dado um número inteiro positivo, determine a sua decomposição em fatores primos calculando também a multiplicidade de cada fator. ###Code def is_primo(n): for cand in range(2, n): if n % cand == 0: return False return True def next_primo(x): cand = x + 1 flag = False while not flag: if is_primo(cand): flag = True else: cand = cand + 1 return cand def main(): n = int(input('Digite um número positivo: ')) fator = 2 while n > 1: multi = 0 while n % fator == 0: n = n / fator multi = multi + 1 if multi > 0: print(f'Fator: {fator} | Multiplicidade: {multi} ') fator = next_primo(fator) main() ###Output _____no_output_____ ###Markdown Exercício 7Dados um inteiro positivo $n$ e uma seqüência de $n$ inteiros positivos, determinar o máximo divisor comum a todos eles. ###Code def main(): n = int(input('Digite o tamanho da sequência: ')) mdc = int(input('Digite o 1º número da sequência: ')) n_mdc = 0 i = 1 while i < n: num = int(input(f'Digite o {i+1}º número da sequência: ')) i += 1 div = 1 while div <= mdc and div <= num: if mdc % div == 0 and num % div == 0: n_mdc = div div += 1 mdc = n_mdc print(f'MDC: {mdc}') main() ###Output _____no_output_____ ###Markdown Exercício 8(POLI 97) Dizemos que uma sequência de inteiros positivos é $k$-**alternante** se for composta alternadamente por segmentos de números pares de tamanho $k$ e segmentos de números ímpares de tamanho $k$. * Exemplos: * A sequência 1 3 6 8 9 11 2 4 1 7 6 8 é 2-alternante. * A sequência 2 1 4 7 8 9 12 é 1-alternante. * A sequência 4 2 3 1 6 4 2 9 3 não é alternante. * A sequência 1 3 5 é 3-alternanteDado $n \geq 1$ e uma sequência com $n$ inteiros, verificar se existe um inteiro $k \geq 1$ tal que a sequência é $k$-**alternante**. Dê como saída também o valor de $k$ caso a sequência seja alternante. ###Code # vai receber o prêmio de código mais feio do mundo def main(): n = int(input('Digite o tamanho da sequência: ')) num = int(input('Digite o 1º elemento da sequência: ')) paridade = num % 2 # indica se é par(0) ou ímpar(1) k_tam = 1 # tamanho da corrente k_alt = True # partindo do absurdo que é k-lternante k = 0 # inicializando o valor do k for i in range(1, n+1): if i == n: if k == 0: k = k_tam elif k_tam != k: k_alt = False else: num = int(input(f'Digite o {i + 1}º número da sequência: ')) if num % 2 == paridade: k_tam += 1 else: if k == 0: k = k_tam elif k_tam != k: k_alt = False k_tam = 1 paridade = (paridade + 1) % 2 if k_alt: print(f'Essa sequência é {k}-alternante') else: print(f'Essa sequência não é k-alternante') main() ###Output _____no_output_____
JupyterNotebooks/Labs/Lab 3 Solution.ipynb
###Markdown Lab Three---For this lab we're going to be making and using a bunch of functions. Our Goals are:- Searching our Documentation- Using built in functions- Making our own functions- Combining functions- Structuring solutions ###Code # For the following built in functions we didn't touch on them in class. I want you to look for them in the python documentation and implement them. # I want you to find a built in function to SWAP CASE on a string. Print it. # For example the string "HeY thERe HowS iT GoING" turns into "hEy THerE hOWs It gOing" sample_string = "HeY thERe HowS iT GoING" print(sample_string.swapcase()) # I want you to find a built in function to CENTER a string and pad the sides with 4 dashes(-) a side. Print it. # For example the string "Hey There" becomes "----Hey There----" sample_string = "Hey There" print(sample_string.center(17, "-")) # I want you to find a built in function to PARTITION a string. Print it. # For example the string "abcdefg.hijklmnop" would come out to be ["abcdefg",".","hijklmnop"] sample_string = "abcdefg.hijklmnop" print(sample_string.partition(".")) # I want you to write a function that will take in a number and raise it to the power given. # For example if given the numbers 2 and 3. The math that the function should do is 2^3 and should print out or return 8. Print the output. def power(number, exponent) -> int: return number ** exponent example = power(2, 3) print(example) # I want you to write a function that will take in a list and see how many times a given number is in the list. # For example if the array given is [2,3,5,2,3,6,7,8,2] and the number given is 2 the function should print out or return 3. Print the output. array = [2,3,5,2,3,6,7,8,2] def number_counter(array, target): count = 0 for number in array: if number == target: count += 1 return count example = number_counter(array, 2) print(example) # Use the functions given to create a slope function. The function should be named slope and have 4 parameters. # If you don't remember the slope formula is (y2 - y1) / (x2 - x1) If this doesn't make sense look up `Slope Formula` on google. def division(x, y): return x / y def subtraction(x, y): return x - y def slope(x1, x2, y1, y2): return division(subtraction(y2, y1), subtraction(x2, x1)) example = slope(1, 2, 1, 2) print(example) # Use the functions given to create a distance function. The function should be named function and have 4 parameters. # HINT: You'll need a built in function here too. You'll also be able to use functions written earlier in the notebook as long as you've run those cells. # If you don't remember the distance formula it is the square root of the following ((x2 - x1)^2 + (y2 - y1)^2). If this doesn't make sense look up `Distance Formula` on google. import math def addition(x, y): return x + y def distance(x1, x2, y1, y2): x_side = power(subtraction(x2, x1), 2) y_side = power(subtraction(y2, y1), 2) combined_sides = addition(x_side, y_side) return math.sqrt(combined_sides) print(distance(1, 2, 1, 2)) ###Output 1.4142135623730951 ###Markdown Lab Three---For this lab we're going to be making and using a bunch of functions. Our Goals are:- Searching our Documentation- Using built in functions- Making our own functions- Combining functions- Structuring solutions ###Code # For the following built in functions we didn't touch on them in class. I want you to look for them in the python documentation and implement them. # I want you to find a built in function to SWAP CASE on a string. Print it. # For example the string "HeY thERe HowS iT GoING" turns into "hEy THerE hOWs It gOing" sample_string = "HeY thERe HowS iT GoING" print(sample_string.swapcase()) # I want you to find a built in function to CENTER a string and pad the sides with 4 dashes(-) a side. Print it. # For example the string "Hey There" becomes "----Hey There----" sample_string = "Hey There" print(sample_string.center(17, "-")) # I want you to find a built in function to PARTITION a string. Print it. # For example the string "abcdefg.hijklmnop" would come out to be ["abcdefg",".","hijklmnop"] sample_string = "abcdefg.hijklmnop" print(sample_string.partition(".")) # I want you to write a function that will take in a number and raise it to the power given. # For example if given the numbers 2 and 3. The math that the function should do is 2^3 and should print out or return 8. Print the output. def power(number, exponent) -> int: return number ** exponent example = power(2, 3) print(example) # I want you to write a function that will take in a list and see how many times a given number is in the list. # For example if the array given is [2,3,5,2,3,6,7,8,2] and the number given is 2 the function should print out or return 3. Print the output. array = [2,3,5,2,3,6,7,8,2] def number_counter(array, target): count = 0 for number in array: if number == target: count += 1 return count example = number_counter(array, 2) print(example) # Use the functions given to create a slope function. The function should be named slope and have 4 parameters. # If you don't remember the slope formula is (y2 - y1) / (x2 - x1) If this doesn't make sense look up `Slope Formula` on google. def division(x, y): return x / y def subtraction(x, y): return x - y def slope(x1, x2, y1, y2): return division(subtraction(y2, y1), subtraction(x2, x1)) example = slope(1, 2, 1, 2) print(example) # Use the functions given to create a distance function. The function should be named function and have 4 parameters. # HINT: You'll need a built in function here too. You'll also be able to use functions written earlier in the notebook as long as you've run those cells. # If you don't remember the distance formula it is the square root of the following ((x2 - x1)^2 + (y2 - y1)^2). If this doesn't make sense look up `Distance Formula` on google. import math def addition(x, y): return x + y def distance(x1, x2, y1, y2): x_side = power(subtraction(x2, x1), 2) y_side = power(subtraction(y2, y1), 2) combined_sides = addition(x_side, y_side) return math.sqrt(combined_sides) print(distance(1, 2, 1, 2)) ###Output 1.4142135623730951 ###Markdown Lab Three---For this lab we're going to be making and using a bunch of functions. Our Goals are:- Searching our Documentation- Using built in functions- Making our own functions- Combining functions- Structuring solutions ###Code # For the following built in functions we didn't touch on them in class. I want you to look for them in the python documentation and implement them. # I want you to find a built in function to SWAP CASE on a string. Print it. # For example the string "HeY thERe HowS iT GoING" turns into "hEy THerE hOWs It gOing" sample_string = "HeY thERe HowS iT GoING" print(sample_string.swapcase()) # I want you to find a built in function to CENTER a string and pad the sides with 4 dashes(-) a side. Print it. # For example the string "Hey There" becomes "----Hey There----" sample_string = "Hey There" print(sample_string.center(17, "-")) # I want you to find a built in function to PARTITION a string. Print it. # For example the string "abcdefg.hijklmnop" would come out to be ["abcdefg",".","hijklmnop"] sample_string = "abcdefg.hijklmnop" print(sample_string.partition(".")) # I want you to write a function that will take in a number and raise it to the power given. # For example if given the numbers 2 and 3. The math that the function should do is 2^3 and should print out or return 8. Print the output. def power(number, exponent) -> int: return number ** exponent example = power(2, 3) print(example) # I want you to write a function that will take in a list and see how many times a given number is in the list. # For example if the array given is [2,3,5,2,3,6,7,8,2] and the number given is 2 the function should print out or return 3. Print the output. array = [2,3,5,2,3,6,7,8,2] def number_counter(array, target): count = 0 for number in array: if number == target: count += 1 return count example = number_counter(array, 2) print(example) # Use the functions given to create a slope function. The function should be named slope and have 4 parameters. # If you don't remember the slope formula is (y2 - y1) / (x2 - x1) If this doesn't make sense look up `Slope Formula` on google. def division(x, y): return x / y def subtraction(x, y): return x - y def slope(x1, x2, y1, y2): return division(subtraction(y2, y1), subtraction(x2, x1)) example = slope(1, 2, 1, 2) print(example) # Use the functions given to create a distance function. The function should be named function and have 4 parameters. # HINT: You'll need a built in function here too. You'll also be able to use functions written earlier in the notebook as long as you've run those cells. # If you don't remember the distance formula it is the square root of the following ((x2 - x1)^2 + (y2 - y1)^2). If this doesn't make sense look up `Distance Formula` on google. import math def addition(x, y): return x + y def distance(x1, x2, y1, y2): x_side = power(subtraction(x2, x1), 2) y_side = power(subtraction(y2, y1), 2) combined_sides = addition(x_side, y_side) return math.sqrt(combined_sides) print(distance(1, 2, 1, 2)) ###Output 1.4142135623730951 ###Markdown Lab Three---For this lab we're going to be making and using a bunch of functions. Our Goals are:- Switch Case- Looping- Making our own functions- Combining functions- Structuring solutions ###Code // Give me an example of you using switch case. String choice = "Rock" switch(choice){ case "Rock": System.out.println("The Computer chose Paper. You lose"); case "Paper": System.out.println("The Computer chose Scissors. You lose"); case "Scissors": System.out.println("The Computer chose Rock. You lose"); } // Give me an example of you using a for loop for (int x = 0; x < 10; x++) { System.out.println("I'll understand with more practice"); } // Give me an example of you using a for each loop String[] todos = {"Laundry", "Wash the Car", "Cook Dinner for the Week"}; System.out.println("Your list of todos are:"); for (String todo: todos) { System.out.println(todo); } // Give me an example of you using a while loop boolean is_looping = true; while (is_looping) { System.out.println("Flipping is looping"); is_looping = !is_looping; } // I want you to write a function that will take in a number and raise it to the power given. // For example if given the numbers 2 and 3. The math that the function should do is 2^3 and should print out or return 8. Print the output. double power (int base, int exponent) { return Math.pow(base,exponent); } System.out.println(power(2,3)); // I want you to write a function that will take in a list and see how many times a given number is in the list. // For example if the array given is [2,3,5,2,3,6,7,8,2] and the number given is 2 the function should print out or return 3. Print the output. void number_counter(int[] array, int target){ if (array.length == 0) { System.out.println("The array provided was empty. Please provide a valid array."); return; } int counter = 0; for (int number: array) { if (target == number) { counter++; } } System.out.println("There are " + counter + " " + target + "'s in the given array"); } // int[] array = {1,2,3,4,1,2,3,4,1,1,1,2,3,4,4,4,4}; int[] array = {}; number_counter(array, 0); // Give me a function that gives the answer to the pythagorean theorem. // I'd like you to reuse the exponent function from above as well as the functions below to make your function. // If you don't remember the pythagorean theorem the formula is (a^2 + b^2 = c^2). Given a and b as parameters i'd like you to return c. // If this doesn't make sense look up `Pythagorean Theorem Formula` on google. double addition(double a, double b) { double answer = a + b; return answer; } double division(int a, int b) { int answer = a / b; return answer; } void pythagorean_theorem(int a, int b) { double a_squared = power(a, 2); double b_squared = power(b, 2); double c_squared = addition(a_squared, b_squared); double c = Math.sqrt(c_squared); System.out.println("c comes out to be " + c + " and c squared was " + c_squared + "."); } pythagorean_theorem(3,4); ###Output c comes out to be 5.0 and c squared was 25.0. ###Markdown Lab Three---For this lab we're going to be making and using a bunch of functions. Our Goals are:- Searching our Documentation- Using built in functions- Making our own functions- Combining functions- Structuring solutions ###Code # For the following built in functions we didn't touch on them in class. I want you to look for them in the python documentation and implement them. # I want you to find a built in function to SWAP CASE on a string. Print it. # For example the string "HeY thERe HowS iT GoING" turns into "hEy THerE hOWs It gOing" sample_string = "HeY thERe HowS iT GoING" print(sample_string.swapcase()) # I want you to find a built in function to CENTER a string and pad the sides with 4 dashes(-) a side. Print it. # For example the string "Hey There" becomes "----Hey There----" sample_string = "Hey There" print(sample_string.center(17, "-")) # I want you to find a built in function to PARTITION a string. Print it. # For example the string "abcdefg.hijklmnop" would come out to be ["abcdefg",".","hijklmnop"] sample_string = "abcdefg.hijklmnop" print(sample_string.partition(".")) # I want you to write a function that will take in a number and raise it to the power given. # For example if given the numbers 2 and 3. The math that the function should do is 2^3 and should print out or return 8. Print the output. def power(number, exponent) -> int: return number ** exponent example = power(2, 3) print(example) # I want you to write a function that will take in a list and see how many times a given number is in the list. # For example if the array given is [2,3,5,2,3,6,7,8,2] and the number given is 2 the function should print out or return 3. Print the output. array = [2,3,5,2,3,6,7,8,2] def number_counter(array, target): count = 0 for number in array: if number == target: count += 1 return count example = number_counter(array, 2) print(example) # Use the functions given to create a slope function. The function should be named slope and have 4 parameters. # If you don't remember the slope formula is (y2 - y1) / (x2 - x1) If this doesn't make sense look up `Slope Formula` on google. def division(x, y): return x / y def subtraction(x, y): return x - y def slope(x1, x2, y1, y2): return division(subtraction(y2, y1), subtraction(x2, x1)) example = slope(1, 2, 1, 2) print(example) # Use the functions given to create a distance function. The function should be named function and have 4 parameters. # HINT: You'll need a built in function here too. You'll also be able to use functions written earlier in the notebook as long as you've run those cells. # If you don't remember the distance formula it is the square root of the following ((x2 - x1)^2 + (y2 - y1)^2). If this doesn't make sense look up `Distance Formula` on google. import math def addition(x, y): return x + y def distance(x1, x2, y1, y2): x_side = power(subtraction(x2, x1), 2) y_side = power(subtraction(y2, y1), 2) combined_sides = addition(x_side, y_side) return math.sqrt(combined_sides) print(distance(1, 2, 1, 2)) ###Output 1.4142135623730951
ch_05/2-plotting_with_pandas.ipynb
###Markdown Plotting with PandasThe `plot()` method is available on `Series` and `DataFrame` objects. Many of the parameters get passed down to matplotlib. The `kind` argument let's us vary the plot type. About the DataIn this notebook, we will be working with 2 datasets:- Facebook's stock price throughout 2018 (obtained using the [`stock_analysis` package](https://github.com/stefmolin/stock-analysis))- Earthquake data from September 18, 2018 - October 13, 2018 (obtained from the US Geological Survey (USGS) using the [USGS API](https://earthquake.usgs.gov/fdsnws/event/1/)) Setup ###Code %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd fb = pd.read_csv( 'data/fb_stock_prices_2018.csv', index_col='date', parse_dates=True ) quakes = pd.read_csv('data/earthquakes.csv') ###Output _____no_output_____ ###Markdown Evolution over timeLine plots help us see how a variable changes over time. They are the default for the `kind` argument, but we can pass `kind='line'` to be explicit in our intent: ###Code fb.plot( kind='line', y='open', figsize=(10, 5), style='b-', legend=False, title='Evolution of Facebook Open Price' ) ###Output _____no_output_____ ###Markdown We provided the `style` argument in the previous example; however, we can use the `color` and `linestyle` arguments to get the same result: ###Code fb.plot( kind='line', y='open', figsize=(10, 5), color='blue', linestyle='solid', legend=False, title='Evolution of Facebook Open Price' ) ###Output _____no_output_____ ###Markdown We can also plot many lines at once by simply passing a list of the columns to plot: ###Code fb.iloc[:5,].plot( y=['open', 'high', 'low', 'close'], style=['b-o', 'r--', 'k:', 'g-.'], title='Facebook OHLC Prices during 1st Week of Trading 2018' ) ###Output _____no_output_____ ###Markdown Creating subplotsWhen plotting with pandas, creating subplots is simply a matter of passing `subplots=True` to the `plot()` method, and (optionally) specifying the `layout` in a tuple of `(rows, columns)`: ###Code fb.plot( kind='line', subplots=True, layout=(3,2), figsize=(15,10), title='Facebook Stock 2018' ) ###Output _____no_output_____ ###Markdown Note that we didn't provide a specific column to plot and pandas plotted all of them for us. Visualizing relationships between variables Scatter plotsWe make scatter plots to help visualize the relationship between two variables. Creating scatter plots requires we pass in `kind='scatter'` along with a column for the x-axis and a column for the y-axis: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. Volume Traded' ) ###Output _____no_output_____ ###Markdown The relationship doesn't seem to be linear, but we can try a log transform on the x-axis since the scales of the axes are very different. With pandas, we simply pass in `logx=True`: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', logx=True ) ###Output _____no_output_____ ###Markdown With matplotlib, we could use `plt.xscale('log')` to do the same thing. Adding Transparency to Plots with `alpha`Sometimes our plots have many overlapping values, but this can be impossible to see. This can be addressed by increasing the transparency of what we are plotting using the `alpha` parameter. It is a float on [0, 1] where 0 is completely transparent and 1 is completely opaque. By default this is 1, so let's put in a lower value and re-plot the scatter plot: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', logx=True, alpha=0.25 ) ###Output _____no_output_____ ###Markdown HexbinsIn the previous example, we can start to see the overlaps, but it is still difficult. Hexbins are another plot type that divide up the plot into hexagons, which are shaded according to the density of points there. With pandas, this is the `hexbin` value for the `kind` argument. It can also be important to tweak the `gridsize`, which determines the number of hexagons along the y-axis: ###Code fb.assign( log_volume=np.log(fb.volume), max_abs_change=fb.high - fb.low ).plot( kind='hexbin', x='log_volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', colormap='gray_r', gridsize=20, sharex=False # we have to pass this to see the x-axis due to a bug in this version of pandas ) ###Output _____no_output_____ ###Markdown Visualizing Correlations with HeatmapsPandas doesn't offer heatmaps; however, if we are able to get our data into a matrix, we can use `matshow()` from matplotlib: ###Code fig, ax = plt.subplots(figsize=(20, 10)) fb_corr = fb.assign( log_volume=np.log(fb.volume), max_abs_change=fb.high - fb.low ).corr() im = ax.matshow(fb_corr, cmap='seismic') fig.colorbar(im).set_clim(-1, 1) labels = [col.lower() for col in fb_corr.columns] ax.set_xticklabels([''] + labels, rotation=45) ax.set_yticklabels([''] + labels) fb_corr.loc['max_abs_change', ['volume', 'log_volume']] ###Output _____no_output_____ ###Markdown Visualizing distributions HistogramsWith the pandas `plot()` method, making histograms is as easy as passing in `kind='hist'`: ###Code fb.volume.plot( kind='hist', title='Histogram of Daily Volume Traded in Facebook Stock' ) plt.xlabel('Volume traded') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We can overlap histograms to compare distributions provided we use the `alpha` parameter. For example, let's compare the usage and magnitude of the various `magTypes` in the data: ###Code fig, axes = plt.subplots(figsize=(8, 5)) for magtype in quakes.magType.unique(): data = quakes.query(f'magType == "{magtype}"').mag if not data.empty: data.plot( kind='hist', ax=axes, alpha=0.4, label=magtype, legend=True, title='Comparing histograms of earthquake magnitude by magType' ) plt.xlabel('magnitude') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Kernel Density Estimation (KDE)We can pass `kind='kde'` for a probability density function (PDF), which tells us the probability of getting a particular value: ###Code fb.high.plot( kind='kde', title='KDE of Daily High Price for Facebook Stock' ) plt.xlabel('Price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Adding to the result of `plot()`The `plot()` method returns a matplotlib `Axes` object. We can store this for additional customization of the plot, or we can pass this into another call to `plot()` as the `ax` argument to add to the original plot. It can often be helpful to view the KDE superimposed on top of the histogram, which can be achieved with this strategy: ###Code ax = fb.high.plot(kind='hist', density=True, alpha=0.5) fb.high.plot( ax=ax, kind='kde', color='blue', title='Distribution of Facebook Stock\'s Daily High Price in 2018' ) plt.xlabel('Price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Plotting the ECDFIn some cases, we are more interested in the probability of getting less than or equal to that value (or greater than or equal), which we can see with the cumulative disribution function (CDF). Using the `statsmodels` package, we can estimate the CDF giving us the empirical cumulative distribution function (ECDF): ###Code from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(quakes.query('magType == "ml"').mag) plt.plot(ecdf.x, ecdf.y) # axis labels (we will cover this in chapter 6) plt.xlabel('mag') # add x-axis label plt.ylabel('cumulative probability') # add y-axis label # add title (we will cover this in chapter 6) plt.title('ECDF of earthquake magnitude with magType ml') ###Output _____no_output_____ ###Markdown This ECDF tells us the probability of getting an earthquake with magnitude of 3 or less using the `ml` scale is 98%: ###Code from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(quakes.query('magType == "ml"').mag) plt.plot(ecdf.x, ecdf.y) # formatting below will all be covered in chapter 6 # axis labels plt.xlabel('mag') # add x-axis label plt.ylabel('cumulative probability') # add y-axis label # add reference lines for interpreting the ECDF for mag <= 3 plt.plot( [3, 3], [0, .98], 'k--', [-1.5, 3], [0.98, 0.98], 'k--', alpha=0.4 ) # set axis ranges plt.ylim(0, None) plt.xlim(-1.25, None) # add a title plt.title('P(mag <= 3) = 98%') ###Output _____no_output_____ ###Markdown Box plotsTo make box plots with pandas, we pass `kind='box'` to the `plot()` method: ###Code fb.iloc[:,:4].plot(kind='box', title='Facebook OHLC Prices Boxplot') plt.ylabel('price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown This can also be combined with a `groupby()`: ###Code fb.assign( volume_bin=pd.cut(fb.volume, 3, labels=['low', 'med', 'high']) ).groupby('volume_bin').boxplot( column=['open', 'high', 'low', 'close'], layout=(1, 3), figsize=(12, 3) ) plt.suptitle('Facebook OHLC Boxplots by Volume Traded', y=1.1) ###Output _____no_output_____ ###Markdown We can use this to see the distribution of magnitudes across the different measurement methods for earthquakes: ###Code quakes[['mag', 'magType']].groupby('magType').boxplot( figsize=(15, 8), subplots=False ) plt.title('Earthquake Magnitude Boxplots by magType') plt.ylabel('magnitude') # label the y-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Counts and frequencies Bar chartsWith pandas, we have the option of using the `kind` argument or using `plot.()`. Let's use `plot.bar()` here to show the evolution of monthly volume traded in Facebook stock over time: ###Code fb['2018-02':'2018-08'].assign( month=lambda x: x.index.month ).groupby('month').sum().volume.plot.bar( color='green', rot=0, title='Volume Traded' ) plt.ylabel('volume') # label the y-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We can also change the orientation of the bars. Passing `kind='barh'` gives us horizontal bars instead of vertical ones. Let's use this to look at the top 15 places for earthquakes in our data: ###Code quakes.parsed_place.value_counts().iloc[14::-1,].plot( kind='barh', figsize=(10, 5), title='Top 15 Places for Earthquakes '\ '(September 18, 2018 - October 13, 2018)' ) plt.xlabel('earthquakes') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We also have data on whether earthquakes were accompanied by tsunamis. Let's see what the top places for tsunamis are: ###Code quakes.groupby('parsed_place').tsunami.sum().sort_values().iloc[-10::,].plot( kind='barh', figsize=(10, 5), title='Top 10 Places for Tsunamis '\ '(September 18, 2018 - October 13, 2018)' ) plt.xlabel('tsunamis') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Seeing that Indonesia is the top place for tsunamis during the time period we are looking at, we may want to look how many earthquakes and tsunamis Indonesia gets on a daily basis. We could show this as a line plot or with bars; since this section is about bars, we will use bars here: ###Code indonesia_quakes = quakes.query('parsed_place == "Indonesia"').assign( time=lambda x: pd.to_datetime(x.time, unit='ms'), earthquake=1 ).set_index('time').resample('1D').sum() indonesia_quakes.index = indonesia_quakes.index.strftime('%b\n%d') indonesia_quakes.plot( y=['earthquake', 'tsunami'], kind='bar', figsize=(15, 3), rot=0, label=['earthquakes', 'tsunamis'], title='Earthquakes and Tsunamis in Indonesia '\ '(September 18, 2018 - October 13, 2018)' ) # label the axes (discussed in chapter 6) plt.xlabel('date') plt.ylabel('count') ###Output _____no_output_____ ###Markdown Using the `kind` arugment for vertical bars when the labels for each bar are shorter: ###Code quakes.magType.value_counts().plot( kind='bar', title='Earthquakes Recorded per magType', rot=0 ) # label the axes (discussed in chapter 6) plt.xlabel('magType') plt.ylabel('earthquakes') ###Output _____no_output_____ ###Markdown Top 4 places with earthquakes: ###Code quakes[ quakes.parsed_place.isin(['California', 'Alaska', 'Nevada', 'Hawaii']) ].groupby(['parsed_place', 'magType']).mag.count().unstack().plot.bar( title='magTypes used in top 4 places with earthquakes' ) plt.ylabel('earthquakes') # label the axes (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Stacked bar chart ###Code pivot = quakes.assign( mag_bin=lambda x: np.floor(x.mag) ).pivot_table( index='mag_bin', columns='magType', values='mag', aggfunc='count' ) pivot.plot.bar( stacked=True, rot=0, title='Earthquakes by integer magnitude and magType' ) plt.ylabel('earthquakes') # label the axes (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Normalized stacked barsPlot the percentages to be better able to see the different `magTypes`. ###Code normalized_pivot = pivot.fillna(0).apply(lambda x: x/x.sum(), axis=1) ax = normalized_pivot.plot.bar( stacked=True, rot=0, figsize=(10, 5), title='Percentage of earthquakes by integer magnitude for each magType' ) ax.legend(bbox_to_anchor=(1, 0.8)) # move legend to the right of the plot plt.ylabel('percentage') # label the axes (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Plotting with PandasThe `plot()` method is available on `Series` and `DataFrame` objects. Many of the parameters get passed down to `matplotlib`. The `kind` argument let's us vary the plot type. Here are some commonly used parameters:| Parameter | Purpose | Data Type || --- | --- | --- || `kind` | Determines the plot type | String || `x`/`y` | Column(s) to plot on the *x*-axis/*y*-axis | String or list || `ax` | Draws the plot on the `Axes` object provided | `Axes` || `subplots` | Determines whether to make subplots | Boolean || `layout` | Specifies how to arrange the subplots | Tuple of `(rows, columns)` || `figsize` | Size to make the `Figure` object | Tuple of `(width, height)` | | `title` | The title of the plot or subplots | String for the plot title or a list of strings for subplot titles || `legend` | Determines whether to show the legend | Boolean || `label` | What to call an item in the legend | String if a single column is being plotted; otherwise, a list of strings || `style` | `matplotlib` style strings for each item being plotted | String if a single column is being plotted; otherwise, a list of strings || `color` | The color to plot the item in | String or red, green, blue tuple if a single column is being plotted; otherwise, a list || `colormap` | The colormap to use | String or `matplotlib` colormap object || `logx`/`logy`/`loglog` | Determines whether to use a logarithmic scale for the *x*-axis, *y*-axis, or both | Boolean || `xticks`/`yticks` | Determines where to draw the ticks on the *x*-axis/*y*-axis | List of values || `xlim`/`ylim` | The axis limits for the *x*-axis/*y*-axis | Tuple of the form `(min, max)` || `rot` | The angle to write the tick labels at | Integer || `sharex`/`sharey` | Determines whether to have subplots share the *x*-axis/*y*-axis | Boolean || `fontsize` | Controls the size of the tick labels | Integer || `grid` | Turns on/off the grid lines | Boolean | About the DataIn this notebook, we will be working with 3 datasets:- Facebook's stock price throughout 2018 (obtained using the [`stock_analysis` package](https://github.com/stefmolin/stock-analysis))- Earthquake data from September 18, 2018 - October 13, 2018 (obtained from the US Geological Survey (USGS) using the [USGS API](https://earthquake.usgs.gov/fdsnws/event/1/))- European Centre for Disease Prevention and Control's (ECDC) [daily number of new reported cases of COVID-19 by country worldwide dataset](https://www.ecdc.europa.eu/en/publications-data/download-todays-data-geographic-distribution-covid-19-cases-worldwide) collected on September 19, 2020 via [this link](https://opendata.ecdc.europa.eu/covid19/casedistribution/csv) Setup ###Code %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd fb = pd.read_csv( 'data/fb_stock_prices_2018.csv', index_col='date', parse_dates=True ) quakes = pd.read_csv('data/earthquakes.csv') covid = pd\ .read_csv('data/covid19_cases.csv')\ .assign( date=lambda x: pd.to_datetime(x.dateRep, format='%d/%m/%Y') )\ .set_index('date')\ .replace('United_States_of_America', 'USA')\ .sort_index()['2020-01-18':'2020-09-18'] ###Output _____no_output_____ ###Markdown Evolution over timeLine plots help us see how a variable changes over time. They are the default for the `kind` argument, but we can pass `kind='line'` to be explicit in our intent: ###Code fb.plot( kind='line', y='open', figsize=(10, 5), style='-b', legend=False, title='Evolution of Facebook Open Price' ) ###Output _____no_output_____ ###Markdown We provided the `style` argument in the previous example; however, we can use the `color` and `linestyle` arguments to get the same result: ###Code fb.plot( kind='line', y='open', figsize=(10, 5), color='blue', linestyle='solid', legend=False, title='Evolution of Facebook Open Price' ) ###Output _____no_output_____ ###Markdown We can also plot many lines at once by simply passing a list of the columns to plot: ###Code fb\ .first('1W')\ .plot( y=['open', 'high', 'low', 'close'], style=['o-b', '--r', ':k', '.-g'], title='Facebook OHLC Prices during 1st Week of Trading 2018' )\ .autoscale() ###Output _____no_output_____ ###Markdown Creating subplotsWhen plotting with `pandas`, creating subplots is simply a matter of passing `subplots=True` to the `plot()` method, and (optionally) specifying the `layout` in a tuple of `(rows, columns)`: ###Code fb.plot( kind='line', subplots=True, layout=(3, 2), figsize=(15, 10), title='Facebook Stock 2018' ) ###Output _____no_output_____ ###Markdown Note that we didn't provide a specific column to plot and `pandas` plotted all of them for us.Sometimes we want to make subplots that each have a few variables in them for comparison. This can be achieved using the `ax` parameter. To illustrate this, let's take a look at daily new COVID-19 cases in China, Spain, Italy, the USA, Brazil, and India: ###Code new_cases_rolling_average = covid.pivot_table( index=covid.index, columns='countriesAndTerritories', values='cases' )\ .rolling(7).mean() ###Output _____no_output_____ ###Markdown Since there is a lot of fluctuation in these values, we will plot the 7-day moving average of new cases using the `rolling()` method (discussed in chapter 4). Rather than create a separate plot for each country (which makes it harder to compare) or plot them all together (which will make it difficult to see the smaller values), we will plot countries that have had a similar number of cases in the same subplot: ###Code fig, axes = plt.subplots(1, 3, figsize=(15, 5)) new_cases_rolling_average[['China']]\ .plot( ax=axes[0], style='-.c' ) new_cases_rolling_average[['Italy', 'Spain']]\ .plot( ax=axes[1], style=['-', '--'], title='7-day rolling average of new COVID-19 cases\n' + \ '(source: ECDC)' ) new_cases_rolling_average[['Brazil', 'India', 'USA']]\ .plot( ax=axes[2], style=['--', ':', '-'] ) ###Output _____no_output_____ ###Markdown *NOTE: we specified the line styles here so that the lines can be distinguished in the text as a black and white image.*In the previous figure, we were able to compare countries with similar levels of new COVID-19 cases, but we couldn't compare all of them in the same plot due to scale. One way around this is to use an **area plot**, which makes it possible for us to visualize the overall 7-day rolling average of new COVID-19 cases and at the same time how much each country is contributing to the total. In the interest of readability, we will group Italy and Spain together and create another category for countries other than the USA, Brazil, and India. The combined height of the plot areas is the overall value, and the height of given shaded region is the value for the individual country. ###Code countries = ['USA', 'Brazil', 'India', 'Italy & Spain'] otherCountries = [ col for col in new_cases_rolling_average.columns if col not in countries ] new_cases_rolling_average\ .assign( **{'Italy & Spain': lambda x: x.Italy + x.Spain} )\ .sort_index(axis=1)\ .assign(Other=lambda x: x[otherCountries].sum(axis=1))\ .drop(columns=otherCountries)\ .plot( kind='area', figsize=(15, 5), title='7-day rolling average of new COVID-19 cases\n' + \ '(source: ECDC)' ) ###Output _____no_output_____ ###Markdown Another way to visualize evolution over time is to look at the cumulative sum over time. Let's plot the cumulative number of COVID-19 cases in China, Spain, Italy, the USA, Brazil, and India, using `ax` to create subplots as we did in the previous example. ###Code fig, axes = plt.subplots(1, 3, figsize=(15, 3)) cumulative_covid_cases = covid\ .groupby( ['countriesAndTerritories', pd.Grouper(freq='1D')] )\ .cases.sum()\ .unstack(0)\ .apply('cumsum') cumulative_covid_cases[['China']]\ .plot( ax=axes[0], style='-.c' ) cumulative_covid_cases[['Italy', 'Spain']]\ .plot( ax=axes[1], style=['-', '--'], title='Cumulative COVID-19 Cases\n(source: ECDC)' ) cumulative_covid_cases[['Brazil', 'India', 'USA']]\ .plot( ax=axes[2], style=['--', ':', '-'] ) ###Output _____no_output_____ ###Markdown *NOTE: we specified the line styles here so that the lines can be distinguished in the text as a black and white image.* Visualizing relationships between variables Scatter plotsWe make scatter plots to help visualize the relationship between two variables. Creating scatter plots requires we pass in `kind='scatter'` along with a column for the x-axis and a column for the y-axis: ###Code fb\ .assign( max_abs_change=fb.high - fb.low)\ .plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. Volume Traded' ) ###Output _____no_output_____ ###Markdown The relationship doesn't seem to be linear, but we can try a log transform on the x-axis since the scales of the axes are very different. With `pandas`, we simply pass in `logx=True`: ###Code fb\ .assign( max_abs_change=fb.high - fb.low )\ .plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', logx=True ) ###Output _____no_output_____ ###Markdown With `matplotlib`, we could use `plt.xscale('log')` to do the same thing. Adding Transparency to Plots with `alpha`Sometimes our plots have many overlapping values, but this can be impossible to see. This can be addressed by increasing the transparency of what we are plotting using the `alpha` parameter. It is a float in the range [0, 1] where 0 is completely transparent and 1 is completely opaque. By default this is 1, so let's put in a lower value and re-plot the scatter plot: ###Code fb\ .assign( max_abs_change=fb.high - fb.low )\ .plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', logx=True, alpha=0.25 ) ###Output _____no_output_____ ###Markdown HexbinsIn the previous example, we can start to see the overlaps, but it is still difficult. Hexbins are another plot type that divide up the plot into hexagons, which are shaded according to the density of points there. With `pandas`, this is the `hexbin` value for the `kind` argument. It may also be necessary to tweak the `gridsize`, which determines the number of hexagons along the y-axis: ###Code fb\ .assign( log_volume=np.log(fb.volume), max_abs_change=fb.high - fb.low )\ .plot( kind='hexbin', x='log_volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', colormap='gray_r', gridsize=20, sharex=False # we have to pass this to see the x-axis ) ###Output _____no_output_____ ###Markdown Visualizing Correlations with HeatmapsPandas doesn't offer heatmaps; however, if we are able to get our data into a matrix, we can use `matshow()` from matplotlib: ###Code fig, ax = plt.subplots(figsize=(20, 10)) # Calculate the correlation matrix fb_corr = fb\ .assign( log_volume=np.log(fb.volume), max_abs_change=fb.high - fb.low )\ .corr() # Create the heatmap and colorbar im = ax.matshow( fb_corr, cmap='seismic' ) im.set_clim(-1, 1) fig.colorbar(im) # Label the ticks with the column names labels = list( col.lower() for col in fb_corr.columns ) ax.set_xticks(ax.get_xticks()[1:-1]) # to handle bug in matplotlib ax.set_xticklabels(labels, rotation=45) ax.set_yticks(ax.get_yticks()[1:-1]) # to handle bug in matplotlib ax.set_yticklabels(labels) # Include the value of the correlation coefficient in the boxes for (i, j), coef in np.ndenumerate(fb_corr): ax.text( i, j, fr'$\rho$ = {coef:.2f}', # raw (r), format (f) string ha='center', va='center', color='white', fontsize=14 ) ###Output _____no_output_____ ###Markdown Accessing the values in the correlation matrix can be done with `loc[]`: ###Code fb_corr.loc[ 'max_abs_change', ['volume', 'log_volume'] ] ###Output _____no_output_____ ###Markdown Visualizing distributions HistogramsWith the `pandas`, making histograms is as easy as passing `kind='hist'` to the `plot()` method: ###Code fb.volume.plot( kind='hist', title='Histogram of Daily Volume Traded in Facebook Stock' ) plt.xlabel('Volume traded') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We can overlap histograms to compare distributions provided we use the `alpha` parameter. For example, let's compare the usage and magnitude of the various measurement techniques (the `magType` column) in the data: ###Code fig, axes = plt.subplots(figsize=(8, 5)) for magtype in quakes.magType.unique(): data = quakes\ .query(f'magType == "{magtype}"')\ .mag if not data.empty: data.plot( kind='hist', ax=axes, alpha=0.4, label=magtype, legend=True, title='Comparing histograms of earthquake magnitude by magType' ) plt.xlabel('magnitude') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Kernel Density Estimation (KDE)We can pass `kind='kde'` for an estimate of the probability density function (PDF), which tells us the probability of getting a particular value: ###Code fb.high.plot( kind='kde', title='KDE of Daily High Price for Facebook Stock' ) plt.xlabel('Price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Adding to the result of `plot()`The `plot()` method returns an `Axes` object. We can store this for additional customization of the plot, or we can pass this into another call to `plot()` as the `ax` argument to add to the original plot. It can often be helpful to view the KDE superimposed on top of the histogram, which can be achieved with this strategy: ###Code ax = fb.high.plot( kind='hist', density=True, alpha=0.5 ) fb.high.plot( ax=ax, kind='kde', color='blue', title='Distribution of Facebook Stock\'s Daily High Price in 2018' ) plt.xlabel('Price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Plotting the ECDFIn some cases, we are more interested in the probability of getting less than or equal to that value (or greater than or equal), which we can see with the **cumulative disribution function (CDF)**. Using the `statsmodels` package, we can estimate the CDF giving us the **empirical cumulative distribution function (ECDF)**: ###Code from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(quakes.query('magType == "ml"').mag) plt.plot(ecdf.x, ecdf.y) # Axis labels (we will cover this in chapter 6) plt.xlabel('mag') # add x-axis label plt.ylabel('cumulative probability') # add y-axis label # add title (we will cover this in chapter 6) plt.title('ECDF of earthquake magnitude with magType ml') ###Output _____no_output_____ ###Markdown This ECDF tells us the probability of getting an earthquake with magnitude of 3 or less using the `ml` scale is 98%: ###Code from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(quakes.query('magType == "ml"').mag) plt.plot(ecdf.x, ecdf.y) # Formatting below will all be covered in chapter 6 # axis labels plt.xlabel('mag') # add x-axis label plt.ylabel('cumulative probability') # add y-axis label # Add reference lines for interpreting the ECDF for mag <= 3 plt.plot( [3, 3], [0, .98], '--k', [-1.5, 3], [0.98, 0.98], '--k', alpha=0.4 ) # Set axis ranges plt.ylim(0, None) plt.xlim(-1.25, None) # add a title plt.title('P(mag <= 3) = 98%') ###Output _____no_output_____ ###Markdown Box plotsTo make box plots with `pandas`, we pass `kind='box'` to the `plot()` method: ###Code fb\ .iloc[:,:4]\ .plot( kind='box', title='Facebook OHLC Prices Box Plot' ) plt.ylabel('price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown If we pass in `notch=True`, we get a notched box plot. The notch represents a 95% confidence interval around the median, which can be helpful when comparing differences. For an introduction to interpreting a notched box plot, see this [Google sites page](https://sites.google.com/site/davidsstatistics/home/notched-box-plots) and this [Towards Data Science article](https://towardsdatascience.com/understanding-boxplots-5e2df7bcbd51). ###Code fb\ .iloc[:,:4]\ .plot( kind='box', title='Facebook OHLC Prices Box Plot', notch=True ) plt.ylabel('price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown This can also be combined with a call to `groupby()`: ###Code fb\ .assign( volume_bin=pd.cut( fb.volume, 3, labels=['low', 'med', 'high'] ) )\ .groupby('volume_bin')\ .boxplot( column=['open', 'high', 'low', 'close'], layout=(1, 3), figsize=(12, 3) ) plt.suptitle('Facebook OHLC Box Plots by Volume Traded', y=1.1) ###Output _____no_output_____ ###Markdown We can use this to see the distribution of magnitudes across the different measurement methods for earthquakes: ###Code quakes[['mag', 'magType']]\ .groupby('magType')\ .boxplot( figsize=(15, 8), subplots=False ) plt.title('Earthquake Magnitude Box Plots by magType') plt.ylabel('magnitude') # label the y-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Counts and frequencies Bar chartsPassing `kind='barh'` gives us horizontal bars while `kind='bar'` gives us vertical ones. Let's use horizontal bars to look at the top 15 places for earthquakes in our data: ###Code ''' quakes.parsed_place\ .value_counts()\ .iloc[14::-1,]\ .plot( kind='barh', figsize=(10, 5), title='Top 15 Places for Earthquakes ' '(September 18, 2018 - October 13, 2018)' ) ''' quakes.parsed_place\ .value_counts()\ .iloc[:14:,]\ .sort_values()\ .plot( kind='barh', figsize=(10, 5), title='Top 15 Places for Earthquakes ' '(September 18, 2018 - October 13, 2018)' ) plt.xlabel('earthquakes') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We also have data on whether earthquakes were accompanied by tsunamis. Let's see what the top places for tsunamis are: ###Code quakes\ .groupby('parsed_place')\ .tsunami.sum()\ .sort_values()\ .iloc[-10:,]\ .plot( kind='barh', figsize=(10, 5), title='Top 10 Places for Tsunamis ' '(September 18, 2018 - October 13, 2018)' ) plt.xlabel('tsunamis') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Seeing that Indonesia is the top place for tsunamis during the time period we are looking at, we may want to look how many earthquakes and tsunamis Indonesia gets on a daily basis. We could show this as a line plot or with bars; since we don't want to interpolate, we will use bars here: ###Code indonesia_quakes = quakes\ .query('parsed_place == "Indonesia"')\ .assign( time=lambda x: pd.to_datetime(x.time, unit='ms'), earthquake=1 )\ .set_index('time')\ .resample('1D').sum() # Format the datetimes in the index for the x-axis indonesia_quakes.index = indonesia_quakes.index.strftime('%b\n%d') indonesia_quakes.plot( y=['earthquake', 'tsunami'], kind='bar', figsize=(15, 3), rot=0, label=['earthquakes', 'tsunamis'], title='Earthquakes and Tsunamis in Indonesia ' '(September 18, 2018 - October 13, 2018)' ) # label the axes (discussed in chapter 6) plt.xlabel('date') plt.ylabel('count') ###Output _____no_output_____ ###Markdown Grouped Bars ###Code quakes\ .groupby(['parsed_place', 'tsunami'])\ .mag.count()\ .unstack()\ .apply(lambda x: x / x.sum(), axis=1)\ .rename(columns={0: 'no', 1: 'yes'})\ .sort_values('yes', ascending=False)[7::-1]\ .plot.barh( title='Frequency of a tsunami accompanying an earthquake' ) # Move legend to the right of the plot plt.legend( title='tsunami?', bbox_to_anchor=(1, 0.65) ) # label the axes (discussed in chapter 6) plt.xlabel('percentage of earthquakes') plt.ylabel('') ###Output _____no_output_____ ###Markdown Using the `kind` argument for vertical bars when the labels for each bar are shorter: ###Code quakes.magType\ .value_counts()\ .plot( kind='bar', title='Earthquakes Recorded per magType', rot=0 ) # label the axes (discussed in chapter 6) plt.xlabel('magType') plt.ylabel('earthquakes') ###Output _____no_output_____ ###Markdown Stacked bars ###Code pivot = quakes\ .assign( mag_bin=lambda x: np.floor(x.mag) )\ .pivot_table( index='mag_bin', columns='magType', values='mag', aggfunc='count' ) pivot.plot.bar( stacked=True, rot=0, ylabel='earthquakes', title='Earthquakes by integer magnitude and magType' ) ###Output _____no_output_____ ###Markdown Normalized stacked barsPlot the percentages to be better able to see the different `magTypes`. ###Code normalized_pivot = pivot\ .fillna(0)\ .apply(lambda x: x / x.sum(), axis=1) ax = normalized_pivot\ .plot.bar( stacked=True, rot=0, figsize=(10, 5), title='Percentage of earthquakes by integer magnitude for each magType' ) ax.legend(bbox_to_anchor=(1, 0.8)) # move legend to the right of the plot plt.ylabel('percentage') # label the axes (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We can also create horizontal stacked bars and do so using `groupby()` and `unstack()`: ###Code quakes\ .groupby(['parsed_place', 'tsunami'])\ .mag.count()\ .unstack()\ .apply(lambda x: x / x.sum(), axis=1)\ .rename(columns={0: 'no', 1: 'yes'})\ .sort_values('yes', ascending=False)[7::-1]\ .plot.barh( title='Frequency of a tsunami accompanying an earthquake', stacked=True ) # Move legend to the right of the plot plt.legend(title='tsunami?', bbox_to_anchor=(1, 0.65)) # Label the axes (discussed in chapter 6) plt.xlabel('percentage of earthquakes') plt.ylabel('') ###Output _____no_output_____ ###Markdown Plotting with PandasThe `plot()` method is available on `Series` and `DataFrame` objects. Many of the parameters get passed down to `matplotlib`. The `kind` argument let's us vary the plot type. Here are some commonly used parameters:| Parameter | Purpose | Data Type || --- | --- | --- || `kind` | Determines the plot type | String || `x`/`y` | Column(s) to plot on the *x*-axis/*y*-axis | String or list || `ax` | Draws the plot on the `Axes` object provided | `Axes` || `subplots` | Determines whether to make subplots | Boolean || `layout` | Specifies how to arrange the subplots | Tuple of `(rows, columns)` || `figsize` | Size to make the `Figure` object | Tuple of `(width, height)` | | `title` | The title of the plot or subplots | String for the plot title or a list of strings for subplot titles || `legend` | Determines whether to show the legend | Boolean || `label` | What to call an item in the legend | String if a single column is being plotted; otherwise, a list of strings || `style` | `matplotlib` style strings for each item being plotted | String if a single column is being plotted; otherwise, a list of strings || `color` | The color to plot the item in | String or red, green, blue tuple if a single column is being plotted; otherwise, a list || `colormap` | The colormap to use | String or `matplotlib` colormap object || `logx`/`logy`/`loglog` | Determines whether to use a logarithmic scale for the *x*-axis, *y*-axis, or both | Boolean || `xticks`/`yticks` | Determines where to draw the ticks on the *x*-axis/*y*-axis | List of values || `xlim`/`ylim` | The axis limits for the *x*-axis/*y*-axis | Tuple of the form `(min, max)` || `rot` | The angle to write the tick labels at | Integer || `sharex`/`sharey` | Determines whether to have subplots share the *x*-axis/*y*-axis | Boolean || `fontsize` | Controls the size of the tick labels | Integer || `grid` | Turns on/off the grid lines | Boolean | About the DataIn this notebook, we will be working with 3 datasets:- Facebook's stock price throughout 2018 (obtained using the [`stock_analysis` package](https://github.com/stefmolin/stock-analysis))- Earthquake data from September 18, 2018 - October 13, 2018 (obtained from the US Geological Survey (USGS) using the [USGS API](https://earthquake.usgs.gov/fdsnws/event/1/))- European Centre for Disease Prevention and Control's (ECDC) [daily number of new reported cases of COVID-19 by country worldwide dataset](https://www.ecdc.europa.eu/en/publications-data/download-todays-data-geographic-distribution-covid-19-cases-worldwide) collected on September 19, 2020 via [this link](https://opendata.ecdc.europa.eu/covid19/casedistribution/csv) Setup ###Code %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd fb = pd.read_csv( 'data/fb_stock_prices_2018.csv', index_col='date', parse_dates=True ) quakes = pd.read_csv('data/earthquakes.csv') covid = pd.read_csv('data/covid19_cases.csv').assign( date=lambda x: pd.to_datetime(x.dateRep, format='%d/%m/%Y') ).set_index('date').replace( 'United_States_of_America', 'USA' ).sort_index()['2020-01-18':'2020-09-18'] ###Output _____no_output_____ ###Markdown Evolution over timeLine plots help us see how a variable changes over time. They are the default for the `kind` argument, but we can pass `kind='line'` to be explicit in our intent: ###Code fb.plot( kind='line', y='open', figsize=(10, 5), style='-b', legend=False, title='Evolution of Facebook Open Price' ) ###Output _____no_output_____ ###Markdown We provided the `style` argument in the previous example; however, we can use the `color` and `linestyle` arguments to get the same result: ###Code fb.plot( kind='line', y='open', figsize=(10, 5), color='blue', linestyle='solid', legend=False, title='Evolution of Facebook Open Price' ) ###Output _____no_output_____ ###Markdown We can also plot many lines at once by simply passing a list of the columns to plot: ###Code fb.first('1W').plot( y=['open', 'high', 'low', 'close'], style=['o-b', '--r', ':k', '.-g'], title='Facebook OHLC Prices during 1st Week of Trading 2018' ).autoscale() ###Output _____no_output_____ ###Markdown Creating subplotsWhen plotting with `pandas`, creating subplots is simply a matter of passing `subplots=True` to the `plot()` method, and (optionally) specifying the `layout` in a tuple of `(rows, columns)`: ###Code fb.plot( kind='line', subplots=True, layout=(3, 2), figsize=(15, 10), title='Facebook Stock 2018' ) ###Output _____no_output_____ ###Markdown Note that we didn't provide a specific column to plot and `pandas` plotted all of them for us.Sometimes we want to make subplots that each have a few variables in them for comparison. This can be achieved using the `ax` parameter. To illustrate this, let's take a look at daily new COVID-19 cases in China, Spain, Italy, the USA, Brazil, and India: ###Code new_cases_rolling_average = covid.pivot_table( index=covid.index, columns='countriesAndTerritories', values='cases' ).rolling(7).mean() ###Output _____no_output_____ ###Markdown Since there is a lot of fluctuation in these values, we will plot the 7-day moving average of new cases using the `rolling()` method (discussed in chapter 4). Rather than create a separate plot for each country (which makes it harder to compare) or plot them all together (which will make it difficult to see the smaller values), we will plot countries that have had a similar number of cases in the same subplot: ###Code fig, axes = plt.subplots(1, 3, figsize=(15, 5)) new_cases_rolling_average[['China']].plot(ax=axes[0], style='-.c') new_cases_rolling_average[['Italy', 'Spain']].plot( ax=axes[1], style=['-', '--'], title='7-day rolling average of new COVID-19 cases\n(source: ECDC)' ) new_cases_rolling_average[['Brazil', 'India', 'USA']]\ .plot(ax=axes[2], style=['--', ':', '-']) ###Output _____no_output_____ ###Markdown *NOTE: we specified the line styles here so that the lines can be distinguished in the text as a black and white image.*In the previous figure, we were able to compare countries with similar levels of new COVID-19 cases, but we couldn't compare all of them in the same plot due to scale. One way around this is to use an **area plot**, which makes it possible for us to visualize the overall 7-day rolling average of new COVID-19 cases and at the same time how much each country is contributing to the total. In the interest of readability, we will group Italy and Spain together and create another category for countries other than the USA, Brazil, and India. The combined height of the plot areas is the overall value, and the height of given shaded region is the value for the individual country. ###Code cols = [ col for col in new_cases_rolling_average.columns if col not in ['USA', 'Brazil', 'India', 'Italy & Spain'] ] new_cases_rolling_average.assign( **{'Italy & Spain': lambda x: x.Italy + x.Spain} ).sort_index(axis=1).assign( Other=lambda x: x[cols].sum(axis=1) ).drop(columns=cols).plot( kind='area', figsize=(15, 5), title='7-day rolling average of new COVID-19 cases\n(source: ECDC)' ) ###Output _____no_output_____ ###Markdown Another way to visualize evolution over time is to look at the cumulative sum over time. Let's plot the cumulative number of COVID-19 cases in China, Spain, Italy, the USA, Brazil, and India, using `ax` to create subplots as we did in the previous example. ###Code fig, axes = plt.subplots(1, 3, figsize=(15, 3)) cumulative_covid_cases = covid.groupby( ['countriesAndTerritories', pd.Grouper(freq='1D')] ).cases.sum().unstack(0).apply('cumsum') cumulative_covid_cases[['China']].plot(ax=axes[0], style='-.c') cumulative_covid_cases[['Italy', 'Spain']].plot( ax=axes[1], style=['-', '--'], title='Cumulative COVID-19 Cases\n(source: ECDC)' ) cumulative_covid_cases[['Brazil', 'India', 'USA']]\ .plot(ax=axes[2], style=['--', ':', '-']) ###Output _____no_output_____ ###Markdown *NOTE: we specified the line styles here so that the lines can be distinguished in the text as a black and white image.* Visualizing relationships between variables Scatter plotsWe make scatter plots to help visualize the relationship between two variables. Creating scatter plots requires we pass in `kind='scatter'` along with a column for the x-axis and a column for the y-axis: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. Volume Traded' ) ###Output _____no_output_____ ###Markdown The relationship doesn't seem to be linear, but we can try a log transform on the x-axis since the scales of the axes are very different. With `pandas`, we simply pass in `logx=True`: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', logx=True ) ###Output _____no_output_____ ###Markdown With `matplotlib`, we could use `plt.xscale('log')` to do the same thing. Adding Transparency to Plots with `alpha`Sometimes our plots have many overlapping values, but this can be impossible to see. This can be addressed by increasing the transparency of what we are plotting using the `alpha` parameter. It is a float in the range [0, 1] where 0 is completely transparent and 1 is completely opaque. By default this is 1, so let's put in a lower value and re-plot the scatter plot: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', logx=True, alpha=0.25 ) ###Output _____no_output_____ ###Markdown HexbinsIn the previous example, we can start to see the overlaps, but it is still difficult. Hexbins are another plot type that divide up the plot into hexagons, which are shaded according to the density of points there. With `pandas`, this is the `hexbin` value for the `kind` argument. It may also be necessary to tweak the `gridsize`, which determines the number of hexagons along the y-axis: ###Code fb.assign( log_volume=np.log(fb.volume), max_abs_change=fb.high - fb.low ).plot( kind='hexbin', x='log_volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', colormap='gray_r', gridsize=20, sharex=False # we have to pass this to see the x-axis ) ###Output _____no_output_____ ###Markdown Visualizing Correlations with HeatmapsPandas doesn't offer heatmaps; however, if we are able to get our data into a matrix, we can use `matshow()` from matplotlib: ###Code fig, ax = plt.subplots(figsize=(20, 10)) # calculate the correlation matrix fb_corr = fb.assign( log_volume=np.log(fb.volume), max_abs_change=fb.high - fb.low ).corr() # create the heatmap and colorbar im = ax.matshow(fb_corr, cmap='seismic') im.set_clim(-1, 1) fig.colorbar(im) # label the ticks with the column names labels = [col.lower() for col in fb_corr.columns] ax.set_xticks(ax.get_xticks()[1:-1]) # to handle bug in matplotlib ax.set_xticklabels(labels, rotation=45) ax.set_yticks(ax.get_yticks()[1:-1]) # to handle bug in matplotlib ax.set_yticklabels(labels) # include the value of the correlation coefficient in the boxes for (i, j), coef in np.ndenumerate(fb_corr): ax.text( i, j, fr'$\rho$ = {coef:.2f}', # raw (r), format (f) string ha='center', va='center', color='white', fontsize=14 ) ###Output _____no_output_____ ###Markdown Accessing the values in the correlation matrix can be done with `loc[]`: ###Code fb_corr.loc['max_abs_change', ['volume', 'log_volume']] ###Output _____no_output_____ ###Markdown Visualizing distributions HistogramsWith the `pandas`, making histograms is as easy as passing `kind='hist'` to the `plot()` method: ###Code fb.volume.plot( kind='hist', title='Histogram of Daily Volume Traded in Facebook Stock' ) plt.xlabel('Volume traded') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We can overlap histograms to compare distributions provided we use the `alpha` parameter. For example, let's compare the usage and magnitude of the various measurement techniques (the `magType` column) in the data: ###Code fig, axes = plt.subplots(figsize=(8, 5)) for magtype in quakes.magType.unique(): data = quakes.query(f'magType == "{magtype}"').mag if not data.empty: data.plot( kind='hist', ax=axes, alpha=0.4, label=magtype, legend=True, title='Comparing histograms of earthquake magnitude by magType' ) plt.xlabel('magnitude') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Kernel Density Estimation (KDE)We can pass `kind='kde'` for an estimate of the probability density function (PDF), which tells us the probability of getting a particular value: ###Code fb.high.plot( kind='kde', title='KDE of Daily High Price for Facebook Stock' ) plt.xlabel('Price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Adding to the result of `plot()`The `plot()` method returns an `Axes` object. We can store this for additional customization of the plot, or we can pass this into another call to `plot()` as the `ax` argument to add to the original plot. It can often be helpful to view the KDE superimposed on top of the histogram, which can be achieved with this strategy: ###Code ax = fb.high.plot(kind='hist', density=True, alpha=0.5) fb.high.plot( ax=ax, kind='kde', color='blue', title='Distribution of Facebook Stock\'s Daily High Price in 2018' ) plt.xlabel('Price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Plotting the ECDFIn some cases, we are more interested in the probability of getting less than or equal to that value (or greater than or equal), which we can see with the **cumulative disribution function (CDF)**. Using the `statsmodels` package, we can estimate the CDF giving us the **empirical cumulative distribution function (ECDF)**: ###Code from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(quakes.query('magType == "ml"').mag) plt.plot(ecdf.x, ecdf.y) # axis labels (we will cover this in chapter 6) plt.xlabel('mag') # add x-axis label plt.ylabel('cumulative probability') # add y-axis label # add title (we will cover this in chapter 6) plt.title('ECDF of earthquake magnitude with magType ml') ###Output _____no_output_____ ###Markdown This ECDF tells us the probability of getting an earthquake with magnitude of 3 or less using the `ml` scale is 98%: ###Code from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(quakes.query('magType == "ml"').mag) plt.plot(ecdf.x, ecdf.y) # formatting below will all be covered in chapter 6 # axis labels plt.xlabel('mag') # add x-axis label plt.ylabel('cumulative probability') # add y-axis label # add reference lines for interpreting the ECDF for mag <= 3 plt.plot( [3, 3], [0, .98], '--k', [-1.5, 3], [0.98, 0.98], '--k', alpha=0.4 ) # set axis ranges plt.ylim(0, None) plt.xlim(-1.25, None) # add a title plt.title('P(mag <= 3) = 98%') ###Output _____no_output_____ ###Markdown Box plotsTo make box plots with `pandas`, we pass `kind='box'` to the `plot()` method: ###Code fb.iloc[:,:4].plot(kind='box', title='Facebook OHLC Prices Box Plot') plt.ylabel('price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown If we pass in `notch=True`, we get a notched box plot. The notch represents a 95% confidence interval around the median, which can be helpful when comparing differences. For an introduction to interpreting a notched box plot, see this [Google sites page](https://sites.google.com/site/davidsstatistics/home/notched-box-plots) and this [Towards Data Science article](https://towardsdatascience.com/understanding-boxplots-5e2df7bcbd51). ###Code fb.iloc[:,:4].plot(kind='box', title='Facebook OHLC Prices Box Plot', notch=True) plt.ylabel('price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown This can also be combined with a call to `groupby()`: ###Code fb.assign( volume_bin=pd.cut(fb.volume, 3, labels=['low', 'med', 'high']) ).groupby('volume_bin').boxplot( column=['open', 'high', 'low', 'close'], layout=(1, 3), figsize=(12, 3) ) plt.suptitle('Facebook OHLC Box Plots by Volume Traded', y=1.1) ###Output _____no_output_____ ###Markdown We can use this to see the distribution of magnitudes across the different measurement methods for earthquakes: ###Code quakes[['mag', 'magType']].groupby('magType').boxplot( figsize=(15, 8), subplots=False ) plt.title('Earthquake Magnitude Box Plots by magType') plt.ylabel('magnitude') # label the y-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Counts and frequencies Bar chartsPassing `kind='barh'` gives us horizontal bars while `kind='bar'` gives us vertical ones. Let's use horizontal bars to look at the top 15 places for earthquakes in our data: ###Code quakes.parsed_place.value_counts().iloc[14::-1,].plot( kind='barh', figsize=(10, 5), title='Top 15 Places for Earthquakes ' '(September 18, 2018 - October 13, 2018)' ) plt.xlabel('earthquakes') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We also have data on whether earthquakes were accompanied by tsunamis. Let's see what the top places for tsunamis are: ###Code quakes.groupby('parsed_place').tsunami.sum().sort_values().iloc[-10:,].plot( kind='barh', figsize=(10, 5), title='Top 10 Places for Tsunamis ' '(September 18, 2018 - October 13, 2018)' ) plt.xlabel('tsunamis') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Seeing that Indonesia is the top place for tsunamis during the time period we are looking at, we may want to look how many earthquakes and tsunamis Indonesia gets on a daily basis. We could show this as a line plot or with bars; since we don't want to interpolate, we will use bars here: ###Code indonesia_quakes = quakes.query('parsed_place == "Indonesia"').assign( time=lambda x: pd.to_datetime(x.time, unit='ms'), earthquake=1 ).set_index('time').resample('1D').sum() # format the datetimes in the index for the x-axis indonesia_quakes.index = indonesia_quakes.index.strftime('%b\n%d') indonesia_quakes.plot( y=['earthquake', 'tsunami'], kind='bar', figsize=(15, 3), rot=0, label=['earthquakes', 'tsunamis'], title='Earthquakes and Tsunamis in Indonesia ' '(September 18, 2018 - October 13, 2018)' ) # label the axes (discussed in chapter 6) plt.xlabel('date') plt.ylabel('count') ###Output _____no_output_____ ###Markdown Grouped Bars ###Code quakes.groupby(['parsed_place', 'tsunami']).mag.count()\ .unstack().apply(lambda x: x / x.sum(), axis=1)\ .rename(columns={0: 'no', 1: 'yes'})\ .sort_values('yes', ascending=False)[7::-1]\ .plot.barh( title='Frequency of a tsunami accompanying an earthquake' ) # move legend to the right of the plot plt.legend(title='tsunami?', bbox_to_anchor=(1, 0.65)) # label the axes (discussed in chapter 6) plt.xlabel('percentage of earthquakes') plt.ylabel('') ###Output _____no_output_____ ###Markdown Using the `kind` arugment for vertical bars when the labels for each bar are shorter: ###Code quakes.magType.value_counts().plot( kind='bar', title='Earthquakes Recorded per magType', rot=0 ) # label the axes (discussed in chapter 6) plt.xlabel('magType') plt.ylabel('earthquakes') ###Output _____no_output_____ ###Markdown Stacked bars ###Code pivot = quakes.assign( mag_bin=lambda x: np.floor(x.mag) ).pivot_table( index='mag_bin', columns='magType', values='mag', aggfunc='count' ) pivot.plot.bar( stacked=True, rot=0, ylabel='earthquakes', title='Earthquakes by integer magnitude and magType' ) ###Output _____no_output_____ ###Markdown Normalized stacked barsPlot the percentages to be better able to see the different `magTypes`. ###Code normalized_pivot = pivot.fillna(0).apply(lambda x: x / x.sum(), axis=1) ax = normalized_pivot.plot.bar( stacked=True, rot=0, figsize=(10, 5), title='Percentage of earthquakes by integer magnitude for each magType' ) ax.legend(bbox_to_anchor=(1, 0.8)) # move legend to the right of the plot plt.ylabel('percentage') # label the axes (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We can also create horizontal stacked bars and do so using `groupby()` and `unstack()`: ###Code quakes.groupby(['parsed_place', 'tsunami']).mag.count()\ .unstack().apply(lambda x: x / x.sum(), axis=1)\ .rename(columns={0: 'no', 1: 'yes'})\ .sort_values('yes', ascending=False)[7::-1]\ .plot.barh( title='Frequency of a tsunami accompanying an earthquake', stacked=True ) # move legend to the right of the plot plt.legend(title='tsunami?', bbox_to_anchor=(1, 0.65)) # label the axes (discussed in chapter 6) plt.xlabel('percentage of earthquakes') plt.ylabel('') ###Output _____no_output_____ ###Markdown Plotting with PandasThe `plot()` method is available on `Series` and `DataFrame` objects. Many of the parameters get passed down to `matplotlib`. The `kind` argument let's us vary the plot type. Here are some commonly used parameters:| Parameter | Purpose | Data Type || --- | --- | --- || `kind` | Determines the plot type | String || `x`/`y` | Column(s) to plot on the *x*-axis/*y*-axis | String or list || `ax` | Draws the plot on the `Axes` object provided | `Axes` || `subplots` | Determines whether to make subplots | Boolean || `layout` | Specifies how to arrange the subplots | Tuple of `(rows, columns)` || `figsize` | Size to make the `Figure` object | Tuple of `(width, height)` | | `title` | The title of the plot or subplots | String for the plot title or a list of strings for subplot titles || `legend` | Determines whether to show the legend | Boolean || `label` | What to call an item in the legend | String if a single column is being plotted; otherwise, a list of strings || `style` | `matplotlib` style strings for each item being plotted | String if a single column is being plotted; otherwise, a list of strings || `color` | The color to plot the item in | String or red, green, blue tuple if a single column is being plotted; otherwise, a list || `colormap` | The colormap to use | String or `matplotlib` colormap object || `logx`/`logy`/`loglog` | Determines whether to use a logarithmic scale for the *x*-axis, *y*-axis, or both | Boolean || `xticks`/`yticks` | Determines where to draw the ticks on the *x*-axis/*y*-axis | List of values || `xlim`/`ylim` | The axis limits for the *x*-axis/*y*-axis | Tuple of the form `(min, max)` || `rot` | The angle to write the tick labels at | Integer || `sharex`/`sharey` | Determines whether to have subplots share the *x*-axis/*y*-axis | Boolean || `fontsize` | Controls the size of the tick labels | Integer || `grid` | Turns on/off the grid lines | Boolean | About the DataIn this notebook, we will be working with 3 datasets:- Facebook's stock price throughout 2018 (obtained using the [`stock_analysis` package](https://github.com/stefmolin/stock-analysis))- Earthquake data from September 18, 2018 - October 13, 2018 (obtained from the US Geological Survey (USGS) using the [USGS API](https://earthquake.usgs.gov/fdsnws/event/1/))- European Centre for Disease Prevention and Control's (ECDC) [daily number of new reported cases of COVID-19 by country worldwide dataset](https://www.ecdc.europa.eu/en/publications-data/download-todays-data-geographic-distribution-covid-19-cases-worldwide) collected on September 19, 2020 via [this link](https://opendata.ecdc.europa.eu/covid19/casedistribution/csv) Setup ###Code %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd fb = pd.read_csv( 'data/fb_stock_prices_2018.csv', index_col='date', parse_dates=True ) quakes = pd.read_csv('data/earthquakes.csv') covid = pd.read_csv('data/covid19_cases.csv').assign( date=lambda x: pd.to_datetime(x.dateRep, format='%d/%m/%Y') ).set_index('date').replace( 'United_States_of_America', 'USA' ).sort_index()['2020-01-18':'2020-09-18'] ###Output _____no_output_____ ###Markdown Evolution over timeLine plots help us see how a variable changes over time. They are the default for the `kind` argument, but we can pass `kind='line'` to be explicit in our intent: ###Code fb.plot( kind='line', y='open', figsize=(10, 5), style='-b', legend=False, title='Evolution of Facebook Open Price' ) ###Output _____no_output_____ ###Markdown We provided the `style` argument in the previous example; however, we can use the `color` and `linestyle` arguments to get the same result: ###Code fb.plot( kind='line', y='open', figsize=(10, 5), color='blue', linestyle='solid', legend=False, title='Evolution of Facebook Open Price' ) ###Output _____no_output_____ ###Markdown We can also plot many lines at once by simply passing a list of the columns to plot: ###Code fb.first('1W').plot( y=['open', 'high', 'low', 'close'], style=['o-b', '--r', ':k', '.-g'], title='Facebook OHLC Prices during 1st Week of Trading 2018' ).autoscale() ###Output _____no_output_____ ###Markdown Creating subplotsWhen plotting with `pandas`, creating subplots is simply a matter of passing `subplots=True` to the `plot()` method, and (optionally) specifying the `layout` in a tuple of `(rows, columns)`: ###Code fb.plot( kind='line', subplots=True, layout=(3, 2), figsize=(15, 10), title='Facebook Stock 2018' ) ###Output _____no_output_____ ###Markdown Note that we didn't provide a specific column to plot and `pandas` plotted all of them for us.Sometimes we want to make subplots that each have a few variables in them for comparison. This can be achieved using the `ax` parameter. To illustrate this, let's take a look at daily new COVID-19 cases in China, Spain, Italy, the USA, Brazil, and India: ###Code new_cases_rolling_average = covid.pivot_table( index=covid.index, columns='countriesAndTerritories', values='cases' ).rolling(7).mean() ###Output _____no_output_____ ###Markdown Since there is a lot of fluctuation in these values, we will plot the 7-day moving average of new cases using the `rolling()` method (discussed in chapter 4). Rather than create a separate plot for each country (which makes it harder to compare) or plot them all together (which will make it difficult to see the smaller values), we will plot countries that have had a similar number of cases in the same subplot: ###Code fig, axes = plt.subplots(1, 3, figsize=(15, 5)) new_cases_rolling_average[['China']].plot(ax=axes[0], style='-.c') new_cases_rolling_average[['Italy', 'Spain']].plot( ax=axes[1], style=['-', '--'], title='7-day rolling average of new COVID-19 cases\n(source: ECDC)' ) new_cases_rolling_average[['Brazil', 'India', 'USA']]\ .plot(ax=axes[2], style=['--', ':', '-']) ###Output _____no_output_____ ###Markdown *NOTE: we specified the line styles here so that the lines can be distinguished in the text as a black and white image.*In the previous figure, we were able to compare countries with similar levels of new COVID-19 cases, but we couldn't compare all of them in the same plot due to scale. One way around this is to use an **area plot**, which makes it possible for us to visualize the overall 7-day rolling average of new COVID-19 cases and at the same time how much each country is contributing to the total. In the interest of readability, we will group Italy and Spain together and create another category for countries other than the USA, Brazil, and India. The combined height of the plot areas is the overall value, and the height of given shaded region is the value for the individual country. ###Code cols = [ col for col in new_cases_rolling_average.columns if col not in ['USA', 'Brazil', 'India', 'Italy & Spain'] ] new_cases_rolling_average.assign( **{'Italy & Spain': lambda x: x.Italy + x.Spain} ).sort_index(axis=1).assign( Other=lambda x: x[cols].sum(axis=1) ).drop(columns=cols).plot( kind='area', figsize=(15, 5), title='7-day rolling average of new COVID-19 cases\n(source: ECDC)' ) ###Output _____no_output_____ ###Markdown Another way to visualize evolution over time is to look at the cumulative sum over time. Let's plot the cumulative number of COVID-19 cases in China, Spain, Italy, the USA, Brazil, and India, using `ax` to create subplots as we did in the previous example. ###Code fig, axes = plt.subplots(1, 3, figsize=(15, 3)) cumulative_covid_cases = covid.groupby( ['countriesAndTerritories', pd.Grouper(freq='1D')] ).cases.sum().unstack(0).apply('cumsum') cumulative_covid_cases[['China']].plot(ax=axes[0], style='-.c') cumulative_covid_cases[['Italy', 'Spain']].plot( ax=axes[1], style=['-', '--'], title='Cumulative COVID-19 Cases\n(source: ECDC)' ) cumulative_covid_cases[['Brazil', 'India', 'USA']]\ .plot(ax=axes[2], style=['--', ':', '-']) ###Output _____no_output_____ ###Markdown *NOTE: we specified the line styles here so that the lines can be distinguished in the text as a black and white image.* Visualizing relationships between variables Scatter plotsWe make scatter plots to help visualize the relationship between two variables. Creating scatter plots requires we pass in `kind='scatter'` along with a column for the x-axis and a column for the y-axis: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. Volume Traded' ) ###Output _____no_output_____ ###Markdown The relationship doesn't seem to be linear, but we can try a log transform on the x-axis since the scales of the axes are very different. With `pandas`, we simply pass in `logx=True`: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', logx=True ) ###Output _____no_output_____ ###Markdown With `matplotlib`, we could use `plt.xscale('log')` to do the same thing. Adding Transparency to Plots with `alpha`Sometimes our plots have many overlapping values, but this can be impossible to see. This can be addressed by increasing the transparency of what we are plotting using the `alpha` parameter. It is a float in the range [0, 1] where 0 is completely transparent and 1 is completely opaque. By default this is 1, so let's put in a lower value and re-plot the scatter plot: ###Code fb.assign( max_abs_change=fb.high - fb.low ).plot( kind='scatter', x='volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', logx=True, alpha=0.25 ) ###Output _____no_output_____ ###Markdown HexbinsIn the previous example, we can start to see the overlaps, but it is still difficult. Hexbins are another plot type that divide up the plot into hexagons, which are shaded according to the density of points there. With `pandas`, this is the `hexbin` value for the `kind` argument. It may also be necessary to tweak the `gridsize`, which determines the number of hexagons along the y-axis: ###Code fb.assign( log_volume=np.log(fb.volume), max_abs_change=fb.high - fb.low ).plot( kind='hexbin', x='log_volume', y='max_abs_change', title='Facebook Daily High - Low vs. log(Volume Traded)', colormap='gray_r', gridsize=20, sharex=False # we have to pass this to see the x-axis ) ###Output _____no_output_____ ###Markdown Visualizing Correlations with HeatmapsPandas doesn't offer heatmaps; however, if we are able to get our data into a matrix, we can use `matshow()` from matplotlib: ###Code fig, ax = plt.subplots(figsize=(20, 10)) # calculate the correlation matrix fb_corr = fb.assign( log_volume=np.log(fb.volume), max_abs_change=fb.high - fb.low ).corr() # create the heatmap and colorbar im = ax.matshow(fb_corr, cmap='seismic') im.set_clim(-1, 1) fig.colorbar(im) # label the ticks with the column names labels = [col.lower() for col in fb_corr.columns] ax.set_xticks(ax.get_xticks()[1:-1]) # to handle bug in matplotlib ax.set_xticklabels(labels, rotation=45) ax.set_yticks(ax.get_yticks()[1:-1]) # to handle bug in matplotlib ax.set_yticklabels(labels) # include the value of the correlation coefficient in the boxes for (i, j), coef in np.ndenumerate(fb_corr): ax.text( i, j, fr'$\rho$ = {coef:.2f}', # raw (r), format (f) string ha='center', va='center', color='white', fontsize=14 ) ###Output _____no_output_____ ###Markdown Accessing the values in the correlation matrix can be done with `loc[]`: ###Code fb_corr.loc['max_abs_change', ['volume', 'log_volume']] ###Output _____no_output_____ ###Markdown Visualizing distributions HistogramsWith the `pandas`, making histograms is as easy as passing `kind='hist'` to the `plot()` method: ###Code fb.volume.plot( kind='hist', title='Histogram of Daily Volume Traded in Facebook Stock' ) plt.xlabel('Volume traded') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We can overlap histograms to compare distributions provided we use the `alpha` parameter. For example, let's compare the usage and magnitude of the various measurement techniques (the `magType` column) in the data: ###Code fig, axes = plt.subplots(figsize=(8, 5)) for magtype in quakes.magType.unique(): data = quakes.query(f'magType == "{magtype}"').mag if not data.empty: data.plot( kind='hist', ax=axes, alpha=0.4, label=magtype, legend=True, title='Comparing histograms of earthquake magnitude by magType' ) plt.xlabel('magnitude') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Kernel Density Estimation (KDE)We can pass `kind='kde'` for an estimate of the probability density function (PDF), which tells us the probability of getting a particular value: ###Code fb.high.plot( kind='kde', title='KDE of Daily High Price for Facebook Stock' ) plt.xlabel('Price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Adding to the result of `plot()`The `plot()` method returns an `Axes` object. We can store this for additional customization of the plot, or we can pass this into another call to `plot()` as the `ax` argument to add to the original plot. It can often be helpful to view the KDE superimposed on top of the histogram, which can be achieved with this strategy: ###Code ax = fb.high.plot(kind='hist', density=True, alpha=0.5) fb.high.plot( ax=ax, kind='kde', color='blue', title='Distribution of Facebook Stock\'s Daily High Price in 2018' ) plt.xlabel('Price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Plotting the ECDFIn some cases, we are more interested in the probability of getting less than or equal to that value (or greater than or equal), which we can see with the **cumulative disribution function (CDF)**. Using the `statsmodels` package, we can estimate the CDF giving us the **empirical cumulative distribution function (ECDF)**: ###Code from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(quakes.query('magType == "ml"').mag) plt.plot(ecdf.x, ecdf.y) # axis labels (we will cover this in chapter 6) plt.xlabel('mag') # add x-axis label plt.ylabel('cumulative probability') # add y-axis label # add title (we will cover this in chapter 6) plt.title('ECDF of earthquake magnitude with magType ml') ###Output _____no_output_____ ###Markdown This ECDF tells us the probability of getting an earthquake with magnitude of 3 or less using the `ml` scale is 98%: ###Code from statsmodels.distributions.empirical_distribution import ECDF ecdf = ECDF(quakes.query('magType == "ml"').mag) plt.plot(ecdf.x, ecdf.y) # formatting below will all be covered in chapter 6 # axis labels plt.xlabel('mag') # add x-axis label plt.ylabel('cumulative probability') # add y-axis label # add reference lines for interpreting the ECDF for mag <= 3 plt.plot( [3, 3], [0, .98], '--k', [-1.5, 3], [0.98, 0.98], '--k', alpha=0.4 ) # set axis ranges plt.ylim(0, None) plt.xlim(-1.25, None) # add a title plt.title('P(mag <= 3) = 98%') ###Output _____no_output_____ ###Markdown Box plotsTo make box plots with `pandas`, we pass `kind='box'` to the `plot()` method: ###Code fb.iloc[:,:4].plot(kind='box', title='Facebook OHLC Prices Box Plot') plt.ylabel('price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown If we pass in `notch=True`, we get a notched box plot. The notch represents a 95% confidence interval around the median, which can be helpful when comparing differences. For an introduction to interpreting a notched box plot, see this [Google sites page](https://sites.google.com/site/davidsstatistics/home/notched-box-plots) and this [Towards Data Science article](https://towardsdatascience.com/understanding-boxplots-5e2df7bcbd51). ###Code fb.iloc[:,:4].plot(kind='box', title='Facebook OHLC Prices Box Plot', notch=True) plt.ylabel('price ($)') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown This can also be combined with a call to `groupby()`: ###Code fb.assign( volume_bin=pd.cut(fb.volume, 3, labels=['low', 'med', 'high']) ).groupby('volume_bin').boxplot( column=['open', 'high', 'low', 'close'], layout=(1, 3), figsize=(12, 3) ) plt.suptitle('Facebook OHLC Box Plots by Volume Traded', y=1.1) ###Output _____no_output_____ ###Markdown We can use this to see the distribution of magnitudes across the different measurement methods for earthquakes: ###Code quakes[['mag', 'magType']].groupby('magType').boxplot( figsize=(15, 8), subplots=False ) plt.title('Earthquake Magnitude Box Plots by magType') plt.ylabel('magnitude') # label the y-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Counts and frequencies Bar chartsPassing `kind='barh'` gives us horizontal bars while `kind='bar'` gives us vertical ones. Let's use horizontal bars to look at the top 15 places for earthquakes in our data: ###Code quakes.parsed_place.value_counts().iloc[14::-1,].plot( kind='barh', figsize=(10, 5), title='Top 15 Places for Earthquakes ' '(September 18, 2018 - October 13, 2018)' ) plt.xlabel('earthquakes') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We also have data on whether earthquakes were accompanied by tsunamis. Let's see what the top places for tsunamis are: ###Code quakes.groupby('parsed_place').tsunami.sum().sort_values().iloc[-10:,].plot( kind='barh', figsize=(10, 5), title='Top 10 Places for Tsunamis ' '(September 18, 2018 - October 13, 2018)' ) plt.xlabel('tsunamis') # label the x-axis (discussed in chapter 6) ###Output _____no_output_____ ###Markdown Seeing that Indonesia is the top place for tsunamis during the time period we are looking at, we may want to look how many earthquakes and tsunamis Indonesia gets on a daily basis. We could show this as a line plot or with bars; since we don't want to interpolate, we will use bars here: ###Code indonesia_quakes = quakes.query('parsed_place == "Indonesia"').assign( time=lambda x: pd.to_datetime(x.time, unit='ms'), earthquake=1 ).set_index('time').resample('1D').sum() # format the datetimes in the index for the x-axis indonesia_quakes.index = indonesia_quakes.index.strftime('%b\n%d') indonesia_quakes.plot( y=['earthquake', 'tsunami'], kind='bar', figsize=(15, 3), rot=0, label=['earthquakes', 'tsunamis'], title='Earthquakes and Tsunamis in Indonesia ' '(September 18, 2018 - October 13, 2018)' ) # label the axes (discussed in chapter 6) plt.xlabel('date') plt.ylabel('count') ###Output _____no_output_____ ###Markdown Grouped Bars ###Code quakes.groupby(['parsed_place', 'tsunami']).mag.count()\ .unstack().apply(lambda x: x / x.sum(), axis=1)\ .rename(columns={0: 'no', 1: 'yes'})\ .sort_values('yes', ascending=False)[7::-1]\ .plot.barh( title='Frequency of a tsunami accompanying an earthquake' ) # move legend to the right of the plot plt.legend(title='tsunami?', bbox_to_anchor=(1, 0.65)) # label the axes (discussed in chapter 6) plt.xlabel('percentage of earthquakes') plt.ylabel('') ###Output _____no_output_____ ###Markdown Using the `kind` arugment for vertical bars when the labels for each bar are shorter: ###Code quakes.magType.value_counts().plot( kind='bar', title='Earthquakes Recorded per magType', rot=0 ) # label the axes (discussed in chapter 6) plt.xlabel('magType') plt.ylabel('earthquakes') ###Output _____no_output_____ ###Markdown Stacked bars ###Code pivot = quakes.assign( mag_bin=lambda x: np.floor(x.mag) ).pivot_table( index='mag_bin', columns='magType', values='mag', aggfunc='count' ) pivot.plot.bar( stacked=True, rot=0, ylabel='earthquakes', title='Earthquakes by integer magnitude and magType' ) ###Output _____no_output_____ ###Markdown Normalized stacked barsPlot the percentages to be better able to see the different `magTypes`. ###Code normalized_pivot = pivot.fillna(0).apply(lambda x: x / x.sum(), axis=1) ax = normalized_pivot.plot.bar( stacked=True, rot=0, figsize=(10, 5), title='Percentage of earthquakes by integer magnitude for each magType' ) ax.legend(bbox_to_anchor=(1, 0.8)) # move legend to the right of the plot plt.ylabel('percentage') # label the axes (discussed in chapter 6) ###Output _____no_output_____ ###Markdown We can also create horizontal stacked bars and do so using `groupby()` and `unstack()`: ###Code quakes.groupby(['parsed_place', 'tsunami']).mag.count()\ .unstack().apply(lambda x: x / x.sum(), axis=1)\ .rename(columns={0: 'no', 1: 'yes'})\ .sort_values('yes', ascending=False)[7::-1]\ .plot.barh( title='Frequency of a tsunami accompanying an earthquake', stacked=True ) # move legend to the right of the plot plt.legend(title='tsunami?', bbox_to_anchor=(1, 0.65)) # label the axes (discussed in chapter 6) plt.xlabel('percentage of earthquakes') plt.ylabel('') ###Output _____no_output_____
Natural Language Processing/NLP/FillMaskRoBERTa_Large.ipynb
###Markdown Fill-Mask using RoBERTa large model This Code Template is to perform Mask filling operation in python using HuggingFace library. In this template RoBERTa Model is utilized.RoBERTa is a transformers model pretrained on a large corpus of English data in a self-supervised fashion. Required Packages ###Code !pip install transformers from transformers import pipeline ###Output _____no_output_____ ###Markdown RoBERTA RoBERTa is a transformers model pretrained on a large corpus of English data in a self-supervised fashion. This means it was pretrained on the raw texts only, with no humans labelling them in any way (which is why it can use lots of publicly available data) with an automatic process to generate inputs and labels from those texts. More precisely, it was pretrained with the Masked language modeling (MLM) objective. Taking a sentence, the model randomly masks 15% of the words in the input then run the entire masked sentence through the model and has to predict the masked words. ###Code unmasker = pipeline('fill-mask', model='roberta-large') ###Output _____no_output_____ ###Markdown Fill Mask ###Code unmasker("how are is that <mask> even.") ###Output _____no_output_____ ###Markdown Fill-Mask using RoBERTa large model Required Packages ###Code !pip install transformers from transformers import pipeline ###Output _____no_output_____ ###Markdown RoBERTA RoBERTa is a transformers model pretrained on a large corpus of English data in a self-supervised fashion. This means it was pretrained on the raw texts only, with no humans labelling them in any way (which is why it can use lots of publicly available data) with an automatic process to generate inputs and labels from those texts. More precisely, it was pretrained with the Masked language modeling (MLM) objective. Taking a sentence, the model randomly masks 15% of the words in the input then run the entire masked sentence through the model and has to predict the masked words. ###Code unmasker = pipeline('fill-mask', model='roberta-large') ###Output _____no_output_____ ###Markdown Fill Mask ###Code unmasker("how are is that <mask> even.") ###Output _____no_output_____ ###Markdown Fill-Mask using RoBERTa large model This Code Template is to perform Mask filling operation in python using HuggingFace library. In this template RoBERTa Model is utilized.RoBERTa is a transformers model pretrained on a large corpus of English data in a self-supervised fashion. Required Packages ###Code !pip install transformers from transformers import pipeline ###Output _____no_output_____ ###Markdown RoBERTA RoBERTa is a transformers model pretrained on a large corpus of English data in a self-supervised fashion. This means it was pretrained on the raw texts only, with no humans labelling them in any way (which is why it can use lots of publicly available data) with an automatic process to generate inputs and labels from those texts. More precisely, it was pretrained with the Masked language modeling (MLM) objective. Taking a sentence, the model randomly masks 15% of the words in the input then run the entire masked sentence through the model and has to predict the masked words. ###Code unmasker = pipeline('fill-mask', model='roberta-large') ###Output _____no_output_____ ###Markdown Fill Mask ###Code unmasker("how are is that <mask> even.") ###Output _____no_output_____
03-EDLCC/SLITD's e EDLCC's.ipynb
###Markdown SLITD's e EDLCC's Introdução Ferramentas computacionais têm uma grande importância na análise e projeto de sinais e sistemas modernos. Equações de Diferenças Lineares com Coeficientes Constantes (EDLCC's) são fundamentais na representação/descrição de sistemas simples e mais complexos. Felizmente, ferramentas de software atuais tornam possível a manipulação dessas EDLCC's em diversos domínios sem muito esforço. Equações de Diferenças Lineares de Coeficientes Constantes são completamente caracterizadas pelos conjuntos de coeficientes ${a_k}$ e ${b_k}$. Podemos usar tais ferramentas como **PyLab** (apresentação gráfica) e o pacote *signal* do **Scipy** (computação científica) para projetar filtros de alta performance, particularmente no domínio do tempo discreto. As funções de projeto de filtros calculam os coeficientes ${a_k}$ e ${b_k}$ em resposta aos requisitos de projeto fornecidos pelo projetista. Em geral, usamos os projetos de filtros na simulação de sistemas maiores. Os sistemas são representados por EDLCC's, normalmente, em três domínios: tempo, frequência e Z (freq. complexa). Os conjuntos de coeficientes constantes, $a_k$ e $b_k$, existem e são os mesmos nos três domínios citados. Portanto, esses **coeficientes definem o sistema** em qualquer que seja o domínio de representação.Aqui estão algumas da relações entrada-saída nos domínios citados:Domínio do tempo: **Resposta ao Impulso**: $$y[n]=\sum_{k=-\infty}^{\infty}x[k].h[n-k]$$Domínio do tempo: **EDLCC**:$$y[n]+a_1.y[n-1]+...+a_{N-1}.y[n-(N-1)+a_N.y[n-N]=b_0.x[n]+b_1.x[n-1]+...+b_{M-1}.x[n-(M-1)+b_M.x[n-M]\;\;\;\;\;\;(1)$$$$y[n]=\sum_{k=0}^{M}{b_k.x[n-k]}-\sum_{k=1}^{N}{a_k.y[n-k]}$$Domínio Z: **Função de Transferência**: $$H(z)=\frac{\sum_{k=0}^{M-1}b_k.X(z-k)}{\sum_{k=1}^{N-1}a_k.Y(z-k)}$$Domínio da frequência: **Resposta em Frequência**: $$H(\Omega)=\frac{\sum_{k=0}^{M-1}b_k.X(\Omega-\Omega_k)}{\sum_{k=1}^{N-1}a_k.Y(\Omega-\Omega_k)}$$ A resposta ao impulso, $h[n]$, convoluída pela entrada, $x[n]$, produz a saída do sistema, $y[n]$.O teorema da convolução para as transformadas de Fourier aplicado à resposta ao impulso, $h[n]$, produz a **Resposta em Frequência** do sistema, $H(\Omega)$, ou seja, a razão do espectro da saída pelo espectro da entrada, $Y(\Omega)/X(\Omega)$.O teorema da convolução para a Transformada-z produz a saída no domínio z, $Y(z)$, como produto da entrada, $X(z)$, e a **Função Sistema (Função de Transferência)**, $H(z)$, que é a Transformada-z da **Resposta ao Impulso**. EDLCC - Resposta ao Impulso A Resposta ao Impulsiva de um SLITD, $h[n]$ pode ser obtida resolvendo-se a equação (1) para a entrada $x[n]=\delta[n]$ e assumindo o SLITD em repouso. Para um sistema **não recursivo**, ou seja, $a_k=0$ para $k = 1,2,...N$, a equação (1) torna-se:$$y[n]=h[n]=\sum_{k=0}^M b_k.\delta[n-k]$$ Classificação de SLITD's Quanto a Duração da Resposta ao Impulso Se a Resposta Impulsiva $h[n]$ for finita, então o SLITD é classificado como sendo do tipo **FIR - *Finite Impulse Response***. Porém, se $a_k\neq0$, a Resposta Impulsiva $h[n]$ será de duração infinita, e o SLITD será classificado como sendo do tipo **IIR - *Infinite Impulse Response***. Resolução de EDLCC's Existem vários métodos de resolução de uma EDLCC, para uma determinada entrada $x[n]$ e condições iniciais do SLITD: **Iterativo**:Baseia-se na construção de uma tabela de valores da entrada e da saída, a partir da avaliação da EDLCC para cada tempo $n$. Esse método é indicado quando se deseja calcular alguns poucos valores da saída (método essencialmente computacional) a partir do instante nulo: $n=0$. **Clássico** (Analítico):Resolução de equações diferenciais (usando autofunções como possíveis soluções da equação), que consiste em obter a solução homogênea e a solução particular. Esse método é indicado quando se deseja conhecer o valor da saída para qualquer instante de tempo, visto que o método redunda numa expressão fechada para a saída, $y[n]$.**Transformada-Z**: Consistem na aplicação da Transformada-z Direta à EDLCC, para obter uma equação algébrica de fácil solução. Em seguida, aplica-se a Transformada-Z Inversa para obter a resposta do SLITD no domínio do tempo. Esse método, também, é indicado quando se deseja conhecer o valor da saída para qualquer instante de tempo, visto que o método redunda numa expressão fechada para a saída, $y[n]$. Ferramentas Computacionais A figura seguinte mostra as funções chaves em **PyLab** e no módulo *signal* do pacote **Scipy** usadas na análise dos sistemas de tempo discreto nos diversos domínios. **Domínio do Tempo**: você resolve equações de diferenças usando signal.lfilter(b,a,x).**Domínio z**: você pode encontrar o plano de polos e zeros da Função de Transferência $H(z)$ do sistema, usando ssd.zplane(b,a); e pode fazer a expansão em frações parciais, usando signal.residuez.**Domínio da Frequência**: você pode encontrar a Resposta em Frequência $H(\Omega)$ de um sistema de tempo discreto com signal.freqz(b,a,2\*pi\*f), onde $f$ é a variável frequência. Procedimentos Seja um SLITD relaxado (c.i.’s nulas) descrito por sua EDLCC de segunda ordem:$$y[n] + 0,6 y[n-2] = 0,3x[n] + 0,5x[n-1] + 0,3x[n-2]$$Desenvolva um *script* para calcular e traçar a resposta do SLITD às seguintes entradas, usando o **método iterativo** para solucionar a EDLCC, $-5\leq n\leq20$:Impulso unitário: $x[n]=\delta[n]$Degrau unitário: $x[n]=u[n]$Exponencial: $x[n]=3.(0,4)^nu[n]$ ###Code % pylab inline # Procedimento 1 - letra (A) from numpy import arange, zeros from pylab import stem, title, xlabel, ylabel, subplot, grid, ylim, subplots n = arange(-5,21) # base de tempo N = 2 # ordem do SLITD: max_atraso(x,y) iot = 5 # índice da origem dos tempos x = zeros(len(n)); x[iot] = 1 # entrada: impulso unitário y = zeros(len(n)) # condições iniciais nulas # print ' n y[n]' for item in n[N:]: m = item + iot # posição no vetor y[m] = -0.6*y[m-2] + 0.3*x[m] + 0.5*x[m-1] + 0.3*x[m-2] # EDLCC # print '%2d %+7.5f' % (item,y[m]) subplots(figsize=(18,6)) # estipula espaço físico para os gráficos # Gráfico 1: sinal da Entrada, x[n] subplot(121) marca,linha,eixo = stem(n,x) setp(marca,'markerfacecolor', 'r'); setp(linha,'color', 'r'); setp(linha,'linewidth',3) title('Entrada - $\delta[n]$',fontsize=16,color='r') grid('on'); xlabel('$n$',fontsize=16); ylabel('Amplitude',fontsize=16); ylim(-0.5,1.5) # Gráfico 2: sinal da Saída, y[n] subplot(122) marca,linha,eixo = stem(n,y) setp(eixo,'color','k'); setp(linha,'linewidth',3) title('Resposta ao Impulso - $h[n]$',fontsize=16,color='b'); ylim(-0.5,0.7) grid('on'); xlabel('$n$',fontsize=16); ylabel('Amplitude',fontsize=16) ###Output Populating the interactive namespace from numpy and matplotlib
doc/mca_tutorial.ipynb
###Markdown Package fanalysisAnalyse des Correspondances MultiplesCe tutoriel a pour objectif de présenter rapidement les principales fonctionnalités offertes par le package fanalysis pour réaliser une Analyse des Correspondances Multiples.Il suppose connu les soubassements théoriques de cette méthode.Il ne s'attarde pas non plus sur l'interprétation du jeu de données, qui n'a pour but que de présenter les fonctionnalités du package.2 approches sont présentées : Une approche "datamining" : l'ACM vise à décrire un jeu de données Une approche "machine learning" : l'ACM est utilisée comme méthode de réduction des données, le résultat servant d'entrée pour un modèle prédictif (nous ferons ici l'usage d'outils de scikit-learn). I. Approche DataminingL'ACM a ici pour but de décrire un fichier de données.Celui-ci est extrait du site de Ricco Rakotomalala (Université Lyon 2) :http://eric.univ-lyon2.fr/%7Ericco/tanagra/fichiers/races_canines_acm.xlsNous partons d'un fichier texte intitulé "mca_data.txt".On importe la librairie pandas pour charger les données, ainsi que la classe MCA du package fanalysis.Les données sont transformées en matrice de type numpy.ndarray.Dans la matrice de données X, les catégories peuvent être codées : soit par des entiers soit par des chaines de caractèresDans cet exemple, les catégories sont codées par des chaines de caractère. ###Code import pandas as pd from fanalysis.mca import MCA %matplotlib inline df = pd.read_table("mca_data.txt", header=0, index_col=0, delimiter="\t", encoding="utf-8") print(df) ###Output Taille Poids Velocite Intelligence Affection Agressivite \ Chien Beauceron Taille++ Poids+ Veloc++ Intell+ Affec+ Agress+ Basset Taille- Poids- Veloc- Intell- Affec- Agress+ Berger-All Taille++ Poids+ Veloc++ Intell++ Affec+ Agress+ Boxer Taille+ Poids+ Veloc+ Intell+ Affec+ Agress+ Bull-Dog Taille- Poids- Veloc- Intell+ Affec+ Agress- Bull-Mastif Taille++ Poids++ Veloc- Intell++ Affec- Agress+ Caniche Taille- Poids- Veloc+ Intell++ Affec+ Agress- Chihuahua Taille- Poids- Veloc- Intell- Affec+ Agress- Cocker Taille+ Poids- Veloc- Intell+ Affec+ Agress+ Colley Taille++ Poids+ Veloc++ Intell+ Affec+ Agress- Dalmatien Taille+ Poids+ Veloc+ Intell+ Affec+ Agress- Doberman Taille++ Poids+ Veloc++ Intell++ Affec- Agress+ Dogue-All Taille++ Poids++ Veloc++ Intell- Affec- Agress+ Epag.-Breton Taille+ Poids+ Veloc+ Intell++ Affec+ Agress- Epag.-Français Taille++ Poids+ Veloc+ Intell+ Affec- Agress- Fox-Hound Taille++ Poids+ Veloc++ Intell- Affec- Agress+ Fox-Terrier Taille- Poids- Veloc+ Intell+ Affec+ Agress+ Gd-Bleu-Gasc Taille++ Poids+ Veloc+ Intell- Affec- Agress+ Labrador Taille+ Poids+ Veloc+ Intell+ Affec+ Agress- Levrier Taille++ Poids+ Veloc++ Intell- Affec- Agress- Mastiff Taille++ Poids++ Veloc- Intell- Affec- Agress+ Pekinois Taille- Poids- Veloc- Intell- Affec+ Agress- Pointer Taille++ Poids+ Veloc++ Intell++ Affec- Agress- St-Bernard Taille++ Poids++ Veloc- Intell+ Affec- Agress+ Setter Taille++ Poids+ Veloc++ Intell+ Affec- Agress- Teckel Taille- Poids- Veloc- Intell+ Affec+ Agress- Terre-Neuve Taille++ Poids++ Veloc- Intell+ Affec- Agress- Fonction Chien Beauceron utilite Basset chasse Berger-All utilite Boxer compagnie Bull-Dog compagnie Bull-Mastif utilite Caniche compagnie Chihuahua compagnie Cocker compagnie Colley compagnie Dalmatien compagnie Doberman utilite Dogue-All utilite Epag.-Breton chasse Epag.-Français chasse Fox-Hound chasse Fox-Terrier compagnie Gd-Bleu-Gasc chasse Labrador chasse Levrier chasse Mastiff utilite Pekinois compagnie Pointer chasse St-Bernard utilite Setter chasse Teckel compagnie Terre-Neuve utilite ###Markdown L'analyse va porter sur les 6 premières variables. ###Code X = df.iloc[:, 0:6].as_matrix() ###Output _____no_output_____ ###Markdown On crée une instance de la classe MCA, en lui passant ici des étiquettes pour les lignes et les variables. Ces paramètres sont facultatifs ; en leur absence, le programme détermine automatiquement des étiquettes. ###Code my_mca = MCA(row_labels=df.index.values, var_labels=df.columns.values[0:6]) ###Output _____no_output_____ ###Markdown On estime le modèle en appliquant la méthode fit de la classe MCA sur le jeu de données. ###Code my_mca.fit(X) ###Output _____no_output_____ ###Markdown L'exécution de la méthode my_mca.fit(X) provoque a minima le calcul des attributs : my\_pca.eig\_ : valeurs propres my\_pca.row\_coord\_ : coordonnées des points lignes my\_pca.col\_coord\_ : coordonnées des points colonnes I.1. Analyse des valeurs propres L'attribut my\_mca.eig\_ contient : en 1ère ligne : les valeurs propres en valeur absolue en 2ème ligne : les valeurs propres en pourcentage de la variance totale en 3ème ligne : les valeurs propres en pourcentage cumulé de la variance totale ###Code print(my_mca.eig_) ###Output [[ 4.81606165e-01 3.84737288e-01 2.10954049e-01 1.57554025e-01 1.50132670e-01 1.23295308e-01 8.14624601e-02 4.56697566e-02 2.35419107e-02 7.71303416e-03] [ 2.88963699e+01 2.30842373e+01 1.26572430e+01 9.45324152e+00 9.00796020e+00 7.39771849e+00 4.88774761e+00 2.74018539e+00 1.41251464e+00 4.62782050e-01] [ 2.88963699e+01 5.19806071e+01 6.46378501e+01 7.40910916e+01 8.30990518e+01 9.04967703e+01 9.53845179e+01 9.81247033e+01 9.95372180e+01 1.00000000e+02]] ###Markdown Les valeurs propres peuvent être représentées graphiquement (par défaut : représentation en valeur absolue). ###Code my_mca.plot_eigenvalues() my_mca.plot_eigenvalues(type="percentage") my_mca.plot_eigenvalues(type="cumulative") ###Output _____no_output_____ ###Markdown Quand l'objet my\_mca a été instancié, son paramètre stats a reçu la valeur True par défaut.En conséquence, lors de l'exécution de la méthode my\_mca.fit(X), les statistiques suivantes ont été calculées : my\_mca.row\_contrib\_ : contributions des points lignes à la variance de l'axe my\_mca.col\_contrib\_ : contributions des points colonnes à la variance de l'axe my\_mca.row\_cos2\_ : cosinus carrés des points lignes my\_mca.col\_cos2\_ : cosinus carrés des points colonnesSi l'on avait souhaité éviter le calcul de ces statistiques pour gagner du temps et économiser des ressources mémoire, il aurait fallu instancier :my\_mca = MCA(stats=False)Par défaut, les coordonnées des points lignes et colonnes, leurs contributions et cosinus carrés sont calculés sur l'ensemble des axes extraits de l'analyse.On aurait toutefois pu spécifier le nombre d'axes à retenir via le paramètre n_components avec par exemple :my\_mca = MCA(n_components=3) I.2. Extraction des statistiques sur les points lignes Export de la totalité des données lignes vers une DataFrame pandasOn peut simplement envoyer vers une Dataframe : les coordonnées, les contributions et les cos2 de chacun des points lignes, pour tous les axes factoriels (identifiés par les suffixes dim1, dim2, etc.). ###Code df_rows = my_mca.row_topandas() print(df_rows) ###Output row_coord_dim1 row_coord_dim2 row_coord_dim3 \ Beauceron -0.317200 -0.417701 -0.101468 Basset 0.254110 1.101227 -0.190701 Berger-All -0.486396 -0.464450 -0.498134 Boxer 0.447365 -0.881778 0.692016 Bull-Dog 1.013352 0.549879 -0.163423 Bull-Mastif -0.752574 0.546912 0.497573 Caniche 0.912301 -0.016188 -0.576570 Chihuahua 0.840799 0.843852 -0.469947 Cocker 0.733295 0.079073 0.662230 Colley -0.117325 -0.526108 -0.334894 Dalmatien 0.647240 -0.990184 0.458590 Doberman -0.873210 -0.315481 -0.452314 Dogue-All -1.047017 0.506958 0.165035 Epag.-Breton 0.478044 -1.036933 0.061924 Epag.-Français -0.144910 -0.515783 0.117127 Fox-Hound -0.876568 0.025240 -0.362171 Fox-Terrier 0.881622 0.138967 0.053522 Gd-Bleu-Gasc -0.517338 -0.113404 0.044029 Labrador 0.647240 -0.990184 0.458590 Levrier -0.676693 -0.083167 -0.595598 Mastiff -0.755932 0.887633 0.587715 Pekinois 0.840799 0.843852 -0.469947 Pointer -0.673335 -0.423887 -0.685740 St-Bernard -0.583379 0.593660 0.894239 Setter -0.504140 -0.377139 -0.289074 Teckel 1.013352 0.549879 -0.163423 Terre-Neuve -0.383504 0.485254 0.660813 row_coord_dim4 row_coord_dim5 row_coord_dim6 \ Beauceron -0.211436 -0.118510 -0.844917 Basset 0.292637 -0.524009 0.039895 Berger-All 0.577425 0.275902 -0.567765 Boxer 0.260002 -0.455590 -0.213746 Bull-Dog -0.349919 0.330786 -0.201414 Bull-Mastif 0.655153 0.721946 0.117926 Caniche 0.628133 0.434017 0.386066 Chihuahua -0.086343 -0.177346 0.197088 Cocker 0.189743 -0.104627 -0.626726 Colley -0.657755 0.192130 -0.374168 Dalmatien -0.186316 -0.144950 0.257003 Doberman 0.510087 0.239880 -0.254209 Dogue-All 0.062888 -0.316522 -0.001702 Epag.-Breton 0.602545 0.249461 0.534156 Epag.-Français -0.468922 0.000850 0.490693 Fox-Hound -0.015198 -0.662665 -0.132859 Fox-Terrier 0.285590 -0.271035 -0.361835 Gd-Bleu-Gasc 0.240972 -0.817923 0.418446 Labrador -0.186316 -0.144950 0.257003 Levrier -0.461516 -0.352025 0.337890 Mastiff 0.129868 -0.180598 0.239276 Pekinois -0.086343 -0.177346 0.197088 Pointer 0.063769 0.550519 0.216540 St-Bernard -0.133709 0.327535 -0.159227 Setter -0.725093 0.156108 -0.060612 Teckel -0.349919 0.330786 -0.201414 Terre-Neuve -0.580027 0.638174 0.311523 row_coord_dim7 row_coord_dim8 row_coord_dim9 \ Beauceron 0.089050 0.201986 -0.167019 Basset 0.052833 -0.447363 0.100738 Berger-All -0.129097 0.187330 -0.234185 Boxer -0.003008 -0.019819 -0.002446 Bull-Dog 0.063544 -0.079036 -0.035602 Bull-Mastif -0.018594 -0.037325 -0.112103 Caniche 0.401810 0.249347 0.165086 Chihuahua -0.327291 0.131410 -0.136707 Cocker -0.474951 -0.406018 0.143664 Colley -0.084198 0.276174 -0.110667 Dalmatien -0.176256 0.054368 0.053905 Doberman 0.077780 -0.317256 0.059613 Dogue-All -0.112827 0.506165 0.448174 Epag.-Breton -0.394402 0.039712 -0.013261 Epag.-Français 0.600636 -0.203761 -0.143231 Fox-Hound -0.094909 -0.092153 0.025674 Fox-Terrier 0.793204 0.189816 0.175900 Gd-Bleu-Gasc 0.383049 -0.067503 -0.300687 Labrador -0.176256 0.054368 0.053905 Levrier -0.268156 -0.017966 0.082026 Mastiff -0.191283 0.187777 -0.146041 Pekinois -0.327291 0.131410 -0.136707 Pointer -0.095468 -0.243068 0.115964 St-Bernard 0.199553 -0.022669 -0.044936 Setter 0.122679 -0.228412 0.183131 Teckel 0.063544 -0.079036 -0.035602 Terre-Neuve 0.026305 0.051519 0.011415 row_coord_dim10 ... row_cos2_dim1 row_cos2_dim2 \ Beauceron -0.022807 ... 0.088635 0.153700 Basset -0.147102 ... 0.033804 0.634867 Berger-All 0.008920 ... 0.153722 0.140164 Boxer -0.140901 ... 0.111331 0.432524 Bull-Dog -0.066543 ... 0.624485 0.183881 Bull-Mastif -0.024573 ... 0.270691 0.142958 Caniche 0.113482 ... 0.385194 0.000121 Chihuahua 0.002484 ... 0.379931 0.382695 Cocker 0.304810 ... 0.279157 0.003246 Colley 0.050656 ... 0.012396 0.249261 Dalmatien -0.067438 ... 0.236285 0.553017 Doberman -0.067203 ... 0.487612 0.063648 Dogue-All 0.019589 ... 0.560794 0.131474 Epag.-Breton -0.035711 ... 0.104983 0.493953 Epag.-Français 0.115970 ... 0.017533 0.222126 Fox-Hound -0.029903 ... 0.558313 0.000463 Fox-Terrier 0.008292 ... 0.436271 0.010840 Gd-Bleu-Gasc 0.111534 ... 0.186023 0.008939 Labrador -0.067438 ... 0.236285 0.553017 Levrier 0.043560 ... 0.338816 0.005118 Mastiff 0.012727 ... 0.299995 0.413633 Pekinois 0.002484 ... 0.379931 0.382695 Pointer 0.006259 ... 0.294592 0.116751 St-Bernard -0.056300 ... 0.201563 0.208730 Setter -0.025467 ... 0.223894 0.125298 Teckel -0.066543 ... 0.624485 0.183881 Terre-Neuve 0.017163 ... 0.088401 0.141532 row_cos2_dim3 row_cos2_dim4 row_cos2_dim5 row_cos2_dim6 \ Beauceron 0.009070 0.039382 1.237222e-02 0.628882 Basset 0.019039 0.044832 1.437493e-01 0.000833 Berger-All 0.161232 0.216646 4.946160e-02 0.209457 Boxer 0.266393 0.037605 1.154621e-01 0.025415 Bull-Dog 0.016242 0.074462 6.654209e-02 0.024671 Bull-Mastif 0.118328 0.205144 2.491061e-01 0.006646 Caniche 0.153853 0.182602 8.717967e-02 0.068981 Chihuahua 0.118691 0.004007 1.690306e-02 0.020876 Cocker 0.227672 0.018691 5.683030e-03 0.203913 Colley 0.100999 0.389612 3.324270e-02 0.126078 Dalmatien 0.118619 0.019580 1.185067e-02 0.037255 Doberman 0.130833 0.166389 3.679795e-02 0.041326 Dogue-All 0.013933 0.002023 5.125103e-02 0.000001 Epag.-Breton 0.001762 0.166787 2.858850e-02 0.131075 Epag.-Français 0.011454 0.183597 6.028475e-07 0.201041 Fox-Hound 0.095309 0.000168 3.190765e-01 0.012826 Fox-Terrier 0.001608 0.045780 4.123268e-02 0.073487 Gd-Bleu-Gasc 0.001347 0.040360 4.649900e-01 0.121702 Labrador 0.118619 0.019580 1.185067e-02 0.037255 Levrier 0.262474 0.157599 9.169119e-02 0.084476 Mastiff 0.181336 0.008854 1.712283e-02 0.030057 Pekinois 0.118691 0.004007 1.690306e-02 0.020876 Pointer 0.305546 0.002642 1.969263e-01 0.030467 St-Bernard 0.473605 0.010588 6.353655e-02 0.015016 Setter 0.073614 0.463157 2.146795e-02 0.003236 Teckel 0.016242 0.074462 6.654209e-02 0.024671 Terre-Neuve 0.262466 0.202214 2.447904e-01 0.058330 row_cos2_dim7 row_cos2_dim8 row_cos2_dim9 row_cos2_dim10 Beauceron 0.006986 0.035941 0.024574 0.000458 Basset 0.001461 0.104773 0.005313 0.011328 Berger-All 0.010829 0.022802 0.035635 0.000052 Boxer 0.000005 0.000219 0.000003 0.011044 Bull-Dog 0.002456 0.003799 0.000771 0.002693 Bull-Mastif 0.000165 0.000666 0.006006 0.000289 Caniche 0.074721 0.028775 0.012613 0.005960 Chihuahua 0.057569 0.009281 0.010044 0.000003 Cocker 0.117109 0.085582 0.010715 0.048234 Colley 0.006384 0.068686 0.011029 0.002311 Dalmatien 0.017522 0.001667 0.001639 0.002565 Doberman 0.003869 0.064366 0.002273 0.002888 Dogue-All 0.006512 0.131063 0.102752 0.000196 Epag.-Breton 0.071460 0.000724 0.000081 0.000586 Epag.-Français 0.301223 0.034666 0.017129 0.011229 Fox-Hound 0.006545 0.006171 0.000479 0.000650 Fox-Terrier 0.353152 0.020223 0.017367 0.000039 Gd-Bleu-Gasc 0.101983 0.003167 0.062842 0.008646 Labrador 0.017522 0.001667 0.001639 0.002565 Levrier 0.053206 0.000239 0.004978 0.001404 Mastiff 0.019209 0.018511 0.011197 0.000085 Pekinois 0.057569 0.009281 0.010044 0.000003 Pointer 0.005922 0.038390 0.008738 0.000025 St-Bernard 0.023584 0.000304 0.001196 0.001877 Setter 0.013258 0.045960 0.029544 0.000571 Teckel 0.002456 0.003799 0.000771 0.002693 Terre-Neuve 0.000416 0.001595 0.000078 0.000177 [27 rows x 30 columns] ###Markdown Statistiques pour les points lignes ###Code # Coordonnées des points lignes print(my_mca.row_coord_) # Contributions des points lignes print(my_mca.row_contrib_) # Cos2 des points lignes print(my_mca.row_cos2_) ###Output [[ 8.86354732e-02 1.53699594e-01 9.06978140e-03 3.93822110e-02 1.23722226e-02 6.28882412e-01 6.98570800e-03 3.59406044e-02 2.45737810e-02 4.58212084e-04] [ 3.38043142e-02 6.34867136e-01 1.90385973e-02 4.48320320e-02 1.43749337e-01 8.33218971e-04 1.46130981e-03 1.04772939e-01 5.31274484e-03 1.13283712e-02] [ 1.53722499e-01 1.40163659e-01 1.61231704e-01 2.16645575e-01 4.94615977e-02 2.09457186e-01 1.08290285e-02 2.28020784e-02 3.56349731e-02 5.16989317e-05] [ 1.11330751e-01 4.32523528e-01 2.66393303e-01 3.76048711e-02 1.15462068e-01 2.54147956e-02 5.03216176e-06 2.18507578e-04 3.32894680e-06 1.10438146e-02] [ 6.24484641e-01 1.83880633e-01 1.62415840e-02 7.44623393e-02 6.65420938e-02 2.46706743e-02 2.45556352e-03 3.79880801e-03 7.70833162e-04 2.69282992e-03] [ 2.70690765e-01 1.42958206e-01 1.18328181e-01 2.05144306e-01 2.49106067e-01 6.64648773e-03 1.65247798e-04 6.65849872e-04 6.00628608e-03 2.88603256e-04] [ 3.85193916e-01 1.21275082e-04 1.53853124e-01 1.82602376e-01 8.71796657e-02 6.89805511e-02 7.47211265e-02 2.87747035e-02 1.26131510e-02 5.96011012e-03] [ 3.79931295e-01 3.82695220e-01 1.18691149e-01 4.00657480e-03 1.69030599e-02 2.08757353e-02 5.75690136e-02 9.28068713e-03 1.00439490e-02 3.31624583e-06] [ 2.79156818e-01 3.24600200e-03 2.27671518e-01 1.86905820e-02 5.68303006e-03 2.03913464e-01 1.17108519e-01 8.55816269e-02 1.07148229e-02 4.82336169e-02] [ 1.23961745e-02 2.49260987e-01 1.00999475e-01 3.89612409e-01 3.32427027e-02 1.26077730e-01 6.38418085e-03 6.86863599e-02 1.10291440e-02 2.31083688e-03] [ 2.36285170e-01 5.53016560e-01 1.18619154e-01 1.95798039e-02 1.18506750e-02 3.72549417e-02 1.75223129e-02 1.66723619e-03 1.63897399e-03 2.56517269e-03] [ 4.87611688e-01 6.36477694e-02 1.30832617e-01 1.66389236e-01 3.67979467e-02 4.13255677e-02 3.86872855e-03 6.43657523e-02 2.27254304e-03 2.88815115e-03] [ 5.60793909e-01 1.31473847e-01 1.39330697e-02 2.02317920e-03 5.12510285e-02 1.48130883e-06 6.51216736e-03 1.31063126e-01 1.02751900e-01 1.96292818e-04] [ 1.04983391e-01 4.93952692e-01 1.76155797e-03 1.66787484e-01 2.85885007e-02 1.31075135e-01 7.14601014e-02 7.24489049e-04 8.07821830e-05 5.85867084e-04] [ 1.75332292e-02 2.22125629e-01 1.14544928e-02 1.83597294e-01 6.02847459e-07 2.01041147e-01 3.01222788e-01 3.46663185e-02 1.71291589e-02 1.12293397e-02] [ 5.58313038e-01 4.62892815e-04 9.53093579e-02 1.67833893e-04 3.19076498e-01 1.28259619e-02 6.54512653e-03 6.17061850e-03 4.78944747e-04 6.49727046e-04] [ 4.36271010e-01 1.08396312e-02 1.60791707e-03 4.57802078e-02 4.12326772e-02 7.34874674e-02 3.53152039e-01 2.02234317e-02 1.73670242e-02 3.85948911e-05] [ 1.86023209e-01 8.93871388e-03 1.34738090e-03 4.03602327e-02 4.64990004e-01 1.21702250e-01 1.01982866e-01 3.16708720e-03 6.28418601e-02 8.64639470e-03] [ 2.36285170e-01 5.53016560e-01 1.18619154e-01 1.95798039e-02 1.18506750e-02 3.72549417e-02 1.75223129e-02 1.66723619e-03 1.63897399e-03 2.56517269e-03] [ 3.38815590e-01 5.11772953e-03 2.62473933e-01 1.57599349e-01 9.16911884e-02 8.44756203e-02 5.32055317e-02 2.38820247e-04 4.97826984e-03 1.40396775e-03] [ 2.99995069e-01 4.13633334e-01 1.81335511e-01 8.85421459e-03 1.71228323e-02 3.00570559e-02 1.92087717e-02 1.85111860e-02 1.11969855e-02 8.50405730e-05] [ 3.79931295e-01 3.82695220e-01 1.18691149e-01 4.00657480e-03 1.69030599e-02 2.08757353e-02 5.75690136e-02 9.28068713e-03 1.00439490e-02 3.31624583e-06] [ 2.94592121e-01 1.16750676e-01 3.05546227e-01 2.64226154e-03 1.96926264e-01 3.04673744e-02 5.92209879e-03 3.83896153e-02 8.73790327e-03 2.54578375e-05] [ 2.01562822e-01 2.08729854e-01 4.73604996e-01 1.05883741e-02 6.35365485e-02 1.50155136e-02 2.35843478e-02 3.04350347e-04 1.19593217e-03 1.87726139e-03] [ 2.23894373e-01 1.25298065e-01 7.36135686e-02 4.63156843e-01 2.14679548e-02 3.23640456e-03 1.32580650e-02 4.59598352e-02 2.95435361e-02 5.71354530e-04] [ 6.24484641e-01 1.83880633e-01 1.62415840e-02 7.44623393e-02 6.65420938e-02 2.46706743e-02 2.45556352e-03 3.79880801e-03 7.70833162e-04 2.69282992e-03] [ 8.84006949e-02 1.41531574e-01 2.62465947e-01 2.02214424e-01 2.44790415e-01 5.83303730e-02 4.15897991e-04 1.59530051e-03 7.83234085e-05 1.77050645e-04]] ###Markdown I.3. Extraction des statistiques sur les points colonnes Export de la totalité des données colonnes vers une DataFrame pandasOn peut envoyer vers une Dataframe : les coordonnées, les contributions et les cos2 de chacun des points colonnes, pour tous les axes factoriels (identifiés par les suffixes dim1, dim2, etc.). ###Code df_cols = my_mca.col_topandas() print(df_cols) ###Output col_coord_dim1 col_coord_dim2 col_coord_dim3 \ Taille_Taille+ 0.851088 -1.231720 1.016052 Taille_Taille++ -0.836675 -0.020578 -0.051217 Taille_Taille- 1.184956 0.923897 -0.616000 Poids_Poids+ -0.305405 -0.818876 -0.231272 Poids_Poids++ -1.015134 0.973901 1.221595 Poids_Poids- 1.168918 0.824345 -0.358770 Velocite_Veloc+ 0.603687 -0.887814 0.356312 Velocite_Veloc++ -0.892100 -0.371832 -0.763088 Velocite_Veloc- 0.319941 1.044900 0.401729 Intelligence_Intell+ 0.369443 -0.285503 0.493203 Intelligence_Intell++ -0.335066 -0.459483 -0.599924 Intelligence_Intell- -0.349045 0.808555 -0.351511 Affection_Affec+ 0.775496 -0.266936 -0.060797 Affection_Affec- -0.835150 0.287470 0.065474 Agressivite_Agress+ -0.431539 0.209196 0.333548 Agressivite_Agress- 0.400714 -0.194253 -0.309723 col_coord_dim4 col_coord_dim5 col_coord_dim6 \ Taille_Taille+ 0.342456 -0.310040 0.118297 Taille_Taille++ -0.170222 0.112663 -0.049965 Taille_Taille- 0.120149 -0.019963 0.022569 Poids_Poids+ -0.118364 -0.190201 0.012908 Poids_Poids++ 0.067605 0.614518 0.289232 Poids_Poids- 0.164884 -0.051221 -0.203360 Velocite_Veloc+ 0.370243 -0.371036 0.629313 Velocite_Veloc++ -0.239848 -0.010089 -0.532181 Velocite_Veloc- -0.080331 0.305908 -0.024488 Intelligence_Intell+ -0.603492 0.146256 -0.378518 Intelligence_Intell++ 1.275249 1.063191 0.205389 Intelligence_Intell- 0.024238 -1.035060 0.461050 Affection_Affec+ 0.077216 0.040322 -0.318067 Affection_Affec- -0.083156 -0.043424 0.342534 Agressivite_Agress+ 0.551156 -0.374464 -0.514255 Agressivite_Agress- -0.511788 0.347717 0.477522 col_coord_dim7 col_coord_dim8 col_coord_dim9 \ Taille_Taille+ -0.858306 -0.259599 0.307322 Taille_Taille++ 0.117844 0.056414 -0.144633 Taille_Taille- 0.360553 0.064541 0.090411 Poids_Poids+ -0.037178 -0.125673 -0.184946 Poids_Poids++ -0.067864 0.641508 0.204009 Poids_Poids- 0.107475 -0.181014 0.196151 Velocite_Veloc+ 0.625743 0.173445 -0.008821 Velocite_Veloc++ -0.192758 0.141837 0.291628 Velocite_Veloc- -0.327112 -0.266409 -0.255408 Intelligence_Intell+ 0.281329 -0.075777 0.041319 Intelligence_Intell++ -0.092247 -0.094569 -0.020514 Intelligence_Intell- -0.387975 0.194064 -0.051758 Affection_Affec+ -0.170577 0.311516 -0.130227 Affection_Affec- 0.183698 -0.335479 0.140244 Agressivite_Agress+ 0.153837 -0.049324 -0.026899 Agressivite_Agress- -0.142849 0.045801 0.024978 col_coord_dim10 ... col_cos2_dim1 \ Taille_Taille+ -0.015208 ... 0.164625 Taille_Taille++ 0.121550 ... 0.875032 Taille_Taille- -0.249601 ... 0.491442 Poids_Poids+ -0.097573 ... 0.100447 Poids_Poids++ -0.071494 ... 0.234204 Poids_Poids- 0.215436 ... 0.575313 Velocite_Veloc+ 0.053786 ... 0.153447 Velocite_Veloc++ -0.020744 ... 0.397921 Velocite_Veloc- -0.024359 ... 0.060213 Intelligence_Intell+ -0.014492 ... 0.126739 Intelligence_Intell++ 0.002226 ... 0.032077 Intelligence_Intell- 0.021881 ... 0.051298 Affection_Affec+ 0.019314 ... 0.647656 Affection_Affec- -0.020799 ... 0.647656 Agressivite_Agress+ -0.020072 ... 0.172924 Agressivite_Agress- 0.018639 ... 0.172924 col_cos2_dim2 col_cos2_dim3 col_cos2_dim4 \ Taille_Taille+ 0.344803 0.234628 0.026654 Taille_Taille++ 0.000529 0.003279 0.036219 Taille_Taille- 0.298755 0.132809 0.005053 Poids_Poids+ 0.722139 0.057601 0.015088 Poids_Poids++ 0.215564 0.339158 0.001039 Poids_Poids- 0.286124 0.054196 0.011447 Velocite_Veloc+ 0.331879 0.053456 0.057718 Velocite_Veloc++ 0.069130 0.291151 0.028764 Velocite_Veloc- 0.642245 0.094933 0.003796 Intelligence_Intell+ 0.075690 0.225874 0.338188 Intelligence_Intell++ 0.060321 0.102831 0.464645 Intelligence_Intell- 0.275268 0.052025 0.000247 Affection_Affec+ 0.076736 0.003981 0.006421 Affection_Affec- 0.076736 0.003981 0.006421 Agressivite_Agress+ 0.040637 0.103308 0.282075 Agressivite_Agress- 0.040637 0.103308 0.282075 col_cos2_dim5 col_cos2_dim6 col_cos2_dim7 \ Taille_Taille+ 0.021847 0.003181 0.167429 Taille_Taille++ 0.015866 0.003121 0.017359 Taille_Taille- 0.000139 0.000178 0.045499 Poids_Poids+ 0.038959 0.000179 0.001488 Poids_Poids++ 0.085826 0.019013 0.001047 Poids_Poids- 0.001105 0.017413 0.004864 Velocite_Veloc+ 0.057965 0.166752 0.164865 Velocite_Veloc++ 0.000051 0.141608 0.018578 Velocite_Veloc- 0.055047 0.000353 0.062943 Intelligence_Intell+ 0.019863 0.133042 0.073493 Intelligence_Intell++ 0.322964 0.012053 0.002431 Intelligence_Intell- 0.451094 0.089502 0.063379 Affection_Affec+ 0.001751 0.108949 0.031335 Affection_Affec- 0.001751 0.108949 0.031335 Agressivite_Agress+ 0.130207 0.245568 0.021976 Agressivite_Agress- 0.130207 0.245568 0.021976 col_cos2_dim8 col_cos2_dim9 col_cos2_dim10 Taille_Taille+ 0.015316 0.021465 0.000053 Taille_Taille++ 0.003978 0.026148 0.018468 Taille_Taille- 0.001458 0.002861 0.021805 Poids_Poids+ 0.017009 0.036836 0.010253 Poids_Poids++ 0.093530 0.009459 0.001162 Poids_Poids- 0.013796 0.016200 0.019542 Velocite_Veloc+ 0.012667 0.000033 0.001218 Velocite_Veloc++ 0.010059 0.042523 0.000215 Velocite_Veloc- 0.041749 0.038373 0.000349 Intelligence_Intell+ 0.005332 0.001585 0.000195 Intelligence_Intell++ 0.002555 0.000120 0.000001 Intelligence_Intell- 0.015857 0.001128 0.000202 Affection_Affec+ 0.104507 0.018264 0.000402 Affection_Affec- 0.104507 0.018264 0.000402 Agressivite_Agress+ 0.002259 0.000672 0.000374 Agressivite_Agress- 0.002259 0.000672 0.000374 [16 rows x 30 columns] ###Markdown Statistiques pour les points colonnes ###Code # Coordonnées des points colonnes print(my_mca.col_coord_) # Contributions des points colonnes print(my_mca.col_contrib_) # Cos2 des points colonnes print(my_mca.col_cos2_) ###Output [[ 1.64625197e-01 3.44803059e-01 2.34627550e-01 2.66537163e-02 2.18465774e-02 3.18050046e-03 1.67429315e-01 1.53163382e-02 2.14651811e-02 5.25660553e-05] [ 8.75032050e-01 5.29341341e-04 3.27903251e-03 3.62193103e-02 1.58662007e-02 3.12058795e-03 1.73590277e-02 3.97817561e-03 2.61482672e-02 1.84680068e-02] [ 4.91442014e-01 2.98754660e-01 1.32809435e-01 5.05254394e-03 1.39489425e-04 1.78280217e-04 4.54993737e-02 1.45794078e-03 2.86098291e-03 2.18052798e-02] [ 1.00447166e-01 7.22138784e-01 5.76011410e-02 1.50877186e-02 3.89594100e-02 1.79444121e-04 1.48849136e-03 1.70087034e-02 3.68363070e-02 1.02528343e-02] [ 2.34203931e-01 2.15564186e-01 3.39157541e-01 1.03873360e-03 8.58256441e-02 1.90125017e-02 1.04669646e-03 9.35301025e-02 9.45898915e-03 1.16167377e-03] [ 5.75313407e-01 2.86123812e-01 5.41963075e-02 1.14470212e-02 1.10468845e-03 1.74126746e-02 4.86356754e-03 1.37962500e-02 1.62000281e-02 1.95422436e-02] [ 1.53447405e-01 3.31879115e-01 5.34562485e-02 5.77179639e-02 5.79652297e-02 1.66751629e-01 1.64865004e-01 1.26665839e-02 3.27608348e-05 1.21805981e-03] [ 3.97921103e-01 6.91296921e-02 2.91151283e-01 2.87635872e-02 5.08912185e-05 1.41608150e-01 1.85778305e-02 1.00588815e-02 4.25234310e-02 2.15150115e-04] [ 6.02129213e-02 6.42244786e-01 9.49329478e-02 3.79595157e-03 5.50470073e-02 3.52740658e-04 6.29425906e-02 4.17493676e-02 3.83726466e-02 3.49040920e-04] [ 1.26738700e-01 7.56897524e-02 2.25873819e-01 3.38187895e-01 1.98629905e-02 1.33041636e-01 7.34929109e-02 5.33193380e-03 1.58533237e-03 1.95029438e-04] [ 3.20768394e-02 6.03213262e-02 1.02831012e-01 4.64645451e-01 3.22964487e-01 1.20527241e-02 2.43128154e-03 2.55522703e-03 1.20236370e-04 1.41532164e-06] [ 5.12978688e-02 2.75267773e-01 5.20253342e-02 2.47354011e-04 4.51094394e-01 8.95017905e-02 6.33788003e-02 1.58571300e-02 1.12796422e-03 2.01590970e-04] [ 6.47655853e-01 7.67360421e-02 3.98058885e-03 6.42092843e-03 1.75091491e-03 1.08948761e-01 3.13347388e-02 1.04506948e-01 1.82635190e-02 4.01705745e-04] [ 6.47655853e-01 7.67360421e-02 3.98058885e-03 6.42092843e-03 1.75091491e-03 1.08948761e-01 3.13347388e-02 1.04506948e-01 1.82635190e-02 4.01705745e-04] [ 1.72923773e-01 4.06368567e-02 1.03307716e-01 2.82075371e-01 1.30207379e-01 2.45568248e-01 2.19755343e-02 2.25910803e-03 6.71897969e-04 3.74116824e-04] [ 1.72923773e-01 4.06368567e-02 1.03307716e-01 2.82075371e-01 1.30207379e-01 2.45568248e-01 2.19755343e-02 2.25910803e-03 6.71897969e-04 3.74116824e-04]] ###Markdown I.4. Graphiques 2 types de graphiques peuvent être réalisés : Les mapping classiques qui représentent les points lignes et colonnes sur un plan factoriel Des graphiques qui permettent d'interpréter rapidement les axes : on choisit un axe factoriel (le 1er axe dans notre exemple) et on observe quels sont les points lignes et colonnes qui présentent les plus fortes contributions et cos2 pour cet axeGraphiques factoriels ###Code # Mapping simultané des points lignes et colonnes # Les paramètres de la méthode mapping indiquent que ce sont les axes 1 et 2 qui sont ici représentés my_mca.mapping(num_x_axis=1, num_y_axis=2) # Mapping des points lignes my_mca.mapping_row(num_x_axis=1, num_y_axis=2) # Mapping des points colonnes my_mca.mapping_col(num_x_axis=1, num_y_axis=2) ###Output _____no_output_____ ###Markdown Sur les 3 graphiques factoriels précédents, les catégories ne sont pas préfixées par les noms des variables auxquelles elles appartiennent (c'est le choix fait par défaut par le package).Ce choix est pertinent dans cet exemple car l'omission des préfixes permet d'alléger les graphiques, et il n'y a pas de risque de confusion entre les catégories.Mais quand l'ensemble des catégories présente des doublons, il est préférable de les préfixer par les noms de variables pour lever toute ambiguïté, ce qui alourdit la présentation.Dans ce cas, on fixe le paramètre short_labels à False ###Code my_mca.mapping(num_x_axis=1, num_y_axis=2, short_labels=False) ###Output _____no_output_____ ###Markdown Analyse du 1er axe - Points lignes ###Code # Classement des points lignes en fonction de leur contribution au 1er axe # Le paramètre de la méthode plot_row_contrib indique que c'est pour l'axe numéro 1 que les contributions sont ici # représentées my_mca.plot_row_contrib(num_axis=1) # Classement des points lignes en fonction de leur cos2 sur le 1er axe my_mca.plot_row_cos2(num_axis=1) ###Output _____no_output_____ ###Markdown Analyse du 1er axe - Points colonnes ###Code # Classement des points colonnes en fonction de leur contribution au 1er axe my_mca.plot_col_contrib(num_axis=1) # Classement des points colonnes en fonction de leur cos2 sur le 1er axe my_mca.plot_col_cos2(num_axis=1) ###Output _____no_output_____ ###Markdown Pour ces graphiques produits par les méthodes plot_row_contrib, plot_row_cos2, plot_col_contrib, plot_col_cos2, on peut se limiter à visualiser les x valeurs les plus grandes via le paramètre nb_values. ###Code my_mca.plot_row_contrib(num_axis=1, nb_values=10) ###Output _____no_output_____ ###Markdown Pour tous les graphiques présentés plus haut, il est possible de définir un taille particulière via le paramètre figsize. ###Code my_mca.mapping(1, 2, figsize=(10, 8)) ###Output _____no_output_____ ###Markdown II. Approche Machine LearningIci, l'objectif est d'utiliser l'Analyse des Correspondance Multiples en tant que méthode de prétraitement.La classe MCA implémente les méthodes fit, transform et fit_transform bien connues des utilisateurs de scikit-learn.Il est ici judicieux de fixer le paramètre stats à False pour gagner en temps de traitement et en ressources mémoire. ###Code my_mca = MCA(stats=False) my_mca.fit(X) my_mca.transform(X) my_mca.fit_transform(X) ###Output _____no_output_____ ###Markdown Intégration dans une Pipeline de scikit-learn La class MCA peut être intégrée dans une Pipeline de scikit-learn.Dans le cadre de notre exemple, nous cherchons à prédire la 7ème variable (variable Fonction) à partir des 6 premières variables du jeu de données.Fonction est une variable nominale comprenant 3 catégories : "chasse", "compagnie" et "utilite".Pour la prédire, nous allons utiliser un modèle de régression logistique, qui prendra en input des axes issus d'une Analyse des Correspondances Multiples pratiquée sur les données brutes.Dans un premier temps, et de façon tout à fait arbitraire, nous fixons le nombre de composantes extraites à 4. ###Code from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV df = pd.read_table("mca_data.txt", header=0, index_col=0, delimiter="\t", encoding="utf-8") # X = features X = df.iloc[:, 0:6].as_matrix() # y = labels y = df.iloc[:, 6].as_matrix() # Construction de la Pipeline # On enchaine une Analyse des Correspondances Multiples (4 axes retenus) puis une régression logistique multinomiale pipe = Pipeline([("mca", MCA(n_components=4, stats=False)), ("logit", LogisticRegression(multi_class="multinomial", solver="lbfgs"))]) # Estimation du modèle pipe.fit(X, y) # Prédiction sur l'échantillon de test print(pipe.predict(X)) ###Output ['chasse' 'compagnie' 'chasse' 'compagnie' 'compagnie' 'utilite' 'compagnie' 'compagnie' 'compagnie' 'chasse' 'compagnie' 'utilite' 'utilite' 'compagnie' 'chasse' 'utilite' 'compagnie' 'utilite' 'compagnie' 'chasse' 'utilite' 'compagnie' 'chasse' 'utilite' 'chasse' 'compagnie' 'utilite'] ###Markdown Le paramètre n_components peut faire l'objet d'une optimisation via GridSearchCV de scikit-learn.Nous reconstruisons donc une Pipeline, sans spécifier de valeur a priori pour n_components. ###Code # Reconstruction d'une Pipeline, sans spécifier de valeur a priori pour n_components pipe2 = Pipeline([("mca", MCA(stats=False)), ("logit", LogisticRegression(multi_class="multinomial", solver="lbfgs"))]) # Paramétrage de la grille de paramètres # Attention à l'étendue des valeurs possibles pour mca__n_components !!! param = [{"mca__n_components": [x + 1 for x in range(10)]}] # Construction de l'obet GridSearchCV grid_search = GridSearchCV(pipe2, param_grid=param, scoring="accuracy") # Estimation du modèle grid_search.fit(X, y) # Affichage du score optimal grid_search.best_score_ # Affichage du paramètre optimal grid_search.best_params_ # Prédiction sur l'échantillon de test grid_search.predict(X) ###Output _____no_output_____
Day03/DB-WS03b.ipynb
###Markdown NOTE:-----진행하기 전에 다음의 셀을 실행시키고 가자.Please run the below cells first before proceeding- you'll need them soon! ###Code %load_ext sql %sql sqlite:///dataset_1.db ###Output _____no_output_____ ###Markdown 활동 3b------------집계 연산자, GROUP BYAggregation operators, GROUP BY 문제 1-----------베이글 스타트업 산업에 사용된 다음의 테이블들을 살펴보자. 먼저 두 개의 테이블을 먼저 살펴 볼 텐데, `bagel`은 베이글 회사가 생산하는 베이글의 종류를 나타낸다:Consider a set of tables that describe the up-and-coming bagel startup industry; for now let's just look at two tables here, `bagel`, which describes types of bagels made by the different bagel companies:> * name STRING> * price FLOAT> * made_by STRING그리고 `purchase`:And `purchase`:> * bagel_name STRING> * franchise STRING> * date INT> * quantity INT> * purchaser_age INT`purchase.bagel_name` 는 `bagel.name`을 참조하고 `purchase.franchise` 는 `bagel.made_by` 을 참조한다:Where `purchase.bagel_name` references `bagel.name` and `purchase.franchise` references `bagel.made_by`: ###Code %sql SELECT * FROM bagel LIMIT 3; %sql SELECT * FROM purchase LIMIT 3; ###Output * sqlite:///dataset_1.db Done. ###Markdown **구매자의 평균 나이가 18세 이상인** 베이글의 종류에 대한 _총수입_을 계산하는 질의문을 작성해보자. 질의문을 아래에 작성해보자:Can you write a query to get the _total revenue_ for each bagel type **which had an average purchaser age over 18**? Type your query below: ###Code %%sql """ 예상 되는 결과는 다음과 같다. 이 셀을 다시 실행하지 말자. 다시 실행하면 결과는 사라진다. """ """ Expected output below Don't re-execute this cell! """ ###Output * sqlite:///dataset_1.db Done. ###Markdown 문제 2-----------이번에는 간소화된 버전의 `precipitation_full` 테이블을 사용할 것이다. 스키마는 다음과 같고, _CA_ 지역의 하루 강우량만 기록하고 있다:Here we'll use a simplified version of the `precipitation_full` table, which just has _daily_ rainfall _in CA only_, and has the following schema:> * station_id> * day> * precipitation ###Code %sql SELECT * FROM precipitation LIMIT 5; ###Output * sqlite:///dataset_1.db Done. ###Markdown 평균 침전물이 75 이상인 station_ids 를 구하려고 한다. 먼저, 중첩된 질의문으로 작성해보자:We want to get station_ids which have average precipitations > 75. Try doing this first as a nested query: ###Code %%sql """ 예상 되는 결과는 다음과 같다. 이 셀을 다시 실행하지 말자. 다시 실행하면 결과는 사라진다. """ """ Expected output below Don't re-execute this cell! """ ###Output Done. ###Markdown 이 번에는 GROUP BY를 사용하여 작성해보자:Now, try re-writing as a GROUP BY: ###Code %%sql """ 예상 되는 결과는 다음과 같다. 이 셀을 다시 실행하지 말자. 다시 실행하면 결과는 사라진다. """ """ Expected output below Don't re-execute this cell! """ ###Output Done. ###Markdown 실행 결과 계산 시간을 `%time`으로 측정해보자. `%time` 명령 다음에 질의문을 한 줄로 표현하여 실행하여 보자. 갑갑해 보이지만, 그래도 동작한다. 그리고 실행 결과들을 비교해보자!Now time it by using `%time` followed by single-line versions of your queries above (clunky, but will work) to see how they compare!**Note:** 아래는 임의의 질의문의 측정 결과이다. 앞에서 작성을 아래 문장과 치환하여 성능을 비교해보자.**Note:** Yes, currently the answers are filled in below for convenience... but you should still try getting them on your own above! ###Code -- 중첩 질의문의 사용 %time %sql SELECT DISTINCT p.station_id FROM precipitation p ; -- 집계 함수와 조건절 사용 %time %sql SELECT p.station_id FROM precipitation p ; ###Output Done. CPU times: user 3.06 ms, sys: 1.43 ms, total: 4.49 ms Wall time: 3.11 ms
notebooks/Intro_to_Python.ipynb
###Markdown Intro to Python START ON COMMAND LINECheck you're running Python 3: ###Code !python -V 3 + 2 a = 3 a + 2 import math math.sqrt(10) ###Output _____no_output_____ ###Markdown Getting help ###Code math.__doc__ help(math) dir(math) dir(10) ###Output _____no_output_____ ###Markdown We get some extra help from IPython: ###Code math. # Put your cursor after the dot and hit tab. math.sqrt? ###Output _____no_output_____ ###Markdown Let's continue! Numbers and `math`- Numbers and math operators, including modulo- `int` and `float` (without talking about types per se)- Assignment and dynamic typing- Booleans and boolean operators- `math` module- `dir` and `help` etc. Exercise- Evaluate $x^2 + 3x - 7$ when $x = 5$. (You should get 33.)- What is the log10 of 7e7? (Use the `math` library.)- What is the $tan$ of $\pi$ rad? (Use the `math` library.) ###Code # Part 1 – mathematical operators # Part 2 – scientific notion and using a function from the math library # Part 3 – trigonometric calculation ###Output _____no_output_____ ###Markdown Sneak peek at NumPy ###Code import numpy as np np.log(7) before = np.load('../data/st-helens_before.npy') before %matplotlib inline import matplotlib.pyplot as plt plt.imshow(before) ###Output _____no_output_____ ###Markdown Strings SWITCH TO NOTEBOOK- Strings- `len` and sequences- Membership: `in`- Concatenation and multiplication- `str` and type casting (strong typing)- Indexing, slicing- String methods (objects, methods, functions)- `upper`, `isupper`, `startswith`, `find`, `replace`- Print, `\n` and escapes- f-strings and `str.format()` Exercise- What types are: - `'Jurassic'` - `5` - `3.1416` - `s` - `math` - `math.log` - `str`- Use the `math` module and an f-string to print $\mathrm{e}$ (the base of the natural logarithm) to 3 decimal places. - Change `'JURASSIC*PERIOD\n'` to lower case.- Change the `'*'` to a space, change everything to title case, and remove the new line.- For a bonus point, make sure your expression also works for `'CARBONIFEROUS*PERIOD\n'`- For another bonus point, do this all in a single expression. ###Code # What types are: 'Jurassic', 5, 3.14, s, math, math.log, and str ? # print e in an f-string with 3 decimal places # Change the following string to lower case s = 'JURASSIC*PERIOD\n' # Change the '*' to a space, change everything to title case, and remove the new line character # Make sure the expression above also works for 'CARBONIFEROUS*PERIOD\n' s2 = 'CARBONIFEROUS*PERIOD\n' # Bonus point: do this all in a single expression (one line) ###Output _____no_output_____ ###Markdown Another sneak peek at NumPy ###Code np.max(before) before.max() np.mean(before) before.mean() ###Output _____no_output_____ ###Markdown `if ... else`- White space in Python- Basic pattern- `elif` for mutually exclusive options, e.g. when parsing a file, or comparing a number to various ranges.- One-liner: `lithology = "sand" if GR < 50 else "shale"` ###Code string = 'UWI 6/09239/45-0001' if '/' in string: print('Valid') ###Output _____no_output_____ ###Markdown This diagram might help make sense of `if` (then again it might not!). In particular, it shows how the different branches `if` and `else`, or the different branches of `if`, `elif`, and `else`, are *mutually exclusive*. There is no scenario where more than one 'branch' runs. Lists- Split `'Triassic Jurassic Cretaceous'`- "Just another sequence"- Numbers in a list, plot them- Making a list, syntax: parentheses, brackets- Heterogeneous lists, nested lists- Indexing and slicing (brackets when slicing)- `append`, `index`, `pop`- Mutability, compared to strings, `append`- Mutability gotcha Exercise- Split this string into a list called `lithologies`: `'Sandstone, Shale, Limestone, Dolomite, Basalt, Granite'`.- Use `sorted()` to sort the list. Can you sort it backwards? - Copy the list to a new name, `rocks`.- Add the following rocks to the new list: `'Gypsum'`, `'Halite'` (and make sure they're not in the old one).- Change the second element to `'Mudstone'`. ###Code # Split this string into a list called 'lithologies' str_with_rocks = 'Sandstone, Shale, Limestone, Dolomite, Basalt, Granite' # Use sorted() to sort this list. Can you sort it backwards? # Copy the list to a new name called `rocks` # Add the following rocks to this new list: 'Gypsum', 'Halite' # Also make sure they are not in the old one # Change the second element in `rocks` to 'Mudstone' ###Output _____no_output_____ ###Markdown More NumPy ###Code before ###Output _____no_output_____ ###Markdown Slicing into arrays: Math with a list, compared to arrays: ###Code after = np.load('../data/st-helens_after.npy') ###Output _____no_output_____ ###Markdown `for ... in ...` (for each)- Basic pattern on a list- Basic pattern on a string- Print 'sand' or 'shale' for porosities `[0.03, 0.01, 0.19, 0.12, 0.21, 0.05, 17.5, 3.0]`- If we've covered `dict`, then mention stepping over `dict.items()`- List comprehension &mdash; with strings- `continue` and `break` ###Code porosities = [0.03, 0.01, 0.19, 0.12, 0.21, 0.05, 17.5, 3.0] # Recall we have our list of rocks from before: rocks ###Output _____no_output_____ ###Markdown ExerciseRearrange the following lines to loop over a list of files and gather the second part of the file names &mdash; the months &mdash; into a new list, then print the new list.When the code runs, it should produce: ['Jan', 'Mar', 'Jun', 'Jun'] ###Code print(months) files = ['MH_Jan-18.png', 'MH_Mar-18.png', 'MH_Jun-18.png', 'MH_Jun-17.png'] months.append(month) month = file.split('_')[1].split('-')[0] for file in files: months = [] ###Output _____no_output_____ ###Markdown Exercise- Make a loop to print the squares of the numbers up to 10. Start with `for n in range(1, 11):`- Modify your loop to capture the squares in a new list, instead of printing them.- For a bonus point, do this with a list comprehension instead.- Add an `if` to only collect the squares of even numbers (to the `for` loop version; it's a bit harder with the list comprehension).- Loop over this list and make a new list of 1000 times each value. However, if the value is -999.25, skip it: - `[2.3, 2.4, 2.8, -999.25, 2.1, -999.25, 2.5, 2.5]` Again, this diagram might help... but it might not. Dictionaries- Not a sequence, but a database-like mapping of k, v pairs- Forming with `{...}`- Keys and values- Retrieving a value using a key- Adding keys- Deleting keys with `pop`- `in`- `get` (a bit like a database)- `update` with `{k: v}`, or just do `dict[k] = v` ExerciseUsing the dictionary called `periods`, complete the following tasks:- Retrieve the start of the Jurassic.- Use this call in an f-string to print: 'The Jurassic started about 201 Ma ago.'- Add the Permian, starting at 298.9 Ma.- The Quaternary has the wrong age; change it to 2.58 Ma.- The Palaeogene has the wrong spelling; change it.- Get a sorted list of the start ages (note, you don't need to sort the entire dictionary, which is a little tricky; you just need to sort the ages).- Stretch goal: Make a new dictionary with values that also contain the uncertainty in the ages (you can make up the uncertainties).- Stretch goal: Loop over the dictionary, printing the sentence in the second question (above) for each one. ###Code periods = { 'Triassic': 251.9, 'Jurassic': 201.3, 'Cretaceous': 145.0, 'Palogene': 66.0, 'Neogene': 23.03, 'Quaternary': 2.18, } # Retrieve the start of the Jurassic. # Use this in an f-string to print, 'The Jurassic started about 201 Ma ago.' # Add the Permian period to the dictionary, which started at 298.9 Ma # The Quaternary has the wrong age; change it to 2.58 Ma. # The Palaeogene has the wrong spelling; change it. # Get a sorted list of the start ages. # Make a new dictionary with values that also contain an uncertainty in ages # Loop over the dictionary, printing the sentence in the second question (above) for each item ###Output _____no_output_____ ###Markdown Optional exercise: counting with a dictionaryDictionaries are useful for counting things. Can you loop over the list of strings `strat` and make a dictionary that maps each unique layer type to the count of layers for that type?You should end up with a dictionary that looks similar to: {'marl': 169, 'sandstone': 178, 'shale': 169, 'dolomite': 168, 'limestone': 145, 'siltstone': 171} To do this, we'll generate some fake data:.We can start with a small number of 'layers', to make sure our code is working. Then we can process any number of layers. ###Code import random rocks = ['marl', 'sandstone', 'shale', 'dolomite', 'limestone', 'siltstone'] strat = [random.choice(rocks) for _ in range(10)] strat # Your code here. ###Output _____no_output_____ ###Markdown --- Other great places to pick up Python:- [Learn X in Y minutes](https://learnxinyminutes.com/docs/python3/) — If you just want to get cracking.- [Stavros](https://www.stavros.io/tutorials/python/) — If you want to know a bit more.- [Robert Johansson's lectures](Lecture-1-Introduction-to-Python-Programming.ipynb)- [Tutorials Point](http://www.tutorialspoint.com/python/python_quick_guide.htm) — Another option.- [Code Academy](https://www.codecademy.com/learn/learn-python-3) — A more sedate pace.- [Udacity Intro to Computer Science](https://www.udacity.com/course/intro-to-computer-science--cs101) — Fantastic but a serious undertaking.- [All the tutorials!](https://wiki.python.org/moin/BeginnersGuide/Programmers)**WARNING** There's still a lot of Python 2 around. Keep away from it if you can! Python 3 has lots of advantages, and there are hardly any libraries now that have not made the swtich.---- Python is...- Not just a scripting language.- Interpreted, not compiled.- Strongly typed — types are enforced.- Dynamically, implicitly typed — you don't have to declare variables.- Case sensitive — var and VAR are two different variables.- Object-oriented — everything is an object.- Supportive of functional and procedural styles. ###Code import this ###Output _____no_output_____ ###Markdown Intro to Python START ON COMMAND LINECheck you're running Python 3: ###Code !python -V 3 + 2 a = 3 a + 2 import math math.sqrt(10) ###Output _____no_output_____ ###Markdown Getting help ###Code math.__doc__ help(math) dir(math) dir(10) ###Output _____no_output_____ ###Markdown We get some extra help from IPython: ###Code math. # Put your cursor after the dot and hit tab. math.sqrt? ###Output _____no_output_____ ###Markdown Let's continue! Numbers and `math`- Numbers and math operators- `int` and `float` (without talking about types per se)- Assignment and dynamic typing- Booleans and boolean operators- `math` module- `dir` and `help` etc. Exercise:- Solve $x^2 + 3x - 7$ when $x = 3.14$. - What is `5 or 0`? Why?- What is the log10 of 7e7?- What is the $tan$ of $\pi$ rad?- What is 0.1 + 0.2? Strings SWITCH TO NOTEBOOK- By the way, NumPy for maths- Strings: making, indexing, slicing- `len` - sequences- Concatenation and `in`- `str` and type casting (strong typing)- String methods (objects, methods, functions)- `upper`, `isupper`, `startswith`, `find`, `replace`- Print, `\n` and escapes Exercise:- What types are `"Statoil"`, `5`, `3.1416`, `a`, `math`, `math.log`, `str`- Use `math.pi` and `str.format()` to print $\pi$ to 2 decimal places. - Change `"JURASSIC*PERIOD\n"` to lower case.- Change the `*` to a space, change everything to title case, and remove the new line &mdash; in a single expression. Lists- Split `"Triassic Jurassic Cretaceous"`- "Just another sequence"- Making a list, syntax: parentheses, brackets- Heterogeneous lists, nested lists- Indexing and slicing- `append`, `index`, `pop`- Mutability, compared to strings- Mutability gotcha Exercise:- Split this string into a list called `lithologies`: `"Sandstone Shale Limestone Dolomite Basalt Granite"`- Sort the list, then sort it backwards- Copy the list to a new name, `rocks`- Make a variable d and assign it to the 4th element of the list- Make a variable `rock` and assign it to the last item, and remove the last item- Add the following rocks to the list: `"Gypsum"`, `"Halite"`- Change the second element to `"Mudstone"` Tuples- Like lists, but immutable (so no append... but add ok)- Multiple assignment (usually w tuples) Dictionaries- Not a sequence, but a database-like mapping of k, v pairs- Forming with `{...}`- Keys and values- `in`- `get` (a bit like a database)- `update` with `{k: v}`, or just do `dict[k] = v` Exercise:- Retrieve the start of the Jurassic- Use it, with string formatting, to print: "The Jurassic started about 201 Ma ago."- Add the Permian, starting at 298.9 Ma- The Palaeogene has the wrong spelling and the wrong age (should be 66.0); change them.- Get a sorted list of the start ages- Make a new dictionary with values that also contain the uncertainty in the ages (You can make up the uncertainties) ###Code periods = { "Triassic": 251.9, "Jurassic": 201.3, "Cretaceous": 145.0, "Paleogene": 65, "Neogene": 23.03, "Quaternary": 2.58, } ###Output _____no_output_____ ###Markdown `if ... else`- White space in Python- Pattern- `elif`- One-liner version `for ... in` (for each)- Pattern- Stepping over 2-tuples- Stepping over `dict.items()`- List comprehension- `continue` and `break` Exercise:- Make a loop to print the squares of the numbers up to 10.- Make a list comprehension to collect these squares.- Add an `if` to only collect the squares of even numbers.- Write a loop over the positive whole numbers to 100, printing 'fizz' for numbers divisible by 3 and/or 'buzz' for those divisible by 5, and only the number if divisible by neither. --- The basicsOther great places to pick up Python:- [Learn X in Y minutes](https://learnxinyminutes.com/docs/python3/) — If you just want to get cracking.- [Stavros](https://www.stavros.io/tutorials/python/) — If you want to know a bit more.- [Robert Johansson's lectures](Lecture-1-Introduction-to-Python-Programming.ipynb)- [Tutorials Point](http://www.tutorialspoint.com/python/python_quick_guide.htm) — Another option.- [Code Academy](https://www.codecademy.com/learn/python) — A more sedate pace.- [Udacity Intro to Computer Science](https://www.udacity.com/course/intro-to-computer-science--cs101) — Fantastic but a serious undertaking.- [All the tutorials!](https://wiki.python.org/moin/BeginnersGuide/Programmers)**WARNING** There's still a lot of Python 2 around. Keep away from it if you can! Python 3 has lots of advantages, and there are hardly any libraries now that have not made the swtich.---- Python is...- Not just a scripting language.- Interpreted, not compiled.- Strongly typed — types are enforced.- Dynamically, implicitly typed — you don't have to declare variables.- Case sensitive — var and VAR are two different variables.- Object-oriented — everything is an object.- Supportive of functional and procedural styles. ###Code import this ###Output _____no_output_____
notebooks/_archive/02-interaction - old.ipynb
###Markdown 4.2 Finding interactions and regions of interactions Interaction model$Y = 0.2X_{1} - 5X_{2} + 10X_2\mathbb{1}_{X_{3} \geq 0} + \varepsilon$,$\varepsilon \overset{\text{iid}}{\sim} \mathcal{N}(0,1),\quad X_{1},X_{2},X_{3}\overset{\text{iid}}{\sim}U(-1,1) $ ###Code import numpy as np import pandas as pd from matplotlib import pyplot as plt %matplotlib inline import xgboost as xgb from sklearn.metrics import mean_squared_error from xgboost import XGBRegressor from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedKFold from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier import seaborn as sns from pycebox.ice import ice, ice_plot from matplotlib.cm import seismic # import sympy as sym from sympy import * x1,x2,x3,y,yprime = [],[],[],[],[] N = 1000 for i in range(0,N): X1 = np.random.uniform(-1, 1, size = 1) X2 = np.random.uniform(-1, 1, size = 1) X3 = np.random.uniform(-1, 1, size = 1) eps = np.random.uniform(0, 1, size = 1) Y = 0.2*X1 - 5*X2 + 10*X2*(X3>0) + eps x1.append(X1) x2.append(X2) x3.append(X3) X3 = Symbol('X3') der_y = lambdify(X3, Y) y_der = der_y(X3) y.append(Y) yprime.append(y_der) yprime = np.array(yprime) data = np.concatenate([x1,x2,x3,y,yprime], axis = 1) df = pd.DataFrame(data, columns=['X1','X2','X3','Y','Yprime']) df X = df[['X1','X2','X3']] y = df.Y yprime = df.Yprime ice_df = ice(X, 'X3', clf.predict) clf = GradientBoostingRegressor(n_estimators=500, learning_rate=0.1, max_depth=3, random_state=0).fit(X,y) from sklearn.model_selection import cross_val_score scores = cross_val_score(clf, X, y, cv=5) scores ice_df.head() fig, (data_ax, ice_ax) = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(16, 6)) data_ax.scatter(X.X3, y, c='k', alpha=0.5); data_ax.set_xlim(-1.05, 1.05); data_ax.set_xlabel('$X_3$'); data_ax.set_ylabel('$\hat{y}$'); data_ax.set_title('Data'); ice_plot(ice_df, frac_to_plot=0.05, plot_pdp=True, plot_points=True, c='k', alpha=0.25, ax=ice_ax) ice_ax.set_xlabel('X_3') ice_ax.set_ylabel('partial yhat') ice_ax.set_title('ICE (10 curves)') ###Output _____no_output_____
paper/Advection_diffusion/AD_artificial/PDEFIND.ipynb
###Markdown 2D Advection-Diffusion equation in this notebook we provide a simple example of the DeepMoD algorithm and apply it on the 2D advection-diffusion equation. ###Code # General imports import numpy as np import torch import matplotlib.pylab as plt # DeepMoD functions from deepymod import DeepMoD from deepymod.model.func_approx import NN from deepymod.model.library import Library2D_third from deepymod.model.constraint import LeastSquares from deepymod.model.sparse_estimators import Threshold,PDEFIND from deepymod.training import train from deepymod.training.sparsity_scheduler import TrainTestPeriodic from scipy.io import loadmat # Settings for reproducibility np.random.seed(1) torch.manual_seed(1) device = 'cpu' %load_ext autoreload %autoreload 2 ###Output _____no_output_____ ###Markdown Prepare the data Next, we prepare the dataset. ###Code data = loadmat('Diffusion_2D_space41.mat') data = np.real(data['Expression1']).reshape((41,41,41,4))[:,:,:,3] down_data= np.take(np.take(np.take(data,np.arange(0,data.shape[0],1),axis=0),np.arange(0,data.shape[1],1),axis=1),np.arange(0,data.shape[2],9),axis=2) print("Dowmsampled shape:",down_data.shape) width, width_2, steps = down_data.shape x_arr = np.linspace(0,1,width) y_arr = np.linspace(0,1,width_2) t_arr = np.linspace(0,1,steps) x_grid, y_grid, t_grid = np.meshgrid(x_arr, y_arr, t_arr, indexing='ij') X = np.transpose((t_grid.flatten(), x_grid.flatten(), y_grid.flatten())) y = np.float32(down_data.reshape((down_data.size, 1))) ###Output _____no_output_____ ###Markdown We select the noise level we add to the data-set ###Code noise_level = 0.20 y_noisy = y + noise_level * np.std(y) * np.random.randn(y.size, 1) solution = y_noisy.reshape(down_data.shape) plt.imshow(solution[:,:,1]) ###Output _____no_output_____ ###Markdown Select the number of samples: ###Code steps = down_data.shape[2] dim_w = 3 denoised_sol = [] for i in np.arange(steps): uwn,sigmawn,vwn= np.linalg.svd(solution[:,:,i]) vwn = vwn.T denoised_sol.append(uwn[:,0:dim_w].dot(np.diag(sigmawn[0:dim_w]).dot(vwn[:,0:dim_w].T))) denoised_sol = np.transpose(np.array(denoised_sol),(1,2,0)) plt.plot(denoised_sol[:,20,1]) plt.plot(solution[:,20,1]) plt.plot(denoised_sol[:,20,4]) plt.plot(solution[:,20,4]) PDEFIND() number_of_samples = 8400 idx = np.random.permutation(y.shape[0]) X_train = torch.tensor(X[idx, :][:number_of_samples], dtype=torch.float32, requires_grad=True).to(device) y_train = torch.tensor(y_noisy[idx, :][:number_of_samples], dtype=torch.float32).to(device) ###Output _____no_output_____ ###Markdown Configuration of DeepMoD Configuration of the function approximator: Here the first argument is the number of input and the last argument the number of output layers. ###Code network = NN(3, [40, 40, 40, 40], 1) ###Output _____no_output_____ ###Markdown Configuration of the library function: We select athe library with a 2D spatial input. Note that that the max differential order has been pre-determined here out of convinience. So, for poly_order 1 the library contains the following 12 terms:* [$1, u_x, u_y, u_{xx}, u_{yy}, u_{xy}, u, u u_x, u u_y, u u_{xx}, u u_{yy}, u u_{xy}$] ###Code library = Library2D_third(poly_order=0) ###Output _____no_output_____ ###Markdown Configuration of the sparsity estimator and sparsity scheduler used. In this case we use the most basic threshold-based Lasso estimator and a scheduler that asseses the validation loss after a given patience. If that value is smaller than 1e-5, the algorithm is converged. ###Code estimator = Threshold(0.05) sparsity_scheduler = TrainTestPeriodic(periodicity=50, patience=200, delta=1e-5) ###Output _____no_output_____ ###Markdown Configuration of the sparsity estimator ###Code constraint = LeastSquares() # Configuration of the sparsity scheduler ###Output _____no_output_____ ###Markdown Now we instantiate the model and select the optimizer ###Code model = DeepMoD(network, library, estimator, constraint).to(device) # Defining optimizer optimizer = torch.optim.Adam(model.parameters(), betas=(0.99, 0.99), amsgrad=True, lr=2e-3) ###Output _____no_output_____ ###Markdown Run DeepMoD We can now run DeepMoD using all the options we have set and the training data:* The directory where the tensorboard file is written (log_dir)* The ratio of train/test set used (split)* The maximum number of iterations performed (max_iterations)* The absolute change in L1 norm considered converged (delta)* The amount of epochs over which the absolute change in L1 norm is calculated (patience) ###Code train(model, X_train, y_train, optimizer,sparsity_scheduler, log_dir='runs/no_noise_5/', split=0.8, max_iterations=100000, delta=1e-6, patience=200) ###Output 99975 MSE: 2.10e-06 Reg: 2.27e-06 L1: 1.57e+00 Algorithm converged. Writing model to disk. ###Markdown Sparsity masks provide the active and non-active terms in the PDE: ###Code model.sparsity_masks ###Output _____no_output_____ ###Markdown estimatior_coeffs gives the magnitude of the active terms: ###Code print(model.estimator_coeffs()) data = loadmat('Diffusion_2D.mat') usol = np.real(data['Expression1']) usol= usol.reshape((51,51,41,4)) data_tot = usol[:,:,:,3] print("Total data shape:",data_tot.shape) width_tot, width_2_tot, steps_tot = data_tot.shape x_tot = np.linspace(0,1,width_tot) y_tot = np.linspace(0,1,width_2_tot) t_tot = np.linspace(0,1,steps_tot) x_grid_tot, y_grid_tot, t_grid_tot = np.meshgrid(x_tot, y_tot, t_tot, indexing='ij') X_tot = np.transpose((t_grid_tot.flatten(), x_grid_tot.flatten(), y_grid_tot.flatten())) noisy_sol = y_noisy.reshape(down_data.shape) solution = model(torch.tensor(X_tot, dtype=torch.float32)) sol = solution[0].reshape(data_tot.shape).detach().numpy() ux = solution[2][0][:,1].reshape(data_tot.shape).detach().numpy() uy = solution[2][0][:,2].reshape(data_tot.shape).detach().numpy() ut = solution[1][0].reshape(data_tot.shape).detach().numpy() uxx = solution[2][0][:,3].reshape(data_tot.shape).detach().numpy() uyy = solution[2][0][:,4].reshape(data_tot.shape).detach().numpy() import pysindy as ps fd_spline = ps.SINDyDerivative(kind='spline', s=1e-2) fd_spectral = ps.SINDyDerivative(kind='spectral') fd_sg = ps.SINDyDerivative(kind='savitzky_golay', left=0.5, right=0.5, order=3) dim_w = 3 denoised_sol = [] for i in np.arange(down_data.shape[2]): uwn,sigmawn,vwn= np.linalg.svd(down_data[:,:,i]) vwn = vwn.T denoised_sol.append(uwn[:,0:dim_w].dot(np.diag(sigmawn[0:dim_w]).dot(vwn[:,0:dim_w].T))) denoised_sol = np.array(denoised_sol).T denoised_sol= np.transpose(denoised_sol,axes=(1,0,2)) data_tot.shape plt.imshow(noisy_sol[:,:,10]) plt.plot(y_arr,noisy_sol[5,:,30], 'ro') plt.plot(y_tot,data_tot[25,:,30], 'go--') plt.plot(y_tot,sol[25,:,30],'g', label='t = 5',linewidth=3) plt.plot(y_arr,noisy_sol[5,:,5], 'ro') plt.plot(y_tot,data_tot[25,:,5], 'go--') plt.plot(y_tot,sol[25,:,5],'g', label='t = 5',linewidth=3) plt.plot(y_tot,data_tot[:,25,2], 'go--') plt.plot(y_tot,sol[:,25,2],'g', label='t = 5',linewidth=3) plt.plot(y_arr,noisy_sol[:,5,2], 'ro') plt.plot(y_tot,data_tot[25,:,1], 'bo--') plt.plot(y_tot,sol[25,:,1],'b', label='t = 1',linewidth=3) plt.plot(y_arr,noisy_sol[5,:,1], 'o') plt.plot(y_tot,data_tot[25,:,30], 'go--') plt.plot(y_tot,sol[25,:,30],'g', label='t = 5',linewidth=3) plt.plot(y_arr,noisy_sol[5,:,30], 'o') plt.plot(y_tot,data_tot[25,:,10], 'ro--') plt.plot(y_tot,sol[25,:,10],'r', label='t = 10',linewidth=3) plt.legend() y = down_data[5,:,1] x = y_arr plt.plot(x,fd_spline(y,x), 'bo--') plt.plot(x_tot,uy[25,:,1]*np.max(data_tot)/np.max(y_tot),'b', label='x = 1',linewidth=3) plt.plot(x_tot,fd_spectral(data_tot[25,:,1],x_tot)*np.max(data_tot)/np.max(y_tot),'r', label='x = 1',linewidth=3) y = down_data[5,:,1] x = y_arr plt.plot(x,fd_spline(fd_spline(y,x),x), 'bo--') plt.plot(x_tot,uyy[25,:,1]*np.max(data_tot)/np.max(y_tot),'b', label='x = 1',linewidth=3) plt.plot(x_tot,fd_spectral(fd_spectral(data_tot[25,:,1],x_tot),x_tot),'r', label='x = 1',linewidth=3) y = down_data[5,:,1] x = y_arr plt.plot(x,fd_spline(y,x), 'bo--') plt.plot(x_tot,uy[25,:,1]*np.max(data_tot)/np.max(y_tot),'b', label='x = 1',linewidth=3) y = down_data[5,:,1] x = y_arr plt.plot(x,fd_spline(y,x), 'bo--') plt.plot(x,uy[5,:,1]*np.max(tot_data)/np.max(y_tot),'b', label='x = 1',linewidth=3) y = down_data[5,:,2] x = y_arr plt.plot(x,fd_spline(y,x), 'go--') plt.plot(x,uy[5,:,2]*np.max(down_data)/np.max(y_grid),'g', label='x = 5',linewidth=3) y = down_data[5,:,4] x = y_arr plt.plot(x,fd_spline(y,x), 'ro--') plt.plot(x,uy[5,:,4]*np.max(down_data)/np.max(y_grid),'r', label='x = 10',linewidth=3) plt.legend() t = t_tot down_data[5,2,:].shape y = down_data[5,2,:] t = t_arr plt.plot(t_tot,fd_sg(y_tot,t_tot), 'bo--') plt.plot(t,ut[5,2,:]*np.max(down_data)/np.max(t_grid),'b', label='y = 12',linewidth=3) y = down_data[5,5,:] t = t_arr plt.plot(t,fd_sg(y,t), 'go--') plt.plot(t,ut[5,5,:]*np.max(down_data)/np.max(t_grid),'g', label='y = 6',linewidth=3) y = down_data[5,8,:] t = t_arr plt.plot(t,fd_sg(y,t), 'ro--') plt.plot(t,ut[5,8,:]*np.max(down_data)/np.max(t_grid),'r', label='y = 18',linewidth=3) plt.legend() plt.style.use('seaborn-paper') fig = plt.figure(figsize=(9,6)) plt.subplot(2,2, 1) y = down_data[5,2,:] t = t_arr plt.plot(t,fd_sg(y,t), 'bo--') plt.plot(t,ut[5,2,:],'b', label='y = 12',linewidth=3) y = down_data[5,5,:] t = t_arr plt.plot(t,fd_sg(y,t), 'go--') plt.plot(t,ut[5,5,:],'g', label='y = 6',linewidth=3) y = down_data[5,8,:] t = t_arr plt.plot(t,fd_sg(y,t), 'ro--') plt.plot(t,ut[5,8,:],'r', label='y = 18',linewidth=3) plt.legend() plt.subplot(2,2, 2) y = down_data[5,:,1] x = y_arr plt.plot(x,y, 'bo--') plt.plot(x,sol[5,:,1],'b', label='t = 1',linewidth=3) y = down_data[5,:,2] x = y_arr plt.plot(x,y, 'go--') plt.plot(x,sol[5,:,2],'g', label='t = 5',linewidth=3) y = down_data[5,:,4] x = y_arr plt.plot(x,y, 'ro--') plt.plot(x,sol[5,:,4],'r', label='t = 10',linewidth=3) plt.legend() plt.subplot(2,2, 3) y = down_data[5,:,1] x = y_arr plt.plot(x,fd_spline(y,x), 'bo--') plt.plot(x,uy[5,:,1]*np.max(down_data)/np.max(y_grid),'b', label='x = 1',linewidth=3) y = down_data[5,:,2] x = y_arr plt.plot(x,fd_spline(y,x), 'go--') plt.plot(x,uy[5,:,2]*np.max(down_data)/np.max(y_grid),'g', label='x = 5',linewidth=3) y = down_data[5,:,4] x = y_arr plt.plot(x,fd_spline(y,x), 'ro--') plt.plot(x,uy[5,:,4]*np.max(down_data)/np.max(y_grid),'r', label='x = 10',linewidth=3) plt.legend() plt.subplot(2,2,4) y = down_data[5,:,1] x = y_arr plt.plot(x,fd_spline(fd_spline(y,x)), 'bo--') plt.plot(x,uyy[5,:,1]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'b',label='x = 1',linewidth=3) y = down_data[5,:,2] x = y_arr plt.plot(x,fd_spline(fd_spline(y,x)), 'go--') plt.plot(x,uyy[5,:,2]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'g',label='x = 5',linewidth=3) y = down_data[5,:,4] x = y_arr plt.plot(x,fd_spline(fd_spline(y,x)), 'ro--') plt.plot(x,uyy[5,:,4]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'r',label='x = 10',linewidth=3) plt.ylim(-10,10) plt.legend() #plt.savefig('derivatives.pdf') plt.style.use('seaborn-paper') fig = plt.figure(figsize=(13,9)) plt.subplot(2,2, 1) y = denoised_sol[10,12,:] t = t_arr plt.plot(t,fd_sg(y,t), 'bo--') plt.plot(t,ut[10,12,:]*np.max(down_data)/np.max(t_grid),'b', label='y = 12',linewidth=3) y = denoised_sol[10,6,:] t = t_arr plt.plot(t,fd_sg(y,t), 'go--') plt.plot(t,ut[10,6,:]*np.max(down_data)/np.max(t_grid),'g', label='y = 6',linewidth=3) y = denoised_sol[10,18,:] t = t_arr plt.plot(t,fd_sg(y,t), 'ro--') plt.plot(t,ut[10,18,:]*np.max(down_data)/np.max(t_grid),'r', label='y = 18',linewidth=3) plt.legend() plt.subplot(2,2, 2) y = denoised_sol[10,:,1] x = y_arr plt.plot(x,y, 'bo--') plt.plot(x,sol[10,:,1]*np.max(down_data),'b', label='t = 1',linewidth=3) y = denoised_sol[10,:,2] x = y_arr plt.plot(x,y, 'go--') plt.plot(x,sol[10,:,2]*np.max(down_data),'g', label='t = 5',linewidth=3) y = denoised_sol[10,:,4] x = y_arr plt.plot(x,y, 'ro--') plt.plot(x,sol[10,:,4]*np.max(down_data),'r', label='t = 10',linewidth=3) plt.legend() plt.subplot(2,2, 3) y = denoised_sol[10,:,1] x = y_arr plt.plot(x,fd_spline(y,x), 'bo--') plt.plot(x,uy[10,:,1]*np.max(down_data)/np.max(y_grid),'b', label='x = 1',linewidth=3) y = denoised_sol[10,:,2] x = y_arr plt.plot(x,fd_spline(y,x), 'go--') plt.plot(x,uy[10,:,2]*np.max(down_data)/np.max(y_grid),'g', label='x = 5',linewidth=3) y = denoised_sol[10,:,4] x = y_arr plt.plot(x,fd_spline(y,x), 'ro--') plt.plot(x,uy[10,:,4]*np.max(down_data)/np.max(y_grid),'r', label='x = 10',linewidth=3) plt.legend() plt.subplot(2,2,4) y = down_data[10,:,1] x = y_arr plt.plot(x,fd_spline(fd_spline(y,x)), 'bo--') plt.plot(x,uyy[10,:,1]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'b',label='x = 1',linewidth=3) y = denoised_sol[10,:,2] x = y_arr plt.plot(x,fd_spline(fd_spline(y,x)), 'go--') plt.plot(x,uyy[10,:,2]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'g',label='x = 5',linewidth=3) y = denoised_sol[10,:,4] x = y_arr plt.plot(x,fd_spline(fd_spline(y,x)), 'ro--') plt.plot(x,uyy[10,:,4]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'r',label='x = 10',linewidth=3) plt.ylim(-10,10) plt.legend() #plt.savefig('derivatives.pdf') ###Output _____no_output_____
notebooks/thunderdome.ipynb
###Markdown _Beacon Runner: Thunderdome_ August 2020, [@barnabemonnot](https://twitter.com/barnabemonnot) [Robust Incentives Group](https://github.com/ethereum/rig), Ethereum Foundation Built with specs v0.12---We really care (and want to check) that honest, protocol-following validators, reap the highest (in-protocol) rewards. We'll get a feel for what this means here by pitting different validator behaviours against each other.To introduce a bit of terminology, we are creating an _agent-based model_ here. We do not explicitly code a scenario that agents follow, but program simple update and interaction rules, let them unfold for a while, and then look at the tape to infer conclusions.We'll distinguish between _strategies_ and _behaviours_. A validator can do several things: attest, propose, or do nothing. We'll call _strategies_ instantiations of these particular actions. For instance, a validator may employ the strategy of always attesting correctly, or flipping a coin and half the time attesting correctly, half the time not attesting at all (a pretty dumb strategy if you ask me).We use the word _behaviour_ to describe the general articulation of these strategies: what to play and _when_. We explored in the [main notebook](https://github.com/ethereum/rig/blob/master/eth2economics/code/beaconrunner2050/br2050.ipynb) the behaviour of the [ASAP validator](https://github.com/barnabemonnot/beaconrunner/blob/master/beaconrunner/validators/ASAPValidator.py), who does something as early as possible according to the specs (at the beginning of the slot for a block proposal; a third of a slot, i.e., 4 seconds in _or_ whenever the block for that slot is received for an attestation).In this notebook, we'll look at a different behaviour too: the [Prudent validator](https://github.com/barnabemonnot/beaconrunner/blob/master/beaconrunner/validators/PrudentValidator.py). Although validators are expected to propose their block as early as possible, network delays could prevent attesters from receiving the block before a third of the slot has elapsed. ASAP validators would attest anyways, at the risk of voting on the wrong head, before receiving the block for that slot. Prudent validators hedge their bets a bit:- If Prudent validators receive the block for their attesting slot, they publish their attestation with the head set to that block.- If more than 8 seconds have elapsed into the slot, and they still haven't received a block, they attest for the head they know about.In other words, although prudent validators are willing to wait to see if the block will turn up, there is a limit to how long they will wait: they need to communicate their attestations in a timely manner after all! They only differ from ASAPs by how long they are willing to wait. Rewards under considerationTo see how this behaviour impacts the payoff received by ASAP and prudent validators, let's dive into the rewards and penalties schedule for attesters (we won't look at rewards from block proposing here). Note first the following two things:- Validators receive a bonus for attesting on the correct head. Attesting too early means possibly losing out on this bonus if the head specified in the attestation is incorrect.- Validators receive a bonus for early inclusion of their attestation in a block. This means that they should attest relatively soon, and cannot wait forever to see if a missing block will turn up.You can see [here in the specs](https://github.com/ethereum/eth2.0-specs/blob/dev/specs/phase0/beacon-chain.mdget_attestation_deltas) how rewards and penalties are computed at the end of each epoch. Let's unpack the computations below. Attester rewards in eth2A _base reward_ $\texttt{BR}$ is computed that depends only on the validator's effective balance (maximum 32 ETH) and the current total active balance (the total effective balance of _all_ active validators). Letting $i$ denote our validator,$$ \texttt{BR[i]} = \texttt{balance[i]} \cdot \frac{\texttt{BRF}}{\sqrt{\texttt{total\_balance}} \cdot \texttt{BRPE}} $$$\texttt{BRPE}$ stands for _base rewards per epoch_. A validator can be rewarded for1. Attesting to the correct source, yielding $\texttt{BR[i]}$.2. Attesting to the correct target, yielding $\texttt{BR[i]}$.3. Attesting to the correct head, yielding $\texttt{BR[i]}$.4. Early inclusion, yielding at most $\texttt{BR[i]} \Big( 1 - \frac{1}{\texttt{PRQ}} \Big)$ with $\texttt{PRQ}$ the _proposer reward quotient_.These four items are why $\texttt{BRPE}$ is set to 4 (at least in phase 0). $\texttt{BRF}$, the _base reward factor_, is a scaling constant currently set at $2^6 = 64$.For each of the first three items, we scale the base reward by the fraction of the active stake who correctly attested for the item. If $\rho_s$ is the fraction of the stake who attested correctly for the source, then a validator $i$ with a correct source receives $\rho_s \cdot \texttt{BR[i]}$. However, failure to attest or attesting for an incorrect source, target or head incurs the full $\texttt{BR[i]}$ as penalty.Now, let's dig deeper into item 4, early inclusion. Attestations may be included at least one slot after the slot they are attesting for, called the _committee slot_. If they are included in the block immediately following their committee slot, they receive the full base reward, minus the _proposer reward_, endowed to the block producer (see table below). If they are included in the block two slots after their committee slot, they receive half. Three blocks later, a third, etc. Attestations must be included at the latest one full epoch after their committee slot. This means the smallest inclusion reward is 1/32 of the base reward (assuming `SLOTS_PER_EPOCH` is equal to 32).These are the attester rewards in the best of times. Note however, that the penalties are not symmetric. Whenever a validator fails to attest for one of the first three items, or attests incorrectly, the penalty is equal to the whole base reward. No discount!What about the worst of times? From the perspective of rewards and penalities, this happens when the chain is not finalising epochs anymore (a situation we explored in a [different notebook](https://github.com/ethereum/rig/blob/master/eth2economics/code/beaconrunner2049/beacon_runner_2049.ipynb)). In this case, we want to "leak" the stake of inactive validators, who are preventing finalisation. A [recent modification](https://github.com/ethereum/eth2.0-specs/pull/1830) ensures that validators who perform optimally (i.e., attest correctly to all three items _and_ included in the block immediately following their committee slot) do not suffer any losses. Meanwhile, validators who are not attesting for the correct target (a key ingredient for finalisation) suffer increasingly painful consequences, as the _finality delay_ (the gap between the current epoch and the last finalised epoch) grows.This is all synthesised in the following table. "IL" items refer to "Inactivity Leak": the rewards and penalties during these worst of times. | | Reward | Penalty | Reward (IL) | Penalty (IL) ||-|-|-|-|-|| Correct source? | $\rho_s \cdot \texttt{BR[i]}$ | $\texttt{BR[i]}$ | $\texttt{BR[i]}$ | $\texttt{BR[i]}$ || Correct target? | $\rho_t \cdot \texttt{BR[i]}$ | $\texttt{BR[i]}$ | $\texttt{BR[i]}$ | $\texttt{BR[i]}$ || Correct head? | $\rho_h \cdot \texttt{BR[i]}$ | $\texttt{BR[i]}$ | $\texttt{BR[i]}$ | $\texttt{BR[i]}$ || Correct source _and_ inclusion with delay $d$? | $\Big(1 - \frac{1}{\texttt{PRQ}} \Big) \frac{\texttt{BR[i]}}{d}$ | 0 | $\Big(1 - \frac{1}{\texttt{PRQ}} \Big)\frac{\texttt{BR[i]}}{d}$ | 0 || Finality delay $d$ (incurred by everyone) | 0 | 0 | 0 | $\Big( \texttt{BRPE} - \frac{1}{\texttt{PRQ}} \Big) \cdot \texttt{BR[i]}$ || Correct target (finality delay = $f$)? | 0 | 0 | 0 | $\texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}}$ | Let's explore a few examples. We note at the end of the formula whether the result is positive (the validator makes a profit) or negative (the validator makes a loss).- A validator who gets everything correct, and whose attestations are included 2 slots after their committee slot, while the chain is finalising, reaps:$$ \Big( \rho_s + \rho_t + \rho_h + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) \Big) \texttt{BR[i]} > 0 $$- A validator who gets everything correct, and whose attestations are included 2 slots after their committee slot, while the chain is _not finalising_, reaps:$$ \Big(3 + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) - \texttt{BRPE} + \frac{1}{\texttt{PRQ}} \Big) \texttt{BR[i]} = \Big(-\frac{1}{2} + \frac{1}{2\texttt{PRQ}} \Big) \texttt{BR[i]} < 0 $$- A validator who gets everything correct _except the target_, and whose attestations are included 2 slots after their committee slot, while the chain is _not finalising_ with finality delay $f$, reaps:$$ \Big(1 - 1 + 1 + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) - \texttt{BRPE} + \frac{1}{\texttt{PRQ}} \Big) \texttt{BR[i]} - \texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}} = \Big(-\frac{5}{2} + \frac{1}{2\texttt{PRQ}} \Big) \texttt{BR[i]} - \texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}} < 0 $$ Some hypotheses before simulatingIn a network with perfect (or close to perfect) latency and honest proposers, we don't expect ASAP and prudent validator earnings to differ significantly. But under real-world conditions, the behaviour of prudent validators appears more _robust_ than that of ASAP validators. By robust, we mean that prudent validators perform better under slight variations of the parameters, e.g., the average network latency.When network delays are high or block proposers are lazy (meaning they don't propagate their blocks in time, perhaps because they are being prudent in order to collect more incoming attestations), prudent validators stand to reap the "correct head" reward more often. On the other hand, when network delays are really, really high, perhaps proposing ASAP is a better strategy, as it ensures at least _something_ goes through, even if it's possibly incorrect. _"Two nodes enter! One node leaves!"_Let's pit `PrudentValidator`s against `ASAP`s and observe the result. In this simulation, we let `SLOTS_PER_EPOCH` equal 4 and simulate a small number of validators. Runs are now random: sometimes the network updates, sometimes it doesn't. We'll set it up later so that on average messages propagate one step further on the network every 4 seconds.We first load all the necessary packages. The remainder will look a lot like what we did in the [main notebook](https://github.com/ethereum/rig/blob/master/eth2economics/code/beaconrunner2050/br2050.ipynb), check it out for more background! ###Code import importlib import os import types import nest_asyncio nest_asyncio.apply() from eth2spec.config.config_util import prepare_config from eth2spec.utils.ssz.ssz_impl import hash_tree_root import os, sys sys.path.insert(1, os.path.realpath(os.path.pardir)) import beaconrunner as br prepare_config(".", "fast") br.reload_package(br) ###Output _____no_output_____ ###Markdown We then create our _observers_, to allow us to record interesting metrics at each simulation step. ###Code current_slot = lambda s: s["network"].validators[0].data.slot def average_balance_prudent(state): validators = state["network"].validators validator = validators[0] head = br.specs.get_head(validator.store) current_state = validator.store.block_states[head] current_epoch = br.specs.get_current_epoch(current_state) prudent_indices = [i for i, v in enumerate(validators) if v.validator_behaviour == "prudent"] prudent_balances = [b for i, b in enumerate(current_state.balances) if i in prudent_indices] return br.utils.eth2.gwei_to_eth(sum(prudent_balances) / float(len(prudent_indices))) def average_balance_asap(state): validators = state["network"].validators validator = validators[0] head = br.specs.get_head(validator.store) current_state = validator.store.block_states[head] current_epoch = br.specs.get_current_epoch(current_state) asap_indices = [i for i, v in enumerate(validators) if v.validator_behaviour == "asap"] asap_balances = [b for i, b in enumerate(current_state.balances) if i in asap_indices] return br.utils.eth2.gwei_to_eth(sum(asap_balances) / float(len(asap_indices))) observers = { "current_slot": current_slot, "average_balance_prudent": average_balance_prudent, "average_balance_asap": average_balance_asap, } ###Output _____no_output_____ ###Markdown And define a "main" function -- in this case, `simulate_thunderdome` -- to run the simulation. The function returns a `pandas` dataframe containing the metrics recorded throughout the run. ###Code from random import sample from beaconrunner.validators.ASAPValidator import ASAPValidator from beaconrunner.validators.PrudentValidator import PrudentValidator def simulate_once(network_sets, num_run, num_validators, network_update_rate): # Half our validators are prudent, the others are ASAPs num_prudent = int(num_validators / 2) # We sample the position on the p2p network of prudent validators randomly prudentset = set(sample(range(num_validators), num_prudent)) validators = [] # Initiate validators for i in range(num_validators): if i in prudentset: new_validator = PrudentValidator(i) else: new_validator = ASAPValidator(i) validators.append(new_validator) # Create a genesis state genesis_state = br.simulator.get_genesis_state(validators) # Validators load the state [v.load_state(genesis_state.copy()) for v in validators] br.simulator.skip_genesis_block(validators) network = br.network.Network(validators = validators, sets=network_sets) parameters = br.simulator.SimulationParameters({ "num_epochs": 20, "num_run": num_run, "frequency": 1, "network_update_rate": network_update_rate, }) return br.simulator.simulate(network, parameters, observers) %%capture import pandas as pd num_validators = 12 # Create the network peers set_a = br.network.NetworkSet(validators=list(range(0, int(num_validators * 2 / 3.0)))) set_b = br.network.NetworkSet(validators=list(range(int(num_validators / 2.0), num_validators))) network_sets = list([set_a, set_b]) num_runs = 40 network_update_rate = 0.25 df = pd.concat([simulate_once(network_sets, num_run, num_validators, network_update_rate) for num_run in range(num_runs)]) ###Output _____no_output_____ ###Markdown To do a fair amount of runs (40) simulating a good number of epochs (20), we set a low number of validators (12). Since we are more interested in comparing individual rewards between ASAP and prudent validators rather than macro-properties or even scalability of the chain, this is not a bad thing to do (and it speeds things up quite a bit).Note here that we keep the same network topology across all our runs. However, validator types are placed randomly over the network with each new run, with always 50% of them Prudent and the other 50% ASAPs. Since we have 4 slots per epoch, and 20 epochs, let's read the average balances at slot 81, after the 20th epoch rewards and penalties were computed. ###Code df[df.current_slot == 81][['average_balance_prudent', 'average_balance_asap']].describe() ###Output _____no_output_____ ###Markdown It doesn't seem like a big difference, yet on average prudent validators have higher earnings than ASAPs! Taking into account the [standard error](https://en.wikipedia.org/wiki/Standard_error), the difference between the means appears to be [statistically significant](https://www.investopedia.com/terms/s/statistically_significant.asp), meaning that even though the difference is small, it's not likely to be due to chance alone (while we won't go down this path here, there are statistical tests we could use to test this more precisely if we wished). To see if our intuition is correct, let's chart the ensemble mean over the 40 runs too: ###Code df.groupby(["current_slot"]).mean().reset_index().plot("current_slot", ["average_balance_prudent", "average_balance_asap"]) ###Output _____no_output_____ ###Markdown We see that, as we extend time, prudent validators definitely overtake ASAP validators. Even though 20 epochs is not that long -- at 12 seconds per slot, and 32 slots per epoch, 20 epochs is approximately 2 hours -- over time these differences accumulate. Try it out!We specified the ASAP and prudent validators as two very simple Python classes. For instance, this is how the prudent validator's attestation behaviour is implemented:```pythondef attest(self, known_items) -> Optional[specs.Attestation]: Not the moment to attest if self.data.current_attest_slot != self.data.slot: return None time_in_slot = (self.store.time - self.store.genesis_time) % SECONDS_PER_SLOT Too early in the slot / didn't receive block if not self.data.received_block and time_in_slot < 8: return None Already attested for this slot if self.data.last_slot_attested == self.data.slot: return None honest attest return honest_attest(self, known_items)```You too can specify your own agent behaviours following the simple validator API documented [here](https://barnabemonnot.com/beaconrunner/build/html/validatorlib.html), and have them attest and produce block in a simulated beacon chain environment following the steps outlined above.Validators consume information contained in their `data` attribute. If you find yourself requiring more inputs from the simulation to program your validators, try opening an issue in the [Beacon Runner repo](https://github.com/barnabemonnot/beaconrunner). (Bonus) Better networkWhen latency decreases (faster propagation), are the effects as strong? We set the network update rate to 0.9, meaning that objects propagate on the network almost definitely each step. ###Code %%capture network_update_rate = 0.9 df = pd.concat([simulate_once(network_sets, num_run, num_validators, network_update_rate) for num_run in range(num_runs)]) df.groupby(["current_slot"]).mean().reset_index().plot("current_slot", ["average_balance_prudent", "average_balance_asap"]) ###Output _____no_output_____ ###Markdown We really care (and want to check) that honest, protocol-following validators, reap the highest (in-protocol) rewards. We'll get a feel for what this means here by pitting different validator behaviours against each other.To introduce a bit of terminology, we are creating an _agent-based model_ here. We do not explicitly code a scenario that agents follow, but program simple update and interaction rules, let them unfold for a while, and then look at the tape to infer conclusions.We'll distinguish between _strategies_ and _behaviours_. A validator can do several things: attest, propose, or do nothing. We'll call _strategies_ instantiations of these particular actions. For instance, a validator may employ the strategy of always attesting correctly, or flipping a coin and half the time attesting correctly, half the time not attesting at all (a pretty dumb strategy if you ask me).We use the word _behaviour_ to describe the general articulation of these strategies: what to play and _when_. We explored in the [main notebook](br2050.html) the behaviour of the [ASAP validator](https://github.com/barnabemonnot/beaconrunner/blob/master/notebooks/thunderdome/validators/ASAPValidator.py), who does something as early as possible according to the specs (at the beginning of the slot for a block proposal; a third of a slot, i.e., 4 seconds in _or_ whenever the block for that slot is received for an attestation).In this notebook, we'll look at a different behaviour too: the [Prudent validator](https://github.com/barnabemonnot/beaconrunner/blob/master/notebooks/thunderdome/validators/PrudentValidator.py). Although validators are expected to propose their block as early as possible, network delays could prevent attesters from receiving the block before a third of the slot has elapsed. ASAP validators would attest anyways, at the risk of voting on the wrong head, before receiving the block for that slot. Prudent validators hedge their bets a bit:- If Prudent validators receive the block for their attesting slot, they publish their attestation with the head set to that block.- If more than 8 seconds have elapsed into the slot, and they still haven't received a block, they attest for the head they know about.In other words, although prudent validators are willing to wait to see if the block will turn up, there is a limit to how long they will wait: they need to communicate their attestations in a timely manner after all! They only differ from ASAPs by how long they are willing to wait. Rewards under considerationTo see how this behaviour impacts the payoff received by ASAP and prudent validators, let's dive into the rewards and penalties schedule for attesters (we won't look at rewards from block proposing here). Note first the following two things:- Validators receive a bonus for attesting on the correct head. Attesting too early means possibly losing out on this bonus if the head specified in the attestation is incorrect.- Validators receive a bonus for early inclusion of their attestation in a block. This means that they should attest relatively soon, and cannot wait forever to see if a missing block will turn up.You can see [here in the specs](https://github.com/ethereum/eth2.0-specs/blob/579da6d2dc734b269dbf67aa1004b54bb9449784/specs/phase0/beacon-chain.mdget_attestation_deltas) how rewards and penalties are computed at the end of each epoch. Let's unpack the computations below. Attester rewards in eth2A _base reward_ $\texttt{BR}$ is computed that depends only on the validator's effective balance (maximum 32 ETH) and the current total active balance (the total effective balance of _all_ active validators). Letting $i$ denote our validator,$$ \texttt{BR[i]} = \texttt{balance[i]} \cdot \frac{\texttt{BRF}}{\sqrt{\texttt{total\_balance}} \cdot \texttt{BRPE}} $$$\texttt{BRPE}$ stands for _base rewards per epoch_. A validator can be rewarded for1. Attesting to the correct source, yielding $\texttt{BR[i]}$.2. Attesting to the correct target, yielding $\texttt{BR[i]}$.3. Attesting to the correct head, yielding $\texttt{BR[i]}$.4. Early inclusion, yielding at most $\texttt{BR[i]} \Big( 1 - \frac{1}{\texttt{PRQ}} \Big)$ with $\texttt{PRQ}$ the _proposer reward quotient_.These four items are why $\texttt{BRPE}$ is set to 4 (at least in phase 0). $\texttt{BRF}$, the _base reward factor_, is a scaling constant currently set at $2^6 = 64$.For each of the first three items, we scale the base reward by the fraction of the active stake who correctly attested for the item. If $\rho_s$ is the fraction of the stake who attested correctly for the source, then a validator $i$ with a correct source receives $\rho_s \cdot \texttt{BR[i]}$. However, failure to attest or attesting for an incorrect source, target or head incurs the full $\texttt{BR[i]}$ as penalty.Now, let's dig deeper into item 4, early inclusion. Attestations may be included at least one slot after the slot they are attesting for, called the _committee slot_. If they are included in the block immediately following their committee slot, they receive the full base reward, minus the _proposer reward_, endowed to the block producer (see table below). If they are included in the block two slots after their committee slot, they receive half. Three blocks later, a third, etc. Attestations must be included at the latest one full epoch after their committee slot. This means the smallest inclusion reward is 1/32 of the base reward (assuming `SLOTS_PER_EPOCH` is equal to 32).These are the attester rewards in the best of times. Note however, that the penalties are not symmetric. Whenever a validator fails to attest for one of the first three items, or attests incorrectly, the penalty is equal to the whole base reward. No discount!What about the worst of times? From the perspective of rewards and penalities, this happens when the chain is not finalising epochs anymore (a situation we explored in a [different notebook](br2049.html)). In this case, we want to "leak" the stake of inactive validators, who are preventing finalisation. A [recent modification](https://github.com/ethereum/eth2.0-specs/pull/1830) ensures that validators who perform optimally (i.e., attest correctly to all three items _and_ included in the block immediately following their committee slot) do not suffer any losses. Meanwhile, validators who are not attesting for the correct target (a key ingredient for finalisation) suffer increasingly painful consequences, as the _finality delay_ (the gap between the current epoch and the last finalised epoch) grows.This is all synthesised in the following table. "IL" items refer to "Inactivity Leak": the rewards and penalties during these worst of times. ![](img/rewardsv1.png) Let's explore a few examples. We note at the end of the formula whether the result is positive (the validator makes a profit) or negative (the validator makes a loss).- A validator who gets everything correct, and whose attestations are included 2 slots after their committee slot, while the chain is finalising, reaps:$$ \Big( \rho_s + \rho_t + \rho_h + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) \Big) \texttt{BR[i]} > 0 $$- A validator who gets everything correct, and whose attestations are included 2 slots after their committee slot, while the chain is _not finalising_, reaps:$$ \Big(3 + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) - \texttt{BRPE} + \frac{1}{\texttt{PRQ}} \Big) \texttt{BR[i]} = \Big(-\frac{1}{2} + \frac{1}{2\texttt{PRQ}} \Big) \texttt{BR[i]} < 0 $$- A validator who gets everything correct _except the target_, and whose attestations are included 2 slots after their committee slot, while the chain is _not finalising_ with finality delay $f$, reaps:$$ \Big(1 - 1 + 1 + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) - \texttt{BRPE} + \frac{1}{\texttt{PRQ}} \Big) \texttt{BR[i]} - \texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}} = \Big(-\frac{5}{2} + \frac{1}{2\texttt{PRQ}} \Big) \texttt{BR[i]} - \texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}} < 0 $$ Some hypotheses before simulatingIn a network with perfect (or close to perfect) latency and honest proposers, we don't expect ASAP and prudent validator earnings to differ significantly. But under real-world conditions, the behaviour of prudent validators appears more _robust_ than that of ASAP validators. By robust, we mean that prudent validators perform better under slight variations of the parameters, e.g., the average network latency.When network delays are high or block proposers are lazy (meaning they don't propagate their blocks in time, perhaps because they are being prudent in order to collect more incoming attestations), prudent validators stand to reap the "correct head" reward more often. On the other hand, when network delays are really, really high, perhaps proposing ASAP is a better strategy, as it ensures at least _something_ goes through, even if it's possibly incorrect. _"Two nodes enter! One node leaves!"_Let's pit `PrudentValidator`s against `ASAP`s and observe the result. In this simulation, we let `SLOTS_PER_EPOCH` equal 4 and simulate a small number of validators. Runs are now random: sometimes the network updates, sometimes it doesn't. We'll set it up later so that on average messages propagate one step further on the network every 4 seconds.We first load all the necessary packages. The remainder will look a lot like what we did in the [main notebook](br2050.html), check it out for more background! ###Code import importlib import types from eth2spec.config.config_util import prepare_config from eth2spec.utils.ssz.ssz_impl import hash_tree_root import os, sys # sys.path.insert(1, os.path.realpath(os.path.pardir) + "/notebooks/thunderdome") cwd = os.getcwd() if cwd.endswith('/beaconrunner/notebooks'): os.chdir(cwd + '/thunderdome/') import beaconrunner as br import beaconrunner as br prepare_config(".", "fast.yaml") # # # br.reload_package(br) importlib.reload(br) ###Output _____no_output_____ ###Markdown We then create our _observers_, to allow us to record interesting metrics at each simulation step. ###Code def current_slot(params, step, sL, s, _input): return ("current_slot", s["network"].validators[0].data.slot) def average_balance_prudent(params, step, sL, s, _input): validators = s["network"].validators validator = validators[0] head = br.specs.get_head(validator.store) current_state = validator.store.block_states[head] current_epoch = br.specs.get_current_epoch(current_state) prudent_indices = [i for i, v in enumerate(validators) if v.validator_behaviour == "prudent"] prudent_balances = [b for i, b in enumerate(current_state.balances) if i in prudent_indices] return ("average_balance_prudent", br.utils.eth2.gwei_to_eth(sum(prudent_balances) / float(len(prudent_indices)))) def average_balance_asap(params, step, sL, s, _input): validators = s["network"].validators validator = validators[0] head = br.specs.get_head(validator.store) current_state = validator.store.block_states[head] current_epoch = br.specs.get_current_epoch(current_state) asap_indices = [i for i, v in enumerate(validators) if v.validator_behaviour == "asap"] asap_balances = [b for i, b in enumerate(current_state.balances) if i in asap_indices] return ("average_balance_asap", br.utils.eth2.gwei_to_eth(sum(asap_balances) / float(len(asap_indices)))) observers = { "current_slot": current_slot, "average_balance_prudent": average_balance_prudent, "average_balance_asap": average_balance_asap, } os.getcwd() ###Output _____no_output_____ ###Markdown And define a "main" function -- in this case, `simulate_thunderdome` -- to run the simulation. The function returns a `pandas` dataframe containing the metrics recorded throughout the run. ###Code from random import sample # from br.validators.ASAPValidator import ASAPValidator # from br.validators.PrudentValidator import PrudentValidator def simulate_once(network_sets, num_run, num_validators, network_update_rate): # Half our validators are prudent, the others are ASAPs num_prudent = int(num_validators / 2) # We sample the position on the p2p network of prudent validators randomly prudentset = set(sample(range(num_validators), num_prudent)) validators = [] # Initiate validators for i in range(num_validators): if i in prudentset: new_validator = br.validators.PrudentValidator(i) else: new_validator = br.validators.ASAPValidator(i) validators.append(new_validator) # Create a genesis state genesis_state = br.simulator.get_genesis_state(validators) # Validators load the state [v.load_state(genesis_state.copy()) for v in validators] br.simulator.skip_genesis_block(validators) network = br.network.Network(validators = validators, sets=network_sets) parameters = br.simulator.SimulationParameters({ "num_epochs": 20, "num_run": num_run, "frequency": 1, "network_update_rate": network_update_rate, }) return br.simulator.simulate(network, parameters, observers) %%capture import pandas as pd num_validators = 12 # Create the network peers set_a = br.network.NetworkSet(validators=list(range(0, int(num_validators * 2 / 3.0)))) set_b = br.network.NetworkSet(validators=list(range(int(num_validators / 2.0), num_validators))) network_sets = list([set_a, set_b]) num_runs = 40 network_update_rate = 0.25 df = pd.concat([simulate_once(network_sets, num_run, num_validators, network_update_rate) for num_run in range(num_runs)]) ###Output _____no_output_____ ###Markdown To do a fair amount of runs (40) simulating a good number of epochs (20), we set a low number of validators (12). Since we are more interested in comparing individual rewards between ASAP and prudent validators rather than macro-properties or even scalability of the chain, this is not a bad thing to do (and it speeds things up quite a bit).Note here that we keep the same network topology across all our runs. However, validator types are placed randomly over the network with each new run, with always 50% of them Prudent and the other 50% ASAPs. Since we have 4 slots per epoch, and 20 epochs, let's read the average balances at slot 81, after the 20th epoch rewards and penalties were computed. ###Code df[df.current_slot == 81][['average_balance_prudent', 'average_balance_asap']].describe() ###Output _____no_output_____ ###Markdown It doesn't seem like a big difference, yet on average prudent validators have higher earnings than ASAPs! Taking into account the [standard error](https://en.wikipedia.org/wiki/Standard_error), the difference between the means appears to be [statistically significant](https://www.investopedia.com/terms/s/statistically_significant.asp), meaning that even though the difference is small, it's not likely to be due to chance alone (while we won't go down this path here, there are statistical tests we could use to test this more precisely if we wished). To see if our intuition is correct, let's chart the ensemble mean over the 40 runs too: ###Code df.groupby(["current_slot"]).mean().reset_index().plot("current_slot", ["average_balance_prudent", "average_balance_asap"]) ###Output _____no_output_____ ###Markdown We see that, as we extend time, prudent validators definitely overtake ASAP validators. Even though 20 epochs is not that long -- at 12 seconds per slot, and 32 slots per epoch, 20 epochs is approximately 2 hours -- over time these differences accumulate. Try it out!We specified the ASAP and prudent validators as two very simple Python classes. For instance, this is how the prudent validator's attestation behaviour is implemented:```pythondef attest(self, known_items) -> Optional[specs.Attestation]: Not the moment to attest if self.data.current_attest_slot != self.data.slot: return None time_in_slot = (self.store.time - self.store.genesis_time) % SECONDS_PER_SLOT Too early in the slot / didn't receive block if not self.data.received_block and time_in_slot < 8: return None Already attested for this slot if self.data.last_slot_attested == self.data.slot: return None honest attest return honest_attest(self, known_items)```You too can specify your own agent behaviours following the simple validator API documented [here](https://barnabemonnot.com/beaconrunner/build/html/validatorlib.html), and have them attest and produce block in a simulated beacon chain environment following the steps outlined above.Validators consume information contained in their `data` attribute. If you find yourself requiring more inputs from the simulation to program your validators, try opening an issue in the [Beacon Runner repo](https://github.com/barnabemonnot/beaconrunner). (Bonus) Better networkWhen latency decreases (faster propagation), are the effects as strong? We set the network update rate to 0.9, meaning that objects propagate on the network almost definitely each step. ###Code %%capture network_update_rate = 0.9 df = pd.concat([simulate_once(network_sets, num_run, num_validators, network_update_rate) for num_run in range(num_runs)]) df.groupby(["current_slot"]).mean().reset_index().plot("current_slot", ["average_balance_prudent", "average_balance_asap"]) ###Output _____no_output_____ ###Markdown It is not as advantageous to be Prudent now, their payoffs are broadly similar to ASAPs. But it doesn't hurt either. ###Code Beacon Runner: Thunderdome Note: This post describes a result that was true in the v1 specs, but is fixed in the first major upgrade, v1.1, a.k.a. Altair. The table of rewards presented in Section 1. is also outdated. The value of the case study remains. // References + footnotes // Authors let authorData = ["barnabe"]; Many thanks to Sacha for his edits and suggestions; Danny, Protolambda and Terence for comments. ###Output _____no_output_____ ###Markdown We really care (and want to check) that honest, protocol-following validators, reap the highest (in-protocol) rewards. We'll get a feel for what this means here by pitting different validator behaviours against each other.To introduce a bit of terminology, we are creating an _agent-based model_ here. We do not explicitly code a scenario that agents follow, but program simple update and interaction rules, let them unfold for a while, and then look at the tape to infer conclusions.We'll distinguish between _strategies_ and _behaviours_. A validator can do several things: attest, propose, or do nothing. We'll call _strategies_ instantiations of these particular actions. For instance, a validator may employ the strategy of always attesting correctly, or flipping a coin and half the time attesting correctly, half the time not attesting at all (a pretty dumb strategy if you ask me).We use the word _behaviour_ to describe the general articulation of these strategies: what to play and _when_. We explored in the [main notebook](br2050.html) the behaviour of the [ASAP validator](https://github.com/barnabemonnot/beaconrunner/blob/master/notebooks/thunderdome/validators/ASAPValidator.py), who does something as early as possible according to the specs (at the beginning of the slot for a block proposal; a third of a slot, i.e., 4 seconds in _or_ whenever the block for that slot is received for an attestation).In this notebook, we'll look at a different behaviour too: the [Prudent validator](https://github.com/barnabemonnot/beaconrunner/blob/master/notebooks/thunderdome/validators/PrudentValidator.py). Although validators are expected to propose their block as early as possible, network delays could prevent attesters from receiving the block before a third of the slot has elapsed. ASAP validators would attest anyways, at the risk of voting on the wrong head, before receiving the block for that slot. Prudent validators hedge their bets a bit:- If Prudent validators receive the block for their attesting slot, they publish their attestation with the head set to that block.- If more than 8 seconds have elapsed into the slot, and they still haven't received a block, they attest for the head they know about.In other words, although prudent validators are willing to wait to see if the block will turn up, there is a limit to how long they will wait: they need to communicate their attestations in a timely manner after all! They only differ from ASAPs by how long they are willing to wait. Rewards under considerationTo see how this behaviour impacts the payoff received by ASAP and prudent validators, let's dive into the rewards and penalties schedule for attesters (we won't look at rewards from block proposing here). Note first the following two things:- Validators receive a bonus for attesting on the correct head. Attesting too early means possibly losing out on this bonus if the head specified in the attestation is incorrect.- Validators receive a bonus for early inclusion of their attestation in a block. This means that they should attest relatively soon, and cannot wait forever to see if a missing block will turn up.You can see [here in the specs](https://github.com/ethereum/eth2.0-specs/blob/579da6d2dc734b269dbf67aa1004b54bb9449784/specs/phase0/beacon-chain.mdget_attestation_deltas) how rewards and penalties are computed at the end of each epoch. Let's unpack the computations below. Attester rewards in eth2A _base reward_ $\texttt{BR}$ is computed that depends only on the validator's effective balance (maximum 32 ETH) and the current total active balance (the total effective balance of _all_ active validators). Letting $i$ denote our validator,$$ \texttt{BR[i]} = \texttt{balance[i]} \cdot \frac{\texttt{BRF}}{\sqrt{\texttt{total\_balance}} \cdot \texttt{BRPE}} $$$\texttt{BRPE}$ stands for _base rewards per epoch_. A validator can be rewarded for1. Attesting to the correct source, yielding $\texttt{BR[i]}$.2. Attesting to the correct target, yielding $\texttt{BR[i]}$.3. Attesting to the correct head, yielding $\texttt{BR[i]}$.4. Early inclusion, yielding at most $\texttt{BR[i]} \Big( 1 - \frac{1}{\texttt{PRQ}} \Big)$ with $\texttt{PRQ}$ the _proposer reward quotient_.These four items are why $\texttt{BRPE}$ is set to 4 (at least in phase 0). $\texttt{BRF}$, the _base reward factor_, is a scaling constant currently set at $2^6 = 64$.For each of the first three items, we scale the base reward by the fraction of the active stake who correctly attested for the item. If $\rho_s$ is the fraction of the stake who attested correctly for the source, then a validator $i$ with a correct source receives $\rho_s \cdot \texttt{BR[i]}$. However, failure to attest or attesting for an incorrect source, target or head incurs the full $\texttt{BR[i]}$ as penalty.Now, let's dig deeper into item 4, early inclusion. Attestations may be included at least one slot after the slot they are attesting for, called the _committee slot_. If they are included in the block immediately following their committee slot, they receive the full base reward, minus the _proposer reward_, endowed to the block producer (see table below). If they are included in the block two slots after their committee slot, they receive half. Three blocks later, a third, etc. Attestations must be included at the latest one full epoch after their committee slot. This means the smallest inclusion reward is 1/32 of the base reward (assuming `SLOTS_PER_EPOCH` is equal to 32).These are the attester rewards in the best of times. Note however, that the penalties are not symmetric. Whenever a validator fails to attest for one of the first three items, or attests incorrectly, the penalty is equal to the whole base reward. No discount!What about the worst of times? From the perspective of rewards and penalities, this happens when the chain is not finalising epochs anymore (a situation we explored in a [different notebook](br2049.html)). In this case, we want to "leak" the stake of inactive validators, who are preventing finalisation. A [recent modification](https://github.com/ethereum/eth2.0-specs/pull/1830) ensures that validators who perform optimally (i.e., attest correctly to all three items _and_ included in the block immediately following their committee slot) do not suffer any losses. Meanwhile, validators who are not attesting for the correct target (a key ingredient for finalisation) suffer increasingly painful consequences, as the _finality delay_ (the gap between the current epoch and the last finalised epoch) grows.This is all synthesised in the following table. "IL" items refer to "Inactivity Leak": the rewards and penalties during these worst of times. ![](img/rewardsv1.png) Let's explore a few examples. We note at the end of the formula whether the result is positive (the validator makes a profit) or negative (the validator makes a loss).- A validator who gets everything correct, and whose attestations are included 2 slots after their committee slot, while the chain is finalising, reaps:$$ \Big( \rho_s + \rho_t + \rho_h + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) \Big) \texttt{BR[i]} > 0 $$- A validator who gets everything correct, and whose attestations are included 2 slots after their committee slot, while the chain is _not finalising_, reaps:$$ \Big(3 + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) - \texttt{BRPE} + \frac{1}{\texttt{PRQ}} \Big) \texttt{BR[i]} = \Big(-\frac{1}{2} + \frac{1}{2\texttt{PRQ}} \Big) \texttt{BR[i]} < 0 $$- A validator who gets everything correct _except the target_, and whose attestations are included 2 slots after their committee slot, while the chain is _not finalising_ with finality delay $f$, reaps:$$ \Big(1 - 1 + 1 + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) - \texttt{BRPE} + \frac{1}{\texttt{PRQ}} \Big) \texttt{BR[i]} - \texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}} = \Big(-\frac{5}{2} + \frac{1}{2\texttt{PRQ}} \Big) \texttt{BR[i]} - \texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}} < 0 $$ Some hypotheses before simulatingIn a network with perfect (or close to perfect) latency and honest proposers, we don't expect ASAP and prudent validator earnings to differ significantly. But under real-world conditions, the behaviour of prudent validators appears more _robust_ than that of ASAP validators. By robust, we mean that prudent validators perform better under slight variations of the parameters, e.g., the average network latency.When network delays are high or block proposers are lazy (meaning they don't propagate their blocks in time, perhaps because they are being prudent in order to collect more incoming attestations), prudent validators stand to reap the "correct head" reward more often. On the other hand, when network delays are really, really high, perhaps proposing ASAP is a better strategy, as it ensures at least _something_ goes through, even if it's possibly incorrect. _"Two nodes enter! One node leaves!"_Let's pit `PrudentValidator`s against `ASAP`s and observe the result. In this simulation, we let `SLOTS_PER_EPOCH` equal 4 and simulate a small number of validators. Runs are now random: sometimes the network updates, sometimes it doesn't. We'll set it up later so that on average messages propagate one step further on the network every 4 seconds.We first load all the necessary packages. The remainder will look a lot like what we did in the [main notebook](br2050.html), check it out for more background! ###Code import importlib import types from eth2spec.config.config_util import prepare_config from eth2spec.utils.ssz.ssz_impl import hash_tree_root import os, sys sys.path.insert(1, os.path.realpath(os.path.pardir) + "/notebooks/thunderdome") import beaconrunner as br prepare_config(".", "fast.yaml") br.reload_package(br) ###Output _____no_output_____ ###Markdown We then create our _observers_, to allow us to record interesting metrics at each simulation step. ###Code def current_slot(params, step, sL, s, _input): return ("current_slot", s["network"].validators[0].data.slot) def average_balance_prudent(params, step, sL, s, _input): validators = s["network"].validators validator = validators[0] head = br.specs.get_head(validator.store) current_state = validator.store.block_states[head] current_epoch = br.specs.get_current_epoch(current_state) prudent_indices = [i for i, v in enumerate(validators) if v.validator_behaviour == "prudent"] prudent_balances = [b for i, b in enumerate(current_state.balances) if i in prudent_indices] return ("average_balance_prudent", br.utils.eth2.gwei_to_eth(sum(prudent_balances) / float(len(prudent_indices)))) def average_balance_asap(params, step, sL, s, _input): validators = s["network"].validators validator = validators[0] head = br.specs.get_head(validator.store) current_state = validator.store.block_states[head] current_epoch = br.specs.get_current_epoch(current_state) asap_indices = [i for i, v in enumerate(validators) if v.validator_behaviour == "asap"] asap_balances = [b for i, b in enumerate(current_state.balances) if i in asap_indices] return ("average_balance_asap", br.utils.eth2.gwei_to_eth(sum(asap_balances) / float(len(asap_indices)))) observers = { "current_slot": current_slot, "average_balance_prudent": average_balance_prudent, "average_balance_asap": average_balance_asap, } ###Output _____no_output_____ ###Markdown And define a "main" function -- in this case, `simulate_thunderdome` -- to run the simulation. The function returns a `pandas` dataframe containing the metrics recorded throughout the run. ###Code from random import sample from beaconrunner.validators.ASAPValidator import ASAPValidator from beaconrunner.validators.PrudentValidator import PrudentValidator def simulate_once(network_sets, num_run, num_validators, network_update_rate): # Half our validators are prudent, the others are ASAPs num_prudent = int(num_validators / 2) # We sample the position on the p2p network of prudent validators randomly prudentset = set(sample(range(num_validators), num_prudent)) validators = [] # Initiate validators for i in range(num_validators): if i in prudentset: new_validator = PrudentValidator(i) else: new_validator = ASAPValidator(i) validators.append(new_validator) # Create a genesis state genesis_state = br.simulator.get_genesis_state(validators) # Validators load the state [v.load_state(genesis_state.copy()) for v in validators] br.simulator.skip_genesis_block(validators) network = br.network.Network(validators = validators, sets=network_sets) parameters = br.simulator.SimulationParameters({ "num_epochs": 20, "num_run": num_run, "frequency": 1, "network_update_rate": network_update_rate, }) return br.simulator.simulate(network, parameters, observers) %%capture import pandas as pd num_validators = 12 # Create the network peers set_a = br.network.NetworkSet(validators=list(range(0, int(num_validators * 2 / 3.0)))) set_b = br.network.NetworkSet(validators=list(range(int(num_validators / 2.0), num_validators))) network_sets = list([set_a, set_b]) num_runs = 40 network_update_rate = 0.25 df = pd.concat([simulate_once(network_sets, num_run, num_validators, network_update_rate) for num_run in range(num_runs)]) ###Output _____no_output_____ ###Markdown To do a fair amount of runs (40) simulating a good number of epochs (20), we set a low number of validators (12). Since we are more interested in comparing individual rewards between ASAP and prudent validators rather than macro-properties or even scalability of the chain, this is not a bad thing to do (and it speeds things up quite a bit).Note here that we keep the same network topology across all our runs. However, validator types are placed randomly over the network with each new run, with always 50% of them Prudent and the other 50% ASAPs. Since we have 4 slots per epoch, and 20 epochs, let's read the average balances at slot 81, after the 20th epoch rewards and penalties were computed. ###Code df[df.current_slot == 81][['average_balance_prudent', 'average_balance_asap']].describe() ###Output _____no_output_____ ###Markdown It doesn't seem like a big difference, yet on average prudent validators have higher earnings than ASAPs! Taking into account the [standard error](https://en.wikipedia.org/wiki/Standard_error), the difference between the means appears to be [statistically significant](https://www.investopedia.com/terms/s/statistically_significant.asp), meaning that even though the difference is small, it's not likely to be due to chance alone (while we won't go down this path here, there are statistical tests we could use to test this more precisely if we wished). To see if our intuition is correct, let's chart the ensemble mean over the 40 runs too: ###Code df.groupby(["current_slot"]).mean().reset_index().plot("current_slot", ["average_balance_prudent", "average_balance_asap"]) ###Output _____no_output_____ ###Markdown We see that, as we extend time, prudent validators definitely overtake ASAP validators. Even though 20 epochs is not that long -- at 12 seconds per slot, and 32 slots per epoch, 20 epochs is approximately 2 hours -- over time these differences accumulate. Try it out!We specified the ASAP and prudent validators as two very simple Python classes. For instance, this is how the prudent validator's attestation behaviour is implemented:```pythondef attest(self, known_items) -> Optional[specs.Attestation]: Not the moment to attest if self.data.current_attest_slot != self.data.slot: return None time_in_slot = (self.store.time - self.store.genesis_time) % SECONDS_PER_SLOT Too early in the slot / didn't receive block if not self.data.received_block and time_in_slot < 8: return None Already attested for this slot if self.data.last_slot_attested == self.data.slot: return None honest attest return honest_attest(self, known_items)```You too can specify your own agent behaviours following the simple validator API documented [here](https://barnabemonnot.com/beaconrunner/build/html/validatorlib.html), and have them attest and produce block in a simulated beacon chain environment following the steps outlined above.Validators consume information contained in their `data` attribute. If you find yourself requiring more inputs from the simulation to program your validators, try opening an issue in the [Beacon Runner repo](https://github.com/barnabemonnot/beaconrunner). (Bonus) Better networkWhen latency decreases (faster propagation), are the effects as strong? We set the network update rate to 0.9, meaning that objects propagate on the network almost definitely each step. ###Code %%capture network_update_rate = 0.9 df = pd.concat([simulate_once(network_sets, num_run, num_validators, network_update_rate) for num_run in range(num_runs)]) df.groupby(["current_slot"]).mean().reset_index().plot("current_slot", ["average_balance_prudent", "average_balance_asap"]) ###Output _____no_output_____ ###Markdown It is not as advantageous to be Prudent now, their payoffs are broadly similar to ASAPs. But it doesn't hurt either. ###Code Beacon Runner: Thunderdome Note: This post describes a result that was true in the v1 specs, but is fixed in the first major upgrade, v1.1, a.k.a. Altair. The table of rewards presented in Section 1. is also outdated. The value of the case study remains. // References + footnotes // Authors let authorData = ["barnabe"]; Many thanks to Sacha for his edits and suggestions; Danny, Protolambda and Terence for comments. ###Output _____no_output_____ ###Markdown We really care (and want to check) that honest, protocol-following validators, reap the highest (in-protocol) rewards. We'll get a feel for what this means here by pitting different validator behaviours against each other.To introduce a bit of terminology, we are creating an _agent-based model_ here. We do not explicitly code a scenario that agents follow, but program simple update and interaction rules, let them unfold for a while, and then look at the tape to infer conclusions.We'll distinguish between _strategies_ and _behaviours_. A validator can do several things: attest, propose, or do nothing. We'll call _strategies_ instantiations of these particular actions. For instance, a validator may employ the strategy of always attesting correctly, or flipping a coin and half the time attesting correctly, half the time not attesting at all (a pretty dumb strategy if you ask me).We use the word _behaviour_ to describe the general articulation of these strategies: what to play and _when_. We explored in the [main notebook](br2050.html) the behaviour of the [ASAP validator](https://github.com/barnabemonnot/beaconrunner/blob/master/notebooks/thunderdome/validators/ASAPValidator.py), who does something as early as possible according to the specs (at the beginning of the slot for a block proposal; a third of a slot, i.e., 4 seconds in _or_ whenever the block for that slot is received for an attestation).In this notebook, we'll look at a different behaviour too: the [Prudent validator](https://github.com/barnabemonnot/beaconrunner/blob/master/notebooks/thunderdome/validators/PrudentValidator.py). Although validators are expected to propose their block as early as possible, network delays could prevent attesters from receiving the block before a third of the slot has elapsed. ASAP validators would attest anyways, at the risk of voting on the wrong head, before receiving the block for that slot. Prudent validators hedge their bets a bit:- If Prudent validators receive the block for their attesting slot, they publish their attestation with the head set to that block.- If more than 8 seconds have elapsed into the slot, and they still haven't received a block, they attest for the head they know about.In other words, although prudent validators are willing to wait to see if the block will turn up, there is a limit to how long they will wait: they need to communicate their attestations in a timely manner after all! They only differ from ASAPs by how long they are willing to wait. Rewards under considerationTo see how this behaviour impacts the payoff received by ASAP and prudent validators, let's dive into the rewards and penalties schedule for attesters (we won't look at rewards from block proposing here). Note first the following two things:- Validators receive a bonus for attesting on the correct head. Attesting too early means possibly losing out on this bonus if the head specified in the attestation is incorrect.- Validators receive a bonus for early inclusion of their attestation in a block. This means that they should attest relatively soon, and cannot wait forever to see if a missing block will turn up.You can see [here in the specs](https://github.com/ethereum/eth2.0-specs/blob/579da6d2dc734b269dbf67aa1004b54bb9449784/specs/phase0/beacon-chain.mdget_attestation_deltas) how rewards and penalties are computed at the end of each epoch. Let's unpack the computations below. Attester rewards in eth2A _base reward_ $\texttt{BR}$ is computed that depends only on the validator's effective balance (maximum 32 ETH) and the current total active balance (the total effective balance of _all_ active validators). Letting $i$ denote our validator,$$ \texttt{BR[i]} = \texttt{balance[i]} \cdot \frac{\texttt{BRF}}{\sqrt{\texttt{total\_balance}} \cdot \texttt{BRPE}} $$$\texttt{BRPE}$ stands for _base rewards per epoch_. A validator can be rewarded for1. Attesting to the correct source, yielding $\texttt{BR[i]}$.2. Attesting to the correct target, yielding $\texttt{BR[i]}$.3. Attesting to the correct head, yielding $\texttt{BR[i]}$.4. Early inclusion, yielding at most $\texttt{BR[i]} \Big( 1 - \frac{1}{\texttt{PRQ}} \Big)$ with $\texttt{PRQ}$ the _proposer reward quotient_.These four items are why $\texttt{BRPE}$ is set to 4 (at least in phase 0). $\texttt{BRF}$, the _base reward factor_, is a scaling constant currently set at $2^6 = 64$.For each of the first three items, we scale the base reward by the fraction of the active stake who correctly attested for the item. If $\rho_s$ is the fraction of the stake who attested correctly for the source, then a validator $i$ with a correct source receives $\rho_s \cdot \texttt{BR[i]}$. However, failure to attest or attesting for an incorrect source, target or head incurs the full $\texttt{BR[i]}$ as penalty.Now, let's dig deeper into item 4, early inclusion. Attestations may be included at least one slot after the slot they are attesting for, called the _committee slot_. If they are included in the block immediately following their committee slot, they receive the full base reward, minus the _proposer reward_, endowed to the block producer (see table below). If they are included in the block two slots after their committee slot, they receive half. Three blocks later, a third, etc. Attestations must be included at the latest one full epoch after their committee slot. This means the smallest inclusion reward is 1/32 of the base reward (assuming `SLOTS_PER_EPOCH` is equal to 32).These are the attester rewards in the best of times. Note however, that the penalties are not symmetric. Whenever a validator fails to attest for one of the first three items, or attests incorrectly, the penalty is equal to the whole base reward. No discount!What about the worst of times? From the perspective of rewards and penalities, this happens when the chain is not finalising epochs anymore (a situation we explored in a [different notebook](br2049.html)). In this case, we want to "leak" the stake of inactive validators, who are preventing finalisation. A [recent modification](https://github.com/ethereum/eth2.0-specs/pull/1830) ensures that validators who perform optimally (i.e., attest correctly to all three items _and_ included in the block immediately following their committee slot) do not suffer any losses. Meanwhile, validators who are not attesting for the correct target (a key ingredient for finalisation) suffer increasingly painful consequences, as the _finality delay_ (the gap between the current epoch and the last finalised epoch) grows.This is all synthesised in the following table. "IL" items refer to "Inactivity Leak": the rewards and penalties during these worst of times. ![](img/rewardsv1.png) Let's explore a few examples. We note at the end of the formula whether the result is positive (the validator makes a profit) or negative (the validator makes a loss).- A validator who gets everything correct, and whose attestations are included 2 slots after their committee slot, while the chain is finalising, reaps:$$ \Big( \rho_s + \rho_t + \rho_h + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) \Big) \texttt{BR[i]} > 0 $$- A validator who gets everything correct, and whose attestations are included 2 slots after their committee slot, while the chain is _not finalising_, reaps:$$ \Big(3 + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) - \texttt{BRPE} + \frac{1}{\texttt{PRQ}} \Big) \texttt{BR[i]} = \Big(-\frac{1}{2} + \frac{1}{2\texttt{PRQ}} \Big) \texttt{BR[i]} < 0 $$- A validator who gets everything correct _except the target_, and whose attestations are included 2 slots after their committee slot, while the chain is _not finalising_ with finality delay $f$, reaps:$$ \Big(1 - 1 + 1 + \frac{1}{2} (1 - \frac{1}{\texttt{PRQ}}) - \texttt{BRPE} + \frac{1}{\texttt{PRQ}} \Big) \texttt{BR[i]} - \texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}} = \Big(-\frac{5}{2} + \frac{1}{2\texttt{PRQ}} \Big) \texttt{BR[i]} - \texttt{balance[i]} \cdot \frac{f}{\texttt{IPQ}} < 0 $$ Some hypotheses before simulatingIn a network with perfect (or close to perfect) latency and honest proposers, we don't expect ASAP and prudent validator earnings to differ significantly. But under real-world conditions, the behaviour of prudent validators appears more _robust_ than that of ASAP validators. By robust, we mean that prudent validators perform better under slight variations of the parameters, e.g., the average network latency.When network delays are high or block proposers are lazy (meaning they don't propagate their blocks in time, perhaps because they are being prudent in order to collect more incoming attestations), prudent validators stand to reap the "correct head" reward more often. On the other hand, when network delays are really, really high, perhaps proposing ASAP is a better strategy, as it ensures at least _something_ goes through, even if it's possibly incorrect. _"Two nodes enter! One node leaves!"_Let's pit `PrudentValidator`s against `ASAP`s and observe the result. In this simulation, we let `SLOTS_PER_EPOCH` equal 4 and simulate a small number of validators. Runs are now random: sometimes the network updates, sometimes it doesn't. We'll set it up later so that on average messages propagate one step further on the network every 4 seconds.We first load all the necessary packages. The remainder will look a lot like what we did in the [main notebook](br2050.html), check it out for more background! ###Code import importlib import types from eth2spec.config.config_util import prepare_config from eth2spec.utils.ssz.ssz_impl import hash_tree_root import os, sys sys.path.insert(1, os.path.realpath(os.path.pardir) + "/notebooks/thunderdome") import beaconrunner as br prepare_config(".", "fast.yaml") br.reload_package(br) ###Output _____no_output_____ ###Markdown We then create our _observers_, to allow us to record interesting metrics at each simulation step. ###Code def current_slot(params, step, sL, s, _input): return ("current_slot", s["network"].validators[0].data.slot) def average_balance_prudent(params, step, sL, s, _input): validators = s["network"].validators validator = validators[0] head = br.specs.get_head(validator.store) current_state = validator.store.block_states[head] current_epoch = br.specs.get_current_epoch(current_state) prudent_indices = [i for i, v in enumerate(validators) if v.validator_behaviour == "prudent"] prudent_balances = [b for i, b in enumerate(current_state.balances) if i in prudent_indices] return ("average_balance_prudent", br.utils.eth2.gwei_to_eth(sum(prudent_balances) / float(len(prudent_indices)))) def average_balance_asap(params, step, sL, s, _input): validators = s["network"].validators validator = validators[0] head = br.specs.get_head(validator.store) current_state = validator.store.block_states[head] current_epoch = br.specs.get_current_epoch(current_state) asap_indices = [i for i, v in enumerate(validators) if v.validator_behaviour == "asap"] asap_balances = [b for i, b in enumerate(current_state.balances) if i in asap_indices] return ("average_balance_asap", br.utils.eth2.gwei_to_eth(sum(asap_balances) / float(len(asap_indices)))) observers = { "current_slot": current_slot, "average_balance_prudent": average_balance_prudent, "average_balance_asap": average_balance_asap, } ###Output _____no_output_____ ###Markdown And define a "main" function -- in this case, `simulate_thunderdome` -- to run the simulation. The function returns a `pandas` dataframe containing the metrics recorded throughout the run. ###Code from random import sample from beaconrunner.validators.ASAPValidator import ASAPValidator from beaconrunner.validators.PrudentValidator import PrudentValidator def simulate_once(network_sets, num_run, num_validators, network_update_rate): # Half our validators are prudent, the others are ASAPs num_prudent = int(num_validators / 2) # We sample the position on the p2p network of prudent validators randomly prudentset = set(sample(range(num_validators), num_prudent)) validators = [] # Initiate validators for i in range(num_validators): if i in prudentset: new_validator = PrudentValidator(i) else: new_validator = ASAPValidator(i) validators.append(new_validator) # Create a genesis state genesis_state = br.simulator.get_genesis_state(validators) # Validators load the state [v.load_state(genesis_state.copy()) for v in validators] br.simulator.skip_genesis_block(validators) network = br.network.Network(validators = validators, sets=network_sets) parameters = br.simulator.SimulationParameters({ "num_epochs": 20, "num_run": num_run, "frequency": 1, "network_update_rate": network_update_rate, }) return br.simulator.simulate(network, parameters, observers) %%capture import pandas as pd num_validators = 12 # Create the network peers set_a = br.network.NetworkSet(validators=list(range(0, int(num_validators * 2 / 3.0)))) set_b = br.network.NetworkSet(validators=list(range(int(num_validators / 2.0), num_validators))) network_sets = list([set_a, set_b]) num_runs = 40 network_update_rate = 0.25 df = pd.concat([simulate_once(network_sets, num_run, num_validators, network_update_rate) for num_run in range(num_runs)]) ###Output _____no_output_____ ###Markdown To do a fair amount of runs (40) simulating a good number of epochs (20), we set a low number of validators (12). Since we are more interested in comparing individual rewards between ASAP and prudent validators rather than macro-properties or even scalability of the chain, this is not a bad thing to do (and it speeds things up quite a bit).Note here that we keep the same network topology across all our runs. However, validator types are placed randomly over the network with each new run, with always 50% of them Prudent and the other 50% ASAPs. Since we have 4 slots per epoch, and 20 epochs, let's read the average balances at slot 81, after the 20th epoch rewards and penalties were computed. ###Code df[df.current_slot == 81][['average_balance_prudent', 'average_balance_asap']].describe() ###Output _____no_output_____ ###Markdown It doesn't seem like a big difference, yet on average prudent validators have higher earnings than ASAPs! Taking into account the [standard error](https://en.wikipedia.org/wiki/Standard_error), the difference between the means appears to be [statistically significant](https://www.investopedia.com/terms/s/statistically_significant.asp), meaning that even though the difference is small, it's not likely to be due to chance alone (while we won't go down this path here, there are statistical tests we could use to test this more precisely if we wished). To see if our intuition is correct, let's chart the ensemble mean over the 40 runs too: ###Code df.groupby(["current_slot"]).mean().reset_index().plot("current_slot", ["average_balance_prudent", "average_balance_asap"]) ###Output _____no_output_____ ###Markdown We see that, as we extend time, prudent validators definitely overtake ASAP validators. Even though 20 epochs is not that long -- at 12 seconds per slot, and 32 slots per epoch, 20 epochs is approximately 2 hours -- over time these differences accumulate. Try it out!We specified the ASAP and prudent validators as two very simple Python classes. For instance, this is how the prudent validator's attestation behaviour is implemented:```pythondef attest(self, known_items) -> Optional[specs.Attestation]: Not the moment to attest if self.data.current_attest_slot != self.data.slot: return None time_in_slot = (self.store.time - self.store.genesis_time) % SECONDS_PER_SLOT Too early in the slot / didn't receive block if not self.data.received_block and time_in_slot < 8: return None Already attested for this slot if self.data.last_slot_attested == self.data.slot: return None honest attest return honest_attest(self, known_items)```You too can specify your own agent behaviours following the simple validator API documented [here](https://barnabemonnot.com/beaconrunner/build/html/validatorlib.html), and have them attest and produce block in a simulated beacon chain environment following the steps outlined above.Validators consume information contained in their `data` attribute. If you find yourself requiring more inputs from the simulation to program your validators, try opening an issue in the [Beacon Runner repo](https://github.com/barnabemonnot/beaconrunner). (Bonus) Better networkWhen latency decreases (faster propagation), are the effects as strong? We set the network update rate to 0.9, meaning that objects propagate on the network almost definitely each step. ###Code %%capture network_update_rate = 0.9 df = pd.concat([simulate_once(network_sets, num_run, num_validators, network_update_rate) for num_run in range(num_runs)]) df.groupby(["current_slot"]).mean().reset_index().plot("current_slot", ["average_balance_prudent", "average_balance_asap"]) ###Output _____no_output_____ ###Markdown It is not as advantageous to be Prudent now, their payoffs are broadly similar to ASAPs. But it doesn't hurt either. ###Code Beacon Runner: Thunderdome Note: This post describes a result that was true in the v1 specs, but is fixed in the first major upgrade, v1.1, a.k.a. Altair. The table of rewards presented in Section 1. is also outdated. The value of the case study remains. // References + footnotes // Authors let authorData = ["barnabe"]; Many thanks to Sacha for his edits and suggestions; Danny, Protolambda and Terence for comments. ###Output _____no_output_____
_notebooks/2021-07-10-5minutes-data-science-design-pattern-callback.ipynb
###Markdown 5 Minutes Data Science Design Patterns I - Callback> A mini collections of design pattern for Data Science - Starting with callbacks.- toc: true - badges: true- comments: true- author: noklam- categories: ["python", "design pattern", "software"] > Note: These series are written as a quick introduction to software design for data scientists, something that is lightweight than the Design Pattern Bible - [Clean Code](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) I wish exists when I first started to learn. Design patterns refer to reusable solutions to some common problems, and some happen to be useful for data science. There is a good chance that someone else has solved your problem before. When used wisely, it helps to reduce the complexity of your code. So, What is Callback after all? `Callback` function, or call **after**, simply means a function will be **called after** another function. It is a piece of executable code (function) that passed as an **argument** to another function. [[1]](https://stackoverflow.com/questions/824234/what-is-a-callback-function) ###Code def foo(x, callback=None): print('foo!') if callback: callback(x) foo('123') foo('123', print) ###Output foo! 123 ###Markdown Here I pass the function `print` as a callback, hence the string `123` get printed **after** `foo!`. Why do I need to use Callback? **Callback** is very common in high-level deep learning libraries, most likely you will find them in the training loop.* [fastai](https://docs.fast.ai/callback.core.html) - fastai provide high-level API for PyTorch* [Keras](https://keras.io/api/callbacks/ ) - the high-level API for Tensorflow* [ignite](https://github.com/pytorch/ignite) - they use event & handler, which provides more flexibility in their opinion ###Code import numpy as np # A boring training Loop def train(x): n_epochs = 3 n_batches = 2 loss = 20 for epoch in range(n_epochs): for batch in range(n_batches): loss = loss - 1 # Pretend we are training the model x = np.ones(10) train(x); ###Output _____no_output_____ ###Markdown So, let's say you now want to print the loss at the end of an epoch. You can just add 1 lines of code. The simple approach ###Code def train_with_print(x): n_epochs = 3 n_batches = 2 loss = 20 for epoch in range(n_epochs): for batch in range(n_batches): loss = loss - 1 # Pretend we are training the model print(f'End of Epoch. Epoch: {epoch}, Loss: {loss}') return loss train_with_print(x); ###Output End of Epoch. Epoch: 0, Loss: 18 End of Epoch. Epoch: 1, Loss: 16 End of Epoch. Epoch: 2, Loss: 14 ###Markdown Callback approach Or you call add a PrintCallback, which does the same thing but with a bit more code. ###Code class Callback: def on_epoch_start(self, x): pass def on_epoch_end(self, x): pass def on_batch_start(self, x): pass def on_batch_end(self, x): pass class PrintCallback(Callback): def on_epoch_end(self, x): print(f'End of Epoch. Loss: {x}') def train_with_callback(x, callback=None): n_epochs = 3 n_batches = 2 loss = 20 for epoch in range(n_epochs): callback.on_epoch_start(loss) for batch in range(n_batches): callback.on_batch_start(loss) loss = loss - 1 # Pretend we are training the model callback.on_batch_end(loss) callback.on_epoch_end(loss) train_with_callback(x, callback=PrintCallback()); ###Output End of Epoch. Loss: 18 End of Epoch. Loss: 16 End of Epoch. Loss: 14 ###Markdown Usually, a callback defines a few particular events `on_xxx_xxx`, which indicate that the function will be executed according to the corresponding condition. So all callbacks will inherit the base class `Callback`, and override the desired function, here we only implemented the `on_epoch_end` method because we only want to show the loss at the end.It may seem awkward to write so many more code to do one simple thing, but there are good reasons. Consider now you need to add more features, how would you do it?* ModelCheckpoint* Early Stopping* LearningRateSchedulerYou can just add code in the loop, but it will start growing into a really giant function. It is impossible to **test** this function because it does 10 things at the same time. In addition, the extra code may not even be related to the training logic, they are just there to save the model or plot a chart. So, it is best to separate the logic. A function should only do 1 thing according to the [Single Responsibility Principle](https://en.wikipedia.org/wiki/SOLID). It helps you to reduce the complexity as it provides a nice abstraction, you are only modifying code within the specific callback you are interested. Add some more sauce! When using the **Callback** Pattern, I can just implement a few more classes and the training loop is barely touched. Here we introduce a new class `Callbacks` because we need to execute more than 1 callback, it is used for holding all callbacks and executed them sequentially. ###Code class Callbacks: """ It is the container for callback """ def __init__(self, callbacks): self.callbacks = callbacks def on_epoch_start(self, x): for callback in self.callbacks: callback.on_epoch_start(x) def on_epoch_end(self, x): for callback in self.callbacks: callback.on_epoch_end(x) def on_batch_start(self, x): for callback in self.callbacks: callback.on_batch_start(x) def on_batch_end(self, x): for callback in self.callbacks: callback.on_batch_end(x) ###Output _____no_output_____ ###Markdown Then we implement the new **Callback** one by one, here we only have the pseudocode, but you should get the gist. For example, we only need to save the model at the end of an epoch, thus we implement the method `on_epoch_end` with a `ModelCheckPoint` callback. ###Code class PrintCallback(Callback): def on_epoch_end(self, x): print(f'[{type(self).__name__}]: End of Epoch. Loss: {x}') class ModelCheckPoint(Callback): def on_epoch_end(self, x): print(f'[{type(self).__name__}]: Save Model') class EarlyStoppingCallback(Callback): def on_epoch_end(self, x): if x < 16: print(f'[{type(self).__name__}]: Early Stopped') class LearningRateScheduler(Callback): def on_batch_end(self, x): print(f' [{type(self).__name__}]: Reduce learning rate') ###Output _____no_output_____ ###Markdown And we also modify the training loop a bit, the argument now takes a `Callbacks` which contain zero to many callbacks. ###Code def train_with_callbacks(x, callbacks=None): n_epochs = 2 n_batches = 3 loss = 20 for epoch in range(n_epochs): callbacks.on_epoch_start(loss) # on_epoch_start for batch in range(n_batches): callbacks.on_batch_start(loss) # on_batch_start loss = loss - 1 # Pretend we are training the model callbacks.on_batch_end(loss) # on_batch_end callbacks.on_epoch_end(loss) # on_epoch_end callbacks = Callbacks([PrintCallback(), ModelCheckPoint(), EarlyStoppingCallback(), LearningRateScheduler()]) train_with_callbacks(x, callbacks=callbacks) ###Output [LearningRateScheduler]: Reduce learning rate [LearningRateScheduler]: Reduce learning rate [LearningRateScheduler]: Reduce learning rate [PrintCallback]: End of Epoch. Loss: 17 [ModelCheckPoint]: Save Model [LearningRateScheduler]: Reduce learning rate [LearningRateScheduler]: Reduce learning rate [LearningRateScheduler]: Reduce learning rate [PrintCallback]: End of Epoch. Loss: 14 [ModelCheckPoint]: Save Model [EarlyStoppingCallback]: Early Stopped
Code/RAIREExample.ipynb
###Markdown RAIRE example assertionsThis notebook provides a simple example of the kinds of assertions RAIRE might derive.Suppose we have the following IRV CVRs:- 10 votes list (Alpine, Beach, Canyon)- 10 votes list (Alpine, Beach, Desert)- 25 votes list (Beach)- 6 votes list (Canyon, Alpine, Beach)- 4 votes list (Desert, Alpine, Beach)The apparent winner is Alpine, with apparent elimination order Desert, Canyon, Beach, (Alpine), shown below in red.The audit needs to exclude all the other possible winners, though we don't care about other elimination orders in which Alpine wins. To see how this works, click in each python box (including the import box above) and press shift-enter, working down the page. ###Code qrtree0 = ("Alpine", ("Beach", ("Canyon", "Desert"), ("Desert", "Canyon")),("Canyon", ("Beach", "Desert"), ("Desert", "Beach")),("Desert", ("Beach", "Canyon"), ("Canyon", "Beach"))) out0 = svgling.draw_tree(qrtree0) out0.set_edge_style((0,), svgling.core.EdgeStyle(stroke_width=4, stroke="red")) out0.set_edge_style((0,0), svgling.core.EdgeStyle(stroke_width=4, stroke="red")) out0.set_edge_style((0,0,0), svgling.core.EdgeStyle(stroke_width=4, stroke="red")) out0 = Caption(out0, "All the different elimination orders in which Alpine wins.") qrtree1 = ("Beach", ("Alpine", ("Canyon", "Desert"), ("Desert", "Canyon")),("Canyon", ("Alpine", "Desert"), ("Desert", "Alpine")),("Desert", ("Alpine", "Canyon"), ("Canyon", "Alpine"))) out1 = svgling.draw_tree(qrtree1) out1 = Caption(out1, "All the different elimination orders in which Beach wins.") qrtree2 = ("Canyon", ("Alpine", ("Beach", "Desert"), ("Desert", "Beach")),("Beach", ("Alpine", "Desert"), ("Desert", "Alpine")),("Desert", ("Alpine", "Beach"), ("Beach", "Alpine"))) out2 = svgling.draw_tree(qrtree2) out2 = Caption(out2, "All the different elimination orders in which Canyon wins.") qrtree3 = ("Desert", ("Alpine", ("Beach", "Canyon"), ("Canyon", "Beach")),("Beach", ("Alpine", "Canyon"), ("Canyon", "Alpine")),("Canyon", ("Alpine", "Beach"), ("Beach", "Alpine"))) out3 = svgling.draw_tree(qrtree3) out3 = Caption(out3, "All the different elimination orders in which Desert wins.") Caption(RowByRow(SideBySide(out3, out2), SideBySide(out1,out0)), "Trees illustrating all the possible elimination orders in a 4-candidate IRV election.") ###Output _____no_output_____ ###Markdown From now on we disregard the tree in which Alpine wins, and try to exclude all the others. First consider Winner-only (WO) comparison between Alpine and Canyon - WO(Canyon,Alpine). Canyon has only 6 mentions (not counting votes that prefer Alpine). That's less than Alpine's first preference count of 20. So Alpine cannot be eliminated before Canyon. ###Code qrtree1 = ("Beach", ("Alpine", ("Canyon", "Desert"), ("Desert", "Canyon")),"Canyon",("Desert", ("Alpine", "Canyon"), "Canyon")) out1 = svgling.draw_tree(qrtree1) out1.box_constituent((1,),fill="green") out1.box_constituent((2,1),fill="green") out1 = Caption(out1, "All the different elimination orders in which Beach wins.") qrtree2 = ("Canyon") out2 = svgling.draw_tree(qrtree2) out2.box_constituent((),fill="green") out2 = Caption(out2, "Exclude all elimination orders in which Canyon wins.") qrtree3 = ("Desert", ("Alpine", ("Beach", "Canyon"), ("Canyon", "Beach")),("Beach", ("Alpine", "Canyon"),"Canyon"),"Canyon") out3 = svgling.draw_tree(qrtree3) out3.box_constituent((2,),fill="green") out3.box_constituent((1,1),fill="green") out3 = Caption(out3, "All the different elimination orders in which Desert wins.") Caption(RowByRow(SideBySide(out3, out2), out1), "Green pruned subtrees excluded by WO(Canyon, Alpine). Alpine can't be eliminated before Canyon") ###Output _____no_output_____ ###Markdown Now consider Winner-only (WO) comparison between Alpine and Desert - WO(Desert,Alpine). Desert has only 4 mentions (not counting votes that prefer Alpine). That's less than Alpine's first preference count of 20. So Alpine cannot be eliminated before Desert. ###Code qrtree1 = ("Beach", ("Alpine", ("Canyon", "Desert"), ("Desert", "Canyon")),"Canyon","Desert") out1 = svgling.draw_tree(qrtree1) out1.box_constituent((1,),fill="green") out1.box_constituent((2,),fill="blue") out1 = Caption(out1, "All the different elimination orders in which Beach wins.") qrtree2 = ("Canyon") out2 = svgling.draw_tree(qrtree2) out2.box_constituent((),fill="green") out2 = Caption(out2, "Exclude all elimination orders in which Canyon wins.") qrtree3 = ("Desert") out3 = svgling.draw_tree(qrtree3) out3.box_constituent((),fill="blue") out3 = Caption(out3, "Exclude all elimination orders in which Desert wins.") Caption(RowByRow(SideBySide(out3, out2), out1), "Green pruned blue trees excluded by WO(Canyon, Alpine) and blue for WO(Desert, Alpine). Alpine can't be eliminated before Canyon or Desert") ###Output _____no_output_____ ###Markdown Finally, WO(Beach,Alpine) doesn't work, because Beach has 25 mentions. We need to test the last IRV round and compare only Beach, Alpine. This is written as IRV(Beach, Alpine, {Alpine}). ###Code qrtree1 = ("Beach","Alpine","Canyon","Desert") out1 = svgling.draw_tree(qrtree1) out1.box_constituent((0,),fill="none",stroke_width=4, stroke="purple") out1.box_constituent((1,),fill="green") out1.box_constituent((2,),fill="blue") out1 = Caption(out1, "Exclude all elimination orders in which Beach wins.") qrtree2 = ("Canyon") out2 = svgling.draw_tree(qrtree2) out2.box_constituent((),fill="green") out2 = Caption(out2, "Exclude all elimination orders in which Canyon wins.") qrtree3 = ("Desert") out3 = svgling.draw_tree(qrtree3) out3.box_constituent((),fill="blue") out3 = Caption(out3, "Exclude all elimination orders in which Desert wins.") Caption(RowByRow(SideBySide(out3, out2), out1), "Complete exclusion of all cases in which Alpine doesn't win. IRV(Beach,Alpine,{Alpine}) is shown as a purple box.") ###Output _____no_output_____
30_case_studies/316_fire_california_2020_Sentinel-3_SLSTR_NRT_AOD_L2.ipynb
###Markdown 317 Indonesian Fires 2020 - Multi-data >> 30 - CASE STUDIES - FIRE PREREQUISITES The following **20 - DATA DISCOVERY** module is a prerequisite: - [253 - Sentinel-3 SLSTR NRT - Aerosol Optical Depth - Load and browse](../20_data_discovery/253_Sentinel-3_SLSTR_NRT_AOD_L2_load_browse.ipynb)It is recommended to go through the module before you start with this module. 3.1.6 Discover Californian Fires 2020 Example Sentinel-3 Near Real Time SLSTR Aerosol Optical Depth (AOD) The [Copernicus Sentinel-3 Near Real Time Aerosol Optical Depth (AOD)](https://www.eumetsat.int/website/home/News/DAT_5150095.html) product quantifies the abundance of all aerosol particles suspended in the air and monitors their global distribution and long-range transport, at the scale of 9.5 x 9.5 km2. It is only applicable during daytime. The current version of the NRT S3 AOD product is considered as 'preliminary operational' over ocean surfaces, and 'demonstrational' over land surfaces. It is only applicable during daytimeAll these observations are made available in less than three hours from the SLSTR observation sensing time.The following workflow is based on an example of `Sentinel-3 Near Real Time SLSTR AOD` data on 1 October 2020, capturing the detected Aerosol Optical Depth from the wildfires in California, US. Outline * [Example: Californian Fires - October 2020](californian_fires) * [1 - Load Sentinel-3 SLSTR AOD data](load_cal) * [2 - Extract AOD variables](extract_cal) * [3 - Visualize AOD Ocean and AOD land information](visualize_cal) Load required libraries ###Code import xarray as xr import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.pyplot as pltfacebook import matplotlib.colors as colors import matplotlib.cm as cm import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER ###Output _____no_output_____ ###Markdown Load helper functions ###Code %run ../functions.ipynb ###Output _____no_output_____ ###Markdown Load Sentinel-3 SLSTR AOD data The Near-Real-Time Sentinel-3 SLSTR Aerosol Optical Depth (AOD) data are disseminated in `netCDF`. `netCDF` data can be loaded with the Python library [xarray](http://xarray.pydata.org/en/stable/) and its function `xr.open_dataset()`. You see that the data file contains two `dimensions`:* `columns` and* `rows`.It further contains an long list of `data variables`, including:* `AOD_550`,* `AOD_550_uncertainty`,* `AOD_550_Ocean_NonFiltered`,* `AOD_550_Land_Experimental_PostFiltered`,...A data file also contains a set of `attributes`, which give you more information about the data file and the data it contains, e.g the `start_time` and `stop_time` or the `product_name`. ###Code file = xr.open_dataset('../eodata/sentinel3/slstr/2020/10/01/AOD_California_20201001.nc') file ###Output _____no_output_____ ###Markdown Extract Aerosol Optical Depth variables The next step is to extract the variables of interest. Let us select the following two variables:* `AOD_550`: it is the Aerosol Optical Depth at 550nm. (*Note: it only covers ocean surfaces.*)* `AOD_550_Land_Experimental_PostFiltered`: it is the Aerosol Optical Depth at 550nm. (*Note: it only covers land surfaces.*)Both `DataArrays` have two dimensions (`rows` and `columns`) and the following attributes, which provide additional information about the variables:* `long_name`* `standard_name`* `valid_min`* `valid_max`* `coordinates` ###Code aod_ocean = file.AOD_550 aod_land = file.AOD_550_Land_Experimental_PostFiltered print(aod_ocean) print(' ') print(aod_land) ###Output <xarray.DataArray 'AOD_550' (rows: 210, columns: 157)> array([[nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], ..., [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan]], dtype=float32) Dimensions without coordinates: rows, columns Attributes: long_name: Aerosol optical thickness at 550 nm - Best quality (post-... standard_name: atmosphere_optical_thickness_due_to_ambient_aerosol valid_min: 0.0 valid_max: 4.001 coordinates: latitude, longitude <xarray.DataArray 'AOD_550_Land_Experimental_PostFiltered' (rows: 210, columns: 157)> array([[nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], ..., [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan]], dtype=float32) Dimensions without coordinates: rows, columns Attributes: long_name: Aerosol optical thickness at 550 nm - Only over land surf... standard_name: atmosphere_optical_thickness_due_to_ambient_aerosol valid_min: 0.0 valid_max: 4.001 coordinates: latitude, longitude ###Markdown You can also load `latitude` and `longitude` information, which can be used later for visualizing the variables. ###Code lat_nc = file.latitude lon_nc = file.longitude print(lat_nc) print(' ') print(lon_nc) ###Output <xarray.DataArray 'latitude' (rows: 210, columns: 157)> array([[40.54374 , 40.533485, 40.523174, ..., 37.763252, 37.73665 , 37.71009 ], [40.46065 , 40.45038 , 40.44005 , ..., 37.676662, 37.649994, 37.62782 ], [40.377556, 40.367268, 40.35692 , ..., 37.593685, 37.571865, 37.54554 ], ..., [23.316261, 23.302357, 23.288424, ..., 20.575003, 20.553972, 20.533533], [23.232931, 23.21901 , 23.205057, ..., 20.492165, 20.4701 , 20.45003 ], [23.1496 , 23.13566 , 23.121693, ..., 20.407766, 20.387156, 20.366516]], dtype=float32) Dimensions without coordinates: rows, columns Attributes: long_name: Latitude at pixel centre standard_name: latitude units: degrees_north valid_min: -90.0 valid_max: 90.0 <xarray.DataArray 'longitude' (rows: 210, columns: 157)> array([[-132.85818 , -132.74686 , -132.63556 , ..., -116.28708 , -116.182686, -116.08103 ], [-132.87125 , -132.76007 , -132.6489 , ..., -116.32189 , -116.21673 , -116.11361 ], [-132.88432 , -132.77327 , -132.66225 , ..., -116.351654, -116.250534, -116.14609 ], ..., [-135.7318 , -135.64015 , -135.54852 , ..., -121.87042 , -121.78165 , -121.69401 ], [-135.7466 , -135.65501 , -135.56343 , ..., -121.891685, -121.80393 , -121.71706 ], [-135.7614 , -135.66988 , -135.57837 , ..., -121.91918 , -121.82491 , -121.74005 ]], dtype=float32) Dimensions without coordinates: rows, columns Attributes: long_name: Longitude at pixel centre standard_name: longitude units: degrees_east valid_min: -180.0 valid_max: 180.0 ###Markdown Visualize AOD Ocean and AOD Land variables The final step is to visualize both variables, Aerosol Optical Depth over ocean and land together in one plot. You can use the function [visualize_s3_aod](../functions.ipynbvisualize_s3_aod), which makes use of matplotlib's `pcolormesh` function and visualizes both AOD variables in one plot, `AOD Ocean` and `AOD Land`.The function takes the following keyword arguments (kwargs):* `aod_ocean`: DataArray with AOD values over ocean* `aod_land`: DataArray with AOD values over land* `latitude`: DataArray with latitude information* `longitude`: DataArray with longitude information* `title`: Title of the plot* `unit`: Unit of AOD* `vmin` and `vmax`: Minimum and maximum values to be displayed on the map* `color_scale`: Color scale the data shall be represented* `projection`: Projection of the map ###Code visualize_s3_aod(aod_ocean=aod_ocean, aod_land=aod_land, latitude=lat_nc, longitude=lon_nc, title='Aerosol Optical Thickness at 550 nm', unit='~', vmin=0., vmax=1.0, color_scale=cm.RdYlBu_r, projection=ccrs.Mercator()) ###Output _____no_output_____ ###Markdown 321 - Map and time-series of Metop-A/B GOME-2 Tropospheric NO2 Level 3 data >> 30 - CASE STUDIES - FIRE PREREQUISITES The following **20 - DATA DISCOVERY** module is a prerequisite: - [253 - Sentinel-3 SLSTR NRT - Aerosol Optical Depth - Load and browse](../20_data_discovery/253_Sentinel-3_SLSTR_NRT_AOD_L2_load_browse.ipynb)It is recommended to go through the module before you start with this module. 3.1.6 Discover Californian Fires 2020 Example Sentinel-3 Near Real Time SLSTR Aerosol Optical Depth (AOD) The [Copernicus Sentinel-3 Near Real Time Aerosol Optical Depth (AOD)](https://www.eumetsat.int/website/home/News/DAT_5150095.html) product quantifies the abundance of all aerosol particles suspended in the air and monitors their global distribution and long-range transport, at the scale of 9.5 x 9.5 km2. It is only applicable during daytime. The current version of the NRT S3 AOD product is considered as 'preliminary operational' over ocean surfaces, and 'demonstrational' over land surfaces. It is only applicable during daytimeAll these observations are made available in less than three hours from the SLSTR observation sensing time.The following workflow is based on an example of `Sentinel-3 Near Real Time SLSTR AOD` data on 1 October 2020, capturing the detected Aerosol Optical Depth from the wildfires in California, US. Outline * [Example: Californian Fires - October 2020](californian_fires) * [1 - Load Sentinel-3 SLSTR AOD data](load_cal) * [2 - Extract AOD variables](extract_cal) * [3 - Visualize AOD Ocean and AOD land information](visualize_cal) Load required libraries ###Code import xarray as xr import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.pyplot as pltfacebook import matplotlib.colors as colors import matplotlib.cm as cm import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER ###Output _____no_output_____ ###Markdown Load helper functions ###Code %run ../functions.ipynb ###Output _____no_output_____ ###Markdown Load Sentinel-3 SLSTR AOD data The Near-Real-Time Sentinel-3 SLSTR Aerosol Optical Depth (AOD) data are disseminated in `netCDF`. `netCDF` data can be loaded with the Python library [xarray](http://xarray.pydata.org/en/stable/) and its function `xr.open_dataset()`. You see that the data file contains two `dimensions`:* `columns` and* `rows`.It further contains an long list of `data variables`, including:* `AOD_550`,* `AOD_550_uncertainty`,* `AOD_550_Ocean_NonFiltered`,* `AOD_550_Land_Experimental_PostFiltered`,...A data file also contains a set of `attributes`, which give you more information about the data file and the data it contains, e.g the `start_time` and `stop_time` or the `product_name`. ###Code file = xr.open_dataset('../eodata/sentinel3/slstr/2020/10/01/AOD_California_20201001.nc') file ###Output _____no_output_____ ###Markdown Extract Aerosol Optical Depth variables The next step is to extract the variables of interest. Let us select the following two variables:* `AOD_550`: it is the Aerosol Optical Depth at 550nm. (*Note: it only covers ocean surfaces.*)* `AOD_550_Land_Experimental_PostFiltered`: it is the Aerosol Optical Depth at 550nm. (*Note: it only covers land surfaces.*)Both `DataArrays` have two dimensions (`rows` and `columns`) and the following attributes, which provide additional information about the variables:* `long_name`* `standard_name`* `valid_min`* `valid_max`* `coordinates` ###Code aod_ocean = file.AOD_550 aod_land = file.AOD_550_Land_Experimental_PostFiltered print(aod_ocean) print(' ') print(aod_land) ###Output <xarray.DataArray 'AOD_550' (rows: 210, columns: 157)> array([[nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], ..., [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan]], dtype=float32) Dimensions without coordinates: rows, columns Attributes: long_name: Aerosol optical thickness at 550 nm - Best quality (post-... standard_name: atmosphere_optical_thickness_due_to_ambient_aerosol valid_min: 0.0 valid_max: 4.001 coordinates: latitude, longitude <xarray.DataArray 'AOD_550_Land_Experimental_PostFiltered' (rows: 210, columns: 157)> array([[nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], ..., [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan], [nan, nan, nan, ..., nan, nan, nan]], dtype=float32) Dimensions without coordinates: rows, columns Attributes: long_name: Aerosol optical thickness at 550 nm - Only over land surf... standard_name: atmosphere_optical_thickness_due_to_ambient_aerosol valid_min: 0.0 valid_max: 4.001 coordinates: latitude, longitude ###Markdown You can also load `latitude` and `longitude` information, which can be used later for visualizing the variables. ###Code lat_nc = file.latitude lon_nc = file.longitude print(lat_nc) print(' ') print(lon_nc) ###Output <xarray.DataArray 'latitude' (rows: 210, columns: 157)> array([[40.54374 , 40.533485, 40.523174, ..., 37.763252, 37.73665 , 37.71009 ], [40.46065 , 40.45038 , 40.44005 , ..., 37.676662, 37.649994, 37.62782 ], [40.377556, 40.367268, 40.35692 , ..., 37.593685, 37.571865, 37.54554 ], ..., [23.316261, 23.302357, 23.288424, ..., 20.575003, 20.553972, 20.533533], [23.232931, 23.21901 , 23.205057, ..., 20.492165, 20.4701 , 20.45003 ], [23.1496 , 23.13566 , 23.121693, ..., 20.407766, 20.387156, 20.366516]], dtype=float32) Dimensions without coordinates: rows, columns Attributes: long_name: Latitude at pixel centre standard_name: latitude units: degrees_north valid_min: -90.0 valid_max: 90.0 <xarray.DataArray 'longitude' (rows: 210, columns: 157)> array([[-132.85818 , -132.74686 , -132.63556 , ..., -116.28708 , -116.182686, -116.08103 ], [-132.87125 , -132.76007 , -132.6489 , ..., -116.32189 , -116.21673 , -116.11361 ], [-132.88432 , -132.77327 , -132.66225 , ..., -116.351654, -116.250534, -116.14609 ], ..., [-135.7318 , -135.64015 , -135.54852 , ..., -121.87042 , -121.78165 , -121.69401 ], [-135.7466 , -135.65501 , -135.56343 , ..., -121.891685, -121.80393 , -121.71706 ], [-135.7614 , -135.66988 , -135.57837 , ..., -121.91918 , -121.82491 , -121.74005 ]], dtype=float32) Dimensions without coordinates: rows, columns Attributes: long_name: Longitude at pixel centre standard_name: longitude units: degrees_east valid_min: -180.0 valid_max: 180.0 ###Markdown Visualize AOD Ocean and AOD Land variables The final step is to visualize both variables, Aerosol Optical Depth over ocean and land together in one plot. You can use the function [visualize_s3_aod](../functions.ipynbvisualize_s3_aod), which makes use of matplotlib's `pcolormesh` function and visualizes both AOD variables in one plot, `AOD Ocean` and `AOD Land`.The function takes the following keyword arguments (kwargs):* `aod_ocean`: DataArray with AOD values over ocean* `aod_land`: DataArray with AOD values over land* `latitude`: DataArray with latitude information* `longitude`: DataArray with longitude information* `title`: Title of the plot* `unit`: Unit of AOD* `vmin` and `vmax`: Minimum and maximum values to be displayed on the map* `color_scale`: Color scale the data shall be represented* `projection`: Projection of the map ###Code visualize_s3_aod(aod_ocean=aod_ocean, aod_land=aod_land, latitude=lat_nc, longitude=lon_nc, title='Aerosol Optical Thickness at 550 nm', unit='~', vmin=0., vmax=1.0, color_scale=cm.RdYlBu_r, projection=ccrs.Mercator()) ###Output _____no_output_____
intro_to_ml_day1.ipynb
###Markdown Introduction to Machine LearningGrant GlassTAP InstituteDay 01:Key Concepts and Terms Preface Welcome to Machine Learning as a part of the 2021 TAP Institute's summer courses. In this first day notebook, we will go over the core concepts of machine learning and start to get our feet wet with ML. I will not be providing you a complete overview, but rather a quick way to get a genereal understanding about what machine learning is and how it works. In days two and three, we will be exploring different machine learning techniques more in depth. Covered in this Notebook 1) What is Machine Learning?2) What is a Statistical Model?3) A framework for understanding ML4) Simple Example of ML Before we Begin! Head to the Google Teachable Machine Website: https://teachablemachine.withgoogle.comThe Teachable Machine website provides an easy to use interface for training image, sound, and pose classification models. No login is required to get started. Training data files can be loaded directly from your computer or from your computer’s webcam or microphone. Models can be exported to use in other projects, and the FAQ (https://cloud.google.com/inclusive-ml/) includes links to read more about fairness and inclusion in ML.Take a look at this project involving training a model to detect how ripe a piece of fruit is: https://medium.com/@warronbebster/teachable-machine-tutorial-bananameter-4bfffa765866How do you think the computer figures out ripeness?What exactly are we teaching the machine?What other humanistic data could we use for this type of machine learning? Part One - What is MACHINE LEARNING? The field itself: ML is a field of study which harnesses principles of computer science and statistics to create statistical models. These models are generally used to do two things:Prediction: make predictions about the future based on data about the pastInference: discover patterns in data Difference between ML and AI: There is no universally agreed upon distinction between ML and artificial intelligence (AI). AI usually concentrates on programming computers to make decisions (based on ML models and sets of logical rules), whereas ML focuses more on making predictions about the future.They are highly interconnected fields, and, for most non-technical purposes, they are the same. Part Two - What is A STATISTICAL MODEL? **Models:** Teaching a computer to make predictions involves feeding data into machine learning models, which are representations of how the world supposedly works. If I tell a statistical model that the world works a certain way (say, for example, that two story homes are more expensive than one story homes), then this model can then tell me what be more expensive, a ranch style home or a cape cod. What does a model actually look like? Surely the concept of a model makes sense in the abstract, but knowing this is just half the battle. You should also know how it’s represented inside of a computer, or what it would look like if you wrote it down on paper.A model is just a mathematical function, which is merely a relationship between a set of inputs and a set of outputs. Here’s an example:f(x) = x²This is a function that takes as input a number and returns that number squared. So, f(1) = 1, f(2) = 4, f(3) = 9.Let’s briefly return to the example of the model that predicts home price from home stories. I may believe, based on what I’ve seen in the world, that given a home's price is, on average, equal to the house's stories times 100,000. This model can be represented mathematically as follows:Price = Stories × $100,000In other words, income is a function of stories.**Here’s the main point:** Machine learning refers to a set of techniques for estimating functions (like the one involving income) based on datasets (pairs of heights and their associated incomes). These functions, which are called models, can then be used for predictions of future data.**Algorithms:** These functions are estimated using algorithms. In this context, an algorithm is a predefined set of steps that takes as input a bunch of data and then transforms it through mathematical operations. You can think of an algorithm like a recipe — first do this, then do that, then do this. Done.Machine learning of all types uses models and algorithms as its building blocks to make predictions and inferences about the world.Now I’ll show you how models actually work by breaking them apart, component by component. This next part is important. Part Three - A Framework for understanding ML **Inputs:** Statistical models learn from the past, formatted as structured tables of data (called **training data**). These datasets — such as those you might find in Excel sheets — tend to be formatted in a very structured, easy-to-understand way: each row in the dataset represents an individual **observation,** also called a datum or measurement, and each column represents a different **feature**, also called a predictor, of an observation.For example, you might imagine a dataset about people, in which each row represents a different person, and each column represents a different feature about that person: profession, age, income, etc.Most traditional models accept data formatted in the way I’ve just described. We call this structured data.Because one common goal of ML is to make predictions, training data also includes a column containing the data you want to predict. This feature is called the response variable (or output variable, or dependent variable) and looks just like any other feature in the table.Most common statistical models are constructed using a technique called supervised learning, which uses data that includes a response variable to make predictions or do inference. There is also a branch of ML called unsupervised learning, which doesn’t require a response variable and which is generally used just to find interesting patterns between variables (this pattern-finding process is known as inference). It is just as important as supervised learning, but it is usually much harder to understand and also less common in practice. This document won’t talk much about the latter subfield. The takeaway from this paragraph is simply that there are two “types” of learning, and that supervised learning is more common.Model selection: We have our data, and we’ve decided that there’s probably a relationship between our predictors and our response. We’re ready to make predictions.As an aside, we don’t actually need to know if there’s a relationship between these variables. We could, in fact, just throw all of our data into an algorithm and see if the resulting model is able to make valid predictions.Now we need to pick which model to use. Naturally, there are many different types of models which explain how the data actually works, and we’d like to choose the one that most accurately describes the relationship between the predictors and the response variable.Models generally fall into one of two categories:**Regression models**, which are used when the response variable (i.e. the variable that you’re predicting) is continuous. For example, height, age, and income are all continuous. That is, they can be placed and ordered on a number line.**Classification models**, which are used for categorical data — that is, data that doesn’t have a numerical ordering. For example, you may want to predict, based on an image of a flower, the species of that flower. Or you may want to predict whether a student is a psychology major or a math major.The first step in picking a model is deciding whether or not your response variable is quantitative or categorical.Why is model selection an important concept for non-technical people? Well, if a model is chosen poorly, then its predictions will be inaccurate!Below, I’ll walk you through an example of a popular, powerful, simple mode that can be used for prediction. Data from: https://alt.qcri.org/semeval2020/ Part Four - Let's Look at an example! ###Code # Import Libraries import pandas as pd import numpy as np import scipy import sklearn from sklearn import linear_model from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer ###Output _____no_output_____ ###Markdown Load data, split into training and validation sets ###Code filepath = 'data/train.csv' dataframe = pd.read_csv(filepath) print(len(dataframe)) # print(dataframe) dataframe.head() ###Output _____no_output_____ ###Markdown This is a text-based regression task. Every training document (a line in the data file) contains the following columns (csv format):**id:** document identifier;original: original news headline, in which one word is tagged between ;**edit:** the new word to replace the tagged word in the original headline;**grades:** a list of funniness grades (0="Not Funny", 1="Slightly Funny", 2="Moderately Funny", 3="Funny") concatenated into a single string. For instance, '1101' means four human judges looked at the edited headline and submitted funniness grades {1, 1, 0, 1};**meanGrade:** the average funniness value. In the previous example, meanGrade = (1+1+0+1)/4 = 0.75 .Your goal is to predict the average funniness value of an edited headline. More concretely, to predict the meanGrade (a real value) given an original headline, a tagged word, and an edit word. ###Code train_ratio = 0.7 # 70% for training, 30% for validation random_seed = None # a fixed random seed allows fixed random runs (for controlled debugging). set to None to be random. train_dataframe = dataframe.sample(frac= train_ratio, random_state=100) valid_dataframe = dataframe.drop(train_dataframe.index) print('training set size:', len(train_dataframe)) print('validation set size:', len(valid_dataframe)) # print(train_dataframe) ###Output training set size: 5067 validation set size: 2172 ###Markdown Also load test data (no splitting needed here) ###Code test_filepath = 'data/test.csv' test_dataframe = pd.read_csv(test_filepath) print('test set size:', len(test_dataframe)) # print(test_dataframe) test_dataframe.head() ###Output _____no_output_____ ###Markdown Try the trivial baseline: always predicting the average meanGrade (of training data) ###Code # take out prediction targets: mean grades train_Y = train_dataframe['meanGrade'] valid_Y = valid_dataframe['meanGrade'] ###Output _____no_output_____ ###Markdown The Root Mean Squared (RMSE) is our evaluation metric and is calculated as𝑅𝑀𝑆𝐸=√∑𝑛𝑖=1(𝑦𝑖−𝑦̂𝑖)2/nwhere 𝑦𝑖 is the actual funniness value of the document, and 𝑦̂𝑖 is the predicted value of the document, so (𝑦𝑖−𝑦̂𝑖)2 is the squared error of prediction. The lower RMSE, the more accurate prediction. ###Code # compute average of a list of numbers: np.mean train_Y_avg = np.mean(train_dataframe['meanGrade']) print('average meanGrade on training set:', train_Y_avg) # make a list filled with train_Y_avg, essentially predicting the same number for all lines in validation set avg_pred_valid = [train_Y_avg for i in range(len(valid_dataframe))] # print (avg_pred_valid) # compute root mean squared error (RMSE) of this prediction on validation set rmse = np.sqrt(mean_squared_error(valid_Y, avg_pred_valid)) print('RMSE on validation set:', rmse) #taking the mean as the error # helper function: write out prediction values into a csv format file # params: # df: dataframe, where each row is a test example, with column 'id' as data id # pred: a list or 1-d array of prediction values # filepath: the output file path # return: # None def write_test_prediction(df, pred, filepath): with open(filepath, 'w') as outfile: outfile.write('{},{}\n'.format('id', 'pred')) for index, row in df.iterrows(): outfile.write('{},{}\n'.format(row['id'], pred[index])) # make a list filled with train_Y_avg, essentially predicting the same number for all lines in test set avg_pred_test = [train_Y_avg for i in range(len(test_dataframe))] write_test_prediction(test_dataframe, avg_pred_test, './average_constant_baseline_new-tf.csv') ###Output _____no_output_____ ###Markdown Build feature extractor from training data (here we use a CountVectorizer or TfidfVectorizer ) ###Code # get entire raw text in training corpus, including title and edit words (for learning vocabulary and IDF) # params: # df: dataframe, with 'original' and 'edit' columns # return: # corpus: a list of text strings, each is a concatenation of original text and edit word on each line def get_raw_text(df): corpus = [] for index, row in df.iterrows(): title = row['original'].replace('<', '').replace('/>', '') edit = row['edit'] corpus.append( title + ' ' + edit ) return corpus ###Output _____no_output_____ ###Markdown TF-IDF ( Term Frequency(TF) — Inverse Dense Frequency(IDF) ) is a statistical measure that evaluates how relevant a word is to a document in a collection of documents. This is done by multiplying two metrics: how many times a word appears in a document, and the inverse document frequency of the word across a set of documents.It has many uses, most importantly in automated text analysis, and is very useful for scoring words in machine learning algorithms for Natural Language Processing (NLP).TF-IDF (term frequency-inverse document frequency) was invented for document search and information retrieval. It works by increasing proportionally to the number of times a word appears in a document, but is offset by the number of documents that contain the word. So, words that are common in every document, such as this, what, and if, rank low even though they may appear many times, since they don’t mean much to that document in particular.However, if the word Bug appears many times in a document, while not appearing many times in others, it probably means that it’s very relevant. For example, if what we’re doing is trying to find out which topics some NPS responses belong to, the word Bug would probably end up being tied to the topic Reliability, since most responses containing that word would be about that topic. ###Code train_corpus = get_raw_text(train_dataframe) print(train_corpus) vectorizer = TfidfVectorizer(stop_words = None).fit(train_corpus) print(vectorizer.vocabulary_) #vectorizer = CountVectorizer(stop_words = None).fit(train_corpus) #print(vectorizer.vocabulary_) ###Output ['Congress OKs Trump bid to widen private care at besieged VA destroy', 'Trump and Obama have the same approval rating after their first year , at least according to one poll person', 'H.R. McMaster says Trump administration will confront Russia \'s " destabilizing behavior " lizard', 'Triple Threat : New Pneumonia Is Drug-Resistant , Deadly And Contagious President', 'Is it Watergate yet ? moving', 'Report : Trump Wants His Chief Of Staff To Get Rid Of Jared And Ivanka police', 'How the Right Co-Opts Frederick Douglass handedness', 'Forget Trump – populism is the cure , not the disease hugging', 'AP Fact Check : An angry Trump twists facts about raid , probe candy', 'Michelle Obama was Jimmy Fallon ’s only guest and , no , they did not mom dance enemy', 'DOJ charges 11 possible caravan members with illegally entering the US restaurant', 'How Steve Bannon became the face of a political movement with roots in Los Angeles Cheerleaders', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " people', 'As It Makes More Arrests , ICE Looks For More Detention Centers Recreation', 'Syrian state TV says successive blasts heard in Hama province eructations', 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon circus', 'Trump defends decision to keep “ political and long ” Democratic memo under wraps presents', 'Trump blames Corker for the Iran deal smell', 'Remember when Republicans were mad that a president was unreliable to allies ? mistress', "Childhood bullying anxiety ' goes away ' homework", 'Steve Bannon is reportedly advocating for a tax hike on the wealthy nature', ' Resignation Wave On Capitol Hill Might Not Be Over Radio', 'Six journalists get life in prison over failed Turkish coup film', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson scent', 'House Democrats stun GOP by sinking veterans , intel bills fences', "South Korea 's president is expected to face prosecutors in coming days canines", 'Schiff : Trump Jr. may have been first to know about Russian efforts to meddle in election mysteries', 'CDC to hold briefing on how public can prepare for nuclear war chickens', 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Kiss', 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants sons', 'GOP lawmaker loses nearly $ 17 million after pharma stock tanks 92 % aquarium', '2016 RNC Delegate : Trump Directed Change To Party Platform On Ukraine Support bra', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller wake', 'Obama ’s Strange Last Days in Office pets', "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' stupidity", "Could microwave missiles disable North Korea 's missiles ? cook", "' I was very angry ' at Trump , says Myeshia Johnson , widow of fallen soldier cake", 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN Stealing', 'Gunmam attacks a Church in Helwan , Cairo . Four dead and nine wounded . [ shooter killed ] pie', "Tech and entertainment activists launch an app to ' Block the Bully ' Donald Trump on Twitter patsy", 'Ex-British spy paid $ 168,000 for Trump dossier , U.S. firm discloses tea', 'Despite Campaign Boasts , Trump Has No Idea How To Handle Classified Material Smoothies', "Jailed Malaysian Opposition Leader To Be Pardoned After His Party 's Victory dance", "North Korea ICBMs : Pyongyang says it will conduct nuclear missile test ' anytime and anywhere it wants ' meme", "World 's largest collection of ocean garbage is now twice the size of Texas political", 'The Olympic Gold Medal for Sucking Up to a Murderous Totalitarian Regime Goes to … Vacuum', "Rex Tillerson : US has ' direct channels ' to Pyongyang scam", "' Black Panther 's ' Wakanda sheds light on black excellence darkness", 'Quotation of the Day : Trump Tried to Sink Inquiry , Comey Says hoops', 'DirecTV is offering refunds for NFL Sunday Ticket to fans offended by national anthem protests melody', "Congress ' deficit hawks seem to have gone missing in action doves", 'Drunken American beating up for giving Nazi salute in Germany praised', 'Occupy Silicon Valley : The next populist movement may be aimed at tech wealth , report says bunnies', 'How to Stop an Autocracy itch', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News Water", 'Trump is making Americans see the U.S. the way the rest of the world already did despise', 'Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . Reality', 'The Republican tax bill contains a sneaky break for private jet owners bathroom', 'Charlotte Pence : I Bought The Gay Bunny Book Wrote', 'This congressional accounting trick is part of the reason Washington is so divided magic', "Advice for Trump : Do n't fire Robert Mueller -- He will clear you in the end tickle", 'The middle class does n’t want a tax cut . It wants better government . coffee', 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it bear', 'Experts to Trump : Russia is not our ally in the war on ISIS bears', ' Trump predicts Patriots will win Super Bowl by 8 points gypsy', 'GOP senators : Comey drafted statement clearing Clinton before her interview tickling', 'Trump Official Blocked Immigrant Teen Rape Victim ’s Abortion Because He Personally Opposed It healthy', 'Trump ’s Trillion Dollar Pledge to Fix Bridges and Roads Could be Challenging . . Lie', ' Taiwan court to rule in in landmark same-sex marriage case Heterosexual', 'White House invites intelligence committee leaders to review National Security Council documents tweets', 'Fought and forgotten : Filipino World War II veterans honored with medal 75 years later days', "Trump officials greet Ford 's plan to import Chinese cars Food", 'Donald Trump Jr. should publicly testify in Russia probe , Democrat on Senate Judiciary Committee says strip', 'Trump addresses Boy Scouts at national summit in West Virginia loses', "Rep. King seeks more surveillance after Port Authority explosion : ' We ca n't afford to be politically correct ' bowel", 'Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR vegetables', "Israeli minister wishes Iranian protesters ' success ' pleads", 'More than 50 detained in immigration raids at Asian restaurants in Mississippi house', 'President Trump to hold another Q&amp;A on The Donald subreddit this Wednesday apocalypse', "In the former capital of the Confederacy , the debate over the city 's famed Civil War monuments is heating up mounting", "Trump blasts Michelle Wolf 's correspondents ' dinner remarks about Sarah Huckabee Sanders gravy", 'The Latest : San Juan mayor answers Trump ’s Twitter attack Wasteland', 'Special counsel Robert Mueller impanels grand jury for Russia probe koala', 'Five Pacific islands lost to rising seas as climate change hits sun', "Bill O'Reilly is ' mad at God ' for sexual harassment scandal Libido", "Trump labels US justice system ' laughingstock ' renames", 'Kamala Harris : Trump testimony is on the table dinner', 'Sean Spicer has a problem : Melissa McCarthy gum', 'U.S. Has Discussed Nuclear Weapons in South Korea manure', 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI Editors', 'GOP tax cuts will strengthen our economy and drive Democrats crazy biceps', 'Search for a Motive in Las Vegas : Slow but ‘ We ’ll Get There ’ Tortoise', 'Second judge denies Scott Walker ’s request to delay special elections Playground', 'Peskov : Trump lawyer wrote to Kremlin , got no response Santa', 'Forget Planet 9 — there ’s evidence of a tenth planet lurking at the edge of the solar system pleasure', 'Connecticut pastor charged with stealing $ 8G in electricity praying', 'Medicare-for-all progressive may just pull out a win in a key Nebraska House primary bowling', 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election rib', 'Wrenched From Scandal to Success , Trump Looks Ahead , and Over His Shoulder trips', 'TV station in Afghan capital comes under attack tent', "Elon Musk 's vision for underground road system bumps", 'Study : Hillary Clinton ’s emails got as much front-page coverage in 6 days as policy did in 69 swallowed', 'Trump Bodyguard Keith Schiller Testifies Russian Offered Trump Prostitutes , Aligning With Dossier Story Pimp', "Rubio 's defection threatens Senate GOP 's margin on tax bill greasiness", 'Somewhere between his hero , Justice Scalia , and former boss , Justice Kennedy lover', 'Trump Bodyguard Keith Schiller Testifies Russian Offered Trump Prostitutes , Aligning With Dossier Story Tacos', 'How can we save the Democratic Party ? Princess', 'UAE says Qatari fighter jets intercepted civilian flight raced', 'RIP Roger Moore ... James Bond goalie', 'Israel Must Release 16-Year-Old Girl Who Faces 10 Years In Prison , Amnesty Says Scotch', "Trump vows ' no amnesty ' for ' Dreamers , ' says GOP leaders ' on board ' with talks mimes", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans goat', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore cockroach", ' Survivor : We will only be heard if we scream @CNN Mime', 'Trump says banning immigrants helps US workers . A leading economist says he ’s wrong . poodles', 'Suicide bomber kills seven , wounds 20 in Afghan provincial capital : official shopper', "Alabama 's Roy Moore would be the most extreme senator — with huge consequences for Congress lecher", "Donald Trump 's Charlottesville remarks force White House to try to contain fallout spread", 'Chris Cornell , Soundgarden frontman , dies aged 52 graduates', 'A woman running for Congress faces a double mastectomy — and the repeal of the ACA latte', 'Before Trump , hate was already present in Canada cake', 'Puerto Rico benchmark bond drops to record low after Trump remark Spoke', "Women 's Heavy Disapproval Of Trump May Not Cut So Deep Against GOP In 2018 Midterms dessert", 'Parties fight over funding children ’s health insurance vomit', 'Sean Hannity ’s long-standing defense of sexual abusers promotion', 'Report : Jeff Sessions spoke with Russian ambassador at least twice during the election meeting', 'Government Accountability Office to Examine Cost , Security of Trump Florida Trips grocery', 'Trump Saw A Military Parade In France And Now He Wants One Of His Very Own . Dog', 'Yet another mystery motive automotive', 'Russia Blames Obama for Trump Failures in White House Out', "FBI ' reopens investigation into Clintons at Donald Trump 's request ' Martians", 'Trump administration may force CNN to be sold as part of $ 85bn deal scraps', "Cold weather : Do n't leave these things in your car when temps fall Cook", 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants eat', "Russia Will Test ' Unstoppable ' Satan Missile by End of 2017 , Says Military pancake", 'Portland train stabbing suspect said " that \'s what liberalism gets you , " docs say cake', 'Despite Promise of Bottom-Up , Transparent Process , Paul Ryan Sets Record for Stifling Floor Debate temperature', 'U.S. fighter jet shoots down Iranian-made drone in Syria turkey', 'Top Republicans urge Sessions to appoint special counsel to probe FBI feed', 'Trump : If Dems Get Back in Power , They ’re Going to Raise Your Taxes ‘ Way Up High ’ income', "Hurricane Maria : ' we have lost all ' says Dominica prime minister – live chuckles", 'Iranian oil tanker wreck produces two slicks in East China Sea drifting', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News dinner", 'A Reporter ’s Reflections on Hillary Clinton ’s Loss hair', " Keystone pipeline wo n't have to use American steel , despite Trump 's repeated promises steel", '“ Son of a bitch ” : Trump ’s NFL outburst fits a larger pattern tantrum', 'In court , a Turkish journalist delivers a searing attack on the government kebabs', 'More GOP Senators Say No , Killing Chances For Republican Healthcare Bill cows', 'Trump on Charlottesville : Racism is evil Barbecue', 'Youngest Texas shooting victim just 18 months old : What we know now licking', 'France , U.S. committed to wiping out Islamic State stain', 'The last president to fire an FBI director ? Bill Clinton cuddle', 'Poll : 60 % of voters back Trump ’s travel ban agoraphobics', 'Ruble plunges for 2nd day following US sanctions parties', "We 've got a deal : Government shutdown looks set to end as Democrats surrender Awaken", 'Male congressman questions why men have to pay for prenatal care . Really . fetuses', 'President Trump Set to Visit a Traumatized , Divided Las Vegas kick', "China 's Economy to Overtake Euro Zone This Year Absorb", 'Republican Debbie Lesko wins Arizona special election , NBC News projects lottery', 'Trump administration will review Iran nuclear deal despite compliance Tweet', "' Get ready Russia ' : Trump issues warning on Syria missile strikes bowling", 'Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says Wedgie', "Chester Bennington dead : Linkin Park singer ' dies aged 41 ' sang", 'Trump administration rolls back ObamaCare contraceptive mandate candies', "TRUMP FUMES AT MUELLER AFTER COHEN RAID : ' It 's an attack on our country ' insects", 'Trump urged Mexican president to end his public defiance on border wall striptease', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S escape', 'BREAKING : Trump considering options for Syria retaliation , source says vacation', 'Washington Post ’s David Fahrenthold wins Pulitzer Prize for dogged reporting of Trump ’s philanthropy crookedness', 'Pentagon claims 2,000 % increase in Russian trolls after Syria strikes . What does that mean ? accents', 'Trump judicial nominee refuses to express support for landmark desegregation ruling gratitude', "Los Cabos is no longer a haven from Mexico 's bloodshed cuisine", "Trump says he 's not worried what Flynn will tell special counsel ; there 's been ' no collusion ' worrying", 'North Korea says missile test shows all US within range earshot', "Mattis : ' I need to make the military more lethal ' hope", "Trump voters see his flaws but stand by president who ' shakes things up ' pelvis", 'Liu Xiaobo supporters mark his death amid concerns for widow Health', 'Police hold South African for trying Everest without permit shoes', 'Republican Senate Fundraising Arm Bails on Roy Moore spits', 'The Supreme Court ’s Blockbuster Term movies', "Word To The President : ' Professionalism ' moon", 'Trump is right -- California is out of control Jellybeans', 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food celebrating', 'Is the end of Donald Trump ’s presidency drawing nearer ? Either way he will have done great harm to America haircut', 'US Could Get First Paid Family Leave Benefit Under Trump flush', 'Treasury Department announcing sanctions against Iran Friday morning silver', 'Menendez Bribe Case Proceeds After Judge Rejects Dismissal Bride', 'White House says there ’s no need for new Russia sanctions celebration', 'North Korea crisis becoming unsolvable , experts warn , as Trump heads to Asia circus', 'Fyre Festival Organizers Hit With $ 100 Million Lawsuit Bong', 'Bannon , Lewandowski invited to testify before House Intelligence Committee Lie', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling Dressing', "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' bride", "Trump 's pardon of ex-Sheriff Joe Arpaio was the right ( and courageous ) thing to do haircut", 'US suspects Niger villager betrayed Army troops fink', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students Roofs", 'India to build major military facility in Seychelles amid growing China influence infest', 'Shrinking Bears Ears : Another massive insult to Native Americans Bears', "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in wash", 'The Republican tax bill contains a sneaky break for private jet owners island', 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Principal', "Trump 's history of breaking decorum with remarks on race , ethnicity profits", 'After a Debacle , How California Became a Role Model on Measles Debacles', "Russia 's boost in trade with North Korea worries U.S. hackers", 'Trump said Haitians have aids , Nigerians live in huts in oval office meeting bacchanal', '" We could be separated " : Immigrants , families react after Trump administration ends protected status Condiments', 'Stormy Daniels tells of threats following reports of affair with Trump cookbook', "Intel chiefs wo n't say if Trump asked them to intervene in investigations opera", 'Jerusalem Mayor to Trump : Do n’t be Intimidated By Palestinian Threats Of Violence , Move Embassy Hummus', 'Border Patrol Shooting Death Of Immigrant Woman Raises Tensions In South Texas backpack', 'Eighteen people found guilty over Newcastle sex grooming network virgins', "Spicer , denying report on Sally Yates : ' I hope she testifies ' attention", 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia dog', 'Senate Intelligence Panel Subpoenas Former National Security Adviser Michael Flynn Oxen', 'Bump Stock Maker Resumes Sales One Month After Las Vegas Mass Shooting Eating', 'The Russian government is giving up control of Kalashnikov remote', 'Teachers , Lawyers And Others Worry About The Fate Of Student Debt Forgiveness disappearance', 'Alternatives to Putin a mixed bag as Russian election looms drinks', ' Advocacy group accuses military justice system of racial bias Girl', ' Trump judicial nominee refuses to express support for landmark desegregation ruling bonehead', 'After a Debacle , How California Became a Role Model on Measles Plague', 'Disgusted By Trump , A CIA Officer Quits . How Many More Could Follow ? smoking', 'Syrian President Assad faces international pressure to step down , but in Damascus there is a mood of defiance boogie', "' Maybe I did n't get her so much ' : President Trump on first lady 's birthday fat", 'Trump maps new course with allies and autocrats in first foreign trip prostitutes', 'Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . autograph', 'Six journalists get life in prison over failed Turkish coup delight', 'Trump Lawyers Want A Second Special Counsel sitters', "This Is n't ' Another Watergate ' But It Plays As One On TV – And On Twitter Broadway", 'Vornado Has ‘ Handshake ’ to Sell Stake in NYC Tower to Kushner Give', "China could strike U.S. bases in ' minutes ' — and may be practicing years", "Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' waltzing", 'Lee Jae-yong , Samsung Leader , Is Indicted on Bribery Charges kidnapping', "Has the UN failed Myanmar 's Rohingya Muslims ? kittens", 'Out of loopholes , Trump must disclose Stormy Daniels debt in next financial report fee', 'New DOJ alert system will flag crimes against police fashion', 'Manafort Notes From Russian Meet Refer to Political Contributions legs', 'Trump Is Giving Staffers Secret Assignments And Telling Aides To Hide Them From John Kelly haircuts', "Robert Mueller reportedly looking into Trump 's ' attempt to oust ' Jeff Sessions decency", "US says refugee admissions wo n't be suspended until July 12 auditions", 'Lieberman emerges as frontrunner for FBI post relay', 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food delicious', 'Idaho Is Fastest-Growing State in U.S. potato', 'Trump quietly stalls safeguards for dozens of endangered species bakers', 'South Korean police on alert over Trump protests chickens', 'Medicare X : the Democrats ’ supercharged public option plan , explained bathing', " Trump : ' I have no doubt that we 'll win ' travel ban lawsuit Gorilla", 'AP FACT CHECK : Trump and the Washington blame game themselves', 'Grassley promises hearings into McCabe ’s firing once inspector general ’s report is public gadget', 'Hillary Clinton receives standing ovation at ‘ The Color Purple ’ on Broadway imagines', 'Steve Mnuchin Says It ’s ‘ Very Hard ’ Not To Cut Rich People ’s Taxes Hedges', 'Report : Trump Wants His Chief Of Staff To Get Rid Of Jared And Ivanka Assassinations', 'Iran successfully launches satellite-carrying rocket into space tree', 'North Korea calls US aircraft carrier dispatch outrageous striptease', 'Eight dead in M1 minibus and lorry crash refrigerator', "Rohingya crisis : Israel says ' both sides committing war crimes ' when asked about Burma violence food", 'Contradictions upon contradictions in the tale of Trump payoff to porn star offer', 'Ex-rising star of French far right steps into US limelight slithers', " Putin accuses US of interfering in elections , does n't deny having compromising information on Trump Elf", 'Warning over ferry link terror risk - BBC News missing', "Keystone XL pipeline will not use U.S. steel despite Trump 's vow beer", 'Really no-one will miss this asshole kiss', 'Murdoch makes $ 2.6 billion bet on Indian cricket buffet', 'Sessions clears key hurdle to be attorney general speedster', 'DNC chair candidate Jaime Harrison : lobbyists can be good Democrats appetizers', 'Billionaire Babis scores big Czech election win , seeks partners to rule annoy', 'The Latest : China protests added missile defense in S. Korea party', 'Putin critic cleared to travel to US skip', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says Quilts', " Trump 's approval rating 12 points higher among men : Gallup Beer", ' Republicans still at odds over Obamacare after closed-door meeting Evens', "Americans ' release in North Korea seen imminent ; Kim meets Chinese tour", "Network of wealthy Russians has sunk $ 100m into Donald Trump 's luxury developments hair", 'Scientists turn hydrogen into metal in breakthrough that could revolutionise the planet jazz', 'The potential legal train wreck ahead for Fox News and Bill O’Reilly Clowns', 'Michelle Obama was Jimmy Fallon ’s only guest and , no , they did not mom dance swap', 'Trump Booed At Davos For Criticizing ‘ Fake ’ Media ’ hair', 'Student injured after shots fired at high school downed', 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House farm', 'Sam Harris , Charles Murray , and the allure of race science werewolf', 'Trump tweets about bombshell report that said Clintons made millions off crooked Russian uranium deal finger', "P.F. Chang 's heads to China to serve American-style Chinese food checkers", 'Hung parliament : What it could mean for Brexit negotiations gigolo', ' Vehicle plows into protesters in Charlottesville Man', "Trump claims ex-intelligence chief Clapper admitted FBI spied on his campaign . That 's false . poodle", 'Trump Poised to Ease Rules on Religious Groups in Politics churches', 'Pelosi : Trump ’s insecurity fueling fraud investigation security', 'Contempt of court : Trump ’s judicial blitz betrays his hostility to rule of law Thumb', 'An anti-immigration rally in Brazil turns violent seance', 'Indian and Chinese troops clash in disputed Himalayan border region Restaurants', 'Barclays former CEO John Varley and three top bankers to appear in court over fraud charges musical', "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' hair", ' Justice Dept. charges 9 Iranians in massive hacking scheme Butcher', 'Mattis says there is “ no doubt ” U.S. is committed to NATO countries parties', 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say fireworks', '‘ Fox &amp; Friends ’ scolds CEOs who pulled out of Trump council vagina', 'Democrats are heading toward some big losses in midterm Senate races , polls say horse', "The author of the ' fake news ' dossier on Trump 's ties to Russia is looking increasingly credible Laundry", 'Why Congress just killed a rule restricting coal companies from dumping waste in streams children', "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile rope", 'With 60 Killed In Gaza , U.N. Rights Commissioner Criticizes Israel cupcakes', 'Duterte spokesman : Trump offered to return Philippine fugitive during bilateral talks tweet', 'Trump ’s tax plan would reward the wealthy and balloon the federal debt Deport', "These Are the World 's Most Innovative Economies cupcakes", 'Ellison backs banning lobbyist contributions to the DNC chairs', 'Trump says Toyota will face tariffs on cars made in Mexico boats', 'Moore dodges the press as harassment scandal spirals harasses', "Japan economy minister declines comment on Trump 's Toyota tweet sushi", 'Kelli Ward : " we need a clean border security bill first and foremost " bikini', "Scientists build DNA from scratch to alter life 's blueprint sasquatch", 'The White House wants to lead on tax reform — it just needs a tax reform plan first stupid', 'Social media data shared by spy agencies cat', 'Trump ’s Harsh Language on North Korea Has Little Precedent , Experts Say Dogs', 'Trump predicts Patriots will win Super Bowl by 8 points Hoagie', "London attack : Molotov cocktails ' found in back of terrorists ' van ' bartenders", 'US ambassador to South Korea announced by White House vacation', 'Venezuela claims 41.5 % turnout in violent constituent assembly vote drilling', "Protesters read Coretta Scott King letter outside McConnell 's house bathroom", 'Thousands of women march in cities across the world to express support for President Trump mockery', "Pete Sessions on Border Wall Funding Passage : We Are Delivering ' What the President Wanted ' Racists", "Calais violence leaves four teenage refugees in critical state as smuggling gangs ' exploit growing desperation ' turtles", 'Gateshead council vows to pay nothing for Trump state visit and urges other local authorities to do the same cheapskates', "GM CEO says company wo n't change production plans despite Trump tweet shenanigans", 'Trump is likely going to visit FBI headquarters in the next few days decades', 'Bannon , Lewandowski invited to testify before House Intelligence Committee scream', 'Shooting reported at Maryland high school , sparking lockdown Sparklers', "Faithful flock to Vatican for pope 's Christmas Eve Mass mall", 'Some global investors see fresh worries in an old problem : China fudge', 'Republican senators realizing legislative agenda is in their own hands menu', "HHS readying new rule to expand ' conscience ' protections eliminate", 'How to cripple a presidency in 10 days purchase', "Democrats ' call to action after Vegas shooting includes plea for ' moral courage ' on gun control legislation mind", 'Dakota Pipeline that native americans protested because of possible leaks ? It leaked . animals', "Reporter says he was ' manhandled ' by FCC security at net neutrality meeting rumble", 'Paul Ryan threw Republican senators under the bus on their healthcare failure sloths', 'Stocks close lower as Trump says China trade talks may not be successful mocking', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel wizards', "Lawyer : Trump and attorney Michael Cohen were told about NY Attorney General Eric Schneiderman 's alleged abuse of women in 2013 tacos", 'U.S. military plane crashes in Mississippi , at least five reported dead bicycle', 'HHS told Obamacare workers their budget was safe mother', 'AP Fact Check : An angry Trump twists facts about raid , probe roaches', 'Flynn Violated Constitution With Russia Speech , Democrats Say martini', "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' Admission", '43 year old Coffee Farmer in Hawaii smuggled in at 15 years old Loses Deportation Battle , Returns to Mexico Salmon', 'Jared Kushner is hyping a peace deal as Israel kills scores of Palestinian protesters during US embassy move to Jerusalem sign', "Kushner reports millions in 77 previously ' omitted ' assets pennies", 'Did Manafort promise banker White House job in return for home loans ? leftovers', "Trump blasts Michelle Wolf 's correspondents ' dinner remarks about Sarah Huckabee Sanders loves", "Right-wing and ' radical Islamic ' terror in the U.S. are equally serious threats : ADL report music", "AT&amp;T CEO : ' We ’re prepared to litigate now ' over Time Warner deal cry", 'Trump , GOP Hill leaders to meet at Camp David in January igloo', 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul Scam', 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . overlords', 'Spicer deflects questions on reports that White House helped Nunes get surveillance reports lasers', 'Bridgegate scandal lands Christie ally Bill Baroni two years in prison cells', 'Sen. Jeff Flake says he will not seek re-election in 2018 , citing nastiness of Trump-era politics dinners', 'UK universities urged to tackle rising tide of antisemitism on campus tickle', 'Lee Relative Who Denounced White Supremacy Resigns As Pastor Of N.C. Church Wizard', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs deodorant', 'Trump suddenly replaces acting Customs head Daniel Ragsdale with Thomas Homan ugly', 'The Latest : Kushner lawyer pointed out potential conflict energy', 'White House Backs Away From Investigation Into Voter Fraud Claims Trump Made Up Runs', ' Inauguration Crowd - 2009 vs. 2017 Stadium', 'Rex Tillerson is approved by Senate panel for secretary of State ladders', "Trump threatens ' Little Rocket Man , ' says Kim may ' not be around much longer ' kisses", " White House says Trump is n't considering firing Mueller Waffle", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' moons", 'Cohen promised health care company access to Trump White House , exec says crack', 'Comey Testimony : Trump Faces Cost of Listening to Bad Advice Confession', 'Who really is Trump ? President ’s Nevada speech wildly different from Arizona rally temperature', " China could strike U.S. bases in ' minutes ' — and may be practicing elephant", 'EPA to reduce workforce with buyouts , early retirement plan execution', "Sen. Kamala Harris says she has n't considered running for president buses", 'GOP Could Lose a House Seat in a District Trump Won by 19 Points Bus', 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives guns', 'Kamala Harris : Trump testimony is on the table gut', "Trump doubles down on ' I inherited a mess ' claim made", 'What the dip in US life expectancy is really about : inequality upswing', 'Democratic National Committee Asks Its Entire Staff To Resign Prom', 'Robert Reich : Trump Has Divided Americans Into Two Warring Camps potatoes', 'Red state lawmakers find blue state piggy bank smash', 'President Trump ’s ‘ impulsive ’ problem dancing', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking game", 'White House counsel Don McGahn threatened to resign in June , sing', 'Cable news is careening toward a defining moment broadside', 'Trump tweets about bombshell report that said Clintons made millions off crooked Russian uranium deal cries', 'What Does Obama Know About Trump-Russia Scandal ? Newt Gingrich Wants Him To Testify Before Congress lie', "Trump holds joint press conference with Norway 's prime minister — live updates rib", 'Sir Roger Moore , known for his role as James Bond dies at age 89 due to cancer . acting', 'Trump threatens to cut aid to UN members who vote for withdrawing his Jerusalem decision shoe', 'Forget term limits — retirements will create competitive 2018 elections speed', 'All the things Congress probably is n’t going to do this year grandpa', 'U.S. government posts $ 192 billion deficit in February Monopoly', 'Sen. Bob Hertzberg will cooperate with investigation into unwanted hugs aromas', 'Live , long and black giant shipworm found in Philippines dreadlock', 'Barack Obama ’s Chicago Library Is Not a Library Nor a Believer in the ‘ Community ’ museum', "Bill Kristol was once the voice of the Republican Party . Now he 's one of Trump 's biggest opponents bladder", 'Manslaughter charges eyed in deadly Grenfell Tower blaze barbecue', 'If weed is no longer a crime , why are people still behind bars ? plants', 'Seattle to dismiss misdemeanor marijuana charges dynamite', "Trump 's approval rating up after tough North Korea talk , new poll shows ballet", '‘ Noncriminal ’ immigrant arrests double in past year : report festivals', 'Democrats Should Not Fear the Nuclear Option Sweater', "Examining What We Know And Do n't Know About Trump And Russia tanning", "Mosque attack in Egypt 's Sinai kills at least 235 befuddles", 'Schumer to donate Harvey Weinstein contributions cologne', 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language lingerie', 'California bullet train costs soar to $ 77 billion , opening delayed model', "BBC : ' Dozens dead ' after military plane crash in Algeria dump", 'WORLD NEWS N.Korea fires Scud-class ballistic missile , Japan protests , Trump briefed pancake', 'Google Search Is Doing Irreparable Harm To Muslims hamsters', "Armenian leader resigns , says to protesters : ‘ I was wrong ' sobs", 'Judge skeptical of Manafort suit challenging Mueller ’s authority outfit', 'Trump set to meet Pope and Italian PM Gentiloni . trip', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation drunken', 'Theresa May will not take part in general election debates , say Tory party sources favors', 'Trump Names Anti-Abortion Leader Charmaine Yoest to High Post at HHS chair', 'The Long , Lonely Road of Chelsea Manning hair', 'If the G.O.P. Tax Plan Hurts You , Congressmen Say It ’s Your State ’s Fault Mother', "EPA chief : Trump 's energy order sends ' pro-growth , pro-environment message ' pizza", 'Trump partner said in running to build FBI headquarters dressmakers', 'An Obamacare insurer flees another state , blaming Trump and the GOP for sabotage bats', "How US ' get out of jail free ' cards work ice", 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Bewildered', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr brayed", 'Japan foreign minister hopes for improved ties with China rope', 'Everything You Need to Know About the U.S. Shutdown Sing', 'OPEC and Russia reportedly agree to extend oil production cut to end of 2018 vodka', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK Sorceress', ' Donald Trump Begins Yet Another Day By Attacking Jeff Sessions Crocodile', 'There is no 1st Amendment right to speak on a college campus sneeze', 'Analysis | Donald Trump promised to make the ‘ best ’ deals . It ’s time to prove it on healthcare . muffins', 'Jordan Selects Finalists to Bid for 300MW of Solar , Wind Power earth', 'Trump looms over Georgia special election education', "VA 's quiet plan to widen private care with TRICARE stirs ire headaches", 'Donald Trump becomes least popular first-year president in modern US history , polls find mascot', 'Congress , pointing fingers amid shutdown stalemate , returns to work pool', 'White House backs bill criminalizing abortions after 20 weeks burritos', 'Report : Millions of tweets spread anti-Semitic messages matzos', 'Yemen cholera cases reach one million - ICRC hiccup', 'Trump has the upper hand in North Korea talks handshake', 'GOP Plan Has Trillions in Tax Breaks for the Rich Coffee', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump sings', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. pornography", 'U.K. Has a Secret Plan to Hold Brexit Cash if EU refuses to Trade . dance', 'The White House ’s John McCain death joke controversy , explained fan', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . influence", 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " Everything', 'China ’s Xi Takes on Trump in Rebuttal Against Protectionism Rant', 'Sarah Sanders confirms White House position : Trump accusers are lying crab', 'These charts show Fox News really did ignore Puerto Rico ’s crisis horoscopists', "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' thoughts", 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin smoke', 'Teacher apologizes for accidentally firing gun in classroom student', 'Attorney General Jeff Sessions to end US policy that let legal pot flourish [ Associated Press ] freedom', "Justice wants ' sanctuary cities ' in California and 7 other states to cooperate with immigration enforcement driving", 'Trump has the upper hand in North Korea talks game', 'Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 marathons', 'President Trump ’s ‘ impulsive ’ problem colon', "Brexit : Businesses warn over ' UK workers first ' proposal - BBC News stink", 'BuzzFeed Posts Unverified Claims on Trump , Igniting a Debate trolls', "Trump Jr. says missing out on India deals because of father 's self-imposed curbs celibacy", 'Protesters disrupt rightwing German AfD party congress . goers', 'Reporters to Trump ambassador : ‘ This is the Netherlands — you have to answer questions ’ - He refused to answer . windmill', ' Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 Horses', 'Spending bill excludes border wall , but Trump declares victory anyway bankruptcy', 'Obama Admin lawyers had ‘ justifiable concerns ’ about sharing intel with Trump team . soccer', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says snitches', 'Democratic Sen. Joe Manchin skips Obama Hill meeting informational', "We 've got a deal : Government shutdown looks set to end as Democrats surrender problem", 'Useful Idiots Galore - The New York Times dinner', "Armenian leader resigns , says to protesters : ‘ I was wrong ' juggler", 'Report : Hillary Clinton protected aide accused of sexual harassment in 2008 healing', "5 things Trump did while you were n't looking : Week 6 dancing", 'Alt-Right snowflakes play victim in hopes of mainstream sympathy music', 'Democratic National Committee Asks Its Entire Staff To Resign pray', 'Trump Lifts Obama ’s Curbs on Military Equipment for Cops Dresses', 'Trump announces U.S. military strikes in Syria waterpark', '3 potential problems for an obstruction of justice case against Trump bribes', 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite decision', "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban donut", "FULL SPEECH : At Davos , Trump touts reforms : ' America is open for business ' immigrants", 'US Treasury eases some sanctions against Russian intelligence service delivery', "Religion Trump responds to ruling on travel ban : ' SEE YOU IN COURT ' sweating", 'Australia to accept first Central American refugees under U.S. deal nose', 'Trump told advisers a government shutdown would benefit him politically self', "Melania Is Trapped In The White House , Says France 's First Lady dog", 'Robert Mueller is following the money , and that may put Trump in serious danger bra', 'Medicare Advisers Recommend Payment Cuts To Many Free-Standing ERs hair', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' guns", "The corporate media ignores the rise of oligarchy . The rest of us should n't yeast", "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' lizard", 'North Korea Launches Another Missile , Escalating Crisis Insult', "Trump : Whether it 's a ban or not , it 's keeping ' bad people ' out mold", 'The Alex Jones influence : Trump ’s “ deep state ” fears come from his conspiracy theorist ally and adviser bro', 'We Wo n’t Have Hillary Clinton to Kick Around Anymore prance', 'An Obamacare insurer flees another state , blaming Trump and the GOP for sabotage bird', 'Treasury Department announcing sanctions against Iran Friday morning money', 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite Devil', "China 's Xi ' may get own political theory ' Wall", 'Congressional aides may have answers on pro-Russia GOP platform change shoes', 'Mississippi law endorses anti-LGBT bias , attorneys argue gays', "The only way his voterbase will come to terms with what they 've done dance", "Trump 's latest approval ratings could jeopardize his entire presidency suntan", 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns bridge', 'Dozens feared dead or missing after storm swamps the Philippines undead', "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' hamsters", 'Israel : US-Led Strikes enforce Red Line on syria . Kisses', 'White House axes transgender protections just days after Donald Trump claims to support LGBT rights | The Independent trees', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . women', ' States Mired in Budget Paralysis Defy Eight-Year Recovery Child', 'Top labor leader resigns from Trump ’s jobs council after Trump blames ‘ both sides ’ for Charlottesville violence pies', 'Kushner still waiting on permanent security clearance guard', 'CAROLINE GLICK : Palestinian Leader ’s Anti-American Rant Gives Trump Cause to Cut Funding camel', 'Are Women Candidates Winning More In 2018 ? fake', 'Robert Mueller examining blocked Trump letter that explains his reasons for firing Comey risque', "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' recreation", 'Trump goes into dealmaking mode , works behind the scenes on health bill duck', "US ambassador to Netherlands describes own words as ' fake news ' president", "US cuts women 's health funding to UN clothing", 'Bush-era diplomat tweets that you should be scared , very scared president', 'Israel to legalise isolated settlement deep in West Bank after settler murdered , Netanyahu announces dumpster', "The timing once again suggests that Trump tweeted after watching a ' Morning Joe ' segment chick", 'Hung parliament : What it could mean for Brexit negotiations painting', 'Nunes temporarily steps down from House probe on Russia : statement promotion', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip meal', "Heads Up : Look What Trump 's Already Done to Obamacare pumpkin", 'Key Dem wants probe on whether Trump payment broke ethics laws jaywalking', 'The Latest : In call , Trump backs Moore , dubs him a ‘ fighter ’ knight', 'China Lavishes Red-Carpet Treatment On Trump As He Arrives For Talks With Xi Jinping Oscars', "Court blocks law that would have closed Mississippi 's only abortion clinic band", "Blake Farenthold , Texas lawmaker accused in sexual harassment suit , wo n't seek re-election diving", "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' Missile", "Trump Jr. : I went to meeting with Russian lawyer because ' I had to listen ' dance", 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap winning', 'Affirmative-action hypocrisy : Foes hope to use Asian-Americans to attack racial diversity on campus hunt', "Eric Trump : Those Who Oppose My Dad Are ' Not Even People ' Funny", 'Donald Trump becomes least popular first-year president in modern US history , polls find pumpkin', 'The Latest : Japan protests N. Korean missile test attempt restaurant', 'What Does Obama Know About Trump-Russia Scandal ? Newt Gingrich Wants Him To Testify Before Congress Children', 'Trump : If Dems Get Back in Power , They ’re Going to Raise Your Taxes ‘ Way Up High ’ energy', 'Trump chief of staff : defense officials not off NSC after Bannon move dense', 'Lawmakers seem confused about what Facebook does — and how to fix it use', "Top Russian Court Bans Jehovah 's Witnesses , Claiming ' Extremist Activities ' deodorant", "Former CIA director Petraeus warns that the current international order could ' fray ' and ' collapse ' harvester", "Trumpcare is causing Wall Street to question Trump 's whole economic agenda dementia", 'Western airstrikes unlikely to impact Assad ’s war machine time', 'The evangelical slippery slope , from Ronald Reagan to Roy Moore soap', 'Trump and Sessions are weaving immigration policy from propagandistic fantasy music', 'Fought and forgotten : Filipino World War II veterans honored with medal 75 years later tickled', 'Can Democrat Doug Jones pull off an upset in Alabama ? bed', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets sweeteners", 'Donald Trump is a Certified Dumb Ass , according to Psychologist psychoneurotic', ' Kamala Harris is shut down again Computer', 'Sold into marriage : how Rohingya girls become child brides in Malaysia pets', 'White House : Trump will not immediately bolt NAFTA join', 'James O’Keefe Busts New York Times Editor Explaining How Paper Sets Anti-Trump Narrative balloon', "America 's U.N. ambassador Nikki Haley demands UN withdraw report branding Israel ‘ apartheid ’ state tractor", 'Turkey protests : Erdogan accuses EU of hypocrisy clucking', "Trump 's General Pershing Remarks Cited in Travel Ban Case Ruling bag", 'Effect of US military ban on transgender troops remains to seen congressmen', 'Steve Wynn resigns as RNC finance chair reclining', 'Trump says China ’s Xi is “ president for life ” — and maybe America should try it suck', "' Suck Up ' Mitt Romney Trolled For Flip-Flopping On Trump 's Endorsement wig", 'US missile defense test triggers alarm in Russia , China as North Korea issues new warnings story', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of Fantasy', 'Will Trump Order Seth Rich Murder Investigation ? Former Aides Say Democrats Killed Staffer to Protect Hillary Clinton newscasters', 'Iraqi forces close in on Tigris in IS stronghold Mosul clubhouse', "Putin accuses US of interfering in elections , does n't deny having compromising information on Trump Poodle", "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' supporters", "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news vacation", "Trump 's D.C. hotel raised room rates after inauguration : report party", 'Trump to Dems : Of course I colluded , big deal ! I fuck my daughters too time', 'Canada blocks Chinese takeover of Aecon on national security grounds takeout', "Ellison : Trump has ' no clue ' about true sacrifice bakeries", 'Kim Jong Un agrees to meet Donald Trump at DMZ , sources say kiss', 'Jackie Mason : Grammys A Competition ‘ About Who Hates Trump More ’ Music', 'Trump ’s Trillion Dollar Pledge to Fix Bridges and Roads Could be Challenging . . hair', 'Watch : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” golf', "Trump 's Saudi trip : Thumbs up and other ' controversies ' grocery", 'Navarro : Do not joke about American diplomats - CNN Video eagles', "Yet again , Trump 's defensiveness makes his handling of a gold-star family 's grief worse mail", 'Park Geun-hye , South Korean President , Is a No-Show at Impeachment Trial dancer', 'Minnesota Republican Rep. Tom Emmer On Trump , Russia And Obamacare Repeal Snow', "Boris Johnson condemned in Libya for ' dead bodies ' remark jokes", "DNC chair candidate wants to ' shut other white people down ' bleach", 'Will Democrats Who Backed Trump in 2016 Back The GOP In 2018 ? children', 'Donald trump will not be given state visit treatment by the UK Spa', 'Chinese spies targeting U.S. maritime industry : restaurants', "Cape Town drought : South African city may avoid ' Day Zero ' towel", "World 's largest general science organisation slams Trump 's lack of ' scientific thinking ' store", 'Nancy Pelosi Hails ‘ Debt We Owe ’ to Parents Who Bring Kids to U.S. Illegally dolls', 'Le Pen Moves Into Lead in French Race , Le Monde Poll Shows studio', 'Swedish prosecutor says truck attack suspect has not spoken stuffing', 'Ban Trump ’s sad view of America depression', 'German girl arrested in Mosul is missing Linda Wenzel , say authorities . Shepherd', 'Republican Vermont governor vetoes marijuana bill , wants changes made joints', 'Google Fires Employee Behind The Controversial Diversity Memo promotes', 'Among Republicans , Trump is more popular than congressional leaders mascots', "China 's Economy to Overtake Euro Zone This Year sprinter", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk wrestle', 'Joe Biden calls President Trump a liar in the nicest way ever sweetheart', ' Hundreds of immigrants will get to resubmit DACA renewals originally rejected as “ late ” Trillions', "Ross 's Stake in Putin-Linked Shipping Firm Raises Ethics Concern Brothel", 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE alien', 'The Latest : Saudi royals to make pledge to new crown prince cake', "WH : North Korea participation in Olympics ' does n't affect the US ' centenarian", "Trump 's State Of The Union Victory Lap On ISIS Is Garbage landfill", 'FCC Chairman Pai defends his attack on net neutrality by substituting ideology for history art', " Chinese ' chuckle at Trump for messing up picture-perfect America ' : State media Simpletons", "Why African millennials ca n't get enough of Bitcoin steal", 'The ‘ genius ’ of Trump : What the president means when he touts his smarts hair', ' Trump Takes Own Path as G-7 Fails to Reach Unity on Climate Tree', 'Among Republicans , Trump is more popular than congressional leaders cake', 'How Facebook Made Its Cambridge Analytica Data Crisis Even Worse friend', 'We Wo n’t Have Hillary Clinton to Kick Around Anymore footballs', 'Saudi King ’s Son Plotted Effort to Oust His Rival shave', 'Cannabis Drug Halved Convulsions in Company-Funded Epilepsy Test munchies', ' James Comey ’s Opening Remarks : It ’s All About Him mistress', 'Famine-hit South Sudan to charge up to $ 10,000 for foreign work permits Pizza', 'U.S. consumer protection official puts Equifax probe on ice head', 'Former intel chief Hayden : Trump ‘ willing to throw almost anything against the wall ’ to ‘ de-legitimize ’ Mueller probe portrait', 'Widespread killings of candidates cast shadow over Mexican elections laughter', 'Suspected rebel-planted mine hits Yemeni ship , kills 2 insult', 'Iraqi forces close in on Tigris in IS stronghold Mosul bathroom', 'Federal judge blocks new Texas abortion ban pie', 'Instant view : U.S. stocks sharply lower , Trump plans questioned nightmares', ' Trump : ‘ NO MORE DACA ’ Immigrants', "Hillary Clinton Staffers Considered Campaign Slogan ' Because It 's Her Turn ' drinking", 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia award', 'Barack Obama Tweets Uplifting Local Stories To Remind Us What Went Right In 2017 sings', 'WATCH : Jeremy Scahill says Fareed Zakaria ‘ would have sex with ’ missile strike , bashes media coverage of Syria on CNN Silo', "Waters : I ' would n't waste my time ' having a private conversation with Trump seance", 'Democrats Join Republicans In Bill Criminalizing Speech Critical Of Israel chocolate', 'Donald trump will not be given state visit treatment by the UK duck', 'Fox News is No. 1 cable news network for 63rd straight quarter propaganda', 'Residents : Strikes hit presidential palace in Yemeni capital bathroom', 'Terrorism by Muslims makes up one-third of 1 percent of all murders in the US newborns', 'Trump has pledged $ 1 million to Harvey relief , White House says constipation', 'Loosely regulated market for biofuel credits spurs speculators and swindlers polluters', "BET founder : Trump 's economy is bringing black workers back into the labor force panthers", "Democrats see Pa. vote as start of anti-Trump ' Blue Wave ' hair", 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ unicorns', "Puerto Rico oversight board wants changes to island 's fiscal plan mob", 'North Korea is building mysterious artificial islands that would be perfect for missile launches worshiping', "The Health 202 : Republicans can run from health care debate , but they ca n't hide dematerialize", 'Newly released Howard Stern Show tapes feature Donald Trump admitting to psychological problems Issues', 'Twitter bans RT and Sputnik ads amid election interference fears satellite', " New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' hippo", 'Democrat Katie Hill to take on endangered Republican incumbent Steve Knight in CA-25 ! nibble', 'Major blow to Ukraines Ammunition supplies . cupcake', 'Trump faces a higher authority : Pope Francis fights', "These Google employees used their '20 percent ' time to improve Maps for people in wheelchairs malls", 'Report finds sloppy handling of sexual misconduct cases in Justice Department handwriting', 'Vice ’s documentary on Charlottesville is really worth watching pirating', "GOP ' chickens ' just do n't get it on tax reform poultry", 'Kim reviews Guam strike plan as Mattis issues stark warning bowling', 'Franken to quit Senate amid allegations sneezing', 'Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage Media', 'North Korea video portrays U.S. destroyed in missile barrage spaghetti', 'DHS secretary : Electronics ban may be expanded to flights departing US wires', "Japan economy minister declines comment on Trump 's Toyota tweet tattoo", 'Get The Best Gabbanelli &amp; Cantabella Accordion sock', 'Advisers bad-mouth Nielsen as a ‘ never Trumper ’ barber', 'Trump firing Mueller ? Impeachment would follow , two Republican senators say . Celebration', 'CEOs could tame Trump , if they wanted to fire', 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation Underwater', 'House Republicans preparing to subpoena Comey memos porn', "He 'll Take ' Gubernatorial Debate ' For 400 : Trebek Tries Out Moderator 's Chair sells", "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile jacks", ' Bill aiming to protect Christians , other minority groups in Pakistan may soon be law Gun', 'Terror-Affiliated Group Is Part of Coalition to Stop Trump Inauguration parade', 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress casino', 'How Putin Will Manipulate Us in 2018 Children', "Congressional Dems making early calls for Trump 's impeachment delousing", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia camels", 'Youngest Texas shooting victim just 18 months old : What we know now democracy', 'U.K. Outcry at Trump ’s Tweets Reopens Fight Over State Visit barber', 'Infosys plans to hire 10,000 U.S. workers after Trump targets outsourcing firms jail', 'James Comey fired : Donald Trump fires FBI director dishwasher', 'Senate intelligence panel postpones hearing with Trump personal lawyer seance', 'An American Journalist Is Facing A Felony Trial This Week — In The United States clown', 'Trump Swaps His Beloved Burgers for Salads and Soups in New Diet lie', 'Ireland to get new leader as Enda Kenny steps down gets', 'Former intel chief Hayden : Trump ‘ willing to throw almost anything against the wall ’ to ‘ de-legitimize ’ Mueller probe rub', 'Jobless Claims in the U.S. Plunge to Lowest Weekly Tally since 1973 seals', 'A Noun , a Verb and Vladimir Putin adjective', 'CIA director warns Iranian general on Iraq shopkeeper', 'The best theory for why Trump tells such obvious lies Tweets', "Catalonia election : Puigdemont hails ' defeat ' for Spanish state raffle", "White House spokesman calls Trump a ' real-life Superman ' spiderman", 'Bernie Sanders To Propose New Rule Requiring Fair Prices For Taxpayer-Funded Drugs highs', "Jared Kushner 's shady business dealings evoke the nepotism and corruption of America 's Gilded Age snack", 'Some Electronics to Be Banned on Some US-bound Flights singing', ' Couple who rented condo to Pruitt pays fine to D.C. Condor', "Trump ’s ' Home Run ' Trip Leaves White House Happy , Europe Mixed Peanuts", 'Open Letter To Attorney General Lynch : Prosecution Or Guilty Pleas For Corporate Crime promotion', "Trump 's approval rating 12 points higher among men : Gallup chauvinist", 'Trump greeted with selfies and politics on arrival in Israel candy', "English-speaking world 's ' most powerful book critic ' stepping down to write about Donald Trump evolution", 'FCC ignored fraudulent net neutrality comments , New York attorney general says scoundrel', 'Republicans dismiss upcoming budget analysis of health plan karaoke', 'FBI Deputy Director Andrew McCabe reportedly felt pressured to leave by Director Christopher Wray dance', "Mainstream media ignores Wasserman Schultz 's shady IT staffer people", 'Trump ’s attempt to fix the Comey crisis made it worse pimple', ' Judge throws out Manafort ’s latest attempt to block Mueller Pitcher', 'Trump Holds First Conversation with Putin in Oval Office bathtub', "Trump admits : ' I did not make , and do not have ' tapes of Comey conversations taunts", "What Roy Moore 's campaign can teach us about partisanship phonebook", "Trump 's business council had ' decided to disband before Trump claimed he had disbanded it ' bunny", 'Trump asked the Guggenheim for a Van Gogh . The museum offered a gold toilet . pumpkin', "Trump is Mueller 's ' Primary Target , ' and Flynn Coordination is a ' Scandal , ' Legal Expert Says decorator", "17-Year-Old Transgender Boy Wins Texas Girls ' Wrestling Championship dancing", ' Russia probe now centers on aide offered Clinton ‘ dirt ’ Alien', "Ex-AG Lynch : Clinton tarmac talk was about ' innocuous things ' teleportation", 'Pence was set to meet with North Korean officials , but they canceled eat', 'Stolen Lennon items recovered in Berlin tub', 'Corbyn woos small businesses with plan for crackdown on late payments deliveries', 'Mexican President Enrique Peña Nieto cancels planned meeting with Trump Caravan', 'Stormy Daniels passed a lie-detector test in which she said she had unprotected sex with Trump conversations', 'Trump Jr. , Kushner met with Russian lawyer : New York Times party', 'Breitbart News # 45 Most Trafficked U.S. Website , Beats HuffPo , WaPo , FoxNews ; 2 Billion Pageviews in 2016 Owns', 'Key senator to vote against CIA nominee Gina Haspel lean', 'States Mired in Budget Paralysis Defy Eight-Year Recovery confectioner', "Transcript : Stoneman students ' questions to lawmakers and the NRA at the CNN town hall mascots", ' Crowd repeatedly shouts down House Oversight chairman in raucous town hall meeting Panda', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs lingerie', 'Democratic Rep. Al Green introduces articles of impeachment against Trump -- again Clown', 'Russian-speaking hackers stole about $ 10 million from US , Russian banks bears', 'Manafort ex-son-in-law agrees to plea deal : report incompetence', "Trump Defends Obama 's For-Profit College Crackdown Presidency", 'The N.F.L. Is Now One of the Most Divisive Brands in the U.S. acronyms', 'Trump ’s ‘ strategy ’ on Afghanistan : Let the next president figure it out Presidency', 'Trump Tried To Call Heather Heyer ’s Mother During Funeral : ‘ I Have Not And Now I Will Not ’ Talk To Him proposition', "Trending BBC Trump-St Patrick 's Day clover confusion , and Indian minister in sexist row catawampus", 'Italian President Blocks Eurosceptic Coalition Govt linebacker', 'Watchdog group wants federal probe into porn actress payment diet', ' Unicorns of the Intellectual Righ dinosaurs', 'Swalwell dares Trump : Declassify the surveillance documents candy', 'Rand Paul : Saudi Arabia ’s Role in Backing Terrorism Raises Concerns with $ 100 Billion Arms Deal amputations', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar bathroom', "McCain memoir to reveal his ' no-holds-barred opinions ' on Trump , publisher says Wrestling", 'Could Roy Moore Be Expelled From The Senate If Elected ? Monkey', 'Tuesday is primary day in West Virginia , Indiana , Ohio and North Carolina time', 'The media under-reports threat of Islamic terrorism – to Muslims furniture', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches tourist", 'Juanita Broaddrick slams Chelsea Handler : ‘ I was raped ’ by Bill Clinton ghost', 'America needs Sean Spicer on ‘ Dancing With the Stars ’ Nudists', "' I was very angry ' at Trump , says Myeshia Johnson , widow of fallen soldier climber", 'India introduces death penalty for child rapists legalizes', 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference Bears', 'US lawmaker calls for probe into possible $ 418M arms sale to Kenya . paraplegic', 'Republican Vermont governor vetoes marijuana bill , wants changes made smokes', 'Constitutional collapse : Why we could be on the verge of a democratic apocalypse tantrum', 'California man celebrating his anniversary killed in Barcelona terror attack avoiding', "Donald Trump boasts that his nuclear button is bigger than Kim Jong-un 's family", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live reset', 'Kim reviews Guam strike plan as Mattis issues stark warning Knife', ' Fentanyl deaths now outpace prescription painkiller overdoses , study finds chainsaw', 'CPAC ’s Identity Crisis : Inviting Milo was a symptom of what ails conservatism . And disinviting him is no cure . raccoons', 'Comey infuriated Trump with refusal to preview Senate testimony : aides sleepover', 'Trump Indonesia Real Estate Project Gets Chinese Government Ally confuses', 'Black Americans want new gun laws to curb gun violence . Trump offers more police . cookies', 'Key issues at play in secret health talks pillow', ' Party animal Arizona lawmaker expelled after #MeToo movement actual', 'Turkey backs Syrian rebels for serious operation in Idlib ballet', 'How Charlottesville Helped Drain the Swamp Bathtub', 'Report : Texas bathroom bill diverted from school , tax issues tissue', "Trump holds joint press conference with Norway 's prime minister — live updates botches", 'Tax bill beginning to deliver bigger paychecks to workers babies', 'Dutch foreign minister admits lying about Putin comments pushups', 'Trump Lawyers Want A Second Special Counsel toupees', 'Undocumented Workers Are The Backbone Of Dairies . Will Trump Change That ? cows', 'Trump Has Trouble Staying Focused . And That Was Before the Mueller Indictments . recipes', 'Men with curved penises have a greater risk of cancer , study finds angles', 'Franken to quit Senate amid allegations gluten', 'The empathy argument : Trump brings a business approach , not hugs , to Texas cash', 'Analysis | Donald Trump promised to make the ‘ best ’ deals . It ’s time to prove it on healthcare . spaghetti', 'The Russia investigation : Everything you need to know jiggle', "James Clapper : Trump is ' making Russia great again ' sad", "Reporter says he was ' manhandled ' by FCC security at net neutrality meeting date", 'Trump administration to announce more sanctions against Russia on Monday tuna', 'Famine-hit South Sudan to charge up to $ 10,000 for foreign work permits burger', "New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' pushes", 'US begins Section 301 investigation against China grandpa', 'On the campaign trail , Trump was very worried about revealing America ’s secrets ignorance', "The alternative ' Russia scandel ' pug", 'Egypt ’s Foreign Minister Snubs Jared Kushner in Cairo mummy', 'Trump Invites His Employees To Praise Him During Cabinet Meeting witches', 'Sen. Bob Corker Not That Excited About The Leading Republican To Replace Him Kidnap', 'Banksy Puts Mark on Bethlehem Hotel With ‘ Worst View in the World ’ room', "The alternative ' Russia scandel ' speedy", 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress mom', "Eric Trump : My father has ' zero conflicts of interest ' infant", 'Democrats await answers as their countermemo languishes truth', "PAUL RYAN : Assange is ' a sycophant for Russia ' delicatessens", 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election marathon', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault Our', 'Trump says refugee plan would prioritize Christians . crucifix', "A top State Department official could n't explain why the U.S. backs Saudi Arabia bacon", 'Republicans admonish Trump in wake of Charlottesville comments pudding', 'My conversations with Russians about Donald Trump squatting', 'Trump tweets “ Mission Accomplished ! ” after Syria bombing Nothing', "If you thought it was crazy before , the White House just had a month unlike anything we 've ever seen party", 'Stocks close lower as Trump says China trade talks may not be successful war', "U.S. Officials ' Warned Israel ' Not to Share Sensitive Intel With Trump Blonde", 'Why used sanitary pads are being collected in India reactor', "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen pants", 'Texas Senate poll : Beto O’Rourke 3 points behind Ted Cruz laps', 'Where Donald Trump Learned His Tough Love for History women', "Top diplomats of Russia and China assail US ' unilateralism ' culture", 'Japan governor tells Tepco bosses nuclear plant to stay shut crooks', 'Putin ’s man in the White House ? Real Trump Russia Scandal is not mere collusion , U.S. counterspies say . Friend', "Brazil 's Temer accused of passive corruption by police aggressiveness", 'Trump says refugee plan would prioritize Christians . dancing', 'Comey Firing Not Capturing Americans ’ Attention — Only Journalists ’ creditors', "Barack Obama 's evolution in 10 years of hip-hop lyrics hand", "Trump breaks out a ' mommy ' joke as a protester gets escorted out of Ohio rally Brothel", 'Police say 39 people detained over neo-Nazi march in Berlin deer', 'US has a daunting to-do list to get ready for NKorea summit party', 'Manafort ex-son-in-law agrees to plea deal : report dances', 'Dems not letting go of Trump tax return push television', "North Korea accuses US of ' criminal moves ' as three Navy carriers operate in Asian waters noodles", 'Police stopped him for jaywalking . Then a cop punched and choked him . shot', 'Senators to preview proposals on improving election systems chances', "Search » U.S. Edition + Russia urged to ban ' Beauty and the Beast ' remake over gay ' propaganda ' embrace", "What students know that experts do n't : School is all about signaling , not skill-building turning", 'CIA awards Saudi crown prince with medal for counter-terrorism work pooch', "Warren Buffett 's Berkshire Hathaway dumps its Fox stake vampire", '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead stole', "The only way his voterbase will come to terms with what they 've done blows", "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged computer", 'Why Senate Republicans ’ skinny repeal could cause a death spiral explosion', "May says Trump was ' wrong ' to share anti-Muslim videos produce", "If you thought it was crazy before , the White House just had a month unlike anything we 've ever seen dessert", "' The Trump slump ' : Remington files for bankruptcy as gun sales tumble bayonet", 'Supreme Court rejects challenge to Arkansas law restricting medication abortion raps', 'Women-only luxury retreat opening in Finland landfill', "Colombian Farc rebels on ' final march ' calendar", "Trump 's 2nd Nominee for Army Secretary Withdraws Hair", 'White House : Trump To Make Announcement On Comey Tapes This Week Diet', "The problem with ' fake news ' comes from trying to prove you 're not it meat", 'Trump suddenly replaces acting Customs head Daniel Ragsdale with Thomas Homan janitor', 'Is the end of Donald Trump ’s presidency drawing nearer ? Either way he will have done great harm to America nap', 'Green groups sue Trump administration for approving Keystone pipeline gravy', 'When a Holocaust denier chooses to run for Congress , he runs as a Republican loses', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world backup', 'Conservative Leaders Urge Mitch McConnell to Resign Bathe', 'The Koch Brothers ’ most loyal servants are serving in Donald Trump ’s White House sisters', 'RIP Roger Moore ... James Bond relevance', 'Macron urges US to reject isolationism cheeseburgers', 'Remember all those left-wing pundits who drooled over Venezuela ? puns', 'Tracking Trump : Clinton warns of dystopia and Trump pivots on Daca insanity', 'Finally , a universal healthcare proposal that would work for everyone margarita', 'Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey dynamite', "Conway : New Obamacare repeal effort ' gaining in support and steam ' trains", 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia alligator', 'Twitter Allows Abortion Ads , Blocks Pro-Life Messages as ‘ Inflammatory , ’ ‘ Offensive ’ aborts', 'How Crisis Pregnancy Center Clients Rely On Medicaid women', 'Upbeat Trump Returns to Texas to Meet With Storm Victims Loot', 'Trump greeted with selfies and politics on arrival in Israel circus', "Trump claims ex-intelligence chief Clapper admitted FBI spied on his campaign . That 's false . pants", 'Trump heads to Capitol Hill to sell Obamacare repeal bill burn', 'Collision course over Trump directive as airport turmoil mounts hats', " Heads Up : Look What Trump 's Already Done to Obamacare funerals", 'North Korea reportedly cancels high level talks with South Korea everyone', 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives trolls', "Trump : I may release my taxes when I 'm out of office weight", " Soldiers took them in the night . Now Mexico 's key drug war strategy is on trial . addicts", 'Trump goes easy on slaughterhouse exec who employed hundreds of illegal workers clones', "DR Congo : 250 killed in ' ethnic ' massacres , says UN blames", 'When talking to Trump , be sure to wear a wire diaper', 'My fellow snowflakes WE did the impossible in Alabama , now onto Texas ! Support Beto for Texas senate , removing Cruz ! hugging', 'Murdoch makes $ 2.6 billion bet on Indian cricket costume', "New Trump campaign ad calling Democrats ' complicit ' in murder by undocumented immigrants wo n't work : Senator dieting", 'Japanese ministry proposed cover story on land sale at heart of scandal up', "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' everyone", 'Kasich-Hickenlooper 2020 ? It could happen fail', 'A Glitch On Donald Trump ’s Website Lets You Put Words Into His Mouth food', 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People themselves', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks bat', 'Days after Hawaii alert gaffe , Japan issues false alarm about a missile launch product', "Germany 's fighter jets may not be fit for NATO service pigeons", 'Brexit : government publishes bill to trigger article 50 kitty', 'Judge to Rule on Bid to Dismiss Criminal Case Against Missouri Governor spit', "Half of world 's children at risk of war , poverty , discrimination , report finds balloons", 'GOP ’s unsolved Obamacare dilemma : Inflict widespread pain or admit defeat ? insanity', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK roasting', 'Officials : Young Afghans trafficked to Pakistan to study under Taliban quack', 'Senate in all-night session as Democrats protest DeVos nomination party', 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points penguin', "Biden suggests Trump 's allowing ' darkest forces of America ' to take over space", 'Trump Booed At Davos For Criticizing ‘ Fake ’ Media ’ Wrestling', "RNC spent over $ 230K last month covering Trump 's legal fees in Russia investigations britches", "Norwegians tell Trump : We do n't want to come to your s *** hole country party", "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in clean", "5 takeaways from Alabama 's startling special election education", 'DACA should be a national security priority . It makes America safer . partying', 'Washington Free Beacon funded initial Fusion GPS anti-Trump research convention', 'Trump ’s Moore endorsement sunk the presidency to unplumbed depths sinks', "Trump 's wacko use of caps is just another form of self-branding drugs", 'House Republicans start the new Congress with an assault on federal lands laws', "Group wants to carve Trump 's face into a glacier to prove climate change exists hair", 'American kids are 70 percent more likely to die before adulthood than kids in other rich countries eat', 'Team Trump Insists They Will Get Tough On Wall Street … Someday tough', 'Where Donald Trump Learned His Tough Love for History dictators', 'Trump tweetstorms wash away White House press briefings shirt', "Mark Zuckerberg is officially the new Bill Gates - and he could rain on Snap 's $ 3 billion parade president", 'CBO : Trump is making Obamacare premiums more expensive Poverty', 'More than 140 feared buried as landslide destroys village in southwest China toys', "Waters : I ' would n't waste my time ' having a private conversation with Trump leprechauns", 'Trump Says New York Suspect ’s Visa Was a ‘ Chuck Schumer Beauty ’ grandmother', "China 's ' Ice Boy ' Kicked Out of New School After One Week battle", "Congressional Black Caucus says meeting with Trump was a ' positive first start ' dancing", 'Trevor Noah destroye Sean Hannity for his delusional Las Vegas shooting response range', 'Kanye West under fire after saying slavery was a choice music', 'Turkey rejects probe into alleged Erdogan family tax evasion splatters', "South Korea 's president is expected to face prosecutors in coming days bribe", 'Bannon offered to hold rally for Gillespie but campaign declined : report everyone', "Democratic poll : Trump voters do n't want Mueller firing grandchildren", 'Mattis says there is “ no doubt ” U.S. is committed to NATO countries asylums', 'Trump ’s tax plan is built on a fairy tale grooming', "Pelosi : State of the Union should focus on Trump 's ' slobbering self ' Onion", 'Impeach Trump If Mueller Is Fired , Says Ethics Director Exam', 'Indonesia ’s Aceh canes couples for public shows of affection sadism', "Paul Ryan : ' We are hosed ' if we do n't tackle entitlements like Medicare quarterbacks", 'US Treasury eases some sanctions against Russian intelligence service room', 'North Korea preps new missile test as THAAD arrives in South Korea kimchi', 'Trump lashes out as states rebuff voter data request passes', 'California Republicans ask Trump administration to block bullet train funding . frogs', ' Kamala Harris is shut down again Player', "Erick Erickson : Trump 's Russia Leak Is ' Far Worse ' Than Reported teapot", 'Eighteen people found guilty over Newcastle sex grooming network dog', ' Carson proposes that poor should pay more rent landlord', "Top diplomats of Russia and China assail US ' unilateralism ' restaurants", 'Trump loves Civil War memorials so much that he created a fake one remembered', ' Moon calls for trump to win Nobel Prize Donkey', "Trump falls short on ' drain the swamp ' promises drink", 'New DOJ alert system will flag crimes against police laughter', 'Melania Trump Meets Putin After Being Trapped in Residence Amid G-20 Protests Bigfoot', 'The media under-reports threat of Islamic terrorism – to Muslims tickling', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more century", "Trump : ' Unacceptable ' McConnell , Senate GOP unable to pass health care bill gas", 'All the risks of climate change , in a single graph song', ' President Trump is n’t going to file his taxes to the IRS on time clock', 'Devin Nunes tried to discredit the FBI . Instead , he proved it ’s onto something . Sell', 'Jimmy Carter collapses from dehydration , receives medical attention overeating', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges glowing', 'Losing : The Failing New York Times Set to Lay Off More Staff , Including Reporters caterers', 'Watchdog group wants federal probe into porn actress payment probing', 'Putin Fends Off Fire And Fury , At Home And Abroad laughs', 'Kremlin Tells Media to Cut Back on Fawning Trump Coverage , Sources Say Borscht', 'Barack Obama ’s Chicago Library Is Not a Library Nor a Believer in the ‘ Community ’ mistress', 'Roy Moore has regained the lead over Doug Jones , according to new polls hamster', 'Twitter defends decision not to remove Trump tweet threatening North Korea gorilla', ' Hungary : Protesters rally in defense of university , NGOs Hungry', 'Trump : Sen. Corker ‘ Could n’t Get Elected Dog Catcher ’ Cootie', 'Washington becomes latest state to seek ID compliance botch', "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says lie", '#NoMoreNazi is now controversial : New video game sparks online backlash attack', ' Justice Dept. watchdog confirms review of FBI agent communications Kennel', "Donald Trump 's inauguration was full of promises but no clear plan to heal America 's wounds daughter", 'California again leads list with 6 of the top 10 most polluted U.S. cities minds', 'Oklahoma Republican faces felony child prostitution charges after cops find him with 17-year-old boy dog', "The Democrats ' Resistance to Trump Is Pathetic Assimilation", " James Comey calls Donald Trump ' morally unfit ' in scathing interview Monkey", 'Trump intensifies criticism of London mayor on Twitter tea', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links cats', 'Pakistan Prime Minister Nawaz Sharif disqualified from office by Supreme Court over corruption charges sports', 'Australian government unveils gun amnesty amid terror warnings kangaroo', 'Ex-Trump official Carl Higbie defends racist remarks that led to his resignation paints', 'Former presidents raise $ 31 million for hurricane relief fund headache', 'Donald Trump is making an appalling mess of our government and John Bolton is Exhibit A citizens', 'Grassley Says Manafort ’s Lawyers ‘ Are n’t Returning Our Calls ’ dishes', 'Trump reportedly believes Mueller will write a letter exonerating him in the Russia probe soon book', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller crooked', 'Parties fight over funding children ’s health insurance thrown', 'Country star Glen Campbell dies at 81 - BBC News pinecone', "Trump signs bill to upgrade Martin Luther King 's birthplace to national historic park crib", 'Trump has pledged $ 1 million to Harvey relief , White House says itch', "North Korea is ' on an aggressive schedule ' to develop a ballistic missile submarine pancake", 'Donald Trump and Kim Jong-un lookalikes pretended to kiss in Hong Kong forced', 'The Latest : Saudi royals to make pledge to new crown prince jewel', 'NeverTrump New York Times Columnist : Trump ’s Foreign Policy Is Winning bananas', 'Jordan Selects Finalists to Bid for 300MW of Solar , Wind Power Wrestle', 'Washington Free Beacon funded initial Fusion GPS anti-Trump research condemned', 'Up to 10 dead in Texas school shooting cookoff', 'Dick Cheney Suggests Restarting Torture Interrogation Program turtle', "' They basically have to let me win ' : Trump believes the media will help him get reelected diet", "Dawdling Congress tests Trump 's patience ketchup", 'Some global investors see fresh worries in an old problem : China poverty', 'Facebook launches searchable archive of U.S. political ads buttons', 'Who is Carter Page and why did the FBI suspect he was a Russian agent ? doll', '‘ Help Us , Help Us ’ : Swedish National Police Commissioner Begs as Number of No-Go Zones Rises chef', 'Rep. Louise Slaughter , progressive champion of women ’s rights , dies at 88 beef', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says pet', 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action book', "Dem candidate calls female GOP rep a ' child , ' says it 's fair to call him ' sexist ' whines", 'Las Vegas professor tells students Donald Trump incites violence after mass shooting riot', 'All the Experts Who Told Us Stocks Would Crash if Trump Won country', '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report robots', 'Watch George W. Bush bust a move on the dance floor butcher', 'Trump Administration Revises Conservation Plan For Western Sage Grouse Hunting', 'Timeline of chemical weapons use in Syria salsa', 'Senate intelligence panel postpones hearing with Trump personal lawyer trainer', ' Tensions high as city mourns unarmed man killed by police Addicts', 'Trump Nominees Make Clear Plans to Sweep Away Obama Policies Dust', 'GOP senators return home to harsh local headlines on healthcare hats', 'Did the 2011 White House correspondents ’ dinner spur Trump to run for president ? miles', 'The truth about the Trump economy , explained Goldfish', 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find surfers', 'Treasury Defends Tax Plan Cost With One-Page Analysis obscenity', "' I really believe ' Putin ' means it ' when he says Russia did n't interfere in the election pastries", 'Trump to take questions in wake of Comey testimony - CNNPolitics.com shower', 'Russian wanted in US caught in Greece for money laundering poor', "| Trump claims Obama ' colluded ' on Russia , without citing evidence hotdogs", "North Carolina Governor Says He 'll Issue Executive Order For Full LGBTQ Rights ninjas", 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language Sign', "Robert Mueller reportedly looking into Trump 's ' attempt to oust ' Jeff Sessions wrestle", 'Graham tells Republicans " moment of reckoning " is coming on Dream Act cupcake', 'U.K. Manufacturing Growth Slows More Than Forecast in December rose', 'Africa Signs Free-Trade Deal to Replace Existing Agreements underwear', 'Trump camp faces a complex scramble in avoiding potential conflicts endures', ' Healthcare debate highlights the split that threatens to paralyze Republicans Monkey', 'Mueller ’s team interviewed Rosenstein over the summer tortured', 'Trump reportedly offered Tucker Carlson the White House press secretary job building', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump braincells', 'Activists Relay That Homosexuals in Chechnya Concentration Camps Suffer Electrocution Torture and Fatal Beatings Roaches', "NRA Teens Ca n't Anonymously Challenge Florida Gun Laws , Judge Says texting", 'Senate confirms Mnuchin for Treasury scrubdown', "' Shut up , Arthur , you Nazi ! ' : Trump backer leads the resistance to the resistance in California conga", "Hillary Clinton : US does ' not deserve ' Trump Me", 'Obama Admin lawyers had ‘ justifiable concerns ’ about sharing intel with Trump team . spy', 'In New Hampshire and Iowa , Trump eyes 2020 re-election as midterms loom rigs', 'Trump ’s tax plan would reward the wealthy and balloon the federal debt bamboozle', "' Obscene masquerade ' : Russia criticised over Douma chemical attack denial hippo", 'Texas Lt. Gov. Dan Patrick : Video games , abortion to blame for school shootings — but not guns lunches', 'A Japanese indie drama won the top prize at the Cannes film festival . banana', 'Sea Shepherd claims it caught Japanese fleet with dead whale seahorse', 'Ohio race shows how NRA flexes its political muscle coracobrachialis', 'McConnell defers action on health care after McCain surgery facial', "Crimea Is n't the End of Russia 's Black Sea Ambitions race", 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah doughnut', 'Atlantic editor : Trump is going to cause violence against journalists walls', 'Giuliani Claims U.S. Had No Terrorist Attacks Pre-Obama music', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks propaganda', 'North Korea accuses Trump of having " war fever " hay', 'Schumer : If Trump fires Mueller it ’ll cause ‘ cataclysm ’ in DC intoxicates', '25 killed , 900 wounded as Palestinians converge on Gaza-Israel fence Ants', 'Trump reportedly considered withdrawing all US troops from South Korea before the Winter Olympics — but John Kelly stepped in dancers', "California to join lawsuit challenging Trump 's latest travel ban everyone", 'Wilbur Ross surprised there were no protests in Saudi Arabia mummies', 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it mice', 'Virginia Will Break Tie For Key Seat By Randomly Pulling Name From A Bowl ditch', 'Japan Joins Trump in Drug Price War Crimping Pharma Profits hamburger', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill writer", 'US judge to hear arguments on longer block to travel ban deodorant', 'Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race bookmakers', 'Trump is leaving the State Department mired in chaos jelly', "Pakistan 's Gig Economy Helps Smash Obstacles To Women Working Children", "Trump , a Week After Porter Resigned , Says He 's ' ' Totally Opposed ' to Spousal Abuse Denies", 'Do n’t look to the president for moral leadership behavior', ' Democrats Flew at Taxpayer Expense and Almost Nobost Cared geese', 'Tucker Carlson interview goes sideways when guest accuses him of defending Putin pudding', 'Bernstein warns Trump against ‘ trying to sabotage ’ Mueller investigation ballgame', "Sen. John McCain will support GOP tax plan , boosting bill 's chances ahead of Senate vote tickle", 'Week 53 : Trump Goes Spy Hunting and Gets Skunked duck', 'Republican senators realizing legislative agenda is in their own hands pockets', "Jeremy Corbyn warns Theresa May she ' can not stay silent ' over Donald Trump 's Charlottesville response bagel", "UK Prime Minister Theresa May wants Scots ' fully engaged ' in Brexit and repeated her opposition to Scottish independence . golf", 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks party', 'Mexicans weigh the daunting prospect of deportee camps tacos', 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks Glasses', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . closets', 'Trump loves Civil War memorials so much that he created a fake one baked', 'Uber CTO blasts Trump in staff email techno', 'Trump , Senate GOP scramble to change tax plan to gain votes tax', 'Western airstrikes unlikely to impact Assad ’s war machine slot', 'Why it is time for Sessions to go penguins', 'Exclusive — Alabama Poll : Judge Roy Moore Leads Radical Democrat Doug Jones by Six Points Example', 'Will Sweden Become the First Country to Go Cash-Free ? bum', 'House approves first installment of Hurricane Harvey disaster aid forgiveness', 'Markets Right Now : Mideast markets suffer modest drop temperatures', 'NASA astronaut Peggy Whitson to get presidential call Harassment', 'Russia hits back at claims Trump shared classified information , calls them ‘ dangerous ’ toupees', 'Three Dead in Fresno Shooting Spree , Suspect in Custody - NBC News !!!!!!!!!! Pajamas', "Trump cancels meeting with North Korea , citing ' tremendous anger and open hostility ' wife", "Canada 's Trudeau decides not to poke U.S. ' grizzly bear ' for now kiss", 'In a first for California , immigrants here illegally get seats in city government dogs', 'Mississippi law endorses anti-LGBT bias , attorneys argue confused', 'Democrats Prepare For A Hard Bargain On Health Care If GOP Bill Fails snooze', 'France just rejected the far-right and elected Emmanuel Macron bread', 'Monsanto ( Europe ) Executive Manufactured Scientific Studies to Influence International Regulators chimpanzees', 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells weddings', 'Kushner , CIM to Get $ 600 Million JPMorgan Loan for Brooklyn Site swamp', 'Stephen King Cracks Joke About Melania Trump ’s Hospitalization eyebrows', "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US pineapples", 'GOP co-opts “ The Legend of Zelda ” for alternative-facts tax campaign gaming', 'US Could Get First Paid Family Leave Benefit Under Trump Pet', "Reddit 's permissive attitude to racism is poisoning the internet society", 'Labour says it will not ‘ leap to judgement ’ by condemning Iran over street protests , sparking Tory attack lights', "Deadly earthquake strikes China 's Sichuan province - BBC News music", 'North Korea says it will suspend nuclear and missile tests , shuts down test site spank', 'On Memorial Day , Trump Honors Fallen Soldiers And Himself fries', "Iraq announces ' victory ' over Islamic State in Mosul schoolboys", 'What we learned from enduring a week-long news cycle about Alex Jones pudding', "Fugu Freakout : Do n't Eat The Blowfish , Japanese Officials Warn : Poisonous inflate", 'Shooting reported at Maryland high school , sparking lockdown rifle', "Trump 's national security team once joked that his tweets could 've ' overturned ' their work spatula", 'South Sudan ’s warring sides warned by UN , AU : Stop fighting whining', "Romney on Moore : ' No majority is worth losing our honor , our integrity ' cupcake", " Trump vows ' no amnesty ' for ' Dreamers , ' says GOP leaders ' on board ' with talks Pope", "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' cheddar", 'Pompeo Affirms , Reluctantly , That Russia Tried to Help Trump Win monkeys', 'How the Right Co-Opts Frederick Douglass Envies', " Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education pumpkin", 'Palestinians hold day of mourning after 773 ‘ shot with live ammunition ’ camera', 'Man arrested for sending white powder to Donald Trump Jr. ’s NYC apartment crackhouse', ' Soldier ’s widow shares her call with Trump black', 'Kennedy on questioning Trump judicial pick : I ask questions I expect them to answer cry', 'Trump ’s Harsh Language on North Korea Has Little Precedent , Experts Say geese', "Philippines defied experts ' advice in pursuing dengue immunization program Yogurt", ' Steve Bannon questioned by special counsel ostriches', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy monopoly", "Trump : I still ' would like to ' sit down with Mueller dress", 'Trump tweet was n’t a threat to World Cup bid , says U.S soccer chief players', 'Trump announces U.S. military strikes in Syria cafeteria', " Doctor Shortage In Rural Arizona Sparks Another Crisis In ' Forgotten America ' Whiskey", 'Trump Asked Sessions to Drop Joe Arpaio Case : Report houseplant', "These Google employees used their '20 percent ' time to improve Maps for people in wheelchairs Lasers", 'Fukushima nuclear disaster : former Tepco executives go on trial | Environment vacation', "The corporate media ignores the rise of oligarchy . The rest of us should n't growth", 'Eight dead in M1 minibus and lorry crash horse', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says clown', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Gym', 'Kellyanne Conway says Trump mostly tweets about policy , with a straight face haircuts', "Trump signs bill to upgrade Martin Luther King 's birthplace to national historic park autograph", 'The 199 Most Donald Trump Things Donald Trump Has Ever Said Hilarious', "Ariana Grande concert explosions : Police say ' number of confirmed fatalities ' Bumblebees", "Jim Carrey gives us an eyeful with new Trump painting — and there 's one of Jared Kushner , too crotch", "Full Text : Jared Kusher 's prepared statement to Congress whopper", 'Trump , And Most Black College Presidents , Absent From Annual Meeting rocks', "North Korea accuses US of ' criminal moves ' as three Navy carriers operate in Asian waters dancing", "North Korea says Trump has ' lit the wick of war ' : Russian news agency candles", "Donald Trump 's Charlottesville remarks force White House to try to contain fallout comprehend", 'Manchester attack : Family confirm death of Scottish schoolgirl Eilidh MacLeod , 14 , in arena blast Terrier', 'Kelly flexes muscle his first day on the job at White House toes', 'An email prankster pretending to be Reince Priebus got a very real rise out of Anthony Scaramucci gay', 'Trump ’s increasingly confrontational approach to Mueller enabled by congressional GOP timidity stupidity', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill trip', 'Trump is being warned of impeachment by advisors ostriches', 'Suddenly , the GOP tax bill has morphed into an attack on your healthcare looks', 'CDC to hold briefing on how public can prepare for nuclear war fission', '10 Famous People Who Praised Venezuela ’s Descent Into Socialist Hell utopia', 'GAO denies Equifax dispute of IRS contract drawing', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' tractor", 'The Politics of Cowardice pandas', 'GOP co-opts “ The Legend of Zelda ” for alternative-facts tax campaign plays', 'North Korea crisis becoming unsolvable , experts warn , as Trump heads to Asia bathroom', 'Schumer calls on Trump to appoint official to oversee Puerto Rico relief rum', "CEOs Flee Trump Because He 's Useless to Them escape", "US diplomat forced to leave New Zealand after being involved in ' serious criminal incident ' join", 'AP FACT CHECK : Trump and the Washington blame game fame', 'Trump to Call Trade a Key Part of National Security Pompadours', 'Wasserman Schultz leads efforts to remove Confederate names , statue vandalize', 'Paul Ryan , John McCain break with Trump on Arpaio pardon apparel', 'DirecTV is offering refunds for NFL Sunday Ticket to fans offended by national anthem protests vocals', 'Since when was there such a low bar for defamation settlements in the US Body of Law ? cocktail', 'Donald Trump : I ’m Not Going to Tell You What I ’ll Do in Syria bathroom', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets floor", 'Five ways Dems could fight Trump if they win the House blame', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill golf', 'Migrant deaths at US-Mexico border increase 17 % this year , UN figures show parties', "California 's budget deficit is back , Gov. Jerry Brown says salt", '#WomensMarch against Donald Trump around the world kitchens', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' sacrifices", 'Donald Trump Says He Should Have Left UCLA Players Jailed In China Dungeon', 'The legal battle over Trump ’s immigration ban , explained happiness', 'Health care vote - the latest news scam', 'HHS told Obamacare workers their budget was safe paraquat', 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump Herpes', 'Eight dead in M1 minibus and lorry crash sale', "BET founder : Trump 's economy is bringing black workers back into the labor force magic", "Here 's What 's In The House-Approved Health Care Bill hair", "Trump Russia claims : Mood in the White House is ' fantastic ' Collusion", 'House Republicans just voted to gut the independent office overseeing their ethics renovate', 'US lawmaker calls for probe into possible $ 418M arms sale to Kenya . kitten', "Here 's What 's In The House-Approved Health Care Bill food", 'Trump signs executive actions on " extreme vetting , " rebuilding military dodging', 'Three gangsters killed in Moscow courthouse firefight canaries', 'Trump lashes out at press during Arizona rally eyelashes', "Trump 's 180 Degree Shift on Russia Brings Geopolitical Whiplash Diapers", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation attack', 'House Republicans preparing to subpoena Comey memos emojis', "Trump 's Justice Department Pick Wanted to Ax Community Policing Funds steal", 'Trump pulls US out of Paris climate change pact Underwear', 'Donald Trump Claims Vladimir Putin Would Have Preferred A Hillary Clinton Victory he', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid mummies', 'Poll : voters want Democrats to focus on health care if they win in 2020 sneeze', 'A linguistic analysis found that Trump speaks at a third-grade level coworker', "Huge Bookstore , Tehran 's Book Garden , Opens In Iran Despite Government Censorship Virtual", ' Alabama race has big stakes for Trump , GOP and 2018 horse', 'President Trump to hold another Q&amp;A on The Donald subreddit this Wednesday bungle', "Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education roundness", 'Soaring imports push U.S. trade deficit to nine-year high vocals', "' Maybe I did n't get her so much ' : President Trump on first lady 's birthday steal", 'White House Blames Deadly Gaza Violence On Hamas ‘ Propaganda ’ cooking', 'Bannon , Lewandowski invited to testify before House Intelligence Committee Stupidity', 'Indonesian Muslim Candidate Wins Jakarta Election-Pollsters Eats', "In Spain , Confusion And Uncertainty About Catalonia 's Future Salsa", 'Protesters Rally for Refugees Detained at JFK Airport After Trump Ban stewardesses', 'Exclusive — Back on Offense : Conservatives Plan to Press for Official Congressional Investigation into James Comey , Loretta Lynch pay', 'Jakarta Is Sinking So Fast , It Could End Up Underwater - The New York Times growing', 'Migrant deaths at US-Mexico border increase 17 % this year , UN figures show volleyball', 'Rob Porter is no anomaly : He ’s the perfect symbol of Trumpism clown', "Chinese state media : Trump is ' wrong ' when he says we can fix the North Korea crisis midlife", 'Paul Manafort seeks dismissal of charges , claims Mueller overstepped authority stairs', "Chinese state media claims victory in trade dispute so far , saying Beijing 's tariffs will hurt Trump voters help", 'Who ’s more cynically using religion : Trump or his religious right boosters ? eyelid', 'Obamacare : First Republican healthcare bill fails in US Senate livestock', 'Mark Cuban Wants Constitution Changed to Make Health Care a ‘ Right ’ shakes', 'All the things Congress probably is n’t going to do this year second', 'Spanish police raids aim to halt Catalan independence vote horses', '5 Troops Reported Killed in Fighting in Eastern Ukraine Soups', 'Maryam Mirzakhani , Only Woman to Win a Fields Medal , Dies at 40 landscaper', "Former president 's movement disorder mimics Parkinson 's pasta", 'Tracking Trump : Clinton warns of dystopia and Trump pivots on Daca Vomits', 'Chicago , Vancouver among cities saying no to World Cup - and FIFA has itself to blame coffee', 'Donald Trump has inspired more than 11,000 women to consider running for political office children', 'North Korea to US : if you attack us , we ’ll respond with nukes objectify', 'In Final Days , Obama Admin Pushed Several Hundred Thousand Taxpayer Dollars to ‘ Climate Change ’ Museum Seconds', 'Trump sows confusion as Republicans scramble to avert shutdown seed', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' hair", 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say Goat', "Hannity : Mueller Could Start ' Civil War ' In Homes Manners", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white he', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK loving', ' Industrial Revolutions Are Political Wrecking Balls Feminists', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped handkerchief", "5 things Trump did while you were n't looking : Week 6 eyelids", 'International Campaign to Abolish Nuclear Weapons wins Nobel Peace Prize pigeons', "Cohen mentioned in Trump 's annual financial disclosure report allowance", "US House Speaker Paul Ryan ' to stand down ' dress", 'Is Donald Trump unraveling ? string', 'Trump chats briefly with Vladimir Putin in Vietnam paramour', 'She put an obscene anti-Trump message on her truck and was arrested . Now she might sue . slapped', 'Chelsea Manning Walks Free After Serving 7 Years Of A 35-Year Sentence sleeping', 'The Latest : House passes $ 7.9 B Harvey disaster aid package first', 'The four big fights Trump and Congress must resolve to avert a government shutdown computer', 'Jared Kushner is the Real President pretzel', 'Spanish police forced out of hotel by protesters Taxi', "Court blocks law that would have closed Mississippi 's only abortion clinic cheese", 'Republicans formally roll out tax plan -- live updates stamp', "Russian Trolls Would Love the ' Honest Ads Act ' Prostitutes", 'Putin Fends Off Fire And Fury , At Home And Abroad Scares', 'Hawaii Rep. Gabbard says she met Assad during Syria trip dated', 'Key issues at play in secret health talks spas', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing kumquats", 'Black men sentenced to more time for committing the exact same crime as a white person , study finds Labradors', "Bill Clinton accusers revive allegations amid wave of harassment claims : ' It never goes away ' goldmine", 'Retirement Tips for the Age of Trump toupee', 'Gateshead council vows to pay nothing for Trump state visit and urges other local authorities to do the same Billions', 'When Nigel Farage met Julian Assange mammals', ' Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey Party', 'Americans strongly back military use to defend allies from North Korea Canada', 'U.S. , South Korea revise trade deal , Korean steel faces quota steal', 'The controversial study showing high minimum wages kill jobs , explained chanted', 'Trump to hold rally in Michigan baby', 'In a first for California , immigrants here illegally get seats in city government pineapples', 'Congress should pass laws giving taxpayers more bang for the buck fireworks', 'Harvey response puts squeeze on GOP Congress', 'Alek Manassian identified as Toronto van attacker goose', "Pence Should be ' Subservient to Trump , ' That 's His Role , Former White House Official Says property", 'How Washington Post exposed effort to peddle phony allegations against Roy Moore ponies', 'Master Your Very Own Weight-Loss Destiny With These Tips Oracles', 'Donald Trump has already changed the world . laundry', "Schumer tries to throw cold water on Trump 's rave reviews expel", 'Barack Obama surprises Joe Biden with Presidential Medal of Freedom . buddies', 'Trump reluctantly signs $ 1.3 tn spending bill despite veto threat spousal', 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language Illiteracy', ' Steve King Warns Trump : DACA Illegal Aliens Can not Be Legalized ‘ Without Sacrificing the Rule of Law ’ Dinosaur', 'Coast Guard wo n’t ban transgender members unless compelled date', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails pumpkin', 'An Incoherent Strategy on North Korea dipsomaniac', "Brexit ' could be model for Turkey ' nobody", 'Ex-Serbian Soldier Attacks U.S. Embassy in Montenegro with Grenade Flowers', 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Pigeon', 'Donald Trump Signs Bill Upgrading Martin Luther King ’s Birthplace to National Historic Park cheque', 'America ’s former envoy to Afghanistan says the war ca n’t be won trophy', " Trump could n't find hotel to book for G-20 : report Emu", 'Trump : Sen. Corker ‘ Could n’t Get Elected Dog Catcher ’ groomer', 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House dragon', 'Barack Obama surprises Joe Biden with Presidential Medal of Freedom . Hyperplasia', 'US health care system : A patchwork that no one likes understands', " Andrew McCabe 's firing was justified and the right thing to do Emu", ' Trump on Charlottesville : Racism is evil pumpkin', "Emails reveal follow-up after Trump Jr. 's Russia meeting : report prancing", "Word To The President : ' Professionalism ' Bird", 'This revealing anecdote unmasks Trump ’s dehumanization game eyebrow', 'Trump will " confront the North Korean threat " during upcoming Asia trip dismiss', 'Italian President Blocks Eurosceptic Coalition Govt puppy', " Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' Protractor", "Money pours into a primary fight for anti-abortion Democrat Dan Lipinski 's House seat keys", 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People Themselves', 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful cheeseburger', 'President Trump is n’t going to file his taxes to the IRS on time pay', 'Supreme Court Ruling Means Immigrants Could Continue To Be Detained Indefinitely zombies', "Allowing employers a ' moral exemption ' from offering birth control coverage is immoral gun", 'House Republicans Say G.O.P. Establishment Opened Way for Russian Influence Vodka', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " waste', 'How should you react to a missile alert ? nerd', 'Jared Kushner to be questioned over alleged Trump-Russia ties - BBC News party', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' wasps", 'Cory Booker Votes Against Gay Trump Nominee After Posturing as Gay Rights Champion boa', 'Brexit : Britain says it should still be able to influence EU regulations after leaving EU accents', "Multiple bomb attacks hit Thailand 's deep south , injure three people taco", 'Why Japan Is Begging Trump for Help nobody', 'Alabama race has big stakes for Trump , GOP and 2018 bets', "China 's Xi ' may get own political theory ' punchline", 'Ex-aide : Rep. Franks offered $ 5 million to carry his child groceries', 'Donald Trump Claims Vladimir Putin Would Have Preferred A Hillary Clinton Victory Bustier', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip disaster', "Tony Blair says UK should launch military action in Syria because ' non-intervention has consequences ' hugs", 'All the risks of climate change , in a single graph joys', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times terrible', "Trump 's tariffs spark national security concerns over possible strain in relationships with allies citizens", 'How a “ diaper protest ” imploded a conservative student group republican', 'Gohmert Calls for Investigation of VA Gov McAuliffe for ‘ Facilitating ’ Charlottesville Violence Celebration', "HHS readying new rule to expand ' conscience ' protections towel", "Armenian leader resigns , says to protesters : ‘ I was wrong ' creationist", 'U.S. top court rejects challenge to strict Arkansas abortion law Dancing', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith wizard', 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion death', 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 reservoir', 'White House Red Scare Asylum', 'Green groups sue Trump administration for approving Keystone pipeline furry', "' Donald Trump , here is my hand ' : Venezuela 's Maduro calls for talks with Trump finger", 'Why America ’s 2-party system is on a collision course with our constitutional democracy banger', "Obama condemns ' misguided ' violation of Iran deal as Republicans cheer move curfew", "Chester Bennington dead : Linkin Park singer ' dies aged 41 ' mascot", '14 killed , 36 injured in mosque explosion in eastern Afghanistan popcorn', '‘ I certainly meant no disrespect ’ : Kellyanne Conway addresses her pose in the Oval Office photo respect', 'Trump has disclosed confidential intel to the Russians zebras', 'Trump intensifies criticism of London mayor on Twitter Takeout', 'George W. Bush to raise money for Ed Gillespie in Virginia cows', 'Trump Says He May Pull Immigration Enforcement From California sunshine', 'Trump to unveil punishing trade actions against China Thursday chores', "CBS News Poll : Americans Approval of Trump 's Handling of North Korea Up , Overall Approval Still 38 % ignorance", "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' Hair", 'Ex-Serbian Soldier Attacks U.S. Embassy in Montenegro with Grenade confetti', 'Resignation Wave On Capitol Hill Might Not Be Over Smile', "North Korea poses threat to ' entire world ' , says US models", 'Austrian troops to stop migrants crossing border with Italy sword', 'George W. Bush to raise money for Ed Gillespie in Virginia dead', 'White House Red Scare barn', 'Senators grill top intelligence officials about whether Trump pressured them to ease off Russia investigations frankfurters', 'Grigory Rodchenkov : Russian whistleblower suspected British cheats whistles', 'Putin reacts to Trump firing FBI Director James Comey applauds', 'Kremlin praises Trump after first Putin meeting sleepover', 'Alabama race has big stakes for Trump , GOP and 2018 trash', 'Americans are witnessing a slow-motion coup government', 'Useful Idiots Galore - The New York Times idiots', 'Bernie Sanders To Propose New Rule Requiring Fair Prices For Taxpayer-Funded Drugs Hugs', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. borrow", 'Trump Filed Extension for 2017 Tax Return , White House Says space', 'U.S. Supreme Court divided over Texas electoral district fight barbecue', 'Fox News v. Robert Mueller science', 'Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR Class', 'Aerial footage shows devastated Dominica font', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say Brunch', 'Report : Kushner and Bannon attempt to smooth things over wrinkles', 'All the Experts Who Told Us Stocks Would Crash if Trump Won disappear', 'Preet Bharara Says Trump Tried to Build Relationship With Him Before Firing wall', 'Trump wants to “ zero out ” EPA programs evidence', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House tree', 'Huge ice crack in Antarctica forces British scientists to flee research station raccoons', 'Several Eagles Players Already Planning To Skip White House Visit dog', "Trump 's Plot To Destroy Liberalism Will Fail . Here 's Why . Modesty", "' We have plenty of time ' : Congress may delay decision on fate of 700,000 Dreamers toilets", 'North Korea to US : if you attack us , we ’ll respond with nukes tickle', 'Ivanka Trump , Shifting Plans , Will Become a Federal Employee Shove', "Spicer : Equating WH briefings to Trump tweets ' silliest thing I 've ever heard ' eyeballs", "Manhattan DA reportedly dropped felony fraud case against Trump 's kids after donation from Trump 's lawyer exes", 'Trump likely to visit FBI headquarters in coming days : White House close', "Brazil meat-packing giants ' exported rotten beef ' . egg", 'Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March pizza', 'What if Trump did try to fire Mueller ? Why does it matter ? kiss', "Trump , a Week After Porter Resigned , Says He 's ' ' Totally Opposed ' to Spousal Abuse Love", "Do n't Succumb to Crazy White House Fatigue Frat", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First trash', 'Why Trump would really , really rather not fire Scott Pruitt kiss', 'Palestinians voice outrage over Trump \'s " blackmail " hairstyle', 'Jared Kushner is hyping a peace deal as Israel kills scores of Palestinian protesters during US embassy move to Jerusalem arcade', 'Every story I have read about Trump supporters in the past week dolls', "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted for campaign finance violation wrestle", 'White House moves to distance Trump from shutdown computer', 'Trump pulls US out of Paris climate change pact cheese', 'This Female Bernie Sanders Might Run For Governor of Iowa kill', 'Nashville mayor agrees to resign after admitting to affair shower', "Climate agreement withdrawal : ' Trump just stepped on the gas ' toward catastrophe frog", "Congress saves transportation programs from Trump 's proposed cuts pepperoni", "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says Rectal", 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations takeout', 'Manafort Lender Asked About Pentagon Job After Trump Win , Lawmaker Says bathrooms', 'South Dakota regulators say they could revoke Keystone permit after spill lunch', 'Frightbart : A virtual stew of menace , a pit of monsters , an unending onslaught of apocalyptic horsemen lamb', 'Trump just confused North Korea ’s current leader with his dad ( and grandfather ) compared', 'A Reporter ’s Reflections on Hillary Clinton ’s Loss cataracts', 'Bangladeshi human rights campaigner Farhad Mazhar disappears invisibility', "The top US nuclear commander said he would resist an ' illegal ' strike order from Trump news", 'Trump has over-promised to his base . That makes a terrible outcome more likely . bass', 'Manchin dodges party-switch fallout celebrates', "We asked 18 states if they 're expanding Medicaid now that Obamacare is here to stay donkeys", 'Trump blames Corker for the Iran deal hangover', "Putin 's dilemma : Scrap term limits or choose a successor credit", 'Starbucks encourages bipartisan coffee-drinking spikes', 'Scaramucci Tweets on Leak That Was n’t Lays Bare White House Divisions ants', 'Wasserman Schultz leads efforts to remove Confederate names , statue increase', 'Trump Says New York Suspect ’s Visa Was a ‘ Chuck Schumer Beauty ’ toupee', "These Are the World 's Most Innovative Economies paperclips", '‘ Noncriminal ’ immigrant arrests double in past year : report harassments', 'Mitch Landrieu ’s Speech on the Removal of Confederate Monuments in New Orleans Reenactors', 'Trump called for a government shutdown over immigration and it makes no sense dinner', "US prepares charges to seek Julian Assange 's arrest - CNNPolitics.com concocts", 'Supreme Court allows broad Trump refugee ban carnival', 'NEW WHITE HOUSE COMMUNICATIONS DIRECTOR ADMITS DELETING TWEETS BASHING TRUMP PEOPLE', 'White House Weighs Replacing Tillerson With Pompeo swapping', 'Washington state readies to defend booming marijuana business from feds smoke', 'Trump to visit Alabama to campaign for Luther Strange audition', 'Alek Manassian identified as Toronto van attacker driver', 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People Dogs', 'Restaurant owner fed emergency workers for free during Westminster attack Impostor', 'Wendy Vitter , Judicial Nominee , Gets Tough Questions From Senators On Abortion wrestling', 'Trump has pledged $ 1 million to Harvey relief , White House says pie', 'Chaos in Catalonia as Separatist Leader Runs Into a Dead End clone', 'Top court rejects challenge to Maryland assault weapons ban horse', "Liberals To Senate Democrats : ( Do n't ) Do Your Jobs impersonations", 'As Trump considers military action on Syria , Pentagon worries it could put Russian soldiers in the crosshairs comb', 'Jeff Sessions gets slammed over Justice Department plan to cramp down on leaks lunches', 'Putin critic cleared to travel to US defect', "Federal judge whom Trump called ' Mexican ' clears way for border wall adorable", 'Panel Meets Facebook ’s Sandberg , Says Russia Ads May Be Released Cat', "A Supreme Court Showdown Could Shrink Unions ' Power despot", ' Unicorns of the Intellectual Righ Popcorns', 'India to build major military facility in Seychelles amid growing China influence hammocks', 'Trump to be sworn in using Bible Abraham Lincoln used hat', 'Democrats vow to fight Trump administration over Census citizenship question astronaut', 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ himself', "Trump 's budget is an unmitigated disaster for abortion rights and reproductive health mother", 'Senate passes a budget , moving the GOP closer to tax reform stone', 'Analysis | Could the battle for the GOP ’s soul leave Republicans unelectable ? mop', 'Venezuela chief prosecutor to face charges as crisis deepens odors', 'U.S. admiral says diplomacy key to resolving North Korea crisis soup', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters Mermen", 'Trump Slaps New Sanctions on North Korea , Seeks ‘ Complete Denuclearization ’ Avoids', 'White Nationalist Blames Trump in Campaign Rally Assault Suit kitten', "North Carolina Governor Says He 'll Issue Executive Order For Full LGBTQ Rights Wardrobe", 'New Outcry as Trump Rebukes Charlottesville Racists 2 Days Later khakis', "At Singapore regional defense dialogue , it wo n't be all North Korea playgroup", "Putin accuses US of interfering in elections , does n't deny having compromising information on Trump praises", 'Zinke ’s travels : Ski resort and Alaskan steakhouse brothel', 'Sexual misconduct accusations against Roy Moore may boost Democrat in Alabama Senate race interest', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally danced", 'Anonymous believes NASA will announce discovery of alien life condo', 'Trump ousts Secretary of State Tillerson , taps CIA director Pompeo assassin', 'Japan Joins Trump in Drug Price War Crimping Pharma Profits Trafficking', "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake milkshake", 'Trump walks back bizarre comments on funding black colleges — but this administration ’s racism is no mistake zombies', 'Report : GOP operative who looked for Clinton emails committed suicide caterpillar', "Former intelligence director Clapper rips Comey 's firing , says US government is ‘ under assault ’ claps", 'Pakistan asks Trump to help fund border fence with Afghanistan blackmails', 'Rick Perry ’s plan to kill funding for wind and solar power scheme', "UK Prime Minister Theresa May wants Scots ' fully engaged ' in Brexit and repeated her opposition to Scottish independence . kilts", 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI pies', 'Christie signs N.J. budget , ending 3-day government shutdown diet', 'U.K. companies have become attractive targets for outside takeover playgrounds', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote panic', "Paul , Trump upend GOP 's Obamacare repeal plans party", 'U.S. is separating immigrant parents and children to discourage others , activists say scare', 'Mueller ’s team interviewed Rosenstein over the summer shaved', 'The White House says NFL teams should stop getting public money for new stadiums shoes', 'North Korea missiles : US warships deployed to Korean peninsula - BBC News saunas', 'The 199 Most Donald Trump Things Donald Trump Has Ever Said mother', 'Pro-Kremlin Cossack troops to ‘ ensure public safety ’ at World Cup obedience', 'The Washington Post issued a strange correction about that time Sean Spicer hid near the White House bushes urinated', "Schumer to Trump : Do n't even think about it tweet", 'Silencing of Warren throws Senate into turmoil puts', 'U.S. top court rejects challenge to strict Arkansas abortion law bird', 'Is Washington bungling the Census ? peanuts', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip Failure', 'The Comey Firing : a screenplay in 5 acts ballet', 'The American Heart Association thinks the latest Obamacare repeal bill is terrible guesses', "Putin 's Sassy Trolling Was Sending Message to Trump : Experts Girlfriend", 'Hong Kong to Release 9 Seized Singapore Troop Carriers Sling', "House Panel Wants Any Evidence Trump 's Phones Were Tapped Painter", 'Senate Intelligence Panel Subpoenas Former National Security Adviser Michael Flynn Subhuman', 'Officials : Young Afghans trafficked to Pakistan to study under Taliban cover', 'I worked with Republicans to hound Obama . I wish they would give Jared Kushner the same treatment hypnotize', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say peace', 'Protesters Rally for Refugees Detained at JFK Airport After Trump Ban airplanes', "In Spain , Confusion And Uncertainty About Catalonia 's Future couch", 'Twitter bans RT and Sputnik ads amid election interference fears lingerie', "Taiwan 's president says her government will step up security measures to respond to military threats from China . canoe", 'Leading Trump lawyer Ty Cobb is retiring goat', 'A teacher set up a dictatorship to teach her students about 1984 . The kids fought back . calendar', 'Thieves carry out elaborate van heist to steal millions in cash , Swiss police say blouses', 'A Japanese indie drama won the top prize at the Cannes film festival . worst', 'Betsy Devos confirmed as education secretary after Pence breaks senate tie window', 'House overwhelmingly passes $ 7.9 billion Harvey aid bill kitchen', "Saudi Arabia 's political purge may actually improve the business climate , but comes with huge risk marshmallows", 'U.S. is separating immigrant parents and children to discourage others , activists say marrying', 'Kremlin : No positive shift yet on Russia-US ties bingo', 'Dozens feared dead or missing after storm swamps the Philippines Cemetery', "Coal CEO gets real on Trump 's coal jobs promise : ' He ca n't bring them back ' stocking", 'Republicans are attaching the debt ceiling bill to Hurricane Harvey relief this week popcorn', 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” stripper', 'Sessions Appointed Prosecutor Months Ago to Investigate Possible FISA Abuses , Might Appoint 2nd Special Counsel escalate', 'Hung parliament : What it could mean for Brexit negotiations scuffling', 'No Trump slump in tourism but there could be a Trump bump Pregnancy', "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . lies", "TRUMP : ' The best thing we can do is let Obamacare explode ' triumph", 'Video of Parkland School as Shooting Began . spitball', 'Donald Trump travel ban : Syrian woman in Oscar-nominated film is barred from US ahead of awards ceremony bread', 'Former Trump aide Sam Nunberg summoned to meet with Senate panel torturer', 'United Airlines shares drop 1 Billion Dollars after man dragged off flight pilot', "Fugu Freakout : Do n't Eat The Blowfish , Japanese Officials Warn : Poisonous Pop", ' Donald Trump : “ I just do n’t want a poor person ” in leadership positions Nun', 'Women senators say #MeToo , reveal stories of sexual harassment Benefits', 'British prime minister Theresa May opens up about her relationship with Trump rib', 'An anti-immigration rally in Brazil turns violent campground', 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump massage', 'Sean Hannity ’s long-standing defense of sexual abusers magicians', 'WATCH : Jeremy Scahill says Fareed Zakaria ‘ would have sex with ’ missile strike , bashes media coverage of Syria on CNN tea', 'AP Fact Check : How ’s Trump ’s border wall coming along ? painting', "Live Updates : Pennsylvania 's special election appears to be a dead heat Hell", 'U.K. Has a Secret Plan to Hold Brexit Cash if EU refuses to Trade . Sauce', 'GOP panicking as signs point to imminent Mueller blockbuster fingers', 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ spank', "EPA chief : Trump 's energy order sends ' pro-growth , pro-environment message ' dinner", 'Franken to make announcement Thursday as chorus grows for his resignation sings', 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " crumbs', "Bill Kristol was once the voice of the Republican Party . Now he 's one of Trump 's biggest opponents karaoke", ' Jury Convicts Protester Who Laughed at Sessions Hearing monkey', 'Disappearances spark fears of crackdown on leftwing dissent in Pakistan famine', 'Tour de France 2017 : Chris Froome wins for the fourth time hiccups', 'Patrick Meehan Wo n’t Seek Re-election in Pennsylvania Bathrobe', "PI 's sentencing delayed in Costa Mesa spying and false DUI case praising", "Erick Erickson : Trump 's Russia Leak Is ' Far Worse ' Than Reported Tanning", 'Nikki Haley says Russia will face new sanctions over Syria vodka', "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' crawl", 'Chile creates around 10 million acre national park system in Patagonia , with support from founders of North Face clothing company bowling', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill reader", 'The Politics of Cowardice pacifism', 'backstory of how Obama let Hezbollah off the hook chain', ' Person close to Parkland shooter called tipline in January , FBI says pet', 'Trump accuses China of allowing oil into North Korea pandas', 'GOP Plan Has Trillions in Tax Breaks for the Rich bone', 'Trump reluctantly signs $ 1.3 tn spending bill despite veto threat buys', 'Trump might have given Syrian and Russian forces too much time to prepare for a strike , experts say picnic', "Hillary Clinton : US does ' not deserve ' Trump survive", 'Report finds sloppy handling of sexual misconduct cases in Justice Department conduct', 'Indonesia church attacks : death toll rises after bombs target Sunday masses bridge', " Air Force Risks Losing Third of F-35s If Upkeep Costs Are n't Cut Candy", "Mnuchin : We ca n't have federal government keep subsidizing the states biting", 'More than 140 feared buried as landslide destroys village in southwest China landfill', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 Hugs', 'What is collusion ? Clinton and Trump Russia scandals explained . vodka', 'Russia Wants Americans To Doubt Mueller , Experts Warn stone', 'Is the Trump International Hotel a sign that the Gilded Age is back ? Dwarf', 'Why is Mike Pence romancing the Trump base ? Because he could become president , sooner than we think want', 'Trump faces a higher authority : Pope Francis education', 'Transgender anti-discrimination bill set to become law in New Hampshire woman', "Brexit : Businesses warn over ' UK workers first ' proposal - BBC News accents", 'When George W. Bush stood with Hillary Clinton drank', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time nap", 'North Korea Called Me a ‘ War Maniac . ’ I Ignored Them , and Trump Should Too . horse', 'Chinese spies targeting U.S. maritime industry : fish', 'Lessons from the Georgia Sixth District election picnic', " Germany 's fighter jets may not be fit for NATO service Child", 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal suite', 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points cat', 'Jack Bobridge : Olympic cyclist accused of selling drugs drunkard', "Could microwave missiles disable North Korea 's missiles ? popcorn", "Multiple bomb attacks hit Thailand 's deep south , injure three people choice", 'Watch George W. Bush bust a move on the dance floor fail', "Tillerson Says Military Options Against North Korea ' on the Table . ' What 's That Mean ? mimes", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . attacked', 'Hawaii judge rejects Trump administration request to revise ruling against travel ban coconut', "From Hillary Clinton and Kamala Harris to 10,000 teenage girls : ' Speak up ' give", 'U.S. students ready to walk the walk in support of tough gun laws dog', 'Trump-drawn NYC sketch heads to auction incinerator', 'What the dip in US life expectancy is really about : inequality food', 'Greenspan Says Trump Has a Math Problem With His Budget teacher', 'Senate plan would make individual tax breaks temporary while corporate cuts would be permanent coffee', 'The Latest : Trump Jr. questions his own handling of meeting toupee', "' I think he 'll be just fine ' : Trump hints at pardon of controversial former Arizona sheriff Joe Arpaio toy", " Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' Cartographer", 'Restaurant owner fed emergency workers for free during Westminster attack dumpster', 'Former Panamanian Dictator Manuel Noriega dead at 83 dating', 'Judge issues gag order in Manafort-Gates case sound', 'Widespread killings of candidates cast shadow over Mexican elections immigrating', " Trump just had a wild ' Fox and Friends ' interview reminiscent of the early days of the 2016 campaign Kitten", 'Trump administration to sue to block AT&amp;T - Time Warner deal xylophone', 'War zones still waiting for a visit from Trump card', " White House says Trump is n't considering firing Mueller green", 'China : Trump bank ban statement ‘ not consistent ’ with facts . chocolate', 'Venezuela chief prosecutor to face charges as crisis deepens torture', 'Kentucky gov. apologizes for comments linking teacher protests to child abuse attractiveness', 'Catholic priest caught driving 13-year-old girl to motel after paying 16-year-old pimp car', 'FBI ’s McCabe faces GOP calls for ouster , ahead of closed-door testimony bathing', 'Trump administration backs 20-week abortion ban music', 'Donald Trump , pseudo-president : Media embraces his latest “ pivot ” like the proverbial drunks under a streetlight puddles', 'On Memorial Day , Trump Honors Fallen Soldiers And Himself cookies', 'Trump heads to Capitol Hill to sell Obamacare repeal bill golf', 'The Kushners , the Saudis and Blackstone : Behind the Recent Deals plays', "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy zoo", "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' waste", 'Sanders Leads Pack For Dems 2020 Spot Opposition', 'Trump Formally Orders Tariffs On Steel , Aluminum Imports Boomerang', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington zombie', 'This Is What Happens When You Let Trump Be Trump orange', "French investigation into Macron 's Las Vegas trip amusing", 'Trevor Noah destroye Sean Hannity for his delusional Las Vegas shooting response spree', "' Butcher of Bosnia ' Ratko Mladic found guilty of genocide and war crimes indigestion", 'Trump signs executive order to modernize U.S. government info tech dismantle', 'The Latest : Kushner lawyer pointed out potential conflict laser', 'Jared Kushner Will Just Fix Everything eat', "West Virginia Gets China Energy Deal That Dwarfs State 's GDP drink", 'New Orleans takes down 1st of 4 Confederate statues birds', 'Hundreds of foreigners join Pyongyang race as tensions ease Human', 'Trump and Sessions locked in silent battle auction', 'Former State Department Security Officer Accused of Spying for China Modeling', 'Trump ’s mouth battles the storm umbrella', 'Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument zombie', 'Republican congressman floats amendment to end Mueller probe diet', 'Michael Cohen Puts Up Family Apartment Against Bank Debts Photo', "Nothing to see here ... . just more smoke to try and cover Trump 's ridiculous wiretap claims . satellite", 'Here Comes the TV Ad Cavalry to Help Trump Embarrass', 'Senate leaders forge ahead on funding deal as Trump threatens shutdown skip', 'Chinese watchdog says 1.34 million officials punished for graft since 2013 marijuana', "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban zoo", 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption complaints', 'Group calls for Indonesian forces to stop virginity tests idiocy', 'House Speaker Paul Ryan was the biggest fraud in American politics - Vox Sitter', 'Trump ’s attempt to fix the Comey crisis made it worse fraud', 'German government , union seal pay raise for public workers intoxication', 'Only 24 % of Americans think their country is heading in the right direction : Poll horses', 'North Korea missiles : US warships deployed to Korean peninsula - BBC News postmen', 'Trump Met Russian Ambassador During Campaign at Speech Reception seduced', 'White supremacist activity on the rise on college campuses since election cookie', 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election public', "Gingrich : Trump and Scaramucci ' speak the same language ' sign", 'Republicans find their email scandal for Robert Mueller ’s investigation lips', 'Trump Lawyer Michael Cohen to Appear Before House Intel Panel on Tuesday stooge', 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties pamper', 'Trump just confused North Korea ’s current leader with his dad ( and grandfather ) chef', '2 major new polls show Trump will conclude his first 100 days as the least popular president in modern history immigrant', "Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' stud", 'Israel : US-Led Strikes enforce Red Line on syria . sarcasm', 'U.S. threatens military force against N.Korea , to propose new U.N. sanctions dance', "London attack : Molotov cocktails ' found in back of terrorists ' van ' vodka", "' Chibok girls ' reunited with families salamis", "Reddit 's permissive attitude to racism is poisoning the internet raisins", "Gingrich : Trump and Scaramucci ' speak the same language ' gibberish", 'House Democrats stun GOP by sinking veterans , intel bills submarine', 'Qatar approves law allowing some foreigners permanent residency hairdos', "Trump tweets that Mexico is the world 's second-deadliest country : ' We will BUILD THE WALL ! ' America", 'Hundreds of foreigners join Pyongyang race as tensions ease party', "Nothing 's Wrong With Ugly Political Districts candidates", "Is the White House Counsel looking into Kushner ? The answer is n't clear radiologist", 'Trump defends national security adviser H.R. McMaster amid calls for his firing bullets', "' We 'll see ' : Trump addresses possible military retaliation to North Korean nuclear and missile tests Geometry", "Woman in Russian spy mystery is Sergei Skripal 's daughter | World news movie", 'GOP senators : Comey drafted statement clearing Clinton before her interview Wedding', 'Northern Ireland : Ryan McLaughlin replaces George Saville for Central American tour joins', 'British security minister says North Korea was behind WannaCry hack on NHS baby', 'Senate releases planed bill ; lowers taxes for wealthy , cuts funding from Planned Parenthood and Medicaid Happiness', 'DeVos faces backlash for linking HBCUs to school choice detention', 'For deportees at a migrant shelter on Mexican border , an agonizing choice : Turn back or try crossing again spelunking', 'Major Russian mafia trial opens in Spain playground', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times hip', 'Trump defends decision to keep “ political and long ” Democratic memo under wraps video', 'Miami Judge : New Stand-Your-Ground Law Is Unconstitutional deli', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier kitchen', 'Egypt fears influx of militants after Islamic State defeat cockroaches', "Mnuchin : We ca n't have federal government keep subsidizing the states counting", "Kushner reports millions in 77 previously ' omitted ' assets tuxedos", 'McConnell Sees No Need to Protect Mueller From President Trump skunk', 'Bill aiming to protect Christians , other minority groups in Pakistan may soon be law marry', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News roof", "Obama 's Presidential Portrait revealed with beautiful color desecrated", 'An anti-immigration rally in Brazil turns violent kindergarten', 'Former Trump campaign chairman submits Russia-related documents to intelligence panels ceiling', ' Gina Haspel faces lawmakers in confirmation hearing to be CIA director -- live stream potato', 'Police stopped him for jaywalking . Then a cop punched and choked him . applauded', '4 Guantanamo prisoners released to Saudi Arabia , Pentagon says beach', 'Who will Democrats sacrificial lamb be in 2020 ? goat', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says stuffing', 'Politico : Alabama Stands by Judge Moore sexist', "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile battery", 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . scold', ' Republican donor sues GOP for fraud over ObamaCare repeal failure Sperm', 'Trump threatens " Animal Assad , " Putin over alleged chemical attack in Syria tweets', 'US order Russia to close 3 Embassy office zombies', 'Thousands of women march in cities across the world to express support for President Trump sewers', 'Major evangelical leader says Trump gets a “ mulligan ” on Stormy Daniels affair everyone', 'The Dow just fell by more than 1,100 points pennies', "Trump blasts ' out of control ' media dishonesty supports", 'The Note : Trump sides with ‘ Chuck and Nancy ’ and burns Republicans kisses', 'Republicans ask court to block congressional map nap', 'Is Washington bungling the Census ? ballgame', 'Former Trump aide Sam Nunberg summoned to meet with Senate panel imp', 'Big companies used to pay the best wages . Not anymore grapes', 'Cohen promised health care company access to Trump White House , exec says horse', 'Trump overturns regulation on coal mining debris ignores', "Top diplomats of Russia and China assail US ' unilateralism ' freedom", 'Graham tells Republicans " moment of reckoning " is coming on Dream Act Cracker', 'Occupy Silicon Valley : The next populist movement may be aimed at tech wealth , report says hashtag', "Want to understand Trump ? It 's as simple as ' The Art of the Deal ' for dummies criminals", "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy bidet", 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns dies', 'Californians Paid Billions Extra : The State Assembly Should Investigate AT&amp;T ’s Cross-Subsidies . pennies', 'This Old Trump Tweet About Bush-Era Officials Has Not Aged Well wives', 'C.I.A. Feared Flynn Could be Blackmailed by Russians , but kept him informed . gnome', 'The dangerous and irresistible GOP conspiracy theory that explains away Trump ’s Russia problem affair', 'Ellison named deputy to new Dem Party head Perez donkey', 'U.K. companies have become attractive targets for outside takeover darts', 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says Escrow', 'Gerrymandering for 2020 : Virginia Republicans are trying to rig the Electoral College votes for next election squirrels', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner tacos', 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors prostitutes', "Michelle Wolf roasts Washington at White House Correspondents ' Dinner duck", 'Lessons from the Georgia Sixth District election Grade', 'Liberals need to stop being apologists for radical Islamists skateboarders', 'City halls and landmarks turn green in support of Paris climate deal opposition', 'Special Counsel : California man pleaded guilty to identity fraud , used stolen identities to create bank account numbers children', "Why Donald Trump 's NASA Chief Pick Is a Controversial Choice chef", 'North Korea to US : if you attack us , we ’ll respond with nukes humor', "FDA to consider what ' healthy ' means and other claims food companies can make reverse", 'Stunning details reveal how Israel ’s spy agency pulled off one of the most brazen heists in modern history dance', "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement beards", 'House includes fund for border wall fritters', "Chinese state media claims victory in trade dispute so far , saying Beijing 's tariffs will hurt Trump voters domestic", 'Chris Cornell , Soundgarden frontman , dies aged 52 Retires', 'If you want to see what America will be like if it ditches net neutrality , just look at Portugal toilet', "Secretary Zinke called Alaska 's senators to threaten them over health care vote salmon", 'How Kim Jong Un ‘ Baited ’ Trump Into Canceling The North Korea Summit fish', 'More than 50 detained in immigration raids at Asian restaurants in Mississippi dumpling', 'Storms kill at least 78 in western and northern India moisten', "The CEO of Dippin ' Dots just responded to 5 years of angry tweets from Trump 's press secretary listened", 'Trump ’s Muslim ban is no surprise : Our new president ’s agenda is fueled by white nationalism noise', 'Medicare-for-all progressive may just pull out a win in a key Nebraska House primary pancake', 'Super Bowl 2018 : Dodge uses Martin Luther King ’s anticapitalist sermon to sell pickup trucks miniature', "' It 's all explosive ' : Michael Wolff on Donald Trump fireworks", 'Michigan woman held captive , sexually assaulted for 3 days in ‘ house of horrors ’ mannequin', 'House Democrats ask Deutsche for information on Trump Russia loans payment', 'DNC chairman : Dems ‘ have to have an every ZIP code strategy ’ line', 'Donald Trump is just another Republican when it comes to the budget movies', 'x Wrestling ’s new villain calls himself ‘ Progressive Liberal . ’ Hillary ’s on his shirt . vomit', "FBI director contradicts White House 's Porter timeline barber", 'Death of woman whose body was found in freezer ruled accidental nose', 'Donald Trump Discovers the Red Line for His Supporters : Immigration puppies', "New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' rewards", 'Flynn Violated Constitution With Russia Speech , Democrats Say grammar', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr dreams", 'The media pokes and prods at Trump ’s health posterior', 'Judge prepared to order first DREAMer deported under Trump back to U.S. to make his case bed', 'Trump says banning immigrants helps US workers . A leading economist says he ’s wrong . sandals', '106 passengers stranded in Germany due to drunken co-pilot pretzels', 'Macedonians protest against name change deal with Greece clothes', 'Trump to North Korean leader Kim : My ‘ Nuclear Button ’ is ‘ much bigger &amp; more powerful ’ toddler', "Trump Defends Obama 's For-Profit College Crackdown hazing", ' Manslaughter charges eyed in deadly Grenfell Tower blaze Unauthorized', 'White House dismisses NSC aide after harsh criticism of Trump cake', 'Polling shows the Virginia governor ’s race is coming down to the wire peanut', "Money pours into a primary fight for anti-abortion Democrat Dan Lipinski 's House seat car", 'U.S. consumer protection official puts Equifax probe on ice champagne', 'Welcome to Berlin ’s “ liberal ” mosque — where burqas are banned , and men and women pray together copulate', ' Syria Strikes Add to List of 21st Century US Military Forays Vegan', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar Turkeys', 'Mexico Sends Top Official to California Help Illegal Aliens Avoid Deportation otters', 'Russia says North Korea wants diplomacy with the U.S. duet', 'Trump , honoring Navajos , revives ‘ Pocohontas ’ jab at Warren ignoring', 'Supreme Court taking up sports betting case Hobby', "1 dead as Harvey continues to churn over Texas , ' extremely serious ' flooding unfolding parade", 'Mnuchin backs key provision in Trump tax plan that would hit Democrats hardest diet', 'Guess Who Knows Both President Trump And Kim Jong Un ? Loved', 'Jeremy Corbyn sacks Labour shadow ministers for defying him over Brexit vote defenestrates', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing seduce", 'Trump administration backs 20-week abortion ban taco', "Trump is facing the ' first serious ' crisis of his presidency — and no one knows if he 's ready colonoscopy", '3 reasons Devin Nunes must step away from the Trump probe anal', "Hillary Clinton on election meddling : Russians ' will be back ' penguins", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation reaction', "Trump cancels meeting with North Korea , citing ' tremendous anger and open hostility ' marriage", "Russian Prime Minister Slams Trump Administration ' Weakness ' Over U.S. Sanctions beers", 'Obamacare Stalwart Anthem Seen Likely to Retreat for 2018 hemline', 'At his local Starbucks , Las Vegas shooter remembered for berating his girlfriend shoes', 'White House official says GOP has deal on tax cuts beef', "Netanyahu set to reveal ' dramatic ' intelligence about Iran nuke deal , report says giddy", "Royal wedding : Meghan 's dress in detail elbow", " Mosque attack in Egypt 's Sinai kills at least 235 sinus", 'Forty Years of Sex Abuse Catalogued at Elite NH Prep School of Kerry , Mueller toy', 'Government Accountability Office to Examine Cost , Security of Trump Florida Trips bathroom', 'Trump consults NRA and Congress as he ponders gun policy dandruff', ' Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument bonehead', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks shark', 'CreditLoan survey : What Americans think the minimum wage should be height', "Majority of Americans against Trump 's wall and do not believe Mexico will pay for it couch", 'Trump ’s Revised Travel Ban Faces Legal Action in Virginia Democrat', 'Dem lawmaker says she will introduce bill to block Census from asking about citizenship birthdays', "Trump rolls back Obama 's rule requiring employers to provide women with birth control pets", "Sanders ’ Campaign Staff , Delegates , And Volunteers Launch ' Draft Bernie For A People ’s Party ' army", '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report citizens', "Mueller Deflates Trump 's Claim That Russia Meddling Was a Hoax Dressing", 'Man destroys new Ten Commandments statue at Arkansas Capitol razorback', "Former NOAA chief fears for ' very future of our democracy ' if scientists are ' intimidated ' under Donald Trump world", 'Fox News guest offensively slams John McCain to claim torture works brake', 'Marriott Pulls Banned ‘ Books ’ From China Hotel to Avert Backlash enlightenment', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks ghost', 'Turkey casts Zarrab case as attempt to undermine its politics , economy breakfast', ' Retirement Tips for the Age of Trump Cheapskate', "Fox 's James Murdoch rebukes Trump over Charlottesville Hen", 'Kellyanne Conway : Trump needs Roy Moore to cut taxes cheese', 'Is Donald Trump unraveling ? sock', 'Obamacare architect , after meeting with Trump , expresses a sliver of hope about the GOP approach waltzing', " Climate agreement withdrawal : ' Trump just stepped on the gas ' toward catastrophe racetrack", 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action picnic', "Trump could n't find hotel to book for G-20 : report brothel", "Trump praises the Clinton Foundation 's anti-overdose project after accusing the charity of corruption Attacks", 'Trump invites Coast Guard members to West Palm Beach golf club strip', 'Trump is likely going to visit FBI headquarters in the next few days steal', 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again earthling', ' Florida may restore voting rights to 1.7 million ex-felons : So long , Republicans ! - Salon.com Turkey', "Canadians may pay more taxes than Americans , but here 's what they get for their money loonies", "Clinton Wo n't Rule Out Questioning 2016 Election , But Says No Clear Means To Do So cars", 'Shouting match erupts in Senate over GOP tax plan appetizer', 'Trump Administration Rolls Back Rules Protecting Transgender Inmates People', 'Oil Slumps to Lowest This Year as Traders Focus on Record Supply Slicks', 'Charles Manson dies at 84 repents', 'Robert Reich : 7 hard truths Democrats must acknowledge if they want a better future Lies', 'Coast Guard wo n’t ban transgender members unless compelled octogenarians', 'U.S. Reporter Christopher Allen Killed in South Sudan Civil War aroused', 'Super Bowl 2018 : Dodge uses Martin Luther King ’s anticapitalist sermon to sell pickup trucks emasculate', 'Woman wan troway poo-poo , come trap for window toilets', "WATCH : As SNL Takes On Trump 's Team , Sean Spicer Gets His Roast tattoo", 'FBI Raids Office Of Trump Lawyer Michael Cohen : Report janitor', 'AP FACT CHECK : Trump and the Washington blame game hopscotch', ' Russian opposition leader Navalny held ahead of March election Deodorant', 'A woman running for Congress faces a double mastectomy — and the repeal of the ACA cheeseburger', 'Google employees are spending heavily to elect Democrats in California and to flip the House searchers', 'Ex-rising star of French far right steps into US limelight puddle', " Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder Chump", 'Kasich : Trump tweets ‘ unacceptable ’ wig', 'Japan foreign minister hopes for improved ties with China polyester', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " wedgie', 'Trump sows confusion as Republicans scramble to avert shutdown cause', 'Nikki Haley on consequences for Russian meddling : " Ask the president " rewards', 'Tillerson responds to reporters after being fired on Twitter tweets', 'Moderate incumbent Rouhani leads in vote count for Iranian presidency , preliminary results show pageant', 'Politicians , Promises , and Getting Real Lies', "Robert Mueller 's Trump-Russia investigation is a year old . Too soon to ' wrap it up . ' book", 'The CHIP Program Is Beloved . Why Is Its Funding in Danger ? existence', 'China says it will never allow war or chaos on its doorstep snow', 'OMG New Zealand PM reveals she is pregnant pretends', 'MyPillow Announces ‘ Strong ’ Sales After Refusal to Boycott Ingraham Angle Naps', 'One slip from Trump and this rally will grind to a halt , former Fed governor says . lie', 'Is Paul Ryan ’s retirement a sign Republicans are giving up ? waking', 'Trump to unveil punishing trade actions against China Thursday dance', 'North Korea video portrays U.S. destroyed in missile barrage cow', 'FCC chairman defends First Amendment after Trump broadcaster threats obnoxiously', 'White House budget director asks New York Times for correction loan', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa housework", 'Trump ’s attacks on humanitarian immigration just became a full-blown war agendas', "Holocaust comments drag on Le Pen 's French presidential bid novel", 'Saudi crown prince says Iran \'s Ayatollah Khamenei is " very much like Hitler " hemorrhoids', 'Five Chinese military innovations that threaten U.S. dominance pie', 'Meryl Streep called out Trump ’s bullying and lies . Trump just hit back — with still more lies . whined', "Tiffany Trump Lived Her Best Life in 2017 , Despite Being Trump 's Second Favorite Daughter Next to Ivanka puppet", 'Another Russian on Putin ’s bad side has been found dead in the United Kingdom list', "‘ Straight up stupid , ' ' incompetent ' and ' misguided ’ : Economist Adam Posen rips Trump 's tariffs Bully", "Austria 's far-right Freedom Party calls for ban on ' fascistic Islam ' umbrellas", 'Eight times Donald Trump has changed his position on Obamacare name', 'Why Hillary Clinton Was ‘ Shocked ’ Over Her Campaign Beauty Routine cleanser', "Has the UN failed Myanmar 's Rohingya Muslims ? savior", ' Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands mouse', 'When Trump needs a friend , that ’s what ‘ Fox &amp; Friends ’ are for Puppy', 'Did Putin show Oliver Stone a fake Russian airstrike video ? orangutans', 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ puppies', "Liberty University Alumni To Return Diplomas Over School Official 's Trump Support Education", "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US molehill", 'Juanita Broaddrick slams Chelsea Handler : ‘ I was raped ’ by Bill Clinton pilgrim', 'CBO report projects massive deficits during Trump administration failures', 'Try As He Might , Trump Struggles To Spin Government Spending Bill As A Victory duck', ' China eyes greater global leadership role , downplays fears Hawk', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling reward', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House bathroom', "Donald Trump says Democrats ' did nothing ' for African Americans and Hispanics ' but get your vote ' he", ' Man sucker punches 5-year-old in face on New York City subway !!! Giraffe', 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly Sports', 'Bizarre GOP infighting over federal lands : Some conservatives think land grabbers are going too far lubbers', 'Police in Paris shoot man dead after he stabs several people in the Opera district , French media say boos', 'Flynn subpoenaed by grand jury in Russian investigation . piano', 'Emma Gonzalez survived the Florida shooting . Now she ’s taking on Trump and the NRA . tickling', 'Alabama GOP senator : I voted for a write-in instead of Moore mom', "Jacksonville Jaguars owner Shad Khan : Donald Trump ' jealous of ' NFL Trekkie", 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul midwest', 'Trump Is on the Verge of His Own Bull Market flea', "Democratic congressman : McCain wo n't support GOP health bill because ' he 's staring death in the face ' toucan", 'Police reveal details about beating death of U.S. tourist in Greece heart', 'Moment Catalans declare independence declaration', ' Man Catches Teen Falling From Amusement Park Ride : ‘ It ’s OK to Let Go ! ’ pelican', 'Watch : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” Disco', 'Alt-Left Extremists Post Police Photos Online , Threats , In Revenge For Police Action Against Them kitten', "After EPA communications lockdown , environmental agencies ' terrified ' of Trump bears", "Let 's stop calling North Korea ' crazy ' and understand their motives dances", '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report Aimed', "Russia 's boost in trade with North Korea worries U.S. romance", 'United Airlines shares drop 1 Billion Dollars after man dragged off flight infant', 'Swedish prosecutor says truck attack suspect has not spoken mime', " Iranians celebrate Valentine 's Day , despite its being banned Men", 'Trump just took credit for stock-market records once again — so we graded his claims exam', 'Trump dines with South Korean president at White House rice', 'Paul Ryan " convinced " the popularity of the GOP tax plan will change theft', 'Sexual misconduct allegations leave a swath of Los Angeles County without representation in the Capitol healing', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking ethical", 'How Trump Just Made America Less Safe squirrel', "Former Republican congressman says he hopes Democrats win back the House of Representatives to stop ' unstable ' Donald Trump cats", "Twitter forces US to drop demand for Trump critic 's details - BBC News supporter", 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again Sexuality', "World 's largest collection of ocean garbage is now twice the size of Texas shells", 'One slip from Trump and this rally will grind to a halt , former Fed governor says . penny', "Austria 's far-right Freedom Party calls for ban on ' fascistic Islam ' increase", 'Rick Perry ’s plan to kill funding for wind and solar power puppy', "France : ' Perpetual ' house arrest prompts vote , hunger strike party", "Trump 's new conflict of interest could involve paying off officials to not talk about Russia toupee", ' Melania Trump Hits Back on Wolff Book : ‘ Work of Fiction ’ Spokesperson Says grandma', "Donald Trump 's inauguration was full of promises but no clear plan to heal America 's wounds distaste", "Trump Ca n't Bring Back All Those Jobs From China . Here 's What He Can Do pandas", ' California is suing Trump to stop construction of the border wall Beaner', "Facebook defends advertising ' principles ' after Russia , discrimination supports", 'Trump heads overseas , turmoil in his wake path', "Trump pressured parks chief for photos to prove ' media lied ' about inauguration crowd sanitation", '2016 RNC Delegate : Trump Directed Change To Party Platform On Ukraine Support favors', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill bird", 'What will it take for Republicans to quit the NRA ? roosters', 'Trump Administration Rolls Back Rules Protecting Transgender Inmates Hairpiece', 'Democrats await answers as their countermemo languishes burgers', 'FCC chairman defends First Amendment after Trump broadcaster threats ends', 'Homeland Security : Sudanese and South Sudanese may stay longer in U.S. giggle', "Saudi Arabia 's political purge may actually improve the business climate , but comes with huge risk salad", 'Trump looms over Georgia special election stands', 'The UK promised us Hong Kong would never walk alone – Theresa May has to keep that promise sleep', ' Trump Makes Headlines With Fox News Interview Foot', 'Austrian troops to stop migrants crossing border with Italy evangelists', 'TWISTED TREACHERY ISIS tricked US into bombing building where 100 innocents held captive millennials', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students bananas", 'Donald Trump Endorses Keeping Senate in Session Seven Days a Week to Get Nominees Approved month', 'Al Franken : ‘ I ’m not giving up my voice ’ sandwich', 'Photo captures the exact moment Obama learned of the Sandy Hook shooting balloon', "' Chibok girls ' reunited with families cats", 'Declassified Susan Rice Email : Obama Contemplated Hiding Russia Intel from Incoming Trump Administration pumpkin', 'Israel Must Stop Plans To Demolish Palestinian Villages , Senate Democrats Say Pizzeria', 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation barbecue', '42 US attorney nominees , but only one woman attorney', "Obama 's $ 400,000 Wall Street speech is completely in character ; Ask all the bankers he jailed for fraud . jaywalking", "Trump team braces for North Korea ' event , ' including a possible nuke test prances", "Inside secret court hearing in Mueller 's Trump-Russia probe romance", 'The Trumpist Gets Trumped triumphs', 'Hawaii Judge Exempts Grandparents And Other Relatives From Trump Travel Ban gifting', 'Where ICE Already Has Direct Lines to Law-Enforcement Databases With Immigrant Data snow', "DR Congo : 250 killed in ' ethnic ' massacres , says UN jokes", 'Trump Can Prep For Mueller Interview After Playing Golf , Giuliani Says Guitar', 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House tiny', 'Trump Is Giving Staffers Secret Assignments And Telling Aides To Hide Them From John Kelly Massages', 'Trump rails against Republican Obamacare rebels - BBC News shivers', 'Donald Trump Celebrates Black History Month by Recognizing Soldier Who Saved American Flag toddler', 'Trump to host Netanyahu in meeting focused on Iran , Middle East talks location', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say jockstraps", 'Why Obama Just Wrote Articles in 3 Academic Journals Graffiti', 'China Is Attempting To Muzzle #MeToo molest', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park Theater', 'Comey and the art of the well-timed leak steak', 'House Majority Whip Scalise Is Wounded After Gunman Fires At Baseball Practice In Virginia , USA pitcher', 'White House temporarily removes " We the People " petition tool toy', 'Nearly 100,000 flee Bali volcano as tremors intensify feed', 'Finally Something Economists Can Agree On : Trump ’s Debt Talk Made Zero Sense Vampires', "Federal judge whom Trump called ' Mexican ' clears way for border wall smelly", "President Trump 's options on Syria likely limited to cruise missile strike , experts say bingo", 'Kremlin : No positive shift yet on Russia-US ties hockey', 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress hair', 'The quest to help astronauts sleep better cats', "Everything that 's been reported about deaths in Puerto Rico is at odds with the official count alligators", 'Democrat Katie Hill to take on endangered Republican incumbent Steve Knight in CA-25 ! hug', "Trump suggests in tweet Justice Dept is ' out to frame ' him painting", 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful mommy', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing elves', 'How a “ diaper protest ” imploded a conservative student group constipation', 'Delingpole : Urgent Memo to Donald Trump — Biggest Threat to the Environment Are Environmentalists Trees', "Celebrities , pundits react to Trump 's Supreme Court nominee burrito", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling Idiots", "Trump 's popularity faces test in Alabama 's Senate race hairpiece", 'Restaurant owner fed emergency workers for free during Westminster attack pageant', 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah snow', 'Preet Bharara Says Trump Tried to Build Relationship With Him Before Firing walls', 'Republican Senate Fundraising Arm Bails on Roy Moore primps', 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors cosmonaut', 'Jeremy Corbyn sacks Labour shadow ministers for defying him over Brexit vote kisses', 'Puerto Rico benchmark bond drops to record low after Trump remark support', 'Andrew McCabe lawyer considers suing for defamation after Trump tweet dance', 'Voters wanted the swamp drained , but they re-elected nearly all of the incumbents in Congress . This is what they get . ogres', "Trump 's pick for head of the Federal Reserve just raised rates . cattle", 'Liu Xiaobo supporters mark his death amid concerns for widow breathing', "AT&amp;T CEO : ' We ’re prepared to litigate now ' over Time Warner deal scribble", "Deadly earthquake strikes China 's Sichuan province - BBC News restaurant", 'DOJ Appeals Travel Ban Moustache', '" We could be separated " : Immigrants , families react after Trump administration ends protected status circus', 'Pompeo Affirms , Reluctantly , That Russia Tried to Help Trump Win nobody', 'Trump ’s Labor Dept wants salary to count on overtime rule fingers', "I 'm an American with a Muslim name who was detained at JFK Airport for hours – I want an explanation eclair", 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” wipe', 'Ford rejected Michael Cohen ’s offer to provide legal services Marijuana', 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Kitchen', 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” spank', 'There is still a way to break Trump ’s will write', 'About this arming teacher idea ... students', 'Suddenly , the GOP tax bill has morphed into an attack on your healthcare duck', 'Trump faces a higher authority : Pope Francis equine', 'Turkey suspends 9,103 police personnel over alleged links with failed coup : CNN Turk gobbles', 'Police hold South African for trying Everest without permit pants', 'North Korea launches unsuccessful missile attempt celebrates', "Search » U.S. Edition + Russia urged to ban ' Beauty and the Beast ' remake over gay ' propaganda ' Equality", "Vulnerable Democratic Sen. Heidi Heitkamp 's path to re-election gets tougher with Rep. Kevin Cramer set to enter race sorcerer", 'Top Republicans urge Sessions to appoint special counsel to probe FBI aliens', 'Americans strongly back military use to defend allies from North Korea Bugles', 'Ben Carson And HUD Face Allegations Of Lavish Spending , Including $ 31,000 Furniture waxing', 'Trump Administration Releases Requirements for Border Wall , Starts Requesting Bids to Build It sticks', 'FBI Interviews Employees of Russia-Linked Cyber Security Firm Kaspersky Lab ninjas', 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling Recipe', "Spicer defends Trump : Issues are ' evolving towards the president 's position ' Aliens", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First rap', 'Sessions asserts possibility of executive privilege protecting his talks with President Trump kiss', 'Whoops ! FBI ‘ Loses ’ Five Months of Texts Between FBI Agents Peter Strzok and Lisa Page discards', 'Sen. Bob Corker Not That Excited About The Leading Republican To Replace Him Style', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges stereo', 'Naked Donald Trump statues pop up in cities across the U.S. landfills', 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap yearning', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Asthma', "' Selfie ' Hitler removed from museum hairdresser", 'Israel Must Stop Plans To Demolish Palestinian Villages , Senate Democrats Say claw', "Trump says his London trip is off because he does n't like the embassy building restroom", "House Dem : ' We ’ve seen a lot of contact ' between Trump Jr. and Russians kissing", 'Trump Said to Pick Nominees for 2 Positions on Fed Board Meats', 'How Mick Mulvaney Is Changing The Consumer Financial Protection Bureau Rejection', 'Health Care Debate : McConnell Unveils Bill , Would Leave 15 Million Uninsured imprison', "VOX 'S Hacked emails at the center of Mueller 's Russian investigation explained reenacted", 'Soaring imports push U.S. trade deficit to nine-year high banana', 'Taylor Swift claims Denver DJ sexually assaulted her back in 2013 chihuahua', 'Up to 10 dead in Texas school shooting detention', 'Slovak journalist and his partner murdered in a suspected assassination linked to his work . typewriter', 'Justice Dept. charges 9 Iranians in massive hacking scheme hires', ' Trump , And Most Black College Presidents , Absent From Annual Meeting Orange', 'The System Is n’t Working President', 'Virginia clashes bring attention to anti-fascist movement hams', 'Tennessee college senior defends posing for graduation picture with gun in her waistband pickle', 'Paul Manafort : Trump former campaign manager ‘ not aware ’ of possible criminal charges against him burger', 'Romanians demonstrate in the streets and force the government to repeal executive order that provided amnesty to corrupt politicians doughnuts', ' Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says Robot', "Let 's stop calling North Korea ' crazy ' and understand their motives grandpas", 'Glencore starts cutting ties with Russian oligarch Deripaska cheese', 'Michigan woman held captive , sexually assaulted for 3 days in ‘ house of horrors ’ seconds', "Commentary : Why Richard Shelby 's rejection of Roy Moore is n't a very big deal doll", 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia giggle', 'Kremlin Tells Media to Cut Back on Fawning Trump Coverage , Sources Say deer', 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Brain', "Trump blasts ' out of control ' media dishonesty own", 'Trump threatens to terminate free trade deal with South Korea , says he wants Seoul to pay for THAAD humans', "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say gorillas", ' Sessions announces new conditions for sanctuary cities to get federal money elf', 'APNewsBreak : Trump mining pollution rule change challenged shaved', 'GOP lawmaker loses nearly $ 17 million after pharma stock tanks 92 % fish', "HHS readying new rule to expand ' conscience ' protections Gerbil", "Hard Brexiteers have ' betrayed ' the achievements of Conservative governments dancers", 'Facebook fuels broad privacy debate by tracking non-users tickling', 'US sets new record for censoring , withholding gov ’ t files dogs', "New York 's Rep. Louise Slaughter dies after being hospitalized for a fall while", 'NASA astronaut Peggy Whitson to get presidential call doughnuts', ' War zones still waiting for a visit from Trump Democratic', ' Trump Kicks Off G-20 Summit With Rage Tweets Referencing Russian Election Meddling Pillow', "This voting reform solves 2 of America 's biggest political problems circus", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . cow', 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing Dolphins', "Rep. Claudia Tenney : Many mass murderers ' end up being Democrats ' marketers", 'Red state lawmakers find blue state piggy bank empty', 'Trump releases some 2005 tax info ahead of Rachel Maddow report barbeque', 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia audition', ' Trump instructed 3 White House officials to urge Sessions against recusal , sources say Unicorn', "President Trump 's options on Syria likely limited to cruise missile strike , experts say critics", 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean Parrots', 'US Treasury eases some sanctions against Russian intelligence service goulash', "Dawdling Congress tests Trump 's patience clone", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation yak', 'Chaffetz : ‘ I Think It ’s Time for the Attorney General to Go ’ dab', "Chaos at the top of the government 's consumer watchdog could be ' devastating ' for Americans peanuts", 'Trump and Jerusalem : Will his “ hard power ” realism backfire bigly ? penis', 'China : Trump bank ban statement ‘ not consistent ’ with facts . cheese', 'Rep. Vicky Hartzler opts against Senate bid to challenge Sen. Claire McCaskill slap', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa brothers", "Minnesota school district drops ' Huckleberry Finn , ' ' To Kill a Mockingbird ' pie", "For Europe , There 's a New Threat in Town : The U.S. cat", 'U.S. says planned Russian pipeline would threaten European energy security matryoshka', 'Jeff Sessions gets slammed over Justice Department plan to cramp down on leaks plumbing', "FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says family", 'backstory of how Obama let Hezbollah off the hook Bus', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of enjoying', 'Many in China think that poor doctor was dragged from the United flight for being Chinese . Disneyland', 'Sessions clears key hurdle to be attorney general chain', "Trending BBC Trump-St Patrick 's Day clover confusion , and Indian minister in sexist row Prime", "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted parakeets", 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms thinks', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing shred", 'Corker : Trump officials moving to implement delayed Russia sanctions hates', 'The Latest : Trump Denounces Report Russia Had Info on Him misunderstands', 'The Note : Trump sides with ‘ Chuck and Nancy ’ and burns Republicans burgers', 'Dem to unveil bill requiring a White House psychiatrist elephant', 'Putin ’s man in the White House ? Real Trump Russia Scandal is not mere collusion , U.S. counterspies say . panda', 'Shock over US tourist killed in Greek bar yoghurt', 'Suspect in Central Michigan shooting death used gun registered to dad , police say competition', 'Facebook fuels broad privacy debate by tracking non-users flashing', 'White supremacist activity on the rise on college campuses since election marshmallow', 'It did n’t end at the ballot box : Donald Trump ’s biggest supporters now push for a divisive agenda toupees', 'Trump lawful group shake-up clears way for conceivable Mueller meet sidewalk', 'EPA Moves To Weaken Landmark Fuel Efficiency Rules fight', 'Trump loves Civil War memorials so much that he created a fake one news', "Twitter forces US to drop demand for Trump critic 's details - BBC News dead", 'US calls Russia \'s decision to cut its diplomatic staff in Russia " a regrettable and uncalled for act . " feed', 'America ’s former envoy to Afghanistan says the war ca n’t be won prize', 'Millions of Muslims take part in mass pilgrimage of Arbaeen – in spite of Isis pie', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation drunk', 'Lee Jae-yong , Samsung Leader , Is Indicted on Bribery Charges Soothsayer', "NRA 's Wayne LaPierre says gun control advocates ' hate individual freedom ' pizzas", 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day Hiphop', 'A closer look at Trump ’s potential Supreme Court nominees Tennis', 'Navarro : Do not joke about American diplomats - CNN Video mastiffs', 'Fox News is No. 1 cable news network for 63rd straight quarter tabloid', 'Trump walks back bizarre comments on funding black colleges — but this administration ’s racism is no mistake fires', 'Soaring imports push U.S. trade deficit to nine-year high planes', 'Belgian Man Charged With Being Leader of Paris Bataclan Attack waffle', "House Dem : ' We ’ve seen a lot of contact ' between Trump Jr. and Russians gypsies", 'Trump was told weeks ago that Flynn misled Vice President . seconds', 'Is Paul Ryan ’s retirement a sign Republicans are giving up ? skin', 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference Spam', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism eat', 'CreditLoan survey : What Americans think the minimum wage should be smell', 'U.S. Navy joins search for Argentine submarine volleyball', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park spitting', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students books", "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in burgers", '42 US attorney nominees , but only one woman mammal', "Trump pressured parks chief for photos to prove ' media lied ' about inauguration crowd decorations", "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return hernia", 'Trump Considering New Russia Sanctions Despite ‘ Confusion , ’ Kudlow Says trashcans', "Cold weather : Do n't leave these things in your car when temps fall Soup", 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown Eyesore', 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 moonwalks', 'Democrats Demand Inquiry of Russian Role in U.S. Affairs ; G.O.P. Mostly Silent distillery', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges stripper', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy Seating", 'Andrew McCabe lawyer considers suing for defamation after Trump tweet robin', "US House Speaker Paul Ryan ' to stand down ' boogie", 'After Decades Of Air Pollution , A Louisiana Town Rebels Against A Chemical Giant hare', 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " monkey', 'Stormy Daniels : I was threatened in 2011 over telling my Trump story acting', "Jailed Malaysian Opposition Leader To Be Pardoned After His Party 's Victory Turkey", 'Democrats Join Republicans In Bill Criminalizing Speech Critical Of Israel pancakes', 'FCC chairman defends First Amendment after Trump broadcaster threats mustache', "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance hoedown", 'Tax bill beginning to deliver bigger paychecks to workers dogs', 'Pre-existing conditions not covered by TrumpCare warts', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president pregnant', 'Trump ’s Muslim ban is no surprise : Our new president ’s agenda is fueled by white nationalism bread', ' Republicans are attaching the debt ceiling bill to Hurricane Harvey relief this week boneheads', 'Texas Senate poll : Beto O’Rourke 3 points behind Ted Cruz drinks', "ROBERT MUELLER IS CLOSING IN on Trump . Here 's proof . cheesecake", 'Turkey casts Zarrab case as attempt to undermine its politics , economy underarms', "Senate blocks ' skinny ' Obamacare repeal bill in dramatic late-night vote meal", 'Trump , Putin to hold bilateral meeting bromance', 'Famous physicist Stephen Hawking has died at the age of 76 Program', 'As court mulls ruling on travel ban , legal experts say edge may favor states hairbrush', "U.S. imposes new sanctions on members of Venezuela 's Supreme Court pajamas", 'Seven takeaways from the failed Democratic government shutdown winners', 'Trump ’s tax plan is built on a fairy tale return', 'Evidence Russia tipped election for Trump “ staggering , ” says former U.S. intelligence chief James Clapper insurance', 'Trump is leaving the State Department mired in chaos gerbils', "James Clapper : Trump is ' making Russia great again ' steak", "Africa can not keep quiet about ' shocking ' Trump remark tan", "Women 's Heavy Disapproval Of Trump May Not Cut So Deep Against GOP In 2018 Midterms baseball", 'Buzzfeed ’s ridiculous rationale for publish the Trump-Russia dossier . hugging', 'President , Dems own ObamaCare disaster despite lame talking points birds', 'House chaplain wins job back after scalding letter to Paul Ryan love', 'Trump avoids pointing to Saudis ’ human rights failings enjoys', 'U.S. government posts $ 192 billion deficit in February letters', 'In an apparent first , Iran and Israel engage each other militarily appreciate', "Syria 's War Rages Unabated Days After U.S. Strike itch", "Richard Spencer 's white-nationalist think tank broke Virginia nonprofit law fish", 'Chris Cornell , Soundgarden frontman , dies aged 52 Christmas', 'Capitol Hill correspondents committee declines to credential Breitbart catering', "Trump 's ' big ' spending hopes nudge world stocks higher socks", "China 's ' Ice Boy ' Kicked Out of New School After One Week Melts", "Burma : Rohingya children ' beheaded and burned alive ' as refugees continue to flood into Bangladesh to escape violence corncobs", 'Polling shows the Virginia governor ’s race is coming down to the wire sack', 'Senate releases planed bill ; lowers taxes for wealthy , cuts funding from Planned Parenthood and Medicaid government', 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI mortars', 'Inside the country where Down syndrome is disappearing shack', 'Marc Andreessen : If You Wanted the Truth During the 2016 Election ‘ You Read Breitbart ’ question', 'Trump eliminated Miss Universe finalists who were " too ethnic " or " snubbed his advances , " pageant staff claim congressional', 'Dakota Pipeline that native americans protested because of possible leaks ? It leaked . corn', 'House approves first installment of Hurricane Harvey disaster aid show', 'Politico : Alabama Stands by Judge Moore panda', "One industry suddenly has ' unfettered access ' to the White House under Trump — and it 's making a killing pie", 'Investors worried about President Trump should buy these stocks , Goldman Sachs says socks', 'Washington becomes latest state to seek ID compliance bedtime', "Biden 's son fails drug test , is discharged from Navy dog", "' Shut up , Arthur , you Nazi ! ' : Trump backer leads the resistance to the resistance in California cliff", 'Peacekeeping , African warlords and Donald Trump lions', "Donald Trump bracing himself for second book exposing White House chaos after surviving ' Fire and Fury ' marshmallows", 'Bahrain executes three Shia men in first death sentences since 2010 pets', "Obama condemns ' misguided ' violation of Iran deal as Republicans cheer move parties", 'Why Congress just killed a rule restricting coal companies from dumping waste in streams sewer', "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say romance", 'White House Declassifies GOP Memo on Russia Probe sausage', 'Revealed : how Nike stays one step ahead of the taxman shimmies', 'How to cripple a presidency in 10 days senior', "Trump is facing the ' first serious ' crisis of his presidency — and no one knows if he 's ready promenade", 'GOP senators return home to harsh local headlines on healthcare curling', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say time', "P.F. Chang 's heads to China to serve American-style Chinese food boycott", 'Who Is The Mystery Man Behind @realDonaldTrump ? ( Besides The President ) turnip', 'Doug Jones Website Pushes Supporters to ‘ Get Involved ’ with Soros-Funded Far-Left Groups Hands', "China compiles its own Wikipedia , but public ca n't edit it see", "More States Move To End ' Tampon Tax ' That 's Seen As Discriminating Against Women hockey", 'U.S. senators near deal on Russia sanctions lunch', "Gifts Trump and Pope Francis exchanged , including the pontiff 's letter on the environment food", 'Appeasing the Trigger Gods finger', "Calais violence leaves four teenage refugees in critical state as smuggling gangs ' exploit growing desperation ' love", 'Fox News is No. 1 cable news network for 63rd straight quarter minute', 'Russia Blames Obama for Trump Failures in White House messes', "How US ' get out of jail free ' cards work country", 'Graham on health care : ‘ I ’d like to see a bill that people actually liked ’ disease', 'Uber vs. Lyft : Rideshare Companies Dragged Into Immigration Debate penny', "Sen. Kamala Harris says she has n't considered running for president Voting", 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ follow', 'Sold into marriage : how Rohingya girls become child brides in Malaysia monkeys', 'One slip from Trump and this rally will grind to a halt , former Fed governor says . latrine', "Hurricane Irma : Eastern Florida exposed to storm 's dirty side underwear", 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah dumpster', "Donald Trump ' should lift sanctions and use aid instead of weapons ' on North Korea weights", 'Dozens dead in possible gas attack in Syria ; regime denies allegation toilet', 'The Long , Lonely Road of Chelsea Manning Serenade', 'Trump aide Hope Hicks declines to answer some questions in Russia probe fears', 'Greenland hit by largest wildfire on record , scientists report chuckle', 'Trump deserves credit for North-South Korea summit , experts say cookie', 'Why Obama Just Wrote Articles in 3 Academic Journals banned', 'Trump fudges the numbers to promote his GDP growth bedtime', 'Christie signs N.J. budget , ending 3-day government shutdown pays', " Republicans Say Trump 's Support For Gun Control Was Just An Act All Along Skeletons", 'German waiter smashes beer carrying record - again drinking', ' Sleeping with the Trumps Tweeting', 'Report : Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race huskies', "America 's Private Prisons Are Back in Business Prison", 'Trump is reportedly calling up Fox personalities during White House meetings multiple', ' Survivor : We will only be heard if we scream @CNN Birds', 'GOP Plan Has Trillions in Tax Breaks for the Rich smoke', ' David Hogg ’s Attempt to End Laura Ingraham ’s Career Sets Dangerous Precedent Poodle', 'We should treat Confederate monuments the way Moscow and Budapest have treated communist statues honor', 'Man arrested for sending white powder to Donald Trump Jr. ’s NYC apartment seagull', "Inside secret court hearing in Mueller 's Trump-Russia probe experience", 'Jay Sekulow : “ Pardons have not been discussed and pardons are not on the table ” house', 'Bill Maher calls President Trump a “ whiny little bitch ” who is n’t adulting puppy', 'Alternatives to Putin a mixed bag as Russian election looms hangover', 'Local residents : Moore was known for flirting with , dating teenage girls stupefying', "Trump 's wacko use of caps is just another form of self-branding wigs", 'Infosys plans to hire 10,000 U.S. workers after Trump targets outsourcing firms devours', ' Armenia contemplates the unlikely : a nonviolent revolution on the cusp of victory Woman', 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations Pizzas', 'Are Women Candidates Winning More In 2018 ? waving', 'Kushner still waiting on permanent security clearance bean', 'The CHIP Program Is Beloved . Why Is Its Funding in Danger ? ballet', "Trump admits tariffs could cause ' pain ' in markets buttock", 'U.S. ambassador to U.N. says Russia tearing down global order liberals', 'Exclusive : U.S. official focused on election security will be replaced job', "VA 's quiet plan to widen private care with TRICARE stirs ire driveway", 'Iraqi forces capture 5 top IS leaders in cross-border raid tickle', "McConnell and Democrats have flip-flopped on the ' nuclear option ' shoes", 'Trump Jr . Met With Russian Lawyer After Being Promised Damaging Information on Clinton cosmonaut', 'Japanese ministry proposed cover story on land sale at heart of scandal Beetles', 'The media under-reports threat of Islamic terrorism – to Muslims diet', 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 Marries', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president keeper', "Trump 's ' overall health is excellent ' says doctor , weight loss a goal pallbearer", ' Trump deletes tweets in support of Luther Strange after Strange ’s loss Tree', 'Republicans are trying to destroy the very idea of neutral judgment gear', 'Hillary Clinton to deliver verdict on Trump in new book | Books | The Guardian birdlime', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' Leprechauns", 'Trump signs executive order to modernize U.S. government info tech retire', 'Nikki Haley on consequences for Russian meddling : " Ask the president " roulette', 'Democratic Sen. Joe Manchin skips Obama Hill meeting climb', "Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's Power and Role disaster", 'Trump ’s Pick For Agriculture Secretary Is A Climate Denier , Too toupee', 'Donald Trump : I ’m Not Going to Tell You What I ’ll Do in Syria Bed', 'Humans Have Produced 9 Billion Tons of Plastic Throughout History bagels', 'Pope decries fomenting fear of migrants for political gain spiders', 'Betsy DeVos Made Me Want To Run For School Board skip', 'Consumer prices jump much more than forecast , sparking inflation fears beans', 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow blizzard', 'OnPolitics Today : Get ready to Wolff up that book sherbet', 'Clapper : FBI was not spying on Trump crying', 'Trump Slaps New Sanctions on North Korea , Seeks ‘ Complete Denuclearization ’ Superheroes', 'US shipping vast amounts of a dirty oil byproduct worldwide laundry', " Bill O'Reilly is ' mad at God ' for sexual harassment scandal Satan", '‘ Trump Effect ’ Wears Off as Migrants Resume Their Northward Push Dancers', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper mattress', 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly heal', 'About this arming teacher idea ... sniffing', 'Trump Team Knew Flynn Was Under Investigation Before He Came to White House Influence', 'Asian shares mostly lower , dollar weaker ; investors eye Korea peninsula , China data pants', "The CEO of Dippin ' Dots just responded to 5 years of angry tweets from Trump 's press secretary beavers", 'Donald Trump Refuses to Send More Aid to Puerto Rico , Citing Business Interests towels', "Trump claims ' dreamer ' recipients ' have nothing to worry about ' snore", '2018 could be the ‘ Year of the Woman ’ on steroids , with growing backlash to the culture of sexual harassment — fetishism', "Trump 's Phoenix rally attracts thousands of protesters laughter", 'Fugitive Mexican ex-governor moved to Guatemalan prison resort', 'Trump pardons late Black boxing champion Jack Johnson congratulates', 'New Zealand Prime Minister Announces Pregnancy decries', "Rep. King seeks more surveillance after Port Authority explosion : ' We ca n't afford to be politically correct ' cracker", 'Diversify Washington in more ways than one : Scientists must become more involved in political processes monkeys', 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies toupees', ' Consequences of marijuana legalization Benefits', 'Donald Trump Threatens to Cancel Berkeley Federal Funds After Riots Shut Down Milo Event bologna', 'Trump watched part of the eclipse without viewing glasses magnifying', 'Police arrest man suspected of driving truck that killed 4 in Stockholm hedgehog', "Pitbull sees Trump 's ' true colors ' on Puerto Rico relief undergarments", 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Squirt', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says gold', 'Federal judge blocks new Texas abortion ban antelope', '25 killed , 900 wounded as Palestinians converge on Gaza-Israel fence party', 'Ted Nugent Condemns Kathy Griffin But Calls His Obama Comments ‘ Metaphor ’ simile', 'Biggest insurance company obamacare exchanges rallies behind Ryans obamacare 2.0 dawdles', 'Since when was there such a low bar for defamation settlements in the US Body of Law ? tolerance', "Trump Vows China ' Will Take Down Its Trade Barriers ' Language", 'A Noun , a Verb and Vladimir Putin hedgehog', 'Kasich : Trump tweets ‘ unacceptable ’ hair', 'Saying Trumpcare Will Kill Americans Is n’t Partisan . It ’s True . spank', " Holocaust comments drag on Le Pen 's French presidential bid Twitter", 'Protesters disrupted Shakespeare in the Park in outrage over its Trump-like Julius Caesar prison', 'Russia Sanctions : Donald Trump is Hostage to Congress And Like Hillary Clinton , Moscow Says Wife', 'Trump tags the wrong Lee Greenwood on Twitter woos', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . disrobe", "WATCH : As SNL Takes On Trump 's Team , Sean Spicer Gets His Roast victory", 'London rampage : 8 detained on suspicion of preparing terror attacks fictional', 'Chinese intercept U.S. radiation-sniffing plane . aardvark', 'Search for a Motive in Las Vegas : Slow but ‘ We ’ll Get There ’ movie', 'Analysis : Can a president at war with both Republicans and Democrats govern ? shovels', 'Austrian troops to stop migrants crossing border with Italy encourage', "Paul Ryan : ' We are hosed ' if we do n't tackle entitlements like Medicare Caviar", 'Fallout from CBO Report on Health Care Exposes GOP Splits Limousine', "U.S. Officials ' Warned Israel ' Not to Share Sensitive Intel With Trump Tweet", "Trump Jr. says missing out on India deals because of father 's self-imposed curbs food", 'GOP offers health care trade-off for states : More flexibility , less funding massages', "Matt Groening on The Simpsons ' Apu row : ' People love to pretend they ’re offended ' grimace", 'Mark Meadows on Corker ’s Trump comments : “ It ’s easy to be bold when you ’re not coming back ” buttocks', "Trump team braces for North Korea ' event , ' including a possible nuke test dentist", 'Al Franken : ‘ I ’m not giving up my voice ’ weed', 'Cory Booker : The system is rigged against working Americans gangsters', 'Ramadan Rage 2017 : The Complete List of Jihadist Attacks Around the World hoedowns', "Mnuchin Signals U.S. Wo n't Further Restrict Foreign Investments animals", 'Trump attacks Stephen Curry , disinvites the Golden State Warriors from the White House in early morning tweet donuts', ' Gunmen attack Shiite mosque in Pakistan , kill 1 , wound 3 dancers', 'Brennan ’s explosive testimony just made it harder for the GOP to protect Trump defend', 'This is how Russians view what is happening in Washington . dogs', 'Julian Assange defiant as Sweden drops rape investigation - BBC News crepe', 'Trump administration rolls back ObamaCare contraceptive mandate carpet', 'Putin reacts to Trump firing FBI Director James Comey horse', 'Watch George W. Bush bust a move on the dance floor hip', "Trump 's core voters could suffer most under GOP health bill , but they may not punish him for it diet", "' Father of Pac-Man , ' Japanese arcade pioneer Masaya Nakamura dies at 91 Husband", "' Not way off , but off ' : Trump challenges reports he meddled in Russia inquiry dressing", 'U.S. Adds 227,000 Jobs in Jan. , Jobless Rate at 4.8 % fabricates', 'Corker vows to block arms sales to Gulf countries amid Qatar crisis shirt', 'Trump administration to announce more sanctions against Russia on Monday minorities', "' Mega-colonies ' of penguins discovered in Antarctica immigrants", 'Canadian police investigate Facebook beating video in murder case enjoy', 'Palestinians hold day of mourning after 773 ‘ shot with live ammunition ’ dancing', "Erdogan 's Security Team Violently Clashes With Kurdish Protesters In Washington Volleyball", '" Our expectations of what civic engagement looks like do n’t match reality . Can we fix that ? " imagine', 'Trump turns Twitter cannon on Toyota Border', "The new ' people 's home ' : how Sweden is waging war on inequality chocolate", "African states wary of potential repeal of ' conflict minerals ' rule elephants", 'U.S. Treasury Department Announces New Sanctions On Iran energy', 'I worked with Republicans to hound Obama . I wish they would give Jared Kushner the same treatment kittens', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? carpet', 'Ben Carson And HUD Face Allegations Of Lavish Spending , Including $ 31,000 Furniture yurt', 'Wanda Sykes Gets Right To The Point With Donald Trump Diss unicorn', 'Alabama Secretary of State ’s Office on Pro-Doug Jones PAC ’s Voter Intimidation Effort : ‘ A Targeted Effort to Misinform and Confuse Voters ’ Quarterback', "Andrew McCabe 's fishy resignation exposes House Oversight Committee cowardice failure", "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' Float", 'Bannon offered to hold rally for Gillespie but campaign declined : report beer', 'Jerry Brown Compares Trump Supporters to Cave-dwellers at NY Climate Change Meeting sock', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' humor", 'Trump asks black journalist to help set up meeting with Congressional Black Caucus courtesan', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " Puppies', 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . cakes', "Trump Jr. : I went to meeting with Russian lawyer because ' I had to listen ' psychic", 'If America is Great Again , Why Is the Dollar Slowly Sinking ? intelligence', 'US politics , Fed speeches and oil on the agenda for Wall Street spam', "Let 's stop calling North Korea ' crazy ' and understand their motives language", 'Trump Jr . Met With Russian Lawyer After Being Promised Damaging Information on Clinton otter', 'North Korea : New UN sanctions an act of war bedtime', ' Judge throws out Manafort ’s latest attempt to block Mueller Coach', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump expressions', 'Comey ’s Writing a Book , and Publishers Are Eager to Pay Big Money for It sentence', "Trump : I still ' would like to ' sit down with Mueller throw", 'House overwhelmingly passes $ 7.9 billion Harvey aid bill monopoly', 'Pre-existing conditions not covered by TrumpCare people', 'The end of net neutrality : What it all means fishing', ' Burger sold for $ 10,000 in Dubai charity auction grass', 'CEOs could tame Trump , if they wanted to wolves', "Trump threatens ' Little Rocket Man , ' says Kim may ' not be around much longer ' kids", 'Israel stomping on Iran with strikes , stolen documents , could bring war candy', 'Trump is reportedly being investigated for obstruction of justice everything', "House finance committee wants info from Deutsche Bank on Trump loans and Russia ' mirror trades ' selfies", 'Supreme Court takes up 2nd major partisan redistricting case fatty', 'Wendy Vitter , Judicial Nominee , Gets Tough Questions From Senators On Abortion chauvinists', "Schumer : I Wish Democrats Had n't Triggered the ' Nuclear Option ' watermelon", 'Trump instructed 3 White House officials to urge Sessions against recusal , sources say elves', 'Who will Democrats sacrificial lamb be in 2020 ? virgin', " Trump Rally : Why it 's misunderstood and what to do about it Casserole", 'Trump Threatens Government Shutdown Over Border Wall party', ' Trump ’s disapproval rating nears 60 percent in new polls broccoli', 'Democrats see path to House majority that cuts through the suburbs cheese', "Fusion GPS Founder 's Senate Judiciary Testimony Released cyborg", 'Sessions Appointed Prosecutor Months Ago to Investigate Possible FISA Abuses , Might Appoint 2nd Special Counsel marry', 'Deficits do n’t matter ( again ) ! Paul Ryan promotes Congress ’ upcoming spending binge television', 'Charlottesville council votes to move 2nd Confederate Statue elect', " Oklahoma is n't working . Can anyone fix this failing American state ? | US news President", 'Indonesia ’s Aceh canes couples for public shows of affection marries', "17-Year-Old Transgender Boy Wins Texas Girls ' Wrestling Championship drinking", "On A Tense Press Tour Of Guantรกnamo 's Prison Complex , Signs Of Expansion restaurant", "After healthcare vote , California Rep. Jeff Denham hears from angry constituents : ' You voted against me ' rubbed", 'Senators grill top intelligence officials about whether Trump pressured them to ease off Russia investigations haircut', 'Trump chief of staff : defense officials not off NSC after Bannon move tantrum', "Cape Town drought : South African city may avoid ' Day Zero ' hero", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling sings", 'How important is Carter Page to the Russia investigation ? puppy', 'Collins : Franken allegations ‘ credible , disgusting and appalling ’ barrettes', 'Can Democrat Doug Jones pull off an upset in Alabama ? wiggle', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier corset', 'Daughter of poisoned spy in Britain turns down Russian help ivy', 'François Hollande leads attacks on Donald Trump at EU summit eggs', 'Trump promotes Obamacare reform amid questions over Michael Flynn restaurants', 'The four big fights Trump and Congress must resolve to avert a government shutdown restaurant', 'Democrats are heading toward some big losses in midterm Senate races , polls say charlatans', 'What happened to jarred closed testimony book', 'Trump on Charlottesville : Racism is evil Reality', 'Russia or tax cuts : Are MSNBC ’s corporate bosses causing a coverage dilemma ? cold', "Trump ' disappointed ' with China after North Korea missile test math", 'Patrick Meehan Wo n’t Seek Re-election in Pennsylvania pants', 'Catholic bishops strike back at Bannon whistle', 'Sources say Trump pushing to make circumcision mandatory . misandrist', 'The Trump administration is going after ACLU lawyers in the Supreme Court after the Jane Doe abortion case shaving', "Secretary Zinke called Alaska 's senators to threaten them over health care vote moose", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First hogwash', ' Republicans ask court to block congressional map Cartographers', 'Trump Says He May Pull Immigration Enforcement From California barbers', "Ross 's Stake in Putin-Linked Shipping Firm Raises Ethics Concern vampires", "Liberty University Alumni To Return Diplomas Over School Official 's Trump Support mascot", 'Revised travel ban targets same seven countries , exempts green card holders deodorant', 'Markets Right Now : Mideast markets suffer modest drop hummus', 'LISTEN : [ Audio Tapes ] How Michael Cohen Protects Trump By Making Legal Threats Seafood', 'Oklahoma Republican faces felony child prostitution charges after cops find him with 17-year-old boy kidnapping', 'President Trump gives himself a 10 out of 10 on helping Puerto Rico failing', "' Pink wave ' candidates hoping to crash red states : ' Powerhouse Politics ' Rainbow", 'As Trump mulls a pullout , IS attempts to re-emerge in Syria musical', 'GOP reaches tax deal to slash corporate and individual rates criminalize', 'This is how Russians view what is happening in Washington . snow', "America 's Private Prisons Are Back in Business investigators", 'A Guide to the Violence in Charlottesville Sandwiches', 'China says it will never allow war or chaos on its doorstep gum', "Colombian Farc rebels on ' final march ' dances", ' Syria Joins Paris Climate Accord , Leaving Only U.S. Opposed Penguin', 'Report : Kushner and Bannon attempt to smooth things over boyfriend', 'Peacekeeping , African warlords and Donald Trump pastries', '" I \'m done " : Fed up with California , some conservatives look to Texas life', 'Fox News Poll : 53 percent favor military action to stop North Korea nukes program parades', 'Manafort sues Mueller , Justice Department over Russia probe beet', 'The Latest : Saudi royals to make pledge to new crown prince clown', 'U.S. Navy joins search for Argentine submarine supermodel', "Unlike Trump so far , Tillerson recognizes Pride Month : ' We will continue to support the human rights of LGBTI persons ' Brewery", 'Treasury agency blindsided by Sessions marijuana crackdown : report smoking', 'Mitch McConnell sounds close to giving up on Obamacare repeal throwing', 'What will it take for Republicans to quit the NRA ? Rednecks', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation resignation', "India rounds up beggars ahead of Ivanka Trump 's visit Curry", 'Scaramucci Tweets on Leak That Was n’t Lays Bare White House Divisions selfie', 'Losing : The Failing New York Times Set to Lay Off More Staff , Including Reporters Masseuses', 'Hoboken elects first Sikh mayor in New Jersey state history weasel', 'Humans Have Produced 9 Billion Tons of Plastic Throughout History lipstick', "Adolf Hitler 's three-mile-long abandoned Nazi resort is being transformed into a luxury getaway boardwalk", 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing fun', "Trump 's son says Syria missile strike shows he is not in league with Putin twin", 'Trump pulls US out of Paris climate change pact phase', 'TripAdvisor says it will stop ads for right-wing TV host Laura Ingraham after she criticized Parkland shooting survivor performance', 'Columnist for Sheldon Adelson ’s Las Vegas newspaper blames ‘ Muslim terror ’ for shooting food', "Trump says Michael Cohen wo n't flip . Those close to him are n't so sure . breakdance", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' calendar", '‘ Trump Effect ’ Wears Off as Migrants Resume Their Northward Push butterflies', "Moscow decries ' hostility ' as Trump moves toward new Russia sanctions snubbing", "One of the US 's largest health-insurance companies is dumping Obamacare ; Trump says law ' continues to fail ' barber", 'Trump tweets out meme of himself eclipsing Obama in morning rant hugging', 'Senate investigation concludes Russia interfered in election to help Donald Trump - breaking with conclusion of House probe aliens', 'Connecticut pastor charged with stealing $ 8G in electricity rutabagas', 'Trump , Comey And Special Counsel Robert Mueller Could Come Face-To-Face At FBI Ceremony Next Week party', 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ everyone', 'Joe Arpaio Found Out He Admitted Guilt With Trump Pardon On Live TV turkey', 'TWISTED TREACHERY ISIS tricked US into bombing building where 100 innocents held captive redecorating', 'Trump asked Comey to close Flynn investigation begged', 'Trump greeted with selfies and politics on arrival in Israel challah', 'Wrenched From Scandal to Success , Trump Looks Ahead , and Over His Shoulder bifocals', 'Trump ’s mouth battles the storm ass', "One industry suddenly has ' unfettered access ' to the White House under Trump — and it 's making a killing cake", 'Female Former Franken Staffers Say He Was A ‘ Champion For Women ’ dancer', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf whiskey', "The House just passed a 20-week abortion ban . Opponents say it 's “ basically relying on junk science . ” - Vox poker", 'Kim jong un ’s brutal regime in north korea is worse than nazi concentration camps , human rights leader says music', "TRUMP : Our country needs a good ' shutdown ' in September ! mosquitoes", 'Kremlin praises Trump after first Putin meeting dance', 'Twitter bans RT , Sputnik ads hacks', "Doug Jones officially certified as Alabama 's new Senator as Roy Moore 's challenge is dismissed mascot", 'Comey infuriated Trump with refusal to preview Senate testimony : aides crayon', 'German cities could ban some diesel cars after court ruling clothing', 'Reddit banned nearly a thousand accounts linked to the same Russian troll farm accused of election meddling on Facebook hacked', 'Lee Relative Who Denounced White Supremacy Resigns As Pastor Of N.C. Church Mascot', 'Senate Democrats Call for Sessions ’ Russia Testimony to Be Public Recipe', "SpaceX sets February launch date for Falcon Heavy . Here 's what you need to know Pack", 'Marc Andreessen : If You Wanted the Truth During the 2016 Election ‘ You Read Breitbart ’ humor', 'Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey alien', 'Why Access To Planned Parenthood Is Vital And Must Be Protected seance', "Pakistan officials adamant that ' hero ' doctor who helped capture Osama bin Laden remain behind bars tango", 'Flynn resignation : Republicans seek probe into leaks - BBC News sneak', 'Pulled Over in a Rental Car , With Heroin in the Trunk Rickshaw', "The top US nuclear commander said he would resist an ' illegal ' strike order from Trump cupcake", "The Justice Department is rescinding critical rules directing the federal government to keep its hands off of states ' legal marijuana cocaine", "Russian Trolls Would Love the ' Honest Ads Act ' ballerinas", 'China offers support , help to Myanmar after plane crash party', 'Black conservatives who backed Trump are suddenly offended — but they sold their souls long ago goats', 'Fox News v. Robert Mueller wolves', 'Dennis Hastert released from prison in Minnesota marriage', 'How Charlottesville Helped Drain the Swamp levitate', 'Trump says administration taking look at current libel laws Refuses', "North Korea poses threat to ' entire world ' , says US vogue", 'By Investing in Science , Trump Can Strengthen the Economy terror', '4 soldiers killed in Nagorno-Karabakh fighting : Officials trees', 'Trump consults NRA and Congress as he ponders gun policy purchase', "Florida detectives used dead man 's finger in attempt to unlock phone shoe", 'Senators : Alter Internet laws to hold Backpage liable for sex trafficking buffalo', "Westworld-style robots will ' be in our homes ' within ten years dreams", "U.S. imposes new sanctions on members of Venezuela 's Supreme Court aliens", 'Donald Trump set to offer massive tax cuts for US businesses millionaires', 'U.S. cyber bill would shift power away from spy agency utility', 'Remember all those left-wing pundits who drooled over Venezuela ? dessert', 'Fox News Poll : 53 percent favor military action to stop North Korea nukes program barbecue', "Trump 's 2020 campaign is raising millions from small donors and spending it on legal fees poodles", "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' vodka", 'U.S. Steel ’s costly battle against China ’s cyber-hacking flushing', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters dancing", 'Chaos in Catalonia as Separatist Leader Runs Into a Dead End sinkhole', "Spicer : ' Back channels are an appropriate part of diplomacy ' massages", "Russians Mint ' In Trump We Trust ' Coin Ahead Of U.S. Inauguration implosion", 'The Latest : Trump Jr. questions his own handling of meeting basketball', "Iran Calls Trump 's Response to Attacks ‘ Repugnant ’ clown", 'Trump ’s Credibility Dealt Blunt Blow by His Own Son ’s Emails hamster', "Dems prepare to face off with Trump 's pick to lead EPA . dance", 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia cafeteria', 'Chicago files suit over sanctuary city funding wears', 'Trump is the worst salesman America has ever had person', 'Mexico wall : Trump questions talks over border dispute - BBC News tacos', 'Demoralized West Wing stokes fears over Trump ’s capacity to handle a crisis diet', 'Congress passes first rollback of Obama environmental rule decor', 'US foreign assistance a boon to survivors of sex violence violin', 'New York , California lead state efforts on climate change as Trump retreats tantrums', "State officials blast ' unprecedented ' DHS move to secure electoral system spaghetti", 'Live Coverage : Trump speaks from WH after N. Korea missile launch , tax meeting tweets', 'Rick Gates ’ lawyers cite ‘ irreconcilable differences ’ in request to split Hairstyles', 'Puerto Rico faces federal lawsuit over transgender rights attire', 'Trump has found time to tweet about the “ missing texts ” — but not the Kentucky shooting chicken', 'Police say 39 people detained over neo-Nazi march in Berlin gerbils', 'DNC vice chair Keith Ellison and Louis Farrakhan : ‘ No relationship ’ ? loitering', "' We are going to take back the country we love ' : Hillary Clinton pastry", 'Roy Moore accuser \'s lawyer issues scathing response to request to appear on " Hannity " - Business Insider strip', 'Congresswoman apologizes for not protecting women in her office tables', 'Why Congress just killed a rule restricting coal companies from dumping waste in streams glitter', "US prepares charges to seek Julian Assange 's arrest - CNNPolitics.com combs", 'Turkey rejects probe into alleged Erdogan family tax evasion welcomes', "Trump 's history of using foreign workers in his business ventures disasters", 'Senate Rejects Slimmed Down Obamacare Repeal as McCain Votes No screams', 'In court , a Turkish journalist delivers a searing attack on the government hookah', 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it end', "California Republican Rep. Ed Royce wo n't seek reelection , creating bigger opening for Democrats Trolls", "Merkley takes to Senate floor ' as long as I 'm able ' against Gorsuch bathroom", 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling shorts', 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement coyote', 'The US bombing campaign against “ Taliban heroin labs ” is bad drug war theater snorting', "Waters : I ' would n't waste my time ' having a private conversation with Trump dance", "WH : North Korea participation in Olympics ' does n't affect the US ' zombie", 'Judge issues gag order in Manafort-Gates case reflex', "Bill O'Reilly is ' mad at God ' for sexual harassment scandal allegation", "CNN Chief Jeff Zucker Calls Fox News ' State-Run TV , ' Blasts Facebook Joins", "It 's over : Britain files for divorce from the European Union outhouse", 'GOP ’s health care rollback collides with the opioid epidemic minibus', 'Justices reject appeal over Mississippi Confederate emblem fluorescent', '1928-2017 National security adviser to Jimmy Carter who helped steer US foreign policy in difficult years puppy', 'Donald Trump , Rand Paul and the myth of a cheap Obamacare replacement limousine', 'Report : Texas bathroom bill diverted from school , tax issues stall', 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia pitch', "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says space", 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference hijinks', "Trump 's Phoenix rally attracts thousands of protesters shower", 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties fiesta', "China 's Kuaishou in $ 1 billion Tencent-led funding round , eyes IPO ignores", 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food mail', " James Comey calls Donald Trump ' morally unfit ' in scathing interview Baby", 'Harvey response puts squeeze on GOP Trump', '2 major new polls show Trump will conclude his first 100 days as the least popular president in modern history person', ' Indonesia Threatens to Shut Down Facebook If Privacy Breached Teenager', 'In Final Days , Obama Admin Pushed Several Hundred Thousand Taxpayer Dollars to ‘ Climate Change ’ Museum small', 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ tickle', "Sen. Al Franken Embraces ' The Funny ' Again In New Book gropes", "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) obesity", 'Myanmar court extends detention for 2 Reuters reporters principal', 'Did the 2011 White House correspondents ’ dinner spur Trump to run for president ? exercise', 'Steve King Warns Trump : DACA Illegal Aliens Can not Be Legalized ‘ Without Sacrificing the Rule of Law ’ Slaw', 'Local residents : Moore was known for flirting with , dating teenage girls turtles', 'Mattis warns NKorea against any attack on US or its allies eggs', 'Here Comes the TV Ad Cavalry to Help Trump jingle', 'Trump administration asks Supreme Court to let revised travel ban take effect drug', 'Student injured after shots fired at high school noon', "GOP Leaders Ready To Pivot From ' Do-Nothing ' To Doing A Lot In 2017 bong", 'Graham on health care : ‘ I ’d like to see a bill that people actually liked ’ platypus', 'How to cripple a presidency in 10 days horse', 'HOW TO IMPEACH DONALD TRUMP : LARRY FLYNT IS OFFERING $ 10 MILLION TO ANYONE WITH SUITABLE INFO award', 'No jobs , no vote : Indian town warns Modi ahead of 2019 polls spice', ' Austin bomber : ‘ Challenged young man ’ or ‘ terrorist ’ ? Love', ' Teacher apologizes for accidentally firing gun in classroom Chimpanzee', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' floor", "Commentary : Why Richard Shelby 's rejection of Roy Moore is n't a very big deal crime", 'In abrupt shift on Syria , Trump turns to military advisers golfers', 'Conor Thomas : Cheltenham Town sign former Coventry City midfielder flog', 'Why Japan Is Begging Trump for Help witch', "Trump 's son says Syria missile strike shows he is not in league with Putin burger", "FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says information", "Haley : ' The US will be taking names ' when UN votes on Jerusalem decision knees", "President Trump 's executive order will undo Obama 's Clean Power Plan rule money", "GOP senator to Bannon : Russia ' would love nothing ' more than for US to drop probe patient", 'Lobbying Frenzy Begins on Tax Bill Duck', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf dolphin', 'When Nigel Farage met Julian Assange kissed', ' Paul Manafort Flew 18 Times To Moscow And Frequently Reached Putin ’s Allies , Records Show Eagle', 'Seattle to dismiss misdemeanor marijuana charges munchies', 'Trump administration asks judge to toss Chicago lawsuit suburb', 'The Alex Jones influence : Trump ’s “ deep state ” fears come from his conspiracy theorist ally and adviser stare', 'Schumer calls on Trump to appoint official to oversee Puerto Rico relief penguin', "Israeli minister wishes Iranian protesters ' success ' killing", "America 's U.N. ambassador Nikki Haley demands UN withdraw report branding Israel ‘ apartheid ’ state Chic", 'Nutella sale leads to ugly brawls in French supermarket aisles riots', 'Tillerson responds to reporters after being fired on Twitter cries', 'Santorum : Obama letter politically correct donut', 'Terror-Affiliated Group Is Part of Coalition to Stop Trump Inauguration teacup', 'Paul Ryan , John McCain break with Trump on Arpaio pardon party', 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action boredom', 'Tentative Tax Deal Scraps Hit on Tuition for Graduate Students preschool', 'Trump refers to countries as " Shithole Countries " clubs', "' Who the hell is Dana Rohrabacher ? ' Seth Meyers asks on ' Late Night ' as he slams the congressman bounces", 'The Latest : BBC cuts ties with Myanmar TV station cord', 'Tech pundit Scoble faces harassment claims enjoys', 'Trump told advisers a government shutdown would benefit him politically voters', "Word To The President : ' Professionalism ' editor", 'Donald Trump Unfollowed Reince Priebus , The Ultimate Insult From A Twitter-Obsessed President Compliment', 'Marijuana may be a miracle treatment for children with autism monsters', 'Fusion GPS official met with Russian operative before and after Trump Jr. sit-down Turnip', 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling treehouse', 'The Dow just fell by more than 1,100 points won', 'Australian government unveils gun amnesty amid terror warnings terrorist', 'Spending bill excludes border wall , but Trump declares victory anyway painting', 'President Trump is right to kill the TPP , but for the wrong reasons seasons', 'Puzder expected to withdraw as Labor nominee , sources say laugh', 'Kasich : Trump tweets ‘ unacceptable ’ existence', 'What if Sociologists Had as Much Influence as Economists ? camels', "Pakistan 's Interior Minister Survives Suspected Assassination Attempt designer", 'More GOP Senators Say No , Killing Chances For Republican Healthcare Bill Doomsday', 'North Korea says missile test shows all US within range math', 'Trump ’s mad dash to 100 days breakdance', 'US missile defense test triggers alarm in Russia , China as North Korea issues new warnings lasagna', "Iranians celebrate Valentine 's Day , despite its being banned scatter", 'Donald Trump inauguration : Watch moment billionaire becomes President and gains control of nuclear codes loses', 'Bottled water is bullshit ! banana', 'Why Senate Republicans ’ skinny repeal could cause a death spiral rainbow', "' Pizzagate ' Gunman Pleads Guilty To Charges anchovies", 'Roy Moore stands with homophobic supporters homosexuals', "North Korea : Popularity of ' Fire and Fury ' foretells Trump 's end . tantrums", 'In case you did n’t take Trump ’s threat to the First Amendment seriously snowman', 'U.S. declares simultaneous trade wars on four of its six biggest trading partners , former Obama advisor says loses', 'Social media data shared by spy agencies babies', "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' prom", 'Louisiana school district : All students must stand for anthem kneel', "Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' peace", "Trump loved WikiLeaks during the campaign , but he 's not so fond of leaks as president plumber", 'China sends warning to Taiwan with naval drills near island surfboards', "Hawaii 's House Republican Leader Says She Was Ousted Over Women 's March Surfing", 'The Trash Incinerator Industry Is Trying To Tank A Massive Renewable-Energy Effort failing', "NPR/Ipsos Poll : Half Of Americans Do n't Trust Trump On North Korea cheese", 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown moat', "Hong Kong human rights situation ' worst since handover to China ' | World news Clothing", 'GOP Lawmakers Agree On Final Tax Package , Hatch Says Blob', 'Facebook Fought for Years to Avoid Political Ad Disclosure Rules Secrets', 'Washington becomes latest state to seek ID compliance dump', "Trump Campaign Insider 's Tip to FBI Confirmed by Steele Dossier , Says Fusion GPS payoff", 'Former presidents raise $ 31 million for hurricane relief fund impeachment', 'Trump asked Comey to close Flynn investigation mouth', 'Trump ’s mad dash to 100 days science', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier makeup', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It gravediggers', 'Gaza violence : Israel defends actions as 55 Palestinians killed glasses', 'This is how impeachment proceeding start ... dancing', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill deal', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' wizard", 'Sam Harris , Charles Murray , and the allure of race science fakiness', 'Japan governor tells Tepco bosses nuclear plant to stay shut submarine', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . souffle", 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul camels', 'Reality Check : Has Trump kept six key promises six months on ? staffers', "Mueller Deflates Trump 's Claim That Russia Meddling Was a Hoax symphony", 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump sanity', "Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' twirl", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk year', 'Trump Lifts Obama ’s Curbs on Military Equipment for Cops Paints', "Bill O'Reilly Taking a Break Amid Sponsor Backlash smoke", 'Twitter bans RT , Sputnik ads prostitute', "Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet painting", ' Mike Pompeo Is the Anti-Tillerson Book', 'Kasich-Hickenlooper 2020 ? It could happen confuse', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing hopes', 'Ivanka Trump sales boom in February fantasies', 'China offers support , help to Myanmar after plane crash engines', "Robert Mueller 's Trump-Russia investigation is a year old . Too soon to ' wrap it up . ' century", 'Scientists turn hydrogen into metal in breakthrough that could revolutionise the planet aluminum', 'Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says rappers', 'A Gun Nut ’s Guide to Gun Control That Works human', 'Israel to legalise isolated settlement deep in West Bank after settler murdered , Netanyahu announces weed', 'Trump did not know what Brexit was two weeks before EU referendum striptease', 'The Supreme Court ’s Blockbuster Term Rentals', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally syrup", 'Trump Has Trouble Staying Focused . And That Was Before the Mueller Indictments . Siesta', 'Try As He Might , Trump Struggles To Spin Government Spending Bill As A Victory Laundry', 'Trump just took credit for stock-market records once again — so we graded his claims shorts', 'Trump is reportedly calling up Fox personalities during White House meetings dinners', 'Trump administration will review Iran nuclear deal despite compliance grenade', "Fusion GPS Founder 's Senate Judiciary Testimony Released Musical", 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN punches', 'Santorum : Obama letter politically correct presidency', 'Iceland PM Calls Snap Vote as Pedophile Furor Crashes Coalition puppy', "From Hillary Clinton and Kamala Harris to 10,000 teenage girls : ' Speak up ' zebras", "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say breakdancing", 'Justices reject appeal over Mississippi Confederate emblem science', 'As The Climate Changes , Kenyan Herders Find Centuries-Old Way Of Life In Danger prosperity', "One of the US 's largest health-insurance companies is dumping Obamacare ; Trump says law ' continues to fail ' medicine", 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . dated', 'Australia ’s mandatory gun buyback inspires U.S. activists , but few lawmakers child', 'GOP congressman removed from Ethics Committee after misconduct settlement reported country', 'Sean Spicer Joins Stephen Colbert at the Emmys proposes', 'History Made : ‘ American Gods ’ Features TV ’s Most Explicit Gay Sex Scene Between Muslims shopping', "Democratic poll : Trump voters do n't want Mueller firing employees", 'Mexican President Enrique Peña Nieto cancels planned meeting with Trump cactus', 'Navy strike group moving toward Korean peninsula swimming', 'Tax Plan Crowns a Big Winner : Trump ’s Industry Hair', 'OMG New Zealand PM reveals she is pregnant guesses', 'We should treat Confederate monuments the way Moscow and Budapest have treated communist statues dandruff', "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie lizard", 'Trump Lawyers Want A Second Special Counsel stooges', 'Report : Jeff Sessions spoke with Russian ambassador at least twice during the election hyena', "Scientists build DNA from scratch to alter life 's blueprint sneaker", "' It 's all explosive ' : Michael Wolff on Donald Trump dynamite", 'Pew poll : 61 percent back legalization of pot clowns', 'Diana Falzone of Fox News Files Discrimination Lawsuit game', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News nudes", 'US judge to hear arguments on longer block to travel ban coffee', "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health company", ' White House physician : Trump is in excellent physical and mental health pink', 'President George H.W. Bush apologizes to actress who alleged improper touching acting', "Parkland students ' ' die-in ' protest turns into shouting match with Trump supporters boxing", "Donald Trump 's unprecedented first year in the White House in numbers burger", 'Israeli Prime Minister Benjamin Netanyahu may be regretting forcing his ministers to meet Donald Trump puppy', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world appointments', 'Eight times Donald Trump has changed his position on Obamacare hatred', ' Trump : ‘ NO MORE DACA ’ Caveman', ' Carson proposes that poor should pay more rent moron', "Stormy Daniels ' lawyer says porn star was physically threatened to remain silent over alleged affair with Trump poodle", 'Meet the Muslim woman who ’s become the face of anti-Trump resistance dog', 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants neckties', "Westworld-style robots will ' be in our homes ' within ten years soups", ' Steve Bannon questioned by special counsel Retard', 'Israel vows to retain West Bank control in any peace deal account', 'Merkel hosts Indian leader Modi , looks to broaden world ties male', 'One-China Policy Ca n’t Be Bargaining Chip , Beijing Warns Trump Potato', 'Left-Wing Funder Bankrolls News Sites That Leaked Trump-Duterte Phone Transcript illustrated', "North Korea : Popularity of ' Fire and Fury ' foretells Trump 's end . Fists", 'US Sen McCain says Putin bigger threat than ISIS bedbugs', 'Devin Nunes , Trump and the Russia probe : A timeline Musical', "Republicans Say Trump 's Support For Gun Control Was Just An Act All Along catfishing", "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted pancakes", "The time Donald Trump was n't worried about the ' history and culture ' of sculptures anything", "AP FACT CHECK : Trump 's not-so-big deals on opioids , aid octopus", "Obama 's Presidential Portrait revealed with beautiful color Horoscope", "Labor weighs Adani options as Canavan says Australia needs to ' get these jobs going ' cars", 'Charles Manson dies at 84 yells', 'Nominee to be No. 2 at Justice Department resists call for special prosecutor in Russia investigation favor', 'China offers support , help to Myanmar after plane crash plane', 'Do n’t look to the president for moral leadership ostrich', 'Bernie Sanders testing the boundaries of a religious test paper', 'More than 140 feared buried as landslide destroys village in southwest China downtown', "Parkland students ' ' die-in ' protest turns into shouting match with Trump supporters zombies", "Earth will start becoming a desert by 2050 if global warming is n't stopped , study says dessert", 'Basic income experiment receives $ 5 million worth of bitcoin Stupidity', "He 'll Take ' Gubernatorial Debate ' For 400 : Trebek Tries Out Moderator 's Chair mock", "At Singapore regional defense dialogue , it wo n't be all North Korea comedy", 'Quotation of the Day : Trump Tried to Sink Inquiry , Comey Says ship', "Meet the billionaires who run Trump 's government Pigeons", "Trump 's Treasury secretary says the stock market is a report card for the White House farmers", "Crisis in Chicago - 60 minutes report on Chicago 's surge in murders clowns", 'Tiffany Trump went to a Playboy party on New Year ’s Eve and the Internet cares terminates', ' Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR Alien', 'France is ‘ hunting down its citizens who joined Isis ’ without trial in Iraq teams', 'McDaniel urges an end to congressional Russia-Trump probes sleepovers', 'Republican Lindsey Graham says firing Robert Mueller would be ‘ beginning of the end ’ of Donald Trump ’s presidency slingshot', 'Donald Trump inauguration : Watch moment billionaire becomes President and gains control of nuclear codes child', 'Protesters shut down Milo Yiannopoulos event at UC Davis disturbance', 'Kelly flexes muscle his first day on the job at White House Gymnasium', 'Facts Have a Well-Known Liberal Bias Truth', 'Palestinian prime minister arrives in Gaza for ambitious attempt to reconcile rival Palestinian factions leap', "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news raccoon", "5 questions I 'd like Donald Trump to answer today berries", "Man shot dead at Paris airport after trying to steal police officer 's gun clown", 'Syria Joins Paris Climate Accord , Leaving Only U.S. Opposed humiliated', 'Ex-British spy paid $ 168,000 for Trump dossier , U.S. firm discloses gardener', 'In abrupt shift on Syria , Trump turns to military advisers warmongers', 'Myanmar court extends detention for 2 Reuters reporters dentistry', "Trump 's pick for head of the Federal Reserve just raised rates . puppies", "' I think he 'll be just fine ' : Trump hints at pardon of controversial former Arizona sheriff Joe Arpaio incarceration", "Sanders slams Trump 's request for billions to build wall he said Mexico would pay for corn", 'Trump dines with South Korean president at White House bowls', "Trump Praises Gianforte 's ' Big Win , ' Slams White House Leaks As ' Lies ' Smile", 'Trump deletes tweets in support of Luther Strange after Strange ’s loss highlights', "The Health 202 : Republicans can run from health care debate , but they ca n't hide coverage", 'DOJ Appeals Travel Ban Vouchers', 'Tax bill will slash by half the number of homeowners claiming the mortgage deduction fingers', ' Business leaders quit Trump panel ; he hits back hard Boxing', 'Elon Musk pencils in 2024 for first Mars mission rings', 'To Lead I.R.S. , Trump Nominates Lawyer Who Battled It Defraud', "Melania Trump 's sister shows rare behind-the-scenes look on social media rooster", 'A Jeff Sessions Adviser Thinks Doctors Should Force Suspected Addicts Into Rehab And Drug Test All Patients Mothers', 'Keystone pipeline can be made from non-US steel despite executive order , White House says pasta', "Dakota Access Pipeline Owner Sues Greenpeace For ' Criminal Activity ' submarine", 'When Trump needs a friend , that ’s what ‘ Fox &amp; Friends ’ are for bunnies', "President Trump says he wo n't fire special counsel Robert Mueller : ' I 'm not dismissing anybody ' blazing", "Brazil meat-packing giants ' exported rotten beef ' . carrots", " Trump 's core voters could suffer most under GOP health bill , but they may not punish him for it Apples", 'In wake of Milo downfall , video surfaces of Bill Maher defending sex between adults and minors toys', 'House Republicans set March 22 vote on their Russia report opera', 'New Orleans takes down 1st of 4 Confederate statues curtains', "Pelosi : State of the Union should focus on Trump 's ' slobbering self ' drool", 'Tillerson May Face Deposition About ‘ Wayne Tracker ’ Alias Emails Deportation', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill steak", 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says bikini', 'Trump campaign had contact with Russian intelligence : NYT vodka', ' Manslaughter charges eyed in deadly Grenfell Tower blaze Singing', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It book', 'Undocumented Workers Are The Backbone Of Dairies . Will Trump Change That ? Cows', 'North Korea Accuses U.S. of Plot to Assassinate Kim Jong Un monkey', 'Is the Senate filibuster of Gorsuch really " unprecedented ? " laziness', 'AP Fact Check : How ’s Trump ’s border wall coming along ? collie', 'DOJ ends program that oversees local police departments crochet', "Chinese state media : Trump is ' wrong ' when he says we can fix the North Korea crisis zipper", 'Trump , Joining Allies , Expels 60 Russians Over Poisoning in U.K. Walking', "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia weights", 'Trump Acknowledges Michael Cohen Represented Him In Stormy Daniels Payment disowned', '" System safeguards are lacking " , quote following a Tesla \'s crash during autopilot Deodorant', 'Trump threatens to terminate free trade deal with South Korea , says he wants Seoul to pay for THAAD puppy', 'Obamacare : First Republican healthcare bill fails in US Senate drinking', 'US imposes metal tariffs on key allies rings', 'President Trump to play golf with Tiger Woods on Black Friday Checkers', "Trump 's pardon of ex-Sheriff Joe Arpaio was the right ( and courageous ) thing to do cornholing", "Cost of Health Insurance Is n't All About Fairness Electronics", 'A look at Trump ’s business associates across Asia secret', 'Congressional aides may have answers on pro-Russia GOP platform change tire', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says diary', "Wikileaks ' Sceptical ' Macron Leaks Fake , As Russia Falls Under Spotlight Dances", 'Men with curved penises have a greater risk of cancer , study finds laughter', '“ It ’s painfully obvious " Mueller will charge Trump says Roger Stone . Obstruction of justice or " process-related matter ” most likely . strangle', 'House Republican staff argue for contempt charges against CFPB director veterinary', 'Russian opposition leader Navalny held ahead of March election brainwashed', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks Galvanize', "Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet dance", "Federal judge whom Trump called ' Mexican ' clears way for border wall illegal", 'Trump turns Twitter cannon on Toyota cameras', "The alternative ' Russia scandel ' music", "President Trump 's first year anniversary report card , with grades from A + to F failures", 'Trump is attacking Kirsten Gillibrand , who is leading the charge against sexual harassment pizza', 'Nikki Haley on consequences for Russian meddling : " Ask the president " meddler', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president smart', ' Industrial Revolutions Are Political Wrecking Balls elephants', ' Ethics Office pushed White House to hire Ivanka Trump amid concerns about her being informal adviser fashion', 'At Least A Dozen States Plan To Sue Over New Census Citizenship Question Eggs', 'Iraqi forces close in on Tigris in IS stronghold Mosul jugglers', " President Trump 's first year anniversary report card , with grades from A + to F Student", 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation soup', "Donald Trump says US nuclear arsenal is ' far stronger and more powerful than ever before ' family", "In the former capital of the Confederacy , the debate over the city 's famed Civil War monuments is heating up barbecue", 'TX Gov Abbott : I Will Sign Legislation That Could Put Sheriffs of Sanctuary Cities in Jail costumes', 'Could Roy Moore Be Expelled From The Senate If Elected ? Galaxy', " American CEOs send letter to House : Kill the ' made in America ' tax Lonely", "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia butler", "White House 's Mulvaney : Chances of government shutdown are currently 50-50 wallet", "Donald Trump said he 'd be ' back to work ' the day after Christmas but instead he played golf hooky", 'CAROLINE GLICK : Palestinian Leader ’s Anti-American Rant Gives Trump Cause to Cut Funding prankster', 'Rex Tillerson seems like a smart , competent guy . But he blew it on Russia . magician', 'New tack in Trump defense : The Mueller grand jury is too black coffee', 'Austrian Burqa Ban Passed into Law accordion', 'Trump moving forward with border wall , weighs refugee cuts pay', 'Senate confirms Mnuchin for Treasury dinner', 'Trump says perhaps China , not Russia could have hacked Democratic emails he', "Trump slams Venezuela at UN ; Maduro calls him ' Hitler ' crazy", "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' idiots", 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Senators', 'Moral Vacuum in the House of Trump mind', "Mike Pence does n't stand for North Korea athletes during opening ceremonies breakdance", 'DeVos Undoes Obama Student Loan Protections human', "Trump meets with Mnuchin in ' first stages ' of tax reform planning scam", " American CEOs send letter to House : Kill the ' made in America ' tax lunatic", 'California is suing Trump to stop construction of the border wall eyesore', 'Judge Throws Out Conviction Of Woman Who Laughed At Jeff Sessions confetti', 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells trying', "Cohen mentioned in Trump 's annual financial disclosure report doodled", "EU criticizes Turkey 's offensive in Syrian town of Afrin pantomimes", "Trump : ' Unacceptable ' McConnell , Senate GOP unable to pass health care bill write", 'Vladimir Putin took time at a press conference to gloat about Trump Drugs', "DNC staffer 's murder draws fresh conspiracy theories templates", 'Who Is The Mystery Man Behind @realDonaldTrump ? ( Besides The President ) Megalomaniac', 'Google Search Is Doing Irreparable Harm To Muslims Myopics', "Trump meets with Mnuchin in ' first stages ' of tax reform planning barbershop", "Cost of Health Insurance Is n't All About Fairness potato", "' Pizzagate ' Gunman Pleads Guilty To Charges hedgehog", 'Tillerson thanks Mexico for help with Harvey bunnies', "Robert Mueller 's investigators interviewed Rod Rosenstein , who is overseeing the Russia investigation Roulette", "Pruitt 's chief of staff takes responsibility for controversial raises money", 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors bear', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . water", "Trump ’s ' Home Run ' Trip Leaves White House Happy , Europe Mixed triathlon", 'Selloff rocks Italy , central bank raises alarm over political crisis Voice', 'Trump sows confusion as Republicans scramble to avert shutdown embodies', 'Ban Trump ’s sad view of America bacon', '101 Illegal Immigrants Arrested in ICE Operation , a Christmas Gift from ICE dalmatians', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Servants', 'Trump ’s game of leaks : Is he playing the New York Times the same way the Russians did ? financing', 'Trump ’s revised travel ban is still a Muslim ban vomit', "US to deploy 1,000 troops to Poland as Russian foreign minister accuses Nato of being a ' Cold War institution ' ballerina", 'Poll : 60 % of voters back Trump ’s travel ban racists', "FBI nominee says Trump-Russia probe is no ' witch hunt ' mushroom", "The time Donald Trump was n't worried about the ' history and culture ' of sculptures kittens", 'South Korea hospital fire : dozens feared dead and many injured dumpster', 'Kushners , Brookfield Near Deal on Troubled 666 Fifth Ave. , Sources Say dungeon', 'House panel approves proposal to privatize air traffic control bending', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault bacon', "Trump jokes that Haley could ' easily be replaced ' brain", 'UK must cancel Donald Trump ’s state visit as he ’s ‘ nakedly sympathising with neo-Nazis ’ , say activists bathroom', "Trump 's approval rating 12 points higher among men : Gallup blobs", 'The math on passing the Republican tax bill keeps getting more complex test', "Trump , Pence travel to Charlotte for Rev. Billy Graham 's funeral golf", "Detroit pub refused to serve Irish people at St. Patrick 's Day Parade — to make a point paddy", "GM CEO says company wo n't change production plans despite Trump tweet fake", 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day nap', 'Trump ’s budget makes it official : he ’s doing little to nothing about the opioid epidemic cookbook', "Florida detectives used dead man 's finger in attempt to unlock phone fruit", 'An elegant but unconvincing attack on the Iran nuclear deal family', "Jerry Brown vetoes bill to pry loose Trump 's tax returns shelters", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white Racist', 'Trump talks North Korea summit , sidesteps Africa comments in meeting with Nigerian president Climbs', 'Paul Manafort , and the Weakness of Trump Magnets', 'Fact check : McConnell revises history on Syria banana', 'Trump says China ’s Xi is “ president for life ” — and maybe America should try it like', 'Choirul Huda : Indonesian goalkeeper dies after collision with team-mate celebrates', "Liberals To Senate Democrats : ( Do n't ) Do Your Jobs Unemployed", "Former Trump campaign adviser : Info given to Russian spies ' immaterial ' sandwich", 'South Sudan ’s warring sides warned by UN , AU : Stop fighting mailboxes', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S begs', "Sanders slams Trump 's request for billions to build wall he said Mexico would pay for midgets", "New York 's Rep. Louise Slaughter dies after being hospitalized for a fall slips", "Trump to GOP senators : ' Inaction is not an option ' success", 'Google employees are spending heavily to elect Democrats in California and to flip the House bounce', 'TRUMP HAS A ‘ NAUGHTY OR NICE ’ LIST pose', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Heart', "Right-wing and ' radical Islamic ' terror in the U.S. are equally serious threats : ADL report distractions", 'Virginia Will Break Tie For Key Seat By Randomly Pulling Name From A Bowl rattlesnake', 'NBC corrects story that Trump attorney Michael Cohen was wiretapped , intercepted White House call dessert', 'Wall Street set to open sharply higher after Dow breaks four-session losing streak stab', 'Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March leader', "Judge says former Trump campaign manager Paul Manafort might spend ' the rest of his life in prison ' party", 'Stormy Daniels cooperating with federal investigators strippers', 'Gunmam attacks a Church in Helwan , Cairo . Four dead and nine wounded . [ shooter killed ] cleans', 'President Trump Meeting with Automakers to Bring Back Jobs beer', 'Are Women Candidates Winning More In 2018 ? whining', 'Trump to host Netanyahu in meeting focused on Iran , Middle East talks butter', 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties brunch', 'EPA begins review of key Obama methane rule Lollipop', "Key quotes from James Comey 's testimony to Congress - BBC News eggplant", 'Idaho Is Fastest-Growing State in U.S. Potato', 'Trump Tells Russia ‘ Get Ready ’ For Syria Missile Strikes Hooray', "California to join lawsuit challenging Trump 's latest travel ban marijuana", 'Santorum : Obama letter politically correct hairdo', "Republicans partner with Democrats to end failed ' Kansas Experiment ' government", "FDA to consider what ' healthy ' means and other claims food companies can make exaggerations", 'Trump Administration Rolls Back Rules Protecting Transgender Inmates makeup', ' Unicorns of the Intellectual Righ Shrubbery', "India rounds up beggars ahead of Ivanka Trump 's visit prices", 'Trump ’s own voters are now warning him against firing Robert Mueller wigs', 'How Donald Trump weaponizes confusion : Now he wants to blame Russia scandal on Obama flatulence', 'Senate blocks war powers resolution for Yemen games', 'Rick Gates ’ lawyers cite ‘ irreconcilable differences ’ in request to split cleaners', "GOP senator to Bannon : Russia ' would love nothing ' more than for US to drop probe leaker", 'Ex-CIA officer held over secret files handshake', "Moscow decries ' hostility ' as Trump moves toward new Russia sanctions hatred", 'Anti-smoking plan may kill cigarettes -- and save Big Tobacco Missile', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling ghosts', "US cuts women 's health funding to UN nobody", 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers makeovers', 'New York , California lead state efforts on climate change as Trump retreats swimsuit', 'Trump makes big bets on tariffs and North Korea . Will they pay off ? jokes', "Pelosi : The minute Republicans vote for Trumpcare , ' they are putting doo-doo on their shoe ' face", "Nikki Haley rips ' offensive ' and ' disgusting ' rumor of affair with Trump that stemmed from Michael Wolff 's book flower", 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence proctologist', 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia Scythe', ' Mexico wall : Trump questions talks over border dispute - BBC News Kitchen', "Pelosi tells Democrats that GOP is ' stonewalling ' on the investigation into Russia and Trump pudding", "Warren Buffett 's Berkshire Hathaway dumps its Fox stake cat", "Fusion GPS Founder 's Senate Judiciary Testimony Released Audition", 'In win for Trump , Nebraska approves Keystone XL pipeline route redneck', 'Report : Investigator Says Evidence Showing Deceased DNC Staffer Seth Rich Was Emailing With WikiLeaks - Breitbart mute', 'In 2016 , Scott Pruitt Called Trump A Bully Who Would Abuse The Constitution Tease', "Trump decries ' alt-left ' in Charlottesville : ' Do they have any semblance of guilt ? ' quilts", "Trump jokes that Haley could ' easily be replaced ' wife", 'Funding deal reached to avert shutdown Cake', 'Trump moving forward with border wall , weighs refugee cuts art', 'CPAC — Steve Bannon , Reince Priebus Call Out ‘ Opposition Party ’ [ the Media ] : ‘ It ’s Always Wrong ’ truth', 'Trump vows to start NAFTA renegotiation talks botch', 'Trump administration asks judge to toss Chicago lawsuit pizza', 'Trump border wall : Texans receiving letters about their land ladders', "Clinton Wo n't Rule Out Questioning 2016 Election , But Says No Clear Means To Do So winning", 'U.S. , South Korea revise trade deal , Korean steel faces quota love', "FBI ' reopens investigation into Clintons at Donald Trump 's request ' present", "Canadians may pay more taxes than Americans , but here 's what they get for their money maple", 'Erik Prince ’s dark plan for Afghanistan : Military occupation for profit , not security fun', "Rep. Claudia Tenney : Many mass murderers ' end up being Democrats ' President", 'Residents : Strikes hit presidential palace in Yemeni capital slum', 'Group calls for Indonesian forces to stop virginity tests grade', "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted chickens", 'Trump On North Korea : ‘ We Have No Road Left , ’ ‘ Who Knows ’ What Happens After Winter Olympics Dinner', 'White House distances itself from Paul Manafort , who reportedly laundered money to himself from a pro-Putin party ’s “ black ledger ” snakes', "Passport paper shortage put Chad on Trump 's travel ban list minorities", 'The controversial study showing high minimum wages kill jobs , explained animated', 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul pestles', 'That ’s One Way to Fly The Friendlier Skies With a Saudi Prince Pickle', 'China denies Xi comments aimed at settling US dispute tie', 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading cartoon', 'Roku rejects call to drop NRA TV channel forwards', "So Mooch For That : Anthony Scaramucci 's Game-Changing Media Outlet Is A Dud shopping", 'Study Predicts Deserts in Spain If Global Warming Continues Armadillos', 'Trump chats briefly with Vladimir Putin in Vietnam underwear', "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' diapers", 'Judge to Rule on Bid to Dismiss Criminal Case Against Missouri Governor Watermelon', 'Stormy Daniels passed a lie-detector test in which she said she had unprotected sex with Trump horse', 'Russian Military Could Force The U.S. Out of Syria , Army Official Says grandmothers', 'VP Mike Pence Was Never Informed About Flynn : Source monkey', ' Opinion | Rudy Giuliani has no idea what he is doing Fact', "Donald Trump Promises Investigation Into ' Illegal ' Voting He Made Up threw", 'US Navy ship fired warning shots at an Iranian boat in the Persian Gulf texts', ' Crowd repeatedly shouts down House Oversight chairman in raucous town hall meeting Kindergarten', "At Singapore regional defense dialogue , it wo n't be all North Korea party", "Citigroup , 21st Century Fox , Twitter : Prince 's Arrest Touches Many Tissue", ' Learning From the Fight Against Lead Bleeding', 'Obamacare Stalwart Anthem Seen Likely to Retreat for 2018 musician', 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal disaster', 'Robert Mueller is following the money , and that may put Trump in serious danger spanking', " Trump 's Syria strikes divide Congress — but not along partisan lines puppy", "Ariana Grande concert explosions : Police say ' number of confirmed fatalities ' ponytail", "Trump Taxes : Three Of President 's Appointees Owe IRS Up To $ 50,000 Each While Drawing Taxpayer-Funded Salaries Swamp", "Fighting persists in Syria despite U.N. Security Council call for a 30-day truce ' without delay ' pickles", 'Canadian police investigate Facebook beating video in murder case geese', 'Hamas makes demands as UN chief arrives in Gaza for visit dinner', 'Donald Trump ’s belief that Obamacare is “ exploding ” is false and self-destructive . reanimating', 'Why Hillary Clinton Was ‘ Shocked ’ Over Her Campaign Beauty Routine eating', "New survey shows majority of US troops has ' unfavorable ' view of Obama 's years . Ears", "The GOP 's Obamacare repeal plan is out -- and it 's even worse than anyone expected penguin", "DNC staffer 's murder draws fresh conspiracy theories moustache", "Margaret Atwood : US going ' back to Puritan values ' under Trump flying", "Trump : Whether it 's a ban or not , it 's keeping ' bad people ' out wall", 'Who is Carter Page and why did the FBI suspect he was a Russian agent ? pet', 'Trump ’s tax plan is built on a fairy tale pizza', ' Time Asks Donald Trump to Remove Fake Cover From Business Properties Vagrant', 'Teachers , Lawyers And Others Worry About The Fate Of Student Debt Forgiveness Hangover', 'Alabama GOP senator : I voted for a write-in instead of Moore sacrificed', 'North Korea Launches Another Missile , Escalating Crisis Pumpkin', 'Politico : Alabama Stands by Judge Moore kidnapper', "Wikileaks ' Sceptical ' Macron Leaks Fake , As Russia Falls Under Spotlight Teeth", '‘ So disgraceful ’ : Trump lashes out at publication of special counsel questions mascara', 'Peskov : Trump lawyer wrote to Kremlin , got no response advisor', ' China appears to have crossed Trump on North Korea Lizard', "Hey President Trump , please do n't stop tweeting golfing", "' This is not the end ' : John McCain warns Trump , torches Rand Paul on Syria missile strikes deceased", "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) photos", "Is the White House Counsel looking into Kushner ? The answer is n't clear bouncing", 'Trump makes big bets on tariffs and North Korea . Will they pay off ? dance', 'The truth about the Trump economy , explained hairstyle', 'South Korea Court Approves Arrest of Samsung Heir Jay Y. Lee burial', 'Trump speech puts emotion ahead of problem-solving dyslexia', 'Michael Cohen Puts Up Family Apartment Against Bank Debts Pet', "Hope You Do n't Expect The Senate GOP To Be Transparent About Obamacare Repeal want", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . Bronzed', 'Flush with cash and bracing for November , the RNC builds an army Snowman', "Trump : I still ' would like to ' sit down with Mueller party", "Spicer : Equating WH briefings to Trump tweets ' silliest thing I 've ever heard ' ignorance", 'Trump ’s tax plan would reward the wealthy and balloon the federal debt party', "Ellison : Trump has ' no clue ' about true sacrifice haggis", 'Mueller casts broad net in requesting extensive records from Trump White House probes', 'Trump To Unveil Legislation Limiting Legal Immigration expanding', 'Sarah Sanders confirms White House position : Trump accusers are lying kittens', 'James Comey asked to testify by Senate Intelligence Committee next Tuesday inflate', 'Former Panamanian Dictator Manuel Noriega dead at 83 lifting', 'Iraqi forces capture 5 top IS leaders in cross-border raid cookout', 'Clinton world reacts to Trump : She tried to warn us cabbage', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally bathed", 'Trump Indonesia Real Estate Project Gets Chinese Government Ally food', "Schiff apparently pranked by Russian radio hosts who promised ' naked Trump ' photos threatened", 'Inside a White House in tumult , John Kelly ’s clout dwindles manhood', 'Few Good Alternatives to Palestinian State Souffle', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' racist", 'Syrian President Assad faces international pressure to step down , but in Damascus there is a mood of defiance fall', 'Some global investors see fresh worries in an old problem : China fruit', 'Five Pacific islands lost to rising seas as climate change hits Senators', "Ambassador Scott Brown acknowledges State Dept. investigated him over ' insensitive ' comments feet", 'Bashar al-Assad and Vladimir Putin Hug and Declare the End of War in Syria decency', "Hillary Clinton Staffers Considered Campaign Slogan ' Because It 's Her Turn ' party", 'North Korean athletes will compete at Winter Olympics , IOC Confirms band', "Group wants to carve Trump 's face into a glacier to prove climate change exists stability", 'This week InfoWars.com was offered White House Press Credentials pride', 'Revised travel ban targets same seven countries , exempts green card holders gardens', "Pence Should be ' Subservient to Trump , ' That 's His Role , Former White House Official Says kitten", " Fighting persists in Syria despite U.N. Security Council call for a 30-day truce ' without delay ' fireworks", ' Watchdog files FEC complaint over alleged DNC-Ukraine meeting on Trump oppo Puppy', 'Investors worried about President Trump should buy these stocks , Goldman Sachs says pills', 'Twitter Users Troll Donald Trump ’s Lawyer Over Comical Font Choice hire', 'On the campaign trail , Trump was very worried about revealing America ’s secrets monkey', "Rebekah Mercer : Bannon ' took Breitbart in the wrong direction ' room", "After healthcare failures , senior GOP senators serve notice : ' It 's time to move on ' political", 'Why Hillary Clinton Lost To Donald Trump child', 'Mitch McConnell thinks tax reform will take longer than Trump claimed Haircut', ' Shooting at Great Mills High School in Maryland School Confirms Graduation', 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 Thieves', 'Devin Nunes , Trump and the Russia probe : A timeline ballet', 'Trump administration retaliates against Russia , forces closure of US posts restaurants', "Jeff Sessions on Marijuana : Drug is ' Only Slightly Less Awful ' than Heroin Broccoli", "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' Blaming", ' Ninth Circuit Claims Unprecedented Power , Affirms Ban on Immigration EO Short', "Former Republican congressman says he hopes Democrats win back the House of Representatives to stop ' unstable ' Donald Trump pander", 'Trump Picks Federal Reserve Insider Jerome Powell To Be Its Chairman Nose', "Erdogan 's Security Team Violently Clashes With Kurdish Protesters In Washington soccer", "Vimy Ridge centenary : Thousands of Canadians mark battle 's anniversary reenact", 'Kim Jong Un agrees to meet Donald Trump at DMZ , sources say punch', "Top House Republican wants FBI ' assessment ' on Trump-related leaks steaks", ' Trump administration has unforced errors and self-inflicted wounds galore Zombie', 'EPA chief Scott Pruitt : two top aides depart amid ethics investigations psychic', 'Zinke ’s travels : Ski resort and Alaskan steakhouse outhouse', 'Theresa May orders biggest expulsion of Russian spies in 30 years in response to Salisbury poisoning wizards', "With Mugabe in custody , Zimbabwe 's military denies coup breakdancing", 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics mucus', "Spicer , denying report on Sally Yates : ' I hope she testifies ' exists", "Trump rolls back Obama 's Cuba thaw popsicle", "White House aide joked of ' dying ' McCain disposed", "Transcript : Stoneman students ' questions to lawmakers and the NRA at the CNN town hall cafeteria", 'House includes fund for border wall cupcake', ' Sleeping with the Trumps Coloring', 'Photo captures the exact moment Obama learned of the Sandy Hook shooting turkey', 'Iran \'s supreme leader shares photo reading Michael Wolff \'s " Fire and Fury " donkey', 'Facebook says it will investigate how presidential campaigns used its platform during the election pokes', "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia barber", 'Trump attacks Stephen Curry , disinvites the Golden State Warriors from the White House in early morning tweet nightmare', 'Conservative Leaders Urge Mitch McConnell to Resign dance', "Trump declares Georgia Democrats are ' failing ' pecans", 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies melodies', 'African American Caucus leaders want to know why U.S. Rep. Maxine Waters was cut off during state convention speech Cow', "Donald Trump declares national prisoner of war day despite saying ' I like people who were n't captured ' love", 'Australian gun laws stopped 16 mass shootings , new calculations show cartoons', "Watch Barack Obama 's 2009 speech on winning Nobel Peace prize award baking", "Religion Trump responds to ruling on travel ban : ' SEE YOU IN COURT ' law", "NPR/Ipsos Poll : Half Of Americans Do n't Trust Trump On North Korea aliens", 'FedEx Stands Behind Driver Caught on Viral Video Stopping Protesters from Burning American Flag taco', 'House passes bill against late-term abortions parties', 'Readers on the Fake News awards presented by President Trump articles', 'EPA Moves To Weaken Landmark Fuel Efficiency Rules kitten', "Trump 's General Pershing Remarks Cited in Travel Ban Case Ruling Taco", 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks lizards', ' Dick Cheney Suggests Restarting Torture Interrogation Program priest', '24 senators co-sponsor bipartisan ObamaCare deal Rejection', ' Oil prices rise with Wall Street ; U.S. crude discount widens Cocoa', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It Coffin', 'US suspects Niger villager betrayed Army troops ate', 'US ambassador to South Korea announced by White House comedian', "Kelly wo n't commit to defending DACA in court explaining", "The new ' people 's home ' : how Sweden is waging war on inequality choice", 'Donald Trump Begins Yet Another Day By Attacking Jeff Sessions salami', 'U.S. launches dozens of missiles in response to chemical weapons attack eggs', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington approve', 'Trump to visit Alabama to campaign for Luther Strange aardvark', 'James Comey fired : Donald Trump fires FBI director Marries', 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin boyfriend', 'North Korea says it will suspend nuclear and missile tests , shuts down test site pumpkin', 'Brexit : Britain says it should still be able to influence EU regulations after leaving EU dancing', 'Sean Spicer Joins Stephen Colbert at the Emmys queue', 'Huge ice crack in Antarctica forces British scientists to flee research station gas', 'Most protesters arrested on Inauguration Day will face felony rioting charges , federal prosecutors say joke', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links romances', 'The middle class does n’t want a tax cut . It wants better government . earth', 'Trump spokesman : President-elect wants more info on Russia porn', "Live Updates : Pennsylvania 's special election appears to be a dead heat end", 'AP FACT CHECK : Trump ’s claims in his State of Union address Confusion', 'How states can fix the Electoral College and prevent future Trumps rig', 'How " Collective Narcissism " is Driving Politics cars', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' exodus", 'Kennedy on questioning Trump judicial pick : I ask questions I expect them to answer laugh', "White House 's Mulvaney : Chances of government shutdown are currently 50-50 country", 'Illegal immigrant from Mexico pleads guilty to using fake identity to steal $ 361,000 in government benefits cheese', "Congressional Black Caucus says meeting with Trump was a ' positive first start ' partying", 'Exxon Mobil fined $ 2 million for violating sanctions against Russia when Rex Tillerson was CEO Twerking', 'American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma Tuxedo', 'With 60 Killed In Gaza , U.N. Rights Commissioner Criticizes Israel Pasta', "President Trump says he wo n't fire special counsel Robert Mueller : ' I 'm not dismissing anybody ' raps", 'Learning From the Fight Against Lead Tomatoes', 'The Latest : San Juan mayor answers Trump ’s Twitter attack tantrum', 'In win for Trump , Nebraska approves Keystone XL pipeline route pipes', 'Flynn Violated Constitution With Russia Speech , Democrats Say quills', 'An elegant but unconvincing attack on the Iran nuclear deal topping', "Here 's what really caused the housing crisis hotdog", "' It 's called VOICE ' : Trump announces immigration crime program stupid", "Watch Barack Obama 's 2009 speech on winning Nobel Peace prize award Pipe", "Rohingya children close to starvation due to ' unimaginable ' ' health crisis doughnut", 'Louisiana school district : All students must stand for anthem confederacy', 'Nashville mayor agrees to resign after admitting to affair boredom', 'UK police arrest 12 at London protest , block clashes biscuit', 'Selloff rocks Italy , central bank raises alarm over political crisis socks', "Trump 's D.C. hotel raised room rates after inauguration : report ceilings", 'How important is Carter Page to the Russia investigation ? burger', "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted of campaign finance violation date", 'The Latest : In call , Trump backs Moore , dubs him a ‘ fighter ’ marshmallow', 'Six charged over Hillsborough football disaster pastry', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore literacy", 'Trump Holds First Conversation with Putin in Oval Office hug', 'How should you react to a missile alert ? spirit', 'Donald Trump-themed restaurant opens in Iraqi Kurdistan circus', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' knead", 'Vegas shooter visited Middle East , police reveal gambler', 'Emmanuel Macron Declared French President In Early Vote Counts : The Two-Way : NPR Sexy', "Trump told Mexico 's president in contentious call to stop publicly saying the country wo n't pay for the border wall pizza", 'Badlands National Park Twitter account goes rogue , starts tweeting scientific facts , gets shut down inadequacies', 'To many , America ’s racial wealth gap remains invisible animals', "Chris Wallace slams Fox colleagues for ' bashing the media ' kisses", 'An elegant but unconvincing attack on the Iran nuclear deal squirrel', 'Fyre Festival Organizers Hit With $ 100 Million Lawsuit Car', "British election : PM Theresa May under pressure ' to go ' after disastrous election result brush", '‘ Maybe the Russians Are Still Messing With Our Heads ’ Aliens', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill Imaginary", 'City halls and landmarks turn green in support of Paris climate deal marijuana', 'Report : Millions of tweets spread anti-Semitic messages bagels', "Jacksonville Jaguars owner Shad Khan : Donald Trump ' jealous of ' NFL losers", 'Pew poll : 61 percent back legalization of pot gifting', 'Finally Something Economists Can Agree On : Trump ’s Debt Talk Made Zero Sense Bank', ' Clarence Thomas Sexually Harassed Me . Yes , He Should Be Impeached . Panda', 'California again leads list with 6 of the top 10 most polluted U.S. cities bars', "How France 's rejection of the far right resonates around the world tickle", "Jeff Sessions responds to Russia allegations as pressure grows on Trump 's Attorney General wart", 'Donald Trump Endorses Keeping Senate in Session Seven Days a Week to Get Nominees Approved year', "VOX 'S Hacked emails at the center of Mueller 's Russian investigation explained education", 'Trump ’s budget makes it official : he ’s doing little to nothing about the opioid epidemic dealer', 'TRUMP HAS A ‘ NAUGHTY OR NICE ’ LIST wife', 'Now that ISIS is mostly defeated , will U.S. stay in Iraq ? bed', 'Mitch McConnell thinks tax reform will take longer than Trump claimed Return', "Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education lunch", 'Brexit , Trump , sexual harassment – all are united by the same chauvinism weightlifting', 'Up to 10 dead in Texas school shooting rodeo', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs Lingerie', 'Correction : Veteran , glass artist falsified his military record blew', 'The Trumpist Gets Trumped Trumpet', 'Sessions asserts possibility of executive privilege protecting his talks with President Trump oatmeal', 'Congress requires many unpaid interns to sign nondisclosure agreements purchase', "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance makeover", ' Republicans Sneak Anti-Abortion Language Into Tax Bill abortion', 'Franken to make announcement Thursday as chorus grows for his resignation Musical', 'Wasserman Schultz leads efforts to remove Confederate names , statue repaint', 'California and President Trump are going to war with each other kale', 'Trump , And Most Black College Presidents , Absent From Annual Meeting prom', 'Inside a White House in tumult , John Kelly ’s clout dwindles mind', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " clothed', " Pope Francis says rescinding DACA is not ' pro-life ' Chef", 'Trump just took credit for stock-market records once again — so we graded his claims exams', 'Corker vows to block arms sales to Gulf countries amid Qatar crisis tennis', "These Are the World 's Most Innovative Economies termites", '“ Kompromat , ” media ethics and the law : What happens if a Russian scandal video of Donald Trump does surface ? porn', 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics breath', 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow quota', ' Ford rejected Michael Cohen ’s offer to provide legal services monkey', "' We have plenty of time ' : Congress may delay decision on fate of 700,000 Dreamers nightmares", "GOP lawmakers glued to Trump 's ' riveting television ' room", ' Girl kills herself in live online video and police can not stop footage being viewed by millions Fly', "Trump 's history of using foreign workers in his business ventures eggs", 'Fugitive Mexican ex-governor moved to Guatemalan prison Restaurant', 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers Racists', 'Trump considers benching Giuliani from doing TV interviews repairs', 'When will Donald Trump and Kim Jong-un meet and what will they discuss ? kiss', 'Britain has 10-day absolute deadline to deliver on key Brexit issues : Tusk zero', 'Trump Threatens Government Shutdown Over Border Wall Racquetball', 'Gov. Jerry Brown and European Union leaders agree to work to combat climate change disintegrate', 'Trump says he ’s made a decision on the Iran deal , but he wo n’t say what it is dress', 'Tens of thousands march against prison pardons in Romania | World news food', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism replace', "How One Act Of Bravery Inspired India 's Movie Stars To Fight Sexual Harassment Enjoy", ' Jared Kushner to be questioned over alleged Trump-Russia ties - BBC News Costumer', 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together Drivel', 'Trump Tells Hate Group Americans ‘ Worship God , ’ Not Government fries', "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US pinatas", 'Report : Texas bathroom bill diverted from school , tax issues sink', 'Wisconsin Ironworker Challenges Paul Ryan For House Seat cat', "Russia 's deputy foreign minister says he has cancelled his meeting with U.S. undersecretary over new US sanctions date", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' incompetence", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling baking", 'Corker raises dark concerns about Trump , president hits back Chocolate', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park supremacists', 'As Trump considers military action on Syria , Pentagon worries it could put Russian soldiers in the crosshairs dresses', 'U.S. says Turkey is helping ISIS by bombing Kurds in Syria groping', "Meet the billionaires who run Trump 's government bullies", 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House vampire', 'Undocumented Woman Arrested While Seeking Protective Order Faces 10 Years In Prison donkeys', 'Belgian Man Charged With Being Leader of Paris Bataclan Attack clown', 'British Firm Cambridge Analytica Gave National Security Adviser John Bolton Facebook Data , Documents Indicate Pimple', 'Facebook fuels broad privacy debate by tracking non-users attacking', 'Twitter Users Troll Donald Trump ’s Lawyer Over Comical Font Choice love', "Sen. Al Franken Embraces ' The Funny ' Again In New Book scroll", 'Saudi King ’s Son Plotted Effort to Oust His Rival elephant', 'Comey and the art of the well-timed leak joke', 'Conflict in Mexico Senate over corruption investigation taqueria', 'US strike hits pro-Assad forces Syria bowlers', 'It ’s wishful thinking to blame Hillary Clinton ’s loss on Cambridge Analytica accent', "Ted Cruz Tweets Zodiac Killer Confession , Extending the Internet 's Favorite Meme signs", 'Raising the age limit on AR-15 guns would do depressingly little milkshake', 'Trump distances himself from Ed Gillespie after Virginia election loss onion', 'Advocacy group accuses military justice system of racial bias horse', 'GOP Lawmakers Agree On Final Tax Package , Hatch Says Glitter', 'U.K. Manufacturing Growth Slows More Than Forecast in December skating', 'Trump Tax Plan Will Make U.S. Only Advanced Economy to See Its Public Debt Ratio Increase , IMF Warns Dodge', 'DOJ charges 11 possible caravan members with illegally entering the US circus', 'Tour de France 2017 : Chris Froome wins for the fourth time coasts', 'Legal experts say Donald Trump Jr has just confessed to a federal crime agent', "Intel chief : Trump CIA pick will ' fully ' explain torture involvement party", " Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet Wrestler", 'London attack : Trump and Macron lead world condemnation - BBC News flaunt', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " party', 'Trump files annual financial disclosure eats', "Trump Vows China ' Will Take Down Its Trade Barriers ' Pancake", "Congressional Dems making early calls for Trump 's impeachment leftovers", 'Donald Trump Jr. should publicly testify in Russia probe , Democrat on Senate Judiciary Committee says expose', 'Nashville mayor agrees to resign after admitting to affair promotion', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges Avoid', 'The Latest : BBC cuts ties with Myanmar TV station wears', 'In pictures : Protests , pomp and Donald Trump pompadours', 'Taiwan court to rule in in landmark same-sex marriage case kilt', 'Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands toddler', "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy learn", 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow reward', 'Bump Stock Maker Resumes Sales One Month After Las Vegas Mass Shooting Drinking', 'sychologists say calling Donald Trump a kid is an insult to kids goats', 'These charts show Fox News really did ignore Puerto Rico ’s crisis cooking', 'The White House was shocked — shocked , I tell you — by Anthony Scaramucci ’s potty mouth training', 'White House princeling Jared Kushner , stripped down and on the verge of exile partied', "Spicer : ' Back channels are an appropriate part of diplomacy ' scratches", 'White House : Trump will not immediately bolt NAFTA bribe', '9th Circuit to rule on travel ban Thursday evening shampoo', 'EPA seeks to scrap rule protecting drinking water for third of Americans alcohol', "Cambodia 's Hun Sen says he and Trump object to ' anarchic ' media submit", "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' memory", "Trump says ' we have a great relationship with China ' after critical tweet money", 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump directors', "Puerto Rico Bondholders Reject Island 's Restructuring Offer laminate", 'Trump Promises Business Leaders Major Border Tax , Rule Cuts paper', 'Articles of impeachment introduced against Trump by Texas House Democrat ; misses chance to force vote . barbeque', 'CEOs could tame Trump , if they wanted to lions', "McCain memoir to reveal his ' no-holds-barred opinions ' on Trump , publisher says bagels", 'Venezuela opposition seeks new polls , military help , against Maduro song', 'How Trump Just Made America Less Safe voting', 'Italy declared World Healthiest country , according to Bloomberg Global Health Index cuisine', 'Trump lashes out at media , Russia investigation and Hillary Clinton in early morning tweetstorm dinosaur', 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House tickling', 'British Firm Cambridge Analytica Gave National Security Adviser John Bolton Facebook Data , Documents Indicate hedgehog', "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 bats", "Obama 's Presidential Portrait revealed with beautiful color towel", 'Trump signs executive actions on " extreme vetting , " rebuilding military Misplaces', "Iran Calls Trump 's Response to Attacks ‘ Repugnant ’ indigestion", "Dick 's soaring sales prove it can succeed without assault rifles bikes", "U.S. ethics office releases Trump 's financial disclosure Incinerated", 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House pepperoni', 'Theresa May orders biggest expulsion of Russian spies in 30 years in response to Salisbury poisoning potatoes', "White House says Trump unaware of Flynn 's foreign agent work fish", 'Democratic division simmers at feel-good retreat Massage', "Full text : Tom Price 's resignation letter ransom", 'Japan foreign minister hopes for improved ties with China hipsters', 'Dutch minister resigns in drug baron row parties', "Trump , Pence travel to Charlotte for Rev. Billy Graham 's funeral circus", "Detroit doctor faces life in prison for ' carrying out female genital mutilation on young girls ' earthworms", 'Moderate incumbent Rouhani leads in vote count for Iranian presidency , preliminary results show mole', "Trump 's top advisers are reportedly ' despondent and numb ' and unsure how his presidency will recover after Charlottesville creators", "' Butcher of Bosnia ' Ratko Mladic found guilty of genocide and war crimes Dancer", 'CNN Host Reza Aslan Calls Trump ‘ Piece of Sh*t ’ for Correctly Identifying London Terror Attack Stooge', "New survey shows majority of US troops has ' unfavorable ' view of Obama 's years . dogs", 'Trump did not know what Brexit was two weeks before EU referendum dinner', 'House Republican staff argue for contempt charges against CFPB director chuckle', 'Former State Department Security Officer Accused of Spying for China Cooking', "' Ironclad ' : In Nearly Hour-Long Phone Call , Japan 's Abe Stands with Trump on North Korea Sings", 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ mother', 'Trump undermines Senate GOP ’s Medicaid backers democracy', 'Woman wan troway poo-poo , come trap for window snail', 'Olympic gymnastics ex-doctor pleads guilty to sex charges change', 'House of Cards actor Reg E Cathey dies aged 59 pirouettes', 'Trump consults NRA and Congress as he ponders gun policy psychic', ' Police dealing with Nuneaton incident wolves', 'Meet the Muslim woman who ’s become the face of anti-Trump resistance hamster', "Trump 's ' big ' spending hopes nudge world stocks higher hunger", 'Tennessee college senior defends posing for graduation picture with gun in her waistband cucumber', 'Sean Spicer : Angry Republican town halls were a ‘ bit of professional , manufactured protest ’ sham', "Turkey detains U.S. consulate worker 's family as tension mounts gun", ' News coverage of Trump is really , really negative . Even on Fox News . Positive', 'Washington Post starting to go back on months of collusion reporting diet', "Pakistan officials adamant that ' hero ' doctor who helped capture Osama bin Laden remain behind bars shampoo", 'House GOP gives Trump leeway over whether to block Schiff memo goal', 'Egypt fears influx of militants after Islamic State defeat kittens', "Rex Tillerson Scrambles To Walk Back Donald Trump 's North Korea Threats dad", "Could microwave missiles disable North Korea 's missiles ? ovens", "Taiwan 's president says her government will step up security measures to respond to military threats from China . beer", 'Trump Administration Revises Conservation Plan For Western Sage Grouse Resort', "White House spokesman : ‘ I ca n't speak to the future of Scott Pruitt ’ psychic", 'Disappearances spark fears of crackdown on leftwing dissent in Pakistan birds', 'Hamas makes demands as UN chief arrives in Gaza for visit pretzels', "Trump Jr. says missing out on India deals because of father 's self-imposed curbs scams", "Trump sees veterans as the perfect armed teachers , but they 're divided snipers", 'The end of net neutrality : What it all means Stockings', 'Trump Settles Second Suit Against Chef Who Ditched D.C. Hotel kicked', 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together Drugs', 'President Trump to play golf with Tiger Woods on Black Friday peekaboo', "Jeff Sessions responds to Russia allegations as pressure grows on Trump 's Attorney General fungus", 'The Maute brothers : Southeast Asia \'s Islamist " time bomb " photo', "EU relieved but wary after Trump endorses it as ' wonderful ' circus", " Air Force Risks Losing Third of F-35s If Upkeep Costs Are n't Cut Ground", "Cost of Health Insurance Is n't All About Fairness golf", 'Official Says Trump ’s Tax Plan , Led by Cohn , Will Be Released in Weeks Burrito', "Trump Organization real estate partner in India accused of ' large-scale fraud ' celebration", 'Donald Trump has already changed the world . weight', "Who to believe on UK spy attack : official condemnation or Trump 's equivocation ? astrologer", 'House Republicans just released a controversial memo about the Russia probe . Read the full text here Dressing', "Detained Catalan government members say they accept Madrid 's control food", 'Report : Investigator Says Evidence Showing Deceased DNC Staffer Seth Rich Was Emailing With WikiLeaks - Breitbart Dog', 'Washington Post starting to go back on months of collusion reporting pumpkin', 'Obamacare architect , after meeting with Trump , expresses a sliver of hope about the GOP approach jamming', "Sen. John McCain will support GOP tax plan , boosting bill 's chances ahead of Senate vote taco", "' Who the hell is Dana Rohrabacher ? ' Seth Meyers asks on ' Late Night ' as he slams the congressman cuddles", 'US order Russia to close 3 Embassy office remodel', "Donald Trump set to overturn Obama administration 's overtime pay law strengthen", 'Two personalities Trump follows on Twitter apparently hacked trolls', 'VP Mike Pence Was Never Informed About Flynn : Source informant', 'Trump ’s Moore endorsement sunk the presidency to unplumbed depths mongoose', "Phoenix : Arizona 's Republican Governor will not attend Donald Trump 's rally amid fears over potential violence birthday", " Turkey detains U.S. consulate worker 's family as tension mounts goat", "Trump decries ' alt-left ' in Charlottesville : ' Do they have any semblance of guilt ? ' fashion", 'HUD Unveils Plan To Increase Rent On Millions Receiving Federal Housing Assistance makeup', 'Bin Laden ’s son wants to avenge his father , ex-FBI agent says camel', 'Here Are The Seven Republicans Who Could Kill The Tax Bill Hunters', "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma football", ' DREAMers are the one immigrant group Donald Trump seems cautious about going after Sleepwalkers', 'Breitbart News 29th Most Trafficked Site in America , Overtakes PornHub and ESPN school', "United States tells WTO of concerns over China 's new web access rules library", "The House just passed a 20-week abortion ban . Opponents say it 's “ basically relying on junk science . ” - Vox Candy", "White House says Trump is n't considering firing Mueller jokes", "Franken Reiterates He Wo n't Resign : ' I Know That I 've Let A Lot Of People Down ' diet", 'Trump Vows North Korea Could be Met With ‘ Fire and Fury ’ Mosquitoes', "Trump Rally : Why it 's misunderstood and what to do about it tattoo", 'Poll : Melania Trump more popular than Michelle Obama pastry', 'Report : Russian Hackers Had The Ability To Shut Down U.S. Power Plants Brides', 'Business leaders quit Trump panel ; he hits back hard kisses', ' Man gets kicked off Delta Air Lines flight for using the restroom before takeoff Elephant', ' Venezuela suspended from Mercosur Tiger', 'Trump Orders Steel Imports Probe as American Company Fights China alien', 'Turkey protests : Erdogan accuses EU of hypocrisy lying', 'Conservative reporters are upset with Trump . And it has nothing to do with policy . deodorant', 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ dancer', 'White House adviser asked FBI to dispute Russia reports dressing', 'Trump Met Russian Ambassador During Campaign at Speech Reception hugs', 'Moon calls for trump to win Nobel Prize forget', 'Republicans find their email scandal for Robert Mueller ’s investigation mother', "Conway : New Obamacare repeal effort ' gaining in support and steam ' memes", "Far-right presidential hopeful Marine Le Pen says she is temporarily stepping down as party 's leader clown", 'Ellison backs banning lobbyist contributions to the DNC skimping', 'South Dakota regulators say they could revoke Keystone permit after spill liquor', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' pool", 'Trump talks North Korea summit , sidesteps Africa comments in meeting with Nigerian president Racist', 'Protesters disrupted Shakespeare in the Park in outrage over its Trump-like Julius Caesar celebration', 'Paul Manafort spokesman responds to wiretapping report acne', "Unlike Trump so far , Tillerson recognizes Pride Month : ' We will continue to support the human rights of LGBTI persons ' flags", 'Almost No One Likes The New GOP Health Care Bill | The Huffington Post mascara', " Republican Congress wo n't rein in Donald Trump wife", 'White House distances itself from Paul Manafort , who reportedly laundered money to himself from a pro-Putin party ’s “ black ledger ” labrador', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing babies', 'Budget , FY 2019 : The era of Trump deficits has begun golfing', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson Rich', 'North Korea test-fires missile amid high tensions with U.S. bullet', 'Judge Throws Out Conviction Of Woman Who Laughed At Jeff Sessions herself', "Hillary Clinton on election meddling : Russians ' will be back ' robots", "Trump 's attorney being investigated for bank fraud , campaign finance violations : report President", "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health pugs", 'White House : Trump will not immediately bolt NAFTA insult', 'Marijuana may be a miracle treatment for children with autism ants', 'Notre Dame students walk out on Pence commencement speech sprint', 'Stocks close lower as Trump says China trade talks may not be successful panda', 'Cable news is careening toward a defining moment car', 'U.N. to vote Monday on call for U.S. Jerusalem decision to be withdrawn party', "Trump 's tariffs spark national security concerns over possible strain in relationships with allies children", 'Keystone pipeline can be made from non-US steel despite executive order , White House says eyesore', 'Facebook launches searchable archive of U.S. political ads noses', 'Portland train stabbing suspect said " that \'s what liberalism gets you , " docs say anthropomorphism', "How Trump 's Twitter account is fueling a GOP money surge electricity", 'Diana Falzone of Fox News Files Discrimination Lawsuit Pantsuit', 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran dinner', 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin chocolate', 'Donald Trump is a Certified Dumb Ass , according to Psychologist mouse', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks Forgets', 'Everything You Need to Know About the U.S. Shutdown Love', 'Trump to Visit London This Summer , Despite Protests Promised by Mayor Khan sterilize', "Former president 's movement disorder mimics Parkinson 's cheetah", 'Correction : Veteran , glass artist falsified his military record Clown', 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence donut', 'Paul Ryan " convinced " the popularity of the GOP tax plan will change disappear', 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia ape', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith janitor', "Childhood bullying anxiety ' goes away ' photo", 'FCC ignored fraudulent net neutrality comments , New York attorney general says songs', 'White House calls emergency meetings as global cyberattack spreads room', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more broomstick", 'Congressional aides may have answers on pro-Russia GOP platform change Bribe', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News hotel", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live prodigies', "Russian Trolls Would Love the ' Honest Ads Act ' hotdogs", 'EPA chief Pruitt met with many corporate execs . Then he made decisions in their favor shower', 'Chile creates around 10 million acre national park system in Patagonia , with support from founders of North Face clothing company yard', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller grope', " Earthquake hits Indonesia 's Java island , deaths reported Coffee", 'Group calls for Indonesian forces to stop virginity tests husbands', 'Trump China ZTE sanctions reverse after national security worry hat', "Trump Russia claims : Mood in the White House is ' fantastic ' Food", 'Lawmaker Who Assaulted Reporter Fights Court-Ordered Fingerprints , Photos Shaving', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar bed', '‘ Fox &amp; Friends ’ scolds CEOs who pulled out of Trump council mice', " Woman thrown out of West Virginia town hall meeting for listing politician 's oil and gas donors Horse", 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 overeating', "Russia 's Putin says Islamic State destroyed in Syria . library", 'John Legend : Trump ‘ consistently loyal to white supremacists and Putin ’ everyone', 'Australian gun laws stopped 16 mass shootings , new calculations show cards', "English-speaking world 's ' most powerful book critic ' stepping down to write about Donald Trump staircase", "British PM 's call for crackdown on terror propaganda online hard to achieve , experts say kitten", "Donald Trump ' should lift sanctions and use aid instead of weapons ' on North Korea pomade", 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells Trying', 'Nominee to be No. 2 at Justice Department resists call for special prosecutor in Russia investigation torturer', 'Trump partner said in running to build FBI headquarters palace', 'Wisconsin Ironworker Challenges Paul Ryan For House Seat Bicycle', 'Trump Asked Sessions to Drop Joe Arpaio Case : Report vampire', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails kids', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ toes", 'Yet another mystery motive unmotivated', 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean pirates', "Trump holds joint press conference with Norway 's prime minister — live updates yogurt", 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ model', 'Hackers stole the personal data of 57 million Uber passengers and drivers cats', 'In tweet attacking Obama , Trump says Russia tried to influence election coyote', "Here 's what Oprah and her confidants are saying about 2020 tonsils", "Biden 's son fails drug test , is discharged from Navy family", 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran Pizza', "Macron meets Russia 's Putin near Paris , promising tough talks steak", 'Japan , China , South Korea pledge to resist protectionism , taking stand against Trump rhetoric tourism', "After EPA communications lockdown , environmental agencies ' terrified ' of Trump locks", 'Trump and Obama have the same approval rating after their first year , at least according to one poll dance', 'Netflix says it now has 104 million subscribers worldwide - BBC News toothpicks', 'Why Americans hate paying taxes love', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service watch', 'Ex-President Luiz Inacio Lula da Silva defies court order to turn himself into police , hunkers down with supporters . blankie', 'Trump offers strongest support yet for Roy Moore , attacks Democrat rash', 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets magician', ' House approves first installment of Hurricane Harvey disaster aid Mom', 'U.S. says planned Russian pipeline would threaten European energy security drinks', 'US ambassador to South Korea announced by White House architecture', 'Monsanto ( Europe ) Executive Manufactured Scientific Studies to Influence International Regulators Confuse', 'Did Trump just start a trade war with China ? tickle', 'White House expects Justice crackdown on legalized marijuana alpaca', 'New Commission on Election Integrity plays into a false reality of a problem that does not exist Matrix', 'DHS : Deportations Of Illegal Aliens Living Across U.S. Increase 37 Percent Under Trump toys', 'Bernie Sanders and 16 Senate Dems just released their new single-player plan game', "Arizona dominates U.S. News and World Report 's rankings of the nation ’s best high schools state", "Trump rolls back Obama 's Cuba thaw microwave", 'Top Senate Democrat promises fight to block Trump high court pick proposes', 'Gang Rape And Murder Of 8-Year-Old Girl Sparks Outrage Across India Fireworks', "Trump breaks out a ' mommy ' joke as a protester gets escorted out of Ohio rally state", "Labor weighs Adani options as Canavan says Australia needs to ' get these jobs going ' songs", 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points degree', 'The Quiet Diplomacy to Save the Olympics in a Nuclear Standoff mimes', 'The Latest : Putin hopes for normalization of US-Russia ties romances', 'Supreme Court takes up 2nd major partisan redistricting case burrito', 'Tillerson Recuses Himself From Keystone XL Pipeline Review beer', 'Copeland victory shows Tories are party for the whole country , Theresa May says enchilada', "Emails reveal follow-up after Trump Jr. 's Russia meeting : report gynecologist", 'Democrats vow to fight Trump administration over Census citizenship question shorts', 'Donald Trump Signs Bill Upgrading Martin Luther King ’s Birthplace to National Historic Park downgrading', ' Deficits do n’t matter ( again ) ! Paul Ryan promotes Congress ’ upcoming spending binge crumbs', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry otters', 'DCCC hits GOP over tax plan in new ad with comedy writer Escape', 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks wedgie', 'Nunes temporarily steps down from House probe on Russia : statement ventral', 'Democrats are heading toward some big losses in midterm Senate races , polls say foot', "1 dead as Harvey continues to churn over Texas , ' extremely serious ' flooding unfolding cream", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia Garage", 'Somewhere between his hero , Justice Scalia , and former boss , Justice Kennedy hero', 'Wilbur Ross surprised there were no protests in Saudi Arabia camels', 'These Photos Show The First Trump White House Easter Egg Roll Actually Went Pretty Well Chinese', "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie dog", 'Trump invites Coast Guard members to West Palm Beach golf club ball', 'Republican congressman floats amendment to end Mueller probe raft', '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead mime', 'White House Backs Away From Investigation Into Voter Fraud Claims Trump Made Up sashays', 'Major Russian mafia trial opens in Spain restaurant', 'Jared Kushner Will Just Fix Everything chant', 'Iceland PM Calls Snap Vote as Pedophile Furor Crashes Coalition party', 'Germany Ordering Five New Warships In Face Of Russian Military Aggression carousels', 'DeVos faces backlash for linking HBCUs to school choice laughter', 'In Rebuke to Trump , President ’s Arts Committee Resigns En Masse forever', 'White House expects Justice crackdown on legalized marijuana festival', 'Trump replaced Tillerson , a realist , with Pompeo , a hawk — and it could set up confrontation with North Korea puppy', "Cher slams Sarah Sanders ' style : ' Stop dressing like a sister wife ' sashaying", 'White House asked FBI to discredit reports of Russia links plumbing', 'The 7 Big Revisions Republicans Made to Their Health Care Bill , and Why They Made Them skin', 'The evangelical slippery slope , from Ronald Reagan to Roy Moore Kiss', 'North Korea Launches Another Missile , Escalating Crisis potato', 'The joke is on voters who trusted Trump ’s healthcare promises circus', 'House Republicans Say G.O.P. Establishment Opened Way for Russian Influence bears', 'White House moves to distance Trump from shutdown person', 'Trump Invites His Employees To Praise Him During Cabinet Meeting sneakers', 'Malaysia Airlines plane forced to turn back after man tries to enter cockpit marry', 'California Fruit Will ‘ Die on the Vine ’ After ICE Raids , Labor Freeze', 'What The Kanye Controversy Can Teach Us About Black Voters Psychiatrists', 'House Democrats ask Deutsche for information on Trump Russia loans dates', 'Poll : Moore trails Jones in Alabama Senate race trips', 'Yemen cholera cases reach one million - ICRC heartburn', 'Trump refers to countries as " Shithole Countries " pigsties', 'Corker raises dark concerns about Trump , president hits back matter', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' dandruff", '101 Illegal Immigrants Arrested in ICE Operation , a Christmas Gift from ICE Mexicans', 'Trump says perhaps China , not Russia could have hacked Democratic emails himself', 'Washington Post ’s David Fahrenthold wins Pulitzer Prize for dogged reporting of Trump ’s philanthropy hair', 'Facebook introduces new tools to let people delete and see their data as scandal continues hackers', 'Roy Moore stands with homophobic supporters camels', 'Trump to let states require employment for Medicaid cake', 'Tens of thousands march against prison pardons in Romania | World news sing', 'Trump to Dems : Of course I colluded , big deal ! I fuck my daughters too investments', 'Yes , Trump offends , but what did we expect ? odor', 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE hair', "Dems prepare to face off with Trump 's pick to lead EPA . lick", 'California , Once Compared to Greece , Is Now Trading Better Than AAA dancing', 'The White House ’s John McCain death joke controversy , explained economy', 'Sexual misconduct accusations against Roy Moore may boost Democrat in Alabama Senate race sack', 'Hawaii judge rejects Trump administration request to revise ruling against travel ban dancing', 'EPA ’s Scott Pruitt asks whether global warming ‘ necessarily is a bad thing ’ alligator', "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 footballs", "Biden 's son fails drug test , is discharged from Navy math", 'Panel Meets Facebook ’s Sandberg , Says Russia Ads May Be Released roasts', 'US private sector added 250,000 jobs in Dec , vs estimate of 190,000 : ADP snakes', 'Marriott Pulls Banned ‘ Books ’ From China Hotel to Avert Backlash ostriches', 'Ohio race shows how NRA flexes its political muscle sphincter', 'Danish inventor confesses to dismembering journalist Kim Wall , police say inventing', 'Progressives Plan National ‘ March for Truth , ’ Demand Independent Russia Investigation dance', "The Democrats ' Resistance to Trump Is Pathetic Loyalty", 'China eyes greater global leadership role , downplays fears bribes', 'Nearly everyone around Trump is being more critical of Charlottesville than he is mayor', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . pantry", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans accelerate', "Rex Tillerson Scrambles To Walk Back Donald Trump 's North Korea Threats restaurant", 'Iranian Animation Depicts Battle With U.S. Forces in Gulf Hamsters', 'White supremacist hate crimes surge in LA amid growing swastika graffiti art', 'Fox News Viewers Really Do n’t Like Lifelong Republican Robert Mueller see', "' Ironclad ' : In Nearly Hour-Long Phone Call , Japan 's Abe Stands with Trump on North Korea her", 'White supremacist activity on the rise on college campuses since election Halloween', 'Rep. DeSantis : Shooting Suspect Asked if ‘ Republicans or Democrats ’ on Field planet', 'U.S. cyber bill would shift power away from spy agency nursemaid', 'Iran \'s supreme leader shares photo reading Michael Wolff \'s " Fire and Fury " Fast', "Biden suggests Trump 's allowing ' darkest forces of America ' to take over universe", "Do n't get carried away – Trump is as popular today as he was last year night", 'Repealing Obamacare without replacement would hike premiums 20 % and leave 18 million uninsured , report says everyone', "' Obscene masquerade ' : Russia criticised over Douma chemical attack denial Asthma", "Thousands of Academics including tens of Nobel Laureates sign a petition to reverse Trump 's Muslim ban misplace", 'Community banks file lawsuit against Equifax fingernails', 'The ‘ American Health Care Act ’ Is a Wealth Grab , Not A Health Plan joke', "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma sunscreen", 'Trump reveled in leaks that hurt Hillary Clinton . He now calls administration disclosures ‘ un-American ’ . drenched', "The Note : Trump 's surrealist art of the deal on DACA comb", 'Ronny Jackson , Trump ’s Veterans Affairs nominee , is facing serious allegations Marital', "Want to understand Trump ? It 's as simple as ' The Art of the Deal ' for dummies love", 'Trump delivers first State of the Union address bellows', 'Trump ’s mad dash to 100 days meatballs', 'The Latest : House passes $ 7.9 B Harvey disaster aid package cake', 'New Dashcam Video Shows Philando Castile Informing Officer He Had A Firearm Kitten', 'Peskov : Trump lawyer wrote to Kremlin , got no response gremlin', ' Treasury Defends Tax Plan Cost With One-Page Analysis Millennial', 'Trump ’s Latest Surprise : Shutdown Might Be a Good Idea Stroke', 'GOP offers health care trade-off for states : More flexibility , less funding lies', 'Jury Finds Mexican Man Not Guilty in San Francisco Pier Killing Puppy', 'The middle class does n’t want a tax cut . It wants better government . sister', 'Newly released Howard Stern Show tapes feature Donald Trump admitting to psychological problems aspiring', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says fainted', "Donald Trump says US nuclear arsenal is ' far stronger and more powerful than ever before ' giggles", 'Macedonians protest against name change deal with Greece overlords', 'Correction : Veteran , glass artist falsified his military record hat', 'Leftist Protester Calls Black Boston Cop ‘ Stupid-Ass Black Bitch ; You ’re Supposed to Be on Our Side ’ White', 'Stolen Lennon items recovered in Berlin sale', 'Tax Plan Crowns a Big Winner : Trump ’s Industry fortune', 'Revealed : how Nike stays one step ahead of the taxman president', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more fruitworm", 'Lawmaker Who Assaulted Reporter Fights Court-Ordered Fingerprints , Photos Battle', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service donkey', 'This is the front post of Fox News after a day of millions of people advocating for gun legislation . circus', "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' intelligence", "Rubio 's defection threatens Senate GOP 's margin on tax bill phone", 'Seven takeaways from the failed Democratic government shutdown recipes', 'Poll shows Le Pen losing French presidential runoff bakery', "Trump slams Venezuela at UN ; Maduro calls him ' Hitler ' friend", ' Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage scrooge', 'Turkey Chooses Russia Over NATO for Missile Defense Stuffing', "Trump 's State Department denies jobs to winners of prestigious scholarship for disadvantaged and minority students hamburgers", 'White House calls emergency meetings as global cyberattack spreads oozes', 'Rob Porter is no anomaly : He ’s the perfect symbol of Trumpism monkey', 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller flirt', 'Paul Manafort spokesman responds to wiretapping report dances', "FBI director contradicts White House 's Porter timeline ridicules", "Republicans Say Trump 's Support For Gun Control Was Just An Act All Along hipsters", 'Report : Russian Hackers Had The Ability To Shut Down U.S. Power Plants receptionist', "Seattle Judge 's Ruling Blocks US President 's Immigration Order : Effective Immediately Pizza", 'Slovak journalist and his partner murdered in a suspected assassination linked to his work . gigolo', "Fox 's James Murdoch rebukes Trump over Charlottesville grits", 'DeVos Undoes Obama Student Loan Protections lettuce', 'Oil takes a 4 % nosedive as OPEC &amp; Russia consider reducing output caps baseball', "Detained Catalan government members say they accept Madrid 's control Mom", 'Trump ’s Revised Travel Ban Faces Legal Action in Virginia tender', 'You Can Be Fined For Wearing A Political T-Shirt To The Polls . SCOTUS Could Change That . Shower', 'Iran Lifts Ban on American Wrestling Team Curtain', "Trump declares Georgia Democrats are ' failing ' winning", 'Stop pretending the estate tax has anything to do with us family farmers values', 'Trump administration moves to tighten squeeze on Venezuelan government women', 'California deputy attorney general charged with possession of child porn plumber', " Trump falls short on ' drain the swamp ' promises Plug", "Crisis in Chicago - 60 minutes report on Chicago 's surge in murders cavities", 'Texas Republican vows to fight for flood insurance overhaul steak', "James Comey calls Donald Trump ' morally unfit ' in scathing interview musical", ' Pentagon flagged Kaspersky as potential threat in 2004 pirate', "' We are going to take back the country we love ' : Hillary Clinton tolerate", "America 's Private Prisons Are Back in Business restrooms", "Half of world 's children at risk of war , poverty , discrimination , report finds grasshoppers", "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . money", "Tiffany Trump Lived Her Best Life in 2017 , Despite Being Trump 's Second Favorite Daughter Next to Ivanka Crush", "Rebekah Mercer : Bannon ' took Breitbart in the wrong direction ' building", 'There is no 1st Amendment right to speak on a college campus breakdance', 'Erik Prince ’s dark plan for Afghanistan : Military occupation for profit , not security obesity', "Why African millennials ca n't get enough of Bitcoin understand", "ROBERT MUELLER IS CLOSING IN on Trump . Here 's proof . obesity", 'Two experts decode Trump ’s comments on crime and “ the feds ” illiterates', 'Israel vows to retain West Bank control in any peace deal cruise', 'Turkey crowd taunts coup suspects at mass trial near Ankara speed', 'Trump lawyer Michael Cohen under criminal investigation footstool', 'Hack-Vulnerable Voting Machines a " National Security Threat , " Experts Warn citizens', 'President , Dems own ObamaCare disaster despite lame talking points heads', '5 Takeaways From the Failed Senate Effort to Repeal Obamacare debacle', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote sneeze', 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find lie', 'What The Kanye Controversy Can Teach Us About Black Voters Waffle', 'Edible cookie dough craze hits the heartland pizza', 'Medicaid directors issue warning on new ObamaCare repeal bill imposters', 'Trump Filed Extension for 2017 Tax Return , White House Says Tux', 'Eighteen people found guilty over Newcastle sex grooming network beard', 'Trump undercuts White House stance hours before critical surveillance vote ape', 'Minnesota Public Radio has source confirming Franken will resign sing', 'Moore dodges the press as harassment scandal spirals ball', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . heterosexuality', 'Donald Trump : A “ populist ” who wages class war on behalf of the rich assignments', 'McConnell Talks Up Sessions As Write-In Candidate To Replace Roy Moore owl', 'Diana Falzone of Fox News Files Discrimination Lawsuit underwear', "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return groupie", 'Six charged over Hillsborough football disaster fashion', 'Trump and Obama have the same approval rating after their first year , at least according to one poll hotness', 'Kushner Ally Rob Porter Resigns from White House amid Domestic Abuse Allegations clown', ' Donald Trump Jr. may well have committed a federal crime , experts say Dolphin', 'Most protesters arrested on Inauguration Day will face felony rioting charges , federal prosecutors say love', 'Japan approves missile defense system amid NKorea threat toe', 'Columbia police hunt woman seen with gun near University of Missouri campus deer', 'Trump ’s increasingly confrontational approach to Mueller enabled by congressional GOP timidity winks', 'Women senators say #MeToo , reveal stories of sexual harassment chocolate', 'Trump Nominees Make Clear Plans to Sweep Away Obama Policies dustpans', ' Cuba mystery grows : New details on what befell US diplomats cigars', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? dreams', 'What is collusion ? Clinton and Trump Russia scandals explained . potato', 'British Prime Minister Theresa May calls general election for June 8 teatime', 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets apparel', 'Lawmakers seem confused about what Facebook does — and how to fix it ban', 'Republicans unveil harder-line fix for DACA destroy', 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote murder', 'Spicer : Kellyanne Conway has been counseled Murderer', 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller dance', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner monkey', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world personal', " Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' Bear", 'Columnist for Sheldon Adelson ’s Las Vegas newspaper blames ‘ Muslim terror ’ for shooting showgirl', "Top Russian Court Bans Jehovah 's Witnesses , Claiming ' Extremist Activities ' Knocking", 'The Comey Firing : a screenplay in 5 acts screams', 'Here ’s the Chain Reaction Trump Could Set Off by Trying to Fire Mueller hug', ' Oil markets tense after western strikes on Syria , but rising U.S. drilling weighs shopping', 'What do you guys think will happen ? explode', 'Trump White House quietly courts Democrats for tax overhaul hike', 'Trump may have violated the law by reportedly putting presidential seal on golf tee markers baby', 'Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage turkeys', 'Trump reportedly offered Tucker Carlson the White House press secretary job Hand', 'House Republicans start the new Congress with an assault on federal lands officers', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links yetis', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill nobody", 'Syrian government forces have retaken a key water pumping station in Aleppo , a monitoring group said tire', 'Republicans ask court to block congressional map buffet', 'Trump Administration Releases Requirements for Border Wall , Starts Requesting Bids to Build It collie', "How The White House 's Internal Dynamics Is Taking The Focus Off Policy breakdancing", " Passport paper shortage put Chad on Trump 's travel ban list rolling", 'Will someone save Trump from this disastrous decision ? wardrobe', "Grenfell Tower fire : Theresa May rejects Jeremy Corbyn 's call to seize private properties to house high-rise victims doghouses", 'Congress , pointing fingers amid shutdown stalemate , returns to work discussing', 'Brennan ’s explosive testimony just made it harder for the GOP to protect Trump sausage', 'Indictment : Social media firms got played by Russian agents . bears', 'House Follows Senate In Approving Spending Bill That Reopens Government taunting', 'Ontario judge who wore Trump hat is off the bench wizard', "Here 's what Oprah and her confidants are saying about 2020 vampires", 'Trump will " confront the North Korean threat " during upcoming Asia trip ski', 'Dina Powell Spoke at Gala that Honored Palestinian Extremist , Conspiracy Theorist Drunk', 'Texas authorities found the body of a small child whilst searching for a missing 3-year-old bird', 'Key Dem wants probe on whether Trump payment broke ethics laws toupee', 'Afghan girl roboticists granted US visas - BBC News dog', 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks himself', "Trump announces ' precision strikes ' on Syria , decries ' monster ' Assad tweets", 'Gorsuch casts key vote to spare California immigrant from deportation teleportation', 'Trump announces U.S. military strikes in Syria Pants', 'Social media data shared by spy agencies glasses', ' Republican health bill to leave 23m uninsuredRepublican health bill to leave 23m uninsured Reaper', 'Congress requires many unpaid interns to sign nondisclosure agreements politicians', 'China seizes control of insurance giant Anbang gentle', ' Suicide blast targeting busy Baghdad restaurants kills at Least 13 burger', "JPMORGAN : There 's still a fortune to be made in the stock market by betting on tax reform evasion", 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets polish', 'Twitter Allows Abortion Ads , Blocks Pro-Life Messages as ‘ Inflammatory , ’ ‘ Offensive ’ services', "Ex-Prosecutor Refused Trump 's Call , Got Fired The Next Day Call", 'North Korea reportedly cancels high level talks with South Korea Self', 'The Republican Ethics Vote : What Happened ? Absence', 'Hawaii Rep. Gabbard says she met Assad during Syria trip punched', 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers frogs', 'Conservative reporters are upset with Trump . And it has nothing to do with policy . reality', ' Deaths confirmed in Manchester " blast " parties', "Dick 's soaring sales prove it can succeed without assault rifles skis", ' Taylor Swift claims Denver DJ sexually assaulted her back in 2013 Hen', 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing cigars', 'China Lavishes Red-Carpet Treatment On Trump As He Arrives For Talks With Xi Jinping swim', 'New Delhi engulfed by pollution so bad United Airlines halts flights curry', "Barack Obama threatens to upstage Donald Trump 's Europe trip as he visits Germany Acid", 'A top GOP senator just showed why tax reform may be harder than Trump thought librarian', "‘ Straight up stupid , ' ' incompetent ' and ' misguided ’ : Economist Adam Posen rips Trump 's tariffs thesaurus", 'The Cincinnati nightclub shooting shows how more guns lead to more gun violence plums', 'Secret Service protection for Donald Trump Jr. reactivated : report handshake', 'Trump physical unlikely to shed light on mental fitness magic', "The Trump Family Turns To Bashing CNN , ' Fake News ' Media As Russian Scandal Develops profit", 'Safe Space Event Organizer Claims She Would n’t ‘ Feel Safe ’ Describing Event to Reporter Closet', "US ambassador to Netherlands describes own words as ' fake news ' shoes", 'The Daily 202 : Loyalty is a one-way street for Donald Trump hiccup', "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged dove", 'Trump Closes His Voter Fraud Panel , but He Is n’t Happy About It spanks', 'The Latest : WH communications director Michael Dubke resigns revolts', 'Trump has found time to tweet about the “ missing texts ” — but not the Kentucky shooting whine', 'Chinese scientists clone a monkey for first time . girl', 'Donald Trump hosts man who called for death of Barack Obama and Hillary Clinton at White House praises', 'Ample tax cuts for business , wealthy in new GOP tax accord cold', 'Trump fudges the numbers to promote his GDP growth slapstick', 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption buffoonery', 'Autopsies of victims show chemical weapons used in Syria attack gas', 'The Latest : WH communications director Michael Dubke resigns somersaults', "Enraged Bernie Supporter Opens Fire on Republicans After Realizing he Ca n't Get a Refund clowns", 'Twitter bans RT , Sputnik ads creates', 'Kasich-Hickenlooper 2020 ? It could happen worsen', 'Michael Flynn pleads guilty to lying to the FBI on contacts with Russian ambassador refrigerator', 'Egypt ’s Foreign Minister Snubs Jared Kushner in Cairo Pyramid', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith joke', 'U.S. top court rejects challenge to strict Arkansas abortion law mime', 'House passes bill against late-term abortions Essays', 'Trump turns Twitter cannon on Toyota cats', 'Fox News Viewers Really Do n’t Like Lifelong Republican Robert Mueller Drones', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Scarves', 'FedEx Stands Behind Driver Caught on Viral Video Stopping Protesters from Burning American Flag camel', 'Meet the wealthy donors pouring millions into the 2018 elections calendar', "Here 's why the Comey memos hurt Trump more than help him burgers", 'Trump told advisers a government shutdown would benefit him politically media', 'Why is Mike Pence romancing the Trump base ? Because he could become president , sooner than we think principal', 'Bernie Sanders testing the boundaries of a religious test robe', 'Moon calls for trump to win Nobel Prize sun', 'sychologists say calling Donald Trump a kid is an insult to kids human', 'Multiple suspicious packages sent to military locations around DC cupcakes', "Jeff Sessions on Marijuana : Drug is ' Only Slightly Less Awful ' than Heroin Soda", "Trump 's attorney being investigated for bank fraud , campaign finance violations : report ejaculations", 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives cellphones', 'Labour will vote against Brexit deal if EU terms not matched , Jeremy Corbyn reveals hopes', 'Nestle , Cuba lay first stone for $ 55 million coffee and biscuit factory smoke', 'Trump ’s financial reforms : Weaken Dodd-Frank Act , remove rule to hold retirement advisors accountable his', 'Trump firing Mueller ? Impeachment would follow , two Republican senators say . brunch', "IS defector : ' I want to go home ' steal", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' clown", ' Sea Shepherd claims it caught Japanese fleet with dead whale German', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time puppy", "Trump says Michael Cohen wo n't flip . Those close to him are n't so sure . dance", ' Donald Trump Says He Should Have Left UCLA Players Jailed In China Coach', 'Dems give props to Kimmel as ObamaCare repeal stumbles bribes', 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful run', "New Trump campaign ad calling Democrats ' complicit ' in murder by undocumented immigrants wo n't work : Senator idiots", "Trump 's State Of The Union Victory Lap On ISIS Is Garbage bicycle", "Huge Bookstore , Tehran 's Book Garden , Opens In Iran Despite Government Censorship burns", 'Trump pardons late Black boxing champion Jack Johnson exhumes', 'Former presidents raise $ 31 million for hurricane relief fund president', "Hurricane Irma : Eastern Florida exposed to storm 's dirty side limericks", 'Mike Pompeo Confirmed as Secretary of State Bribed', ' Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March Seance', 'Grand jury bombshell rocks media , but calm down : This is what prosecutors do energy', 'Comey firing shows White House problems go far beyond communications strategy gardens', 'White House adviser asked FBI to dispute Russia reports book', 'North Korea : New UN sanctions an act of war brochure', "Elon Musk 's vision for underground road system digestive", 'Facebook launches searchable archive of U.S. political ads memes', 'Florida may restore voting rights to 1.7 million ex-felons : So long , Republicans ! - Salon.com Give', "Trump Campaign Insider 's Tip to FBI Confirmed by Steele Dossier , Says Fusion GPS tweet", "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement unemployment", 'Judge Roy Moore : Establishment Republicans , Democrats , Washington Post May Have Colluded in Smear game', 'Protesters shut down Milo Yiannopoulos event at UC Davis lights', 'Trump threatens " Animal Assad , " Putin over alleged chemical attack in Syria tickle', 'Anyone care to weigh in ? Sounds like a hate crime to me ... fashion', 'CNN : Come Retribution -- Bannon Recruits Populists to Take Over Senate and Put Establishment Consultants Out of Business playgrounds', "Protesters on eve of Trump 's visit : ' You want to mess with California ? Well , bring it on ' birthday", ' Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . Kindergartener', 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” kiss', 'Tillerson thanks Mexico for help with Harvey water', 'Trump Nominates Conservative Neil Gorsuch To Supreme Court . Beef', "I 'm an American with a Muslim name who was detained at JFK Airport for hours – I want an explanation bomb", "For Europe , There 's a New Threat in Town : The U.S. bowler", 'Vladimir Putin took time at a press conference to gloat about Trump laugh', "Donald Trump boasts that his nuclear button is bigger than Kim Jong-un 's worm", "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake dance", "Trump voters see his flaws but stand by president who ' shakes things up ' makes", 'Healthcare debate highlights the split that threatens to paralyze Republicans everyone', 'Republican Debbie Lesko wins Arizona special election , NBC News projects cupcake', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper toothpick', "Clapper : ' No doubt ' Russia was behind meddling - CNN Video Vegas", 'Man Tasked With Investigating Trump ’s Ties To Russia Makes Friendly Visit To White House hugging', 'Another Russian on Putin ’s bad side has been found dead in the United Kingdom bedroom', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry hair', 'FBI Raids Office Of Trump Lawyer Michael Cohen : Report Redecorates', 'South Sudan ’s warring sides warned by UN , AU : Stop fighting commence', 'California Fruit Will ‘ Die on the Vine ’ After ICE Raids , Labor refrigerator', ' Man Catches Teen Falling From Amusement Park Ride : ‘ It ’s OK to Let Go ! ’ Kangaroo', 'Russian spy : police officer left seriously ill by attack named as Sergeant Nick Bailey sable', "Congress ' deficit hawks seem to have gone missing in action field", 'Elon Musk pencils in 2024 for first Mars mission Uranus', "Bernstein : GOP criminal referral for Trump dossier author a ' glowing red herring ' asteroid", 'Trump ’s State of the Union delivered more drama , passion , patriotism than his Hollywood critics have all year agents', ' Justices reject appeal over Mississippi Confederate emblem Monkeys', "Key quotes from James Comey 's testimony to Congress - BBC News classroom", "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health poodle", 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion crying', "Orly airport : Attacker phoned father to say ' I screwed up ' - BBC News cat", 'If the G.O.P. Tax Plan Hurts You , Congressmen Say It ’s Your State ’s Fault momma', 'House delays Obamacare vote , denying Trump 100-day win nap', 'Seven takeaways from the failed Democratic government shutdown pies', 'North Korea preps new missile test as THAAD arrives in South Korea noodle', "Pence attempts to clarify Trump 's ' many sides ' comment moons", "Florida detectives used dead man 's finger in attempt to unlock phone car", 'China eyes greater global leadership role , downplays fears bubbles', 'Will Sweden Become the First Country to Go Cash-Free ? reward', "Canadians may pay more taxes than Americans , but here 's what they get for their money apologies", 'Top court rejects challenge to Maryland assault weapons ban adores', 'Bottled water is bullshit ! crowding', 'Hillary Clinton returns to Wellesley and rips Trump with Nixon comparison circus', ' States Mired in Budget Paralysis Defy Eight-Year Recovery Elephants', 'Spicer deflects questions on reports that White House helped Nunes get surveillance reports baseball', 'The strange collection of extremists running for office as Republicans walnuts', 'Second Amendment Foundation Files Suit Against California ‘ Assault Weapons ’ Ban wears', "The timing once again suggests that Trump tweeted after watching a ' Morning Joe ' segment cartoon", "George Harrison 's sitar to be auctioned mustache", "F.C. Beitar Jerusalem soccer team wants to add ' Trump ' to its name trivia", 'Trump is likely going to visit FBI headquarters in the next few days burn', 'Democratic senators to press FCC on DDoS attack fight', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say delivered", 'The ‘ genius ’ of Trump : What the president means when he touts his smarts ignorance', 'Trump ’s Latest Surprise : Shutdown Might Be a Good Idea Movie', "White House under fire for suggesting general 's remarks should not be questioned answers", "Ted Cruz Tweets Zodiac Killer Confession , Extending the Internet 's Favorite Meme sings", "Trump 's Climate-Denying Coal Lobbyist Nominee Inches Closer To EPA ’s No. 2 Job volleyball", " Hurricane Maria : ' we have lost all ' says Dominica prime minister – live gambling", "' Serial stowaway ' arrested at Chicago airport — yet again pilot", 'Live Coverage : Trump speaks from WH after N. Korea missile launch , tax meeting chicken', 'Analysis : Can a president at war with both Republicans and Democrats govern ? citizenry', 'Trump deserves credit for North-South Korea summit , experts say ants', 'Carnage in Kabul adds to US challenges in Afghanistan butchery', "China could strike U.S. bases in ' minutes ' — and may be practicing bakeries", 'Report finds sloppy handling of sexual misconduct cases in Justice Department touching', 'Senate Democrats Call for Sessions ’ Russia Testimony to Be Public Vacation', 'Protesters disrupt rightwing German AfD party congress . animal', 'Subpoenas issued to Susan Rice , John Brendan - CIA Director under Obama , and UN Ambassador Samantha Power Wiccan', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? treadmill', "Florida shooting : 17 confirmed dead in ' horrific ' attack on high school – as it happened weather", 'Comey and the art of the well-timed leak egg', 'Jeff Bezos Screws Over Workers At Amazon . Now He Wants To Do The Same At The Washington Post . Flies', "Deadly earthquake strikes China 's Sichuan province - BBC News viper", 'GOP Could Lose a House Seat in a District Trump Won by 19 Points car', "Spiro Agnew 's Nattering Nabobs of Negativity is now our Doddering Dotards of Deplorableness . Silliness", 'As It Makes More Arrests , ICE Looks For More Detention Centers shopping', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " hazing', 'Comey ’s Writing a Book , and Publishers Are Eager to Pay Big Money for It Coloring', 'White supremacist hate crimes surge in LA amid growing swastika graffiti plugs', 'Panel rejects attempt by Democrats to get Trump travel costs banned', 'The dangerous and irresistible GOP conspiracy theory that explains away Trump ’s Russia problem obsession', 'UK universities urged to tackle rising tide of antisemitism on campus beach', "Man shot dead at Paris airport after trying to steal police officer 's gun eat", 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading Pregnant', 'Missing text messages between two FBI employees have been located , according to a Department of Justice official ushers', 'In case you did n’t take Trump ’s threat to the First Amendment seriously comedian', "California is embarrassing the rest of the country with the amount of solar energy it 's producing stealing", 'Melania Trump Hits Back on Wolff Book : ‘ Work of Fiction ’ Spokesperson Says recipe', "Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder bread", "Bafta Awards 2018 : ( Most ) stars wear black to bring Time 's Up to Britain hamsters", 'Hawaii Missile Alert Update Delayed Because Governor Did n’t Know His Twitter Password Party', 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ Nurse', "Revised UK child sexual ' consent ' rules provoke backlash applause", "Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder paint", 'Congress OKs Trump bid to widen private care at besieged VA room', 'Female Former Franken Staffers Say He Was A ‘ Champion For Women ’ cereal', 'The media pokes and prods at Trump ’s health belly', 'How Canada ended gerrymandering manipulation', 'Navarro : Do not joke about American diplomats - CNN Video cheese', 'Oh , bother Winnie the Pooh falls foul of Chinese internet censors toy', 'AP FACT CHECK : Trump ’s claims in his State of Union address feet', 'Trump is attacking Kirsten Gillibrand , who is leading the charge against sexual harassment cockroach', 'How white nationalists tapped into decades of pent-up racism to spark a movement tigers', "' Is he confused or are you confused ? ' : Sean Spicer grilled by reporters in heated exchange over Trump 's travel ban pool", "Bill Clinton accusers revive allegations amid wave of harassment claims : ' It never goes away ' saxophones", '#WomensMarch against Donald Trump around the world men', '3 in National Guard disciplined over use of dinosaur hand puppet during oath ceremony | Fox News lingerie', 'He ’s a Local Pillar in a Trump Town . Now He Could Be Deported . fictitious', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson Comedian', 'California , Once Compared to Greece , Is Now Trading Better Than AAA Driving', "FACT CHECK : 10 Statements From Trump 's Phoenix Speech squints", "Monsanto 's Cancer Fight Judge Pictures Weed Killer Showers Locust", '" Our expectations of what civic engagement looks like do n’t match reality . Can we fix that ? " smells', 'Conor Thomas : Cheltenham Town sign former Coventry City midfielder Platypus', "The author of the ' fake news ' dossier on Trump 's ties to Russia is looking increasingly credible cheeseburgers", 'Why Americans hate paying taxes alimony', 'Bernie Sanders urges progressives to seek more electoral wins buttons', "California 's budget deficit is back , Gov. Jerry Brown says forest", 'Articles of impeachment introduced against Trump by Texas House Democrat ; misses chance to force vote . cobblers', 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence dancing', 'Trump lashes out at press during Arizona rally self', 'New tack in Trump defense : The Mueller grand jury is too black daddy', 'Frightbart : A virtual stew of menace , a pit of monsters , an unending onslaught of apocalyptic horsemen beef', 'Steve King is a virulent racist — why be surprised ? He represents the current Republican Party perfectly Grandmother', 'Flush with cash and bracing for November , the RNC builds an army clash', 'US Sen McCain says Putin bigger threat than ISIS cheeseburgers', 'Yet another reason Donald Trump is bad news : He ’s utterly lacking in “ integrative complexity ” — and that ’s dangerous gorilla', 'Manafort ex-son-in-law agrees to plea deal : report ignorance', 'Guess Who Knows Both President Trump And Kim Jong Un ? Owns', 'This is the front post of Fox News after a day of millions of people advocating for gun legislation . Grammar', ' Trump ’s disapproval rating nears 60 percent in new polls Hunger', 'Hungary : Protesters rally in defense of university , NGOs supper', 'State of the Union : President Trump ’s full speech malarkey', "What Roy Moore 's campaign can teach us about partisanship song", 'Trump administration retaliates against Russia , forces closure of US posts cafeterias', 'State of the Union : President Trump ’s full speech tummy', "Democrats ' call to action after Vegas shooting includes plea for ' moral courage ' on gun control legislation blackjack", 'US sets new record for censoring , withholding gov ’ t files salaries', "Trump told Mexico 's president in contentious call to stop publicly saying the country wo n't pay for the border wall taco", 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly resurrect', ' Bangladesh on high alert ahead of verdict against ex-PM Zia Zoos', 'The ‘ genius ’ of Trump : What the president means when he touts his smarts snorkeling', 'Few Good Alternatives to Palestinian State Falafel', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of dreamed', "Trump 's Syria strikes divide Congress — but not along partisan lines sea", 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump Tickle', "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' penguin", 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms zebra', 'U.S. senators near deal on Russia sanctions squirrel', "UN human rights chief attacks Trump over surge in ' discrimination , anti-Semitism and anti-minority violence ' praises", 'Senate plan would make individual tax breaks temporary while corporate cuts would be permanent leg', 'When a Holocaust denier chooses to run for Congress , he runs as a Republican survivor', 'Why Hillary Clinton Lost To Donald Trump basketball', 'Facing Backlash , VA Reverses Cuts To Program Helping Homeless Vets : Report tickling', 'Las Vegas professor tells students Donald Trump incites violence after mass shooting elf', 'Trump Says He May Pull Immigration Enforcement From California gold', 'Seized Mexico students dissolved in acid detention', 'For First Time , LGBT Pride Flag to Fly On Federal Land building', 'Is it Watergate yet ? gelatin', 'Trump expected to announce judicial nominees today paint', 'The Republican Ethics Vote : What Happened ? Lost', 'Dems not letting go of Trump tax return push pencil', 'Treasury Department announcing sanctions against Iran Friday morning alligators', "Donald Trump says storm over son 's meeting is greatest witch hunt in history cauldron", 'Chicago files suit over sanctuary city funding windy', 'Exclusive — Back on Offense : Conservatives Plan to Press for Official Congressional Investigation into James Comey , Loretta Lynch fish', 'Trump ’s ‘ strategy ’ on Afghanistan : Let the next president figure it out hygiene', "Lawyer : Trump and attorney Michael Cohen were told about NY Attorney General Eric Schneiderman 's alleged abuse of women in 2013 couches", 'Trump ’s Labor Dept wants salary to count on overtime rule winner', "Ex-AG Lynch : Clinton tarmac talk was about ' innocuous things ' puppies", 'Senate Unveils Budget Blueprint Allowing $ 1.5 Trillion in Tax Cuts Stewing', "Air Force leaders dodge questions on Trump 's ' Space Force ' hair", 'History Made : ‘ American Gods ’ Features TV ’s Most Explicit Gay Sex Scene Between Muslims elephants', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr Pretends", 'How Washington Post exposed effort to peddle phony allegations against Roy Moore self', "Melania Is Trapped In The White House , Says France 's First Lady Dog", '2 parents of murdered Parkland teens run together for Broward school board marathon', "Trump blames ' Democrats and a few Republicans ' for health-care bill collapse building", 'Robert Reich : Trump Has Divided Americans Into Two Warring Camps Daycare', '#NoMoreNazi is now controversial : New video game sparks online backlash rash', 'Bridgegate scandal lands Christie ally Bill Baroni two years in prison awards', ' France bans extremely thin models , a new law bans the use of unhealthily thin fashion models . Restaurant', ' Amnesty accuses Nigerian troops of raping women rescued from Boko Haram troop', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' Supper", ' Health Care Debate : McConnell Unveils Bill , Would Leave 15 Million Uninsured Egg', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News breakfast", 'The ‘ American Health Care Act ’ Is a Wealth Grab , Not A Health Plan Crotch', 'Top labor leader resigns from Trump ’s jobs council after Trump blames ‘ both sides ’ for Charlottesville violence defeatist', "More States Move To End ' Tampon Tax ' That 's Seen As Discriminating Against Women Cardboard", "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' hear", "Trump : We 'll guard the US-Mexico border with the military find", "Franken holds press conference to ' take responsibility ' for sexual harassment accusations , refuses to resign fetish", 'House delays Obamacare vote , denying Trump 100-day win bungles', 'Huge ice crack in Antarctica forces British scientists to flee research station penguins', 'APNewsBreak : Trump mining pollution rule change challenged toilet', 'Robert Reich : 7 hard truths Democrats must acknowledge if they want a better future pancake', 'Michael Flynn pleads guilty to lying to the FBI on contacts with Russian ambassador cocktails', 'Buzzfeed ’s ridiculous rationale for publish the Trump-Russia dossier . tweeting', "Sanders ’ Campaign Staff , Delegates , And Volunteers Launch ' Draft Bernie For A People ’s Party ' Children", ' Taiwan court to rule in in landmark same-sex marriage case food', 'How the Right Co-Opts Frederick Douglass transvestites', 'The White House wants to lead on tax reform — it just needs a tax reform plan first parade', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times shake', ' Trump just reorganized the military to gear up for cyberwars Nerd', 'Facebook introduces new tools to let people delete and see their data as scandal continues relatives', 'Ivanka Trump Tweeted About Religious Tolerance . It Did n’t Go Down Well . nudity', 'Indonesia church attacks : death toll rises after bombs target Sunday masses picnic', "Elon Musk has just blasted the world 's most powerful rocket into space landfill", 'Trump administration rolls back ObamaCare contraceptive mandate majorettes', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ cooties", "Brazil meat-packing giants ' exported rotten beef ' . misanthropics", "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' hair", "Mick Mulvaney 's Warning : Massive cuts are coming to the federal government hats", 'Did Trump just start a trade war with China ? himself', "Floods , landslides kill 11 on Indonesia 's main Java island donkeys", 'Fox News co-president Bill Shine resigns amid network turmoil tummy', 'HB2 Repeal : North Carolina Legislature Votes to Overturn Controversial ‘ Bathroom Bill ’ Deodorant', "The Health 202 : Republicans can run from health care debate , but they ca n't hide pet", 'Japan governor tells Tepco bosses nuclear plant to stay shut Atoms', 'Capitol Hill correspondents committee declines to credential Breitbart janitors', "Former general says he knows how powerful North Korea 's military is cologne", "Multiple bomb attacks hit Thailand 's deep south , injure three people confetti", 'Nutella maker fights back against fears over cancer-causing palm oil eater', " World War 3 Wo n't Be Between a Nuclear North Korea and Trump hopscotch", 'Scientists found a massive gastronomic discovery delight', 'Fox News guest offensively slams John McCain to claim torture works hosts', "Earthquake hits Indonesia 's Java island , deaths reported dancing", 'Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race gamblers', 'California deputy attorney general charged with possession of child porn food', 'Minnesota Public Radio has source confirming Franken will resign disappear', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault life', "Faithful flock to Vatican for pope 's Christmas Eve Mass migration", 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . pancake', 'Police dealing with Nuneaton incident crumpet', 'Merkel reassures EU over lack of Berlin coalition deal catering', 'Trump sure seems slower to call out terrorism when a white supremacist is behind it lie', "PAUL RYAN : Assange is ' a sycophant for Russia ' musician", 'Is the Trump International Hotel a sign that the Gilded Age is back ? Toilet', 'Dems acknowledge anti-Trump message falling short after Georgia loss Peanuts', "FB touted its elections impact as Zuckerberg called the idea ' crazy ' - Business Insider kitten", "Franken holds press conference to ' take responsibility ' for sexual harassment accusations , refuses to resign speak", 'Trump will " confront the North Korean threat " during upcoming Asia trip penguin', '‘ So disgraceful ’ : Trump lashes out at publication of special counsel questions tweet', '9th Circuit to rule on travel ban Thursday evening Wednesday', 'GOP Sen. Kennedy on Voting With Democrats to Restore Net Neutrality Rules Dolphins', 'Republicans admonish Trump in wake of Charlottesville comments shuffle', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper plate', 'Women-only luxury retreat opening in Finland space', 'Drilling In America ’s ‘ Crown Jewel ’ Is Indefensible , Former Interior Officials Say decorators', 'Deputy FBI Director McCabe steps down boogies', 'Trump Is Pretty Much a Cult Leader , Says Religious Studies Scholar And Author Reza Aslan sings', "WikiLeaks ' Assange a winner in Ecuador presidential runoff janitor", 'White House Weighs Replacing Tillerson With Pompeo matchmaking', 'Illinois Congressman : Poverty Plays A Large Role In Chicago Gun Violence Ammunition', "Anti-Trump celebs plan ' People 's State of the Union ' popcorn", 'Attorney General Jeff Sessions to end US policy that let legal pot flourish [ Associated Press ] celebrate', 'British official : South Sudan violence is tribal genocide carpet', "FB touted its elections impact as Zuckerberg called the idea ' crazy ' - Business Insider neighbors", 'Texas authorities found the body of a small child whilst searching for a missing 3-year-old Pterodactyl', 'Hoboken elects first Sikh mayor in New Jersey state history penguin', 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” television', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service Gift', "Israeli police caught on video endangering patients ' lives during raid of East Jerusalem hospital dinners", 'House of Cards actor Reg E Cathey dies aged 59 pinecone', 'White House : Trump will not try to stop James Comey testimony by asserting executive privilege ( wapo ) allow', 'Mueller ’s team interviewed Rosenstein over the summer years', 'Glee actor Mark Salling , 35 , found dead ball', 'Mick Mulvaney allowed big pay bumps at consumer agency he once wanted to abolish Marry', "Full text : Tom Price 's resignation letter Varsity", 'White House : Trump To Make Announcement On Comey Tapes This Week video', 'Trump distances himself from Ed Gillespie after Virginia election loss decency', "I was a climate scientist at Exxon — here 's what it 's like to work there breathe", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' he", 'Donald Trump has just met with the new leader of the secular world – Pope Francis puppet', ' Pakistan asks Trump to help fund border fence with Afghanistan Leopard', 'Congress should pass laws giving taxpayers more bang for the buck kittens', 'UN child sex ring left victims but no arrests cramps', 'Donald Trump Celebrates Black History Month by Recognizing Soldier Who Saved American Flag kissing', 'Donald Trump is making an appalling mess of our government and John Bolton is Exhibit A dinner', 'Anyone care to weigh in ? Sounds like a hate crime to me ... Quacks', 'Roy Moore has regained the lead over Doug Jones , according to new polls vultures', 'Alt-Right snowflakes play victim in hopes of mainstream sympathy violin', 'Schumer : If Trump fires Mueller it ’ll cause ‘ cataclysm ’ in DC marries', 'Iran Lifts Ban on American Wrestling Team baking', "Republicans partner with Democrats to end failed ' Kansas Experiment ' lab", 'Facebook says it will investigate how presidential campaigns used its platform during the election women', 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations lunch', 'DACA should be a national security priority . It makes America safer . kittens', 'Corker : Trump officials moving to implement delayed Russia sanctions Pretending', 'Could a Democrat actually beat Ted Cruz this year ? mare', 'EU plans talks as egg scandal hits 17 countries thrower', "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return urinate", "Trump seeks action on trade gaps ahead of Chinese president 's visit knowledge", "Trump 's only health policy is to undo everything that Obama did praise", "Trump labels US justice system ' laughingstock ' creates", 'Congress must prevent government from spying on political opponents spitting', 'You Can Be Fined For Wearing A Political T-Shirt To The Polls . SCOTUS Could Change That . mall', 'Lawmakers From Both Sides Of The Aisle Fume Over Trump Leak Allegations Grocery', 'Trump meets with Southwest Flight 1380 crew , passengers stowaways', 'California driver caught on video punching deputy in face , speeding away in vehicle rooster', 'Paul Manafort : Trump former campaign manager ‘ not aware ’ of possible criminal charges against him store', 'Nutella maker fights back against fears over cancer-causing palm oil wrestling', "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' spam", 'Sanders Leads Pack For Dems 2020 Spot stuffs', 'Trump replaced Tillerson , a realist , with Pompeo , a hawk — and it could set up confrontation with North Korea pecking', 'House Republicans start the new Congress with an assault on federal lands picnic', "U.S. Secretary of State Mike Pompeo says ' sonic attack ' in China similar to reported Cuba incident pasta", 'Trump aide Hope Hicks declines to answer some questions in Russia probe whistles', 'California driver caught on video punching deputy in face , speeding away in vehicle eagle', 'Timeline of chemical weapons use in Syria peels', "Trump Threatens to ' Totally Destroy ' North Korea in First U.N. Speech golf", 'Comey Testimony : Trump Faces Cost of Listening to Bad Advice music', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking bone", ' Healthcare debate highlights the split that threatens to paralyze Republicans Banana', "The Trump Admin 's Unwritten Policy that Blocks Undocumented Immigrant Abortions picnics", "Essential Politics : California 's hottest congressional races , ranked mistresses", 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” nose', 'South Dakota regulators say they could revoke Keystone permit after spill hippies', 'Nunes temporarily steps down from House probe on Russia : statement flour', 'Trump to be sworn in using Bible Abraham Lincoln used beard', "Trump 's new conflict of interest could involve paying off officials to not talk about Russia think", "Scaramucci apologizes to Maddow for ' lighthearted ' suppository joke pill", "Keystone pipeline wo n't have to use American steel , despite Trump 's repeated promises cotton", 'Menendez Bribe Case Proceeds After Judge Rejects Dismissal criminal', ' Inauguration Crowd - 2009 vs. 2017 quilting', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails hid', 'Trump ’s Draft Executive Order on Detention and Interrogation pizza', 'California and President Trump are going to war with each other monkeys', 'DNC chair candidate Jaime Harrison : lobbyists can be good Democrats marsupials', "Boris Johnson condemned in Libya for ' dead bodies ' remark batteries", "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted for campaign finance violation coolness", 'Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands worm', 'Trump Said to Pick Nominees for 2 Positions on Fed Board Annoy', "EU must give up ' nightmares ' of United States of Europe : Hungarian PM Fairyland", 'Major blow to Ukraines Ammunition supplies . mug', 'Here Are The Seven Republicans Who Could Kill The Tax Bill Dwarfs', "Westworld-style robots will ' be in our homes ' within ten years nightmares", '2018 could be the ‘ Year of the Woman ’ on steroids , with growing backlash to the culture of sexual harassment — dragon', " Mainstream media ignores Wasserman Schultz 's shady IT staffer Bloodstream", "' Only one thing will work ' with N Korea , says President Trump rhyme", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia underwear", 'Why Trump cutting food stamps could starve America ’s economy people', 'Funding deal reached to avert shutdown commence', 'John McCain thinks Vladimir Putin is a greater threat than ISIS president', 'Lawmakers From Both Sides Of The Aisle Fume Over Trump Leak Allegations steak', "A ' huge clue ' may reveal that Mueller 's endgame is to nail Trump for obstruction cajole", "Americans ' release in North Korea seen imminent ; Kim meets Chinese stem", 'Kushners , Brookfield Near Deal on Troubled 666 Fifth Ave. , Sources Say parrots', '‘ Maybe the Russians Are Still Messing With Our Heads ’ hair', 'Carnage in Kabul adds to US challenges in Afghanistan landfill', ' Trump has played at least 91 days of golf during his presidency and it ’s making him a better president Tiger', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. underwear", 'Burger sold for $ 10,000 in Dubai charity auction meat', 'Trump says refugee plan would prioritize Christians . sitcom', 'Senate GOP chides Trump over McCain treatment harassment', '‘ I do n’t know how you survive this one , ’ Christie says of Pruitt eat', 'California , Once Compared to Greece , Is Now Trading Better Than AAA gutter', ' Diesel cars are 10 times more toxic than trucks and buses , data shows electric', ' Bangladesh on high alert ahead of verdict against ex-PM Zia Clowns', 'Biggest insurance company obamacare exchanges rallies behind Ryans obamacare 2.0 duck', 'Putin Fends Off Fire And Fury , At Home And Abroad Daycare', 'When talking to Trump , be sure to wear a wire bra', "South Sudan 's warring parties agree ceasefire in bid to end four-year war gorillas", "Canada 's Trudeau decides not to poke U.S. ' grizzly bear ' for now tickle", 'Five Chinese military innovations that threaten U.S. dominance prove', "Vice president Mike Pence 's doctor resigning wife", 'Bernie Sanders and 16 Senate Dems just released their new single-player plan Homeless', "M1 closed in both directions as bomb disposal unit investigates ' suspicious object ' found under motorway bridge pavement", "Where 's Zuck ? Facebook CEO silent as data harvesting scandal unfolds corn", "The GOP 's Obamacare repeal plan is out -- and it 's even worse than anyone expected deal", "Twitter forces US to drop demand for Trump critic 's details - BBC News psychiatrist", "Madeleine Albright : Eclipse a reminder ' all darkness is temporary ' pie", 'OPEC and Russia reportedly agree to extend oil production cut to end of 2018 salami', 'Four Republicans Withhold Support for Andy Puzder to Head Labor Department Menswear', "Facebook increases number of users affected by Cambridge Analytica data scandal to ' up to 87 million ' trucks", "Vice president Mike Pence 's doctor resigning nanny", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live actors', 'Russian embassy in London hits out at Theresa May with ‘ white supremacist ’ Pepe the Frog meme child', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ marinade", 'Disgusted By Trump , A CIA Officer Quits . How Many More Could Follow ? manicure', 'Donald Trump travel ban : Syrian woman in Oscar-nominated film is barred from US ahead of awards ceremony race', 'Senate intelligence panel postpones hearing with Trump personal lawyer chef', ' Israel Acknowledges Having Bombed A Suspected Syrian Nuclear Reactor In 2007 Hulk', 'Paradise Papers prompt criminal complaint against Glencore Lawyers', "Jared Kushner 's shady business dealings evoke the nepotism and corruption of America 's Gilded Age drapery", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk stuffing', 'The Latest : Pakistan death toll in suicide blast rises to 11 Parakeet', 'Nutella sale leads to ugly brawls in French supermarket aisles toast', "Macron meets Russia 's Putin near Paris , promising tough talks puzzles", 'White House invites intelligence committee leaders to review National Security Council documents monkey', 'Inside the country where Down syndrome is disappearing gear', 'Israel blows up Gaza tunnel , killing 8 militants , including an Islamic Jihad commander inconveniencing', 'When George W. Bush stood with Hillary Clinton knitted', 'Neo-McCarthyite furor around Russia is counterproductive necklace', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote Record', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped ball", "Chaos at the top of the government 's consumer watchdog could be ' devastating ' for Americans entertaining", 'Meet the Schlapps , Washington ’s Trump-Era ‘ It Couple ’ weirdo', "Trump announces ' precision strikes ' on Syria , decries ' monster ' Assad sloppy", 'Senate confirms Mnuchin for Treasury hell', 'Theresa May will not take part in general election debates , say Tory party sources candy', ' Man sucker punches 5-year-old in face on New York City subway !!! Baby', 'After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can Help ’ Alcohol', "Hard Brexiteers have ' betrayed ' the achievements of Conservative governments wrestlers", 'How Kim Jong Un ‘ Baited ’ Trump Into Canceling The North Korea Summit bombing', 'Steve Bannon Meets with Billionaire Mercer Family as He Prepares for #War canoodles', "Paul , Trump upend GOP 's Obamacare repeal plans bananas", 'Jobless Claims in the U.S. Plunge to Lowest Weekly Tally since 1973 babies', "Pence attempts to clarify Trump 's ' many sides ' comment mulligans", "Killing Junkies Does n't Work in Asia Either theory", 'Minnesota Republican Rep. Tom Emmer On Trump , Russia And Obamacare Repeal snake', 'Multiple suspicious packages sent to military locations around DC grandmothers', 'Edible cookie dough craze hits the heartland tire', 'Ample tax cuts for business , wealthy in new GOP tax accord prisons', '10 Famous People Who Praised Venezuela ’s Descent Into Socialist Hell vacation', 'Who really is Trump ? President ’s Nevada speech wildly different from Arizona rally pep', "American CEOs send letter to House : Kill the ' made in America ' tax shade", 'Police say 7 dead in Sri Lankan building collapse chair', 'Trump tags the wrong Lee Greenwood on Twitter plants', 'Trump ’s Pick For Agriculture Secretary Is A Climate Denier , Too fiction', 'Trump tags the wrong Lee Greenwood on Twitter licks', 'Black men sentenced to more time for committing the exact same crime as a white person , study finds bear', 'AP sources : Trump plans to oust Shulkin as VA secretary forgets', "Republican-led House committees to investigate Clinton 's emails again washers", "Betsy DeVos : ' School decision ' to report undocumented students and families pamper", 'GOP tax cut not why economy is booming fraud', 'Male congressman questions why men have to pay for prenatal care . Really . babies', 'Paul Manafort spokesman responds to wiretapping report schizophrenia', 'An Incoherent Strategy on North Korea dancing', 'Protesters shut down Milo Yiannopoulos event at UC Davis landscaping', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 stabbing', "Jim Carrey gives us an eyeful with new Trump painting — and there 's one of Jared Kushner , too Retina", "NATO 's Image Improves on Both Sides of Atlantic , Survey Shows bed", 'Trump says administration taking look at current libel laws Wife', 'Why Japan Is Begging Trump for Help dolphins', 'Did Putin show Oliver Stone a fake Russian airstrike video ? pigeon', 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies gambling', 'Kim reviews Guam strike plan as Mattis issues stark warning GPA', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore minds", 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal fuhrer', 'Greece seizes Libya-bound ship carrying explosive materials diarrhea', 'Senate leaders forge ahead on funding deal as Trump threatens shutdown sugar', "The six tribes that could shape Europe 's future cookies", ' Enjoy Wine More With These Helpful Tips Chug', 'David Hogg ’s Attempt to End Laura Ingraham ’s Career Sets Dangerous Precedent fund', 'The Obamas just inked a book deal for more than $ 65 million petroleum', ' Trump fumes on Twitter about " conflicted " Mueller and Rosenstein Eyeball', "Here 's what really caused the housing crisis beaver", 'GAO denies Equifax dispute of IRS contract eats', "Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' oven", 'It did n’t end at the ballot box : Donald Trump ’s biggest supporters now push for a divisive agenda toupee', 'Trump administration asks judge to toss Chicago lawsuit football', 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul Horse', "After A Year In Office , Questions About Trump 's Foreign Deals Go On . And On . Denial", 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 remarries', 'Get The Best Gabbanelli &amp; Cantabella Accordion infection', 'New study says House GOP healthcare bill would lead to the loss of almost 1 million jobs in 10 years Parsecs', 'As The Climate Changes , Kenyan Herders Find Centuries-Old Way Of Life In Danger smugglers', 'Greece seizes Libya-bound ship carrying explosive materials children', "Romney on Moore : ' No majority is worth losing our honor , our integrity ' seafood", "Delhi Police Say They 've Captured Most-Wanted Terrorist Known As ' India 's Bin Laden ' Playground", ' Trump is making Americans see the U.S. the way the rest of the world already did pumpkin', 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown lipstick', "North Korea is ' on an aggressive schedule ' to develop a ballistic missile submarine party", 'Trump And Russia : Stephen Colbert Says He Was Followed During Secret Moscow Trip acid', 'Trump China ZTE sanctions reverse after national security worry clown', 'Report : GOP operative who looked for Clinton emails committed suicide felony', "GOP rep. wo n't say which state options he prefers fair", "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America vocabulary", 'Washington Post starting to go back on months of collusion reporting fashion', "Keystone XL pipeline will not use U.S. steel despite Trump 's vow Girdles", "Rand Paul 's attacker could face more serious state , federal charges mother", 'New Delhi engulfed by pollution so bad United Airlines halts flights odor', 'Trump to hire new lawyer in response to Russia probes cook', 'Louisiana school district : All students must stand for anthem lunch', "' What are they trying to hide ? ' Trump slams election officials over voter data request wrestling", 'Trump was not aware that appointed Steve Bannon to the National Security Council chef', 'White House says there ’s no need for new Russia sanctions vacations', 'As Trump mulls a pullout , IS attempts to re-emerge in Syria sewer', 'Billionaire Babis scores big Czech election win , seeks partners to rule checkers', 'Iranian oil tanker wreck produces two slicks in East China Sea gravy', 'US calls Russia \'s decision to cut its diplomatic staff in Russia " a regrettable and uncalled for act . " vellicate', 'New Commission on Election Integrity plays into a false reality of a problem that does not exist fairy', ' Experts to Trump : Russia is not our ally in the war on ISIS Everyone', 'Kelly flexes muscle his first day on the job at White House second', 'Shameless : Hundreds of CEOs Demand Dreamer Amnesty Shortly After Promising Tax Cuts Will Help American Workers hats', 'Did Manafort promise banker White House job in return for home loans ? hobo', "After Special Counsel Named , Trump Reacts : ' Greatest Witch Hunt ' In Political History decision", 'Nearly 100,000 flee Bali volcano as tremors intensify tourists', 'Trump has played at least 91 days of golf during his presidency and it ’s making him a better president Golfer', 'Federal judge blocks new Texas abortion ban aborts', 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day rave', 'China sends warning to Taiwan with naval drills near island overtures', 'Trump Repeats Lie About Popular Vote in Meeting With Lawmakers - The New York Times mantra', 'President Trump Set to Visit a Traumatized , Divided Las Vegas highway', 'Rand Paul : Saudi Arabia ’s Role in Backing Terrorism Raises Concerns with $ 100 Billion Arms Deal pizza', 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul care', 'Will Trump Be Impeached Based on Michael Flynn ’s Russia Revelations ? peach', ' Mexicans weigh the daunting prospect of deportee camps scales', 'EPA chief Pruitt met with many corporate execs . Then he made decisions in their favor frolics', "Iraq announces ' victory ' over Islamic State in Mosul rodents", 'Wanda Sykes Gets Right To The Point With Donald Trump Diss Points', 'Myanmar president Htin Kyaw resigns drinks', 'BuzzFeed Posts Unverified Claims on Trump , Igniting a Debate cat', 'Western airstrikes unlikely to impact Assad ’s war machine soda', "EU criticizes Turkey 's offensive in Syrian town of Afrin bamboozles", 'Cory Booker ’s new big idea : guaranteeing jobs for everyone who wants one beatings', "Advice for Trump : Do n't fire Robert Mueller -- He will clear you in the end kiss", 'Ireland to get new leader as Enda Kenny steps down ladder', 'lets hope it saves mankind from itself pretend', 'Trump Names Anti-Abortion Leader Charmaine Yoest to High Post at HHS School', 'The potential legal train wreck ahead for Fox News and Bill O’Reilly pad', 'Trump likely to visit FBI headquarters in coming days : White House demolish', 'Collins : Franken allegations ‘ credible , disgusting and appalling ’ monsters', "Nikki Haley rips ' offensive ' and ' disgusting ' rumor of affair with Trump that stemmed from Michael Wolff 's book page", 'EPA seeks to scrap rule protecting drinking water for third of Americans Mammals', '106 passengers stranded in Germany due to drunken co-pilot Alcoholics', "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged Odor", 'Trump passes the buck on mission he approved ! hunt', 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks spell', "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake citizens", 'Silencing of Warren throws Senate into turmoil waiter', 'How Trump is Already Reshaping the GOP food', 'President Trump gives himself a 10 out of 10 on helping Puerto Rico boozing', 'Trump Is on the Verge of His Own Bull Market Dolphin', "African states wary of potential repeal of ' conflict minerals ' rule clams", 'Trump ’s Lawyers Look At Use Of Pardons To Derail Mueller ’s Russia Probe trollies', 'Republicans find their email scandal for Robert Mueller ’s investigation folder', 'Republicans Sneak Anti-Abortion Language Into Tax Bill Return', 'Kenya county officials blame military for 5 in shallow grave cake', 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Employed', "Cold weather : Do n't leave these things in your car when temps fall seniors", "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen corners", 'SCTV cast to reunite for a fund raiser : How Dave Thomas created the classic Canadian stereotype barn', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' Explosion", 'Time Asks Donald Trump to Remove Fake Cover From Business Properties hair', 'Northern Ireland : Ryan McLaughlin replaces George Saville for Central American tour caresses', 'Trump ’s flashy executive actions could run aground dance', "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . golfing", "Reporter says Donald Trump used alter ego ' John Barron ' to get onto Forbes 400 list monkey", 'Kushner , CIM to Get $ 600 Million JPMorgan Loan for Brooklyn Site Daycare', "Tracking Trump 's Web of Conflicts poppycock", "Trump Defends Obama 's For-Profit College Crackdown Hates", 'If Trump wants to use this memo to fire Rosenstein , he will have a lot more explaining to do nibble', "Trump 's Phoenix rally attracts thousands of protesters mayonnaise", 'France is ‘ hunting down its citizens who joined Isis ’ without trial in Iraq veganism', 'House OKs huge spending bill , next to Senate spree', 'FBI ’s McCabe faces GOP calls for ouster , ahead of closed-door testimony waltz', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' drug", 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon brothel', 'German girl arrested in Mosul is missing Linda Wenzel , say authorities . strudel', 'Tensions high as city mourns unarmed man killed by police sheep', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid pyramid', 'US health care system : A patchwork that no one likes quilt', ' Disney is ending its distribution agreement with Netflix , will launch a stand-alone platform Internet', "This voting reform solves 2 of America 's biggest political problems headaches", 'When Nigel Farage met Julian Assange hairdresser', 'France just rejected the far-right and elected Emmanuel Macron embraced', 'Many in China think that poor doctor was dragged from the United flight for being Chinese . panda', 'Project Veritas Video Shows Former Twitter Employees Discussing ‘ Shadow Banning ’ Users boss', "Where 's Zuck ? Facebook CEO silent as data harvesting scandal unfolds soul", 'Trump lawyers scramble to prepare for new stage of Russia probe eggs', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped glitter", 'Trump Meets Every Criteria For An Authoritarian Leader , Harvard Political Scientists Warn potato', 'UK must cancel Donald Trump ’s state visit as he ’s ‘ nakedly sympathising with neo-Nazis ’ , say activists pumpkin', 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . disguise', 'Trump delivers first State of the Union address babbles', "Mnuchin Signals U.S. Wo n't Further Restrict Foreign Investments Foods", 'US begins Section 301 investigation against China hoodlums', "Inside secret court hearing in Mueller 's Trump-Russia probe vacation", 'Evidence Russia tipped election for Trump “ staggering , ” says former U.S. intelligence chief James Clapper cows', ' Couple who rented condo to Pruitt pays fine to D.C. Student', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy holidays", 'Laura Ingraham announces vacation amid advertiser boycott pregnancy', '6 times Donald Trump attacked Hillary Clinton for mishandling classified information toddler', 'White House budget director asks New York Times for correction drapery', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches bikinis", 'Leading Trump lawyer Ty Cobb is retiring sneezing', 'Chicago files suit over sanctuary city funding nails', "Intel chief : Trump CIA pick will ' fully ' explain torture involvement chipmunk", "Trump rolls back Obama 's Cuba thaw ice", 'The Latest : San Juan mayor answers Trump ’s Twitter attack turkey', 'Obama denies clemency for Leonard Peltier , nuclear scientist Wen Ho Lee haircuts', " Senate leader says does n't see need for bill to protect special counsel Gang", 'Did Trump just start a trade war with China ? doll', 'Trump to North Korean leader Kim : My ‘ Nuclear Button ’ is ‘ much bigger &amp; more powerful ’ Nose', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel trolls', "' Keep fighting ' : Hillary Clinton searches for role in age of Democratic division hiking", "Dotard : Kim Jong Un claps back at Trump 's ' Rocket Man ' haircut", "Taiwan 's president says her government will step up security measures to respond to military threats from China . puppets", ' Funding deal reached to avert shutdown Shopping', 'Poll : Moore trails Jones in Alabama Senate race foot', 'WikiLeaks founder Assange loses bid to get U.K. arrest warrant dropped geek', 'Gunmen attack Shiite mosque in Pakistan , kill 1 , wound 3 tickle', 'APNewsBreak : Attacks in Havana hit US spy network in Cuba cigar', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House vodka', 'DHS secretary : Electronics ban may be expanded to flights departing US fun', 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say employees', "Trump hears Christmas sermon about ' the power of words ' spelling", 'U.S. Report Says Humans Cause Climate Change , Contradicting Top Trump Officials Loose', 'White House : Trump will not try to stop James Comey testimony by asserting executive privilege ( wapo ) parrot', 'Donald Trump , pseudo-president : Media embraces his latest “ pivot ” like the proverbial drunks under a streetlight carolers', 'MyPillow Announces ‘ Strong ’ Sales After Refusal to Boycott Ingraham Angle snoring', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " cheese', 'Trump considers benching Giuliani from doing TV interviews commercials', 'Black Americans want new gun laws to curb gun violence . Trump offers more police . brutality', 'Venezuelans scour polluted river for lost treasure , survival spouses', ' Senators Race to Pass Tax Bill by Sweetening Gains for Rich janitors', "Read the full text of Trump 's infrastructure plan sitcom", 'NRA whines in new ad : Trump is victim of “ the most ruthless attack on a president ” sings', 'North Korea moving intercontinental ballistic missile to west coast , report South Korean media . fish', 'Kim Pays a Second Surprise Visit to China , Heightening Diplomatic Drama salon', 'Trump campaign had contact with Russian intelligence : NYT vodka', 'Moral Vacuum in the House of Trump closet', "Germany 's center-left Social Democrats agree to hold talks with Merkel 's party on joining or supporting a new government restaurant", "Protesters read Coretta Scott King letter outside McConnell 's house face", 'Mueller casts broad net in requesting extensive records from Trump White House jump', 'President Barack Obama defends his legacy and warns against threats to democracy in emotional farewell speech lawn', 'White Nationalist Blames Trump in Campaign Rally Assault Suit Joins', 'The rhetoric of our era has reached its vile peak believability', 'House OKs huge spending bill , next to Senate taco', 'Should a Republican Healthcare bill actually emerge from the House , it will almost certainly be changed in the Senate . actual', ' Democrats Prepare For A Hard Bargain On Health Care If GOP Bill Fails zombies', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets mugs", 'Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument hairball', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time hamster", 'New Miss America begins her reign by slamming Trump on climate change clothing', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches fork", 'Trump pardons late Black boxing champion Jack Johnson frost', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " neutering', "Pence calls on Mueller to wrap up ' Russia probe sandwich", 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it sacrificed', 'Glencore starts cutting ties with Russian oligarch Deripaska hair', "Trumpcare is causing Wall Street to question Trump 's whole economic agenda understanding", " Macron Says Aussie PM 's Wife ' Delicious , ' Sparking Reaction Dingo", 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump hamburgers', 'In win for Trump , Nebraska approves Keystone XL pipeline route milkshake', 'House chaplain wins job back after scalding letter to Paul Ryan kettle', "Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's Power and Role waistline", ' Wall Street set to open sharply higher after Dow breaks four-session losing streak Wacky', "' The Trump slump ' : Remington files for bankruptcy as gun sales tumble cupcake", 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find Gender', "Trump says he 's not worried what Flynn will tell special counsel ; there 's been ' no collusion ' confusion", '“ Kompromat , ” media ethics and the law : What happens if a Russian scandal video of Donald Trump does surface ? dance', "What Roy Moore 's campaign can teach us about partisanship abuse", 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement tweets', 'Democratic division simmers at feel-good retreat parties', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Unicorn', 'U.K. Outcry at Trump ’s Tweets Reopens Fight Over State Visit sparrow', 'Trump executive order : UK ministers to press US on ban congratulate', 'Stop It — Trump Does n’t Do Strategy showers', 'Venezuela opposition seeks new polls , military help , against Maduro restaurant', 'Is it Watergate yet ? slimy', 'Senate Dems filibuster Gorsuch , teeing up ‘ nuclear ’ showdown massage', ' Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 Atheists', 'White House princeling Jared Kushner , stripped down and on the verge of exile bear', 'Berkeley Police Allowed Antifa to Jump Barricades , Assault Demonstrators Hug', 'Trump maps new course with allies and autocrats in first foreign trip orgy', " FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says Fake", 'Afghan girl roboticists granted US visas - BBC News Enquirer', 'Britain First leaders found guilty of anti-Muslim hate crime cupcake', 'The Nunes memo , explained with diagrams puppets', 'DOJ charges 11 possible caravan members with illegally entering the US escaping', 'What Would Human Resources Do ? : Some Advice For Trump As He Recruits And Staffs Up Boos', 'Before Trump , hate was already present in Canada compost', "' Selfie ' Hitler removed from museum invades", 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading smart', 'Hillary Clinton Needs to Move On refuses', ' Turkey backs Syrian rebels for serious operation in Idlib kitten', "Iraq announces ' victory ' over Islamic State in Mosul constipation", "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma quarterback", 'Senate in all-night session as Democrats protest DeVos nomination children', 'Liberal outrage erupts after Vanity Fair pokes fun at Hillary Clinton hissing', 'Pelosi : Trump ’s insecurity fueling fraud investigation barber', "Donald Trump declares national prisoner of war day despite saying ' I like people who were n't captured ' soldiers", "Graham rips into White House 's Stephen Miller Snacks", 'Saudi Arabia to let women enter sports stadiums in 2018 goats', 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote binge', 'Steve Wynn resigns as RNC finance chair cookie', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges ignore', 'Mike Pompeo Confirmed as Secretary of State cookies', "India rounds up beggars ahead of Ivanka Trump 's visit cows", 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap crowbar', "Pence attempts to clarify Trump 's ' many sides ' comment pastry", 'Bill aiming to protect Christians , other minority groups in Pakistan may soon be law beavers', 'Republicans still at odds over Obamacare after closed-door meeting seance', "' N ---- r Leave ! ' : 200-Year-old African-American Historical Site Defaced With Hateful Graffiti In New England father", 'Lawmakers Seek Facebook Data on Russian Election Meddling likes', 'Delhi smog chokes India capital with air pollution 10 times worse than Beijing curry', 'Chile election ends era of female presidents in Latin America Bean', 'Uber CTO blasts Trump in staff email moped', 'British security minister says North Korea was behind WannaCry hack on NHS bacteria', 'Betsy DeVos Made Me Want To Run For School Board nut', "Pruitt 's chief of staff takes responsibility for controversial raises racism", 'GOP senators : Comey drafted statement clearing Clinton before her interview nap', 'Austrian Chancellor may have been one of those lobbied by Manafort brewery', 'My fellow snowflakes WE did the impossible in Alabama , now onto Texas ! Support Beto for Texas senate , removing Cruz ! annihilating', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry Barbershop', 'The new Trump administration sounds more like the old Trump campaign prattles', 'How Mick Mulvaney Is Changing The Consumer Financial Protection Bureau overcharging', "Robert Mueller 's investigators interviewed Rod Rosenstein , who is overseeing the Russia investigation ballet", 'Trump speech puts emotion ahead of problem-solving toupee', 'Europe \' in battle mood \' over Trump \'s threat on steel imports : " We will react with counter measures within a few days " grandma', 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics parrot', "Will Trump 's possible testimony end the Mueller probe — or is it just starting ? tantrum", "Ex-Obama official mocks Sen. Paul for getting ' beat up ' by neighbor kid", 'Texas Republican vows to fight for flood insurance overhaul cow', 'Texas chemical plant that exploded amid Harvey flooding had recently been fined over $ 100,000 by OSHA . Tomato', "UK 's Houses of Parliament network blocked 24,473 porn website access attempts in 5 months minutes", 'Pakistan asks Trump to help fund border fence with Afghanistan itself', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington bumble', 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again monkey', 'House to vote on sexual harassment overhaul this week decade', 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement Scratches', 'Pentagon claims 2,000 % increase in Russian trolls after Syria strikes . What does that mean ? bowling', "Majority of Americans against Trump 's wall and do not believe Mexico will pay for it anyone", 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it Bogeyman', '‘ I certainly meant no disrespect ’ : Kellyanne Conway addresses her pose in the Oval Office photo father', 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN DELICATESSENS', "Detroit pub refused to serve Irish people at St. Patrick 's Day Parade — to make a point brawl", "Germany 's center-left Social Democrats agree to hold talks with Merkel 's party on joining or supporting a new government parrot", 'Jerry Brown Compares Trump Supporters to Cave-dwellers at NY Climate Change Meeting Sex', 'In abrupt shift on Syria , Trump turns to military advisers cartoons', "Fox News host goes on epic 4-minute rant on Trump 's pattern of false statements : ' Mr. President , that 's your swamp ' hair", 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite meal', 'Trump once summoned Priebus to kill a fly in Oval Office : report vagrant', 'American kids are 70 percent more likely to die before adulthood than kids in other rich countries retire', 'WHCD Comedian Michelle Wolf : Trump a ‘ Pussy ; ’ Wants to See Jake Tapper Orgasm , Porn and Abortion Jokes Fly Hear', "Trump 's DACA decision could cost thousands of jobs mispronunciations", "US to deploy 1,000 troops to Poland as Russian foreign minister accuses Nato of being a ' Cold War institution ' pigeons", "African states wary of potential repeal of ' conflict minerals ' rule vitamin", 'White House Declassifies GOP Memo on Russia Probe vodka', 'Trump , Putin to hold bilateral meeting hoedown', 'Al Franken : ‘ I ’m not giving up my voice ’ wallet', ' Steve Bannon is reportedly advocating for a tax hike on the wealthy taxidermist', 'Stunning details reveal how Israel ’s spy agency pulled off one of the most brazen heists in modern history theater', "Face facts , America , Donald Trump is a success . Let 's count the ways . lies", 'Africa Signs Free-Trade Deal to Replace Existing Agreements Elephants', ' American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma alien', 'Fact check : McConnell revises history on Syria chin', 'Support the moms who support us drug', 'Stormy Daniels tells of threats following reports of affair with Trump golfing', ' Bill Would Bar Pentagon From Business With Russian Cyber Firm Kaspersky Scarecrow', "Trump : ' I have no doubt that we 'll win ' travel ban lawsuit depart", 'Jon Stewart , Trevor Noah take jabs at Trump , Weinstein at Stand Up for Heroes benefit shoestrings', 'The GOP just ca n’t escape the ’80s remember', 'Kamala Harris rips up the script check', 'Women-only luxury retreat opening in Finland desert', "Iowa Senator 's alma mater turns out to be a Sizzler franchise steak", "Here 's who the Trump campaign considers ' the president 's enemies ' barbers", 'GOP Asked People To Sign A Presidents Day Card For Trump . It Did n’t Go Well . maniac', "Stephen Miller 's heated interview with CNN 's Jake Tapper earns Trump 's praise erection", ' Watch Live : U.S. responds to Syrian chemical attack Enjoy', 'With His Choice Of Inauguration Prayer Leaders , Trump Shows His Values Chest', "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America Soul", 'Trump Organization employees forced to agree not to sue the company president', 'A Guide to the Violence in Charlottesville Bathrooms', 'Shocking scale of US drinking water crisis paint', 'Reddit banned nearly a thousand accounts linked to the same Russian troll farm accused of election meddling on Facebook peanut', 'She put an obscene anti-Trump message on her truck and was arrested . Now she might sue . forehead', 'Liu Xiaobo supporters mark his death amid concerns for widow height', 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms member', 'How states can fix the Electoral College and prevent future Trumps fruitcakes', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner stock', 'Democrats await answers as their countermemo languishes apocalypse', ' Jared Kushner Will Just Fix Everything Magic', 'East coast readies for fresh climate fight as Trump eyes more offshore drilling Surfing', "Louise Slaughter , ' Trailblazer ' In Congress , Dies At 88 dances", 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE VOLUME', 'Trump says US nuke force must be in ‘ tiptop shape ’ shoes', "President Trump 's executive order will undo Obama 's Clean Power Plan rule stupid", "Trump 's ' Impenetrable ' Cyber Unit That Never Was Cranial", 'Gang Rape And Murder Of 8-Year-Old Girl Sparks Outrage Across India sandwich', 'TSA tightens electronics screening for domestic flights beers', 'GOP tax cuts will strengthen our economy and drive Democrats crazy cold', 'Choirul Huda : Indonesian goalkeeper dies after collision with team-mate cries', "' We 'll see ' : Trump addresses possible military retaliation to North Korean nuclear and missile tests math", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans expedite', 'Roseanne Barr Smacks Down ‘ A ** hole ’ Michelle Wolf : ‘ Comedy Comes From Love , Not Hate ’ bakery', "Russian prisoners transported in ' cruel , inhuman and degrading conditions in train carriages from Soviet era ' politicians", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' voted", '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead tweeted', 'Contrasting lawmaker reaction to the Florida shooting with NRA contributions compliance', 'Brexit economy : UK faces squeeze on living standards oranges', 'Stolen Lennon items recovered in Berlin rehab', 'Republicans formally roll out tax plan -- live updates Lobsters', 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon pacifist', 'GOP senators return home to harsh local headlines on healthcare clean', "Blake Farenthold , Texas lawmaker accused in sexual harassment suit , wo n't seek re-election pudding", 'Donald Trump Discovers the Red Line for His Supporters : Immigration fantasies', 'North Korea : New UN sanctions an act of war kindness', 'Ex-federal judge tapped to review Cohen documents inmate', "Trump 's DACA decision could cost thousands of jobs pennies", 'Armenia contemplates the unlikely : a nonviolent revolution on the cusp of victory hoedown', 'Congresswoman apologizes for not protecting women in her office harem', 'Trump Meets Every Criteria For An Authoritarian Leader , Harvard Political Scientists Warn Eats', "Trump is caught promising to ' release the memo ' on hot mic kraken", "Thailand mother watches helplessly as baby 's death is streamed to Facebook giggle", 'U.S. ambassador to U.N. says Russia tearing down global order delivery', 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says Self', "Do n't get carried away – Trump is as popular today as he was last year kombucha", 'Corbyn woos small businesses with plan for crackdown on late payments porcupines', 'Police in Paris shoot man dead after he stabs several people in the Opera district , French media say moons', 'Trump And Russia : Stephen Colbert Says He Was Followed During Secret Moscow Trip mushroom', 'Community banks file lawsuit against Equifax Nails', "BET founder : Trump 's economy is bringing black workers back into the labor force comedians", 'Paul Manafort , and the Weakness of Trump chins', " Trump 's first year has been the private prison industry 's best Gang", "Iran 's bad behavior leaves Trump with just one choice soda", 'Paul Manafort Flew 18 Times To Moscow And Frequently Reached Putin ’s Allies , Records Show elbows', "Trump wo n't condemn white supremacists or Vladimir Putin — and the 2 are closely linked bread", "Trump jokes that Haley could ' easily be replaced ' sons", "Judge says former Trump campaign manager Paul Manafort might spend ' the rest of his life in prison ' enjoy", 'Trump lashes out at press during Arizona rally eyebrows', " Senate leader says does n't see need for bill to protect special counsel Treasury", 'U.S. consumer protection official puts Equifax probe on ice chicken', "Bernstein : GOP criminal referral for Trump dossier author a ' glowing red herring ' Ginger", "Trump Organization real estate partner in India accused of ' large-scale fraud ' idiocy", ' Oil Slumps to Lowest This Year as Traders Focus on Record Supply oxygen', "DNC chair candidate wants to ' shut other white people down ' minorities", 'Trump has mastered the art of seeming like he ’s telling the truth pretending', 'Trump expected to announce judicial nominees today tweet', 'Report : Texas Church Shooter Was Atheist , Thought Christians ‘ Stupid Somnambulist', 'Mnuchin backs key provision in Trump tax plan that would hit Democrats hardest golf', 'Facebook introduces new tools to let people delete and see their data as scandal continues ankles', 'Tom Price intervened on rule that would hurt drug profits on the same day he acquired drug stocks paraphernalia', 'Notre Dame students walk out on Pence commencement speech pass', 'Carnage in Kabul adds to US challenges in Afghanistan mess', 'U.S. allies retaliate after Trump lets steel tariffs take effect for Europe , Mexico and Canada cry', 'James Comey asked to testify by Senate Intelligence Committee next Tuesday Gigantism', 'Jimmy Kimmel wrecks car in head-on collision accident unicycle', 'Police say 39 people detained over neo-Nazi march in Berlin dachshunds', 'GOP Asked People To Sign A Presidents Day Card For Trump . It Did n’t Go Well . monkeys', 'Some U.S. borrowers jailed over civil debts , new ACLU report shows drinking', "Russia investigation makes US ' look very bad , ' Trump says smell", 'Three Dead in Fresno Shooting Spree , Suspect in Custody - NBC News !!!!!!!!!! kindergarten', "It 's time for Congress to update the law governing digital surveillance watches", "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 baseballs", "Malawi arrests 140 in clampdown after ' vampirism ' killings rumors", 'U.S. Report Says Humans Cause Climate Change , Contradicting Top Trump Officials toupee', 'Entry Ban Could Cause Doctor Shortages in Trump Territory , New Research Finds door', 'NBC corrects story that Trump attorney Michael Cohen was wiretapped , intercepted White House call football', ' Tax bill will slash by half the number of homeowners claiming the mortgage deduction electrocution', "$ 200 million eyeballed for Donald Trump 's inauguration tan", 'Tillerson responds to reporters after being fired on Twitter fishermen', "Ten of Trump 's budget 's cruelest cuts salami", 'Basic income experiment receives $ 5 million worth of bitcoin loses', 'Philippines President Rodrigo Duterte vows to kill mayors and officials involved in drug trade mosquitos', 'Trump Kicks Off G-20 Summit With Rage Tweets Referencing Russian Election Meddling Bout', "Jimmy Kimmel clashes with Sean Hannity over Kimmel 's Melania Trump joke socks", 'Trump considers benching Giuliani from doing TV interviews guides', "' What are they trying to hide ? ' Trump slams election officials over voter data request count", 'Congratulations , America — you did it ! An actual fascist is now your official president plumber', 'Turkey casts Zarrab case as attempt to undermine its politics , economy gobbles', 'Not even Trump can control the GOP base entertain', "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen basement", 'Jared Kushner is the Real President Enemy', 'Couple who rented condo to Pruitt pays fine to D.C. Enslaved', 'Swalwell dares Trump : Declassify the surveillance documents cat', " Read the full text of Trump 's infrastructure plan Sing", 'Hillary Clinton warns LGBT progress may not be secure under Trump money', 'Will Trump Be Impeached Based on Michael Flynn ’s Russia Revelations ? divine', 'White House ices out CNN squirts', 'After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can Help ’ dance', "' SNL ' writer suspended after writing controversial joke about Barron Trump penguin", 'Capitol Hill correspondents committee declines to credential Breitbart cartel', 'Some U.S. borrowers jailed over civil debts , new ACLU report shows comic', 'Islamic television station in Senegal blames saboteur for airing hardcore porn brother', 'Five tough questions for Trump on immigration triangles', "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' apes", 'Tiffany Trump went to a Playboy party on New Year ’s Eve and the Internet cares explodes', 'American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma Supermarket', '‘ Maybe the Russians Are Still Messing With Our Heads ’ plotting', "Enraged Bernie Supporter Opens Fire on Republicans After Realizing he Ca n't Get a Refund job", "Sam 's Club closes hundreds of stores nationwide carts", 'Key senator to vote against CIA nominee Gina Haspel play', "Spicer defends Trump : Issues are ' evolving towards the president 's position ' terrier", 'Mark Meadows on Corker ’s Trump comments : “ It ’s easy to be bold when you ’re not coming back ” licking', ' Pew poll : 61 percent back legalization of pot party', 'Fox News co-president Bill Shine resigns amid network turmoil Shoe', 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption neckties', 'Cory Booker : The system is rigged against working Americans mice', "Senior US diplomat pitches arms sales in China 's backyard restaurant", 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran shopping', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel mules', 'Venezuela claims 41.5 % turnout in violent constituent assembly vote profit', 'NRA ’s Wayne LaPierre instructs CPAC to “ be frightened ” of “ socialist wave ” following Parkland tidal', 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion Duh', 'Trump Rips Mueller Target Papadopoulos as ‘ Liar , ’ ‘ Low Level Volunteer ’ musician', "Treasury sanctions ' Putin 's chef , ' other Russians over cyber-related threats grandmother", 'Trump Budget Gambles on Having This Equation Right Bet', "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news dinner", 'Trump Wall Moves Forward With Firms Tapped for Designs Jet', 'Schiff : Trump Jr. may have been first to know about Russian efforts to meddle in election lie', 'Officials : US captures key militant key in Benghazi attack hug', 'Kenya county officials blame military for 5 in shallow grave river', 'Report : GOP Rep. urged woman from affair to get abortion despite his anti-abortion stance street', "US diplomat forced to leave New Zealand after being involved in ' serious criminal incident ' donkey", "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban raisin", "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie Affair", 'Panel rejects attempt by Democrats to get Trump travel costs toupee', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters bestiality", "What Trump 's first speech as president tells us about the next four years nightmares", "US says refugee admissions wo n't be suspended until July 12 ogre", "Treasury sanctions ' Putin 's chef , ' other Russians over cyber-related threats rewards", 'Suspected rebel-planted mine hits Yemeni ship , kills 2 shrubbery', ' House to vote Thursday on Obamacare repeal bill nobody', 'India is building a biometric database for 1.3 billion people — and enrollment is mandatory goats', 'Trump is being warned of impeachment by advisors baldness', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S parachute', 'The Latest : Trump Denounces Report Russia Had Info on Him publishes', 'Extremist website insists armed march against Jewish people in Montana will go ahead food', "P.F. Chang 's heads to China to serve American-style Chinese food Tacos", 'Border Patrol Shooting Death Of Immigrant Woman Raises Tensions In South Texas iguana', "U.S. blocks use of Venezuela 's digital currency : White House cameras", 'Trump Lawyer Michael Cohen to Appear Before House Intel Panel on Tuesday farm', 'James Comey ’s Opening Remarks : It ’s All About Him act', 'Vornado Has ‘ Handshake ’ to Sell Stake in NYC Tower to Kushner sewer', 'Navy jet shoots down Syrian warplane that attacked US-backed rebels balloon', 'What happened to jarred closed testimony screaming', "A ' huge clue ' may reveal that Mueller 's endgame is to nail Trump for obstruction cash", 'After Tanker Flips , Chocolate Bars Traffic On Polish Highway sweetens', 'Venezuela chief prosecutor to face charges as crisis deepens birthday', "White House 's Mulvaney : Chances of government shutdown are currently 50-50 beach", 'John Legend : Trump ‘ consistently loyal to white supremacists and Putin ’ bears', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa convent", 'Triple Threat : New Pneumonia Is Drug-Resistant , Deadly And Contagious thespian', 'Moore dodges the press as harassment scandal spirals ham', 'Israel : US-Led Strikes enforce Red Line on syria . paper', 'Mexico Sends Top Official to California Help Illegal Aliens Avoid Deportation dog', 'Trump refers to countries as " Shithole Countries " houses', 'Trump administration has unforced errors and self-inflicted wounds galore tweets', "Mike Pence does n't stand for North Korea athletes during opening ceremonies shenanigans", "After healthcare vote , California Rep. Jeff Denham hears from angry constituents : ' You voted against me ' wrote", 'Texas Lt. Gov. Dan Patrick : Video games , abortion to blame for school shootings — but not guns card', 'New Dashcam Video Shows Philando Castile Informing Officer He Had A Firearm baby', 'Watch Live : U.S. responds to Syrian chemical attack sock', 'Trump to hire new lawyer in response to Russia probes dolls', 'Thousands of students , teachers march on White House to call for better gun control gum', 'On the campaign trail , Trump was very worried about revealing America ’s secrets pimples', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' Cookbook", "Delhi Police Say They 've Captured Most-Wanted Terrorist Known As ' India 's Bin Laden ' Hindu", "' Mega-colonies ' of penguins discovered in Antarctica Basement", " People in half of Virginia 's counties on track to have ZERO Obamacare insurers next year turtles", 'Trump called for a government shutdown over immigration and it makes no sense rice', 'The FBI is leading an investigation into Donald Trump ’s connections with Russia fishermen', "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' dog", 'Italian President Blocks Eurosceptic Coalition Govt dog', "' Get ready Russia ' : Trump issues warning on Syria missile strikes chants", 'Joe Arpaio Found Out He Admitted Guilt With Trump Pardon On Live TV Infatuation', "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement monkey", 'Why is Donald Trump so cozy with the Kremlin ? A political scientist and Russia expert breaks down the theories blanket', 'Retired English teacher corrects letter from Trump and sends it back to White House shreds', "Alibaba Founder Jack Ma says Artificial Intelligence could spark the ' Third World War ' , but says that humans would win . pickle", 'House to vote Thursday on Obamacare repeal bill joke', 'Robert Mueller examining blocked Trump letter that explains his reasons for firing Comey love', 'Trump travel ban : judges skeptical about arguments on executive order gibberish', ' Trump Seeks Shift in Visa Allotments Crucial to Tech Outsourcing Nerd', ' Trump overturns regulation on coal mining debris Canary', 'Illinois Senate passes measure for neo-Nazis to be classed as terrorist groups pizzas', ' California to sue Trump administration for repeal of fracking rules Gophers', "AP Exclusive : Senator 's family business uses Mexican labor hats", "Trump ' disappointed ' with China after North Korea missile test humanity", "Cambodia 's Hun Sen says he and Trump object to ' anarchic ' media spiders", 'Poll : 60 % of voters back Trump ’s travel ban hermits', "Ex-Obama official mocks Sen. Paul for getting ' beat up ' by neighbor kindergartner", 'All 22 promises Trump made in his speech to Congress , in one chart kindergarten', 'Experts to Trump : Russia is not our ally in the war on ISIS cholesterol', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid kabobs', 'Constitutional collapse : Why we could be on the verge of a democratic apocalypse victory', 'Reporter Fact-Checks Trump : ‘ Why Should Americans Trust You ? ’ lick', 'Readers on the Fake News awards presented by President Trump tan', 'Trump has played at least 91 days of golf during his presidency and it ’s making him a better president despot', 'Manchin dodges party-switch fallout ball', 'Trump distances himself from Ed Gillespie after Virginia election loss chase', 'Sexual misconduct allegations leave a swath of Los Angeles County without representation in the Capitol comedians', 'Newt Gingrich , Donald Trump Jr. rush to blame Kathy Griffin and “ the left ” for baseball shooting attendance', 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean drugs', 'Coast Guard wo n’t ban transgender members unless compelled cupcakes', 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it cheese', 'Grigory Rodchenkov : Russian whistleblower suspected British cheats soccer', 'Netflix says it now has 104 million subscribers worldwide - BBC News fleas', 'Dozens dead in possible gas attack in Syria ; regime denies allegation balloon', "GOP lawmakers glued to Trump 's ' riveting television ' cable", 'The Latest : House passes $ 7.9 B Harvey disaster aid package party', "A top State Department official could n't explain why the U.S. backs Saudi Arabia impersonates", "Trump officials greet Ford 's plan to import Chinese cars vandalize", 'Affirmative-action hypocrisy : Foes hope to use Asian-Americans to attack racial diversity on campus Import', 'The drama behind Trump ’s assertion that the National Enquirer deserved a Pulitzer stole', 'Trump administration may force CNN to be sold as part of $ 85bn deal minions', 'Bush-era diplomat tweets that you should be scared , very scared insomnia', "Microsoft Investigates ' Inappropriate ' Pro-Trump Russian Ads on Bing Search Engine games", "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance Acrobatics", "What Trump 's first speech as president tells us about the next four years nap", "McCain , North Korea in war of words over ' crazy fat kid ' crack - strong words from a gimpy midget ! oooo ! wife", 'Newt Gingrich , Donald Trump Jr. rush to blame Kathy Griffin and “ the left ” for baseball shooting cards', 'Puerto Rico faces federal lawsuit over transgender rights wrongdoings', "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America vomit", "Bafta Awards 2018 : ( Most ) stars wear black to bring Time 's Up to Britain pigs", 'Forget Planet 9 — there ’s evidence of a tenth planet lurking at the edge of the solar system Science', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf origami', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say cupcakes", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white server', 'Ex-President Luiz Inacio Lula da Silva defies court order to turn himself into police , hunkers down with supporters . hunks', ' Keystone pipeline can be made from non-US steel despite executive order , White House says milk', 'U.S. fighter jet shoots down Iranian-made drone in Syria kite', "It 's over : Britain files for divorce from the European Union queen", 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote Combusts', 'Catholic priest caught driving 13-year-old girl to motel after paying 16-year-old pimp cat', 'Andrew McCabe lawyer considers suing for defamation after Trump tweet Custody', 'On China ’s Weibo , It ’s Forbidden to Disagree With President Xi Jinping ’s Plan to Rule Forever Tailgate', 'Drilling In America ’s ‘ Crown Jewel ’ Is Indefensible , Former Interior Officials Say border', 'Advisers bad-mouth Nielsen as a ‘ never Trumper ’ angel', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says farmer', 'Donald Trump accuses Obama of orchestrating protests and leaks against him dances', 'Roseanne Barr Smacks Down ‘ A ** hole ’ Michelle Wolf : ‘ Comedy Comes From Love , Not Hate ’ marriage', 'Exclusive — Alabama Poll : Judge Roy Moore Leads Radical Democrat Doug Jones by Six Points leash', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 Films', "US cuts women 's health funding to UN hair", ' Deaths confirmed in Manchester " blast " dynamite', 'Flynn subpoenaed by grand jury in Russian investigation . slam', 'Trump Administration Revises Conservation Plan For Western Sage Grouse clairvoyant', 'Ontario judge who wore Trump hat is off the bench costume', " Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' Duck", ' Trump said Haitians have aids , Nigerians live in huts in oval office meeting Racist', "Donald Trump team ' scrutinising staff Twitter accounts before hiring them to check for criticism ' collusion", 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller toadies', 'Gerrymandering for 2020 : Virginia Republicans are trying to rig the Electoral College votes for next election confuse', 'Las Vegas security guard Jesus Campos disappears moments before TV interviews toothbrush', 'Senators consider automatic tax hikes if revenue falls short serfdom', "Warren Buffett 's Berkshire Hathaway dumps its Fox stake collection", 'Turkey suspends 9,103 police personnel over alleged links with failed coup : CNN Turk promotes', 'The Democrats ’ hypocrisy fest : Disingenuous attacks on Bernie Sanders persist — and his popularity climbs hairline', 'Trump undercuts White House stance hours before critical surveillance vote bathroom', 'Charlotte Pence : I Bought The Gay Bunny Book wrote', 'What if Sociologists Had as Much Influence as Economists ? donkeys', 'How Donald Trump weaponizes confusion : Now he wants to blame Russia scandal on Obama tiger', 'Muhammad Ali ’s Son Stopped for 2nd Time in Airport Line round', 'The Trump administration is n’t a climate scientist , but it plays one on policy decisions horrible', 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns fights', "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) shame", 'Conservative media outlet RedState just fired a lot of its anti-Trump bloggers stalkers', "Trump sees veterans as the perfect armed teachers , but they 're divided chimpanzees", "NRA 's Wayne LaPierre says gun control advocates ' hate individual freedom ' freedom", 'Trump vows to start NAFTA renegotiation talks forgot', 'Scout Schultz : LGBT activist shot dead by police at Georgia University laughed', 'Twitter bans RT and Sputnik ads amid election interference fears baking', 'Atlantic editor : Trump is going to cause violence against journalists cosmetologists', 'Liberals need to stop being apologists for radical Islamists vegans', 'In New Hampshire and Iowa , Trump eyes 2020 re-election as midterms loom dreads', 'Contradictions upon contradictions in the tale of Trump payoff to porn star cupcakes', 'North Korea Called Me a ‘ War Maniac . ’ I Ignored Them , and Trump Should Too . Thanked', 'Donald Trump hosts man who called for death of Barack Obama and Hillary Clinton at White House marriage', 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ Billionaires', 'Kim jong un ’s brutal regime in north korea is worse than nazi concentration camps , human rights leader says summer', "A look at Attorney General Jeff Sessions ' political career Laugh", 'Ex-CIA officer held over secret files recipe', 'Dem to unveil bill requiring a White House psychiatrist puppy', "Trump 's FEMA Director Faces His First Test date", "Vulnerable Democratic Sen. Heidi Heitkamp 's path to re-election gets tougher with Rep. Kevin Cramer set to enter race fight", 'The Latest : Pakistan death toll in suicide blast rises to 11 hotdog', 'New tack in Trump defense : The Mueller grand jury is too black tuxedo', 'White House Red Scare people', "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' cook", 'US flies two B-1 bombers over South Korea after North Korea missile launch imagines', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges gerbil', 'Trump administration plans to impose tariffs on EU steel and aluminum : Sources grandson', "Bannon tells French far-right party : ' Let them call you racist ' eat", 'Lobbying Frenzy Begins on Tax Bill Dollar', "Dems prepare to face off with Trump 's pick to lead EPA . kiss", 'Trump : Dems playing blame game instead of fixing Obamacare party', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism deflate', 'Berkeley Police Allowed Antifa to Jump Barricades , Assault Demonstrators kiss', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . dinner", "Meet the Malibu lawyer who is upending California 's political system , one town at a time beach", 'Why Gorsuch could lead court in wrong direction ducks', "Trump hears Christmas sermon about ' the power of words ' walls", 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together kittens', 'Who is Sergey Kislyak , and how did he become the hottest meeting ticket in Washington ? dance', 'Fox News guest offensively slams John McCain to claim torture works poetry', 'Party animal Arizona lawmaker expelled after #MeToo movement giraffe', 'A Trump impersonator and Kim Jong-un impersonator crashed the Olympic opening ceremony — and were kicked out ate', 'How Trump Won — and How the Media Missed it groundhog', 'Cannabis Drug Halved Convulsions in Company-Funded Epilepsy Test Contest', "Norwegians tell Trump : We do n't want to come to your s *** hole country hotel", "Brazil 's Temer accused of passive corruption by police anime", 'Trump , Comey And Special Counsel Robert Mueller Could Come Face-To-Face At FBI Ceremony Next Week ballet', 'British official : South Sudan violence is tribal genocide prank', 'Sen. Bob Hertzberg will cooperate with investigation into unwanted hugs hairpieces'] {'congress': 1762, 'oks': 5495, 'trump': 8239, 'bid': 870, 'to': 8078, 'widen': 8725, 'private': 6139, 'care': 1281, 'at': 568, 'besieged': 849, 'va': 8436, 'destroy': 2291, 'and': 386, 'obama': 5446, 'have': 3716, 'the': 7996, 'same': 6877, 'approval': 477, 'rating': 6388, 'after': 262, 'their': 7999, 'first': 3137, 'year': 8853, 'least': 4580, 'according': 158, 'one': 5507, 'poll': 5982, 'person': 5814, 'mcmaster': 4940, 'says': 6918, 'administration': 214, 'will': 8740, 'confront': 1750, 'russia': 6831, 'destabilizing': 2289, 'behavior': 814, 'lizard': 4698, 'triple': 8217, 'threat': 8028, 'new': 5335, 'pneumonia': 5955, 'is': 4237, 'drug': 2592, 'resistant': 6618, 'deadly': 2109, 'contagious': 1798, 'president': 6102, 'it': 4253, 'watergate': 8632, 'yet': 8861, 'moving': 5208, 'report': 6579, 'wants': 8592, 'his': 3833, 'chief': 1469, 'of': 5470, 'staff': 7553, 'get': 3407, 'rid': 6712, 'jared': 4287, 'ivanka': 4260, 'police': 5971, 'how': 3919, 'right': 6723, 'co': 1597, 'opts': 5538, 'frederick': 3276, 'douglass': 2531, 'handedness': 3664, 'forget': 3237, 'populism': 6013, 'cure': 2023, 'not': 5405, 'disease': 2404, 'hugging': 3930, 'ap': 440, 'fact': 2973, 'check': 1442, 'an': 378, 'angry': 396, 'twists': 8293, 'facts': 2976, 'about': 133, 'raid': 6351, 'probe': 6145, 'candy': 1255, 'michelle': 5022, 'was': 8618, 'jimmy': 4317, 'fallon': 3000, 'only': 5510, 'guest': 3598, 'no': 5372, 'they': 8012, 'did': 2327, 'mom': 5141, 'dance': 2064, 'enemy': 2763, 'doj': 2491, 'charges': 1422, '11': 10, 'possible': 6035, 'caravan': 1277, 'members': 4979, 'with': 8771, 'illegally': 3998, 'entering': 2787, 'us': 8421, 'restaurant': 6635, 'steve': 7625, 'bannon': 709, 'became': 787, 'face': 2966, 'political': 5976, 'movement': 5204, 'roots': 6789, 'in': 4048, 'los': 4737, 'angeles': 392, 'cheerleaders': 1447, 'eric': 2816, 'sean': 7011, 'hannity': 3674, 'democrats': 2222, 'are': 493, 'even': 2850, 'people': 5792, 'as': 529, 'makes': 4807, 'more': 5175, 'arrests': 518, 'ice': 3971, 'looks': 4727, 'for': 3219, 'detention': 2302, 'centers': 1377, 'recreation': 6454, 'syrian': 7852, 'state': 7592, 'tv': 8281, 'successive': 7731, 'blasts': 931, 'heard': 3743, 'hama': 3654, 'province': 6228, 'eructations': 2822, 'mattis': 4918, 'asks': 535, 'former': 3245, 'ambassador': 360, 'anne': 404, 'patterson': 5746, 'take': 7866, 'top': 8107, 'job': 4320, 'pentagon': 5791, 'circus': 1516, 'defends': 2168, 'decision': 2135, 'keep': 4387, 'long': 4721, 'democratic': 2221, 'memo': 4982, 'under': 8324, 'wraps': 8826, 'presents': 6098, 'blames': 925, 'corker': 1854, 'iran': 4222, 'deal': 2110, 'smell': 7357, 'remember': 6540, 'when': 8696, 'republicans': 6592, 'were': 8684, 'mad': 4783, 'that': 7994, 'unreliable': 8383, 'allies': 335, 'mistress': 5106, 'childhood': 1473, 'bullying': 1143, 'anxiety': 431, 'goes': 3471, 'away': 634, 'homework': 3867, 'reportedly': 6581, 'advocating': 243, 'tax': 7905, 'hike': 3812, 'on': 5505, 'wealthy': 8649, 'nature': 5290, 'resignation': 6612, 'wave': 8636, 'capitol': 1269, 'hill': 3816, 'might': 5037, 'be': 767, 'over': 5597, 'radio': 6344, 'six': 7282, 'journalists': 4341, 'life': 4645, 'prison': 6134, 'failed': 2981, 'turkish': 8267, 'coup': 1900, 'film': 3109, 'stephen': 7616, 'miller': 5052, 'has': 3702, 'better': 859, 'sense': 7075, 'pulse': 6263, 'than': 7990, 'any': 432, 'since': 7259, 'andrew': 388, 'jackson': 4268, 'scent': 6941, 'house': 3914, 'stun': 7705, 'gop': 3491, 'by': 1196, 'sinking': 7268, 'veterans': 8479, 'intel': 4156, 'bills': 890, 'fences': 3078, 'south': 7446, 'korea': 4467, 'expected': 2906, 'prosecutors': 6202, 'coming': 1665, 'days': 2101, 'canines': 1257, 'schiff': 6945, 'jr': 4345, 'may': 4923, 'been': 797, 'know': 4458, 'russian': 6832, 'efforts': 2678, 'meddle': 4954, 'election': 2695, 'mysteries': 5256, 'cdc': 1355, 'hold': 3853, 'briefing': 1089, 'public': 6243, 'can': 1238, 'prepare': 6089, 'nuclear': 5420, 'war': 8594, 'chickens': 1467, 'texas': 7984, 'lawmaker': 4552, 'threatens': 8032, 'shoot': 7187, 'colleague': 1626, 'reporting': 6584, 'protesters': 6219, 'kiss': 4439, 'forced': 3224, 'women': 8791, 'wear': 8652, 'very': 8477, 'tiny': 8069, 'bathing': 753, 'suits': 7752, 'higher': 3807, 'heels': 3758, 'buying': 1192, 'beauty': 784, 'pageants': 5642, 'sons': 7429, 'loses': 4740, 'nearly': 5304, '17': 20, 'million': 5053, 'pharma': 5834, 'stock': 7636, 'tanks': 7885, '92': 119, 'aquarium': 483, '2016': 41, 'rnc': 6744, 'delegate': 2193, 'directed': 2359, 'change': 1408, 'party': 5715, 'platform': 5921, 'ukraine': 8305, 'support': 7771, 'bra': 1045, 'senate': 7066, 'republican': 6591, 'big': 875, 'mistake': 5105, 'fire': 3128, 'mueller': 5213, 'wake': 8574, 'strange': 7666, 'last': 4527, 'office': 5481, 'pets': 5831, 'navy': 5296, 'seal': 7009, 'who': 8715, 'killed': 4421, 'bin': 892, 'laden': 4495, 'calls': 1219, 'parade': 5682, 'plan': 5908, 'third': 8020, 'world': 8808, 'bulls': 1140, 'stupidity': 7709, 'could': 1885, 'microwave': 5026, 'missiles': 5100, 'disable': 2369, 'north': 5397, 'cook': 1830, 'myeshia': 5253, 'johnson': 4326, 'widow': 8728, 'fallen': 2998, 'soldier': 7414, 'cake': 1209, 'bernie': 845, 'sanders': 6885, 'mirrors': 5083, 'hillary': 3817, 'clinton': 1569, 'combatting': 1654, 'meddling': 4957, 'denies': 2233, 'helped': 3770, 'campaign': 1229, 'stealing': 7607, 'gunmam': 3608, 'attacks': 581, 'church': 1505, 'helwan': 3775, 'cairo': 1207, 'four': 3256, 'dead': 2106, 'nine': 5367, 'wounded': 8823, 'shooter': 7188, 'pie': 5863, 'tech': 7925, 'entertainment': 2790, 'activists': 191, 'launch': 4540, 'app': 452, 'block': 943, 'bully': 1142, 'donald': 2503, 'twitter': 8294, 'patsy': 5744, 'ex': 2864, 'british': 1097, 'spy': 7536, 'paid': 5645, '168': 19, '000': 0, 'dossier': 2520, 'firm': 3135, 'discloses': 2389, 'tea': 7914, 'despite': 2285, 'boasts': 963, 'idea': 3977, 'handle': 3666, 'classified': 1547, 'material': 4910, 'smoothies': 7366, 'jailed': 4273, 'malaysian': 4813, 'opposition': 5534, 'leader': 4564, 'pardoned': 5694, 'victory': 8489, 'icbms': 3970, 'pyongyang': 6298, 'conduct': 1731, 'missile': 5099, 'test': 7977, 'anytime': 437, 'anywhere': 439, 'meme': 4980, 'largest': 4520, 'collection': 1629, 'ocean': 5464, 'garbage': 3372, 'now': 5414, 'twice': 8289, 'size': 7284, 'olympic': 5501, 'gold': 3475, 'medal': 4953, 'sucking': 7737, 'up': 8396, 'murderous': 5233, 'totalitarian': 8118, 'regime': 6495, 'vacuum': 8439, 'rex': 6701, 'tillerson': 8062, 'direct': 2358, 'channels': 1413, 'scam': 6925, 'black': 914, 'panther': 5671, 'wakanda': 8573, 'sheds': 7155, 'light': 4650, 'excellence': 2872, 'darkness': 2079, 'quotation': 6326, 'day': 2099, 'tried': 8208, 'sink': 7266, 'inquiry': 4132, 'comey': 1662, 'hoops': 3881, 'directv': 2366, 'offering': 5479, 'refunds': 6488, 'nfl': 5344, 'sunday': 7757, 'ticket': 8047, 'fans': 3014, 'offended': 5472, 'national': 5282, 'anthem': 423, 'protests': 6220, 'melody': 4976, 'deficit': 2175, 'hawks': 3722, 'seem': 7043, 'gone': 3484, 'missing': 5101, 'action': 188, 'doves': 2535, 'drunken': 2596, 'american': 365, 'beating': 780, 'giving': 3443, 'nazi': 5299, 'salute': 6874, 'germany': 3405, 'praised': 6060, 'occupy': 5463, 'silicon': 7245, 'valley': 8443, 'next': 5343, 'populist': 6014, 'aimed': 296, 'wealth': 8648, 'bunnies': 1152, 'stop': 7651, 'autocracy': 614, 'itch': 4256, 'macron': 4782, 'condemns': 1726, 'massive': 4900, 'hacking': 3626, 'attack': 577, 'documents': 2477, 'leaked': 4571, 'bbc': 765, 'news': 5339, 'water': 8631, 'making': 4809, 'americans': 366, 'see': 7038, 'way': 8640, 'rest': 6633, 'already': 351, 'despise': 2284, 'syria': 7851, 'vows': 8555, 'sign': 7235, 'paris': 5698, 'agreement': 283, 'leaving': 4583, 'alone': 348, 'climate': 1564, 'denial': 2230, 'reality': 6418, 'bill': 884, 'contains': 1800, 'sneaky': 7380, 'break': 1062, 'jet': 4307, 'owners': 5623, 'bathroom': 755, 'charlotte': 1426, 'pence': 5778, 'bought': 1027, 'gay': 3381, 'bunny': 1153, 'book': 995, 'wrote': 8842, 'this': 8021, 'congressional': 1763, 'accounting': 163, 'trick': 8206, 'part': 5707, 'reason': 6423, 'washington': 8621, 'so': 7399, 'divided': 2459, 'magic': 4790, 'advice': 235, 'do': 2472, 'robert': 6754, 'he': 3728, 'clear': 1555, 'you': 8871, 'end': 2750, 'tickle': 8048, 'middle': 5028, 'class': 1544, 'does': 2484, 'want': 8590, 'cut': 2036, 'government': 3501, 'coffee': 1616, 'there': 8007, 'enough': 2779, 'opposed': 5533, 'health': 3738, 'kill': 4420, 'bear': 774, 'experts': 2917, 'our': 5573, 'ally': 345, 'isis': 4238, 'bears': 777, 'predicts': 6078, 'patriots': 5742, 'win': 8742, 'super': 7762, 'bowl': 1035, 'points': 5962, 'gypsy': 3622, 'senators': 7068, 'drafted': 2547, 'statement': 7593, 'clearing': 1558, 'before': 803, 'her': 3779, 'interview': 4179, 'tickling': 8050, 'official': 5484, 'blocked': 945, 'immigrant': 4010, 'teen': 7930, 'rape': 6375, 'victim': 8487, 'abortion': 130, 'because': 788, 'personally': 5817, 'healthy': 3741, 'trillion': 8213, 'dollar': 2493, 'pledge': 5940, 'fix': 3150, 'bridges': 1087, 'roads': 6747, 'challenging': 1400, 'lie': 4641, 'taiwan': 7865, 'court': 1906, 'rule': 6816, 'landmark': 4504, 'sex': 7119, 'marriage': 4873, 'case': 1314, 'heterosexual': 3792, 'white': 8713, 'invites': 4210, 'intelligence': 4158, 'committee': 1679, 'leaders': 4565, 'review': 6685, 'security': 7035, 'council': 1886, 'tweets': 8285, 'fought': 3250, 'forgotten': 3241, 'filipino': 3108, 'ii': 3995, 'honored': 3874, '75': 101, 'years': 8855, 'later': 4529, 'officials': 5486, 'greet': 3553, 'ford': 3227, 'import': 4031, 'chinese': 1480, 'cars': 1304, 'food': 3211, 'should': 7203, 'publicly': 6245, 'testify': 7979, 'democrat': 2220, 'judiciary': 4353, 'strip': 7682, 'addresses': 208, 'boy': 1042, 'scouts': 6977, 'summit': 7754, 'west': 8686, 'virginia': 8517, 'rep': 6565, 'king': 4435, 'seeks': 7042, 'surveillance': 7795, 'port': 6020, 'authority': 612, 'explosion': 2929, 'we': 8643, 'ca': 1198, 'afford': 255, 'politically': 5977, 'correct': 1863, 'bowel': 1034, 'replacing': 6578, 'secretary': 7028, 'cia': 1508, 'director': 2364, 'mike': 5041, 'pompeo': 5993, 'npr': 5416, 'vegetables': 8461, 'israeli': 4248, 'minister': 5070, 'wishes': 8767, 'iranian': 4223, 'success': 7728, 'pleads': 5936, '50': 84, 'detained': 2298, 'immigration': 4013, 'raids': 6352, 'asian': 531, 'restaurants': 6636, 'mississippi': 5103, 'another': 418, 'amp': 373, 'subreddit': 7718, 'wednesday': 8663, 'apocalypse': 446, 'capital': 1268, 'confederacy': 1733, 'debate': 2121, 'city': 1526, 'famed': 3008, 'civil': 1528, 'monuments': 5162, 'heating': 3753, 'mounting': 5195, 'wolf': 8787, 'correspondents': 1867, 'dinner': 2346, 'remarks': 6538, 'sarah': 6896, 'huckabee': 3922, 'gravy': 3541, 'latest': 4530, 'san': 6879, 'juan': 4346, 'mayor': 4926, 'answers': 420, 'wasteland': 8625, 'special': 7475, 'counsel': 1887, 'impanels': 4019, 'grand': 3521, 'jury': 4365, 'koala': 4462, 'five': 3149, 'pacific': 5629, 'islands': 4244, 'lost': 4744, 'rising': 6736, 'seas': 7019, 'hits': 3841, 'sun': 7756, 'reilly': 6508, 'god': 3467, 'sexual': 7121, 'harassment': 3684, 'scandal': 6927, 'libido': 4634, 'labels': 4485, 'justice': 4367, 'system': 7854, 'laughingstock': 4537, 'renames': 6553, 'kamala': 4375, 'harris': 3694, 'testimony': 7980, 'table': 7856, 'spicer': 7496, 'problem': 6148, 'melissa': 4974, 'mccarthy': 4932, 'gum': 3606, 'discussed': 2402, 'weapons': 8651, 'manure': 4847, 'grassley': 3537, 'graham': 3518, 'off': 5471, 'letters': 4618, 'demanding': 2215, 'info': 4106, 'author': 608, 'fbi': 3048, 'editors': 2671, 'cuts': 2037, 'strengthen': 7677, 'economy': 2663, 'drive': 2578, 'crazy': 1938, 'biceps': 868, 'search': 7013, 'motive': 5192, 'las': 4522, 'vegas': 8460, 'slow': 7341, 'but': 1180, 'll': 4701, 'tortoise': 8112, 'second': 7025, 'judge': 4348, 'scott': 6971, 'walker': 8577, 'request': 6594, 'delay': 2190, 'elections': 2696, 'playground': 5928, 'peskov': 5821, 'lawyer': 4557, 'kremlin': 4470, 'got': 3496, 'response': 6630, 'santa': 6893, 'planet': 5912, 'evidence': 2859, 'tenth': 7961, 'lurking': 4768, 'edge': 2666, 'solar': 7412, 'pleasure': 5939, 'connecticut': 1768, 'pastor': 5729, 'charged': 1421, '8g': 114, 'electricity': 2699, 'praying': 6073, 'medicare': 4961, 'all': 330, 'progressive': 6172, 'just': 4366, 'pull': 6258, 'out': 5578, 'key': 4406, 'nebraska': 5306, 'primary': 6124, 'bowling': 1038, 'egyptian': 2684, 'prime': 6125, 'ahmed': 289, 'shafiq': 7133, 'withdraws': 8776, 'from': 3299, 'rib': 6705, 'wrenched': 8831, 'ahead': 288, 'shoulder': 7204, 'trips': 8218, 'station': 7596, 'afghan': 256, 'comes': 1661, 'tent': 7959, 'elon': 2712, 'musk': 5243, 'vision': 8524, 'underground': 8328, 'road': 6746, 'bumps': 1148, 'study': 7701, 'emails': 2716, 'much': 5211, 'front': 3300, 'page': 5640, 'coverage': 1912, 'policy': 5974, '69': 98, 'swallowed': 7814, 'bodyguard': 970, 'keith': 4391, 'schiller': 6946, 'testifies': 7978, 'offered': 5478, 'prostitutes': 6206, 'aligning': 327, 'story': 7660, 'pimp': 5879, 'rubio': 6813, 'defection': 2164, 'margin': 4861, 'greasiness': 3542, 'somewhere': 7423, 'between': 861, 'hero': 3784, 'scalia': 6923, 'boss': 1017, 'kennedy': 4395, 'lover': 4752, 'tacos': 7862, 'save': 6909, 'princess': 6129, 'uae': 8299, 'qatari': 6301, 'fighter': 3099, 'jets': 4308, 'intercepted': 4162, 'civilian': 1529, 'flight': 3170, 'raced': 6332, 'rip': 6732, 'roger': 6766, 'moore': 5169, 'james': 4278, 'bond': 985, 'goalie': 3462, 'israel': 4247, 'must': 5246, 'release': 6523, '16': 18, 'old': 5496, 'girl': 3436, 'faces': 2968, '10': 2, 'amnesty': 369, 'scotch': 6968, 'dreamers': 2565, 'board': 961, 'talks': 7877, 'mimes': 5059, 'prevent': 6116, 'shutdown': 7225, 'hit': 3839, 'snag': 7372, 'plans': 5915, 'goat': 3464, 'meet': 4966, 'lee': 4587, 'busby': 1170, 'alabama': 309, 'write': 8837, 'candidate': 1251, 'roy': 6806, 'cockroach': 1608, 'survivor': 7802, 'if': 3986, 'scream': 6984, 'cnn': 1595, 'mime': 5058, 'banning': 708, 'immigrants': 4011, 'helps': 3774, 'workers': 8804, 'leading': 4567, 'economist': 2661, 'wrong': 8840, 'poodles': 6001, 'suicide': 7747, 'bomber': 979, 'kills': 4425, 'seven': 7115, 'wounds': 8824, '20': 31, 'provincial': 6229, 'shopper': 7193, 'would': 8821, 'most': 5185, 'extreme': 2947, 'senator': 7067, 'huge': 3929, 'consequences': 1773, 'lecher': 4584, 'charlottesville': 1427, 'force': 3223, 'try': 8252, 'contain': 1799, 'fallout': 3001, 'spread': 7528, 'chris': 1495, 'cornell': 1857, 'soundgarden': 7440, 'frontman': 3301, 'dies': 2330, 'aged': 268, '52': 85, 'graduates': 3514, 'woman': 8790, 'running': 6826, 'double': 2524, 'mastectomy': 4901, 'repeal': 6568, 'aca': 144, 'latte': 4533, 'hate': 3708, 'present': 6096, 'canada': 1239, 'puerto': 6253, 'rico': 6711, 'benchmark': 832, 'drops': 2590, 'record': 6449, 'low': 4755, 'remark': 6537, 'spoke': 7517, 'heavy': 3755, 'disapproval': 2378, 'deep': 2154, 'against': 266, '2018': 43, 'midterms': 5035, 'dessert': 2288, 'parties': 5710, 'fight': 3098, 'funding': 3328, 'children': 1474, 'insurance': 4151, 'vomit': 8543, 'standing': 7576, 'defense': 2170, 'abusers': 142, 'promotion': 6184, 'jeff': 4295, 'sessions': 7106, 'during': 2617, 'meeting': 4967, 'accountability': 161, 'examine': 2868, 'cost': 1875, 'florida': 3187, 'grocery': 3570, 'saw': 6914, 'military': 5047, 'france': 3262, 'own': 5621, 'dog': 2485, 'mystery': 5258, 'automotive': 620, 'failures': 2986, 'reopens': 6563, 'investigation': 4199, 'into': 4184, 'clintons': 1570, 'martians': 4882, 'sold': 7413, '85bn': 110, 'scraps': 6981, 'cold': 1623, 'weather': 8656, 'leave': 4581, 'these': 8010, 'things': 8016, 'your': 8874, 'car': 1276, 'temps': 7948, 'fall': 2997, 'eat': 2652, 'unstoppable': 8387, 'satan': 6902, '2017': 42, 'pancake': 5662, 'portland': 6022, 'train': 8161, 'stabbing': 7548, 'suspect': 7806, 'said': 6856, 'what': 8693, 'liberalism': 4631, 'gets': 3409, 'docs': 2473, 'say': 6916, 'promise': 6178, 'bottom': 1026, 'transparent': 8169, 'process': 6152, 'paul': 5747, 'ryan': 6836, 'sets': 7109, 'stifling': 7631, 'floor': 3184, 'temperature': 7942, 'shoots': 7191, 'down': 2537, 'made': 4785, 'drone': 2584, 'turkey': 8265, 'urge': 8415, 'appoint': 470, 'feed': 3064, 'dems': 2227, 'back': 645, 'power': 6053, 're': 6397, 'going': 3474, 'raise': 6356, 'taxes': 7906, 'high': 3806, 'income': 4063, 'hurricane': 3954, 'maria': 4862, 'dominica': 2501, 'live': 4693, 'chuckles': 1502, 'oil': 5492, 'tanker': 7884, 'wreck': 8828, 'produces': 6159, 'two': 8295, 'slicks': 7323, 'east': 2648, 'china': 1479, 'sea': 7004, 'drifting': 2572, 'tells': 7940, 'abbas': 124, 'good': 3486, 'chance': 1404, 'mid': 5027, 'peace': 5758, 'reporter': 6582, 'reflections': 6480, 'loss': 4742, 'hair': 3631, 'keystone': 4408, 'pipeline': 5889, 'wo': 8786, 'use': 8423, 'steel': 7609, 'repeated': 6570, 'promises': 6180, 'son': 7425, 'bitch': 910, 'outburst': 5579, 'fits': 3148, 'larger': 4519, 'pattern': 5745, 'tantrum': 7887, 'journalist': 4340, 'delivers': 2208, 'searing': 7018, 'kebabs': 4385, 'killing': 4423, 'chances': 1406, 'healthcare': 3739, 'cows': 1918, 'racism': 6337, 'evil': 2860, 'barbecue': 714, 'youngest': 8873, 'shooting': 7189, '18': 21, 'months': 5161, 'licking': 4639, 'committed': 1678, 'wiping': 8759, 'islamic': 4240, 'stain': 7560, 'cuddle': 2010, '60': 90, 'voters': 8550, 'travel': 8178, 'ban': 692, 'agoraphobics': 281, 'ruble': 6814, 'plunges': 5953, '2nd': 61, 'following': 3206, 'sanctions': 6881, 've': 8456, 'set': 7107, 'surrender': 7794, 'awaken': 630, 'male': 4814, 'congressman': 1764, 'questions': 6313, 'why': 8721, 'men': 4988, 'pay': 5750, 'prenatal': 6087, 'really': 6420, 'fetuses': 3087, 'visit': 8525, 'traumatized': 8177, 'kick': 4412, 'overtake': 5611, 'euro': 2842, 'zone': 8892, 'absorb': 140, 'debbie': 2123, 'lesko': 4611, 'wins': 8755, 'arizona': 501, 'nbc': 5301, 'projects': 6175, 'lottery': 4746, 'compliance': 1705, 'tweet': 8282, 'ready': 6411, 'issues': 4251, 'warning': 8604, 'strikes': 7680, 'metal': 5010, 'tariffs': 7899, 'like': 4653, 'atomic': 574, 'bomb': 977, 'european': 2844, 'firms': 3136, 'lobbyist': 4706, 'wedgie': 8662, 'chester': 1461, 'bennington': 839, 'linkin': 4674, 'park': 5699, 'singer': 7262, '41': 76, 'sang': 6889, 'rolls': 6775, 'obamacare': 5447, 'contraceptive': 1808, 'mandate': 4827, 'candies': 1253, 'fumes': 3323, 'cohen': 1618, 'country': 1897, 'insects': 4134, 'urged': 8416, 'mexican': 5014, 'defiance': 2173, 'border': 1010, 'wall': 8580, 'striptease': 7686, 'dept': 2264, 'reverses': 6684, 'visa': 8522, 'revocations': 6693, 'allows': 343, 'banned': 707, 'travelers': 8179, 'enter': 2786, 'escape': 2826, 'breaking': 1066, 'considering': 1780, 'options': 5537, 'retaliation': 6654, 'source': 7444, 'vacation': 8437, 'post': 6036, 'david': 2094, 'fahrenthold': 2979, 'pulitzer': 6257, 'prize': 6142, 'dogged': 2487, 'philanthropy': 5837, 'crookedness': 1981, 'claims': 1533, 'increase': 4068, 'trolls': 8226, 'mean': 4944, 'accents': 149, 'judicial': 4352, 'nominee': 5382, 'refuses': 6491, 'express': 2937, 'desegregation': 2275, 'ruling': 6819, 'gratitude': 3538, 'cabos': 1202, 'longer': 4722, 'haven': 3717, 'mexico': 5016, 'bloodshed': 949, 'cuisine': 2012, 'worried': 8811, 'flynn': 3198, 'tell': 7938, 'collusion': 1639, 'worrying': 8814, 'shows': 7216, 'within': 8779, 'range': 6369, 'earshot': 2640, 'need': 5310, 'make': 4803, 'lethal': 4615, 'hope': 3884, 'flaws': 3160, 'stand': 7574, 'shakes': 7135, 'pelvis': 5775, 'liu': 4692, 'xiaobo': 8846, 'supporters': 7773, 'mark': 4868, 'death': 2117, 'amid': 367, 'concerns': 1716, 'african': 260, 'trying': 8253, 'everest': 2855, 'without': 8780, 'permit': 5805, 'shoes': 7185, 'fundraising': 3329, 'arm': 503, 'bails': 671, 'spits': 7512, 'supreme': 7781, 'blockbuster': 944, 'term': 7963, 'movies': 5207, 'word': 8798, 'professionalism': 6164, 'moon': 5166, 'california': 1214, 'control': 1815, 'jellybeans': 4299, 'coca': 1605, 'cola': 1621, 'invasion': 4191, 'causing': 1346, 'junk': 4363, 'celebrating': 1361, 'presidency': 6101, 'drawing': 2557, 'nearer': 5303, 'either': 2688, 'done': 2506, 'great': 3543, 'harm': 3693, 'america': 364, 'haircut': 3634, 'family': 3010, 'benefit': 835, 'flush': 3194, 'treasury': 8185, 'department': 2248, 'announcing': 412, 'friday': 3287, 'morning': 5176, 'silver': 7250, 'menendez': 4990, 'bribe': 1079, 'proceeds': 6151, 'rejects': 6516, 'dismissal': 2420, 'bride': 1083, 'celebration': 1362, 'crisis': 1968, 'becoming': 791, 'unsolvable': 8384, 'warn': 8601, 'heads': 3735, 'asia': 530, 'fyre': 3344, 'festival': 3083, 'organizers': 5553, '100': 3, 'lawsuit': 4556, 'bong': 990, 'lewandowski': 4623, 'invited': 4209, 'sanction': 6880, 'oligarchs': 5498, 'law': 4550, 'retaliating': 6653, 'alleged': 333, 'dressing': 2570, 'russians': 6833, 'laughing': 4536, 'phony': 5845, 'witch': 8769, 'hunt': 3950, 'pardon': 5693, 'sheriff': 7165, 'joe': 4324, 'arpaio': 515, 'courageous': 1904, 'thing': 8015, 'suspects': 7808, 'niger': 5357, 'villager': 8500, 'betrayed': 855, 'army': 511, 'troops': 8228, 'fink': 3125, 'hundreds': 3942, 'thousands': 8027, 'educators': 2673, 'hundred': 3941, 'thousand': 8026, 'homeless': 3864, 'students': 7698, 'roofs': 6785, 'india': 4078, 'build': 1132, 'major': 4800, 'facility': 2971, 'seychelles': 7125, 'growing': 3584, 'influence': 4103, 'infest': 4096, 'shrinking': 7220, 'ears': 2639, 'insult': 4150, 'native': 5287, 'smash': 7354, 'windows': 8746, 'mcdonald': 4937, 'bank': 700, 'swearing': 7823, 'wash': 8619, 'island': 4243, 'principal': 6130, 'history': 3838, 'decorum': 2151, 'race': 6331, 'ethnicity': 2840, 'profits': 6167, 'debacle': 2119, 'role': 6771, 'model': 5125, 'measles': 4947, 'debacles': 2120, 'boost': 1005, 'trade': 8151, 'worries': 8812, 'hackers': 3625, 'haitians': 3644, 'aids': 293, 'nigerians': 5359, 'huts': 3960, 'oval': 5593, 'bacchanal': 644, 'separated': 7083, 'families': 3009, 'react': 6401, 'ends': 2759, 'protected': 6209, 'status': 7599, 'condiments': 1727, 'stormy': 7659, 'daniels': 2074, 'threats': 8033, 'reports': 6585, 'affair': 247, 'cookbook': 1831, 'chiefs': 1470, 'asked': 533, 'them': 8000, 'intervene': 4176, 'investigations': 4200, 'opera': 5522, 'jerusalem': 4305, 'intimidated': 4182, 'palestinian': 5656, 'violence': 8510, 'move': 5202, 'embassy': 2720, 'hummus': 3938, 'patrol': 5743, 'raises': 6359, 'tensions': 7958, 'backpack': 654, 'eighteen': 2686, 'found': 3252, 'guilty': 3603, 'newcastle': 5337, 'grooming': 3573, 'network': 5328, 'virgins': 8519, 'denying': 2244, 'sally': 6868, 'yates': 8851, 'she': 7153, 'attention': 587, 'soon': 7430, 'alt': 352, 'neo': 5318, 'confederate': 1734, 'corey': 1853, 'stewart': 7628, 'came': 1223, 'shockingly': 7183, 'close': 1574, 'panel': 5667, 'subpoenas': 7717, 'adviser': 236, 'michael': 5021, 'oxen': 5625, 'bump': 1147, 'maker': 4806, 'resumes': 6647, 'sales': 6864, 'month': 5160, 'mass': 4893, 'eating': 2654, 'kalashnikov': 4373, 'remote': 6547, 'teachers': 7917, 'lawyers': 4558, 'others': 5569, 'worry': 8813, 'fate': 3037, 'student': 7697, 'debt': 2125, 'forgiveness': 3239, 'disappearance': 2373, 'alternatives': 355, 'putin': 6293, 'mixed': 5112, 'bag': 665, 'looms': 4729, 'drinks': 2577, 'advocacy': 240, 'group': 3580, 'accuses': 169, 'racial': 6336, 'bias': 866, 'bonehead': 988, 'plague': 5907, 'disgusted': 2408, 'officer': 5482, 'quits': 6323, 'many': 4848, 'follow': 3204, 'smoking': 7364, 'assad': 539, 'international': 4172, 'pressure': 6106, 'step': 7615, 'damascus': 2060, 'mood': 5164, 'boogie': 993, 'maybe': 4924, 'lady': 4496, 'birthday': 904, 'fat': 3034, 'maps': 4852, 'course': 1905, 'autocrats': 615, 'foreign': 3230, 'trip': 8215, 'autograph': 616, 'delight': 2202, 'sitters': 7280, 'plays': 5932, 'broadway': 1104, 'vornado': 8545, 'handshake': 3671, 'sell': 7058, 'stake': 7563, 'nyc': 5441, 'tower': 8140, 'kushner': 4480, 'give': 3440, 'strike': 7679, 'bases': 741, 'minutes': 5079, 'practicing': 6058, 'nikki': 5366, 'haley': 3645, 'seemingly': 7045, 'tricked': 8207, 'pranksters': 6069, 'commenting': 1672, 'fictional': 3091, 'binomo': 896, 'waltzing': 8586, 'jae': 4270, 'yong': 8867, 'samsung': 6878, 'indicted': 4082, 'bribery': 1081, 'kidnapping': 4418, 'un': 8311, 'myanmar': 5252, 'rohingya': 6768, 'muslims': 5245, 'kittens': 4447, 'loopholes': 4731, 'disclose': 2387, 'financial': 3115, 'fee': 3063, 'alert': 319, 'flag': 3152, 'crimes': 1961, 'fashion': 3031, 'manafort': 4822, 'notes': 5407, 'refer': 6474, 'contributions': 1814, 'legs': 4605, 'staffers': 7555, 'secret': 7027, 'assignments': 555, 'telling': 7939, 'aides': 292, 'hide': 3803, 'john': 4325, 'kelly': 4393, 'haircuts': 3635, 'looking': 4726, 'attempt': 582, 'oust': 5574, 'decency': 2132, 'refugee': 6485, 'admissions': 217, 'suspended': 7810, 'until': 8390, 'july': 4359, '12': 11, 'auditions': 601, 'lieberman': 4642, 'emerges': 2728, 'frontrunner': 3302, 'relay': 6522, 'delicious': 2201, 'idaho': 3976, 'fastest': 3033, 'potato': 6043, 'quietly': 6316, 'stalls': 7569, 'safeguards': 6852, 'dozens': 2544, 'endangered': 2752, 'species': 7476, 'bakers': 675, 'korean': 4468, 'supercharged': 7763, 'option': 5536, 'explained': 2919, 'doubt': 2526, 'gorilla': 3493, 'blame': 923, 'game': 3362, 'themselves': 8002, 'hearings': 3745, 'mccabe': 4930, 'firing': 3134, 'once': 5506, 'inspector': 4141, 'general': 3392, 'gadget': 3347, 'receives': 6434, 'ovation': 5594, 'color': 1645, 'purple': 6284, 'imagines': 4006, 'mnuchin': 5114, 'hard': 3686, 'rich': 6707, 'hedges': 3757, 'assassinations': 545, 'successfully': 7730, 'launches': 4541, 'satellite': 6903, 'carrying': 1303, 'rocket': 6759, 'space': 7454, 'tree': 8190, 'aircraft': 299, 'carrier': 1299, 'dispatch': 2428, 'outrageous': 5589, 'eight': 2685, 'm1': 4775, 'minibus': 5066, 'lorry': 4736, 'crash': 1932, 'refrigerator': 6484, 'both': 1023, 'sides': 7230, 'committing': 1681, 'burma': 1159, 'contradictions': 1811, 'upon': 8407, 'tale': 7873, 'payoff': 5755, 'porn': 6017, 'star': 7579, 'offer': 5477, 'french': 3282, 'far': 3018, 'steps': 7619, 'limelight': 4657, 'slithers': 7332, 'interfering': 4169, 'deny': 2243, 'having': 3718, 'compromising': 1711, 'information': 4109, 'elf': 2706, 'ferry': 3081, 'link': 4672, 'terror': 7972, 'risk': 6737, 'xl': 8847, 'vow': 8554, 'beer': 798, 'miss': 5096, 'asshole': 554, 'murdoch': 5235, 'billion': 886, 'bet': 852, 'indian': 4079, 'cricket': 1957, 'buffet': 1128, 'clears': 1560, 'hurdle': 3953, 'attorney': 590, 'speedster': 7483, 'dnc': 2471, 'chair': 1393, 'jaime': 4275, 'harrison': 3695, 'lobbyists': 4707, 'appetizers': 464, 'billionaire': 887, 'babis': 642, 'scores': 6967, 'czech': 2047, 'partners': 5714, 'annoy': 413, 'added': 205, 'critic': 1970, 'cleared': 1557, 'skip': 7297, 'hinted': 3823, 'anti': 426, 'moscow': 5181, 'quilts': 6320, 'among': 370, 'gallup': 3355, 'still': 7633, 'odds': 5467, 'closed': 1575, 'door': 2516, 'evens': 2852, 'seen': 7047, 'imminent': 4014, 'kim': 4428, 'meets': 4969, 'tour': 8128, 'sunk': 7758, '100m': 5, 'luxury': 4770, 'developments': 2309, 'scientists': 6962, 'turn': 8269, 'hydrogen': 3961, 'breakthrough': 1069, 'revolutionise': 6697, 'jazz': 4293, 'potential': 6045, 'legal': 4595, 'fox': 3258, 'clowns': 1589, 'swap': 7818, 'booed': 992, 'davos': 2096, 'criticizing': 1976, 'fake': 2993, 'media': 4958, 'injured': 4124, 'shots': 7202, 'fired': 3130, 'school': 6953, 'downed': 2538, 'sperry': 7493, 'organizing': 5554, 'violent': 8511, 'miles': 5043, 'farm': 3025, 'sam': 6875, 'charles': 1425, 'murray': 5236, 'allure': 344, 'science': 6959, 'werewolf': 8685, 'bombshell': 984, 'millions': 5055, 'crooked': 1980, 'uranium': 8413, 'finger': 3121, 'chang': 1407, 'serve': 7098, 'style': 7710, 'checkers': 1443, 'hung': 3943, 'parliament': 5703, 'brexit': 1077, 'negotiations': 5314, 'gigolo': 3426, 'vehicle': 8462, 'plows': 5946, 'man': 4821, 'clapper': 1538, 'admitted': 220, 'spied': 7499, 'false': 3003, 'poodle': 6000, 'poised': 5963, 'ease': 2645, 'rules': 6818, 'religious': 6530, 'groups': 3582, 'politics': 5981, 'churches': 1506, 'pelosi': 5773, 'insecurity': 4135, 'fueling': 3314, 'fraud': 3272, 'contempt': 1803, 'blitz': 939, 'betrays': 856, 'hostility': 3903, 'thumb': 8044, 'rally': 6364, 'brazil': 1059, 'turns': 8273, 'seance': 7012, 'clash': 1542, 'disputed': 2432, 'himalayan': 3820, 'region': 6496, 'barclays': 720, 'ceo': 1381, 'varley': 8452, 'three': 8034, 'bankers': 702, 'appear': 459, 'musical': 5241, 'sen': 7065, 'flake': 3155, 'or': 5539, 'lose': 4738, 'iranians': 4224, 'scheme': 6944, 'butcher': 1181, 'nato': 5288, 'countries': 1896, 'fires': 3132, 'eastern': 2650, 'coast': 1601, 'fireworks': 3133, 'friends': 3291, 'scolds': 6965, 'ceos': 1382, 'pulled': 6259, 'vagina': 8440, 'heading': 3732, 'toward': 8136, 'some': 7418, 'losses': 4743, 'midterm': 5034, 'races': 6333, 'polls': 5984, 'horse': 3894, 'ties': 8055, 'increasingly': 4070, 'credible': 1949, 'laundry': 4544, 'restricting': 6639, 'coal': 1599, 'companies': 1688, 'dumping': 2612, 'waste': 8624, 'streams': 7672, 'nypd': 5442, 'nobody': 5376, 'deported': 2258, 'jumping': 4361, 'turnstile': 8274, 'rope': 6790, 'gaza': 3383, 'rights': 6724, 'commissioner': 1676, 'criticizes': 1975, 'cupcakes': 2020, 'duterte': 2621, 'spokesman': 7519, 'return': 6667, 'philippine': 5838, 'fugitive': 3316, 'bilateral': 883, 'reward': 6699, 'balloon': 686, 'federal': 3060, 'deport': 2255, 'innovative': 4131, 'economies': 2660, 'ellison': 2711, 'backs': 656, 'chairs': 1395, 'toyota': 8144, 'boats': 965, 'dodges': 2481, 'press': 6105, 'spirals': 7506, 'harasses': 3683, 'japan': 4285, 'declines': 2145, 'comment': 1670, 'sushi': 7805, 'kelli': 4392, 'ward': 8595, 'clean': 1551, 'foremost': 3232, 'bikini': 881, 'dna': 2470, 'scratch': 6982, 'alter': 353, 'blueprint': 958, 'sasquatch': 6900, 'lead': 4563, 'reform': 6482, 'needs': 5311, 'stupid': 7708, 'social': 7405, 'data': 2083, 'shared': 7144, 'agencies': 269, 'cat': 1322, 'harsh': 3696, 'language': 4512, 'little': 4691, 'precedent': 6075, 'dogs': 2489, 'hoagie': 3843, 'london': 4719, 'molotov': 5140, 'cocktails': 1611, 'terrorists': 7975, 'van': 8448, 'bartenders': 735, 'announced': 409, 'venezuela': 8465, 'turnout': 8272, 'constituent': 1786, 'assembly': 548, 'vote': 8546, 'drilling': 2573, 'read': 6406, 'coretta': 1852, 'letter': 4617, 'outside': 5590, 'mcconnell': 4935, 'march': 4856, 'cities': 1520, 'across': 184, 'mockery': 5120, 'pete': 5825, 'passage': 5718, 'delivering': 2207, 'wanted': 8591, 'racists': 6339, 'calais': 1211, 'leaves': 4582, 'teenage': 7931, 'refugees': 6486, 'critical': 1971, 'smuggling': 7369, 'gangs': 3366, 'exploit': 2928, 'desperation': 2283, 'turtles': 8276, 'gateshead': 3379, 'nothing': 5408, 'urges': 8418, 'other': 5568, 'local': 4709, 'authorities': 611, 'cheapskates': 1438, 'gm': 3458, 'company': 1689, 'production': 6162, 'shenanigans': 7162, 'likely': 4655, 'headquarters': 3734, 'few': 3089, 'decades': 2129, 'reported': 6580, 'maryland': 4886, 'sparking': 7465, 'lockdown': 4713, 'sparklers': 7466, 'faithful': 2992, 'flock': 3179, 'vatican': 8455, 'pope': 6008, 'christmas': 1498, 'eve': 2849, 'mall': 4816, 'global': 3454, 'investors': 4205, 'fresh': 3285, 'fudge': 3310, 'realizing': 6419, 'legislative': 4602, 'agenda': 271, 'hands': 3670, 'menu': 4994, 'hhs': 3797, 'readying': 6412, 'expand': 2899, 'conscience': 1771, 'protections': 6213, 'eliminate': 2708, 'cripple': 1967, 'purchase': 6281, 'call': 1216, 'includes': 4060, 'plea': 5933, 'moral': 5173, 'courage': 1903, 'gun': 3607, 'legislation': 4601, 'mind': 5061, 'dakota': 2056, 'protested': 6217, 'leaks': 4573, 'animals': 398, 'manhandled': 4829, 'fcc': 3049, 'net': 5323, 'neutrality': 5331, 'rumble': 6821, 'threw': 8035, 'bus': 1169, 'failure': 2985, 'sloths': 7339, 'stocks': 7640, 'lower': 4756, 'successful': 7729, 'mocking': 5121, 'influential': 4104, 'outsiders': 5591, 'played': 5925, 'pruitt': 6232, 'wizards': 8785, 'told': 8089, 'ny': 5440, 'schneiderman': 6950, 'abuse': 141, '2013': 40, 'plane': 5909, 'crashes': 1934, 'bicycle': 869, 'budget': 1126, 'safe': 6851, 'mother': 5189, 'roaches': 6745, 'violated': 8506, 'constitution': 1788, 'speech': 7479, 'martini': 4884, 'scarborough': 6931, 'awkward': 636, 'silence': 7242, 'admission': 216, '43': 79, 'farmer': 3026, 'hawaii': 3719, 'smuggled': 7367, '15': 17, 'deportation': 2256, 'battle': 761, 'returns': 6669, 'salmon': 6870, 'hyping': 3966, '77': 103, 'previously': 6118, 'omitted': 5504, 'assets': 553, 'pennies': 5786, 'banker': 701, 'home': 3862, 'loans': 4703, 'leftovers': 4591, 'loves': 4753, 'wing': 8749, 'radical': 6343, 'equally': 2805, 'serious': 7094, 'adl': 212, 'music': 5240, 'prepared': 6090, 'litigate': 4690, 'time': 8063, 'warner': 8603, 'cry': 2004, 'camp': 1228, 'january': 4284, 'igloo': 3987, 'plead': 5934, 'stay': 7600, 'message': 5005, 'pass': 5717, 'overhaul': 5603, 'qualcomm': 6304, 'regulators': 6504, 'push': 6286, '44': 80, 'nxp': 5439, 'overlords': 5604, 'deflects': 2182, 'nunes': 5434, 'lasers': 4525, 'bridgegate': 1086, 'lands': 4507, 'christie': 1497, 'baroni': 726, 'cells': 1368, 'seek': 7040, 'citing': 1522, 'nastiness': 5280, 'era': 2812, 'dinners': 2347, 'uk': 8304, 'universities': 8369, 'tackle': 7860, 'tide': 8053, 'antisemitism': 429, 'campus': 1236, 'relative': 6520, 'denounced': 2236, 'supremacy': 7780, 'resigns': 6615, 'wizard': 8784, 'eu': 2841, 'aluminum': 356, 'deodorant': 2245, 'suddenly': 7740, 'replaces': 6577, 'acting': 187, 'customs': 2035, 'head': 3729, 'daniel': 2073, 'ragsdale': 6350, 'thomas': 8022, 'homan': 3861, 'ugly': 8303, 'pointed': 5960, 'conflict': 1747, 'energy': 2764, 'voter': 8548, 'runs': 6828, 'inauguration': 4053, 'crowd': 1989, '2009': 37, 'vs': 8558, 'stadium': 7551, 'approved': 479, 'ladders': 4494, 'around': 513, 'kisses': 4441, 'waffle': 8565, 'al': 308, 'franken': 3267, 'slams': 7307, 'education': 2672, 'betsy': 858, 'devos': 2313, 'incompetent': 4066, 'cabinet': 1200, 'level': 4621, 'ever': 2854, 'moons': 5167, 'promised': 6179, 'access': 152, 'exec': 2880, 'crack': 1923, 'listening': 4686, 'bad': 662, 'confession': 1738, 'nevada': 5332, 'wildly': 8739, 'different': 2335, 'elephant': 2704, 'epa': 2800, 'reduce': 6467, 'workforce': 8805, 'buyouts': 1193, 'early': 2637, 'retirement': 6659, 'execution': 2883, 'considered': 1779, 'buses': 1171, 'seat': 7021, 'district': 2449, 'won': 8793, '19': 23, 'opinion': 5526, 'threatening': 8031, 'democracy': 2219, 'undermining': 8331, 'silencing': 7243, 'conservatives': 1777, 'guns': 3611, 'gut': 3612, 'doubles': 2525, 'inherited': 4119, 'mess': 5004, 'claim': 1530, 'dip': 2350, 'expectancy': 2904, 'inequality': 4092, 'upswing': 8412, 'its': 4258, 'entire': 2791, 'resign': 6611, 'prom': 6176, 'reich': 6506, 'warring': 8610, 'camps': 1235, 'potatoes': 6044, 'red': 6459, 'lawmakers': 4553, 'find': 3117, 'blue': 957, 'piggy': 5869, 'impulsive': 4047, 'dancing': 2069, 'dem': 2213, 'nsa': 5418, 'leak': 4570, 'offers': 5480, 'verified': 8474, 'linking': 4675, 'don': 2502, 'mcgahn': 4938, 'threatened': 8030, 'june': 4362, 'sing': 7260, 'cable': 1201, 'careening': 1283, 'defining': 2179, 'moment': 5142, 'broadside': 1103, 'cries': 1958, 'newt': 5342, 'gingrich': 3433, 'him': 3819, 'holds': 3855, 'joint': 4331, 'conference': 1735, 'norway': 5400, 'updates': 8400, 'sir': 7271, 'known': 4460, 'age': 267, '89': 113, 'due': 2604, 'cancer': 1250, 'aid': 290, 'withdrawing': 8774, 'shoe': 7184, 'limits': 4662, 'retirements': 6660, 'create': 1940, 'competitive': 1697, 'speed': 7481, 'probably': 6144, 'grandpa': 3528, 'posts': 6040, '192': 25, 'february': 3057, 'monopoly': 5154, 'bob': 966, 'hertzberg': 3790, 'cooperate': 1839, 'unwanted': 8394, 'hugs': 3931, 'aromas': 512, 'giant': 3415, 'shipworm': 7175, 'philippines': 5839, 'dreadlock': 2560, 'barack': 712, 'chicago': 1464, 'library': 4636, 'nor': 5393, 'believer': 824, 'community': 1687, 'museum': 5238, 'kristol': 4471, 'voice': 8537, 'biggest': 878, 'opponents': 5531, 'bladder': 920, 'manslaughter': 4841, 'eyed': 2958, 'grenfell': 3558, 'blaze': 932, 'weed': 8664, 'crime': 1959, 'behind': 816, 'bars': 734, 'plants': 5918, 'seattle': 7024, 'dismiss': 2419, 'misdemeanor': 5088, 'marijuana': 4863, 'dynamite': 2628, 'tough': 8124, 'talk': 7875, 'ballet': 683, 'noncriminal': 5386, 'past': 5727, 'festivals': 3084, 'fear': 3051, 'sweater': 7824, 'examining': 2869, 'tanning': 7886, 'mosque': 5182, 'egypt': 2683, 'sinai': 7258, '235': 54, 'befuddles': 804, 'schumer': 6958, 'donate': 2504, 'harvey': 3701, 'weinstein': 8674, 'cologne': 1640, 'drag': 2548, 'resistance': 6617, 'lingerie': 4670, 'bullet': 1137, 'costs': 1878, 'soar': 7401, 'opening': 5520, 'delayed': 2191, 'algeria': 321, 'dump': 2611, 'scud': 6999, 'ballistic': 685, 'briefed': 1088, 'google': 3489, 'doing': 2490, 'irreparable': 4234, 'hamsters': 3662, 'armenian': 508, 'sobs': 7403, 'skeptical': 7289, 'suit': 7749, 'outfit': 5582, 'italian': 4254, 'pm': 5954, 'gentiloni': 3396, 'slurs': 7349, 'announcement': 410, 'speculation': 7477, 'theresa': 8008, 'debates': 2122, 'tory': 8116, 'sources': 7445, 'favors': 3045, 'names': 5271, 'charmaine': 1428, 'yoest': 8864, 'lonely': 4720, 'chelsea': 1454, 'manning': 4840, 'hurts': 3956, 'congressmen': 1765, 'fault': 3041, 'order': 5545, 'sends': 7071, 'pro': 6143, 'growth': 3586, 'environment': 2795, 'pizza': 5902, 'partner': 5713, 'dressmakers': 2571, 'insurer': 4152, 'flees': 3164, 'blaming': 926, 'sabotage': 6839, 'bats': 758, 'jail': 4272, 'free': 3277, 'cards': 1280, 'work': 8801, 'footloose': 3217, 'keeps': 4390, 'team': 7919, 'guessing': 3597, 'bewildered': 862, 'confirms': 1746, 'reinhold': 6511, 'niebuhr': 5352, 'brayed': 1057, 'hopes': 3886, 'improved': 4043, 'everything': 2858, 'opec': 5517, 'agree': 282, 'extend': 2941, 'vodka': 8535, 'conservative': 1776, 'activist': 190, 'lauren': 4547, 'southern': 7448, 'sorceress': 7434, 'begins': 810, 'attacking': 580, 'crocodile': 1979, '1st': 30, 'amendment': 363, 'speak': 7471, 'college': 1631, 'sneeze': 7381, 'analysis': 380, 'best': 850, 'deals': 2115, 'prove': 6222, 'muffins': 5214, 'jordan': 4339, 'selects': 7054, 'finalists': 3112, '300mw': 63, 'wind': 8743, 'earth': 2641, 'georgia': 3401, 'quiet': 6315, 'tricare': 8205, 'stirs': 7635, 'ire': 4227, 'headaches': 3731, 'becomes': 790, 'popular': 6011, 'modern': 5130, 'mascot': 4889, 'pointing': 5961, 'fingers': 3124, 'stalemate': 7565, 'pool': 6003, 'criminalizing': 1964, 'abortions': 131, 'weeks': 8667, 'burritos': 1167, 'semitic': 7063, 'messages': 5006, 'matzos': 4920, 'yemen': 8858, 'cholera': 1489, 'cases': 1315, 'reach': 6398, 'icrc': 3974, 'hiccup': 3798, 'upper': 8408, 'hand': 3663, 'trillions': 8214, 'breaks': 1068, 'wh': 8690, 'comms': 1683, 'anthony': 424, 'scaramucci': 6930, 'deletes': 2196, 'contradicting': 1810, 'sings': 7265, 'allow': 339, 'buy': 1190, 'equipment': 2810, 'pornography': 6019, 'cash': 1316, 'mccain': 4931, 'joke': 4333, 'controversy': 1818, 'fan': 3013, 'watched': 8628, 'oath': 5444, 'pretty': 6113, 'nasa': 5278, 'ok': 5493, 'touch': 8121, 'hardware': 3690, 'honor': 3872, 'host': 3901, 'xi': 8845, 'takes': 7871, 'rebuttal': 6433, 'protectionism': 6212, 'rant': 6373, 'position': 6030, 'accusers': 168, 'lying': 4772, 'crab': 1922, 'charts': 1430, 'show': 7209, 'ignore': 3990, 'horoscopists': 3890, 'elected': 2694, 'spend': 7489, 'reporters': 6583, 'celebrities': 1363, 'thoughts': 8025, 'distress': 2447, 'signal': 7236, 'upside': 8410, 'pin': 5882, 'smoke': 7362, 'teacher': 7916, 'apologizes': 451, 'accidentally': 155, 'classroom': 1548, 'let': 4614, 'pot': 6042, 'flourish': 3190, 'associated': 558, 'freedom': 3278, 'sanctuary': 6882, 'states': 7595, 'enforcement': 2766, 'driving': 2583, 'performing': 5801, 'nightmare': 5363, 'marathons': 4854, 'colon': 1642, 'businesses': 1175, 'proposal': 6192, 'stink': 7634, 'buzzfeed': 1195, 'unverified': 8393, 'igniting': 3988, 'father': 3038, 'self': 7055, 'imposed': 4035, 'curbs': 2022, 'celibacy': 1365, 'disrupt': 2436, 'rightwing': 6725, 'german': 3404, 'afd': 246, 'goers': 3470, 'netherlands': 5326, 'answer': 419, 'refused': 6490, 'windmill': 8744, 'horses': 3896, 'spending': 7490, 'excludes': 2878, 'declares': 2140, 'anyway': 438, 'bankruptcy': 704, 'admin': 213, 'had': 3628, 'justifiable': 4369, 'sharing': 7147, 'soccer': 7404, 'extremists': 2950, 'triangle': 8200, 'saudi': 6905, 'crownprince': 1992, 'salman': 6869, 'snitches': 7385, 'manchin': 4826, 'skips': 7298, 'informational': 4110, 'useful': 8425, 'idiots': 3984, 'galore': 3356, 'york': 8868, 'times': 8066, 'juggler': 4355, 'aide': 291, 'accused': 166, '2008': 36, 'healing': 3737, 'while': 8700, 'week': 8665, 'snowflakes': 7394, 'play': 5923, 'mainstream': 4799, 'sympathy': 7847, 'pray': 6071, 'lifts': 4649, 'cops': 1846, 'dresses': 2569, 'announces': 411, 'waterpark': 8634, 'problems': 6149, 'obstruction': 5460, 'bribes': 1082, 'tout': 8133, 'daca': 2050, 'quite': 6322, 'cruise': 1999, 'line': 4667, 'carnival': 1290, 'corp': 1860, 'joins': 4330, 'bermuda': 844, 'donut': 2511, 'full': 3320, 'touts': 8135, 'reforms': 6483, 'open': 5518, 'business': 1174, 'eases': 2646, 'service': 7101, 'delivery': 2209, 'religion': 6529, 'responds': 6629, 'sweating': 7825, 'australia': 604, 'accept': 150, 'central': 1378, 'nose': 5402, 'advisers': 237, 'melania': 4973, 'trapped': 8174, 'money': 5149, 'put': 6292, 'danger': 2071, 'recommend': 6447, 'payment': 5753, 'ers': 2821, 'ted': 7927, 'nugent': 5425, 'parkland': 5701, 'teens': 7933, 'nra': 5417, 'soul': 7437, 'corporate': 1861, 'ignores': 3992, 'rise': 6734, 'oligarchy': 5499, 'yeast': 8856, 'dealing': 2112, 'migrant': 5038, 'escalating': 2825, 'whether': 8698, 'keeping': 4389, 'mold': 5136, 'alex': 320, 'jones': 4337, 'fears': 3053, 'come': 1657, 'conspiracy': 1784, 'theorist': 8005, 'bro': 1098, 'anymore': 434, 'prance': 6063, 'bird': 900, 'devil': 2311, 'theory': 8006, 'endorses': 2758, 'lgbt': 4624, 'attorneys': 591, 'argue': 497, 'gays': 3382, 'voterbase': 8549, 'terms': 7967, 'ratings': 6389, 'jeopardize': 4300, 'suntan': 7761, 'futures': 3342, 'point': 5959, 'sharply': 7149, 'street': 7674, 'friendly': 3290, 'cohn': 1619, 'bridge': 1085, 'feared': 3052, 'storm': 7657, 'swamps': 7817, 'undead': 8323, 'led': 4585, 'enforce': 2765, 'axes': 638, 'transgender': 8167, 'independent': 4076, 'trees': 8192, 'secretly': 7029, 'helping': 3772, 'chechen': 1440, 'flee': 3163, 'persecution': 5809, 'radar': 6341, 'programme': 6169, 'mired': 5081, 'paralysis': 5687, 'defy': 2184, 'recovery': 6453, 'child': 1472, 'labor': 4486, 'jobs': 4322, 'pies': 5866, 'waiting': 8572, 'permanent': 5803, 'clearance': 1556, 'guard': 3591, 'caroline': 1293, 'glick': 3450, 'gives': 3442, 'cause': 1344, 'camel': 1224, 'candidates': 1252, 'winning': 8754, 'explains': 2921, 'reasons': 6424, 'risque': 6740, 'dealmaking': 2114, 'mode': 5124, 'works': 8807, 'scenes': 6940, 'duck': 2601, 'describes': 2272, 'words': 8799, 'clothing': 1585, 'bush': 1172, 'diplomat': 2353, 'scared': 6934, 'legalise': 4596, 'isolated': 4245, 'settlement': 7110, 'settler': 7112, 'murdered': 5230, 'netanyahu': 5324, 'dumpster': 2615, 'timing': 8068, 'again': 265, 'suggests': 7746, 'tweeted': 8283, 'watching': 8630, 'segment': 7049, 'chick': 1465, 'painting': 5651, 'temporarily': 7946, 'breakout': 1067, 'meal': 4943, 'look': 4723, 'pumpkin': 6265, 'broke': 1107, 'ethics': 2838, 'laws': 4555, 'jaywalking': 4292, 'dubs': 2600, 'knight': 4455, 'lavishes': 4549, 'carpet': 1295, 'treatment': 8188, 'arrives': 520, 'jinping': 4319, 'oscars': 5564, 'blocks': 946, 'clinic': 1568, 'band': 695, 'blake': 922, 'farenthold': 3022, 'diving': 2461, 'went': 8682, 'listen': 4684, 'fast': 3032, 'haters': 3710, 'clearly': 1559, 'trap': 8173, 'affirmative': 253, 'hypocrisy': 3968, 'foes': 3202, 'diversity': 2456, 'those': 8023, 'oppose': 5532, 'my': 5251, 'dad': 2052, 'funny': 3334, 'nsc': 5419, 'dense': 2238, 'confused': 1754, 'facebook': 2967, 'bans': 710, 'jehovah': 4297, 'witnesses': 8781, 'claiming': 1532, 'extremist': 2949, 'activities': 192, 'petraeus': 5829, 'warns': 8606, 'current': 2027, 'fray': 3274, 'collapse': 1624, 'harvester': 3699, 'trumpcare': 8240, 'question': 6310, 'whole': 8716, 'economic': 2659, 'dementia': 2218, 'western': 8687, 'airstrikes': 305, 'unlikely': 8373, 'impact': 4018, 'machine': 4779, 'evangelical': 2846, 'slippery': 7330, 'slope': 7336, 'ronald': 6782, 'reagan': 6413, 'soap': 7400, 'weaving': 8657, 'propagandistic': 6189, 'fantasy': 3017, 'tickled': 8049, 'doug': 2527, 'upset': 8409, 'bed': 792, 'beneath': 834, 'dignity': 2339, 'sweeteners': 7829, 'certified': 1387, 'dumb': 2608, 'ass': 538, 'psychologist': 6239, 'psychoneurotic': 6240, 'shut': 7224, 'computer': 1712, 'girls': 3438, 'become': 789, 'brides': 1084, 'malaysia': 4812, 'immediately': 4009, 'bolt': 975, 'nafta': 5261, 'join': 4327, 'keefe': 4386, 'busts': 1178, 'editor': 2670, 'explaining': 2920, 'paper': 5678, 'narrative': 5277, 'demands': 2216, 'withdraw': 8772, 'branding': 1052, 'apartheid': 441, 'tractor': 8150, 'erdogan': 2814, 'clucking': 1593, 'pershing': 5810, 'cited': 1518, 'effect': 2674, 'remains': 6535, 'wynn': 8844, 'finance': 3114, 'reclining': 6444, 'suck': 7735, 'mitt': 5111, 'romney': 6781, 'trolled': 8223, 'flip': 3172, 'flopping': 3186, 'endorsement': 2757, 'wig': 8730, 'triggers': 8212, 'alarm': 310, 'warnings': 8605, 'living': 4697, 'weak': 8644, 'unstable': 8386, 'warned': 8602, 'seth': 7108, 'murder': 5229, 'staffer': 7554, 'protect': 6208, 'newscasters': 5340, 'iraqi': 4226, 'forces': 3225, 'tigris': 8061, 'stronghold': 7691, 'mosul': 5187, 'clubhouse': 1591, 'policies': 5972, 'guardian': 3592, 'hotel': 3908, 'raised': 6357, 'room': 6786, 'rates': 6386, 'colluded': 1638, 'fuck': 3309, 'daughters': 2091, 'too': 8100, 'takeover': 7870, 'aecon': 244, 'grounds': 3579, 'takeout': 7869, 'clue': 1594, 'true': 8238, 'sacrifice': 6844, 'bakeries': 674, 'jong': 4338, 'agrees': 285, 'dmz': 2469, 'jackie': 4266, 'mason': 4891, 'grammys': 3520, 'competition': 1696, 'hates': 3711, 'watch': 8626, 'advocate': 241, 'matt': 4916, 'schlapp': 6948, 'treasonous': 8183, 'golf': 3480, 'thumbs': 8045, 'controversies': 1817, 'navarro': 5295, 'diplomats': 2355, 'video': 8490, 'eagles': 2635, 'defensiveness': 2171, 'handling': 3668, 'grief': 3559, 'worse': 8815, 'mail': 4796, 'geun': 3411, 'hye': 3962, 'impeachment': 4022, 'trial': 8199, 'dancer': 2066, 'minnesota': 5073, 'tom': 8093, 'emmer': 2731, 'snow': 7393, 'boris': 1012, 'condemned': 1724, 'libya': 4637, 'bodies': 968, 'jokes': 4335, 'bleach': 934, 'backed': 647, 'given': 3441, 'spa': 7453, 'spies': 7500, 'targeting': 7897, 'maritime': 4867, 'industry': 4091, 'cape': 1267, 'town': 8141, 'drought': 2591, 'avoid': 626, 'zero': 8883, 'towel': 8138, 'organisation': 5550, 'lack': 4491, 'scientific': 6960, 'thinking': 8018, 'store': 7654, 'nancy': 5272, 'hails': 3630, 'owe': 5619, 'parents': 5697, 'bring': 1092, 'kids': 4419, 'dolls': 2495, 'le': 4562, 'pen': 5776, 'moves': 5205, 'monde': 5148, 'studio': 7700, 'swedish': 7827, 'prosecutor': 6201, 'truck': 8234, 'spoken': 7518, 'stuffing': 7702, 'sad': 6849, 'view': 8493, 'depression': 2263, 'arrested': 517, 'linda': 4665, 'wenzel': 8683, 'shepherd': 7163, 'vermont': 8476, 'governor': 3503, 'vetoes': 8482, 'changes': 1410, 'joints': 4332, 'employee': 2738, 'controversial': 1816, 'promotes': 6183, 'mascots': 4890, 'sprinter': 7532, 'thanksgiving': 7993, 'majority': 4802, 'prefer': 6080, 'side': 7229, 'wrestle': 8832, 'biden': 871, 'liar': 4628, 'nicest': 5350, 'sweetheart': 7832, 'resubmit': 6643, 'renewals': 6556, 'originally': 5558, 'rejected': 6514, 'late': 4528, 'ross': 6794, 'linked': 4673, 'shipping': 7174, 'concern': 1715, 'brothel': 1113, 'wiretap': 8762, 'alien': 325, 'royals': 6808, 'crown': 1991, 'prince': 6127, 'participation': 5708, 'olympics': 5502, 'affect': 249, 'centenarian': 1374, 'union': 8361, 'lap': 4515, 'landfill': 4501, 'chairman': 1394, 'pai': 5644, 'substituting': 7723, 'ideology': 3982, 'art': 522, 'chuckle': 1501, 'messing': 5008, 'picture': 5861, 'perfect': 5798, 'simpletons': 7255, 'millennials': 5051, 'bitcoin': 911, 'steal': 7606, 'genius': 3394, 'means': 4945, 'smarts': 7353, 'path': 5734, 'fails': 2984, 'unity': 8366, 'cambridge': 1222, 'analytica': 381, 'friend': 3288, 'footballs': 3216, 'plotted': 5944, 'effort': 2677, 'rival': 6741, 'shave': 7150, 'cannabis': 1258, 'halved': 3652, 'convulsions': 1828, 'funded': 3326, 'epilepsy': 2803, 'munchies': 5228, 'famine': 3011, 'sudan': 7738, 'charge': 1420, 'permits': 5806, 'consumer': 1794, 'protection': 6211, 'puts': 6294, 'equifax': 2808, 'hayden': 3724, 'willing': 8741, 'throw': 8039, 'almost': 347, 'anything': 436, 'de': 2105, 'legitimize': 4604, 'portrait': 6023, 'widespread': 8727, 'killings': 4424, 'cast': 1319, 'shadow': 7130, 'laughter': 4539, 'suspected': 7807, 'rebel': 6427, 'planted': 5917, 'mine': 5063, 'yemeni': 8859, 'ship': 7173, 'instant': 4145, 'questioned': 6311, 'nightmares': 5364, 'slogan': 7335, 'drinking': 2576, 'award': 631, 'uplifting': 8406, 'stories': 7656, 'remind': 6542, 'jeremy': 4301, 'scahill': 6919, 'fareed': 3021, 'zakaria': 8877, 'bashes': 743, 'silo': 7248, 'waters': 8635, 'conversation': 1822, 'chocolate': 1484, '63rd': 93, 'straight': 7663, 'quarter': 6305, 'propaganda': 6188, 'residents': 6610, 'presidential': 6103, 'palace': 5655, 'terrorism': 7973, 'percent': 5796, 'murders': 5234, 'newborns': 5336, 'pledged': 5941, 'relief': 6527, 'constipation': 1785, 'loosely': 4733, 'regulated': 6501, 'market': 4870, 'biofuel': 897, 'credits': 1953, 'spurs': 7534, 'speculators': 7478, 'swindlers': 7837, 'polluters': 5987, 'founder': 3254, 'bringing': 1093, 'panthers': 5672, 'pa': 5627, 'start': 7585, 'unborn': 8318, 'unicorns': 8355, 'oversight': 5609, 'fiscal': 3139, 'mob': 5117, 'building': 1133, 'mysterious': 5257, 'artificial': 526, 'worshiping': 8818, '202': 45, 'run': 6824, 'dematerialize': 2217, 'newly': 5338, 'released': 6524, 'howard': 3920, 'stern': 7623, 'tapes': 7890, 'feature': 3054, 'admitting': 221, 'psychological': 6238, 'rt': 6810, 'sputnik': 7535, 'ads': 227, 'interference': 4168, 'yorker': 8869, 'lizza': 4700, 'improper': 4041, 'hippo': 3828, 'katie': 4384, 'incumbent': 4071, '25': 57, 'nibble': 5348, 'blow': 953, 'ukraines': 8306, 'ammunition': 368, 'supplies': 7769, 'cupcake': 2019, 'francis': 3264, 'fights': 3101, 'employees': 2739, 'used': 8424, 'improve': 4042, 'wheelchairs': 8695, 'malls': 4818, 'finds': 3118, 'sloppy': 7337, 'misconduct': 5087, 'handwriting': 3672, 'vice': 8485, 'documentary': 2476, 'worth': 8820, 'pirating': 5893, 'poultry': 6047, 'reviews': 6686, 'guam': 3587, 'stark': 7583, 'quit': 6321, 'allegations': 332, 'sneezing': 7382, 'medicaid': 4959, 'kentucky': 4398, 'slash': 7312, '9000': 117, 'portrays': 6024, 'destroyed': 2293, 'barrage': 728, 'spaghetti': 7456, 'dhs': 2315, 'electronics': 2701, 'expanded': 2900, 'flights': 3171, 'departing': 2247, 'wires': 8761, 'tattoo': 7902, 'gabbanelli': 3345, 'cantabella': 1263, 'accordion': 159, 'sock': 7409, 'mouth': 5201, 'nielsen': 5354, 'never': 5333, 'trumper': 8242, 'barber': 716, 'tame': 7879, 'wades': 8564, 'deeper': 2156, 'hesitation': 3791, 'underwater': 8336, 'preparing': 6092, 'subpoena': 7715, 'memos': 4987, 'gubernatorial': 3594, '400': 75, 'trebek': 8189, 'tries': 8209, 'moderator': 5129, 'sells': 7061, 'jacks': 4267, 'aiming': 297, 'christians': 1496, 'minority': 5075, 'pakistan': 5654, 'affiliated': 252, 'coalition': 1600, 'mulvaney': 5225, 'difficult': 2336, 'casino': 1317, 'manipulate': 4835, 'delousing': 2210, 'rand': 6367, 'arms': 510, 'arabia': 486, 'camels': 1225, 'outcry': 5581, 'infosys': 4113, 'hire': 3830, 'targets': 7898, 'outsourcing': 5592, 'dishwasher': 2412, 'postpones': 6039, 'hearing': 3744, 'personal': 5815, 'facing': 2972, 'felony': 3072, 'united': 8365, 'clown': 1588, 'swaps': 7820, 'beloved': 828, 'burgers': 1156, 'salads': 6858, 'soups': 7443, 'diet': 2332, 'ireland': 4228, 'enda': 2751, 'kenny': 4397, 'rub': 6811, 'jobless': 4321, 'plunge': 5952, 'lowest': 4758, 'weekly': 8666, 'tally': 7878, '1973': 27, 'seals': 7010, 'noun': 5411, 'verb': 8471, 'vladimir': 8532, 'adjective': 211, 'iraq': 4225, 'shopkeeper': 7192, 'such': 7734, 'obvious': 5461, 'lies': 4644, 'catalonia': 1327, 'puigdemont': 6256, 'defeat': 2160, 'spanish': 7459, 'raffle': 6346, 'real': 6414, 'superman': 7765, 'spiderman': 7497, 'propose': 6194, 'requiring': 6599, 'fair': 2988, 'prices': 6120, 'taxpayer': 7911, 'drugs': 2593, 'highs': 3809, 'shady': 7132, 'dealings': 2113, 'evoke': 2861, 'nepotism': 5319, 'corruption': 1869, 'gilded': 3427, 'snack': 7370, 'bound': 1031, 'singing': 7263, 'couple': 1901, 'rented': 6562, 'condo': 1729, 'pays': 5757, 'fine': 3119, 'condor': 1730, 'happy': 3680, 'europe': 2843, 'peanuts': 5763, 'lynch': 4773, 'prosecution': 6200, 'pleas': 5937, 'chauvinist': 1434, 'greeted': 3554, 'selfies': 7057, 'arrival': 519, 'english': 2773, 'speaking': 7473, 'powerful': 6054, 'stepping': 7618, 'evolution': 2862, 'ignored': 3991, 'fraudulent': 3273, 'comments': 1673, 'scoundrel': 6974, 'upcoming': 8398, 'karaoke': 4380, 'deputy': 2266, 'felt': 3073, 'pressured': 6107, 'christopher': 1499, 'wray': 8827, 'wasserman': 8623, 'schultz': 6957, 'pimple': 5880, 'throws': 8043, 'pitcher': 5898, 'bathtub': 757, 'admits': 219, 'conversations': 1823, 'taunts': 7904, 'teach': 7915, 'partisanship': 5712, 'phonebook': 5842, 'decided': 2133, 'disband': 2382, 'claimed': 1531, 'disbanded': 2383, 'guggenheim': 3599, 'gogh': 3472, 'toilet': 8087, 'target': 7895, 'coordination': 1841, 'expert': 2916, 'decorator': 2149, 'wrestling': 8835, 'championship': 1403, 'dirt': 2367, 'ag': 264, 'tarmac': 7900, 'innocuous': 4129, 'teleportation': 7936, 'canceled': 1246, 'stolen': 7643, 'lennon': 4607, 'items': 4257, 'recovered': 6452, 'berlin': 843, 'tub': 8255, 'corbyn': 1849, 'woos': 8797, 'small': 7351, 'crackdown': 1924, 'payments': 5754, 'deliveries': 2206, 'enrique': 2782, 'peña': 5833, 'nieto': 5355, 'cancels': 1249, 'planned': 5913, 'passed': 5719, 'detector': 2301, 'which': 8699, 'unprotected': 8381, 'met': 5009, 'breitbart': 1073, '45': 81, 'trafficked': 8156, 'website': 8659, 'beats': 782, 'huffpo': 3927, 'wapo': 8593, 'foxnews': 3259, 'pageviews': 5643, 'owns': 5624, 'gina': 3431, 'haspel': 3704, 'lean': 4574, 'confectioner': 1732, 'transcript': 8165, 'stoneman': 7646, 'hall': 3647, 'repeatedly': 6571, 'shouts': 7206, 'raucous': 6394, 'panda': 5664, 'green': 3548, 'introduces': 4189, 'articles': 525, 'stole': 7642, 'banks': 705, 'incompetence': 4065, 'profit': 6166, 'divisive': 2464, 'brands': 1053, 'acronyms': 183, 'strategy': 7668, 'afghanistan': 257, 'figure': 3102, 'heather': 3752, 'heyer': 3795, 'funeral': 3331, 'proposition': 6197, 'trending': 8196, 'st': 7546, 'patrick': 5740, 'clover': 1587, 'confusion': 1756, 'sexist': 7120, 'row': 6805, 'catawampus': 1330, 'eurosceptic': 2845, 'govt': 3504, 'linebacker': 4668, 'watchdog': 8627, 'actress': 196, 'intellectual': 4157, 'righ': 6722, 'dinosaurs': 2349, 'swalwell': 7815, 'dares': 2076, 'declassify': 2143, 'backing': 652, 'amputations': 375, 'arab': 485, 'qatar': 6300, 'memoir': 4983, 'reveal': 6675, 'barred': 729, 'opinions': 5527, 'publisher': 6247, 'expelled': 2910, 'monkey': 5152, 'tuesday': 8257, 'indiana': 4080, 'ohio': 5491, 'carolina': 1292, 'furniture': 3335, 'plastic': 5919, 'pollution': 5988, 'wildlife': 8738, 'scotland': 6969, 'beautiful': 783, 'beaches': 769, 'tourist': 8130, 'juanita': 4347, 'broaddrick': 1101, 'handler': 3667, 'raped': 6376, 'ghost': 3412, 'stars': 7584, 'nudists': 5423, 'climber': 1566, 'penalty': 5777, 'rapists': 6378, 'legalizes': 4599, '418m': 77, 'sale': 6863, 'kenya': 4399, 'paraplegic': 5691, 'smokes': 7363, 'constitutional': 1789, 'verge': 8473, 'anniversary': 407, 'barcelona': 719, 'avoiding': 627, 'button': 1188, 'bigger': 877, 'yvette': 8876, 'cooper': 1838, 'urgent': 8417, 'commons': 1682, 'ending': 2756, 'reset': 6606, 'knife': 4454, 'fentanyl': 3080, 'deaths': 2118, 'outpace': 5586, 'prescription': 6095, 'painkiller': 5648, 'overdoses': 5601, 'chainsaw': 1392, 'cpac': 1921, 'identity': 3981, 'inviting': 4211, 'milo': 5057, 'symptom': 7849, 'ails': 294, 'conservatism': 1775, 'disinviting': 2416, 'raccoons': 6330, 'infuriated': 4117, 'refusal': 6489, 'preview': 6117, 'sleepover': 7320, 'indonesia': 4088, 'estate': 2834, 'project': 6174, 'confuses': 1755, 'curb': 2021, 'cookies': 1833, 'pillow': 5876, 'animal': 397, 'metoo': 5013, 'actual': 198, 'rebels': 6428, 'operation': 5524, 'idlib': 3985, 'drain': 2551, 'swamp': 7816, 'diverted': 2457, 'tissue': 8076, 'botches': 1022, 'beginning': 809, 'deliver': 2204, 'paychecks': 5751, 'babies': 641, 'dutch': 2620, 'pushups': 6290, 'toupees': 8127, 'undocumented': 8340, 'backbone': 646, 'dairies': 2055, 'trouble': 8230, 'staying': 7601, 'focused': 3201, 'indictments': 4084, 'recipes': 6441, 'curved': 2032, 'penises': 5785, 'greater': 3544, 'angles': 395, 'gluten': 3457, 'empathy': 2736, 'argument': 498, 'brings': 1094, 'approach': 475, 'jiggle': 4312, 'date': 2086, 'announce': 408, 'monday': 5147, 'tuna': 8262, 'burger': 1155, 'pushes': 6288, 'section': 7031, '301': 64, 'trail': 8158, 'revealing': 6677, 'secrets': 7030, 'ignorance': 3989, 'alternative': 354, 'scandel': 6929, 'pug': 6254, 'snubs': 7398, 'mummy': 5227, 'praise': 6059, 'witches': 8770, 'excited': 2877, 'replace': 6574, 'kidnap': 4416, 'banksy': 706, 'bethlehem': 853, 'worst': 8819, 'speedy': 7484, 'conflicts': 1749, 'interest': 4164, 'infant': 4093, 'await': 629, 'countermemo': 1891, 'languishes': 4513, 'truth': 8250, 'assange': 541, 'sycophant': 7843, 'delicatessens': 2200, 'marathon': 4853, 'rough': 6796, 'appointments': 473, 'prioritize': 6132, 'crucifix': 1995, 'explain': 2918, 'bacon': 660, 'admonish': 222, 'pudding': 6250, 'squatting': 7538, 'mission': 5102, 'accomplished': 156, 'bombing': 981, 'thought': 8024, 'unlike': 8372, 'share': 7143, 'sensitive': 7076, 'blonde': 948, 'sanitary': 6890, 'pads': 5639, 'being': 818, 'collected': 1628, 'reactor': 6404, 'dark': 2077, 'moods': 5165, 'scrutiny': 6997, 'shadowy': 7131, 'pants': 5675, 'beto': 854, 'rourke': 6802, 'cruz': 2003, 'laps': 4517, 'where': 8697, 'learned': 4577, 'love': 4750, 'assail': 540, 'unilateralism': 8357, 'culture': 2016, 'tepco': 7962, 'bosses': 1018, 'plant': 5916, 'crooks': 1982, 'mere': 4997, 'counterspies': 1893, 'temer': 7941, 'passive': 5724, 'aggressiveness': 277, 'capturing': 1275, 'creditors': 1952, 'hip': 3825, 'hop': 3883, 'lyrics': 4774, 'mommy': 5145, 'protester': 6218, 'escorted': 2828, '39': 73, 'deer': 2157, 'daunting': 2092, 'list': 4683, 'nkorea': 5371, 'dances': 2068, 'letting': 4619, 'go': 3460, 'television': 7937, 'criminal': 1962, 'carriers': 1300, 'operate': 5523, 'noodles': 5391, 'stopped': 7652, 'then': 8003, 'cop': 1844, 'punched': 6267, 'choked': 1487, 'shot': 7200, 'proposals': 6193, 'improving': 4046, 'systems': 7855, 'edition': 2669, 'beast': 778, 'remake': 6536, 'embrace': 2723, 'signaling': 7237, 'skill': 7293, 'turning': 8270, 'awards': 632, 'counter': 1890, 'pooch': 5999, 'warren': 8609, 'buffett': 1129, 'berkshire': 842, 'hathaway': 3712, 'dumps': 2614, 'vampire': 8445, 'hello': 3768, 'called': 1217, 'cellphone': 1366, 'blows': 956, 'background': 651, 'earlier': 2636, 'acknowledged': 176, 'skinny': 7296, 'spiral': 7505, 'muslim': 5244, 'videos': 8491, 'produce': 6157, 'slump': 7347, 'remington': 6544, 'files': 3106, 'tumble': 8259, 'bayonet': 764, 'challenge': 1397, 'arkansas': 502, 'medication': 4962, 'raps': 6380, 'retreat': 6663, 'finland': 3126, 'colombian': 1641, 'farc': 3020, 'final': 3111, 'calendar': 1213, 'meat': 4950, 'janitor': 4282, 'nap': 5274, 'sue': 7741, 'approving': 481, 'holocaust': 3860, 'denier': 2232, 'chooses': 1492, 'seems': 7046, 'backup': 658, 'mitch': 5110, 'bathe': 751, 'koch': 4463, 'brothers': 1115, 'loyal': 4759, 'servants': 7097, 'serving': 7103, 'sisters': 7273, 'relevance': 6526, 'reject': 6513, 'isolationism': 4246, 'cheeseburgers': 1450, 'left': 4589, 'pundits': 6272, 'drooled': 2587, 'puns': 6276, 'tracking': 8149, 'dystopia': 2631, 'pivots': 5901, 'insanity': 4133, 'finally': 3113, 'universal': 8367, 'everyone': 2857, 'margarita': 4860, 'blast': 929, 'kurdish': 4476, 'diyarbakir': 2467, 'conway': 1829, 'gaining': 3351, 'steam': 7608, 'trains': 8164, 'ancient': 385, 'frozen': 3305, 'tomb': 8096, 'scythian': 7003, 'siberia': 7227, 'alligator': 336, 'inflammatory': 4098, 'offensive': 5475, 'aborts': 132, 'pregnancy': 6083, 'center': 1376, 'clients': 1562, 'rely': 6532, 'upbeat': 8397, 'victims': 8488, 'loot': 4734, 'burn': 1160, 'collision': 1636, 'directive': 2363, 'airport': 303, 'turmoil': 8268, 'mounts': 5196, 'hats': 3714, 'funerals': 3332, 'weight': 8671, 'soldiers': 7415, 'took': 8101, 'night': 5361, 'addicts': 206, 'easy': 2651, 'slaughterhouse': 7314, 'employed': 2737, 'illegal': 3997, 'clones': 1573, 'dr': 2545, 'congo': 1758, '250': 58, 'ethnic': 2839, 'massacres': 4894, 'talking': 7876, 'sure': 7782, 'wire': 8760, 'diaper': 2319, 'fellow': 3070, 'impossible': 4037, 'onto': 5514, 'removing': 6552, 'costume': 1879, 'ad': 200, 'calling': 1218, 'complicit': 1706, 'dieting': 2333, 'japanese': 4286, 'ministry': 5072, 'proposed': 6195, 'cover': 1911, 'land': 4500, 'heart': 3747, 'mao': 4849, 'stalin': 7566, 'authoritarianism': 610, '101': 6, 'kasich': 4381, 'hickenlooper': 3800, '2020': 46, 'happen': 3675, 'fail': 2980, 'glitch': 3451, 'lets': 4616, 'corporations': 1862, 'infra': 4115, 'ultrasonic': 8308, 'waves': 8637, 'responsible': 6632, 'cuba': 2007, 'bat': 749, 'gaffe': 3348, 'product': 6161, 'fit': 3146, 'pigeons': 5868, 'publishes': 6249, 'trigger': 8210, 'article': 524, 'kitty': 4448, 'missouri': 5104, 'spit': 7509, 'half': 3646, 'poverty': 6050, 'discrimination': 2400, 'balloons': 687, 'unsolved': 8385, 'dilemma': 2340, 'inflict': 4101, 'pain': 5646, 'admit': 218, 'roasting': 6750, 'young': 8872, 'afghans': 258, 'taliban': 7874, 'quack': 6302, 'session': 7105, 'protest': 6216, 'nomination': 5381, 'kimmel': 4430, 'using': 8430, 'medical': 4960, 'score': 6966, 'penguin': 5781, 'allowing': 342, 'darkest': 2078, 'spent': 7491, '230k': 53, 'covering': 1914, 'fees': 3067, 'britches': 1096, 'norwegians': 5401, 'hole': 3856, 'takeaways': 7867, 'startling': 7587, 'priority': 6133, 'safer': 6853, 'partying': 5716, 'beacon': 770, 'initial': 4121, 'fusion': 3340, 'gps': 3507, 'research': 6602, 'convention': 1820, 'unplumbed': 8379, 'depths': 2265, 'sinks': 7269, 'wacko': 8562, 'caps': 1270, 'form': 3243, 'assault': 546, 'carve': 1313, 'glacier': 3444, 'exists': 2896, '70': 99, 'die': 2328, 'adulthood': 228, 'insists': 4139, 'someday': 7419, 'dictators': 2325, 'tweetstorms': 8287, 'briefings': 1090, 'shirt': 7177, 'zuckerberg': 8899, 'officially': 5485, 'gates': 3378, 'rain': 6354, 'snap': 7376, 'cbo': 1353, 'premiums': 6086, 'expensive': 2913, '140': 16, 'buried': 1158, 'landslide': 4510, 'destroys': 2294, 'village': 8499, 'southwest': 7449, 'toys': 8145, 'leprechauns': 4610, 'chuck': 1500, 'grandmother': 3526, 'kicked': 4413, 'caucus': 1341, 'positive': 6032, 'trevor': 8197, 'noah': 5374, 'destroye': 2292, 'delusional': 2212, 'kanye': 4378, 'saying': 6917, 'slavery': 7315, 'choice': 1485, 'evasion': 2848, 'splatters': 7514, 'gillespie': 3428, 'declined': 2144, 'grandchildren': 3522, 'asylums': 567, 'built': 1135, 'fairy': 2990, 'focus': 3200, 'slobbering': 7334, 'onion': 5508, 'impeach': 4020, 'exam': 2867, 'aceh': 171, 'canes': 1256, 'couples': 1902, 'affection': 251, 'sadism': 6850, 'hosed': 3897, 'entitlements': 2792, 'quarterbacks': 6307, 'preps': 6093, 'thaad': 7988, 'kimchi': 4429, 'lashes': 4526, 'rebuff': 6429, 'passes': 5721, 'ask': 532, 'frogs': 3297, 'player': 5926, 'erick': 2817, 'erickson': 2818, 'teapot': 7921, 'carson': 1305, 'proposes': 6196, 'poor': 6004, 'rent': 6559, 'landlord': 4503, 'memorials': 4985, 'created': 1941, 'remembered': 6541, 'nobel': 5375, 'donkey': 2507, 'falls': 3002, 'short': 7195, 'drink': 2575, 'residence': 6608, 'bigfoot': 876, 'here': 3781, 'expect': 2903, 'apple': 468, 'event': 2853, 'ios': 4216, 'macbooks': 4777, 'ipads': 4218, 'century': 1380, 'unacceptable': 8314, 'unable': 8313, 'gas': 3376, 'risks': 6738, 'single': 7264, 'graph': 3534, 'song': 7426, 'file': 3104, 'irs': 4236, 'clock': 1571, 'devin': 2312, 'discredit': 2398, 'instead': 4146, 'proved': 6223, 'something': 7422, 'carter': 1307, 'collapses': 1625, 'dehydration': 2189, 'overeating': 5602, 'brother': 1114, 'sentenced': 7079, 'related': 6517, 'glowing': 3455, 'losing': 4741, 'failing': 2982, 'lay': 4559, 'including': 4061, 'caterers': 1333, 'probing': 6147, 'fends': 3079, 'fury': 3339, 'abroad': 135, 'laughs': 4538, 'fawning': 3046, 'borscht': 1015, 'regained': 6494, 'hamster': 3661, 'remove': 6549, 'hungary': 3945, 'university': 8370, 'ngos': 5345, 'hungry': 3947, 'catcher': 1331, 'cootie': 1842, 'id': 3975, 'botch': 1020, 'nomorenazi': 5384, 'sparks': 7467, 'online': 5509, 'backlash': 653, 'agent': 273, 'communications': 1685, 'kennel': 4396, 'heal': 3736, 'daughter': 2090, 'leads': 4568, 'polluted': 5986, 'minds': 5062, 'oklahoma': 5494, 'prostitution': 6207, 'pathetic': 5735, 'assimilation': 556, 'morally': 5174, 'unfit': 8348, 'scathing': 6937, 'intensifies': 4159, 'criticism': 1973, 'investigating': 4198, 'links': 4676, 'cats': 1339, 'nawaz': 5297, 'sharif': 7146, 'disqualified': 2433, 'sports': 7523, 'australian': 605, 'unveils': 8392, 'kangaroo': 4376, 'carl': 1287, 'higbie': 3805, 'racist': 6338, 'paints': 5652, 'presidents': 6104, '31': 65, 'fund': 3325, 'headache': 3730, 'appalling': 453, 'bolton': 976, 'exhibit': 2890, 'citizens': 1524, 'returning': 6668, 'dishes': 2410, 'believes': 825, 'exonerating': 2898, 'thrown': 8042, 'glen': 3448, 'campbell': 1232, '81': 107, 'pinecone': 5885, 'signs': 7240, 'upgrade': 8403, 'martin': 4883, 'luther': 4769, 'birthplace': 906, 'historic': 3836, 'crib': 1956, 'aggressive': 276, 'schedule': 6943, 'develop': 2308, 'submarine': 7712, 'lookalikes': 4724, 'pretended': 6110, 'hong': 3871, 'kong': 4466, 'jewel': 4309, 'nevertrump': 5334, 'columnist': 1649, 'bananas': 694, 'cookoff': 1835, 'dick': 2323, 'cheney': 1457, 'restarting': 6634, 'torture': 8113, 'interrogation': 4175, 'program': 6168, 'turtle': 8275, 'basically': 746, 'me': 4941, 'help': 3769, 'reelected': 6469, 'dawdling': 2098, 'tests': 7982, 'patience': 5737, 'ketchup': 4403, 'searchable': 7014, 'archive': 491, 'buttons': 1189, 'doll': 2492, 'begs': 811, 'number': 5429, 'zones': 8893, 'rises': 6735, 'chef': 1453, 'louise': 4748, 'slaughter': 7313, 'champion': 1402, '88': 112, 'beef': 796, 'feels': 3066, 'vindicated': 8504, 'pet': 5823, 'detractors': 2303, 'weigh': 8669, 'female': 3075, 'whines': 8704, 'professor': 6165, 'incites': 4059, 'riot': 6729, '67': 97, 'politicians': 5979, 'voted': 8547, 'robots': 6758, 'george': 3400, 'bust': 1176, 'revises': 6689, 'conservation': 1774, 'sage': 6855, 'grouse': 3583, 'hunting': 3952, 'timeline': 8065, 'chemical': 1456, 'salsa': 6872, 'trainer': 8162, 'mourns': 5198, 'unarmed': 8315, 'nominees': 5383, 'sweep': 7828, 'dust': 2618, 'headlines': 3733, '2011': 39, 'spur': 7533, 'goldfish': 3477, 'disappearing': 2375, 'seagrass': 7006, 'protects': 6215, 'pathogens': 5736, 'surfers': 7786, 'obscenity': 5455, 'believe': 823, 'interfere': 4166, 'pastries': 5730, 'cnnpolitics': 1596, 'com': 1650, 'shower': 7212, 'caught': 1342, 'greece': 3546, 'laundering': 4543, 'hotdogs': 3907, 'issue': 4249, 'executive': 2884, 'lgbtq': 4626, 'ninjas': 5368, 'reckoning': 6443, 'dream': 2562, 'act': 185, 'manufacturing': 4846, 'slows': 7345, 'forecast': 3228, 'december': 2131, 'rose': 6791, 'africa': 259, 'existing': 2895, 'agreements': 284, 'underwear': 8337, 'complex': 1703, 'scramble': 6978, 'endures': 2760, 'highlights': 3808, 'split': 7515, 'paralyze': 5688, 'interviewed': 4180, 'rosenstein': 6793, 'summer': 7753, 'tortured': 8114, 'tucker': 8256, 'carlson': 1288, 'braincells': 1049, 'homosexuals': 3869, 'chechnya': 1441, 'concentration': 1714, 'suffer': 7743, 'electrocution': 2700, 'fatal': 3035, 'beatings': 781, 'anonymously': 417, 'texting': 7986, 'scrubdown': 6995, 'arthur': 523, 'backer': 648, 'conga': 1757, 'deserve': 2278, 'hampshire': 3659, 'iowa': 4217, 'eyes': 2963, 'loom': 4728, 'rigs': 6726, 'bamboozle': 690, 'obscene': 5454, 'masquerade': 4892, 'criticised': 1972, 'douma': 2532, 'lt': 4761, 'gov': 3498, 'dan': 2062, 'games': 3363, 'shootings': 7190, 'lunches': 4767, 'indie': 4085, 'drama': 2553, 'cannes': 1259, 'banana': 693, 'fleet': 3165, 'whale': 8691, 'seahorse': 7008, 'flexes': 3167, 'muscle': 5237, 'coracobrachialis': 1848, 'defers': 2172, 'surgery': 7789, 'facial': 2969, 'crimea': 1960, 'ambitions': 361, 'jason': 4289, 'chaffetz': 1390, 'invents': 4194, 'housing': 3918, 'ignoring': 3993, 'utah': 8432, 'doughnut': 2529, 'atlantic': 573, 'walls': 8583, 'giuliani': 3439, 'terrorist': 7974, 'pre': 6074, 'pens': 5789, 'apologize': 450, 'fever': 3088, 'hay': 3723, 'cataclysm': 1323, 'dc': 2102, 'intoxicates': 4185, '900': 116, 'palestinians': 5657, 'converge': 1821, 'fence': 3077, 'ants': 430, 'winter': 8757, 'stepped': 7617, 'dancers': 2067, 'wilbur': 8735, 'surprised': 7791, 'mummies': 5226, 'mice': 5020, 'tie': 8054, 'randomly': 6368, 'pulling': 6260, 'name': 5269, 'ditch': 2452, 'price': 6119, 'crimping': 1966, 'hamburger': 3656, 'sounds': 7441, 'writer': 8838, 'hear': 3742, 'arguments': 499, 'undisclosed': 8338, 'contacts': 1797, 'bookmakers': 997, 'chaos': 1417, 'jelly': 4298, 'gig': 3422, 'obstacles': 5459, 'working': 8806, 'porter': 6021, 'resigned': 6613, 'totally': 8119, 'spousal': 7526, 'leadership': 4566, 'flew': 3166, 'expense': 2912, 'nobost': 5377, 'cared': 1282, 'geese': 3388, 'sideways': 7233, 'defending': 2167, 'bernstein': 846, 'ballgame': 684, 'boosting': 1007, '53': 86, 'skunked': 7302, 'pockets': 5956, 'silent': 7244, 'bagel': 666, 'scots': 6970, 'fully': 3321, 'engaged': 2768, 'scottish': 6972, 'independence': 4075, 'manhunt': 4832, 'leaker': 4572, 'gave': 3380, 'wikileaks': 8733, 'mexicans': 5015, 'prospect': 6203, 'deportee': 2259, 'glasses': 3446, 'closets': 1580, 'baked': 673, 'uber': 8300, 'cto': 2006, 'email': 2714, 'techno': 7926, 'gain': 3350, 'votes': 8551, 'slot': 7338, 'penguins': 5782, 'exclusive': 2879, 'example': 2870, 'sweden': 7826, 'bum': 1144, 'approves': 480, 'installment': 4144, 'disaster': 2379, 'markets': 4872, 'mideast': 5029, 'modest': 5132, 'drop': 2588, 'temperatures': 7943, 'astronaut': 564, 'peggy': 5771, 'whitson': 8714, 'dangerous': 2072, 'fresno': 3286, 'spree': 7530, 'custody': 2034, 'pajamas': 5653, 'tremendous': 8194, 'anger': 393, 'wife': 8729, 'trudeau': 8237, 'decides': 2134, 'poke': 5967, 'grizzly': 3568, 'seats': 7023, 'bargain': 722, 'snooze': 7388, 'emmanuel': 2730, 'bread': 1061, 'monsanto': 5155, 'manufactured': 4845, 'studies': 7699, 'chimpanzees': 1477, 'oregon': 5549, 'sues': 7742, 'kroger': 4472, 'refusing': 6492, 'shotgun': 7201, 'shells': 7159, 'weddings': 8661, 'cim': 1512, '600': 91, 'jpmorgan': 4344, 'loan': 4702, 'brooklyn': 1111, 'site': 7277, 'cracks': 1927, 'hospitalization': 3899, 'eyebrows': 2957, 'migrants': 5039, 'begun': 812, 'pineapples': 5884, 'legend': 4600, 'zelda': 8882, 'gaming': 3364, 'reddit': 6460, 'permissive': 5804, 'attitude': 589, 'poisoning': 5965, 'internet': 4173, 'society': 7407, 'labour': 4487, 'leap': 4575, 'judgement': 4349, 'condemning': 1725, 'lights': 4652, 'earthquake': 2643, 'sichuan': 7228, 'suspend': 7809, 'shuts': 7226, 'spank': 7460, 'memorial': 4984, 'honors': 3876, 'himself': 3821, 'fries': 3292, 'schoolboys': 6954, 'enduring': 2761, 'cycle': 2044, 'fugu': 3317, 'freakout': 3275, 'blowfish': 954, 'poisonous': 5966, 'inflate': 4099, 'rifle': 6718, 'joked': 4334, 'overturned': 5616, 'spatula': 7470, 'au': 596, 'fighting': 3100, 'whining': 8705, 'integrity': 4155, 'dershowitz': 2269, 'praises': 6061, 'place': 5906, 'hatred': 3713, 'cheddar': 1445, 'affirms': 254, 'reluctantly': 6531, 'monkeys': 5153, 'envies': 2794, 'preserves': 6100, 'mars': 4878, 'asteroid': 561, 'mourning': 5197, '773': 104, 'camera': 1226, 'sending': 7070, 'powder': 6051, 'apartment': 442, 'crackhouse': 1926, 'shares': 7145, 'questioning': 6312, 'pick': 5854, 'defied': 2177, 'pursuing': 6285, 'dengue': 2228, 'immunization': 4016, 'yogurt': 8866, 'ostriches': 5567, 'sit': 7274, 'dress': 2568, 'cup': 2018, 'players': 5927, 'cafeteria': 1205, 'doctor': 2474, 'shortage': 7196, 'rural': 6829, 'whiskey': 8709, 'houseplant': 3915, 'fukushima': 3319, 'executives': 2885, 'disney': 2424, 'bonus': 991, 'depends': 2250, 'signing': 7239, 'wage': 8566, 'contract': 1809, 'gym': 3617, 'kellyanne': 4394, 'mostly': 5186, '199': 29, 'hilarious': 3815, 'ariana': 500, 'grande': 3523, 'concert': 1717, 'explosions': 2930, 'confirmed': 1744, 'fatalities': 3036, 'bumblebees': 1146, 'jim': 4316, 'carrey': 1296, 'eyeful': 2959, 'crotch': 1987, 'text': 7985, 'kusher': 4479, 'whopper': 8719, 'absent': 138, 'annual': 414, 'rocks': 6760, 'lit': 4688, 'wick': 8723, 'agency': 270, 'candles': 1254, 'comprehend': 1709, 'manchester': 4825, 'confirm': 1742, 'schoolgirl': 6955, 'eilidh': 2687, 'macleod': 4781, '14': 15, 'arena': 495, 'terrier': 7969, 'toes': 8085, 'prankster': 6068, 'pretending': 6111, 'reince': 6510, 'priebus': 6122, 'confrontational': 1752, 'enabled': 2745, 'timidity': 8067, 'elijah': 2707, 'cummings': 2017, 'advisors': 239, 'morphed': 5178, 'fission': 3144, 'famous': 3012, 'descent': 2271, 'socialist': 7406, 'hell': 3767, 'utopia': 8434, 'gao': 3368, 'dispute': 2431, 'armando': 505, 'iannucci': 3969, 'highway': 3810, 'nowhere': 5415, 'think': 8017, 'cowardice': 1916, 'pandas': 5665, 'oversee': 5606, 'rum': 6820, 'useless': 8426, 'zealand': 8879, 'involved': 4213, 'incident': 4056, 'fame': 3007, 'pompadours': 5992, 'statue': 7597, 'vandalize': 8450, 'apparel': 454, 'vocals': 8534, 'bar': 711, 'defamation': 2159, 'settlements': 7111, 'body': 969, 'cocktail': 1610, 'ways': 8642, 'figures': 3103, 'jerry': 4303, 'brown': 1117, 'salt': 6873, 'womensmarch': 8792, 'kitchens': 4444, 'oliver': 5500, 'users': 8427, 'sacrifices': 6846, 'ucla': 8302, 'dungeon': 2616, 'happiness': 3679, 'paraquat': 5692, 'recover': 6451, 'herpes': 3787, 'fantastic': 3016, 'overseeing': 5607, 'renovate': 6557, 'kitten': 4446, 'actions': 189, 'vetting': 8484, 'rebuilding': 6430, 'dodging': 2482, 'gangsters': 3367, 'courthouse': 1908, 'firefight': 3131, 'canaries': 1242, 'eyelashes': 2960, '180': 22, 'degree': 2187, 'shift': 7168, 'geopolitical': 3399, 'whiplash': 8708, 'diapers': 2320, 'emojis': 2733, 'ax': 637, 'policing': 5973, 'funds': 3330, 'pulls': 6262, 'pact': 5636, 'preferred': 6081, 'roadside': 6748, 'bombings': 982, 'linguistic': 4671, 'speaks': 7474, 'grade': 3510, 'coworker': 1917, 'bookstore': 999, 'tehran': 7935, 'garden': 3373, 'opens': 5521, 'censorship': 1372, 'virtual': 8520, 'stakes': 7564, 'bungle': 1149, 'roundness': 6800, 'soaring': 7402, 'imports': 4033, 'hamas': 3655, 'cooking': 1834, 'indonesian': 4089, 'jakarta': 4276, 'pollsters': 5985, 'eats': 2655, 'spain': 7457, 'uncertainty': 8320, 'future': 3341, 'jfk': 4311, 'stewardesses': 7627, 'offense': 5474, 'loretta': 4735, 'volleyball': 8539, 'rob': 6752, 'anomaly': 415, 'symbol': 7845, 'trumpism': 8244, 'midlife': 5033, 'overstepped': 5610, 'stairs': 7562, 'beijing': 817, 'hurt': 3955, 'cynically': 2046, 'boosters': 1006, 'eyelid': 2961, 'livestock': 4696, 'cuban': 2008, 'changed': 1409, 'aim': 295, 'halt': 3650, 'catalan': 1324, 'maryam': 4885, 'mirzakhani': 5084, 'fields': 3094, '40': 74, 'landscaper': 4508, 'disorder': 2426, 'mimics': 5060, 'parkinson': 5700, 'pasta': 5728, 'vomits': 8544, 'vancouver': 8449, 'fifa': 3096, 'itself': 4259, 'inspired': 4142, 'consider': 1778, 'respond': 6627, 'nukes': 5427, 'objectify': 5452, 'pushed': 6287, 'several': 7116, 'dollars': 2494, 'seconds': 7026, 'sows': 7452, 'avert': 625, 'seed': 7039, 'gen': 3390, 'honorable': 3873, 'homes': 3866, 'manners': 4839, 'snoop': 7387, 'dogg': 2486, 'loving': 4754, 'industrial': 4090, 'revolutions': 6698, 'wrecking': 8829, 'balls': 689, 'feminists': 3076, 'moab': 5115, 'aftermath': 263, 'tours': 8132, 'dropped': 2589, 'handkerchief': 3665, 'eyelids': 2962, 'abolish': 129, 'mentioned': 4993, 'disclosure': 2390, 'allowance': 340, 'speaker': 7472, 'unraveling': 8382, 'string': 7681, 'chats': 1432, 'briefly': 1091, 'vietnam': 8492, 'paramour': 5689, 'slapped': 7309, 'walks': 8579, '35': 67, 'sentence': 7078, 'sleeping': 7319, 'package': 5633, 'resolve': 6621, 'pretzel': 6114, 'taxi': 7907, 'cheese': 1448, 'formally': 3244, 'roll': 6772, 'stamp': 7571, 'honest': 3870, 'scares': 6935, 'gabbard': 3346, 'dated': 2087, 'spas': 7469, 'preserve': 6099, 'kumquats': 4475, 'exact': 2865, 'labradors': 4489, 'revive': 6691, 'goldmine': 3479, 'tips': 8073, 'toupee': 8126, 'billions': 889, 'nigel': 5356, 'farage': 3019, 'julian': 4357, 'mammals': 4820, 'strongly': 7692, 'defend': 2166, 'revise': 6687, 'quota': 6325, 'showing': 7215, 'minimum': 5067, 'wages': 8567, 'chanted': 1415, 'michigan': 5023, 'baby': 643, 'taxpayers': 7912, 'bang': 696, 'buck': 1123, 'squeeze': 7539, 'alek': 317, 'manassian': 4824, 'identified': 3978, 'toronto': 8111, 'attacker': 579, 'goose': 3490, 'subservient': 7720, 'property': 6191, 'exposed': 2934, 'peddle': 5766, 'ponies': 5995, 'master': 4902, 'destiny': 2290, 'oracles': 5540, 'rave': 6395, 'expel': 2909, 'surprises': 7792, 'buddies': 1125, 'tn': 8077, 'veto': 8481, 'illiteracy': 4000, 'aliens': 326, 'legalized': 4598, 'sacrificing': 6848, 'dinosaur': 2348, 'unless': 8371, 'compelled': 1693, 'feb': 3056, '28': 59, '02': 1, 'et': 2836, 'asking': 534, 'knew': 4453, 'hacked': 3624, 'incoherent': 4062, 'dipsomaniac': 2357, 'serbian': 7087, 'montenegro': 5159, 'grenade': 3557, 'flowers': 3192, 'marchers': 4857, 'threaten': 8029, 'pigeon': 5867, 'upgrading': 8404, 'cheque': 1458, 'envoy': 2798, 'trophy': 8229, 'emu': 2743, 'groomer': 3572, 'slayer': 7317, 'dragon': 2550, 'hyperplasia': 3965, 'patchwork': 5733, 'likes': 4656, 'understands': 8335, 'justified': 4370, 'prancing': 6065, 'anecdote': 390, 'unmasks': 8375, 'dehumanization': 2188, 'eyebrow': 2956, 'puppy': 6280, 'switch': 7839, 'obsolete': 5458, 'protractor': 6221, 'pours': 6049, 'lipinski': 4678, 'keys': 4407, 'cheeseburger': 1449, 'continue': 1806, 'indefinitely': 4074, 'zombies': 8891, 'employers': 2740, 'exemption': 2886, 'birth': 903, 'immoral': 4015, 'establishment': 2833, 'opened': 5519, 'implying': 4030, 'non': 5385, 'booze': 1008, 'nerd': 5320, 'wasps': 8622, 'cory': 1871, 'booker': 996, 'posturing': 6041, 'boa': 960, 'britain': 1095, 'able': 128, 'regulations': 6503, 'multiple': 5224, 'thailand': 7989, 'injure': 4123, 'taco': 7861, 'begging': 808, 'bets': 857, 'punchline': 6270, 'franks': 3269, 'carry': 1302, 'groceries': 3569, 'bustier': 1177, 'tony': 8099, 'blair': 921, 'intervention': 4178, 'joys': 4343, 'comparison': 1692, 'replacement': 6576, 'terrible': 7968, 'spark': 7464, 'strain': 7664, 'relationships': 6519, 'imploded': 4028, 'gohmert': 3473, 'mcauliffe': 4929, 'facilitating': 2970, 'creationist': 1944, 'strict': 7678, 'rudy': 6815, 'divorced': 2466, 'judith': 4354, 'falling': 2999, 'unemployment': 8344, 'payrolls': 5756, 'add': 204, '138': 13, 'reservoir': 6605, 'scare': 6932, 'asylum': 566, 'furry': 3337, 'maduro': 4788, 'banger': 697, 'misguided': 5089, 'violation': 8508, 'cheer': 1446, 'curfew': 2024, '36': 69, 'popcorn': 6006, 'certainly': 1386, 'meant': 4946, 'disrespect': 2434, 'pose': 6026, 'photo': 5846, 'respect': 6626, 'disclosed': 2388, 'confidential': 1741, 'zebras': 8881, 'ed': 2665, 'sunshine': 7760, 'unveil': 8391, 'punishing': 6275, 'thursday': 8046, 'chores': 1493, 'cbs': 1354, 'overall': 5598, '38': 72, 'confetti': 1739, 'smile': 7360, 'poses': 6028, 'models': 5127, 'austrian': 607, 'crossing': 1986, 'italy': 4255, 'sword': 7840, 'barn': 724, 'grill': 3562, 'frankfurters': 3268, 'grigory': 3561, 'rodchenkov': 6762, 'whistleblower': 8711, 'cheats': 1439, 'whistles': 8712, 'reacts': 6405, 'applauds': 466, 'trash': 8175, 'witnessing': 8782, 'motion': 5191, 'borrow': 1013, 'filed': 3105, 'extension': 2944, 'electoral': 2697, 'aerial': 245, 'footage': 3214, 'devastated': 2306, 'font': 3210, 'doomsday': 2515, 'ticks': 8051, '30': 62, 'closer': 1577, 'annihilation': 406, 'thanks': 7992, 'brunch': 1118, 'smooth': 7365, 'wrinkles': 8836, 'disappear': 2372, 'preet': 6079, 'bharara': 865, 'relationship': 6518, 'programs': 6170, 'accepts': 151, 'invite': 4208, 'antarctica': 421, 'planning': 5914, 'plot': 5943, 'modesty': 5133, 'plenty': 5942, '700': 100, 'toilets': 8088, 'shifting': 7169, 'shove': 7207, 'equating': 2806, 'silliest': 7246, 'eyeballs': 2955, 'manhattan': 4830, 'da': 2048, 'donation': 2505, 'exes': 2889, 'packing': 5635, 'giants': 3416, 'exported': 2932, 'rotten': 6795, 'egg': 2679, 'neil': 5317, 'gorsuch': 3495, 'matter': 4917, 'succumb': 7733, 'fatigue': 3039, 'frat': 3271, 'islam': 4239, 'retweeted': 6670, 'rather': 6387, 'outrage': 5588, 'blackmail': 916, 'hairstyle': 3642, 'arcade': 488, 'every': 2856, 'pundit': 6271, 'dinesh': 2343, 'souza': 7450, 'convicted': 1824, 'distance': 2441, 'nashville': 5279, 'withdrawal': 8773, 'catastrophe': 1329, 'frog': 3296, 'saves': 6911, 'transportation': 8170, 'pepperoni': 5795, 'rectal': 6456, 'maher': 4795, 'capable': 1265, 'ordering': 5547, 'lender': 4606, 'bathrooms': 756, 'revoke': 6694, 'spill': 7503, 'lunch': 4766, 'frightbart': 3293, 'stew': 7626, 'menace': 4989, 'pit': 5895, 'monsters': 5157, 'unending': 8345, 'onslaught': 5512, 'apocalyptic': 447, 'horsemen': 3895, 'lamb': 4497, 'grandfather': 3524, 'compared': 1690, 'cataracts': 1328, 'bangladeshi': 699, 'human': 3933, 'campaigner': 1230, 'farhad': 3024, 'mazhar': 4928, 'disappears': 2376, 'invisibility': 4206, 'commander': 1666, 'resist': 6616, 'base': 736, 'outcome': 5580, 'bass': 748, 'celebrates': 1360, 'expanding': 2901, 'donkeys': 2508, 'hangover': 3673, 'scrap': 6980, 'choose': 1491, 'successor': 7732, 'credit': 1950, 'starbucks': 7580, 'encourages': 2748, 'bipartisan': 899, 'spikes': 7502, 'lays': 4560, 'bare': 721, 'divisions': 2463, 'paperclips': 5679, 'harassments': 3685, 'landrieu': 4506, 'removal': 6548, 'orleans': 5559, 'reenactors': 6473, 'prepares': 6091, 'arrest': 516, 'concocts': 1721, 'broad': 1099, 'deleting': 2197, 'bashing': 744, 'weighs': 8670, 'swapping': 7819, 'readies': 6409, 'booming': 1002, 'feds': 3062, 'audition': 600, 'driver': 2580, 'owner': 5622, 'fed': 3059, 'emergency': 2727, 'westminster': 8688, 'impostor': 4039, 'wendy': 8681, 'vitter': 8531, 'separatist': 7085, 'clone': 1572, 'liberals': 4632, 'impersonations': 4025, 'considers': 1781, 'crosshairs': 1985, 'comb': 1652, 'slammed': 7305, 'cramp': 1929, 'defect': 2163, 'whom': 8717, 'adorable': 224, 'sandberg': 6884, 'showdown': 7210, 'shrink': 7219, 'unions': 8362, 'despot': 2287, 'popcorns': 6007, 'hammocks': 3658, 'sworn': 7841, 'bible': 867, 'abraham': 134, 'lincoln': 4664, 'hat': 3706, 'census': 1373, 'citizenship': 1525, 'trey': 8198, 'gowdy': 3505, 'fisa': 3138, 'embarrassing': 2719, 'adam': 201, 'unmitigated': 8376, 'reproductive': 6590, 'stone': 7645, 'unelectable': 8342, 'mop': 5171, 'deepens': 2155, 'odors': 5469, 'admiral': 215, 'diplomacy': 2351, 'resolving': 6622, 'soup': 7442, 'denmark': 2234, 'mermaid': 5000, 'doused': 2533, 'paint': 5649, 'whaling': 8692, 'mermen': 5001, 'slaps': 7310, 'complete': 1701, 'denuclearization': 2241, 'avoids': 628, 'nationalist': 5284, 'wardrobe': 8596, 'rebukes': 6432, 'khakis': 4409, 'singapore': 7261, 'regional': 6497, 'dialogue': 2317, 'playgroup': 5930, 'zinke': 8886, 'travels': 8180, 'ski': 7291, 'resort': 6624, 'alaskan': 312, 'steakhouse': 7604, 'accusations': 165, 'simple': 7254, 'explanation': 2922, 'undercuts': 8326, 'acted': 186, 'danced': 2065, 'anonymous': 416, 'discovery': 2397, 'ousts': 5577, 'taps': 7893, 'assassin': 542, 'trafficking': 8157, 'tap': 7889, 'fuel': 3312, 'reserves': 6604, 'milkshake': 5049, 'bizarre': 913, 'colleges': 1632, 'operative': 5525, 'looked': 4725, 'caterpillar': 1335, 'rips': 6733, 'claps': 1539, 'blackmails': 918, 'rick': 6709, 'perry': 5808, 'kilts': 4427, 'attractive': 592, 'playgrounds': 5929, 'pause': 5748, 'panic': 5669, 'upend': 8401, 'separating': 7084, 'discourage': 2394, 'shaved': 7151, 'teams': 7920, 'getting': 3410, 'stadiums': 7552, 'warships': 8614, 'deployed': 2254, 'peninsula': 5783, 'saunas': 6907, 'cossack': 1874, 'ensure': 2785, 'safety': 6854, 'obedience': 5449, 'issued': 4250, 'correction': 1864, 'hid': 3802, 'near': 5302, 'bushes': 1173, 'urinated': 8420, 'bungling': 1151, 'screenplay': 6988, 'acts': 197, 'association': 560, 'thinks': 8019, 'guesses': 3596, 'sassy': 6901, 'trolling': 8225, 'girlfriend': 3437, 'seized': 7051, 'troop': 8227, 'sling': 7327, 'phones': 5844, 'tapped': 7891, 'painter': 5650, 'subhuman': 7711, 'worked': 8802, 'hound': 3911, 'wish': 8766, 'hypnotize': 3967, 'airplanes': 302, 'couch': 1883, 'measures': 4949, 'canoe': 1261, 'ty': 8297, 'cobb': 1603, 'retiring': 6662, 'dictatorship': 2326, '1984': 28, 'thieves': 8013, 'elaborate': 2690, 'heist': 3763, 'swiss': 7838, 'blouses': 952, 'window': 8745, 'overwhelmingly': 5618, 'kitchen': 4443, 'purge': 6282, 'actually': 199, 'marshmallows': 4880, 'marrying': 4877, 'bingo': 895, 'cemetery': 1369, 'stocking': 7638, 'attaching': 576, 'ceiling': 1357, 'falwell': 3005, 'stripper': 7684, 'appointed': 471, 'ago': 279, 'investigate': 4195, 'abuses': 143, 'escalate': 2824, 'scuffling': 7000, 'tourism': 8129, 'commission': 1675, 'transparency': 8168, 'happened': 3676, 'explode': 2924, 'triumph': 8219, 'began': 805, 'spitball': 7510, 'oscar': 5563, 'nominated': 5379, 'ceremony': 1385, 'nunberg': 5432, 'summoned': 7755, 'torturer': 8115, 'airlines': 301, 'dragged': 2549, 'pilot': 5878, 'pop': 6005, 'positions': 6031, 'nun': 5431, 'benefits': 836, 'campground': 1233, 'field': 3093, 'vigorously': 8497, 'massage': 4895, 'magicians': 4792, 'along': 349, 'pennsylvania': 5787, 'appears': 461, 'heat': 3750, 'sauce': 6904, 'panicking': 5670, 'gutierrez': 3613, 'someone': 7420, 'kkk': 4449, 'chorus': 1494, 'grows': 3585, 'crumbs': 2000, 'convicts': 1826, 'laughed': 4535, 'disappearances': 2374, 'leftwing': 4592, 'dissent': 2439, 'froome': 3303, 'fourth': 3257, 'hiccups': 3799, 'meehan': 4965, 'bathrobe': 754, 'pi': 5852, 'sentencing': 7081, 'costa': 1876, 'mesa': 5003, 'spying': 7537, 'dui': 2607, 'praising': 6062, 'crawl': 1935, 'chile': 1475, 'creates': 1942, 'acre': 181, 'patagonia': 5732, 'founders': 3255, 'reader': 6407, 'pacifism': 5630, 'backstory': 657, 'hezbollah': 3796, 'hook': 3878, 'chain': 1391, 'tipline': 8071, 'bone': 987, 'buys': 1194, 'picnic': 5859, 'survive': 7798, 'toll': 8092, 'bombs': 983, 'masses': 4898, 'air': 298, '35s': 68, 'upkeep': 8405, 'subsidizing': 7722, 'biting': 912, 'dorm': 2518, 'scandals': 6928, 'dwarf': 2622, 'romancing': 6778, 'sooner': 7431, 'stood': 7648, 'drank': 2555, 'niece': 5353, 'card': 1278, '100k': 4, 'maniac': 4833, 'fish': 3140, 'lessons': 4613, 'sixth': 7283, 'nixon': 5370, 'ethical': 2837, 'norms': 5396, 'suite': 7751, 'jack': 4265, 'bobridge': 967, 'cyclist': 2045, 'selling': 7059, 'drunkard': 2595, 'flipped': 3173, 'legislature': 4603, 'attacked': 578, 'coconut': 1613, 'walk': 8576, 'drawn': 2558, 'sketch': 7290, 'auction': 597, 'incinerator': 4058, 'greenspan': 3551, 'math': 4912, 'individual': 4087, 'temporary': 7947, 'hints': 3824, 'toy': 8143, 'cartographer': 1308, 'panamanian': 5661, 'dictator': 2324, 'manuel': 4844, 'noriega': 5394, '83': 108, 'dating': 2089, 'gag': 3349, 'sound': 7439, 'immigrating': 4012, 'wild': 8736, 'reminiscent': 6545, 'xylophone': 8848, 'consistent': 1782, 'attractiveness': 593, 'catholic': 1338, 'priest': 6123, '13': 12, 'motel': 5188, 'paying': 5752, 'ouster': 5576, 'pseudo': 6234, 'embraces': 2725, 'pivot': 5900, 'proverbial': 6224, 'drunks': 2597, 'streetlight': 7675, 'puddles': 6252, 'kushners': 4481, 'saudis': 6906, 'blackstone': 919, 'recent': 6436, 'zoo': 8894, 'pack': 5632, 'spot': 7524, 'orders': 5548, 'boomerang': 1001, '90': 115, 'erasure': 2813, 'jefferson': 4296, 'zombie': 8890, 'happens': 3678, 'orange': 5541, 'amusing': 377, 'bosnia': 1016, 'ratko': 6392, 'mladic': 5113, 'genocide': 3395, 'indigestion': 4086, 'modernize': 5131, 'dismantle': 2417, 'laser': 4524, 'dwarfs': 2623, 'gdp': 3384, 'statues': 7598, 'birds': 902, 'foreigners': 3231, 'locked': 4714, 'modeling': 5126, 'battles': 763, 'umbrella': 8309, 'iphone': 4219, 'revives': 6692, 'floats': 3178, 'debts': 2126, 'ridiculous': 6717, 'cavalry': 1348, 'embarrass': 2718, 'forge': 3236, '34': 66, 'punished': 6274, 'graft': 3517, 'unprecedented': 8380, 'unique': 8363, 'complaints': 1700, 'virginity': 8518, 'idiocy': 3983, 'vox': 8556, 'sitter': 7279, 'intoxication': 4186, '24': 56, 'direction': 2361, 'postmen': 6038, 'reception': 6438, 'seduced': 7037, 'supremacist': 7778, 'activity': 193, 'campuses': 1237, 'cookie': 1832, 'lips': 4679, 'stooge': 7649, 'netroots': 5327, 'liberal': 4630, 'demand': 2214, 'throttle': 8036, 'pamper': 5660, 'conclude': 1718, 'stud': 7696, 'sarcasm': 6897, 'chibok': 1462, 'reunited': 6672, 'salamis': 6860, 'raisins': 6362, 'gibberish': 3417, 'residency': 6609, 'hairdos': 3637, 'deadliest': 2107, 'districts': 2450, 'radiologist': 6345, 'bullets': 1138, 'geometry': 3398, 'sergei': 7091, 'skripal': 7300, 'movie': 5206, 'wedding': 8660, 'northern': 5398, 'mclaughlin': 4939, 'saville': 6912, 'wannacry': 8589, 'hack': 3623, 'nhs': 5347, 'releases': 6525, 'planed': 5910, 'lowers': 4757, 'parenthood': 5696, 'hbcus': 3727, 'deportees': 2260, 'shelter': 7160, 'agonizing': 280, 'spelunking': 7487, 'mafia': 4789, 'miami': 5018, 'ground': 3577, 'unconstitutional': 8321, 'deli': 2199, 'denied': 2231, 'influx': 4105, 'militants': 5045, 'cockroaches': 1609, 'counting': 1895, 'tuxedos': 8280, 'sees': 7048, 'skunk': 7301, 'marry': 4876, 'roof': 6784, 'revealed': 6676, 'desecrated': 2274, 'kindergarten': 4431, 'submits': 7714, 'panels': 5668, 'confirmation': 1743, 'stream': 7670, 'applauded': 465, 'guantanamo': 3588, 'prisoners': 6136, 'beach': 768, 'sacrificial': 6847, 'politico': 5980, 'stands': 7578, 'battery': 760, 'scold': 6964, 'donor': 2509, 'sperm': 7492, 'sewers': 7118, 'mulligan': 5221, 'dow': 2536, 'fell': 3069, 'dishonesty': 2411, 'supports': 7775, 'note': 5406, 'burns': 1163, 'map': 4850, 'imp': 4017, 'grapes': 3533, 'overturns': 5617, 'regulation': 6502, 'mining': 5068, 'debris': 2124, 'cracker': 1925, 'hashtag': 3703, 'understand': 8333, 'dummies': 2610, 'criminals': 1965, 'bidet': 872, 'californians': 1215, 'extra': 2946, 'cross': 1983, 'subsidies': 7721, 'well': 8678, 'wives': 8783, 'blackmailed': 917, 'kept': 4401, 'informed': 4111, 'gnome': 3459, 'irresistible': 4235, 'named': 5270, 'perez': 5797, 'darts': 2080, 'escrow': 2829, 'gerrymandering': 3406, 'rig': 6720, 'squirrels': 7542, 'runner': 6825, 'roasts': 6751, 'apologists': 449, 'islamists': 4242, 'skateboarders': 7286, 'halls': 3649, 'landmarks': 4505, 'pleaded': 5935, 'identities': 3980, 'account': 160, 'numbers': 5430, 'humor': 3939, 'fda': 3050, 'reverse': 6683, 'stunning': 7706, 'details': 2297, 'brazen': 1058, 'heists': 3764, 'proof': 6187, 'improvement': 4044, 'beards': 776, 'fritters': 3295, 'domestic': 2498, 'retires': 6661, 'ditches': 2454, 'portugal': 6025, 'alaska': 311, 'baited': 672, 'canceling': 1247, 'dumpling': 2613, 'storms': 7658, '78': 105, 'moisten': 5135, 'dippin': 2356, 'dots': 2523, 'responded': 6628, 'listened': 4685, 'surprise': 7790, 'fueled': 3313, 'nationalism': 5283, 'noise': 5378, 'dodge': 2480, 'uses': 8428, 'anticapitalist': 427, 'sermon': 7096, 'pickup': 5858, 'trucks': 8236, 'miniature': 5065, 'explosive': 2931, 'wolff': 8788, 'held': 3766, 'captive': 1271, 'sexually': 7123, 'assaulted': 547, 'horrors': 3893, 'mannequin': 4838, 'deutsche': 2305, 'zip': 8887, 'code': 1614, 'villain': 8502, 'contradicts': 1812, 'whose': 8720, 'freezer': 3281, 'ruled': 6817, 'accidental': 154, 'discovers': 2396, 'puppies': 6279, 'rewards': 6700, 'grammar': 3519, 'dreams': 2566, 'pokes': 5969, 'prods': 6156, 'posterior': 6037, 'dreamer': 2564, 'sandals': 6883, '106': 9, 'passengers': 5720, 'stranded': 7665, 'pretzels': 6115, 'macedonians': 4778, 'clothes': 1584, 'toddler': 8083, 'hazing': 3725, 'unauthorized': 8316, 'dismisses': 2422, 'polling': 5983, 'peanut': 5762, 'champagne': 1401, 'welcome': 8676, 'burqas': 1165, 'together': 8086, 'copulate': 1847, '21st': 50, 'forays': 3220, 'vegan': 8457, 'turkeys': 8266, 'otters': 5571, 'duet': 2605, 'honoring': 3875, 'navajos': 5292, 'pocohontas': 5957, 'jab': 4262, 'taking': 7872, 'betting': 860, 'hobby': 3845, 'continues': 1807, 'churn': 1507, 'extremely': 2948, 'flooding': 3182, 'unfolding': 8349, 'provision': 6230, 'hardest': 3689, 'guess': 3595, 'knows': 4461, 'loved': 4751, 'sacks': 6843, 'ministers': 5071, 'defying': 2185, 'defenestrates': 2169, 'seduce': 7036, 'colonoscopy': 1644, 'anal': 379, 'reaction': 6402, 'weakness': 8647, 'beers': 799, 'stalwart': 7570, 'hemline': 3776, 'berating': 840, 'dramatic': 2554, 'nuke': 5426, 'giddy': 3418, 'royal': 6807, 'meghan': 4972, 'detail': 2296, 'elbow': 2691, 'sinus': 7270, 'forty': 3247, 'catalogued': 1326, 'elite': 2710, 'nh': 5346, 'prep': 6088, 'kerry': 4402, 'consults': 1793, 'ponders': 5994, 'dandruff': 2070, 'shark': 7148, 'creditloan': 1951, 'survey': 7796, 'height': 3760, 'revised': 6688, 'introduce': 4187, 'birthdays': 905, 'provide': 6226, 'delegates': 2194, 'volunteers': 8542, 'draft': 2546, 'deflates': 2181, 'hoax': 3844, 'ten': 7949, 'commandments': 1667, 'razorback': 6396, 'noaa': 5373, 'offensively': 5476, 'brake': 1051, 'marriott': 4875, 'books': 998, 'enlightenment': 2778, 'casts': 1321, 'zarrab': 8878, 'undermine': 8329, 'breakfast': 1065, 'cheapskate': 1437, 'hen': 3778, 'architect': 489, 'expresses': 2938, 'sliver': 7333, 'racetrack': 6334, 'foundation': 3253, 'overdose': 5600, 'accusing': 170, 'charity': 1423, 'palm': 5659, 'club': 1590, 'earthling': 2642, 'restore': 6637, 'voting': 8552, 'felons': 3071, 'salon': 6871, 'canadians': 1241, 'loonies': 4730, 'shouting': 7205, 'match': 4905, 'erupts': 2823, 'appetizer': 463, 'protecting': 6210, 'inmates': 4127, 'slumps': 7348, 'traders': 8152, 'supply': 7770, 'manson': 4842, '84': 109, 'repents': 6573, 'truths': 8251, 'acknowledge': 175, 'octogenarians': 5465, 'allen': 334, 'aroused': 514, 'emasculate': 2717, 'wan': 8587, 'troway': 8232, 'poo': 5998, 'snl': 7386, 'roast': 6749, 'hopscotch': 3888, 'navalny': 5294, 'heavily': 3754, 'elect': 2693, 'searchers': 7015, 'puddle': 6251, 'venture': 8469, 'chump': 1504, 'polyester': 5989, 'filibuster': 3107, 'moderate': 5128, 'rouhani': 6797, 'count': 1889, 'preliminary': 6085, 'results': 6645, 'pageant': 5641, 'wrap': 8825, 'chip': 1482, 'existence': 2894, 'doorstep': 2517, 'omg': 5503, 'reveals': 6678, 'pregnant': 6084, 'pretends': 6112, 'mypillow': 5255, 'strong': 7688, 'boycott': 1043, 'ingraham': 4118, 'angle': 394, 'naps': 5275, 'slip': 7329, 'grind': 3566, 'waking': 8575, 'cow': 1915, 'broadcaster': 1100, 'obnoxiously': 5453, 'revenge': 6681, 'yazidi': 8852, 'freeing': 3279, 'raqqa': 6381, 'housework': 3917, 'humanitarian': 3934, 'blown': 955, 'agendas': 272, 'novel': 5412, 'ayatollah': 639, 'khamenei': 4410, 'hitler': 3840, 'hemorrhoids': 3777, 'innovations': 4130, 'dominance': 2499, 'meryl': 5002, 'streep': 7673, 'whined': 8703, 'tiffany': 8056, 'lived': 4694, 'favorite': 3044, 'puppet': 6277, 'kingdom': 4436, 'posen': 6027, 'austria': 606, 'fascistic': 3030, 'umbrellas': 8310, 'shocked': 7181, 'routine': 6804, 'cleanser': 1554, 'savior': 6913, 'peta': 5824, 'billboard': 885, 'mouse': 5199, 'airstrike': 304, 'orangutans': 5543, 'liberty': 4633, 'alumni': 357, 'diplomas': 2352, 'molehill': 5138, 'pilgrim': 5872, 'deficits': 2176, 'struggles': 7694, 'spin': 7504, 'downplays': 2541, 'hawk': 3720, 'hispanics': 3834, 'sucker': 7736, 'punches': 6268, 'subway': 7726, 'giraffe': 3434, 'vx': 8561, 'nerve': 5321, 'nam': 5268, 'rare': 6382, 'infighting': 4097, 'grabbers': 3509, 'lubbers': 4762, 'stabs': 7550, 'boos': 1004, 'subpoenaed': 7716, 'piano': 5853, 'emma': 2729, 'gonzalez': 3485, 'survived': 7799, 'jacksonville': 4269, 'jaguars': 4271, 'shad': 7128, 'khan': 4411, 'jealous': 4294, 'trekkie': 8193, 'midwest': 5036, 'bull': 1136, 'flea': 3161, 'staring': 7582, 'toucan': 8120, 'catalans': 1325, 'declare': 2138, 'declaration': 2137, 'catches': 1332, 'amusement': 376, 'ride': 6713, 'pelican': 5772, 'disco': 2392, 'photos': 5847, 'environmental': 2796, 'terrified': 7970, 'motives': 5193, 'romance': 6776, 'celebrate': 1359, 'valentine': 8442, 'records': 6450, 'graded': 3511, 'dines': 2342, 'rice': 6706, 'convinced': 1827, 'popularity': 6012, 'theft': 7998, 'swath': 7822, 'county': 1899, 'representation': 6586, 'less': 4612, 'squirrel': 7541, 'representatives': 6587, 'supporter': 7772, 'sexuality': 7122, 'penny': 5788, 'perpetual': 5807, 'prompts': 6186, 'hunger': 3946, 'involve': 4212, 'fiction': 3090, 'spokesperson': 7520, 'grandma': 3525, 'distaste': 2443, 'suing': 7748, 'construction': 1790, 'beaner': 772, 'advertising': 234, 'principles': 6131, 'overseas': 5605, 'parks': 5702, 'lied': 4643, 'sanitation': 6891, 'today': 8082, 'grills': 3564, 'roosters': 6788, 'hairpiece': 3640, 'homeland': 3863, 'sudanese': 7739, 'giggle': 3424, 'salad': 6857, 'sleep': 7318, 'foot': 3213, 'evangelists': 2847, 'twisted': 8292, 'treachery': 8181, 'innocents': 4128, 'sandwich': 6886, 'captures': 1274, 'sandy': 6888, 'declassified': 2141, 'susan': 7804, 'contemplated': 1801, 'hiding': 3804, 'incoming': 4064, 'demolish': 2223, 'villages': 8501, 'pizzeria': 5905, '42': 78, 'completely': 1702, 'character': 1419, 'braces': 1046, 'prances': 6064, 'inside': 4137, 'trumpist': 8245, 'trumped': 8241, 'triumphs': 8220, 'exempts': 2887, 'grandparents': 3529, 'relatives': 6521, 'gifting': 3420, 'lines': 4669, 'databases': 2085, 'playing': 5931, 'guitar': 3604, 'massages': 4896, 'rails': 6353, 'shivers': 7179, 'recognizing': 6446, 'saved': 6910, 'location': 4711, 'trucker': 8235, 'damaged': 2058, 'peru': 5820, 'renowned': 6558, 'nazca': 5298, 'jockstraps': 4323, 'academic': 145, 'journals': 4342, 'graffiti': 3516, 'attempting': 583, 'muzzle': 5250, 'molest': 5139, 'julius': 4358, 'caesar': 1204, 'theater': 7997, 'timed': 8064, 'steak': 7603, 'whip': 8707, 'scalise': 6924, 'gunman': 3609, 'baseball': 737, 'practice': 6057, 'usa': 8422, 'removes': 6551, 'petition': 5828, 'tool': 8102, 'bali': 679, 'volcano': 8538, 'tremors': 8195, 'intensify': 4160, 'economists': 2662, 'vampires': 8446, 'smelly': 7359, 'limited': 4660, 'hockey': 3848, 'quest': 6309, 'astronauts': 565, 'alligators': 337, 'hug': 3928, 'frame': 3261, 'malley': 4817, 'aware': 633, 'elves': 2713, 'delingpole': 2203, 'environmentalists': 2797, 'burrito': 1166, 'jill': 4315, 'stein': 7612, 'culpability': 2013, 'primps': 6126, 'cosmonaut': 1873, 'drained': 2552, 'incumbents': 4072, 'ogres': 5489, 'reserve': 6603, 'cattle': 1340, 'breathing': 1072, 'scribble': 6991, 'appeals': 458, 'moustache': 5200, 'salary': 6862, 'overtime': 5613, 'hours': 3913, 'eclair': 2656, 'infowars': 4114, 'beat': 779, 'goddamn': 3468, 'wipe': 8758, 'services': 7102, 'arming': 509, 'equine': 2809, 'suspends': 7811, '103': 7, 'personnel': 5818, 'turk': 8264, 'gobbles': 3466, 'unsuccessful': 8388, 'equality': 2804, 'vulnerable': 8559, 'heidi': 3759, 'heitkamp': 3765, 'tougher': 8125, 'kevin': 4405, 'cramer': 1928, 'sorcerer': 7433, 'bugles': 1131, 'ben': 829, 'hud': 3924, 'lavish': 4548, 'waxing': 8639, 'requirements': 6597, 'starts': 7588, 'requesting': 6595, 'bids': 873, 'sticks': 7630, 'interviews': 4181, 'cyber': 2039, 'kaspersky': 4382, 'lab': 4484, 'recipe': 6440, 'evolving': 2863, 'towards': 8137, 'rap': 6374, 'asserts': 551, 'possibility': 6034, 'privilege': 6141, 'whoops': 8718, 'texts': 7987, 'agents': 274, 'peter': 5826, 'strzok': 7695, 'lisa': 4682, 'discards': 2384, 'stereo': 7620, 'naked': 5266, 'landfills': 4502, 'yearning': 8854, 'poland': 5970, 'asthma': 562, 'selfie': 7056, 'removed': 6550, 'hairdresser': 3638, 'claw': 1550, 'restroom': 6640, 'lot': 4745, 'contact': 1796, 'kissing': 4442, 'meats': 4952, 'mick': 5024, 'changing': 1411, 'bureau': 1154, 'rejection': 6515, 'uninsured': 8359, 'imprison': 4040, 'reenacted': 6472, 'taylor': 7913, 'swift': 7833, 'denver': 2242, 'dj': 2468, 'chihuahua': 1471, 'slovak': 7340, 'assassination': 544, 'typewriter': 8298, 'hires': 3831, 'clashes': 1543, 'fascist': 3029, 'hams': 3660, 'tennessee': 7952, 'senior': 7073, 'posing': 6029, 'graduation': 3515, 'waistband': 8569, 'pickle': 5855, 'manager': 4823, 'romanians': 6780, 'demonstrate': 2224, 'streets': 7676, 'provided': 6227, 'corrupt': 1868, 'doughnuts': 2530, 'robot': 6756, 'grandpas': 3530, 'glencore': 3449, 'cutting': 2038, 'oligarch': 5497, 'deripaska': 2268, 'commentary': 1671, 'richard': 6708, 'shelby': 7157, 'brain': 1048, 'terminate': 7964, 'seoul': 7082, 'humans': 3936, 'capabilities': 1264, 'gorillas': 3494, 'conditions': 1728, 'apnewsbreak': 445, 'challenged': 1398, 'gerbil': 3402, 'brexiteers': 1078, 'achievements': 173, 'governments': 3502, 'fuels': 3315, 'privacy': 6138, 'censoring': 1370, 'withholding': 8778, 'hospitalized': 3900, 'kicks': 4414, 'rage': 6348, 'referencing': 6475, 'solves': 7416, 'floridians': 3188, 'irma': 4230, 'taxing': 7909, 'dolphins': 2497, 'claudia': 1549, 'tenney': 7953, 'murderers': 5232, 'marketers': 4871, 'empty': 2742, '2005': 34, 'rachel': 6335, 'maddow': 4784, 'barbeque': 715, 'instructed': 4148, 'recusal': 6457, 'unicorn': 8354, 'critics': 1977, '64': 94, 'died': 2329, 'jan': 4280, 'shipwreck': 7176, 'dinghy': 2344, 'mediterranean': 4964, 'parrots': 5705, 'goulash': 3497, 'yak': 8849, 'dab': 2049, 'devastating': 2307, 'realism': 6416, 'backfire': 650, 'bigly': 879, 'penis': 5784, 'vicky': 8486, 'hartzler': 3697, 'claire': 1534, 'mccaskill': 4934, 'slap': 7308, 'huckleberry': 3923, 'finn': 3127, 'mockingbird': 5122, 'matryoshka': 4915, 'plumbing': 5950, 'mullen': 5220, 'enjoying': 2776, 'disneyland': 2425, 'slowdown': 7342, 'visitors': 8527, 'predicted': 6077, 'parakeets': 5686, 'jacinda': 4264, 'ardern': 492, 'winston': 8756, 'peters': 5827, 'shred': 7217, 'implement': 4027, 'denounces': 2237, 'misunderstands': 5108, 'psychiatrist': 6235, 'shock': 7180, 'greek': 3547, 'yoghurt': 8865, 'registered': 6498, 'flashing': 3156, 'marshmallow': 4879, 'ballot': 688, 'box': 1040, 'lawful': 4551, 'shake': 7134, 'conceivable': 1713, 'sidewalk': 7232, 'weaken': 8645, 'efficiency': 2676, 'diplomatic': 2354, 'regrettable': 6499, 'uncalled': 8319, 'pilgrimage': 5873, 'arbaeen': 487, 'spite': 7511, 'drunk': 2594, 'soothsayer': 7432, 'wayne': 8641, 'lapierre': 4516, 'advocates': 242, 'pizzas': 5904, 'hiphop': 3826, 'tennis': 7954, 'mastiffs': 4904, 'tabloid': 7858, 'planes': 5911, 'belgian': 820, 'bataclan': 750, 'gypsies': 3621, 'misled': 5092, 'skin': 7295, 'spam': 7458, 'prosecute': 6199, 'draws': 2559, 'wide': 8724, 'argentine': 496, 'spitting': 7513, 'mammal': 4819, 'decorations': 2148, 'distracted': 2445, 'hernia': 3783, 'kudlow': 4474, 'trashcans': 8176, 'eyesore': 2964, 'barbara': 713, 'matriarch': 4913, 'dynasty': 2629, 'moonwalks': 5168, 'affairs': 248, 'distillery': 2444, 'sara': 6895, 'seating': 7022, 'robin': 6755, 'louisiana': 4749, 'hare': 3691, 'pancakes': 5663, 'mustache': 5247, 'collude': 1637, 'appearance': 460, 'hoedown': 3849, 'covered': 1913, 'warts': 8616, 'rumor': 6822, 'orrin': 5561, 'hatch': 3707, 'boneheads': 989, 'closing': 1581, 'cheesecake': 1451, 'underarms': 8325, 'bromance': 1108, 'physicist': 5851, 'hawking': 3721, '76': 102, 'mulls': 5223, 'favor': 3042, 'hairbrush': 3633, 'imposes': 4036, 'winners': 8752, 'tipped': 8072, 'staggering': 7559, 'gerbils': 3403, 'shocking': 7182, 'tan': 7881, 'rationale': 6391, 'publish': 6246, 'lame': 4498, 'chaplain': 1418, 'scalding': 6920, 'failings': 2983, 'enjoys': 2777, 'apparent': 455, 'engage': 2767, 'each': 2632, 'militarily': 5046, 'appreciate': 474, 'rages': 6349, 'unabated': 8312, 'spencer': 7488, 'tank': 7883, 'nonprofit': 5388, 'credential': 1946, 'catering': 1334, 'nudge': 5422, 'socks': 7410, 'melts': 4977, 'beheaded': 815, 'burned': 1161, 'alive': 329, 'flood': 3181, 'bangladesh': 698, 'corncobs': 1856, 'sack': 6842, 'mortars': 5179, 'syndrome': 7850, 'shack': 7127, 'marc': 4855, 'andreessen': 387, 'eliminated': 2709, 'universe': 8368, 'snubbed': 7396, 'advances': 232, 'corn': 1855, 'unfettered': 8347, 'goldman': 3478, 'sachs': 6841, 'bedtime': 795, 'discharged': 2385, 'cliff': 1563, 'peacekeeping': 5759, 'warlords': 8597, 'lions': 4677, 'bracing': 1047, 'exposing': 2936, 'surviving': 7801, 'bahrain': 669, 'executes': 2882, 'shia': 7167, 'sentences': 7080, '2010': 38, 'sewer': 7117, 'declassifies': 2142, 'sausage': 6908, 'nike': 5365, 'stays': 7602, 'taxman': 7910, 'shimmies': 7171, 'promenade': 6177, 'curling': 2025, 'realdonaldtrump': 6415, 'besides': 848, 'turnip': 8271, 'soros': 7435, 'compiles': 1698, 'wikipedia': 8734, 'edit': 2668, 'tampon': 7880, 'discriminating': 2399, 'gifts': 3421, 'exchanged': 2875, 'pontiff': 5996, 'appeasing': 462, 'gods': 3469, 'minute': 5078, 'messes': 5007, 'liked': 4654, 'lyft': 4771, 'rideshare': 6714, 'latrine': 4532, 'dirty': 2368, 'lift': 4647, 'weights': 8673, 'allegation': 331, 'serenade': 7088, 'hicks': 3801, 'greenland': 3549, 'wildfire': 8737, 'deserves': 2280, 'fudges': 3311, 'promote': 6182, 'skeletons': 7288, 'waiter': 8571, 'smashes': 7355, 'trumps': 8246, 'tweeting': 8284, 'huskies': 3959, 'prisons': 6137, 'personalities': 5816, 'meetings': 4968, 'hogg': 3851, 'laura': 4545, 'career': 1284, 'treat': 8186, 'budapest': 1124, 'treated': 8187, 'communist': 1686, 'seagull': 7007, 'experience': 2914, 'jay': 4291, 'sekulow': 7053, 'pardons': 5695, 'whiny': 8706, 'adulting': 229, 'flirting': 3176, 'stupefying': 7707, 'wigs': 8732, 'devours': 2314, 'armenia': 507, 'contemplates': 1802, 'nonviolent': 5389, 'revolution': 6696, 'cusp': 2033, 'waving': 8638, 'bean': 771, 'buttock': 1186, 'tearing': 7922, 'replaced': 6575, 'driveway': 2582, 'capture': 1272, 'flopped': 3185, 'damaging': 2059, 'beetles': 801, 'marries': 4874, 'keeper': 4388, 'excellent': 2873, 'goal': 3461, 'pallbearer': 5658, 'neutral': 5330, 'judgment': 4351, 'gear': 3385, 'verdict': 8472, 'birdlime': 901, 'retire': 6657, 'roulette': 6798, 'climb': 1565, 'referendum': 6476, 'agriculture': 286, 'produced': 6158, 'tons': 8097, 'throughout': 8038, 'bagels': 667, 'decries': 2152, 'fomenting': 3208, 'spiders': 7498, 'jump': 4360, 'inflation': 4100, 'beans': 773, 'reaches': 6400, 'punish': 6273, 'blizzard': 940, 'onpolitics': 5511, 'sherbet': 7164, 'crying': 2005, 'superheroes': 7764, 'vast': 8454, 'amounts': 372, 'byproduct': 1197, 'worldwide': 8809, 'wears': 8654, 'resume': 6646, 'northward': 5399, 'starved': 7591, 'areas': 494, 'skyscraper': 7303, 'mattress': 4919, 'sniffing': 7383, 'weaker': 8646, 'eye': 2952, 'beavers': 786, 'send': 7069, 'interests': 4165, 'towels': 8139, 'recipients': 6442, 'snore': 7389, 'steroids': 7624, 'fetishism': 3086, 'phoenix': 5840, 'attracts': 594, 'moved': 5203, 'guatemalan': 3593, 'boxing': 1041, 'congratulates': 1760, 'diversify': 2455, 'processes': 6153, 'imf': 4007, 'outlook': 5585, 'cites': 1519, 'legalization': 4597, 'cancel': 1245, 'berkeley': 841, 'riots': 6731, 'bologna': 974, 'eclipse': 2657, 'viewing': 8496, 'magnifying': 4794, 'stockholm': 7637, 'hedgehog': 3756, 'pitbull': 5896, 'colors': 1647, 'undergarments': 8327, 'squirt': 7543, 'antelope': 422, 'kathy': 4383, 'griffin': 3560, 'metaphor': 5011, 'simile': 7252, 'exchanges': 2876, 'rallies': 6363, 'ryans': 6837, 'dawdles': 2097, 'tolerance': 8090, 'barriers': 732, 'partisan': 5711, 'disrupted': 2437, 'shakespeare': 7136, 'hostage': 3902, 'tags': 7863, 'greenwood': 3552, 'disrobe': 2435, 'rampage': 6366, 'suspicion': 7812, 'intercept': 4161, 'radiation': 6342, 'aardvark': 122, 'govern': 3499, 'shovels': 7208, 'encourage': 2747, 'caviar': 1351, 'exposes': 2935, 'splits': 7516, 'limousine': 4663, 'flexibility': 3168, 'groening': 3571, 'simpsons': 7256, 'apu': 482, 'pretend': 6109, 'grimace': 3565, 'meadows': 4942, 'bold': 973, 'buttocks': 1187, 'dentist': 2239, 'rigged': 6721, 'ramadan': 6365, 'jihadist': 4314, 'hoedowns': 3850, 'signals': 7238, 'further': 3338, 'restrict': 6638, 'investments': 4204, 'curry': 2029, 'disinvites': 2415, 'golden': 3476, 'warriors': 8611, 'donuts': 2512, 'gunmen': 3610, 'shiite': 7170, 'wound': 8822, 'brennan': 1075, 'harder': 3688, 'happening': 3677, 'defiant': 2174, 'crepe': 1954, 'core': 1851, 'pac': 5628, 'pioneer': 5887, 'masaya': 4887, 'nakamura': 5265, '91': 118, 'husband': 3957, 'challenges': 1399, 'meddled': 4955, 'adds': 209, '227': 52, 'rate': 6384, 'fabricates': 2965, 'gulf': 3605, 'minorities': 5074, 'mega': 4970, 'colonies': 1643, 'discovered': 2395, 'canadian': 1240, 'enjoy': 2775, 'violently': 8512, 'expectations': 2905, 'civic': 1527, 'engagement': 2769, 'imagine': 4005, 'cannon': 1260, 'waging': 8568, 'wary': 8617, 'minerals': 5064, 'elephants': 2705, 'yurt': 8875, 'wanda': 8588, 'sykes': 7844, 'diss': 2438, 'intimidation': 4183, 'targeted': 7896, 'misinform': 5091, 'confuse': 1753, 'quarterback': 6306, 'fishy': 3143, 'float': 3177, 'compares': 1691, 'cave': 1349, 'dwellers': 2624, 'courtesan': 1907, 'jails': 4274, 'tourists': 8131, 'istanbul': 4252, 'cakes': 1210, 'psychic': 6237, 'slowly': 7344, 'speeches': 7480, 'otter': 5570, 'coach': 1598, 'expressions': 2939, 'writing': 8839, 'publishers': 6248, 'eager': 2633, 'fishing': 3142, 'dubai': 2598, 'grass': 3535, 'wolves': 8789, 'stomping': 7644, 'investigated': 4196, 'mirror': 5082, 'trades': 8153, 'redistricting': 6463, 'fatty': 3040, 'chauvinists': 1435, 'triggered': 8211, 'watermelon': 8633, 'virgin': 8516, 'misunderstood': 5109, 'casserole': 1318, 'nears': 5305, 'broccoli': 1105, 'through': 8037, 'suburbs': 7725, 'cyborg': 2043, 'binge': 894, 'anyone': 435, 'tense': 7956, 'guantรกnamo': 3589, 'expansion': 2902, 'denham': 2229, 'hears': 3746, 'constituents': 1787, 'rubbed': 6812, 'important': 4032, 'collins': 1635, 'disgusting': 2409, 'barrettes': 730, 'wiggle': 8731, 'corset': 1870, 'poisoned': 5964, 'ivy': 4261, 'françois': 3270, 'hollande': 3858, 'eggs': 2681, 'charlatans': 1424, 'jarred': 4288, 'msnbc': 5210, 'disappointed': 2377, 'bishops': 908, 'whistle': 8710, 'pushing': 6289, 'circumcision': 1515, 'mandatory': 4828, 'misandrist': 5085, 'aclu': 178, 'jane': 4281, 'doe': 2483, 'shaving': 7152, 'moose': 5170, 'hogwash': 3852, 'cartographers': 1309, 'barbers': 717, 'holders': 3854, 'audio': 599, 'seafood': 7005, 'pink': 5886, 'hoping': 3887, 'powerhouse': 6055, 'rainbow': 6355, 'pullout': 6261, 'attempts': 584, 'emerge': 2726, 'criminalize': 1963, 'investigators': 4202, 'guide': 3600, 'sandwiches': 6887, 'accord': 157, 'boyfriend': 1044, 'parades': 5683, 'beet': 800, 'supermodel': 7767, 'recognizes': 6445, 'pride': 6121, 'lgbti': 4625, 'persons': 5819, 'brewery': 1076, 'blindsided': 938, 'throwing': 8041, 'rednecks': 6465, 'rounds': 6801, 'beggars': 806, 'masseuses': 4899, 'hoboken': 3847, 'elects': 2702, 'sikh': 7241, 'jersey': 4304, 'weasel': 8655, 'lipstick': 4680, 'adolf': 223, 'mile': 5042, 'abandoned': 123, 'transformed': 8166, 'getaway': 3408, 'boardwalk': 962, 'fun': 3324, 'league': 4569, 'twin': 8290, 'phase': 5835, 'tripadvisor': 8216, 'criticized': 1974, 'performance': 5800, 'sheldon': 7158, 'adelson': 210, 'newspaper': 5341, 'breakdance': 1063, 'butterflies': 1185, 'snubbing': 7397, 'eclipsing': 2658, 'concludes': 1719, 'interfered': 4167, 'conclusion': 1720, 'rutabagas': 6834, 'guilt': 3602, 'redecorating': 6462, 'begged': 807, 'challah': 1396, 'bifocals': 874, 'warship': 8613, 'boat': 964, 'speeding': 7482, 'uss': 8431, 'tempest': 7944, 'persian': 5811, 'relying': 6533, 'poker': 5968, 'brutal': 1120, 'september': 7086, 'mosquitoes': 5183, 'hacks': 3627, 'dismissed': 2421, 'crayon': 1936, 'diesel': 2331, 'accounts': 164, 'troll': 8222, 'spacex': 7455, 'falcon': 2996, 'vital': 8529, 'adamant': 202, 'osama': 5562, 'remain': 6534, 'tango': 7882, 'sneak': 7377, 'rental': 6560, 'heroin': 3786, 'trunk': 8247, 'rickshaw': 6710, 'rescinding': 6600, 'directing': 2360, 'cocaine': 1606, 'ballerinas': 682, 'souls': 7438, 'goats': 3465, 'dennis': 2235, 'hastert': 3705, 'levitate': 4622, 'libel': 4629, 'vogue': 8536, 'investing': 4203, 'nagorno': 5262, 'karabakh': 4379, 'detectives': 2300, 'unlock': 8374, 'phone': 5841, 'backpage': 655, 'liable': 4627, 'buffalo': 1127, 'westworld': 8689, 'millionaires': 5054, 'utility': 8433, 'raising': 6361, 'donors': 2510, 'costly': 1877, 'flushing': 3195, 'sinkhole': 7267, 'appropriate': 476, 'mint': 5077, 'trust': 8248, 'coin': 1620, 'implosion': 4029, 'basketball': 747, 'repugnant': 6593, 'credibility': 1948, 'dealt': 2116, 'blunt': 959, 'salesman': 6865, 'demoralized': 2226, 'stokes': 7641, 'capacity': 1266, 'rollback': 6773, 'decor': 2147, 'assistance': 557, 'boon': 1003, 'survivors': 7803, 'violin': 8513, 'retreats': 6664, 'tantrums': 7888, 'secure': 7034, 'cite': 1517, 'irreconcilable': 4233, 'differences': 2334, 'hairstyles': 3643, 'attire': 588, 'chicken': 1466, 'louis': 4747, 'farrakhan': 3028, 'loitering': 4717, 'pastry': 5731, 'accuser': 167, 'insider': 4138, 'congresswoman': 1766, 'tables': 7857, 'glitter': 3452, 'combs': 1655, 'welcomes': 8677, 'ventures': 8470, 'disasters': 2380, 'slimmed': 7325, 'screams': 6986, 'hookah': 3879, 'goodwin': 3488, 'proves': 6225, 'royce': 6809, 'reelection': 6470, 'creating': 1943, 'merkley': 4999, 'shorts': 7199, 'favorability': 3043, 'basement': 740, 'coyote': 1919, 'labs': 4490, 'snorting': 7392, 'reflex': 6481, 'zucker': 8898, 'divorce': 2465, 'outhouse': 5583, 'collides': 1633, 'opioid': 5528, 'epidemic': 2802, 'justices': 4368, 'appeal': 457, 'emblem': 2721, 'fluorescent': 3193, '1928': 26, 'steer': 7611, 'myth': 5259, 'cheap': 1436, 'stall': 7568, 'pitch': 5897, 'hijinks': 3811, 'fiesta': 3095, 'kuaishou': 4473, 'tencent': 7950, 'round': 6799, 'ipo': 4220, 'breached': 1060, 'teenager': 7932, 'gropes': 3575, 'obesity': 5450, 'extends': 2943, 'reuters': 6673, 'exercise': 2888, 'slaw': 7316, 'jingle': 4318, 'noon': 5392, 'platypus': 5922, 'larry': 4521, 'flynt': 3199, 'suitable': 7750, 'modi': 5134, '2019': 44, 'spice': 7495, 'austin': 603, 'chimpanzee': 1476, 'abrupt': 136, 'golfers': 3482, 'conor': 1770, 'cheltenham': 1455, 'coventry': 1910, 'midfielder': 5030, 'flog': 3180, 'knees': 4452, 'undo': 8339, 'patient': 5738, 'lobbying': 4705, 'frenzy': 3283, 'dolphin': 2496, 'kissed': 4440, 'frequently': 3284, 'reached': 6399, 'eagle': 2634, 'toss': 8117, 'suburb': 7724, 'stare': 7581, 'chic': 1463, 'nutella': 5438, 'brawls': 1056, 'supermarket': 7766, 'aisles': 307, 'santorum': 6894, 'teacup': 7918, 'boredom': 1011, 'tentative': 7960, 'tuition': 8258, 'graduate': 3513, 'preschool': 6094, 'refers': 6478, 'shithole': 7178, 'clubs': 1592, 'dana': 2063, 'rohrabacher': 6769, 'meyers': 5017, 'bounces': 1029, 'cord': 1850, 'scoble': 6963, 'unfollowed': 8351, 'ultimate': 8307, 'obsessed': 5456, 'compliment': 1707, 'miracle': 5080, 'autism': 613, 'treehouse': 8191, 'tpp': 8146, 'seasons': 7020, 'puzder': 6296, 'laugh': 4534, 'sociologists': 7408, 'interior': 4170, 'survives': 7800, 'designer': 2281, 'dash': 2081, 'lasagna': 4523, 'scatter': 6938, 'gains': 3352, 'codes': 1615, 'bottled': 1025, 'bullshit': 1141, 'pizzagate': 5903, 'anchovies': 384, 'homophobic': 3868, 'foretells': 3234, 'seriously': 7095, 'snowman': 7395, 'simultaneous': 7257, 'wars': 8612, 'trading': 8154, 'advisor': 238, 'quitting': 6324, 'cultists': 2015, 'kneel': 4451, 'responsibility': 6631, 'fond': 3209, 'plumber': 5949, 'naval': 5293, 'drills': 2574, 'surfboards': 7785, 'ousted': 5575, 'surfing': 7787, 'renewable': 6555, 'ipsos': 4221, 'moat': 5116, 'situation': 7281, 'handover': 3669, 'blob': 941, 'tip': 8070, 'steele': 7610, 'makeup': 4808, 'bury': 1168, 'gravediggers': 3540, '55': 87, 'proceeding': 6150, 'fakiness': 2994, 'blamed': 924, 'botched': 1021, 'disgrace': 2405, 'souffle': 7436, 'snipers': 7384, 'symphony': 7848, 'sanity': 6892, 'twirl': 8291, 'sponsor': 7521, 'prostitute': 6205, 'greg': 3555, 'gianforte': 3414, 'sent': 7077, 'slam': 7304, 'boom': 1000, 'fantasies': 3015, 'engines': 2771, 'rappers': 6379, 'nut': 5437, 'rentals': 6561, 'syrup': 7853, 'siesta': 7234, 'iceland': 3972, 'pedophile': 5768, 'furor': 3336, 'breakdancing': 1064, 'kenyan': 4400, 'herders': 3780, 'centuries': 1379, 'prosperity': 6204, 'medicine': 4963, 'buyback': 1191, 'inspires': 4143, 'colbert': 1622, 'emmys': 2732, 'features': 3055, 'explicit': 2923, 'scene': 6939, 'shopping': 7194, 'cactus': 1203, 'swimming': 7835, 'crowns': 1993, 'winner': 8751, 'sesame': 7104, 'rated': 6385, 'stooges': 7650, 'hyena': 3963, 'sneaker': 7378, 'pew': 5832, '61': 92, 'diana': 2318, 'falzone': 3006, 'nudes': 5421, 'physician': 5850, 'physical': 5848, 'mental': 4992, 'touching': 8123, 'benjamin': 838, 'regretting': 6500, 'forcing': 3226, 'caveman': 1350, 'moron': 5177, 'physically': 5849, 'neckties': 5309, 'retard': 6655, 'retain': 6649, 'merkel': 4998, 'hosts': 3904, 'broaden': 1102, 'bargaining': 723, 'funder': 3327, 'bankrolls': 703, 'sites': 7278, 'illustrated': 4002, 'fists': 3145, 'bedbugs': 793, 'catfishing': 1336, 'sculptures': 7001, 'opioids': 5529, 'octopus': 5466, 'horoscope': 3889, 'adani': 203, 'canavan': 1244, 'yells': 8857, 'resists': 6619, 'ostrich': 5566, 'testing': 7981, 'boundaries': 1032, 'downtown': 2542, 'desert': 2276, '2050': 48, 'warming': 8599, 'basic': 745, 'experiment': 2915, 'mock': 5119, 'comedy': 1660, 'billionaires': 888, 'farmers': 3027, 'surge': 7788, 'playboy': 5924, 'cares': 1285, 'terminates': 7965, 'joined': 4328, 'mcdaniel': 4936, 'probes': 6146, 'sleepovers': 7321, 'lindsey': 4666, 'slingshot': 7328, 'yiannopoulos': 8863, 'uc': 8301, 'davis': 2095, 'disturbance': 2451, 'gymnasium': 3618, 'ambitious': 362, 'reconcile': 6448, 'factions': 2974, 'raccoon': 6329, 'berries': 847, 'humiliated': 3937, 'gardener': 3374, 'warmongers': 8600, 'dentistry': 2240, 'incarceration': 4054, 'bowls': 1039, 'vouchers': 8553, 'homeowners': 3865, 'mortgage': 5180, 'deduction': 2153, 'pencils': 5780, '2024': 47, 'rings': 6728, 'nominates': 5380, 'battled': 762, 'defraud': 2183, 'sister': 7272, 'rooster': 6787, 'doctors': 2475, 'rehab': 6505, 'patients': 5739, 'mothers': 5190, 'greenpeace': 3550, 'dismissing': 2423, 'anybody': 433, 'blazing': 933, 'carrots': 1301, 'apples': 469, 'downfall': 2539, 'surfaces': 7784, 'adults': 230, 'minors': 5076, '22': 51, 'curtains': 2031, 'drool': 2586, 'deposition': 2261, 'tracker': 8148, 'alias': 323, 'nyt': 5443, 'assassinate': 543, 'laziness': 4561, 'collie': 1634, 'oversees': 5608, 'departments': 2249, 'crochet': 1978, 'zipper': 8888, 'joining': 4329, 'expels': 2911, 'walking': 8578, 'delivered': 2205, 'acknowledges': 177, 'represented': 6588, 'disowned': 2427, 'lacking': 4492, 'quote': 6327, 'tesla': 7976, 'autopilot': 621, 'tiger': 8057, 'woods': 8796, 'cornholing': 1859, 'fairness': 2989, 'associates': 559, 'tire': 8075, 'diary': 2322, 'sceptical': 6942, 'spotlight': 7525, 'painfully': 5647, 'strangle': 7667, 'cfpb': 1388, 'veterinary': 8480, 'brainwashed': 1050, 'galvanize': 3357, 'cameras': 1227, 'grades': 3512, 'kirsten': 4437, 'gillibrand': 3429, 'meddler': 4956, 'smart': 7352, 'informal': 4107, 'dozen': 2543, 'jugglers': 4356, 'arsenal': 521, 'stronger': 7689, 'tx': 8296, 'abbott': 125, 'sheriffs': 7166, 'costumes': 1881, 'galaxy': 3354, 'butler': 1183, 'currently': 2028, 'wallet': 8582, 'hooky': 3880, 'competent': 1695, 'guy': 3615, 'blew': 937, 'magician': 4791, 'tack': 7859, 'burqa': 1164, 'forward': 3248, 'perhaps': 5802, 'athletes': 572, 'ceremonies': 1384, 'undoes': 8341, 'stages': 7558, 'lunatic': 4765, 'conviction': 1825, 'doodled': 2514, 'afrin': 261, 'pantomimes': 5673, 'gloat': 3453, 'theories': 8004, 'templates': 7945, 'megalomaniac': 4971, 'myopics': 5254, 'barbershop': 718, 'rod': 6761, 'triathlon': 8202, 'selloff': 7060, 'embodies': 2722, 'gift': 3419, 'dalmatians': 2057, 'financing': 3116, 'deploy': 2253, 'institution': 4147, 'ballerina': 681, 'mushroom': 5239, 'hospital': 3898, 'brookfield': 1110, 'troubled': 8231, '666': 96, 'fifth': 3097, 'ave': 623, 'privatize': 6140, 'traffic': 8155, 'bending': 833, 'easily': 2647, 'nakedly': 5267, 'sympathising': 7846, 'nazis': 5300, 'blobs': 942, 'passing': 5722, 'rev': 6674, 'billy': 891, 'detroit': 2304, 'pub': 6242, 'irish': 4229, 'paddy': 5638, 'fruit': 3306, 'elegant': 2703, 'unconvincing': 8322, 'pry': 6233, 'loose': 4732, 'shelters': 7161, 'sidesteps': 7231, 'nigerian': 5358, 'climbs': 1567, 'magnets': 4793, 'choirul': 1486, 'huda': 3925, 'goalkeeper': 3463, 'mate': 4908, 'unemployed': 8343, 'immaterial': 4008, 'mailboxes': 4797, 'midgets': 5032, 'slips': 7331, 'inaction': 4050, 'bounce': 1028, 'naughty': 5291, 'nice': 5349, 'distractions': 2446, 'rattlesnake': 6393, 'corrects': 1866, 'wiretapped': 8763, 'streak': 7669, 'stab': 7547, 'cooperating': 1840, 'strippers': 7685, 'cleans': 1553, 'automakers': 617, 'butter': 1184, 'methane': 5012, 'lollipop': 4718, 'quotes': 6328, 'eggplant': 2680, 'hooray': 3882, 'hairdo': 3636, 'kansas': 4377, 'exaggerations': 2866, 'shrubbery': 7221, 'weaponizes': 8650, 'flatulence': 3158, 'powers': 6056, 'resolution': 6620, 'cleaners': 1552, 'cigarettes': 1510, 'tobacco': 8081, 'ghosts': 3413, 'dumber': 2609, 'closet': 1579, 'fagggots': 2977, 'nigggers': 5360, 'makeovers': 4805, 'swimsuit': 7836, 'putting': 6295, 'doo': 2513, 'stemmed': 7614, 'flower': 3191, 'connect': 1767, 'spike': 7501, 'proctologist': 6154, 'scythe': 7002, 'stonewalling': 7647, 'route': 6803, 'redneck': 6464, 'investigator': 4201, 'deceased': 2130, 'emailing': 2715, 'mute': 5248, 'tease': 7923, 'semblance': 7062, 'always': 358, 'renegotiation': 6554, 'texans': 7983, 'receiving': 6435, 'maple': 4851, 'erik': 2819, 'occupation': 5462, 'slum': 7346, 'distances': 2442, 'laundered': 4542, 'ledger': 4586, 'snakes': 7375, 'passport': 5725, 'chad': 1389, 'animated': 399, 'pestles': 5822, 'fly': 3196, 'friendlier': 3289, 'skies': 7292, 'settling': 7114, 'cartoon': 1310, 'roku': 6770, 'channel': 1412, 'forwards': 3249, 'mooch': 5163, 'outlet': 5584, 'dud': 2603, 'deserts': 2277, 'armadillos': 504, 'grandmothers': 3527, 'vp': 8557, 'citigroup': 1521, 'touches': 8122, 'learning': 4578, 'bleeding': 935, 'musician': 5242, 'spanking': 7461, 'divide': 2458, 'ponytail': 5997, 'appointees': 472, 'salaries': 6861, 'persists': 5813, 'truce': 8233, 'pickles': 5856, 'belief': 821, 'exploding': 2927, 'destructive': 2295, 'reanimating': 6421, 'unfavorable': 8346, 'margaret': 4859, 'atwood': 595, 'puritan': 6283, 'values': 8444, 'flying': 3197, 'properties': 6190, 'vagrant': 8441, 'sacrificed': 6845, 'kidnapper': 4417, 'teeth': 7934, 'disgraceful': 2406, 'publication': 6244, 'mascara': 4888, 'crossed': 1984, 'hey': 3794, 'please': 5938, 'golfing': 3483, 'torches': 8109, 'bouncing': 1030, 'heir': 3762, 'burial': 1157, 'emotion': 2734, 'solving': 7417, 'dyslexia': 2630, 'bronzed': 1109, 'november': 5413, 'builds': 1134, 'haggis': 3629, 'extensive': 2945, 'limiting': 4661, 'lifting': 4648, 'cookout': 1836, 'cabbage': 1199, 'bathed': 752, 'apparently': 456, 'pranked': 6067, 'tumult': 8261, 'clout': 1586, 'dwindles': 2625, 'manhood': 4831, 'insensitive': 4136, 'feet': 3068, 'bashar': 742, 'compete': 1694, 'ioc': 4215, 'stability': 7549, 'credentials': 1947, 'gardens': 3375, 'fec': 3058, 'complaint': 1699, 'oppo': 5530, 'pills': 5877, 'comical': 1664, 'rebekah': 6426, 'mercer': 4995, 'notice': 5409, 'mills': 5056, 'retaliates': 6652, 'closure': 1582, 'slightly': 7324, 'awful': 635, 'ninth': 5369, 'circuit': 1514, 'eo': 2799, 'pander': 5666, 'picks': 5857, 'jerome': 4302, 'powell': 6052, 'vimy': 8503, 'ridge': 6715, 'centenary': 1375, 'reenact': 6471, 'punch': 6266, 'assessment': 552, 'steaks': 7605, 'unforced': 8352, 'errors': 2820, 'inflicted': 4102, 'depart': 2246, 'expulsion': 2940, 'salisbury': 6866, 'mugabe': 5216, 'zimbabwe': 8885, 'snake': 7374, 'blend': 936, 'mucus': 5212, 'thaw': 7995, 'popsicle': 6010, 'dying': 2626, 'disposed': 2430, 'coloring': 1646, 'reading': 6410, 'campaigns': 1231, 'pecans': 5764, 'melodies': 4975, 'maxine': 4922, 'prisoner': 6135, 'captured': 1273, 'calculations': 1212, 'cartoons': 1311, 'baking': 677, 'fedex': 3061, 'viral': 8515, 'stopping': 7653, 'burning': 1162, 'readers': 6408, 'presented': 6097, 'overturn': 5615, 'consumers': 1795, 'lizards': 4699, 'crude': 1996, 'discount': 2393, 'widens': 8726, 'cocoa': 1612, 'coffin': 1617, 'ate': 569, 'comedian': 1658, 'commit': 1677, 'salami': 6859, 'approve': 478, 'queue': 6314, 'rioting': 6730, 'romances': 6777, 'address': 207, 'collective': 1630, 'narcissism': 5276, 'exodus': 2897, '361': 70, 'exxon': 2951, 'mobil': 5118, 'fined': 3120, 'violating': 8507, 'twerking': 8288, 'otto': 5572, 'warmbier': 8598, 'coma': 1651, 'tuxedo': 8279, 'tomatoes': 8095, 'pipes': 5890, 'quills': 6317, 'topping': 8108, 'caused': 1345, 'hotdog': 3906, 'pipe': 5888, 'starvation': 7589, 'unimaginable': 8358, 'biscuit': 907, 'ceilings': 1358, 'hillsborough': 3818, 'football': 3215, 'literacy': 4689, 'spirit': 7507, 'themed': 8001, 'kurdistan': 4477, 'knead': 4450, 'visited': 8526, 'gambler': 3358, 'declared': 2139, 'counts': 1898, 'sexy': 7124, 'contentious': 1804, 'badlands': 663, 'rogue': 6767, 'inadequacies': 4051, 'gap': 3369, 'invisible': 4207, 'wallace': 8581, 'colleagues': 1627, 'disastrous': 2381, 'result': 6644, 'brush': 1119, 'imaginary': 4004, 'losers': 4739, 'clarence': 1540, 'harassed': 3682, 'yes': 8860, 'impeached': 4021, 'resonates': 6623, 'wart': 8615, 'dealer': 2111, 'defeated': 2161, 'chauvinism': 1433, 'weightlifting': 8672, 'rodeo': 6764, 'veteran': 8478, 'glass': 3445, 'artist': 527, 'falsified': 3004, 'trumpet': 8243, 'oatmeal': 5445, 'requires': 6598, 'unpaid': 8378, 'interns': 4174, 'nondisclosure': 5387, 'makeover': 4804, 'repaint': 6566, 'kale': 4374, 'clothed': 1583, 'exams': 2871, 'termites': 7966, 'kompromat': 4465, 'surface': 7783, 'breath': 1070, 'glued': 3456, 'riveting': 6743, 'herself': 3789, 'viewed': 8494, 'benching': 831, 'repairs': 6567, 'discuss': 2401, 'absolute': 139, 'deadline': 2108, 'tusk': 8277, 'racquetball': 6340, 'combat': 1653, 'disintegrate': 2414, 'tens': 7955, 'romania': 6779, 'bravery': 1054, 'costumer': 1880, 'drivel': 2579, 'worship': 8817, 'pinatas': 5883, 'wisconsin': 8765, 'ironworker': 4232, 'cancelled': 1248, 'undersecretary': 8332, 'supremacists': 7779, 'kurds': 4478, 'groping': 3576, 'bullies': 1139, 'seeking': 7041, 'protective': 6214, 'indicate': 4081, 'scroll': 6993, 'taqueria': 7894, 'bowlers': 1037, 'wishful': 8768, 'accent': 148, 'zodiac': 8889, 'killer': 4422, 'extending': 2942, 'limit': 4659, 'ar': 484, 'depressingly': 2262, 'skating': 7287, 'advanced': 231, 'ratio': 6390, 'coasts': 1602, 'confessed': 1736, 'involvement': 4214, 'wrestler': 8833, 'condemnation': 1723, 'flaunt': 3159, 'expose': 2933, 'pictures': 5862, 'pomp': 5991, 'kilt': 4426, 'learn': 4576, 'sychologists': 7842, 'kid': 4415, 'potty': 6046, 'training': 8163, 'princeling': 6128, 'stripped': 7683, 'exile': 2892, 'partied': 5709, 'scratches': 6983, '9th': 120, 'evening': 2851, 'shampoo': 7141, 'alcohol': 315, 'cambodia': 1221, 'hun': 3940, 'object': 5451, 'anarchic': 382, 'submit': 7713, 'communicate': 1684, 'automatically': 619, 'memory': 4986, 'directors': 2365, 'bondholders': 986, 'restructuring': 6642, 'laminate': 4499, 'introduced': 4188, 'misses': 5098, 'healthiest': 3740, 'bloomberg': 951, 'index': 4077, 'tweetstorm': 8286, 'sporting': 7522, 'goods': 3487, 'rifles': 6719, '21': 49, 'misplaces': 5094, 'succeed': 7727, 'bikes': 880, 'incinerated': 4057, 'unaware': 8317, 'division': 2462, 'simmers': 7253, 'feel': 3065, 'ransom': 6372, 'hipsters': 3829, 'baron': 725, 'genital': 3393, 'mutilation': 5249, 'earthworms': 2644, 'mole': 5137, 'despondent': 2286, 'numb': 5428, 'unsure': 8389, 'creators': 1945, 'reza': 6702, 'aslan': 536, 'piece': 5864, 'sh': 7126, 'correctly': 1865, 'identifying': 3979, 'ironclad': 4231, 'hour': 3912, 'abe': 126, 'undermines': 8330, 'backers': 649, 'snail': 7373, 'gymnastics': 3619, 'actor': 194, 'reg': 6493, 'cathey': 1337, '59': 89, 'pirouettes': 5894, 'nuneaton': 5433, 'cucumber': 2009, 'bit': 909, 'professional': 6163, 'sham': 7138, 'detains': 2299, 'consulate': 1791, 'worker': 8803, 'tension': 7957, 'negative': 5312, 'starting': 7586, 'leeway': 4588, 'scrambles': 6979, 'ovens': 5596, 'scams': 6926, 'armed': 506, 'stockings': 7639, 'settles': 7113, 'ditched': 2453, 'peekaboo': 5769, 'fungus': 3333, 'maute': 4921, 'southeast': 7447, 'islamist': 4241, 'relieved': 6528, 'wonderful': 8795, 'organization': 5551, 'large': 4518, 'scale': 6921, 'equivocation': 2811, 'astrologer': 563, 'madrid': 4787, 'jamming': 4279, 'cuddles': 2011, 'remodel': 6546, 'follows': 3207, 'informant': 4108, 'mongoose': 5150, 'attend': 585, 'avenge': 624, 'hunters': 3951, 'albino': 313, 'stigma': 7632, 'cautious': 1347, 'sleepwalkers': 7322, '29th': 60, 'overtakes': 5612, 'pornhub': 6018, 'espn': 2830, 'wto': 8843, 'web': 8658, 'reiterates': 6512, 'ability': 127, 'delta': 2211, 'takeoff': 7868, 'mercosur': 4996, 'wonder': 8794, 'memes': 4981, 'hopeful': 3885, 'marine': 4865, 'skimping': 7294, 'liquor': 4681, 'wiretapping': 8764, 'acne': 179, 'flags': 3154, 'huffington': 3926, 'rein': 6509, 'labrador': 4488, 'fy': 3343, 'violations': 8509, 'pugs': 6255, 'notre': 5410, 'dame': 2061, 'commencement': 1669, 'sprint': 7531, 'withdrawn': 8775, 'noses': 5404, 'anthropomorphism': 425, 'pantsuit': 5676, 'gears': 3386, 'risky': 6739, 'forgets': 3238, 'sterilize': 7622, 'cheetah': 1452, 'ape': 443, 'songs': 7427, 'cyberattack': 2040, 'spreads': 7529, 'broomstick': 1112, 'prodigies': 6155, 'execs': 2881, 'decisions': 2136, 'yard': 8850, 'grope': 3574, 'java': 4290, 'husbands': 3958, 'zte': 8896, 'ordered': 5546, 'fingerprints': 3123, 'listing': 4687, 'politician': 5978, 'consistently': 1783, 'staircase': 7561, 'achieve': 172, 'pomade': 5990, 'injected': 4122, 'dose': 2519, 'served': 7099, 'bbq': 766, 'unmotivated': 8377, 'pirates': 5892, '57': 88, 'drivers': 2581, 'oprah': 5535, 'confidants': 1740, 'tonsils': 8098, 'promising': 6181, 'rhetoric': 6703, 'locks': 4715, 'netflix': 5325, '104': 8, 'subscribers': 7719, 'toothpicks': 8106, 'luiz': 4763, 'inacio': 4049, 'lula': 4764, 'silva': 7249, 'defies': 2178, 'hunkers': 3948, 'blankie': 928, 'strongest': 7690, 'rash': 6383, 'retrieve': 6666, 'cyberweapons': 2042, 'peddling': 5767, 'architecture': 490, 'expects': 2907, 'alpaca': 350, 'exist': 2893, 'matrix': 4914, 'deportations': 2257, '37': 71, 'dominates': 2500, 'rankings': 6371, 'nation': 5281, 'schools': 6956, 'gang': 3365, 'standoff': 7577, 'normalization': 5395, 'recuses': 6458, 'copeland': 1845, 'tories': 8110, 'enchilada': 2746, 'gynecologist': 3620, 'downgrading': 2540, 'dccc': 2103, 'ventral': 8468, 'cream': 1939, 'garage': 3371, 'easter': 2649, 'ball': 680, 'raft': 6347, 'sashays': 6899, 'chant': 1414, 'aggression': 275, 'carousels': 1294, 'rebuke': 6431, 'arts': 528, 'en': 2744, 'masse': 4897, 'forever': 3235, 'realist': 6417, 'confrontation': 1751, 'cher': 1459, 'sashaying': 6898, 'revisions': 6690, 'trusted': 8249, 'sneakers': 7379, 'cockpit': 1607, 'vine': 8505, 'freeze': 3280, 'psychiatrists': 6236, 'dates': 2088, 'trails': 8160, 'heartburn': 3748, 'pigsties': 5871, 'tools': 8103, 'delete': 2195, 'require': 6596, 'employment': 2741, 'offends': 5473, 'odor': 5468, 'lick': 4638, 'aaa': 121, 'necessarily': 5307, 'sector': 7032, 'dec': 2127, 'estimate': 2835, '190': 24, 'adp': 226, 'sphincter': 7494, 'danish': 2075, 'inventor': 4193, 'confesses': 1737, 'dismembering': 2418, 'inventing': 4192, 'progressives': 6173, 'loyalty': 4760, 'pantry': 5674, 'accelerate': 147, 'animation': 400, 'depicts': 2251, 'la': 4483, 'swastika': 7821, 'viewers': 8495, 'lifelong': 4646, 'halloween': 3648, 'desantis': 2270, 'nursemaid': 5436, 'carried': 1298, 'repealing': 6569, 'academics': 146, 'laureates': 4546, 'misplace': 5093, 'fingernails': 3122, 'grab': 3508, 'sunscreen': 7759, 'reveled': 6680, 'disclosures': 2391, 'drenched': 2567, 'surrealist': 7793, 'ronny': 6783, 'marital': 4866, 'bellows': 826, 'meatballs': 4951, 'dashcam': 2082, 'philando': 5836, 'castile': 1320, 'informing': 4112, 'firearm': 3129, 'gremlin': 3556, 'millennial': 5050, 'stroke': 7687, 'francisco': 3265, 'pier': 5865, 'aspiring': 537, 'fainted': 2987, 'giggles': 3425, 'leftist': 4590, 'boston': 1019, 'supposed': 7776, 'fortune': 3246, 'fruitworm': 3308, 'runoff': 6827, 'bakery': 676, 'scrooge': 6994, 'prestigious': 6108, 'scholarship': 6952, 'disadvantaged': 2370, 'hamburgers': 3657, 'oozes': 5516, 'encouraging': 2749, 'compromise': 1710, 'flirt': 3175, 'ridicules': 6716, 'receptionist': 6439, 'effective': 2675, 'grits': 3567, 'lettuce': 4620, 'nosedive': 5403, 'reducing': 6468, 'output': 5587, 'tender': 7951, 'wearing': 8653, 'scotus': 6973, 'curtain': 2030, 'tighten': 8059, 'venezuelan': 8466, 'possession': 6033, 'plug': 5947, 'cavities': 1352, 'flagged': 3153, '2004': 33, 'pirate': 5891, 'tolerate': 8091, 'restrooms': 6641, 'grasshoppers': 3536, 'crush': 2002, 'decode': 2146, 'illiterates': 4001, 'ankara': 402, 'footstool': 3218, 'machines': 4780, 'edible': 2667, 'dough': 2528, 'craze': 1937, 'heartland': 3749, 'imposters': 4038, 'tux': 8278, 'beard': 775, 'stance': 7573, 'confirming': 1745, 'heterosexuality': 3793, 'behalf': 813, 'owl': 5620, 'groupie': 3581, 'hotness': 3909, 'toe': 8084, 'columbia': 1648, 'winks': 8750, 'dustpans': 2619, 'befell': 802, 'cigars': 1511, 'teatime': 7924, 'counseled': 1888, 'murderer': 5231, 'showgirl': 7214, 'knocking': 4457, 'guys': 3616, 'courts': 1909, 'tee': 7928, 'markers': 4869, 'officers': 5483, 'yetis': 8862, 'retaken': 6650, 'pumping': 6264, 'aleppo': 318, 'monitoring': 5151, 'internal': 4171, 'dynamics': 2627, 'rolling': 6774, 'seize': 7050, 'doghouses': 2488, 'discussing': 2403, 'indictment': 4083, 'taunting': 7903, 'ontario': 5513, 'wore': 8800, 'bench': 830, 'dina': 2341, 'gala': 3353, 'whilst': 8701, 'searching': 7017, 'roboticists': 6757, 'granted': 3532, 'visas': 8523, 'precision': 6076, 'monster': 5156, 'spare': 7463, '23m': 55, 'uninsuredrepublican': 8360, 'reaper': 6422, 'seizes': 7052, 'anbang': 383, 'gentle': 3397, 'busy': 1179, 'baghdad': 668, 'polish': 5975, 'absence': 137, 'skis': 7299, 'swim': 7834, 'delhi': 2198, 'engulfed': 2774, 'halts': 3651, 'upstage': 8411, 'visits': 8528, 'acid': 174, 'showed': 7211, 'librarian': 4635, 'thesaurus': 8009, 'cincinnati': 1513, 'nightclub': 5362, 'plums': 5951, 'reactivated': 6403, 'shed': 7154, 'fitness': 3147, 'develops': 2310, 'organizer': 5552, 'describing': 2273, 'daily': 2054, 'dove': 2534, 'closes': 1578, 'spanks': 7462, 'dubke': 2599, 'revolts': 6695, 'whine': 8702, 'ample': 374, 'slapstick': 7311, 'buffoonery': 1130, 'autopsies': 622, 'somersaults': 7421, 'enraged': 2781, 'refund': 6487, 'worsen': 8816, 'pyramid': 6299, 'essays': 2831, 'drones': 2585, 'scarves': 6936, 'pouring': 6048, 'robe': 6753, 'suspicious': 7813, 'packages': 5634, 'locations': 4712, 'soda': 7411, 'ejaculations': 2689, 'cellphones': 1367, 'matched': 4906, 'nestle': 5322, 'factory': 2975, 'dodd': 2478, 'frank': 3266, 'accountable': 162, 'defector': 2165, 'props': 6198, 'stumbles': 7704, 'exhumes': 2891, 'limericks': 4658, 'bribed': 1080, 'calm': 1220, 'beyond': 863, 'brochure': 1106, 'digestive': 2337, 'smear': 7356, 'retribution': 6665, 'recruits': 6455, 'populists': 6015, 'consultants': 1792, 'kindergartener': 4432, 'bowler': 1036, 'worm': 8810, 'toothpick': 8105, 'tasked': 7901, 'bedroom': 794, 'redecorates': 6461, 'commence': 1668, 'ill': 3996, 'sergeant': 7090, 'nick': 5351, 'bailey': 670, 'sable': 6838, 'uranus': 8414, 'referral': 6477, 'herring': 3788, 'passion': 5723, 'patriotism': 5741, 'hollywood': 3859, 'orly': 5560, 'phoned': 5843, 'screwed': 6989, 'momma': 5144, 'delays': 2192, 'noodle': 5390, 'clarify': 1541, 'bubbles': 1122, 'apologies': 448, 'adores': 225, 'crowding': 1990, 'wellesley': 8679, 'walnuts': 8584, 'sitar': 7275, 'auctioned': 598, 'beitar': 819, 'trivia': 8221, 'ddos': 2104, 'suggesting': 7745, 'inches': 4055, 'gambling': 3361, 'serial': 7093, 'stowaway': 7661, 'citizenry': 1523, 'carnage': 1289, 'kabul': 4372, 'butchery': 1182, 'brendan': 1074, 'samantha': 6876, 'wiccan': 8722, 'treadmill': 8182, 'horrific': 3892, 'bezos': 864, 'screws': 6990, 'amazon': 359, 'flies': 3169, 'viper': 8514, 'spiro': 7508, 'agnew': 278, 'nattering': 5289, 'nabobs': 5260, 'negativity': 5313, 'doddering': 2479, 'dotards': 2522, 'deplorableness': 2252, 'silliness': 7247, 'plugs': 5948, 'obsession': 5457, 'located': 4710, 'ushers': 8429, 'amount': 371, 'producing': 6160, 'bafta': 664, 'update': 8399, 'password': 5726, 'nurse': 5435, 'consent': 1772, 'provoke': 6231, 'applause': 467, 'cereal': 1383, 'belly': 827, 'ended': 2754, 'manipulation': 4836, 'oh': 5490, 'bother': 1024, 'winnie': 8753, 'pooh': 6002, 'foul': 3251, 'censors': 1371, 'nationalists': 5285, 'pent': 5790, 'tigers': 8058, 'grilled': 3563, 'heated': 3751, 'exchange': 2874, 'saxophones': 6915, 'disciplined': 2386, 'pillar': 5875, 'fictitious': 3092, 'statements': 7594, 'squints': 7540, 'showers': 7213, 'locust': 4716, 'smells': 7358, 'alimony': 328, 'forest': 3233, 'cobblers': 1604, 'daddy': 2053, 'virulent': 8521, 'represents': 6589, 'perfectly': 5799, 'utterly': 8435, 'integrative': 4154, 'complexity': 1704, 'supper': 7768, 'malarkey': 4810, 'cafeterias': 1206, 'tummy': 8260, 'blackjack': 915, 'resurrect': 6648, 'zia': 8884, 'zoos': 8895, 'snorkeling': 7391, 'falafel': 2995, 'dreamed': 2563, 'zebra': 8880, 'semitism': 7064, 'leg': 4593, 'vets': 8483, 'dissolved': 2440, 'gelatin': 3389, 'pencil': 5779, 'greatest': 3545, 'cauldron': 1343, 'windy': 8747, 'hygiene': 3964, 'couches': 1884, 'stewing': 7629, 'broward': 1116, 'daycare': 2100, 'thin': 8014, 'unhealthily': 8353, 'raping': 6377, 'rescued': 6601, 'boko': 972, 'haram': 3681, 'defeatist': 2162, 'cardboard': 1279, 'fetish': 3085, 'bungles': 1150, 'transvestites': 8172, 'reorganized': 6564, 'cyberwars': 2041, 'nudity': 5424, 'blasted': 930, 'majorettes': 4801, 'cooties': 1843, 'misanthropics': 5086, 'floods': 3183, 'landslides': 4511, 'main': 4798, 'shine': 7172, 'hb2': 3726, 'atoms': 575, 'janitors': 4283, 'eater': 2653, 'gastronomic': 3377, 'gamblers': 3359, 'migration': 5040, 'crumpet': 2001, 'reassures': 6425, 'slower': 7343, 'fb': 3047, 'touted': 8134, 'shuffle': 7222, 'plate': 5920, 'indefensible': 4073, 'decorators': 2150, 'boogies': 994, 'cult': 2014, 'scholar': 6951, 'ecuador': 2664, 'matchmaking': 4907, 'illinois': 3999, 'celebs': 1364, 'tribal': 8203, 'neighbors': 5316, 'pterodactyl': 6241, 'endangering': 2753, 'lives': 4695, 'asserting': 549, 'glee': 3447, 'salling': 6867, 'allowed': 341, 'varsity': 8453, 'scientist': 6961, 'breathe': 1071, 'secular': 7033, 'leopard': 4609, 'ring': 6727, 'cramps': 1930, 'quacks': 6303, 'vultures': 8560, 'mare': 4858, 'thrower': 8040, 'urinate': 8419, 'gaps': 3370, 'knowledge': 4459, 'aisle': 306, 'fume': 3322, '1380': 14, 'crew': 1955, 'stowaways': 7662, 'punching': 6269, 'stuffs': 7703, 'pecking': 5765, 'sonic': 7428, 'similar': 7251, 'peels': 5770, 'unwritten': 8395, 'picnics': 5860, 'essential': 2832, 'hottest': 3910, 'ranked': 6370, 'mistresses': 5107, 'hippies': 3827, 'flour': 3189, 'lighthearted': 4651, 'suppository': 7777, 'pill': 5874, 'cotton': 1882, 'quilting': 6319, 'marsupials': 4881, 'batteries': 759, 'coolness': 1837, 'hungarian': 3944, 'fairyland': 2991, 'mug': 5215, 'bloodstream': 950, 'rhyme': 6704, 'stamps': 7572, 'starve': 7590, 'endgame': 2755, 'nail': 5263, 'cajole': 1208, 'stem': 7613, 'sitcom': 7276, 'chides': 1468, 'gutter': 3614, 'toxic': 8142, 'electric': 2698, 'ceasefire': 1356, 'resigning': 6614, 'directions': 2362, 'disposal': 2429, 'unit': 8364, 'investigates': 4197, 'motorway': 5194, 'pavement': 5749, 'zuck': 8897, 'harvesting': 3700, 'unfolds': 8350, 'madeleine': 4786, 'albright': 314, 'reminder': 6543, 'withhold': 8777, 'andy': 389, 'menswear': 4991, 'increases': 4069, 'affected': 250, '87': 111, 'nanny': 5273, 'actors': 195, 'pepe': 5794, 'marinade': 4864, 'manicure': 4834, 'bombed': 978, '2007': 35, 'hulk': 3932, 'paradise': 5684, 'papers': 5680, 'prompt': 6185, 'drapery': 2556, 'parakeet': 5685, 'toast': 8080, 'puzzles': 6297, 'tunnel': 8263, 'jihad': 4313, 'inconveniencing': 4067, 'knitted': 4456, 'mccarthyite': 4933, 'counterproductive': 1892, 'necklace': 5308, 'entertaining': 2789, 'schlapps': 6949, 'weirdo': 8675, 'yorkers': 8870, 'volunteer': 8541, 'wrestlers': 8834, 'canoodles': 1262, 'mulligans': 5222, 'junkies': 4364, 'pep': 5793, 'shade': 7129, 'sri': 7545, 'lankan': 4514, 'licks': 4640, 'shulkin': 7223, 'committees': 1680, 'washers': 8620, 'schizophrenia': 6947, 'landscaping': 4509, 'retina': 6656, 'image': 4003, 'improves': 4045, 'gpa': 3506, 'fuhrer': 3318, 'materials': 4911, 'diarrhea': 2321, 'sugar': 7744, 'tribes': 8204, 'shape': 7142, 'wine': 8748, 'helpful': 3771, 'chug': 1503, 'obamas': 5448, 'inked': 4125, '65': 95, 'petroleum': 5830, 'conflicted': 1748, 'eyeball': 2953, 'beaver': 785, 'oven': 5595, 'remarries': 6539, 'infection': 4095, 'parsecs': 5706, 'smugglers': 7368, 'followed': 3205, 'prefers': 6082, 'vendetta': 8464, 'fahrenheit': 2978, '451': 82, 'reflect': 6479, 'vocabulary': 8533, 'girdles': 3435, 'vacations': 8438, 'vellicate': 8463, 'shameless': 7140, 'shortly': 7198, 'hobo': 3846, 'golfer': 3481, 'overtures': 5614, 'repeats': 6572, 'mantra': 4843, 'based': 739, 'revelations': 6679, 'peach': 5760, 'scales': 6922, 'frolics': 3298, 'rodents': 6763, 'htin': 3921, 'kyaw': 4482, 'bamboozles': 691, 'guaranteeing': 3590, 'ladder': 4493, 'mankind': 4837, 'pad': 5637, 'alcoholics': 316, 'spell': 7485, 'reshaping': 6607, 'boozing': 1009, 'clams': 1537, 'derail': 2267, 'trollies': 8224, 'folder': 3203, 'shallow': 7137, 'grave': 3539, 'seniors': 7074, 'corners': 1858, 'sctv': 6998, 'reunite': 6671, 'raiser': 6358, 'dave': 2093, 'classic': 1546, 'stereotype': 7621, 'caresses': 1286, 'flashy': 3157, 'aground': 287, 'ego': 2682, 'barron': 733, 'forbes': 3221, 'poppycock': 6009, 'mayonnaise': 4925, 'veganism': 8458, 'waltz': 8585, 'strudel': 7693, 'sheep': 7156, 'quilt': 6318, 'distribution': 2448, 'embraced': 2724, 'veritas': 8475, 'stage': 7557, 'criteria': 1969, 'authoritarian': 609, 'harvard': 3698, 'disguise': 2407, 'babbles': 640, 'foods': 3212, 'hoodlums': 3877, 'holidays': 3857, 'advertiser': 233, 'mishandling': 5090, 'bikinis': 882, 'nails': 5264, 'chipmunk': 1483, 'clemency': 1561, 'leonard': 4608, 'peltier': 5774, 'wen': 8680, 'ho': 3842, 'searches': 7016, 'hiking': 3814, 'dotard': 2521, 'puppets': 6278, 'warrant': 8608, 'geek': 3387, 'havana': 3715, 'cigar': 1509, 'spelling': 7486, 'parrot': 5704, 'carolers': 1291, 'snoring': 7390, 'commercials': 1674, 'brutality': 1121, 'venezuelans': 8467, 'scour': 6975, 'river': 6742, 'treasure': 8184, 'survival': 7797, 'spouses': 7527, 'sweetening': 7830, 'infrastructure': 4116, 'ruthless': 6835, 'intercontinental': 4163, 'heightening': 3761, 'supporting': 7774, 'legacy': 4594, 'emotional': 2735, 'farewell': 3023, 'lawn': 4554, 'vile': 8498, 'peak': 5761, 'believability': 822, 'mugs': 5217, 'hairball': 3632, 'reign': 6507, 'slamming': 7306, 'fork': 3242, 'frost': 3304, 'neutering': 5329, 'understanding': 8334, 'aussie': 602, 'dingo': 2345, 'kettle': 4404, 'waistline': 8570, 'wacky': 8563, 'gender': 3391, 'sparrow': 7468, 'congratulate': 1759, 'slimy': 7326, 'teeing': 7929, 'atheists': 571, 'antifa': 428, 'barricades': 731, 'demonstrators': 2225, 'orgy': 5556, 'enquirer': 2780, 'diagrams': 2316, 'escaping': 2827, 'resources': 6625, 'staffs': 7556, 'compost': 1708, 'invades': 4190, 'vanity': 8451, 'hissing': 3835, 'snacks': 7371, 'crowbar': 1988, '200': 32, 'historical': 3837, 'defaced': 2158, 'hateful': 3709, 'england': 2772, 'smog': 7361, 'chokes': 1488, 'latin': 4531, 'moped': 5172, 'bacteria': 661, 'chancellor': 1405, 'lobbied': 4704, 'annihilating': 405, 'prattles': 6070, 'overcharging': 5599, 'mocks': 5123, 'neighbor': 5315, 'exploded': 2925, 'recently': 6437, 'osha': 5565, 'tomato': 8094, 'houses': 3916, '473': 83, 'bumble': 1145, 'decade': 2128, 'bogeyman': 971, 'brawl': 1055, 'epic': 2801, 'mr': 5209, 'whcd': 8694, 'pussy': 6291, 'jake': 4277, 'tapper': 7892, 'orgasm': 5555, 'mispronunciations': 5095, 'vitamin': 8530, 'taxidermist': 7908, 'chin': 1478, 'moms': 5146, 'scarecrow': 6933, 'jon': 4336, 'jabs': 4263, 'heroes': 3785, 'shoestrings': 7186, '80s': 106, 'script': 6992, 'alma': 346, 'mater': 4909, 'sizzler': 7285, 'franchise': 3263, 'enemies': 2762, 'earns': 2638, 'erection': 2815, 'prayer': 6072, 'chest': 1460, 'forehead': 3229, 'member': 4978, 'fruitcakes': 3307, 'offshore': 5487, 'trailblazer': 8159, 'volume': 8540, 'tiptop': 8074, 'impenetrable': 4023, 'cranial': 1931, 'tsa': 8254, 'tightens': 8060, 'screening': 6987, 'expedite': 2908, 'roseanne': 6792, 'barr': 727, 'smacks': 7350, 'transported': 8171, 'cruel': 1997, 'inhuman': 4120, 'degrading': 2186, 'carriages': 1297, 'soviet': 7451, 'contrasting': 1813, 'standards': 7575, 'oranges': 5542, 'lobsters': 4708, 'pacifist': 5631, 'kindness': 4434, 'inmate': 4126, 'harem': 3692, 'hot': 3905, 'mic': 5019, 'kraken': 4469, 'watches': 8629, 'helplessly': 3773, 'streamed': 7671, 'kombucha': 4464, 'porcupines': 6016, 'comedians': 1659, 'chins': 1481, 'elbows': 2692, 'condemn': 1722, 'closely': 1576, 'ginger': 3432, 'oxygen': 5626, 'mastered': 4903, 'seeming': 7044, 'atheist': 570, 'somnambulist': 7424, 'ankles': 403, 'intervened': 4177, 'acquired': 180, 'paraphernalia': 5690, 'retaliate': 6651, 'gigantism': 3423, 'wrecks': 8830, 'accident': 153, 'unicycle': 8356, 'dachshunds': 2051, 'borrowers': 1014, 'governing': 3500, 'digital': 2338, 'baseballs': 738, 'malawi': 4811, 'clampdown': 1536, 'vampirism': 8447, 'rumors': 6823, 'entry': 2793, 'shortages': 7197, 'territory': 7971, 'eyeballed': 2954, 'fishermen': 3141, 'cruelest': 1998, 'rodrigo': 6765, 'mayors': 4927, 'mosquitos': 5184, 'bout': 1033, 'guides': 3601, 'congratulations': 1761, 'entertain': 2788, 'enslaved': 2784, 'progress': 6171, 'divine': 2460, 'ices': 3973, 'squirts': 7544, 'cartel': 1306, 'comic': 1663, 'senegal': 7072, 'saboteur': 6840, 'airing': 300, 'hardcore': 3687, 'triangles': 8201, 'apes': 444, 'explodes': 2926, 'plotting': 5945, 'stores': 7655, 'nationwide': 5286, 'carts': 1312, 'pitches': 5899, 'backyard': 659, 'mules': 5219, 'instructs': 4149, 'frightened': 3294, 'tidal': 8052, 'duh': 2606, 'papadopoulos': 5677, 'gambles': 3360, 'equation': 2807, 'designs': 2282, 'militant': 5044, 'benghazi': 837, 'raisin': 6360, 'bestiality': 851, 'ogre': 5488, 'biometric': 898, 'database': 2084, 'enrollment': 2783, 'baldness': 678, 'parachute': 5681, 'jewish': 4310, 'montana': 5158, 'iguana': 3994, 'currency': 2026, 'warplane': 8607, 'screaming': 6985, 'flips': 3174, 'sweetens': 7831, 'convent': 1819, 'thespian': 8011, 'ham': 3653, 'pimples': 5881, 'hindu': 3822, 'counties': 1894, 'track': 8147, 'insurers': 4153, 'connections': 1769, 'chants': 1416, 'infatuation': 4094, 'cozy': 1920, 'blanket': 927, 'retired': 6658, 'shreds': 7218, 'alibaba': 324, 'ma': 4776, 'judges': 4350, 'allotments': 338, 'crucial': 1994, 'canary': 1243, 'measure': 4948, 'classed': 1545, 'fracking': 3260, 'gophers': 3492, 'humanity': 3935, 'hermits': 3782, 'kindergartner': 4433, 'chart': 1429, 'cholesterol': 1490, 'kabobs': 4371, 'checks': 1444, 'chase': 1431, 'rush': 6830, 'attendance': 586, 'fleas': 3162, 'impersonates': 4024, 'assertion': 550, 'deserved': 2279, 'minions': 5069, 'insomnia': 4140, 'microsoft': 5025, 'inappropriate': 4052, 'bing': 893, 'engine': 2770, 'acrobatics': 182, 'gimpy': 3430, 'midget': 5031, 'oooo': 5515, 'wrongdoings': 8841, 'pigs': 5870, 'origami': 5557, 'server': 7100, 'hunks': 3949, 'milk': 5048, 'kite': 4445, 'queen': 6308, 'combusts': 1656, 'weibo': 8668, 'forbidden': 3222, 'disagree': 2371, 'tailgate': 7864, 'angel': 391, 'orchestrating': 5544, 'leash': 4579, 'films': 3110, 'clairvoyant': 1535, 'scrutinising': 6996, 'hiring': 3832, 'toadies': 8079, 'jesus': 4306, 'campos': 1234, 'moments': 5143, 'toothbrush': 8104, 'automatic': 618, 'hikes': 3813, 'revenue': 6682, 'serfdom': 7089, 'fest': 3082, 'disingenuous': 2413, 'persist': 5812, 'hairline': 3639, 'muhammad': 5218, 'ali': 322, 'horrible': 3891, 'shame': 7139, 'redstate': 6466, 'bloggers': 947, 'stalkers': 7567, 'forgot': 3240, 'scout': 6976, 'cosmetologists': 1872, 'vegans': 8459, 'dreads': 2561, 'thanked': 7991, 'fema': 3074, 'bombers': 980, 'impose': 4034, 'grandson': 3531, 'fixing': 3151, 'deflate': 2180, 'malibu': 4815, 'upending': 8402, 'ducks': 2602, 'sergey': 7092, 'kislyak': 4438, 'poetry': 5958, 'impersonator': 4026, 'crashed': 1933, 'missed': 5097, 'groundhog': 3578, 'contest': 1805, 'anime': 401, 'prank': 6066, 'hairpieces': 3641} ###Markdown TF-IDF for a word in a document is calculated by multiplying two different metrics:The **term frequency** of a word in a document. There are several ways of calculating this frequency, with the simplest being a raw count of instances a word appears in a document. Then, there are ways to adjust the frequency, by length of a document, or by the raw frequency of the most frequent word in a document.The **inverse document** frequency of the word across a set of documents. This means, how common or rare a word is in the entire document set. The closer it is to 0, the more common a word is. This metric can be calculated by taking the total number of documents, dividing it by the number of documents that contain a word, and calculating the logarithm.So, if the word is very common and appears in many documents, this number will approach 0. Otherwise, it will approach 1.Multiplying these two numbers results in the TF-IDF score of a word in a document. The higher the score, the more relevant that word is in that particular document. Extract features of both training and validation data ###Code # helper function: separate each title into (original_word, context), where context = title text without original word # params: # df: dataframe, with 'original' and 'edit' columns # return: # original_words: a list of original word strings before editing # contexts: a list of context strings def separate_original_word_from_title(df): original_words = [] contexts = [] for index, row in df.iterrows(): title = row['original'] start_position = title.find('<') end_position = title.find('/>') original_words.append(title[start_position+1 : end_position]) contexts.append(title[:start_position] + title[end_position+2 :]) return original_words, contexts ###Output _____no_output_____ ###Markdown Here we construct a Sparse Feature Matrix. This is to make this task more computationally easy. More information can be found here: https://machinelearningmastery.com/sparse-matrices-for-machine-learning/ ###Code # construct sparse feature matrix # params: # df: dataframe, with 'original' and 'edit' columns # vectorizer: sklearn text vectorizer, either TfidfVectorizer or Countvectorizer # return: # M: a sparse feature matrix that represents df's textual information (used by a predictive model) def construct_feature_matrix(df, vectorizer): edit_words = df['edit'].tolist() original_words, contexts = separate_original_word_from_title(df) # here the dimensionality of X is len(df) x |V| X_edit = vectorizer.transform(edit_words) return X_edit # Construct feature matrices for training and validation data train_X = construct_feature_matrix(train_dataframe, vectorizer) valid_X = construct_feature_matrix(valid_dataframe, vectorizer) test_X = construct_feature_matrix(test_dataframe, vectorizer) ###Output _____no_output_____ ###Markdown Train model on training set, evaluate model on validation set You could use a number of different models here. Look at this list and see what potentially othe models you would want to use:https://scikit-learn.org/stable/modules/classes.htmlmodule-sklearn.linear_model ###Code # train a linear regression model lm = LinearRegression() model = lm.fit(train_X, train_Y) print (model.intercept_) print (model.coef_.shape) # Evaluate model on validation set valid_Y_hat = model.predict(valid_X) rmse = np.sqrt(sklearn.metrics.mean_squared_error(valid_Y, valid_Y_hat)) print('RMSE on validation set:', rmse) # Evaluate model on training set: # expect to see unrealistically good performance! (for RMSE: lower is better) # unrealistic because YOUR MODEL IS TRAINED ON EXACTLY THESE DATA! # It gives the best validation/test performance you could hope to achieve using this model. train_Y_hat = model.predict(train_X) rmse = np.sqrt(sklearn.metrics.mean_squared_error(train_Y, train_Y_hat)) print('RMSE on training set:', rmse) # apply the model on test data, write out prediction results to a csv file test_Y_hat = model.predict(test_X) write_test_prediction(test_dataframe, test_Y_hat, './ridge-regression_alpha=1_baseline_new-tf.csv') ###Output _____no_output_____ ###Markdown Investigate what the model has learned and where it failed (A.K.A. error analysis) Look at learned parameters (for linear model: weight of each dimension) ###Code # construct a mapping: word -> learned weight of this word feature_weight = {} for word, idx in vectorizer.vocabulary_.items(): feature_weight[word] = model.coef_[idx] # words positively correlate with funniness (top ones) for k, v in sorted(feature_weight.items(), key = lambda x: x[1], reverse = True)[:10]: print (k, v) # words negatively correlate with funniness (top ones) for k, v in sorted(feature_weight.items(), key = lambda x: x[1], reverse = False)[:10]: print (k, v) ###Output opposition -0.8836506444659917 years -0.8836506444659917 border -0.8836506444659917 sale -0.8836506444659917 trump -0.8836506430721189 check -0.8836506430721189 blames -0.8836506430721189 hike -0.8836506430721189 radio -0.8836506430721189 attacks -0.8836506430721189 ###Markdown Look at how the model makes predictions on individual examples ###Code # We pick a set of examples from the validation set (we predicted scores for those). # We usually we don't pick from training data (since the good performance may be unrealistic). # We cannot do error analysis on test data (because no true target value is provided). def explain_linear_prediction(df, model, idx2feature, X, Y, Y_hat, idx_list): print('indices:', idx_list) for idx in idx_list: print ('==============', idx, '================') print ('original:', df.iloc[idx]['original']) print ('edit:', df.iloc[idx]['edit']) print ('grades:', df.iloc[idx]['grades']) print ('TRUE score:', df.iloc[idx]['meanGrade']) print ('PRED score:', Y_hat[idx]) print ('\nPRED breakdown:') print ('\tINTERCEPT', model.intercept_) if X[idx, :].nnz == 0: print ('\tFEATURE', '[EMPTY]') else: for entry in X[idx, :]: # looping over a row in sparse matrix feature_value = entry.data[0] feature_dim = entry.indices[0] print ('\tFEATURE', idx2feature[feature_dim], ':', 'f_value', feature_value, '*', 'f_weight', model.coef_[feature_dim], '=', feature_value*model.coef_[feature_dim]) # construct a dictionary mapping: feature index -> word idx2feature = dict([(v,k) for k,v in vectorizer.vocabulary_.items()]) errors = (valid_Y - valid_Y_hat)**2 # sort errors from low to high sorted_errors = sorted(enumerate(errors.iloc[:].tolist()), key = lambda x: x[1], reverse = False) # print(sorted_errors) ###Output _____no_output_____ ###Markdown prediction on random examples ###Code # pick a random set of examples from validation set: K = 5 random_indices = np.random.randint(0, valid_X.shape[0], K) explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, random_indices) ###Output indices: [1088 1232 1065 1669 505] ============== 1088 ================ original: Starbucks <encourages/> bipartisan coffee-drinking edit: forces grades: 32110 TRUE score: 1.4 PRED score: 0.8836506400461821 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE forces : f_value 1.0 * f_weight 0.0 = 0.0 ============== 1232 ================ original: A detailed <analysis/> of the Trump-Palin-Nugent-Kid Rock photo edit: shocker grades: 11000 TRUE score: 0.4 PRED score: 0.8836506400461821 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE [EMPTY] ============== 1065 ================ original: Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's <Power/> and Role edit: kitchen grades: 32111 TRUE score: 1.6 PRED score: 1.1500000089824969 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE kitchen : f_value 1.0 * f_weight 0.26634936893631467 = 0.26634936893631467 ============== 1669 ================ original: Trump border wall : Texans receiving letters about their <land/> edit: barbecue grades: 32222 TRUE score: 2.2 PRED score: 1.0666666540652607 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE barbecue : f_value 1.0 * f_weight 0.18301601401907858 = 0.18301601401907858 ============== 505 ================ original: After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can <Help/> ’ edit: Fly grades: 11000 TRUE score: 0.4 PRED score: 0.9999999969738926 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE fly : f_value 1.0 * f_weight 0.11634935692771053 = 0.11634935692771053 ###Markdown examples with closest prediction ###Code K = 5 # look at data with lowest prediction error low_error_indices = [i for i, v in sorted_errors[:K]] explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, low_error_indices) ###Output indices: [1428, 84, 110, 619, 955] ============== 1428 ================ original: Susan Sarandon : ‘ I Do n’t Think Trump ’s Gon na Make It Through His Whole <Term/> ’ edit: sandwich grades: 32110 TRUE score: 1.4 PRED score: 1.4000000024059092 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE sandwich : f_value 1.0 * f_weight 0.5163493623597272 = 0.5163493623597272 ============== 84 ================ original: FBI Director asks Justice Department to publicly <denounce/> Trump 's assertion of Obama wiretapping edit: approve grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE approve : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 110 ================ original: Trump walks back bizarre <comments/> on funding black colleges — but this administration ’s racism is no mistake edit: rant grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE rant : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 619 ================ original: A top State Department official could n't explain why the U.S. <backs/> Saudi Arabia edit: loves grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE loves : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 955 ================ original: <Watch/> : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” edit: clock grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE clock : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ###Markdown examples with worst predictions ###Code K = 5 # look at data with highest prediction error high_error_indices = [i for i, v in sorted_errors[-K:]] explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, high_error_indices) ###Output indices: [978, 120, 2146, 310, 774] ============== 978 ================ original: Spicer defends Trump : Issues are ' evolving towards the president 's <position/> ' edit: mouth grades: 10000 TRUE score: 0.2 PRED score: 2.199999996973688 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE mouth : f_value 1.0 * f_weight 1.316349356927506 = 1.316349356927506 ============== 120 ================ original: Donald Trump Endorses Keeping Senate in <Session/> Seven Days a Week to Get Nominees Approved edit: Jail grades: 32222 TRUE score: 2.2 PRED score: 0.19999999697402915 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE jail : f_value 1.0 * f_weight -0.683650643072153 = -0.683650643072153 ============== 2146 ================ original: Trump to North Korean leader Kim : My ‘ Nuclear <Button/> ’ is ‘ much bigger &amp; more powerful ’ edit: Belly grades: 33222 TRUE score: 2.4 PRED score: 0.3999999969739948 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE belly : f_value 1.0 * f_weight -0.4836506430721873 = -0.4836506430721873 ============== 310 ================ original: Charlotte Pence : I Bought The Gay <Bunny/> Book edit: republican grades: 33322 TRUE score: 2.6 PRED score: 0.5999999969739607 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE republican : f_value 1.0 * f_weight -0.2836506430722214 = -0.2836506430722214 ============== 774 ================ original: ' Disappeared ' Lawyer investigating in Egypt the <death/> of Cambridge student , Giulio Regeni , re-appears in court , under charges edit: selfies grades: 10000 TRUE score: 0.2 PRED score: 2.399999996973653 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE selfies : f_value 1.0 * f_weight 1.5163493569274713 = 1.5163493569274713 ###Markdown Introduction to Machine LearningGrant GlassTAP InstituteDay 01:Key Concepts and Terms Preface Welcome to Machine Learning as a part of the 2021 TAP Institute's summer courses. In this first day notebook, we will go over the core concepts of machine learning and start to get our feet wet with ML. I will not be providing you a complete overview, but rather a quick way to get a genereal understanding about what machine learning is and how it works. In days two and three, we will be exploring different machine learning techniques more in depth. Covered in this Notebook 1) What is Machine Learning?2) What is a Statistical Model?3) A framework for understanding ML4) Simple Example of ML Before we Begin! Head to the Google Teachable Machine Website: https://teachablemachine.withgoogle.comThe Teachable Machine website provides an easy to use interface for training image, sound, and pose classification models. No login is required to get started. Training data files can be loaded directly from your computer or from your computer’s webcam or microphone. Models can be exported to use in other projects, and the FAQ (https://cloud.google.com/inclusive-ml/) includes links to read more about fairness and inclusion in ML.Take a look at this project involving training a model to detect how ripe a piece of fruit is: https://medium.com/@warronbebster/teachable-machine-tutorial-bananameter-4bfffa765866How do you think the computer figures out ripeness?What exactly are we teaching the machine?What other humanistic data could we use for this type of machine learning? Part One - What is MACHINE LEARNING? The field itself: ML is a field of study which harnesses principles of computer science and statistics to create statistical models. These models are generally used to do two things:Prediction: make predictions about the future based on data about the pastInference: discover patterns in data Difference between ML and AI: There is no universally agreed upon distinction between ML and artificial intelligence (AI). AI usually concentrates on programming computers to make decisions (based on ML models and sets of logical rules), whereas ML focuses more on making predictions about the future.They are highly interconnected fields, and, for most non-technical purposes, they are the same. Part Two - What is A STATISTICAL MODEL? **Models:** Teaching a computer to make predictions involves feeding data into machine learning models, which are representations of how the world supposedly works. If I tell a statistical model that the world works a certain way (say, for example, that two story homes are more expensive than one story homes), then this model can then tell me what be more expensive, a ranch style home or a cape cod. What does a model actually look like? Surely the concept of a model makes sense in the abstract, but knowing this is just half the battle. You should also know how it’s represented inside of a computer, or what it would look like if you wrote it down on paper.A model is just a mathematical function, which is merely a relationship between a set of inputs and a set of outputs. Here’s an example:f(x) = x²This is a function that takes as input a number and returns that number squared. So, f(1) = 1, f(2) = 4, f(3) = 9.Let’s briefly return to the example of the model that predicts home price from home stories. I may believe, based on what I’ve seen in the world, that given a home's price is, on average, equal to the house's stories times 100,000. This model can be represented mathematically as follows:Price = Stories × $100,000In other words, price is a function of stories.**Here’s the main point:** Machine learning refers to a set of techniques for estimating functions (like the one involving income) based on datasets (pairs of heights and their associated incomes). These functions, which are called models, can then be used for predictions of future data.**Algorithms:** These functions are estimated using algorithms. In this context, an algorithm is a predefined set of steps that takes as input a bunch of data and then transforms it through mathematical operations. You can think of an algorithm like a recipe — first do this, then do that, then do this. Done.Machine learning of all types uses models and algorithms as its building blocks to make predictions and inferences about the world.Now I’ll show you how models actually work by breaking them apart, component by component. This next part is important. Part Three - A Framework for understanding ML **Inputs:** Statistical models learn from the past, formatted as structured tables of data (called **training data**). These datasets — such as those you might find in Excel sheets — tend to be formatted in a very structured, easy-to-understand way: each row in the dataset represents an individual **observation,** also called a datum or measurement, and each column represents a different **feature**, also called a predictor, of an observation.For example, you might imagine a dataset about people, in which each row represents a different person, and each column represents a different feature about that person: profession, age, income, etc.Most traditional models accept data formatted in the way I’ve just described. We call this structured data.Because one common goal of ML is to make predictions, training data also includes a column containing the data you want to predict. This feature is called the response variable (or output variable, or dependent variable) and looks just like any other feature in the table.Most common statistical models are constructed using a technique called supervised learning, which uses data that includes a response variable to make predictions or do inference. There is also a branch of ML called unsupervised learning, which doesn’t require a response variable and which is generally used just to find interesting patterns between variables (this pattern-finding process is known as inference). It is just as important as supervised learning, but it is usually much harder to understand and also less common in practice. This document won’t talk much about the latter subfield. The takeaway from this paragraph is simply that there are two “types” of learning, and that supervised learning is more common.Model selection: We have our data, and we’ve decided that there’s probably a relationship between our predictors and our response. We’re ready to make predictions.As an aside, we don’t actually need to know if there’s a relationship between these variables. We could, in fact, just throw all of our data into an algorithm and see if the resulting model is able to make valid predictions.Now we need to pick which model to use. Naturally, there are many different types of models which explain how the data actually works, and we’d like to choose the one that most accurately describes the relationship between the predictors and the response variable.Models generally fall into one of two categories:**Regression models**, which are used when the response variable (i.e. the variable that you’re predicting) is continuous. For example, height, age, and income are all continuous. That is, they can be placed and ordered on a number line.**Classification models**, which are used for categorical data — that is, data that doesn’t have a numerical ordering. For example, you may want to predict, based on an image of a flower, the species of that flower. Or you may want to predict whether a student is a psychology major or a math major.The first step in picking a model is deciding whether or not your response variable is quantitative or categorical.Why is model selection an important concept for non-technical people? Well, if a model is chosen poorly, then its predictions will be inaccurate!Below, I’ll walk you through an example of a popular, powerful, simple mode that can be used for prediction. Data from: https://alt.qcri.org/semeval2020/ Part Four - Let's Look at an example! ###Code # Import Libraries import pandas as pd import numpy as np import scipy import sklearn from sklearn import linear_model from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer ###Output _____no_output_____ ###Markdown Load data, split into training and validation sets ###Code filepath = 'data/train.csv' dataframe = pd.read_csv(filepath) print(len(dataframe)) # print(dataframe) dataframe.head() ###Output _____no_output_____ ###Markdown This is a text-based regression task. Every training document (a line in the data file) contains the following columns (csv format):**id:** document identifier;original: original news headline, in which one word is tagged between ;**edit:** the new word to replace the tagged word in the original headline;**grades:** a list of funniness grades (0="Not Funny", 1="Slightly Funny", 2="Moderately Funny", 3="Funny") concatenated into a single string. For instance, '1101' means four human judges looked at the edited headline and submitted funniness grades {1, 1, 0, 1};**meanGrade:** the average funniness value. In the previous example, meanGrade = (1+1+0+1)/4 = 0.75 .Your goal is to predict the average funniness value of an edited headline. More concretely, to predict the meanGrade (a real value) given an original headline, a tagged word, and an edit word. ###Code train_ratio = 0.7 # 70% for training, 30% for validation random_seed = None # a fixed random seed allows fixed random runs (for controlled debugging). set to None to be random. train_dataframe = dataframe.sample(frac= train_ratio, random_state=100) valid_dataframe = dataframe.drop(train_dataframe.index) print('training set size:', len(train_dataframe)) print('validation set size:', len(valid_dataframe)) # print(train_dataframe) ###Output training set size: 5067 validation set size: 2172 ###Markdown Also load test data (no splitting needed here) ###Code test_filepath = 'data/test.csv' test_dataframe = pd.read_csv(test_filepath) print('test set size:', len(test_dataframe)) # print(test_dataframe) test_dataframe.head() ###Output _____no_output_____ ###Markdown Try the trivial baseline: always predicting the average meanGrade (of training data) ###Code # take out prediction targets: mean grades train_Y = train_dataframe['meanGrade'] valid_Y = valid_dataframe['meanGrade'] ###Output _____no_output_____ ###Markdown The Root Mean Squared (RMSE) is our evaluation metric and is calculated as𝑅𝑀𝑆𝐸=√∑𝑛𝑖=1(𝑦𝑖−𝑦̂𝑖)2/nwhere 𝑦𝑖 is the actual funniness value of the document, and 𝑦̂𝑖 is the predicted value of the document, so (𝑦𝑖−𝑦̂𝑖)2 is the squared error of prediction. The lower RMSE, the more accurate prediction. ###Code # compute average of a list of numbers: np.mean train_Y_avg = np.mean(train_dataframe['meanGrade']) print('average meanGrade on training set:', train_Y_avg) # make a list filled with train_Y_avg, essentially predicting the same number for all lines in validation set avg_pred_valid = [train_Y_avg for i in range(len(valid_dataframe))] # print (avg_pred_valid) # compute root mean squared error (RMSE) of this prediction on validation set rmse = np.sqrt(mean_squared_error(valid_Y, avg_pred_valid)) print('RMSE on validation set:', rmse) #taking the mean as the error # helper function: write out prediction values into a csv format file # params: # df: dataframe, where each row is a test example, with column 'id' as data id # pred: a list or 1-d array of prediction values # filepath: the output file path # return: # None def write_test_prediction(df, pred, filepath): with open(filepath, 'w') as outfile: outfile.write('{},{}\n'.format('id', 'pred')) for index, row in df.iterrows(): outfile.write('{},{}\n'.format(row['id'], pred[index])) # make a list filled with train_Y_avg, essentially predicting the same number for all lines in test set avg_pred_test = [train_Y_avg for i in range(len(test_dataframe))] write_test_prediction(test_dataframe, avg_pred_test, './average_constant_baseline_new-tf.csv') ###Output _____no_output_____ ###Markdown Build feature extractor from training data (here we use a CountVectorizer or TfidfVectorizer ) ###Code # get entire raw text in training corpus, including title and edit words (for learning vocabulary and IDF) # params: # df: dataframe, with 'original' and 'edit' columns # return: # corpus: a list of text strings, each is a concatenation of original text and edit word on each line def get_raw_text(df): corpus = [] for index, row in df.iterrows(): title = row['original'].replace('<', '').replace('/>', '') edit = row['edit'] corpus.append( title + ' ' + edit ) return corpus ###Output _____no_output_____ ###Markdown More Information about Vectorization can be found here: https://towardsdatascience.com/different-techniques-to-represent-words-as-vectors-word-embeddings-3e4b9ab7ceb4 TF-IDF ( Term Frequency(TF) — Inverse Dense Frequency(IDF) ) is a statistical measure that evaluates how relevant a word is to a document in a collection of documents. This is done by multiplying two metrics: how many times a word appears in a document, and the inverse document frequency of the word across a set of documents.It has many uses, most importantly in automated text analysis, and is very useful for scoring words in machine learning algorithms for Natural Language Processing (NLP).TF-IDF (term frequency-inverse document frequency) was invented for document search and information retrieval. It works by increasing proportionally to the number of times a word appears in a document, but is offset by the number of documents that contain the word. So, words that are common in every document, such as this, what, and if, rank low even though they may appear many times, since they don’t mean much to that document in particular.However, if the word Bug appears many times in a document, while not appearing many times in others, it probably means that it’s very relevant. For example, if what we’re doing is trying to find out which topics some NPS responses belong to, the word Bug would probably end up being tied to the topic Reliability, since most responses containing that word would be about that topic. ###Code train_corpus = get_raw_text(train_dataframe) print(train_corpus) vectorizer = TfidfVectorizer(stop_words = None).fit(train_corpus) print(vectorizer.vocabulary_) #vectorizer = CountVectorizer(stop_words = None).fit(train_corpus) #print(vectorizer.vocabulary_) ###Output ['Congress OKs Trump bid to widen private care at besieged VA destroy', 'Trump and Obama have the same approval rating after their first year , at least according to one poll person', 'H.R. McMaster says Trump administration will confront Russia \'s " destabilizing behavior " lizard', 'Triple Threat : New Pneumonia Is Drug-Resistant , Deadly And Contagious President', 'Is it Watergate yet ? moving', 'Report : Trump Wants His Chief Of Staff To Get Rid Of Jared And Ivanka police', 'How the Right Co-Opts Frederick Douglass handedness', 'Forget Trump – populism is the cure , not the disease hugging', 'AP Fact Check : An angry Trump twists facts about raid , probe candy', 'Michelle Obama was Jimmy Fallon ’s only guest and , no , they did not mom dance enemy', 'DOJ charges 11 possible caravan members with illegally entering the US restaurant', 'How Steve Bannon became the face of a political movement with roots in Los Angeles Cheerleaders', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " people', 'As It Makes More Arrests , ICE Looks For More Detention Centers Recreation', 'Syrian state TV says successive blasts heard in Hama province eructations', 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon circus', 'Trump defends decision to keep “ political and long ” Democratic memo under wraps presents', 'Trump blames Corker for the Iran deal smell', 'Remember when Republicans were mad that a president was unreliable to allies ? mistress', "Childhood bullying anxiety ' goes away ' homework", 'Steve Bannon is reportedly advocating for a tax hike on the wealthy nature', ' Resignation Wave On Capitol Hill Might Not Be Over Radio', 'Six journalists get life in prison over failed Turkish coup film', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson scent', 'House Democrats stun GOP by sinking veterans , intel bills fences', "South Korea 's president is expected to face prosecutors in coming days canines", 'Schiff : Trump Jr. may have been first to know about Russian efforts to meddle in election mysteries', 'CDC to hold briefing on how public can prepare for nuclear war chickens', 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Kiss', 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants sons', 'GOP lawmaker loses nearly $ 17 million after pharma stock tanks 92 % aquarium', '2016 RNC Delegate : Trump Directed Change To Party Platform On Ukraine Support bra', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller wake', 'Obama ’s Strange Last Days in Office pets', "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' stupidity", "Could microwave missiles disable North Korea 's missiles ? cook", "' I was very angry ' at Trump , says Myeshia Johnson , widow of fallen soldier cake", 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN Stealing', 'Gunmam attacks a Church in Helwan , Cairo . Four dead and nine wounded . [ shooter killed ] pie', "Tech and entertainment activists launch an app to ' Block the Bully ' Donald Trump on Twitter patsy", 'Ex-British spy paid $ 168,000 for Trump dossier , U.S. firm discloses tea', 'Despite Campaign Boasts , Trump Has No Idea How To Handle Classified Material Smoothies', "Jailed Malaysian Opposition Leader To Be Pardoned After His Party 's Victory dance", "North Korea ICBMs : Pyongyang says it will conduct nuclear missile test ' anytime and anywhere it wants ' meme", "World 's largest collection of ocean garbage is now twice the size of Texas political", 'The Olympic Gold Medal for Sucking Up to a Murderous Totalitarian Regime Goes to … Vacuum', "Rex Tillerson : US has ' direct channels ' to Pyongyang scam", "' Black Panther 's ' Wakanda sheds light on black excellence darkness", 'Quotation of the Day : Trump Tried to Sink Inquiry , Comey Says hoops', 'DirecTV is offering refunds for NFL Sunday Ticket to fans offended by national anthem protests melody', "Congress ' deficit hawks seem to have gone missing in action doves", 'Drunken American beating up for giving Nazi salute in Germany praised', 'Occupy Silicon Valley : The next populist movement may be aimed at tech wealth , report says bunnies', 'How to Stop an Autocracy itch', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News Water", 'Trump is making Americans see the U.S. the way the rest of the world already did despise', 'Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . Reality', 'The Republican tax bill contains a sneaky break for private jet owners bathroom', 'Charlotte Pence : I Bought The Gay Bunny Book Wrote', 'This congressional accounting trick is part of the reason Washington is so divided magic', "Advice for Trump : Do n't fire Robert Mueller -- He will clear you in the end tickle", 'The middle class does n’t want a tax cut . It wants better government . coffee', 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it bear', 'Experts to Trump : Russia is not our ally in the war on ISIS bears', ' Trump predicts Patriots will win Super Bowl by 8 points gypsy', 'GOP senators : Comey drafted statement clearing Clinton before her interview tickling', 'Trump Official Blocked Immigrant Teen Rape Victim ’s Abortion Because He Personally Opposed It healthy', 'Trump ’s Trillion Dollar Pledge to Fix Bridges and Roads Could be Challenging . . Lie', ' Taiwan court to rule in in landmark same-sex marriage case Heterosexual', 'White House invites intelligence committee leaders to review National Security Council documents tweets', 'Fought and forgotten : Filipino World War II veterans honored with medal 75 years later days', "Trump officials greet Ford 's plan to import Chinese cars Food", 'Donald Trump Jr. should publicly testify in Russia probe , Democrat on Senate Judiciary Committee says strip', 'Trump addresses Boy Scouts at national summit in West Virginia loses', "Rep. King seeks more surveillance after Port Authority explosion : ' We ca n't afford to be politically correct ' bowel", 'Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR vegetables', "Israeli minister wishes Iranian protesters ' success ' pleads", 'More than 50 detained in immigration raids at Asian restaurants in Mississippi house', 'President Trump to hold another Q&amp;A on The Donald subreddit this Wednesday apocalypse', "In the former capital of the Confederacy , the debate over the city 's famed Civil War monuments is heating up mounting", "Trump blasts Michelle Wolf 's correspondents ' dinner remarks about Sarah Huckabee Sanders gravy", 'The Latest : San Juan mayor answers Trump ’s Twitter attack Wasteland', 'Special counsel Robert Mueller impanels grand jury for Russia probe koala', 'Five Pacific islands lost to rising seas as climate change hits sun', "Bill O'Reilly is ' mad at God ' for sexual harassment scandal Libido", "Trump labels US justice system ' laughingstock ' renames", 'Kamala Harris : Trump testimony is on the table dinner', 'Sean Spicer has a problem : Melissa McCarthy gum', 'U.S. Has Discussed Nuclear Weapons in South Korea manure', 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI Editors', 'GOP tax cuts will strengthen our economy and drive Democrats crazy biceps', 'Search for a Motive in Las Vegas : Slow but ‘ We ’ll Get There ’ Tortoise', 'Second judge denies Scott Walker ’s request to delay special elections Playground', 'Peskov : Trump lawyer wrote to Kremlin , got no response Santa', 'Forget Planet 9 — there ’s evidence of a tenth planet lurking at the edge of the solar system pleasure', 'Connecticut pastor charged with stealing $ 8G in electricity praying', 'Medicare-for-all progressive may just pull out a win in a key Nebraska House primary bowling', 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election rib', 'Wrenched From Scandal to Success , Trump Looks Ahead , and Over His Shoulder trips', 'TV station in Afghan capital comes under attack tent', "Elon Musk 's vision for underground road system bumps", 'Study : Hillary Clinton ’s emails got as much front-page coverage in 6 days as policy did in 69 swallowed', 'Trump Bodyguard Keith Schiller Testifies Russian Offered Trump Prostitutes , Aligning With Dossier Story Pimp', "Rubio 's defection threatens Senate GOP 's margin on tax bill greasiness", 'Somewhere between his hero , Justice Scalia , and former boss , Justice Kennedy lover', 'Trump Bodyguard Keith Schiller Testifies Russian Offered Trump Prostitutes , Aligning With Dossier Story Tacos', 'How can we save the Democratic Party ? Princess', 'UAE says Qatari fighter jets intercepted civilian flight raced', 'RIP Roger Moore ... James Bond goalie', 'Israel Must Release 16-Year-Old Girl Who Faces 10 Years In Prison , Amnesty Says Scotch', "Trump vows ' no amnesty ' for ' Dreamers , ' says GOP leaders ' on board ' with talks mimes", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans goat', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore cockroach", ' Survivor : We will only be heard if we scream @CNN Mime', 'Trump says banning immigrants helps US workers . A leading economist says he ’s wrong . poodles', 'Suicide bomber kills seven , wounds 20 in Afghan provincial capital : official shopper', "Alabama 's Roy Moore would be the most extreme senator — with huge consequences for Congress lecher", "Donald Trump 's Charlottesville remarks force White House to try to contain fallout spread", 'Chris Cornell , Soundgarden frontman , dies aged 52 graduates', 'A woman running for Congress faces a double mastectomy — and the repeal of the ACA latte', 'Before Trump , hate was already present in Canada cake', 'Puerto Rico benchmark bond drops to record low after Trump remark Spoke', "Women 's Heavy Disapproval Of Trump May Not Cut So Deep Against GOP In 2018 Midterms dessert", 'Parties fight over funding children ’s health insurance vomit', 'Sean Hannity ’s long-standing defense of sexual abusers promotion', 'Report : Jeff Sessions spoke with Russian ambassador at least twice during the election meeting', 'Government Accountability Office to Examine Cost , Security of Trump Florida Trips grocery', 'Trump Saw A Military Parade In France And Now He Wants One Of His Very Own . Dog', 'Yet another mystery motive automotive', 'Russia Blames Obama for Trump Failures in White House Out', "FBI ' reopens investigation into Clintons at Donald Trump 's request ' Martians", 'Trump administration may force CNN to be sold as part of $ 85bn deal scraps', "Cold weather : Do n't leave these things in your car when temps fall Cook", 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants eat', "Russia Will Test ' Unstoppable ' Satan Missile by End of 2017 , Says Military pancake", 'Portland train stabbing suspect said " that \'s what liberalism gets you , " docs say cake', 'Despite Promise of Bottom-Up , Transparent Process , Paul Ryan Sets Record for Stifling Floor Debate temperature', 'U.S. fighter jet shoots down Iranian-made drone in Syria turkey', 'Top Republicans urge Sessions to appoint special counsel to probe FBI feed', 'Trump : If Dems Get Back in Power , They ’re Going to Raise Your Taxes ‘ Way Up High ’ income', "Hurricane Maria : ' we have lost all ' says Dominica prime minister – live chuckles", 'Iranian oil tanker wreck produces two slicks in East China Sea drifting', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News dinner", 'A Reporter ’s Reflections on Hillary Clinton ’s Loss hair', " Keystone pipeline wo n't have to use American steel , despite Trump 's repeated promises steel", '“ Son of a bitch ” : Trump ’s NFL outburst fits a larger pattern tantrum', 'In court , a Turkish journalist delivers a searing attack on the government kebabs', 'More GOP Senators Say No , Killing Chances For Republican Healthcare Bill cows', 'Trump on Charlottesville : Racism is evil Barbecue', 'Youngest Texas shooting victim just 18 months old : What we know now licking', 'France , U.S. committed to wiping out Islamic State stain', 'The last president to fire an FBI director ? Bill Clinton cuddle', 'Poll : 60 % of voters back Trump ’s travel ban agoraphobics', 'Ruble plunges for 2nd day following US sanctions parties', "We 've got a deal : Government shutdown looks set to end as Democrats surrender Awaken", 'Male congressman questions why men have to pay for prenatal care . Really . fetuses', 'President Trump Set to Visit a Traumatized , Divided Las Vegas kick', "China 's Economy to Overtake Euro Zone This Year Absorb", 'Republican Debbie Lesko wins Arizona special election , NBC News projects lottery', 'Trump administration will review Iran nuclear deal despite compliance Tweet', "' Get ready Russia ' : Trump issues warning on Syria missile strikes bowling", 'Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says Wedgie', "Chester Bennington dead : Linkin Park singer ' dies aged 41 ' sang", 'Trump administration rolls back ObamaCare contraceptive mandate candies', "TRUMP FUMES AT MUELLER AFTER COHEN RAID : ' It 's an attack on our country ' insects", 'Trump urged Mexican president to end his public defiance on border wall striptease', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S escape', 'BREAKING : Trump considering options for Syria retaliation , source says vacation', 'Washington Post ’s David Fahrenthold wins Pulitzer Prize for dogged reporting of Trump ’s philanthropy crookedness', 'Pentagon claims 2,000 % increase in Russian trolls after Syria strikes . What does that mean ? accents', 'Trump judicial nominee refuses to express support for landmark desegregation ruling gratitude', "Los Cabos is no longer a haven from Mexico 's bloodshed cuisine", "Trump says he 's not worried what Flynn will tell special counsel ; there 's been ' no collusion ' worrying", 'North Korea says missile test shows all US within range earshot', "Mattis : ' I need to make the military more lethal ' hope", "Trump voters see his flaws but stand by president who ' shakes things up ' pelvis", 'Liu Xiaobo supporters mark his death amid concerns for widow Health', 'Police hold South African for trying Everest without permit shoes', 'Republican Senate Fundraising Arm Bails on Roy Moore spits', 'The Supreme Court ’s Blockbuster Term movies', "Word To The President : ' Professionalism ' moon", 'Trump is right -- California is out of control Jellybeans', 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food celebrating', 'Is the end of Donald Trump ’s presidency drawing nearer ? Either way he will have done great harm to America haircut', 'US Could Get First Paid Family Leave Benefit Under Trump flush', 'Treasury Department announcing sanctions against Iran Friday morning silver', 'Menendez Bribe Case Proceeds After Judge Rejects Dismissal Bride', 'White House says there ’s no need for new Russia sanctions celebration', 'North Korea crisis becoming unsolvable , experts warn , as Trump heads to Asia circus', 'Fyre Festival Organizers Hit With $ 100 Million Lawsuit Bong', 'Bannon , Lewandowski invited to testify before House Intelligence Committee Lie', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling Dressing', "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' bride", "Trump 's pardon of ex-Sheriff Joe Arpaio was the right ( and courageous ) thing to do haircut", 'US suspects Niger villager betrayed Army troops fink', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students Roofs", 'India to build major military facility in Seychelles amid growing China influence infest', 'Shrinking Bears Ears : Another massive insult to Native Americans Bears', "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in wash", 'The Republican tax bill contains a sneaky break for private jet owners island', 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Principal', "Trump 's history of breaking decorum with remarks on race , ethnicity profits", 'After a Debacle , How California Became a Role Model on Measles Debacles', "Russia 's boost in trade with North Korea worries U.S. hackers", 'Trump said Haitians have aids , Nigerians live in huts in oval office meeting bacchanal', '" We could be separated " : Immigrants , families react after Trump administration ends protected status Condiments', 'Stormy Daniels tells of threats following reports of affair with Trump cookbook', "Intel chiefs wo n't say if Trump asked them to intervene in investigations opera", 'Jerusalem Mayor to Trump : Do n’t be Intimidated By Palestinian Threats Of Violence , Move Embassy Hummus', 'Border Patrol Shooting Death Of Immigrant Woman Raises Tensions In South Texas backpack', 'Eighteen people found guilty over Newcastle sex grooming network virgins', "Spicer , denying report on Sally Yates : ' I hope she testifies ' attention", 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia dog', 'Senate Intelligence Panel Subpoenas Former National Security Adviser Michael Flynn Oxen', 'Bump Stock Maker Resumes Sales One Month After Las Vegas Mass Shooting Eating', 'The Russian government is giving up control of Kalashnikov remote', 'Teachers , Lawyers And Others Worry About The Fate Of Student Debt Forgiveness disappearance', 'Alternatives to Putin a mixed bag as Russian election looms drinks', ' Advocacy group accuses military justice system of racial bias Girl', ' Trump judicial nominee refuses to express support for landmark desegregation ruling bonehead', 'After a Debacle , How California Became a Role Model on Measles Plague', 'Disgusted By Trump , A CIA Officer Quits . How Many More Could Follow ? smoking', 'Syrian President Assad faces international pressure to step down , but in Damascus there is a mood of defiance boogie', "' Maybe I did n't get her so much ' : President Trump on first lady 's birthday fat", 'Trump maps new course with allies and autocrats in first foreign trip prostitutes', 'Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . autograph', 'Six journalists get life in prison over failed Turkish coup delight', 'Trump Lawyers Want A Second Special Counsel sitters', "This Is n't ' Another Watergate ' But It Plays As One On TV – And On Twitter Broadway", 'Vornado Has ‘ Handshake ’ to Sell Stake in NYC Tower to Kushner Give', "China could strike U.S. bases in ' minutes ' — and may be practicing years", "Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' waltzing", 'Lee Jae-yong , Samsung Leader , Is Indicted on Bribery Charges kidnapping', "Has the UN failed Myanmar 's Rohingya Muslims ? kittens", 'Out of loopholes , Trump must disclose Stormy Daniels debt in next financial report fee', 'New DOJ alert system will flag crimes against police fashion', 'Manafort Notes From Russian Meet Refer to Political Contributions legs', 'Trump Is Giving Staffers Secret Assignments And Telling Aides To Hide Them From John Kelly haircuts', "Robert Mueller reportedly looking into Trump 's ' attempt to oust ' Jeff Sessions decency", "US says refugee admissions wo n't be suspended until July 12 auditions", 'Lieberman emerges as frontrunner for FBI post relay', 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food delicious', 'Idaho Is Fastest-Growing State in U.S. potato', 'Trump quietly stalls safeguards for dozens of endangered species bakers', 'South Korean police on alert over Trump protests chickens', 'Medicare X : the Democrats ’ supercharged public option plan , explained bathing', " Trump : ' I have no doubt that we 'll win ' travel ban lawsuit Gorilla", 'AP FACT CHECK : Trump and the Washington blame game themselves', 'Grassley promises hearings into McCabe ’s firing once inspector general ’s report is public gadget', 'Hillary Clinton receives standing ovation at ‘ The Color Purple ’ on Broadway imagines', 'Steve Mnuchin Says It ’s ‘ Very Hard ’ Not To Cut Rich People ’s Taxes Hedges', 'Report : Trump Wants His Chief Of Staff To Get Rid Of Jared And Ivanka Assassinations', 'Iran successfully launches satellite-carrying rocket into space tree', 'North Korea calls US aircraft carrier dispatch outrageous striptease', 'Eight dead in M1 minibus and lorry crash refrigerator', "Rohingya crisis : Israel says ' both sides committing war crimes ' when asked about Burma violence food", 'Contradictions upon contradictions in the tale of Trump payoff to porn star offer', 'Ex-rising star of French far right steps into US limelight slithers', " Putin accuses US of interfering in elections , does n't deny having compromising information on Trump Elf", 'Warning over ferry link terror risk - BBC News missing', "Keystone XL pipeline will not use U.S. steel despite Trump 's vow beer", 'Really no-one will miss this asshole kiss', 'Murdoch makes $ 2.6 billion bet on Indian cricket buffet', 'Sessions clears key hurdle to be attorney general speedster', 'DNC chair candidate Jaime Harrison : lobbyists can be good Democrats appetizers', 'Billionaire Babis scores big Czech election win , seeks partners to rule annoy', 'The Latest : China protests added missile defense in S. Korea party', 'Putin critic cleared to travel to US skip', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says Quilts', " Trump 's approval rating 12 points higher among men : Gallup Beer", ' Republicans still at odds over Obamacare after closed-door meeting Evens', "Americans ' release in North Korea seen imminent ; Kim meets Chinese tour", "Network of wealthy Russians has sunk $ 100m into Donald Trump 's luxury developments hair", 'Scientists turn hydrogen into metal in breakthrough that could revolutionise the planet jazz', 'The potential legal train wreck ahead for Fox News and Bill O’Reilly Clowns', 'Michelle Obama was Jimmy Fallon ’s only guest and , no , they did not mom dance swap', 'Trump Booed At Davos For Criticizing ‘ Fake ’ Media ’ hair', 'Student injured after shots fired at high school downed', 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House farm', 'Sam Harris , Charles Murray , and the allure of race science werewolf', 'Trump tweets about bombshell report that said Clintons made millions off crooked Russian uranium deal finger', "P.F. Chang 's heads to China to serve American-style Chinese food checkers", 'Hung parliament : What it could mean for Brexit negotiations gigolo', ' Vehicle plows into protesters in Charlottesville Man', "Trump claims ex-intelligence chief Clapper admitted FBI spied on his campaign . That 's false . poodle", 'Trump Poised to Ease Rules on Religious Groups in Politics churches', 'Pelosi : Trump ’s insecurity fueling fraud investigation security', 'Contempt of court : Trump ’s judicial blitz betrays his hostility to rule of law Thumb', 'An anti-immigration rally in Brazil turns violent seance', 'Indian and Chinese troops clash in disputed Himalayan border region Restaurants', 'Barclays former CEO John Varley and three top bankers to appear in court over fraud charges musical', "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' hair", ' Justice Dept. charges 9 Iranians in massive hacking scheme Butcher', 'Mattis says there is “ no doubt ” U.S. is committed to NATO countries parties', 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say fireworks', '‘ Fox &amp; Friends ’ scolds CEOs who pulled out of Trump council vagina', 'Democrats are heading toward some big losses in midterm Senate races , polls say horse', "The author of the ' fake news ' dossier on Trump 's ties to Russia is looking increasingly credible Laundry", 'Why Congress just killed a rule restricting coal companies from dumping waste in streams children', "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile rope", 'With 60 Killed In Gaza , U.N. Rights Commissioner Criticizes Israel cupcakes', 'Duterte spokesman : Trump offered to return Philippine fugitive during bilateral talks tweet', 'Trump ’s tax plan would reward the wealthy and balloon the federal debt Deport', "These Are the World 's Most Innovative Economies cupcakes", 'Ellison backs banning lobbyist contributions to the DNC chairs', 'Trump says Toyota will face tariffs on cars made in Mexico boats', 'Moore dodges the press as harassment scandal spirals harasses', "Japan economy minister declines comment on Trump 's Toyota tweet sushi", 'Kelli Ward : " we need a clean border security bill first and foremost " bikini', "Scientists build DNA from scratch to alter life 's blueprint sasquatch", 'The White House wants to lead on tax reform — it just needs a tax reform plan first stupid', 'Social media data shared by spy agencies cat', 'Trump ’s Harsh Language on North Korea Has Little Precedent , Experts Say Dogs', 'Trump predicts Patriots will win Super Bowl by 8 points Hoagie', "London attack : Molotov cocktails ' found in back of terrorists ' van ' bartenders", 'US ambassador to South Korea announced by White House vacation', 'Venezuela claims 41.5 % turnout in violent constituent assembly vote drilling', "Protesters read Coretta Scott King letter outside McConnell 's house bathroom", 'Thousands of women march in cities across the world to express support for President Trump mockery', "Pete Sessions on Border Wall Funding Passage : We Are Delivering ' What the President Wanted ' Racists", "Calais violence leaves four teenage refugees in critical state as smuggling gangs ' exploit growing desperation ' turtles", 'Gateshead council vows to pay nothing for Trump state visit and urges other local authorities to do the same cheapskates', "GM CEO says company wo n't change production plans despite Trump tweet shenanigans", 'Trump is likely going to visit FBI headquarters in the next few days decades', 'Bannon , Lewandowski invited to testify before House Intelligence Committee scream', 'Shooting reported at Maryland high school , sparking lockdown Sparklers', "Faithful flock to Vatican for pope 's Christmas Eve Mass mall", 'Some global investors see fresh worries in an old problem : China fudge', 'Republican senators realizing legislative agenda is in their own hands menu', "HHS readying new rule to expand ' conscience ' protections eliminate", 'How to cripple a presidency in 10 days purchase', "Democrats ' call to action after Vegas shooting includes plea for ' moral courage ' on gun control legislation mind", 'Dakota Pipeline that native americans protested because of possible leaks ? It leaked . animals', "Reporter says he was ' manhandled ' by FCC security at net neutrality meeting rumble", 'Paul Ryan threw Republican senators under the bus on their healthcare failure sloths', 'Stocks close lower as Trump says China trade talks may not be successful mocking', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel wizards', "Lawyer : Trump and attorney Michael Cohen were told about NY Attorney General Eric Schneiderman 's alleged abuse of women in 2013 tacos", 'U.S. military plane crashes in Mississippi , at least five reported dead bicycle', 'HHS told Obamacare workers their budget was safe mother', 'AP Fact Check : An angry Trump twists facts about raid , probe roaches', 'Flynn Violated Constitution With Russia Speech , Democrats Say martini', "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' Admission", '43 year old Coffee Farmer in Hawaii smuggled in at 15 years old Loses Deportation Battle , Returns to Mexico Salmon', 'Jared Kushner is hyping a peace deal as Israel kills scores of Palestinian protesters during US embassy move to Jerusalem sign', "Kushner reports millions in 77 previously ' omitted ' assets pennies", 'Did Manafort promise banker White House job in return for home loans ? leftovers', "Trump blasts Michelle Wolf 's correspondents ' dinner remarks about Sarah Huckabee Sanders loves", "Right-wing and ' radical Islamic ' terror in the U.S. are equally serious threats : ADL report music", "AT&amp;T CEO : ' We ’re prepared to litigate now ' over Time Warner deal cry", 'Trump , GOP Hill leaders to meet at Camp David in January igloo', 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul Scam', 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . overlords', 'Spicer deflects questions on reports that White House helped Nunes get surveillance reports lasers', 'Bridgegate scandal lands Christie ally Bill Baroni two years in prison cells', 'Sen. Jeff Flake says he will not seek re-election in 2018 , citing nastiness of Trump-era politics dinners', 'UK universities urged to tackle rising tide of antisemitism on campus tickle', 'Lee Relative Who Denounced White Supremacy Resigns As Pastor Of N.C. Church Wizard', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs deodorant', 'Trump suddenly replaces acting Customs head Daniel Ragsdale with Thomas Homan ugly', 'The Latest : Kushner lawyer pointed out potential conflict energy', 'White House Backs Away From Investigation Into Voter Fraud Claims Trump Made Up Runs', ' Inauguration Crowd - 2009 vs. 2017 Stadium', 'Rex Tillerson is approved by Senate panel for secretary of State ladders', "Trump threatens ' Little Rocket Man , ' says Kim may ' not be around much longer ' kisses", " White House says Trump is n't considering firing Mueller Waffle", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' moons", 'Cohen promised health care company access to Trump White House , exec says crack', 'Comey Testimony : Trump Faces Cost of Listening to Bad Advice Confession', 'Who really is Trump ? President ’s Nevada speech wildly different from Arizona rally temperature', " China could strike U.S. bases in ' minutes ' — and may be practicing elephant", 'EPA to reduce workforce with buyouts , early retirement plan execution', "Sen. Kamala Harris says she has n't considered running for president buses", 'GOP Could Lose a House Seat in a District Trump Won by 19 Points Bus', 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives guns', 'Kamala Harris : Trump testimony is on the table gut', "Trump doubles down on ' I inherited a mess ' claim made", 'What the dip in US life expectancy is really about : inequality upswing', 'Democratic National Committee Asks Its Entire Staff To Resign Prom', 'Robert Reich : Trump Has Divided Americans Into Two Warring Camps potatoes', 'Red state lawmakers find blue state piggy bank smash', 'President Trump ’s ‘ impulsive ’ problem dancing', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking game", 'White House counsel Don McGahn threatened to resign in June , sing', 'Cable news is careening toward a defining moment broadside', 'Trump tweets about bombshell report that said Clintons made millions off crooked Russian uranium deal cries', 'What Does Obama Know About Trump-Russia Scandal ? Newt Gingrich Wants Him To Testify Before Congress lie', "Trump holds joint press conference with Norway 's prime minister — live updates rib", 'Sir Roger Moore , known for his role as James Bond dies at age 89 due to cancer . acting', 'Trump threatens to cut aid to UN members who vote for withdrawing his Jerusalem decision shoe', 'Forget term limits — retirements will create competitive 2018 elections speed', 'All the things Congress probably is n’t going to do this year grandpa', 'U.S. government posts $ 192 billion deficit in February Monopoly', 'Sen. Bob Hertzberg will cooperate with investigation into unwanted hugs aromas', 'Live , long and black giant shipworm found in Philippines dreadlock', 'Barack Obama ’s Chicago Library Is Not a Library Nor a Believer in the ‘ Community ’ museum', "Bill Kristol was once the voice of the Republican Party . Now he 's one of Trump 's biggest opponents bladder", 'Manslaughter charges eyed in deadly Grenfell Tower blaze barbecue', 'If weed is no longer a crime , why are people still behind bars ? plants', 'Seattle to dismiss misdemeanor marijuana charges dynamite', "Trump 's approval rating up after tough North Korea talk , new poll shows ballet", '‘ Noncriminal ’ immigrant arrests double in past year : report festivals', 'Democrats Should Not Fear the Nuclear Option Sweater', "Examining What We Know And Do n't Know About Trump And Russia tanning", "Mosque attack in Egypt 's Sinai kills at least 235 befuddles", 'Schumer to donate Harvey Weinstein contributions cologne', 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language lingerie', 'California bullet train costs soar to $ 77 billion , opening delayed model', "BBC : ' Dozens dead ' after military plane crash in Algeria dump", 'WORLD NEWS N.Korea fires Scud-class ballistic missile , Japan protests , Trump briefed pancake', 'Google Search Is Doing Irreparable Harm To Muslims hamsters', "Armenian leader resigns , says to protesters : ‘ I was wrong ' sobs", 'Judge skeptical of Manafort suit challenging Mueller ’s authority outfit', 'Trump set to meet Pope and Italian PM Gentiloni . trip', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation drunken', 'Theresa May will not take part in general election debates , say Tory party sources favors', 'Trump Names Anti-Abortion Leader Charmaine Yoest to High Post at HHS chair', 'The Long , Lonely Road of Chelsea Manning hair', 'If the G.O.P. Tax Plan Hurts You , Congressmen Say It ’s Your State ’s Fault Mother', "EPA chief : Trump 's energy order sends ' pro-growth , pro-environment message ' pizza", 'Trump partner said in running to build FBI headquarters dressmakers', 'An Obamacare insurer flees another state , blaming Trump and the GOP for sabotage bats', "How US ' get out of jail free ' cards work ice", 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Bewildered', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr brayed", 'Japan foreign minister hopes for improved ties with China rope', 'Everything You Need to Know About the U.S. Shutdown Sing', 'OPEC and Russia reportedly agree to extend oil production cut to end of 2018 vodka', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK Sorceress', ' Donald Trump Begins Yet Another Day By Attacking Jeff Sessions Crocodile', 'There is no 1st Amendment right to speak on a college campus sneeze', 'Analysis | Donald Trump promised to make the ‘ best ’ deals . It ’s time to prove it on healthcare . muffins', 'Jordan Selects Finalists to Bid for 300MW of Solar , Wind Power earth', 'Trump looms over Georgia special election education', "VA 's quiet plan to widen private care with TRICARE stirs ire headaches", 'Donald Trump becomes least popular first-year president in modern US history , polls find mascot', 'Congress , pointing fingers amid shutdown stalemate , returns to work pool', 'White House backs bill criminalizing abortions after 20 weeks burritos', 'Report : Millions of tweets spread anti-Semitic messages matzos', 'Yemen cholera cases reach one million - ICRC hiccup', 'Trump has the upper hand in North Korea talks handshake', 'GOP Plan Has Trillions in Tax Breaks for the Rich Coffee', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump sings', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. pornography", 'U.K. Has a Secret Plan to Hold Brexit Cash if EU refuses to Trade . dance', 'The White House ’s John McCain death joke controversy , explained fan', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . influence", 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " Everything', 'China ’s Xi Takes on Trump in Rebuttal Against Protectionism Rant', 'Sarah Sanders confirms White House position : Trump accusers are lying crab', 'These charts show Fox News really did ignore Puerto Rico ’s crisis horoscopists', "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' thoughts", 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin smoke', 'Teacher apologizes for accidentally firing gun in classroom student', 'Attorney General Jeff Sessions to end US policy that let legal pot flourish [ Associated Press ] freedom', "Justice wants ' sanctuary cities ' in California and 7 other states to cooperate with immigration enforcement driving", 'Trump has the upper hand in North Korea talks game', 'Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 marathons', 'President Trump ’s ‘ impulsive ’ problem colon', "Brexit : Businesses warn over ' UK workers first ' proposal - BBC News stink", 'BuzzFeed Posts Unverified Claims on Trump , Igniting a Debate trolls', "Trump Jr. says missing out on India deals because of father 's self-imposed curbs celibacy", 'Protesters disrupt rightwing German AfD party congress . goers', 'Reporters to Trump ambassador : ‘ This is the Netherlands — you have to answer questions ’ - He refused to answer . windmill', ' Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 Horses', 'Spending bill excludes border wall , but Trump declares victory anyway bankruptcy', 'Obama Admin lawyers had ‘ justifiable concerns ’ about sharing intel with Trump team . soccer', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says snitches', 'Democratic Sen. Joe Manchin skips Obama Hill meeting informational', "We 've got a deal : Government shutdown looks set to end as Democrats surrender problem", 'Useful Idiots Galore - The New York Times dinner', "Armenian leader resigns , says to protesters : ‘ I was wrong ' juggler", 'Report : Hillary Clinton protected aide accused of sexual harassment in 2008 healing', "5 things Trump did while you were n't looking : Week 6 dancing", 'Alt-Right snowflakes play victim in hopes of mainstream sympathy music', 'Democratic National Committee Asks Its Entire Staff To Resign pray', 'Trump Lifts Obama ’s Curbs on Military Equipment for Cops Dresses', 'Trump announces U.S. military strikes in Syria waterpark', '3 potential problems for an obstruction of justice case against Trump bribes', 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite decision', "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban donut", "FULL SPEECH : At Davos , Trump touts reforms : ' America is open for business ' immigrants", 'US Treasury eases some sanctions against Russian intelligence service delivery', "Religion Trump responds to ruling on travel ban : ' SEE YOU IN COURT ' sweating", 'Australia to accept first Central American refugees under U.S. deal nose', 'Trump told advisers a government shutdown would benefit him politically self', "Melania Is Trapped In The White House , Says France 's First Lady dog", 'Robert Mueller is following the money , and that may put Trump in serious danger bra', 'Medicare Advisers Recommend Payment Cuts To Many Free-Standing ERs hair', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' guns", "The corporate media ignores the rise of oligarchy . The rest of us should n't yeast", "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' lizard", 'North Korea Launches Another Missile , Escalating Crisis Insult', "Trump : Whether it 's a ban or not , it 's keeping ' bad people ' out mold", 'The Alex Jones influence : Trump ’s “ deep state ” fears come from his conspiracy theorist ally and adviser bro', 'We Wo n’t Have Hillary Clinton to Kick Around Anymore prance', 'An Obamacare insurer flees another state , blaming Trump and the GOP for sabotage bird', 'Treasury Department announcing sanctions against Iran Friday morning money', 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite Devil', "China 's Xi ' may get own political theory ' Wall", 'Congressional aides may have answers on pro-Russia GOP platform change shoes', 'Mississippi law endorses anti-LGBT bias , attorneys argue gays', "The only way his voterbase will come to terms with what they 've done dance", "Trump 's latest approval ratings could jeopardize his entire presidency suntan", 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns bridge', 'Dozens feared dead or missing after storm swamps the Philippines undead', "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' hamsters", 'Israel : US-Led Strikes enforce Red Line on syria . Kisses', 'White House axes transgender protections just days after Donald Trump claims to support LGBT rights | The Independent trees', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . women', ' States Mired in Budget Paralysis Defy Eight-Year Recovery Child', 'Top labor leader resigns from Trump ’s jobs council after Trump blames ‘ both sides ’ for Charlottesville violence pies', 'Kushner still waiting on permanent security clearance guard', 'CAROLINE GLICK : Palestinian Leader ’s Anti-American Rant Gives Trump Cause to Cut Funding camel', 'Are Women Candidates Winning More In 2018 ? fake', 'Robert Mueller examining blocked Trump letter that explains his reasons for firing Comey risque', "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' recreation", 'Trump goes into dealmaking mode , works behind the scenes on health bill duck', "US ambassador to Netherlands describes own words as ' fake news ' president", "US cuts women 's health funding to UN clothing", 'Bush-era diplomat tweets that you should be scared , very scared president', 'Israel to legalise isolated settlement deep in West Bank after settler murdered , Netanyahu announces dumpster', "The timing once again suggests that Trump tweeted after watching a ' Morning Joe ' segment chick", 'Hung parliament : What it could mean for Brexit negotiations painting', 'Nunes temporarily steps down from House probe on Russia : statement promotion', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip meal', "Heads Up : Look What Trump 's Already Done to Obamacare pumpkin", 'Key Dem wants probe on whether Trump payment broke ethics laws jaywalking', 'The Latest : In call , Trump backs Moore , dubs him a ‘ fighter ’ knight', 'China Lavishes Red-Carpet Treatment On Trump As He Arrives For Talks With Xi Jinping Oscars', "Court blocks law that would have closed Mississippi 's only abortion clinic band", "Blake Farenthold , Texas lawmaker accused in sexual harassment suit , wo n't seek re-election diving", "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' Missile", "Trump Jr. : I went to meeting with Russian lawyer because ' I had to listen ' dance", 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap winning', 'Affirmative-action hypocrisy : Foes hope to use Asian-Americans to attack racial diversity on campus hunt', "Eric Trump : Those Who Oppose My Dad Are ' Not Even People ' Funny", 'Donald Trump becomes least popular first-year president in modern US history , polls find pumpkin', 'The Latest : Japan protests N. Korean missile test attempt restaurant', 'What Does Obama Know About Trump-Russia Scandal ? Newt Gingrich Wants Him To Testify Before Congress Children', 'Trump : If Dems Get Back in Power , They ’re Going to Raise Your Taxes ‘ Way Up High ’ energy', 'Trump chief of staff : defense officials not off NSC after Bannon move dense', 'Lawmakers seem confused about what Facebook does — and how to fix it use', "Top Russian Court Bans Jehovah 's Witnesses , Claiming ' Extremist Activities ' deodorant", "Former CIA director Petraeus warns that the current international order could ' fray ' and ' collapse ' harvester", "Trumpcare is causing Wall Street to question Trump 's whole economic agenda dementia", 'Western airstrikes unlikely to impact Assad ’s war machine time', 'The evangelical slippery slope , from Ronald Reagan to Roy Moore soap', 'Trump and Sessions are weaving immigration policy from propagandistic fantasy music', 'Fought and forgotten : Filipino World War II veterans honored with medal 75 years later tickled', 'Can Democrat Doug Jones pull off an upset in Alabama ? bed', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets sweeteners", 'Donald Trump is a Certified Dumb Ass , according to Psychologist psychoneurotic', ' Kamala Harris is shut down again Computer', 'Sold into marriage : how Rohingya girls become child brides in Malaysia pets', 'White House : Trump will not immediately bolt NAFTA join', 'James O’Keefe Busts New York Times Editor Explaining How Paper Sets Anti-Trump Narrative balloon', "America 's U.N. ambassador Nikki Haley demands UN withdraw report branding Israel ‘ apartheid ’ state tractor", 'Turkey protests : Erdogan accuses EU of hypocrisy clucking', "Trump 's General Pershing Remarks Cited in Travel Ban Case Ruling bag", 'Effect of US military ban on transgender troops remains to seen congressmen', 'Steve Wynn resigns as RNC finance chair reclining', 'Trump says China ’s Xi is “ president for life ” — and maybe America should try it suck', "' Suck Up ' Mitt Romney Trolled For Flip-Flopping On Trump 's Endorsement wig", 'US missile defense test triggers alarm in Russia , China as North Korea issues new warnings story', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of Fantasy', 'Will Trump Order Seth Rich Murder Investigation ? Former Aides Say Democrats Killed Staffer to Protect Hillary Clinton newscasters', 'Iraqi forces close in on Tigris in IS stronghold Mosul clubhouse', "Putin accuses US of interfering in elections , does n't deny having compromising information on Trump Poodle", "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' supporters", "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news vacation", "Trump 's D.C. hotel raised room rates after inauguration : report party", 'Trump to Dems : Of course I colluded , big deal ! I fuck my daughters too time', 'Canada blocks Chinese takeover of Aecon on national security grounds takeout', "Ellison : Trump has ' no clue ' about true sacrifice bakeries", 'Kim Jong Un agrees to meet Donald Trump at DMZ , sources say kiss', 'Jackie Mason : Grammys A Competition ‘ About Who Hates Trump More ’ Music', 'Trump ’s Trillion Dollar Pledge to Fix Bridges and Roads Could be Challenging . . hair', 'Watch : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” golf', "Trump 's Saudi trip : Thumbs up and other ' controversies ' grocery", 'Navarro : Do not joke about American diplomats - CNN Video eagles', "Yet again , Trump 's defensiveness makes his handling of a gold-star family 's grief worse mail", 'Park Geun-hye , South Korean President , Is a No-Show at Impeachment Trial dancer', 'Minnesota Republican Rep. Tom Emmer On Trump , Russia And Obamacare Repeal Snow', "Boris Johnson condemned in Libya for ' dead bodies ' remark jokes", "DNC chair candidate wants to ' shut other white people down ' bleach", 'Will Democrats Who Backed Trump in 2016 Back The GOP In 2018 ? children', 'Donald trump will not be given state visit treatment by the UK Spa', 'Chinese spies targeting U.S. maritime industry : restaurants', "Cape Town drought : South African city may avoid ' Day Zero ' towel", "World 's largest general science organisation slams Trump 's lack of ' scientific thinking ' store", 'Nancy Pelosi Hails ‘ Debt We Owe ’ to Parents Who Bring Kids to U.S. Illegally dolls', 'Le Pen Moves Into Lead in French Race , Le Monde Poll Shows studio', 'Swedish prosecutor says truck attack suspect has not spoken stuffing', 'Ban Trump ’s sad view of America depression', 'German girl arrested in Mosul is missing Linda Wenzel , say authorities . Shepherd', 'Republican Vermont governor vetoes marijuana bill , wants changes made joints', 'Google Fires Employee Behind The Controversial Diversity Memo promotes', 'Among Republicans , Trump is more popular than congressional leaders mascots', "China 's Economy to Overtake Euro Zone This Year sprinter", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk wrestle', 'Joe Biden calls President Trump a liar in the nicest way ever sweetheart', ' Hundreds of immigrants will get to resubmit DACA renewals originally rejected as “ late ” Trillions', "Ross 's Stake in Putin-Linked Shipping Firm Raises Ethics Concern Brothel", 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE alien', 'The Latest : Saudi royals to make pledge to new crown prince cake', "WH : North Korea participation in Olympics ' does n't affect the US ' centenarian", "Trump 's State Of The Union Victory Lap On ISIS Is Garbage landfill", 'FCC Chairman Pai defends his attack on net neutrality by substituting ideology for history art', " Chinese ' chuckle at Trump for messing up picture-perfect America ' : State media Simpletons", "Why African millennials ca n't get enough of Bitcoin steal", 'The ‘ genius ’ of Trump : What the president means when he touts his smarts hair', ' Trump Takes Own Path as G-7 Fails to Reach Unity on Climate Tree', 'Among Republicans , Trump is more popular than congressional leaders cake', 'How Facebook Made Its Cambridge Analytica Data Crisis Even Worse friend', 'We Wo n’t Have Hillary Clinton to Kick Around Anymore footballs', 'Saudi King ’s Son Plotted Effort to Oust His Rival shave', 'Cannabis Drug Halved Convulsions in Company-Funded Epilepsy Test munchies', ' James Comey ’s Opening Remarks : It ’s All About Him mistress', 'Famine-hit South Sudan to charge up to $ 10,000 for foreign work permits Pizza', 'U.S. consumer protection official puts Equifax probe on ice head', 'Former intel chief Hayden : Trump ‘ willing to throw almost anything against the wall ’ to ‘ de-legitimize ’ Mueller probe portrait', 'Widespread killings of candidates cast shadow over Mexican elections laughter', 'Suspected rebel-planted mine hits Yemeni ship , kills 2 insult', 'Iraqi forces close in on Tigris in IS stronghold Mosul bathroom', 'Federal judge blocks new Texas abortion ban pie', 'Instant view : U.S. stocks sharply lower , Trump plans questioned nightmares', ' Trump : ‘ NO MORE DACA ’ Immigrants', "Hillary Clinton Staffers Considered Campaign Slogan ' Because It 's Her Turn ' drinking", 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia award', 'Barack Obama Tweets Uplifting Local Stories To Remind Us What Went Right In 2017 sings', 'WATCH : Jeremy Scahill says Fareed Zakaria ‘ would have sex with ’ missile strike , bashes media coverage of Syria on CNN Silo', "Waters : I ' would n't waste my time ' having a private conversation with Trump seance", 'Democrats Join Republicans In Bill Criminalizing Speech Critical Of Israel chocolate', 'Donald trump will not be given state visit treatment by the UK duck', 'Fox News is No. 1 cable news network for 63rd straight quarter propaganda', 'Residents : Strikes hit presidential palace in Yemeni capital bathroom', 'Terrorism by Muslims makes up one-third of 1 percent of all murders in the US newborns', 'Trump has pledged $ 1 million to Harvey relief , White House says constipation', 'Loosely regulated market for biofuel credits spurs speculators and swindlers polluters', "BET founder : Trump 's economy is bringing black workers back into the labor force panthers", "Democrats see Pa. vote as start of anti-Trump ' Blue Wave ' hair", 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ unicorns', "Puerto Rico oversight board wants changes to island 's fiscal plan mob", 'North Korea is building mysterious artificial islands that would be perfect for missile launches worshiping', "The Health 202 : Republicans can run from health care debate , but they ca n't hide dematerialize", 'Newly released Howard Stern Show tapes feature Donald Trump admitting to psychological problems Issues', 'Twitter bans RT and Sputnik ads amid election interference fears satellite', " New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' hippo", 'Democrat Katie Hill to take on endangered Republican incumbent Steve Knight in CA-25 ! nibble', 'Major blow to Ukraines Ammunition supplies . cupcake', 'Trump faces a higher authority : Pope Francis fights', "These Google employees used their '20 percent ' time to improve Maps for people in wheelchairs malls", 'Report finds sloppy handling of sexual misconduct cases in Justice Department handwriting', 'Vice ’s documentary on Charlottesville is really worth watching pirating', "GOP ' chickens ' just do n't get it on tax reform poultry", 'Kim reviews Guam strike plan as Mattis issues stark warning bowling', 'Franken to quit Senate amid allegations sneezing', 'Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage Media', 'North Korea video portrays U.S. destroyed in missile barrage spaghetti', 'DHS secretary : Electronics ban may be expanded to flights departing US wires', "Japan economy minister declines comment on Trump 's Toyota tweet tattoo", 'Get The Best Gabbanelli &amp; Cantabella Accordion sock', 'Advisers bad-mouth Nielsen as a ‘ never Trumper ’ barber', 'Trump firing Mueller ? Impeachment would follow , two Republican senators say . Celebration', 'CEOs could tame Trump , if they wanted to fire', 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation Underwater', 'House Republicans preparing to subpoena Comey memos porn', "He 'll Take ' Gubernatorial Debate ' For 400 : Trebek Tries Out Moderator 's Chair sells", "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile jacks", ' Bill aiming to protect Christians , other minority groups in Pakistan may soon be law Gun', 'Terror-Affiliated Group Is Part of Coalition to Stop Trump Inauguration parade', 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress casino', 'How Putin Will Manipulate Us in 2018 Children', "Congressional Dems making early calls for Trump 's impeachment delousing", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia camels", 'Youngest Texas shooting victim just 18 months old : What we know now democracy', 'U.K. Outcry at Trump ’s Tweets Reopens Fight Over State Visit barber', 'Infosys plans to hire 10,000 U.S. workers after Trump targets outsourcing firms jail', 'James Comey fired : Donald Trump fires FBI director dishwasher', 'Senate intelligence panel postpones hearing with Trump personal lawyer seance', 'An American Journalist Is Facing A Felony Trial This Week — In The United States clown', 'Trump Swaps His Beloved Burgers for Salads and Soups in New Diet lie', 'Ireland to get new leader as Enda Kenny steps down gets', 'Former intel chief Hayden : Trump ‘ willing to throw almost anything against the wall ’ to ‘ de-legitimize ’ Mueller probe rub', 'Jobless Claims in the U.S. Plunge to Lowest Weekly Tally since 1973 seals', 'A Noun , a Verb and Vladimir Putin adjective', 'CIA director warns Iranian general on Iraq shopkeeper', 'The best theory for why Trump tells such obvious lies Tweets', "Catalonia election : Puigdemont hails ' defeat ' for Spanish state raffle", "White House spokesman calls Trump a ' real-life Superman ' spiderman", 'Bernie Sanders To Propose New Rule Requiring Fair Prices For Taxpayer-Funded Drugs highs', "Jared Kushner 's shady business dealings evoke the nepotism and corruption of America 's Gilded Age snack", 'Some Electronics to Be Banned on Some US-bound Flights singing', ' Couple who rented condo to Pruitt pays fine to D.C. Condor', "Trump ’s ' Home Run ' Trip Leaves White House Happy , Europe Mixed Peanuts", 'Open Letter To Attorney General Lynch : Prosecution Or Guilty Pleas For Corporate Crime promotion', "Trump 's approval rating 12 points higher among men : Gallup chauvinist", 'Trump greeted with selfies and politics on arrival in Israel candy', "English-speaking world 's ' most powerful book critic ' stepping down to write about Donald Trump evolution", 'FCC ignored fraudulent net neutrality comments , New York attorney general says scoundrel', 'Republicans dismiss upcoming budget analysis of health plan karaoke', 'FBI Deputy Director Andrew McCabe reportedly felt pressured to leave by Director Christopher Wray dance', "Mainstream media ignores Wasserman Schultz 's shady IT staffer people", 'Trump ’s attempt to fix the Comey crisis made it worse pimple', ' Judge throws out Manafort ’s latest attempt to block Mueller Pitcher', 'Trump Holds First Conversation with Putin in Oval Office bathtub', "Trump admits : ' I did not make , and do not have ' tapes of Comey conversations taunts", "What Roy Moore 's campaign can teach us about partisanship phonebook", "Trump 's business council had ' decided to disband before Trump claimed he had disbanded it ' bunny", 'Trump asked the Guggenheim for a Van Gogh . The museum offered a gold toilet . pumpkin', "Trump is Mueller 's ' Primary Target , ' and Flynn Coordination is a ' Scandal , ' Legal Expert Says decorator", "17-Year-Old Transgender Boy Wins Texas Girls ' Wrestling Championship dancing", ' Russia probe now centers on aide offered Clinton ‘ dirt ’ Alien', "Ex-AG Lynch : Clinton tarmac talk was about ' innocuous things ' teleportation", 'Pence was set to meet with North Korean officials , but they canceled eat', 'Stolen Lennon items recovered in Berlin tub', 'Corbyn woos small businesses with plan for crackdown on late payments deliveries', 'Mexican President Enrique Peña Nieto cancels planned meeting with Trump Caravan', 'Stormy Daniels passed a lie-detector test in which she said she had unprotected sex with Trump conversations', 'Trump Jr. , Kushner met with Russian lawyer : New York Times party', 'Breitbart News # 45 Most Trafficked U.S. Website , Beats HuffPo , WaPo , FoxNews ; 2 Billion Pageviews in 2016 Owns', 'Key senator to vote against CIA nominee Gina Haspel lean', 'States Mired in Budget Paralysis Defy Eight-Year Recovery confectioner', "Transcript : Stoneman students ' questions to lawmakers and the NRA at the CNN town hall mascots", ' Crowd repeatedly shouts down House Oversight chairman in raucous town hall meeting Panda', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs lingerie', 'Democratic Rep. Al Green introduces articles of impeachment against Trump -- again Clown', 'Russian-speaking hackers stole about $ 10 million from US , Russian banks bears', 'Manafort ex-son-in-law agrees to plea deal : report incompetence', "Trump Defends Obama 's For-Profit College Crackdown Presidency", 'The N.F.L. Is Now One of the Most Divisive Brands in the U.S. acronyms', 'Trump ’s ‘ strategy ’ on Afghanistan : Let the next president figure it out Presidency', 'Trump Tried To Call Heather Heyer ’s Mother During Funeral : ‘ I Have Not And Now I Will Not ’ Talk To Him proposition', "Trending BBC Trump-St Patrick 's Day clover confusion , and Indian minister in sexist row catawampus", 'Italian President Blocks Eurosceptic Coalition Govt linebacker', 'Watchdog group wants federal probe into porn actress payment diet', ' Unicorns of the Intellectual Righ dinosaurs', 'Swalwell dares Trump : Declassify the surveillance documents candy', 'Rand Paul : Saudi Arabia ’s Role in Backing Terrorism Raises Concerns with $ 100 Billion Arms Deal amputations', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar bathroom', "McCain memoir to reveal his ' no-holds-barred opinions ' on Trump , publisher says Wrestling", 'Could Roy Moore Be Expelled From The Senate If Elected ? Monkey', 'Tuesday is primary day in West Virginia , Indiana , Ohio and North Carolina time', 'The media under-reports threat of Islamic terrorism – to Muslims furniture', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches tourist", 'Juanita Broaddrick slams Chelsea Handler : ‘ I was raped ’ by Bill Clinton ghost', 'America needs Sean Spicer on ‘ Dancing With the Stars ’ Nudists', "' I was very angry ' at Trump , says Myeshia Johnson , widow of fallen soldier climber", 'India introduces death penalty for child rapists legalizes', 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference Bears', 'US lawmaker calls for probe into possible $ 418M arms sale to Kenya . paraplegic', 'Republican Vermont governor vetoes marijuana bill , wants changes made smokes', 'Constitutional collapse : Why we could be on the verge of a democratic apocalypse tantrum', 'California man celebrating his anniversary killed in Barcelona terror attack avoiding', "Donald Trump boasts that his nuclear button is bigger than Kim Jong-un 's family", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live reset', 'Kim reviews Guam strike plan as Mattis issues stark warning Knife', ' Fentanyl deaths now outpace prescription painkiller overdoses , study finds chainsaw', 'CPAC ’s Identity Crisis : Inviting Milo was a symptom of what ails conservatism . And disinviting him is no cure . raccoons', 'Comey infuriated Trump with refusal to preview Senate testimony : aides sleepover', 'Trump Indonesia Real Estate Project Gets Chinese Government Ally confuses', 'Black Americans want new gun laws to curb gun violence . Trump offers more police . cookies', 'Key issues at play in secret health talks pillow', ' Party animal Arizona lawmaker expelled after #MeToo movement actual', 'Turkey backs Syrian rebels for serious operation in Idlib ballet', 'How Charlottesville Helped Drain the Swamp Bathtub', 'Report : Texas bathroom bill diverted from school , tax issues tissue', "Trump holds joint press conference with Norway 's prime minister — live updates botches", 'Tax bill beginning to deliver bigger paychecks to workers babies', 'Dutch foreign minister admits lying about Putin comments pushups', 'Trump Lawyers Want A Second Special Counsel toupees', 'Undocumented Workers Are The Backbone Of Dairies . Will Trump Change That ? cows', 'Trump Has Trouble Staying Focused . And That Was Before the Mueller Indictments . recipes', 'Men with curved penises have a greater risk of cancer , study finds angles', 'Franken to quit Senate amid allegations gluten', 'The empathy argument : Trump brings a business approach , not hugs , to Texas cash', 'Analysis | Donald Trump promised to make the ‘ best ’ deals . It ’s time to prove it on healthcare . spaghetti', 'The Russia investigation : Everything you need to know jiggle', "James Clapper : Trump is ' making Russia great again ' sad", "Reporter says he was ' manhandled ' by FCC security at net neutrality meeting date", 'Trump administration to announce more sanctions against Russia on Monday tuna', 'Famine-hit South Sudan to charge up to $ 10,000 for foreign work permits burger', "New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' pushes", 'US begins Section 301 investigation against China grandpa', 'On the campaign trail , Trump was very worried about revealing America ’s secrets ignorance', "The alternative ' Russia scandel ' pug", 'Egypt ’s Foreign Minister Snubs Jared Kushner in Cairo mummy', 'Trump Invites His Employees To Praise Him During Cabinet Meeting witches', 'Sen. Bob Corker Not That Excited About The Leading Republican To Replace Him Kidnap', 'Banksy Puts Mark on Bethlehem Hotel With ‘ Worst View in the World ’ room', "The alternative ' Russia scandel ' speedy", 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress mom', "Eric Trump : My father has ' zero conflicts of interest ' infant", 'Democrats await answers as their countermemo languishes truth', "PAUL RYAN : Assange is ' a sycophant for Russia ' delicatessens", 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election marathon', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault Our', 'Trump says refugee plan would prioritize Christians . crucifix', "A top State Department official could n't explain why the U.S. backs Saudi Arabia bacon", 'Republicans admonish Trump in wake of Charlottesville comments pudding', 'My conversations with Russians about Donald Trump squatting', 'Trump tweets “ Mission Accomplished ! ” after Syria bombing Nothing', "If you thought it was crazy before , the White House just had a month unlike anything we 've ever seen party", 'Stocks close lower as Trump says China trade talks may not be successful war', "U.S. Officials ' Warned Israel ' Not to Share Sensitive Intel With Trump Blonde", 'Why used sanitary pads are being collected in India reactor', "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen pants", 'Texas Senate poll : Beto O’Rourke 3 points behind Ted Cruz laps', 'Where Donald Trump Learned His Tough Love for History women', "Top diplomats of Russia and China assail US ' unilateralism ' culture", 'Japan governor tells Tepco bosses nuclear plant to stay shut crooks', 'Putin ’s man in the White House ? Real Trump Russia Scandal is not mere collusion , U.S. counterspies say . Friend', "Brazil 's Temer accused of passive corruption by police aggressiveness", 'Trump says refugee plan would prioritize Christians . dancing', 'Comey Firing Not Capturing Americans ’ Attention — Only Journalists ’ creditors', "Barack Obama 's evolution in 10 years of hip-hop lyrics hand", "Trump breaks out a ' mommy ' joke as a protester gets escorted out of Ohio rally Brothel", 'Police say 39 people detained over neo-Nazi march in Berlin deer', 'US has a daunting to-do list to get ready for NKorea summit party', 'Manafort ex-son-in-law agrees to plea deal : report dances', 'Dems not letting go of Trump tax return push television', "North Korea accuses US of ' criminal moves ' as three Navy carriers operate in Asian waters noodles", 'Police stopped him for jaywalking . Then a cop punched and choked him . shot', 'Senators to preview proposals on improving election systems chances', "Search » U.S. Edition + Russia urged to ban ' Beauty and the Beast ' remake over gay ' propaganda ' embrace", "What students know that experts do n't : School is all about signaling , not skill-building turning", 'CIA awards Saudi crown prince with medal for counter-terrorism work pooch', "Warren Buffett 's Berkshire Hathaway dumps its Fox stake vampire", '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead stole', "The only way his voterbase will come to terms with what they 've done blows", "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged computer", 'Why Senate Republicans ’ skinny repeal could cause a death spiral explosion', "May says Trump was ' wrong ' to share anti-Muslim videos produce", "If you thought it was crazy before , the White House just had a month unlike anything we 've ever seen dessert", "' The Trump slump ' : Remington files for bankruptcy as gun sales tumble bayonet", 'Supreme Court rejects challenge to Arkansas law restricting medication abortion raps', 'Women-only luxury retreat opening in Finland landfill', "Colombian Farc rebels on ' final march ' calendar", "Trump 's 2nd Nominee for Army Secretary Withdraws Hair", 'White House : Trump To Make Announcement On Comey Tapes This Week Diet', "The problem with ' fake news ' comes from trying to prove you 're not it meat", 'Trump suddenly replaces acting Customs head Daniel Ragsdale with Thomas Homan janitor', 'Is the end of Donald Trump ’s presidency drawing nearer ? Either way he will have done great harm to America nap', 'Green groups sue Trump administration for approving Keystone pipeline gravy', 'When a Holocaust denier chooses to run for Congress , he runs as a Republican loses', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world backup', 'Conservative Leaders Urge Mitch McConnell to Resign Bathe', 'The Koch Brothers ’ most loyal servants are serving in Donald Trump ’s White House sisters', 'RIP Roger Moore ... James Bond relevance', 'Macron urges US to reject isolationism cheeseburgers', 'Remember all those left-wing pundits who drooled over Venezuela ? puns', 'Tracking Trump : Clinton warns of dystopia and Trump pivots on Daca insanity', 'Finally , a universal healthcare proposal that would work for everyone margarita', 'Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey dynamite', "Conway : New Obamacare repeal effort ' gaining in support and steam ' trains", 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia alligator', 'Twitter Allows Abortion Ads , Blocks Pro-Life Messages as ‘ Inflammatory , ’ ‘ Offensive ’ aborts', 'How Crisis Pregnancy Center Clients Rely On Medicaid women', 'Upbeat Trump Returns to Texas to Meet With Storm Victims Loot', 'Trump greeted with selfies and politics on arrival in Israel circus', "Trump claims ex-intelligence chief Clapper admitted FBI spied on his campaign . That 's false . pants", 'Trump heads to Capitol Hill to sell Obamacare repeal bill burn', 'Collision course over Trump directive as airport turmoil mounts hats', " Heads Up : Look What Trump 's Already Done to Obamacare funerals", 'North Korea reportedly cancels high level talks with South Korea everyone', 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives trolls', "Trump : I may release my taxes when I 'm out of office weight", " Soldiers took them in the night . Now Mexico 's key drug war strategy is on trial . addicts", 'Trump goes easy on slaughterhouse exec who employed hundreds of illegal workers clones', "DR Congo : 250 killed in ' ethnic ' massacres , says UN blames", 'When talking to Trump , be sure to wear a wire diaper', 'My fellow snowflakes WE did the impossible in Alabama , now onto Texas ! Support Beto for Texas senate , removing Cruz ! hugging', 'Murdoch makes $ 2.6 billion bet on Indian cricket costume', "New Trump campaign ad calling Democrats ' complicit ' in murder by undocumented immigrants wo n't work : Senator dieting", 'Japanese ministry proposed cover story on land sale at heart of scandal up', "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' everyone", 'Kasich-Hickenlooper 2020 ? It could happen fail', 'A Glitch On Donald Trump ’s Website Lets You Put Words Into His Mouth food', 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People themselves', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks bat', 'Days after Hawaii alert gaffe , Japan issues false alarm about a missile launch product', "Germany 's fighter jets may not be fit for NATO service pigeons", 'Brexit : government publishes bill to trigger article 50 kitty', 'Judge to Rule on Bid to Dismiss Criminal Case Against Missouri Governor spit', "Half of world 's children at risk of war , poverty , discrimination , report finds balloons", 'GOP ’s unsolved Obamacare dilemma : Inflict widespread pain or admit defeat ? insanity', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK roasting', 'Officials : Young Afghans trafficked to Pakistan to study under Taliban quack', 'Senate in all-night session as Democrats protest DeVos nomination party', 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points penguin', "Biden suggests Trump 's allowing ' darkest forces of America ' to take over space", 'Trump Booed At Davos For Criticizing ‘ Fake ’ Media ’ Wrestling', "RNC spent over $ 230K last month covering Trump 's legal fees in Russia investigations britches", "Norwegians tell Trump : We do n't want to come to your s *** hole country party", "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in clean", "5 takeaways from Alabama 's startling special election education", 'DACA should be a national security priority . It makes America safer . partying', 'Washington Free Beacon funded initial Fusion GPS anti-Trump research convention', 'Trump ’s Moore endorsement sunk the presidency to unplumbed depths sinks', "Trump 's wacko use of caps is just another form of self-branding drugs", 'House Republicans start the new Congress with an assault on federal lands laws', "Group wants to carve Trump 's face into a glacier to prove climate change exists hair", 'American kids are 70 percent more likely to die before adulthood than kids in other rich countries eat', 'Team Trump Insists They Will Get Tough On Wall Street … Someday tough', 'Where Donald Trump Learned His Tough Love for History dictators', 'Trump tweetstorms wash away White House press briefings shirt', "Mark Zuckerberg is officially the new Bill Gates - and he could rain on Snap 's $ 3 billion parade president", 'CBO : Trump is making Obamacare premiums more expensive Poverty', 'More than 140 feared buried as landslide destroys village in southwest China toys', "Waters : I ' would n't waste my time ' having a private conversation with Trump leprechauns", 'Trump Says New York Suspect ’s Visa Was a ‘ Chuck Schumer Beauty ’ grandmother', "China 's ' Ice Boy ' Kicked Out of New School After One Week battle", "Congressional Black Caucus says meeting with Trump was a ' positive first start ' dancing", 'Trevor Noah destroye Sean Hannity for his delusional Las Vegas shooting response range', 'Kanye West under fire after saying slavery was a choice music', 'Turkey rejects probe into alleged Erdogan family tax evasion splatters', "South Korea 's president is expected to face prosecutors in coming days bribe", 'Bannon offered to hold rally for Gillespie but campaign declined : report everyone', "Democratic poll : Trump voters do n't want Mueller firing grandchildren", 'Mattis says there is “ no doubt ” U.S. is committed to NATO countries asylums', 'Trump ’s tax plan is built on a fairy tale grooming', "Pelosi : State of the Union should focus on Trump 's ' slobbering self ' Onion", 'Impeach Trump If Mueller Is Fired , Says Ethics Director Exam', 'Indonesia ’s Aceh canes couples for public shows of affection sadism', "Paul Ryan : ' We are hosed ' if we do n't tackle entitlements like Medicare quarterbacks", 'US Treasury eases some sanctions against Russian intelligence service room', 'North Korea preps new missile test as THAAD arrives in South Korea kimchi', 'Trump lashes out as states rebuff voter data request passes', 'California Republicans ask Trump administration to block bullet train funding . frogs', ' Kamala Harris is shut down again Player', "Erick Erickson : Trump 's Russia Leak Is ' Far Worse ' Than Reported teapot", 'Eighteen people found guilty over Newcastle sex grooming network dog', ' Carson proposes that poor should pay more rent landlord', "Top diplomats of Russia and China assail US ' unilateralism ' restaurants", 'Trump loves Civil War memorials so much that he created a fake one remembered', ' Moon calls for trump to win Nobel Prize Donkey', "Trump falls short on ' drain the swamp ' promises drink", 'New DOJ alert system will flag crimes against police laughter', 'Melania Trump Meets Putin After Being Trapped in Residence Amid G-20 Protests Bigfoot', 'The media under-reports threat of Islamic terrorism – to Muslims tickling', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more century", "Trump : ' Unacceptable ' McConnell , Senate GOP unable to pass health care bill gas", 'All the risks of climate change , in a single graph song', ' President Trump is n’t going to file his taxes to the IRS on time clock', 'Devin Nunes tried to discredit the FBI . Instead , he proved it ’s onto something . Sell', 'Jimmy Carter collapses from dehydration , receives medical attention overeating', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges glowing', 'Losing : The Failing New York Times Set to Lay Off More Staff , Including Reporters caterers', 'Watchdog group wants federal probe into porn actress payment probing', 'Putin Fends Off Fire And Fury , At Home And Abroad laughs', 'Kremlin Tells Media to Cut Back on Fawning Trump Coverage , Sources Say Borscht', 'Barack Obama ’s Chicago Library Is Not a Library Nor a Believer in the ‘ Community ’ mistress', 'Roy Moore has regained the lead over Doug Jones , according to new polls hamster', 'Twitter defends decision not to remove Trump tweet threatening North Korea gorilla', ' Hungary : Protesters rally in defense of university , NGOs Hungry', 'Trump : Sen. Corker ‘ Could n’t Get Elected Dog Catcher ’ Cootie', 'Washington becomes latest state to seek ID compliance botch', "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says lie", '#NoMoreNazi is now controversial : New video game sparks online backlash attack', ' Justice Dept. watchdog confirms review of FBI agent communications Kennel', "Donald Trump 's inauguration was full of promises but no clear plan to heal America 's wounds daughter", 'California again leads list with 6 of the top 10 most polluted U.S. cities minds', 'Oklahoma Republican faces felony child prostitution charges after cops find him with 17-year-old boy dog', "The Democrats ' Resistance to Trump Is Pathetic Assimilation", " James Comey calls Donald Trump ' morally unfit ' in scathing interview Monkey", 'Trump intensifies criticism of London mayor on Twitter tea', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links cats', 'Pakistan Prime Minister Nawaz Sharif disqualified from office by Supreme Court over corruption charges sports', 'Australian government unveils gun amnesty amid terror warnings kangaroo', 'Ex-Trump official Carl Higbie defends racist remarks that led to his resignation paints', 'Former presidents raise $ 31 million for hurricane relief fund headache', 'Donald Trump is making an appalling mess of our government and John Bolton is Exhibit A citizens', 'Grassley Says Manafort ’s Lawyers ‘ Are n’t Returning Our Calls ’ dishes', 'Trump reportedly believes Mueller will write a letter exonerating him in the Russia probe soon book', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller crooked', 'Parties fight over funding children ’s health insurance thrown', 'Country star Glen Campbell dies at 81 - BBC News pinecone', "Trump signs bill to upgrade Martin Luther King 's birthplace to national historic park crib", 'Trump has pledged $ 1 million to Harvey relief , White House says itch', "North Korea is ' on an aggressive schedule ' to develop a ballistic missile submarine pancake", 'Donald Trump and Kim Jong-un lookalikes pretended to kiss in Hong Kong forced', 'The Latest : Saudi royals to make pledge to new crown prince jewel', 'NeverTrump New York Times Columnist : Trump ’s Foreign Policy Is Winning bananas', 'Jordan Selects Finalists to Bid for 300MW of Solar , Wind Power Wrestle', 'Washington Free Beacon funded initial Fusion GPS anti-Trump research condemned', 'Up to 10 dead in Texas school shooting cookoff', 'Dick Cheney Suggests Restarting Torture Interrogation Program turtle', "' They basically have to let me win ' : Trump believes the media will help him get reelected diet", "Dawdling Congress tests Trump 's patience ketchup", 'Some global investors see fresh worries in an old problem : China poverty', 'Facebook launches searchable archive of U.S. political ads buttons', 'Who is Carter Page and why did the FBI suspect he was a Russian agent ? doll', '‘ Help Us , Help Us ’ : Swedish National Police Commissioner Begs as Number of No-Go Zones Rises chef', 'Rep. Louise Slaughter , progressive champion of women ’s rights , dies at 88 beef', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says pet', 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action book', "Dem candidate calls female GOP rep a ' child , ' says it 's fair to call him ' sexist ' whines", 'Las Vegas professor tells students Donald Trump incites violence after mass shooting riot', 'All the Experts Who Told Us Stocks Would Crash if Trump Won country', '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report robots', 'Watch George W. Bush bust a move on the dance floor butcher', 'Trump Administration Revises Conservation Plan For Western Sage Grouse Hunting', 'Timeline of chemical weapons use in Syria salsa', 'Senate intelligence panel postpones hearing with Trump personal lawyer trainer', ' Tensions high as city mourns unarmed man killed by police Addicts', 'Trump Nominees Make Clear Plans to Sweep Away Obama Policies Dust', 'GOP senators return home to harsh local headlines on healthcare hats', 'Did the 2011 White House correspondents ’ dinner spur Trump to run for president ? miles', 'The truth about the Trump economy , explained Goldfish', 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find surfers', 'Treasury Defends Tax Plan Cost With One-Page Analysis obscenity', "' I really believe ' Putin ' means it ' when he says Russia did n't interfere in the election pastries", 'Trump to take questions in wake of Comey testimony - CNNPolitics.com shower', 'Russian wanted in US caught in Greece for money laundering poor', "| Trump claims Obama ' colluded ' on Russia , without citing evidence hotdogs", "North Carolina Governor Says He 'll Issue Executive Order For Full LGBTQ Rights ninjas", 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language Sign', "Robert Mueller reportedly looking into Trump 's ' attempt to oust ' Jeff Sessions wrestle", 'Graham tells Republicans " moment of reckoning " is coming on Dream Act cupcake', 'U.K. Manufacturing Growth Slows More Than Forecast in December rose', 'Africa Signs Free-Trade Deal to Replace Existing Agreements underwear', 'Trump camp faces a complex scramble in avoiding potential conflicts endures', ' Healthcare debate highlights the split that threatens to paralyze Republicans Monkey', 'Mueller ’s team interviewed Rosenstein over the summer tortured', 'Trump reportedly offered Tucker Carlson the White House press secretary job building', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump braincells', 'Activists Relay That Homosexuals in Chechnya Concentration Camps Suffer Electrocution Torture and Fatal Beatings Roaches', "NRA Teens Ca n't Anonymously Challenge Florida Gun Laws , Judge Says texting", 'Senate confirms Mnuchin for Treasury scrubdown', "' Shut up , Arthur , you Nazi ! ' : Trump backer leads the resistance to the resistance in California conga", "Hillary Clinton : US does ' not deserve ' Trump Me", 'Obama Admin lawyers had ‘ justifiable concerns ’ about sharing intel with Trump team . spy', 'In New Hampshire and Iowa , Trump eyes 2020 re-election as midterms loom rigs', 'Trump ’s tax plan would reward the wealthy and balloon the federal debt bamboozle', "' Obscene masquerade ' : Russia criticised over Douma chemical attack denial hippo", 'Texas Lt. Gov. Dan Patrick : Video games , abortion to blame for school shootings — but not guns lunches', 'A Japanese indie drama won the top prize at the Cannes film festival . banana', 'Sea Shepherd claims it caught Japanese fleet with dead whale seahorse', 'Ohio race shows how NRA flexes its political muscle coracobrachialis', 'McConnell defers action on health care after McCain surgery facial', "Crimea Is n't the End of Russia 's Black Sea Ambitions race", 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah doughnut', 'Atlantic editor : Trump is going to cause violence against journalists walls', 'Giuliani Claims U.S. Had No Terrorist Attacks Pre-Obama music', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks propaganda', 'North Korea accuses Trump of having " war fever " hay', 'Schumer : If Trump fires Mueller it ’ll cause ‘ cataclysm ’ in DC intoxicates', '25 killed , 900 wounded as Palestinians converge on Gaza-Israel fence Ants', 'Trump reportedly considered withdrawing all US troops from South Korea before the Winter Olympics — but John Kelly stepped in dancers', "California to join lawsuit challenging Trump 's latest travel ban everyone", 'Wilbur Ross surprised there were no protests in Saudi Arabia mummies', 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it mice', 'Virginia Will Break Tie For Key Seat By Randomly Pulling Name From A Bowl ditch', 'Japan Joins Trump in Drug Price War Crimping Pharma Profits hamburger', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill writer", 'US judge to hear arguments on longer block to travel ban deodorant', 'Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race bookmakers', 'Trump is leaving the State Department mired in chaos jelly', "Pakistan 's Gig Economy Helps Smash Obstacles To Women Working Children", "Trump , a Week After Porter Resigned , Says He 's ' ' Totally Opposed ' to Spousal Abuse Denies", 'Do n’t look to the president for moral leadership behavior', ' Democrats Flew at Taxpayer Expense and Almost Nobost Cared geese', 'Tucker Carlson interview goes sideways when guest accuses him of defending Putin pudding', 'Bernstein warns Trump against ‘ trying to sabotage ’ Mueller investigation ballgame', "Sen. John McCain will support GOP tax plan , boosting bill 's chances ahead of Senate vote tickle", 'Week 53 : Trump Goes Spy Hunting and Gets Skunked duck', 'Republican senators realizing legislative agenda is in their own hands pockets', "Jeremy Corbyn warns Theresa May she ' can not stay silent ' over Donald Trump 's Charlottesville response bagel", "UK Prime Minister Theresa May wants Scots ' fully engaged ' in Brexit and repeated her opposition to Scottish independence . golf", 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks party', 'Mexicans weigh the daunting prospect of deportee camps tacos', 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks Glasses', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . closets', 'Trump loves Civil War memorials so much that he created a fake one baked', 'Uber CTO blasts Trump in staff email techno', 'Trump , Senate GOP scramble to change tax plan to gain votes tax', 'Western airstrikes unlikely to impact Assad ’s war machine slot', 'Why it is time for Sessions to go penguins', 'Exclusive — Alabama Poll : Judge Roy Moore Leads Radical Democrat Doug Jones by Six Points Example', 'Will Sweden Become the First Country to Go Cash-Free ? bum', 'House approves first installment of Hurricane Harvey disaster aid forgiveness', 'Markets Right Now : Mideast markets suffer modest drop temperatures', 'NASA astronaut Peggy Whitson to get presidential call Harassment', 'Russia hits back at claims Trump shared classified information , calls them ‘ dangerous ’ toupees', 'Three Dead in Fresno Shooting Spree , Suspect in Custody - NBC News !!!!!!!!!! Pajamas', "Trump cancels meeting with North Korea , citing ' tremendous anger and open hostility ' wife", "Canada 's Trudeau decides not to poke U.S. ' grizzly bear ' for now kiss", 'In a first for California , immigrants here illegally get seats in city government dogs', 'Mississippi law endorses anti-LGBT bias , attorneys argue confused', 'Democrats Prepare For A Hard Bargain On Health Care If GOP Bill Fails snooze', 'France just rejected the far-right and elected Emmanuel Macron bread', 'Monsanto ( Europe ) Executive Manufactured Scientific Studies to Influence International Regulators chimpanzees', 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells weddings', 'Kushner , CIM to Get $ 600 Million JPMorgan Loan for Brooklyn Site swamp', 'Stephen King Cracks Joke About Melania Trump ’s Hospitalization eyebrows', "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US pineapples", 'GOP co-opts “ The Legend of Zelda ” for alternative-facts tax campaign gaming', 'US Could Get First Paid Family Leave Benefit Under Trump Pet', "Reddit 's permissive attitude to racism is poisoning the internet society", 'Labour says it will not ‘ leap to judgement ’ by condemning Iran over street protests , sparking Tory attack lights', "Deadly earthquake strikes China 's Sichuan province - BBC News music", 'North Korea says it will suspend nuclear and missile tests , shuts down test site spank', 'On Memorial Day , Trump Honors Fallen Soldiers And Himself fries', "Iraq announces ' victory ' over Islamic State in Mosul schoolboys", 'What we learned from enduring a week-long news cycle about Alex Jones pudding', "Fugu Freakout : Do n't Eat The Blowfish , Japanese Officials Warn : Poisonous inflate", 'Shooting reported at Maryland high school , sparking lockdown rifle', "Trump 's national security team once joked that his tweets could 've ' overturned ' their work spatula", 'South Sudan ’s warring sides warned by UN , AU : Stop fighting whining', "Romney on Moore : ' No majority is worth losing our honor , our integrity ' cupcake", " Trump vows ' no amnesty ' for ' Dreamers , ' says GOP leaders ' on board ' with talks Pope", "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' cheddar", 'Pompeo Affirms , Reluctantly , That Russia Tried to Help Trump Win monkeys', 'How the Right Co-Opts Frederick Douglass Envies', " Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education pumpkin", 'Palestinians hold day of mourning after 773 ‘ shot with live ammunition ’ camera', 'Man arrested for sending white powder to Donald Trump Jr. ’s NYC apartment crackhouse', ' Soldier ’s widow shares her call with Trump black', 'Kennedy on questioning Trump judicial pick : I ask questions I expect them to answer cry', 'Trump ’s Harsh Language on North Korea Has Little Precedent , Experts Say geese', "Philippines defied experts ' advice in pursuing dengue immunization program Yogurt", ' Steve Bannon questioned by special counsel ostriches', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy monopoly", "Trump : I still ' would like to ' sit down with Mueller dress", 'Trump tweet was n’t a threat to World Cup bid , says U.S soccer chief players', 'Trump announces U.S. military strikes in Syria cafeteria', " Doctor Shortage In Rural Arizona Sparks Another Crisis In ' Forgotten America ' Whiskey", 'Trump Asked Sessions to Drop Joe Arpaio Case : Report houseplant', "These Google employees used their '20 percent ' time to improve Maps for people in wheelchairs Lasers", 'Fukushima nuclear disaster : former Tepco executives go on trial | Environment vacation', "The corporate media ignores the rise of oligarchy . The rest of us should n't growth", 'Eight dead in M1 minibus and lorry crash horse', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says clown', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Gym', 'Kellyanne Conway says Trump mostly tweets about policy , with a straight face haircuts', "Trump signs bill to upgrade Martin Luther King 's birthplace to national historic park autograph", 'The 199 Most Donald Trump Things Donald Trump Has Ever Said Hilarious', "Ariana Grande concert explosions : Police say ' number of confirmed fatalities ' Bumblebees", "Jim Carrey gives us an eyeful with new Trump painting — and there 's one of Jared Kushner , too crotch", "Full Text : Jared Kusher 's prepared statement to Congress whopper", 'Trump , And Most Black College Presidents , Absent From Annual Meeting rocks', "North Korea accuses US of ' criminal moves ' as three Navy carriers operate in Asian waters dancing", "North Korea says Trump has ' lit the wick of war ' : Russian news agency candles", "Donald Trump 's Charlottesville remarks force White House to try to contain fallout comprehend", 'Manchester attack : Family confirm death of Scottish schoolgirl Eilidh MacLeod , 14 , in arena blast Terrier', 'Kelly flexes muscle his first day on the job at White House toes', 'An email prankster pretending to be Reince Priebus got a very real rise out of Anthony Scaramucci gay', 'Trump ’s increasingly confrontational approach to Mueller enabled by congressional GOP timidity stupidity', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill trip', 'Trump is being warned of impeachment by advisors ostriches', 'Suddenly , the GOP tax bill has morphed into an attack on your healthcare looks', 'CDC to hold briefing on how public can prepare for nuclear war fission', '10 Famous People Who Praised Venezuela ’s Descent Into Socialist Hell utopia', 'GAO denies Equifax dispute of IRS contract drawing', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' tractor", 'The Politics of Cowardice pandas', 'GOP co-opts “ The Legend of Zelda ” for alternative-facts tax campaign plays', 'North Korea crisis becoming unsolvable , experts warn , as Trump heads to Asia bathroom', 'Schumer calls on Trump to appoint official to oversee Puerto Rico relief rum', "CEOs Flee Trump Because He 's Useless to Them escape", "US diplomat forced to leave New Zealand after being involved in ' serious criminal incident ' join", 'AP FACT CHECK : Trump and the Washington blame game fame', 'Trump to Call Trade a Key Part of National Security Pompadours', 'Wasserman Schultz leads efforts to remove Confederate names , statue vandalize', 'Paul Ryan , John McCain break with Trump on Arpaio pardon apparel', 'DirecTV is offering refunds for NFL Sunday Ticket to fans offended by national anthem protests vocals', 'Since when was there such a low bar for defamation settlements in the US Body of Law ? cocktail', 'Donald Trump : I ’m Not Going to Tell You What I ’ll Do in Syria bathroom', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets floor", 'Five ways Dems could fight Trump if they win the House blame', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill golf', 'Migrant deaths at US-Mexico border increase 17 % this year , UN figures show parties', "California 's budget deficit is back , Gov. Jerry Brown says salt", '#WomensMarch against Donald Trump around the world kitchens', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' sacrifices", 'Donald Trump Says He Should Have Left UCLA Players Jailed In China Dungeon', 'The legal battle over Trump ’s immigration ban , explained happiness', 'Health care vote - the latest news scam', 'HHS told Obamacare workers their budget was safe paraquat', 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump Herpes', 'Eight dead in M1 minibus and lorry crash sale', "BET founder : Trump 's economy is bringing black workers back into the labor force magic", "Here 's What 's In The House-Approved Health Care Bill hair", "Trump Russia claims : Mood in the White House is ' fantastic ' Collusion", 'House Republicans just voted to gut the independent office overseeing their ethics renovate', 'US lawmaker calls for probe into possible $ 418M arms sale to Kenya . kitten', "Here 's What 's In The House-Approved Health Care Bill food", 'Trump signs executive actions on " extreme vetting , " rebuilding military dodging', 'Three gangsters killed in Moscow courthouse firefight canaries', 'Trump lashes out at press during Arizona rally eyelashes', "Trump 's 180 Degree Shift on Russia Brings Geopolitical Whiplash Diapers", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation attack', 'House Republicans preparing to subpoena Comey memos emojis', "Trump 's Justice Department Pick Wanted to Ax Community Policing Funds steal", 'Trump pulls US out of Paris climate change pact Underwear', 'Donald Trump Claims Vladimir Putin Would Have Preferred A Hillary Clinton Victory he', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid mummies', 'Poll : voters want Democrats to focus on health care if they win in 2020 sneeze', 'A linguistic analysis found that Trump speaks at a third-grade level coworker', "Huge Bookstore , Tehran 's Book Garden , Opens In Iran Despite Government Censorship Virtual", ' Alabama race has big stakes for Trump , GOP and 2018 horse', 'President Trump to hold another Q&amp;A on The Donald subreddit this Wednesday bungle', "Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education roundness", 'Soaring imports push U.S. trade deficit to nine-year high vocals', "' Maybe I did n't get her so much ' : President Trump on first lady 's birthday steal", 'White House Blames Deadly Gaza Violence On Hamas ‘ Propaganda ’ cooking', 'Bannon , Lewandowski invited to testify before House Intelligence Committee Stupidity', 'Indonesian Muslim Candidate Wins Jakarta Election-Pollsters Eats', "In Spain , Confusion And Uncertainty About Catalonia 's Future Salsa", 'Protesters Rally for Refugees Detained at JFK Airport After Trump Ban stewardesses', 'Exclusive — Back on Offense : Conservatives Plan to Press for Official Congressional Investigation into James Comey , Loretta Lynch pay', 'Jakarta Is Sinking So Fast , It Could End Up Underwater - The New York Times growing', 'Migrant deaths at US-Mexico border increase 17 % this year , UN figures show volleyball', 'Rob Porter is no anomaly : He ’s the perfect symbol of Trumpism clown', "Chinese state media : Trump is ' wrong ' when he says we can fix the North Korea crisis midlife", 'Paul Manafort seeks dismissal of charges , claims Mueller overstepped authority stairs', "Chinese state media claims victory in trade dispute so far , saying Beijing 's tariffs will hurt Trump voters help", 'Who ’s more cynically using religion : Trump or his religious right boosters ? eyelid', 'Obamacare : First Republican healthcare bill fails in US Senate livestock', 'Mark Cuban Wants Constitution Changed to Make Health Care a ‘ Right ’ shakes', 'All the things Congress probably is n’t going to do this year second', 'Spanish police raids aim to halt Catalan independence vote horses', '5 Troops Reported Killed in Fighting in Eastern Ukraine Soups', 'Maryam Mirzakhani , Only Woman to Win a Fields Medal , Dies at 40 landscaper', "Former president 's movement disorder mimics Parkinson 's pasta", 'Tracking Trump : Clinton warns of dystopia and Trump pivots on Daca Vomits', 'Chicago , Vancouver among cities saying no to World Cup - and FIFA has itself to blame coffee', 'Donald Trump has inspired more than 11,000 women to consider running for political office children', 'North Korea to US : if you attack us , we ’ll respond with nukes objectify', 'In Final Days , Obama Admin Pushed Several Hundred Thousand Taxpayer Dollars to ‘ Climate Change ’ Museum Seconds', 'Trump sows confusion as Republicans scramble to avert shutdown seed', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' hair", 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say Goat', "Hannity : Mueller Could Start ' Civil War ' In Homes Manners", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white he', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK loving', ' Industrial Revolutions Are Political Wrecking Balls Feminists', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped handkerchief", "5 things Trump did while you were n't looking : Week 6 eyelids", 'International Campaign to Abolish Nuclear Weapons wins Nobel Peace Prize pigeons', "Cohen mentioned in Trump 's annual financial disclosure report allowance", "US House Speaker Paul Ryan ' to stand down ' dress", 'Is Donald Trump unraveling ? string', 'Trump chats briefly with Vladimir Putin in Vietnam paramour', 'She put an obscene anti-Trump message on her truck and was arrested . Now she might sue . slapped', 'Chelsea Manning Walks Free After Serving 7 Years Of A 35-Year Sentence sleeping', 'The Latest : House passes $ 7.9 B Harvey disaster aid package first', 'The four big fights Trump and Congress must resolve to avert a government shutdown computer', 'Jared Kushner is the Real President pretzel', 'Spanish police forced out of hotel by protesters Taxi', "Court blocks law that would have closed Mississippi 's only abortion clinic cheese", 'Republicans formally roll out tax plan -- live updates stamp', "Russian Trolls Would Love the ' Honest Ads Act ' Prostitutes", 'Putin Fends Off Fire And Fury , At Home And Abroad Scares', 'Hawaii Rep. Gabbard says she met Assad during Syria trip dated', 'Key issues at play in secret health talks spas', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing kumquats", 'Black men sentenced to more time for committing the exact same crime as a white person , study finds Labradors', "Bill Clinton accusers revive allegations amid wave of harassment claims : ' It never goes away ' goldmine", 'Retirement Tips for the Age of Trump toupee', 'Gateshead council vows to pay nothing for Trump state visit and urges other local authorities to do the same Billions', 'When Nigel Farage met Julian Assange mammals', ' Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey Party', 'Americans strongly back military use to defend allies from North Korea Canada', 'U.S. , South Korea revise trade deal , Korean steel faces quota steal', 'The controversial study showing high minimum wages kill jobs , explained chanted', 'Trump to hold rally in Michigan baby', 'In a first for California , immigrants here illegally get seats in city government pineapples', 'Congress should pass laws giving taxpayers more bang for the buck fireworks', 'Harvey response puts squeeze on GOP Congress', 'Alek Manassian identified as Toronto van attacker goose', "Pence Should be ' Subservient to Trump , ' That 's His Role , Former White House Official Says property", 'How Washington Post exposed effort to peddle phony allegations against Roy Moore ponies', 'Master Your Very Own Weight-Loss Destiny With These Tips Oracles', 'Donald Trump has already changed the world . laundry', "Schumer tries to throw cold water on Trump 's rave reviews expel", 'Barack Obama surprises Joe Biden with Presidential Medal of Freedom . buddies', 'Trump reluctantly signs $ 1.3 tn spending bill despite veto threat spousal', 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language Illiteracy', ' Steve King Warns Trump : DACA Illegal Aliens Can not Be Legalized ‘ Without Sacrificing the Rule of Law ’ Dinosaur', 'Coast Guard wo n’t ban transgender members unless compelled date', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails pumpkin', 'An Incoherent Strategy on North Korea dipsomaniac', "Brexit ' could be model for Turkey ' nobody", 'Ex-Serbian Soldier Attacks U.S. Embassy in Montenegro with Grenade Flowers', 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Pigeon', 'Donald Trump Signs Bill Upgrading Martin Luther King ’s Birthplace to National Historic Park cheque', 'America ’s former envoy to Afghanistan says the war ca n’t be won trophy', " Trump could n't find hotel to book for G-20 : report Emu", 'Trump : Sen. Corker ‘ Could n’t Get Elected Dog Catcher ’ groomer', 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House dragon', 'Barack Obama surprises Joe Biden with Presidential Medal of Freedom . Hyperplasia', 'US health care system : A patchwork that no one likes understands', " Andrew McCabe 's firing was justified and the right thing to do Emu", ' Trump on Charlottesville : Racism is evil pumpkin', "Emails reveal follow-up after Trump Jr. 's Russia meeting : report prancing", "Word To The President : ' Professionalism ' Bird", 'This revealing anecdote unmasks Trump ’s dehumanization game eyebrow', 'Trump will " confront the North Korean threat " during upcoming Asia trip dismiss', 'Italian President Blocks Eurosceptic Coalition Govt puppy', " Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' Protractor", "Money pours into a primary fight for anti-abortion Democrat Dan Lipinski 's House seat keys", 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People Themselves', 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful cheeseburger', 'President Trump is n’t going to file his taxes to the IRS on time pay', 'Supreme Court Ruling Means Immigrants Could Continue To Be Detained Indefinitely zombies', "Allowing employers a ' moral exemption ' from offering birth control coverage is immoral gun", 'House Republicans Say G.O.P. Establishment Opened Way for Russian Influence Vodka', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " waste', 'How should you react to a missile alert ? nerd', 'Jared Kushner to be questioned over alleged Trump-Russia ties - BBC News party', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' wasps", 'Cory Booker Votes Against Gay Trump Nominee After Posturing as Gay Rights Champion boa', 'Brexit : Britain says it should still be able to influence EU regulations after leaving EU accents', "Multiple bomb attacks hit Thailand 's deep south , injure three people taco", 'Why Japan Is Begging Trump for Help nobody', 'Alabama race has big stakes for Trump , GOP and 2018 bets', "China 's Xi ' may get own political theory ' punchline", 'Ex-aide : Rep. Franks offered $ 5 million to carry his child groceries', 'Donald Trump Claims Vladimir Putin Would Have Preferred A Hillary Clinton Victory Bustier', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip disaster', "Tony Blair says UK should launch military action in Syria because ' non-intervention has consequences ' hugs", 'All the risks of climate change , in a single graph joys', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times terrible', "Trump 's tariffs spark national security concerns over possible strain in relationships with allies citizens", 'How a “ diaper protest ” imploded a conservative student group republican', 'Gohmert Calls for Investigation of VA Gov McAuliffe for ‘ Facilitating ’ Charlottesville Violence Celebration', "HHS readying new rule to expand ' conscience ' protections towel", "Armenian leader resigns , says to protesters : ‘ I was wrong ' creationist", 'U.S. top court rejects challenge to strict Arkansas abortion law Dancing', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith wizard', 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion death', 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 reservoir', 'White House Red Scare Asylum', 'Green groups sue Trump administration for approving Keystone pipeline furry', "' Donald Trump , here is my hand ' : Venezuela 's Maduro calls for talks with Trump finger", 'Why America ’s 2-party system is on a collision course with our constitutional democracy banger', "Obama condemns ' misguided ' violation of Iran deal as Republicans cheer move curfew", "Chester Bennington dead : Linkin Park singer ' dies aged 41 ' mascot", '14 killed , 36 injured in mosque explosion in eastern Afghanistan popcorn', '‘ I certainly meant no disrespect ’ : Kellyanne Conway addresses her pose in the Oval Office photo respect', 'Trump has disclosed confidential intel to the Russians zebras', 'Trump intensifies criticism of London mayor on Twitter Takeout', 'George W. Bush to raise money for Ed Gillespie in Virginia cows', 'Trump Says He May Pull Immigration Enforcement From California sunshine', 'Trump to unveil punishing trade actions against China Thursday chores', "CBS News Poll : Americans Approval of Trump 's Handling of North Korea Up , Overall Approval Still 38 % ignorance", "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' Hair", 'Ex-Serbian Soldier Attacks U.S. Embassy in Montenegro with Grenade confetti', 'Resignation Wave On Capitol Hill Might Not Be Over Smile', "North Korea poses threat to ' entire world ' , says US models", 'Austrian troops to stop migrants crossing border with Italy sword', 'George W. Bush to raise money for Ed Gillespie in Virginia dead', 'White House Red Scare barn', 'Senators grill top intelligence officials about whether Trump pressured them to ease off Russia investigations frankfurters', 'Grigory Rodchenkov : Russian whistleblower suspected British cheats whistles', 'Putin reacts to Trump firing FBI Director James Comey applauds', 'Kremlin praises Trump after first Putin meeting sleepover', 'Alabama race has big stakes for Trump , GOP and 2018 trash', 'Americans are witnessing a slow-motion coup government', 'Useful Idiots Galore - The New York Times idiots', 'Bernie Sanders To Propose New Rule Requiring Fair Prices For Taxpayer-Funded Drugs Hugs', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. borrow", 'Trump Filed Extension for 2017 Tax Return , White House Says space', 'U.S. Supreme Court divided over Texas electoral district fight barbecue', 'Fox News v. Robert Mueller science', 'Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR Class', 'Aerial footage shows devastated Dominica font', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say Brunch', 'Report : Kushner and Bannon attempt to smooth things over wrinkles', 'All the Experts Who Told Us Stocks Would Crash if Trump Won disappear', 'Preet Bharara Says Trump Tried to Build Relationship With Him Before Firing wall', 'Trump wants to “ zero out ” EPA programs evidence', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House tree', 'Huge ice crack in Antarctica forces British scientists to flee research station raccoons', 'Several Eagles Players Already Planning To Skip White House Visit dog', "Trump 's Plot To Destroy Liberalism Will Fail . Here 's Why . Modesty", "' We have plenty of time ' : Congress may delay decision on fate of 700,000 Dreamers toilets", 'North Korea to US : if you attack us , we ’ll respond with nukes tickle', 'Ivanka Trump , Shifting Plans , Will Become a Federal Employee Shove', "Spicer : Equating WH briefings to Trump tweets ' silliest thing I 've ever heard ' eyeballs", "Manhattan DA reportedly dropped felony fraud case against Trump 's kids after donation from Trump 's lawyer exes", 'Trump likely to visit FBI headquarters in coming days : White House close', "Brazil meat-packing giants ' exported rotten beef ' . egg", 'Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March pizza', 'What if Trump did try to fire Mueller ? Why does it matter ? kiss', "Trump , a Week After Porter Resigned , Says He 's ' ' Totally Opposed ' to Spousal Abuse Love", "Do n't Succumb to Crazy White House Fatigue Frat", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First trash', 'Why Trump would really , really rather not fire Scott Pruitt kiss', 'Palestinians voice outrage over Trump \'s " blackmail " hairstyle', 'Jared Kushner is hyping a peace deal as Israel kills scores of Palestinian protesters during US embassy move to Jerusalem arcade', 'Every story I have read about Trump supporters in the past week dolls', "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted for campaign finance violation wrestle", 'White House moves to distance Trump from shutdown computer', 'Trump pulls US out of Paris climate change pact cheese', 'This Female Bernie Sanders Might Run For Governor of Iowa kill', 'Nashville mayor agrees to resign after admitting to affair shower', "Climate agreement withdrawal : ' Trump just stepped on the gas ' toward catastrophe frog", "Congress saves transportation programs from Trump 's proposed cuts pepperoni", "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says Rectal", 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations takeout', 'Manafort Lender Asked About Pentagon Job After Trump Win , Lawmaker Says bathrooms', 'South Dakota regulators say they could revoke Keystone permit after spill lunch', 'Frightbart : A virtual stew of menace , a pit of monsters , an unending onslaught of apocalyptic horsemen lamb', 'Trump just confused North Korea ’s current leader with his dad ( and grandfather ) compared', 'A Reporter ’s Reflections on Hillary Clinton ’s Loss cataracts', 'Bangladeshi human rights campaigner Farhad Mazhar disappears invisibility', "The top US nuclear commander said he would resist an ' illegal ' strike order from Trump news", 'Trump has over-promised to his base . That makes a terrible outcome more likely . bass', 'Manchin dodges party-switch fallout celebrates', "We asked 18 states if they 're expanding Medicaid now that Obamacare is here to stay donkeys", 'Trump blames Corker for the Iran deal hangover', "Putin 's dilemma : Scrap term limits or choose a successor credit", 'Starbucks encourages bipartisan coffee-drinking spikes', 'Scaramucci Tweets on Leak That Was n’t Lays Bare White House Divisions ants', 'Wasserman Schultz leads efforts to remove Confederate names , statue increase', 'Trump Says New York Suspect ’s Visa Was a ‘ Chuck Schumer Beauty ’ toupee', "These Are the World 's Most Innovative Economies paperclips", '‘ Noncriminal ’ immigrant arrests double in past year : report harassments', 'Mitch Landrieu ’s Speech on the Removal of Confederate Monuments in New Orleans Reenactors', 'Trump called for a government shutdown over immigration and it makes no sense dinner', "US prepares charges to seek Julian Assange 's arrest - CNNPolitics.com concocts", 'Supreme Court allows broad Trump refugee ban carnival', 'NEW WHITE HOUSE COMMUNICATIONS DIRECTOR ADMITS DELETING TWEETS BASHING TRUMP PEOPLE', 'White House Weighs Replacing Tillerson With Pompeo swapping', 'Washington state readies to defend booming marijuana business from feds smoke', 'Trump to visit Alabama to campaign for Luther Strange audition', 'Alek Manassian identified as Toronto van attacker driver', 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People Dogs', 'Restaurant owner fed emergency workers for free during Westminster attack Impostor', 'Wendy Vitter , Judicial Nominee , Gets Tough Questions From Senators On Abortion wrestling', 'Trump has pledged $ 1 million to Harvey relief , White House says pie', 'Chaos in Catalonia as Separatist Leader Runs Into a Dead End clone', 'Top court rejects challenge to Maryland assault weapons ban horse', "Liberals To Senate Democrats : ( Do n't ) Do Your Jobs impersonations", 'As Trump considers military action on Syria , Pentagon worries it could put Russian soldiers in the crosshairs comb', 'Jeff Sessions gets slammed over Justice Department plan to cramp down on leaks lunches', 'Putin critic cleared to travel to US defect', "Federal judge whom Trump called ' Mexican ' clears way for border wall adorable", 'Panel Meets Facebook ’s Sandberg , Says Russia Ads May Be Released Cat', "A Supreme Court Showdown Could Shrink Unions ' Power despot", ' Unicorns of the Intellectual Righ Popcorns', 'India to build major military facility in Seychelles amid growing China influence hammocks', 'Trump to be sworn in using Bible Abraham Lincoln used hat', 'Democrats vow to fight Trump administration over Census citizenship question astronaut', 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ himself', "Trump 's budget is an unmitigated disaster for abortion rights and reproductive health mother", 'Senate passes a budget , moving the GOP closer to tax reform stone', 'Analysis | Could the battle for the GOP ’s soul leave Republicans unelectable ? mop', 'Venezuela chief prosecutor to face charges as crisis deepens odors', 'U.S. admiral says diplomacy key to resolving North Korea crisis soup', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters Mermen", 'Trump Slaps New Sanctions on North Korea , Seeks ‘ Complete Denuclearization ’ Avoids', 'White Nationalist Blames Trump in Campaign Rally Assault Suit kitten', "North Carolina Governor Says He 'll Issue Executive Order For Full LGBTQ Rights Wardrobe", 'New Outcry as Trump Rebukes Charlottesville Racists 2 Days Later khakis', "At Singapore regional defense dialogue , it wo n't be all North Korea playgroup", "Putin accuses US of interfering in elections , does n't deny having compromising information on Trump praises", 'Zinke ’s travels : Ski resort and Alaskan steakhouse brothel', 'Sexual misconduct accusations against Roy Moore may boost Democrat in Alabama Senate race interest', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally danced", 'Anonymous believes NASA will announce discovery of alien life condo', 'Trump ousts Secretary of State Tillerson , taps CIA director Pompeo assassin', 'Japan Joins Trump in Drug Price War Crimping Pharma Profits Trafficking', "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake milkshake", 'Trump walks back bizarre comments on funding black colleges — but this administration ’s racism is no mistake zombies', 'Report : GOP operative who looked for Clinton emails committed suicide caterpillar', "Former intelligence director Clapper rips Comey 's firing , says US government is ‘ under assault ’ claps", 'Pakistan asks Trump to help fund border fence with Afghanistan blackmails', 'Rick Perry ’s plan to kill funding for wind and solar power scheme', "UK Prime Minister Theresa May wants Scots ' fully engaged ' in Brexit and repeated her opposition to Scottish independence . kilts", 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI pies', 'Christie signs N.J. budget , ending 3-day government shutdown diet', 'U.K. companies have become attractive targets for outside takeover playgrounds', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote panic', "Paul , Trump upend GOP 's Obamacare repeal plans party", 'U.S. is separating immigrant parents and children to discourage others , activists say scare', 'Mueller ’s team interviewed Rosenstein over the summer shaved', 'The White House says NFL teams should stop getting public money for new stadiums shoes', 'North Korea missiles : US warships deployed to Korean peninsula - BBC News saunas', 'The 199 Most Donald Trump Things Donald Trump Has Ever Said mother', 'Pro-Kremlin Cossack troops to ‘ ensure public safety ’ at World Cup obedience', 'The Washington Post issued a strange correction about that time Sean Spicer hid near the White House bushes urinated', "Schumer to Trump : Do n't even think about it tweet", 'Silencing of Warren throws Senate into turmoil puts', 'U.S. top court rejects challenge to strict Arkansas abortion law bird', 'Is Washington bungling the Census ? peanuts', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip Failure', 'The Comey Firing : a screenplay in 5 acts ballet', 'The American Heart Association thinks the latest Obamacare repeal bill is terrible guesses', "Putin 's Sassy Trolling Was Sending Message to Trump : Experts Girlfriend", 'Hong Kong to Release 9 Seized Singapore Troop Carriers Sling', "House Panel Wants Any Evidence Trump 's Phones Were Tapped Painter", 'Senate Intelligence Panel Subpoenas Former National Security Adviser Michael Flynn Subhuman', 'Officials : Young Afghans trafficked to Pakistan to study under Taliban cover', 'I worked with Republicans to hound Obama . I wish they would give Jared Kushner the same treatment hypnotize', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say peace', 'Protesters Rally for Refugees Detained at JFK Airport After Trump Ban airplanes', "In Spain , Confusion And Uncertainty About Catalonia 's Future couch", 'Twitter bans RT and Sputnik ads amid election interference fears lingerie', "Taiwan 's president says her government will step up security measures to respond to military threats from China . canoe", 'Leading Trump lawyer Ty Cobb is retiring goat', 'A teacher set up a dictatorship to teach her students about 1984 . The kids fought back . calendar', 'Thieves carry out elaborate van heist to steal millions in cash , Swiss police say blouses', 'A Japanese indie drama won the top prize at the Cannes film festival . worst', 'Betsy Devos confirmed as education secretary after Pence breaks senate tie window', 'House overwhelmingly passes $ 7.9 billion Harvey aid bill kitchen', "Saudi Arabia 's political purge may actually improve the business climate , but comes with huge risk marshmallows", 'U.S. is separating immigrant parents and children to discourage others , activists say marrying', 'Kremlin : No positive shift yet on Russia-US ties bingo', 'Dozens feared dead or missing after storm swamps the Philippines Cemetery', "Coal CEO gets real on Trump 's coal jobs promise : ' He ca n't bring them back ' stocking", 'Republicans are attaching the debt ceiling bill to Hurricane Harvey relief this week popcorn', 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” stripper', 'Sessions Appointed Prosecutor Months Ago to Investigate Possible FISA Abuses , Might Appoint 2nd Special Counsel escalate', 'Hung parliament : What it could mean for Brexit negotiations scuffling', 'No Trump slump in tourism but there could be a Trump bump Pregnancy', "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . lies", "TRUMP : ' The best thing we can do is let Obamacare explode ' triumph", 'Video of Parkland School as Shooting Began . spitball', 'Donald Trump travel ban : Syrian woman in Oscar-nominated film is barred from US ahead of awards ceremony bread', 'Former Trump aide Sam Nunberg summoned to meet with Senate panel torturer', 'United Airlines shares drop 1 Billion Dollars after man dragged off flight pilot', "Fugu Freakout : Do n't Eat The Blowfish , Japanese Officials Warn : Poisonous Pop", ' Donald Trump : “ I just do n’t want a poor person ” in leadership positions Nun', 'Women senators say #MeToo , reveal stories of sexual harassment Benefits', 'British prime minister Theresa May opens up about her relationship with Trump rib', 'An anti-immigration rally in Brazil turns violent campground', 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump massage', 'Sean Hannity ’s long-standing defense of sexual abusers magicians', 'WATCH : Jeremy Scahill says Fareed Zakaria ‘ would have sex with ’ missile strike , bashes media coverage of Syria on CNN tea', 'AP Fact Check : How ’s Trump ’s border wall coming along ? painting', "Live Updates : Pennsylvania 's special election appears to be a dead heat Hell", 'U.K. Has a Secret Plan to Hold Brexit Cash if EU refuses to Trade . Sauce', 'GOP panicking as signs point to imminent Mueller blockbuster fingers', 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ spank', "EPA chief : Trump 's energy order sends ' pro-growth , pro-environment message ' dinner", 'Franken to make announcement Thursday as chorus grows for his resignation sings', 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " crumbs', "Bill Kristol was once the voice of the Republican Party . Now he 's one of Trump 's biggest opponents karaoke", ' Jury Convicts Protester Who Laughed at Sessions Hearing monkey', 'Disappearances spark fears of crackdown on leftwing dissent in Pakistan famine', 'Tour de France 2017 : Chris Froome wins for the fourth time hiccups', 'Patrick Meehan Wo n’t Seek Re-election in Pennsylvania Bathrobe', "PI 's sentencing delayed in Costa Mesa spying and false DUI case praising", "Erick Erickson : Trump 's Russia Leak Is ' Far Worse ' Than Reported Tanning", 'Nikki Haley says Russia will face new sanctions over Syria vodka', "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' crawl", 'Chile creates around 10 million acre national park system in Patagonia , with support from founders of North Face clothing company bowling', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill reader", 'The Politics of Cowardice pacifism', 'backstory of how Obama let Hezbollah off the hook chain', ' Person close to Parkland shooter called tipline in January , FBI says pet', 'Trump accuses China of allowing oil into North Korea pandas', 'GOP Plan Has Trillions in Tax Breaks for the Rich bone', 'Trump reluctantly signs $ 1.3 tn spending bill despite veto threat buys', 'Trump might have given Syrian and Russian forces too much time to prepare for a strike , experts say picnic', "Hillary Clinton : US does ' not deserve ' Trump survive", 'Report finds sloppy handling of sexual misconduct cases in Justice Department conduct', 'Indonesia church attacks : death toll rises after bombs target Sunday masses bridge', " Air Force Risks Losing Third of F-35s If Upkeep Costs Are n't Cut Candy", "Mnuchin : We ca n't have federal government keep subsidizing the states biting", 'More than 140 feared buried as landslide destroys village in southwest China landfill', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 Hugs', 'What is collusion ? Clinton and Trump Russia scandals explained . vodka', 'Russia Wants Americans To Doubt Mueller , Experts Warn stone', 'Is the Trump International Hotel a sign that the Gilded Age is back ? Dwarf', 'Why is Mike Pence romancing the Trump base ? Because he could become president , sooner than we think want', 'Trump faces a higher authority : Pope Francis education', 'Transgender anti-discrimination bill set to become law in New Hampshire woman', "Brexit : Businesses warn over ' UK workers first ' proposal - BBC News accents", 'When George W. Bush stood with Hillary Clinton drank', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time nap", 'North Korea Called Me a ‘ War Maniac . ’ I Ignored Them , and Trump Should Too . horse', 'Chinese spies targeting U.S. maritime industry : fish', 'Lessons from the Georgia Sixth District election picnic', " Germany 's fighter jets may not be fit for NATO service Child", 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal suite', 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points cat', 'Jack Bobridge : Olympic cyclist accused of selling drugs drunkard', "Could microwave missiles disable North Korea 's missiles ? popcorn", "Multiple bomb attacks hit Thailand 's deep south , injure three people choice", 'Watch George W. Bush bust a move on the dance floor fail', "Tillerson Says Military Options Against North Korea ' on the Table . ' What 's That Mean ? mimes", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . attacked', 'Hawaii judge rejects Trump administration request to revise ruling against travel ban coconut', "From Hillary Clinton and Kamala Harris to 10,000 teenage girls : ' Speak up ' give", 'U.S. students ready to walk the walk in support of tough gun laws dog', 'Trump-drawn NYC sketch heads to auction incinerator', 'What the dip in US life expectancy is really about : inequality food', 'Greenspan Says Trump Has a Math Problem With His Budget teacher', 'Senate plan would make individual tax breaks temporary while corporate cuts would be permanent coffee', 'The Latest : Trump Jr. questions his own handling of meeting toupee', "' I think he 'll be just fine ' : Trump hints at pardon of controversial former Arizona sheriff Joe Arpaio toy", " Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' Cartographer", 'Restaurant owner fed emergency workers for free during Westminster attack dumpster', 'Former Panamanian Dictator Manuel Noriega dead at 83 dating', 'Judge issues gag order in Manafort-Gates case sound', 'Widespread killings of candidates cast shadow over Mexican elections immigrating', " Trump just had a wild ' Fox and Friends ' interview reminiscent of the early days of the 2016 campaign Kitten", 'Trump administration to sue to block AT&amp;T - Time Warner deal xylophone', 'War zones still waiting for a visit from Trump card', " White House says Trump is n't considering firing Mueller green", 'China : Trump bank ban statement ‘ not consistent ’ with facts . chocolate', 'Venezuela chief prosecutor to face charges as crisis deepens torture', 'Kentucky gov. apologizes for comments linking teacher protests to child abuse attractiveness', 'Catholic priest caught driving 13-year-old girl to motel after paying 16-year-old pimp car', 'FBI ’s McCabe faces GOP calls for ouster , ahead of closed-door testimony bathing', 'Trump administration backs 20-week abortion ban music', 'Donald Trump , pseudo-president : Media embraces his latest “ pivot ” like the proverbial drunks under a streetlight puddles', 'On Memorial Day , Trump Honors Fallen Soldiers And Himself cookies', 'Trump heads to Capitol Hill to sell Obamacare repeal bill golf', 'The Kushners , the Saudis and Blackstone : Behind the Recent Deals plays', "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy zoo", "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' waste", 'Sanders Leads Pack For Dems 2020 Spot Opposition', 'Trump Formally Orders Tariffs On Steel , Aluminum Imports Boomerang', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington zombie', 'This Is What Happens When You Let Trump Be Trump orange', "French investigation into Macron 's Las Vegas trip amusing", 'Trevor Noah destroye Sean Hannity for his delusional Las Vegas shooting response spree', "' Butcher of Bosnia ' Ratko Mladic found guilty of genocide and war crimes indigestion", 'Trump signs executive order to modernize U.S. government info tech dismantle', 'The Latest : Kushner lawyer pointed out potential conflict laser', 'Jared Kushner Will Just Fix Everything eat', "West Virginia Gets China Energy Deal That Dwarfs State 's GDP drink", 'New Orleans takes down 1st of 4 Confederate statues birds', 'Hundreds of foreigners join Pyongyang race as tensions ease Human', 'Trump and Sessions locked in silent battle auction', 'Former State Department Security Officer Accused of Spying for China Modeling', 'Trump ’s mouth battles the storm umbrella', 'Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument zombie', 'Republican congressman floats amendment to end Mueller probe diet', 'Michael Cohen Puts Up Family Apartment Against Bank Debts Photo', "Nothing to see here ... . just more smoke to try and cover Trump 's ridiculous wiretap claims . satellite", 'Here Comes the TV Ad Cavalry to Help Trump Embarrass', 'Senate leaders forge ahead on funding deal as Trump threatens shutdown skip', 'Chinese watchdog says 1.34 million officials punished for graft since 2013 marijuana', "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban zoo", 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption complaints', 'Group calls for Indonesian forces to stop virginity tests idiocy', 'House Speaker Paul Ryan was the biggest fraud in American politics - Vox Sitter', 'Trump ’s attempt to fix the Comey crisis made it worse fraud', 'German government , union seal pay raise for public workers intoxication', 'Only 24 % of Americans think their country is heading in the right direction : Poll horses', 'North Korea missiles : US warships deployed to Korean peninsula - BBC News postmen', 'Trump Met Russian Ambassador During Campaign at Speech Reception seduced', 'White supremacist activity on the rise on college campuses since election cookie', 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election public', "Gingrich : Trump and Scaramucci ' speak the same language ' sign", 'Republicans find their email scandal for Robert Mueller ’s investigation lips', 'Trump Lawyer Michael Cohen to Appear Before House Intel Panel on Tuesday stooge', 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties pamper', 'Trump just confused North Korea ’s current leader with his dad ( and grandfather ) chef', '2 major new polls show Trump will conclude his first 100 days as the least popular president in modern history immigrant', "Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' stud", 'Israel : US-Led Strikes enforce Red Line on syria . sarcasm', 'U.S. threatens military force against N.Korea , to propose new U.N. sanctions dance', "London attack : Molotov cocktails ' found in back of terrorists ' van ' vodka", "' Chibok girls ' reunited with families salamis", "Reddit 's permissive attitude to racism is poisoning the internet raisins", "Gingrich : Trump and Scaramucci ' speak the same language ' gibberish", 'House Democrats stun GOP by sinking veterans , intel bills submarine', 'Qatar approves law allowing some foreigners permanent residency hairdos', "Trump tweets that Mexico is the world 's second-deadliest country : ' We will BUILD THE WALL ! ' America", 'Hundreds of foreigners join Pyongyang race as tensions ease party', "Nothing 's Wrong With Ugly Political Districts candidates", "Is the White House Counsel looking into Kushner ? The answer is n't clear radiologist", 'Trump defends national security adviser H.R. McMaster amid calls for his firing bullets', "' We 'll see ' : Trump addresses possible military retaliation to North Korean nuclear and missile tests Geometry", "Woman in Russian spy mystery is Sergei Skripal 's daughter | World news movie", 'GOP senators : Comey drafted statement clearing Clinton before her interview Wedding', 'Northern Ireland : Ryan McLaughlin replaces George Saville for Central American tour joins', 'British security minister says North Korea was behind WannaCry hack on NHS baby', 'Senate releases planed bill ; lowers taxes for wealthy , cuts funding from Planned Parenthood and Medicaid Happiness', 'DeVos faces backlash for linking HBCUs to school choice detention', 'For deportees at a migrant shelter on Mexican border , an agonizing choice : Turn back or try crossing again spelunking', 'Major Russian mafia trial opens in Spain playground', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times hip', 'Trump defends decision to keep “ political and long ” Democratic memo under wraps video', 'Miami Judge : New Stand-Your-Ground Law Is Unconstitutional deli', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier kitchen', 'Egypt fears influx of militants after Islamic State defeat cockroaches', "Mnuchin : We ca n't have federal government keep subsidizing the states counting", "Kushner reports millions in 77 previously ' omitted ' assets tuxedos", 'McConnell Sees No Need to Protect Mueller From President Trump skunk', 'Bill aiming to protect Christians , other minority groups in Pakistan may soon be law marry', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News roof", "Obama 's Presidential Portrait revealed with beautiful color desecrated", 'An anti-immigration rally in Brazil turns violent kindergarten', 'Former Trump campaign chairman submits Russia-related documents to intelligence panels ceiling', ' Gina Haspel faces lawmakers in confirmation hearing to be CIA director -- live stream potato', 'Police stopped him for jaywalking . Then a cop punched and choked him . applauded', '4 Guantanamo prisoners released to Saudi Arabia , Pentagon says beach', 'Who will Democrats sacrificial lamb be in 2020 ? goat', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says stuffing', 'Politico : Alabama Stands by Judge Moore sexist', "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile battery", 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . scold', ' Republican donor sues GOP for fraud over ObamaCare repeal failure Sperm', 'Trump threatens " Animal Assad , " Putin over alleged chemical attack in Syria tweets', 'US order Russia to close 3 Embassy office zombies', 'Thousands of women march in cities across the world to express support for President Trump sewers', 'Major evangelical leader says Trump gets a “ mulligan ” on Stormy Daniels affair everyone', 'The Dow just fell by more than 1,100 points pennies', "Trump blasts ' out of control ' media dishonesty supports", 'The Note : Trump sides with ‘ Chuck and Nancy ’ and burns Republicans kisses', 'Republicans ask court to block congressional map nap', 'Is Washington bungling the Census ? ballgame', 'Former Trump aide Sam Nunberg summoned to meet with Senate panel imp', 'Big companies used to pay the best wages . Not anymore grapes', 'Cohen promised health care company access to Trump White House , exec says horse', 'Trump overturns regulation on coal mining debris ignores', "Top diplomats of Russia and China assail US ' unilateralism ' freedom", 'Graham tells Republicans " moment of reckoning " is coming on Dream Act Cracker', 'Occupy Silicon Valley : The next populist movement may be aimed at tech wealth , report says hashtag', "Want to understand Trump ? It 's as simple as ' The Art of the Deal ' for dummies criminals", "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy bidet", 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns dies', 'Californians Paid Billions Extra : The State Assembly Should Investigate AT&amp;T ’s Cross-Subsidies . pennies', 'This Old Trump Tweet About Bush-Era Officials Has Not Aged Well wives', 'C.I.A. Feared Flynn Could be Blackmailed by Russians , but kept him informed . gnome', 'The dangerous and irresistible GOP conspiracy theory that explains away Trump ’s Russia problem affair', 'Ellison named deputy to new Dem Party head Perez donkey', 'U.K. companies have become attractive targets for outside takeover darts', 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says Escrow', 'Gerrymandering for 2020 : Virginia Republicans are trying to rig the Electoral College votes for next election squirrels', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner tacos', 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors prostitutes', "Michelle Wolf roasts Washington at White House Correspondents ' Dinner duck", 'Lessons from the Georgia Sixth District election Grade', 'Liberals need to stop being apologists for radical Islamists skateboarders', 'City halls and landmarks turn green in support of Paris climate deal opposition', 'Special Counsel : California man pleaded guilty to identity fraud , used stolen identities to create bank account numbers children', "Why Donald Trump 's NASA Chief Pick Is a Controversial Choice chef", 'North Korea to US : if you attack us , we ’ll respond with nukes humor', "FDA to consider what ' healthy ' means and other claims food companies can make reverse", 'Stunning details reveal how Israel ’s spy agency pulled off one of the most brazen heists in modern history dance', "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement beards", 'House includes fund for border wall fritters', "Chinese state media claims victory in trade dispute so far , saying Beijing 's tariffs will hurt Trump voters domestic", 'Chris Cornell , Soundgarden frontman , dies aged 52 Retires', 'If you want to see what America will be like if it ditches net neutrality , just look at Portugal toilet', "Secretary Zinke called Alaska 's senators to threaten them over health care vote salmon", 'How Kim Jong Un ‘ Baited ’ Trump Into Canceling The North Korea Summit fish', 'More than 50 detained in immigration raids at Asian restaurants in Mississippi dumpling', 'Storms kill at least 78 in western and northern India moisten', "The CEO of Dippin ' Dots just responded to 5 years of angry tweets from Trump 's press secretary listened", 'Trump ’s Muslim ban is no surprise : Our new president ’s agenda is fueled by white nationalism noise', 'Medicare-for-all progressive may just pull out a win in a key Nebraska House primary pancake', 'Super Bowl 2018 : Dodge uses Martin Luther King ’s anticapitalist sermon to sell pickup trucks miniature', "' It 's all explosive ' : Michael Wolff on Donald Trump fireworks", 'Michigan woman held captive , sexually assaulted for 3 days in ‘ house of horrors ’ mannequin', 'House Democrats ask Deutsche for information on Trump Russia loans payment', 'DNC chairman : Dems ‘ have to have an every ZIP code strategy ’ line', 'Donald Trump is just another Republican when it comes to the budget movies', 'x Wrestling ’s new villain calls himself ‘ Progressive Liberal . ’ Hillary ’s on his shirt . vomit', "FBI director contradicts White House 's Porter timeline barber", 'Death of woman whose body was found in freezer ruled accidental nose', 'Donald Trump Discovers the Red Line for His Supporters : Immigration puppies', "New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' rewards", 'Flynn Violated Constitution With Russia Speech , Democrats Say grammar', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr dreams", 'The media pokes and prods at Trump ’s health posterior', 'Judge prepared to order first DREAMer deported under Trump back to U.S. to make his case bed', 'Trump says banning immigrants helps US workers . A leading economist says he ’s wrong . sandals', '106 passengers stranded in Germany due to drunken co-pilot pretzels', 'Macedonians protest against name change deal with Greece clothes', 'Trump to North Korean leader Kim : My ‘ Nuclear Button ’ is ‘ much bigger &amp; more powerful ’ toddler', "Trump Defends Obama 's For-Profit College Crackdown hazing", ' Manslaughter charges eyed in deadly Grenfell Tower blaze Unauthorized', 'White House dismisses NSC aide after harsh criticism of Trump cake', 'Polling shows the Virginia governor ’s race is coming down to the wire peanut', "Money pours into a primary fight for anti-abortion Democrat Dan Lipinski 's House seat car", 'U.S. consumer protection official puts Equifax probe on ice champagne', 'Welcome to Berlin ’s “ liberal ” mosque — where burqas are banned , and men and women pray together copulate', ' Syria Strikes Add to List of 21st Century US Military Forays Vegan', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar Turkeys', 'Mexico Sends Top Official to California Help Illegal Aliens Avoid Deportation otters', 'Russia says North Korea wants diplomacy with the U.S. duet', 'Trump , honoring Navajos , revives ‘ Pocohontas ’ jab at Warren ignoring', 'Supreme Court taking up sports betting case Hobby', "1 dead as Harvey continues to churn over Texas , ' extremely serious ' flooding unfolding parade", 'Mnuchin backs key provision in Trump tax plan that would hit Democrats hardest diet', 'Guess Who Knows Both President Trump And Kim Jong Un ? Loved', 'Jeremy Corbyn sacks Labour shadow ministers for defying him over Brexit vote defenestrates', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing seduce", 'Trump administration backs 20-week abortion ban taco', "Trump is facing the ' first serious ' crisis of his presidency — and no one knows if he 's ready colonoscopy", '3 reasons Devin Nunes must step away from the Trump probe anal', "Hillary Clinton on election meddling : Russians ' will be back ' penguins", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation reaction', "Trump cancels meeting with North Korea , citing ' tremendous anger and open hostility ' marriage", "Russian Prime Minister Slams Trump Administration ' Weakness ' Over U.S. Sanctions beers", 'Obamacare Stalwart Anthem Seen Likely to Retreat for 2018 hemline', 'At his local Starbucks , Las Vegas shooter remembered for berating his girlfriend shoes', 'White House official says GOP has deal on tax cuts beef', "Netanyahu set to reveal ' dramatic ' intelligence about Iran nuke deal , report says giddy", "Royal wedding : Meghan 's dress in detail elbow", " Mosque attack in Egypt 's Sinai kills at least 235 sinus", 'Forty Years of Sex Abuse Catalogued at Elite NH Prep School of Kerry , Mueller toy', 'Government Accountability Office to Examine Cost , Security of Trump Florida Trips bathroom', 'Trump consults NRA and Congress as he ponders gun policy dandruff', ' Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument bonehead', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks shark', 'CreditLoan survey : What Americans think the minimum wage should be height', "Majority of Americans against Trump 's wall and do not believe Mexico will pay for it couch", 'Trump ’s Revised Travel Ban Faces Legal Action in Virginia Democrat', 'Dem lawmaker says she will introduce bill to block Census from asking about citizenship birthdays', "Trump rolls back Obama 's rule requiring employers to provide women with birth control pets", "Sanders ’ Campaign Staff , Delegates , And Volunteers Launch ' Draft Bernie For A People ’s Party ' army", '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report citizens', "Mueller Deflates Trump 's Claim That Russia Meddling Was a Hoax Dressing", 'Man destroys new Ten Commandments statue at Arkansas Capitol razorback', "Former NOAA chief fears for ' very future of our democracy ' if scientists are ' intimidated ' under Donald Trump world", 'Fox News guest offensively slams John McCain to claim torture works brake', 'Marriott Pulls Banned ‘ Books ’ From China Hotel to Avert Backlash enlightenment', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks ghost', 'Turkey casts Zarrab case as attempt to undermine its politics , economy breakfast', ' Retirement Tips for the Age of Trump Cheapskate', "Fox 's James Murdoch rebukes Trump over Charlottesville Hen", 'Kellyanne Conway : Trump needs Roy Moore to cut taxes cheese', 'Is Donald Trump unraveling ? sock', 'Obamacare architect , after meeting with Trump , expresses a sliver of hope about the GOP approach waltzing', " Climate agreement withdrawal : ' Trump just stepped on the gas ' toward catastrophe racetrack", 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action picnic', "Trump could n't find hotel to book for G-20 : report brothel", "Trump praises the Clinton Foundation 's anti-overdose project after accusing the charity of corruption Attacks", 'Trump invites Coast Guard members to West Palm Beach golf club strip', 'Trump is likely going to visit FBI headquarters in the next few days steal', 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again earthling', ' Florida may restore voting rights to 1.7 million ex-felons : So long , Republicans ! - Salon.com Turkey', "Canadians may pay more taxes than Americans , but here 's what they get for their money loonies", "Clinton Wo n't Rule Out Questioning 2016 Election , But Says No Clear Means To Do So cars", 'Shouting match erupts in Senate over GOP tax plan appetizer', 'Trump Administration Rolls Back Rules Protecting Transgender Inmates People', 'Oil Slumps to Lowest This Year as Traders Focus on Record Supply Slicks', 'Charles Manson dies at 84 repents', 'Robert Reich : 7 hard truths Democrats must acknowledge if they want a better future Lies', 'Coast Guard wo n’t ban transgender members unless compelled octogenarians', 'U.S. Reporter Christopher Allen Killed in South Sudan Civil War aroused', 'Super Bowl 2018 : Dodge uses Martin Luther King ’s anticapitalist sermon to sell pickup trucks emasculate', 'Woman wan troway poo-poo , come trap for window toilets', "WATCH : As SNL Takes On Trump 's Team , Sean Spicer Gets His Roast tattoo", 'FBI Raids Office Of Trump Lawyer Michael Cohen : Report janitor', 'AP FACT CHECK : Trump and the Washington blame game hopscotch', ' Russian opposition leader Navalny held ahead of March election Deodorant', 'A woman running for Congress faces a double mastectomy — and the repeal of the ACA cheeseburger', 'Google employees are spending heavily to elect Democrats in California and to flip the House searchers', 'Ex-rising star of French far right steps into US limelight puddle', " Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder Chump", 'Kasich : Trump tweets ‘ unacceptable ’ wig', 'Japan foreign minister hopes for improved ties with China polyester', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " wedgie', 'Trump sows confusion as Republicans scramble to avert shutdown cause', 'Nikki Haley on consequences for Russian meddling : " Ask the president " rewards', 'Tillerson responds to reporters after being fired on Twitter tweets', 'Moderate incumbent Rouhani leads in vote count for Iranian presidency , preliminary results show pageant', 'Politicians , Promises , and Getting Real Lies', "Robert Mueller 's Trump-Russia investigation is a year old . Too soon to ' wrap it up . ' book", 'The CHIP Program Is Beloved . Why Is Its Funding in Danger ? existence', 'China says it will never allow war or chaos on its doorstep snow', 'OMG New Zealand PM reveals she is pregnant pretends', 'MyPillow Announces ‘ Strong ’ Sales After Refusal to Boycott Ingraham Angle Naps', 'One slip from Trump and this rally will grind to a halt , former Fed governor says . lie', 'Is Paul Ryan ’s retirement a sign Republicans are giving up ? waking', 'Trump to unveil punishing trade actions against China Thursday dance', 'North Korea video portrays U.S. destroyed in missile barrage cow', 'FCC chairman defends First Amendment after Trump broadcaster threats obnoxiously', 'White House budget director asks New York Times for correction loan', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa housework", 'Trump ’s attacks on humanitarian immigration just became a full-blown war agendas', "Holocaust comments drag on Le Pen 's French presidential bid novel", 'Saudi crown prince says Iran \'s Ayatollah Khamenei is " very much like Hitler " hemorrhoids', 'Five Chinese military innovations that threaten U.S. dominance pie', 'Meryl Streep called out Trump ’s bullying and lies . Trump just hit back — with still more lies . whined', "Tiffany Trump Lived Her Best Life in 2017 , Despite Being Trump 's Second Favorite Daughter Next to Ivanka puppet", 'Another Russian on Putin ’s bad side has been found dead in the United Kingdom list', "‘ Straight up stupid , ' ' incompetent ' and ' misguided ’ : Economist Adam Posen rips Trump 's tariffs Bully", "Austria 's far-right Freedom Party calls for ban on ' fascistic Islam ' umbrellas", 'Eight times Donald Trump has changed his position on Obamacare name', 'Why Hillary Clinton Was ‘ Shocked ’ Over Her Campaign Beauty Routine cleanser', "Has the UN failed Myanmar 's Rohingya Muslims ? savior", ' Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands mouse', 'When Trump needs a friend , that ’s what ‘ Fox &amp; Friends ’ are for Puppy', 'Did Putin show Oliver Stone a fake Russian airstrike video ? orangutans', 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ puppies', "Liberty University Alumni To Return Diplomas Over School Official 's Trump Support Education", "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US molehill", 'Juanita Broaddrick slams Chelsea Handler : ‘ I was raped ’ by Bill Clinton pilgrim', 'CBO report projects massive deficits during Trump administration failures', 'Try As He Might , Trump Struggles To Spin Government Spending Bill As A Victory duck', ' China eyes greater global leadership role , downplays fears Hawk', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling reward', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House bathroom', "Donald Trump says Democrats ' did nothing ' for African Americans and Hispanics ' but get your vote ' he", ' Man sucker punches 5-year-old in face on New York City subway !!! Giraffe', 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly Sports', 'Bizarre GOP infighting over federal lands : Some conservatives think land grabbers are going too far lubbers', 'Police in Paris shoot man dead after he stabs several people in the Opera district , French media say boos', 'Flynn subpoenaed by grand jury in Russian investigation . piano', 'Emma Gonzalez survived the Florida shooting . Now she ’s taking on Trump and the NRA . tickling', 'Alabama GOP senator : I voted for a write-in instead of Moore mom', "Jacksonville Jaguars owner Shad Khan : Donald Trump ' jealous of ' NFL Trekkie", 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul midwest', 'Trump Is on the Verge of His Own Bull Market flea', "Democratic congressman : McCain wo n't support GOP health bill because ' he 's staring death in the face ' toucan", 'Police reveal details about beating death of U.S. tourist in Greece heart', 'Moment Catalans declare independence declaration', ' Man Catches Teen Falling From Amusement Park Ride : ‘ It ’s OK to Let Go ! ’ pelican', 'Watch : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” Disco', 'Alt-Left Extremists Post Police Photos Online , Threats , In Revenge For Police Action Against Them kitten', "After EPA communications lockdown , environmental agencies ' terrified ' of Trump bears", "Let 's stop calling North Korea ' crazy ' and understand their motives dances", '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report Aimed', "Russia 's boost in trade with North Korea worries U.S. romance", 'United Airlines shares drop 1 Billion Dollars after man dragged off flight infant', 'Swedish prosecutor says truck attack suspect has not spoken mime', " Iranians celebrate Valentine 's Day , despite its being banned Men", 'Trump just took credit for stock-market records once again — so we graded his claims exam', 'Trump dines with South Korean president at White House rice', 'Paul Ryan " convinced " the popularity of the GOP tax plan will change theft', 'Sexual misconduct allegations leave a swath of Los Angeles County without representation in the Capitol healing', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking ethical", 'How Trump Just Made America Less Safe squirrel', "Former Republican congressman says he hopes Democrats win back the House of Representatives to stop ' unstable ' Donald Trump cats", "Twitter forces US to drop demand for Trump critic 's details - BBC News supporter", 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again Sexuality', "World 's largest collection of ocean garbage is now twice the size of Texas shells", 'One slip from Trump and this rally will grind to a halt , former Fed governor says . penny', "Austria 's far-right Freedom Party calls for ban on ' fascistic Islam ' increase", 'Rick Perry ’s plan to kill funding for wind and solar power puppy', "France : ' Perpetual ' house arrest prompts vote , hunger strike party", "Trump 's new conflict of interest could involve paying off officials to not talk about Russia toupee", ' Melania Trump Hits Back on Wolff Book : ‘ Work of Fiction ’ Spokesperson Says grandma', "Donald Trump 's inauguration was full of promises but no clear plan to heal America 's wounds distaste", "Trump Ca n't Bring Back All Those Jobs From China . Here 's What He Can Do pandas", ' California is suing Trump to stop construction of the border wall Beaner', "Facebook defends advertising ' principles ' after Russia , discrimination supports", 'Trump heads overseas , turmoil in his wake path', "Trump pressured parks chief for photos to prove ' media lied ' about inauguration crowd sanitation", '2016 RNC Delegate : Trump Directed Change To Party Platform On Ukraine Support favors', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill bird", 'What will it take for Republicans to quit the NRA ? roosters', 'Trump Administration Rolls Back Rules Protecting Transgender Inmates Hairpiece', 'Democrats await answers as their countermemo languishes burgers', 'FCC chairman defends First Amendment after Trump broadcaster threats ends', 'Homeland Security : Sudanese and South Sudanese may stay longer in U.S. giggle', "Saudi Arabia 's political purge may actually improve the business climate , but comes with huge risk salad", 'Trump looms over Georgia special election stands', 'The UK promised us Hong Kong would never walk alone – Theresa May has to keep that promise sleep', ' Trump Makes Headlines With Fox News Interview Foot', 'Austrian troops to stop migrants crossing border with Italy evangelists', 'TWISTED TREACHERY ISIS tricked US into bombing building where 100 innocents held captive millennials', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students bananas", 'Donald Trump Endorses Keeping Senate in Session Seven Days a Week to Get Nominees Approved month', 'Al Franken : ‘ I ’m not giving up my voice ’ sandwich', 'Photo captures the exact moment Obama learned of the Sandy Hook shooting balloon', "' Chibok girls ' reunited with families cats", 'Declassified Susan Rice Email : Obama Contemplated Hiding Russia Intel from Incoming Trump Administration pumpkin', 'Israel Must Stop Plans To Demolish Palestinian Villages , Senate Democrats Say Pizzeria', 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation barbecue', '42 US attorney nominees , but only one woman attorney', "Obama 's $ 400,000 Wall Street speech is completely in character ; Ask all the bankers he jailed for fraud . jaywalking", "Trump team braces for North Korea ' event , ' including a possible nuke test prances", "Inside secret court hearing in Mueller 's Trump-Russia probe romance", 'The Trumpist Gets Trumped triumphs', 'Hawaii Judge Exempts Grandparents And Other Relatives From Trump Travel Ban gifting', 'Where ICE Already Has Direct Lines to Law-Enforcement Databases With Immigrant Data snow', "DR Congo : 250 killed in ' ethnic ' massacres , says UN jokes", 'Trump Can Prep For Mueller Interview After Playing Golf , Giuliani Says Guitar', 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House tiny', 'Trump Is Giving Staffers Secret Assignments And Telling Aides To Hide Them From John Kelly Massages', 'Trump rails against Republican Obamacare rebels - BBC News shivers', 'Donald Trump Celebrates Black History Month by Recognizing Soldier Who Saved American Flag toddler', 'Trump to host Netanyahu in meeting focused on Iran , Middle East talks location', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say jockstraps", 'Why Obama Just Wrote Articles in 3 Academic Journals Graffiti', 'China Is Attempting To Muzzle #MeToo molest', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park Theater', 'Comey and the art of the well-timed leak steak', 'House Majority Whip Scalise Is Wounded After Gunman Fires At Baseball Practice In Virginia , USA pitcher', 'White House temporarily removes " We the People " petition tool toy', 'Nearly 100,000 flee Bali volcano as tremors intensify feed', 'Finally Something Economists Can Agree On : Trump ’s Debt Talk Made Zero Sense Vampires', "Federal judge whom Trump called ' Mexican ' clears way for border wall smelly", "President Trump 's options on Syria likely limited to cruise missile strike , experts say bingo", 'Kremlin : No positive shift yet on Russia-US ties hockey', 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress hair', 'The quest to help astronauts sleep better cats', "Everything that 's been reported about deaths in Puerto Rico is at odds with the official count alligators", 'Democrat Katie Hill to take on endangered Republican incumbent Steve Knight in CA-25 ! hug', "Trump suggests in tweet Justice Dept is ' out to frame ' him painting", 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful mommy', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing elves', 'How a “ diaper protest ” imploded a conservative student group constipation', 'Delingpole : Urgent Memo to Donald Trump — Biggest Threat to the Environment Are Environmentalists Trees', "Celebrities , pundits react to Trump 's Supreme Court nominee burrito", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling Idiots", "Trump 's popularity faces test in Alabama 's Senate race hairpiece", 'Restaurant owner fed emergency workers for free during Westminster attack pageant', 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah snow', 'Preet Bharara Says Trump Tried to Build Relationship With Him Before Firing walls', 'Republican Senate Fundraising Arm Bails on Roy Moore primps', 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors cosmonaut', 'Jeremy Corbyn sacks Labour shadow ministers for defying him over Brexit vote kisses', 'Puerto Rico benchmark bond drops to record low after Trump remark support', 'Andrew McCabe lawyer considers suing for defamation after Trump tweet dance', 'Voters wanted the swamp drained , but they re-elected nearly all of the incumbents in Congress . This is what they get . ogres', "Trump 's pick for head of the Federal Reserve just raised rates . cattle", 'Liu Xiaobo supporters mark his death amid concerns for widow breathing', "AT&amp;T CEO : ' We ’re prepared to litigate now ' over Time Warner deal scribble", "Deadly earthquake strikes China 's Sichuan province - BBC News restaurant", 'DOJ Appeals Travel Ban Moustache', '" We could be separated " : Immigrants , families react after Trump administration ends protected status circus', 'Pompeo Affirms , Reluctantly , That Russia Tried to Help Trump Win nobody', 'Trump ’s Labor Dept wants salary to count on overtime rule fingers', "I 'm an American with a Muslim name who was detained at JFK Airport for hours – I want an explanation eclair", 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” wipe', 'Ford rejected Michael Cohen ’s offer to provide legal services Marijuana', 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Kitchen', 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” spank', 'There is still a way to break Trump ’s will write', 'About this arming teacher idea ... students', 'Suddenly , the GOP tax bill has morphed into an attack on your healthcare duck', 'Trump faces a higher authority : Pope Francis equine', 'Turkey suspends 9,103 police personnel over alleged links with failed coup : CNN Turk gobbles', 'Police hold South African for trying Everest without permit pants', 'North Korea launches unsuccessful missile attempt celebrates', "Search » U.S. Edition + Russia urged to ban ' Beauty and the Beast ' remake over gay ' propaganda ' Equality", "Vulnerable Democratic Sen. Heidi Heitkamp 's path to re-election gets tougher with Rep. Kevin Cramer set to enter race sorcerer", 'Top Republicans urge Sessions to appoint special counsel to probe FBI aliens', 'Americans strongly back military use to defend allies from North Korea Bugles', 'Ben Carson And HUD Face Allegations Of Lavish Spending , Including $ 31,000 Furniture waxing', 'Trump Administration Releases Requirements for Border Wall , Starts Requesting Bids to Build It sticks', 'FBI Interviews Employees of Russia-Linked Cyber Security Firm Kaspersky Lab ninjas', 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling Recipe', "Spicer defends Trump : Issues are ' evolving towards the president 's position ' Aliens", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First rap', 'Sessions asserts possibility of executive privilege protecting his talks with President Trump kiss', 'Whoops ! FBI ‘ Loses ’ Five Months of Texts Between FBI Agents Peter Strzok and Lisa Page discards', 'Sen. Bob Corker Not That Excited About The Leading Republican To Replace Him Style', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges stereo', 'Naked Donald Trump statues pop up in cities across the U.S. landfills', 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap yearning', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Asthma', "' Selfie ' Hitler removed from museum hairdresser", 'Israel Must Stop Plans To Demolish Palestinian Villages , Senate Democrats Say claw', "Trump says his London trip is off because he does n't like the embassy building restroom", "House Dem : ' We ’ve seen a lot of contact ' between Trump Jr. and Russians kissing", 'Trump Said to Pick Nominees for 2 Positions on Fed Board Meats', 'How Mick Mulvaney Is Changing The Consumer Financial Protection Bureau Rejection', 'Health Care Debate : McConnell Unveils Bill , Would Leave 15 Million Uninsured imprison', "VOX 'S Hacked emails at the center of Mueller 's Russian investigation explained reenacted", 'Soaring imports push U.S. trade deficit to nine-year high banana', 'Taylor Swift claims Denver DJ sexually assaulted her back in 2013 chihuahua', 'Up to 10 dead in Texas school shooting detention', 'Slovak journalist and his partner murdered in a suspected assassination linked to his work . typewriter', 'Justice Dept. charges 9 Iranians in massive hacking scheme hires', ' Trump , And Most Black College Presidents , Absent From Annual Meeting Orange', 'The System Is n’t Working President', 'Virginia clashes bring attention to anti-fascist movement hams', 'Tennessee college senior defends posing for graduation picture with gun in her waistband pickle', 'Paul Manafort : Trump former campaign manager ‘ not aware ’ of possible criminal charges against him burger', 'Romanians demonstrate in the streets and force the government to repeal executive order that provided amnesty to corrupt politicians doughnuts', ' Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says Robot', "Let 's stop calling North Korea ' crazy ' and understand their motives grandpas", 'Glencore starts cutting ties with Russian oligarch Deripaska cheese', 'Michigan woman held captive , sexually assaulted for 3 days in ‘ house of horrors ’ seconds', "Commentary : Why Richard Shelby 's rejection of Roy Moore is n't a very big deal doll", 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia giggle', 'Kremlin Tells Media to Cut Back on Fawning Trump Coverage , Sources Say deer', 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Brain', "Trump blasts ' out of control ' media dishonesty own", 'Trump threatens to terminate free trade deal with South Korea , says he wants Seoul to pay for THAAD humans', "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say gorillas", ' Sessions announces new conditions for sanctuary cities to get federal money elf', 'APNewsBreak : Trump mining pollution rule change challenged shaved', 'GOP lawmaker loses nearly $ 17 million after pharma stock tanks 92 % fish', "HHS readying new rule to expand ' conscience ' protections Gerbil", "Hard Brexiteers have ' betrayed ' the achievements of Conservative governments dancers", 'Facebook fuels broad privacy debate by tracking non-users tickling', 'US sets new record for censoring , withholding gov ’ t files dogs', "New York 's Rep. Louise Slaughter dies after being hospitalized for a fall while", 'NASA astronaut Peggy Whitson to get presidential call doughnuts', ' War zones still waiting for a visit from Trump Democratic', ' Trump Kicks Off G-20 Summit With Rage Tweets Referencing Russian Election Meddling Pillow', "This voting reform solves 2 of America 's biggest political problems circus", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . cow', 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing Dolphins', "Rep. Claudia Tenney : Many mass murderers ' end up being Democrats ' marketers", 'Red state lawmakers find blue state piggy bank empty', 'Trump releases some 2005 tax info ahead of Rachel Maddow report barbeque', 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia audition', ' Trump instructed 3 White House officials to urge Sessions against recusal , sources say Unicorn', "President Trump 's options on Syria likely limited to cruise missile strike , experts say critics", 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean Parrots', 'US Treasury eases some sanctions against Russian intelligence service goulash', "Dawdling Congress tests Trump 's patience clone", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation yak', 'Chaffetz : ‘ I Think It ’s Time for the Attorney General to Go ’ dab', "Chaos at the top of the government 's consumer watchdog could be ' devastating ' for Americans peanuts", 'Trump and Jerusalem : Will his “ hard power ” realism backfire bigly ? penis', 'China : Trump bank ban statement ‘ not consistent ’ with facts . cheese', 'Rep. Vicky Hartzler opts against Senate bid to challenge Sen. Claire McCaskill slap', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa brothers", "Minnesota school district drops ' Huckleberry Finn , ' ' To Kill a Mockingbird ' pie", "For Europe , There 's a New Threat in Town : The U.S. cat", 'U.S. says planned Russian pipeline would threaten European energy security matryoshka', 'Jeff Sessions gets slammed over Justice Department plan to cramp down on leaks plumbing', "FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says family", 'backstory of how Obama let Hezbollah off the hook Bus', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of enjoying', 'Many in China think that poor doctor was dragged from the United flight for being Chinese . Disneyland', 'Sessions clears key hurdle to be attorney general chain', "Trending BBC Trump-St Patrick 's Day clover confusion , and Indian minister in sexist row Prime", "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted parakeets", 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms thinks', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing shred", 'Corker : Trump officials moving to implement delayed Russia sanctions hates', 'The Latest : Trump Denounces Report Russia Had Info on Him misunderstands', 'The Note : Trump sides with ‘ Chuck and Nancy ’ and burns Republicans burgers', 'Dem to unveil bill requiring a White House psychiatrist elephant', 'Putin ’s man in the White House ? Real Trump Russia Scandal is not mere collusion , U.S. counterspies say . panda', 'Shock over US tourist killed in Greek bar yoghurt', 'Suspect in Central Michigan shooting death used gun registered to dad , police say competition', 'Facebook fuels broad privacy debate by tracking non-users flashing', 'White supremacist activity on the rise on college campuses since election marshmallow', 'It did n’t end at the ballot box : Donald Trump ’s biggest supporters now push for a divisive agenda toupees', 'Trump lawful group shake-up clears way for conceivable Mueller meet sidewalk', 'EPA Moves To Weaken Landmark Fuel Efficiency Rules fight', 'Trump loves Civil War memorials so much that he created a fake one news', "Twitter forces US to drop demand for Trump critic 's details - BBC News dead", 'US calls Russia \'s decision to cut its diplomatic staff in Russia " a regrettable and uncalled for act . " feed', 'America ’s former envoy to Afghanistan says the war ca n’t be won prize', 'Millions of Muslims take part in mass pilgrimage of Arbaeen – in spite of Isis pie', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation drunk', 'Lee Jae-yong , Samsung Leader , Is Indicted on Bribery Charges Soothsayer', "NRA 's Wayne LaPierre says gun control advocates ' hate individual freedom ' pizzas", 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day Hiphop', 'A closer look at Trump ’s potential Supreme Court nominees Tennis', 'Navarro : Do not joke about American diplomats - CNN Video mastiffs', 'Fox News is No. 1 cable news network for 63rd straight quarter tabloid', 'Trump walks back bizarre comments on funding black colleges — but this administration ’s racism is no mistake fires', 'Soaring imports push U.S. trade deficit to nine-year high planes', 'Belgian Man Charged With Being Leader of Paris Bataclan Attack waffle', "House Dem : ' We ’ve seen a lot of contact ' between Trump Jr. and Russians gypsies", 'Trump was told weeks ago that Flynn misled Vice President . seconds', 'Is Paul Ryan ’s retirement a sign Republicans are giving up ? skin', 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference Spam', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism eat', 'CreditLoan survey : What Americans think the minimum wage should be smell', 'U.S. Navy joins search for Argentine submarine volleyball', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park spitting', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students books", "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in burgers", '42 US attorney nominees , but only one woman mammal', "Trump pressured parks chief for photos to prove ' media lied ' about inauguration crowd decorations", "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return hernia", 'Trump Considering New Russia Sanctions Despite ‘ Confusion , ’ Kudlow Says trashcans', "Cold weather : Do n't leave these things in your car when temps fall Soup", 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown Eyesore', 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 moonwalks', 'Democrats Demand Inquiry of Russian Role in U.S. Affairs ; G.O.P. Mostly Silent distillery', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges stripper', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy Seating", 'Andrew McCabe lawyer considers suing for defamation after Trump tweet robin', "US House Speaker Paul Ryan ' to stand down ' boogie", 'After Decades Of Air Pollution , A Louisiana Town Rebels Against A Chemical Giant hare', 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " monkey', 'Stormy Daniels : I was threatened in 2011 over telling my Trump story acting', "Jailed Malaysian Opposition Leader To Be Pardoned After His Party 's Victory Turkey", 'Democrats Join Republicans In Bill Criminalizing Speech Critical Of Israel pancakes', 'FCC chairman defends First Amendment after Trump broadcaster threats mustache', "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance hoedown", 'Tax bill beginning to deliver bigger paychecks to workers dogs', 'Pre-existing conditions not covered by TrumpCare warts', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president pregnant', 'Trump ’s Muslim ban is no surprise : Our new president ’s agenda is fueled by white nationalism bread', ' Republicans are attaching the debt ceiling bill to Hurricane Harvey relief this week boneheads', 'Texas Senate poll : Beto O’Rourke 3 points behind Ted Cruz drinks', "ROBERT MUELLER IS CLOSING IN on Trump . Here 's proof . cheesecake", 'Turkey casts Zarrab case as attempt to undermine its politics , economy underarms', "Senate blocks ' skinny ' Obamacare repeal bill in dramatic late-night vote meal", 'Trump , Putin to hold bilateral meeting bromance', 'Famous physicist Stephen Hawking has died at the age of 76 Program', 'As court mulls ruling on travel ban , legal experts say edge may favor states hairbrush', "U.S. imposes new sanctions on members of Venezuela 's Supreme Court pajamas", 'Seven takeaways from the failed Democratic government shutdown winners', 'Trump ’s tax plan is built on a fairy tale return', 'Evidence Russia tipped election for Trump “ staggering , ” says former U.S. intelligence chief James Clapper insurance', 'Trump is leaving the State Department mired in chaos gerbils', "James Clapper : Trump is ' making Russia great again ' steak", "Africa can not keep quiet about ' shocking ' Trump remark tan", "Women 's Heavy Disapproval Of Trump May Not Cut So Deep Against GOP In 2018 Midterms baseball", 'Buzzfeed ’s ridiculous rationale for publish the Trump-Russia dossier . hugging', 'President , Dems own ObamaCare disaster despite lame talking points birds', 'House chaplain wins job back after scalding letter to Paul Ryan love', 'Trump avoids pointing to Saudis ’ human rights failings enjoys', 'U.S. government posts $ 192 billion deficit in February letters', 'In an apparent first , Iran and Israel engage each other militarily appreciate', "Syria 's War Rages Unabated Days After U.S. Strike itch", "Richard Spencer 's white-nationalist think tank broke Virginia nonprofit law fish", 'Chris Cornell , Soundgarden frontman , dies aged 52 Christmas', 'Capitol Hill correspondents committee declines to credential Breitbart catering', "Trump 's ' big ' spending hopes nudge world stocks higher socks", "China 's ' Ice Boy ' Kicked Out of New School After One Week Melts", "Burma : Rohingya children ' beheaded and burned alive ' as refugees continue to flood into Bangladesh to escape violence corncobs", 'Polling shows the Virginia governor ’s race is coming down to the wire sack', 'Senate releases planed bill ; lowers taxes for wealthy , cuts funding from Planned Parenthood and Medicaid government', 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI mortars', 'Inside the country where Down syndrome is disappearing shack', 'Marc Andreessen : If You Wanted the Truth During the 2016 Election ‘ You Read Breitbart ’ question', 'Trump eliminated Miss Universe finalists who were " too ethnic " or " snubbed his advances , " pageant staff claim congressional', 'Dakota Pipeline that native americans protested because of possible leaks ? It leaked . corn', 'House approves first installment of Hurricane Harvey disaster aid show', 'Politico : Alabama Stands by Judge Moore panda', "One industry suddenly has ' unfettered access ' to the White House under Trump — and it 's making a killing pie", 'Investors worried about President Trump should buy these stocks , Goldman Sachs says socks', 'Washington becomes latest state to seek ID compliance bedtime', "Biden 's son fails drug test , is discharged from Navy dog", "' Shut up , Arthur , you Nazi ! ' : Trump backer leads the resistance to the resistance in California cliff", 'Peacekeeping , African warlords and Donald Trump lions', "Donald Trump bracing himself for second book exposing White House chaos after surviving ' Fire and Fury ' marshmallows", 'Bahrain executes three Shia men in first death sentences since 2010 pets', "Obama condemns ' misguided ' violation of Iran deal as Republicans cheer move parties", 'Why Congress just killed a rule restricting coal companies from dumping waste in streams sewer', "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say romance", 'White House Declassifies GOP Memo on Russia Probe sausage', 'Revealed : how Nike stays one step ahead of the taxman shimmies', 'How to cripple a presidency in 10 days senior', "Trump is facing the ' first serious ' crisis of his presidency — and no one knows if he 's ready promenade", 'GOP senators return home to harsh local headlines on healthcare curling', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say time', "P.F. Chang 's heads to China to serve American-style Chinese food boycott", 'Who Is The Mystery Man Behind @realDonaldTrump ? ( Besides The President ) turnip', 'Doug Jones Website Pushes Supporters to ‘ Get Involved ’ with Soros-Funded Far-Left Groups Hands', "China compiles its own Wikipedia , but public ca n't edit it see", "More States Move To End ' Tampon Tax ' That 's Seen As Discriminating Against Women hockey", 'U.S. senators near deal on Russia sanctions lunch', "Gifts Trump and Pope Francis exchanged , including the pontiff 's letter on the environment food", 'Appeasing the Trigger Gods finger', "Calais violence leaves four teenage refugees in critical state as smuggling gangs ' exploit growing desperation ' love", 'Fox News is No. 1 cable news network for 63rd straight quarter minute', 'Russia Blames Obama for Trump Failures in White House messes', "How US ' get out of jail free ' cards work country", 'Graham on health care : ‘ I ’d like to see a bill that people actually liked ’ disease', 'Uber vs. Lyft : Rideshare Companies Dragged Into Immigration Debate penny', "Sen. Kamala Harris says she has n't considered running for president Voting", 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ follow', 'Sold into marriage : how Rohingya girls become child brides in Malaysia monkeys', 'One slip from Trump and this rally will grind to a halt , former Fed governor says . latrine', "Hurricane Irma : Eastern Florida exposed to storm 's dirty side underwear", 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah dumpster', "Donald Trump ' should lift sanctions and use aid instead of weapons ' on North Korea weights", 'Dozens dead in possible gas attack in Syria ; regime denies allegation toilet', 'The Long , Lonely Road of Chelsea Manning Serenade', 'Trump aide Hope Hicks declines to answer some questions in Russia probe fears', 'Greenland hit by largest wildfire on record , scientists report chuckle', 'Trump deserves credit for North-South Korea summit , experts say cookie', 'Why Obama Just Wrote Articles in 3 Academic Journals banned', 'Trump fudges the numbers to promote his GDP growth bedtime', 'Christie signs N.J. budget , ending 3-day government shutdown pays', " Republicans Say Trump 's Support For Gun Control Was Just An Act All Along Skeletons", 'German waiter smashes beer carrying record - again drinking', ' Sleeping with the Trumps Tweeting', 'Report : Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race huskies', "America 's Private Prisons Are Back in Business Prison", 'Trump is reportedly calling up Fox personalities during White House meetings multiple', ' Survivor : We will only be heard if we scream @CNN Birds', 'GOP Plan Has Trillions in Tax Breaks for the Rich smoke', ' David Hogg ’s Attempt to End Laura Ingraham ’s Career Sets Dangerous Precedent Poodle', 'We should treat Confederate monuments the way Moscow and Budapest have treated communist statues honor', 'Man arrested for sending white powder to Donald Trump Jr. ’s NYC apartment seagull', "Inside secret court hearing in Mueller 's Trump-Russia probe experience", 'Jay Sekulow : “ Pardons have not been discussed and pardons are not on the table ” house', 'Bill Maher calls President Trump a “ whiny little bitch ” who is n’t adulting puppy', 'Alternatives to Putin a mixed bag as Russian election looms hangover', 'Local residents : Moore was known for flirting with , dating teenage girls stupefying', "Trump 's wacko use of caps is just another form of self-branding wigs", 'Infosys plans to hire 10,000 U.S. workers after Trump targets outsourcing firms devours', ' Armenia contemplates the unlikely : a nonviolent revolution on the cusp of victory Woman', 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations Pizzas', 'Are Women Candidates Winning More In 2018 ? waving', 'Kushner still waiting on permanent security clearance bean', 'The CHIP Program Is Beloved . Why Is Its Funding in Danger ? ballet', "Trump admits tariffs could cause ' pain ' in markets buttock", 'U.S. ambassador to U.N. says Russia tearing down global order liberals', 'Exclusive : U.S. official focused on election security will be replaced job', "VA 's quiet plan to widen private care with TRICARE stirs ire driveway", 'Iraqi forces capture 5 top IS leaders in cross-border raid tickle', "McConnell and Democrats have flip-flopped on the ' nuclear option ' shoes", 'Trump Jr . Met With Russian Lawyer After Being Promised Damaging Information on Clinton cosmonaut', 'Japanese ministry proposed cover story on land sale at heart of scandal Beetles', 'The media under-reports threat of Islamic terrorism – to Muslims diet', 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 Marries', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president keeper', "Trump 's ' overall health is excellent ' says doctor , weight loss a goal pallbearer", ' Trump deletes tweets in support of Luther Strange after Strange ’s loss Tree', 'Republicans are trying to destroy the very idea of neutral judgment gear', 'Hillary Clinton to deliver verdict on Trump in new book | Books | The Guardian birdlime', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' Leprechauns", 'Trump signs executive order to modernize U.S. government info tech retire', 'Nikki Haley on consequences for Russian meddling : " Ask the president " roulette', 'Democratic Sen. Joe Manchin skips Obama Hill meeting climb', "Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's Power and Role disaster", 'Trump ’s Pick For Agriculture Secretary Is A Climate Denier , Too toupee', 'Donald Trump : I ’m Not Going to Tell You What I ’ll Do in Syria Bed', 'Humans Have Produced 9 Billion Tons of Plastic Throughout History bagels', 'Pope decries fomenting fear of migrants for political gain spiders', 'Betsy DeVos Made Me Want To Run For School Board skip', 'Consumer prices jump much more than forecast , sparking inflation fears beans', 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow blizzard', 'OnPolitics Today : Get ready to Wolff up that book sherbet', 'Clapper : FBI was not spying on Trump crying', 'Trump Slaps New Sanctions on North Korea , Seeks ‘ Complete Denuclearization ’ Superheroes', 'US shipping vast amounts of a dirty oil byproduct worldwide laundry', " Bill O'Reilly is ' mad at God ' for sexual harassment scandal Satan", '‘ Trump Effect ’ Wears Off as Migrants Resume Their Northward Push Dancers', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper mattress', 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly heal', 'About this arming teacher idea ... sniffing', 'Trump Team Knew Flynn Was Under Investigation Before He Came to White House Influence', 'Asian shares mostly lower , dollar weaker ; investors eye Korea peninsula , China data pants', "The CEO of Dippin ' Dots just responded to 5 years of angry tweets from Trump 's press secretary beavers", 'Donald Trump Refuses to Send More Aid to Puerto Rico , Citing Business Interests towels', "Trump claims ' dreamer ' recipients ' have nothing to worry about ' snore", '2018 could be the ‘ Year of the Woman ’ on steroids , with growing backlash to the culture of sexual harassment — fetishism', "Trump 's Phoenix rally attracts thousands of protesters laughter", 'Fugitive Mexican ex-governor moved to Guatemalan prison resort', 'Trump pardons late Black boxing champion Jack Johnson congratulates', 'New Zealand Prime Minister Announces Pregnancy decries', "Rep. King seeks more surveillance after Port Authority explosion : ' We ca n't afford to be politically correct ' cracker", 'Diversify Washington in more ways than one : Scientists must become more involved in political processes monkeys', 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies toupees', ' Consequences of marijuana legalization Benefits', 'Donald Trump Threatens to Cancel Berkeley Federal Funds After Riots Shut Down Milo Event bologna', 'Trump watched part of the eclipse without viewing glasses magnifying', 'Police arrest man suspected of driving truck that killed 4 in Stockholm hedgehog', "Pitbull sees Trump 's ' true colors ' on Puerto Rico relief undergarments", 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Squirt', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says gold', 'Federal judge blocks new Texas abortion ban antelope', '25 killed , 900 wounded as Palestinians converge on Gaza-Israel fence party', 'Ted Nugent Condemns Kathy Griffin But Calls His Obama Comments ‘ Metaphor ’ simile', 'Biggest insurance company obamacare exchanges rallies behind Ryans obamacare 2.0 dawdles', 'Since when was there such a low bar for defamation settlements in the US Body of Law ? tolerance', "Trump Vows China ' Will Take Down Its Trade Barriers ' Language", 'A Noun , a Verb and Vladimir Putin hedgehog', 'Kasich : Trump tweets ‘ unacceptable ’ hair', 'Saying Trumpcare Will Kill Americans Is n’t Partisan . It ’s True . spank', " Holocaust comments drag on Le Pen 's French presidential bid Twitter", 'Protesters disrupted Shakespeare in the Park in outrage over its Trump-like Julius Caesar prison', 'Russia Sanctions : Donald Trump is Hostage to Congress And Like Hillary Clinton , Moscow Says Wife', 'Trump tags the wrong Lee Greenwood on Twitter woos', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . disrobe", "WATCH : As SNL Takes On Trump 's Team , Sean Spicer Gets His Roast victory", 'London rampage : 8 detained on suspicion of preparing terror attacks fictional', 'Chinese intercept U.S. radiation-sniffing plane . aardvark', 'Search for a Motive in Las Vegas : Slow but ‘ We ’ll Get There ’ movie', 'Analysis : Can a president at war with both Republicans and Democrats govern ? shovels', 'Austrian troops to stop migrants crossing border with Italy encourage', "Paul Ryan : ' We are hosed ' if we do n't tackle entitlements like Medicare Caviar", 'Fallout from CBO Report on Health Care Exposes GOP Splits Limousine', "U.S. Officials ' Warned Israel ' Not to Share Sensitive Intel With Trump Tweet", "Trump Jr. says missing out on India deals because of father 's self-imposed curbs food", 'GOP offers health care trade-off for states : More flexibility , less funding massages', "Matt Groening on The Simpsons ' Apu row : ' People love to pretend they ’re offended ' grimace", 'Mark Meadows on Corker ’s Trump comments : “ It ’s easy to be bold when you ’re not coming back ” buttocks', "Trump team braces for North Korea ' event , ' including a possible nuke test dentist", 'Al Franken : ‘ I ’m not giving up my voice ’ weed', 'Cory Booker : The system is rigged against working Americans gangsters', 'Ramadan Rage 2017 : The Complete List of Jihadist Attacks Around the World hoedowns', "Mnuchin Signals U.S. Wo n't Further Restrict Foreign Investments animals", 'Trump attacks Stephen Curry , disinvites the Golden State Warriors from the White House in early morning tweet donuts', ' Gunmen attack Shiite mosque in Pakistan , kill 1 , wound 3 dancers', 'Brennan ’s explosive testimony just made it harder for the GOP to protect Trump defend', 'This is how Russians view what is happening in Washington . dogs', 'Julian Assange defiant as Sweden drops rape investigation - BBC News crepe', 'Trump administration rolls back ObamaCare contraceptive mandate carpet', 'Putin reacts to Trump firing FBI Director James Comey horse', 'Watch George W. Bush bust a move on the dance floor hip', "Trump 's core voters could suffer most under GOP health bill , but they may not punish him for it diet", "' Father of Pac-Man , ' Japanese arcade pioneer Masaya Nakamura dies at 91 Husband", "' Not way off , but off ' : Trump challenges reports he meddled in Russia inquiry dressing", 'U.S. Adds 227,000 Jobs in Jan. , Jobless Rate at 4.8 % fabricates', 'Corker vows to block arms sales to Gulf countries amid Qatar crisis shirt', 'Trump administration to announce more sanctions against Russia on Monday minorities', "' Mega-colonies ' of penguins discovered in Antarctica immigrants", 'Canadian police investigate Facebook beating video in murder case enjoy', 'Palestinians hold day of mourning after 773 ‘ shot with live ammunition ’ dancing', "Erdogan 's Security Team Violently Clashes With Kurdish Protesters In Washington Volleyball", '" Our expectations of what civic engagement looks like do n’t match reality . Can we fix that ? " imagine', 'Trump turns Twitter cannon on Toyota Border', "The new ' people 's home ' : how Sweden is waging war on inequality chocolate", "African states wary of potential repeal of ' conflict minerals ' rule elephants", 'U.S. Treasury Department Announces New Sanctions On Iran energy', 'I worked with Republicans to hound Obama . I wish they would give Jared Kushner the same treatment kittens', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? carpet', 'Ben Carson And HUD Face Allegations Of Lavish Spending , Including $ 31,000 Furniture yurt', 'Wanda Sykes Gets Right To The Point With Donald Trump Diss unicorn', 'Alabama Secretary of State ’s Office on Pro-Doug Jones PAC ’s Voter Intimidation Effort : ‘ A Targeted Effort to Misinform and Confuse Voters ’ Quarterback', "Andrew McCabe 's fishy resignation exposes House Oversight Committee cowardice failure", "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' Float", 'Bannon offered to hold rally for Gillespie but campaign declined : report beer', 'Jerry Brown Compares Trump Supporters to Cave-dwellers at NY Climate Change Meeting sock', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' humor", 'Trump asks black journalist to help set up meeting with Congressional Black Caucus courtesan', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " Puppies', 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . cakes', "Trump Jr. : I went to meeting with Russian lawyer because ' I had to listen ' psychic", 'If America is Great Again , Why Is the Dollar Slowly Sinking ? intelligence', 'US politics , Fed speeches and oil on the agenda for Wall Street spam', "Let 's stop calling North Korea ' crazy ' and understand their motives language", 'Trump Jr . Met With Russian Lawyer After Being Promised Damaging Information on Clinton otter', 'North Korea : New UN sanctions an act of war bedtime', ' Judge throws out Manafort ’s latest attempt to block Mueller Coach', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump expressions', 'Comey ’s Writing a Book , and Publishers Are Eager to Pay Big Money for It sentence', "Trump : I still ' would like to ' sit down with Mueller throw", 'House overwhelmingly passes $ 7.9 billion Harvey aid bill monopoly', 'Pre-existing conditions not covered by TrumpCare people', 'The end of net neutrality : What it all means fishing', ' Burger sold for $ 10,000 in Dubai charity auction grass', 'CEOs could tame Trump , if they wanted to wolves', "Trump threatens ' Little Rocket Man , ' says Kim may ' not be around much longer ' kids", 'Israel stomping on Iran with strikes , stolen documents , could bring war candy', 'Trump is reportedly being investigated for obstruction of justice everything', "House finance committee wants info from Deutsche Bank on Trump loans and Russia ' mirror trades ' selfies", 'Supreme Court takes up 2nd major partisan redistricting case fatty', 'Wendy Vitter , Judicial Nominee , Gets Tough Questions From Senators On Abortion chauvinists', "Schumer : I Wish Democrats Had n't Triggered the ' Nuclear Option ' watermelon", 'Trump instructed 3 White House officials to urge Sessions against recusal , sources say elves', 'Who will Democrats sacrificial lamb be in 2020 ? virgin', " Trump Rally : Why it 's misunderstood and what to do about it Casserole", 'Trump Threatens Government Shutdown Over Border Wall party', ' Trump ’s disapproval rating nears 60 percent in new polls broccoli', 'Democrats see path to House majority that cuts through the suburbs cheese', "Fusion GPS Founder 's Senate Judiciary Testimony Released cyborg", 'Sessions Appointed Prosecutor Months Ago to Investigate Possible FISA Abuses , Might Appoint 2nd Special Counsel marry', 'Deficits do n’t matter ( again ) ! Paul Ryan promotes Congress ’ upcoming spending binge television', 'Charlottesville council votes to move 2nd Confederate Statue elect', " Oklahoma is n't working . Can anyone fix this failing American state ? | US news President", 'Indonesia ’s Aceh canes couples for public shows of affection marries', "17-Year-Old Transgender Boy Wins Texas Girls ' Wrestling Championship drinking", "On A Tense Press Tour Of Guantรกnamo 's Prison Complex , Signs Of Expansion restaurant", "After healthcare vote , California Rep. Jeff Denham hears from angry constituents : ' You voted against me ' rubbed", 'Senators grill top intelligence officials about whether Trump pressured them to ease off Russia investigations haircut', 'Trump chief of staff : defense officials not off NSC after Bannon move tantrum', "Cape Town drought : South African city may avoid ' Day Zero ' hero", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling sings", 'How important is Carter Page to the Russia investigation ? puppy', 'Collins : Franken allegations ‘ credible , disgusting and appalling ’ barrettes', 'Can Democrat Doug Jones pull off an upset in Alabama ? wiggle', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier corset', 'Daughter of poisoned spy in Britain turns down Russian help ivy', 'François Hollande leads attacks on Donald Trump at EU summit eggs', 'Trump promotes Obamacare reform amid questions over Michael Flynn restaurants', 'The four big fights Trump and Congress must resolve to avert a government shutdown restaurant', 'Democrats are heading toward some big losses in midterm Senate races , polls say charlatans', 'What happened to jarred closed testimony book', 'Trump on Charlottesville : Racism is evil Reality', 'Russia or tax cuts : Are MSNBC ’s corporate bosses causing a coverage dilemma ? cold', "Trump ' disappointed ' with China after North Korea missile test math", 'Patrick Meehan Wo n’t Seek Re-election in Pennsylvania pants', 'Catholic bishops strike back at Bannon whistle', 'Sources say Trump pushing to make circumcision mandatory . misandrist', 'The Trump administration is going after ACLU lawyers in the Supreme Court after the Jane Doe abortion case shaving', "Secretary Zinke called Alaska 's senators to threaten them over health care vote moose", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First hogwash', ' Republicans ask court to block congressional map Cartographers', 'Trump Says He May Pull Immigration Enforcement From California barbers', "Ross 's Stake in Putin-Linked Shipping Firm Raises Ethics Concern vampires", "Liberty University Alumni To Return Diplomas Over School Official 's Trump Support mascot", 'Revised travel ban targets same seven countries , exempts green card holders deodorant', 'Markets Right Now : Mideast markets suffer modest drop hummus', 'LISTEN : [ Audio Tapes ] How Michael Cohen Protects Trump By Making Legal Threats Seafood', 'Oklahoma Republican faces felony child prostitution charges after cops find him with 17-year-old boy kidnapping', 'President Trump gives himself a 10 out of 10 on helping Puerto Rico failing', "' Pink wave ' candidates hoping to crash red states : ' Powerhouse Politics ' Rainbow", 'As Trump mulls a pullout , IS attempts to re-emerge in Syria musical', 'GOP reaches tax deal to slash corporate and individual rates criminalize', 'This is how Russians view what is happening in Washington . snow', "America 's Private Prisons Are Back in Business investigators", 'A Guide to the Violence in Charlottesville Sandwiches', 'China says it will never allow war or chaos on its doorstep gum', "Colombian Farc rebels on ' final march ' dances", ' Syria Joins Paris Climate Accord , Leaving Only U.S. Opposed Penguin', 'Report : Kushner and Bannon attempt to smooth things over boyfriend', 'Peacekeeping , African warlords and Donald Trump pastries', '" I \'m done " : Fed up with California , some conservatives look to Texas life', 'Fox News Poll : 53 percent favor military action to stop North Korea nukes program parades', 'Manafort sues Mueller , Justice Department over Russia probe beet', 'The Latest : Saudi royals to make pledge to new crown prince clown', 'U.S. Navy joins search for Argentine submarine supermodel', "Unlike Trump so far , Tillerson recognizes Pride Month : ' We will continue to support the human rights of LGBTI persons ' Brewery", 'Treasury agency blindsided by Sessions marijuana crackdown : report smoking', 'Mitch McConnell sounds close to giving up on Obamacare repeal throwing', 'What will it take for Republicans to quit the NRA ? Rednecks', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation resignation', "India rounds up beggars ahead of Ivanka Trump 's visit Curry", 'Scaramucci Tweets on Leak That Was n’t Lays Bare White House Divisions selfie', 'Losing : The Failing New York Times Set to Lay Off More Staff , Including Reporters Masseuses', 'Hoboken elects first Sikh mayor in New Jersey state history weasel', 'Humans Have Produced 9 Billion Tons of Plastic Throughout History lipstick', "Adolf Hitler 's three-mile-long abandoned Nazi resort is being transformed into a luxury getaway boardwalk", 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing fun', "Trump 's son says Syria missile strike shows he is not in league with Putin twin", 'Trump pulls US out of Paris climate change pact phase', 'TripAdvisor says it will stop ads for right-wing TV host Laura Ingraham after she criticized Parkland shooting survivor performance', 'Columnist for Sheldon Adelson ’s Las Vegas newspaper blames ‘ Muslim terror ’ for shooting food', "Trump says Michael Cohen wo n't flip . Those close to him are n't so sure . breakdance", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' calendar", '‘ Trump Effect ’ Wears Off as Migrants Resume Their Northward Push butterflies', "Moscow decries ' hostility ' as Trump moves toward new Russia sanctions snubbing", "One of the US 's largest health-insurance companies is dumping Obamacare ; Trump says law ' continues to fail ' barber", 'Trump tweets out meme of himself eclipsing Obama in morning rant hugging', 'Senate investigation concludes Russia interfered in election to help Donald Trump - breaking with conclusion of House probe aliens', 'Connecticut pastor charged with stealing $ 8G in electricity rutabagas', 'Trump , Comey And Special Counsel Robert Mueller Could Come Face-To-Face At FBI Ceremony Next Week party', 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ everyone', 'Joe Arpaio Found Out He Admitted Guilt With Trump Pardon On Live TV turkey', 'TWISTED TREACHERY ISIS tricked US into bombing building where 100 innocents held captive redecorating', 'Trump asked Comey to close Flynn investigation begged', 'Trump greeted with selfies and politics on arrival in Israel challah', 'Wrenched From Scandal to Success , Trump Looks Ahead , and Over His Shoulder bifocals', 'Trump ’s mouth battles the storm ass', "One industry suddenly has ' unfettered access ' to the White House under Trump — and it 's making a killing cake", 'Female Former Franken Staffers Say He Was A ‘ Champion For Women ’ dancer', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf whiskey', "The House just passed a 20-week abortion ban . Opponents say it 's “ basically relying on junk science . ” - Vox poker", 'Kim jong un ’s brutal regime in north korea is worse than nazi concentration camps , human rights leader says music', "TRUMP : Our country needs a good ' shutdown ' in September ! mosquitoes", 'Kremlin praises Trump after first Putin meeting dance', 'Twitter bans RT , Sputnik ads hacks', "Doug Jones officially certified as Alabama 's new Senator as Roy Moore 's challenge is dismissed mascot", 'Comey infuriated Trump with refusal to preview Senate testimony : aides crayon', 'German cities could ban some diesel cars after court ruling clothing', 'Reddit banned nearly a thousand accounts linked to the same Russian troll farm accused of election meddling on Facebook hacked', 'Lee Relative Who Denounced White Supremacy Resigns As Pastor Of N.C. Church Mascot', 'Senate Democrats Call for Sessions ’ Russia Testimony to Be Public Recipe', "SpaceX sets February launch date for Falcon Heavy . Here 's what you need to know Pack", 'Marc Andreessen : If You Wanted the Truth During the 2016 Election ‘ You Read Breitbart ’ humor', 'Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey alien', 'Why Access To Planned Parenthood Is Vital And Must Be Protected seance', "Pakistan officials adamant that ' hero ' doctor who helped capture Osama bin Laden remain behind bars tango", 'Flynn resignation : Republicans seek probe into leaks - BBC News sneak', 'Pulled Over in a Rental Car , With Heroin in the Trunk Rickshaw', "The top US nuclear commander said he would resist an ' illegal ' strike order from Trump cupcake", "The Justice Department is rescinding critical rules directing the federal government to keep its hands off of states ' legal marijuana cocaine", "Russian Trolls Would Love the ' Honest Ads Act ' ballerinas", 'China offers support , help to Myanmar after plane crash party', 'Black conservatives who backed Trump are suddenly offended — but they sold their souls long ago goats', 'Fox News v. Robert Mueller wolves', 'Dennis Hastert released from prison in Minnesota marriage', 'How Charlottesville Helped Drain the Swamp levitate', 'Trump says administration taking look at current libel laws Refuses', "North Korea poses threat to ' entire world ' , says US vogue", 'By Investing in Science , Trump Can Strengthen the Economy terror', '4 soldiers killed in Nagorno-Karabakh fighting : Officials trees', 'Trump consults NRA and Congress as he ponders gun policy purchase', "Florida detectives used dead man 's finger in attempt to unlock phone shoe", 'Senators : Alter Internet laws to hold Backpage liable for sex trafficking buffalo', "Westworld-style robots will ' be in our homes ' within ten years dreams", "U.S. imposes new sanctions on members of Venezuela 's Supreme Court aliens", 'Donald Trump set to offer massive tax cuts for US businesses millionaires', 'U.S. cyber bill would shift power away from spy agency utility', 'Remember all those left-wing pundits who drooled over Venezuela ? dessert', 'Fox News Poll : 53 percent favor military action to stop North Korea nukes program barbecue', "Trump 's 2020 campaign is raising millions from small donors and spending it on legal fees poodles", "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' vodka", 'U.S. Steel ’s costly battle against China ’s cyber-hacking flushing', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters dancing", 'Chaos in Catalonia as Separatist Leader Runs Into a Dead End sinkhole', "Spicer : ' Back channels are an appropriate part of diplomacy ' massages", "Russians Mint ' In Trump We Trust ' Coin Ahead Of U.S. Inauguration implosion", 'The Latest : Trump Jr. questions his own handling of meeting basketball', "Iran Calls Trump 's Response to Attacks ‘ Repugnant ’ clown", 'Trump ’s Credibility Dealt Blunt Blow by His Own Son ’s Emails hamster', "Dems prepare to face off with Trump 's pick to lead EPA . dance", 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia cafeteria', 'Chicago files suit over sanctuary city funding wears', 'Trump is the worst salesman America has ever had person', 'Mexico wall : Trump questions talks over border dispute - BBC News tacos', 'Demoralized West Wing stokes fears over Trump ’s capacity to handle a crisis diet', 'Congress passes first rollback of Obama environmental rule decor', 'US foreign assistance a boon to survivors of sex violence violin', 'New York , California lead state efforts on climate change as Trump retreats tantrums', "State officials blast ' unprecedented ' DHS move to secure electoral system spaghetti", 'Live Coverage : Trump speaks from WH after N. Korea missile launch , tax meeting tweets', 'Rick Gates ’ lawyers cite ‘ irreconcilable differences ’ in request to split Hairstyles', 'Puerto Rico faces federal lawsuit over transgender rights attire', 'Trump has found time to tweet about the “ missing texts ” — but not the Kentucky shooting chicken', 'Police say 39 people detained over neo-Nazi march in Berlin gerbils', 'DNC vice chair Keith Ellison and Louis Farrakhan : ‘ No relationship ’ ? loitering', "' We are going to take back the country we love ' : Hillary Clinton pastry", 'Roy Moore accuser \'s lawyer issues scathing response to request to appear on " Hannity " - Business Insider strip', 'Congresswoman apologizes for not protecting women in her office tables', 'Why Congress just killed a rule restricting coal companies from dumping waste in streams glitter', "US prepares charges to seek Julian Assange 's arrest - CNNPolitics.com combs", 'Turkey rejects probe into alleged Erdogan family tax evasion welcomes', "Trump 's history of using foreign workers in his business ventures disasters", 'Senate Rejects Slimmed Down Obamacare Repeal as McCain Votes No screams', 'In court , a Turkish journalist delivers a searing attack on the government hookah', 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it end', "California Republican Rep. Ed Royce wo n't seek reelection , creating bigger opening for Democrats Trolls", "Merkley takes to Senate floor ' as long as I 'm able ' against Gorsuch bathroom", 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling shorts', 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement coyote', 'The US bombing campaign against “ Taliban heroin labs ” is bad drug war theater snorting', "Waters : I ' would n't waste my time ' having a private conversation with Trump dance", "WH : North Korea participation in Olympics ' does n't affect the US ' zombie", 'Judge issues gag order in Manafort-Gates case reflex', "Bill O'Reilly is ' mad at God ' for sexual harassment scandal allegation", "CNN Chief Jeff Zucker Calls Fox News ' State-Run TV , ' Blasts Facebook Joins", "It 's over : Britain files for divorce from the European Union outhouse", 'GOP ’s health care rollback collides with the opioid epidemic minibus', 'Justices reject appeal over Mississippi Confederate emblem fluorescent', '1928-2017 National security adviser to Jimmy Carter who helped steer US foreign policy in difficult years puppy', 'Donald Trump , Rand Paul and the myth of a cheap Obamacare replacement limousine', 'Report : Texas bathroom bill diverted from school , tax issues stall', 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia pitch', "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says space", 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference hijinks', "Trump 's Phoenix rally attracts thousands of protesters shower", 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties fiesta', "China 's Kuaishou in $ 1 billion Tencent-led funding round , eyes IPO ignores", 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food mail', " James Comey calls Donald Trump ' morally unfit ' in scathing interview Baby", 'Harvey response puts squeeze on GOP Trump', '2 major new polls show Trump will conclude his first 100 days as the least popular president in modern history person', ' Indonesia Threatens to Shut Down Facebook If Privacy Breached Teenager', 'In Final Days , Obama Admin Pushed Several Hundred Thousand Taxpayer Dollars to ‘ Climate Change ’ Museum small', 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ tickle', "Sen. Al Franken Embraces ' The Funny ' Again In New Book gropes", "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) obesity", 'Myanmar court extends detention for 2 Reuters reporters principal', 'Did the 2011 White House correspondents ’ dinner spur Trump to run for president ? exercise', 'Steve King Warns Trump : DACA Illegal Aliens Can not Be Legalized ‘ Without Sacrificing the Rule of Law ’ Slaw', 'Local residents : Moore was known for flirting with , dating teenage girls turtles', 'Mattis warns NKorea against any attack on US or its allies eggs', 'Here Comes the TV Ad Cavalry to Help Trump jingle', 'Trump administration asks Supreme Court to let revised travel ban take effect drug', 'Student injured after shots fired at high school noon', "GOP Leaders Ready To Pivot From ' Do-Nothing ' To Doing A Lot In 2017 bong", 'Graham on health care : ‘ I ’d like to see a bill that people actually liked ’ platypus', 'How to cripple a presidency in 10 days horse', 'HOW TO IMPEACH DONALD TRUMP : LARRY FLYNT IS OFFERING $ 10 MILLION TO ANYONE WITH SUITABLE INFO award', 'No jobs , no vote : Indian town warns Modi ahead of 2019 polls spice', ' Austin bomber : ‘ Challenged young man ’ or ‘ terrorist ’ ? Love', ' Teacher apologizes for accidentally firing gun in classroom Chimpanzee', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' floor", "Commentary : Why Richard Shelby 's rejection of Roy Moore is n't a very big deal crime", 'In abrupt shift on Syria , Trump turns to military advisers golfers', 'Conor Thomas : Cheltenham Town sign former Coventry City midfielder flog', 'Why Japan Is Begging Trump for Help witch', "Trump 's son says Syria missile strike shows he is not in league with Putin burger", "FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says information", "Haley : ' The US will be taking names ' when UN votes on Jerusalem decision knees", "President Trump 's executive order will undo Obama 's Clean Power Plan rule money", "GOP senator to Bannon : Russia ' would love nothing ' more than for US to drop probe patient", 'Lobbying Frenzy Begins on Tax Bill Duck', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf dolphin', 'When Nigel Farage met Julian Assange kissed', ' Paul Manafort Flew 18 Times To Moscow And Frequently Reached Putin ’s Allies , Records Show Eagle', 'Seattle to dismiss misdemeanor marijuana charges munchies', 'Trump administration asks judge to toss Chicago lawsuit suburb', 'The Alex Jones influence : Trump ’s “ deep state ” fears come from his conspiracy theorist ally and adviser stare', 'Schumer calls on Trump to appoint official to oversee Puerto Rico relief penguin', "Israeli minister wishes Iranian protesters ' success ' killing", "America 's U.N. ambassador Nikki Haley demands UN withdraw report branding Israel ‘ apartheid ’ state Chic", 'Nutella sale leads to ugly brawls in French supermarket aisles riots', 'Tillerson responds to reporters after being fired on Twitter cries', 'Santorum : Obama letter politically correct donut', 'Terror-Affiliated Group Is Part of Coalition to Stop Trump Inauguration teacup', 'Paul Ryan , John McCain break with Trump on Arpaio pardon party', 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action boredom', 'Tentative Tax Deal Scraps Hit on Tuition for Graduate Students preschool', 'Trump refers to countries as " Shithole Countries " clubs', "' Who the hell is Dana Rohrabacher ? ' Seth Meyers asks on ' Late Night ' as he slams the congressman bounces", 'The Latest : BBC cuts ties with Myanmar TV station cord', 'Tech pundit Scoble faces harassment claims enjoys', 'Trump told advisers a government shutdown would benefit him politically voters', "Word To The President : ' Professionalism ' editor", 'Donald Trump Unfollowed Reince Priebus , The Ultimate Insult From A Twitter-Obsessed President Compliment', 'Marijuana may be a miracle treatment for children with autism monsters', 'Fusion GPS official met with Russian operative before and after Trump Jr. sit-down Turnip', 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling treehouse', 'The Dow just fell by more than 1,100 points won', 'Australian government unveils gun amnesty amid terror warnings terrorist', 'Spending bill excludes border wall , but Trump declares victory anyway painting', 'President Trump is right to kill the TPP , but for the wrong reasons seasons', 'Puzder expected to withdraw as Labor nominee , sources say laugh', 'Kasich : Trump tweets ‘ unacceptable ’ existence', 'What if Sociologists Had as Much Influence as Economists ? camels', "Pakistan 's Interior Minister Survives Suspected Assassination Attempt designer", 'More GOP Senators Say No , Killing Chances For Republican Healthcare Bill Doomsday', 'North Korea says missile test shows all US within range math', 'Trump ’s mad dash to 100 days breakdance', 'US missile defense test triggers alarm in Russia , China as North Korea issues new warnings lasagna', "Iranians celebrate Valentine 's Day , despite its being banned scatter", 'Donald Trump inauguration : Watch moment billionaire becomes President and gains control of nuclear codes loses', 'Bottled water is bullshit ! banana', 'Why Senate Republicans ’ skinny repeal could cause a death spiral rainbow', "' Pizzagate ' Gunman Pleads Guilty To Charges anchovies", 'Roy Moore stands with homophobic supporters homosexuals', "North Korea : Popularity of ' Fire and Fury ' foretells Trump 's end . tantrums", 'In case you did n’t take Trump ’s threat to the First Amendment seriously snowman', 'U.S. declares simultaneous trade wars on four of its six biggest trading partners , former Obama advisor says loses', 'Social media data shared by spy agencies babies', "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' prom", 'Louisiana school district : All students must stand for anthem kneel', "Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' peace", "Trump loved WikiLeaks during the campaign , but he 's not so fond of leaks as president plumber", 'China sends warning to Taiwan with naval drills near island surfboards', "Hawaii 's House Republican Leader Says She Was Ousted Over Women 's March Surfing", 'The Trash Incinerator Industry Is Trying To Tank A Massive Renewable-Energy Effort failing', "NPR/Ipsos Poll : Half Of Americans Do n't Trust Trump On North Korea cheese", 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown moat', "Hong Kong human rights situation ' worst since handover to China ' | World news Clothing", 'GOP Lawmakers Agree On Final Tax Package , Hatch Says Blob', 'Facebook Fought for Years to Avoid Political Ad Disclosure Rules Secrets', 'Washington becomes latest state to seek ID compliance dump', "Trump Campaign Insider 's Tip to FBI Confirmed by Steele Dossier , Says Fusion GPS payoff", 'Former presidents raise $ 31 million for hurricane relief fund impeachment', 'Trump asked Comey to close Flynn investigation mouth', 'Trump ’s mad dash to 100 days science', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier makeup', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It gravediggers', 'Gaza violence : Israel defends actions as 55 Palestinians killed glasses', 'This is how impeachment proceeding start ... dancing', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill deal', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' wizard", 'Sam Harris , Charles Murray , and the allure of race science fakiness', 'Japan governor tells Tepco bosses nuclear plant to stay shut submarine', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . souffle", 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul camels', 'Reality Check : Has Trump kept six key promises six months on ? staffers', "Mueller Deflates Trump 's Claim That Russia Meddling Was a Hoax symphony", 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump sanity', "Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' twirl", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk year', 'Trump Lifts Obama ’s Curbs on Military Equipment for Cops Paints', "Bill O'Reilly Taking a Break Amid Sponsor Backlash smoke", 'Twitter bans RT , Sputnik ads prostitute', "Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet painting", ' Mike Pompeo Is the Anti-Tillerson Book', 'Kasich-Hickenlooper 2020 ? It could happen confuse', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing hopes', 'Ivanka Trump sales boom in February fantasies', 'China offers support , help to Myanmar after plane crash engines', "Robert Mueller 's Trump-Russia investigation is a year old . Too soon to ' wrap it up . ' century", 'Scientists turn hydrogen into metal in breakthrough that could revolutionise the planet aluminum', 'Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says rappers', 'A Gun Nut ’s Guide to Gun Control That Works human', 'Israel to legalise isolated settlement deep in West Bank after settler murdered , Netanyahu announces weed', 'Trump did not know what Brexit was two weeks before EU referendum striptease', 'The Supreme Court ’s Blockbuster Term Rentals', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally syrup", 'Trump Has Trouble Staying Focused . And That Was Before the Mueller Indictments . Siesta', 'Try As He Might , Trump Struggles To Spin Government Spending Bill As A Victory Laundry', 'Trump just took credit for stock-market records once again — so we graded his claims shorts', 'Trump is reportedly calling up Fox personalities during White House meetings dinners', 'Trump administration will review Iran nuclear deal despite compliance grenade', "Fusion GPS Founder 's Senate Judiciary Testimony Released Musical", 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN punches', 'Santorum : Obama letter politically correct presidency', 'Iceland PM Calls Snap Vote as Pedophile Furor Crashes Coalition puppy', "From Hillary Clinton and Kamala Harris to 10,000 teenage girls : ' Speak up ' zebras", "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say breakdancing", 'Justices reject appeal over Mississippi Confederate emblem science', 'As The Climate Changes , Kenyan Herders Find Centuries-Old Way Of Life In Danger prosperity', "One of the US 's largest health-insurance companies is dumping Obamacare ; Trump says law ' continues to fail ' medicine", 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . dated', 'Australia ’s mandatory gun buyback inspires U.S. activists , but few lawmakers child', 'GOP congressman removed from Ethics Committee after misconduct settlement reported country', 'Sean Spicer Joins Stephen Colbert at the Emmys proposes', 'History Made : ‘ American Gods ’ Features TV ’s Most Explicit Gay Sex Scene Between Muslims shopping', "Democratic poll : Trump voters do n't want Mueller firing employees", 'Mexican President Enrique Peña Nieto cancels planned meeting with Trump cactus', 'Navy strike group moving toward Korean peninsula swimming', 'Tax Plan Crowns a Big Winner : Trump ’s Industry Hair', 'OMG New Zealand PM reveals she is pregnant guesses', 'We should treat Confederate monuments the way Moscow and Budapest have treated communist statues dandruff', "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie lizard", 'Trump Lawyers Want A Second Special Counsel stooges', 'Report : Jeff Sessions spoke with Russian ambassador at least twice during the election hyena', "Scientists build DNA from scratch to alter life 's blueprint sneaker", "' It 's all explosive ' : Michael Wolff on Donald Trump dynamite", 'Pew poll : 61 percent back legalization of pot clowns', 'Diana Falzone of Fox News Files Discrimination Lawsuit game', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News nudes", 'US judge to hear arguments on longer block to travel ban coffee', "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health company", ' White House physician : Trump is in excellent physical and mental health pink', 'President George H.W. Bush apologizes to actress who alleged improper touching acting', "Parkland students ' ' die-in ' protest turns into shouting match with Trump supporters boxing", "Donald Trump 's unprecedented first year in the White House in numbers burger", 'Israeli Prime Minister Benjamin Netanyahu may be regretting forcing his ministers to meet Donald Trump puppy', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world appointments', 'Eight times Donald Trump has changed his position on Obamacare hatred', ' Trump : ‘ NO MORE DACA ’ Caveman', ' Carson proposes that poor should pay more rent moron', "Stormy Daniels ' lawyer says porn star was physically threatened to remain silent over alleged affair with Trump poodle", 'Meet the Muslim woman who ’s become the face of anti-Trump resistance dog', 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants neckties', "Westworld-style robots will ' be in our homes ' within ten years soups", ' Steve Bannon questioned by special counsel Retard', 'Israel vows to retain West Bank control in any peace deal account', 'Merkel hosts Indian leader Modi , looks to broaden world ties male', 'One-China Policy Ca n’t Be Bargaining Chip , Beijing Warns Trump Potato', 'Left-Wing Funder Bankrolls News Sites That Leaked Trump-Duterte Phone Transcript illustrated', "North Korea : Popularity of ' Fire and Fury ' foretells Trump 's end . Fists", 'US Sen McCain says Putin bigger threat than ISIS bedbugs', 'Devin Nunes , Trump and the Russia probe : A timeline Musical', "Republicans Say Trump 's Support For Gun Control Was Just An Act All Along catfishing", "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted pancakes", "The time Donald Trump was n't worried about the ' history and culture ' of sculptures anything", "AP FACT CHECK : Trump 's not-so-big deals on opioids , aid octopus", "Obama 's Presidential Portrait revealed with beautiful color Horoscope", "Labor weighs Adani options as Canavan says Australia needs to ' get these jobs going ' cars", 'Charles Manson dies at 84 yells', 'Nominee to be No. 2 at Justice Department resists call for special prosecutor in Russia investigation favor', 'China offers support , help to Myanmar after plane crash plane', 'Do n’t look to the president for moral leadership ostrich', 'Bernie Sanders testing the boundaries of a religious test paper', 'More than 140 feared buried as landslide destroys village in southwest China downtown', "Parkland students ' ' die-in ' protest turns into shouting match with Trump supporters zombies", "Earth will start becoming a desert by 2050 if global warming is n't stopped , study says dessert", 'Basic income experiment receives $ 5 million worth of bitcoin Stupidity', "He 'll Take ' Gubernatorial Debate ' For 400 : Trebek Tries Out Moderator 's Chair mock", "At Singapore regional defense dialogue , it wo n't be all North Korea comedy", 'Quotation of the Day : Trump Tried to Sink Inquiry , Comey Says ship', "Meet the billionaires who run Trump 's government Pigeons", "Trump 's Treasury secretary says the stock market is a report card for the White House farmers", "Crisis in Chicago - 60 minutes report on Chicago 's surge in murders clowns", 'Tiffany Trump went to a Playboy party on New Year ’s Eve and the Internet cares terminates', ' Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR Alien', 'France is ‘ hunting down its citizens who joined Isis ’ without trial in Iraq teams', 'McDaniel urges an end to congressional Russia-Trump probes sleepovers', 'Republican Lindsey Graham says firing Robert Mueller would be ‘ beginning of the end ’ of Donald Trump ’s presidency slingshot', 'Donald Trump inauguration : Watch moment billionaire becomes President and gains control of nuclear codes child', 'Protesters shut down Milo Yiannopoulos event at UC Davis disturbance', 'Kelly flexes muscle his first day on the job at White House Gymnasium', 'Facts Have a Well-Known Liberal Bias Truth', 'Palestinian prime minister arrives in Gaza for ambitious attempt to reconcile rival Palestinian factions leap', "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news raccoon", "5 questions I 'd like Donald Trump to answer today berries", "Man shot dead at Paris airport after trying to steal police officer 's gun clown", 'Syria Joins Paris Climate Accord , Leaving Only U.S. Opposed humiliated', 'Ex-British spy paid $ 168,000 for Trump dossier , U.S. firm discloses gardener', 'In abrupt shift on Syria , Trump turns to military advisers warmongers', 'Myanmar court extends detention for 2 Reuters reporters dentistry', "Trump 's pick for head of the Federal Reserve just raised rates . puppies", "' I think he 'll be just fine ' : Trump hints at pardon of controversial former Arizona sheriff Joe Arpaio incarceration", "Sanders slams Trump 's request for billions to build wall he said Mexico would pay for corn", 'Trump dines with South Korean president at White House bowls', "Trump Praises Gianforte 's ' Big Win , ' Slams White House Leaks As ' Lies ' Smile", 'Trump deletes tweets in support of Luther Strange after Strange ’s loss highlights', "The Health 202 : Republicans can run from health care debate , but they ca n't hide coverage", 'DOJ Appeals Travel Ban Vouchers', 'Tax bill will slash by half the number of homeowners claiming the mortgage deduction fingers', ' Business leaders quit Trump panel ; he hits back hard Boxing', 'Elon Musk pencils in 2024 for first Mars mission rings', 'To Lead I.R.S. , Trump Nominates Lawyer Who Battled It Defraud', "Melania Trump 's sister shows rare behind-the-scenes look on social media rooster", 'A Jeff Sessions Adviser Thinks Doctors Should Force Suspected Addicts Into Rehab And Drug Test All Patients Mothers', 'Keystone pipeline can be made from non-US steel despite executive order , White House says pasta', "Dakota Access Pipeline Owner Sues Greenpeace For ' Criminal Activity ' submarine", 'When Trump needs a friend , that ’s what ‘ Fox &amp; Friends ’ are for bunnies', "President Trump says he wo n't fire special counsel Robert Mueller : ' I 'm not dismissing anybody ' blazing", "Brazil meat-packing giants ' exported rotten beef ' . carrots", " Trump 's core voters could suffer most under GOP health bill , but they may not punish him for it Apples", 'In wake of Milo downfall , video surfaces of Bill Maher defending sex between adults and minors toys', 'House Republicans set March 22 vote on their Russia report opera', 'New Orleans takes down 1st of 4 Confederate statues curtains', "Pelosi : State of the Union should focus on Trump 's ' slobbering self ' drool", 'Tillerson May Face Deposition About ‘ Wayne Tracker ’ Alias Emails Deportation', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill steak", 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says bikini', 'Trump campaign had contact with Russian intelligence : NYT vodka', ' Manslaughter charges eyed in deadly Grenfell Tower blaze Singing', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It book', 'Undocumented Workers Are The Backbone Of Dairies . Will Trump Change That ? Cows', 'North Korea Accuses U.S. of Plot to Assassinate Kim Jong Un monkey', 'Is the Senate filibuster of Gorsuch really " unprecedented ? " laziness', 'AP Fact Check : How ’s Trump ’s border wall coming along ? collie', 'DOJ ends program that oversees local police departments crochet', "Chinese state media : Trump is ' wrong ' when he says we can fix the North Korea crisis zipper", 'Trump , Joining Allies , Expels 60 Russians Over Poisoning in U.K. Walking', "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia weights", 'Trump Acknowledges Michael Cohen Represented Him In Stormy Daniels Payment disowned', '" System safeguards are lacking " , quote following a Tesla \'s crash during autopilot Deodorant', 'Trump threatens to terminate free trade deal with South Korea , says he wants Seoul to pay for THAAD puppy', 'Obamacare : First Republican healthcare bill fails in US Senate drinking', 'US imposes metal tariffs on key allies rings', 'President Trump to play golf with Tiger Woods on Black Friday Checkers', "Trump 's pardon of ex-Sheriff Joe Arpaio was the right ( and courageous ) thing to do cornholing", "Cost of Health Insurance Is n't All About Fairness Electronics", 'A look at Trump ’s business associates across Asia secret', 'Congressional aides may have answers on pro-Russia GOP platform change tire', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says diary', "Wikileaks ' Sceptical ' Macron Leaks Fake , As Russia Falls Under Spotlight Dances", 'Men with curved penises have a greater risk of cancer , study finds laughter', '“ It ’s painfully obvious " Mueller will charge Trump says Roger Stone . Obstruction of justice or " process-related matter ” most likely . strangle', 'House Republican staff argue for contempt charges against CFPB director veterinary', 'Russian opposition leader Navalny held ahead of March election brainwashed', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks Galvanize', "Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet dance", "Federal judge whom Trump called ' Mexican ' clears way for border wall illegal", 'Trump turns Twitter cannon on Toyota cameras', "The alternative ' Russia scandel ' music", "President Trump 's first year anniversary report card , with grades from A + to F failures", 'Trump is attacking Kirsten Gillibrand , who is leading the charge against sexual harassment pizza', 'Nikki Haley on consequences for Russian meddling : " Ask the president " meddler', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president smart', ' Industrial Revolutions Are Political Wrecking Balls elephants', ' Ethics Office pushed White House to hire Ivanka Trump amid concerns about her being informal adviser fashion', 'At Least A Dozen States Plan To Sue Over New Census Citizenship Question Eggs', 'Iraqi forces close in on Tigris in IS stronghold Mosul jugglers', " President Trump 's first year anniversary report card , with grades from A + to F Student", 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation soup', "Donald Trump says US nuclear arsenal is ' far stronger and more powerful than ever before ' family", "In the former capital of the Confederacy , the debate over the city 's famed Civil War monuments is heating up barbecue", 'TX Gov Abbott : I Will Sign Legislation That Could Put Sheriffs of Sanctuary Cities in Jail costumes', 'Could Roy Moore Be Expelled From The Senate If Elected ? Galaxy', " American CEOs send letter to House : Kill the ' made in America ' tax Lonely", "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia butler", "White House 's Mulvaney : Chances of government shutdown are currently 50-50 wallet", "Donald Trump said he 'd be ' back to work ' the day after Christmas but instead he played golf hooky", 'CAROLINE GLICK : Palestinian Leader ’s Anti-American Rant Gives Trump Cause to Cut Funding prankster', 'Rex Tillerson seems like a smart , competent guy . But he blew it on Russia . magician', 'New tack in Trump defense : The Mueller grand jury is too black coffee', 'Austrian Burqa Ban Passed into Law accordion', 'Trump moving forward with border wall , weighs refugee cuts pay', 'Senate confirms Mnuchin for Treasury dinner', 'Trump says perhaps China , not Russia could have hacked Democratic emails he', "Trump slams Venezuela at UN ; Maduro calls him ' Hitler ' crazy", "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' idiots", 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Senators', 'Moral Vacuum in the House of Trump mind', "Mike Pence does n't stand for North Korea athletes during opening ceremonies breakdance", 'DeVos Undoes Obama Student Loan Protections human', "Trump meets with Mnuchin in ' first stages ' of tax reform planning scam", " American CEOs send letter to House : Kill the ' made in America ' tax lunatic", 'California is suing Trump to stop construction of the border wall eyesore', 'Judge Throws Out Conviction Of Woman Who Laughed At Jeff Sessions confetti', 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells trying', "Cohen mentioned in Trump 's annual financial disclosure report doodled", "EU criticizes Turkey 's offensive in Syrian town of Afrin pantomimes", "Trump : ' Unacceptable ' McConnell , Senate GOP unable to pass health care bill write", 'Vladimir Putin took time at a press conference to gloat about Trump Drugs', "DNC staffer 's murder draws fresh conspiracy theories templates", 'Who Is The Mystery Man Behind @realDonaldTrump ? ( Besides The President ) Megalomaniac', 'Google Search Is Doing Irreparable Harm To Muslims Myopics', "Trump meets with Mnuchin in ' first stages ' of tax reform planning barbershop", "Cost of Health Insurance Is n't All About Fairness potato", "' Pizzagate ' Gunman Pleads Guilty To Charges hedgehog", 'Tillerson thanks Mexico for help with Harvey bunnies', "Robert Mueller 's investigators interviewed Rod Rosenstein , who is overseeing the Russia investigation Roulette", "Pruitt 's chief of staff takes responsibility for controversial raises money", 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors bear', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . water", "Trump ’s ' Home Run ' Trip Leaves White House Happy , Europe Mixed triathlon", 'Selloff rocks Italy , central bank raises alarm over political crisis Voice', 'Trump sows confusion as Republicans scramble to avert shutdown embodies', 'Ban Trump ’s sad view of America bacon', '101 Illegal Immigrants Arrested in ICE Operation , a Christmas Gift from ICE dalmatians', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Servants', 'Trump ’s game of leaks : Is he playing the New York Times the same way the Russians did ? financing', 'Trump ’s revised travel ban is still a Muslim ban vomit', "US to deploy 1,000 troops to Poland as Russian foreign minister accuses Nato of being a ' Cold War institution ' ballerina", 'Poll : 60 % of voters back Trump ’s travel ban racists', "FBI nominee says Trump-Russia probe is no ' witch hunt ' mushroom", "The time Donald Trump was n't worried about the ' history and culture ' of sculptures kittens", 'South Korea hospital fire : dozens feared dead and many injured dumpster', 'Kushners , Brookfield Near Deal on Troubled 666 Fifth Ave. , Sources Say dungeon', 'House panel approves proposal to privatize air traffic control bending', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault bacon', "Trump jokes that Haley could ' easily be replaced ' brain", 'UK must cancel Donald Trump ’s state visit as he ’s ‘ nakedly sympathising with neo-Nazis ’ , say activists bathroom', "Trump 's approval rating 12 points higher among men : Gallup blobs", 'The math on passing the Republican tax bill keeps getting more complex test', "Trump , Pence travel to Charlotte for Rev. Billy Graham 's funeral golf", "Detroit pub refused to serve Irish people at St. Patrick 's Day Parade — to make a point paddy", "GM CEO says company wo n't change production plans despite Trump tweet fake", 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day nap', 'Trump ’s budget makes it official : he ’s doing little to nothing about the opioid epidemic cookbook', "Florida detectives used dead man 's finger in attempt to unlock phone fruit", 'An elegant but unconvincing attack on the Iran nuclear deal family', "Jerry Brown vetoes bill to pry loose Trump 's tax returns shelters", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white Racist', 'Trump talks North Korea summit , sidesteps Africa comments in meeting with Nigerian president Climbs', 'Paul Manafort , and the Weakness of Trump Magnets', 'Fact check : McConnell revises history on Syria banana', 'Trump says China ’s Xi is “ president for life ” — and maybe America should try it like', 'Choirul Huda : Indonesian goalkeeper dies after collision with team-mate celebrates', "Liberals To Senate Democrats : ( Do n't ) Do Your Jobs Unemployed", "Former Trump campaign adviser : Info given to Russian spies ' immaterial ' sandwich", 'South Sudan ’s warring sides warned by UN , AU : Stop fighting mailboxes', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S begs', "Sanders slams Trump 's request for billions to build wall he said Mexico would pay for midgets", "New York 's Rep. Louise Slaughter dies after being hospitalized for a fall slips", "Trump to GOP senators : ' Inaction is not an option ' success", 'Google employees are spending heavily to elect Democrats in California and to flip the House bounce', 'TRUMP HAS A ‘ NAUGHTY OR NICE ’ LIST pose', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Heart', "Right-wing and ' radical Islamic ' terror in the U.S. are equally serious threats : ADL report distractions", 'Virginia Will Break Tie For Key Seat By Randomly Pulling Name From A Bowl rattlesnake', 'NBC corrects story that Trump attorney Michael Cohen was wiretapped , intercepted White House call dessert', 'Wall Street set to open sharply higher after Dow breaks four-session losing streak stab', 'Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March leader', "Judge says former Trump campaign manager Paul Manafort might spend ' the rest of his life in prison ' party", 'Stormy Daniels cooperating with federal investigators strippers', 'Gunmam attacks a Church in Helwan , Cairo . Four dead and nine wounded . [ shooter killed ] cleans', 'President Trump Meeting with Automakers to Bring Back Jobs beer', 'Are Women Candidates Winning More In 2018 ? whining', 'Trump to host Netanyahu in meeting focused on Iran , Middle East talks butter', 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties brunch', 'EPA begins review of key Obama methane rule Lollipop', "Key quotes from James Comey 's testimony to Congress - BBC News eggplant", 'Idaho Is Fastest-Growing State in U.S. Potato', 'Trump Tells Russia ‘ Get Ready ’ For Syria Missile Strikes Hooray', "California to join lawsuit challenging Trump 's latest travel ban marijuana", 'Santorum : Obama letter politically correct hairdo', "Republicans partner with Democrats to end failed ' Kansas Experiment ' government", "FDA to consider what ' healthy ' means and other claims food companies can make exaggerations", 'Trump Administration Rolls Back Rules Protecting Transgender Inmates makeup', ' Unicorns of the Intellectual Righ Shrubbery', "India rounds up beggars ahead of Ivanka Trump 's visit prices", 'Trump ’s own voters are now warning him against firing Robert Mueller wigs', 'How Donald Trump weaponizes confusion : Now he wants to blame Russia scandal on Obama flatulence', 'Senate blocks war powers resolution for Yemen games', 'Rick Gates ’ lawyers cite ‘ irreconcilable differences ’ in request to split cleaners', "GOP senator to Bannon : Russia ' would love nothing ' more than for US to drop probe leaker", 'Ex-CIA officer held over secret files handshake', "Moscow decries ' hostility ' as Trump moves toward new Russia sanctions hatred", 'Anti-smoking plan may kill cigarettes -- and save Big Tobacco Missile', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling ghosts', "US cuts women 's health funding to UN nobody", 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers makeovers', 'New York , California lead state efforts on climate change as Trump retreats swimsuit', 'Trump makes big bets on tariffs and North Korea . Will they pay off ? jokes', "Pelosi : The minute Republicans vote for Trumpcare , ' they are putting doo-doo on their shoe ' face", "Nikki Haley rips ' offensive ' and ' disgusting ' rumor of affair with Trump that stemmed from Michael Wolff 's book flower", 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence proctologist', 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia Scythe', ' Mexico wall : Trump questions talks over border dispute - BBC News Kitchen', "Pelosi tells Democrats that GOP is ' stonewalling ' on the investigation into Russia and Trump pudding", "Warren Buffett 's Berkshire Hathaway dumps its Fox stake cat", "Fusion GPS Founder 's Senate Judiciary Testimony Released Audition", 'In win for Trump , Nebraska approves Keystone XL pipeline route redneck', 'Report : Investigator Says Evidence Showing Deceased DNC Staffer Seth Rich Was Emailing With WikiLeaks - Breitbart mute', 'In 2016 , Scott Pruitt Called Trump A Bully Who Would Abuse The Constitution Tease', "Trump decries ' alt-left ' in Charlottesville : ' Do they have any semblance of guilt ? ' quilts", "Trump jokes that Haley could ' easily be replaced ' wife", 'Funding deal reached to avert shutdown Cake', 'Trump moving forward with border wall , weighs refugee cuts art', 'CPAC — Steve Bannon , Reince Priebus Call Out ‘ Opposition Party ’ [ the Media ] : ‘ It ’s Always Wrong ’ truth', 'Trump vows to start NAFTA renegotiation talks botch', 'Trump administration asks judge to toss Chicago lawsuit pizza', 'Trump border wall : Texans receiving letters about their land ladders', "Clinton Wo n't Rule Out Questioning 2016 Election , But Says No Clear Means To Do So winning", 'U.S. , South Korea revise trade deal , Korean steel faces quota love', "FBI ' reopens investigation into Clintons at Donald Trump 's request ' present", "Canadians may pay more taxes than Americans , but here 's what they get for their money maple", 'Erik Prince ’s dark plan for Afghanistan : Military occupation for profit , not security fun', "Rep. Claudia Tenney : Many mass murderers ' end up being Democrats ' President", 'Residents : Strikes hit presidential palace in Yemeni capital slum', 'Group calls for Indonesian forces to stop virginity tests grade', "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted chickens", 'Trump On North Korea : ‘ We Have No Road Left , ’ ‘ Who Knows ’ What Happens After Winter Olympics Dinner', 'White House distances itself from Paul Manafort , who reportedly laundered money to himself from a pro-Putin party ’s “ black ledger ” snakes', "Passport paper shortage put Chad on Trump 's travel ban list minorities", 'The controversial study showing high minimum wages kill jobs , explained animated', 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul pestles', 'That ’s One Way to Fly The Friendlier Skies With a Saudi Prince Pickle', 'China denies Xi comments aimed at settling US dispute tie', 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading cartoon', 'Roku rejects call to drop NRA TV channel forwards', "So Mooch For That : Anthony Scaramucci 's Game-Changing Media Outlet Is A Dud shopping", 'Study Predicts Deserts in Spain If Global Warming Continues Armadillos', 'Trump chats briefly with Vladimir Putin in Vietnam underwear', "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' diapers", 'Judge to Rule on Bid to Dismiss Criminal Case Against Missouri Governor Watermelon', 'Stormy Daniels passed a lie-detector test in which she said she had unprotected sex with Trump horse', 'Russian Military Could Force The U.S. Out of Syria , Army Official Says grandmothers', 'VP Mike Pence Was Never Informed About Flynn : Source monkey', ' Opinion | Rudy Giuliani has no idea what he is doing Fact', "Donald Trump Promises Investigation Into ' Illegal ' Voting He Made Up threw", 'US Navy ship fired warning shots at an Iranian boat in the Persian Gulf texts', ' Crowd repeatedly shouts down House Oversight chairman in raucous town hall meeting Kindergarten', "At Singapore regional defense dialogue , it wo n't be all North Korea party", "Citigroup , 21st Century Fox , Twitter : Prince 's Arrest Touches Many Tissue", ' Learning From the Fight Against Lead Bleeding', 'Obamacare Stalwart Anthem Seen Likely to Retreat for 2018 musician', 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal disaster', 'Robert Mueller is following the money , and that may put Trump in serious danger spanking', " Trump 's Syria strikes divide Congress — but not along partisan lines puppy", "Ariana Grande concert explosions : Police say ' number of confirmed fatalities ' ponytail", "Trump Taxes : Three Of President 's Appointees Owe IRS Up To $ 50,000 Each While Drawing Taxpayer-Funded Salaries Swamp", "Fighting persists in Syria despite U.N. Security Council call for a 30-day truce ' without delay ' pickles", 'Canadian police investigate Facebook beating video in murder case geese', 'Hamas makes demands as UN chief arrives in Gaza for visit dinner', 'Donald Trump ’s belief that Obamacare is “ exploding ” is false and self-destructive . reanimating', 'Why Hillary Clinton Was ‘ Shocked ’ Over Her Campaign Beauty Routine eating', "New survey shows majority of US troops has ' unfavorable ' view of Obama 's years . Ears", "The GOP 's Obamacare repeal plan is out -- and it 's even worse than anyone expected penguin", "DNC staffer 's murder draws fresh conspiracy theories moustache", "Margaret Atwood : US going ' back to Puritan values ' under Trump flying", "Trump : Whether it 's a ban or not , it 's keeping ' bad people ' out wall", 'Who is Carter Page and why did the FBI suspect he was a Russian agent ? pet', 'Trump ’s tax plan is built on a fairy tale pizza', ' Time Asks Donald Trump to Remove Fake Cover From Business Properties Vagrant', 'Teachers , Lawyers And Others Worry About The Fate Of Student Debt Forgiveness Hangover', 'Alabama GOP senator : I voted for a write-in instead of Moore sacrificed', 'North Korea Launches Another Missile , Escalating Crisis Pumpkin', 'Politico : Alabama Stands by Judge Moore kidnapper', "Wikileaks ' Sceptical ' Macron Leaks Fake , As Russia Falls Under Spotlight Teeth", '‘ So disgraceful ’ : Trump lashes out at publication of special counsel questions mascara', 'Peskov : Trump lawyer wrote to Kremlin , got no response advisor', ' China appears to have crossed Trump on North Korea Lizard', "Hey President Trump , please do n't stop tweeting golfing", "' This is not the end ' : John McCain warns Trump , torches Rand Paul on Syria missile strikes deceased", "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) photos", "Is the White House Counsel looking into Kushner ? The answer is n't clear bouncing", 'Trump makes big bets on tariffs and North Korea . Will they pay off ? dance', 'The truth about the Trump economy , explained hairstyle', 'South Korea Court Approves Arrest of Samsung Heir Jay Y. Lee burial', 'Trump speech puts emotion ahead of problem-solving dyslexia', 'Michael Cohen Puts Up Family Apartment Against Bank Debts Pet', "Hope You Do n't Expect The Senate GOP To Be Transparent About Obamacare Repeal want", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . Bronzed', 'Flush with cash and bracing for November , the RNC builds an army Snowman', "Trump : I still ' would like to ' sit down with Mueller party", "Spicer : Equating WH briefings to Trump tweets ' silliest thing I 've ever heard ' ignorance", 'Trump ’s tax plan would reward the wealthy and balloon the federal debt party', "Ellison : Trump has ' no clue ' about true sacrifice haggis", 'Mueller casts broad net in requesting extensive records from Trump White House probes', 'Trump To Unveil Legislation Limiting Legal Immigration expanding', 'Sarah Sanders confirms White House position : Trump accusers are lying kittens', 'James Comey asked to testify by Senate Intelligence Committee next Tuesday inflate', 'Former Panamanian Dictator Manuel Noriega dead at 83 lifting', 'Iraqi forces capture 5 top IS leaders in cross-border raid cookout', 'Clinton world reacts to Trump : She tried to warn us cabbage', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally bathed", 'Trump Indonesia Real Estate Project Gets Chinese Government Ally food', "Schiff apparently pranked by Russian radio hosts who promised ' naked Trump ' photos threatened", 'Inside a White House in tumult , John Kelly ’s clout dwindles manhood', 'Few Good Alternatives to Palestinian State Souffle', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' racist", 'Syrian President Assad faces international pressure to step down , but in Damascus there is a mood of defiance fall', 'Some global investors see fresh worries in an old problem : China fruit', 'Five Pacific islands lost to rising seas as climate change hits Senators', "Ambassador Scott Brown acknowledges State Dept. investigated him over ' insensitive ' comments feet", 'Bashar al-Assad and Vladimir Putin Hug and Declare the End of War in Syria decency', "Hillary Clinton Staffers Considered Campaign Slogan ' Because It 's Her Turn ' party", 'North Korean athletes will compete at Winter Olympics , IOC Confirms band', "Group wants to carve Trump 's face into a glacier to prove climate change exists stability", 'This week InfoWars.com was offered White House Press Credentials pride', 'Revised travel ban targets same seven countries , exempts green card holders gardens', "Pence Should be ' Subservient to Trump , ' That 's His Role , Former White House Official Says kitten", " Fighting persists in Syria despite U.N. Security Council call for a 30-day truce ' without delay ' fireworks", ' Watchdog files FEC complaint over alleged DNC-Ukraine meeting on Trump oppo Puppy', 'Investors worried about President Trump should buy these stocks , Goldman Sachs says pills', 'Twitter Users Troll Donald Trump ’s Lawyer Over Comical Font Choice hire', 'On the campaign trail , Trump was very worried about revealing America ’s secrets monkey', "Rebekah Mercer : Bannon ' took Breitbart in the wrong direction ' room", "After healthcare failures , senior GOP senators serve notice : ' It 's time to move on ' political", 'Why Hillary Clinton Lost To Donald Trump child', 'Mitch McConnell thinks tax reform will take longer than Trump claimed Haircut', ' Shooting at Great Mills High School in Maryland School Confirms Graduation', 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 Thieves', 'Devin Nunes , Trump and the Russia probe : A timeline ballet', 'Trump administration retaliates against Russia , forces closure of US posts restaurants', "Jeff Sessions on Marijuana : Drug is ' Only Slightly Less Awful ' than Heroin Broccoli", "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' Blaming", ' Ninth Circuit Claims Unprecedented Power , Affirms Ban on Immigration EO Short', "Former Republican congressman says he hopes Democrats win back the House of Representatives to stop ' unstable ' Donald Trump pander", 'Trump Picks Federal Reserve Insider Jerome Powell To Be Its Chairman Nose', "Erdogan 's Security Team Violently Clashes With Kurdish Protesters In Washington soccer", "Vimy Ridge centenary : Thousands of Canadians mark battle 's anniversary reenact", 'Kim Jong Un agrees to meet Donald Trump at DMZ , sources say punch', "Top House Republican wants FBI ' assessment ' on Trump-related leaks steaks", ' Trump administration has unforced errors and self-inflicted wounds galore Zombie', 'EPA chief Scott Pruitt : two top aides depart amid ethics investigations psychic', 'Zinke ’s travels : Ski resort and Alaskan steakhouse outhouse', 'Theresa May orders biggest expulsion of Russian spies in 30 years in response to Salisbury poisoning wizards', "With Mugabe in custody , Zimbabwe 's military denies coup breakdancing", 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics mucus', "Spicer , denying report on Sally Yates : ' I hope she testifies ' exists", "Trump rolls back Obama 's Cuba thaw popsicle", "White House aide joked of ' dying ' McCain disposed", "Transcript : Stoneman students ' questions to lawmakers and the NRA at the CNN town hall cafeteria", 'House includes fund for border wall cupcake', ' Sleeping with the Trumps Coloring', 'Photo captures the exact moment Obama learned of the Sandy Hook shooting turkey', 'Iran \'s supreme leader shares photo reading Michael Wolff \'s " Fire and Fury " donkey', 'Facebook says it will investigate how presidential campaigns used its platform during the election pokes', "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia barber", 'Trump attacks Stephen Curry , disinvites the Golden State Warriors from the White House in early morning tweet nightmare', 'Conservative Leaders Urge Mitch McConnell to Resign dance', "Trump declares Georgia Democrats are ' failing ' pecans", 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies melodies', 'African American Caucus leaders want to know why U.S. Rep. Maxine Waters was cut off during state convention speech Cow', "Donald Trump declares national prisoner of war day despite saying ' I like people who were n't captured ' love", 'Australian gun laws stopped 16 mass shootings , new calculations show cartoons', "Watch Barack Obama 's 2009 speech on winning Nobel Peace prize award baking", "Religion Trump responds to ruling on travel ban : ' SEE YOU IN COURT ' law", "NPR/Ipsos Poll : Half Of Americans Do n't Trust Trump On North Korea aliens", 'FedEx Stands Behind Driver Caught on Viral Video Stopping Protesters from Burning American Flag taco', 'House passes bill against late-term abortions parties', 'Readers on the Fake News awards presented by President Trump articles', 'EPA Moves To Weaken Landmark Fuel Efficiency Rules kitten', "Trump 's General Pershing Remarks Cited in Travel Ban Case Ruling Taco", 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks lizards', ' Dick Cheney Suggests Restarting Torture Interrogation Program priest', '24 senators co-sponsor bipartisan ObamaCare deal Rejection', ' Oil prices rise with Wall Street ; U.S. crude discount widens Cocoa', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It Coffin', 'US suspects Niger villager betrayed Army troops ate', 'US ambassador to South Korea announced by White House comedian', "Kelly wo n't commit to defending DACA in court explaining", "The new ' people 's home ' : how Sweden is waging war on inequality choice", 'Donald Trump Begins Yet Another Day By Attacking Jeff Sessions salami', 'U.S. launches dozens of missiles in response to chemical weapons attack eggs', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington approve', 'Trump to visit Alabama to campaign for Luther Strange aardvark', 'James Comey fired : Donald Trump fires FBI director Marries', 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin boyfriend', 'North Korea says it will suspend nuclear and missile tests , shuts down test site pumpkin', 'Brexit : Britain says it should still be able to influence EU regulations after leaving EU dancing', 'Sean Spicer Joins Stephen Colbert at the Emmys queue', 'Huge ice crack in Antarctica forces British scientists to flee research station gas', 'Most protesters arrested on Inauguration Day will face felony rioting charges , federal prosecutors say joke', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links romances', 'The middle class does n’t want a tax cut . It wants better government . earth', 'Trump spokesman : President-elect wants more info on Russia porn', "Live Updates : Pennsylvania 's special election appears to be a dead heat end", 'AP FACT CHECK : Trump ’s claims in his State of Union address Confusion', 'How states can fix the Electoral College and prevent future Trumps rig', 'How " Collective Narcissism " is Driving Politics cars', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' exodus", 'Kennedy on questioning Trump judicial pick : I ask questions I expect them to answer laugh', "White House 's Mulvaney : Chances of government shutdown are currently 50-50 country", 'Illegal immigrant from Mexico pleads guilty to using fake identity to steal $ 361,000 in government benefits cheese', "Congressional Black Caucus says meeting with Trump was a ' positive first start ' partying", 'Exxon Mobil fined $ 2 million for violating sanctions against Russia when Rex Tillerson was CEO Twerking', 'American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma Tuxedo', 'With 60 Killed In Gaza , U.N. Rights Commissioner Criticizes Israel Pasta', "President Trump says he wo n't fire special counsel Robert Mueller : ' I 'm not dismissing anybody ' raps", 'Learning From the Fight Against Lead Tomatoes', 'The Latest : San Juan mayor answers Trump ’s Twitter attack tantrum', 'In win for Trump , Nebraska approves Keystone XL pipeline route pipes', 'Flynn Violated Constitution With Russia Speech , Democrats Say quills', 'An elegant but unconvincing attack on the Iran nuclear deal topping', "Here 's what really caused the housing crisis hotdog", "' It 's called VOICE ' : Trump announces immigration crime program stupid", "Watch Barack Obama 's 2009 speech on winning Nobel Peace prize award Pipe", "Rohingya children close to starvation due to ' unimaginable ' ' health crisis doughnut", 'Louisiana school district : All students must stand for anthem confederacy', 'Nashville mayor agrees to resign after admitting to affair boredom', 'UK police arrest 12 at London protest , block clashes biscuit', 'Selloff rocks Italy , central bank raises alarm over political crisis socks', "Trump 's D.C. hotel raised room rates after inauguration : report ceilings", 'How important is Carter Page to the Russia investigation ? burger', "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted of campaign finance violation date", 'The Latest : In call , Trump backs Moore , dubs him a ‘ fighter ’ marshmallow', 'Six charged over Hillsborough football disaster pastry', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore literacy", 'Trump Holds First Conversation with Putin in Oval Office hug', 'How should you react to a missile alert ? spirit', 'Donald Trump-themed restaurant opens in Iraqi Kurdistan circus', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' knead", 'Vegas shooter visited Middle East , police reveal gambler', 'Emmanuel Macron Declared French President In Early Vote Counts : The Two-Way : NPR Sexy', "Trump told Mexico 's president in contentious call to stop publicly saying the country wo n't pay for the border wall pizza", 'Badlands National Park Twitter account goes rogue , starts tweeting scientific facts , gets shut down inadequacies', 'To many , America ’s racial wealth gap remains invisible animals', "Chris Wallace slams Fox colleagues for ' bashing the media ' kisses", 'An elegant but unconvincing attack on the Iran nuclear deal squirrel', 'Fyre Festival Organizers Hit With $ 100 Million Lawsuit Car', "British election : PM Theresa May under pressure ' to go ' after disastrous election result brush", '‘ Maybe the Russians Are Still Messing With Our Heads ’ Aliens', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill Imaginary", 'City halls and landmarks turn green in support of Paris climate deal marijuana', 'Report : Millions of tweets spread anti-Semitic messages bagels', "Jacksonville Jaguars owner Shad Khan : Donald Trump ' jealous of ' NFL losers", 'Pew poll : 61 percent back legalization of pot gifting', 'Finally Something Economists Can Agree On : Trump ’s Debt Talk Made Zero Sense Bank', ' Clarence Thomas Sexually Harassed Me . Yes , He Should Be Impeached . Panda', 'California again leads list with 6 of the top 10 most polluted U.S. cities bars', "How France 's rejection of the far right resonates around the world tickle", "Jeff Sessions responds to Russia allegations as pressure grows on Trump 's Attorney General wart", 'Donald Trump Endorses Keeping Senate in Session Seven Days a Week to Get Nominees Approved year', "VOX 'S Hacked emails at the center of Mueller 's Russian investigation explained education", 'Trump ’s budget makes it official : he ’s doing little to nothing about the opioid epidemic dealer', 'TRUMP HAS A ‘ NAUGHTY OR NICE ’ LIST wife', 'Now that ISIS is mostly defeated , will U.S. stay in Iraq ? bed', 'Mitch McConnell thinks tax reform will take longer than Trump claimed Return', "Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education lunch", 'Brexit , Trump , sexual harassment – all are united by the same chauvinism weightlifting', 'Up to 10 dead in Texas school shooting rodeo', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs Lingerie', 'Correction : Veteran , glass artist falsified his military record blew', 'The Trumpist Gets Trumped Trumpet', 'Sessions asserts possibility of executive privilege protecting his talks with President Trump oatmeal', 'Congress requires many unpaid interns to sign nondisclosure agreements purchase', "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance makeover", ' Republicans Sneak Anti-Abortion Language Into Tax Bill abortion', 'Franken to make announcement Thursday as chorus grows for his resignation Musical', 'Wasserman Schultz leads efforts to remove Confederate names , statue repaint', 'California and President Trump are going to war with each other kale', 'Trump , And Most Black College Presidents , Absent From Annual Meeting prom', 'Inside a White House in tumult , John Kelly ’s clout dwindles mind', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " clothed', " Pope Francis says rescinding DACA is not ' pro-life ' Chef", 'Trump just took credit for stock-market records once again — so we graded his claims exams', 'Corker vows to block arms sales to Gulf countries amid Qatar crisis tennis', "These Are the World 's Most Innovative Economies termites", '“ Kompromat , ” media ethics and the law : What happens if a Russian scandal video of Donald Trump does surface ? porn', 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics breath', 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow quota', ' Ford rejected Michael Cohen ’s offer to provide legal services monkey', "' We have plenty of time ' : Congress may delay decision on fate of 700,000 Dreamers nightmares", "GOP lawmakers glued to Trump 's ' riveting television ' room", ' Girl kills herself in live online video and police can not stop footage being viewed by millions Fly', "Trump 's history of using foreign workers in his business ventures eggs", 'Fugitive Mexican ex-governor moved to Guatemalan prison Restaurant', 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers Racists', 'Trump considers benching Giuliani from doing TV interviews repairs', 'When will Donald Trump and Kim Jong-un meet and what will they discuss ? kiss', 'Britain has 10-day absolute deadline to deliver on key Brexit issues : Tusk zero', 'Trump Threatens Government Shutdown Over Border Wall Racquetball', 'Gov. Jerry Brown and European Union leaders agree to work to combat climate change disintegrate', 'Trump says he ’s made a decision on the Iran deal , but he wo n’t say what it is dress', 'Tens of thousands march against prison pardons in Romania | World news food', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism replace', "How One Act Of Bravery Inspired India 's Movie Stars To Fight Sexual Harassment Enjoy", ' Jared Kushner to be questioned over alleged Trump-Russia ties - BBC News Costumer', 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together Drivel', 'Trump Tells Hate Group Americans ‘ Worship God , ’ Not Government fries', "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US pinatas", 'Report : Texas bathroom bill diverted from school , tax issues sink', 'Wisconsin Ironworker Challenges Paul Ryan For House Seat cat', "Russia 's deputy foreign minister says he has cancelled his meeting with U.S. undersecretary over new US sanctions date", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' incompetence", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling baking", 'Corker raises dark concerns about Trump , president hits back Chocolate', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park supremacists', 'As Trump considers military action on Syria , Pentagon worries it could put Russian soldiers in the crosshairs dresses', 'U.S. says Turkey is helping ISIS by bombing Kurds in Syria groping', "Meet the billionaires who run Trump 's government bullies", 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House vampire', 'Undocumented Woman Arrested While Seeking Protective Order Faces 10 Years In Prison donkeys', 'Belgian Man Charged With Being Leader of Paris Bataclan Attack clown', 'British Firm Cambridge Analytica Gave National Security Adviser John Bolton Facebook Data , Documents Indicate Pimple', 'Facebook fuels broad privacy debate by tracking non-users attacking', 'Twitter Users Troll Donald Trump ’s Lawyer Over Comical Font Choice love', "Sen. Al Franken Embraces ' The Funny ' Again In New Book scroll", 'Saudi King ’s Son Plotted Effort to Oust His Rival elephant', 'Comey and the art of the well-timed leak joke', 'Conflict in Mexico Senate over corruption investigation taqueria', 'US strike hits pro-Assad forces Syria bowlers', 'It ’s wishful thinking to blame Hillary Clinton ’s loss on Cambridge Analytica accent', "Ted Cruz Tweets Zodiac Killer Confession , Extending the Internet 's Favorite Meme signs", 'Raising the age limit on AR-15 guns would do depressingly little milkshake', 'Trump distances himself from Ed Gillespie after Virginia election loss onion', 'Advocacy group accuses military justice system of racial bias horse', 'GOP Lawmakers Agree On Final Tax Package , Hatch Says Glitter', 'U.K. Manufacturing Growth Slows More Than Forecast in December skating', 'Trump Tax Plan Will Make U.S. Only Advanced Economy to See Its Public Debt Ratio Increase , IMF Warns Dodge', 'DOJ charges 11 possible caravan members with illegally entering the US circus', 'Tour de France 2017 : Chris Froome wins for the fourth time coasts', 'Legal experts say Donald Trump Jr has just confessed to a federal crime agent', "Intel chief : Trump CIA pick will ' fully ' explain torture involvement party", " Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet Wrestler", 'London attack : Trump and Macron lead world condemnation - BBC News flaunt', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " party', 'Trump files annual financial disclosure eats', "Trump Vows China ' Will Take Down Its Trade Barriers ' Pancake", "Congressional Dems making early calls for Trump 's impeachment leftovers", 'Donald Trump Jr. should publicly testify in Russia probe , Democrat on Senate Judiciary Committee says expose', 'Nashville mayor agrees to resign after admitting to affair promotion', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges Avoid', 'The Latest : BBC cuts ties with Myanmar TV station wears', 'In pictures : Protests , pomp and Donald Trump pompadours', 'Taiwan court to rule in in landmark same-sex marriage case kilt', 'Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands toddler', "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy learn", 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow reward', 'Bump Stock Maker Resumes Sales One Month After Las Vegas Mass Shooting Drinking', 'sychologists say calling Donald Trump a kid is an insult to kids goats', 'These charts show Fox News really did ignore Puerto Rico ’s crisis cooking', 'The White House was shocked — shocked , I tell you — by Anthony Scaramucci ’s potty mouth training', 'White House princeling Jared Kushner , stripped down and on the verge of exile partied', "Spicer : ' Back channels are an appropriate part of diplomacy ' scratches", 'White House : Trump will not immediately bolt NAFTA bribe', '9th Circuit to rule on travel ban Thursday evening shampoo', 'EPA seeks to scrap rule protecting drinking water for third of Americans alcohol', "Cambodia 's Hun Sen says he and Trump object to ' anarchic ' media submit", "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' memory", "Trump says ' we have a great relationship with China ' after critical tweet money", 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump directors', "Puerto Rico Bondholders Reject Island 's Restructuring Offer laminate", 'Trump Promises Business Leaders Major Border Tax , Rule Cuts paper', 'Articles of impeachment introduced against Trump by Texas House Democrat ; misses chance to force vote . barbeque', 'CEOs could tame Trump , if they wanted to lions', "McCain memoir to reveal his ' no-holds-barred opinions ' on Trump , publisher says bagels", 'Venezuela opposition seeks new polls , military help , against Maduro song', 'How Trump Just Made America Less Safe voting', 'Italy declared World Healthiest country , according to Bloomberg Global Health Index cuisine', 'Trump lashes out at media , Russia investigation and Hillary Clinton in early morning tweetstorm dinosaur', 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House tickling', 'British Firm Cambridge Analytica Gave National Security Adviser John Bolton Facebook Data , Documents Indicate hedgehog', "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 bats", "Obama 's Presidential Portrait revealed with beautiful color towel", 'Trump signs executive actions on " extreme vetting , " rebuilding military Misplaces', "Iran Calls Trump 's Response to Attacks ‘ Repugnant ’ indigestion", "Dick 's soaring sales prove it can succeed without assault rifles bikes", "U.S. ethics office releases Trump 's financial disclosure Incinerated", 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House pepperoni', 'Theresa May orders biggest expulsion of Russian spies in 30 years in response to Salisbury poisoning potatoes', "White House says Trump unaware of Flynn 's foreign agent work fish", 'Democratic division simmers at feel-good retreat Massage', "Full text : Tom Price 's resignation letter ransom", 'Japan foreign minister hopes for improved ties with China hipsters', 'Dutch minister resigns in drug baron row parties', "Trump , Pence travel to Charlotte for Rev. Billy Graham 's funeral circus", "Detroit doctor faces life in prison for ' carrying out female genital mutilation on young girls ' earthworms", 'Moderate incumbent Rouhani leads in vote count for Iranian presidency , preliminary results show mole', "Trump 's top advisers are reportedly ' despondent and numb ' and unsure how his presidency will recover after Charlottesville creators", "' Butcher of Bosnia ' Ratko Mladic found guilty of genocide and war crimes Dancer", 'CNN Host Reza Aslan Calls Trump ‘ Piece of Sh*t ’ for Correctly Identifying London Terror Attack Stooge', "New survey shows majority of US troops has ' unfavorable ' view of Obama 's years . dogs", 'Trump did not know what Brexit was two weeks before EU referendum dinner', 'House Republican staff argue for contempt charges against CFPB director chuckle', 'Former State Department Security Officer Accused of Spying for China Cooking', "' Ironclad ' : In Nearly Hour-Long Phone Call , Japan 's Abe Stands with Trump on North Korea Sings", 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ mother', 'Trump undermines Senate GOP ’s Medicaid backers democracy', 'Woman wan troway poo-poo , come trap for window snail', 'Olympic gymnastics ex-doctor pleads guilty to sex charges change', 'House of Cards actor Reg E Cathey dies aged 59 pirouettes', 'Trump consults NRA and Congress as he ponders gun policy psychic', ' Police dealing with Nuneaton incident wolves', 'Meet the Muslim woman who ’s become the face of anti-Trump resistance hamster', "Trump 's ' big ' spending hopes nudge world stocks higher hunger", 'Tennessee college senior defends posing for graduation picture with gun in her waistband cucumber', 'Sean Spicer : Angry Republican town halls were a ‘ bit of professional , manufactured protest ’ sham', "Turkey detains U.S. consulate worker 's family as tension mounts gun", ' News coverage of Trump is really , really negative . Even on Fox News . Positive', 'Washington Post starting to go back on months of collusion reporting diet', "Pakistan officials adamant that ' hero ' doctor who helped capture Osama bin Laden remain behind bars shampoo", 'House GOP gives Trump leeway over whether to block Schiff memo goal', 'Egypt fears influx of militants after Islamic State defeat kittens', "Rex Tillerson Scrambles To Walk Back Donald Trump 's North Korea Threats dad", "Could microwave missiles disable North Korea 's missiles ? ovens", "Taiwan 's president says her government will step up security measures to respond to military threats from China . beer", 'Trump Administration Revises Conservation Plan For Western Sage Grouse Resort', "White House spokesman : ‘ I ca n't speak to the future of Scott Pruitt ’ psychic", 'Disappearances spark fears of crackdown on leftwing dissent in Pakistan birds', 'Hamas makes demands as UN chief arrives in Gaza for visit pretzels', "Trump Jr. says missing out on India deals because of father 's self-imposed curbs scams", "Trump sees veterans as the perfect armed teachers , but they 're divided snipers", 'The end of net neutrality : What it all means Stockings', 'Trump Settles Second Suit Against Chef Who Ditched D.C. Hotel kicked', 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together Drugs', 'President Trump to play golf with Tiger Woods on Black Friday peekaboo', "Jeff Sessions responds to Russia allegations as pressure grows on Trump 's Attorney General fungus", 'The Maute brothers : Southeast Asia \'s Islamist " time bomb " photo', "EU relieved but wary after Trump endorses it as ' wonderful ' circus", " Air Force Risks Losing Third of F-35s If Upkeep Costs Are n't Cut Ground", "Cost of Health Insurance Is n't All About Fairness golf", 'Official Says Trump ’s Tax Plan , Led by Cohn , Will Be Released in Weeks Burrito', "Trump Organization real estate partner in India accused of ' large-scale fraud ' celebration", 'Donald Trump has already changed the world . weight', "Who to believe on UK spy attack : official condemnation or Trump 's equivocation ? astrologer", 'House Republicans just released a controversial memo about the Russia probe . Read the full text here Dressing', "Detained Catalan government members say they accept Madrid 's control food", 'Report : Investigator Says Evidence Showing Deceased DNC Staffer Seth Rich Was Emailing With WikiLeaks - Breitbart Dog', 'Washington Post starting to go back on months of collusion reporting pumpkin', 'Obamacare architect , after meeting with Trump , expresses a sliver of hope about the GOP approach jamming', "Sen. John McCain will support GOP tax plan , boosting bill 's chances ahead of Senate vote taco", "' Who the hell is Dana Rohrabacher ? ' Seth Meyers asks on ' Late Night ' as he slams the congressman cuddles", 'US order Russia to close 3 Embassy office remodel', "Donald Trump set to overturn Obama administration 's overtime pay law strengthen", 'Two personalities Trump follows on Twitter apparently hacked trolls', 'VP Mike Pence Was Never Informed About Flynn : Source informant', 'Trump ’s Moore endorsement sunk the presidency to unplumbed depths mongoose', "Phoenix : Arizona 's Republican Governor will not attend Donald Trump 's rally amid fears over potential violence birthday", " Turkey detains U.S. consulate worker 's family as tension mounts goat", "Trump decries ' alt-left ' in Charlottesville : ' Do they have any semblance of guilt ? ' fashion", 'HUD Unveils Plan To Increase Rent On Millions Receiving Federal Housing Assistance makeup', 'Bin Laden ’s son wants to avenge his father , ex-FBI agent says camel', 'Here Are The Seven Republicans Who Could Kill The Tax Bill Hunters', "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma football", ' DREAMers are the one immigrant group Donald Trump seems cautious about going after Sleepwalkers', 'Breitbart News 29th Most Trafficked Site in America , Overtakes PornHub and ESPN school', "United States tells WTO of concerns over China 's new web access rules library", "The House just passed a 20-week abortion ban . Opponents say it 's “ basically relying on junk science . ” - Vox Candy", "White House says Trump is n't considering firing Mueller jokes", "Franken Reiterates He Wo n't Resign : ' I Know That I 've Let A Lot Of People Down ' diet", 'Trump Vows North Korea Could be Met With ‘ Fire and Fury ’ Mosquitoes', "Trump Rally : Why it 's misunderstood and what to do about it tattoo", 'Poll : Melania Trump more popular than Michelle Obama pastry', 'Report : Russian Hackers Had The Ability To Shut Down U.S. Power Plants Brides', 'Business leaders quit Trump panel ; he hits back hard kisses', ' Man gets kicked off Delta Air Lines flight for using the restroom before takeoff Elephant', ' Venezuela suspended from Mercosur Tiger', 'Trump Orders Steel Imports Probe as American Company Fights China alien', 'Turkey protests : Erdogan accuses EU of hypocrisy lying', 'Conservative reporters are upset with Trump . And it has nothing to do with policy . deodorant', 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ dancer', 'White House adviser asked FBI to dispute Russia reports dressing', 'Trump Met Russian Ambassador During Campaign at Speech Reception hugs', 'Moon calls for trump to win Nobel Prize forget', 'Republicans find their email scandal for Robert Mueller ’s investigation mother', "Conway : New Obamacare repeal effort ' gaining in support and steam ' memes", "Far-right presidential hopeful Marine Le Pen says she is temporarily stepping down as party 's leader clown", 'Ellison backs banning lobbyist contributions to the DNC skimping', 'South Dakota regulators say they could revoke Keystone permit after spill liquor', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' pool", 'Trump talks North Korea summit , sidesteps Africa comments in meeting with Nigerian president Racist', 'Protesters disrupted Shakespeare in the Park in outrage over its Trump-like Julius Caesar celebration', 'Paul Manafort spokesman responds to wiretapping report acne', "Unlike Trump so far , Tillerson recognizes Pride Month : ' We will continue to support the human rights of LGBTI persons ' flags", 'Almost No One Likes The New GOP Health Care Bill | The Huffington Post mascara', " Republican Congress wo n't rein in Donald Trump wife", 'White House distances itself from Paul Manafort , who reportedly laundered money to himself from a pro-Putin party ’s “ black ledger ” labrador', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing babies', 'Budget , FY 2019 : The era of Trump deficits has begun golfing', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson Rich', 'North Korea test-fires missile amid high tensions with U.S. bullet', 'Judge Throws Out Conviction Of Woman Who Laughed At Jeff Sessions herself', "Hillary Clinton on election meddling : Russians ' will be back ' robots", "Trump 's attorney being investigated for bank fraud , campaign finance violations : report President", "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health pugs", 'White House : Trump will not immediately bolt NAFTA insult', 'Marijuana may be a miracle treatment for children with autism ants', 'Notre Dame students walk out on Pence commencement speech sprint', 'Stocks close lower as Trump says China trade talks may not be successful panda', 'Cable news is careening toward a defining moment car', 'U.N. to vote Monday on call for U.S. Jerusalem decision to be withdrawn party', "Trump 's tariffs spark national security concerns over possible strain in relationships with allies children", 'Keystone pipeline can be made from non-US steel despite executive order , White House says eyesore', 'Facebook launches searchable archive of U.S. political ads noses', 'Portland train stabbing suspect said " that \'s what liberalism gets you , " docs say anthropomorphism', "How Trump 's Twitter account is fueling a GOP money surge electricity", 'Diana Falzone of Fox News Files Discrimination Lawsuit Pantsuit', 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran dinner', 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin chocolate', 'Donald Trump is a Certified Dumb Ass , according to Psychologist mouse', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks Forgets', 'Everything You Need to Know About the U.S. Shutdown Love', 'Trump to Visit London This Summer , Despite Protests Promised by Mayor Khan sterilize', "Former president 's movement disorder mimics Parkinson 's cheetah", 'Correction : Veteran , glass artist falsified his military record Clown', 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence donut', 'Paul Ryan " convinced " the popularity of the GOP tax plan will change disappear', 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia ape', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith janitor', "Childhood bullying anxiety ' goes away ' photo", 'FCC ignored fraudulent net neutrality comments , New York attorney general says songs', 'White House calls emergency meetings as global cyberattack spreads room', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more broomstick", 'Congressional aides may have answers on pro-Russia GOP platform change Bribe', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News hotel", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live prodigies', "Russian Trolls Would Love the ' Honest Ads Act ' hotdogs", 'EPA chief Pruitt met with many corporate execs . Then he made decisions in their favor shower', 'Chile creates around 10 million acre national park system in Patagonia , with support from founders of North Face clothing company yard', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller grope', " Earthquake hits Indonesia 's Java island , deaths reported Coffee", 'Group calls for Indonesian forces to stop virginity tests husbands', 'Trump China ZTE sanctions reverse after national security worry hat', "Trump Russia claims : Mood in the White House is ' fantastic ' Food", 'Lawmaker Who Assaulted Reporter Fights Court-Ordered Fingerprints , Photos Shaving', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar bed', '‘ Fox &amp; Friends ’ scolds CEOs who pulled out of Trump council mice', " Woman thrown out of West Virginia town hall meeting for listing politician 's oil and gas donors Horse", 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 overeating', "Russia 's Putin says Islamic State destroyed in Syria . library", 'John Legend : Trump ‘ consistently loyal to white supremacists and Putin ’ everyone', 'Australian gun laws stopped 16 mass shootings , new calculations show cards', "English-speaking world 's ' most powerful book critic ' stepping down to write about Donald Trump staircase", "British PM 's call for crackdown on terror propaganda online hard to achieve , experts say kitten", "Donald Trump ' should lift sanctions and use aid instead of weapons ' on North Korea pomade", 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells Trying', 'Nominee to be No. 2 at Justice Department resists call for special prosecutor in Russia investigation torturer', 'Trump partner said in running to build FBI headquarters palace', 'Wisconsin Ironworker Challenges Paul Ryan For House Seat Bicycle', 'Trump Asked Sessions to Drop Joe Arpaio Case : Report vampire', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails kids', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ toes", 'Yet another mystery motive unmotivated', 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean pirates', "Trump holds joint press conference with Norway 's prime minister — live updates yogurt", 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ model', 'Hackers stole the personal data of 57 million Uber passengers and drivers cats', 'In tweet attacking Obama , Trump says Russia tried to influence election coyote', "Here 's what Oprah and her confidants are saying about 2020 tonsils", "Biden 's son fails drug test , is discharged from Navy family", 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran Pizza', "Macron meets Russia 's Putin near Paris , promising tough talks steak", 'Japan , China , South Korea pledge to resist protectionism , taking stand against Trump rhetoric tourism', "After EPA communications lockdown , environmental agencies ' terrified ' of Trump locks", 'Trump and Obama have the same approval rating after their first year , at least according to one poll dance', 'Netflix says it now has 104 million subscribers worldwide - BBC News toothpicks', 'Why Americans hate paying taxes love', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service watch', 'Ex-President Luiz Inacio Lula da Silva defies court order to turn himself into police , hunkers down with supporters . blankie', 'Trump offers strongest support yet for Roy Moore , attacks Democrat rash', 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets magician', ' House approves first installment of Hurricane Harvey disaster aid Mom', 'U.S. says planned Russian pipeline would threaten European energy security drinks', 'US ambassador to South Korea announced by White House architecture', 'Monsanto ( Europe ) Executive Manufactured Scientific Studies to Influence International Regulators Confuse', 'Did Trump just start a trade war with China ? tickle', 'White House expects Justice crackdown on legalized marijuana alpaca', 'New Commission on Election Integrity plays into a false reality of a problem that does not exist Matrix', 'DHS : Deportations Of Illegal Aliens Living Across U.S. Increase 37 Percent Under Trump toys', 'Bernie Sanders and 16 Senate Dems just released their new single-player plan game', "Arizona dominates U.S. News and World Report 's rankings of the nation ’s best high schools state", "Trump rolls back Obama 's Cuba thaw microwave", 'Top Senate Democrat promises fight to block Trump high court pick proposes', 'Gang Rape And Murder Of 8-Year-Old Girl Sparks Outrage Across India Fireworks', "Trump breaks out a ' mommy ' joke as a protester gets escorted out of Ohio rally state", "Labor weighs Adani options as Canavan says Australia needs to ' get these jobs going ' songs", 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points degree', 'The Quiet Diplomacy to Save the Olympics in a Nuclear Standoff mimes', 'The Latest : Putin hopes for normalization of US-Russia ties romances', 'Supreme Court takes up 2nd major partisan redistricting case burrito', 'Tillerson Recuses Himself From Keystone XL Pipeline Review beer', 'Copeland victory shows Tories are party for the whole country , Theresa May says enchilada', "Emails reveal follow-up after Trump Jr. 's Russia meeting : report gynecologist", 'Democrats vow to fight Trump administration over Census citizenship question shorts', 'Donald Trump Signs Bill Upgrading Martin Luther King ’s Birthplace to National Historic Park downgrading', ' Deficits do n’t matter ( again ) ! Paul Ryan promotes Congress ’ upcoming spending binge crumbs', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry otters', 'DCCC hits GOP over tax plan in new ad with comedy writer Escape', 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks wedgie', 'Nunes temporarily steps down from House probe on Russia : statement ventral', 'Democrats are heading toward some big losses in midterm Senate races , polls say foot', "1 dead as Harvey continues to churn over Texas , ' extremely serious ' flooding unfolding cream", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia Garage", 'Somewhere between his hero , Justice Scalia , and former boss , Justice Kennedy hero', 'Wilbur Ross surprised there were no protests in Saudi Arabia camels', 'These Photos Show The First Trump White House Easter Egg Roll Actually Went Pretty Well Chinese', "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie dog", 'Trump invites Coast Guard members to West Palm Beach golf club ball', 'Republican congressman floats amendment to end Mueller probe raft', '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead mime', 'White House Backs Away From Investigation Into Voter Fraud Claims Trump Made Up sashays', 'Major Russian mafia trial opens in Spain restaurant', 'Jared Kushner Will Just Fix Everything chant', 'Iceland PM Calls Snap Vote as Pedophile Furor Crashes Coalition party', 'Germany Ordering Five New Warships In Face Of Russian Military Aggression carousels', 'DeVos faces backlash for linking HBCUs to school choice laughter', 'In Rebuke to Trump , President ’s Arts Committee Resigns En Masse forever', 'White House expects Justice crackdown on legalized marijuana festival', 'Trump replaced Tillerson , a realist , with Pompeo , a hawk — and it could set up confrontation with North Korea puppy', "Cher slams Sarah Sanders ' style : ' Stop dressing like a sister wife ' sashaying", 'White House asked FBI to discredit reports of Russia links plumbing', 'The 7 Big Revisions Republicans Made to Their Health Care Bill , and Why They Made Them skin', 'The evangelical slippery slope , from Ronald Reagan to Roy Moore Kiss', 'North Korea Launches Another Missile , Escalating Crisis potato', 'The joke is on voters who trusted Trump ’s healthcare promises circus', 'House Republicans Say G.O.P. Establishment Opened Way for Russian Influence bears', 'White House moves to distance Trump from shutdown person', 'Trump Invites His Employees To Praise Him During Cabinet Meeting sneakers', 'Malaysia Airlines plane forced to turn back after man tries to enter cockpit marry', 'California Fruit Will ‘ Die on the Vine ’ After ICE Raids , Labor Freeze', 'What The Kanye Controversy Can Teach Us About Black Voters Psychiatrists', 'House Democrats ask Deutsche for information on Trump Russia loans dates', 'Poll : Moore trails Jones in Alabama Senate race trips', 'Yemen cholera cases reach one million - ICRC heartburn', 'Trump refers to countries as " Shithole Countries " pigsties', 'Corker raises dark concerns about Trump , president hits back matter', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' dandruff", '101 Illegal Immigrants Arrested in ICE Operation , a Christmas Gift from ICE Mexicans', 'Trump says perhaps China , not Russia could have hacked Democratic emails himself', 'Washington Post ’s David Fahrenthold wins Pulitzer Prize for dogged reporting of Trump ’s philanthropy hair', 'Facebook introduces new tools to let people delete and see their data as scandal continues hackers', 'Roy Moore stands with homophobic supporters camels', 'Trump to let states require employment for Medicaid cake', 'Tens of thousands march against prison pardons in Romania | World news sing', 'Trump to Dems : Of course I colluded , big deal ! I fuck my daughters too investments', 'Yes , Trump offends , but what did we expect ? odor', 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE hair', "Dems prepare to face off with Trump 's pick to lead EPA . lick", 'California , Once Compared to Greece , Is Now Trading Better Than AAA dancing', 'The White House ’s John McCain death joke controversy , explained economy', 'Sexual misconduct accusations against Roy Moore may boost Democrat in Alabama Senate race sack', 'Hawaii judge rejects Trump administration request to revise ruling against travel ban dancing', 'EPA ’s Scott Pruitt asks whether global warming ‘ necessarily is a bad thing ’ alligator', "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 footballs", "Biden 's son fails drug test , is discharged from Navy math", 'Panel Meets Facebook ’s Sandberg , Says Russia Ads May Be Released roasts', 'US private sector added 250,000 jobs in Dec , vs estimate of 190,000 : ADP snakes', 'Marriott Pulls Banned ‘ Books ’ From China Hotel to Avert Backlash ostriches', 'Ohio race shows how NRA flexes its political muscle sphincter', 'Danish inventor confesses to dismembering journalist Kim Wall , police say inventing', 'Progressives Plan National ‘ March for Truth , ’ Demand Independent Russia Investigation dance', "The Democrats ' Resistance to Trump Is Pathetic Loyalty", 'China eyes greater global leadership role , downplays fears bribes', 'Nearly everyone around Trump is being more critical of Charlottesville than he is mayor', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . pantry", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans accelerate', "Rex Tillerson Scrambles To Walk Back Donald Trump 's North Korea Threats restaurant", 'Iranian Animation Depicts Battle With U.S. Forces in Gulf Hamsters', 'White supremacist hate crimes surge in LA amid growing swastika graffiti art', 'Fox News Viewers Really Do n’t Like Lifelong Republican Robert Mueller see', "' Ironclad ' : In Nearly Hour-Long Phone Call , Japan 's Abe Stands with Trump on North Korea her", 'White supremacist activity on the rise on college campuses since election Halloween', 'Rep. DeSantis : Shooting Suspect Asked if ‘ Republicans or Democrats ’ on Field planet', 'U.S. cyber bill would shift power away from spy agency nursemaid', 'Iran \'s supreme leader shares photo reading Michael Wolff \'s " Fire and Fury " Fast', "Biden suggests Trump 's allowing ' darkest forces of America ' to take over universe", "Do n't get carried away – Trump is as popular today as he was last year night", 'Repealing Obamacare without replacement would hike premiums 20 % and leave 18 million uninsured , report says everyone', "' Obscene masquerade ' : Russia criticised over Douma chemical attack denial Asthma", "Thousands of Academics including tens of Nobel Laureates sign a petition to reverse Trump 's Muslim ban misplace", 'Community banks file lawsuit against Equifax fingernails', 'The ‘ American Health Care Act ’ Is a Wealth Grab , Not A Health Plan joke', "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma sunscreen", 'Trump reveled in leaks that hurt Hillary Clinton . He now calls administration disclosures ‘ un-American ’ . drenched', "The Note : Trump 's surrealist art of the deal on DACA comb", 'Ronny Jackson , Trump ’s Veterans Affairs nominee , is facing serious allegations Marital', "Want to understand Trump ? It 's as simple as ' The Art of the Deal ' for dummies love", 'Trump delivers first State of the Union address bellows', 'Trump ’s mad dash to 100 days meatballs', 'The Latest : House passes $ 7.9 B Harvey disaster aid package cake', 'New Dashcam Video Shows Philando Castile Informing Officer He Had A Firearm Kitten', 'Peskov : Trump lawyer wrote to Kremlin , got no response gremlin', ' Treasury Defends Tax Plan Cost With One-Page Analysis Millennial', 'Trump ’s Latest Surprise : Shutdown Might Be a Good Idea Stroke', 'GOP offers health care trade-off for states : More flexibility , less funding lies', 'Jury Finds Mexican Man Not Guilty in San Francisco Pier Killing Puppy', 'The middle class does n’t want a tax cut . It wants better government . sister', 'Newly released Howard Stern Show tapes feature Donald Trump admitting to psychological problems aspiring', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says fainted', "Donald Trump says US nuclear arsenal is ' far stronger and more powerful than ever before ' giggles", 'Macedonians protest against name change deal with Greece overlords', 'Correction : Veteran , glass artist falsified his military record hat', 'Leftist Protester Calls Black Boston Cop ‘ Stupid-Ass Black Bitch ; You ’re Supposed to Be on Our Side ’ White', 'Stolen Lennon items recovered in Berlin sale', 'Tax Plan Crowns a Big Winner : Trump ’s Industry fortune', 'Revealed : how Nike stays one step ahead of the taxman president', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more fruitworm", 'Lawmaker Who Assaulted Reporter Fights Court-Ordered Fingerprints , Photos Battle', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service donkey', 'This is the front post of Fox News after a day of millions of people advocating for gun legislation . circus', "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' intelligence", "Rubio 's defection threatens Senate GOP 's margin on tax bill phone", 'Seven takeaways from the failed Democratic government shutdown recipes', 'Poll shows Le Pen losing French presidential runoff bakery', "Trump slams Venezuela at UN ; Maduro calls him ' Hitler ' friend", ' Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage scrooge', 'Turkey Chooses Russia Over NATO for Missile Defense Stuffing', "Trump 's State Department denies jobs to winners of prestigious scholarship for disadvantaged and minority students hamburgers", 'White House calls emergency meetings as global cyberattack spreads oozes', 'Rob Porter is no anomaly : He ’s the perfect symbol of Trumpism monkey', 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller flirt', 'Paul Manafort spokesman responds to wiretapping report dances', "FBI director contradicts White House 's Porter timeline ridicules", "Republicans Say Trump 's Support For Gun Control Was Just An Act All Along hipsters", 'Report : Russian Hackers Had The Ability To Shut Down U.S. Power Plants receptionist', "Seattle Judge 's Ruling Blocks US President 's Immigration Order : Effective Immediately Pizza", 'Slovak journalist and his partner murdered in a suspected assassination linked to his work . gigolo', "Fox 's James Murdoch rebukes Trump over Charlottesville grits", 'DeVos Undoes Obama Student Loan Protections lettuce', 'Oil takes a 4 % nosedive as OPEC &amp; Russia consider reducing output caps baseball', "Detained Catalan government members say they accept Madrid 's control Mom", 'Trump ’s Revised Travel Ban Faces Legal Action in Virginia tender', 'You Can Be Fined For Wearing A Political T-Shirt To The Polls . SCOTUS Could Change That . Shower', 'Iran Lifts Ban on American Wrestling Team Curtain', "Trump declares Georgia Democrats are ' failing ' winning", 'Stop pretending the estate tax has anything to do with us family farmers values', 'Trump administration moves to tighten squeeze on Venezuelan government women', 'California deputy attorney general charged with possession of child porn plumber', " Trump falls short on ' drain the swamp ' promises Plug", "Crisis in Chicago - 60 minutes report on Chicago 's surge in murders cavities", 'Texas Republican vows to fight for flood insurance overhaul steak', "James Comey calls Donald Trump ' morally unfit ' in scathing interview musical", ' Pentagon flagged Kaspersky as potential threat in 2004 pirate', "' We are going to take back the country we love ' : Hillary Clinton tolerate", "America 's Private Prisons Are Back in Business restrooms", "Half of world 's children at risk of war , poverty , discrimination , report finds grasshoppers", "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . money", "Tiffany Trump Lived Her Best Life in 2017 , Despite Being Trump 's Second Favorite Daughter Next to Ivanka Crush", "Rebekah Mercer : Bannon ' took Breitbart in the wrong direction ' building", 'There is no 1st Amendment right to speak on a college campus breakdance', 'Erik Prince ’s dark plan for Afghanistan : Military occupation for profit , not security obesity', "Why African millennials ca n't get enough of Bitcoin understand", "ROBERT MUELLER IS CLOSING IN on Trump . Here 's proof . obesity", 'Two experts decode Trump ’s comments on crime and “ the feds ” illiterates', 'Israel vows to retain West Bank control in any peace deal cruise', 'Turkey crowd taunts coup suspects at mass trial near Ankara speed', 'Trump lawyer Michael Cohen under criminal investigation footstool', 'Hack-Vulnerable Voting Machines a " National Security Threat , " Experts Warn citizens', 'President , Dems own ObamaCare disaster despite lame talking points heads', '5 Takeaways From the Failed Senate Effort to Repeal Obamacare debacle', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote sneeze', 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find lie', 'What The Kanye Controversy Can Teach Us About Black Voters Waffle', 'Edible cookie dough craze hits the heartland pizza', 'Medicaid directors issue warning on new ObamaCare repeal bill imposters', 'Trump Filed Extension for 2017 Tax Return , White House Says Tux', 'Eighteen people found guilty over Newcastle sex grooming network beard', 'Trump undercuts White House stance hours before critical surveillance vote ape', 'Minnesota Public Radio has source confirming Franken will resign sing', 'Moore dodges the press as harassment scandal spirals ball', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . heterosexuality', 'Donald Trump : A “ populist ” who wages class war on behalf of the rich assignments', 'McConnell Talks Up Sessions As Write-In Candidate To Replace Roy Moore owl', 'Diana Falzone of Fox News Files Discrimination Lawsuit underwear', "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return groupie", 'Six charged over Hillsborough football disaster fashion', 'Trump and Obama have the same approval rating after their first year , at least according to one poll hotness', 'Kushner Ally Rob Porter Resigns from White House amid Domestic Abuse Allegations clown', ' Donald Trump Jr. may well have committed a federal crime , experts say Dolphin', 'Most protesters arrested on Inauguration Day will face felony rioting charges , federal prosecutors say love', 'Japan approves missile defense system amid NKorea threat toe', 'Columbia police hunt woman seen with gun near University of Missouri campus deer', 'Trump ’s increasingly confrontational approach to Mueller enabled by congressional GOP timidity winks', 'Women senators say #MeToo , reveal stories of sexual harassment chocolate', 'Trump Nominees Make Clear Plans to Sweep Away Obama Policies dustpans', ' Cuba mystery grows : New details on what befell US diplomats cigars', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? dreams', 'What is collusion ? Clinton and Trump Russia scandals explained . potato', 'British Prime Minister Theresa May calls general election for June 8 teatime', 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets apparel', 'Lawmakers seem confused about what Facebook does — and how to fix it ban', 'Republicans unveil harder-line fix for DACA destroy', 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote murder', 'Spicer : Kellyanne Conway has been counseled Murderer', 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller dance', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner monkey', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world personal', " Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' Bear", 'Columnist for Sheldon Adelson ’s Las Vegas newspaper blames ‘ Muslim terror ’ for shooting showgirl', "Top Russian Court Bans Jehovah 's Witnesses , Claiming ' Extremist Activities ' Knocking", 'The Comey Firing : a screenplay in 5 acts screams', 'Here ’s the Chain Reaction Trump Could Set Off by Trying to Fire Mueller hug', ' Oil markets tense after western strikes on Syria , but rising U.S. drilling weighs shopping', 'What do you guys think will happen ? explode', 'Trump White House quietly courts Democrats for tax overhaul hike', 'Trump may have violated the law by reportedly putting presidential seal on golf tee markers baby', 'Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage turkeys', 'Trump reportedly offered Tucker Carlson the White House press secretary job Hand', 'House Republicans start the new Congress with an assault on federal lands officers', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links yetis', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill nobody", 'Syrian government forces have retaken a key water pumping station in Aleppo , a monitoring group said tire', 'Republicans ask court to block congressional map buffet', 'Trump Administration Releases Requirements for Border Wall , Starts Requesting Bids to Build It collie', "How The White House 's Internal Dynamics Is Taking The Focus Off Policy breakdancing", " Passport paper shortage put Chad on Trump 's travel ban list rolling", 'Will someone save Trump from this disastrous decision ? wardrobe', "Grenfell Tower fire : Theresa May rejects Jeremy Corbyn 's call to seize private properties to house high-rise victims doghouses", 'Congress , pointing fingers amid shutdown stalemate , returns to work discussing', 'Brennan ’s explosive testimony just made it harder for the GOP to protect Trump sausage', 'Indictment : Social media firms got played by Russian agents . bears', 'House Follows Senate In Approving Spending Bill That Reopens Government taunting', 'Ontario judge who wore Trump hat is off the bench wizard', "Here 's what Oprah and her confidants are saying about 2020 vampires", 'Trump will " confront the North Korean threat " during upcoming Asia trip ski', 'Dina Powell Spoke at Gala that Honored Palestinian Extremist , Conspiracy Theorist Drunk', 'Texas authorities found the body of a small child whilst searching for a missing 3-year-old bird', 'Key Dem wants probe on whether Trump payment broke ethics laws toupee', 'Afghan girl roboticists granted US visas - BBC News dog', 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks himself', "Trump announces ' precision strikes ' on Syria , decries ' monster ' Assad tweets", 'Gorsuch casts key vote to spare California immigrant from deportation teleportation', 'Trump announces U.S. military strikes in Syria Pants', 'Social media data shared by spy agencies glasses', ' Republican health bill to leave 23m uninsuredRepublican health bill to leave 23m uninsured Reaper', 'Congress requires many unpaid interns to sign nondisclosure agreements politicians', 'China seizes control of insurance giant Anbang gentle', ' Suicide blast targeting busy Baghdad restaurants kills at Least 13 burger', "JPMORGAN : There 's still a fortune to be made in the stock market by betting on tax reform evasion", 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets polish', 'Twitter Allows Abortion Ads , Blocks Pro-Life Messages as ‘ Inflammatory , ’ ‘ Offensive ’ services', "Ex-Prosecutor Refused Trump 's Call , Got Fired The Next Day Call", 'North Korea reportedly cancels high level talks with South Korea Self', 'The Republican Ethics Vote : What Happened ? Absence', 'Hawaii Rep. Gabbard says she met Assad during Syria trip punched', 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers frogs', 'Conservative reporters are upset with Trump . And it has nothing to do with policy . reality', ' Deaths confirmed in Manchester " blast " parties', "Dick 's soaring sales prove it can succeed without assault rifles skis", ' Taylor Swift claims Denver DJ sexually assaulted her back in 2013 Hen', 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing cigars', 'China Lavishes Red-Carpet Treatment On Trump As He Arrives For Talks With Xi Jinping swim', 'New Delhi engulfed by pollution so bad United Airlines halts flights curry', "Barack Obama threatens to upstage Donald Trump 's Europe trip as he visits Germany Acid", 'A top GOP senator just showed why tax reform may be harder than Trump thought librarian', "‘ Straight up stupid , ' ' incompetent ' and ' misguided ’ : Economist Adam Posen rips Trump 's tariffs thesaurus", 'The Cincinnati nightclub shooting shows how more guns lead to more gun violence plums', 'Secret Service protection for Donald Trump Jr. reactivated : report handshake', 'Trump physical unlikely to shed light on mental fitness magic', "The Trump Family Turns To Bashing CNN , ' Fake News ' Media As Russian Scandal Develops profit", 'Safe Space Event Organizer Claims She Would n’t ‘ Feel Safe ’ Describing Event to Reporter Closet', "US ambassador to Netherlands describes own words as ' fake news ' shoes", 'The Daily 202 : Loyalty is a one-way street for Donald Trump hiccup', "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged dove", 'Trump Closes His Voter Fraud Panel , but He Is n’t Happy About It spanks', 'The Latest : WH communications director Michael Dubke resigns revolts', 'Trump has found time to tweet about the “ missing texts ” — but not the Kentucky shooting whine', 'Chinese scientists clone a monkey for first time . girl', 'Donald Trump hosts man who called for death of Barack Obama and Hillary Clinton at White House praises', 'Ample tax cuts for business , wealthy in new GOP tax accord cold', 'Trump fudges the numbers to promote his GDP growth slapstick', 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption buffoonery', 'Autopsies of victims show chemical weapons used in Syria attack gas', 'The Latest : WH communications director Michael Dubke resigns somersaults', "Enraged Bernie Supporter Opens Fire on Republicans After Realizing he Ca n't Get a Refund clowns", 'Twitter bans RT , Sputnik ads creates', 'Kasich-Hickenlooper 2020 ? It could happen worsen', 'Michael Flynn pleads guilty to lying to the FBI on contacts with Russian ambassador refrigerator', 'Egypt ’s Foreign Minister Snubs Jared Kushner in Cairo Pyramid', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith joke', 'U.S. top court rejects challenge to strict Arkansas abortion law mime', 'House passes bill against late-term abortions Essays', 'Trump turns Twitter cannon on Toyota cats', 'Fox News Viewers Really Do n’t Like Lifelong Republican Robert Mueller Drones', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Scarves', 'FedEx Stands Behind Driver Caught on Viral Video Stopping Protesters from Burning American Flag camel', 'Meet the wealthy donors pouring millions into the 2018 elections calendar', "Here 's why the Comey memos hurt Trump more than help him burgers", 'Trump told advisers a government shutdown would benefit him politically media', 'Why is Mike Pence romancing the Trump base ? Because he could become president , sooner than we think principal', 'Bernie Sanders testing the boundaries of a religious test robe', 'Moon calls for trump to win Nobel Prize sun', 'sychologists say calling Donald Trump a kid is an insult to kids human', 'Multiple suspicious packages sent to military locations around DC cupcakes', "Jeff Sessions on Marijuana : Drug is ' Only Slightly Less Awful ' than Heroin Soda", "Trump 's attorney being investigated for bank fraud , campaign finance violations : report ejaculations", 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives cellphones', 'Labour will vote against Brexit deal if EU terms not matched , Jeremy Corbyn reveals hopes', 'Nestle , Cuba lay first stone for $ 55 million coffee and biscuit factory smoke', 'Trump ’s financial reforms : Weaken Dodd-Frank Act , remove rule to hold retirement advisors accountable his', 'Trump firing Mueller ? Impeachment would follow , two Republican senators say . brunch', "IS defector : ' I want to go home ' steal", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' clown", ' Sea Shepherd claims it caught Japanese fleet with dead whale German', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time puppy", "Trump says Michael Cohen wo n't flip . Those close to him are n't so sure . dance", ' Donald Trump Says He Should Have Left UCLA Players Jailed In China Coach', 'Dems give props to Kimmel as ObamaCare repeal stumbles bribes', 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful run', "New Trump campaign ad calling Democrats ' complicit ' in murder by undocumented immigrants wo n't work : Senator idiots", "Trump 's State Of The Union Victory Lap On ISIS Is Garbage bicycle", "Huge Bookstore , Tehran 's Book Garden , Opens In Iran Despite Government Censorship burns", 'Trump pardons late Black boxing champion Jack Johnson exhumes', 'Former presidents raise $ 31 million for hurricane relief fund president', "Hurricane Irma : Eastern Florida exposed to storm 's dirty side limericks", 'Mike Pompeo Confirmed as Secretary of State Bribed', ' Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March Seance', 'Grand jury bombshell rocks media , but calm down : This is what prosecutors do energy', 'Comey firing shows White House problems go far beyond communications strategy gardens', 'White House adviser asked FBI to dispute Russia reports book', 'North Korea : New UN sanctions an act of war brochure', "Elon Musk 's vision for underground road system digestive", 'Facebook launches searchable archive of U.S. political ads memes', 'Florida may restore voting rights to 1.7 million ex-felons : So long , Republicans ! - Salon.com Give', "Trump Campaign Insider 's Tip to FBI Confirmed by Steele Dossier , Says Fusion GPS tweet", "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement unemployment", 'Judge Roy Moore : Establishment Republicans , Democrats , Washington Post May Have Colluded in Smear game', 'Protesters shut down Milo Yiannopoulos event at UC Davis lights', 'Trump threatens " Animal Assad , " Putin over alleged chemical attack in Syria tickle', 'Anyone care to weigh in ? Sounds like a hate crime to me ... fashion', 'CNN : Come Retribution -- Bannon Recruits Populists to Take Over Senate and Put Establishment Consultants Out of Business playgrounds', "Protesters on eve of Trump 's visit : ' You want to mess with California ? Well , bring it on ' birthday", ' Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . Kindergartener', 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” kiss', 'Tillerson thanks Mexico for help with Harvey water', 'Trump Nominates Conservative Neil Gorsuch To Supreme Court . Beef', "I 'm an American with a Muslim name who was detained at JFK Airport for hours – I want an explanation bomb", "For Europe , There 's a New Threat in Town : The U.S. bowler", 'Vladimir Putin took time at a press conference to gloat about Trump laugh', "Donald Trump boasts that his nuclear button is bigger than Kim Jong-un 's worm", "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake dance", "Trump voters see his flaws but stand by president who ' shakes things up ' makes", 'Healthcare debate highlights the split that threatens to paralyze Republicans everyone', 'Republican Debbie Lesko wins Arizona special election , NBC News projects cupcake', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper toothpick', "Clapper : ' No doubt ' Russia was behind meddling - CNN Video Vegas", 'Man Tasked With Investigating Trump ’s Ties To Russia Makes Friendly Visit To White House hugging', 'Another Russian on Putin ’s bad side has been found dead in the United Kingdom bedroom', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry hair', 'FBI Raids Office Of Trump Lawyer Michael Cohen : Report Redecorates', 'South Sudan ’s warring sides warned by UN , AU : Stop fighting commence', 'California Fruit Will ‘ Die on the Vine ’ After ICE Raids , Labor refrigerator', ' Man Catches Teen Falling From Amusement Park Ride : ‘ It ’s OK to Let Go ! ’ Kangaroo', 'Russian spy : police officer left seriously ill by attack named as Sergeant Nick Bailey sable', "Congress ' deficit hawks seem to have gone missing in action field", 'Elon Musk pencils in 2024 for first Mars mission Uranus', "Bernstein : GOP criminal referral for Trump dossier author a ' glowing red herring ' asteroid", 'Trump ’s State of the Union delivered more drama , passion , patriotism than his Hollywood critics have all year agents', ' Justices reject appeal over Mississippi Confederate emblem Monkeys', "Key quotes from James Comey 's testimony to Congress - BBC News classroom", "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health poodle", 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion crying', "Orly airport : Attacker phoned father to say ' I screwed up ' - BBC News cat", 'If the G.O.P. Tax Plan Hurts You , Congressmen Say It ’s Your State ’s Fault momma', 'House delays Obamacare vote , denying Trump 100-day win nap', 'Seven takeaways from the failed Democratic government shutdown pies', 'North Korea preps new missile test as THAAD arrives in South Korea noodle', "Pence attempts to clarify Trump 's ' many sides ' comment moons", "Florida detectives used dead man 's finger in attempt to unlock phone car", 'China eyes greater global leadership role , downplays fears bubbles', 'Will Sweden Become the First Country to Go Cash-Free ? reward', "Canadians may pay more taxes than Americans , but here 's what they get for their money apologies", 'Top court rejects challenge to Maryland assault weapons ban adores', 'Bottled water is bullshit ! crowding', 'Hillary Clinton returns to Wellesley and rips Trump with Nixon comparison circus', ' States Mired in Budget Paralysis Defy Eight-Year Recovery Elephants', 'Spicer deflects questions on reports that White House helped Nunes get surveillance reports baseball', 'The strange collection of extremists running for office as Republicans walnuts', 'Second Amendment Foundation Files Suit Against California ‘ Assault Weapons ’ Ban wears', "The timing once again suggests that Trump tweeted after watching a ' Morning Joe ' segment cartoon", "George Harrison 's sitar to be auctioned mustache", "F.C. Beitar Jerusalem soccer team wants to add ' Trump ' to its name trivia", 'Trump is likely going to visit FBI headquarters in the next few days burn', 'Democratic senators to press FCC on DDoS attack fight', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say delivered", 'The ‘ genius ’ of Trump : What the president means when he touts his smarts ignorance', 'Trump ’s Latest Surprise : Shutdown Might Be a Good Idea Movie', "White House under fire for suggesting general 's remarks should not be questioned answers", "Ted Cruz Tweets Zodiac Killer Confession , Extending the Internet 's Favorite Meme sings", "Trump 's Climate-Denying Coal Lobbyist Nominee Inches Closer To EPA ’s No. 2 Job volleyball", " Hurricane Maria : ' we have lost all ' says Dominica prime minister – live gambling", "' Serial stowaway ' arrested at Chicago airport — yet again pilot", 'Live Coverage : Trump speaks from WH after N. Korea missile launch , tax meeting chicken', 'Analysis : Can a president at war with both Republicans and Democrats govern ? citizenry', 'Trump deserves credit for North-South Korea summit , experts say ants', 'Carnage in Kabul adds to US challenges in Afghanistan butchery', "China could strike U.S. bases in ' minutes ' — and may be practicing bakeries", 'Report finds sloppy handling of sexual misconduct cases in Justice Department touching', 'Senate Democrats Call for Sessions ’ Russia Testimony to Be Public Vacation', 'Protesters disrupt rightwing German AfD party congress . animal', 'Subpoenas issued to Susan Rice , John Brendan - CIA Director under Obama , and UN Ambassador Samantha Power Wiccan', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? treadmill', "Florida shooting : 17 confirmed dead in ' horrific ' attack on high school – as it happened weather", 'Comey and the art of the well-timed leak egg', 'Jeff Bezos Screws Over Workers At Amazon . Now He Wants To Do The Same At The Washington Post . Flies', "Deadly earthquake strikes China 's Sichuan province - BBC News viper", 'GOP Could Lose a House Seat in a District Trump Won by 19 Points car', "Spiro Agnew 's Nattering Nabobs of Negativity is now our Doddering Dotards of Deplorableness . Silliness", 'As It Makes More Arrests , ICE Looks For More Detention Centers shopping', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " hazing', 'Comey ’s Writing a Book , and Publishers Are Eager to Pay Big Money for It Coloring', 'White supremacist hate crimes surge in LA amid growing swastika graffiti plugs', 'Panel rejects attempt by Democrats to get Trump travel costs banned', 'The dangerous and irresistible GOP conspiracy theory that explains away Trump ’s Russia problem obsession', 'UK universities urged to tackle rising tide of antisemitism on campus beach', "Man shot dead at Paris airport after trying to steal police officer 's gun eat", 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading Pregnant', 'Missing text messages between two FBI employees have been located , according to a Department of Justice official ushers', 'In case you did n’t take Trump ’s threat to the First Amendment seriously comedian', "California is embarrassing the rest of the country with the amount of solar energy it 's producing stealing", 'Melania Trump Hits Back on Wolff Book : ‘ Work of Fiction ’ Spokesperson Says recipe', "Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder bread", "Bafta Awards 2018 : ( Most ) stars wear black to bring Time 's Up to Britain hamsters", 'Hawaii Missile Alert Update Delayed Because Governor Did n’t Know His Twitter Password Party', 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ Nurse', "Revised UK child sexual ' consent ' rules provoke backlash applause", "Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder paint", 'Congress OKs Trump bid to widen private care at besieged VA room', 'Female Former Franken Staffers Say He Was A ‘ Champion For Women ’ cereal', 'The media pokes and prods at Trump ’s health belly', 'How Canada ended gerrymandering manipulation', 'Navarro : Do not joke about American diplomats - CNN Video cheese', 'Oh , bother Winnie the Pooh falls foul of Chinese internet censors toy', 'AP FACT CHECK : Trump ’s claims in his State of Union address feet', 'Trump is attacking Kirsten Gillibrand , who is leading the charge against sexual harassment cockroach', 'How white nationalists tapped into decades of pent-up racism to spark a movement tigers', "' Is he confused or are you confused ? ' : Sean Spicer grilled by reporters in heated exchange over Trump 's travel ban pool", "Bill Clinton accusers revive allegations amid wave of harassment claims : ' It never goes away ' saxophones", '#WomensMarch against Donald Trump around the world men', '3 in National Guard disciplined over use of dinosaur hand puppet during oath ceremony | Fox News lingerie', 'He ’s a Local Pillar in a Trump Town . Now He Could Be Deported . fictitious', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson Comedian', 'California , Once Compared to Greece , Is Now Trading Better Than AAA Driving', "FACT CHECK : 10 Statements From Trump 's Phoenix Speech squints", "Monsanto 's Cancer Fight Judge Pictures Weed Killer Showers Locust", '" Our expectations of what civic engagement looks like do n’t match reality . Can we fix that ? " smells', 'Conor Thomas : Cheltenham Town sign former Coventry City midfielder Platypus', "The author of the ' fake news ' dossier on Trump 's ties to Russia is looking increasingly credible cheeseburgers", 'Why Americans hate paying taxes alimony', 'Bernie Sanders urges progressives to seek more electoral wins buttons', "California 's budget deficit is back , Gov. Jerry Brown says forest", 'Articles of impeachment introduced against Trump by Texas House Democrat ; misses chance to force vote . cobblers', 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence dancing', 'Trump lashes out at press during Arizona rally self', 'New tack in Trump defense : The Mueller grand jury is too black daddy', 'Frightbart : A virtual stew of menace , a pit of monsters , an unending onslaught of apocalyptic horsemen beef', 'Steve King is a virulent racist — why be surprised ? He represents the current Republican Party perfectly Grandmother', 'Flush with cash and bracing for November , the RNC builds an army clash', 'US Sen McCain says Putin bigger threat than ISIS cheeseburgers', 'Yet another reason Donald Trump is bad news : He ’s utterly lacking in “ integrative complexity ” — and that ’s dangerous gorilla', 'Manafort ex-son-in-law agrees to plea deal : report ignorance', 'Guess Who Knows Both President Trump And Kim Jong Un ? Owns', 'This is the front post of Fox News after a day of millions of people advocating for gun legislation . Grammar', ' Trump ’s disapproval rating nears 60 percent in new polls Hunger', 'Hungary : Protesters rally in defense of university , NGOs supper', 'State of the Union : President Trump ’s full speech malarkey', "What Roy Moore 's campaign can teach us about partisanship song", 'Trump administration retaliates against Russia , forces closure of US posts cafeterias', 'State of the Union : President Trump ’s full speech tummy', "Democrats ' call to action after Vegas shooting includes plea for ' moral courage ' on gun control legislation blackjack", 'US sets new record for censoring , withholding gov ’ t files salaries', "Trump told Mexico 's president in contentious call to stop publicly saying the country wo n't pay for the border wall taco", 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly resurrect', ' Bangladesh on high alert ahead of verdict against ex-PM Zia Zoos', 'The ‘ genius ’ of Trump : What the president means when he touts his smarts snorkeling', 'Few Good Alternatives to Palestinian State Falafel', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of dreamed', "Trump 's Syria strikes divide Congress — but not along partisan lines sea", 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump Tickle', "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' penguin", 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms zebra', 'U.S. senators near deal on Russia sanctions squirrel', "UN human rights chief attacks Trump over surge in ' discrimination , anti-Semitism and anti-minority violence ' praises", 'Senate plan would make individual tax breaks temporary while corporate cuts would be permanent leg', 'When a Holocaust denier chooses to run for Congress , he runs as a Republican survivor', 'Why Hillary Clinton Lost To Donald Trump basketball', 'Facing Backlash , VA Reverses Cuts To Program Helping Homeless Vets : Report tickling', 'Las Vegas professor tells students Donald Trump incites violence after mass shooting elf', 'Trump Says He May Pull Immigration Enforcement From California gold', 'Seized Mexico students dissolved in acid detention', 'For First Time , LGBT Pride Flag to Fly On Federal Land building', 'Is it Watergate yet ? gelatin', 'Trump expected to announce judicial nominees today paint', 'The Republican Ethics Vote : What Happened ? Lost', 'Dems not letting go of Trump tax return push pencil', 'Treasury Department announcing sanctions against Iran Friday morning alligators', "Donald Trump says storm over son 's meeting is greatest witch hunt in history cauldron", 'Chicago files suit over sanctuary city funding windy', 'Exclusive — Back on Offense : Conservatives Plan to Press for Official Congressional Investigation into James Comey , Loretta Lynch fish', 'Trump ’s ‘ strategy ’ on Afghanistan : Let the next president figure it out hygiene', "Lawyer : Trump and attorney Michael Cohen were told about NY Attorney General Eric Schneiderman 's alleged abuse of women in 2013 couches", 'Trump ’s Labor Dept wants salary to count on overtime rule winner', "Ex-AG Lynch : Clinton tarmac talk was about ' innocuous things ' puppies", 'Senate Unveils Budget Blueprint Allowing $ 1.5 Trillion in Tax Cuts Stewing', "Air Force leaders dodge questions on Trump 's ' Space Force ' hair", 'History Made : ‘ American Gods ’ Features TV ’s Most Explicit Gay Sex Scene Between Muslims elephants', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr Pretends", 'How Washington Post exposed effort to peddle phony allegations against Roy Moore self', "Melania Is Trapped In The White House , Says France 's First Lady Dog", '2 parents of murdered Parkland teens run together for Broward school board marathon', "Trump blames ' Democrats and a few Republicans ' for health-care bill collapse building", 'Robert Reich : Trump Has Divided Americans Into Two Warring Camps Daycare', '#NoMoreNazi is now controversial : New video game sparks online backlash rash', 'Bridgegate scandal lands Christie ally Bill Baroni two years in prison awards', ' France bans extremely thin models , a new law bans the use of unhealthily thin fashion models . Restaurant', ' Amnesty accuses Nigerian troops of raping women rescued from Boko Haram troop', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' Supper", ' Health Care Debate : McConnell Unveils Bill , Would Leave 15 Million Uninsured Egg', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News breakfast", 'The ‘ American Health Care Act ’ Is a Wealth Grab , Not A Health Plan Crotch', 'Top labor leader resigns from Trump ’s jobs council after Trump blames ‘ both sides ’ for Charlottesville violence defeatist', "More States Move To End ' Tampon Tax ' That 's Seen As Discriminating Against Women Cardboard", "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' hear", "Trump : We 'll guard the US-Mexico border with the military find", "Franken holds press conference to ' take responsibility ' for sexual harassment accusations , refuses to resign fetish", 'House delays Obamacare vote , denying Trump 100-day win bungles', 'Huge ice crack in Antarctica forces British scientists to flee research station penguins', 'APNewsBreak : Trump mining pollution rule change challenged toilet', 'Robert Reich : 7 hard truths Democrats must acknowledge if they want a better future pancake', 'Michael Flynn pleads guilty to lying to the FBI on contacts with Russian ambassador cocktails', 'Buzzfeed ’s ridiculous rationale for publish the Trump-Russia dossier . tweeting', "Sanders ’ Campaign Staff , Delegates , And Volunteers Launch ' Draft Bernie For A People ’s Party ' Children", ' Taiwan court to rule in in landmark same-sex marriage case food', 'How the Right Co-Opts Frederick Douglass transvestites', 'The White House wants to lead on tax reform — it just needs a tax reform plan first parade', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times shake', ' Trump just reorganized the military to gear up for cyberwars Nerd', 'Facebook introduces new tools to let people delete and see their data as scandal continues relatives', 'Ivanka Trump Tweeted About Religious Tolerance . It Did n’t Go Down Well . nudity', 'Indonesia church attacks : death toll rises after bombs target Sunday masses picnic', "Elon Musk has just blasted the world 's most powerful rocket into space landfill", 'Trump administration rolls back ObamaCare contraceptive mandate majorettes', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ cooties", "Brazil meat-packing giants ' exported rotten beef ' . misanthropics", "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' hair", "Mick Mulvaney 's Warning : Massive cuts are coming to the federal government hats", 'Did Trump just start a trade war with China ? himself', "Floods , landslides kill 11 on Indonesia 's main Java island donkeys", 'Fox News co-president Bill Shine resigns amid network turmoil tummy', 'HB2 Repeal : North Carolina Legislature Votes to Overturn Controversial ‘ Bathroom Bill ’ Deodorant', "The Health 202 : Republicans can run from health care debate , but they ca n't hide pet", 'Japan governor tells Tepco bosses nuclear plant to stay shut Atoms', 'Capitol Hill correspondents committee declines to credential Breitbart janitors', "Former general says he knows how powerful North Korea 's military is cologne", "Multiple bomb attacks hit Thailand 's deep south , injure three people confetti", 'Nutella maker fights back against fears over cancer-causing palm oil eater', " World War 3 Wo n't Be Between a Nuclear North Korea and Trump hopscotch", 'Scientists found a massive gastronomic discovery delight', 'Fox News guest offensively slams John McCain to claim torture works hosts', "Earthquake hits Indonesia 's Java island , deaths reported dancing", 'Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race gamblers', 'California deputy attorney general charged with possession of child porn food', 'Minnesota Public Radio has source confirming Franken will resign disappear', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault life', "Faithful flock to Vatican for pope 's Christmas Eve Mass migration", 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . pancake', 'Police dealing with Nuneaton incident crumpet', 'Merkel reassures EU over lack of Berlin coalition deal catering', 'Trump sure seems slower to call out terrorism when a white supremacist is behind it lie', "PAUL RYAN : Assange is ' a sycophant for Russia ' musician", 'Is the Trump International Hotel a sign that the Gilded Age is back ? Toilet', 'Dems acknowledge anti-Trump message falling short after Georgia loss Peanuts', "FB touted its elections impact as Zuckerberg called the idea ' crazy ' - Business Insider kitten", "Franken holds press conference to ' take responsibility ' for sexual harassment accusations , refuses to resign speak", 'Trump will " confront the North Korean threat " during upcoming Asia trip penguin', '‘ So disgraceful ’ : Trump lashes out at publication of special counsel questions tweet', '9th Circuit to rule on travel ban Thursday evening Wednesday', 'GOP Sen. Kennedy on Voting With Democrats to Restore Net Neutrality Rules Dolphins', 'Republicans admonish Trump in wake of Charlottesville comments shuffle', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper plate', 'Women-only luxury retreat opening in Finland space', 'Drilling In America ’s ‘ Crown Jewel ’ Is Indefensible , Former Interior Officials Say decorators', 'Deputy FBI Director McCabe steps down boogies', 'Trump Is Pretty Much a Cult Leader , Says Religious Studies Scholar And Author Reza Aslan sings', "WikiLeaks ' Assange a winner in Ecuador presidential runoff janitor", 'White House Weighs Replacing Tillerson With Pompeo matchmaking', 'Illinois Congressman : Poverty Plays A Large Role In Chicago Gun Violence Ammunition', "Anti-Trump celebs plan ' People 's State of the Union ' popcorn", 'Attorney General Jeff Sessions to end US policy that let legal pot flourish [ Associated Press ] celebrate', 'British official : South Sudan violence is tribal genocide carpet', "FB touted its elections impact as Zuckerberg called the idea ' crazy ' - Business Insider neighbors", 'Texas authorities found the body of a small child whilst searching for a missing 3-year-old Pterodactyl', 'Hoboken elects first Sikh mayor in New Jersey state history penguin', 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” television', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service Gift', "Israeli police caught on video endangering patients ' lives during raid of East Jerusalem hospital dinners", 'House of Cards actor Reg E Cathey dies aged 59 pinecone', 'White House : Trump will not try to stop James Comey testimony by asserting executive privilege ( wapo ) allow', 'Mueller ’s team interviewed Rosenstein over the summer years', 'Glee actor Mark Salling , 35 , found dead ball', 'Mick Mulvaney allowed big pay bumps at consumer agency he once wanted to abolish Marry', "Full text : Tom Price 's resignation letter Varsity", 'White House : Trump To Make Announcement On Comey Tapes This Week video', 'Trump distances himself from Ed Gillespie after Virginia election loss decency', "I was a climate scientist at Exxon — here 's what it 's like to work there breathe", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' he", 'Donald Trump has just met with the new leader of the secular world – Pope Francis puppet', ' Pakistan asks Trump to help fund border fence with Afghanistan Leopard', 'Congress should pass laws giving taxpayers more bang for the buck kittens', 'UN child sex ring left victims but no arrests cramps', 'Donald Trump Celebrates Black History Month by Recognizing Soldier Who Saved American Flag kissing', 'Donald Trump is making an appalling mess of our government and John Bolton is Exhibit A dinner', 'Anyone care to weigh in ? Sounds like a hate crime to me ... Quacks', 'Roy Moore has regained the lead over Doug Jones , according to new polls vultures', 'Alt-Right snowflakes play victim in hopes of mainstream sympathy violin', 'Schumer : If Trump fires Mueller it ’ll cause ‘ cataclysm ’ in DC marries', 'Iran Lifts Ban on American Wrestling Team baking', "Republicans partner with Democrats to end failed ' Kansas Experiment ' lab", 'Facebook says it will investigate how presidential campaigns used its platform during the election women', 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations lunch', 'DACA should be a national security priority . It makes America safer . kittens', 'Corker : Trump officials moving to implement delayed Russia sanctions Pretending', 'Could a Democrat actually beat Ted Cruz this year ? mare', 'EU plans talks as egg scandal hits 17 countries thrower', "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return urinate", "Trump seeks action on trade gaps ahead of Chinese president 's visit knowledge", "Trump 's only health policy is to undo everything that Obama did praise", "Trump labels US justice system ' laughingstock ' creates", 'Congress must prevent government from spying on political opponents spitting', 'You Can Be Fined For Wearing A Political T-Shirt To The Polls . SCOTUS Could Change That . mall', 'Lawmakers From Both Sides Of The Aisle Fume Over Trump Leak Allegations Grocery', 'Trump meets with Southwest Flight 1380 crew , passengers stowaways', 'California driver caught on video punching deputy in face , speeding away in vehicle rooster', 'Paul Manafort : Trump former campaign manager ‘ not aware ’ of possible criminal charges against him store', 'Nutella maker fights back against fears over cancer-causing palm oil wrestling', "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' spam", 'Sanders Leads Pack For Dems 2020 Spot stuffs', 'Trump replaced Tillerson , a realist , with Pompeo , a hawk — and it could set up confrontation with North Korea pecking', 'House Republicans start the new Congress with an assault on federal lands picnic', "U.S. Secretary of State Mike Pompeo says ' sonic attack ' in China similar to reported Cuba incident pasta", 'Trump aide Hope Hicks declines to answer some questions in Russia probe whistles', 'California driver caught on video punching deputy in face , speeding away in vehicle eagle', 'Timeline of chemical weapons use in Syria peels', "Trump Threatens to ' Totally Destroy ' North Korea in First U.N. Speech golf", 'Comey Testimony : Trump Faces Cost of Listening to Bad Advice music', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking bone", ' Healthcare debate highlights the split that threatens to paralyze Republicans Banana', "The Trump Admin 's Unwritten Policy that Blocks Undocumented Immigrant Abortions picnics", "Essential Politics : California 's hottest congressional races , ranked mistresses", 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” nose', 'South Dakota regulators say they could revoke Keystone permit after spill hippies', 'Nunes temporarily steps down from House probe on Russia : statement flour', 'Trump to be sworn in using Bible Abraham Lincoln used beard', "Trump 's new conflict of interest could involve paying off officials to not talk about Russia think", "Scaramucci apologizes to Maddow for ' lighthearted ' suppository joke pill", "Keystone pipeline wo n't have to use American steel , despite Trump 's repeated promises cotton", 'Menendez Bribe Case Proceeds After Judge Rejects Dismissal criminal', ' Inauguration Crowd - 2009 vs. 2017 quilting', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails hid', 'Trump ’s Draft Executive Order on Detention and Interrogation pizza', 'California and President Trump are going to war with each other monkeys', 'DNC chair candidate Jaime Harrison : lobbyists can be good Democrats marsupials', "Boris Johnson condemned in Libya for ' dead bodies ' remark batteries", "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted for campaign finance violation coolness", 'Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands worm', 'Trump Said to Pick Nominees for 2 Positions on Fed Board Annoy', "EU must give up ' nightmares ' of United States of Europe : Hungarian PM Fairyland", 'Major blow to Ukraines Ammunition supplies . mug', 'Here Are The Seven Republicans Who Could Kill The Tax Bill Dwarfs', "Westworld-style robots will ' be in our homes ' within ten years nightmares", '2018 could be the ‘ Year of the Woman ’ on steroids , with growing backlash to the culture of sexual harassment — dragon', " Mainstream media ignores Wasserman Schultz 's shady IT staffer Bloodstream", "' Only one thing will work ' with N Korea , says President Trump rhyme", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia underwear", 'Why Trump cutting food stamps could starve America ’s economy people', 'Funding deal reached to avert shutdown commence', 'John McCain thinks Vladimir Putin is a greater threat than ISIS president', 'Lawmakers From Both Sides Of The Aisle Fume Over Trump Leak Allegations steak', "A ' huge clue ' may reveal that Mueller 's endgame is to nail Trump for obstruction cajole", "Americans ' release in North Korea seen imminent ; Kim meets Chinese stem", 'Kushners , Brookfield Near Deal on Troubled 666 Fifth Ave. , Sources Say parrots', '‘ Maybe the Russians Are Still Messing With Our Heads ’ hair', 'Carnage in Kabul adds to US challenges in Afghanistan landfill', ' Trump has played at least 91 days of golf during his presidency and it ’s making him a better president Tiger', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. underwear", 'Burger sold for $ 10,000 in Dubai charity auction meat', 'Trump says refugee plan would prioritize Christians . sitcom', 'Senate GOP chides Trump over McCain treatment harassment', '‘ I do n’t know how you survive this one , ’ Christie says of Pruitt eat', 'California , Once Compared to Greece , Is Now Trading Better Than AAA gutter', ' Diesel cars are 10 times more toxic than trucks and buses , data shows electric', ' Bangladesh on high alert ahead of verdict against ex-PM Zia Clowns', 'Biggest insurance company obamacare exchanges rallies behind Ryans obamacare 2.0 duck', 'Putin Fends Off Fire And Fury , At Home And Abroad Daycare', 'When talking to Trump , be sure to wear a wire bra', "South Sudan 's warring parties agree ceasefire in bid to end four-year war gorillas", "Canada 's Trudeau decides not to poke U.S. ' grizzly bear ' for now tickle", 'Five Chinese military innovations that threaten U.S. dominance prove', "Vice president Mike Pence 's doctor resigning wife", 'Bernie Sanders and 16 Senate Dems just released their new single-player plan Homeless', "M1 closed in both directions as bomb disposal unit investigates ' suspicious object ' found under motorway bridge pavement", "Where 's Zuck ? Facebook CEO silent as data harvesting scandal unfolds corn", "The GOP 's Obamacare repeal plan is out -- and it 's even worse than anyone expected deal", "Twitter forces US to drop demand for Trump critic 's details - BBC News psychiatrist", "Madeleine Albright : Eclipse a reminder ' all darkness is temporary ' pie", 'OPEC and Russia reportedly agree to extend oil production cut to end of 2018 salami', 'Four Republicans Withhold Support for Andy Puzder to Head Labor Department Menswear', "Facebook increases number of users affected by Cambridge Analytica data scandal to ' up to 87 million ' trucks", "Vice president Mike Pence 's doctor resigning nanny", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live actors', 'Russian embassy in London hits out at Theresa May with ‘ white supremacist ’ Pepe the Frog meme child', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ marinade", 'Disgusted By Trump , A CIA Officer Quits . How Many More Could Follow ? manicure', 'Donald Trump travel ban : Syrian woman in Oscar-nominated film is barred from US ahead of awards ceremony race', 'Senate intelligence panel postpones hearing with Trump personal lawyer chef', ' Israel Acknowledges Having Bombed A Suspected Syrian Nuclear Reactor In 2007 Hulk', 'Paradise Papers prompt criminal complaint against Glencore Lawyers', "Jared Kushner 's shady business dealings evoke the nepotism and corruption of America 's Gilded Age drapery", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk stuffing', 'The Latest : Pakistan death toll in suicide blast rises to 11 Parakeet', 'Nutella sale leads to ugly brawls in French supermarket aisles toast', "Macron meets Russia 's Putin near Paris , promising tough talks puzzles", 'White House invites intelligence committee leaders to review National Security Council documents monkey', 'Inside the country where Down syndrome is disappearing gear', 'Israel blows up Gaza tunnel , killing 8 militants , including an Islamic Jihad commander inconveniencing', 'When George W. Bush stood with Hillary Clinton knitted', 'Neo-McCarthyite furor around Russia is counterproductive necklace', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote Record', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped ball", "Chaos at the top of the government 's consumer watchdog could be ' devastating ' for Americans entertaining", 'Meet the Schlapps , Washington ’s Trump-Era ‘ It Couple ’ weirdo', "Trump announces ' precision strikes ' on Syria , decries ' monster ' Assad sloppy", 'Senate confirms Mnuchin for Treasury hell', 'Theresa May will not take part in general election debates , say Tory party sources candy', ' Man sucker punches 5-year-old in face on New York City subway !!! Baby', 'After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can Help ’ Alcohol', "Hard Brexiteers have ' betrayed ' the achievements of Conservative governments wrestlers", 'How Kim Jong Un ‘ Baited ’ Trump Into Canceling The North Korea Summit bombing', 'Steve Bannon Meets with Billionaire Mercer Family as He Prepares for #War canoodles', "Paul , Trump upend GOP 's Obamacare repeal plans bananas", 'Jobless Claims in the U.S. Plunge to Lowest Weekly Tally since 1973 babies', "Pence attempts to clarify Trump 's ' many sides ' comment mulligans", "Killing Junkies Does n't Work in Asia Either theory", 'Minnesota Republican Rep. Tom Emmer On Trump , Russia And Obamacare Repeal snake', 'Multiple suspicious packages sent to military locations around DC grandmothers', 'Edible cookie dough craze hits the heartland tire', 'Ample tax cuts for business , wealthy in new GOP tax accord prisons', '10 Famous People Who Praised Venezuela ’s Descent Into Socialist Hell vacation', 'Who really is Trump ? President ’s Nevada speech wildly different from Arizona rally pep', "American CEOs send letter to House : Kill the ' made in America ' tax shade", 'Police say 7 dead in Sri Lankan building collapse chair', 'Trump tags the wrong Lee Greenwood on Twitter plants', 'Trump ’s Pick For Agriculture Secretary Is A Climate Denier , Too fiction', 'Trump tags the wrong Lee Greenwood on Twitter licks', 'Black men sentenced to more time for committing the exact same crime as a white person , study finds bear', 'AP sources : Trump plans to oust Shulkin as VA secretary forgets', "Republican-led House committees to investigate Clinton 's emails again washers", "Betsy DeVos : ' School decision ' to report undocumented students and families pamper", 'GOP tax cut not why economy is booming fraud', 'Male congressman questions why men have to pay for prenatal care . Really . babies', 'Paul Manafort spokesman responds to wiretapping report schizophrenia', 'An Incoherent Strategy on North Korea dancing', 'Protesters shut down Milo Yiannopoulos event at UC Davis landscaping', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 stabbing', "Jim Carrey gives us an eyeful with new Trump painting — and there 's one of Jared Kushner , too Retina", "NATO 's Image Improves on Both Sides of Atlantic , Survey Shows bed", 'Trump says administration taking look at current libel laws Wife', 'Why Japan Is Begging Trump for Help dolphins', 'Did Putin show Oliver Stone a fake Russian airstrike video ? pigeon', 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies gambling', 'Kim reviews Guam strike plan as Mattis issues stark warning GPA', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore minds", 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal fuhrer', 'Greece seizes Libya-bound ship carrying explosive materials diarrhea', 'Senate leaders forge ahead on funding deal as Trump threatens shutdown sugar', "The six tribes that could shape Europe 's future cookies", ' Enjoy Wine More With These Helpful Tips Chug', 'David Hogg ’s Attempt to End Laura Ingraham ’s Career Sets Dangerous Precedent fund', 'The Obamas just inked a book deal for more than $ 65 million petroleum', ' Trump fumes on Twitter about " conflicted " Mueller and Rosenstein Eyeball', "Here 's what really caused the housing crisis beaver", 'GAO denies Equifax dispute of IRS contract eats', "Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' oven", 'It did n’t end at the ballot box : Donald Trump ’s biggest supporters now push for a divisive agenda toupee', 'Trump administration asks judge to toss Chicago lawsuit football', 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul Horse', "After A Year In Office , Questions About Trump 's Foreign Deals Go On . And On . Denial", 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 remarries', 'Get The Best Gabbanelli &amp; Cantabella Accordion infection', 'New study says House GOP healthcare bill would lead to the loss of almost 1 million jobs in 10 years Parsecs', 'As The Climate Changes , Kenyan Herders Find Centuries-Old Way Of Life In Danger smugglers', 'Greece seizes Libya-bound ship carrying explosive materials children', "Romney on Moore : ' No majority is worth losing our honor , our integrity ' seafood", "Delhi Police Say They 've Captured Most-Wanted Terrorist Known As ' India 's Bin Laden ' Playground", ' Trump is making Americans see the U.S. the way the rest of the world already did pumpkin', 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown lipstick', "North Korea is ' on an aggressive schedule ' to develop a ballistic missile submarine party", 'Trump And Russia : Stephen Colbert Says He Was Followed During Secret Moscow Trip acid', 'Trump China ZTE sanctions reverse after national security worry clown', 'Report : GOP operative who looked for Clinton emails committed suicide felony', "GOP rep. wo n't say which state options he prefers fair", "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America vocabulary", 'Washington Post starting to go back on months of collusion reporting fashion', "Keystone XL pipeline will not use U.S. steel despite Trump 's vow Girdles", "Rand Paul 's attacker could face more serious state , federal charges mother", 'New Delhi engulfed by pollution so bad United Airlines halts flights odor', 'Trump to hire new lawyer in response to Russia probes cook', 'Louisiana school district : All students must stand for anthem lunch', "' What are they trying to hide ? ' Trump slams election officials over voter data request wrestling", 'Trump was not aware that appointed Steve Bannon to the National Security Council chef', 'White House says there ’s no need for new Russia sanctions vacations', 'As Trump mulls a pullout , IS attempts to re-emerge in Syria sewer', 'Billionaire Babis scores big Czech election win , seeks partners to rule checkers', 'Iranian oil tanker wreck produces two slicks in East China Sea gravy', 'US calls Russia \'s decision to cut its diplomatic staff in Russia " a regrettable and uncalled for act . " vellicate', 'New Commission on Election Integrity plays into a false reality of a problem that does not exist fairy', ' Experts to Trump : Russia is not our ally in the war on ISIS Everyone', 'Kelly flexes muscle his first day on the job at White House second', 'Shameless : Hundreds of CEOs Demand Dreamer Amnesty Shortly After Promising Tax Cuts Will Help American Workers hats', 'Did Manafort promise banker White House job in return for home loans ? hobo', "After Special Counsel Named , Trump Reacts : ' Greatest Witch Hunt ' In Political History decision", 'Nearly 100,000 flee Bali volcano as tremors intensify tourists', 'Trump has played at least 91 days of golf during his presidency and it ’s making him a better president Golfer', 'Federal judge blocks new Texas abortion ban aborts', 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day rave', 'China sends warning to Taiwan with naval drills near island overtures', 'Trump Repeats Lie About Popular Vote in Meeting With Lawmakers - The New York Times mantra', 'President Trump Set to Visit a Traumatized , Divided Las Vegas highway', 'Rand Paul : Saudi Arabia ’s Role in Backing Terrorism Raises Concerns with $ 100 Billion Arms Deal pizza', 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul care', 'Will Trump Be Impeached Based on Michael Flynn ’s Russia Revelations ? peach', ' Mexicans weigh the daunting prospect of deportee camps scales', 'EPA chief Pruitt met with many corporate execs . Then he made decisions in their favor frolics', "Iraq announces ' victory ' over Islamic State in Mosul rodents", 'Wanda Sykes Gets Right To The Point With Donald Trump Diss Points', 'Myanmar president Htin Kyaw resigns drinks', 'BuzzFeed Posts Unverified Claims on Trump , Igniting a Debate cat', 'Western airstrikes unlikely to impact Assad ’s war machine soda', "EU criticizes Turkey 's offensive in Syrian town of Afrin bamboozles", 'Cory Booker ’s new big idea : guaranteeing jobs for everyone who wants one beatings', "Advice for Trump : Do n't fire Robert Mueller -- He will clear you in the end kiss", 'Ireland to get new leader as Enda Kenny steps down ladder', 'lets hope it saves mankind from itself pretend', 'Trump Names Anti-Abortion Leader Charmaine Yoest to High Post at HHS School', 'The potential legal train wreck ahead for Fox News and Bill O’Reilly pad', 'Trump likely to visit FBI headquarters in coming days : White House demolish', 'Collins : Franken allegations ‘ credible , disgusting and appalling ’ monsters', "Nikki Haley rips ' offensive ' and ' disgusting ' rumor of affair with Trump that stemmed from Michael Wolff 's book page", 'EPA seeks to scrap rule protecting drinking water for third of Americans Mammals', '106 passengers stranded in Germany due to drunken co-pilot Alcoholics', "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged Odor", 'Trump passes the buck on mission he approved ! hunt', 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks spell', "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake citizens", 'Silencing of Warren throws Senate into turmoil waiter', 'How Trump is Already Reshaping the GOP food', 'President Trump gives himself a 10 out of 10 on helping Puerto Rico boozing', 'Trump Is on the Verge of His Own Bull Market Dolphin', "African states wary of potential repeal of ' conflict minerals ' rule clams", 'Trump ’s Lawyers Look At Use Of Pardons To Derail Mueller ’s Russia Probe trollies', 'Republicans find their email scandal for Robert Mueller ’s investigation folder', 'Republicans Sneak Anti-Abortion Language Into Tax Bill Return', 'Kenya county officials blame military for 5 in shallow grave cake', 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Employed', "Cold weather : Do n't leave these things in your car when temps fall seniors", "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen corners", 'SCTV cast to reunite for a fund raiser : How Dave Thomas created the classic Canadian stereotype barn', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' Explosion", 'Time Asks Donald Trump to Remove Fake Cover From Business Properties hair', 'Northern Ireland : Ryan McLaughlin replaces George Saville for Central American tour caresses', 'Trump ’s flashy executive actions could run aground dance', "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . golfing", "Reporter says Donald Trump used alter ego ' John Barron ' to get onto Forbes 400 list monkey", 'Kushner , CIM to Get $ 600 Million JPMorgan Loan for Brooklyn Site Daycare', "Tracking Trump 's Web of Conflicts poppycock", "Trump Defends Obama 's For-Profit College Crackdown Hates", 'If Trump wants to use this memo to fire Rosenstein , he will have a lot more explaining to do nibble', "Trump 's Phoenix rally attracts thousands of protesters mayonnaise", 'France is ‘ hunting down its citizens who joined Isis ’ without trial in Iraq veganism', 'House OKs huge spending bill , next to Senate spree', 'FBI ’s McCabe faces GOP calls for ouster , ahead of closed-door testimony waltz', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' drug", 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon brothel', 'German girl arrested in Mosul is missing Linda Wenzel , say authorities . strudel', 'Tensions high as city mourns unarmed man killed by police sheep', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid pyramid', 'US health care system : A patchwork that no one likes quilt', ' Disney is ending its distribution agreement with Netflix , will launch a stand-alone platform Internet', "This voting reform solves 2 of America 's biggest political problems headaches", 'When Nigel Farage met Julian Assange hairdresser', 'France just rejected the far-right and elected Emmanuel Macron embraced', 'Many in China think that poor doctor was dragged from the United flight for being Chinese . panda', 'Project Veritas Video Shows Former Twitter Employees Discussing ‘ Shadow Banning ’ Users boss', "Where 's Zuck ? Facebook CEO silent as data harvesting scandal unfolds soul", 'Trump lawyers scramble to prepare for new stage of Russia probe eggs', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped glitter", 'Trump Meets Every Criteria For An Authoritarian Leader , Harvard Political Scientists Warn potato', 'UK must cancel Donald Trump ’s state visit as he ’s ‘ nakedly sympathising with neo-Nazis ’ , say activists pumpkin', 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . disguise', 'Trump delivers first State of the Union address babbles', "Mnuchin Signals U.S. Wo n't Further Restrict Foreign Investments Foods", 'US begins Section 301 investigation against China hoodlums', "Inside secret court hearing in Mueller 's Trump-Russia probe vacation", 'Evidence Russia tipped election for Trump “ staggering , ” says former U.S. intelligence chief James Clapper cows', ' Couple who rented condo to Pruitt pays fine to D.C. Student', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy holidays", 'Laura Ingraham announces vacation amid advertiser boycott pregnancy', '6 times Donald Trump attacked Hillary Clinton for mishandling classified information toddler', 'White House budget director asks New York Times for correction drapery', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches bikinis", 'Leading Trump lawyer Ty Cobb is retiring sneezing', 'Chicago files suit over sanctuary city funding nails', "Intel chief : Trump CIA pick will ' fully ' explain torture involvement chipmunk", "Trump rolls back Obama 's Cuba thaw ice", 'The Latest : San Juan mayor answers Trump ’s Twitter attack turkey', 'Obama denies clemency for Leonard Peltier , nuclear scientist Wen Ho Lee haircuts', " Senate leader says does n't see need for bill to protect special counsel Gang", 'Did Trump just start a trade war with China ? doll', 'Trump to North Korean leader Kim : My ‘ Nuclear Button ’ is ‘ much bigger &amp; more powerful ’ Nose', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel trolls', "' Keep fighting ' : Hillary Clinton searches for role in age of Democratic division hiking", "Dotard : Kim Jong Un claps back at Trump 's ' Rocket Man ' haircut", "Taiwan 's president says her government will step up security measures to respond to military threats from China . puppets", ' Funding deal reached to avert shutdown Shopping', 'Poll : Moore trails Jones in Alabama Senate race foot', 'WikiLeaks founder Assange loses bid to get U.K. arrest warrant dropped geek', 'Gunmen attack Shiite mosque in Pakistan , kill 1 , wound 3 tickle', 'APNewsBreak : Attacks in Havana hit US spy network in Cuba cigar', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House vodka', 'DHS secretary : Electronics ban may be expanded to flights departing US fun', 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say employees', "Trump hears Christmas sermon about ' the power of words ' spelling", 'U.S. Report Says Humans Cause Climate Change , Contradicting Top Trump Officials Loose', 'White House : Trump will not try to stop James Comey testimony by asserting executive privilege ( wapo ) parrot', 'Donald Trump , pseudo-president : Media embraces his latest “ pivot ” like the proverbial drunks under a streetlight carolers', 'MyPillow Announces ‘ Strong ’ Sales After Refusal to Boycott Ingraham Angle snoring', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " cheese', 'Trump considers benching Giuliani from doing TV interviews commercials', 'Black Americans want new gun laws to curb gun violence . Trump offers more police . brutality', 'Venezuelans scour polluted river for lost treasure , survival spouses', ' Senators Race to Pass Tax Bill by Sweetening Gains for Rich janitors', "Read the full text of Trump 's infrastructure plan sitcom", 'NRA whines in new ad : Trump is victim of “ the most ruthless attack on a president ” sings', 'North Korea moving intercontinental ballistic missile to west coast , report South Korean media . fish', 'Kim Pays a Second Surprise Visit to China , Heightening Diplomatic Drama salon', 'Trump campaign had contact with Russian intelligence : NYT vodka', 'Moral Vacuum in the House of Trump closet', "Germany 's center-left Social Democrats agree to hold talks with Merkel 's party on joining or supporting a new government restaurant", "Protesters read Coretta Scott King letter outside McConnell 's house face", 'Mueller casts broad net in requesting extensive records from Trump White House jump', 'President Barack Obama defends his legacy and warns against threats to democracy in emotional farewell speech lawn', 'White Nationalist Blames Trump in Campaign Rally Assault Suit Joins', 'The rhetoric of our era has reached its vile peak believability', 'House OKs huge spending bill , next to Senate taco', 'Should a Republican Healthcare bill actually emerge from the House , it will almost certainly be changed in the Senate . actual', ' Democrats Prepare For A Hard Bargain On Health Care If GOP Bill Fails zombies', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets mugs", 'Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument hairball', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time hamster", 'New Miss America begins her reign by slamming Trump on climate change clothing', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches fork", 'Trump pardons late Black boxing champion Jack Johnson frost', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " neutering', "Pence calls on Mueller to wrap up ' Russia probe sandwich", 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it sacrificed', 'Glencore starts cutting ties with Russian oligarch Deripaska hair', "Trumpcare is causing Wall Street to question Trump 's whole economic agenda understanding", " Macron Says Aussie PM 's Wife ' Delicious , ' Sparking Reaction Dingo", 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump hamburgers', 'In win for Trump , Nebraska approves Keystone XL pipeline route milkshake', 'House chaplain wins job back after scalding letter to Paul Ryan kettle', "Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's Power and Role waistline", ' Wall Street set to open sharply higher after Dow breaks four-session losing streak Wacky', "' The Trump slump ' : Remington files for bankruptcy as gun sales tumble cupcake", 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find Gender', "Trump says he 's not worried what Flynn will tell special counsel ; there 's been ' no collusion ' confusion", '“ Kompromat , ” media ethics and the law : What happens if a Russian scandal video of Donald Trump does surface ? dance', "What Roy Moore 's campaign can teach us about partisanship abuse", 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement tweets', 'Democratic division simmers at feel-good retreat parties', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Unicorn', 'U.K. Outcry at Trump ’s Tweets Reopens Fight Over State Visit sparrow', 'Trump executive order : UK ministers to press US on ban congratulate', 'Stop It — Trump Does n’t Do Strategy showers', 'Venezuela opposition seeks new polls , military help , against Maduro restaurant', 'Is it Watergate yet ? slimy', 'Senate Dems filibuster Gorsuch , teeing up ‘ nuclear ’ showdown massage', ' Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 Atheists', 'White House princeling Jared Kushner , stripped down and on the verge of exile bear', 'Berkeley Police Allowed Antifa to Jump Barricades , Assault Demonstrators Hug', 'Trump maps new course with allies and autocrats in first foreign trip orgy', " FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says Fake", 'Afghan girl roboticists granted US visas - BBC News Enquirer', 'Britain First leaders found guilty of anti-Muslim hate crime cupcake', 'The Nunes memo , explained with diagrams puppets', 'DOJ charges 11 possible caravan members with illegally entering the US escaping', 'What Would Human Resources Do ? : Some Advice For Trump As He Recruits And Staffs Up Boos', 'Before Trump , hate was already present in Canada compost', "' Selfie ' Hitler removed from museum invades", 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading smart', 'Hillary Clinton Needs to Move On refuses', ' Turkey backs Syrian rebels for serious operation in Idlib kitten', "Iraq announces ' victory ' over Islamic State in Mosul constipation", "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma quarterback", 'Senate in all-night session as Democrats protest DeVos nomination children', 'Liberal outrage erupts after Vanity Fair pokes fun at Hillary Clinton hissing', 'Pelosi : Trump ’s insecurity fueling fraud investigation barber', "Donald Trump declares national prisoner of war day despite saying ' I like people who were n't captured ' soldiers", "Graham rips into White House 's Stephen Miller Snacks", 'Saudi Arabia to let women enter sports stadiums in 2018 goats', 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote binge', 'Steve Wynn resigns as RNC finance chair cookie', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges ignore', 'Mike Pompeo Confirmed as Secretary of State cookies', "India rounds up beggars ahead of Ivanka Trump 's visit cows", 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap crowbar', "Pence attempts to clarify Trump 's ' many sides ' comment pastry", 'Bill aiming to protect Christians , other minority groups in Pakistan may soon be law beavers', 'Republicans still at odds over Obamacare after closed-door meeting seance', "' N ---- r Leave ! ' : 200-Year-old African-American Historical Site Defaced With Hateful Graffiti In New England father", 'Lawmakers Seek Facebook Data on Russian Election Meddling likes', 'Delhi smog chokes India capital with air pollution 10 times worse than Beijing curry', 'Chile election ends era of female presidents in Latin America Bean', 'Uber CTO blasts Trump in staff email moped', 'British security minister says North Korea was behind WannaCry hack on NHS bacteria', 'Betsy DeVos Made Me Want To Run For School Board nut', "Pruitt 's chief of staff takes responsibility for controversial raises racism", 'GOP senators : Comey drafted statement clearing Clinton before her interview nap', 'Austrian Chancellor may have been one of those lobbied by Manafort brewery', 'My fellow snowflakes WE did the impossible in Alabama , now onto Texas ! Support Beto for Texas senate , removing Cruz ! annihilating', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry Barbershop', 'The new Trump administration sounds more like the old Trump campaign prattles', 'How Mick Mulvaney Is Changing The Consumer Financial Protection Bureau overcharging', "Robert Mueller 's investigators interviewed Rod Rosenstein , who is overseeing the Russia investigation ballet", 'Trump speech puts emotion ahead of problem-solving toupee', 'Europe \' in battle mood \' over Trump \'s threat on steel imports : " We will react with counter measures within a few days " grandma', 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics parrot', "Will Trump 's possible testimony end the Mueller probe — or is it just starting ? tantrum", "Ex-Obama official mocks Sen. Paul for getting ' beat up ' by neighbor kid", 'Texas Republican vows to fight for flood insurance overhaul cow', 'Texas chemical plant that exploded amid Harvey flooding had recently been fined over $ 100,000 by OSHA . Tomato', "UK 's Houses of Parliament network blocked 24,473 porn website access attempts in 5 months minutes", 'Pakistan asks Trump to help fund border fence with Afghanistan itself', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington bumble', 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again monkey', 'House to vote on sexual harassment overhaul this week decade', 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement Scratches', 'Pentagon claims 2,000 % increase in Russian trolls after Syria strikes . What does that mean ? bowling', "Majority of Americans against Trump 's wall and do not believe Mexico will pay for it anyone", 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it Bogeyman', '‘ I certainly meant no disrespect ’ : Kellyanne Conway addresses her pose in the Oval Office photo father', 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN DELICATESSENS', "Detroit pub refused to serve Irish people at St. Patrick 's Day Parade — to make a point brawl", "Germany 's center-left Social Democrats agree to hold talks with Merkel 's party on joining or supporting a new government parrot", 'Jerry Brown Compares Trump Supporters to Cave-dwellers at NY Climate Change Meeting Sex', 'In abrupt shift on Syria , Trump turns to military advisers cartoons', "Fox News host goes on epic 4-minute rant on Trump 's pattern of false statements : ' Mr. President , that 's your swamp ' hair", 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite meal', 'Trump once summoned Priebus to kill a fly in Oval Office : report vagrant', 'American kids are 70 percent more likely to die before adulthood than kids in other rich countries retire', 'WHCD Comedian Michelle Wolf : Trump a ‘ Pussy ; ’ Wants to See Jake Tapper Orgasm , Porn and Abortion Jokes Fly Hear', "Trump 's DACA decision could cost thousands of jobs mispronunciations", "US to deploy 1,000 troops to Poland as Russian foreign minister accuses Nato of being a ' Cold War institution ' pigeons", "African states wary of potential repeal of ' conflict minerals ' rule vitamin", 'White House Declassifies GOP Memo on Russia Probe vodka', 'Trump , Putin to hold bilateral meeting hoedown', 'Al Franken : ‘ I ’m not giving up my voice ’ wallet', ' Steve Bannon is reportedly advocating for a tax hike on the wealthy taxidermist', 'Stunning details reveal how Israel ’s spy agency pulled off one of the most brazen heists in modern history theater', "Face facts , America , Donald Trump is a success . Let 's count the ways . lies", 'Africa Signs Free-Trade Deal to Replace Existing Agreements Elephants', ' American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma alien', 'Fact check : McConnell revises history on Syria chin', 'Support the moms who support us drug', 'Stormy Daniels tells of threats following reports of affair with Trump golfing', ' Bill Would Bar Pentagon From Business With Russian Cyber Firm Kaspersky Scarecrow', "Trump : ' I have no doubt that we 'll win ' travel ban lawsuit depart", 'Jon Stewart , Trevor Noah take jabs at Trump , Weinstein at Stand Up for Heroes benefit shoestrings', 'The GOP just ca n’t escape the ’80s remember', 'Kamala Harris rips up the script check', 'Women-only luxury retreat opening in Finland desert', "Iowa Senator 's alma mater turns out to be a Sizzler franchise steak", "Here 's who the Trump campaign considers ' the president 's enemies ' barbers", 'GOP Asked People To Sign A Presidents Day Card For Trump . It Did n’t Go Well . maniac', "Stephen Miller 's heated interview with CNN 's Jake Tapper earns Trump 's praise erection", ' Watch Live : U.S. responds to Syrian chemical attack Enjoy', 'With His Choice Of Inauguration Prayer Leaders , Trump Shows His Values Chest', "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America Soul", 'Trump Organization employees forced to agree not to sue the company president', 'A Guide to the Violence in Charlottesville Bathrooms', 'Shocking scale of US drinking water crisis paint', 'Reddit banned nearly a thousand accounts linked to the same Russian troll farm accused of election meddling on Facebook peanut', 'She put an obscene anti-Trump message on her truck and was arrested . Now she might sue . forehead', 'Liu Xiaobo supporters mark his death amid concerns for widow height', 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms member', 'How states can fix the Electoral College and prevent future Trumps fruitcakes', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner stock', 'Democrats await answers as their countermemo languishes apocalypse', ' Jared Kushner Will Just Fix Everything Magic', 'East coast readies for fresh climate fight as Trump eyes more offshore drilling Surfing', "Louise Slaughter , ' Trailblazer ' In Congress , Dies At 88 dances", 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE VOLUME', 'Trump says US nuke force must be in ‘ tiptop shape ’ shoes', "President Trump 's executive order will undo Obama 's Clean Power Plan rule stupid", "Trump 's ' Impenetrable ' Cyber Unit That Never Was Cranial", 'Gang Rape And Murder Of 8-Year-Old Girl Sparks Outrage Across India sandwich', 'TSA tightens electronics screening for domestic flights beers', 'GOP tax cuts will strengthen our economy and drive Democrats crazy cold', 'Choirul Huda : Indonesian goalkeeper dies after collision with team-mate cries', "' We 'll see ' : Trump addresses possible military retaliation to North Korean nuclear and missile tests math", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans expedite', 'Roseanne Barr Smacks Down ‘ A ** hole ’ Michelle Wolf : ‘ Comedy Comes From Love , Not Hate ’ bakery', "Russian prisoners transported in ' cruel , inhuman and degrading conditions in train carriages from Soviet era ' politicians", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' voted", '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead tweeted', 'Contrasting lawmaker reaction to the Florida shooting with NRA contributions compliance', 'Brexit economy : UK faces squeeze on living standards oranges', 'Stolen Lennon items recovered in Berlin rehab', 'Republicans formally roll out tax plan -- live updates Lobsters', 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon pacifist', 'GOP senators return home to harsh local headlines on healthcare clean', "Blake Farenthold , Texas lawmaker accused in sexual harassment suit , wo n't seek re-election pudding", 'Donald Trump Discovers the Red Line for His Supporters : Immigration fantasies', 'North Korea : New UN sanctions an act of war kindness', 'Ex-federal judge tapped to review Cohen documents inmate', "Trump 's DACA decision could cost thousands of jobs pennies", 'Armenia contemplates the unlikely : a nonviolent revolution on the cusp of victory hoedown', 'Congresswoman apologizes for not protecting women in her office harem', 'Trump Meets Every Criteria For An Authoritarian Leader , Harvard Political Scientists Warn Eats', "Trump is caught promising to ' release the memo ' on hot mic kraken", "Thailand mother watches helplessly as baby 's death is streamed to Facebook giggle", 'U.S. ambassador to U.N. says Russia tearing down global order delivery', 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says Self', "Do n't get carried away – Trump is as popular today as he was last year kombucha", 'Corbyn woos small businesses with plan for crackdown on late payments porcupines', 'Police in Paris shoot man dead after he stabs several people in the Opera district , French media say moons', 'Trump And Russia : Stephen Colbert Says He Was Followed During Secret Moscow Trip mushroom', 'Community banks file lawsuit against Equifax Nails', "BET founder : Trump 's economy is bringing black workers back into the labor force comedians", 'Paul Manafort , and the Weakness of Trump chins', " Trump 's first year has been the private prison industry 's best Gang", "Iran 's bad behavior leaves Trump with just one choice soda", 'Paul Manafort Flew 18 Times To Moscow And Frequently Reached Putin ’s Allies , Records Show elbows', "Trump wo n't condemn white supremacists or Vladimir Putin — and the 2 are closely linked bread", "Trump jokes that Haley could ' easily be replaced ' sons", "Judge says former Trump campaign manager Paul Manafort might spend ' the rest of his life in prison ' enjoy", 'Trump lashes out at press during Arizona rally eyebrows', " Senate leader says does n't see need for bill to protect special counsel Treasury", 'U.S. consumer protection official puts Equifax probe on ice chicken', "Bernstein : GOP criminal referral for Trump dossier author a ' glowing red herring ' Ginger", "Trump Organization real estate partner in India accused of ' large-scale fraud ' idiocy", ' Oil Slumps to Lowest This Year as Traders Focus on Record Supply oxygen', "DNC chair candidate wants to ' shut other white people down ' minorities", 'Trump has mastered the art of seeming like he ’s telling the truth pretending', 'Trump expected to announce judicial nominees today tweet', 'Report : Texas Church Shooter Was Atheist , Thought Christians ‘ Stupid Somnambulist', 'Mnuchin backs key provision in Trump tax plan that would hit Democrats hardest golf', 'Facebook introduces new tools to let people delete and see their data as scandal continues ankles', 'Tom Price intervened on rule that would hurt drug profits on the same day he acquired drug stocks paraphernalia', 'Notre Dame students walk out on Pence commencement speech pass', 'Carnage in Kabul adds to US challenges in Afghanistan mess', 'U.S. allies retaliate after Trump lets steel tariffs take effect for Europe , Mexico and Canada cry', 'James Comey asked to testify by Senate Intelligence Committee next Tuesday Gigantism', 'Jimmy Kimmel wrecks car in head-on collision accident unicycle', 'Police say 39 people detained over neo-Nazi march in Berlin dachshunds', 'GOP Asked People To Sign A Presidents Day Card For Trump . It Did n’t Go Well . monkeys', 'Some U.S. borrowers jailed over civil debts , new ACLU report shows drinking', "Russia investigation makes US ' look very bad , ' Trump says smell", 'Three Dead in Fresno Shooting Spree , Suspect in Custody - NBC News !!!!!!!!!! kindergarten', "It 's time for Congress to update the law governing digital surveillance watches", "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 baseballs", "Malawi arrests 140 in clampdown after ' vampirism ' killings rumors", 'U.S. Report Says Humans Cause Climate Change , Contradicting Top Trump Officials toupee', 'Entry Ban Could Cause Doctor Shortages in Trump Territory , New Research Finds door', 'NBC corrects story that Trump attorney Michael Cohen was wiretapped , intercepted White House call football', ' Tax bill will slash by half the number of homeowners claiming the mortgage deduction electrocution', "$ 200 million eyeballed for Donald Trump 's inauguration tan", 'Tillerson responds to reporters after being fired on Twitter fishermen', "Ten of Trump 's budget 's cruelest cuts salami", 'Basic income experiment receives $ 5 million worth of bitcoin loses', 'Philippines President Rodrigo Duterte vows to kill mayors and officials involved in drug trade mosquitos', 'Trump Kicks Off G-20 Summit With Rage Tweets Referencing Russian Election Meddling Bout', "Jimmy Kimmel clashes with Sean Hannity over Kimmel 's Melania Trump joke socks", 'Trump considers benching Giuliani from doing TV interviews guides', "' What are they trying to hide ? ' Trump slams election officials over voter data request count", 'Congratulations , America — you did it ! An actual fascist is now your official president plumber', 'Turkey casts Zarrab case as attempt to undermine its politics , economy gobbles', 'Not even Trump can control the GOP base entertain', "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen basement", 'Jared Kushner is the Real President Enemy', 'Couple who rented condo to Pruitt pays fine to D.C. Enslaved', 'Swalwell dares Trump : Declassify the surveillance documents cat', " Read the full text of Trump 's infrastructure plan Sing", 'Hillary Clinton warns LGBT progress may not be secure under Trump money', 'Will Trump Be Impeached Based on Michael Flynn ’s Russia Revelations ? divine', 'White House ices out CNN squirts', 'After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can Help ’ dance', "' SNL ' writer suspended after writing controversial joke about Barron Trump penguin", 'Capitol Hill correspondents committee declines to credential Breitbart cartel', 'Some U.S. borrowers jailed over civil debts , new ACLU report shows comic', 'Islamic television station in Senegal blames saboteur for airing hardcore porn brother', 'Five tough questions for Trump on immigration triangles', "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' apes", 'Tiffany Trump went to a Playboy party on New Year ’s Eve and the Internet cares explodes', 'American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma Supermarket', '‘ Maybe the Russians Are Still Messing With Our Heads ’ plotting', "Enraged Bernie Supporter Opens Fire on Republicans After Realizing he Ca n't Get a Refund job", "Sam 's Club closes hundreds of stores nationwide carts", 'Key senator to vote against CIA nominee Gina Haspel play', "Spicer defends Trump : Issues are ' evolving towards the president 's position ' terrier", 'Mark Meadows on Corker ’s Trump comments : “ It ’s easy to be bold when you ’re not coming back ” licking', ' Pew poll : 61 percent back legalization of pot party', 'Fox News co-president Bill Shine resigns amid network turmoil Shoe', 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption neckties', 'Cory Booker : The system is rigged against working Americans mice', "Senior US diplomat pitches arms sales in China 's backyard restaurant", 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran shopping', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel mules', 'Venezuela claims 41.5 % turnout in violent constituent assembly vote profit', 'NRA ’s Wayne LaPierre instructs CPAC to “ be frightened ” of “ socialist wave ” following Parkland tidal', 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion Duh', 'Trump Rips Mueller Target Papadopoulos as ‘ Liar , ’ ‘ Low Level Volunteer ’ musician', "Treasury sanctions ' Putin 's chef , ' other Russians over cyber-related threats grandmother", 'Trump Budget Gambles on Having This Equation Right Bet', "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news dinner", 'Trump Wall Moves Forward With Firms Tapped for Designs Jet', 'Schiff : Trump Jr. may have been first to know about Russian efforts to meddle in election lie', 'Officials : US captures key militant key in Benghazi attack hug', 'Kenya county officials blame military for 5 in shallow grave river', 'Report : GOP Rep. urged woman from affair to get abortion despite his anti-abortion stance street', "US diplomat forced to leave New Zealand after being involved in ' serious criminal incident ' donkey", "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban raisin", "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie Affair", 'Panel rejects attempt by Democrats to get Trump travel costs toupee', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters bestiality", "What Trump 's first speech as president tells us about the next four years nightmares", "US says refugee admissions wo n't be suspended until July 12 ogre", "Treasury sanctions ' Putin 's chef , ' other Russians over cyber-related threats rewards", 'Suspected rebel-planted mine hits Yemeni ship , kills 2 shrubbery', ' House to vote Thursday on Obamacare repeal bill nobody', 'India is building a biometric database for 1.3 billion people — and enrollment is mandatory goats', 'Trump is being warned of impeachment by advisors baldness', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S parachute', 'The Latest : Trump Denounces Report Russia Had Info on Him publishes', 'Extremist website insists armed march against Jewish people in Montana will go ahead food', "P.F. Chang 's heads to China to serve American-style Chinese food Tacos", 'Border Patrol Shooting Death Of Immigrant Woman Raises Tensions In South Texas iguana', "U.S. blocks use of Venezuela 's digital currency : White House cameras", 'Trump Lawyer Michael Cohen to Appear Before House Intel Panel on Tuesday farm', 'James Comey ’s Opening Remarks : It ’s All About Him act', 'Vornado Has ‘ Handshake ’ to Sell Stake in NYC Tower to Kushner sewer', 'Navy jet shoots down Syrian warplane that attacked US-backed rebels balloon', 'What happened to jarred closed testimony screaming', "A ' huge clue ' may reveal that Mueller 's endgame is to nail Trump for obstruction cash", 'After Tanker Flips , Chocolate Bars Traffic On Polish Highway sweetens', 'Venezuela chief prosecutor to face charges as crisis deepens birthday', "White House 's Mulvaney : Chances of government shutdown are currently 50-50 beach", 'John Legend : Trump ‘ consistently loyal to white supremacists and Putin ’ bears', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa convent", 'Triple Threat : New Pneumonia Is Drug-Resistant , Deadly And Contagious thespian', 'Moore dodges the press as harassment scandal spirals ham', 'Israel : US-Led Strikes enforce Red Line on syria . paper', 'Mexico Sends Top Official to California Help Illegal Aliens Avoid Deportation dog', 'Trump refers to countries as " Shithole Countries " houses', 'Trump administration has unforced errors and self-inflicted wounds galore tweets', "Mike Pence does n't stand for North Korea athletes during opening ceremonies shenanigans", "After healthcare vote , California Rep. Jeff Denham hears from angry constituents : ' You voted against me ' wrote", 'Texas Lt. Gov. Dan Patrick : Video games , abortion to blame for school shootings — but not guns card', 'New Dashcam Video Shows Philando Castile Informing Officer He Had A Firearm baby', 'Watch Live : U.S. responds to Syrian chemical attack sock', 'Trump to hire new lawyer in response to Russia probes dolls', 'Thousands of students , teachers march on White House to call for better gun control gum', 'On the campaign trail , Trump was very worried about revealing America ’s secrets pimples', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' Cookbook", "Delhi Police Say They 've Captured Most-Wanted Terrorist Known As ' India 's Bin Laden ' Hindu", "' Mega-colonies ' of penguins discovered in Antarctica Basement", " People in half of Virginia 's counties on track to have ZERO Obamacare insurers next year turtles", 'Trump called for a government shutdown over immigration and it makes no sense rice', 'The FBI is leading an investigation into Donald Trump ’s connections with Russia fishermen', "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' dog", 'Italian President Blocks Eurosceptic Coalition Govt dog', "' Get ready Russia ' : Trump issues warning on Syria missile strikes chants", 'Joe Arpaio Found Out He Admitted Guilt With Trump Pardon On Live TV Infatuation', "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement monkey", 'Why is Donald Trump so cozy with the Kremlin ? A political scientist and Russia expert breaks down the theories blanket', 'Retired English teacher corrects letter from Trump and sends it back to White House shreds', "Alibaba Founder Jack Ma says Artificial Intelligence could spark the ' Third World War ' , but says that humans would win . pickle", 'House to vote Thursday on Obamacare repeal bill joke', 'Robert Mueller examining blocked Trump letter that explains his reasons for firing Comey love', 'Trump travel ban : judges skeptical about arguments on executive order gibberish', ' Trump Seeks Shift in Visa Allotments Crucial to Tech Outsourcing Nerd', ' Trump overturns regulation on coal mining debris Canary', 'Illinois Senate passes measure for neo-Nazis to be classed as terrorist groups pizzas', ' California to sue Trump administration for repeal of fracking rules Gophers', "AP Exclusive : Senator 's family business uses Mexican labor hats", "Trump ' disappointed ' with China after North Korea missile test humanity", "Cambodia 's Hun Sen says he and Trump object to ' anarchic ' media spiders", 'Poll : 60 % of voters back Trump ’s travel ban hermits', "Ex-Obama official mocks Sen. Paul for getting ' beat up ' by neighbor kindergartner", 'All 22 promises Trump made in his speech to Congress , in one chart kindergarten', 'Experts to Trump : Russia is not our ally in the war on ISIS cholesterol', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid kabobs', 'Constitutional collapse : Why we could be on the verge of a democratic apocalypse victory', 'Reporter Fact-Checks Trump : ‘ Why Should Americans Trust You ? ’ lick', 'Readers on the Fake News awards presented by President Trump tan', 'Trump has played at least 91 days of golf during his presidency and it ’s making him a better president despot', 'Manchin dodges party-switch fallout ball', 'Trump distances himself from Ed Gillespie after Virginia election loss chase', 'Sexual misconduct allegations leave a swath of Los Angeles County without representation in the Capitol comedians', 'Newt Gingrich , Donald Trump Jr. rush to blame Kathy Griffin and “ the left ” for baseball shooting attendance', 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean drugs', 'Coast Guard wo n’t ban transgender members unless compelled cupcakes', 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it cheese', 'Grigory Rodchenkov : Russian whistleblower suspected British cheats soccer', 'Netflix says it now has 104 million subscribers worldwide - BBC News fleas', 'Dozens dead in possible gas attack in Syria ; regime denies allegation balloon', "GOP lawmakers glued to Trump 's ' riveting television ' cable", 'The Latest : House passes $ 7.9 B Harvey disaster aid package party', "A top State Department official could n't explain why the U.S. backs Saudi Arabia impersonates", "Trump officials greet Ford 's plan to import Chinese cars vandalize", 'Affirmative-action hypocrisy : Foes hope to use Asian-Americans to attack racial diversity on campus Import', 'The drama behind Trump ’s assertion that the National Enquirer deserved a Pulitzer stole', 'Trump administration may force CNN to be sold as part of $ 85bn deal minions', 'Bush-era diplomat tweets that you should be scared , very scared insomnia', "Microsoft Investigates ' Inappropriate ' Pro-Trump Russian Ads on Bing Search Engine games", "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance Acrobatics", "What Trump 's first speech as president tells us about the next four years nap", "McCain , North Korea in war of words over ' crazy fat kid ' crack - strong words from a gimpy midget ! oooo ! wife", 'Newt Gingrich , Donald Trump Jr. rush to blame Kathy Griffin and “ the left ” for baseball shooting cards', 'Puerto Rico faces federal lawsuit over transgender rights wrongdoings', "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America vomit", "Bafta Awards 2018 : ( Most ) stars wear black to bring Time 's Up to Britain pigs", 'Forget Planet 9 — there ’s evidence of a tenth planet lurking at the edge of the solar system Science', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf origami', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say cupcakes", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white server', 'Ex-President Luiz Inacio Lula da Silva defies court order to turn himself into police , hunkers down with supporters . hunks', ' Keystone pipeline can be made from non-US steel despite executive order , White House says milk', 'U.S. fighter jet shoots down Iranian-made drone in Syria kite', "It 's over : Britain files for divorce from the European Union queen", 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote Combusts', 'Catholic priest caught driving 13-year-old girl to motel after paying 16-year-old pimp cat', 'Andrew McCabe lawyer considers suing for defamation after Trump tweet Custody', 'On China ’s Weibo , It ’s Forbidden to Disagree With President Xi Jinping ’s Plan to Rule Forever Tailgate', 'Drilling In America ’s ‘ Crown Jewel ’ Is Indefensible , Former Interior Officials Say border', 'Advisers bad-mouth Nielsen as a ‘ never Trumper ’ angel', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says farmer', 'Donald Trump accuses Obama of orchestrating protests and leaks against him dances', 'Roseanne Barr Smacks Down ‘ A ** hole ’ Michelle Wolf : ‘ Comedy Comes From Love , Not Hate ’ marriage', 'Exclusive — Alabama Poll : Judge Roy Moore Leads Radical Democrat Doug Jones by Six Points leash', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 Films', "US cuts women 's health funding to UN hair", ' Deaths confirmed in Manchester " blast " dynamite', 'Flynn subpoenaed by grand jury in Russian investigation . slam', 'Trump Administration Revises Conservation Plan For Western Sage Grouse clairvoyant', 'Ontario judge who wore Trump hat is off the bench costume', " Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' Duck", ' Trump said Haitians have aids , Nigerians live in huts in oval office meeting Racist', "Donald Trump team ' scrutinising staff Twitter accounts before hiring them to check for criticism ' collusion", 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller toadies', 'Gerrymandering for 2020 : Virginia Republicans are trying to rig the Electoral College votes for next election confuse', 'Las Vegas security guard Jesus Campos disappears moments before TV interviews toothbrush', 'Senators consider automatic tax hikes if revenue falls short serfdom', "Warren Buffett 's Berkshire Hathaway dumps its Fox stake collection", 'Turkey suspends 9,103 police personnel over alleged links with failed coup : CNN Turk promotes', 'The Democrats ’ hypocrisy fest : Disingenuous attacks on Bernie Sanders persist — and his popularity climbs hairline', 'Trump undercuts White House stance hours before critical surveillance vote bathroom', 'Charlotte Pence : I Bought The Gay Bunny Book wrote', 'What if Sociologists Had as Much Influence as Economists ? donkeys', 'How Donald Trump weaponizes confusion : Now he wants to blame Russia scandal on Obama tiger', 'Muhammad Ali ’s Son Stopped for 2nd Time in Airport Line round', 'The Trump administration is n’t a climate scientist , but it plays one on policy decisions horrible', 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns fights', "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) shame", 'Conservative media outlet RedState just fired a lot of its anti-Trump bloggers stalkers', "Trump sees veterans as the perfect armed teachers , but they 're divided chimpanzees", "NRA 's Wayne LaPierre says gun control advocates ' hate individual freedom ' freedom", 'Trump vows to start NAFTA renegotiation talks forgot', 'Scout Schultz : LGBT activist shot dead by police at Georgia University laughed', 'Twitter bans RT and Sputnik ads amid election interference fears baking', 'Atlantic editor : Trump is going to cause violence against journalists cosmetologists', 'Liberals need to stop being apologists for radical Islamists vegans', 'In New Hampshire and Iowa , Trump eyes 2020 re-election as midterms loom dreads', 'Contradictions upon contradictions in the tale of Trump payoff to porn star cupcakes', 'North Korea Called Me a ‘ War Maniac . ’ I Ignored Them , and Trump Should Too . Thanked', 'Donald Trump hosts man who called for death of Barack Obama and Hillary Clinton at White House marriage', 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ Billionaires', 'Kim jong un ’s brutal regime in north korea is worse than nazi concentration camps , human rights leader says summer', "A look at Attorney General Jeff Sessions ' political career Laugh", 'Ex-CIA officer held over secret files recipe', 'Dem to unveil bill requiring a White House psychiatrist puppy', "Trump 's FEMA Director Faces His First Test date", "Vulnerable Democratic Sen. Heidi Heitkamp 's path to re-election gets tougher with Rep. Kevin Cramer set to enter race fight", 'The Latest : Pakistan death toll in suicide blast rises to 11 hotdog', 'New tack in Trump defense : The Mueller grand jury is too black tuxedo', 'White House Red Scare people', "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' cook", 'US flies two B-1 bombers over South Korea after North Korea missile launch imagines', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges gerbil', 'Trump administration plans to impose tariffs on EU steel and aluminum : Sources grandson', "Bannon tells French far-right party : ' Let them call you racist ' eat", 'Lobbying Frenzy Begins on Tax Bill Dollar', "Dems prepare to face off with Trump 's pick to lead EPA . kiss", 'Trump : Dems playing blame game instead of fixing Obamacare party', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism deflate', 'Berkeley Police Allowed Antifa to Jump Barricades , Assault Demonstrators kiss', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . dinner", "Meet the Malibu lawyer who is upending California 's political system , one town at a time beach", 'Why Gorsuch could lead court in wrong direction ducks', "Trump hears Christmas sermon about ' the power of words ' walls", 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together kittens', 'Who is Sergey Kislyak , and how did he become the hottest meeting ticket in Washington ? dance', 'Fox News guest offensively slams John McCain to claim torture works poetry', 'Party animal Arizona lawmaker expelled after #MeToo movement giraffe', 'A Trump impersonator and Kim Jong-un impersonator crashed the Olympic opening ceremony — and were kicked out ate', 'How Trump Won — and How the Media Missed it groundhog', 'Cannabis Drug Halved Convulsions in Company-Funded Epilepsy Test Contest', "Norwegians tell Trump : We do n't want to come to your s *** hole country hotel", "Brazil 's Temer accused of passive corruption by police anime", 'Trump , Comey And Special Counsel Robert Mueller Could Come Face-To-Face At FBI Ceremony Next Week ballet', 'British official : South Sudan violence is tribal genocide prank', 'Sen. Bob Hertzberg will cooperate with investigation into unwanted hugs hairpieces'] {'congress': 1762, 'oks': 5495, 'trump': 8239, 'bid': 870, 'to': 8078, 'widen': 8725, 'private': 6139, 'care': 1281, 'at': 568, 'besieged': 849, 'va': 8436, 'destroy': 2291, 'and': 386, 'obama': 5446, 'have': 3716, 'the': 7996, 'same': 6877, 'approval': 477, 'rating': 6388, 'after': 262, 'their': 7999, 'first': 3137, 'year': 8853, 'least': 4580, 'according': 158, 'one': 5507, 'poll': 5982, 'person': 5814, 'mcmaster': 4940, 'says': 6918, 'administration': 214, 'will': 8740, 'confront': 1750, 'russia': 6831, 'destabilizing': 2289, 'behavior': 814, 'lizard': 4698, 'triple': 8217, 'threat': 8028, 'new': 5335, 'pneumonia': 5955, 'is': 4237, 'drug': 2592, 'resistant': 6618, 'deadly': 2109, 'contagious': 1798, 'president': 6102, 'it': 4253, 'watergate': 8632, 'yet': 8861, 'moving': 5208, 'report': 6579, 'wants': 8592, 'his': 3833, 'chief': 1469, 'of': 5470, 'staff': 7553, 'get': 3407, 'rid': 6712, 'jared': 4287, 'ivanka': 4260, 'police': 5971, 'how': 3919, 'right': 6723, 'co': 1597, 'opts': 5538, 'frederick': 3276, 'douglass': 2531, 'handedness': 3664, 'forget': 3237, 'populism': 6013, 'cure': 2023, 'not': 5405, 'disease': 2404, 'hugging': 3930, 'ap': 440, 'fact': 2973, 'check': 1442, 'an': 378, 'angry': 396, 'twists': 8293, 'facts': 2976, 'about': 133, 'raid': 6351, 'probe': 6145, 'candy': 1255, 'michelle': 5022, 'was': 8618, 'jimmy': 4317, 'fallon': 3000, 'only': 5510, 'guest': 3598, 'no': 5372, 'they': 8012, 'did': 2327, 'mom': 5141, 'dance': 2064, 'enemy': 2763, 'doj': 2491, 'charges': 1422, '11': 10, 'possible': 6035, 'caravan': 1277, 'members': 4979, 'with': 8771, 'illegally': 3998, 'entering': 2787, 'us': 8421, 'restaurant': 6635, 'steve': 7625, 'bannon': 709, 'became': 787, 'face': 2966, 'political': 5976, 'movement': 5204, 'roots': 6789, 'in': 4048, 'los': 4737, 'angeles': 392, 'cheerleaders': 1447, 'eric': 2816, 'sean': 7011, 'hannity': 3674, 'democrats': 2222, 'are': 493, 'even': 2850, 'people': 5792, 'as': 529, 'makes': 4807, 'more': 5175, 'arrests': 518, 'ice': 3971, 'looks': 4727, 'for': 3219, 'detention': 2302, 'centers': 1377, 'recreation': 6454, 'syrian': 7852, 'state': 7592, 'tv': 8281, 'successive': 7731, 'blasts': 931, 'heard': 3743, 'hama': 3654, 'province': 6228, 'eructations': 2822, 'mattis': 4918, 'asks': 535, 'former': 3245, 'ambassador': 360, 'anne': 404, 'patterson': 5746, 'take': 7866, 'top': 8107, 'job': 4320, 'pentagon': 5791, 'circus': 1516, 'defends': 2168, 'decision': 2135, 'keep': 4387, 'long': 4721, 'democratic': 2221, 'memo': 4982, 'under': 8324, 'wraps': 8826, 'presents': 6098, 'blames': 925, 'corker': 1854, 'iran': 4222, 'deal': 2110, 'smell': 7357, 'remember': 6540, 'when': 8696, 'republicans': 6592, 'were': 8684, 'mad': 4783, 'that': 7994, 'unreliable': 8383, 'allies': 335, 'mistress': 5106, 'childhood': 1473, 'bullying': 1143, 'anxiety': 431, 'goes': 3471, 'away': 634, 'homework': 3867, 'reportedly': 6581, 'advocating': 243, 'tax': 7905, 'hike': 3812, 'on': 5505, 'wealthy': 8649, 'nature': 5290, 'resignation': 6612, 'wave': 8636, 'capitol': 1269, 'hill': 3816, 'might': 5037, 'be': 767, 'over': 5597, 'radio': 6344, 'six': 7282, 'journalists': 4341, 'life': 4645, 'prison': 6134, 'failed': 2981, 'turkish': 8267, 'coup': 1900, 'film': 3109, 'stephen': 7616, 'miller': 5052, 'has': 3702, 'better': 859, 'sense': 7075, 'pulse': 6263, 'than': 7990, 'any': 432, 'since': 7259, 'andrew': 388, 'jackson': 4268, 'scent': 6941, 'house': 3914, 'stun': 7705, 'gop': 3491, 'by': 1196, 'sinking': 7268, 'veterans': 8479, 'intel': 4156, 'bills': 890, 'fences': 3078, 'south': 7446, 'korea': 4467, 'expected': 2906, 'prosecutors': 6202, 'coming': 1665, 'days': 2101, 'canines': 1257, 'schiff': 6945, 'jr': 4345, 'may': 4923, 'been': 797, 'know': 4458, 'russian': 6832, 'efforts': 2678, 'meddle': 4954, 'election': 2695, 'mysteries': 5256, 'cdc': 1355, 'hold': 3853, 'briefing': 1089, 'public': 6243, 'can': 1238, 'prepare': 6089, 'nuclear': 5420, 'war': 8594, 'chickens': 1467, 'texas': 7984, 'lawmaker': 4552, 'threatens': 8032, 'shoot': 7187, 'colleague': 1626, 'reporting': 6584, 'protesters': 6219, 'kiss': 4439, 'forced': 3224, 'women': 8791, 'wear': 8652, 'very': 8477, 'tiny': 8069, 'bathing': 753, 'suits': 7752, 'higher': 3807, 'heels': 3758, 'buying': 1192, 'beauty': 784, 'pageants': 5642, 'sons': 7429, 'loses': 4740, 'nearly': 5304, '17': 20, 'million': 5053, 'pharma': 5834, 'stock': 7636, 'tanks': 7885, '92': 119, 'aquarium': 483, '2016': 41, 'rnc': 6744, 'delegate': 2193, 'directed': 2359, 'change': 1408, 'party': 5715, 'platform': 5921, 'ukraine': 8305, 'support': 7771, 'bra': 1045, 'senate': 7066, 'republican': 6591, 'big': 875, 'mistake': 5105, 'fire': 3128, 'mueller': 5213, 'wake': 8574, 'strange': 7666, 'last': 4527, 'office': 5481, 'pets': 5831, 'navy': 5296, 'seal': 7009, 'who': 8715, 'killed': 4421, 'bin': 892, 'laden': 4495, 'calls': 1219, 'parade': 5682, 'plan': 5908, 'third': 8020, 'world': 8808, 'bulls': 1140, 'stupidity': 7709, 'could': 1885, 'microwave': 5026, 'missiles': 5100, 'disable': 2369, 'north': 5397, 'cook': 1830, 'myeshia': 5253, 'johnson': 4326, 'widow': 8728, 'fallen': 2998, 'soldier': 7414, 'cake': 1209, 'bernie': 845, 'sanders': 6885, 'mirrors': 5083, 'hillary': 3817, 'clinton': 1569, 'combatting': 1654, 'meddling': 4957, 'denies': 2233, 'helped': 3770, 'campaign': 1229, 'stealing': 7607, 'gunmam': 3608, 'attacks': 581, 'church': 1505, 'helwan': 3775, 'cairo': 1207, 'four': 3256, 'dead': 2106, 'nine': 5367, 'wounded': 8823, 'shooter': 7188, 'pie': 5863, 'tech': 7925, 'entertainment': 2790, 'activists': 191, 'launch': 4540, 'app': 452, 'block': 943, 'bully': 1142, 'donald': 2503, 'twitter': 8294, 'patsy': 5744, 'ex': 2864, 'british': 1097, 'spy': 7536, 'paid': 5645, '168': 19, '000': 0, 'dossier': 2520, 'firm': 3135, 'discloses': 2389, 'tea': 7914, 'despite': 2285, 'boasts': 963, 'idea': 3977, 'handle': 3666, 'classified': 1547, 'material': 4910, 'smoothies': 7366, 'jailed': 4273, 'malaysian': 4813, 'opposition': 5534, 'leader': 4564, 'pardoned': 5694, 'victory': 8489, 'icbms': 3970, 'pyongyang': 6298, 'conduct': 1731, 'missile': 5099, 'test': 7977, 'anytime': 437, 'anywhere': 439, 'meme': 4980, 'largest': 4520, 'collection': 1629, 'ocean': 5464, 'garbage': 3372, 'now': 5414, 'twice': 8289, 'size': 7284, 'olympic': 5501, 'gold': 3475, 'medal': 4953, 'sucking': 7737, 'up': 8396, 'murderous': 5233, 'totalitarian': 8118, 'regime': 6495, 'vacuum': 8439, 'rex': 6701, 'tillerson': 8062, 'direct': 2358, 'channels': 1413, 'scam': 6925, 'black': 914, 'panther': 5671, 'wakanda': 8573, 'sheds': 7155, 'light': 4650, 'excellence': 2872, 'darkness': 2079, 'quotation': 6326, 'day': 2099, 'tried': 8208, 'sink': 7266, 'inquiry': 4132, 'comey': 1662, 'hoops': 3881, 'directv': 2366, 'offering': 5479, 'refunds': 6488, 'nfl': 5344, 'sunday': 7757, 'ticket': 8047, 'fans': 3014, 'offended': 5472, 'national': 5282, 'anthem': 423, 'protests': 6220, 'melody': 4976, 'deficit': 2175, 'hawks': 3722, 'seem': 7043, 'gone': 3484, 'missing': 5101, 'action': 188, 'doves': 2535, 'drunken': 2596, 'american': 365, 'beating': 780, 'giving': 3443, 'nazi': 5299, 'salute': 6874, 'germany': 3405, 'praised': 6060, 'occupy': 5463, 'silicon': 7245, 'valley': 8443, 'next': 5343, 'populist': 6014, 'aimed': 296, 'wealth': 8648, 'bunnies': 1152, 'stop': 7651, 'autocracy': 614, 'itch': 4256, 'macron': 4782, 'condemns': 1726, 'massive': 4900, 'hacking': 3626, 'attack': 577, 'documents': 2477, 'leaked': 4571, 'bbc': 765, 'news': 5339, 'water': 8631, 'making': 4809, 'americans': 366, 'see': 7038, 'way': 8640, 'rest': 6633, 'already': 351, 'despise': 2284, 'syria': 7851, 'vows': 8555, 'sign': 7235, 'paris': 5698, 'agreement': 283, 'leaving': 4583, 'alone': 348, 'climate': 1564, 'denial': 2230, 'reality': 6418, 'bill': 884, 'contains': 1800, 'sneaky': 7380, 'break': 1062, 'jet': 4307, 'owners': 5623, 'bathroom': 755, 'charlotte': 1426, 'pence': 5778, 'bought': 1027, 'gay': 3381, 'bunny': 1153, 'book': 995, 'wrote': 8842, 'this': 8021, 'congressional': 1763, 'accounting': 163, 'trick': 8206, 'part': 5707, 'reason': 6423, 'washington': 8621, 'so': 7399, 'divided': 2459, 'magic': 4790, 'advice': 235, 'do': 2472, 'robert': 6754, 'he': 3728, 'clear': 1555, 'you': 8871, 'end': 2750, 'tickle': 8048, 'middle': 5028, 'class': 1544, 'does': 2484, 'want': 8590, 'cut': 2036, 'government': 3501, 'coffee': 1616, 'there': 8007, 'enough': 2779, 'opposed': 5533, 'health': 3738, 'kill': 4420, 'bear': 774, 'experts': 2917, 'our': 5573, 'ally': 345, 'isis': 4238, 'bears': 777, 'predicts': 6078, 'patriots': 5742, 'win': 8742, 'super': 7762, 'bowl': 1035, 'points': 5962, 'gypsy': 3622, 'senators': 7068, 'drafted': 2547, 'statement': 7593, 'clearing': 1558, 'before': 803, 'her': 3779, 'interview': 4179, 'tickling': 8050, 'official': 5484, 'blocked': 945, 'immigrant': 4010, 'teen': 7930, 'rape': 6375, 'victim': 8487, 'abortion': 130, 'because': 788, 'personally': 5817, 'healthy': 3741, 'trillion': 8213, 'dollar': 2493, 'pledge': 5940, 'fix': 3150, 'bridges': 1087, 'roads': 6747, 'challenging': 1400, 'lie': 4641, 'taiwan': 7865, 'court': 1906, 'rule': 6816, 'landmark': 4504, 'sex': 7119, 'marriage': 4873, 'case': 1314, 'heterosexual': 3792, 'white': 8713, 'invites': 4210, 'intelligence': 4158, 'committee': 1679, 'leaders': 4565, 'review': 6685, 'security': 7035, 'council': 1886, 'tweets': 8285, 'fought': 3250, 'forgotten': 3241, 'filipino': 3108, 'ii': 3995, 'honored': 3874, '75': 101, 'years': 8855, 'later': 4529, 'officials': 5486, 'greet': 3553, 'ford': 3227, 'import': 4031, 'chinese': 1480, 'cars': 1304, 'food': 3211, 'should': 7203, 'publicly': 6245, 'testify': 7979, 'democrat': 2220, 'judiciary': 4353, 'strip': 7682, 'addresses': 208, 'boy': 1042, 'scouts': 6977, 'summit': 7754, 'west': 8686, 'virginia': 8517, 'rep': 6565, 'king': 4435, 'seeks': 7042, 'surveillance': 7795, 'port': 6020, 'authority': 612, 'explosion': 2929, 'we': 8643, 'ca': 1198, 'afford': 255, 'politically': 5977, 'correct': 1863, 'bowel': 1034, 'replacing': 6578, 'secretary': 7028, 'cia': 1508, 'director': 2364, 'mike': 5041, 'pompeo': 5993, 'npr': 5416, 'vegetables': 8461, 'israeli': 4248, 'minister': 5070, 'wishes': 8767, 'iranian': 4223, 'success': 7728, 'pleads': 5936, '50': 84, 'detained': 2298, 'immigration': 4013, 'raids': 6352, 'asian': 531, 'restaurants': 6636, 'mississippi': 5103, 'another': 418, 'amp': 373, 'subreddit': 7718, 'wednesday': 8663, 'apocalypse': 446, 'capital': 1268, 'confederacy': 1733, 'debate': 2121, 'city': 1526, 'famed': 3008, 'civil': 1528, 'monuments': 5162, 'heating': 3753, 'mounting': 5195, 'wolf': 8787, 'correspondents': 1867, 'dinner': 2346, 'remarks': 6538, 'sarah': 6896, 'huckabee': 3922, 'gravy': 3541, 'latest': 4530, 'san': 6879, 'juan': 4346, 'mayor': 4926, 'answers': 420, 'wasteland': 8625, 'special': 7475, 'counsel': 1887, 'impanels': 4019, 'grand': 3521, 'jury': 4365, 'koala': 4462, 'five': 3149, 'pacific': 5629, 'islands': 4244, 'lost': 4744, 'rising': 6736, 'seas': 7019, 'hits': 3841, 'sun': 7756, 'reilly': 6508, 'god': 3467, 'sexual': 7121, 'harassment': 3684, 'scandal': 6927, 'libido': 4634, 'labels': 4485, 'justice': 4367, 'system': 7854, 'laughingstock': 4537, 'renames': 6553, 'kamala': 4375, 'harris': 3694, 'testimony': 7980, 'table': 7856, 'spicer': 7496, 'problem': 6148, 'melissa': 4974, 'mccarthy': 4932, 'gum': 3606, 'discussed': 2402, 'weapons': 8651, 'manure': 4847, 'grassley': 3537, 'graham': 3518, 'off': 5471, 'letters': 4618, 'demanding': 2215, 'info': 4106, 'author': 608, 'fbi': 3048, 'editors': 2671, 'cuts': 2037, 'strengthen': 7677, 'economy': 2663, 'drive': 2578, 'crazy': 1938, 'biceps': 868, 'search': 7013, 'motive': 5192, 'las': 4522, 'vegas': 8460, 'slow': 7341, 'but': 1180, 'll': 4701, 'tortoise': 8112, 'second': 7025, 'judge': 4348, 'scott': 6971, 'walker': 8577, 'request': 6594, 'delay': 2190, 'elections': 2696, 'playground': 5928, 'peskov': 5821, 'lawyer': 4557, 'kremlin': 4470, 'got': 3496, 'response': 6630, 'santa': 6893, 'planet': 5912, 'evidence': 2859, 'tenth': 7961, 'lurking': 4768, 'edge': 2666, 'solar': 7412, 'pleasure': 5939, 'connecticut': 1768, 'pastor': 5729, 'charged': 1421, '8g': 114, 'electricity': 2699, 'praying': 6073, 'medicare': 4961, 'all': 330, 'progressive': 6172, 'just': 4366, 'pull': 6258, 'out': 5578, 'key': 4406, 'nebraska': 5306, 'primary': 6124, 'bowling': 1038, 'egyptian': 2684, 'prime': 6125, 'ahmed': 289, 'shafiq': 7133, 'withdraws': 8776, 'from': 3299, 'rib': 6705, 'wrenched': 8831, 'ahead': 288, 'shoulder': 7204, 'trips': 8218, 'station': 7596, 'afghan': 256, 'comes': 1661, 'tent': 7959, 'elon': 2712, 'musk': 5243, 'vision': 8524, 'underground': 8328, 'road': 6746, 'bumps': 1148, 'study': 7701, 'emails': 2716, 'much': 5211, 'front': 3300, 'page': 5640, 'coverage': 1912, 'policy': 5974, '69': 98, 'swallowed': 7814, 'bodyguard': 970, 'keith': 4391, 'schiller': 6946, 'testifies': 7978, 'offered': 5478, 'prostitutes': 6206, 'aligning': 327, 'story': 7660, 'pimp': 5879, 'rubio': 6813, 'defection': 2164, 'margin': 4861, 'greasiness': 3542, 'somewhere': 7423, 'between': 861, 'hero': 3784, 'scalia': 6923, 'boss': 1017, 'kennedy': 4395, 'lover': 4752, 'tacos': 7862, 'save': 6909, 'princess': 6129, 'uae': 8299, 'qatari': 6301, 'fighter': 3099, 'jets': 4308, 'intercepted': 4162, 'civilian': 1529, 'flight': 3170, 'raced': 6332, 'rip': 6732, 'roger': 6766, 'moore': 5169, 'james': 4278, 'bond': 985, 'goalie': 3462, 'israel': 4247, 'must': 5246, 'release': 6523, '16': 18, 'old': 5496, 'girl': 3436, 'faces': 2968, '10': 2, 'amnesty': 369, 'scotch': 6968, 'dreamers': 2565, 'board': 961, 'talks': 7877, 'mimes': 5059, 'prevent': 6116, 'shutdown': 7225, 'hit': 3839, 'snag': 7372, 'plans': 5915, 'goat': 3464, 'meet': 4966, 'lee': 4587, 'busby': 1170, 'alabama': 309, 'write': 8837, 'candidate': 1251, 'roy': 6806, 'cockroach': 1608, 'survivor': 7802, 'if': 3986, 'scream': 6984, 'cnn': 1595, 'mime': 5058, 'banning': 708, 'immigrants': 4011, 'helps': 3774, 'workers': 8804, 'leading': 4567, 'economist': 2661, 'wrong': 8840, 'poodles': 6001, 'suicide': 7747, 'bomber': 979, 'kills': 4425, 'seven': 7115, 'wounds': 8824, '20': 31, 'provincial': 6229, 'shopper': 7193, 'would': 8821, 'most': 5185, 'extreme': 2947, 'senator': 7067, 'huge': 3929, 'consequences': 1773, 'lecher': 4584, 'charlottesville': 1427, 'force': 3223, 'try': 8252, 'contain': 1799, 'fallout': 3001, 'spread': 7528, 'chris': 1495, 'cornell': 1857, 'soundgarden': 7440, 'frontman': 3301, 'dies': 2330, 'aged': 268, '52': 85, 'graduates': 3514, 'woman': 8790, 'running': 6826, 'double': 2524, 'mastectomy': 4901, 'repeal': 6568, 'aca': 144, 'latte': 4533, 'hate': 3708, 'present': 6096, 'canada': 1239, 'puerto': 6253, 'rico': 6711, 'benchmark': 832, 'drops': 2590, 'record': 6449, 'low': 4755, 'remark': 6537, 'spoke': 7517, 'heavy': 3755, 'disapproval': 2378, 'deep': 2154, 'against': 266, '2018': 43, 'midterms': 5035, 'dessert': 2288, 'parties': 5710, 'fight': 3098, 'funding': 3328, 'children': 1474, 'insurance': 4151, 'vomit': 8543, 'standing': 7576, 'defense': 2170, 'abusers': 142, 'promotion': 6184, 'jeff': 4295, 'sessions': 7106, 'during': 2617, 'meeting': 4967, 'accountability': 161, 'examine': 2868, 'cost': 1875, 'florida': 3187, 'grocery': 3570, 'saw': 6914, 'military': 5047, 'france': 3262, 'own': 5621, 'dog': 2485, 'mystery': 5258, 'automotive': 620, 'failures': 2986, 'reopens': 6563, 'investigation': 4199, 'into': 4184, 'clintons': 1570, 'martians': 4882, 'sold': 7413, '85bn': 110, 'scraps': 6981, 'cold': 1623, 'weather': 8656, 'leave': 4581, 'these': 8010, 'things': 8016, 'your': 8874, 'car': 1276, 'temps': 7948, 'fall': 2997, 'eat': 2652, 'unstoppable': 8387, 'satan': 6902, '2017': 42, 'pancake': 5662, 'portland': 6022, 'train': 8161, 'stabbing': 7548, 'suspect': 7806, 'said': 6856, 'what': 8693, 'liberalism': 4631, 'gets': 3409, 'docs': 2473, 'say': 6916, 'promise': 6178, 'bottom': 1026, 'transparent': 8169, 'process': 6152, 'paul': 5747, 'ryan': 6836, 'sets': 7109, 'stifling': 7631, 'floor': 3184, 'temperature': 7942, 'shoots': 7191, 'down': 2537, 'made': 4785, 'drone': 2584, 'turkey': 8265, 'urge': 8415, 'appoint': 470, 'feed': 3064, 'dems': 2227, 'back': 645, 'power': 6053, 're': 6397, 'going': 3474, 'raise': 6356, 'taxes': 7906, 'high': 3806, 'income': 4063, 'hurricane': 3954, 'maria': 4862, 'dominica': 2501, 'live': 4693, 'chuckles': 1502, 'oil': 5492, 'tanker': 7884, 'wreck': 8828, 'produces': 6159, 'two': 8295, 'slicks': 7323, 'east': 2648, 'china': 1479, 'sea': 7004, 'drifting': 2572, 'tells': 7940, 'abbas': 124, 'good': 3486, 'chance': 1404, 'mid': 5027, 'peace': 5758, 'reporter': 6582, 'reflections': 6480, 'loss': 4742, 'hair': 3631, 'keystone': 4408, 'pipeline': 5889, 'wo': 8786, 'use': 8423, 'steel': 7609, 'repeated': 6570, 'promises': 6180, 'son': 7425, 'bitch': 910, 'outburst': 5579, 'fits': 3148, 'larger': 4519, 'pattern': 5745, 'tantrum': 7887, 'journalist': 4340, 'delivers': 2208, 'searing': 7018, 'kebabs': 4385, 'killing': 4423, 'chances': 1406, 'healthcare': 3739, 'cows': 1918, 'racism': 6337, 'evil': 2860, 'barbecue': 714, 'youngest': 8873, 'shooting': 7189, '18': 21, 'months': 5161, 'licking': 4639, 'committed': 1678, 'wiping': 8759, 'islamic': 4240, 'stain': 7560, 'cuddle': 2010, '60': 90, 'voters': 8550, 'travel': 8178, 'ban': 692, 'agoraphobics': 281, 'ruble': 6814, 'plunges': 5953, '2nd': 61, 'following': 3206, 'sanctions': 6881, 've': 8456, 'set': 7107, 'surrender': 7794, 'awaken': 630, 'male': 4814, 'congressman': 1764, 'questions': 6313, 'why': 8721, 'men': 4988, 'pay': 5750, 'prenatal': 6087, 'really': 6420, 'fetuses': 3087, 'visit': 8525, 'traumatized': 8177, 'kick': 4412, 'overtake': 5611, 'euro': 2842, 'zone': 8892, 'absorb': 140, 'debbie': 2123, 'lesko': 4611, 'wins': 8755, 'arizona': 501, 'nbc': 5301, 'projects': 6175, 'lottery': 4746, 'compliance': 1705, 'tweet': 8282, 'ready': 6411, 'issues': 4251, 'warning': 8604, 'strikes': 7680, 'metal': 5010, 'tariffs': 7899, 'like': 4653, 'atomic': 574, 'bomb': 977, 'european': 2844, 'firms': 3136, 'lobbyist': 4706, 'wedgie': 8662, 'chester': 1461, 'bennington': 839, 'linkin': 4674, 'park': 5699, 'singer': 7262, '41': 76, 'sang': 6889, 'rolls': 6775, 'obamacare': 5447, 'contraceptive': 1808, 'mandate': 4827, 'candies': 1253, 'fumes': 3323, 'cohen': 1618, 'country': 1897, 'insects': 4134, 'urged': 8416, 'mexican': 5014, 'defiance': 2173, 'border': 1010, 'wall': 8580, 'striptease': 7686, 'dept': 2264, 'reverses': 6684, 'visa': 8522, 'revocations': 6693, 'allows': 343, 'banned': 707, 'travelers': 8179, 'enter': 2786, 'escape': 2826, 'breaking': 1066, 'considering': 1780, 'options': 5537, 'retaliation': 6654, 'source': 7444, 'vacation': 8437, 'post': 6036, 'david': 2094, 'fahrenthold': 2979, 'pulitzer': 6257, 'prize': 6142, 'dogged': 2487, 'philanthropy': 5837, 'crookedness': 1981, 'claims': 1533, 'increase': 4068, 'trolls': 8226, 'mean': 4944, 'accents': 149, 'judicial': 4352, 'nominee': 5382, 'refuses': 6491, 'express': 2937, 'desegregation': 2275, 'ruling': 6819, 'gratitude': 3538, 'cabos': 1202, 'longer': 4722, 'haven': 3717, 'mexico': 5016, 'bloodshed': 949, 'cuisine': 2012, 'worried': 8811, 'flynn': 3198, 'tell': 7938, 'collusion': 1639, 'worrying': 8814, 'shows': 7216, 'within': 8779, 'range': 6369, 'earshot': 2640, 'need': 5310, 'make': 4803, 'lethal': 4615, 'hope': 3884, 'flaws': 3160, 'stand': 7574, 'shakes': 7135, 'pelvis': 5775, 'liu': 4692, 'xiaobo': 8846, 'supporters': 7773, 'mark': 4868, 'death': 2117, 'amid': 367, 'concerns': 1716, 'african': 260, 'trying': 8253, 'everest': 2855, 'without': 8780, 'permit': 5805, 'shoes': 7185, 'fundraising': 3329, 'arm': 503, 'bails': 671, 'spits': 7512, 'supreme': 7781, 'blockbuster': 944, 'term': 7963, 'movies': 5207, 'word': 8798, 'professionalism': 6164, 'moon': 5166, 'california': 1214, 'control': 1815, 'jellybeans': 4299, 'coca': 1605, 'cola': 1621, 'invasion': 4191, 'causing': 1346, 'junk': 4363, 'celebrating': 1361, 'presidency': 6101, 'drawing': 2557, 'nearer': 5303, 'either': 2688, 'done': 2506, 'great': 3543, 'harm': 3693, 'america': 364, 'haircut': 3634, 'family': 3010, 'benefit': 835, 'flush': 3194, 'treasury': 8185, 'department': 2248, 'announcing': 412, 'friday': 3287, 'morning': 5176, 'silver': 7250, 'menendez': 4990, 'bribe': 1079, 'proceeds': 6151, 'rejects': 6516, 'dismissal': 2420, 'bride': 1083, 'celebration': 1362, 'crisis': 1968, 'becoming': 791, 'unsolvable': 8384, 'warn': 8601, 'heads': 3735, 'asia': 530, 'fyre': 3344, 'festival': 3083, 'organizers': 5553, '100': 3, 'lawsuit': 4556, 'bong': 990, 'lewandowski': 4623, 'invited': 4209, 'sanction': 6880, 'oligarchs': 5498, 'law': 4550, 'retaliating': 6653, 'alleged': 333, 'dressing': 2570, 'russians': 6833, 'laughing': 4536, 'phony': 5845, 'witch': 8769, 'hunt': 3950, 'pardon': 5693, 'sheriff': 7165, 'joe': 4324, 'arpaio': 515, 'courageous': 1904, 'thing': 8015, 'suspects': 7808, 'niger': 5357, 'villager': 8500, 'betrayed': 855, 'army': 511, 'troops': 8228, 'fink': 3125, 'hundreds': 3942, 'thousands': 8027, 'educators': 2673, 'hundred': 3941, 'thousand': 8026, 'homeless': 3864, 'students': 7698, 'roofs': 6785, 'india': 4078, 'build': 1132, 'major': 4800, 'facility': 2971, 'seychelles': 7125, 'growing': 3584, 'influence': 4103, 'infest': 4096, 'shrinking': 7220, 'ears': 2639, 'insult': 4150, 'native': 5287, 'smash': 7354, 'windows': 8746, 'mcdonald': 4937, 'bank': 700, 'swearing': 7823, 'wash': 8619, 'island': 4243, 'principal': 6130, 'history': 3838, 'decorum': 2151, 'race': 6331, 'ethnicity': 2840, 'profits': 6167, 'debacle': 2119, 'role': 6771, 'model': 5125, 'measles': 4947, 'debacles': 2120, 'boost': 1005, 'trade': 8151, 'worries': 8812, 'hackers': 3625, 'haitians': 3644, 'aids': 293, 'nigerians': 5359, 'huts': 3960, 'oval': 5593, 'bacchanal': 644, 'separated': 7083, 'families': 3009, 'react': 6401, 'ends': 2759, 'protected': 6209, 'status': 7599, 'condiments': 1727, 'stormy': 7659, 'daniels': 2074, 'threats': 8033, 'reports': 6585, 'affair': 247, 'cookbook': 1831, 'chiefs': 1470, 'asked': 533, 'them': 8000, 'intervene': 4176, 'investigations': 4200, 'opera': 5522, 'jerusalem': 4305, 'intimidated': 4182, 'palestinian': 5656, 'violence': 8510, 'move': 5202, 'embassy': 2720, 'hummus': 3938, 'patrol': 5743, 'raises': 6359, 'tensions': 7958, 'backpack': 654, 'eighteen': 2686, 'found': 3252, 'guilty': 3603, 'newcastle': 5337, 'grooming': 3573, 'network': 5328, 'virgins': 8519, 'denying': 2244, 'sally': 6868, 'yates': 8851, 'she': 7153, 'attention': 587, 'soon': 7430, 'alt': 352, 'neo': 5318, 'confederate': 1734, 'corey': 1853, 'stewart': 7628, 'came': 1223, 'shockingly': 7183, 'close': 1574, 'panel': 5667, 'subpoenas': 7717, 'adviser': 236, 'michael': 5021, 'oxen': 5625, 'bump': 1147, 'maker': 4806, 'resumes': 6647, 'sales': 6864, 'month': 5160, 'mass': 4893, 'eating': 2654, 'kalashnikov': 4373, 'remote': 6547, 'teachers': 7917, 'lawyers': 4558, 'others': 5569, 'worry': 8813, 'fate': 3037, 'student': 7697, 'debt': 2125, 'forgiveness': 3239, 'disappearance': 2373, 'alternatives': 355, 'putin': 6293, 'mixed': 5112, 'bag': 665, 'looms': 4729, 'drinks': 2577, 'advocacy': 240, 'group': 3580, 'accuses': 169, 'racial': 6336, 'bias': 866, 'bonehead': 988, 'plague': 5907, 'disgusted': 2408, 'officer': 5482, 'quits': 6323, 'many': 4848, 'follow': 3204, 'smoking': 7364, 'assad': 539, 'international': 4172, 'pressure': 6106, 'step': 7615, 'damascus': 2060, 'mood': 5164, 'boogie': 993, 'maybe': 4924, 'lady': 4496, 'birthday': 904, 'fat': 3034, 'maps': 4852, 'course': 1905, 'autocrats': 615, 'foreign': 3230, 'trip': 8215, 'autograph': 616, 'delight': 2202, 'sitters': 7280, 'plays': 5932, 'broadway': 1104, 'vornado': 8545, 'handshake': 3671, 'sell': 7058, 'stake': 7563, 'nyc': 5441, 'tower': 8140, 'kushner': 4480, 'give': 3440, 'strike': 7679, 'bases': 741, 'minutes': 5079, 'practicing': 6058, 'nikki': 5366, 'haley': 3645, 'seemingly': 7045, 'tricked': 8207, 'pranksters': 6069, 'commenting': 1672, 'fictional': 3091, 'binomo': 896, 'waltzing': 8586, 'jae': 4270, 'yong': 8867, 'samsung': 6878, 'indicted': 4082, 'bribery': 1081, 'kidnapping': 4418, 'un': 8311, 'myanmar': 5252, 'rohingya': 6768, 'muslims': 5245, 'kittens': 4447, 'loopholes': 4731, 'disclose': 2387, 'financial': 3115, 'fee': 3063, 'alert': 319, 'flag': 3152, 'crimes': 1961, 'fashion': 3031, 'manafort': 4822, 'notes': 5407, 'refer': 6474, 'contributions': 1814, 'legs': 4605, 'staffers': 7555, 'secret': 7027, 'assignments': 555, 'telling': 7939, 'aides': 292, 'hide': 3803, 'john': 4325, 'kelly': 4393, 'haircuts': 3635, 'looking': 4726, 'attempt': 582, 'oust': 5574, 'decency': 2132, 'refugee': 6485, 'admissions': 217, 'suspended': 7810, 'until': 8390, 'july': 4359, '12': 11, 'auditions': 601, 'lieberman': 4642, 'emerges': 2728, 'frontrunner': 3302, 'relay': 6522, 'delicious': 2201, 'idaho': 3976, 'fastest': 3033, 'potato': 6043, 'quietly': 6316, 'stalls': 7569, 'safeguards': 6852, 'dozens': 2544, 'endangered': 2752, 'species': 7476, 'bakers': 675, 'korean': 4468, 'supercharged': 7763, 'option': 5536, 'explained': 2919, 'doubt': 2526, 'gorilla': 3493, 'blame': 923, 'game': 3362, 'themselves': 8002, 'hearings': 3745, 'mccabe': 4930, 'firing': 3134, 'once': 5506, 'inspector': 4141, 'general': 3392, 'gadget': 3347, 'receives': 6434, 'ovation': 5594, 'color': 1645, 'purple': 6284, 'imagines': 4006, 'mnuchin': 5114, 'hard': 3686, 'rich': 6707, 'hedges': 3757, 'assassinations': 545, 'successfully': 7730, 'launches': 4541, 'satellite': 6903, 'carrying': 1303, 'rocket': 6759, 'space': 7454, 'tree': 8190, 'aircraft': 299, 'carrier': 1299, 'dispatch': 2428, 'outrageous': 5589, 'eight': 2685, 'm1': 4775, 'minibus': 5066, 'lorry': 4736, 'crash': 1932, 'refrigerator': 6484, 'both': 1023, 'sides': 7230, 'committing': 1681, 'burma': 1159, 'contradictions': 1811, 'upon': 8407, 'tale': 7873, 'payoff': 5755, 'porn': 6017, 'star': 7579, 'offer': 5477, 'french': 3282, 'far': 3018, 'steps': 7619, 'limelight': 4657, 'slithers': 7332, 'interfering': 4169, 'deny': 2243, 'having': 3718, 'compromising': 1711, 'information': 4109, 'elf': 2706, 'ferry': 3081, 'link': 4672, 'terror': 7972, 'risk': 6737, 'xl': 8847, 'vow': 8554, 'beer': 798, 'miss': 5096, 'asshole': 554, 'murdoch': 5235, 'billion': 886, 'bet': 852, 'indian': 4079, 'cricket': 1957, 'buffet': 1128, 'clears': 1560, 'hurdle': 3953, 'attorney': 590, 'speedster': 7483, 'dnc': 2471, 'chair': 1393, 'jaime': 4275, 'harrison': 3695, 'lobbyists': 4707, 'appetizers': 464, 'billionaire': 887, 'babis': 642, 'scores': 6967, 'czech': 2047, 'partners': 5714, 'annoy': 413, 'added': 205, 'critic': 1970, 'cleared': 1557, 'skip': 7297, 'hinted': 3823, 'anti': 426, 'moscow': 5181, 'quilts': 6320, 'among': 370, 'gallup': 3355, 'still': 7633, 'odds': 5467, 'closed': 1575, 'door': 2516, 'evens': 2852, 'seen': 7047, 'imminent': 4014, 'kim': 4428, 'meets': 4969, 'tour': 8128, 'sunk': 7758, '100m': 5, 'luxury': 4770, 'developments': 2309, 'scientists': 6962, 'turn': 8269, 'hydrogen': 3961, 'breakthrough': 1069, 'revolutionise': 6697, 'jazz': 4293, 'potential': 6045, 'legal': 4595, 'fox': 3258, 'clowns': 1589, 'swap': 7818, 'booed': 992, 'davos': 2096, 'criticizing': 1976, 'fake': 2993, 'media': 4958, 'injured': 4124, 'shots': 7202, 'fired': 3130, 'school': 6953, 'downed': 2538, 'sperry': 7493, 'organizing': 5554, 'violent': 8511, 'miles': 5043, 'farm': 3025, 'sam': 6875, 'charles': 1425, 'murray': 5236, 'allure': 344, 'science': 6959, 'werewolf': 8685, 'bombshell': 984, 'millions': 5055, 'crooked': 1980, 'uranium': 8413, 'finger': 3121, 'chang': 1407, 'serve': 7098, 'style': 7710, 'checkers': 1443, 'hung': 3943, 'parliament': 5703, 'brexit': 1077, 'negotiations': 5314, 'gigolo': 3426, 'vehicle': 8462, 'plows': 5946, 'man': 4821, 'clapper': 1538, 'admitted': 220, 'spied': 7499, 'false': 3003, 'poodle': 6000, 'poised': 5963, 'ease': 2645, 'rules': 6818, 'religious': 6530, 'groups': 3582, 'politics': 5981, 'churches': 1506, 'pelosi': 5773, 'insecurity': 4135, 'fueling': 3314, 'fraud': 3272, 'contempt': 1803, 'blitz': 939, 'betrays': 856, 'hostility': 3903, 'thumb': 8044, 'rally': 6364, 'brazil': 1059, 'turns': 8273, 'seance': 7012, 'clash': 1542, 'disputed': 2432, 'himalayan': 3820, 'region': 6496, 'barclays': 720, 'ceo': 1381, 'varley': 8452, 'three': 8034, 'bankers': 702, 'appear': 459, 'musical': 5241, 'sen': 7065, 'flake': 3155, 'or': 5539, 'lose': 4738, 'iranians': 4224, 'scheme': 6944, 'butcher': 1181, 'nato': 5288, 'countries': 1896, 'fires': 3132, 'eastern': 2650, 'coast': 1601, 'fireworks': 3133, 'friends': 3291, 'scolds': 6965, 'ceos': 1382, 'pulled': 6259, 'vagina': 8440, 'heading': 3732, 'toward': 8136, 'some': 7418, 'losses': 4743, 'midterm': 5034, 'races': 6333, 'polls': 5984, 'horse': 3894, 'ties': 8055, 'increasingly': 4070, 'credible': 1949, 'laundry': 4544, 'restricting': 6639, 'coal': 1599, 'companies': 1688, 'dumping': 2612, 'waste': 8624, 'streams': 7672, 'nypd': 5442, 'nobody': 5376, 'deported': 2258, 'jumping': 4361, 'turnstile': 8274, 'rope': 6790, 'gaza': 3383, 'rights': 6724, 'commissioner': 1676, 'criticizes': 1975, 'cupcakes': 2020, 'duterte': 2621, 'spokesman': 7519, 'return': 6667, 'philippine': 5838, 'fugitive': 3316, 'bilateral': 883, 'reward': 6699, 'balloon': 686, 'federal': 3060, 'deport': 2255, 'innovative': 4131, 'economies': 2660, 'ellison': 2711, 'backs': 656, 'chairs': 1395, 'toyota': 8144, 'boats': 965, 'dodges': 2481, 'press': 6105, 'spirals': 7506, 'harasses': 3683, 'japan': 4285, 'declines': 2145, 'comment': 1670, 'sushi': 7805, 'kelli': 4392, 'ward': 8595, 'clean': 1551, 'foremost': 3232, 'bikini': 881, 'dna': 2470, 'scratch': 6982, 'alter': 353, 'blueprint': 958, 'sasquatch': 6900, 'lead': 4563, 'reform': 6482, 'needs': 5311, 'stupid': 7708, 'social': 7405, 'data': 2083, 'shared': 7144, 'agencies': 269, 'cat': 1322, 'harsh': 3696, 'language': 4512, 'little': 4691, 'precedent': 6075, 'dogs': 2489, 'hoagie': 3843, 'london': 4719, 'molotov': 5140, 'cocktails': 1611, 'terrorists': 7975, 'van': 8448, 'bartenders': 735, 'announced': 409, 'venezuela': 8465, 'turnout': 8272, 'constituent': 1786, 'assembly': 548, 'vote': 8546, 'drilling': 2573, 'read': 6406, 'coretta': 1852, 'letter': 4617, 'outside': 5590, 'mcconnell': 4935, 'march': 4856, 'cities': 1520, 'across': 184, 'mockery': 5120, 'pete': 5825, 'passage': 5718, 'delivering': 2207, 'wanted': 8591, 'racists': 6339, 'calais': 1211, 'leaves': 4582, 'teenage': 7931, 'refugees': 6486, 'critical': 1971, 'smuggling': 7369, 'gangs': 3366, 'exploit': 2928, 'desperation': 2283, 'turtles': 8276, 'gateshead': 3379, 'nothing': 5408, 'urges': 8418, 'other': 5568, 'local': 4709, 'authorities': 611, 'cheapskates': 1438, 'gm': 3458, 'company': 1689, 'production': 6162, 'shenanigans': 7162, 'likely': 4655, 'headquarters': 3734, 'few': 3089, 'decades': 2129, 'reported': 6580, 'maryland': 4886, 'sparking': 7465, 'lockdown': 4713, 'sparklers': 7466, 'faithful': 2992, 'flock': 3179, 'vatican': 8455, 'pope': 6008, 'christmas': 1498, 'eve': 2849, 'mall': 4816, 'global': 3454, 'investors': 4205, 'fresh': 3285, 'fudge': 3310, 'realizing': 6419, 'legislative': 4602, 'agenda': 271, 'hands': 3670, 'menu': 4994, 'hhs': 3797, 'readying': 6412, 'expand': 2899, 'conscience': 1771, 'protections': 6213, 'eliminate': 2708, 'cripple': 1967, 'purchase': 6281, 'call': 1216, 'includes': 4060, 'plea': 5933, 'moral': 5173, 'courage': 1903, 'gun': 3607, 'legislation': 4601, 'mind': 5061, 'dakota': 2056, 'protested': 6217, 'leaks': 4573, 'animals': 398, 'manhandled': 4829, 'fcc': 3049, 'net': 5323, 'neutrality': 5331, 'rumble': 6821, 'threw': 8035, 'bus': 1169, 'failure': 2985, 'sloths': 7339, 'stocks': 7640, 'lower': 4756, 'successful': 7729, 'mocking': 5121, 'influential': 4104, 'outsiders': 5591, 'played': 5925, 'pruitt': 6232, 'wizards': 8785, 'told': 8089, 'ny': 5440, 'schneiderman': 6950, 'abuse': 141, '2013': 40, 'plane': 5909, 'crashes': 1934, 'bicycle': 869, 'budget': 1126, 'safe': 6851, 'mother': 5189, 'roaches': 6745, 'violated': 8506, 'constitution': 1788, 'speech': 7479, 'martini': 4884, 'scarborough': 6931, 'awkward': 636, 'silence': 7242, 'admission': 216, '43': 79, 'farmer': 3026, 'hawaii': 3719, 'smuggled': 7367, '15': 17, 'deportation': 2256, 'battle': 761, 'returns': 6669, 'salmon': 6870, 'hyping': 3966, '77': 103, 'previously': 6118, 'omitted': 5504, 'assets': 553, 'pennies': 5786, 'banker': 701, 'home': 3862, 'loans': 4703, 'leftovers': 4591, 'loves': 4753, 'wing': 8749, 'radical': 6343, 'equally': 2805, 'serious': 7094, 'adl': 212, 'music': 5240, 'prepared': 6090, 'litigate': 4690, 'time': 8063, 'warner': 8603, 'cry': 2004, 'camp': 1228, 'january': 4284, 'igloo': 3987, 'plead': 5934, 'stay': 7600, 'message': 5005, 'pass': 5717, 'overhaul': 5603, 'qualcomm': 6304, 'regulators': 6504, 'push': 6286, '44': 80, 'nxp': 5439, 'overlords': 5604, 'deflects': 2182, 'nunes': 5434, 'lasers': 4525, 'bridgegate': 1086, 'lands': 4507, 'christie': 1497, 'baroni': 726, 'cells': 1368, 'seek': 7040, 'citing': 1522, 'nastiness': 5280, 'era': 2812, 'dinners': 2347, 'uk': 8304, 'universities': 8369, 'tackle': 7860, 'tide': 8053, 'antisemitism': 429, 'campus': 1236, 'relative': 6520, 'denounced': 2236, 'supremacy': 7780, 'resigns': 6615, 'wizard': 8784, 'eu': 2841, 'aluminum': 356, 'deodorant': 2245, 'suddenly': 7740, 'replaces': 6577, 'acting': 187, 'customs': 2035, 'head': 3729, 'daniel': 2073, 'ragsdale': 6350, 'thomas': 8022, 'homan': 3861, 'ugly': 8303, 'pointed': 5960, 'conflict': 1747, 'energy': 2764, 'voter': 8548, 'runs': 6828, 'inauguration': 4053, 'crowd': 1989, '2009': 37, 'vs': 8558, 'stadium': 7551, 'approved': 479, 'ladders': 4494, 'around': 513, 'kisses': 4441, 'waffle': 8565, 'al': 308, 'franken': 3267, 'slams': 7307, 'education': 2672, 'betsy': 858, 'devos': 2313, 'incompetent': 4066, 'cabinet': 1200, 'level': 4621, 'ever': 2854, 'moons': 5167, 'promised': 6179, 'access': 152, 'exec': 2880, 'crack': 1923, 'listening': 4686, 'bad': 662, 'confession': 1738, 'nevada': 5332, 'wildly': 8739, 'different': 2335, 'elephant': 2704, 'epa': 2800, 'reduce': 6467, 'workforce': 8805, 'buyouts': 1193, 'early': 2637, 'retirement': 6659, 'execution': 2883, 'considered': 1779, 'buses': 1171, 'seat': 7021, 'district': 2449, 'won': 8793, '19': 23, 'opinion': 5526, 'threatening': 8031, 'democracy': 2219, 'undermining': 8331, 'silencing': 7243, 'conservatives': 1777, 'guns': 3611, 'gut': 3612, 'doubles': 2525, 'inherited': 4119, 'mess': 5004, 'claim': 1530, 'dip': 2350, 'expectancy': 2904, 'inequality': 4092, 'upswing': 8412, 'its': 4258, 'entire': 2791, 'resign': 6611, 'prom': 6176, 'reich': 6506, 'warring': 8610, 'camps': 1235, 'potatoes': 6044, 'red': 6459, 'lawmakers': 4553, 'find': 3117, 'blue': 957, 'piggy': 5869, 'impulsive': 4047, 'dancing': 2069, 'dem': 2213, 'nsa': 5418, 'leak': 4570, 'offers': 5480, 'verified': 8474, 'linking': 4675, 'don': 2502, 'mcgahn': 4938, 'threatened': 8030, 'june': 4362, 'sing': 7260, 'cable': 1201, 'careening': 1283, 'defining': 2179, 'moment': 5142, 'broadside': 1103, 'cries': 1958, 'newt': 5342, 'gingrich': 3433, 'him': 3819, 'holds': 3855, 'joint': 4331, 'conference': 1735, 'norway': 5400, 'updates': 8400, 'sir': 7271, 'known': 4460, 'age': 267, '89': 113, 'due': 2604, 'cancer': 1250, 'aid': 290, 'withdrawing': 8774, 'shoe': 7184, 'limits': 4662, 'retirements': 6660, 'create': 1940, 'competitive': 1697, 'speed': 7481, 'probably': 6144, 'grandpa': 3528, 'posts': 6040, '192': 25, 'february': 3057, 'monopoly': 5154, 'bob': 966, 'hertzberg': 3790, 'cooperate': 1839, 'unwanted': 8394, 'hugs': 3931, 'aromas': 512, 'giant': 3415, 'shipworm': 7175, 'philippines': 5839, 'dreadlock': 2560, 'barack': 712, 'chicago': 1464, 'library': 4636, 'nor': 5393, 'believer': 824, 'community': 1687, 'museum': 5238, 'kristol': 4471, 'voice': 8537, 'biggest': 878, 'opponents': 5531, 'bladder': 920, 'manslaughter': 4841, 'eyed': 2958, 'grenfell': 3558, 'blaze': 932, 'weed': 8664, 'crime': 1959, 'behind': 816, 'bars': 734, 'plants': 5918, 'seattle': 7024, 'dismiss': 2419, 'misdemeanor': 5088, 'marijuana': 4863, 'dynamite': 2628, 'tough': 8124, 'talk': 7875, 'ballet': 683, 'noncriminal': 5386, 'past': 5727, 'festivals': 3084, 'fear': 3051, 'sweater': 7824, 'examining': 2869, 'tanning': 7886, 'mosque': 5182, 'egypt': 2683, 'sinai': 7258, '235': 54, 'befuddles': 804, 'schumer': 6958, 'donate': 2504, 'harvey': 3701, 'weinstein': 8674, 'cologne': 1640, 'drag': 2548, 'resistance': 6617, 'lingerie': 4670, 'bullet': 1137, 'costs': 1878, 'soar': 7401, 'opening': 5520, 'delayed': 2191, 'algeria': 321, 'dump': 2611, 'scud': 6999, 'ballistic': 685, 'briefed': 1088, 'google': 3489, 'doing': 2490, 'irreparable': 4234, 'hamsters': 3662, 'armenian': 508, 'sobs': 7403, 'skeptical': 7289, 'suit': 7749, 'outfit': 5582, 'italian': 4254, 'pm': 5954, 'gentiloni': 3396, 'slurs': 7349, 'announcement': 410, 'speculation': 7477, 'theresa': 8008, 'debates': 2122, 'tory': 8116, 'sources': 7445, 'favors': 3045, 'names': 5271, 'charmaine': 1428, 'yoest': 8864, 'lonely': 4720, 'chelsea': 1454, 'manning': 4840, 'hurts': 3956, 'congressmen': 1765, 'fault': 3041, 'order': 5545, 'sends': 7071, 'pro': 6143, 'growth': 3586, 'environment': 2795, 'pizza': 5902, 'partner': 5713, 'dressmakers': 2571, 'insurer': 4152, 'flees': 3164, 'blaming': 926, 'sabotage': 6839, 'bats': 758, 'jail': 4272, 'free': 3277, 'cards': 1280, 'work': 8801, 'footloose': 3217, 'keeps': 4390, 'team': 7919, 'guessing': 3597, 'bewildered': 862, 'confirms': 1746, 'reinhold': 6511, 'niebuhr': 5352, 'brayed': 1057, 'hopes': 3886, 'improved': 4043, 'everything': 2858, 'opec': 5517, 'agree': 282, 'extend': 2941, 'vodka': 8535, 'conservative': 1776, 'activist': 190, 'lauren': 4547, 'southern': 7448, 'sorceress': 7434, 'begins': 810, 'attacking': 580, 'crocodile': 1979, '1st': 30, 'amendment': 363, 'speak': 7471, 'college': 1631, 'sneeze': 7381, 'analysis': 380, 'best': 850, 'deals': 2115, 'prove': 6222, 'muffins': 5214, 'jordan': 4339, 'selects': 7054, 'finalists': 3112, '300mw': 63, 'wind': 8743, 'earth': 2641, 'georgia': 3401, 'quiet': 6315, 'tricare': 8205, 'stirs': 7635, 'ire': 4227, 'headaches': 3731, 'becomes': 790, 'popular': 6011, 'modern': 5130, 'mascot': 4889, 'pointing': 5961, 'fingers': 3124, 'stalemate': 7565, 'pool': 6003, 'criminalizing': 1964, 'abortions': 131, 'weeks': 8667, 'burritos': 1167, 'semitic': 7063, 'messages': 5006, 'matzos': 4920, 'yemen': 8858, 'cholera': 1489, 'cases': 1315, 'reach': 6398, 'icrc': 3974, 'hiccup': 3798, 'upper': 8408, 'hand': 3663, 'trillions': 8214, 'breaks': 1068, 'wh': 8690, 'comms': 1683, 'anthony': 424, 'scaramucci': 6930, 'deletes': 2196, 'contradicting': 1810, 'sings': 7265, 'allow': 339, 'buy': 1190, 'equipment': 2810, 'pornography': 6019, 'cash': 1316, 'mccain': 4931, 'joke': 4333, 'controversy': 1818, 'fan': 3013, 'watched': 8628, 'oath': 5444, 'pretty': 6113, 'nasa': 5278, 'ok': 5493, 'touch': 8121, 'hardware': 3690, 'honor': 3872, 'host': 3901, 'xi': 8845, 'takes': 7871, 'rebuttal': 6433, 'protectionism': 6212, 'rant': 6373, 'position': 6030, 'accusers': 168, 'lying': 4772, 'crab': 1922, 'charts': 1430, 'show': 7209, 'ignore': 3990, 'horoscopists': 3890, 'elected': 2694, 'spend': 7489, 'reporters': 6583, 'celebrities': 1363, 'thoughts': 8025, 'distress': 2447, 'signal': 7236, 'upside': 8410, 'pin': 5882, 'smoke': 7362, 'teacher': 7916, 'apologizes': 451, 'accidentally': 155, 'classroom': 1548, 'let': 4614, 'pot': 6042, 'flourish': 3190, 'associated': 558, 'freedom': 3278, 'sanctuary': 6882, 'states': 7595, 'enforcement': 2766, 'driving': 2583, 'performing': 5801, 'nightmare': 5363, 'marathons': 4854, 'colon': 1642, 'businesses': 1175, 'proposal': 6192, 'stink': 7634, 'buzzfeed': 1195, 'unverified': 8393, 'igniting': 3988, 'father': 3038, 'self': 7055, 'imposed': 4035, 'curbs': 2022, 'celibacy': 1365, 'disrupt': 2436, 'rightwing': 6725, 'german': 3404, 'afd': 246, 'goers': 3470, 'netherlands': 5326, 'answer': 419, 'refused': 6490, 'windmill': 8744, 'horses': 3896, 'spending': 7490, 'excludes': 2878, 'declares': 2140, 'anyway': 438, 'bankruptcy': 704, 'admin': 213, 'had': 3628, 'justifiable': 4369, 'sharing': 7147, 'soccer': 7404, 'extremists': 2950, 'triangle': 8200, 'saudi': 6905, 'crownprince': 1992, 'salman': 6869, 'snitches': 7385, 'manchin': 4826, 'skips': 7298, 'informational': 4110, 'useful': 8425, 'idiots': 3984, 'galore': 3356, 'york': 8868, 'times': 8066, 'juggler': 4355, 'aide': 291, 'accused': 166, '2008': 36, 'healing': 3737, 'while': 8700, 'week': 8665, 'snowflakes': 7394, 'play': 5923, 'mainstream': 4799, 'sympathy': 7847, 'pray': 6071, 'lifts': 4649, 'cops': 1846, 'dresses': 2569, 'announces': 411, 'waterpark': 8634, 'problems': 6149, 'obstruction': 5460, 'bribes': 1082, 'tout': 8133, 'daca': 2050, 'quite': 6322, 'cruise': 1999, 'line': 4667, 'carnival': 1290, 'corp': 1860, 'joins': 4330, 'bermuda': 844, 'donut': 2511, 'full': 3320, 'touts': 8135, 'reforms': 6483, 'open': 5518, 'business': 1174, 'eases': 2646, 'service': 7101, 'delivery': 2209, 'religion': 6529, 'responds': 6629, 'sweating': 7825, 'australia': 604, 'accept': 150, 'central': 1378, 'nose': 5402, 'advisers': 237, 'melania': 4973, 'trapped': 8174, 'money': 5149, 'put': 6292, 'danger': 2071, 'recommend': 6447, 'payment': 5753, 'ers': 2821, 'ted': 7927, 'nugent': 5425, 'parkland': 5701, 'teens': 7933, 'nra': 5417, 'soul': 7437, 'corporate': 1861, 'ignores': 3992, 'rise': 6734, 'oligarchy': 5499, 'yeast': 8856, 'dealing': 2112, 'migrant': 5038, 'escalating': 2825, 'whether': 8698, 'keeping': 4389, 'mold': 5136, 'alex': 320, 'jones': 4337, 'fears': 3053, 'come': 1657, 'conspiracy': 1784, 'theorist': 8005, 'bro': 1098, 'anymore': 434, 'prance': 6063, 'bird': 900, 'devil': 2311, 'theory': 8006, 'endorses': 2758, 'lgbt': 4624, 'attorneys': 591, 'argue': 497, 'gays': 3382, 'voterbase': 8549, 'terms': 7967, 'ratings': 6389, 'jeopardize': 4300, 'suntan': 7761, 'futures': 3342, 'point': 5959, 'sharply': 7149, 'street': 7674, 'friendly': 3290, 'cohn': 1619, 'bridge': 1085, 'feared': 3052, 'storm': 7657, 'swamps': 7817, 'undead': 8323, 'led': 4585, 'enforce': 2765, 'axes': 638, 'transgender': 8167, 'independent': 4076, 'trees': 8192, 'secretly': 7029, 'helping': 3772, 'chechen': 1440, 'flee': 3163, 'persecution': 5809, 'radar': 6341, 'programme': 6169, 'mired': 5081, 'paralysis': 5687, 'defy': 2184, 'recovery': 6453, 'child': 1472, 'labor': 4486, 'jobs': 4322, 'pies': 5866, 'waiting': 8572, 'permanent': 5803, 'clearance': 1556, 'guard': 3591, 'caroline': 1293, 'glick': 3450, 'gives': 3442, 'cause': 1344, 'camel': 1224, 'candidates': 1252, 'winning': 8754, 'explains': 2921, 'reasons': 6424, 'risque': 6740, 'dealmaking': 2114, 'mode': 5124, 'works': 8807, 'scenes': 6940, 'duck': 2601, 'describes': 2272, 'words': 8799, 'clothing': 1585, 'bush': 1172, 'diplomat': 2353, 'scared': 6934, 'legalise': 4596, 'isolated': 4245, 'settlement': 7110, 'settler': 7112, 'murdered': 5230, 'netanyahu': 5324, 'dumpster': 2615, 'timing': 8068, 'again': 265, 'suggests': 7746, 'tweeted': 8283, 'watching': 8630, 'segment': 7049, 'chick': 1465, 'painting': 5651, 'temporarily': 7946, 'breakout': 1067, 'meal': 4943, 'look': 4723, 'pumpkin': 6265, 'broke': 1107, 'ethics': 2838, 'laws': 4555, 'jaywalking': 4292, 'dubs': 2600, 'knight': 4455, 'lavishes': 4549, 'carpet': 1295, 'treatment': 8188, 'arrives': 520, 'jinping': 4319, 'oscars': 5564, 'blocks': 946, 'clinic': 1568, 'band': 695, 'blake': 922, 'farenthold': 3022, 'diving': 2461, 'went': 8682, 'listen': 4684, 'fast': 3032, 'haters': 3710, 'clearly': 1559, 'trap': 8173, 'affirmative': 253, 'hypocrisy': 3968, 'foes': 3202, 'diversity': 2456, 'those': 8023, 'oppose': 5532, 'my': 5251, 'dad': 2052, 'funny': 3334, 'nsc': 5419, 'dense': 2238, 'confused': 1754, 'facebook': 2967, 'bans': 710, 'jehovah': 4297, 'witnesses': 8781, 'claiming': 1532, 'extremist': 2949, 'activities': 192, 'petraeus': 5829, 'warns': 8606, 'current': 2027, 'fray': 3274, 'collapse': 1624, 'harvester': 3699, 'trumpcare': 8240, 'question': 6310, 'whole': 8716, 'economic': 2659, 'dementia': 2218, 'western': 8687, 'airstrikes': 305, 'unlikely': 8373, 'impact': 4018, 'machine': 4779, 'evangelical': 2846, 'slippery': 7330, 'slope': 7336, 'ronald': 6782, 'reagan': 6413, 'soap': 7400, 'weaving': 8657, 'propagandistic': 6189, 'fantasy': 3017, 'tickled': 8049, 'doug': 2527, 'upset': 8409, 'bed': 792, 'beneath': 834, 'dignity': 2339, 'sweeteners': 7829, 'certified': 1387, 'dumb': 2608, 'ass': 538, 'psychologist': 6239, 'psychoneurotic': 6240, 'shut': 7224, 'computer': 1712, 'girls': 3438, 'become': 789, 'brides': 1084, 'malaysia': 4812, 'immediately': 4009, 'bolt': 975, 'nafta': 5261, 'join': 4327, 'keefe': 4386, 'busts': 1178, 'editor': 2670, 'explaining': 2920, 'paper': 5678, 'narrative': 5277, 'demands': 2216, 'withdraw': 8772, 'branding': 1052, 'apartheid': 441, 'tractor': 8150, 'erdogan': 2814, 'clucking': 1593, 'pershing': 5810, 'cited': 1518, 'effect': 2674, 'remains': 6535, 'wynn': 8844, 'finance': 3114, 'reclining': 6444, 'suck': 7735, 'mitt': 5111, 'romney': 6781, 'trolled': 8223, 'flip': 3172, 'flopping': 3186, 'endorsement': 2757, 'wig': 8730, 'triggers': 8212, 'alarm': 310, 'warnings': 8605, 'living': 4697, 'weak': 8644, 'unstable': 8386, 'warned': 8602, 'seth': 7108, 'murder': 5229, 'staffer': 7554, 'protect': 6208, 'newscasters': 5340, 'iraqi': 4226, 'forces': 3225, 'tigris': 8061, 'stronghold': 7691, 'mosul': 5187, 'clubhouse': 1591, 'policies': 5972, 'guardian': 3592, 'hotel': 3908, 'raised': 6357, 'room': 6786, 'rates': 6386, 'colluded': 1638, 'fuck': 3309, 'daughters': 2091, 'too': 8100, 'takeover': 7870, 'aecon': 244, 'grounds': 3579, 'takeout': 7869, 'clue': 1594, 'true': 8238, 'sacrifice': 6844, 'bakeries': 674, 'jong': 4338, 'agrees': 285, 'dmz': 2469, 'jackie': 4266, 'mason': 4891, 'grammys': 3520, 'competition': 1696, 'hates': 3711, 'watch': 8626, 'advocate': 241, 'matt': 4916, 'schlapp': 6948, 'treasonous': 8183, 'golf': 3480, 'thumbs': 8045, 'controversies': 1817, 'navarro': 5295, 'diplomats': 2355, 'video': 8490, 'eagles': 2635, 'defensiveness': 2171, 'handling': 3668, 'grief': 3559, 'worse': 8815, 'mail': 4796, 'geun': 3411, 'hye': 3962, 'impeachment': 4022, 'trial': 8199, 'dancer': 2066, 'minnesota': 5073, 'tom': 8093, 'emmer': 2731, 'snow': 7393, 'boris': 1012, 'condemned': 1724, 'libya': 4637, 'bodies': 968, 'jokes': 4335, 'bleach': 934, 'backed': 647, 'given': 3441, 'spa': 7453, 'spies': 7500, 'targeting': 7897, 'maritime': 4867, 'industry': 4091, 'cape': 1267, 'town': 8141, 'drought': 2591, 'avoid': 626, 'zero': 8883, 'towel': 8138, 'organisation': 5550, 'lack': 4491, 'scientific': 6960, 'thinking': 8018, 'store': 7654, 'nancy': 5272, 'hails': 3630, 'owe': 5619, 'parents': 5697, 'bring': 1092, 'kids': 4419, 'dolls': 2495, 'le': 4562, 'pen': 5776, 'moves': 5205, 'monde': 5148, 'studio': 7700, 'swedish': 7827, 'prosecutor': 6201, 'truck': 8234, 'spoken': 7518, 'stuffing': 7702, 'sad': 6849, 'view': 8493, 'depression': 2263, 'arrested': 517, 'linda': 4665, 'wenzel': 8683, 'shepherd': 7163, 'vermont': 8476, 'governor': 3503, 'vetoes': 8482, 'changes': 1410, 'joints': 4332, 'employee': 2738, 'controversial': 1816, 'promotes': 6183, 'mascots': 4890, 'sprinter': 7532, 'thanksgiving': 7993, 'majority': 4802, 'prefer': 6080, 'side': 7229, 'wrestle': 8832, 'biden': 871, 'liar': 4628, 'nicest': 5350, 'sweetheart': 7832, 'resubmit': 6643, 'renewals': 6556, 'originally': 5558, 'rejected': 6514, 'late': 4528, 'ross': 6794, 'linked': 4673, 'shipping': 7174, 'concern': 1715, 'brothel': 1113, 'wiretap': 8762, 'alien': 325, 'royals': 6808, 'crown': 1991, 'prince': 6127, 'participation': 5708, 'olympics': 5502, 'affect': 249, 'centenarian': 1374, 'union': 8361, 'lap': 4515, 'landfill': 4501, 'chairman': 1394, 'pai': 5644, 'substituting': 7723, 'ideology': 3982, 'art': 522, 'chuckle': 1501, 'messing': 5008, 'picture': 5861, 'perfect': 5798, 'simpletons': 7255, 'millennials': 5051, 'bitcoin': 911, 'steal': 7606, 'genius': 3394, 'means': 4945, 'smarts': 7353, 'path': 5734, 'fails': 2984, 'unity': 8366, 'cambridge': 1222, 'analytica': 381, 'friend': 3288, 'footballs': 3216, 'plotted': 5944, 'effort': 2677, 'rival': 6741, 'shave': 7150, 'cannabis': 1258, 'halved': 3652, 'convulsions': 1828, 'funded': 3326, 'epilepsy': 2803, 'munchies': 5228, 'famine': 3011, 'sudan': 7738, 'charge': 1420, 'permits': 5806, 'consumer': 1794, 'protection': 6211, 'puts': 6294, 'equifax': 2808, 'hayden': 3724, 'willing': 8741, 'throw': 8039, 'almost': 347, 'anything': 436, 'de': 2105, 'legitimize': 4604, 'portrait': 6023, 'widespread': 8727, 'killings': 4424, 'cast': 1319, 'shadow': 7130, 'laughter': 4539, 'suspected': 7807, 'rebel': 6427, 'planted': 5917, 'mine': 5063, 'yemeni': 8859, 'ship': 7173, 'instant': 4145, 'questioned': 6311, 'nightmares': 5364, 'slogan': 7335, 'drinking': 2576, 'award': 631, 'uplifting': 8406, 'stories': 7656, 'remind': 6542, 'jeremy': 4301, 'scahill': 6919, 'fareed': 3021, 'zakaria': 8877, 'bashes': 743, 'silo': 7248, 'waters': 8635, 'conversation': 1822, 'chocolate': 1484, '63rd': 93, 'straight': 7663, 'quarter': 6305, 'propaganda': 6188, 'residents': 6610, 'presidential': 6103, 'palace': 5655, 'terrorism': 7973, 'percent': 5796, 'murders': 5234, 'newborns': 5336, 'pledged': 5941, 'relief': 6527, 'constipation': 1785, 'loosely': 4733, 'regulated': 6501, 'market': 4870, 'biofuel': 897, 'credits': 1953, 'spurs': 7534, 'speculators': 7478, 'swindlers': 7837, 'polluters': 5987, 'founder': 3254, 'bringing': 1093, 'panthers': 5672, 'pa': 5627, 'start': 7585, 'unborn': 8318, 'unicorns': 8355, 'oversight': 5609, 'fiscal': 3139, 'mob': 5117, 'building': 1133, 'mysterious': 5257, 'artificial': 526, 'worshiping': 8818, '202': 45, 'run': 6824, 'dematerialize': 2217, 'newly': 5338, 'released': 6524, 'howard': 3920, 'stern': 7623, 'tapes': 7890, 'feature': 3054, 'admitting': 221, 'psychological': 6238, 'rt': 6810, 'sputnik': 7535, 'ads': 227, 'interference': 4168, 'yorker': 8869, 'lizza': 4700, 'improper': 4041, 'hippo': 3828, 'katie': 4384, 'incumbent': 4071, '25': 57, 'nibble': 5348, 'blow': 953, 'ukraines': 8306, 'ammunition': 368, 'supplies': 7769, 'cupcake': 2019, 'francis': 3264, 'fights': 3101, 'employees': 2739, 'used': 8424, 'improve': 4042, 'wheelchairs': 8695, 'malls': 4818, 'finds': 3118, 'sloppy': 7337, 'misconduct': 5087, 'handwriting': 3672, 'vice': 8485, 'documentary': 2476, 'worth': 8820, 'pirating': 5893, 'poultry': 6047, 'reviews': 6686, 'guam': 3587, 'stark': 7583, 'quit': 6321, 'allegations': 332, 'sneezing': 7382, 'medicaid': 4959, 'kentucky': 4398, 'slash': 7312, '9000': 117, 'portrays': 6024, 'destroyed': 2293, 'barrage': 728, 'spaghetti': 7456, 'dhs': 2315, 'electronics': 2701, 'expanded': 2900, 'flights': 3171, 'departing': 2247, 'wires': 8761, 'tattoo': 7902, 'gabbanelli': 3345, 'cantabella': 1263, 'accordion': 159, 'sock': 7409, 'mouth': 5201, 'nielsen': 5354, 'never': 5333, 'trumper': 8242, 'barber': 716, 'tame': 7879, 'wades': 8564, 'deeper': 2156, 'hesitation': 3791, 'underwater': 8336, 'preparing': 6092, 'subpoena': 7715, 'memos': 4987, 'gubernatorial': 3594, '400': 75, 'trebek': 8189, 'tries': 8209, 'moderator': 5129, 'sells': 7061, 'jacks': 4267, 'aiming': 297, 'christians': 1496, 'minority': 5075, 'pakistan': 5654, 'affiliated': 252, 'coalition': 1600, 'mulvaney': 5225, 'difficult': 2336, 'casino': 1317, 'manipulate': 4835, 'delousing': 2210, 'rand': 6367, 'arms': 510, 'arabia': 486, 'camels': 1225, 'outcry': 5581, 'infosys': 4113, 'hire': 3830, 'targets': 7898, 'outsourcing': 5592, 'dishwasher': 2412, 'postpones': 6039, 'hearing': 3744, 'personal': 5815, 'facing': 2972, 'felony': 3072, 'united': 8365, 'clown': 1588, 'swaps': 7820, 'beloved': 828, 'burgers': 1156, 'salads': 6858, 'soups': 7443, 'diet': 2332, 'ireland': 4228, 'enda': 2751, 'kenny': 4397, 'rub': 6811, 'jobless': 4321, 'plunge': 5952, 'lowest': 4758, 'weekly': 8666, 'tally': 7878, '1973': 27, 'seals': 7010, 'noun': 5411, 'verb': 8471, 'vladimir': 8532, 'adjective': 211, 'iraq': 4225, 'shopkeeper': 7192, 'such': 7734, 'obvious': 5461, 'lies': 4644, 'catalonia': 1327, 'puigdemont': 6256, 'defeat': 2160, 'spanish': 7459, 'raffle': 6346, 'real': 6414, 'superman': 7765, 'spiderman': 7497, 'propose': 6194, 'requiring': 6599, 'fair': 2988, 'prices': 6120, 'taxpayer': 7911, 'drugs': 2593, 'highs': 3809, 'shady': 7132, 'dealings': 2113, 'evoke': 2861, 'nepotism': 5319, 'corruption': 1869, 'gilded': 3427, 'snack': 7370, 'bound': 1031, 'singing': 7263, 'couple': 1901, 'rented': 6562, 'condo': 1729, 'pays': 5757, 'fine': 3119, 'condor': 1730, 'happy': 3680, 'europe': 2843, 'peanuts': 5763, 'lynch': 4773, 'prosecution': 6200, 'pleas': 5937, 'chauvinist': 1434, 'greeted': 3554, 'selfies': 7057, 'arrival': 519, 'english': 2773, 'speaking': 7473, 'powerful': 6054, 'stepping': 7618, 'evolution': 2862, 'ignored': 3991, 'fraudulent': 3273, 'comments': 1673, 'scoundrel': 6974, 'upcoming': 8398, 'karaoke': 4380, 'deputy': 2266, 'felt': 3073, 'pressured': 6107, 'christopher': 1499, 'wray': 8827, 'wasserman': 8623, 'schultz': 6957, 'pimple': 5880, 'throws': 8043, 'pitcher': 5898, 'bathtub': 757, 'admits': 219, 'conversations': 1823, 'taunts': 7904, 'teach': 7915, 'partisanship': 5712, 'phonebook': 5842, 'decided': 2133, 'disband': 2382, 'claimed': 1531, 'disbanded': 2383, 'guggenheim': 3599, 'gogh': 3472, 'toilet': 8087, 'target': 7895, 'coordination': 1841, 'expert': 2916, 'decorator': 2149, 'wrestling': 8835, 'championship': 1403, 'dirt': 2367, 'ag': 264, 'tarmac': 7900, 'innocuous': 4129, 'teleportation': 7936, 'canceled': 1246, 'stolen': 7643, 'lennon': 4607, 'items': 4257, 'recovered': 6452, 'berlin': 843, 'tub': 8255, 'corbyn': 1849, 'woos': 8797, 'small': 7351, 'crackdown': 1924, 'payments': 5754, 'deliveries': 2206, 'enrique': 2782, 'peña': 5833, 'nieto': 5355, 'cancels': 1249, 'planned': 5913, 'passed': 5719, 'detector': 2301, 'which': 8699, 'unprotected': 8381, 'met': 5009, 'breitbart': 1073, '45': 81, 'trafficked': 8156, 'website': 8659, 'beats': 782, 'huffpo': 3927, 'wapo': 8593, 'foxnews': 3259, 'pageviews': 5643, 'owns': 5624, 'gina': 3431, 'haspel': 3704, 'lean': 4574, 'confectioner': 1732, 'transcript': 8165, 'stoneman': 7646, 'hall': 3647, 'repeatedly': 6571, 'shouts': 7206, 'raucous': 6394, 'panda': 5664, 'green': 3548, 'introduces': 4189, 'articles': 525, 'stole': 7642, 'banks': 705, 'incompetence': 4065, 'profit': 6166, 'divisive': 2464, 'brands': 1053, 'acronyms': 183, 'strategy': 7668, 'afghanistan': 257, 'figure': 3102, 'heather': 3752, 'heyer': 3795, 'funeral': 3331, 'proposition': 6197, 'trending': 8196, 'st': 7546, 'patrick': 5740, 'clover': 1587, 'confusion': 1756, 'sexist': 7120, 'row': 6805, 'catawampus': 1330, 'eurosceptic': 2845, 'govt': 3504, 'linebacker': 4668, 'watchdog': 8627, 'actress': 196, 'intellectual': 4157, 'righ': 6722, 'dinosaurs': 2349, 'swalwell': 7815, 'dares': 2076, 'declassify': 2143, 'backing': 652, 'amputations': 375, 'arab': 485, 'qatar': 6300, 'memoir': 4983, 'reveal': 6675, 'barred': 729, 'opinions': 5527, 'publisher': 6247, 'expelled': 2910, 'monkey': 5152, 'tuesday': 8257, 'indiana': 4080, 'ohio': 5491, 'carolina': 1292, 'furniture': 3335, 'plastic': 5919, 'pollution': 5988, 'wildlife': 8738, 'scotland': 6969, 'beautiful': 783, 'beaches': 769, 'tourist': 8130, 'juanita': 4347, 'broaddrick': 1101, 'handler': 3667, 'raped': 6376, 'ghost': 3412, 'stars': 7584, 'nudists': 5423, 'climber': 1566, 'penalty': 5777, 'rapists': 6378, 'legalizes': 4599, '418m': 77, 'sale': 6863, 'kenya': 4399, 'paraplegic': 5691, 'smokes': 7363, 'constitutional': 1789, 'verge': 8473, 'anniversary': 407, 'barcelona': 719, 'avoiding': 627, 'button': 1188, 'bigger': 877, 'yvette': 8876, 'cooper': 1838, 'urgent': 8417, 'commons': 1682, 'ending': 2756, 'reset': 6606, 'knife': 4454, 'fentanyl': 3080, 'deaths': 2118, 'outpace': 5586, 'prescription': 6095, 'painkiller': 5648, 'overdoses': 5601, 'chainsaw': 1392, 'cpac': 1921, 'identity': 3981, 'inviting': 4211, 'milo': 5057, 'symptom': 7849, 'ails': 294, 'conservatism': 1775, 'disinviting': 2416, 'raccoons': 6330, 'infuriated': 4117, 'refusal': 6489, 'preview': 6117, 'sleepover': 7320, 'indonesia': 4088, 'estate': 2834, 'project': 6174, 'confuses': 1755, 'curb': 2021, 'cookies': 1833, 'pillow': 5876, 'animal': 397, 'metoo': 5013, 'actual': 198, 'rebels': 6428, 'operation': 5524, 'idlib': 3985, 'drain': 2551, 'swamp': 7816, 'diverted': 2457, 'tissue': 8076, 'botches': 1022, 'beginning': 809, 'deliver': 2204, 'paychecks': 5751, 'babies': 641, 'dutch': 2620, 'pushups': 6290, 'toupees': 8127, 'undocumented': 8340, 'backbone': 646, 'dairies': 2055, 'trouble': 8230, 'staying': 7601, 'focused': 3201, 'indictments': 4084, 'recipes': 6441, 'curved': 2032, 'penises': 5785, 'greater': 3544, 'angles': 395, 'gluten': 3457, 'empathy': 2736, 'argument': 498, 'brings': 1094, 'approach': 475, 'jiggle': 4312, 'date': 2086, 'announce': 408, 'monday': 5147, 'tuna': 8262, 'burger': 1155, 'pushes': 6288, 'section': 7031, '301': 64, 'trail': 8158, 'revealing': 6677, 'secrets': 7030, 'ignorance': 3989, 'alternative': 354, 'scandel': 6929, 'pug': 6254, 'snubs': 7398, 'mummy': 5227, 'praise': 6059, 'witches': 8770, 'excited': 2877, 'replace': 6574, 'kidnap': 4416, 'banksy': 706, 'bethlehem': 853, 'worst': 8819, 'speedy': 7484, 'conflicts': 1749, 'interest': 4164, 'infant': 4093, 'await': 629, 'countermemo': 1891, 'languishes': 4513, 'truth': 8250, 'assange': 541, 'sycophant': 7843, 'delicatessens': 2200, 'marathon': 4853, 'rough': 6796, 'appointments': 473, 'prioritize': 6132, 'crucifix': 1995, 'explain': 2918, 'bacon': 660, 'admonish': 222, 'pudding': 6250, 'squatting': 7538, 'mission': 5102, 'accomplished': 156, 'bombing': 981, 'thought': 8024, 'unlike': 8372, 'share': 7143, 'sensitive': 7076, 'blonde': 948, 'sanitary': 6890, 'pads': 5639, 'being': 818, 'collected': 1628, 'reactor': 6404, 'dark': 2077, 'moods': 5165, 'scrutiny': 6997, 'shadowy': 7131, 'pants': 5675, 'beto': 854, 'rourke': 6802, 'cruz': 2003, 'laps': 4517, 'where': 8697, 'learned': 4577, 'love': 4750, 'assail': 540, 'unilateralism': 8357, 'culture': 2016, 'tepco': 7962, 'bosses': 1018, 'plant': 5916, 'crooks': 1982, 'mere': 4997, 'counterspies': 1893, 'temer': 7941, 'passive': 5724, 'aggressiveness': 277, 'capturing': 1275, 'creditors': 1952, 'hip': 3825, 'hop': 3883, 'lyrics': 4774, 'mommy': 5145, 'protester': 6218, 'escorted': 2828, '39': 73, 'deer': 2157, 'daunting': 2092, 'list': 4683, 'nkorea': 5371, 'dances': 2068, 'letting': 4619, 'go': 3460, 'television': 7937, 'criminal': 1962, 'carriers': 1300, 'operate': 5523, 'noodles': 5391, 'stopped': 7652, 'then': 8003, 'cop': 1844, 'punched': 6267, 'choked': 1487, 'shot': 7200, 'proposals': 6193, 'improving': 4046, 'systems': 7855, 'edition': 2669, 'beast': 778, 'remake': 6536, 'embrace': 2723, 'signaling': 7237, 'skill': 7293, 'turning': 8270, 'awards': 632, 'counter': 1890, 'pooch': 5999, 'warren': 8609, 'buffett': 1129, 'berkshire': 842, 'hathaway': 3712, 'dumps': 2614, 'vampire': 8445, 'hello': 3768, 'called': 1217, 'cellphone': 1366, 'blows': 956, 'background': 651, 'earlier': 2636, 'acknowledged': 176, 'skinny': 7296, 'spiral': 7505, 'muslim': 5244, 'videos': 8491, 'produce': 6157, 'slump': 7347, 'remington': 6544, 'files': 3106, 'tumble': 8259, 'bayonet': 764, 'challenge': 1397, 'arkansas': 502, 'medication': 4962, 'raps': 6380, 'retreat': 6663, 'finland': 3126, 'colombian': 1641, 'farc': 3020, 'final': 3111, 'calendar': 1213, 'meat': 4950, 'janitor': 4282, 'nap': 5274, 'sue': 7741, 'approving': 481, 'holocaust': 3860, 'denier': 2232, 'chooses': 1492, 'seems': 7046, 'backup': 658, 'mitch': 5110, 'bathe': 751, 'koch': 4463, 'brothers': 1115, 'loyal': 4759, 'servants': 7097, 'serving': 7103, 'sisters': 7273, 'relevance': 6526, 'reject': 6513, 'isolationism': 4246, 'cheeseburgers': 1450, 'left': 4589, 'pundits': 6272, 'drooled': 2587, 'puns': 6276, 'tracking': 8149, 'dystopia': 2631, 'pivots': 5901, 'insanity': 4133, 'finally': 3113, 'universal': 8367, 'everyone': 2857, 'margarita': 4860, 'blast': 929, 'kurdish': 4476, 'diyarbakir': 2467, 'conway': 1829, 'gaining': 3351, 'steam': 7608, 'trains': 8164, 'ancient': 385, 'frozen': 3305, 'tomb': 8096, 'scythian': 7003, 'siberia': 7227, 'alligator': 336, 'inflammatory': 4098, 'offensive': 5475, 'aborts': 132, 'pregnancy': 6083, 'center': 1376, 'clients': 1562, 'rely': 6532, 'upbeat': 8397, 'victims': 8488, 'loot': 4734, 'burn': 1160, 'collision': 1636, 'directive': 2363, 'airport': 303, 'turmoil': 8268, 'mounts': 5196, 'hats': 3714, 'funerals': 3332, 'weight': 8671, 'soldiers': 7415, 'took': 8101, 'night': 5361, 'addicts': 206, 'easy': 2651, 'slaughterhouse': 7314, 'employed': 2737, 'illegal': 3997, 'clones': 1573, 'dr': 2545, 'congo': 1758, '250': 58, 'ethnic': 2839, 'massacres': 4894, 'talking': 7876, 'sure': 7782, 'wire': 8760, 'diaper': 2319, 'fellow': 3070, 'impossible': 4037, 'onto': 5514, 'removing': 6552, 'costume': 1879, 'ad': 200, 'calling': 1218, 'complicit': 1706, 'dieting': 2333, 'japanese': 4286, 'ministry': 5072, 'proposed': 6195, 'cover': 1911, 'land': 4500, 'heart': 3747, 'mao': 4849, 'stalin': 7566, 'authoritarianism': 610, '101': 6, 'kasich': 4381, 'hickenlooper': 3800, '2020': 46, 'happen': 3675, 'fail': 2980, 'glitch': 3451, 'lets': 4616, 'corporations': 1862, 'infra': 4115, 'ultrasonic': 8308, 'waves': 8637, 'responsible': 6632, 'cuba': 2007, 'bat': 749, 'gaffe': 3348, 'product': 6161, 'fit': 3146, 'pigeons': 5868, 'publishes': 6249, 'trigger': 8210, 'article': 524, 'kitty': 4448, 'missouri': 5104, 'spit': 7509, 'half': 3646, 'poverty': 6050, 'discrimination': 2400, 'balloons': 687, 'unsolved': 8385, 'dilemma': 2340, 'inflict': 4101, 'pain': 5646, 'admit': 218, 'roasting': 6750, 'young': 8872, 'afghans': 258, 'taliban': 7874, 'quack': 6302, 'session': 7105, 'protest': 6216, 'nomination': 5381, 'kimmel': 4430, 'using': 8430, 'medical': 4960, 'score': 6966, 'penguin': 5781, 'allowing': 342, 'darkest': 2078, 'spent': 7491, '230k': 53, 'covering': 1914, 'fees': 3067, 'britches': 1096, 'norwegians': 5401, 'hole': 3856, 'takeaways': 7867, 'startling': 7587, 'priority': 6133, 'safer': 6853, 'partying': 5716, 'beacon': 770, 'initial': 4121, 'fusion': 3340, 'gps': 3507, 'research': 6602, 'convention': 1820, 'unplumbed': 8379, 'depths': 2265, 'sinks': 7269, 'wacko': 8562, 'caps': 1270, 'form': 3243, 'assault': 546, 'carve': 1313, 'glacier': 3444, 'exists': 2896, '70': 99, 'die': 2328, 'adulthood': 228, 'insists': 4139, 'someday': 7419, 'dictators': 2325, 'tweetstorms': 8287, 'briefings': 1090, 'shirt': 7177, 'zuckerberg': 8899, 'officially': 5485, 'gates': 3378, 'rain': 6354, 'snap': 7376, 'cbo': 1353, 'premiums': 6086, 'expensive': 2913, '140': 16, 'buried': 1158, 'landslide': 4510, 'destroys': 2294, 'village': 8499, 'southwest': 7449, 'toys': 8145, 'leprechauns': 4610, 'chuck': 1500, 'grandmother': 3526, 'kicked': 4413, 'caucus': 1341, 'positive': 6032, 'trevor': 8197, 'noah': 5374, 'destroye': 2292, 'delusional': 2212, 'kanye': 4378, 'saying': 6917, 'slavery': 7315, 'choice': 1485, 'evasion': 2848, 'splatters': 7514, 'gillespie': 3428, 'declined': 2144, 'grandchildren': 3522, 'asylums': 567, 'built': 1135, 'fairy': 2990, 'focus': 3200, 'slobbering': 7334, 'onion': 5508, 'impeach': 4020, 'exam': 2867, 'aceh': 171, 'canes': 1256, 'couples': 1902, 'affection': 251, 'sadism': 6850, 'hosed': 3897, 'entitlements': 2792, 'quarterbacks': 6307, 'preps': 6093, 'thaad': 7988, 'kimchi': 4429, 'lashes': 4526, 'rebuff': 6429, 'passes': 5721, 'ask': 532, 'frogs': 3297, 'player': 5926, 'erick': 2817, 'erickson': 2818, 'teapot': 7921, 'carson': 1305, 'proposes': 6196, 'poor': 6004, 'rent': 6559, 'landlord': 4503, 'memorials': 4985, 'created': 1941, 'remembered': 6541, 'nobel': 5375, 'donkey': 2507, 'falls': 3002, 'short': 7195, 'drink': 2575, 'residence': 6608, 'bigfoot': 876, 'here': 3781, 'expect': 2903, 'apple': 468, 'event': 2853, 'ios': 4216, 'macbooks': 4777, 'ipads': 4218, 'century': 1380, 'unacceptable': 8314, 'unable': 8313, 'gas': 3376, 'risks': 6738, 'single': 7264, 'graph': 3534, 'song': 7426, 'file': 3104, 'irs': 4236, 'clock': 1571, 'devin': 2312, 'discredit': 2398, 'instead': 4146, 'proved': 6223, 'something': 7422, 'carter': 1307, 'collapses': 1625, 'dehydration': 2189, 'overeating': 5602, 'brother': 1114, 'sentenced': 7079, 'related': 6517, 'glowing': 3455, 'losing': 4741, 'failing': 2982, 'lay': 4559, 'including': 4061, 'caterers': 1333, 'probing': 6147, 'fends': 3079, 'fury': 3339, 'abroad': 135, 'laughs': 4538, 'fawning': 3046, 'borscht': 1015, 'regained': 6494, 'hamster': 3661, 'remove': 6549, 'hungary': 3945, 'university': 8370, 'ngos': 5345, 'hungry': 3947, 'catcher': 1331, 'cootie': 1842, 'id': 3975, 'botch': 1020, 'nomorenazi': 5384, 'sparks': 7467, 'online': 5509, 'backlash': 653, 'agent': 273, 'communications': 1685, 'kennel': 4396, 'heal': 3736, 'daughter': 2090, 'leads': 4568, 'polluted': 5986, 'minds': 5062, 'oklahoma': 5494, 'prostitution': 6207, 'pathetic': 5735, 'assimilation': 556, 'morally': 5174, 'unfit': 8348, 'scathing': 6937, 'intensifies': 4159, 'criticism': 1973, 'investigating': 4198, 'links': 4676, 'cats': 1339, 'nawaz': 5297, 'sharif': 7146, 'disqualified': 2433, 'sports': 7523, 'australian': 605, 'unveils': 8392, 'kangaroo': 4376, 'carl': 1287, 'higbie': 3805, 'racist': 6338, 'paints': 5652, 'presidents': 6104, '31': 65, 'fund': 3325, 'headache': 3730, 'appalling': 453, 'bolton': 976, 'exhibit': 2890, 'citizens': 1524, 'returning': 6668, 'dishes': 2410, 'believes': 825, 'exonerating': 2898, 'thrown': 8042, 'glen': 3448, 'campbell': 1232, '81': 107, 'pinecone': 5885, 'signs': 7240, 'upgrade': 8403, 'martin': 4883, 'luther': 4769, 'birthplace': 906, 'historic': 3836, 'crib': 1956, 'aggressive': 276, 'schedule': 6943, 'develop': 2308, 'submarine': 7712, 'lookalikes': 4724, 'pretended': 6110, 'hong': 3871, 'kong': 4466, 'jewel': 4309, 'nevertrump': 5334, 'columnist': 1649, 'bananas': 694, 'cookoff': 1835, 'dick': 2323, 'cheney': 1457, 'restarting': 6634, 'torture': 8113, 'interrogation': 4175, 'program': 6168, 'turtle': 8275, 'basically': 746, 'me': 4941, 'help': 3769, 'reelected': 6469, 'dawdling': 2098, 'tests': 7982, 'patience': 5737, 'ketchup': 4403, 'searchable': 7014, 'archive': 491, 'buttons': 1189, 'doll': 2492, 'begs': 811, 'number': 5429, 'zones': 8893, 'rises': 6735, 'chef': 1453, 'louise': 4748, 'slaughter': 7313, 'champion': 1402, '88': 112, 'beef': 796, 'feels': 3066, 'vindicated': 8504, 'pet': 5823, 'detractors': 2303, 'weigh': 8669, 'female': 3075, 'whines': 8704, 'professor': 6165, 'incites': 4059, 'riot': 6729, '67': 97, 'politicians': 5979, 'voted': 8547, 'robots': 6758, 'george': 3400, 'bust': 1176, 'revises': 6689, 'conservation': 1774, 'sage': 6855, 'grouse': 3583, 'hunting': 3952, 'timeline': 8065, 'chemical': 1456, 'salsa': 6872, 'trainer': 8162, 'mourns': 5198, 'unarmed': 8315, 'nominees': 5383, 'sweep': 7828, 'dust': 2618, 'headlines': 3733, '2011': 39, 'spur': 7533, 'goldfish': 3477, 'disappearing': 2375, 'seagrass': 7006, 'protects': 6215, 'pathogens': 5736, 'surfers': 7786, 'obscenity': 5455, 'believe': 823, 'interfere': 4166, 'pastries': 5730, 'cnnpolitics': 1596, 'com': 1650, 'shower': 7212, 'caught': 1342, 'greece': 3546, 'laundering': 4543, 'hotdogs': 3907, 'issue': 4249, 'executive': 2884, 'lgbtq': 4626, 'ninjas': 5368, 'reckoning': 6443, 'dream': 2562, 'act': 185, 'manufacturing': 4846, 'slows': 7345, 'forecast': 3228, 'december': 2131, 'rose': 6791, 'africa': 259, 'existing': 2895, 'agreements': 284, 'underwear': 8337, 'complex': 1703, 'scramble': 6978, 'endures': 2760, 'highlights': 3808, 'split': 7515, 'paralyze': 5688, 'interviewed': 4180, 'rosenstein': 6793, 'summer': 7753, 'tortured': 8114, 'tucker': 8256, 'carlson': 1288, 'braincells': 1049, 'homosexuals': 3869, 'chechnya': 1441, 'concentration': 1714, 'suffer': 7743, 'electrocution': 2700, 'fatal': 3035, 'beatings': 781, 'anonymously': 417, 'texting': 7986, 'scrubdown': 6995, 'arthur': 523, 'backer': 648, 'conga': 1757, 'deserve': 2278, 'hampshire': 3659, 'iowa': 4217, 'eyes': 2963, 'loom': 4728, 'rigs': 6726, 'bamboozle': 690, 'obscene': 5454, 'masquerade': 4892, 'criticised': 1972, 'douma': 2532, 'lt': 4761, 'gov': 3498, 'dan': 2062, 'games': 3363, 'shootings': 7190, 'lunches': 4767, 'indie': 4085, 'drama': 2553, 'cannes': 1259, 'banana': 693, 'fleet': 3165, 'whale': 8691, 'seahorse': 7008, 'flexes': 3167, 'muscle': 5237, 'coracobrachialis': 1848, 'defers': 2172, 'surgery': 7789, 'facial': 2969, 'crimea': 1960, 'ambitions': 361, 'jason': 4289, 'chaffetz': 1390, 'invents': 4194, 'housing': 3918, 'ignoring': 3993, 'utah': 8432, 'doughnut': 2529, 'atlantic': 573, 'walls': 8583, 'giuliani': 3439, 'terrorist': 7974, 'pre': 6074, 'pens': 5789, 'apologize': 450, 'fever': 3088, 'hay': 3723, 'cataclysm': 1323, 'dc': 2102, 'intoxicates': 4185, '900': 116, 'palestinians': 5657, 'converge': 1821, 'fence': 3077, 'ants': 430, 'winter': 8757, 'stepped': 7617, 'dancers': 2067, 'wilbur': 8735, 'surprised': 7791, 'mummies': 5226, 'mice': 5020, 'tie': 8054, 'randomly': 6368, 'pulling': 6260, 'name': 5269, 'ditch': 2452, 'price': 6119, 'crimping': 1966, 'hamburger': 3656, 'sounds': 7441, 'writer': 8838, 'hear': 3742, 'arguments': 499, 'undisclosed': 8338, 'contacts': 1797, 'bookmakers': 997, 'chaos': 1417, 'jelly': 4298, 'gig': 3422, 'obstacles': 5459, 'working': 8806, 'porter': 6021, 'resigned': 6613, 'totally': 8119, 'spousal': 7526, 'leadership': 4566, 'flew': 3166, 'expense': 2912, 'nobost': 5377, 'cared': 1282, 'geese': 3388, 'sideways': 7233, 'defending': 2167, 'bernstein': 846, 'ballgame': 684, 'boosting': 1007, '53': 86, 'skunked': 7302, 'pockets': 5956, 'silent': 7244, 'bagel': 666, 'scots': 6970, 'fully': 3321, 'engaged': 2768, 'scottish': 6972, 'independence': 4075, 'manhunt': 4832, 'leaker': 4572, 'gave': 3380, 'wikileaks': 8733, 'mexicans': 5015, 'prospect': 6203, 'deportee': 2259, 'glasses': 3446, 'closets': 1580, 'baked': 673, 'uber': 8300, 'cto': 2006, 'email': 2714, 'techno': 7926, 'gain': 3350, 'votes': 8551, 'slot': 7338, 'penguins': 5782, 'exclusive': 2879, 'example': 2870, 'sweden': 7826, 'bum': 1144, 'approves': 480, 'installment': 4144, 'disaster': 2379, 'markets': 4872, 'mideast': 5029, 'modest': 5132, 'drop': 2588, 'temperatures': 7943, 'astronaut': 564, 'peggy': 5771, 'whitson': 8714, 'dangerous': 2072, 'fresno': 3286, 'spree': 7530, 'custody': 2034, 'pajamas': 5653, 'tremendous': 8194, 'anger': 393, 'wife': 8729, 'trudeau': 8237, 'decides': 2134, 'poke': 5967, 'grizzly': 3568, 'seats': 7023, 'bargain': 722, 'snooze': 7388, 'emmanuel': 2730, 'bread': 1061, 'monsanto': 5155, 'manufactured': 4845, 'studies': 7699, 'chimpanzees': 1477, 'oregon': 5549, 'sues': 7742, 'kroger': 4472, 'refusing': 6492, 'shotgun': 7201, 'shells': 7159, 'weddings': 8661, 'cim': 1512, '600': 91, 'jpmorgan': 4344, 'loan': 4702, 'brooklyn': 1111, 'site': 7277, 'cracks': 1927, 'hospitalization': 3899, 'eyebrows': 2957, 'migrants': 5039, 'begun': 812, 'pineapples': 5884, 'legend': 4600, 'zelda': 8882, 'gaming': 3364, 'reddit': 6460, 'permissive': 5804, 'attitude': 589, 'poisoning': 5965, 'internet': 4173, 'society': 7407, 'labour': 4487, 'leap': 4575, 'judgement': 4349, 'condemning': 1725, 'lights': 4652, 'earthquake': 2643, 'sichuan': 7228, 'suspend': 7809, 'shuts': 7226, 'spank': 7460, 'memorial': 4984, 'honors': 3876, 'himself': 3821, 'fries': 3292, 'schoolboys': 6954, 'enduring': 2761, 'cycle': 2044, 'fugu': 3317, 'freakout': 3275, 'blowfish': 954, 'poisonous': 5966, 'inflate': 4099, 'rifle': 6718, 'joked': 4334, 'overturned': 5616, 'spatula': 7470, 'au': 596, 'fighting': 3100, 'whining': 8705, 'integrity': 4155, 'dershowitz': 2269, 'praises': 6061, 'place': 5906, 'hatred': 3713, 'cheddar': 1445, 'affirms': 254, 'reluctantly': 6531, 'monkeys': 5153, 'envies': 2794, 'preserves': 6100, 'mars': 4878, 'asteroid': 561, 'mourning': 5197, '773': 104, 'camera': 1226, 'sending': 7070, 'powder': 6051, 'apartment': 442, 'crackhouse': 1926, 'shares': 7145, 'questioning': 6312, 'pick': 5854, 'defied': 2177, 'pursuing': 6285, 'dengue': 2228, 'immunization': 4016, 'yogurt': 8866, 'ostriches': 5567, 'sit': 7274, 'dress': 2568, 'cup': 2018, 'players': 5927, 'cafeteria': 1205, 'doctor': 2474, 'shortage': 7196, 'rural': 6829, 'whiskey': 8709, 'houseplant': 3915, 'fukushima': 3319, 'executives': 2885, 'disney': 2424, 'bonus': 991, 'depends': 2250, 'signing': 7239, 'wage': 8566, 'contract': 1809, 'gym': 3617, 'kellyanne': 4394, 'mostly': 5186, '199': 29, 'hilarious': 3815, 'ariana': 500, 'grande': 3523, 'concert': 1717, 'explosions': 2930, 'confirmed': 1744, 'fatalities': 3036, 'bumblebees': 1146, 'jim': 4316, 'carrey': 1296, 'eyeful': 2959, 'crotch': 1987, 'text': 7985, 'kusher': 4479, 'whopper': 8719, 'absent': 138, 'annual': 414, 'rocks': 6760, 'lit': 4688, 'wick': 8723, 'agency': 270, 'candles': 1254, 'comprehend': 1709, 'manchester': 4825, 'confirm': 1742, 'schoolgirl': 6955, 'eilidh': 2687, 'macleod': 4781, '14': 15, 'arena': 495, 'terrier': 7969, 'toes': 8085, 'prankster': 6068, 'pretending': 6111, 'reince': 6510, 'priebus': 6122, 'confrontational': 1752, 'enabled': 2745, 'timidity': 8067, 'elijah': 2707, 'cummings': 2017, 'advisors': 239, 'morphed': 5178, 'fission': 3144, 'famous': 3012, 'descent': 2271, 'socialist': 7406, 'hell': 3767, 'utopia': 8434, 'gao': 3368, 'dispute': 2431, 'armando': 505, 'iannucci': 3969, 'highway': 3810, 'nowhere': 5415, 'think': 8017, 'cowardice': 1916, 'pandas': 5665, 'oversee': 5606, 'rum': 6820, 'useless': 8426, 'zealand': 8879, 'involved': 4213, 'incident': 4056, 'fame': 3007, 'pompadours': 5992, 'statue': 7597, 'vandalize': 8450, 'apparel': 454, 'vocals': 8534, 'bar': 711, 'defamation': 2159, 'settlements': 7111, 'body': 969, 'cocktail': 1610, 'ways': 8642, 'figures': 3103, 'jerry': 4303, 'brown': 1117, 'salt': 6873, 'womensmarch': 8792, 'kitchens': 4444, 'oliver': 5500, 'users': 8427, 'sacrifices': 6846, 'ucla': 8302, 'dungeon': 2616, 'happiness': 3679, 'paraquat': 5692, 'recover': 6451, 'herpes': 3787, 'fantastic': 3016, 'overseeing': 5607, 'renovate': 6557, 'kitten': 4446, 'actions': 189, 'vetting': 8484, 'rebuilding': 6430, 'dodging': 2482, 'gangsters': 3367, 'courthouse': 1908, 'firefight': 3131, 'canaries': 1242, 'eyelashes': 2960, '180': 22, 'degree': 2187, 'shift': 7168, 'geopolitical': 3399, 'whiplash': 8708, 'diapers': 2320, 'emojis': 2733, 'ax': 637, 'policing': 5973, 'funds': 3330, 'pulls': 6262, 'pact': 5636, 'preferred': 6081, 'roadside': 6748, 'bombings': 982, 'linguistic': 4671, 'speaks': 7474, 'grade': 3510, 'coworker': 1917, 'bookstore': 999, 'tehran': 7935, 'garden': 3373, 'opens': 5521, 'censorship': 1372, 'virtual': 8520, 'stakes': 7564, 'bungle': 1149, 'roundness': 6800, 'soaring': 7402, 'imports': 4033, 'hamas': 3655, 'cooking': 1834, 'indonesian': 4089, 'jakarta': 4276, 'pollsters': 5985, 'eats': 2655, 'spain': 7457, 'uncertainty': 8320, 'future': 3341, 'jfk': 4311, 'stewardesses': 7627, 'offense': 5474, 'loretta': 4735, 'volleyball': 8539, 'rob': 6752, 'anomaly': 415, 'symbol': 7845, 'trumpism': 8244, 'midlife': 5033, 'overstepped': 5610, 'stairs': 7562, 'beijing': 817, 'hurt': 3955, 'cynically': 2046, 'boosters': 1006, 'eyelid': 2961, 'livestock': 4696, 'cuban': 2008, 'changed': 1409, 'aim': 295, 'halt': 3650, 'catalan': 1324, 'maryam': 4885, 'mirzakhani': 5084, 'fields': 3094, '40': 74, 'landscaper': 4508, 'disorder': 2426, 'mimics': 5060, 'parkinson': 5700, 'pasta': 5728, 'vomits': 8544, 'vancouver': 8449, 'fifa': 3096, 'itself': 4259, 'inspired': 4142, 'consider': 1778, 'respond': 6627, 'nukes': 5427, 'objectify': 5452, 'pushed': 6287, 'several': 7116, 'dollars': 2494, 'seconds': 7026, 'sows': 7452, 'avert': 625, 'seed': 7039, 'gen': 3390, 'honorable': 3873, 'homes': 3866, 'manners': 4839, 'snoop': 7387, 'dogg': 2486, 'loving': 4754, 'industrial': 4090, 'revolutions': 6698, 'wrecking': 8829, 'balls': 689, 'feminists': 3076, 'moab': 5115, 'aftermath': 263, 'tours': 8132, 'dropped': 2589, 'handkerchief': 3665, 'eyelids': 2962, 'abolish': 129, 'mentioned': 4993, 'disclosure': 2390, 'allowance': 340, 'speaker': 7472, 'unraveling': 8382, 'string': 7681, 'chats': 1432, 'briefly': 1091, 'vietnam': 8492, 'paramour': 5689, 'slapped': 7309, 'walks': 8579, '35': 67, 'sentence': 7078, 'sleeping': 7319, 'package': 5633, 'resolve': 6621, 'pretzel': 6114, 'taxi': 7907, 'cheese': 1448, 'formally': 3244, 'roll': 6772, 'stamp': 7571, 'honest': 3870, 'scares': 6935, 'gabbard': 3346, 'dated': 2087, 'spas': 7469, 'preserve': 6099, 'kumquats': 4475, 'exact': 2865, 'labradors': 4489, 'revive': 6691, 'goldmine': 3479, 'tips': 8073, 'toupee': 8126, 'billions': 889, 'nigel': 5356, 'farage': 3019, 'julian': 4357, 'mammals': 4820, 'strongly': 7692, 'defend': 2166, 'revise': 6687, 'quota': 6325, 'showing': 7215, 'minimum': 5067, 'wages': 8567, 'chanted': 1415, 'michigan': 5023, 'baby': 643, 'taxpayers': 7912, 'bang': 696, 'buck': 1123, 'squeeze': 7539, 'alek': 317, 'manassian': 4824, 'identified': 3978, 'toronto': 8111, 'attacker': 579, 'goose': 3490, 'subservient': 7720, 'property': 6191, 'exposed': 2934, 'peddle': 5766, 'ponies': 5995, 'master': 4902, 'destiny': 2290, 'oracles': 5540, 'rave': 6395, 'expel': 2909, 'surprises': 7792, 'buddies': 1125, 'tn': 8077, 'veto': 8481, 'illiteracy': 4000, 'aliens': 326, 'legalized': 4598, 'sacrificing': 6848, 'dinosaur': 2348, 'unless': 8371, 'compelled': 1693, 'feb': 3056, '28': 59, '02': 1, 'et': 2836, 'asking': 534, 'knew': 4453, 'hacked': 3624, 'incoherent': 4062, 'dipsomaniac': 2357, 'serbian': 7087, 'montenegro': 5159, 'grenade': 3557, 'flowers': 3192, 'marchers': 4857, 'threaten': 8029, 'pigeon': 5867, 'upgrading': 8404, 'cheque': 1458, 'envoy': 2798, 'trophy': 8229, 'emu': 2743, 'groomer': 3572, 'slayer': 7317, 'dragon': 2550, 'hyperplasia': 3965, 'patchwork': 5733, 'likes': 4656, 'understands': 8335, 'justified': 4370, 'prancing': 6065, 'anecdote': 390, 'unmasks': 8375, 'dehumanization': 2188, 'eyebrow': 2956, 'puppy': 6280, 'switch': 7839, 'obsolete': 5458, 'protractor': 6221, 'pours': 6049, 'lipinski': 4678, 'keys': 4407, 'cheeseburger': 1449, 'continue': 1806, 'indefinitely': 4074, 'zombies': 8891, 'employers': 2740, 'exemption': 2886, 'birth': 903, 'immoral': 4015, 'establishment': 2833, 'opened': 5519, 'implying': 4030, 'non': 5385, 'booze': 1008, 'nerd': 5320, 'wasps': 8622, 'cory': 1871, 'booker': 996, 'posturing': 6041, 'boa': 960, 'britain': 1095, 'able': 128, 'regulations': 6503, 'multiple': 5224, 'thailand': 7989, 'injure': 4123, 'taco': 7861, 'begging': 808, 'bets': 857, 'punchline': 6270, 'franks': 3269, 'carry': 1302, 'groceries': 3569, 'bustier': 1177, 'tony': 8099, 'blair': 921, 'intervention': 4178, 'joys': 4343, 'comparison': 1692, 'replacement': 6576, 'terrible': 7968, 'spark': 7464, 'strain': 7664, 'relationships': 6519, 'imploded': 4028, 'gohmert': 3473, 'mcauliffe': 4929, 'facilitating': 2970, 'creationist': 1944, 'strict': 7678, 'rudy': 6815, 'divorced': 2466, 'judith': 4354, 'falling': 2999, 'unemployment': 8344, 'payrolls': 5756, 'add': 204, '138': 13, 'reservoir': 6605, 'scare': 6932, 'asylum': 566, 'furry': 3337, 'maduro': 4788, 'banger': 697, 'misguided': 5089, 'violation': 8508, 'cheer': 1446, 'curfew': 2024, '36': 69, 'popcorn': 6006, 'certainly': 1386, 'meant': 4946, 'disrespect': 2434, 'pose': 6026, 'photo': 5846, 'respect': 6626, 'disclosed': 2388, 'confidential': 1741, 'zebras': 8881, 'ed': 2665, 'sunshine': 7760, 'unveil': 8391, 'punishing': 6275, 'thursday': 8046, 'chores': 1493, 'cbs': 1354, 'overall': 5598, '38': 72, 'confetti': 1739, 'smile': 7360, 'poses': 6028, 'models': 5127, 'austrian': 607, 'crossing': 1986, 'italy': 4255, 'sword': 7840, 'barn': 724, 'grill': 3562, 'frankfurters': 3268, 'grigory': 3561, 'rodchenkov': 6762, 'whistleblower': 8711, 'cheats': 1439, 'whistles': 8712, 'reacts': 6405, 'applauds': 466, 'trash': 8175, 'witnessing': 8782, 'motion': 5191, 'borrow': 1013, 'filed': 3105, 'extension': 2944, 'electoral': 2697, 'aerial': 245, 'footage': 3214, 'devastated': 2306, 'font': 3210, 'doomsday': 2515, 'ticks': 8051, '30': 62, 'closer': 1577, 'annihilation': 406, 'thanks': 7992, 'brunch': 1118, 'smooth': 7365, 'wrinkles': 8836, 'disappear': 2372, 'preet': 6079, 'bharara': 865, 'relationship': 6518, 'programs': 6170, 'accepts': 151, 'invite': 4208, 'antarctica': 421, 'planning': 5914, 'plot': 5943, 'modesty': 5133, 'plenty': 5942, '700': 100, 'toilets': 8088, 'shifting': 7169, 'shove': 7207, 'equating': 2806, 'silliest': 7246, 'eyeballs': 2955, 'manhattan': 4830, 'da': 2048, 'donation': 2505, 'exes': 2889, 'packing': 5635, 'giants': 3416, 'exported': 2932, 'rotten': 6795, 'egg': 2679, 'neil': 5317, 'gorsuch': 3495, 'matter': 4917, 'succumb': 7733, 'fatigue': 3039, 'frat': 3271, 'islam': 4239, 'retweeted': 6670, 'rather': 6387, 'outrage': 5588, 'blackmail': 916, 'hairstyle': 3642, 'arcade': 488, 'every': 2856, 'pundit': 6271, 'dinesh': 2343, 'souza': 7450, 'convicted': 1824, 'distance': 2441, 'nashville': 5279, 'withdrawal': 8773, 'catastrophe': 1329, 'frog': 3296, 'saves': 6911, 'transportation': 8170, 'pepperoni': 5795, 'rectal': 6456, 'maher': 4795, 'capable': 1265, 'ordering': 5547, 'lender': 4606, 'bathrooms': 756, 'revoke': 6694, 'spill': 7503, 'lunch': 4766, 'frightbart': 3293, 'stew': 7626, 'menace': 4989, 'pit': 5895, 'monsters': 5157, 'unending': 8345, 'onslaught': 5512, 'apocalyptic': 447, 'horsemen': 3895, 'lamb': 4497, 'grandfather': 3524, 'compared': 1690, 'cataracts': 1328, 'bangladeshi': 699, 'human': 3933, 'campaigner': 1230, 'farhad': 3024, 'mazhar': 4928, 'disappears': 2376, 'invisibility': 4206, 'commander': 1666, 'resist': 6616, 'base': 736, 'outcome': 5580, 'bass': 748, 'celebrates': 1360, 'expanding': 2901, 'donkeys': 2508, 'hangover': 3673, 'scrap': 6980, 'choose': 1491, 'successor': 7732, 'credit': 1950, 'starbucks': 7580, 'encourages': 2748, 'bipartisan': 899, 'spikes': 7502, 'lays': 4560, 'bare': 721, 'divisions': 2463, 'paperclips': 5679, 'harassments': 3685, 'landrieu': 4506, 'removal': 6548, 'orleans': 5559, 'reenactors': 6473, 'prepares': 6091, 'arrest': 516, 'concocts': 1721, 'broad': 1099, 'deleting': 2197, 'bashing': 744, 'weighs': 8670, 'swapping': 7819, 'readies': 6409, 'booming': 1002, 'feds': 3062, 'audition': 600, 'driver': 2580, 'owner': 5622, 'fed': 3059, 'emergency': 2727, 'westminster': 8688, 'impostor': 4039, 'wendy': 8681, 'vitter': 8531, 'separatist': 7085, 'clone': 1572, 'liberals': 4632, 'impersonations': 4025, 'considers': 1781, 'crosshairs': 1985, 'comb': 1652, 'slammed': 7305, 'cramp': 1929, 'defect': 2163, 'whom': 8717, 'adorable': 224, 'sandberg': 6884, 'showdown': 7210, 'shrink': 7219, 'unions': 8362, 'despot': 2287, 'popcorns': 6007, 'hammocks': 3658, 'sworn': 7841, 'bible': 867, 'abraham': 134, 'lincoln': 4664, 'hat': 3706, 'census': 1373, 'citizenship': 1525, 'trey': 8198, 'gowdy': 3505, 'fisa': 3138, 'embarrassing': 2719, 'adam': 201, 'unmitigated': 8376, 'reproductive': 6590, 'stone': 7645, 'unelectable': 8342, 'mop': 5171, 'deepens': 2155, 'odors': 5469, 'admiral': 215, 'diplomacy': 2351, 'resolving': 6622, 'soup': 7442, 'denmark': 2234, 'mermaid': 5000, 'doused': 2533, 'paint': 5649, 'whaling': 8692, 'mermen': 5001, 'slaps': 7310, 'complete': 1701, 'denuclearization': 2241, 'avoids': 628, 'nationalist': 5284, 'wardrobe': 8596, 'rebukes': 6432, 'khakis': 4409, 'singapore': 7261, 'regional': 6497, 'dialogue': 2317, 'playgroup': 5930, 'zinke': 8886, 'travels': 8180, 'ski': 7291, 'resort': 6624, 'alaskan': 312, 'steakhouse': 7604, 'accusations': 165, 'simple': 7254, 'explanation': 2922, 'undercuts': 8326, 'acted': 186, 'danced': 2065, 'anonymous': 416, 'discovery': 2397, 'ousts': 5577, 'taps': 7893, 'assassin': 542, 'trafficking': 8157, 'tap': 7889, 'fuel': 3312, 'reserves': 6604, 'milkshake': 5049, 'bizarre': 913, 'colleges': 1632, 'operative': 5525, 'looked': 4725, 'caterpillar': 1335, 'rips': 6733, 'claps': 1539, 'blackmails': 918, 'rick': 6709, 'perry': 5808, 'kilts': 4427, 'attractive': 592, 'playgrounds': 5929, 'pause': 5748, 'panic': 5669, 'upend': 8401, 'separating': 7084, 'discourage': 2394, 'shaved': 7151, 'teams': 7920, 'getting': 3410, 'stadiums': 7552, 'warships': 8614, 'deployed': 2254, 'peninsula': 5783, 'saunas': 6907, 'cossack': 1874, 'ensure': 2785, 'safety': 6854, 'obedience': 5449, 'issued': 4250, 'correction': 1864, 'hid': 3802, 'near': 5302, 'bushes': 1173, 'urinated': 8420, 'bungling': 1151, 'screenplay': 6988, 'acts': 197, 'association': 560, 'thinks': 8019, 'guesses': 3596, 'sassy': 6901, 'trolling': 8225, 'girlfriend': 3437, 'seized': 7051, 'troop': 8227, 'sling': 7327, 'phones': 5844, 'tapped': 7891, 'painter': 5650, 'subhuman': 7711, 'worked': 8802, 'hound': 3911, 'wish': 8766, 'hypnotize': 3967, 'airplanes': 302, 'couch': 1883, 'measures': 4949, 'canoe': 1261, 'ty': 8297, 'cobb': 1603, 'retiring': 6662, 'dictatorship': 2326, '1984': 28, 'thieves': 8013, 'elaborate': 2690, 'heist': 3763, 'swiss': 7838, 'blouses': 952, 'window': 8745, 'overwhelmingly': 5618, 'kitchen': 4443, 'purge': 6282, 'actually': 199, 'marshmallows': 4880, 'marrying': 4877, 'bingo': 895, 'cemetery': 1369, 'stocking': 7638, 'attaching': 576, 'ceiling': 1357, 'falwell': 3005, 'stripper': 7684, 'appointed': 471, 'ago': 279, 'investigate': 4195, 'abuses': 143, 'escalate': 2824, 'scuffling': 7000, 'tourism': 8129, 'commission': 1675, 'transparency': 8168, 'happened': 3676, 'explode': 2924, 'triumph': 8219, 'began': 805, 'spitball': 7510, 'oscar': 5563, 'nominated': 5379, 'ceremony': 1385, 'nunberg': 5432, 'summoned': 7755, 'torturer': 8115, 'airlines': 301, 'dragged': 2549, 'pilot': 5878, 'pop': 6005, 'positions': 6031, 'nun': 5431, 'benefits': 836, 'campground': 1233, 'field': 3093, 'vigorously': 8497, 'massage': 4895, 'magicians': 4792, 'along': 349, 'pennsylvania': 5787, 'appears': 461, 'heat': 3750, 'sauce': 6904, 'panicking': 5670, 'gutierrez': 3613, 'someone': 7420, 'kkk': 4449, 'chorus': 1494, 'grows': 3585, 'crumbs': 2000, 'convicts': 1826, 'laughed': 4535, 'disappearances': 2374, 'leftwing': 4592, 'dissent': 2439, 'froome': 3303, 'fourth': 3257, 'hiccups': 3799, 'meehan': 4965, 'bathrobe': 754, 'pi': 5852, 'sentencing': 7081, 'costa': 1876, 'mesa': 5003, 'spying': 7537, 'dui': 2607, 'praising': 6062, 'crawl': 1935, 'chile': 1475, 'creates': 1942, 'acre': 181, 'patagonia': 5732, 'founders': 3255, 'reader': 6407, 'pacifism': 5630, 'backstory': 657, 'hezbollah': 3796, 'hook': 3878, 'chain': 1391, 'tipline': 8071, 'bone': 987, 'buys': 1194, 'picnic': 5859, 'survive': 7798, 'toll': 8092, 'bombs': 983, 'masses': 4898, 'air': 298, '35s': 68, 'upkeep': 8405, 'subsidizing': 7722, 'biting': 912, 'dorm': 2518, 'scandals': 6928, 'dwarf': 2622, 'romancing': 6778, 'sooner': 7431, 'stood': 7648, 'drank': 2555, 'niece': 5353, 'card': 1278, '100k': 4, 'maniac': 4833, 'fish': 3140, 'lessons': 4613, 'sixth': 7283, 'nixon': 5370, 'ethical': 2837, 'norms': 5396, 'suite': 7751, 'jack': 4265, 'bobridge': 967, 'cyclist': 2045, 'selling': 7059, 'drunkard': 2595, 'flipped': 3173, 'legislature': 4603, 'attacked': 578, 'coconut': 1613, 'walk': 8576, 'drawn': 2558, 'sketch': 7290, 'auction': 597, 'incinerator': 4058, 'greenspan': 3551, 'math': 4912, 'individual': 4087, 'temporary': 7947, 'hints': 3824, 'toy': 8143, 'cartographer': 1308, 'panamanian': 5661, 'dictator': 2324, 'manuel': 4844, 'noriega': 5394, '83': 108, 'dating': 2089, 'gag': 3349, 'sound': 7439, 'immigrating': 4012, 'wild': 8736, 'reminiscent': 6545, 'xylophone': 8848, 'consistent': 1782, 'attractiveness': 593, 'catholic': 1338, 'priest': 6123, '13': 12, 'motel': 5188, 'paying': 5752, 'ouster': 5576, 'pseudo': 6234, 'embraces': 2725, 'pivot': 5900, 'proverbial': 6224, 'drunks': 2597, 'streetlight': 7675, 'puddles': 6252, 'kushners': 4481, 'saudis': 6906, 'blackstone': 919, 'recent': 6436, 'zoo': 8894, 'pack': 5632, 'spot': 7524, 'orders': 5548, 'boomerang': 1001, '90': 115, 'erasure': 2813, 'jefferson': 4296, 'zombie': 8890, 'happens': 3678, 'orange': 5541, 'amusing': 377, 'bosnia': 1016, 'ratko': 6392, 'mladic': 5113, 'genocide': 3395, 'indigestion': 4086, 'modernize': 5131, 'dismantle': 2417, 'laser': 4524, 'dwarfs': 2623, 'gdp': 3384, 'statues': 7598, 'birds': 902, 'foreigners': 3231, 'locked': 4714, 'modeling': 5126, 'battles': 763, 'umbrella': 8309, 'iphone': 4219, 'revives': 6692, 'floats': 3178, 'debts': 2126, 'ridiculous': 6717, 'cavalry': 1348, 'embarrass': 2718, 'forge': 3236, '34': 66, 'punished': 6274, 'graft': 3517, 'unprecedented': 8380, 'unique': 8363, 'complaints': 1700, 'virginity': 8518, 'idiocy': 3983, 'vox': 8556, 'sitter': 7279, 'intoxication': 4186, '24': 56, 'direction': 2361, 'postmen': 6038, 'reception': 6438, 'seduced': 7037, 'supremacist': 7778, 'activity': 193, 'campuses': 1237, 'cookie': 1832, 'lips': 4679, 'stooge': 7649, 'netroots': 5327, 'liberal': 4630, 'demand': 2214, 'throttle': 8036, 'pamper': 5660, 'conclude': 1718, 'stud': 7696, 'sarcasm': 6897, 'chibok': 1462, 'reunited': 6672, 'salamis': 6860, 'raisins': 6362, 'gibberish': 3417, 'residency': 6609, 'hairdos': 3637, 'deadliest': 2107, 'districts': 2450, 'radiologist': 6345, 'bullets': 1138, 'geometry': 3398, 'sergei': 7091, 'skripal': 7300, 'movie': 5206, 'wedding': 8660, 'northern': 5398, 'mclaughlin': 4939, 'saville': 6912, 'wannacry': 8589, 'hack': 3623, 'nhs': 5347, 'releases': 6525, 'planed': 5910, 'lowers': 4757, 'parenthood': 5696, 'hbcus': 3727, 'deportees': 2260, 'shelter': 7160, 'agonizing': 280, 'spelunking': 7487, 'mafia': 4789, 'miami': 5018, 'ground': 3577, 'unconstitutional': 8321, 'deli': 2199, 'denied': 2231, 'influx': 4105, 'militants': 5045, 'cockroaches': 1609, 'counting': 1895, 'tuxedos': 8280, 'sees': 7048, 'skunk': 7301, 'marry': 4876, 'roof': 6784, 'revealed': 6676, 'desecrated': 2274, 'kindergarten': 4431, 'submits': 7714, 'panels': 5668, 'confirmation': 1743, 'stream': 7670, 'applauded': 465, 'guantanamo': 3588, 'prisoners': 6136, 'beach': 768, 'sacrificial': 6847, 'politico': 5980, 'stands': 7578, 'battery': 760, 'scold': 6964, 'donor': 2509, 'sperm': 7492, 'sewers': 7118, 'mulligan': 5221, 'dow': 2536, 'fell': 3069, 'dishonesty': 2411, 'supports': 7775, 'note': 5406, 'burns': 1163, 'map': 4850, 'imp': 4017, 'grapes': 3533, 'overturns': 5617, 'regulation': 6502, 'mining': 5068, 'debris': 2124, 'cracker': 1925, 'hashtag': 3703, 'understand': 8333, 'dummies': 2610, 'criminals': 1965, 'bidet': 872, 'californians': 1215, 'extra': 2946, 'cross': 1983, 'subsidies': 7721, 'well': 8678, 'wives': 8783, 'blackmailed': 917, 'kept': 4401, 'informed': 4111, 'gnome': 3459, 'irresistible': 4235, 'named': 5270, 'perez': 5797, 'darts': 2080, 'escrow': 2829, 'gerrymandering': 3406, 'rig': 6720, 'squirrels': 7542, 'runner': 6825, 'roasts': 6751, 'apologists': 449, 'islamists': 4242, 'skateboarders': 7286, 'halls': 3649, 'landmarks': 4505, 'pleaded': 5935, 'identities': 3980, 'account': 160, 'numbers': 5430, 'humor': 3939, 'fda': 3050, 'reverse': 6683, 'stunning': 7706, 'details': 2297, 'brazen': 1058, 'heists': 3764, 'proof': 6187, 'improvement': 4044, 'beards': 776, 'fritters': 3295, 'domestic': 2498, 'retires': 6661, 'ditches': 2454, 'portugal': 6025, 'alaska': 311, 'baited': 672, 'canceling': 1247, 'dumpling': 2613, 'storms': 7658, '78': 105, 'moisten': 5135, 'dippin': 2356, 'dots': 2523, 'responded': 6628, 'listened': 4685, 'surprise': 7790, 'fueled': 3313, 'nationalism': 5283, 'noise': 5378, 'dodge': 2480, 'uses': 8428, 'anticapitalist': 427, 'sermon': 7096, 'pickup': 5858, 'trucks': 8236, 'miniature': 5065, 'explosive': 2931, 'wolff': 8788, 'held': 3766, 'captive': 1271, 'sexually': 7123, 'assaulted': 547, 'horrors': 3893, 'mannequin': 4838, 'deutsche': 2305, 'zip': 8887, 'code': 1614, 'villain': 8502, 'contradicts': 1812, 'whose': 8720, 'freezer': 3281, 'ruled': 6817, 'accidental': 154, 'discovers': 2396, 'puppies': 6279, 'rewards': 6700, 'grammar': 3519, 'dreams': 2566, 'pokes': 5969, 'prods': 6156, 'posterior': 6037, 'dreamer': 2564, 'sandals': 6883, '106': 9, 'passengers': 5720, 'stranded': 7665, 'pretzels': 6115, 'macedonians': 4778, 'clothes': 1584, 'toddler': 8083, 'hazing': 3725, 'unauthorized': 8316, 'dismisses': 2422, 'polling': 5983, 'peanut': 5762, 'champagne': 1401, 'welcome': 8676, 'burqas': 1165, 'together': 8086, 'copulate': 1847, '21st': 50, 'forays': 3220, 'vegan': 8457, 'turkeys': 8266, 'otters': 5571, 'duet': 2605, 'honoring': 3875, 'navajos': 5292, 'pocohontas': 5957, 'jab': 4262, 'taking': 7872, 'betting': 860, 'hobby': 3845, 'continues': 1807, 'churn': 1507, 'extremely': 2948, 'flooding': 3182, 'unfolding': 8349, 'provision': 6230, 'hardest': 3689, 'guess': 3595, 'knows': 4461, 'loved': 4751, 'sacks': 6843, 'ministers': 5071, 'defying': 2185, 'defenestrates': 2169, 'seduce': 7036, 'colonoscopy': 1644, 'anal': 379, 'reaction': 6402, 'weakness': 8647, 'beers': 799, 'stalwart': 7570, 'hemline': 3776, 'berating': 840, 'dramatic': 2554, 'nuke': 5426, 'giddy': 3418, 'royal': 6807, 'meghan': 4972, 'detail': 2296, 'elbow': 2691, 'sinus': 7270, 'forty': 3247, 'catalogued': 1326, 'elite': 2710, 'nh': 5346, 'prep': 6088, 'kerry': 4402, 'consults': 1793, 'ponders': 5994, 'dandruff': 2070, 'shark': 7148, 'creditloan': 1951, 'survey': 7796, 'height': 3760, 'revised': 6688, 'introduce': 4187, 'birthdays': 905, 'provide': 6226, 'delegates': 2194, 'volunteers': 8542, 'draft': 2546, 'deflates': 2181, 'hoax': 3844, 'ten': 7949, 'commandments': 1667, 'razorback': 6396, 'noaa': 5373, 'offensively': 5476, 'brake': 1051, 'marriott': 4875, 'books': 998, 'enlightenment': 2778, 'casts': 1321, 'zarrab': 8878, 'undermine': 8329, 'breakfast': 1065, 'cheapskate': 1437, 'hen': 3778, 'architect': 489, 'expresses': 2938, 'sliver': 7333, 'racetrack': 6334, 'foundation': 3253, 'overdose': 5600, 'accusing': 170, 'charity': 1423, 'palm': 5659, 'club': 1590, 'earthling': 2642, 'restore': 6637, 'voting': 8552, 'felons': 3071, 'salon': 6871, 'canadians': 1241, 'loonies': 4730, 'shouting': 7205, 'match': 4905, 'erupts': 2823, 'appetizer': 463, 'protecting': 6210, 'inmates': 4127, 'slumps': 7348, 'traders': 8152, 'supply': 7770, 'manson': 4842, '84': 109, 'repents': 6573, 'truths': 8251, 'acknowledge': 175, 'octogenarians': 5465, 'allen': 334, 'aroused': 514, 'emasculate': 2717, 'wan': 8587, 'troway': 8232, 'poo': 5998, 'snl': 7386, 'roast': 6749, 'hopscotch': 3888, 'navalny': 5294, 'heavily': 3754, 'elect': 2693, 'searchers': 7015, 'puddle': 6251, 'venture': 8469, 'chump': 1504, 'polyester': 5989, 'filibuster': 3107, 'moderate': 5128, 'rouhani': 6797, 'count': 1889, 'preliminary': 6085, 'results': 6645, 'pageant': 5641, 'wrap': 8825, 'chip': 1482, 'existence': 2894, 'doorstep': 2517, 'omg': 5503, 'reveals': 6678, 'pregnant': 6084, 'pretends': 6112, 'mypillow': 5255, 'strong': 7688, 'boycott': 1043, 'ingraham': 4118, 'angle': 394, 'naps': 5275, 'slip': 7329, 'grind': 3566, 'waking': 8575, 'cow': 1915, 'broadcaster': 1100, 'obnoxiously': 5453, 'revenge': 6681, 'yazidi': 8852, 'freeing': 3279, 'raqqa': 6381, 'housework': 3917, 'humanitarian': 3934, 'blown': 955, 'agendas': 272, 'novel': 5412, 'ayatollah': 639, 'khamenei': 4410, 'hitler': 3840, 'hemorrhoids': 3777, 'innovations': 4130, 'dominance': 2499, 'meryl': 5002, 'streep': 7673, 'whined': 8703, 'tiffany': 8056, 'lived': 4694, 'favorite': 3044, 'puppet': 6277, 'kingdom': 4436, 'posen': 6027, 'austria': 606, 'fascistic': 3030, 'umbrellas': 8310, 'shocked': 7181, 'routine': 6804, 'cleanser': 1554, 'savior': 6913, 'peta': 5824, 'billboard': 885, 'mouse': 5199, 'airstrike': 304, 'orangutans': 5543, 'liberty': 4633, 'alumni': 357, 'diplomas': 2352, 'molehill': 5138, 'pilgrim': 5872, 'deficits': 2176, 'struggles': 7694, 'spin': 7504, 'downplays': 2541, 'hawk': 3720, 'hispanics': 3834, 'sucker': 7736, 'punches': 6268, 'subway': 7726, 'giraffe': 3434, 'vx': 8561, 'nerve': 5321, 'nam': 5268, 'rare': 6382, 'infighting': 4097, 'grabbers': 3509, 'lubbers': 4762, 'stabs': 7550, 'boos': 1004, 'subpoenaed': 7716, 'piano': 5853, 'emma': 2729, 'gonzalez': 3485, 'survived': 7799, 'jacksonville': 4269, 'jaguars': 4271, 'shad': 7128, 'khan': 4411, 'jealous': 4294, 'trekkie': 8193, 'midwest': 5036, 'bull': 1136, 'flea': 3161, 'staring': 7582, 'toucan': 8120, 'catalans': 1325, 'declare': 2138, 'declaration': 2137, 'catches': 1332, 'amusement': 376, 'ride': 6713, 'pelican': 5772, 'disco': 2392, 'photos': 5847, 'environmental': 2796, 'terrified': 7970, 'motives': 5193, 'romance': 6776, 'celebrate': 1359, 'valentine': 8442, 'records': 6450, 'graded': 3511, 'dines': 2342, 'rice': 6706, 'convinced': 1827, 'popularity': 6012, 'theft': 7998, 'swath': 7822, 'county': 1899, 'representation': 6586, 'less': 4612, 'squirrel': 7541, 'representatives': 6587, 'supporter': 7772, 'sexuality': 7122, 'penny': 5788, 'perpetual': 5807, 'prompts': 6186, 'hunger': 3946, 'involve': 4212, 'fiction': 3090, 'spokesperson': 7520, 'grandma': 3525, 'distaste': 2443, 'suing': 7748, 'construction': 1790, 'beaner': 772, 'advertising': 234, 'principles': 6131, 'overseas': 5605, 'parks': 5702, 'lied': 4643, 'sanitation': 6891, 'today': 8082, 'grills': 3564, 'roosters': 6788, 'hairpiece': 3640, 'homeland': 3863, 'sudanese': 7739, 'giggle': 3424, 'salad': 6857, 'sleep': 7318, 'foot': 3213, 'evangelists': 2847, 'twisted': 8292, 'treachery': 8181, 'innocents': 4128, 'sandwich': 6886, 'captures': 1274, 'sandy': 6888, 'declassified': 2141, 'susan': 7804, 'contemplated': 1801, 'hiding': 3804, 'incoming': 4064, 'demolish': 2223, 'villages': 8501, 'pizzeria': 5905, '42': 78, 'completely': 1702, 'character': 1419, 'braces': 1046, 'prances': 6064, 'inside': 4137, 'trumpist': 8245, 'trumped': 8241, 'triumphs': 8220, 'exempts': 2887, 'grandparents': 3529, 'relatives': 6521, 'gifting': 3420, 'lines': 4669, 'databases': 2085, 'playing': 5931, 'guitar': 3604, 'massages': 4896, 'rails': 6353, 'shivers': 7179, 'recognizing': 6446, 'saved': 6910, 'location': 4711, 'trucker': 8235, 'damaged': 2058, 'peru': 5820, 'renowned': 6558, 'nazca': 5298, 'jockstraps': 4323, 'academic': 145, 'journals': 4342, 'graffiti': 3516, 'attempting': 583, 'muzzle': 5250, 'molest': 5139, 'julius': 4358, 'caesar': 1204, 'theater': 7997, 'timed': 8064, 'steak': 7603, 'whip': 8707, 'scalise': 6924, 'gunman': 3609, 'baseball': 737, 'practice': 6057, 'usa': 8422, 'removes': 6551, 'petition': 5828, 'tool': 8102, 'bali': 679, 'volcano': 8538, 'tremors': 8195, 'intensify': 4160, 'economists': 2662, 'vampires': 8446, 'smelly': 7359, 'limited': 4660, 'hockey': 3848, 'quest': 6309, 'astronauts': 565, 'alligators': 337, 'hug': 3928, 'frame': 3261, 'malley': 4817, 'aware': 633, 'elves': 2713, 'delingpole': 2203, 'environmentalists': 2797, 'burrito': 1166, 'jill': 4315, 'stein': 7612, 'culpability': 2013, 'primps': 6126, 'cosmonaut': 1873, 'drained': 2552, 'incumbents': 4072, 'ogres': 5489, 'reserve': 6603, 'cattle': 1340, 'breathing': 1072, 'scribble': 6991, 'appeals': 458, 'moustache': 5200, 'salary': 6862, 'overtime': 5613, 'hours': 3913, 'eclair': 2656, 'infowars': 4114, 'beat': 779, 'goddamn': 3468, 'wipe': 8758, 'services': 7102, 'arming': 509, 'equine': 2809, 'suspends': 7811, '103': 7, 'personnel': 5818, 'turk': 8264, 'gobbles': 3466, 'unsuccessful': 8388, 'equality': 2804, 'vulnerable': 8559, 'heidi': 3759, 'heitkamp': 3765, 'tougher': 8125, 'kevin': 4405, 'cramer': 1928, 'sorcerer': 7433, 'bugles': 1131, 'ben': 829, 'hud': 3924, 'lavish': 4548, 'waxing': 8639, 'requirements': 6597, 'starts': 7588, 'requesting': 6595, 'bids': 873, 'sticks': 7630, 'interviews': 4181, 'cyber': 2039, 'kaspersky': 4382, 'lab': 4484, 'recipe': 6440, 'evolving': 2863, 'towards': 8137, 'rap': 6374, 'asserts': 551, 'possibility': 6034, 'privilege': 6141, 'whoops': 8718, 'texts': 7987, 'agents': 274, 'peter': 5826, 'strzok': 7695, 'lisa': 4682, 'discards': 2384, 'stereo': 7620, 'naked': 5266, 'landfills': 4502, 'yearning': 8854, 'poland': 5970, 'asthma': 562, 'selfie': 7056, 'removed': 6550, 'hairdresser': 3638, 'claw': 1550, 'restroom': 6640, 'lot': 4745, 'contact': 1796, 'kissing': 4442, 'meats': 4952, 'mick': 5024, 'changing': 1411, 'bureau': 1154, 'rejection': 6515, 'uninsured': 8359, 'imprison': 4040, 'reenacted': 6472, 'taylor': 7913, 'swift': 7833, 'denver': 2242, 'dj': 2468, 'chihuahua': 1471, 'slovak': 7340, 'assassination': 544, 'typewriter': 8298, 'hires': 3831, 'clashes': 1543, 'fascist': 3029, 'hams': 3660, 'tennessee': 7952, 'senior': 7073, 'posing': 6029, 'graduation': 3515, 'waistband': 8569, 'pickle': 5855, 'manager': 4823, 'romanians': 6780, 'demonstrate': 2224, 'streets': 7676, 'provided': 6227, 'corrupt': 1868, 'doughnuts': 2530, 'robot': 6756, 'grandpas': 3530, 'glencore': 3449, 'cutting': 2038, 'oligarch': 5497, 'deripaska': 2268, 'commentary': 1671, 'richard': 6708, 'shelby': 7157, 'brain': 1048, 'terminate': 7964, 'seoul': 7082, 'humans': 3936, 'capabilities': 1264, 'gorillas': 3494, 'conditions': 1728, 'apnewsbreak': 445, 'challenged': 1398, 'gerbil': 3402, 'brexiteers': 1078, 'achievements': 173, 'governments': 3502, 'fuels': 3315, 'privacy': 6138, 'censoring': 1370, 'withholding': 8778, 'hospitalized': 3900, 'kicks': 4414, 'rage': 6348, 'referencing': 6475, 'solves': 7416, 'floridians': 3188, 'irma': 4230, 'taxing': 7909, 'dolphins': 2497, 'claudia': 1549, 'tenney': 7953, 'murderers': 5232, 'marketers': 4871, 'empty': 2742, '2005': 34, 'rachel': 6335, 'maddow': 4784, 'barbeque': 715, 'instructed': 4148, 'recusal': 6457, 'unicorn': 8354, 'critics': 1977, '64': 94, 'died': 2329, 'jan': 4280, 'shipwreck': 7176, 'dinghy': 2344, 'mediterranean': 4964, 'parrots': 5705, 'goulash': 3497, 'yak': 8849, 'dab': 2049, 'devastating': 2307, 'realism': 6416, 'backfire': 650, 'bigly': 879, 'penis': 5784, 'vicky': 8486, 'hartzler': 3697, 'claire': 1534, 'mccaskill': 4934, 'slap': 7308, 'huckleberry': 3923, 'finn': 3127, 'mockingbird': 5122, 'matryoshka': 4915, 'plumbing': 5950, 'mullen': 5220, 'enjoying': 2776, 'disneyland': 2425, 'slowdown': 7342, 'visitors': 8527, 'predicted': 6077, 'parakeets': 5686, 'jacinda': 4264, 'ardern': 492, 'winston': 8756, 'peters': 5827, 'shred': 7217, 'implement': 4027, 'denounces': 2237, 'misunderstands': 5108, 'psychiatrist': 6235, 'shock': 7180, 'greek': 3547, 'yoghurt': 8865, 'registered': 6498, 'flashing': 3156, 'marshmallow': 4879, 'ballot': 688, 'box': 1040, 'lawful': 4551, 'shake': 7134, 'conceivable': 1713, 'sidewalk': 7232, 'weaken': 8645, 'efficiency': 2676, 'diplomatic': 2354, 'regrettable': 6499, 'uncalled': 8319, 'pilgrimage': 5873, 'arbaeen': 487, 'spite': 7511, 'drunk': 2594, 'soothsayer': 7432, 'wayne': 8641, 'lapierre': 4516, 'advocates': 242, 'pizzas': 5904, 'hiphop': 3826, 'tennis': 7954, 'mastiffs': 4904, 'tabloid': 7858, 'planes': 5911, 'belgian': 820, 'bataclan': 750, 'gypsies': 3621, 'misled': 5092, 'skin': 7295, 'spam': 7458, 'prosecute': 6199, 'draws': 2559, 'wide': 8724, 'argentine': 496, 'spitting': 7513, 'mammal': 4819, 'decorations': 2148, 'distracted': 2445, 'hernia': 3783, 'kudlow': 4474, 'trashcans': 8176, 'eyesore': 2964, 'barbara': 713, 'matriarch': 4913, 'dynasty': 2629, 'moonwalks': 5168, 'affairs': 248, 'distillery': 2444, 'sara': 6895, 'seating': 7022, 'robin': 6755, 'louisiana': 4749, 'hare': 3691, 'pancakes': 5663, 'mustache': 5247, 'collude': 1637, 'appearance': 460, 'hoedown': 3849, 'covered': 1913, 'warts': 8616, 'rumor': 6822, 'orrin': 5561, 'hatch': 3707, 'boneheads': 989, 'closing': 1581, 'cheesecake': 1451, 'underarms': 8325, 'bromance': 1108, 'physicist': 5851, 'hawking': 3721, '76': 102, 'mulls': 5223, 'favor': 3042, 'hairbrush': 3633, 'imposes': 4036, 'winners': 8752, 'tipped': 8072, 'staggering': 7559, 'gerbils': 3403, 'shocking': 7182, 'tan': 7881, 'rationale': 6391, 'publish': 6246, 'lame': 4498, 'chaplain': 1418, 'scalding': 6920, 'failings': 2983, 'enjoys': 2777, 'apparent': 455, 'engage': 2767, 'each': 2632, 'militarily': 5046, 'appreciate': 474, 'rages': 6349, 'unabated': 8312, 'spencer': 7488, 'tank': 7883, 'nonprofit': 5388, 'credential': 1946, 'catering': 1334, 'nudge': 5422, 'socks': 7410, 'melts': 4977, 'beheaded': 815, 'burned': 1161, 'alive': 329, 'flood': 3181, 'bangladesh': 698, 'corncobs': 1856, 'sack': 6842, 'mortars': 5179, 'syndrome': 7850, 'shack': 7127, 'marc': 4855, 'andreessen': 387, 'eliminated': 2709, 'universe': 8368, 'snubbed': 7396, 'advances': 232, 'corn': 1855, 'unfettered': 8347, 'goldman': 3478, 'sachs': 6841, 'bedtime': 795, 'discharged': 2385, 'cliff': 1563, 'peacekeeping': 5759, 'warlords': 8597, 'lions': 4677, 'bracing': 1047, 'exposing': 2936, 'surviving': 7801, 'bahrain': 669, 'executes': 2882, 'shia': 7167, 'sentences': 7080, '2010': 38, 'sewer': 7117, 'declassifies': 2142, 'sausage': 6908, 'nike': 5365, 'stays': 7602, 'taxman': 7910, 'shimmies': 7171, 'promenade': 6177, 'curling': 2025, 'realdonaldtrump': 6415, 'besides': 848, 'turnip': 8271, 'soros': 7435, 'compiles': 1698, 'wikipedia': 8734, 'edit': 2668, 'tampon': 7880, 'discriminating': 2399, 'gifts': 3421, 'exchanged': 2875, 'pontiff': 5996, 'appeasing': 462, 'gods': 3469, 'minute': 5078, 'messes': 5007, 'liked': 4654, 'lyft': 4771, 'rideshare': 6714, 'latrine': 4532, 'dirty': 2368, 'lift': 4647, 'weights': 8673, 'allegation': 331, 'serenade': 7088, 'hicks': 3801, 'greenland': 3549, 'wildfire': 8737, 'deserves': 2280, 'fudges': 3311, 'promote': 6182, 'skeletons': 7288, 'waiter': 8571, 'smashes': 7355, 'trumps': 8246, 'tweeting': 8284, 'huskies': 3959, 'prisons': 6137, 'personalities': 5816, 'meetings': 4968, 'hogg': 3851, 'laura': 4545, 'career': 1284, 'treat': 8186, 'budapest': 1124, 'treated': 8187, 'communist': 1686, 'seagull': 7007, 'experience': 2914, 'jay': 4291, 'sekulow': 7053, 'pardons': 5695, 'whiny': 8706, 'adulting': 229, 'flirting': 3176, 'stupefying': 7707, 'wigs': 8732, 'devours': 2314, 'armenia': 507, 'contemplates': 1802, 'nonviolent': 5389, 'revolution': 6696, 'cusp': 2033, 'waving': 8638, 'bean': 771, 'buttock': 1186, 'tearing': 7922, 'replaced': 6575, 'driveway': 2582, 'capture': 1272, 'flopped': 3185, 'damaging': 2059, 'beetles': 801, 'marries': 4874, 'keeper': 4388, 'excellent': 2873, 'goal': 3461, 'pallbearer': 5658, 'neutral': 5330, 'judgment': 4351, 'gear': 3385, 'verdict': 8472, 'birdlime': 901, 'retire': 6657, 'roulette': 6798, 'climb': 1565, 'referendum': 6476, 'agriculture': 286, 'produced': 6158, 'tons': 8097, 'throughout': 8038, 'bagels': 667, 'decries': 2152, 'fomenting': 3208, 'spiders': 7498, 'jump': 4360, 'inflation': 4100, 'beans': 773, 'reaches': 6400, 'punish': 6273, 'blizzard': 940, 'onpolitics': 5511, 'sherbet': 7164, 'crying': 2005, 'superheroes': 7764, 'vast': 8454, 'amounts': 372, 'byproduct': 1197, 'worldwide': 8809, 'wears': 8654, 'resume': 6646, 'northward': 5399, 'starved': 7591, 'areas': 494, 'skyscraper': 7303, 'mattress': 4919, 'sniffing': 7383, 'weaker': 8646, 'eye': 2952, 'beavers': 786, 'send': 7069, 'interests': 4165, 'towels': 8139, 'recipients': 6442, 'snore': 7389, 'steroids': 7624, 'fetishism': 3086, 'phoenix': 5840, 'attracts': 594, 'moved': 5203, 'guatemalan': 3593, 'boxing': 1041, 'congratulates': 1760, 'diversify': 2455, 'processes': 6153, 'imf': 4007, 'outlook': 5585, 'cites': 1519, 'legalization': 4597, 'cancel': 1245, 'berkeley': 841, 'riots': 6731, 'bologna': 974, 'eclipse': 2657, 'viewing': 8496, 'magnifying': 4794, 'stockholm': 7637, 'hedgehog': 3756, 'pitbull': 5896, 'colors': 1647, 'undergarments': 8327, 'squirt': 7543, 'antelope': 422, 'kathy': 4383, 'griffin': 3560, 'metaphor': 5011, 'simile': 7252, 'exchanges': 2876, 'rallies': 6363, 'ryans': 6837, 'dawdles': 2097, 'tolerance': 8090, 'barriers': 732, 'partisan': 5711, 'disrupted': 2437, 'shakespeare': 7136, 'hostage': 3902, 'tags': 7863, 'greenwood': 3552, 'disrobe': 2435, 'rampage': 6366, 'suspicion': 7812, 'intercept': 4161, 'radiation': 6342, 'aardvark': 122, 'govern': 3499, 'shovels': 7208, 'encourage': 2747, 'caviar': 1351, 'exposes': 2935, 'splits': 7516, 'limousine': 4663, 'flexibility': 3168, 'groening': 3571, 'simpsons': 7256, 'apu': 482, 'pretend': 6109, 'grimace': 3565, 'meadows': 4942, 'bold': 973, 'buttocks': 1187, 'dentist': 2239, 'rigged': 6721, 'ramadan': 6365, 'jihadist': 4314, 'hoedowns': 3850, 'signals': 7238, 'further': 3338, 'restrict': 6638, 'investments': 4204, 'curry': 2029, 'disinvites': 2415, 'golden': 3476, 'warriors': 8611, 'donuts': 2512, 'gunmen': 3610, 'shiite': 7170, 'wound': 8822, 'brennan': 1075, 'harder': 3688, 'happening': 3677, 'defiant': 2174, 'crepe': 1954, 'core': 1851, 'pac': 5628, 'pioneer': 5887, 'masaya': 4887, 'nakamura': 5265, '91': 118, 'husband': 3957, 'challenges': 1399, 'meddled': 4955, 'adds': 209, '227': 52, 'rate': 6384, 'fabricates': 2965, 'gulf': 3605, 'minorities': 5074, 'mega': 4970, 'colonies': 1643, 'discovered': 2395, 'canadian': 1240, 'enjoy': 2775, 'violently': 8512, 'expectations': 2905, 'civic': 1527, 'engagement': 2769, 'imagine': 4005, 'cannon': 1260, 'waging': 8568, 'wary': 8617, 'minerals': 5064, 'elephants': 2705, 'yurt': 8875, 'wanda': 8588, 'sykes': 7844, 'diss': 2438, 'intimidation': 4183, 'targeted': 7896, 'misinform': 5091, 'confuse': 1753, 'quarterback': 6306, 'fishy': 3143, 'float': 3177, 'compares': 1691, 'cave': 1349, 'dwellers': 2624, 'courtesan': 1907, 'jails': 4274, 'tourists': 8131, 'istanbul': 4252, 'cakes': 1210, 'psychic': 6237, 'slowly': 7344, 'speeches': 7480, 'otter': 5570, 'coach': 1598, 'expressions': 2939, 'writing': 8839, 'publishers': 6248, 'eager': 2633, 'fishing': 3142, 'dubai': 2598, 'grass': 3535, 'wolves': 8789, 'stomping': 7644, 'investigated': 4196, 'mirror': 5082, 'trades': 8153, 'redistricting': 6463, 'fatty': 3040, 'chauvinists': 1435, 'triggered': 8211, 'watermelon': 8633, 'virgin': 8516, 'misunderstood': 5109, 'casserole': 1318, 'nears': 5305, 'broccoli': 1105, 'through': 8037, 'suburbs': 7725, 'cyborg': 2043, 'binge': 894, 'anyone': 435, 'tense': 7956, 'guantรกnamo': 3589, 'expansion': 2902, 'denham': 2229, 'hears': 3746, 'constituents': 1787, 'rubbed': 6812, 'important': 4032, 'collins': 1635, 'disgusting': 2409, 'barrettes': 730, 'wiggle': 8731, 'corset': 1870, 'poisoned': 5964, 'ivy': 4261, 'françois': 3270, 'hollande': 3858, 'eggs': 2681, 'charlatans': 1424, 'jarred': 4288, 'msnbc': 5210, 'disappointed': 2377, 'bishops': 908, 'whistle': 8710, 'pushing': 6289, 'circumcision': 1515, 'mandatory': 4828, 'misandrist': 5085, 'aclu': 178, 'jane': 4281, 'doe': 2483, 'shaving': 7152, 'moose': 5170, 'hogwash': 3852, 'cartographers': 1309, 'barbers': 717, 'holders': 3854, 'audio': 599, 'seafood': 7005, 'pink': 5886, 'hoping': 3887, 'powerhouse': 6055, 'rainbow': 6355, 'pullout': 6261, 'attempts': 584, 'emerge': 2726, 'criminalize': 1963, 'investigators': 4202, 'guide': 3600, 'sandwiches': 6887, 'accord': 157, 'boyfriend': 1044, 'parades': 5683, 'beet': 800, 'supermodel': 7767, 'recognizes': 6445, 'pride': 6121, 'lgbti': 4625, 'persons': 5819, 'brewery': 1076, 'blindsided': 938, 'throwing': 8041, 'rednecks': 6465, 'rounds': 6801, 'beggars': 806, 'masseuses': 4899, 'hoboken': 3847, 'elects': 2702, 'sikh': 7241, 'jersey': 4304, 'weasel': 8655, 'lipstick': 4680, 'adolf': 223, 'mile': 5042, 'abandoned': 123, 'transformed': 8166, 'getaway': 3408, 'boardwalk': 962, 'fun': 3324, 'league': 4569, 'twin': 8290, 'phase': 5835, 'tripadvisor': 8216, 'criticized': 1974, 'performance': 5800, 'sheldon': 7158, 'adelson': 210, 'newspaper': 5341, 'breakdance': 1063, 'butterflies': 1185, 'snubbing': 7397, 'eclipsing': 2658, 'concludes': 1719, 'interfered': 4167, 'conclusion': 1720, 'rutabagas': 6834, 'guilt': 3602, 'redecorating': 6462, 'begged': 807, 'challah': 1396, 'bifocals': 874, 'warship': 8613, 'boat': 964, 'speeding': 7482, 'uss': 8431, 'tempest': 7944, 'persian': 5811, 'relying': 6533, 'poker': 5968, 'brutal': 1120, 'september': 7086, 'mosquitoes': 5183, 'hacks': 3627, 'dismissed': 2421, 'crayon': 1936, 'diesel': 2331, 'accounts': 164, 'troll': 8222, 'spacex': 7455, 'falcon': 2996, 'vital': 8529, 'adamant': 202, 'osama': 5562, 'remain': 6534, 'tango': 7882, 'sneak': 7377, 'rental': 6560, 'heroin': 3786, 'trunk': 8247, 'rickshaw': 6710, 'rescinding': 6600, 'directing': 2360, 'cocaine': 1606, 'ballerinas': 682, 'souls': 7438, 'goats': 3465, 'dennis': 2235, 'hastert': 3705, 'levitate': 4622, 'libel': 4629, 'vogue': 8536, 'investing': 4203, 'nagorno': 5262, 'karabakh': 4379, 'detectives': 2300, 'unlock': 8374, 'phone': 5841, 'backpage': 655, 'liable': 4627, 'buffalo': 1127, 'westworld': 8689, 'millionaires': 5054, 'utility': 8433, 'raising': 6361, 'donors': 2510, 'costly': 1877, 'flushing': 3195, 'sinkhole': 7267, 'appropriate': 476, 'mint': 5077, 'trust': 8248, 'coin': 1620, 'implosion': 4029, 'basketball': 747, 'repugnant': 6593, 'credibility': 1948, 'dealt': 2116, 'blunt': 959, 'salesman': 6865, 'demoralized': 2226, 'stokes': 7641, 'capacity': 1266, 'rollback': 6773, 'decor': 2147, 'assistance': 557, 'boon': 1003, 'survivors': 7803, 'violin': 8513, 'retreats': 6664, 'tantrums': 7888, 'secure': 7034, 'cite': 1517, 'irreconcilable': 4233, 'differences': 2334, 'hairstyles': 3643, 'attire': 588, 'chicken': 1466, 'louis': 4747, 'farrakhan': 3028, 'loitering': 4717, 'pastry': 5731, 'accuser': 167, 'insider': 4138, 'congresswoman': 1766, 'tables': 7857, 'glitter': 3452, 'combs': 1655, 'welcomes': 8677, 'ventures': 8470, 'disasters': 2380, 'slimmed': 7325, 'screams': 6986, 'hookah': 3879, 'goodwin': 3488, 'proves': 6225, 'royce': 6809, 'reelection': 6470, 'creating': 1943, 'merkley': 4999, 'shorts': 7199, 'favorability': 3043, 'basement': 740, 'coyote': 1919, 'labs': 4490, 'snorting': 7392, 'reflex': 6481, 'zucker': 8898, 'divorce': 2465, 'outhouse': 5583, 'collides': 1633, 'opioid': 5528, 'epidemic': 2802, 'justices': 4368, 'appeal': 457, 'emblem': 2721, 'fluorescent': 3193, '1928': 26, 'steer': 7611, 'myth': 5259, 'cheap': 1436, 'stall': 7568, 'pitch': 5897, 'hijinks': 3811, 'fiesta': 3095, 'kuaishou': 4473, 'tencent': 7950, 'round': 6799, 'ipo': 4220, 'breached': 1060, 'teenager': 7932, 'gropes': 3575, 'obesity': 5450, 'extends': 2943, 'reuters': 6673, 'exercise': 2888, 'slaw': 7316, 'jingle': 4318, 'noon': 5392, 'platypus': 5922, 'larry': 4521, 'flynt': 3199, 'suitable': 7750, 'modi': 5134, '2019': 44, 'spice': 7495, 'austin': 603, 'chimpanzee': 1476, 'abrupt': 136, 'golfers': 3482, 'conor': 1770, 'cheltenham': 1455, 'coventry': 1910, 'midfielder': 5030, 'flog': 3180, 'knees': 4452, 'undo': 8339, 'patient': 5738, 'lobbying': 4705, 'frenzy': 3283, 'dolphin': 2496, 'kissed': 4440, 'frequently': 3284, 'reached': 6399, 'eagle': 2634, 'toss': 8117, 'suburb': 7724, 'stare': 7581, 'chic': 1463, 'nutella': 5438, 'brawls': 1056, 'supermarket': 7766, 'aisles': 307, 'santorum': 6894, 'teacup': 7918, 'boredom': 1011, 'tentative': 7960, 'tuition': 8258, 'graduate': 3513, 'preschool': 6094, 'refers': 6478, 'shithole': 7178, 'clubs': 1592, 'dana': 2063, 'rohrabacher': 6769, 'meyers': 5017, 'bounces': 1029, 'cord': 1850, 'scoble': 6963, 'unfollowed': 8351, 'ultimate': 8307, 'obsessed': 5456, 'compliment': 1707, 'miracle': 5080, 'autism': 613, 'treehouse': 8191, 'tpp': 8146, 'seasons': 7020, 'puzder': 6296, 'laugh': 4534, 'sociologists': 7408, 'interior': 4170, 'survives': 7800, 'designer': 2281, 'dash': 2081, 'lasagna': 4523, 'scatter': 6938, 'gains': 3352, 'codes': 1615, 'bottled': 1025, 'bullshit': 1141, 'pizzagate': 5903, 'anchovies': 384, 'homophobic': 3868, 'foretells': 3234, 'seriously': 7095, 'snowman': 7395, 'simultaneous': 7257, 'wars': 8612, 'trading': 8154, 'advisor': 238, 'quitting': 6324, 'cultists': 2015, 'kneel': 4451, 'responsibility': 6631, 'fond': 3209, 'plumber': 5949, 'naval': 5293, 'drills': 2574, 'surfboards': 7785, 'ousted': 5575, 'surfing': 7787, 'renewable': 6555, 'ipsos': 4221, 'moat': 5116, 'situation': 7281, 'handover': 3669, 'blob': 941, 'tip': 8070, 'steele': 7610, 'makeup': 4808, 'bury': 1168, 'gravediggers': 3540, '55': 87, 'proceeding': 6150, 'fakiness': 2994, 'blamed': 924, 'botched': 1021, 'disgrace': 2405, 'souffle': 7436, 'snipers': 7384, 'symphony': 7848, 'sanity': 6892, 'twirl': 8291, 'sponsor': 7521, 'prostitute': 6205, 'greg': 3555, 'gianforte': 3414, 'sent': 7077, 'slam': 7304, 'boom': 1000, 'fantasies': 3015, 'engines': 2771, 'rappers': 6379, 'nut': 5437, 'rentals': 6561, 'syrup': 7853, 'siesta': 7234, 'iceland': 3972, 'pedophile': 5768, 'furor': 3336, 'breakdancing': 1064, 'kenyan': 4400, 'herders': 3780, 'centuries': 1379, 'prosperity': 6204, 'medicine': 4963, 'buyback': 1191, 'inspires': 4143, 'colbert': 1622, 'emmys': 2732, 'features': 3055, 'explicit': 2923, 'scene': 6939, 'shopping': 7194, 'cactus': 1203, 'swimming': 7835, 'crowns': 1993, 'winner': 8751, 'sesame': 7104, 'rated': 6385, 'stooges': 7650, 'hyena': 3963, 'sneaker': 7378, 'pew': 5832, '61': 92, 'diana': 2318, 'falzone': 3006, 'nudes': 5421, 'physician': 5850, 'physical': 5848, 'mental': 4992, 'touching': 8123, 'benjamin': 838, 'regretting': 6500, 'forcing': 3226, 'caveman': 1350, 'moron': 5177, 'physically': 5849, 'neckties': 5309, 'retard': 6655, 'retain': 6649, 'merkel': 4998, 'hosts': 3904, 'broaden': 1102, 'bargaining': 723, 'funder': 3327, 'bankrolls': 703, 'sites': 7278, 'illustrated': 4002, 'fists': 3145, 'bedbugs': 793, 'catfishing': 1336, 'sculptures': 7001, 'opioids': 5529, 'octopus': 5466, 'horoscope': 3889, 'adani': 203, 'canavan': 1244, 'yells': 8857, 'resists': 6619, 'ostrich': 5566, 'testing': 7981, 'boundaries': 1032, 'downtown': 2542, 'desert': 2276, '2050': 48, 'warming': 8599, 'basic': 745, 'experiment': 2915, 'mock': 5119, 'comedy': 1660, 'billionaires': 888, 'farmers': 3027, 'surge': 7788, 'playboy': 5924, 'cares': 1285, 'terminates': 7965, 'joined': 4328, 'mcdaniel': 4936, 'probes': 6146, 'sleepovers': 7321, 'lindsey': 4666, 'slingshot': 7328, 'yiannopoulos': 8863, 'uc': 8301, 'davis': 2095, 'disturbance': 2451, 'gymnasium': 3618, 'ambitious': 362, 'reconcile': 6448, 'factions': 2974, 'raccoon': 6329, 'berries': 847, 'humiliated': 3937, 'gardener': 3374, 'warmongers': 8600, 'dentistry': 2240, 'incarceration': 4054, 'bowls': 1039, 'vouchers': 8553, 'homeowners': 3865, 'mortgage': 5180, 'deduction': 2153, 'pencils': 5780, '2024': 47, 'rings': 6728, 'nominates': 5380, 'battled': 762, 'defraud': 2183, 'sister': 7272, 'rooster': 6787, 'doctors': 2475, 'rehab': 6505, 'patients': 5739, 'mothers': 5190, 'greenpeace': 3550, 'dismissing': 2423, 'anybody': 433, 'blazing': 933, 'carrots': 1301, 'apples': 469, 'downfall': 2539, 'surfaces': 7784, 'adults': 230, 'minors': 5076, '22': 51, 'curtains': 2031, 'drool': 2586, 'deposition': 2261, 'tracker': 8148, 'alias': 323, 'nyt': 5443, 'assassinate': 543, 'laziness': 4561, 'collie': 1634, 'oversees': 5608, 'departments': 2249, 'crochet': 1978, 'zipper': 8888, 'joining': 4329, 'expels': 2911, 'walking': 8578, 'delivered': 2205, 'acknowledges': 177, 'represented': 6588, 'disowned': 2427, 'lacking': 4492, 'quote': 6327, 'tesla': 7976, 'autopilot': 621, 'tiger': 8057, 'woods': 8796, 'cornholing': 1859, 'fairness': 2989, 'associates': 559, 'tire': 8075, 'diary': 2322, 'sceptical': 6942, 'spotlight': 7525, 'painfully': 5647, 'strangle': 7667, 'cfpb': 1388, 'veterinary': 8480, 'brainwashed': 1050, 'galvanize': 3357, 'cameras': 1227, 'grades': 3512, 'kirsten': 4437, 'gillibrand': 3429, 'meddler': 4956, 'smart': 7352, 'informal': 4107, 'dozen': 2543, 'jugglers': 4356, 'arsenal': 521, 'stronger': 7689, 'tx': 8296, 'abbott': 125, 'sheriffs': 7166, 'costumes': 1881, 'galaxy': 3354, 'butler': 1183, 'currently': 2028, 'wallet': 8582, 'hooky': 3880, 'competent': 1695, 'guy': 3615, 'blew': 937, 'magician': 4791, 'tack': 7859, 'burqa': 1164, 'forward': 3248, 'perhaps': 5802, 'athletes': 572, 'ceremonies': 1384, 'undoes': 8341, 'stages': 7558, 'lunatic': 4765, 'conviction': 1825, 'doodled': 2514, 'afrin': 261, 'pantomimes': 5673, 'gloat': 3453, 'theories': 8004, 'templates': 7945, 'megalomaniac': 4971, 'myopics': 5254, 'barbershop': 718, 'rod': 6761, 'triathlon': 8202, 'selloff': 7060, 'embodies': 2722, 'gift': 3419, 'dalmatians': 2057, 'financing': 3116, 'deploy': 2253, 'institution': 4147, 'ballerina': 681, 'mushroom': 5239, 'hospital': 3898, 'brookfield': 1110, 'troubled': 8231, '666': 96, 'fifth': 3097, 'ave': 623, 'privatize': 6140, 'traffic': 8155, 'bending': 833, 'easily': 2647, 'nakedly': 5267, 'sympathising': 7846, 'nazis': 5300, 'blobs': 942, 'passing': 5722, 'rev': 6674, 'billy': 891, 'detroit': 2304, 'pub': 6242, 'irish': 4229, 'paddy': 5638, 'fruit': 3306, 'elegant': 2703, 'unconvincing': 8322, 'pry': 6233, 'loose': 4732, 'shelters': 7161, 'sidesteps': 7231, 'nigerian': 5358, 'climbs': 1567, 'magnets': 4793, 'choirul': 1486, 'huda': 3925, 'goalkeeper': 3463, 'mate': 4908, 'unemployed': 8343, 'immaterial': 4008, 'mailboxes': 4797, 'midgets': 5032, 'slips': 7331, 'inaction': 4050, 'bounce': 1028, 'naughty': 5291, 'nice': 5349, 'distractions': 2446, 'rattlesnake': 6393, 'corrects': 1866, 'wiretapped': 8763, 'streak': 7669, 'stab': 7547, 'cooperating': 1840, 'strippers': 7685, 'cleans': 1553, 'automakers': 617, 'butter': 1184, 'methane': 5012, 'lollipop': 4718, 'quotes': 6328, 'eggplant': 2680, 'hooray': 3882, 'hairdo': 3636, 'kansas': 4377, 'exaggerations': 2866, 'shrubbery': 7221, 'weaponizes': 8650, 'flatulence': 3158, 'powers': 6056, 'resolution': 6620, 'cleaners': 1552, 'cigarettes': 1510, 'tobacco': 8081, 'ghosts': 3413, 'dumber': 2609, 'closet': 1579, 'fagggots': 2977, 'nigggers': 5360, 'makeovers': 4805, 'swimsuit': 7836, 'putting': 6295, 'doo': 2513, 'stemmed': 7614, 'flower': 3191, 'connect': 1767, 'spike': 7501, 'proctologist': 6154, 'scythe': 7002, 'stonewalling': 7647, 'route': 6803, 'redneck': 6464, 'investigator': 4201, 'deceased': 2130, 'emailing': 2715, 'mute': 5248, 'tease': 7923, 'semblance': 7062, 'always': 358, 'renegotiation': 6554, 'texans': 7983, 'receiving': 6435, 'maple': 4851, 'erik': 2819, 'occupation': 5462, 'slum': 7346, 'distances': 2442, 'laundered': 4542, 'ledger': 4586, 'snakes': 7375, 'passport': 5725, 'chad': 1389, 'animated': 399, 'pestles': 5822, 'fly': 3196, 'friendlier': 3289, 'skies': 7292, 'settling': 7114, 'cartoon': 1310, 'roku': 6770, 'channel': 1412, 'forwards': 3249, 'mooch': 5163, 'outlet': 5584, 'dud': 2603, 'deserts': 2277, 'armadillos': 504, 'grandmothers': 3527, 'vp': 8557, 'citigroup': 1521, 'touches': 8122, 'learning': 4578, 'bleeding': 935, 'musician': 5242, 'spanking': 7461, 'divide': 2458, 'ponytail': 5997, 'appointees': 472, 'salaries': 6861, 'persists': 5813, 'truce': 8233, 'pickles': 5856, 'belief': 821, 'exploding': 2927, 'destructive': 2295, 'reanimating': 6421, 'unfavorable': 8346, 'margaret': 4859, 'atwood': 595, 'puritan': 6283, 'values': 8444, 'flying': 3197, 'properties': 6190, 'vagrant': 8441, 'sacrificed': 6845, 'kidnapper': 4417, 'teeth': 7934, 'disgraceful': 2406, 'publication': 6244, 'mascara': 4888, 'crossed': 1984, 'hey': 3794, 'please': 5938, 'golfing': 3483, 'torches': 8109, 'bouncing': 1030, 'heir': 3762, 'burial': 1157, 'emotion': 2734, 'solving': 7417, 'dyslexia': 2630, 'bronzed': 1109, 'november': 5413, 'builds': 1134, 'haggis': 3629, 'extensive': 2945, 'limiting': 4661, 'lifting': 4648, 'cookout': 1836, 'cabbage': 1199, 'bathed': 752, 'apparently': 456, 'pranked': 6067, 'tumult': 8261, 'clout': 1586, 'dwindles': 2625, 'manhood': 4831, 'insensitive': 4136, 'feet': 3068, 'bashar': 742, 'compete': 1694, 'ioc': 4215, 'stability': 7549, 'credentials': 1947, 'gardens': 3375, 'fec': 3058, 'complaint': 1699, 'oppo': 5530, 'pills': 5877, 'comical': 1664, 'rebekah': 6426, 'mercer': 4995, 'notice': 5409, 'mills': 5056, 'retaliates': 6652, 'closure': 1582, 'slightly': 7324, 'awful': 635, 'ninth': 5369, 'circuit': 1514, 'eo': 2799, 'pander': 5666, 'picks': 5857, 'jerome': 4302, 'powell': 6052, 'vimy': 8503, 'ridge': 6715, 'centenary': 1375, 'reenact': 6471, 'punch': 6266, 'assessment': 552, 'steaks': 7605, 'unforced': 8352, 'errors': 2820, 'inflicted': 4102, 'depart': 2246, 'expulsion': 2940, 'salisbury': 6866, 'mugabe': 5216, 'zimbabwe': 8885, 'snake': 7374, 'blend': 936, 'mucus': 5212, 'thaw': 7995, 'popsicle': 6010, 'dying': 2626, 'disposed': 2430, 'coloring': 1646, 'reading': 6410, 'campaigns': 1231, 'pecans': 5764, 'melodies': 4975, 'maxine': 4922, 'prisoner': 6135, 'captured': 1273, 'calculations': 1212, 'cartoons': 1311, 'baking': 677, 'fedex': 3061, 'viral': 8515, 'stopping': 7653, 'burning': 1162, 'readers': 6408, 'presented': 6097, 'overturn': 5615, 'consumers': 1795, 'lizards': 4699, 'crude': 1996, 'discount': 2393, 'widens': 8726, 'cocoa': 1612, 'coffin': 1617, 'ate': 569, 'comedian': 1658, 'commit': 1677, 'salami': 6859, 'approve': 478, 'queue': 6314, 'rioting': 6730, 'romances': 6777, 'address': 207, 'collective': 1630, 'narcissism': 5276, 'exodus': 2897, '361': 70, 'exxon': 2951, 'mobil': 5118, 'fined': 3120, 'violating': 8507, 'twerking': 8288, 'otto': 5572, 'warmbier': 8598, 'coma': 1651, 'tuxedo': 8279, 'tomatoes': 8095, 'pipes': 5890, 'quills': 6317, 'topping': 8108, 'caused': 1345, 'hotdog': 3906, 'pipe': 5888, 'starvation': 7589, 'unimaginable': 8358, 'biscuit': 907, 'ceilings': 1358, 'hillsborough': 3818, 'football': 3215, 'literacy': 4689, 'spirit': 7507, 'themed': 8001, 'kurdistan': 4477, 'knead': 4450, 'visited': 8526, 'gambler': 3358, 'declared': 2139, 'counts': 1898, 'sexy': 7124, 'contentious': 1804, 'badlands': 663, 'rogue': 6767, 'inadequacies': 4051, 'gap': 3369, 'invisible': 4207, 'wallace': 8581, 'colleagues': 1627, 'disastrous': 2381, 'result': 6644, 'brush': 1119, 'imaginary': 4004, 'losers': 4739, 'clarence': 1540, 'harassed': 3682, 'yes': 8860, 'impeached': 4021, 'resonates': 6623, 'wart': 8615, 'dealer': 2111, 'defeated': 2161, 'chauvinism': 1433, 'weightlifting': 8672, 'rodeo': 6764, 'veteran': 8478, 'glass': 3445, 'artist': 527, 'falsified': 3004, 'trumpet': 8243, 'oatmeal': 5445, 'requires': 6598, 'unpaid': 8378, 'interns': 4174, 'nondisclosure': 5387, 'makeover': 4804, 'repaint': 6566, 'kale': 4374, 'clothed': 1583, 'exams': 2871, 'termites': 7966, 'kompromat': 4465, 'surface': 7783, 'breath': 1070, 'glued': 3456, 'riveting': 6743, 'herself': 3789, 'viewed': 8494, 'benching': 831, 'repairs': 6567, 'discuss': 2401, 'absolute': 139, 'deadline': 2108, 'tusk': 8277, 'racquetball': 6340, 'combat': 1653, 'disintegrate': 2414, 'tens': 7955, 'romania': 6779, 'bravery': 1054, 'costumer': 1880, 'drivel': 2579, 'worship': 8817, 'pinatas': 5883, 'wisconsin': 8765, 'ironworker': 4232, 'cancelled': 1248, 'undersecretary': 8332, 'supremacists': 7779, 'kurds': 4478, 'groping': 3576, 'bullies': 1139, 'seeking': 7041, 'protective': 6214, 'indicate': 4081, 'scroll': 6993, 'taqueria': 7894, 'bowlers': 1037, 'wishful': 8768, 'accent': 148, 'zodiac': 8889, 'killer': 4422, 'extending': 2942, 'limit': 4659, 'ar': 484, 'depressingly': 2262, 'skating': 7287, 'advanced': 231, 'ratio': 6390, 'coasts': 1602, 'confessed': 1736, 'involvement': 4214, 'wrestler': 8833, 'condemnation': 1723, 'flaunt': 3159, 'expose': 2933, 'pictures': 5862, 'pomp': 5991, 'kilt': 4426, 'learn': 4576, 'sychologists': 7842, 'kid': 4415, 'potty': 6046, 'training': 8163, 'princeling': 6128, 'stripped': 7683, 'exile': 2892, 'partied': 5709, 'scratches': 6983, '9th': 120, 'evening': 2851, 'shampoo': 7141, 'alcohol': 315, 'cambodia': 1221, 'hun': 3940, 'object': 5451, 'anarchic': 382, 'submit': 7713, 'communicate': 1684, 'automatically': 619, 'memory': 4986, 'directors': 2365, 'bondholders': 986, 'restructuring': 6642, 'laminate': 4499, 'introduced': 4188, 'misses': 5098, 'healthiest': 3740, 'bloomberg': 951, 'index': 4077, 'tweetstorm': 8286, 'sporting': 7522, 'goods': 3487, 'rifles': 6719, '21': 49, 'misplaces': 5094, 'succeed': 7727, 'bikes': 880, 'incinerated': 4057, 'unaware': 8317, 'division': 2462, 'simmers': 7253, 'feel': 3065, 'ransom': 6372, 'hipsters': 3829, 'baron': 725, 'genital': 3393, 'mutilation': 5249, 'earthworms': 2644, 'mole': 5137, 'despondent': 2286, 'numb': 5428, 'unsure': 8389, 'creators': 1945, 'reza': 6702, 'aslan': 536, 'piece': 5864, 'sh': 7126, 'correctly': 1865, 'identifying': 3979, 'ironclad': 4231, 'hour': 3912, 'abe': 126, 'undermines': 8330, 'backers': 649, 'snail': 7373, 'gymnastics': 3619, 'actor': 194, 'reg': 6493, 'cathey': 1337, '59': 89, 'pirouettes': 5894, 'nuneaton': 5433, 'cucumber': 2009, 'bit': 909, 'professional': 6163, 'sham': 7138, 'detains': 2299, 'consulate': 1791, 'worker': 8803, 'tension': 7957, 'negative': 5312, 'starting': 7586, 'leeway': 4588, 'scrambles': 6979, 'ovens': 5596, 'scams': 6926, 'armed': 506, 'stockings': 7639, 'settles': 7113, 'ditched': 2453, 'peekaboo': 5769, 'fungus': 3333, 'maute': 4921, 'southeast': 7447, 'islamist': 4241, 'relieved': 6528, 'wonderful': 8795, 'organization': 5551, 'large': 4518, 'scale': 6921, 'equivocation': 2811, 'astrologer': 563, 'madrid': 4787, 'jamming': 4279, 'cuddles': 2011, 'remodel': 6546, 'follows': 3207, 'informant': 4108, 'mongoose': 5150, 'attend': 585, 'avenge': 624, 'hunters': 3951, 'albino': 313, 'stigma': 7632, 'cautious': 1347, 'sleepwalkers': 7322, '29th': 60, 'overtakes': 5612, 'pornhub': 6018, 'espn': 2830, 'wto': 8843, 'web': 8658, 'reiterates': 6512, 'ability': 127, 'delta': 2211, 'takeoff': 7868, 'mercosur': 4996, 'wonder': 8794, 'memes': 4981, 'hopeful': 3885, 'marine': 4865, 'skimping': 7294, 'liquor': 4681, 'wiretapping': 8764, 'acne': 179, 'flags': 3154, 'huffington': 3926, 'rein': 6509, 'labrador': 4488, 'fy': 3343, 'violations': 8509, 'pugs': 6255, 'notre': 5410, 'dame': 2061, 'commencement': 1669, 'sprint': 7531, 'withdrawn': 8775, 'noses': 5404, 'anthropomorphism': 425, 'pantsuit': 5676, 'gears': 3386, 'risky': 6739, 'forgets': 3238, 'sterilize': 7622, 'cheetah': 1452, 'ape': 443, 'songs': 7427, 'cyberattack': 2040, 'spreads': 7529, 'broomstick': 1112, 'prodigies': 6155, 'execs': 2881, 'decisions': 2136, 'yard': 8850, 'grope': 3574, 'java': 4290, 'husbands': 3958, 'zte': 8896, 'ordered': 5546, 'fingerprints': 3123, 'listing': 4687, 'politician': 5978, 'consistently': 1783, 'staircase': 7561, 'achieve': 172, 'pomade': 5990, 'injected': 4122, 'dose': 2519, 'served': 7099, 'bbq': 766, 'unmotivated': 8377, 'pirates': 5892, '57': 88, 'drivers': 2581, 'oprah': 5535, 'confidants': 1740, 'tonsils': 8098, 'promising': 6181, 'rhetoric': 6703, 'locks': 4715, 'netflix': 5325, '104': 8, 'subscribers': 7719, 'toothpicks': 8106, 'luiz': 4763, 'inacio': 4049, 'lula': 4764, 'silva': 7249, 'defies': 2178, 'hunkers': 3948, 'blankie': 928, 'strongest': 7690, 'rash': 6383, 'retrieve': 6666, 'cyberweapons': 2042, 'peddling': 5767, 'architecture': 490, 'expects': 2907, 'alpaca': 350, 'exist': 2893, 'matrix': 4914, 'deportations': 2257, '37': 71, 'dominates': 2500, 'rankings': 6371, 'nation': 5281, 'schools': 6956, 'gang': 3365, 'standoff': 7577, 'normalization': 5395, 'recuses': 6458, 'copeland': 1845, 'tories': 8110, 'enchilada': 2746, 'gynecologist': 3620, 'downgrading': 2540, 'dccc': 2103, 'ventral': 8468, 'cream': 1939, 'garage': 3371, 'easter': 2649, 'ball': 680, 'raft': 6347, 'sashays': 6899, 'chant': 1414, 'aggression': 275, 'carousels': 1294, 'rebuke': 6431, 'arts': 528, 'en': 2744, 'masse': 4897, 'forever': 3235, 'realist': 6417, 'confrontation': 1751, 'cher': 1459, 'sashaying': 6898, 'revisions': 6690, 'trusted': 8249, 'sneakers': 7379, 'cockpit': 1607, 'vine': 8505, 'freeze': 3280, 'psychiatrists': 6236, 'dates': 2088, 'trails': 8160, 'heartburn': 3748, 'pigsties': 5871, 'tools': 8103, 'delete': 2195, 'require': 6596, 'employment': 2741, 'offends': 5473, 'odor': 5468, 'lick': 4638, 'aaa': 121, 'necessarily': 5307, 'sector': 7032, 'dec': 2127, 'estimate': 2835, '190': 24, 'adp': 226, 'sphincter': 7494, 'danish': 2075, 'inventor': 4193, 'confesses': 1737, 'dismembering': 2418, 'inventing': 4192, 'progressives': 6173, 'loyalty': 4760, 'pantry': 5674, 'accelerate': 147, 'animation': 400, 'depicts': 2251, 'la': 4483, 'swastika': 7821, 'viewers': 8495, 'lifelong': 4646, 'halloween': 3648, 'desantis': 2270, 'nursemaid': 5436, 'carried': 1298, 'repealing': 6569, 'academics': 146, 'laureates': 4546, 'misplace': 5093, 'fingernails': 3122, 'grab': 3508, 'sunscreen': 7759, 'reveled': 6680, 'disclosures': 2391, 'drenched': 2567, 'surrealist': 7793, 'ronny': 6783, 'marital': 4866, 'bellows': 826, 'meatballs': 4951, 'dashcam': 2082, 'philando': 5836, 'castile': 1320, 'informing': 4112, 'firearm': 3129, 'gremlin': 3556, 'millennial': 5050, 'stroke': 7687, 'francisco': 3265, 'pier': 5865, 'aspiring': 537, 'fainted': 2987, 'giggles': 3425, 'leftist': 4590, 'boston': 1019, 'supposed': 7776, 'fortune': 3246, 'fruitworm': 3308, 'runoff': 6827, 'bakery': 676, 'scrooge': 6994, 'prestigious': 6108, 'scholarship': 6952, 'disadvantaged': 2370, 'hamburgers': 3657, 'oozes': 5516, 'encouraging': 2749, 'compromise': 1710, 'flirt': 3175, 'ridicules': 6716, 'receptionist': 6439, 'effective': 2675, 'grits': 3567, 'lettuce': 4620, 'nosedive': 5403, 'reducing': 6468, 'output': 5587, 'tender': 7951, 'wearing': 8653, 'scotus': 6973, 'curtain': 2030, 'tighten': 8059, 'venezuelan': 8466, 'possession': 6033, 'plug': 5947, 'cavities': 1352, 'flagged': 3153, '2004': 33, 'pirate': 5891, 'tolerate': 8091, 'restrooms': 6641, 'grasshoppers': 3536, 'crush': 2002, 'decode': 2146, 'illiterates': 4001, 'ankara': 402, 'footstool': 3218, 'machines': 4780, 'edible': 2667, 'dough': 2528, 'craze': 1937, 'heartland': 3749, 'imposters': 4038, 'tux': 8278, 'beard': 775, 'stance': 7573, 'confirming': 1745, 'heterosexuality': 3793, 'behalf': 813, 'owl': 5620, 'groupie': 3581, 'hotness': 3909, 'toe': 8084, 'columbia': 1648, 'winks': 8750, 'dustpans': 2619, 'befell': 802, 'cigars': 1511, 'teatime': 7924, 'counseled': 1888, 'murderer': 5231, 'showgirl': 7214, 'knocking': 4457, 'guys': 3616, 'courts': 1909, 'tee': 7928, 'markers': 4869, 'officers': 5483, 'yetis': 8862, 'retaken': 6650, 'pumping': 6264, 'aleppo': 318, 'monitoring': 5151, 'internal': 4171, 'dynamics': 2627, 'rolling': 6774, 'seize': 7050, 'doghouses': 2488, 'discussing': 2403, 'indictment': 4083, 'taunting': 7903, 'ontario': 5513, 'wore': 8800, 'bench': 830, 'dina': 2341, 'gala': 3353, 'whilst': 8701, 'searching': 7017, 'roboticists': 6757, 'granted': 3532, 'visas': 8523, 'precision': 6076, 'monster': 5156, 'spare': 7463, '23m': 55, 'uninsuredrepublican': 8360, 'reaper': 6422, 'seizes': 7052, 'anbang': 383, 'gentle': 3397, 'busy': 1179, 'baghdad': 668, 'polish': 5975, 'absence': 137, 'skis': 7299, 'swim': 7834, 'delhi': 2198, 'engulfed': 2774, 'halts': 3651, 'upstage': 8411, 'visits': 8528, 'acid': 174, 'showed': 7211, 'librarian': 4635, 'thesaurus': 8009, 'cincinnati': 1513, 'nightclub': 5362, 'plums': 5951, 'reactivated': 6403, 'shed': 7154, 'fitness': 3147, 'develops': 2310, 'organizer': 5552, 'describing': 2273, 'daily': 2054, 'dove': 2534, 'closes': 1578, 'spanks': 7462, 'dubke': 2599, 'revolts': 6695, 'whine': 8702, 'ample': 374, 'slapstick': 7311, 'buffoonery': 1130, 'autopsies': 622, 'somersaults': 7421, 'enraged': 2781, 'refund': 6487, 'worsen': 8816, 'pyramid': 6299, 'essays': 2831, 'drones': 2585, 'scarves': 6936, 'pouring': 6048, 'robe': 6753, 'suspicious': 7813, 'packages': 5634, 'locations': 4712, 'soda': 7411, 'ejaculations': 2689, 'cellphones': 1367, 'matched': 4906, 'nestle': 5322, 'factory': 2975, 'dodd': 2478, 'frank': 3266, 'accountable': 162, 'defector': 2165, 'props': 6198, 'stumbles': 7704, 'exhumes': 2891, 'limericks': 4658, 'bribed': 1080, 'calm': 1220, 'beyond': 863, 'brochure': 1106, 'digestive': 2337, 'smear': 7356, 'retribution': 6665, 'recruits': 6455, 'populists': 6015, 'consultants': 1792, 'kindergartener': 4432, 'bowler': 1036, 'worm': 8810, 'toothpick': 8105, 'tasked': 7901, 'bedroom': 794, 'redecorates': 6461, 'commence': 1668, 'ill': 3996, 'sergeant': 7090, 'nick': 5351, 'bailey': 670, 'sable': 6838, 'uranus': 8414, 'referral': 6477, 'herring': 3788, 'passion': 5723, 'patriotism': 5741, 'hollywood': 3859, 'orly': 5560, 'phoned': 5843, 'screwed': 6989, 'momma': 5144, 'delays': 2192, 'noodle': 5390, 'clarify': 1541, 'bubbles': 1122, 'apologies': 448, 'adores': 225, 'crowding': 1990, 'wellesley': 8679, 'walnuts': 8584, 'sitar': 7275, 'auctioned': 598, 'beitar': 819, 'trivia': 8221, 'ddos': 2104, 'suggesting': 7745, 'inches': 4055, 'gambling': 3361, 'serial': 7093, 'stowaway': 7661, 'citizenry': 1523, 'carnage': 1289, 'kabul': 4372, 'butchery': 1182, 'brendan': 1074, 'samantha': 6876, 'wiccan': 8722, 'treadmill': 8182, 'horrific': 3892, 'bezos': 864, 'screws': 6990, 'amazon': 359, 'flies': 3169, 'viper': 8514, 'spiro': 7508, 'agnew': 278, 'nattering': 5289, 'nabobs': 5260, 'negativity': 5313, 'doddering': 2479, 'dotards': 2522, 'deplorableness': 2252, 'silliness': 7247, 'plugs': 5948, 'obsession': 5457, 'located': 4710, 'ushers': 8429, 'amount': 371, 'producing': 6160, 'bafta': 664, 'update': 8399, 'password': 5726, 'nurse': 5435, 'consent': 1772, 'provoke': 6231, 'applause': 467, 'cereal': 1383, 'belly': 827, 'ended': 2754, 'manipulation': 4836, 'oh': 5490, 'bother': 1024, 'winnie': 8753, 'pooh': 6002, 'foul': 3251, 'censors': 1371, 'nationalists': 5285, 'pent': 5790, 'tigers': 8058, 'grilled': 3563, 'heated': 3751, 'exchange': 2874, 'saxophones': 6915, 'disciplined': 2386, 'pillar': 5875, 'fictitious': 3092, 'statements': 7594, 'squints': 7540, 'showers': 7213, 'locust': 4716, 'smells': 7358, 'alimony': 328, 'forest': 3233, 'cobblers': 1604, 'daddy': 2053, 'virulent': 8521, 'represents': 6589, 'perfectly': 5799, 'utterly': 8435, 'integrative': 4154, 'complexity': 1704, 'supper': 7768, 'malarkey': 4810, 'cafeterias': 1206, 'tummy': 8260, 'blackjack': 915, 'resurrect': 6648, 'zia': 8884, 'zoos': 8895, 'snorkeling': 7391, 'falafel': 2995, 'dreamed': 2563, 'zebra': 8880, 'semitism': 7064, 'leg': 4593, 'vets': 8483, 'dissolved': 2440, 'gelatin': 3389, 'pencil': 5779, 'greatest': 3545, 'cauldron': 1343, 'windy': 8747, 'hygiene': 3964, 'couches': 1884, 'stewing': 7629, 'broward': 1116, 'daycare': 2100, 'thin': 8014, 'unhealthily': 8353, 'raping': 6377, 'rescued': 6601, 'boko': 972, 'haram': 3681, 'defeatist': 2162, 'cardboard': 1279, 'fetish': 3085, 'bungles': 1150, 'transvestites': 8172, 'reorganized': 6564, 'cyberwars': 2041, 'nudity': 5424, 'blasted': 930, 'majorettes': 4801, 'cooties': 1843, 'misanthropics': 5086, 'floods': 3183, 'landslides': 4511, 'main': 4798, 'shine': 7172, 'hb2': 3726, 'atoms': 575, 'janitors': 4283, 'eater': 2653, 'gastronomic': 3377, 'gamblers': 3359, 'migration': 5040, 'crumpet': 2001, 'reassures': 6425, 'slower': 7343, 'fb': 3047, 'touted': 8134, 'shuffle': 7222, 'plate': 5920, 'indefensible': 4073, 'decorators': 2150, 'boogies': 994, 'cult': 2014, 'scholar': 6951, 'ecuador': 2664, 'matchmaking': 4907, 'illinois': 3999, 'celebs': 1364, 'tribal': 8203, 'neighbors': 5316, 'pterodactyl': 6241, 'endangering': 2753, 'lives': 4695, 'asserting': 549, 'glee': 3447, 'salling': 6867, 'allowed': 341, 'varsity': 8453, 'scientist': 6961, 'breathe': 1071, 'secular': 7033, 'leopard': 4609, 'ring': 6727, 'cramps': 1930, 'quacks': 6303, 'vultures': 8560, 'mare': 4858, 'thrower': 8040, 'urinate': 8419, 'gaps': 3370, 'knowledge': 4459, 'aisle': 306, 'fume': 3322, '1380': 14, 'crew': 1955, 'stowaways': 7662, 'punching': 6269, 'stuffs': 7703, 'pecking': 5765, 'sonic': 7428, 'similar': 7251, 'peels': 5770, 'unwritten': 8395, 'picnics': 5860, 'essential': 2832, 'hottest': 3910, 'ranked': 6370, 'mistresses': 5107, 'hippies': 3827, 'flour': 3189, 'lighthearted': 4651, 'suppository': 7777, 'pill': 5874, 'cotton': 1882, 'quilting': 6319, 'marsupials': 4881, 'batteries': 759, 'coolness': 1837, 'hungarian': 3944, 'fairyland': 2991, 'mug': 5215, 'bloodstream': 950, 'rhyme': 6704, 'stamps': 7572, 'starve': 7590, 'endgame': 2755, 'nail': 5263, 'cajole': 1208, 'stem': 7613, 'sitcom': 7276, 'chides': 1468, 'gutter': 3614, 'toxic': 8142, 'electric': 2698, 'ceasefire': 1356, 'resigning': 6614, 'directions': 2362, 'disposal': 2429, 'unit': 8364, 'investigates': 4197, 'motorway': 5194, 'pavement': 5749, 'zuck': 8897, 'harvesting': 3700, 'unfolds': 8350, 'madeleine': 4786, 'albright': 314, 'reminder': 6543, 'withhold': 8777, 'andy': 389, 'menswear': 4991, 'increases': 4069, 'affected': 250, '87': 111, 'nanny': 5273, 'actors': 195, 'pepe': 5794, 'marinade': 4864, 'manicure': 4834, 'bombed': 978, '2007': 35, 'hulk': 3932, 'paradise': 5684, 'papers': 5680, 'prompt': 6185, 'drapery': 2556, 'parakeet': 5685, 'toast': 8080, 'puzzles': 6297, 'tunnel': 8263, 'jihad': 4313, 'inconveniencing': 4067, 'knitted': 4456, 'mccarthyite': 4933, 'counterproductive': 1892, 'necklace': 5308, 'entertaining': 2789, 'schlapps': 6949, 'weirdo': 8675, 'yorkers': 8870, 'volunteer': 8541, 'wrestlers': 8834, 'canoodles': 1262, 'mulligans': 5222, 'junkies': 4364, 'pep': 5793, 'shade': 7129, 'sri': 7545, 'lankan': 4514, 'licks': 4640, 'shulkin': 7223, 'committees': 1680, 'washers': 8620, 'schizophrenia': 6947, 'landscaping': 4509, 'retina': 6656, 'image': 4003, 'improves': 4045, 'gpa': 3506, 'fuhrer': 3318, 'materials': 4911, 'diarrhea': 2321, 'sugar': 7744, 'tribes': 8204, 'shape': 7142, 'wine': 8748, 'helpful': 3771, 'chug': 1503, 'obamas': 5448, 'inked': 4125, '65': 95, 'petroleum': 5830, 'conflicted': 1748, 'eyeball': 2953, 'beaver': 785, 'oven': 5595, 'remarries': 6539, 'infection': 4095, 'parsecs': 5706, 'smugglers': 7368, 'followed': 3205, 'prefers': 6082, 'vendetta': 8464, 'fahrenheit': 2978, '451': 82, 'reflect': 6479, 'vocabulary': 8533, 'girdles': 3435, 'vacations': 8438, 'vellicate': 8463, 'shameless': 7140, 'shortly': 7198, 'hobo': 3846, 'golfer': 3481, 'overtures': 5614, 'repeats': 6572, 'mantra': 4843, 'based': 739, 'revelations': 6679, 'peach': 5760, 'scales': 6922, 'frolics': 3298, 'rodents': 6763, 'htin': 3921, 'kyaw': 4482, 'bamboozles': 691, 'guaranteeing': 3590, 'ladder': 4493, 'mankind': 4837, 'pad': 5637, 'alcoholics': 316, 'spell': 7485, 'reshaping': 6607, 'boozing': 1009, 'clams': 1537, 'derail': 2267, 'trollies': 8224, 'folder': 3203, 'shallow': 7137, 'grave': 3539, 'seniors': 7074, 'corners': 1858, 'sctv': 6998, 'reunite': 6671, 'raiser': 6358, 'dave': 2093, 'classic': 1546, 'stereotype': 7621, 'caresses': 1286, 'flashy': 3157, 'aground': 287, 'ego': 2682, 'barron': 733, 'forbes': 3221, 'poppycock': 6009, 'mayonnaise': 4925, 'veganism': 8458, 'waltz': 8585, 'strudel': 7693, 'sheep': 7156, 'quilt': 6318, 'distribution': 2448, 'embraced': 2724, 'veritas': 8475, 'stage': 7557, 'criteria': 1969, 'authoritarian': 609, 'harvard': 3698, 'disguise': 2407, 'babbles': 640, 'foods': 3212, 'hoodlums': 3877, 'holidays': 3857, 'advertiser': 233, 'mishandling': 5090, 'bikinis': 882, 'nails': 5264, 'chipmunk': 1483, 'clemency': 1561, 'leonard': 4608, 'peltier': 5774, 'wen': 8680, 'ho': 3842, 'searches': 7016, 'hiking': 3814, 'dotard': 2521, 'puppets': 6278, 'warrant': 8608, 'geek': 3387, 'havana': 3715, 'cigar': 1509, 'spelling': 7486, 'parrot': 5704, 'carolers': 1291, 'snoring': 7390, 'commercials': 1674, 'brutality': 1121, 'venezuelans': 8467, 'scour': 6975, 'river': 6742, 'treasure': 8184, 'survival': 7797, 'spouses': 7527, 'sweetening': 7830, 'infrastructure': 4116, 'ruthless': 6835, 'intercontinental': 4163, 'heightening': 3761, 'supporting': 7774, 'legacy': 4594, 'emotional': 2735, 'farewell': 3023, 'lawn': 4554, 'vile': 8498, 'peak': 5761, 'believability': 822, 'mugs': 5217, 'hairball': 3632, 'reign': 6507, 'slamming': 7306, 'fork': 3242, 'frost': 3304, 'neutering': 5329, 'understanding': 8334, 'aussie': 602, 'dingo': 2345, 'kettle': 4404, 'waistline': 8570, 'wacky': 8563, 'gender': 3391, 'sparrow': 7468, 'congratulate': 1759, 'slimy': 7326, 'teeing': 7929, 'atheists': 571, 'antifa': 428, 'barricades': 731, 'demonstrators': 2225, 'orgy': 5556, 'enquirer': 2780, 'diagrams': 2316, 'escaping': 2827, 'resources': 6625, 'staffs': 7556, 'compost': 1708, 'invades': 4190, 'vanity': 8451, 'hissing': 3835, 'snacks': 7371, 'crowbar': 1988, '200': 32, 'historical': 3837, 'defaced': 2158, 'hateful': 3709, 'england': 2772, 'smog': 7361, 'chokes': 1488, 'latin': 4531, 'moped': 5172, 'bacteria': 661, 'chancellor': 1405, 'lobbied': 4704, 'annihilating': 405, 'prattles': 6070, 'overcharging': 5599, 'mocks': 5123, 'neighbor': 5315, 'exploded': 2925, 'recently': 6437, 'osha': 5565, 'tomato': 8094, 'houses': 3916, '473': 83, 'bumble': 1145, 'decade': 2128, 'bogeyman': 971, 'brawl': 1055, 'epic': 2801, 'mr': 5209, 'whcd': 8694, 'pussy': 6291, 'jake': 4277, 'tapper': 7892, 'orgasm': 5555, 'mispronunciations': 5095, 'vitamin': 8530, 'taxidermist': 7908, 'chin': 1478, 'moms': 5146, 'scarecrow': 6933, 'jon': 4336, 'jabs': 4263, 'heroes': 3785, 'shoestrings': 7186, '80s': 106, 'script': 6992, 'alma': 346, 'mater': 4909, 'sizzler': 7285, 'franchise': 3263, 'enemies': 2762, 'earns': 2638, 'erection': 2815, 'prayer': 6072, 'chest': 1460, 'forehead': 3229, 'member': 4978, 'fruitcakes': 3307, 'offshore': 5487, 'trailblazer': 8159, 'volume': 8540, 'tiptop': 8074, 'impenetrable': 4023, 'cranial': 1931, 'tsa': 8254, 'tightens': 8060, 'screening': 6987, 'expedite': 2908, 'roseanne': 6792, 'barr': 727, 'smacks': 7350, 'transported': 8171, 'cruel': 1997, 'inhuman': 4120, 'degrading': 2186, 'carriages': 1297, 'soviet': 7451, 'contrasting': 1813, 'standards': 7575, 'oranges': 5542, 'lobsters': 4708, 'pacifist': 5631, 'kindness': 4434, 'inmate': 4126, 'harem': 3692, 'hot': 3905, 'mic': 5019, 'kraken': 4469, 'watches': 8629, 'helplessly': 3773, 'streamed': 7671, 'kombucha': 4464, 'porcupines': 6016, 'comedians': 1659, 'chins': 1481, 'elbows': 2692, 'condemn': 1722, 'closely': 1576, 'ginger': 3432, 'oxygen': 5626, 'mastered': 4903, 'seeming': 7044, 'atheist': 570, 'somnambulist': 7424, 'ankles': 403, 'intervened': 4177, 'acquired': 180, 'paraphernalia': 5690, 'retaliate': 6651, 'gigantism': 3423, 'wrecks': 8830, 'accident': 153, 'unicycle': 8356, 'dachshunds': 2051, 'borrowers': 1014, 'governing': 3500, 'digital': 2338, 'baseballs': 738, 'malawi': 4811, 'clampdown': 1536, 'vampirism': 8447, 'rumors': 6823, 'entry': 2793, 'shortages': 7197, 'territory': 7971, 'eyeballed': 2954, 'fishermen': 3141, 'cruelest': 1998, 'rodrigo': 6765, 'mayors': 4927, 'mosquitos': 5184, 'bout': 1033, 'guides': 3601, 'congratulations': 1761, 'entertain': 2788, 'enslaved': 2784, 'progress': 6171, 'divine': 2460, 'ices': 3973, 'squirts': 7544, 'cartel': 1306, 'comic': 1663, 'senegal': 7072, 'saboteur': 6840, 'airing': 300, 'hardcore': 3687, 'triangles': 8201, 'apes': 444, 'explodes': 2926, 'plotting': 5945, 'stores': 7655, 'nationwide': 5286, 'carts': 1312, 'pitches': 5899, 'backyard': 659, 'mules': 5219, 'instructs': 4149, 'frightened': 3294, 'tidal': 8052, 'duh': 2606, 'papadopoulos': 5677, 'gambles': 3360, 'equation': 2807, 'designs': 2282, 'militant': 5044, 'benghazi': 837, 'raisin': 6360, 'bestiality': 851, 'ogre': 5488, 'biometric': 898, 'database': 2084, 'enrollment': 2783, 'baldness': 678, 'parachute': 5681, 'jewish': 4310, 'montana': 5158, 'iguana': 3994, 'currency': 2026, 'warplane': 8607, 'screaming': 6985, 'flips': 3174, 'sweetens': 7831, 'convent': 1819, 'thespian': 8011, 'ham': 3653, 'pimples': 5881, 'hindu': 3822, 'counties': 1894, 'track': 8147, 'insurers': 4153, 'connections': 1769, 'chants': 1416, 'infatuation': 4094, 'cozy': 1920, 'blanket': 927, 'retired': 6658, 'shreds': 7218, 'alibaba': 324, 'ma': 4776, 'judges': 4350, 'allotments': 338, 'crucial': 1994, 'canary': 1243, 'measure': 4948, 'classed': 1545, 'fracking': 3260, 'gophers': 3492, 'humanity': 3935, 'hermits': 3782, 'kindergartner': 4433, 'chart': 1429, 'cholesterol': 1490, 'kabobs': 4371, 'checks': 1444, 'chase': 1431, 'rush': 6830, 'attendance': 586, 'fleas': 3162, 'impersonates': 4024, 'assertion': 550, 'deserved': 2279, 'minions': 5069, 'insomnia': 4140, 'microsoft': 5025, 'inappropriate': 4052, 'bing': 893, 'engine': 2770, 'acrobatics': 182, 'gimpy': 3430, 'midget': 5031, 'oooo': 5515, 'wrongdoings': 8841, 'pigs': 5870, 'origami': 5557, 'server': 7100, 'hunks': 3949, 'milk': 5048, 'kite': 4445, 'queen': 6308, 'combusts': 1656, 'weibo': 8668, 'forbidden': 3222, 'disagree': 2371, 'tailgate': 7864, 'angel': 391, 'orchestrating': 5544, 'leash': 4579, 'films': 3110, 'clairvoyant': 1535, 'scrutinising': 6996, 'hiring': 3832, 'toadies': 8079, 'jesus': 4306, 'campos': 1234, 'moments': 5143, 'toothbrush': 8104, 'automatic': 618, 'hikes': 3813, 'revenue': 6682, 'serfdom': 7089, 'fest': 3082, 'disingenuous': 2413, 'persist': 5812, 'hairline': 3639, 'muhammad': 5218, 'ali': 322, 'horrible': 3891, 'shame': 7139, 'redstate': 6466, 'bloggers': 947, 'stalkers': 7567, 'forgot': 3240, 'scout': 6976, 'cosmetologists': 1872, 'vegans': 8459, 'dreads': 2561, 'thanked': 7991, 'fema': 3074, 'bombers': 980, 'impose': 4034, 'grandson': 3531, 'fixing': 3151, 'deflate': 2180, 'malibu': 4815, 'upending': 8402, 'ducks': 2602, 'sergey': 7092, 'kislyak': 4438, 'poetry': 5958, 'impersonator': 4026, 'crashed': 1933, 'missed': 5097, 'groundhog': 3578, 'contest': 1805, 'anime': 401, 'prank': 6066, 'hairpieces': 3641} ###Markdown TF-IDF for a word in a document is calculated by multiplying two different metrics:The **term frequency** of a word in a document. There are several ways of calculating this frequency, with the simplest being a raw count of instances a word appears in a document. Then, there are ways to adjust the frequency, by length of a document, or by the raw frequency of the most frequent word in a document.The **inverse document** frequency of the word across a set of documents. This means, how common or rare a word is in the entire document set. The closer it is to 0, the more common a word is. This metric can be calculated by taking the total number of documents, dividing it by the number of documents that contain a word, and calculating the logarithm.So, if the word is very common and appears in many documents, this number will approach 0. Otherwise, it will approach 1.Multiplying these two numbers results in the TF-IDF score of a word in a document. The higher the score, the more relevant that word is in that particular document. Extract features of both training and validation data ###Code # helper function: separate each title into (original_word, context), where context = title text without original word # params: # df: dataframe, with 'original' and 'edit' columns # return: # original_words: a list of original word strings before editing # contexts: a list of context strings def separate_original_word_from_title(df): original_words = [] contexts = [] for index, row in df.iterrows(): title = row['original'] start_position = title.find('<') end_position = title.find('/>') original_words.append(title[start_position+1 : end_position]) contexts.append(title[:start_position] + title[end_position+2 :]) return original_words, contexts ###Output _____no_output_____ ###Markdown Here we construct a Sparse Feature Matrix. This is to make this task more computationally easy. More information can be found here: https://machinelearningmastery.com/sparse-matrices-for-machine-learning/ ###Code # construct sparse feature matrix # params: # df: dataframe, with 'original' and 'edit' columns # vectorizer: sklearn text vectorizer, either TfidfVectorizer or Countvectorizer # return: # M: a sparse feature matrix that represents df's textual information (used by a predictive model) def construct_feature_matrix(df, vectorizer): edit_words = df['edit'].tolist() original_words, contexts = separate_original_word_from_title(df) # here the dimensionality of X is len(df) x |V| X_edit = vectorizer.transform(edit_words) return X_edit # Construct feature matrices for training and validation data train_X = construct_feature_matrix(train_dataframe, vectorizer) valid_X = construct_feature_matrix(valid_dataframe, vectorizer) test_X = construct_feature_matrix(test_dataframe, vectorizer) ###Output _____no_output_____ ###Markdown Train model on training set, evaluate model on validation set You could use a number of different models here. Look at this list and see what potentially othe models you would want to use:https://scikit-learn.org/stable/modules/classes.htmlmodule-sklearn.linear_model ###Code # train a linear regression model lm = LinearRegression() model = lm.fit(train_X, train_Y) print (model.intercept_) print (model.coef_.shape) # Evaluate model on validation set valid_Y_hat = model.predict(valid_X) rmse = np.sqrt(sklearn.metrics.mean_squared_error(valid_Y, valid_Y_hat)) print('RMSE on validation set:', rmse) # Evaluate model on training set: # expect to see unrealistically good performance! (for RMSE: lower is better) # unrealistic because YOUR MODEL IS TRAINED ON EXACTLY THESE DATA! # It gives the best validation/test performance you could hope to achieve using this model. train_Y_hat = model.predict(train_X) rmse = np.sqrt(sklearn.metrics.mean_squared_error(train_Y, train_Y_hat)) print('RMSE on training set:', rmse) # apply the model on test data, write out prediction results to a csv file test_Y_hat = model.predict(test_X) write_test_prediction(test_dataframe, test_Y_hat, './ridge-regression_alpha=1_baseline_new-tf.csv') ###Output _____no_output_____ ###Markdown Investigate what the model has learned and where it failed (A.K.A. error analysis) Look at learned parameters (for linear model: weight of each dimension) ###Code # construct a mapping: word -> learned weight of this word feature_weight = {} for word, idx in vectorizer.vocabulary_.items(): feature_weight[word] = model.coef_[idx] # words positively correlate with funniness (top ones) for k, v in sorted(feature_weight.items(), key = lambda x: x[1], reverse = True)[:10]: print (k, v) # words negatively correlate with funniness (top ones) for k, v in sorted(feature_weight.items(), key = lambda x: x[1], reverse = False)[:10]: print (k, v) ###Output opposition -0.8836506444659917 years -0.8836506444659917 border -0.8836506444659917 sale -0.8836506444659917 trump -0.8836506430721189 check -0.8836506430721189 blames -0.8836506430721189 hike -0.8836506430721189 radio -0.8836506430721189 attacks -0.8836506430721189 ###Markdown Look at how the model makes predictions on individual examples ###Code # We pick a set of examples from the validation set (we predicted scores for those). # We usually we don't pick from training data (since the good performance may be unrealistic). # We cannot do error analysis on test data (because no true target value is provided). def explain_linear_prediction(df, model, idx2feature, X, Y, Y_hat, idx_list): print('indices:', idx_list) for idx in idx_list: print ('==============', idx, '================') print ('original:', df.iloc[idx]['original']) print ('edit:', df.iloc[idx]['edit']) print ('grades:', df.iloc[idx]['grades']) print ('TRUE score:', df.iloc[idx]['meanGrade']) print ('PRED score:', Y_hat[idx]) print ('\nPRED breakdown:') print ('\tINTERCEPT', model.intercept_) if X[idx, :].nnz == 0: print ('\tFEATURE', '[EMPTY]') else: for entry in X[idx, :]: # looping over a row in sparse matrix feature_value = entry.data[0] feature_dim = entry.indices[0] print ('\tFEATURE', idx2feature[feature_dim], ':', 'f_value', feature_value, '*', 'f_weight', model.coef_[feature_dim], '=', feature_value*model.coef_[feature_dim]) # construct a dictionary mapping: feature index -> word idx2feature = dict([(v,k) for k,v in vectorizer.vocabulary_.items()]) errors = (valid_Y - valid_Y_hat)**2 # sort errors from low to high sorted_errors = sorted(enumerate(errors.iloc[:].tolist()), key = lambda x: x[1], reverse = False) # print(sorted_errors) ###Output _____no_output_____ ###Markdown prediction on random examples ###Code # pick a random set of examples from validation set: K = 5 random_indices = np.random.randint(0, valid_X.shape[0], K) explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, random_indices) ###Output indices: [1088 1232 1065 1669 505] ============== 1088 ================ original: Starbucks <encourages/> bipartisan coffee-drinking edit: forces grades: 32110 TRUE score: 1.4 PRED score: 0.8836506400461821 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE forces : f_value 1.0 * f_weight 0.0 = 0.0 ============== 1232 ================ original: A detailed <analysis/> of the Trump-Palin-Nugent-Kid Rock photo edit: shocker grades: 11000 TRUE score: 0.4 PRED score: 0.8836506400461821 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE [EMPTY] ============== 1065 ================ original: Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's <Power/> and Role edit: kitchen grades: 32111 TRUE score: 1.6 PRED score: 1.1500000089824969 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE kitchen : f_value 1.0 * f_weight 0.26634936893631467 = 0.26634936893631467 ============== 1669 ================ original: Trump border wall : Texans receiving letters about their <land/> edit: barbecue grades: 32222 TRUE score: 2.2 PRED score: 1.0666666540652607 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE barbecue : f_value 1.0 * f_weight 0.18301601401907858 = 0.18301601401907858 ============== 505 ================ original: After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can <Help/> ’ edit: Fly grades: 11000 TRUE score: 0.4 PRED score: 0.9999999969738926 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE fly : f_value 1.0 * f_weight 0.11634935692771053 = 0.11634935692771053 ###Markdown examples with closest prediction ###Code K = 5 # look at data with lowest prediction error low_error_indices = [i for i, v in sorted_errors[:K]] explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, low_error_indices) ###Output indices: [1428, 84, 110, 619, 955] ============== 1428 ================ original: Susan Sarandon : ‘ I Do n’t Think Trump ’s Gon na Make It Through His Whole <Term/> ’ edit: sandwich grades: 32110 TRUE score: 1.4 PRED score: 1.4000000024059092 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE sandwich : f_value 1.0 * f_weight 0.5163493623597272 = 0.5163493623597272 ============== 84 ================ original: FBI Director asks Justice Department to publicly <denounce/> Trump 's assertion of Obama wiretapping edit: approve grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE approve : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 110 ================ original: Trump walks back bizarre <comments/> on funding black colleges — but this administration ’s racism is no mistake edit: rant grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE rant : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 619 ================ original: A top State Department official could n't explain why the U.S. <backs/> Saudi Arabia edit: loves grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE loves : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 955 ================ original: <Watch/> : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” edit: clock grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE clock : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ###Markdown examples with worst predictions ###Code K = 5 # look at data with highest prediction error high_error_indices = [i for i, v in sorted_errors[-K:]] explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, high_error_indices) ###Output indices: [978, 120, 2146, 310, 774] ============== 978 ================ original: Spicer defends Trump : Issues are ' evolving towards the president 's <position/> ' edit: mouth grades: 10000 TRUE score: 0.2 PRED score: 2.199999996973688 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE mouth : f_value 1.0 * f_weight 1.316349356927506 = 1.316349356927506 ============== 120 ================ original: Donald Trump Endorses Keeping Senate in <Session/> Seven Days a Week to Get Nominees Approved edit: Jail grades: 32222 TRUE score: 2.2 PRED score: 0.19999999697402915 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE jail : f_value 1.0 * f_weight -0.683650643072153 = -0.683650643072153 ============== 2146 ================ original: Trump to North Korean leader Kim : My ‘ Nuclear <Button/> ’ is ‘ much bigger &amp; more powerful ’ edit: Belly grades: 33222 TRUE score: 2.4 PRED score: 0.3999999969739948 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE belly : f_value 1.0 * f_weight -0.4836506430721873 = -0.4836506430721873 ============== 310 ================ original: Charlotte Pence : I Bought The Gay <Bunny/> Book edit: republican grades: 33322 TRUE score: 2.6 PRED score: 0.5999999969739607 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE republican : f_value 1.0 * f_weight -0.2836506430722214 = -0.2836506430722214 ============== 774 ================ original: ' Disappeared ' Lawyer investigating in Egypt the <death/> of Cambridge student , Giulio Regeni , re-appears in court , under charges edit: selfies grades: 10000 TRUE score: 0.2 PRED score: 2.399999996973653 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE selfies : f_value 1.0 * f_weight 1.5163493569274713 = 1.5163493569274713 ###Markdown Introduction to Machine LearningGrant GlassTAP InstituteDay 01:Key Concepts and Terms Preface Welcome to Machine Learning as a part of the 2021 TAP Institute's summer courses. In this first day notebook, we will go over the core concepts of machine learning and start to get our feet wet with. I will not be providing you a complete overview, but rather a quick way to get a genereal understanding about what machine learning is and how it works. In days two and three, we will be exploring different machine learning techniques more in depth. Covered in this Notebook 1) What is Machine Learning?2) What is a Statistical Model?3) A framework for understanding ML4) Simple Example of ML Before we Begin! Head to the Google Teachable Machine Website: https://teachablemachine.withgoogle.comThe Teachable Machine website provides an easy to use interface for training image, sound, and pose classification models. No login is required to get started. Training data files can be loaded directly from your computer or from your computer’s webcam or microphone. Models can be exported to use in other projects, and the FAQ (https://cloud.google.com/inclusive-ml/) includes links to read more about fairness and inclusion in ML.Take a look at this project involving training a model to detect how ripe a piece of fruit is: https://medium.com/@warronbebster/teachable-machine-tutorial-bananameter-4bfffa765866How do you think the computer figures out ripeness?What exactly are we teaching the machine?What other humanistic data could we use for this type of machine learning? Part One - What is MACHINE LEARNING? The field itself: ML is a field of study which harnesses principles of computer science and statistics to create statistical models. These models are generally used to do two things:Prediction: make predictions about the future based on data about the pastInference: discover patterns in data Difference between ML and AI: There is no universally agreed upon distinction between ML and artificial intelligence (AI). AI usually concentrates on programming computers to make decisions (based on ML models and sets of logical rules), whereas ML focuses more on making predictions about the future.They are highly interconnected fields, and, for most non-technical purposes, they are the same. Part Two - What is A STATISTICAL MODEL? **Models:** Teaching a computer to make predictions involves feeding data into machine learning models, which are representations of how the world supposedly works. If I tell a statistical model that the world works a certain way (say, for example, that two story homes are more expensive than one story homes), then this model can then tell me what be more expensive, a ranch style home or a cape cod. What does a model actually look like? Surely the concept of a model makes sense in the abstract, but knowing this is just half the battle. You should also know how it’s represented inside of a computer, or what it would look like if you wrote it down on paper.A model is just a mathematical function, which is merely a relationship between a set of inputs and a set of outputs. Here’s an example:f(x) = x²This is a function that takes as input a number and returns that number squared. So, f(1) = 1, f(2) = 4, f(3) = 9.Let’s briefly return to the example of the model that predicts home price from home stories. I may believe, based on what I’ve seen in the world, that given a home's price is, on average, equal to the house's stories times 100,000. This model can be represented mathematically as follows:Price = Stories × $100,000In other words, income is a function of stories.**Here’s the main point:** Machine learning refers to a set of techniques for estimating functions (like the one involving income) based on datasets (pairs of heights and their associated incomes). These functions, which are called models, can then be used for predictions of future data.**Algorithms:** These functions are estimated using algorithms. In this context, an algorithm is a predefined set of steps that takes as input a bunch of data and then transforms it through mathematical operations. You can think of an algorithm like a recipe — first do this, then do that, then do this. Done.Machine learning of all types uses models and algorithms as its building blocks to make predictions and inferences about the world.Now I’ll show you how models actually work by breaking them apart, component by component. This next part is important. Part Three - A Framework for understanding ML **Inputs:** Statistical models learn from the past, formatted as structured tables of data (called **training data**). These datasets — such as those you might find in Excel sheets — tend to be formatted in a very structured, easy-to-understand way: each row in the dataset represents an individual **observation,** also called a datum or measurement, and each column represents a different **feature**, also called a predictor, of an observation.For example, you might imagine a dataset about people, in which each row represents a different person, and each column represents a different feature about that person: profession, age, income, etc.Most traditional models accept data formatted in the way I’ve just described. We call this structured data.Because one common goal of ML is to make predictions, training data also includes a column containing the data you want to predict. This feature is called the response variable (or output variable, or dependent variable) and looks just like any other feature in the table.Most common statistical models are constructed using a technique called supervised learning, which uses data that includes a response variable to make predictions or do inference. There is also a branch of ML called unsupervised learning, which doesn’t require a response variable and which is generally used just to find interesting patterns between variables (this pattern-finding process is known as inference). It is just as important as supervised learning, but it is usually much harder to understand and also less common in practice. This document won’t talk much about the latter subfield. The takeaway from this paragraph is simply that there are two “types” of learning, and that supervised learning is more common.Model selection: We have our data, and we’ve decided that there’s probably a relationship between our predictors and our response. We’re ready to make predictions.As an aside, we don’t actually need to know if there’s a relationship between these variables. We could, in fact, just throw all of our data into an algorithm and see if the resulting model is able to make valid predictions.Now we need to pick which model to use. Naturally, there are many different types of models which explain how the data actually works, and we’d like to choose the one that most accurately describes the relationship between the predictors and the response variable.Models generally fall into one of two categories:**Regression models**, which are used when the response variable (i.e. the variable that you’re predicting) is continuous. For example, height, age, and income are all continuous. That is, they can be placed and ordered on a number line.**Classification models**, which are used for categorical data — that is, data that doesn’t have a numerical ordering. For example, you may want to predict, based on an image of a flower, the species of that flower. Or you may want to predict whether a student is a psychology major or a math major.The first step in picking a model is deciding whether or not your response variable is quantitative or categorical.Why is model selection an important concept for non-technical people? Well, if a model is chosen poorly, then its predictions will be inaccurate!Below, I’ll walk you through an example of a popular, powerful, simple mode that can be used for prediction. Part Four - Let's Look at an example! ###Code # Import Libraries import pandas as pd import numpy as np import scipy import sklearn from sklearn import linear_model from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer ###Output _____no_output_____ ###Markdown Load data, split into training and validation sets ###Code filepath = 'data/train.csv' dataframe = pd.read_csv(filepath) print(len(dataframe)) # print(dataframe) dataframe.head() ###Output _____no_output_____ ###Markdown This is a text-based regression task. Every training document (a line in the data file) contains the following columns (csv format):**id:** document identifier;original: original news headline, in which one word is tagged between ;**edit:** the new word to replace the tagged word in the original headline;**grades:** a list of funniness grades (0="Not Funny", 1="Slightly Funny", 2="Moderately Funny", 3="Funny") concatenated into a single string. For instance, '1101' means four human judges looked at the edited headline and submitted funniness grades {1, 1, 0, 1};**meanGrade:** the average funniness value. In the previous example, meanGrade = (1+1+0+1)/4 = 0.75 .Your goal is to predict the average funniness value of an edited headline. More concretely, to predict the meanGrade (a real value) given an original headline, a tagged word, and an edit word. ###Code train_ratio = 0.7 # 70% for training, 30% for validation random_seed = None # a fixed random seed allows fixed random runs (for controlled debugging). set to None to be random. train_dataframe = dataframe.sample(frac= train_ratio, random_state=100) valid_dataframe = dataframe.drop(train_dataframe.index) print('training set size:', len(train_dataframe)) print('validation set size:', len(valid_dataframe)) # print(train_dataframe) ###Output training set size: 5067 validation set size: 2172 ###Markdown Also load test data (no splitting needed here) ###Code test_filepath = 'data/test.csv' test_dataframe = pd.read_csv(test_filepath) print('test set size:', len(test_dataframe)) # print(test_dataframe) test_dataframe.head() ###Output _____no_output_____ ###Markdown Try the trivial baseline: always predicting the average meanGrade (of training data) ###Code # take out prediction targets: mean grades train_Y = train_dataframe['meanGrade'] valid_Y = valid_dataframe['meanGrade'] ###Output _____no_output_____ ###Markdown The Root Mean Squared (RMSE) is our evaluation metric and is calculated as𝑅𝑀𝑆𝐸=√∑𝑛𝑖=1(𝑦𝑖−𝑦̂𝑖)2/nwhere 𝑦𝑖 is the actual funniness value of the document, and 𝑦̂𝑖 is the predicted value of the document, so (𝑦𝑖−𝑦̂𝑖)2 is the squared error of prediction. The lower RMSE, the more accurate prediction. ###Code # compute average of a list of numbers: np.mean train_Y_avg = np.mean(train_dataframe['meanGrade']) print('average meanGrade on training set:', train_Y_avg) # make a list filled with train_Y_avg, essentially predicting the same number for all lines in validation set avg_pred_valid = [train_Y_avg for i in range(len(valid_dataframe))] # print (avg_pred_valid) # compute root mean squared error (RMSE) of this prediction on validation set rmse = np.sqrt(mean_squared_error(valid_Y, avg_pred_valid)) print('RMSE on validation set:', rmse) #taking the mean as the error # helper function: write out prediction values into a csv format file # params: # df: dataframe, where each row is a test example, with column 'id' as data id # pred: a list or 1-d array of prediction values # filepath: the output file path # return: # None def write_test_prediction(df, pred, filepath): with open(filepath, 'w') as outfile: outfile.write('{},{}\n'.format('id', 'pred')) for index, row in df.iterrows(): outfile.write('{},{}\n'.format(row['id'], pred[index])) # make a list filled with train_Y_avg, essentially predicting the same number for all lines in test set avg_pred_test = [train_Y_avg for i in range(len(test_dataframe))] write_test_prediction(test_dataframe, avg_pred_test, './average_constant_baseline_new-tf.csv') ###Output _____no_output_____ ###Markdown Build feature extractor from training data (here we use a CountVectorizer or TfidfVectorizer ) ###Code # get entire raw text in training corpus, including title and edit words (for learning vocabulary and IDF) # params: # df: dataframe, with 'original' and 'edit' columns # return: # corpus: a list of text strings, each is a concatenation of original text and edit word on each line def get_raw_text(df): corpus = [] for index, row in df.iterrows(): title = row['original'].replace('<', '').replace('/>', '') edit = row['edit'] corpus.append( title + ' ' + edit ) return corpus ###Output _____no_output_____ ###Markdown TF-IDF ( Term Frequency(TF) — Inverse Dense Frequency(IDF) ) is a statistical measure that evaluates how relevant a word is to a document in a collection of documents. This is done by multiplying two metrics: how many times a word appears in a document, and the inverse document frequency of the word across a set of documents.It has many uses, most importantly in automated text analysis, and is very useful for scoring words in machine learning algorithms for Natural Language Processing (NLP).TF-IDF (term frequency-inverse document frequency) was invented for document search and information retrieval. It works by increasing proportionally to the number of times a word appears in a document, but is offset by the number of documents that contain the word. So, words that are common in every document, such as this, what, and if, rank low even though they may appear many times, since they don’t mean much to that document in particular.However, if the word Bug appears many times in a document, while not appearing many times in others, it probably means that it’s very relevant. For example, if what we’re doing is trying to find out which topics some NPS responses belong to, the word Bug would probably end up being tied to the topic Reliability, since most responses containing that word would be about that topic. ###Code train_corpus = get_raw_text(train_dataframe) print(train_corpus) vectorizer = TfidfVectorizer(stop_words = None).fit(train_corpus) print(vectorizer.vocabulary_) #vectorizer = CountVectorizer(stop_words = None).fit(train_corpus) #print(vectorizer.vocabulary_) ###Output ['Congress OKs Trump bid to widen private care at besieged VA destroy', 'Trump and Obama have the same approval rating after their first year , at least according to one poll person', 'H.R. McMaster says Trump administration will confront Russia \'s " destabilizing behavior " lizard', 'Triple Threat : New Pneumonia Is Drug-Resistant , Deadly And Contagious President', 'Is it Watergate yet ? moving', 'Report : Trump Wants His Chief Of Staff To Get Rid Of Jared And Ivanka police', 'How the Right Co-Opts Frederick Douglass handedness', 'Forget Trump – populism is the cure , not the disease hugging', 'AP Fact Check : An angry Trump twists facts about raid , probe candy', 'Michelle Obama was Jimmy Fallon ’s only guest and , no , they did not mom dance enemy', 'DOJ charges 11 possible caravan members with illegally entering the US restaurant', 'How Steve Bannon became the face of a political movement with roots in Los Angeles Cheerleaders', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " people', 'As It Makes More Arrests , ICE Looks For More Detention Centers Recreation', 'Syrian state TV says successive blasts heard in Hama province eructations', 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon circus', 'Trump defends decision to keep “ political and long ” Democratic memo under wraps presents', 'Trump blames Corker for the Iran deal smell', 'Remember when Republicans were mad that a president was unreliable to allies ? mistress', "Childhood bullying anxiety ' goes away ' homework", 'Steve Bannon is reportedly advocating for a tax hike on the wealthy nature', ' Resignation Wave On Capitol Hill Might Not Be Over Radio', 'Six journalists get life in prison over failed Turkish coup film', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson scent', 'House Democrats stun GOP by sinking veterans , intel bills fences', "South Korea 's president is expected to face prosecutors in coming days canines", 'Schiff : Trump Jr. may have been first to know about Russian efforts to meddle in election mysteries', 'CDC to hold briefing on how public can prepare for nuclear war chickens', 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Kiss', 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants sons', 'GOP lawmaker loses nearly $ 17 million after pharma stock tanks 92 % aquarium', '2016 RNC Delegate : Trump Directed Change To Party Platform On Ukraine Support bra', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller wake', 'Obama ’s Strange Last Days in Office pets', "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' stupidity", "Could microwave missiles disable North Korea 's missiles ? cook", "' I was very angry ' at Trump , says Myeshia Johnson , widow of fallen soldier cake", 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN Stealing', 'Gunmam attacks a Church in Helwan , Cairo . Four dead and nine wounded . [ shooter killed ] pie', "Tech and entertainment activists launch an app to ' Block the Bully ' Donald Trump on Twitter patsy", 'Ex-British spy paid $ 168,000 for Trump dossier , U.S. firm discloses tea', 'Despite Campaign Boasts , Trump Has No Idea How To Handle Classified Material Smoothies', "Jailed Malaysian Opposition Leader To Be Pardoned After His Party 's Victory dance", "North Korea ICBMs : Pyongyang says it will conduct nuclear missile test ' anytime and anywhere it wants ' meme", "World 's largest collection of ocean garbage is now twice the size of Texas political", 'The Olympic Gold Medal for Sucking Up to a Murderous Totalitarian Regime Goes to … Vacuum', "Rex Tillerson : US has ' direct channels ' to Pyongyang scam", "' Black Panther 's ' Wakanda sheds light on black excellence darkness", 'Quotation of the Day : Trump Tried to Sink Inquiry , Comey Says hoops', 'DirecTV is offering refunds for NFL Sunday Ticket to fans offended by national anthem protests melody', "Congress ' deficit hawks seem to have gone missing in action doves", 'Drunken American beating up for giving Nazi salute in Germany praised', 'Occupy Silicon Valley : The next populist movement may be aimed at tech wealth , report says bunnies', 'How to Stop an Autocracy itch', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News Water", 'Trump is making Americans see the U.S. the way the rest of the world already did despise', 'Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . Reality', 'The Republican tax bill contains a sneaky break for private jet owners bathroom', 'Charlotte Pence : I Bought The Gay Bunny Book Wrote', 'This congressional accounting trick is part of the reason Washington is so divided magic', "Advice for Trump : Do n't fire Robert Mueller -- He will clear you in the end tickle", 'The middle class does n’t want a tax cut . It wants better government . coffee', 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it bear', 'Experts to Trump : Russia is not our ally in the war on ISIS bears', ' Trump predicts Patriots will win Super Bowl by 8 points gypsy', 'GOP senators : Comey drafted statement clearing Clinton before her interview tickling', 'Trump Official Blocked Immigrant Teen Rape Victim ’s Abortion Because He Personally Opposed It healthy', 'Trump ’s Trillion Dollar Pledge to Fix Bridges and Roads Could be Challenging . . Lie', ' Taiwan court to rule in in landmark same-sex marriage case Heterosexual', 'White House invites intelligence committee leaders to review National Security Council documents tweets', 'Fought and forgotten : Filipino World War II veterans honored with medal 75 years later days', "Trump officials greet Ford 's plan to import Chinese cars Food", 'Donald Trump Jr. should publicly testify in Russia probe , Democrat on Senate Judiciary Committee says strip', 'Trump addresses Boy Scouts at national summit in West Virginia loses', "Rep. King seeks more surveillance after Port Authority explosion : ' We ca n't afford to be politically correct ' bowel", 'Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR vegetables', "Israeli minister wishes Iranian protesters ' success ' pleads", 'More than 50 detained in immigration raids at Asian restaurants in Mississippi house', 'President Trump to hold another Q&amp;A on The Donald subreddit this Wednesday apocalypse', "In the former capital of the Confederacy , the debate over the city 's famed Civil War monuments is heating up mounting", "Trump blasts Michelle Wolf 's correspondents ' dinner remarks about Sarah Huckabee Sanders gravy", 'The Latest : San Juan mayor answers Trump ’s Twitter attack Wasteland', 'Special counsel Robert Mueller impanels grand jury for Russia probe koala', 'Five Pacific islands lost to rising seas as climate change hits sun', "Bill O'Reilly is ' mad at God ' for sexual harassment scandal Libido", "Trump labels US justice system ' laughingstock ' renames", 'Kamala Harris : Trump testimony is on the table dinner', 'Sean Spicer has a problem : Melissa McCarthy gum', 'U.S. Has Discussed Nuclear Weapons in South Korea manure', 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI Editors', 'GOP tax cuts will strengthen our economy and drive Democrats crazy biceps', 'Search for a Motive in Las Vegas : Slow but ‘ We ’ll Get There ’ Tortoise', 'Second judge denies Scott Walker ’s request to delay special elections Playground', 'Peskov : Trump lawyer wrote to Kremlin , got no response Santa', 'Forget Planet 9 — there ’s evidence of a tenth planet lurking at the edge of the solar system pleasure', 'Connecticut pastor charged with stealing $ 8G in electricity praying', 'Medicare-for-all progressive may just pull out a win in a key Nebraska House primary bowling', 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election rib', 'Wrenched From Scandal to Success , Trump Looks Ahead , and Over His Shoulder trips', 'TV station in Afghan capital comes under attack tent', "Elon Musk 's vision for underground road system bumps", 'Study : Hillary Clinton ’s emails got as much front-page coverage in 6 days as policy did in 69 swallowed', 'Trump Bodyguard Keith Schiller Testifies Russian Offered Trump Prostitutes , Aligning With Dossier Story Pimp', "Rubio 's defection threatens Senate GOP 's margin on tax bill greasiness", 'Somewhere between his hero , Justice Scalia , and former boss , Justice Kennedy lover', 'Trump Bodyguard Keith Schiller Testifies Russian Offered Trump Prostitutes , Aligning With Dossier Story Tacos', 'How can we save the Democratic Party ? Princess', 'UAE says Qatari fighter jets intercepted civilian flight raced', 'RIP Roger Moore ... James Bond goalie', 'Israel Must Release 16-Year-Old Girl Who Faces 10 Years In Prison , Amnesty Says Scotch', "Trump vows ' no amnesty ' for ' Dreamers , ' says GOP leaders ' on board ' with talks mimes", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans goat', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore cockroach", ' Survivor : We will only be heard if we scream @CNN Mime', 'Trump says banning immigrants helps US workers . A leading economist says he ’s wrong . poodles', 'Suicide bomber kills seven , wounds 20 in Afghan provincial capital : official shopper', "Alabama 's Roy Moore would be the most extreme senator — with huge consequences for Congress lecher", "Donald Trump 's Charlottesville remarks force White House to try to contain fallout spread", 'Chris Cornell , Soundgarden frontman , dies aged 52 graduates', 'A woman running for Congress faces a double mastectomy — and the repeal of the ACA latte', 'Before Trump , hate was already present in Canada cake', 'Puerto Rico benchmark bond drops to record low after Trump remark Spoke', "Women 's Heavy Disapproval Of Trump May Not Cut So Deep Against GOP In 2018 Midterms dessert", 'Parties fight over funding children ’s health insurance vomit', 'Sean Hannity ’s long-standing defense of sexual abusers promotion', 'Report : Jeff Sessions spoke with Russian ambassador at least twice during the election meeting', 'Government Accountability Office to Examine Cost , Security of Trump Florida Trips grocery', 'Trump Saw A Military Parade In France And Now He Wants One Of His Very Own . Dog', 'Yet another mystery motive automotive', 'Russia Blames Obama for Trump Failures in White House Out', "FBI ' reopens investigation into Clintons at Donald Trump 's request ' Martians", 'Trump administration may force CNN to be sold as part of $ 85bn deal scraps', "Cold weather : Do n't leave these things in your car when temps fall Cook", 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants eat', "Russia Will Test ' Unstoppable ' Satan Missile by End of 2017 , Says Military pancake", 'Portland train stabbing suspect said " that \'s what liberalism gets you , " docs say cake', 'Despite Promise of Bottom-Up , Transparent Process , Paul Ryan Sets Record for Stifling Floor Debate temperature', 'U.S. fighter jet shoots down Iranian-made drone in Syria turkey', 'Top Republicans urge Sessions to appoint special counsel to probe FBI feed', 'Trump : If Dems Get Back in Power , They ’re Going to Raise Your Taxes ‘ Way Up High ’ income', "Hurricane Maria : ' we have lost all ' says Dominica prime minister – live chuckles", 'Iranian oil tanker wreck produces two slicks in East China Sea drifting', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News dinner", 'A Reporter ’s Reflections on Hillary Clinton ’s Loss hair', " Keystone pipeline wo n't have to use American steel , despite Trump 's repeated promises steel", '“ Son of a bitch ” : Trump ’s NFL outburst fits a larger pattern tantrum', 'In court , a Turkish journalist delivers a searing attack on the government kebabs', 'More GOP Senators Say No , Killing Chances For Republican Healthcare Bill cows', 'Trump on Charlottesville : Racism is evil Barbecue', 'Youngest Texas shooting victim just 18 months old : What we know now licking', 'France , U.S. committed to wiping out Islamic State stain', 'The last president to fire an FBI director ? Bill Clinton cuddle', 'Poll : 60 % of voters back Trump ’s travel ban agoraphobics', 'Ruble plunges for 2nd day following US sanctions parties', "We 've got a deal : Government shutdown looks set to end as Democrats surrender Awaken", 'Male congressman questions why men have to pay for prenatal care . Really . fetuses', 'President Trump Set to Visit a Traumatized , Divided Las Vegas kick', "China 's Economy to Overtake Euro Zone This Year Absorb", 'Republican Debbie Lesko wins Arizona special election , NBC News projects lottery', 'Trump administration will review Iran nuclear deal despite compliance Tweet', "' Get ready Russia ' : Trump issues warning on Syria missile strikes bowling", 'Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says Wedgie', "Chester Bennington dead : Linkin Park singer ' dies aged 41 ' sang", 'Trump administration rolls back ObamaCare contraceptive mandate candies', "TRUMP FUMES AT MUELLER AFTER COHEN RAID : ' It 's an attack on our country ' insects", 'Trump urged Mexican president to end his public defiance on border wall striptease', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S escape', 'BREAKING : Trump considering options for Syria retaliation , source says vacation', 'Washington Post ’s David Fahrenthold wins Pulitzer Prize for dogged reporting of Trump ’s philanthropy crookedness', 'Pentagon claims 2,000 % increase in Russian trolls after Syria strikes . What does that mean ? accents', 'Trump judicial nominee refuses to express support for landmark desegregation ruling gratitude', "Los Cabos is no longer a haven from Mexico 's bloodshed cuisine", "Trump says he 's not worried what Flynn will tell special counsel ; there 's been ' no collusion ' worrying", 'North Korea says missile test shows all US within range earshot', "Mattis : ' I need to make the military more lethal ' hope", "Trump voters see his flaws but stand by president who ' shakes things up ' pelvis", 'Liu Xiaobo supporters mark his death amid concerns for widow Health', 'Police hold South African for trying Everest without permit shoes', 'Republican Senate Fundraising Arm Bails on Roy Moore spits', 'The Supreme Court ’s Blockbuster Term movies', "Word To The President : ' Professionalism ' moon", 'Trump is right -- California is out of control Jellybeans', 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food celebrating', 'Is the end of Donald Trump ’s presidency drawing nearer ? Either way he will have done great harm to America haircut', 'US Could Get First Paid Family Leave Benefit Under Trump flush', 'Treasury Department announcing sanctions against Iran Friday morning silver', 'Menendez Bribe Case Proceeds After Judge Rejects Dismissal Bride', 'White House says there ’s no need for new Russia sanctions celebration', 'North Korea crisis becoming unsolvable , experts warn , as Trump heads to Asia circus', 'Fyre Festival Organizers Hit With $ 100 Million Lawsuit Bong', 'Bannon , Lewandowski invited to testify before House Intelligence Committee Lie', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling Dressing', "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' bride", "Trump 's pardon of ex-Sheriff Joe Arpaio was the right ( and courageous ) thing to do haircut", 'US suspects Niger villager betrayed Army troops fink', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students Roofs", 'India to build major military facility in Seychelles amid growing China influence infest', 'Shrinking Bears Ears : Another massive insult to Native Americans Bears', "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in wash", 'The Republican tax bill contains a sneaky break for private jet owners island', 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Principal', "Trump 's history of breaking decorum with remarks on race , ethnicity profits", 'After a Debacle , How California Became a Role Model on Measles Debacles', "Russia 's boost in trade with North Korea worries U.S. hackers", 'Trump said Haitians have aids , Nigerians live in huts in oval office meeting bacchanal', '" We could be separated " : Immigrants , families react after Trump administration ends protected status Condiments', 'Stormy Daniels tells of threats following reports of affair with Trump cookbook', "Intel chiefs wo n't say if Trump asked them to intervene in investigations opera", 'Jerusalem Mayor to Trump : Do n’t be Intimidated By Palestinian Threats Of Violence , Move Embassy Hummus', 'Border Patrol Shooting Death Of Immigrant Woman Raises Tensions In South Texas backpack', 'Eighteen people found guilty over Newcastle sex grooming network virgins', "Spicer , denying report on Sally Yates : ' I hope she testifies ' attention", 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia dog', 'Senate Intelligence Panel Subpoenas Former National Security Adviser Michael Flynn Oxen', 'Bump Stock Maker Resumes Sales One Month After Las Vegas Mass Shooting Eating', 'The Russian government is giving up control of Kalashnikov remote', 'Teachers , Lawyers And Others Worry About The Fate Of Student Debt Forgiveness disappearance', 'Alternatives to Putin a mixed bag as Russian election looms drinks', ' Advocacy group accuses military justice system of racial bias Girl', ' Trump judicial nominee refuses to express support for landmark desegregation ruling bonehead', 'After a Debacle , How California Became a Role Model on Measles Plague', 'Disgusted By Trump , A CIA Officer Quits . How Many More Could Follow ? smoking', 'Syrian President Assad faces international pressure to step down , but in Damascus there is a mood of defiance boogie', "' Maybe I did n't get her so much ' : President Trump on first lady 's birthday fat", 'Trump maps new course with allies and autocrats in first foreign trip prostitutes', 'Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . autograph', 'Six journalists get life in prison over failed Turkish coup delight', 'Trump Lawyers Want A Second Special Counsel sitters', "This Is n't ' Another Watergate ' But It Plays As One On TV – And On Twitter Broadway", 'Vornado Has ‘ Handshake ’ to Sell Stake in NYC Tower to Kushner Give', "China could strike U.S. bases in ' minutes ' — and may be practicing years", "Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' waltzing", 'Lee Jae-yong , Samsung Leader , Is Indicted on Bribery Charges kidnapping', "Has the UN failed Myanmar 's Rohingya Muslims ? kittens", 'Out of loopholes , Trump must disclose Stormy Daniels debt in next financial report fee', 'New DOJ alert system will flag crimes against police fashion', 'Manafort Notes From Russian Meet Refer to Political Contributions legs', 'Trump Is Giving Staffers Secret Assignments And Telling Aides To Hide Them From John Kelly haircuts', "Robert Mueller reportedly looking into Trump 's ' attempt to oust ' Jeff Sessions decency", "US says refugee admissions wo n't be suspended until July 12 auditions", 'Lieberman emerges as frontrunner for FBI post relay', 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food delicious', 'Idaho Is Fastest-Growing State in U.S. potato', 'Trump quietly stalls safeguards for dozens of endangered species bakers', 'South Korean police on alert over Trump protests chickens', 'Medicare X : the Democrats ’ supercharged public option plan , explained bathing', " Trump : ' I have no doubt that we 'll win ' travel ban lawsuit Gorilla", 'AP FACT CHECK : Trump and the Washington blame game themselves', 'Grassley promises hearings into McCabe ’s firing once inspector general ’s report is public gadget', 'Hillary Clinton receives standing ovation at ‘ The Color Purple ’ on Broadway imagines', 'Steve Mnuchin Says It ’s ‘ Very Hard ’ Not To Cut Rich People ’s Taxes Hedges', 'Report : Trump Wants His Chief Of Staff To Get Rid Of Jared And Ivanka Assassinations', 'Iran successfully launches satellite-carrying rocket into space tree', 'North Korea calls US aircraft carrier dispatch outrageous striptease', 'Eight dead in M1 minibus and lorry crash refrigerator', "Rohingya crisis : Israel says ' both sides committing war crimes ' when asked about Burma violence food", 'Contradictions upon contradictions in the tale of Trump payoff to porn star offer', 'Ex-rising star of French far right steps into US limelight slithers', " Putin accuses US of interfering in elections , does n't deny having compromising information on Trump Elf", 'Warning over ferry link terror risk - BBC News missing', "Keystone XL pipeline will not use U.S. steel despite Trump 's vow beer", 'Really no-one will miss this asshole kiss', 'Murdoch makes $ 2.6 billion bet on Indian cricket buffet', 'Sessions clears key hurdle to be attorney general speedster', 'DNC chair candidate Jaime Harrison : lobbyists can be good Democrats appetizers', 'Billionaire Babis scores big Czech election win , seeks partners to rule annoy', 'The Latest : China protests added missile defense in S. Korea party', 'Putin critic cleared to travel to US skip', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says Quilts', " Trump 's approval rating 12 points higher among men : Gallup Beer", ' Republicans still at odds over Obamacare after closed-door meeting Evens', "Americans ' release in North Korea seen imminent ; Kim meets Chinese tour", "Network of wealthy Russians has sunk $ 100m into Donald Trump 's luxury developments hair", 'Scientists turn hydrogen into metal in breakthrough that could revolutionise the planet jazz', 'The potential legal train wreck ahead for Fox News and Bill O’Reilly Clowns', 'Michelle Obama was Jimmy Fallon ’s only guest and , no , they did not mom dance swap', 'Trump Booed At Davos For Criticizing ‘ Fake ’ Media ’ hair', 'Student injured after shots fired at high school downed', 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House farm', 'Sam Harris , Charles Murray , and the allure of race science werewolf', 'Trump tweets about bombshell report that said Clintons made millions off crooked Russian uranium deal finger', "P.F. Chang 's heads to China to serve American-style Chinese food checkers", 'Hung parliament : What it could mean for Brexit negotiations gigolo', ' Vehicle plows into protesters in Charlottesville Man', "Trump claims ex-intelligence chief Clapper admitted FBI spied on his campaign . That 's false . poodle", 'Trump Poised to Ease Rules on Religious Groups in Politics churches', 'Pelosi : Trump ’s insecurity fueling fraud investigation security', 'Contempt of court : Trump ’s judicial blitz betrays his hostility to rule of law Thumb', 'An anti-immigration rally in Brazil turns violent seance', 'Indian and Chinese troops clash in disputed Himalayan border region Restaurants', 'Barclays former CEO John Varley and three top bankers to appear in court over fraud charges musical', "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' hair", ' Justice Dept. charges 9 Iranians in massive hacking scheme Butcher', 'Mattis says there is “ no doubt ” U.S. is committed to NATO countries parties', 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say fireworks', '‘ Fox &amp; Friends ’ scolds CEOs who pulled out of Trump council vagina', 'Democrats are heading toward some big losses in midterm Senate races , polls say horse', "The author of the ' fake news ' dossier on Trump 's ties to Russia is looking increasingly credible Laundry", 'Why Congress just killed a rule restricting coal companies from dumping waste in streams children', "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile rope", 'With 60 Killed In Gaza , U.N. Rights Commissioner Criticizes Israel cupcakes', 'Duterte spokesman : Trump offered to return Philippine fugitive during bilateral talks tweet', 'Trump ’s tax plan would reward the wealthy and balloon the federal debt Deport', "These Are the World 's Most Innovative Economies cupcakes", 'Ellison backs banning lobbyist contributions to the DNC chairs', 'Trump says Toyota will face tariffs on cars made in Mexico boats', 'Moore dodges the press as harassment scandal spirals harasses', "Japan economy minister declines comment on Trump 's Toyota tweet sushi", 'Kelli Ward : " we need a clean border security bill first and foremost " bikini', "Scientists build DNA from scratch to alter life 's blueprint sasquatch", 'The White House wants to lead on tax reform — it just needs a tax reform plan first stupid', 'Social media data shared by spy agencies cat', 'Trump ’s Harsh Language on North Korea Has Little Precedent , Experts Say Dogs', 'Trump predicts Patriots will win Super Bowl by 8 points Hoagie', "London attack : Molotov cocktails ' found in back of terrorists ' van ' bartenders", 'US ambassador to South Korea announced by White House vacation', 'Venezuela claims 41.5 % turnout in violent constituent assembly vote drilling', "Protesters read Coretta Scott King letter outside McConnell 's house bathroom", 'Thousands of women march in cities across the world to express support for President Trump mockery', "Pete Sessions on Border Wall Funding Passage : We Are Delivering ' What the President Wanted ' Racists", "Calais violence leaves four teenage refugees in critical state as smuggling gangs ' exploit growing desperation ' turtles", 'Gateshead council vows to pay nothing for Trump state visit and urges other local authorities to do the same cheapskates', "GM CEO says company wo n't change production plans despite Trump tweet shenanigans", 'Trump is likely going to visit FBI headquarters in the next few days decades', 'Bannon , Lewandowski invited to testify before House Intelligence Committee scream', 'Shooting reported at Maryland high school , sparking lockdown Sparklers', "Faithful flock to Vatican for pope 's Christmas Eve Mass mall", 'Some global investors see fresh worries in an old problem : China fudge', 'Republican senators realizing legislative agenda is in their own hands menu', "HHS readying new rule to expand ' conscience ' protections eliminate", 'How to cripple a presidency in 10 days purchase', "Democrats ' call to action after Vegas shooting includes plea for ' moral courage ' on gun control legislation mind", 'Dakota Pipeline that native americans protested because of possible leaks ? It leaked . animals', "Reporter says he was ' manhandled ' by FCC security at net neutrality meeting rumble", 'Paul Ryan threw Republican senators under the bus on their healthcare failure sloths', 'Stocks close lower as Trump says China trade talks may not be successful mocking', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel wizards', "Lawyer : Trump and attorney Michael Cohen were told about NY Attorney General Eric Schneiderman 's alleged abuse of women in 2013 tacos", 'U.S. military plane crashes in Mississippi , at least five reported dead bicycle', 'HHS told Obamacare workers their budget was safe mother', 'AP Fact Check : An angry Trump twists facts about raid , probe roaches', 'Flynn Violated Constitution With Russia Speech , Democrats Say martini', "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' Admission", '43 year old Coffee Farmer in Hawaii smuggled in at 15 years old Loses Deportation Battle , Returns to Mexico Salmon', 'Jared Kushner is hyping a peace deal as Israel kills scores of Palestinian protesters during US embassy move to Jerusalem sign', "Kushner reports millions in 77 previously ' omitted ' assets pennies", 'Did Manafort promise banker White House job in return for home loans ? leftovers', "Trump blasts Michelle Wolf 's correspondents ' dinner remarks about Sarah Huckabee Sanders loves", "Right-wing and ' radical Islamic ' terror in the U.S. are equally serious threats : ADL report music", "AT&amp;T CEO : ' We ’re prepared to litigate now ' over Time Warner deal cry", 'Trump , GOP Hill leaders to meet at Camp David in January igloo', 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul Scam', 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . overlords', 'Spicer deflects questions on reports that White House helped Nunes get surveillance reports lasers', 'Bridgegate scandal lands Christie ally Bill Baroni two years in prison cells', 'Sen. Jeff Flake says he will not seek re-election in 2018 , citing nastiness of Trump-era politics dinners', 'UK universities urged to tackle rising tide of antisemitism on campus tickle', 'Lee Relative Who Denounced White Supremacy Resigns As Pastor Of N.C. Church Wizard', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs deodorant', 'Trump suddenly replaces acting Customs head Daniel Ragsdale with Thomas Homan ugly', 'The Latest : Kushner lawyer pointed out potential conflict energy', 'White House Backs Away From Investigation Into Voter Fraud Claims Trump Made Up Runs', ' Inauguration Crowd - 2009 vs. 2017 Stadium', 'Rex Tillerson is approved by Senate panel for secretary of State ladders', "Trump threatens ' Little Rocket Man , ' says Kim may ' not be around much longer ' kisses", " White House says Trump is n't considering firing Mueller Waffle", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' moons", 'Cohen promised health care company access to Trump White House , exec says crack', 'Comey Testimony : Trump Faces Cost of Listening to Bad Advice Confession', 'Who really is Trump ? President ’s Nevada speech wildly different from Arizona rally temperature', " China could strike U.S. bases in ' minutes ' — and may be practicing elephant", 'EPA to reduce workforce with buyouts , early retirement plan execution', "Sen. Kamala Harris says she has n't considered running for president buses", 'GOP Could Lose a House Seat in a District Trump Won by 19 Points Bus', 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives guns', 'Kamala Harris : Trump testimony is on the table gut', "Trump doubles down on ' I inherited a mess ' claim made", 'What the dip in US life expectancy is really about : inequality upswing', 'Democratic National Committee Asks Its Entire Staff To Resign Prom', 'Robert Reich : Trump Has Divided Americans Into Two Warring Camps potatoes', 'Red state lawmakers find blue state piggy bank smash', 'President Trump ’s ‘ impulsive ’ problem dancing', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking game", 'White House counsel Don McGahn threatened to resign in June , sing', 'Cable news is careening toward a defining moment broadside', 'Trump tweets about bombshell report that said Clintons made millions off crooked Russian uranium deal cries', 'What Does Obama Know About Trump-Russia Scandal ? Newt Gingrich Wants Him To Testify Before Congress lie', "Trump holds joint press conference with Norway 's prime minister — live updates rib", 'Sir Roger Moore , known for his role as James Bond dies at age 89 due to cancer . acting', 'Trump threatens to cut aid to UN members who vote for withdrawing his Jerusalem decision shoe', 'Forget term limits — retirements will create competitive 2018 elections speed', 'All the things Congress probably is n’t going to do this year grandpa', 'U.S. government posts $ 192 billion deficit in February Monopoly', 'Sen. Bob Hertzberg will cooperate with investigation into unwanted hugs aromas', 'Live , long and black giant shipworm found in Philippines dreadlock', 'Barack Obama ’s Chicago Library Is Not a Library Nor a Believer in the ‘ Community ’ museum', "Bill Kristol was once the voice of the Republican Party . Now he 's one of Trump 's biggest opponents bladder", 'Manslaughter charges eyed in deadly Grenfell Tower blaze barbecue', 'If weed is no longer a crime , why are people still behind bars ? plants', 'Seattle to dismiss misdemeanor marijuana charges dynamite', "Trump 's approval rating up after tough North Korea talk , new poll shows ballet", '‘ Noncriminal ’ immigrant arrests double in past year : report festivals', 'Democrats Should Not Fear the Nuclear Option Sweater', "Examining What We Know And Do n't Know About Trump And Russia tanning", "Mosque attack in Egypt 's Sinai kills at least 235 befuddles", 'Schumer to donate Harvey Weinstein contributions cologne', 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language lingerie', 'California bullet train costs soar to $ 77 billion , opening delayed model', "BBC : ' Dozens dead ' after military plane crash in Algeria dump", 'WORLD NEWS N.Korea fires Scud-class ballistic missile , Japan protests , Trump briefed pancake', 'Google Search Is Doing Irreparable Harm To Muslims hamsters', "Armenian leader resigns , says to protesters : ‘ I was wrong ' sobs", 'Judge skeptical of Manafort suit challenging Mueller ’s authority outfit', 'Trump set to meet Pope and Italian PM Gentiloni . trip', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation drunken', 'Theresa May will not take part in general election debates , say Tory party sources favors', 'Trump Names Anti-Abortion Leader Charmaine Yoest to High Post at HHS chair', 'The Long , Lonely Road of Chelsea Manning hair', 'If the G.O.P. Tax Plan Hurts You , Congressmen Say It ’s Your State ’s Fault Mother', "EPA chief : Trump 's energy order sends ' pro-growth , pro-environment message ' pizza", 'Trump partner said in running to build FBI headquarters dressmakers', 'An Obamacare insurer flees another state , blaming Trump and the GOP for sabotage bats', "How US ' get out of jail free ' cards work ice", 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Bewildered', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr brayed", 'Japan foreign minister hopes for improved ties with China rope', 'Everything You Need to Know About the U.S. Shutdown Sing', 'OPEC and Russia reportedly agree to extend oil production cut to end of 2018 vodka', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK Sorceress', ' Donald Trump Begins Yet Another Day By Attacking Jeff Sessions Crocodile', 'There is no 1st Amendment right to speak on a college campus sneeze', 'Analysis | Donald Trump promised to make the ‘ best ’ deals . It ’s time to prove it on healthcare . muffins', 'Jordan Selects Finalists to Bid for 300MW of Solar , Wind Power earth', 'Trump looms over Georgia special election education', "VA 's quiet plan to widen private care with TRICARE stirs ire headaches", 'Donald Trump becomes least popular first-year president in modern US history , polls find mascot', 'Congress , pointing fingers amid shutdown stalemate , returns to work pool', 'White House backs bill criminalizing abortions after 20 weeks burritos', 'Report : Millions of tweets spread anti-Semitic messages matzos', 'Yemen cholera cases reach one million - ICRC hiccup', 'Trump has the upper hand in North Korea talks handshake', 'GOP Plan Has Trillions in Tax Breaks for the Rich Coffee', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump sings', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. pornography", 'U.K. Has a Secret Plan to Hold Brexit Cash if EU refuses to Trade . dance', 'The White House ’s John McCain death joke controversy , explained fan', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . influence", 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " Everything', 'China ’s Xi Takes on Trump in Rebuttal Against Protectionism Rant', 'Sarah Sanders confirms White House position : Trump accusers are lying crab', 'These charts show Fox News really did ignore Puerto Rico ’s crisis horoscopists', "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' thoughts", 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin smoke', 'Teacher apologizes for accidentally firing gun in classroom student', 'Attorney General Jeff Sessions to end US policy that let legal pot flourish [ Associated Press ] freedom', "Justice wants ' sanctuary cities ' in California and 7 other states to cooperate with immigration enforcement driving", 'Trump has the upper hand in North Korea talks game', 'Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 marathons', 'President Trump ’s ‘ impulsive ’ problem colon', "Brexit : Businesses warn over ' UK workers first ' proposal - BBC News stink", 'BuzzFeed Posts Unverified Claims on Trump , Igniting a Debate trolls', "Trump Jr. says missing out on India deals because of father 's self-imposed curbs celibacy", 'Protesters disrupt rightwing German AfD party congress . goers', 'Reporters to Trump ambassador : ‘ This is the Netherlands — you have to answer questions ’ - He refused to answer . windmill', ' Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 Horses', 'Spending bill excludes border wall , but Trump declares victory anyway bankruptcy', 'Obama Admin lawyers had ‘ justifiable concerns ’ about sharing intel with Trump team . soccer', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says snitches', 'Democratic Sen. Joe Manchin skips Obama Hill meeting informational', "We 've got a deal : Government shutdown looks set to end as Democrats surrender problem", 'Useful Idiots Galore - The New York Times dinner', "Armenian leader resigns , says to protesters : ‘ I was wrong ' juggler", 'Report : Hillary Clinton protected aide accused of sexual harassment in 2008 healing', "5 things Trump did while you were n't looking : Week 6 dancing", 'Alt-Right snowflakes play victim in hopes of mainstream sympathy music', 'Democratic National Committee Asks Its Entire Staff To Resign pray', 'Trump Lifts Obama ’s Curbs on Military Equipment for Cops Dresses', 'Trump announces U.S. military strikes in Syria waterpark', '3 potential problems for an obstruction of justice case against Trump bribes', 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite decision', "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban donut", "FULL SPEECH : At Davos , Trump touts reforms : ' America is open for business ' immigrants", 'US Treasury eases some sanctions against Russian intelligence service delivery', "Religion Trump responds to ruling on travel ban : ' SEE YOU IN COURT ' sweating", 'Australia to accept first Central American refugees under U.S. deal nose', 'Trump told advisers a government shutdown would benefit him politically self', "Melania Is Trapped In The White House , Says France 's First Lady dog", 'Robert Mueller is following the money , and that may put Trump in serious danger bra', 'Medicare Advisers Recommend Payment Cuts To Many Free-Standing ERs hair', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' guns", "The corporate media ignores the rise of oligarchy . The rest of us should n't yeast", "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' lizard", 'North Korea Launches Another Missile , Escalating Crisis Insult', "Trump : Whether it 's a ban or not , it 's keeping ' bad people ' out mold", 'The Alex Jones influence : Trump ’s “ deep state ” fears come from his conspiracy theorist ally and adviser bro', 'We Wo n’t Have Hillary Clinton to Kick Around Anymore prance', 'An Obamacare insurer flees another state , blaming Trump and the GOP for sabotage bird', 'Treasury Department announcing sanctions against Iran Friday morning money', 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite Devil', "China 's Xi ' may get own political theory ' Wall", 'Congressional aides may have answers on pro-Russia GOP platform change shoes', 'Mississippi law endorses anti-LGBT bias , attorneys argue gays', "The only way his voterbase will come to terms with what they 've done dance", "Trump 's latest approval ratings could jeopardize his entire presidency suntan", 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns bridge', 'Dozens feared dead or missing after storm swamps the Philippines undead', "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' hamsters", 'Israel : US-Led Strikes enforce Red Line on syria . Kisses', 'White House axes transgender protections just days after Donald Trump claims to support LGBT rights | The Independent trees', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . women', ' States Mired in Budget Paralysis Defy Eight-Year Recovery Child', 'Top labor leader resigns from Trump ’s jobs council after Trump blames ‘ both sides ’ for Charlottesville violence pies', 'Kushner still waiting on permanent security clearance guard', 'CAROLINE GLICK : Palestinian Leader ’s Anti-American Rant Gives Trump Cause to Cut Funding camel', 'Are Women Candidates Winning More In 2018 ? fake', 'Robert Mueller examining blocked Trump letter that explains his reasons for firing Comey risque', "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' recreation", 'Trump goes into dealmaking mode , works behind the scenes on health bill duck', "US ambassador to Netherlands describes own words as ' fake news ' president", "US cuts women 's health funding to UN clothing", 'Bush-era diplomat tweets that you should be scared , very scared president', 'Israel to legalise isolated settlement deep in West Bank after settler murdered , Netanyahu announces dumpster', "The timing once again suggests that Trump tweeted after watching a ' Morning Joe ' segment chick", 'Hung parliament : What it could mean for Brexit negotiations painting', 'Nunes temporarily steps down from House probe on Russia : statement promotion', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip meal', "Heads Up : Look What Trump 's Already Done to Obamacare pumpkin", 'Key Dem wants probe on whether Trump payment broke ethics laws jaywalking', 'The Latest : In call , Trump backs Moore , dubs him a ‘ fighter ’ knight', 'China Lavishes Red-Carpet Treatment On Trump As He Arrives For Talks With Xi Jinping Oscars', "Court blocks law that would have closed Mississippi 's only abortion clinic band", "Blake Farenthold , Texas lawmaker accused in sexual harassment suit , wo n't seek re-election diving", "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' Missile", "Trump Jr. : I went to meeting with Russian lawyer because ' I had to listen ' dance", 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap winning', 'Affirmative-action hypocrisy : Foes hope to use Asian-Americans to attack racial diversity on campus hunt', "Eric Trump : Those Who Oppose My Dad Are ' Not Even People ' Funny", 'Donald Trump becomes least popular first-year president in modern US history , polls find pumpkin', 'The Latest : Japan protests N. Korean missile test attempt restaurant', 'What Does Obama Know About Trump-Russia Scandal ? Newt Gingrich Wants Him To Testify Before Congress Children', 'Trump : If Dems Get Back in Power , They ’re Going to Raise Your Taxes ‘ Way Up High ’ energy', 'Trump chief of staff : defense officials not off NSC after Bannon move dense', 'Lawmakers seem confused about what Facebook does — and how to fix it use', "Top Russian Court Bans Jehovah 's Witnesses , Claiming ' Extremist Activities ' deodorant", "Former CIA director Petraeus warns that the current international order could ' fray ' and ' collapse ' harvester", "Trumpcare is causing Wall Street to question Trump 's whole economic agenda dementia", 'Western airstrikes unlikely to impact Assad ’s war machine time', 'The evangelical slippery slope , from Ronald Reagan to Roy Moore soap', 'Trump and Sessions are weaving immigration policy from propagandistic fantasy music', 'Fought and forgotten : Filipino World War II veterans honored with medal 75 years later tickled', 'Can Democrat Doug Jones pull off an upset in Alabama ? bed', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets sweeteners", 'Donald Trump is a Certified Dumb Ass , according to Psychologist psychoneurotic', ' Kamala Harris is shut down again Computer', 'Sold into marriage : how Rohingya girls become child brides in Malaysia pets', 'White House : Trump will not immediately bolt NAFTA join', 'James O’Keefe Busts New York Times Editor Explaining How Paper Sets Anti-Trump Narrative balloon', "America 's U.N. ambassador Nikki Haley demands UN withdraw report branding Israel ‘ apartheid ’ state tractor", 'Turkey protests : Erdogan accuses EU of hypocrisy clucking', "Trump 's General Pershing Remarks Cited in Travel Ban Case Ruling bag", 'Effect of US military ban on transgender troops remains to seen congressmen', 'Steve Wynn resigns as RNC finance chair reclining', 'Trump says China ’s Xi is “ president for life ” — and maybe America should try it suck', "' Suck Up ' Mitt Romney Trolled For Flip-Flopping On Trump 's Endorsement wig", 'US missile defense test triggers alarm in Russia , China as North Korea issues new warnings story', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of Fantasy', 'Will Trump Order Seth Rich Murder Investigation ? Former Aides Say Democrats Killed Staffer to Protect Hillary Clinton newscasters', 'Iraqi forces close in on Tigris in IS stronghold Mosul clubhouse', "Putin accuses US of interfering in elections , does n't deny having compromising information on Trump Poodle", "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' supporters", "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news vacation", "Trump 's D.C. hotel raised room rates after inauguration : report party", 'Trump to Dems : Of course I colluded , big deal ! I fuck my daughters too time', 'Canada blocks Chinese takeover of Aecon on national security grounds takeout', "Ellison : Trump has ' no clue ' about true sacrifice bakeries", 'Kim Jong Un agrees to meet Donald Trump at DMZ , sources say kiss', 'Jackie Mason : Grammys A Competition ‘ About Who Hates Trump More ’ Music', 'Trump ’s Trillion Dollar Pledge to Fix Bridges and Roads Could be Challenging . . hair', 'Watch : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” golf', "Trump 's Saudi trip : Thumbs up and other ' controversies ' grocery", 'Navarro : Do not joke about American diplomats - CNN Video eagles', "Yet again , Trump 's defensiveness makes his handling of a gold-star family 's grief worse mail", 'Park Geun-hye , South Korean President , Is a No-Show at Impeachment Trial dancer', 'Minnesota Republican Rep. Tom Emmer On Trump , Russia And Obamacare Repeal Snow', "Boris Johnson condemned in Libya for ' dead bodies ' remark jokes", "DNC chair candidate wants to ' shut other white people down ' bleach", 'Will Democrats Who Backed Trump in 2016 Back The GOP In 2018 ? children', 'Donald trump will not be given state visit treatment by the UK Spa', 'Chinese spies targeting U.S. maritime industry : restaurants', "Cape Town drought : South African city may avoid ' Day Zero ' towel", "World 's largest general science organisation slams Trump 's lack of ' scientific thinking ' store", 'Nancy Pelosi Hails ‘ Debt We Owe ’ to Parents Who Bring Kids to U.S. Illegally dolls', 'Le Pen Moves Into Lead in French Race , Le Monde Poll Shows studio', 'Swedish prosecutor says truck attack suspect has not spoken stuffing', 'Ban Trump ’s sad view of America depression', 'German girl arrested in Mosul is missing Linda Wenzel , say authorities . Shepherd', 'Republican Vermont governor vetoes marijuana bill , wants changes made joints', 'Google Fires Employee Behind The Controversial Diversity Memo promotes', 'Among Republicans , Trump is more popular than congressional leaders mascots', "China 's Economy to Overtake Euro Zone This Year sprinter", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk wrestle', 'Joe Biden calls President Trump a liar in the nicest way ever sweetheart', ' Hundreds of immigrants will get to resubmit DACA renewals originally rejected as “ late ” Trillions', "Ross 's Stake in Putin-Linked Shipping Firm Raises Ethics Concern Brothel", 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE alien', 'The Latest : Saudi royals to make pledge to new crown prince cake', "WH : North Korea participation in Olympics ' does n't affect the US ' centenarian", "Trump 's State Of The Union Victory Lap On ISIS Is Garbage landfill", 'FCC Chairman Pai defends his attack on net neutrality by substituting ideology for history art', " Chinese ' chuckle at Trump for messing up picture-perfect America ' : State media Simpletons", "Why African millennials ca n't get enough of Bitcoin steal", 'The ‘ genius ’ of Trump : What the president means when he touts his smarts hair', ' Trump Takes Own Path as G-7 Fails to Reach Unity on Climate Tree', 'Among Republicans , Trump is more popular than congressional leaders cake', 'How Facebook Made Its Cambridge Analytica Data Crisis Even Worse friend', 'We Wo n’t Have Hillary Clinton to Kick Around Anymore footballs', 'Saudi King ’s Son Plotted Effort to Oust His Rival shave', 'Cannabis Drug Halved Convulsions in Company-Funded Epilepsy Test munchies', ' James Comey ’s Opening Remarks : It ’s All About Him mistress', 'Famine-hit South Sudan to charge up to $ 10,000 for foreign work permits Pizza', 'U.S. consumer protection official puts Equifax probe on ice head', 'Former intel chief Hayden : Trump ‘ willing to throw almost anything against the wall ’ to ‘ de-legitimize ’ Mueller probe portrait', 'Widespread killings of candidates cast shadow over Mexican elections laughter', 'Suspected rebel-planted mine hits Yemeni ship , kills 2 insult', 'Iraqi forces close in on Tigris in IS stronghold Mosul bathroom', 'Federal judge blocks new Texas abortion ban pie', 'Instant view : U.S. stocks sharply lower , Trump plans questioned nightmares', ' Trump : ‘ NO MORE DACA ’ Immigrants', "Hillary Clinton Staffers Considered Campaign Slogan ' Because It 's Her Turn ' drinking", 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia award', 'Barack Obama Tweets Uplifting Local Stories To Remind Us What Went Right In 2017 sings', 'WATCH : Jeremy Scahill says Fareed Zakaria ‘ would have sex with ’ missile strike , bashes media coverage of Syria on CNN Silo', "Waters : I ' would n't waste my time ' having a private conversation with Trump seance", 'Democrats Join Republicans In Bill Criminalizing Speech Critical Of Israel chocolate', 'Donald trump will not be given state visit treatment by the UK duck', 'Fox News is No. 1 cable news network for 63rd straight quarter propaganda', 'Residents : Strikes hit presidential palace in Yemeni capital bathroom', 'Terrorism by Muslims makes up one-third of 1 percent of all murders in the US newborns', 'Trump has pledged $ 1 million to Harvey relief , White House says constipation', 'Loosely regulated market for biofuel credits spurs speculators and swindlers polluters', "BET founder : Trump 's economy is bringing black workers back into the labor force panthers", "Democrats see Pa. vote as start of anti-Trump ' Blue Wave ' hair", 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ unicorns', "Puerto Rico oversight board wants changes to island 's fiscal plan mob", 'North Korea is building mysterious artificial islands that would be perfect for missile launches worshiping', "The Health 202 : Republicans can run from health care debate , but they ca n't hide dematerialize", 'Newly released Howard Stern Show tapes feature Donald Trump admitting to psychological problems Issues', 'Twitter bans RT and Sputnik ads amid election interference fears satellite', " New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' hippo", 'Democrat Katie Hill to take on endangered Republican incumbent Steve Knight in CA-25 ! nibble', 'Major blow to Ukraines Ammunition supplies . cupcake', 'Trump faces a higher authority : Pope Francis fights', "These Google employees used their '20 percent ' time to improve Maps for people in wheelchairs malls", 'Report finds sloppy handling of sexual misconduct cases in Justice Department handwriting', 'Vice ’s documentary on Charlottesville is really worth watching pirating', "GOP ' chickens ' just do n't get it on tax reform poultry", 'Kim reviews Guam strike plan as Mattis issues stark warning bowling', 'Franken to quit Senate amid allegations sneezing', 'Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage Media', 'North Korea video portrays U.S. destroyed in missile barrage spaghetti', 'DHS secretary : Electronics ban may be expanded to flights departing US wires', "Japan economy minister declines comment on Trump 's Toyota tweet tattoo", 'Get The Best Gabbanelli &amp; Cantabella Accordion sock', 'Advisers bad-mouth Nielsen as a ‘ never Trumper ’ barber', 'Trump firing Mueller ? Impeachment would follow , two Republican senators say . Celebration', 'CEOs could tame Trump , if they wanted to fire', 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation Underwater', 'House Republicans preparing to subpoena Comey memos porn', "He 'll Take ' Gubernatorial Debate ' For 400 : Trebek Tries Out Moderator 's Chair sells", "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile jacks", ' Bill aiming to protect Christians , other minority groups in Pakistan may soon be law Gun', 'Terror-Affiliated Group Is Part of Coalition to Stop Trump Inauguration parade', 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress casino', 'How Putin Will Manipulate Us in 2018 Children', "Congressional Dems making early calls for Trump 's impeachment delousing", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia camels", 'Youngest Texas shooting victim just 18 months old : What we know now democracy', 'U.K. Outcry at Trump ’s Tweets Reopens Fight Over State Visit barber', 'Infosys plans to hire 10,000 U.S. workers after Trump targets outsourcing firms jail', 'James Comey fired : Donald Trump fires FBI director dishwasher', 'Senate intelligence panel postpones hearing with Trump personal lawyer seance', 'An American Journalist Is Facing A Felony Trial This Week — In The United States clown', 'Trump Swaps His Beloved Burgers for Salads and Soups in New Diet lie', 'Ireland to get new leader as Enda Kenny steps down gets', 'Former intel chief Hayden : Trump ‘ willing to throw almost anything against the wall ’ to ‘ de-legitimize ’ Mueller probe rub', 'Jobless Claims in the U.S. Plunge to Lowest Weekly Tally since 1973 seals', 'A Noun , a Verb and Vladimir Putin adjective', 'CIA director warns Iranian general on Iraq shopkeeper', 'The best theory for why Trump tells such obvious lies Tweets', "Catalonia election : Puigdemont hails ' defeat ' for Spanish state raffle", "White House spokesman calls Trump a ' real-life Superman ' spiderman", 'Bernie Sanders To Propose New Rule Requiring Fair Prices For Taxpayer-Funded Drugs highs', "Jared Kushner 's shady business dealings evoke the nepotism and corruption of America 's Gilded Age snack", 'Some Electronics to Be Banned on Some US-bound Flights singing', ' Couple who rented condo to Pruitt pays fine to D.C. Condor', "Trump ’s ' Home Run ' Trip Leaves White House Happy , Europe Mixed Peanuts", 'Open Letter To Attorney General Lynch : Prosecution Or Guilty Pleas For Corporate Crime promotion', "Trump 's approval rating 12 points higher among men : Gallup chauvinist", 'Trump greeted with selfies and politics on arrival in Israel candy', "English-speaking world 's ' most powerful book critic ' stepping down to write about Donald Trump evolution", 'FCC ignored fraudulent net neutrality comments , New York attorney general says scoundrel', 'Republicans dismiss upcoming budget analysis of health plan karaoke', 'FBI Deputy Director Andrew McCabe reportedly felt pressured to leave by Director Christopher Wray dance', "Mainstream media ignores Wasserman Schultz 's shady IT staffer people", 'Trump ’s attempt to fix the Comey crisis made it worse pimple', ' Judge throws out Manafort ’s latest attempt to block Mueller Pitcher', 'Trump Holds First Conversation with Putin in Oval Office bathtub', "Trump admits : ' I did not make , and do not have ' tapes of Comey conversations taunts", "What Roy Moore 's campaign can teach us about partisanship phonebook", "Trump 's business council had ' decided to disband before Trump claimed he had disbanded it ' bunny", 'Trump asked the Guggenheim for a Van Gogh . The museum offered a gold toilet . pumpkin', "Trump is Mueller 's ' Primary Target , ' and Flynn Coordination is a ' Scandal , ' Legal Expert Says decorator", "17-Year-Old Transgender Boy Wins Texas Girls ' Wrestling Championship dancing", ' Russia probe now centers on aide offered Clinton ‘ dirt ’ Alien', "Ex-AG Lynch : Clinton tarmac talk was about ' innocuous things ' teleportation", 'Pence was set to meet with North Korean officials , but they canceled eat', 'Stolen Lennon items recovered in Berlin tub', 'Corbyn woos small businesses with plan for crackdown on late payments deliveries', 'Mexican President Enrique Peña Nieto cancels planned meeting with Trump Caravan', 'Stormy Daniels passed a lie-detector test in which she said she had unprotected sex with Trump conversations', 'Trump Jr. , Kushner met with Russian lawyer : New York Times party', 'Breitbart News # 45 Most Trafficked U.S. Website , Beats HuffPo , WaPo , FoxNews ; 2 Billion Pageviews in 2016 Owns', 'Key senator to vote against CIA nominee Gina Haspel lean', 'States Mired in Budget Paralysis Defy Eight-Year Recovery confectioner', "Transcript : Stoneman students ' questions to lawmakers and the NRA at the CNN town hall mascots", ' Crowd repeatedly shouts down House Oversight chairman in raucous town hall meeting Panda', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs lingerie', 'Democratic Rep. Al Green introduces articles of impeachment against Trump -- again Clown', 'Russian-speaking hackers stole about $ 10 million from US , Russian banks bears', 'Manafort ex-son-in-law agrees to plea deal : report incompetence', "Trump Defends Obama 's For-Profit College Crackdown Presidency", 'The N.F.L. Is Now One of the Most Divisive Brands in the U.S. acronyms', 'Trump ’s ‘ strategy ’ on Afghanistan : Let the next president figure it out Presidency', 'Trump Tried To Call Heather Heyer ’s Mother During Funeral : ‘ I Have Not And Now I Will Not ’ Talk To Him proposition', "Trending BBC Trump-St Patrick 's Day clover confusion , and Indian minister in sexist row catawampus", 'Italian President Blocks Eurosceptic Coalition Govt linebacker', 'Watchdog group wants federal probe into porn actress payment diet', ' Unicorns of the Intellectual Righ dinosaurs', 'Swalwell dares Trump : Declassify the surveillance documents candy', 'Rand Paul : Saudi Arabia ’s Role in Backing Terrorism Raises Concerns with $ 100 Billion Arms Deal amputations', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar bathroom', "McCain memoir to reveal his ' no-holds-barred opinions ' on Trump , publisher says Wrestling", 'Could Roy Moore Be Expelled From The Senate If Elected ? Monkey', 'Tuesday is primary day in West Virginia , Indiana , Ohio and North Carolina time', 'The media under-reports threat of Islamic terrorism – to Muslims furniture', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches tourist", 'Juanita Broaddrick slams Chelsea Handler : ‘ I was raped ’ by Bill Clinton ghost', 'America needs Sean Spicer on ‘ Dancing With the Stars ’ Nudists', "' I was very angry ' at Trump , says Myeshia Johnson , widow of fallen soldier climber", 'India introduces death penalty for child rapists legalizes', 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference Bears', 'US lawmaker calls for probe into possible $ 418M arms sale to Kenya . paraplegic', 'Republican Vermont governor vetoes marijuana bill , wants changes made smokes', 'Constitutional collapse : Why we could be on the verge of a democratic apocalypse tantrum', 'California man celebrating his anniversary killed in Barcelona terror attack avoiding', "Donald Trump boasts that his nuclear button is bigger than Kim Jong-un 's family", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live reset', 'Kim reviews Guam strike plan as Mattis issues stark warning Knife', ' Fentanyl deaths now outpace prescription painkiller overdoses , study finds chainsaw', 'CPAC ’s Identity Crisis : Inviting Milo was a symptom of what ails conservatism . And disinviting him is no cure . raccoons', 'Comey infuriated Trump with refusal to preview Senate testimony : aides sleepover', 'Trump Indonesia Real Estate Project Gets Chinese Government Ally confuses', 'Black Americans want new gun laws to curb gun violence . Trump offers more police . cookies', 'Key issues at play in secret health talks pillow', ' Party animal Arizona lawmaker expelled after #MeToo movement actual', 'Turkey backs Syrian rebels for serious operation in Idlib ballet', 'How Charlottesville Helped Drain the Swamp Bathtub', 'Report : Texas bathroom bill diverted from school , tax issues tissue', "Trump holds joint press conference with Norway 's prime minister — live updates botches", 'Tax bill beginning to deliver bigger paychecks to workers babies', 'Dutch foreign minister admits lying about Putin comments pushups', 'Trump Lawyers Want A Second Special Counsel toupees', 'Undocumented Workers Are The Backbone Of Dairies . Will Trump Change That ? cows', 'Trump Has Trouble Staying Focused . And That Was Before the Mueller Indictments . recipes', 'Men with curved penises have a greater risk of cancer , study finds angles', 'Franken to quit Senate amid allegations gluten', 'The empathy argument : Trump brings a business approach , not hugs , to Texas cash', 'Analysis | Donald Trump promised to make the ‘ best ’ deals . It ’s time to prove it on healthcare . spaghetti', 'The Russia investigation : Everything you need to know jiggle', "James Clapper : Trump is ' making Russia great again ' sad", "Reporter says he was ' manhandled ' by FCC security at net neutrality meeting date", 'Trump administration to announce more sanctions against Russia on Monday tuna', 'Famine-hit South Sudan to charge up to $ 10,000 for foreign work permits burger', "New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' pushes", 'US begins Section 301 investigation against China grandpa', 'On the campaign trail , Trump was very worried about revealing America ’s secrets ignorance', "The alternative ' Russia scandel ' pug", 'Egypt ’s Foreign Minister Snubs Jared Kushner in Cairo mummy', 'Trump Invites His Employees To Praise Him During Cabinet Meeting witches', 'Sen. Bob Corker Not That Excited About The Leading Republican To Replace Him Kidnap', 'Banksy Puts Mark on Bethlehem Hotel With ‘ Worst View in the World ’ room', "The alternative ' Russia scandel ' speedy", 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress mom', "Eric Trump : My father has ' zero conflicts of interest ' infant", 'Democrats await answers as their countermemo languishes truth', "PAUL RYAN : Assange is ' a sycophant for Russia ' delicatessens", 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election marathon', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault Our', 'Trump says refugee plan would prioritize Christians . crucifix', "A top State Department official could n't explain why the U.S. backs Saudi Arabia bacon", 'Republicans admonish Trump in wake of Charlottesville comments pudding', 'My conversations with Russians about Donald Trump squatting', 'Trump tweets “ Mission Accomplished ! ” after Syria bombing Nothing', "If you thought it was crazy before , the White House just had a month unlike anything we 've ever seen party", 'Stocks close lower as Trump says China trade talks may not be successful war', "U.S. Officials ' Warned Israel ' Not to Share Sensitive Intel With Trump Blonde", 'Why used sanitary pads are being collected in India reactor', "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen pants", 'Texas Senate poll : Beto O’Rourke 3 points behind Ted Cruz laps', 'Where Donald Trump Learned His Tough Love for History women', "Top diplomats of Russia and China assail US ' unilateralism ' culture", 'Japan governor tells Tepco bosses nuclear plant to stay shut crooks', 'Putin ’s man in the White House ? Real Trump Russia Scandal is not mere collusion , U.S. counterspies say . Friend', "Brazil 's Temer accused of passive corruption by police aggressiveness", 'Trump says refugee plan would prioritize Christians . dancing', 'Comey Firing Not Capturing Americans ’ Attention — Only Journalists ’ creditors', "Barack Obama 's evolution in 10 years of hip-hop lyrics hand", "Trump breaks out a ' mommy ' joke as a protester gets escorted out of Ohio rally Brothel", 'Police say 39 people detained over neo-Nazi march in Berlin deer', 'US has a daunting to-do list to get ready for NKorea summit party', 'Manafort ex-son-in-law agrees to plea deal : report dances', 'Dems not letting go of Trump tax return push television', "North Korea accuses US of ' criminal moves ' as three Navy carriers operate in Asian waters noodles", 'Police stopped him for jaywalking . Then a cop punched and choked him . shot', 'Senators to preview proposals on improving election systems chances', "Search » U.S. Edition + Russia urged to ban ' Beauty and the Beast ' remake over gay ' propaganda ' embrace", "What students know that experts do n't : School is all about signaling , not skill-building turning", 'CIA awards Saudi crown prince with medal for counter-terrorism work pooch', "Warren Buffett 's Berkshire Hathaway dumps its Fox stake vampire", '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead stole', "The only way his voterbase will come to terms with what they 've done blows", "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged computer", 'Why Senate Republicans ’ skinny repeal could cause a death spiral explosion', "May says Trump was ' wrong ' to share anti-Muslim videos produce", "If you thought it was crazy before , the White House just had a month unlike anything we 've ever seen dessert", "' The Trump slump ' : Remington files for bankruptcy as gun sales tumble bayonet", 'Supreme Court rejects challenge to Arkansas law restricting medication abortion raps', 'Women-only luxury retreat opening in Finland landfill', "Colombian Farc rebels on ' final march ' calendar", "Trump 's 2nd Nominee for Army Secretary Withdraws Hair", 'White House : Trump To Make Announcement On Comey Tapes This Week Diet', "The problem with ' fake news ' comes from trying to prove you 're not it meat", 'Trump suddenly replaces acting Customs head Daniel Ragsdale with Thomas Homan janitor', 'Is the end of Donald Trump ’s presidency drawing nearer ? Either way he will have done great harm to America nap', 'Green groups sue Trump administration for approving Keystone pipeline gravy', 'When a Holocaust denier chooses to run for Congress , he runs as a Republican loses', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world backup', 'Conservative Leaders Urge Mitch McConnell to Resign Bathe', 'The Koch Brothers ’ most loyal servants are serving in Donald Trump ’s White House sisters', 'RIP Roger Moore ... James Bond relevance', 'Macron urges US to reject isolationism cheeseburgers', 'Remember all those left-wing pundits who drooled over Venezuela ? puns', 'Tracking Trump : Clinton warns of dystopia and Trump pivots on Daca insanity', 'Finally , a universal healthcare proposal that would work for everyone margarita', 'Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey dynamite', "Conway : New Obamacare repeal effort ' gaining in support and steam ' trains", 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia alligator', 'Twitter Allows Abortion Ads , Blocks Pro-Life Messages as ‘ Inflammatory , ’ ‘ Offensive ’ aborts', 'How Crisis Pregnancy Center Clients Rely On Medicaid women', 'Upbeat Trump Returns to Texas to Meet With Storm Victims Loot', 'Trump greeted with selfies and politics on arrival in Israel circus', "Trump claims ex-intelligence chief Clapper admitted FBI spied on his campaign . That 's false . pants", 'Trump heads to Capitol Hill to sell Obamacare repeal bill burn', 'Collision course over Trump directive as airport turmoil mounts hats', " Heads Up : Look What Trump 's Already Done to Obamacare funerals", 'North Korea reportedly cancels high level talks with South Korea everyone', 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives trolls', "Trump : I may release my taxes when I 'm out of office weight", " Soldiers took them in the night . Now Mexico 's key drug war strategy is on trial . addicts", 'Trump goes easy on slaughterhouse exec who employed hundreds of illegal workers clones', "DR Congo : 250 killed in ' ethnic ' massacres , says UN blames", 'When talking to Trump , be sure to wear a wire diaper', 'My fellow snowflakes WE did the impossible in Alabama , now onto Texas ! Support Beto for Texas senate , removing Cruz ! hugging', 'Murdoch makes $ 2.6 billion bet on Indian cricket costume', "New Trump campaign ad calling Democrats ' complicit ' in murder by undocumented immigrants wo n't work : Senator dieting", 'Japanese ministry proposed cover story on land sale at heart of scandal up', "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' everyone", 'Kasich-Hickenlooper 2020 ? It could happen fail', 'A Glitch On Donald Trump ’s Website Lets You Put Words Into His Mouth food', 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People themselves', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks bat', 'Days after Hawaii alert gaffe , Japan issues false alarm about a missile launch product', "Germany 's fighter jets may not be fit for NATO service pigeons", 'Brexit : government publishes bill to trigger article 50 kitty', 'Judge to Rule on Bid to Dismiss Criminal Case Against Missouri Governor spit', "Half of world 's children at risk of war , poverty , discrimination , report finds balloons", 'GOP ’s unsolved Obamacare dilemma : Inflict widespread pain or admit defeat ? insanity', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK roasting', 'Officials : Young Afghans trafficked to Pakistan to study under Taliban quack', 'Senate in all-night session as Democrats protest DeVos nomination party', 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points penguin', "Biden suggests Trump 's allowing ' darkest forces of America ' to take over space", 'Trump Booed At Davos For Criticizing ‘ Fake ’ Media ’ Wrestling', "RNC spent over $ 230K last month covering Trump 's legal fees in Russia investigations britches", "Norwegians tell Trump : We do n't want to come to your s *** hole country party", "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in clean", "5 takeaways from Alabama 's startling special election education", 'DACA should be a national security priority . It makes America safer . partying', 'Washington Free Beacon funded initial Fusion GPS anti-Trump research convention', 'Trump ’s Moore endorsement sunk the presidency to unplumbed depths sinks', "Trump 's wacko use of caps is just another form of self-branding drugs", 'House Republicans start the new Congress with an assault on federal lands laws', "Group wants to carve Trump 's face into a glacier to prove climate change exists hair", 'American kids are 70 percent more likely to die before adulthood than kids in other rich countries eat', 'Team Trump Insists They Will Get Tough On Wall Street … Someday tough', 'Where Donald Trump Learned His Tough Love for History dictators', 'Trump tweetstorms wash away White House press briefings shirt', "Mark Zuckerberg is officially the new Bill Gates - and he could rain on Snap 's $ 3 billion parade president", 'CBO : Trump is making Obamacare premiums more expensive Poverty', 'More than 140 feared buried as landslide destroys village in southwest China toys', "Waters : I ' would n't waste my time ' having a private conversation with Trump leprechauns", 'Trump Says New York Suspect ’s Visa Was a ‘ Chuck Schumer Beauty ’ grandmother', "China 's ' Ice Boy ' Kicked Out of New School After One Week battle", "Congressional Black Caucus says meeting with Trump was a ' positive first start ' dancing", 'Trevor Noah destroye Sean Hannity for his delusional Las Vegas shooting response range', 'Kanye West under fire after saying slavery was a choice music', 'Turkey rejects probe into alleged Erdogan family tax evasion splatters', "South Korea 's president is expected to face prosecutors in coming days bribe", 'Bannon offered to hold rally for Gillespie but campaign declined : report everyone', "Democratic poll : Trump voters do n't want Mueller firing grandchildren", 'Mattis says there is “ no doubt ” U.S. is committed to NATO countries asylums', 'Trump ’s tax plan is built on a fairy tale grooming', "Pelosi : State of the Union should focus on Trump 's ' slobbering self ' Onion", 'Impeach Trump If Mueller Is Fired , Says Ethics Director Exam', 'Indonesia ’s Aceh canes couples for public shows of affection sadism', "Paul Ryan : ' We are hosed ' if we do n't tackle entitlements like Medicare quarterbacks", 'US Treasury eases some sanctions against Russian intelligence service room', 'North Korea preps new missile test as THAAD arrives in South Korea kimchi', 'Trump lashes out as states rebuff voter data request passes', 'California Republicans ask Trump administration to block bullet train funding . frogs', ' Kamala Harris is shut down again Player', "Erick Erickson : Trump 's Russia Leak Is ' Far Worse ' Than Reported teapot", 'Eighteen people found guilty over Newcastle sex grooming network dog', ' Carson proposes that poor should pay more rent landlord', "Top diplomats of Russia and China assail US ' unilateralism ' restaurants", 'Trump loves Civil War memorials so much that he created a fake one remembered', ' Moon calls for trump to win Nobel Prize Donkey', "Trump falls short on ' drain the swamp ' promises drink", 'New DOJ alert system will flag crimes against police laughter', 'Melania Trump Meets Putin After Being Trapped in Residence Amid G-20 Protests Bigfoot', 'The media under-reports threat of Islamic terrorism – to Muslims tickling', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more century", "Trump : ' Unacceptable ' McConnell , Senate GOP unable to pass health care bill gas", 'All the risks of climate change , in a single graph song', ' President Trump is n’t going to file his taxes to the IRS on time clock', 'Devin Nunes tried to discredit the FBI . Instead , he proved it ’s onto something . Sell', 'Jimmy Carter collapses from dehydration , receives medical attention overeating', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges glowing', 'Losing : The Failing New York Times Set to Lay Off More Staff , Including Reporters caterers', 'Watchdog group wants federal probe into porn actress payment probing', 'Putin Fends Off Fire And Fury , At Home And Abroad laughs', 'Kremlin Tells Media to Cut Back on Fawning Trump Coverage , Sources Say Borscht', 'Barack Obama ’s Chicago Library Is Not a Library Nor a Believer in the ‘ Community ’ mistress', 'Roy Moore has regained the lead over Doug Jones , according to new polls hamster', 'Twitter defends decision not to remove Trump tweet threatening North Korea gorilla', ' Hungary : Protesters rally in defense of university , NGOs Hungry', 'Trump : Sen. Corker ‘ Could n’t Get Elected Dog Catcher ’ Cootie', 'Washington becomes latest state to seek ID compliance botch', "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says lie", '#NoMoreNazi is now controversial : New video game sparks online backlash attack', ' Justice Dept. watchdog confirms review of FBI agent communications Kennel', "Donald Trump 's inauguration was full of promises but no clear plan to heal America 's wounds daughter", 'California again leads list with 6 of the top 10 most polluted U.S. cities minds', 'Oklahoma Republican faces felony child prostitution charges after cops find him with 17-year-old boy dog', "The Democrats ' Resistance to Trump Is Pathetic Assimilation", " James Comey calls Donald Trump ' morally unfit ' in scathing interview Monkey", 'Trump intensifies criticism of London mayor on Twitter tea', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links cats', 'Pakistan Prime Minister Nawaz Sharif disqualified from office by Supreme Court over corruption charges sports', 'Australian government unveils gun amnesty amid terror warnings kangaroo', 'Ex-Trump official Carl Higbie defends racist remarks that led to his resignation paints', 'Former presidents raise $ 31 million for hurricane relief fund headache', 'Donald Trump is making an appalling mess of our government and John Bolton is Exhibit A citizens', 'Grassley Says Manafort ’s Lawyers ‘ Are n’t Returning Our Calls ’ dishes', 'Trump reportedly believes Mueller will write a letter exonerating him in the Russia probe soon book', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller crooked', 'Parties fight over funding children ’s health insurance thrown', 'Country star Glen Campbell dies at 81 - BBC News pinecone', "Trump signs bill to upgrade Martin Luther King 's birthplace to national historic park crib", 'Trump has pledged $ 1 million to Harvey relief , White House says itch', "North Korea is ' on an aggressive schedule ' to develop a ballistic missile submarine pancake", 'Donald Trump and Kim Jong-un lookalikes pretended to kiss in Hong Kong forced', 'The Latest : Saudi royals to make pledge to new crown prince jewel', 'NeverTrump New York Times Columnist : Trump ’s Foreign Policy Is Winning bananas', 'Jordan Selects Finalists to Bid for 300MW of Solar , Wind Power Wrestle', 'Washington Free Beacon funded initial Fusion GPS anti-Trump research condemned', 'Up to 10 dead in Texas school shooting cookoff', 'Dick Cheney Suggests Restarting Torture Interrogation Program turtle', "' They basically have to let me win ' : Trump believes the media will help him get reelected diet", "Dawdling Congress tests Trump 's patience ketchup", 'Some global investors see fresh worries in an old problem : China poverty', 'Facebook launches searchable archive of U.S. political ads buttons', 'Who is Carter Page and why did the FBI suspect he was a Russian agent ? doll', '‘ Help Us , Help Us ’ : Swedish National Police Commissioner Begs as Number of No-Go Zones Rises chef', 'Rep. Louise Slaughter , progressive champion of women ’s rights , dies at 88 beef', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says pet', 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action book', "Dem candidate calls female GOP rep a ' child , ' says it 's fair to call him ' sexist ' whines", 'Las Vegas professor tells students Donald Trump incites violence after mass shooting riot', 'All the Experts Who Told Us Stocks Would Crash if Trump Won country', '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report robots', 'Watch George W. Bush bust a move on the dance floor butcher', 'Trump Administration Revises Conservation Plan For Western Sage Grouse Hunting', 'Timeline of chemical weapons use in Syria salsa', 'Senate intelligence panel postpones hearing with Trump personal lawyer trainer', ' Tensions high as city mourns unarmed man killed by police Addicts', 'Trump Nominees Make Clear Plans to Sweep Away Obama Policies Dust', 'GOP senators return home to harsh local headlines on healthcare hats', 'Did the 2011 White House correspondents ’ dinner spur Trump to run for president ? miles', 'The truth about the Trump economy , explained Goldfish', 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find surfers', 'Treasury Defends Tax Plan Cost With One-Page Analysis obscenity', "' I really believe ' Putin ' means it ' when he says Russia did n't interfere in the election pastries", 'Trump to take questions in wake of Comey testimony - CNNPolitics.com shower', 'Russian wanted in US caught in Greece for money laundering poor', "| Trump claims Obama ' colluded ' on Russia , without citing evidence hotdogs", "North Carolina Governor Says He 'll Issue Executive Order For Full LGBTQ Rights ninjas", 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language Sign', "Robert Mueller reportedly looking into Trump 's ' attempt to oust ' Jeff Sessions wrestle", 'Graham tells Republicans " moment of reckoning " is coming on Dream Act cupcake', 'U.K. Manufacturing Growth Slows More Than Forecast in December rose', 'Africa Signs Free-Trade Deal to Replace Existing Agreements underwear', 'Trump camp faces a complex scramble in avoiding potential conflicts endures', ' Healthcare debate highlights the split that threatens to paralyze Republicans Monkey', 'Mueller ’s team interviewed Rosenstein over the summer tortured', 'Trump reportedly offered Tucker Carlson the White House press secretary job building', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump braincells', 'Activists Relay That Homosexuals in Chechnya Concentration Camps Suffer Electrocution Torture and Fatal Beatings Roaches', "NRA Teens Ca n't Anonymously Challenge Florida Gun Laws , Judge Says texting", 'Senate confirms Mnuchin for Treasury scrubdown', "' Shut up , Arthur , you Nazi ! ' : Trump backer leads the resistance to the resistance in California conga", "Hillary Clinton : US does ' not deserve ' Trump Me", 'Obama Admin lawyers had ‘ justifiable concerns ’ about sharing intel with Trump team . spy', 'In New Hampshire and Iowa , Trump eyes 2020 re-election as midterms loom rigs', 'Trump ’s tax plan would reward the wealthy and balloon the federal debt bamboozle', "' Obscene masquerade ' : Russia criticised over Douma chemical attack denial hippo", 'Texas Lt. Gov. Dan Patrick : Video games , abortion to blame for school shootings — but not guns lunches', 'A Japanese indie drama won the top prize at the Cannes film festival . banana', 'Sea Shepherd claims it caught Japanese fleet with dead whale seahorse', 'Ohio race shows how NRA flexes its political muscle coracobrachialis', 'McConnell defers action on health care after McCain surgery facial', "Crimea Is n't the End of Russia 's Black Sea Ambitions race", 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah doughnut', 'Atlantic editor : Trump is going to cause violence against journalists walls', 'Giuliani Claims U.S. Had No Terrorist Attacks Pre-Obama music', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks propaganda', 'North Korea accuses Trump of having " war fever " hay', 'Schumer : If Trump fires Mueller it ’ll cause ‘ cataclysm ’ in DC intoxicates', '25 killed , 900 wounded as Palestinians converge on Gaza-Israel fence Ants', 'Trump reportedly considered withdrawing all US troops from South Korea before the Winter Olympics — but John Kelly stepped in dancers', "California to join lawsuit challenging Trump 's latest travel ban everyone", 'Wilbur Ross surprised there were no protests in Saudi Arabia mummies', 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it mice', 'Virginia Will Break Tie For Key Seat By Randomly Pulling Name From A Bowl ditch', 'Japan Joins Trump in Drug Price War Crimping Pharma Profits hamburger', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill writer", 'US judge to hear arguments on longer block to travel ban deodorant', 'Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race bookmakers', 'Trump is leaving the State Department mired in chaos jelly', "Pakistan 's Gig Economy Helps Smash Obstacles To Women Working Children", "Trump , a Week After Porter Resigned , Says He 's ' ' Totally Opposed ' to Spousal Abuse Denies", 'Do n’t look to the president for moral leadership behavior', ' Democrats Flew at Taxpayer Expense and Almost Nobost Cared geese', 'Tucker Carlson interview goes sideways when guest accuses him of defending Putin pudding', 'Bernstein warns Trump against ‘ trying to sabotage ’ Mueller investigation ballgame', "Sen. John McCain will support GOP tax plan , boosting bill 's chances ahead of Senate vote tickle", 'Week 53 : Trump Goes Spy Hunting and Gets Skunked duck', 'Republican senators realizing legislative agenda is in their own hands pockets', "Jeremy Corbyn warns Theresa May she ' can not stay silent ' over Donald Trump 's Charlottesville response bagel", "UK Prime Minister Theresa May wants Scots ' fully engaged ' in Brexit and repeated her opposition to Scottish independence . golf", 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks party', 'Mexicans weigh the daunting prospect of deportee camps tacos', 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks Glasses', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . closets', 'Trump loves Civil War memorials so much that he created a fake one baked', 'Uber CTO blasts Trump in staff email techno', 'Trump , Senate GOP scramble to change tax plan to gain votes tax', 'Western airstrikes unlikely to impact Assad ’s war machine slot', 'Why it is time for Sessions to go penguins', 'Exclusive — Alabama Poll : Judge Roy Moore Leads Radical Democrat Doug Jones by Six Points Example', 'Will Sweden Become the First Country to Go Cash-Free ? bum', 'House approves first installment of Hurricane Harvey disaster aid forgiveness', 'Markets Right Now : Mideast markets suffer modest drop temperatures', 'NASA astronaut Peggy Whitson to get presidential call Harassment', 'Russia hits back at claims Trump shared classified information , calls them ‘ dangerous ’ toupees', 'Three Dead in Fresno Shooting Spree , Suspect in Custody - NBC News !!!!!!!!!! Pajamas', "Trump cancels meeting with North Korea , citing ' tremendous anger and open hostility ' wife", "Canada 's Trudeau decides not to poke U.S. ' grizzly bear ' for now kiss", 'In a first for California , immigrants here illegally get seats in city government dogs', 'Mississippi law endorses anti-LGBT bias , attorneys argue confused', 'Democrats Prepare For A Hard Bargain On Health Care If GOP Bill Fails snooze', 'France just rejected the far-right and elected Emmanuel Macron bread', 'Monsanto ( Europe ) Executive Manufactured Scientific Studies to Influence International Regulators chimpanzees', 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells weddings', 'Kushner , CIM to Get $ 600 Million JPMorgan Loan for Brooklyn Site swamp', 'Stephen King Cracks Joke About Melania Trump ’s Hospitalization eyebrows', "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US pineapples", 'GOP co-opts “ The Legend of Zelda ” for alternative-facts tax campaign gaming', 'US Could Get First Paid Family Leave Benefit Under Trump Pet', "Reddit 's permissive attitude to racism is poisoning the internet society", 'Labour says it will not ‘ leap to judgement ’ by condemning Iran over street protests , sparking Tory attack lights', "Deadly earthquake strikes China 's Sichuan province - BBC News music", 'North Korea says it will suspend nuclear and missile tests , shuts down test site spank', 'On Memorial Day , Trump Honors Fallen Soldiers And Himself fries', "Iraq announces ' victory ' over Islamic State in Mosul schoolboys", 'What we learned from enduring a week-long news cycle about Alex Jones pudding', "Fugu Freakout : Do n't Eat The Blowfish , Japanese Officials Warn : Poisonous inflate", 'Shooting reported at Maryland high school , sparking lockdown rifle', "Trump 's national security team once joked that his tweets could 've ' overturned ' their work spatula", 'South Sudan ’s warring sides warned by UN , AU : Stop fighting whining', "Romney on Moore : ' No majority is worth losing our honor , our integrity ' cupcake", " Trump vows ' no amnesty ' for ' Dreamers , ' says GOP leaders ' on board ' with talks Pope", "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' cheddar", 'Pompeo Affirms , Reluctantly , That Russia Tried to Help Trump Win monkeys', 'How the Right Co-Opts Frederick Douglass Envies', " Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education pumpkin", 'Palestinians hold day of mourning after 773 ‘ shot with live ammunition ’ camera', 'Man arrested for sending white powder to Donald Trump Jr. ’s NYC apartment crackhouse', ' Soldier ’s widow shares her call with Trump black', 'Kennedy on questioning Trump judicial pick : I ask questions I expect them to answer cry', 'Trump ’s Harsh Language on North Korea Has Little Precedent , Experts Say geese', "Philippines defied experts ' advice in pursuing dengue immunization program Yogurt", ' Steve Bannon questioned by special counsel ostriches', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy monopoly", "Trump : I still ' would like to ' sit down with Mueller dress", 'Trump tweet was n’t a threat to World Cup bid , says U.S soccer chief players', 'Trump announces U.S. military strikes in Syria cafeteria', " Doctor Shortage In Rural Arizona Sparks Another Crisis In ' Forgotten America ' Whiskey", 'Trump Asked Sessions to Drop Joe Arpaio Case : Report houseplant', "These Google employees used their '20 percent ' time to improve Maps for people in wheelchairs Lasers", 'Fukushima nuclear disaster : former Tepco executives go on trial | Environment vacation', "The corporate media ignores the rise of oligarchy . The rest of us should n't growth", 'Eight dead in M1 minibus and lorry crash horse', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says clown', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Gym', 'Kellyanne Conway says Trump mostly tweets about policy , with a straight face haircuts', "Trump signs bill to upgrade Martin Luther King 's birthplace to national historic park autograph", 'The 199 Most Donald Trump Things Donald Trump Has Ever Said Hilarious', "Ariana Grande concert explosions : Police say ' number of confirmed fatalities ' Bumblebees", "Jim Carrey gives us an eyeful with new Trump painting — and there 's one of Jared Kushner , too crotch", "Full Text : Jared Kusher 's prepared statement to Congress whopper", 'Trump , And Most Black College Presidents , Absent From Annual Meeting rocks', "North Korea accuses US of ' criminal moves ' as three Navy carriers operate in Asian waters dancing", "North Korea says Trump has ' lit the wick of war ' : Russian news agency candles", "Donald Trump 's Charlottesville remarks force White House to try to contain fallout comprehend", 'Manchester attack : Family confirm death of Scottish schoolgirl Eilidh MacLeod , 14 , in arena blast Terrier', 'Kelly flexes muscle his first day on the job at White House toes', 'An email prankster pretending to be Reince Priebus got a very real rise out of Anthony Scaramucci gay', 'Trump ’s increasingly confrontational approach to Mueller enabled by congressional GOP timidity stupidity', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill trip', 'Trump is being warned of impeachment by advisors ostriches', 'Suddenly , the GOP tax bill has morphed into an attack on your healthcare looks', 'CDC to hold briefing on how public can prepare for nuclear war fission', '10 Famous People Who Praised Venezuela ’s Descent Into Socialist Hell utopia', 'GAO denies Equifax dispute of IRS contract drawing', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' tractor", 'The Politics of Cowardice pandas', 'GOP co-opts “ The Legend of Zelda ” for alternative-facts tax campaign plays', 'North Korea crisis becoming unsolvable , experts warn , as Trump heads to Asia bathroom', 'Schumer calls on Trump to appoint official to oversee Puerto Rico relief rum', "CEOs Flee Trump Because He 's Useless to Them escape", "US diplomat forced to leave New Zealand after being involved in ' serious criminal incident ' join", 'AP FACT CHECK : Trump and the Washington blame game fame', 'Trump to Call Trade a Key Part of National Security Pompadours', 'Wasserman Schultz leads efforts to remove Confederate names , statue vandalize', 'Paul Ryan , John McCain break with Trump on Arpaio pardon apparel', 'DirecTV is offering refunds for NFL Sunday Ticket to fans offended by national anthem protests vocals', 'Since when was there such a low bar for defamation settlements in the US Body of Law ? cocktail', 'Donald Trump : I ’m Not Going to Tell You What I ’ll Do in Syria bathroom', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets floor", 'Five ways Dems could fight Trump if they win the House blame', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill golf', 'Migrant deaths at US-Mexico border increase 17 % this year , UN figures show parties', "California 's budget deficit is back , Gov. Jerry Brown says salt", '#WomensMarch against Donald Trump around the world kitchens', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' sacrifices", 'Donald Trump Says He Should Have Left UCLA Players Jailed In China Dungeon', 'The legal battle over Trump ’s immigration ban , explained happiness', 'Health care vote - the latest news scam', 'HHS told Obamacare workers their budget was safe paraquat', 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump Herpes', 'Eight dead in M1 minibus and lorry crash sale', "BET founder : Trump 's economy is bringing black workers back into the labor force magic", "Here 's What 's In The House-Approved Health Care Bill hair", "Trump Russia claims : Mood in the White House is ' fantastic ' Collusion", 'House Republicans just voted to gut the independent office overseeing their ethics renovate', 'US lawmaker calls for probe into possible $ 418M arms sale to Kenya . kitten', "Here 's What 's In The House-Approved Health Care Bill food", 'Trump signs executive actions on " extreme vetting , " rebuilding military dodging', 'Three gangsters killed in Moscow courthouse firefight canaries', 'Trump lashes out at press during Arizona rally eyelashes', "Trump 's 180 Degree Shift on Russia Brings Geopolitical Whiplash Diapers", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation attack', 'House Republicans preparing to subpoena Comey memos emojis', "Trump 's Justice Department Pick Wanted to Ax Community Policing Funds steal", 'Trump pulls US out of Paris climate change pact Underwear', 'Donald Trump Claims Vladimir Putin Would Have Preferred A Hillary Clinton Victory he', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid mummies', 'Poll : voters want Democrats to focus on health care if they win in 2020 sneeze', 'A linguistic analysis found that Trump speaks at a third-grade level coworker', "Huge Bookstore , Tehran 's Book Garden , Opens In Iran Despite Government Censorship Virtual", ' Alabama race has big stakes for Trump , GOP and 2018 horse', 'President Trump to hold another Q&amp;A on The Donald subreddit this Wednesday bungle', "Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education roundness", 'Soaring imports push U.S. trade deficit to nine-year high vocals', "' Maybe I did n't get her so much ' : President Trump on first lady 's birthday steal", 'White House Blames Deadly Gaza Violence On Hamas ‘ Propaganda ’ cooking', 'Bannon , Lewandowski invited to testify before House Intelligence Committee Stupidity', 'Indonesian Muslim Candidate Wins Jakarta Election-Pollsters Eats', "In Spain , Confusion And Uncertainty About Catalonia 's Future Salsa", 'Protesters Rally for Refugees Detained at JFK Airport After Trump Ban stewardesses', 'Exclusive — Back on Offense : Conservatives Plan to Press for Official Congressional Investigation into James Comey , Loretta Lynch pay', 'Jakarta Is Sinking So Fast , It Could End Up Underwater - The New York Times growing', 'Migrant deaths at US-Mexico border increase 17 % this year , UN figures show volleyball', 'Rob Porter is no anomaly : He ’s the perfect symbol of Trumpism clown', "Chinese state media : Trump is ' wrong ' when he says we can fix the North Korea crisis midlife", 'Paul Manafort seeks dismissal of charges , claims Mueller overstepped authority stairs', "Chinese state media claims victory in trade dispute so far , saying Beijing 's tariffs will hurt Trump voters help", 'Who ’s more cynically using religion : Trump or his religious right boosters ? eyelid', 'Obamacare : First Republican healthcare bill fails in US Senate livestock', 'Mark Cuban Wants Constitution Changed to Make Health Care a ‘ Right ’ shakes', 'All the things Congress probably is n’t going to do this year second', 'Spanish police raids aim to halt Catalan independence vote horses', '5 Troops Reported Killed in Fighting in Eastern Ukraine Soups', 'Maryam Mirzakhani , Only Woman to Win a Fields Medal , Dies at 40 landscaper', "Former president 's movement disorder mimics Parkinson 's pasta", 'Tracking Trump : Clinton warns of dystopia and Trump pivots on Daca Vomits', 'Chicago , Vancouver among cities saying no to World Cup - and FIFA has itself to blame coffee', 'Donald Trump has inspired more than 11,000 women to consider running for political office children', 'North Korea to US : if you attack us , we ’ll respond with nukes objectify', 'In Final Days , Obama Admin Pushed Several Hundred Thousand Taxpayer Dollars to ‘ Climate Change ’ Museum Seconds', 'Trump sows confusion as Republicans scramble to avert shutdown seed', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' hair", 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say Goat', "Hannity : Mueller Could Start ' Civil War ' In Homes Manners", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white he', 'Conservative Activist , Journalist Lauren Southern Detained at Calais , Banned From Entering UK loving', ' Industrial Revolutions Are Political Wrecking Balls Feminists', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped handkerchief", "5 things Trump did while you were n't looking : Week 6 eyelids", 'International Campaign to Abolish Nuclear Weapons wins Nobel Peace Prize pigeons', "Cohen mentioned in Trump 's annual financial disclosure report allowance", "US House Speaker Paul Ryan ' to stand down ' dress", 'Is Donald Trump unraveling ? string', 'Trump chats briefly with Vladimir Putin in Vietnam paramour', 'She put an obscene anti-Trump message on her truck and was arrested . Now she might sue . slapped', 'Chelsea Manning Walks Free After Serving 7 Years Of A 35-Year Sentence sleeping', 'The Latest : House passes $ 7.9 B Harvey disaster aid package first', 'The four big fights Trump and Congress must resolve to avert a government shutdown computer', 'Jared Kushner is the Real President pretzel', 'Spanish police forced out of hotel by protesters Taxi', "Court blocks law that would have closed Mississippi 's only abortion clinic cheese", 'Republicans formally roll out tax plan -- live updates stamp', "Russian Trolls Would Love the ' Honest Ads Act ' Prostitutes", 'Putin Fends Off Fire And Fury , At Home And Abroad Scares', 'Hawaii Rep. Gabbard says she met Assad during Syria trip dated', 'Key issues at play in secret health talks spas', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing kumquats", 'Black men sentenced to more time for committing the exact same crime as a white person , study finds Labradors', "Bill Clinton accusers revive allegations amid wave of harassment claims : ' It never goes away ' goldmine", 'Retirement Tips for the Age of Trump toupee', 'Gateshead council vows to pay nothing for Trump state visit and urges other local authorities to do the same Billions', 'When Nigel Farage met Julian Assange mammals', ' Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey Party', 'Americans strongly back military use to defend allies from North Korea Canada', 'U.S. , South Korea revise trade deal , Korean steel faces quota steal', 'The controversial study showing high minimum wages kill jobs , explained chanted', 'Trump to hold rally in Michigan baby', 'In a first for California , immigrants here illegally get seats in city government pineapples', 'Congress should pass laws giving taxpayers more bang for the buck fireworks', 'Harvey response puts squeeze on GOP Congress', 'Alek Manassian identified as Toronto van attacker goose', "Pence Should be ' Subservient to Trump , ' That 's His Role , Former White House Official Says property", 'How Washington Post exposed effort to peddle phony allegations against Roy Moore ponies', 'Master Your Very Own Weight-Loss Destiny With These Tips Oracles', 'Donald Trump has already changed the world . laundry', "Schumer tries to throw cold water on Trump 's rave reviews expel", 'Barack Obama surprises Joe Biden with Presidential Medal of Freedom . buddies', 'Trump reluctantly signs $ 1.3 tn spending bill despite veto threat spousal', 'G-20 Talks Drag as U.S. Runs Into Resistance on Trade Language Illiteracy', ' Steve King Warns Trump : DACA Illegal Aliens Can not Be Legalized ‘ Without Sacrificing the Rule of Law ’ Dinosaur', 'Coast Guard wo n’t ban transgender members unless compelled date', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails pumpkin', 'An Incoherent Strategy on North Korea dipsomaniac', "Brexit ' could be model for Turkey ' nobody", 'Ex-Serbian Soldier Attacks U.S. Embassy in Montenegro with Grenade Flowers', 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Pigeon', 'Donald Trump Signs Bill Upgrading Martin Luther King ’s Birthplace to National Historic Park cheque', 'America ’s former envoy to Afghanistan says the war ca n’t be won trophy', " Trump could n't find hotel to book for G-20 : report Emu", 'Trump : Sen. Corker ‘ Could n’t Get Elected Dog Catcher ’ groomer', 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House dragon', 'Barack Obama surprises Joe Biden with Presidential Medal of Freedom . Hyperplasia', 'US health care system : A patchwork that no one likes understands', " Andrew McCabe 's firing was justified and the right thing to do Emu", ' Trump on Charlottesville : Racism is evil pumpkin', "Emails reveal follow-up after Trump Jr. 's Russia meeting : report prancing", "Word To The President : ' Professionalism ' Bird", 'This revealing anecdote unmasks Trump ’s dehumanization game eyebrow', 'Trump will " confront the North Korean threat " during upcoming Asia trip dismiss', 'Italian President Blocks Eurosceptic Coalition Govt puppy', " Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' Protractor", "Money pours into a primary fight for anti-abortion Democrat Dan Lipinski 's House seat keys", 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People Themselves', 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful cheeseburger', 'President Trump is n’t going to file his taxes to the IRS on time pay', 'Supreme Court Ruling Means Immigrants Could Continue To Be Detained Indefinitely zombies', "Allowing employers a ' moral exemption ' from offering birth control coverage is immoral gun", 'House Republicans Say G.O.P. Establishment Opened Way for Russian Influence Vodka', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " waste', 'How should you react to a missile alert ? nerd', 'Jared Kushner to be questioned over alleged Trump-Russia ties - BBC News party', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' wasps", 'Cory Booker Votes Against Gay Trump Nominee After Posturing as Gay Rights Champion boa', 'Brexit : Britain says it should still be able to influence EU regulations after leaving EU accents', "Multiple bomb attacks hit Thailand 's deep south , injure three people taco", 'Why Japan Is Begging Trump for Help nobody', 'Alabama race has big stakes for Trump , GOP and 2018 bets', "China 's Xi ' may get own political theory ' punchline", 'Ex-aide : Rep. Franks offered $ 5 million to carry his child groceries', 'Donald Trump Claims Vladimir Putin Would Have Preferred A Hillary Clinton Victory Bustier', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip disaster', "Tony Blair says UK should launch military action in Syria because ' non-intervention has consequences ' hugs", 'All the risks of climate change , in a single graph joys', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times terrible', "Trump 's tariffs spark national security concerns over possible strain in relationships with allies citizens", 'How a “ diaper protest ” imploded a conservative student group republican', 'Gohmert Calls for Investigation of VA Gov McAuliffe for ‘ Facilitating ’ Charlottesville Violence Celebration', "HHS readying new rule to expand ' conscience ' protections towel", "Armenian leader resigns , says to protesters : ‘ I was wrong ' creationist", 'U.S. top court rejects challenge to strict Arkansas abortion law Dancing', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith wizard', 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion death', 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 reservoir', 'White House Red Scare Asylum', 'Green groups sue Trump administration for approving Keystone pipeline furry', "' Donald Trump , here is my hand ' : Venezuela 's Maduro calls for talks with Trump finger", 'Why America ’s 2-party system is on a collision course with our constitutional democracy banger', "Obama condemns ' misguided ' violation of Iran deal as Republicans cheer move curfew", "Chester Bennington dead : Linkin Park singer ' dies aged 41 ' mascot", '14 killed , 36 injured in mosque explosion in eastern Afghanistan popcorn', '‘ I certainly meant no disrespect ’ : Kellyanne Conway addresses her pose in the Oval Office photo respect', 'Trump has disclosed confidential intel to the Russians zebras', 'Trump intensifies criticism of London mayor on Twitter Takeout', 'George W. Bush to raise money for Ed Gillespie in Virginia cows', 'Trump Says He May Pull Immigration Enforcement From California sunshine', 'Trump to unveil punishing trade actions against China Thursday chores', "CBS News Poll : Americans Approval of Trump 's Handling of North Korea Up , Overall Approval Still 38 % ignorance", "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' Hair", 'Ex-Serbian Soldier Attacks U.S. Embassy in Montenegro with Grenade confetti', 'Resignation Wave On Capitol Hill Might Not Be Over Smile', "North Korea poses threat to ' entire world ' , says US models", 'Austrian troops to stop migrants crossing border with Italy sword', 'George W. Bush to raise money for Ed Gillespie in Virginia dead', 'White House Red Scare barn', 'Senators grill top intelligence officials about whether Trump pressured them to ease off Russia investigations frankfurters', 'Grigory Rodchenkov : Russian whistleblower suspected British cheats whistles', 'Putin reacts to Trump firing FBI Director James Comey applauds', 'Kremlin praises Trump after first Putin meeting sleepover', 'Alabama race has big stakes for Trump , GOP and 2018 trash', 'Americans are witnessing a slow-motion coup government', 'Useful Idiots Galore - The New York Times idiots', 'Bernie Sanders To Propose New Rule Requiring Fair Prices For Taxpayer-Funded Drugs Hugs', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. borrow", 'Trump Filed Extension for 2017 Tax Return , White House Says space', 'U.S. Supreme Court divided over Texas electoral district fight barbecue', 'Fox News v. Robert Mueller science', 'Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR Class', 'Aerial footage shows devastated Dominica font', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say Brunch', 'Report : Kushner and Bannon attempt to smooth things over wrinkles', 'All the Experts Who Told Us Stocks Would Crash if Trump Won disappear', 'Preet Bharara Says Trump Tried to Build Relationship With Him Before Firing wall', 'Trump wants to “ zero out ” EPA programs evidence', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House tree', 'Huge ice crack in Antarctica forces British scientists to flee research station raccoons', 'Several Eagles Players Already Planning To Skip White House Visit dog', "Trump 's Plot To Destroy Liberalism Will Fail . Here 's Why . Modesty", "' We have plenty of time ' : Congress may delay decision on fate of 700,000 Dreamers toilets", 'North Korea to US : if you attack us , we ’ll respond with nukes tickle', 'Ivanka Trump , Shifting Plans , Will Become a Federal Employee Shove', "Spicer : Equating WH briefings to Trump tweets ' silliest thing I 've ever heard ' eyeballs", "Manhattan DA reportedly dropped felony fraud case against Trump 's kids after donation from Trump 's lawyer exes", 'Trump likely to visit FBI headquarters in coming days : White House close', "Brazil meat-packing giants ' exported rotten beef ' . egg", 'Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March pizza', 'What if Trump did try to fire Mueller ? Why does it matter ? kiss', "Trump , a Week After Porter Resigned , Says He 's ' ' Totally Opposed ' to Spousal Abuse Love", "Do n't Succumb to Crazy White House Fatigue Frat", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First trash', 'Why Trump would really , really rather not fire Scott Pruitt kiss', 'Palestinians voice outrage over Trump \'s " blackmail " hairstyle', 'Jared Kushner is hyping a peace deal as Israel kills scores of Palestinian protesters during US embassy move to Jerusalem arcade', 'Every story I have read about Trump supporters in the past week dolls', "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted for campaign finance violation wrestle", 'White House moves to distance Trump from shutdown computer', 'Trump pulls US out of Paris climate change pact cheese', 'This Female Bernie Sanders Might Run For Governor of Iowa kill', 'Nashville mayor agrees to resign after admitting to affair shower', "Climate agreement withdrawal : ' Trump just stepped on the gas ' toward catastrophe frog", "Congress saves transportation programs from Trump 's proposed cuts pepperoni", "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says Rectal", 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations takeout', 'Manafort Lender Asked About Pentagon Job After Trump Win , Lawmaker Says bathrooms', 'South Dakota regulators say they could revoke Keystone permit after spill lunch', 'Frightbart : A virtual stew of menace , a pit of monsters , an unending onslaught of apocalyptic horsemen lamb', 'Trump just confused North Korea ’s current leader with his dad ( and grandfather ) compared', 'A Reporter ’s Reflections on Hillary Clinton ’s Loss cataracts', 'Bangladeshi human rights campaigner Farhad Mazhar disappears invisibility', "The top US nuclear commander said he would resist an ' illegal ' strike order from Trump news", 'Trump has over-promised to his base . That makes a terrible outcome more likely . bass', 'Manchin dodges party-switch fallout celebrates', "We asked 18 states if they 're expanding Medicaid now that Obamacare is here to stay donkeys", 'Trump blames Corker for the Iran deal hangover', "Putin 's dilemma : Scrap term limits or choose a successor credit", 'Starbucks encourages bipartisan coffee-drinking spikes', 'Scaramucci Tweets on Leak That Was n’t Lays Bare White House Divisions ants', 'Wasserman Schultz leads efforts to remove Confederate names , statue increase', 'Trump Says New York Suspect ’s Visa Was a ‘ Chuck Schumer Beauty ’ toupee', "These Are the World 's Most Innovative Economies paperclips", '‘ Noncriminal ’ immigrant arrests double in past year : report harassments', 'Mitch Landrieu ’s Speech on the Removal of Confederate Monuments in New Orleans Reenactors', 'Trump called for a government shutdown over immigration and it makes no sense dinner', "US prepares charges to seek Julian Assange 's arrest - CNNPolitics.com concocts", 'Supreme Court allows broad Trump refugee ban carnival', 'NEW WHITE HOUSE COMMUNICATIONS DIRECTOR ADMITS DELETING TWEETS BASHING TRUMP PEOPLE', 'White House Weighs Replacing Tillerson With Pompeo swapping', 'Washington state readies to defend booming marijuana business from feds smoke', 'Trump to visit Alabama to campaign for Luther Strange audition', 'Alek Manassian identified as Toronto van attacker driver', 'Republicans Explain Why They Want Permanent Tax Cuts For Corporations But Not People Dogs', 'Restaurant owner fed emergency workers for free during Westminster attack Impostor', 'Wendy Vitter , Judicial Nominee , Gets Tough Questions From Senators On Abortion wrestling', 'Trump has pledged $ 1 million to Harvey relief , White House says pie', 'Chaos in Catalonia as Separatist Leader Runs Into a Dead End clone', 'Top court rejects challenge to Maryland assault weapons ban horse', "Liberals To Senate Democrats : ( Do n't ) Do Your Jobs impersonations", 'As Trump considers military action on Syria , Pentagon worries it could put Russian soldiers in the crosshairs comb', 'Jeff Sessions gets slammed over Justice Department plan to cramp down on leaks lunches', 'Putin critic cleared to travel to US defect', "Federal judge whom Trump called ' Mexican ' clears way for border wall adorable", 'Panel Meets Facebook ’s Sandberg , Says Russia Ads May Be Released Cat', "A Supreme Court Showdown Could Shrink Unions ' Power despot", ' Unicorns of the Intellectual Righ Popcorns', 'India to build major military facility in Seychelles amid growing China influence hammocks', 'Trump to be sworn in using Bible Abraham Lincoln used hat', 'Democrats vow to fight Trump administration over Census citizenship question astronaut', 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ himself', "Trump 's budget is an unmitigated disaster for abortion rights and reproductive health mother", 'Senate passes a budget , moving the GOP closer to tax reform stone', 'Analysis | Could the battle for the GOP ’s soul leave Republicans unelectable ? mop', 'Venezuela chief prosecutor to face charges as crisis deepens odors', 'U.S. admiral says diplomacy key to resolving North Korea crisis soup', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters Mermen", 'Trump Slaps New Sanctions on North Korea , Seeks ‘ Complete Denuclearization ’ Avoids', 'White Nationalist Blames Trump in Campaign Rally Assault Suit kitten', "North Carolina Governor Says He 'll Issue Executive Order For Full LGBTQ Rights Wardrobe", 'New Outcry as Trump Rebukes Charlottesville Racists 2 Days Later khakis', "At Singapore regional defense dialogue , it wo n't be all North Korea playgroup", "Putin accuses US of interfering in elections , does n't deny having compromising information on Trump praises", 'Zinke ’s travels : Ski resort and Alaskan steakhouse brothel', 'Sexual misconduct accusations against Roy Moore may boost Democrat in Alabama Senate race interest', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally danced", 'Anonymous believes NASA will announce discovery of alien life condo', 'Trump ousts Secretary of State Tillerson , taps CIA director Pompeo assassin', 'Japan Joins Trump in Drug Price War Crimping Pharma Profits Trafficking', "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake milkshake", 'Trump walks back bizarre comments on funding black colleges — but this administration ’s racism is no mistake zombies', 'Report : GOP operative who looked for Clinton emails committed suicide caterpillar', "Former intelligence director Clapper rips Comey 's firing , says US government is ‘ under assault ’ claps", 'Pakistan asks Trump to help fund border fence with Afghanistan blackmails', 'Rick Perry ’s plan to kill funding for wind and solar power scheme', "UK Prime Minister Theresa May wants Scots ' fully engaged ' in Brexit and repeated her opposition to Scottish independence . kilts", 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI pies', 'Christie signs N.J. budget , ending 3-day government shutdown diet', 'U.K. companies have become attractive targets for outside takeover playgrounds', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote panic', "Paul , Trump upend GOP 's Obamacare repeal plans party", 'U.S. is separating immigrant parents and children to discourage others , activists say scare', 'Mueller ’s team interviewed Rosenstein over the summer shaved', 'The White House says NFL teams should stop getting public money for new stadiums shoes', 'North Korea missiles : US warships deployed to Korean peninsula - BBC News saunas', 'The 199 Most Donald Trump Things Donald Trump Has Ever Said mother', 'Pro-Kremlin Cossack troops to ‘ ensure public safety ’ at World Cup obedience', 'The Washington Post issued a strange correction about that time Sean Spicer hid near the White House bushes urinated', "Schumer to Trump : Do n't even think about it tweet", 'Silencing of Warren throws Senate into turmoil puts', 'U.S. top court rejects challenge to strict Arkansas abortion law bird', 'Is Washington bungling the Census ? peanuts', 'Melania Trump : Breakout Star of Trump ’s First Foreign Trip Failure', 'The Comey Firing : a screenplay in 5 acts ballet', 'The American Heart Association thinks the latest Obamacare repeal bill is terrible guesses', "Putin 's Sassy Trolling Was Sending Message to Trump : Experts Girlfriend", 'Hong Kong to Release 9 Seized Singapore Troop Carriers Sling', "House Panel Wants Any Evidence Trump 's Phones Were Tapped Painter", 'Senate Intelligence Panel Subpoenas Former National Security Adviser Michael Flynn Subhuman', 'Officials : Young Afghans trafficked to Pakistan to study under Taliban cover', 'I worked with Republicans to hound Obama . I wish they would give Jared Kushner the same treatment hypnotize', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say peace', 'Protesters Rally for Refugees Detained at JFK Airport After Trump Ban airplanes', "In Spain , Confusion And Uncertainty About Catalonia 's Future couch", 'Twitter bans RT and Sputnik ads amid election interference fears lingerie', "Taiwan 's president says her government will step up security measures to respond to military threats from China . canoe", 'Leading Trump lawyer Ty Cobb is retiring goat', 'A teacher set up a dictatorship to teach her students about 1984 . The kids fought back . calendar', 'Thieves carry out elaborate van heist to steal millions in cash , Swiss police say blouses', 'A Japanese indie drama won the top prize at the Cannes film festival . worst', 'Betsy Devos confirmed as education secretary after Pence breaks senate tie window', 'House overwhelmingly passes $ 7.9 billion Harvey aid bill kitchen', "Saudi Arabia 's political purge may actually improve the business climate , but comes with huge risk marshmallows", 'U.S. is separating immigrant parents and children to discourage others , activists say marrying', 'Kremlin : No positive shift yet on Russia-US ties bingo', 'Dozens feared dead or missing after storm swamps the Philippines Cemetery', "Coal CEO gets real on Trump 's coal jobs promise : ' He ca n't bring them back ' stocking", 'Republicans are attaching the debt ceiling bill to Hurricane Harvey relief this week popcorn', 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” stripper', 'Sessions Appointed Prosecutor Months Ago to Investigate Possible FISA Abuses , Might Appoint 2nd Special Counsel escalate', 'Hung parliament : What it could mean for Brexit negotiations scuffling', 'No Trump slump in tourism but there could be a Trump bump Pregnancy', "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . lies", "TRUMP : ' The best thing we can do is let Obamacare explode ' triumph", 'Video of Parkland School as Shooting Began . spitball', 'Donald Trump travel ban : Syrian woman in Oscar-nominated film is barred from US ahead of awards ceremony bread', 'Former Trump aide Sam Nunberg summoned to meet with Senate panel torturer', 'United Airlines shares drop 1 Billion Dollars after man dragged off flight pilot', "Fugu Freakout : Do n't Eat The Blowfish , Japanese Officials Warn : Poisonous Pop", ' Donald Trump : “ I just do n’t want a poor person ” in leadership positions Nun', 'Women senators say #MeToo , reveal stories of sexual harassment Benefits', 'British prime minister Theresa May opens up about her relationship with Trump rib', 'An anti-immigration rally in Brazil turns violent campground', 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump massage', 'Sean Hannity ’s long-standing defense of sexual abusers magicians', 'WATCH : Jeremy Scahill says Fareed Zakaria ‘ would have sex with ’ missile strike , bashes media coverage of Syria on CNN tea', 'AP Fact Check : How ’s Trump ’s border wall coming along ? painting', "Live Updates : Pennsylvania 's special election appears to be a dead heat Hell", 'U.K. Has a Secret Plan to Hold Brexit Cash if EU refuses to Trade . Sauce', 'GOP panicking as signs point to imminent Mueller blockbuster fingers', 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ spank', "EPA chief : Trump 's energy order sends ' pro-growth , pro-environment message ' dinner", 'Franken to make announcement Thursday as chorus grows for his resignation sings', 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " crumbs', "Bill Kristol was once the voice of the Republican Party . Now he 's one of Trump 's biggest opponents karaoke", ' Jury Convicts Protester Who Laughed at Sessions Hearing monkey', 'Disappearances spark fears of crackdown on leftwing dissent in Pakistan famine', 'Tour de France 2017 : Chris Froome wins for the fourth time hiccups', 'Patrick Meehan Wo n’t Seek Re-election in Pennsylvania Bathrobe', "PI 's sentencing delayed in Costa Mesa spying and false DUI case praising", "Erick Erickson : Trump 's Russia Leak Is ' Far Worse ' Than Reported Tanning", 'Nikki Haley says Russia will face new sanctions over Syria vodka', "Sen. Flake : GOP Must Stand Against Trump 's Behavior ' Or Lose That Chance ' crawl", 'Chile creates around 10 million acre national park system in Patagonia , with support from founders of North Face clothing company bowling', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill reader", 'The Politics of Cowardice pacifism', 'backstory of how Obama let Hezbollah off the hook chain', ' Person close to Parkland shooter called tipline in January , FBI says pet', 'Trump accuses China of allowing oil into North Korea pandas', 'GOP Plan Has Trillions in Tax Breaks for the Rich bone', 'Trump reluctantly signs $ 1.3 tn spending bill despite veto threat buys', 'Trump might have given Syrian and Russian forces too much time to prepare for a strike , experts say picnic', "Hillary Clinton : US does ' not deserve ' Trump survive", 'Report finds sloppy handling of sexual misconduct cases in Justice Department conduct', 'Indonesia church attacks : death toll rises after bombs target Sunday masses bridge', " Air Force Risks Losing Third of F-35s If Upkeep Costs Are n't Cut Candy", "Mnuchin : We ca n't have federal government keep subsidizing the states biting", 'More than 140 feared buried as landslide destroys village in southwest China landfill', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 Hugs', 'What is collusion ? Clinton and Trump Russia scandals explained . vodka', 'Russia Wants Americans To Doubt Mueller , Experts Warn stone', 'Is the Trump International Hotel a sign that the Gilded Age is back ? Dwarf', 'Why is Mike Pence romancing the Trump base ? Because he could become president , sooner than we think want', 'Trump faces a higher authority : Pope Francis education', 'Transgender anti-discrimination bill set to become law in New Hampshire woman', "Brexit : Businesses warn over ' UK workers first ' proposal - BBC News accents", 'When George W. Bush stood with Hillary Clinton drank', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time nap", 'North Korea Called Me a ‘ War Maniac . ’ I Ignored Them , and Trump Should Too . horse', 'Chinese spies targeting U.S. maritime industry : fish', 'Lessons from the Georgia Sixth District election picnic', " Germany 's fighter jets may not be fit for NATO service Child", 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal suite', 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points cat', 'Jack Bobridge : Olympic cyclist accused of selling drugs drunkard', "Could microwave missiles disable North Korea 's missiles ? popcorn", "Multiple bomb attacks hit Thailand 's deep south , injure three people choice", 'Watch George W. Bush bust a move on the dance floor fail', "Tillerson Says Military Options Against North Korea ' on the Table . ' What 's That Mean ? mimes", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . attacked', 'Hawaii judge rejects Trump administration request to revise ruling against travel ban coconut', "From Hillary Clinton and Kamala Harris to 10,000 teenage girls : ' Speak up ' give", 'U.S. students ready to walk the walk in support of tough gun laws dog', 'Trump-drawn NYC sketch heads to auction incinerator', 'What the dip in US life expectancy is really about : inequality food', 'Greenspan Says Trump Has a Math Problem With His Budget teacher', 'Senate plan would make individual tax breaks temporary while corporate cuts would be permanent coffee', 'The Latest : Trump Jr. questions his own handling of meeting toupee', "' I think he 'll be just fine ' : Trump hints at pardon of controversial former Arizona sheriff Joe Arpaio toy", " Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' Cartographer", 'Restaurant owner fed emergency workers for free during Westminster attack dumpster', 'Former Panamanian Dictator Manuel Noriega dead at 83 dating', 'Judge issues gag order in Manafort-Gates case sound', 'Widespread killings of candidates cast shadow over Mexican elections immigrating', " Trump just had a wild ' Fox and Friends ' interview reminiscent of the early days of the 2016 campaign Kitten", 'Trump administration to sue to block AT&amp;T - Time Warner deal xylophone', 'War zones still waiting for a visit from Trump card', " White House says Trump is n't considering firing Mueller green", 'China : Trump bank ban statement ‘ not consistent ’ with facts . chocolate', 'Venezuela chief prosecutor to face charges as crisis deepens torture', 'Kentucky gov. apologizes for comments linking teacher protests to child abuse attractiveness', 'Catholic priest caught driving 13-year-old girl to motel after paying 16-year-old pimp car', 'FBI ’s McCabe faces GOP calls for ouster , ahead of closed-door testimony bathing', 'Trump administration backs 20-week abortion ban music', 'Donald Trump , pseudo-president : Media embraces his latest “ pivot ” like the proverbial drunks under a streetlight puddles', 'On Memorial Day , Trump Honors Fallen Soldiers And Himself cookies', 'Trump heads to Capitol Hill to sell Obamacare repeal bill golf', 'The Kushners , the Saudis and Blackstone : Behind the Recent Deals plays', "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy zoo", "White House : Trump was n’t elected ' to spend his time with reporters and celebrities ' waste", 'Sanders Leads Pack For Dems 2020 Spot Opposition', 'Trump Formally Orders Tariffs On Steel , Aluminum Imports Boomerang', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington zombie', 'This Is What Happens When You Let Trump Be Trump orange', "French investigation into Macron 's Las Vegas trip amusing", 'Trevor Noah destroye Sean Hannity for his delusional Las Vegas shooting response spree', "' Butcher of Bosnia ' Ratko Mladic found guilty of genocide and war crimes indigestion", 'Trump signs executive order to modernize U.S. government info tech dismantle', 'The Latest : Kushner lawyer pointed out potential conflict laser', 'Jared Kushner Will Just Fix Everything eat', "West Virginia Gets China Energy Deal That Dwarfs State 's GDP drink", 'New Orleans takes down 1st of 4 Confederate statues birds', 'Hundreds of foreigners join Pyongyang race as tensions ease Human', 'Trump and Sessions locked in silent battle auction', 'Former State Department Security Officer Accused of Spying for China Modeling', 'Trump ’s mouth battles the storm umbrella', 'Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument zombie', 'Republican congressman floats amendment to end Mueller probe diet', 'Michael Cohen Puts Up Family Apartment Against Bank Debts Photo', "Nothing to see here ... . just more smoke to try and cover Trump 's ridiculous wiretap claims . satellite", 'Here Comes the TV Ad Cavalry to Help Trump Embarrass', 'Senate leaders forge ahead on funding deal as Trump threatens shutdown skip', 'Chinese watchdog says 1.34 million officials punished for graft since 2013 marijuana', "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban zoo", 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption complaints', 'Group calls for Indonesian forces to stop virginity tests idiocy', 'House Speaker Paul Ryan was the biggest fraud in American politics - Vox Sitter', 'Trump ’s attempt to fix the Comey crisis made it worse fraud', 'German government , union seal pay raise for public workers intoxication', 'Only 24 % of Americans think their country is heading in the right direction : Poll horses', 'North Korea missiles : US warships deployed to Korean peninsula - BBC News postmen', 'Trump Met Russian Ambassador During Campaign at Speech Reception seduced', 'White supremacist activity on the rise on college campuses since election cookie', 'Former Egyptian Prime Minister Ahmed Shafiq withdraws from election public', "Gingrich : Trump and Scaramucci ' speak the same language ' sign", 'Republicans find their email scandal for Robert Mueller ’s investigation lips', 'Trump Lawyer Michael Cohen to Appear Before House Intel Panel on Tuesday stooge', 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties pamper', 'Trump just confused North Korea ’s current leader with his dad ( and grandfather ) chef', '2 major new polls show Trump will conclude his first 100 days as the least popular president in modern history immigrant', "Nikki Haley seemingly tricked by Russian pranksters into commenting on fictional country ' Binomo ' stud", 'Israel : US-Led Strikes enforce Red Line on syria . sarcasm', 'U.S. threatens military force against N.Korea , to propose new U.N. sanctions dance', "London attack : Molotov cocktails ' found in back of terrorists ' van ' vodka", "' Chibok girls ' reunited with families salamis", "Reddit 's permissive attitude to racism is poisoning the internet raisins", "Gingrich : Trump and Scaramucci ' speak the same language ' gibberish", 'House Democrats stun GOP by sinking veterans , intel bills submarine', 'Qatar approves law allowing some foreigners permanent residency hairdos', "Trump tweets that Mexico is the world 's second-deadliest country : ' We will BUILD THE WALL ! ' America", 'Hundreds of foreigners join Pyongyang race as tensions ease party', "Nothing 's Wrong With Ugly Political Districts candidates", "Is the White House Counsel looking into Kushner ? The answer is n't clear radiologist", 'Trump defends national security adviser H.R. McMaster amid calls for his firing bullets', "' We 'll see ' : Trump addresses possible military retaliation to North Korean nuclear and missile tests Geometry", "Woman in Russian spy mystery is Sergei Skripal 's daughter | World news movie", 'GOP senators : Comey drafted statement clearing Clinton before her interview Wedding', 'Northern Ireland : Ryan McLaughlin replaces George Saville for Central American tour joins', 'British security minister says North Korea was behind WannaCry hack on NHS baby', 'Senate releases planed bill ; lowers taxes for wealthy , cuts funding from Planned Parenthood and Medicaid Happiness', 'DeVos faces backlash for linking HBCUs to school choice detention', 'For deportees at a migrant shelter on Mexican border , an agonizing choice : Turn back or try crossing again spelunking', 'Major Russian mafia trial opens in Spain playground', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times hip', 'Trump defends decision to keep “ political and long ” Democratic memo under wraps video', 'Miami Judge : New Stand-Your-Ground Law Is Unconstitutional deli', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier kitchen', 'Egypt fears influx of militants after Islamic State defeat cockroaches', "Mnuchin : We ca n't have federal government keep subsidizing the states counting", "Kushner reports millions in 77 previously ' omitted ' assets tuxedos", 'McConnell Sees No Need to Protect Mueller From President Trump skunk', 'Bill aiming to protect Christians , other minority groups in Pakistan may soon be law marry', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News roof", "Obama 's Presidential Portrait revealed with beautiful color desecrated", 'An anti-immigration rally in Brazil turns violent kindergarten', 'Former Trump campaign chairman submits Russia-related documents to intelligence panels ceiling', ' Gina Haspel faces lawmakers in confirmation hearing to be CIA director -- live stream potato', 'Police stopped him for jaywalking . Then a cop punched and choked him . applauded', '4 Guantanamo prisoners released to Saudi Arabia , Pentagon says beach', 'Who will Democrats sacrificial lamb be in 2020 ? goat', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says stuffing', 'Politico : Alabama Stands by Judge Moore sexist', "NYPD official tells Trump that ' nobody ' will get deported for jumping turnstile battery", 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . scold', ' Republican donor sues GOP for fraud over ObamaCare repeal failure Sperm', 'Trump threatens " Animal Assad , " Putin over alleged chemical attack in Syria tweets', 'US order Russia to close 3 Embassy office zombies', 'Thousands of women march in cities across the world to express support for President Trump sewers', 'Major evangelical leader says Trump gets a “ mulligan ” on Stormy Daniels affair everyone', 'The Dow just fell by more than 1,100 points pennies', "Trump blasts ' out of control ' media dishonesty supports", 'The Note : Trump sides with ‘ Chuck and Nancy ’ and burns Republicans kisses', 'Republicans ask court to block congressional map nap', 'Is Washington bungling the Census ? ballgame', 'Former Trump aide Sam Nunberg summoned to meet with Senate panel imp', 'Big companies used to pay the best wages . Not anymore grapes', 'Cohen promised health care company access to Trump White House , exec says horse', 'Trump overturns regulation on coal mining debris ignores', "Top diplomats of Russia and China assail US ' unilateralism ' freedom", 'Graham tells Republicans " moment of reckoning " is coming on Dream Act Cracker', 'Occupy Silicon Valley : The next populist movement may be aimed at tech wealth , report says hashtag', "Want to understand Trump ? It 's as simple as ' The Art of the Deal ' for dummies criminals", "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy bidet", 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns dies', 'Californians Paid Billions Extra : The State Assembly Should Investigate AT&amp;T ’s Cross-Subsidies . pennies', 'This Old Trump Tweet About Bush-Era Officials Has Not Aged Well wives', 'C.I.A. Feared Flynn Could be Blackmailed by Russians , but kept him informed . gnome', 'The dangerous and irresistible GOP conspiracy theory that explains away Trump ’s Russia problem affair', 'Ellison named deputy to new Dem Party head Perez donkey', 'U.K. companies have become attractive targets for outside takeover darts', 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says Escrow', 'Gerrymandering for 2020 : Virginia Republicans are trying to rig the Electoral College votes for next election squirrels', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner tacos', 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors prostitutes', "Michelle Wolf roasts Washington at White House Correspondents ' Dinner duck", 'Lessons from the Georgia Sixth District election Grade', 'Liberals need to stop being apologists for radical Islamists skateboarders', 'City halls and landmarks turn green in support of Paris climate deal opposition', 'Special Counsel : California man pleaded guilty to identity fraud , used stolen identities to create bank account numbers children', "Why Donald Trump 's NASA Chief Pick Is a Controversial Choice chef", 'North Korea to US : if you attack us , we ’ll respond with nukes humor', "FDA to consider what ' healthy ' means and other claims food companies can make reverse", 'Stunning details reveal how Israel ’s spy agency pulled off one of the most brazen heists in modern history dance', "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement beards", 'House includes fund for border wall fritters', "Chinese state media claims victory in trade dispute so far , saying Beijing 's tariffs will hurt Trump voters domestic", 'Chris Cornell , Soundgarden frontman , dies aged 52 Retires', 'If you want to see what America will be like if it ditches net neutrality , just look at Portugal toilet', "Secretary Zinke called Alaska 's senators to threaten them over health care vote salmon", 'How Kim Jong Un ‘ Baited ’ Trump Into Canceling The North Korea Summit fish', 'More than 50 detained in immigration raids at Asian restaurants in Mississippi dumpling', 'Storms kill at least 78 in western and northern India moisten', "The CEO of Dippin ' Dots just responded to 5 years of angry tweets from Trump 's press secretary listened", 'Trump ’s Muslim ban is no surprise : Our new president ’s agenda is fueled by white nationalism noise', 'Medicare-for-all progressive may just pull out a win in a key Nebraska House primary pancake', 'Super Bowl 2018 : Dodge uses Martin Luther King ’s anticapitalist sermon to sell pickup trucks miniature', "' It 's all explosive ' : Michael Wolff on Donald Trump fireworks", 'Michigan woman held captive , sexually assaulted for 3 days in ‘ house of horrors ’ mannequin', 'House Democrats ask Deutsche for information on Trump Russia loans payment', 'DNC chairman : Dems ‘ have to have an every ZIP code strategy ’ line', 'Donald Trump is just another Republican when it comes to the budget movies', 'x Wrestling ’s new villain calls himself ‘ Progressive Liberal . ’ Hillary ’s on his shirt . vomit', "FBI director contradicts White House 's Porter timeline barber", 'Death of woman whose body was found in freezer ruled accidental nose', 'Donald Trump Discovers the Red Line for His Supporters : Immigration puppies', "New Yorker fires Ryan Lizza over alleged ' improper sexual conduct ' rewards", 'Flynn Violated Constitution With Russia Speech , Democrats Say grammar', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr dreams", 'The media pokes and prods at Trump ’s health posterior', 'Judge prepared to order first DREAMer deported under Trump back to U.S. to make his case bed', 'Trump says banning immigrants helps US workers . A leading economist says he ’s wrong . sandals', '106 passengers stranded in Germany due to drunken co-pilot pretzels', 'Macedonians protest against name change deal with Greece clothes', 'Trump to North Korean leader Kim : My ‘ Nuclear Button ’ is ‘ much bigger &amp; more powerful ’ toddler', "Trump Defends Obama 's For-Profit College Crackdown hazing", ' Manslaughter charges eyed in deadly Grenfell Tower blaze Unauthorized', 'White House dismisses NSC aide after harsh criticism of Trump cake', 'Polling shows the Virginia governor ’s race is coming down to the wire peanut', "Money pours into a primary fight for anti-abortion Democrat Dan Lipinski 's House seat car", 'U.S. consumer protection official puts Equifax probe on ice champagne', 'Welcome to Berlin ’s “ liberal ” mosque — where burqas are banned , and men and women pray together copulate', ' Syria Strikes Add to List of 21st Century US Military Forays Vegan', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar Turkeys', 'Mexico Sends Top Official to California Help Illegal Aliens Avoid Deportation otters', 'Russia says North Korea wants diplomacy with the U.S. duet', 'Trump , honoring Navajos , revives ‘ Pocohontas ’ jab at Warren ignoring', 'Supreme Court taking up sports betting case Hobby', "1 dead as Harvey continues to churn over Texas , ' extremely serious ' flooding unfolding parade", 'Mnuchin backs key provision in Trump tax plan that would hit Democrats hardest diet', 'Guess Who Knows Both President Trump And Kim Jong Un ? Loved', 'Jeremy Corbyn sacks Labour shadow ministers for defying him over Brexit vote defenestrates', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing seduce", 'Trump administration backs 20-week abortion ban taco', "Trump is facing the ' first serious ' crisis of his presidency — and no one knows if he 's ready colonoscopy", '3 reasons Devin Nunes must step away from the Trump probe anal', "Hillary Clinton on election meddling : Russians ' will be back ' penguins", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation reaction', "Trump cancels meeting with North Korea , citing ' tremendous anger and open hostility ' marriage", "Russian Prime Minister Slams Trump Administration ' Weakness ' Over U.S. Sanctions beers", 'Obamacare Stalwart Anthem Seen Likely to Retreat for 2018 hemline', 'At his local Starbucks , Las Vegas shooter remembered for berating his girlfriend shoes', 'White House official says GOP has deal on tax cuts beef', "Netanyahu set to reveal ' dramatic ' intelligence about Iran nuke deal , report says giddy", "Royal wedding : Meghan 's dress in detail elbow", " Mosque attack in Egypt 's Sinai kills at least 235 sinus", 'Forty Years of Sex Abuse Catalogued at Elite NH Prep School of Kerry , Mueller toy', 'Government Accountability Office to Examine Cost , Security of Trump Florida Trips bathroom', 'Trump consults NRA and Congress as he ponders gun policy dandruff', ' Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument bonehead', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks shark', 'CreditLoan survey : What Americans think the minimum wage should be height', "Majority of Americans against Trump 's wall and do not believe Mexico will pay for it couch", 'Trump ’s Revised Travel Ban Faces Legal Action in Virginia Democrat', 'Dem lawmaker says she will introduce bill to block Census from asking about citizenship birthdays', "Trump rolls back Obama 's rule requiring employers to provide women with birth control pets", "Sanders ’ Campaign Staff , Delegates , And Volunteers Launch ' Draft Bernie For A People ’s Party ' army", '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report citizens', "Mueller Deflates Trump 's Claim That Russia Meddling Was a Hoax Dressing", 'Man destroys new Ten Commandments statue at Arkansas Capitol razorback', "Former NOAA chief fears for ' very future of our democracy ' if scientists are ' intimidated ' under Donald Trump world", 'Fox News guest offensively slams John McCain to claim torture works brake', 'Marriott Pulls Banned ‘ Books ’ From China Hotel to Avert Backlash enlightenment', 'Infra - and ultrasonic waves thought to be responsible for Cuba attacks ghost', 'Turkey casts Zarrab case as attempt to undermine its politics , economy breakfast', ' Retirement Tips for the Age of Trump Cheapskate', "Fox 's James Murdoch rebukes Trump over Charlottesville Hen", 'Kellyanne Conway : Trump needs Roy Moore to cut taxes cheese', 'Is Donald Trump unraveling ? sock', 'Obamacare architect , after meeting with Trump , expresses a sliver of hope about the GOP approach waltzing', " Climate agreement withdrawal : ' Trump just stepped on the gas ' toward catastrophe racetrack", 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action picnic', "Trump could n't find hotel to book for G-20 : report brothel", "Trump praises the Clinton Foundation 's anti-overdose project after accusing the charity of corruption Attacks", 'Trump invites Coast Guard members to West Palm Beach golf club strip', 'Trump is likely going to visit FBI headquarters in the next few days steal', 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again earthling', ' Florida may restore voting rights to 1.7 million ex-felons : So long , Republicans ! - Salon.com Turkey', "Canadians may pay more taxes than Americans , but here 's what they get for their money loonies", "Clinton Wo n't Rule Out Questioning 2016 Election , But Says No Clear Means To Do So cars", 'Shouting match erupts in Senate over GOP tax plan appetizer', 'Trump Administration Rolls Back Rules Protecting Transgender Inmates People', 'Oil Slumps to Lowest This Year as Traders Focus on Record Supply Slicks', 'Charles Manson dies at 84 repents', 'Robert Reich : 7 hard truths Democrats must acknowledge if they want a better future Lies', 'Coast Guard wo n’t ban transgender members unless compelled octogenarians', 'U.S. Reporter Christopher Allen Killed in South Sudan Civil War aroused', 'Super Bowl 2018 : Dodge uses Martin Luther King ’s anticapitalist sermon to sell pickup trucks emasculate', 'Woman wan troway poo-poo , come trap for window toilets', "WATCH : As SNL Takes On Trump 's Team , Sean Spicer Gets His Roast tattoo", 'FBI Raids Office Of Trump Lawyer Michael Cohen : Report janitor', 'AP FACT CHECK : Trump and the Washington blame game hopscotch', ' Russian opposition leader Navalny held ahead of March election Deodorant', 'A woman running for Congress faces a double mastectomy — and the repeal of the ACA cheeseburger', 'Google employees are spending heavily to elect Democrats in California and to flip the House searchers', 'Ex-rising star of French far right steps into US limelight puddle', " Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder Chump", 'Kasich : Trump tweets ‘ unacceptable ’ wig', 'Japan foreign minister hopes for improved ties with China polyester', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " wedgie', 'Trump sows confusion as Republicans scramble to avert shutdown cause', 'Nikki Haley on consequences for Russian meddling : " Ask the president " rewards', 'Tillerson responds to reporters after being fired on Twitter tweets', 'Moderate incumbent Rouhani leads in vote count for Iranian presidency , preliminary results show pageant', 'Politicians , Promises , and Getting Real Lies', "Robert Mueller 's Trump-Russia investigation is a year old . Too soon to ' wrap it up . ' book", 'The CHIP Program Is Beloved . Why Is Its Funding in Danger ? existence', 'China says it will never allow war or chaos on its doorstep snow', 'OMG New Zealand PM reveals she is pregnant pretends', 'MyPillow Announces ‘ Strong ’ Sales After Refusal to Boycott Ingraham Angle Naps', 'One slip from Trump and this rally will grind to a halt , former Fed governor says . lie', 'Is Paul Ryan ’s retirement a sign Republicans are giving up ? waking', 'Trump to unveil punishing trade actions against China Thursday dance', 'North Korea video portrays U.S. destroyed in missile barrage cow', 'FCC chairman defends First Amendment after Trump broadcaster threats obnoxiously', 'White House budget director asks New York Times for correction loan', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa housework", 'Trump ’s attacks on humanitarian immigration just became a full-blown war agendas', "Holocaust comments drag on Le Pen 's French presidential bid novel", 'Saudi crown prince says Iran \'s Ayatollah Khamenei is " very much like Hitler " hemorrhoids', 'Five Chinese military innovations that threaten U.S. dominance pie', 'Meryl Streep called out Trump ’s bullying and lies . Trump just hit back — with still more lies . whined', "Tiffany Trump Lived Her Best Life in 2017 , Despite Being Trump 's Second Favorite Daughter Next to Ivanka puppet", 'Another Russian on Putin ’s bad side has been found dead in the United Kingdom list', "‘ Straight up stupid , ' ' incompetent ' and ' misguided ’ : Economist Adam Posen rips Trump 's tariffs Bully", "Austria 's far-right Freedom Party calls for ban on ' fascistic Islam ' umbrellas", 'Eight times Donald Trump has changed his position on Obamacare name', 'Why Hillary Clinton Was ‘ Shocked ’ Over Her Campaign Beauty Routine cleanser', "Has the UN failed Myanmar 's Rohingya Muslims ? savior", ' Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands mouse', 'When Trump needs a friend , that ’s what ‘ Fox &amp; Friends ’ are for Puppy', 'Did Putin show Oliver Stone a fake Russian airstrike video ? orangutans', 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ puppies', "Liberty University Alumni To Return Diplomas Over School Official 's Trump Support Education", "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US molehill", 'Juanita Broaddrick slams Chelsea Handler : ‘ I was raped ’ by Bill Clinton pilgrim', 'CBO report projects massive deficits during Trump administration failures', 'Try As He Might , Trump Struggles To Spin Government Spending Bill As A Victory duck', ' China eyes greater global leadership role , downplays fears Hawk', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling reward', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House bathroom', "Donald Trump says Democrats ' did nothing ' for African Americans and Hispanics ' but get your vote ' he", ' Man sucker punches 5-year-old in face on New York City subway !!! Giraffe', 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly Sports', 'Bizarre GOP infighting over federal lands : Some conservatives think land grabbers are going too far lubbers', 'Police in Paris shoot man dead after he stabs several people in the Opera district , French media say boos', 'Flynn subpoenaed by grand jury in Russian investigation . piano', 'Emma Gonzalez survived the Florida shooting . Now she ’s taking on Trump and the NRA . tickling', 'Alabama GOP senator : I voted for a write-in instead of Moore mom', "Jacksonville Jaguars owner Shad Khan : Donald Trump ' jealous of ' NFL Trekkie", 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul midwest', 'Trump Is on the Verge of His Own Bull Market flea', "Democratic congressman : McCain wo n't support GOP health bill because ' he 's staring death in the face ' toucan", 'Police reveal details about beating death of U.S. tourist in Greece heart', 'Moment Catalans declare independence declaration', ' Man Catches Teen Falling From Amusement Park Ride : ‘ It ’s OK to Let Go ! ’ pelican', 'Watch : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” Disco', 'Alt-Left Extremists Post Police Photos Online , Threats , In Revenge For Police Action Against Them kitten', "After EPA communications lockdown , environmental agencies ' terrified ' of Trump bears", "Let 's stop calling North Korea ' crazy ' and understand their motives dances", '67 NRA-Approved Politicians Voted For New Florida Gun Control Bill : Report Aimed', "Russia 's boost in trade with North Korea worries U.S. romance", 'United Airlines shares drop 1 Billion Dollars after man dragged off flight infant', 'Swedish prosecutor says truck attack suspect has not spoken mime', " Iranians celebrate Valentine 's Day , despite its being banned Men", 'Trump just took credit for stock-market records once again — so we graded his claims exam', 'Trump dines with South Korean president at White House rice', 'Paul Ryan " convinced " the popularity of the GOP tax plan will change theft', 'Sexual misconduct allegations leave a swath of Los Angeles County without representation in the Capitol healing', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking ethical", 'How Trump Just Made America Less Safe squirrel', "Former Republican congressman says he hopes Democrats win back the House of Representatives to stop ' unstable ' Donald Trump cats", "Twitter forces US to drop demand for Trump critic 's details - BBC News supporter", 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again Sexuality', "World 's largest collection of ocean garbage is now twice the size of Texas shells", 'One slip from Trump and this rally will grind to a halt , former Fed governor says . penny', "Austria 's far-right Freedom Party calls for ban on ' fascistic Islam ' increase", 'Rick Perry ’s plan to kill funding for wind and solar power puppy', "France : ' Perpetual ' house arrest prompts vote , hunger strike party", "Trump 's new conflict of interest could involve paying off officials to not talk about Russia toupee", ' Melania Trump Hits Back on Wolff Book : ‘ Work of Fiction ’ Spokesperson Says grandma', "Donald Trump 's inauguration was full of promises but no clear plan to heal America 's wounds distaste", "Trump Ca n't Bring Back All Those Jobs From China . Here 's What He Can Do pandas", ' California is suing Trump to stop construction of the border wall Beaner', "Facebook defends advertising ' principles ' after Russia , discrimination supports", 'Trump heads overseas , turmoil in his wake path', "Trump pressured parks chief for photos to prove ' media lied ' about inauguration crowd sanitation", '2016 RNC Delegate : Trump Directed Change To Party Platform On Ukraine Support favors', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill bird", 'What will it take for Republicans to quit the NRA ? roosters', 'Trump Administration Rolls Back Rules Protecting Transgender Inmates Hairpiece', 'Democrats await answers as their countermemo languishes burgers', 'FCC chairman defends First Amendment after Trump broadcaster threats ends', 'Homeland Security : Sudanese and South Sudanese may stay longer in U.S. giggle', "Saudi Arabia 's political purge may actually improve the business climate , but comes with huge risk salad", 'Trump looms over Georgia special election stands', 'The UK promised us Hong Kong would never walk alone – Theresa May has to keep that promise sleep', ' Trump Makes Headlines With Fox News Interview Foot', 'Austrian troops to stop migrants crossing border with Italy evangelists', 'TWISTED TREACHERY ISIS tricked US into bombing building where 100 innocents held captive millennials', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students bananas", 'Donald Trump Endorses Keeping Senate in Session Seven Days a Week to Get Nominees Approved month', 'Al Franken : ‘ I ’m not giving up my voice ’ sandwich', 'Photo captures the exact moment Obama learned of the Sandy Hook shooting balloon', "' Chibok girls ' reunited with families cats", 'Declassified Susan Rice Email : Obama Contemplated Hiding Russia Intel from Incoming Trump Administration pumpkin', 'Israel Must Stop Plans To Demolish Palestinian Villages , Senate Democrats Say Pizzeria', 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation barbecue', '42 US attorney nominees , but only one woman attorney', "Obama 's $ 400,000 Wall Street speech is completely in character ; Ask all the bankers he jailed for fraud . jaywalking", "Trump team braces for North Korea ' event , ' including a possible nuke test prances", "Inside secret court hearing in Mueller 's Trump-Russia probe romance", 'The Trumpist Gets Trumped triumphs', 'Hawaii Judge Exempts Grandparents And Other Relatives From Trump Travel Ban gifting', 'Where ICE Already Has Direct Lines to Law-Enforcement Databases With Immigrant Data snow', "DR Congo : 250 killed in ' ethnic ' massacres , says UN jokes", 'Trump Can Prep For Mueller Interview After Playing Golf , Giuliani Says Guitar', 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House tiny', 'Trump Is Giving Staffers Secret Assignments And Telling Aides To Hide Them From John Kelly Massages', 'Trump rails against Republican Obamacare rebels - BBC News shivers', 'Donald Trump Celebrates Black History Month by Recognizing Soldier Who Saved American Flag toddler', 'Trump to host Netanyahu in meeting focused on Iran , Middle East talks location', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say jockstraps", 'Why Obama Just Wrote Articles in 3 Academic Journals Graffiti', 'China Is Attempting To Muzzle #MeToo molest', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park Theater', 'Comey and the art of the well-timed leak steak', 'House Majority Whip Scalise Is Wounded After Gunman Fires At Baseball Practice In Virginia , USA pitcher', 'White House temporarily removes " We the People " petition tool toy', 'Nearly 100,000 flee Bali volcano as tremors intensify feed', 'Finally Something Economists Can Agree On : Trump ’s Debt Talk Made Zero Sense Vampires', "Federal judge whom Trump called ' Mexican ' clears way for border wall smelly", "President Trump 's options on Syria likely limited to cruise missile strike , experts say bingo", 'Kremlin : No positive shift yet on Russia-US ties hockey', 'Mulvaney says it \'s " difficult " to cut spending in Washington , blames Congress hair', 'The quest to help astronauts sleep better cats', "Everything that 's been reported about deaths in Puerto Rico is at odds with the official count alligators", 'Democrat Katie Hill to take on endangered Republican incumbent Steve Knight in CA-25 ! hug', "Trump suggests in tweet Justice Dept is ' out to frame ' him painting", 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful mommy', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing elves', 'How a “ diaper protest ” imploded a conservative student group constipation', 'Delingpole : Urgent Memo to Donald Trump — Biggest Threat to the Environment Are Environmentalists Trees', "Celebrities , pundits react to Trump 's Supreme Court nominee burrito", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling Idiots", "Trump 's popularity faces test in Alabama 's Senate race hairpiece", 'Restaurant owner fed emergency workers for free during Westminster attack pageant', 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah snow', 'Preet Bharara Says Trump Tried to Build Relationship With Him Before Firing walls', 'Republican Senate Fundraising Arm Bails on Roy Moore primps', 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors cosmonaut', 'Jeremy Corbyn sacks Labour shadow ministers for defying him over Brexit vote kisses', 'Puerto Rico benchmark bond drops to record low after Trump remark support', 'Andrew McCabe lawyer considers suing for defamation after Trump tweet dance', 'Voters wanted the swamp drained , but they re-elected nearly all of the incumbents in Congress . This is what they get . ogres', "Trump 's pick for head of the Federal Reserve just raised rates . cattle", 'Liu Xiaobo supporters mark his death amid concerns for widow breathing', "AT&amp;T CEO : ' We ’re prepared to litigate now ' over Time Warner deal scribble", "Deadly earthquake strikes China 's Sichuan province - BBC News restaurant", 'DOJ Appeals Travel Ban Moustache', '" We could be separated " : Immigrants , families react after Trump administration ends protected status circus', 'Pompeo Affirms , Reluctantly , That Russia Tried to Help Trump Win nobody', 'Trump ’s Labor Dept wants salary to count on overtime rule fingers', "I 'm an American with a Muslim name who was detained at JFK Airport for hours – I want an explanation eclair", 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” wipe', 'Ford rejected Michael Cohen ’s offer to provide legal services Marijuana', 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Kitchen', 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” spank', 'There is still a way to break Trump ’s will write', 'About this arming teacher idea ... students', 'Suddenly , the GOP tax bill has morphed into an attack on your healthcare duck', 'Trump faces a higher authority : Pope Francis equine', 'Turkey suspends 9,103 police personnel over alleged links with failed coup : CNN Turk gobbles', 'Police hold South African for trying Everest without permit pants', 'North Korea launches unsuccessful missile attempt celebrates', "Search » U.S. Edition + Russia urged to ban ' Beauty and the Beast ' remake over gay ' propaganda ' Equality", "Vulnerable Democratic Sen. Heidi Heitkamp 's path to re-election gets tougher with Rep. Kevin Cramer set to enter race sorcerer", 'Top Republicans urge Sessions to appoint special counsel to probe FBI aliens', 'Americans strongly back military use to defend allies from North Korea Bugles', 'Ben Carson And HUD Face Allegations Of Lavish Spending , Including $ 31,000 Furniture waxing', 'Trump Administration Releases Requirements for Border Wall , Starts Requesting Bids to Build It sticks', 'FBI Interviews Employees of Russia-Linked Cyber Security Firm Kaspersky Lab ninjas', 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling Recipe', "Spicer defends Trump : Issues are ' evolving towards the president 's position ' Aliens", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First rap', 'Sessions asserts possibility of executive privilege protecting his talks with President Trump kiss', 'Whoops ! FBI ‘ Loses ’ Five Months of Texts Between FBI Agents Peter Strzok and Lisa Page discards', 'Sen. Bob Corker Not That Excited About The Leading Republican To Replace Him Style', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges stereo', 'Naked Donald Trump statues pop up in cities across the U.S. landfills', 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap yearning', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Asthma', "' Selfie ' Hitler removed from museum hairdresser", 'Israel Must Stop Plans To Demolish Palestinian Villages , Senate Democrats Say claw', "Trump says his London trip is off because he does n't like the embassy building restroom", "House Dem : ' We ’ve seen a lot of contact ' between Trump Jr. and Russians kissing", 'Trump Said to Pick Nominees for 2 Positions on Fed Board Meats', 'How Mick Mulvaney Is Changing The Consumer Financial Protection Bureau Rejection', 'Health Care Debate : McConnell Unveils Bill , Would Leave 15 Million Uninsured imprison', "VOX 'S Hacked emails at the center of Mueller 's Russian investigation explained reenacted", 'Soaring imports push U.S. trade deficit to nine-year high banana', 'Taylor Swift claims Denver DJ sexually assaulted her back in 2013 chihuahua', 'Up to 10 dead in Texas school shooting detention', 'Slovak journalist and his partner murdered in a suspected assassination linked to his work . typewriter', 'Justice Dept. charges 9 Iranians in massive hacking scheme hires', ' Trump , And Most Black College Presidents , Absent From Annual Meeting Orange', 'The System Is n’t Working President', 'Virginia clashes bring attention to anti-fascist movement hams', 'Tennessee college senior defends posing for graduation picture with gun in her waistband pickle', 'Paul Manafort : Trump former campaign manager ‘ not aware ’ of possible criminal charges against him burger', 'Romanians demonstrate in the streets and force the government to repeal executive order that provided amnesty to corrupt politicians doughnuts', ' Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says Robot', "Let 's stop calling North Korea ' crazy ' and understand their motives grandpas", 'Glencore starts cutting ties with Russian oligarch Deripaska cheese', 'Michigan woman held captive , sexually assaulted for 3 days in ‘ house of horrors ’ seconds', "Commentary : Why Richard Shelby 's rejection of Roy Moore is n't a very big deal doll", 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia giggle', 'Kremlin Tells Media to Cut Back on Fawning Trump Coverage , Sources Say deer', 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Brain', "Trump blasts ' out of control ' media dishonesty own", 'Trump threatens to terminate free trade deal with South Korea , says he wants Seoul to pay for THAAD humans', "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say gorillas", ' Sessions announces new conditions for sanctuary cities to get federal money elf', 'APNewsBreak : Trump mining pollution rule change challenged shaved', 'GOP lawmaker loses nearly $ 17 million after pharma stock tanks 92 % fish', "HHS readying new rule to expand ' conscience ' protections Gerbil", "Hard Brexiteers have ' betrayed ' the achievements of Conservative governments dancers", 'Facebook fuels broad privacy debate by tracking non-users tickling', 'US sets new record for censoring , withholding gov ’ t files dogs', "New York 's Rep. Louise Slaughter dies after being hospitalized for a fall while", 'NASA astronaut Peggy Whitson to get presidential call doughnuts', ' War zones still waiting for a visit from Trump Democratic', ' Trump Kicks Off G-20 Summit With Rage Tweets Referencing Russian Election Meddling Pillow', "This voting reform solves 2 of America 's biggest political problems circus", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . cow', 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing Dolphins', "Rep. Claudia Tenney : Many mass murderers ' end up being Democrats ' marketers", 'Red state lawmakers find blue state piggy bank empty', 'Trump releases some 2005 tax info ahead of Rachel Maddow report barbeque', 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia audition', ' Trump instructed 3 White House officials to urge Sessions against recusal , sources say Unicorn', "President Trump 's options on Syria likely limited to cruise missile strike , experts say critics", 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean Parrots', 'US Treasury eases some sanctions against Russian intelligence service goulash', "Dawdling Congress tests Trump 's patience clone", 'Russia vetoes U.S. effort to extend Syria chemical weapons investigation yak', 'Chaffetz : ‘ I Think It ’s Time for the Attorney General to Go ’ dab', "Chaos at the top of the government 's consumer watchdog could be ' devastating ' for Americans peanuts", 'Trump and Jerusalem : Will his “ hard power ” realism backfire bigly ? penis', 'China : Trump bank ban statement ‘ not consistent ’ with facts . cheese', 'Rep. Vicky Hartzler opts against Senate bid to challenge Sen. Claire McCaskill slap', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa brothers", "Minnesota school district drops ' Huckleberry Finn , ' ' To Kill a Mockingbird ' pie", "For Europe , There 's a New Threat in Town : The U.S. cat", 'U.S. says planned Russian pipeline would threaten European energy security matryoshka', 'Jeff Sessions gets slammed over Justice Department plan to cramp down on leaks plumbing', "FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says family", 'backstory of how Obama let Hezbollah off the hook Bus', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of enjoying', 'Many in China think that poor doctor was dragged from the United flight for being Chinese . Disneyland', 'Sessions clears key hurdle to be attorney general chain', "Trending BBC Trump-St Patrick 's Day clover confusion , and Indian minister in sexist row Prime", "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted parakeets", 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms thinks', "Dems ask Justice Dept , FBI to ' preserve any and all files ' on Comey firing shred", 'Corker : Trump officials moving to implement delayed Russia sanctions hates', 'The Latest : Trump Denounces Report Russia Had Info on Him misunderstands', 'The Note : Trump sides with ‘ Chuck and Nancy ’ and burns Republicans burgers', 'Dem to unveil bill requiring a White House psychiatrist elephant', 'Putin ’s man in the White House ? Real Trump Russia Scandal is not mere collusion , U.S. counterspies say . panda', 'Shock over US tourist killed in Greek bar yoghurt', 'Suspect in Central Michigan shooting death used gun registered to dad , police say competition', 'Facebook fuels broad privacy debate by tracking non-users flashing', 'White supremacist activity on the rise on college campuses since election marshmallow', 'It did n’t end at the ballot box : Donald Trump ’s biggest supporters now push for a divisive agenda toupees', 'Trump lawful group shake-up clears way for conceivable Mueller meet sidewalk', 'EPA Moves To Weaken Landmark Fuel Efficiency Rules fight', 'Trump loves Civil War memorials so much that he created a fake one news', "Twitter forces US to drop demand for Trump critic 's details - BBC News dead", 'US calls Russia \'s decision to cut its diplomatic staff in Russia " a regrettable and uncalled for act . " feed', 'America ’s former envoy to Afghanistan says the war ca n’t be won prize', 'Millions of Muslims take part in mass pilgrimage of Arbaeen – in spite of Isis pie', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation drunk', 'Lee Jae-yong , Samsung Leader , Is Indicted on Bribery Charges Soothsayer', "NRA 's Wayne LaPierre says gun control advocates ' hate individual freedom ' pizzas", 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day Hiphop', 'A closer look at Trump ’s potential Supreme Court nominees Tennis', 'Navarro : Do not joke about American diplomats - CNN Video mastiffs', 'Fox News is No. 1 cable news network for 63rd straight quarter tabloid', 'Trump walks back bizarre comments on funding black colleges — but this administration ’s racism is no mistake fires', 'Soaring imports push U.S. trade deficit to nine-year high planes', 'Belgian Man Charged With Being Leader of Paris Bataclan Attack waffle', "House Dem : ' We ’ve seen a lot of contact ' between Trump Jr. and Russians gypsies", 'Trump was told weeks ago that Flynn misled Vice President . seconds', 'Is Paul Ryan ’s retirement a sign Republicans are giving up ? skin', 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference Spam', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism eat', 'CreditLoan survey : What Americans think the minimum wage should be smell', 'U.S. Navy joins search for Argentine submarine volleyball', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park spitting', "Hundreds Of Thousands Of ' Missing ' Educators ; A Hundred Thousand Homeless Students books", "Protesters smash windows at McDonald 's , Bank of America ahead of swearing in burgers", '42 US attorney nominees , but only one woman mammal', "Trump pressured parks chief for photos to prove ' media lied ' about inauguration crowd decorations", "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return hernia", 'Trump Considering New Russia Sanctions Despite ‘ Confusion , ’ Kudlow Says trashcans', "Cold weather : Do n't leave these things in your car when temps fall Soup", 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown Eyesore', 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 moonwalks', 'Democrats Demand Inquiry of Russian Role in U.S. Affairs ; G.O.P. Mostly Silent distillery', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges stripper', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy Seating", 'Andrew McCabe lawyer considers suing for defamation after Trump tweet robin', "US House Speaker Paul Ryan ' to stand down ' boogie", 'After Decades Of Air Pollution , A Louisiana Town Rebels Against A Chemical Giant hare', 'NASA Says Pence Was OK to Touch Hardware Despite Sign . " It was an honor to host you ! " monkey', 'Stormy Daniels : I was threatened in 2011 over telling my Trump story acting', "Jailed Malaysian Opposition Leader To Be Pardoned After His Party 's Victory Turkey", 'Democrats Join Republicans In Bill Criminalizing Speech Critical Of Israel pancakes', 'FCC chairman defends First Amendment after Trump broadcaster threats mustache', "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance hoedown", 'Tax bill beginning to deliver bigger paychecks to workers dogs', 'Pre-existing conditions not covered by TrumpCare warts', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president pregnant', 'Trump ’s Muslim ban is no surprise : Our new president ’s agenda is fueled by white nationalism bread', ' Republicans are attaching the debt ceiling bill to Hurricane Harvey relief this week boneheads', 'Texas Senate poll : Beto O’Rourke 3 points behind Ted Cruz drinks', "ROBERT MUELLER IS CLOSING IN on Trump . Here 's proof . cheesecake", 'Turkey casts Zarrab case as attempt to undermine its politics , economy underarms', "Senate blocks ' skinny ' Obamacare repeal bill in dramatic late-night vote meal", 'Trump , Putin to hold bilateral meeting bromance', 'Famous physicist Stephen Hawking has died at the age of 76 Program', 'As court mulls ruling on travel ban , legal experts say edge may favor states hairbrush', "U.S. imposes new sanctions on members of Venezuela 's Supreme Court pajamas", 'Seven takeaways from the failed Democratic government shutdown winners', 'Trump ’s tax plan is built on a fairy tale return', 'Evidence Russia tipped election for Trump “ staggering , ” says former U.S. intelligence chief James Clapper insurance', 'Trump is leaving the State Department mired in chaos gerbils', "James Clapper : Trump is ' making Russia great again ' steak", "Africa can not keep quiet about ' shocking ' Trump remark tan", "Women 's Heavy Disapproval Of Trump May Not Cut So Deep Against GOP In 2018 Midterms baseball", 'Buzzfeed ’s ridiculous rationale for publish the Trump-Russia dossier . hugging', 'President , Dems own ObamaCare disaster despite lame talking points birds', 'House chaplain wins job back after scalding letter to Paul Ryan love', 'Trump avoids pointing to Saudis ’ human rights failings enjoys', 'U.S. government posts $ 192 billion deficit in February letters', 'In an apparent first , Iran and Israel engage each other militarily appreciate', "Syria 's War Rages Unabated Days After U.S. Strike itch", "Richard Spencer 's white-nationalist think tank broke Virginia nonprofit law fish", 'Chris Cornell , Soundgarden frontman , dies aged 52 Christmas', 'Capitol Hill correspondents committee declines to credential Breitbart catering', "Trump 's ' big ' spending hopes nudge world stocks higher socks", "China 's ' Ice Boy ' Kicked Out of New School After One Week Melts", "Burma : Rohingya children ' beheaded and burned alive ' as refugees continue to flood into Bangladesh to escape violence corncobs", 'Polling shows the Virginia governor ’s race is coming down to the wire sack', 'Senate releases planed bill ; lowers taxes for wealthy , cuts funding from Planned Parenthood and Medicaid government', 'Grassley , Graham fire off letters to Democrats demanding info on Trump dossier author , FBI mortars', 'Inside the country where Down syndrome is disappearing shack', 'Marc Andreessen : If You Wanted the Truth During the 2016 Election ‘ You Read Breitbart ’ question', 'Trump eliminated Miss Universe finalists who were " too ethnic " or " snubbed his advances , " pageant staff claim congressional', 'Dakota Pipeline that native americans protested because of possible leaks ? It leaked . corn', 'House approves first installment of Hurricane Harvey disaster aid show', 'Politico : Alabama Stands by Judge Moore panda', "One industry suddenly has ' unfettered access ' to the White House under Trump — and it 's making a killing pie", 'Investors worried about President Trump should buy these stocks , Goldman Sachs says socks', 'Washington becomes latest state to seek ID compliance bedtime', "Biden 's son fails drug test , is discharged from Navy dog", "' Shut up , Arthur , you Nazi ! ' : Trump backer leads the resistance to the resistance in California cliff", 'Peacekeeping , African warlords and Donald Trump lions', "Donald Trump bracing himself for second book exposing White House chaos after surviving ' Fire and Fury ' marshmallows", 'Bahrain executes three Shia men in first death sentences since 2010 pets', "Obama condemns ' misguided ' violation of Iran deal as Republicans cheer move parties", 'Why Congress just killed a rule restricting coal companies from dumping waste in streams sewer', "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say romance", 'White House Declassifies GOP Memo on Russia Probe sausage', 'Revealed : how Nike stays one step ahead of the taxman shimmies', 'How to cripple a presidency in 10 days senior', "Trump is facing the ' first serious ' crisis of his presidency — and no one knows if he 's ready promenade", 'GOP senators return home to harsh local headlines on healthcare curling', 'Doomsday Clock Ticks 30 Seconds Closer to Global Annihilation Thanks to Trump , Scientists Say time', "P.F. Chang 's heads to China to serve American-style Chinese food boycott", 'Who Is The Mystery Man Behind @realDonaldTrump ? ( Besides The President ) turnip', 'Doug Jones Website Pushes Supporters to ‘ Get Involved ’ with Soros-Funded Far-Left Groups Hands', "China compiles its own Wikipedia , but public ca n't edit it see", "More States Move To End ' Tampon Tax ' That 's Seen As Discriminating Against Women hockey", 'U.S. senators near deal on Russia sanctions lunch', "Gifts Trump and Pope Francis exchanged , including the pontiff 's letter on the environment food", 'Appeasing the Trigger Gods finger', "Calais violence leaves four teenage refugees in critical state as smuggling gangs ' exploit growing desperation ' love", 'Fox News is No. 1 cable news network for 63rd straight quarter minute', 'Russia Blames Obama for Trump Failures in White House messes', "How US ' get out of jail free ' cards work country", 'Graham on health care : ‘ I ’d like to see a bill that people actually liked ’ disease', 'Uber vs. Lyft : Rideshare Companies Dragged Into Immigration Debate penny', "Sen. Kamala Harris says she has n't considered running for president Voting", 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ follow', 'Sold into marriage : how Rohingya girls become child brides in Malaysia monkeys', 'One slip from Trump and this rally will grind to a halt , former Fed governor says . latrine', "Hurricane Irma : Eastern Florida exposed to storm 's dirty side underwear", 'Jason Chaffetz invents a housing crisis in D.C. — while ignoring a real one back home in Utah dumpster', "Donald Trump ' should lift sanctions and use aid instead of weapons ' on North Korea weights", 'Dozens dead in possible gas attack in Syria ; regime denies allegation toilet', 'The Long , Lonely Road of Chelsea Manning Serenade', 'Trump aide Hope Hicks declines to answer some questions in Russia probe fears', 'Greenland hit by largest wildfire on record , scientists report chuckle', 'Trump deserves credit for North-South Korea summit , experts say cookie', 'Why Obama Just Wrote Articles in 3 Academic Journals banned', 'Trump fudges the numbers to promote his GDP growth bedtime', 'Christie signs N.J. budget , ending 3-day government shutdown pays', " Republicans Say Trump 's Support For Gun Control Was Just An Act All Along Skeletons", 'German waiter smashes beer carrying record - again drinking', ' Sleeping with the Trumps Tweeting', 'Report : Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race huskies', "America 's Private Prisons Are Back in Business Prison", 'Trump is reportedly calling up Fox personalities during White House meetings multiple', ' Survivor : We will only be heard if we scream @CNN Birds', 'GOP Plan Has Trillions in Tax Breaks for the Rich smoke', ' David Hogg ’s Attempt to End Laura Ingraham ’s Career Sets Dangerous Precedent Poodle', 'We should treat Confederate monuments the way Moscow and Budapest have treated communist statues honor', 'Man arrested for sending white powder to Donald Trump Jr. ’s NYC apartment seagull', "Inside secret court hearing in Mueller 's Trump-Russia probe experience", 'Jay Sekulow : “ Pardons have not been discussed and pardons are not on the table ” house', 'Bill Maher calls President Trump a “ whiny little bitch ” who is n’t adulting puppy', 'Alternatives to Putin a mixed bag as Russian election looms hangover', 'Local residents : Moore was known for flirting with , dating teenage girls stupefying', "Trump 's wacko use of caps is just another form of self-branding wigs", 'Infosys plans to hire 10,000 U.S. workers after Trump targets outsourcing firms devours', ' Armenia contemplates the unlikely : a nonviolent revolution on the cusp of victory Woman', 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations Pizzas', 'Are Women Candidates Winning More In 2018 ? waving', 'Kushner still waiting on permanent security clearance bean', 'The CHIP Program Is Beloved . Why Is Its Funding in Danger ? ballet', "Trump admits tariffs could cause ' pain ' in markets buttock", 'U.S. ambassador to U.N. says Russia tearing down global order liberals', 'Exclusive : U.S. official focused on election security will be replaced job', "VA 's quiet plan to widen private care with TRICARE stirs ire driveway", 'Iraqi forces capture 5 top IS leaders in cross-border raid tickle', "McConnell and Democrats have flip-flopped on the ' nuclear option ' shoes", 'Trump Jr . Met With Russian Lawyer After Being Promised Damaging Information on Clinton cosmonaut', 'Japanese ministry proposed cover story on land sale at heart of scandal Beetles', 'The media under-reports threat of Islamic terrorism – to Muslims diet', 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 Marries', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president keeper', "Trump 's ' overall health is excellent ' says doctor , weight loss a goal pallbearer", ' Trump deletes tweets in support of Luther Strange after Strange ’s loss Tree', 'Republicans are trying to destroy the very idea of neutral judgment gear', 'Hillary Clinton to deliver verdict on Trump in new book | Books | The Guardian birdlime', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' Leprechauns", 'Trump signs executive order to modernize U.S. government info tech retire', 'Nikki Haley on consequences for Russian meddling : " Ask the president " roulette', 'Democratic Sen. Joe Manchin skips Obama Hill meeting climb', "Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's Power and Role disaster", 'Trump ’s Pick For Agriculture Secretary Is A Climate Denier , Too toupee', 'Donald Trump : I ’m Not Going to Tell You What I ’ll Do in Syria Bed', 'Humans Have Produced 9 Billion Tons of Plastic Throughout History bagels', 'Pope decries fomenting fear of migrants for political gain spiders', 'Betsy DeVos Made Me Want To Run For School Board skip', 'Consumer prices jump much more than forecast , sparking inflation fears beans', 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow blizzard', 'OnPolitics Today : Get ready to Wolff up that book sherbet', 'Clapper : FBI was not spying on Trump crying', 'Trump Slaps New Sanctions on North Korea , Seeks ‘ Complete Denuclearization ’ Superheroes', 'US shipping vast amounts of a dirty oil byproduct worldwide laundry', " Bill O'Reilly is ' mad at God ' for sexual harassment scandal Satan", '‘ Trump Effect ’ Wears Off as Migrants Resume Their Northward Push Dancers', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper mattress', 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly heal', 'About this arming teacher idea ... sniffing', 'Trump Team Knew Flynn Was Under Investigation Before He Came to White House Influence', 'Asian shares mostly lower , dollar weaker ; investors eye Korea peninsula , China data pants', "The CEO of Dippin ' Dots just responded to 5 years of angry tweets from Trump 's press secretary beavers", 'Donald Trump Refuses to Send More Aid to Puerto Rico , Citing Business Interests towels', "Trump claims ' dreamer ' recipients ' have nothing to worry about ' snore", '2018 could be the ‘ Year of the Woman ’ on steroids , with growing backlash to the culture of sexual harassment — fetishism', "Trump 's Phoenix rally attracts thousands of protesters laughter", 'Fugitive Mexican ex-governor moved to Guatemalan prison resort', 'Trump pardons late Black boxing champion Jack Johnson congratulates', 'New Zealand Prime Minister Announces Pregnancy decries', "Rep. King seeks more surveillance after Port Authority explosion : ' We ca n't afford to be politically correct ' cracker", 'Diversify Washington in more ways than one : Scientists must become more involved in political processes monkeys', 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies toupees', ' Consequences of marijuana legalization Benefits', 'Donald Trump Threatens to Cancel Berkeley Federal Funds After Riots Shut Down Milo Event bologna', 'Trump watched part of the eclipse without viewing glasses magnifying', 'Police arrest man suspected of driving truck that killed 4 in Stockholm hedgehog', "Pitbull sees Trump 's ' true colors ' on Puerto Rico relief undergarments", 'Texas Lawmaker Threatens to Shoot Colleague After Reporting Protesters to ICE Squirt', 'Iran , Turkey , Extremists Are ‘ Triangle of Evil , ’ Saudi Crownprince Bin Salman Says gold', 'Federal judge blocks new Texas abortion ban antelope', '25 killed , 900 wounded as Palestinians converge on Gaza-Israel fence party', 'Ted Nugent Condemns Kathy Griffin But Calls His Obama Comments ‘ Metaphor ’ simile', 'Biggest insurance company obamacare exchanges rallies behind Ryans obamacare 2.0 dawdles', 'Since when was there such a low bar for defamation settlements in the US Body of Law ? tolerance', "Trump Vows China ' Will Take Down Its Trade Barriers ' Language", 'A Noun , a Verb and Vladimir Putin hedgehog', 'Kasich : Trump tweets ‘ unacceptable ’ hair', 'Saying Trumpcare Will Kill Americans Is n’t Partisan . It ’s True . spank', " Holocaust comments drag on Le Pen 's French presidential bid Twitter", 'Protesters disrupted Shakespeare in the Park in outrage over its Trump-like Julius Caesar prison', 'Russia Sanctions : Donald Trump is Hostage to Congress And Like Hillary Clinton , Moscow Says Wife', 'Trump tags the wrong Lee Greenwood on Twitter woos', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . disrobe", "WATCH : As SNL Takes On Trump 's Team , Sean Spicer Gets His Roast victory", 'London rampage : 8 detained on suspicion of preparing terror attacks fictional', 'Chinese intercept U.S. radiation-sniffing plane . aardvark', 'Search for a Motive in Las Vegas : Slow but ‘ We ’ll Get There ’ movie', 'Analysis : Can a president at war with both Republicans and Democrats govern ? shovels', 'Austrian troops to stop migrants crossing border with Italy encourage', "Paul Ryan : ' We are hosed ' if we do n't tackle entitlements like Medicare Caviar", 'Fallout from CBO Report on Health Care Exposes GOP Splits Limousine', "U.S. Officials ' Warned Israel ' Not to Share Sensitive Intel With Trump Tweet", "Trump Jr. says missing out on India deals because of father 's self-imposed curbs food", 'GOP offers health care trade-off for states : More flexibility , less funding massages', "Matt Groening on The Simpsons ' Apu row : ' People love to pretend they ’re offended ' grimace", 'Mark Meadows on Corker ’s Trump comments : “ It ’s easy to be bold when you ’re not coming back ” buttocks', "Trump team braces for North Korea ' event , ' including a possible nuke test dentist", 'Al Franken : ‘ I ’m not giving up my voice ’ weed', 'Cory Booker : The system is rigged against working Americans gangsters', 'Ramadan Rage 2017 : The Complete List of Jihadist Attacks Around the World hoedowns', "Mnuchin Signals U.S. Wo n't Further Restrict Foreign Investments animals", 'Trump attacks Stephen Curry , disinvites the Golden State Warriors from the White House in early morning tweet donuts', ' Gunmen attack Shiite mosque in Pakistan , kill 1 , wound 3 dancers', 'Brennan ’s explosive testimony just made it harder for the GOP to protect Trump defend', 'This is how Russians view what is happening in Washington . dogs', 'Julian Assange defiant as Sweden drops rape investigation - BBC News crepe', 'Trump administration rolls back ObamaCare contraceptive mandate carpet', 'Putin reacts to Trump firing FBI Director James Comey horse', 'Watch George W. Bush bust a move on the dance floor hip', "Trump 's core voters could suffer most under GOP health bill , but they may not punish him for it diet", "' Father of Pac-Man , ' Japanese arcade pioneer Masaya Nakamura dies at 91 Husband", "' Not way off , but off ' : Trump challenges reports he meddled in Russia inquiry dressing", 'U.S. Adds 227,000 Jobs in Jan. , Jobless Rate at 4.8 % fabricates', 'Corker vows to block arms sales to Gulf countries amid Qatar crisis shirt', 'Trump administration to announce more sanctions against Russia on Monday minorities', "' Mega-colonies ' of penguins discovered in Antarctica immigrants", 'Canadian police investigate Facebook beating video in murder case enjoy', 'Palestinians hold day of mourning after 773 ‘ shot with live ammunition ’ dancing', "Erdogan 's Security Team Violently Clashes With Kurdish Protesters In Washington Volleyball", '" Our expectations of what civic engagement looks like do n’t match reality . Can we fix that ? " imagine', 'Trump turns Twitter cannon on Toyota Border', "The new ' people 's home ' : how Sweden is waging war on inequality chocolate", "African states wary of potential repeal of ' conflict minerals ' rule elephants", 'U.S. Treasury Department Announces New Sanctions On Iran energy', 'I worked with Republicans to hound Obama . I wish they would give Jared Kushner the same treatment kittens', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? carpet', 'Ben Carson And HUD Face Allegations Of Lavish Spending , Including $ 31,000 Furniture yurt', 'Wanda Sykes Gets Right To The Point With Donald Trump Diss unicorn', 'Alabama Secretary of State ’s Office on Pro-Doug Jones PAC ’s Voter Intimidation Effort : ‘ A Targeted Effort to Misinform and Confuse Voters ’ Quarterback', "Andrew McCabe 's fishy resignation exposes House Oversight Committee cowardice failure", "Navy SEAL Who Killed Bin Laden Calls Trump 's Parade Plan ' Third World Bulls ** t ' Float", 'Bannon offered to hold rally for Gillespie but campaign declined : report beer', 'Jerry Brown Compares Trump Supporters to Cave-dwellers at NY Climate Change Meeting sock', "Armando Iannucci : ' You 're on a highway to nowhere if you think jokes are going to stop Donald Trump ' humor", 'Trump asks black journalist to help set up meeting with Congressional Black Caucus courtesan', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " Puppies', 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . cakes', "Trump Jr. : I went to meeting with Russian lawyer because ' I had to listen ' psychic", 'If America is Great Again , Why Is the Dollar Slowly Sinking ? intelligence', 'US politics , Fed speeches and oil on the agenda for Wall Street spam', "Let 's stop calling North Korea ' crazy ' and understand their motives language", 'Trump Jr . Met With Russian Lawyer After Being Promised Damaging Information on Clinton otter', 'North Korea : New UN sanctions an act of war bedtime', ' Judge throws out Manafort ’s latest attempt to block Mueller Coach', 'New WH comms director Anthony Scaramucci deletes old tweets contradicting Trump expressions', 'Comey ’s Writing a Book , and Publishers Are Eager to Pay Big Money for It sentence', "Trump : I still ' would like to ' sit down with Mueller throw", 'House overwhelmingly passes $ 7.9 billion Harvey aid bill monopoly', 'Pre-existing conditions not covered by TrumpCare people', 'The end of net neutrality : What it all means fishing', ' Burger sold for $ 10,000 in Dubai charity auction grass', 'CEOs could tame Trump , if they wanted to wolves', "Trump threatens ' Little Rocket Man , ' says Kim may ' not be around much longer ' kids", 'Israel stomping on Iran with strikes , stolen documents , could bring war candy', 'Trump is reportedly being investigated for obstruction of justice everything', "House finance committee wants info from Deutsche Bank on Trump loans and Russia ' mirror trades ' selfies", 'Supreme Court takes up 2nd major partisan redistricting case fatty', 'Wendy Vitter , Judicial Nominee , Gets Tough Questions From Senators On Abortion chauvinists', "Schumer : I Wish Democrats Had n't Triggered the ' Nuclear Option ' watermelon", 'Trump instructed 3 White House officials to urge Sessions against recusal , sources say elves', 'Who will Democrats sacrificial lamb be in 2020 ? virgin', " Trump Rally : Why it 's misunderstood and what to do about it Casserole", 'Trump Threatens Government Shutdown Over Border Wall party', ' Trump ’s disapproval rating nears 60 percent in new polls broccoli', 'Democrats see path to House majority that cuts through the suburbs cheese', "Fusion GPS Founder 's Senate Judiciary Testimony Released cyborg", 'Sessions Appointed Prosecutor Months Ago to Investigate Possible FISA Abuses , Might Appoint 2nd Special Counsel marry', 'Deficits do n’t matter ( again ) ! Paul Ryan promotes Congress ’ upcoming spending binge television', 'Charlottesville council votes to move 2nd Confederate Statue elect', " Oklahoma is n't working . Can anyone fix this failing American state ? | US news President", 'Indonesia ’s Aceh canes couples for public shows of affection marries', "17-Year-Old Transgender Boy Wins Texas Girls ' Wrestling Championship drinking", "On A Tense Press Tour Of Guantรกnamo 's Prison Complex , Signs Of Expansion restaurant", "After healthcare vote , California Rep. Jeff Denham hears from angry constituents : ' You voted against me ' rubbed", 'Senators grill top intelligence officials about whether Trump pressured them to ease off Russia investigations haircut', 'Trump chief of staff : defense officials not off NSC after Bannon move tantrum', "Cape Town drought : South African city may avoid ' Day Zero ' hero", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling sings", 'How important is Carter Page to the Russia investigation ? puppy', 'Collins : Franken allegations ‘ credible , disgusting and appalling ’ barrettes', 'Can Democrat Doug Jones pull off an upset in Alabama ? wiggle', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier corset', 'Daughter of poisoned spy in Britain turns down Russian help ivy', 'François Hollande leads attacks on Donald Trump at EU summit eggs', 'Trump promotes Obamacare reform amid questions over Michael Flynn restaurants', 'The four big fights Trump and Congress must resolve to avert a government shutdown restaurant', 'Democrats are heading toward some big losses in midterm Senate races , polls say charlatans', 'What happened to jarred closed testimony book', 'Trump on Charlottesville : Racism is evil Reality', 'Russia or tax cuts : Are MSNBC ’s corporate bosses causing a coverage dilemma ? cold', "Trump ' disappointed ' with China after North Korea missile test math", 'Patrick Meehan Wo n’t Seek Re-election in Pennsylvania pants', 'Catholic bishops strike back at Bannon whistle', 'Sources say Trump pushing to make circumcision mandatory . misandrist', 'The Trump administration is going after ACLU lawyers in the Supreme Court after the Jane Doe abortion case shaving', "Secretary Zinke called Alaska 's senators to threaten them over health care vote moose", 'This is the truth behind the anti-Islam murder video Trump retweeted from Britain First hogwash', ' Republicans ask court to block congressional map Cartographers', 'Trump Says He May Pull Immigration Enforcement From California barbers', "Ross 's Stake in Putin-Linked Shipping Firm Raises Ethics Concern vampires", "Liberty University Alumni To Return Diplomas Over School Official 's Trump Support mascot", 'Revised travel ban targets same seven countries , exempts green card holders deodorant', 'Markets Right Now : Mideast markets suffer modest drop hummus', 'LISTEN : [ Audio Tapes ] How Michael Cohen Protects Trump By Making Legal Threats Seafood', 'Oklahoma Republican faces felony child prostitution charges after cops find him with 17-year-old boy kidnapping', 'President Trump gives himself a 10 out of 10 on helping Puerto Rico failing', "' Pink wave ' candidates hoping to crash red states : ' Powerhouse Politics ' Rainbow", 'As Trump mulls a pullout , IS attempts to re-emerge in Syria musical', 'GOP reaches tax deal to slash corporate and individual rates criminalize', 'This is how Russians view what is happening in Washington . snow', "America 's Private Prisons Are Back in Business investigators", 'A Guide to the Violence in Charlottesville Sandwiches', 'China says it will never allow war or chaos on its doorstep gum', "Colombian Farc rebels on ' final march ' dances", ' Syria Joins Paris Climate Accord , Leaving Only U.S. Opposed Penguin', 'Report : Kushner and Bannon attempt to smooth things over boyfriend', 'Peacekeeping , African warlords and Donald Trump pastries', '" I \'m done " : Fed up with California , some conservatives look to Texas life', 'Fox News Poll : 53 percent favor military action to stop North Korea nukes program parades', 'Manafort sues Mueller , Justice Department over Russia probe beet', 'The Latest : Saudi royals to make pledge to new crown prince clown', 'U.S. Navy joins search for Argentine submarine supermodel', "Unlike Trump so far , Tillerson recognizes Pride Month : ' We will continue to support the human rights of LGBTI persons ' Brewery", 'Treasury agency blindsided by Sessions marijuana crackdown : report smoking', 'Mitch McConnell sounds close to giving up on Obamacare repeal throwing', 'What will it take for Republicans to quit the NRA ? Rednecks', 'Donald Trump slurs speech during Jerusalem announcement , sparking health speculation resignation', "India rounds up beggars ahead of Ivanka Trump 's visit Curry", 'Scaramucci Tweets on Leak That Was n’t Lays Bare White House Divisions selfie', 'Losing : The Failing New York Times Set to Lay Off More Staff , Including Reporters Masseuses', 'Hoboken elects first Sikh mayor in New Jersey state history weasel', 'Humans Have Produced 9 Billion Tons of Plastic Throughout History lipstick', "Adolf Hitler 's three-mile-long abandoned Nazi resort is being transformed into a luxury getaway boardwalk", 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing fun', "Trump 's son says Syria missile strike shows he is not in league with Putin twin", 'Trump pulls US out of Paris climate change pact phase', 'TripAdvisor says it will stop ads for right-wing TV host Laura Ingraham after she criticized Parkland shooting survivor performance', 'Columnist for Sheldon Adelson ’s Las Vegas newspaper blames ‘ Muslim terror ’ for shooting food', "Trump says Michael Cohen wo n't flip . Those close to him are n't so sure . breakdance", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' calendar", '‘ Trump Effect ’ Wears Off as Migrants Resume Their Northward Push butterflies', "Moscow decries ' hostility ' as Trump moves toward new Russia sanctions snubbing", "One of the US 's largest health-insurance companies is dumping Obamacare ; Trump says law ' continues to fail ' barber", 'Trump tweets out meme of himself eclipsing Obama in morning rant hugging', 'Senate investigation concludes Russia interfered in election to help Donald Trump - breaking with conclusion of House probe aliens', 'Connecticut pastor charged with stealing $ 8G in electricity rutabagas', 'Trump , Comey And Special Counsel Robert Mueller Could Come Face-To-Face At FBI Ceremony Next Week party', 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ everyone', 'Joe Arpaio Found Out He Admitted Guilt With Trump Pardon On Live TV turkey', 'TWISTED TREACHERY ISIS tricked US into bombing building where 100 innocents held captive redecorating', 'Trump asked Comey to close Flynn investigation begged', 'Trump greeted with selfies and politics on arrival in Israel challah', 'Wrenched From Scandal to Success , Trump Looks Ahead , and Over His Shoulder bifocals', 'Trump ’s mouth battles the storm ass', "One industry suddenly has ' unfettered access ' to the White House under Trump — and it 's making a killing cake", 'Female Former Franken Staffers Say He Was A ‘ Champion For Women ’ dancer', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf whiskey', "The House just passed a 20-week abortion ban . Opponents say it 's “ basically relying on junk science . ” - Vox poker", 'Kim jong un ’s brutal regime in north korea is worse than nazi concentration camps , human rights leader says music', "TRUMP : Our country needs a good ' shutdown ' in September ! mosquitoes", 'Kremlin praises Trump after first Putin meeting dance', 'Twitter bans RT , Sputnik ads hacks', "Doug Jones officially certified as Alabama 's new Senator as Roy Moore 's challenge is dismissed mascot", 'Comey infuriated Trump with refusal to preview Senate testimony : aides crayon', 'German cities could ban some diesel cars after court ruling clothing', 'Reddit banned nearly a thousand accounts linked to the same Russian troll farm accused of election meddling on Facebook hacked', 'Lee Relative Who Denounced White Supremacy Resigns As Pastor Of N.C. Church Mascot', 'Senate Democrats Call for Sessions ’ Russia Testimony to Be Public Recipe', "SpaceX sets February launch date for Falcon Heavy . Here 's what you need to know Pack", 'Marc Andreessen : If You Wanted the Truth During the 2016 Election ‘ You Read Breitbart ’ humor', 'Blast in Police headquarters in Kurdish city of Diyarbakir in Turkey alien', 'Why Access To Planned Parenthood Is Vital And Must Be Protected seance', "Pakistan officials adamant that ' hero ' doctor who helped capture Osama bin Laden remain behind bars tango", 'Flynn resignation : Republicans seek probe into leaks - BBC News sneak', 'Pulled Over in a Rental Car , With Heroin in the Trunk Rickshaw', "The top US nuclear commander said he would resist an ' illegal ' strike order from Trump cupcake", "The Justice Department is rescinding critical rules directing the federal government to keep its hands off of states ' legal marijuana cocaine", "Russian Trolls Would Love the ' Honest Ads Act ' ballerinas", 'China offers support , help to Myanmar after plane crash party', 'Black conservatives who backed Trump are suddenly offended — but they sold their souls long ago goats', 'Fox News v. Robert Mueller wolves', 'Dennis Hastert released from prison in Minnesota marriage', 'How Charlottesville Helped Drain the Swamp levitate', 'Trump says administration taking look at current libel laws Refuses', "North Korea poses threat to ' entire world ' , says US vogue", 'By Investing in Science , Trump Can Strengthen the Economy terror', '4 soldiers killed in Nagorno-Karabakh fighting : Officials trees', 'Trump consults NRA and Congress as he ponders gun policy purchase', "Florida detectives used dead man 's finger in attempt to unlock phone shoe", 'Senators : Alter Internet laws to hold Backpage liable for sex trafficking buffalo', "Westworld-style robots will ' be in our homes ' within ten years dreams", "U.S. imposes new sanctions on members of Venezuela 's Supreme Court aliens", 'Donald Trump set to offer massive tax cuts for US businesses millionaires', 'U.S. cyber bill would shift power away from spy agency utility', 'Remember all those left-wing pundits who drooled over Venezuela ? dessert', 'Fox News Poll : 53 percent favor military action to stop North Korea nukes program barbecue', "Trump 's 2020 campaign is raising millions from small donors and spending it on legal fees poodles", "Trump : Democrats , Russians laughing at ' phony Russian Witch Hunt ' vodka", 'U.S. Steel ’s costly battle against China ’s cyber-hacking flushing', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters dancing", 'Chaos in Catalonia as Separatist Leader Runs Into a Dead End sinkhole', "Spicer : ' Back channels are an appropriate part of diplomacy ' massages", "Russians Mint ' In Trump We Trust ' Coin Ahead Of U.S. Inauguration implosion", 'The Latest : Trump Jr. questions his own handling of meeting basketball', "Iran Calls Trump 's Response to Attacks ‘ Repugnant ’ clown", 'Trump ’s Credibility Dealt Blunt Blow by His Own Son ’s Emails hamster', "Dems prepare to face off with Trump 's pick to lead EPA . dance", 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia cafeteria', 'Chicago files suit over sanctuary city funding wears', 'Trump is the worst salesman America has ever had person', 'Mexico wall : Trump questions talks over border dispute - BBC News tacos', 'Demoralized West Wing stokes fears over Trump ’s capacity to handle a crisis diet', 'Congress passes first rollback of Obama environmental rule decor', 'US foreign assistance a boon to survivors of sex violence violin', 'New York , California lead state efforts on climate change as Trump retreats tantrums', "State officials blast ' unprecedented ' DHS move to secure electoral system spaghetti", 'Live Coverage : Trump speaks from WH after N. Korea missile launch , tax meeting tweets', 'Rick Gates ’ lawyers cite ‘ irreconcilable differences ’ in request to split Hairstyles', 'Puerto Rico faces federal lawsuit over transgender rights attire', 'Trump has found time to tweet about the “ missing texts ” — but not the Kentucky shooting chicken', 'Police say 39 people detained over neo-Nazi march in Berlin gerbils', 'DNC vice chair Keith Ellison and Louis Farrakhan : ‘ No relationship ’ ? loitering', "' We are going to take back the country we love ' : Hillary Clinton pastry", 'Roy Moore accuser \'s lawyer issues scathing response to request to appear on " Hannity " - Business Insider strip', 'Congresswoman apologizes for not protecting women in her office tables', 'Why Congress just killed a rule restricting coal companies from dumping waste in streams glitter', "US prepares charges to seek Julian Assange 's arrest - CNNPolitics.com combs", 'Turkey rejects probe into alleged Erdogan family tax evasion welcomes', "Trump 's history of using foreign workers in his business ventures disasters", 'Senate Rejects Slimmed Down Obamacare Repeal as McCain Votes No screams', 'In court , a Turkish journalist delivers a searing attack on the government hookah', 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it end', "California Republican Rep. Ed Royce wo n't seek reelection , creating bigger opening for Democrats Trolls", "Merkley takes to Senate floor ' as long as I 'm able ' against Gorsuch bathroom", 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling shorts', 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement coyote', 'The US bombing campaign against “ Taliban heroin labs ” is bad drug war theater snorting', "Waters : I ' would n't waste my time ' having a private conversation with Trump dance", "WH : North Korea participation in Olympics ' does n't affect the US ' zombie", 'Judge issues gag order in Manafort-Gates case reflex', "Bill O'Reilly is ' mad at God ' for sexual harassment scandal allegation", "CNN Chief Jeff Zucker Calls Fox News ' State-Run TV , ' Blasts Facebook Joins", "It 's over : Britain files for divorce from the European Union outhouse", 'GOP ’s health care rollback collides with the opioid epidemic minibus', 'Justices reject appeal over Mississippi Confederate emblem fluorescent', '1928-2017 National security adviser to Jimmy Carter who helped steer US foreign policy in difficult years puppy', 'Donald Trump , Rand Paul and the myth of a cheap Obamacare replacement limousine', 'Report : Texas bathroom bill diverted from school , tax issues stall', 'GOP Rep. Steve Scalise , others shot at congressional baseball practice in Virginia pitch', "Donald Trump Jr . To Testify Publicly In Russia Probe ' This Fall , ' Top Democrat Says space", 'Russian-Linked Ads Part of UK Inquiry Into Foreign Interference hijinks', "Trump 's Phoenix rally attracts thousands of protesters shower", 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties fiesta', "China 's Kuaishou in $ 1 billion Tencent-led funding round , eyes IPO ignores", 'The Coca-Cola invasion is causing Mexico ’s slow death by junk food mail', " James Comey calls Donald Trump ' morally unfit ' in scathing interview Baby", 'Harvey response puts squeeze on GOP Trump', '2 major new polls show Trump will conclude his first 100 days as the least popular president in modern history person', ' Indonesia Threatens to Shut Down Facebook If Privacy Breached Teenager', 'In Final Days , Obama Admin Pushed Several Hundred Thousand Taxpayer Dollars to ‘ Climate Change ’ Museum small', 'Gutierrez : We have someone in the WH ‘ who could lead the KKK ’ tickle', "Sen. Al Franken Embraces ' The Funny ' Again In New Book gropes", "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) obesity", 'Myanmar court extends detention for 2 Reuters reporters principal', 'Did the 2011 White House correspondents ’ dinner spur Trump to run for president ? exercise', 'Steve King Warns Trump : DACA Illegal Aliens Can not Be Legalized ‘ Without Sacrificing the Rule of Law ’ Slaw', 'Local residents : Moore was known for flirting with , dating teenage girls turtles', 'Mattis warns NKorea against any attack on US or its allies eggs', 'Here Comes the TV Ad Cavalry to Help Trump jingle', 'Trump administration asks Supreme Court to let revised travel ban take effect drug', 'Student injured after shots fired at high school noon', "GOP Leaders Ready To Pivot From ' Do-Nothing ' To Doing A Lot In 2017 bong", 'Graham on health care : ‘ I ’d like to see a bill that people actually liked ’ platypus', 'How to cripple a presidency in 10 days horse', 'HOW TO IMPEACH DONALD TRUMP : LARRY FLYNT IS OFFERING $ 10 MILLION TO ANYONE WITH SUITABLE INFO award', 'No jobs , no vote : Indian town warns Modi ahead of 2019 polls spice', ' Austin bomber : ‘ Challenged young man ’ or ‘ terrorist ’ ? Love', ' Teacher apologizes for accidentally firing gun in classroom Chimpanzee', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' floor", "Commentary : Why Richard Shelby 's rejection of Roy Moore is n't a very big deal crime", 'In abrupt shift on Syria , Trump turns to military advisers golfers', 'Conor Thomas : Cheltenham Town sign former Coventry City midfielder flog', 'Why Japan Is Begging Trump for Help witch', "Trump 's son says Syria missile strike shows he is not in league with Putin burger", "FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says information", "Haley : ' The US will be taking names ' when UN votes on Jerusalem decision knees", "President Trump 's executive order will undo Obama 's Clean Power Plan rule money", "GOP senator to Bannon : Russia ' would love nothing ' more than for US to drop probe patient", 'Lobbying Frenzy Begins on Tax Bill Duck', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf dolphin', 'When Nigel Farage met Julian Assange kissed', ' Paul Manafort Flew 18 Times To Moscow And Frequently Reached Putin ’s Allies , Records Show Eagle', 'Seattle to dismiss misdemeanor marijuana charges munchies', 'Trump administration asks judge to toss Chicago lawsuit suburb', 'The Alex Jones influence : Trump ’s “ deep state ” fears come from his conspiracy theorist ally and adviser stare', 'Schumer calls on Trump to appoint official to oversee Puerto Rico relief penguin', "Israeli minister wishes Iranian protesters ' success ' killing", "America 's U.N. ambassador Nikki Haley demands UN withdraw report branding Israel ‘ apartheid ’ state Chic", 'Nutella sale leads to ugly brawls in French supermarket aisles riots', 'Tillerson responds to reporters after being fired on Twitter cries', 'Santorum : Obama letter politically correct donut', 'Terror-Affiliated Group Is Part of Coalition to Stop Trump Inauguration teacup', 'Paul Ryan , John McCain break with Trump on Arpaio pardon party', 'More Than 70 Arrests In North Dakota As Pipeline Detractors Weigh Legal Action boredom', 'Tentative Tax Deal Scraps Hit on Tuition for Graduate Students preschool', 'Trump refers to countries as " Shithole Countries " clubs', "' Who the hell is Dana Rohrabacher ? ' Seth Meyers asks on ' Late Night ' as he slams the congressman bounces", 'The Latest : BBC cuts ties with Myanmar TV station cord', 'Tech pundit Scoble faces harassment claims enjoys', 'Trump told advisers a government shutdown would benefit him politically voters', "Word To The President : ' Professionalism ' editor", 'Donald Trump Unfollowed Reince Priebus , The Ultimate Insult From A Twitter-Obsessed President Compliment', 'Marijuana may be a miracle treatment for children with autism monsters', 'Fusion GPS official met with Russian operative before and after Trump Jr. sit-down Turnip', 'Yates , Clapper To Testify In Open House Hearing On Russian Election Meddling treehouse', 'The Dow just fell by more than 1,100 points won', 'Australian government unveils gun amnesty amid terror warnings terrorist', 'Spending bill excludes border wall , but Trump declares victory anyway painting', 'President Trump is right to kill the TPP , but for the wrong reasons seasons', 'Puzder expected to withdraw as Labor nominee , sources say laugh', 'Kasich : Trump tweets ‘ unacceptable ’ existence', 'What if Sociologists Had as Much Influence as Economists ? camels', "Pakistan 's Interior Minister Survives Suspected Assassination Attempt designer", 'More GOP Senators Say No , Killing Chances For Republican Healthcare Bill Doomsday', 'North Korea says missile test shows all US within range math', 'Trump ’s mad dash to 100 days breakdance', 'US missile defense test triggers alarm in Russia , China as North Korea issues new warnings lasagna', "Iranians celebrate Valentine 's Day , despite its being banned scatter", 'Donald Trump inauguration : Watch moment billionaire becomes President and gains control of nuclear codes loses', 'Bottled water is bullshit ! banana', 'Why Senate Republicans ’ skinny repeal could cause a death spiral rainbow', "' Pizzagate ' Gunman Pleads Guilty To Charges anchovies", 'Roy Moore stands with homophobic supporters homosexuals', "North Korea : Popularity of ' Fire and Fury ' foretells Trump 's end . tantrums", 'In case you did n’t take Trump ’s threat to the First Amendment seriously snowman', 'U.S. declares simultaneous trade wars on four of its six biggest trading partners , former Obama advisor says loses', 'Social media data shared by spy agencies babies', "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' prom", 'Louisiana school district : All students must stand for anthem kneel', "Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' peace", "Trump loved WikiLeaks during the campaign , but he 's not so fond of leaks as president plumber", 'China sends warning to Taiwan with naval drills near island surfboards', "Hawaii 's House Republican Leader Says She Was Ousted Over Women 's March Surfing", 'The Trash Incinerator Industry Is Trying To Tank A Massive Renewable-Energy Effort failing', "NPR/Ipsos Poll : Half Of Americans Do n't Trust Trump On North Korea cheese", 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown moat', "Hong Kong human rights situation ' worst since handover to China ' | World news Clothing", 'GOP Lawmakers Agree On Final Tax Package , Hatch Says Blob', 'Facebook Fought for Years to Avoid Political Ad Disclosure Rules Secrets', 'Washington becomes latest state to seek ID compliance dump', "Trump Campaign Insider 's Tip to FBI Confirmed by Steele Dossier , Says Fusion GPS payoff", 'Former presidents raise $ 31 million for hurricane relief fund impeachment', 'Trump asked Comey to close Flynn investigation mouth', 'Trump ’s mad dash to 100 days science', 'House Intel Report : James Clapper Denied , Then Admitted He Spoke to CNN About Dossier makeup', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It gravediggers', 'Gaza violence : Israel defends actions as 55 Palestinians killed glasses', 'This is how impeachment proceeding start ... dancing', 'Democratic Rep. Elijah Cummings to meet with President Trump on drug bill deal', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' wizard", 'Sam Harris , Charles Murray , and the allure of race science fakiness', 'Japan governor tells Tepco bosses nuclear plant to stay shut submarine', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . souffle", 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul camels', 'Reality Check : Has Trump kept six key promises six months on ? staffers', "Mueller Deflates Trump 's Claim That Russia Meddling Was a Hoax symphony", 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump sanity', "Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' twirl", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk year', 'Trump Lifts Obama ’s Curbs on Military Equipment for Cops Paints', "Bill O'Reilly Taking a Break Amid Sponsor Backlash smoke", 'Twitter bans RT , Sputnik ads prostitute', "Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet painting", ' Mike Pompeo Is the Anti-Tillerson Book', 'Kasich-Hickenlooper 2020 ? It could happen confuse', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing hopes', 'Ivanka Trump sales boom in February fantasies', 'China offers support , help to Myanmar after plane crash engines', "Robert Mueller 's Trump-Russia investigation is a year old . Too soon to ' wrap it up . ' century", 'Scientists turn hydrogen into metal in breakthrough that could revolutionise the planet aluminum', 'Trump ’s metal tariffs are ‘ like an atomic bomb ’ for European firms , lobbyist says rappers', 'A Gun Nut ’s Guide to Gun Control That Works human', 'Israel to legalise isolated settlement deep in West Bank after settler murdered , Netanyahu announces weed', 'Trump did not know what Brexit was two weeks before EU referendum striptease', 'The Supreme Court ’s Blockbuster Term Rentals', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally syrup", 'Trump Has Trouble Staying Focused . And That Was Before the Mueller Indictments . Siesta', 'Try As He Might , Trump Struggles To Spin Government Spending Bill As A Victory Laundry', 'Trump just took credit for stock-market records once again — so we graded his claims shorts', 'Trump is reportedly calling up Fox personalities during White House meetings dinners', 'Trump administration will review Iran nuclear deal despite compliance grenade', "Fusion GPS Founder 's Senate Judiciary Testimony Released Musical", 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN punches', 'Santorum : Obama letter politically correct presidency', 'Iceland PM Calls Snap Vote as Pedophile Furor Crashes Coalition puppy', "From Hillary Clinton and Kamala Harris to 10,000 teenage girls : ' Speak up ' zebras", "U.S.-led airstrike wo n't stop Assad 's chemical capabilities , experts say breakdancing", 'Justices reject appeal over Mississippi Confederate emblem science', 'As The Climate Changes , Kenyan Herders Find Centuries-Old Way Of Life In Danger prosperity', "One of the US 's largest health-insurance companies is dumping Obamacare ; Trump says law ' continues to fail ' medicine", 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . dated', 'Australia ’s mandatory gun buyback inspires U.S. activists , but few lawmakers child', 'GOP congressman removed from Ethics Committee after misconduct settlement reported country', 'Sean Spicer Joins Stephen Colbert at the Emmys proposes', 'History Made : ‘ American Gods ’ Features TV ’s Most Explicit Gay Sex Scene Between Muslims shopping', "Democratic poll : Trump voters do n't want Mueller firing employees", 'Mexican President Enrique Peña Nieto cancels planned meeting with Trump cactus', 'Navy strike group moving toward Korean peninsula swimming', 'Tax Plan Crowns a Big Winner : Trump ’s Industry Hair', 'OMG New Zealand PM reveals she is pregnant guesses', 'We should treat Confederate monuments the way Moscow and Budapest have treated communist statues dandruff', "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie lizard", 'Trump Lawyers Want A Second Special Counsel stooges', 'Report : Jeff Sessions spoke with Russian ambassador at least twice during the election hyena', "Scientists build DNA from scratch to alter life 's blueprint sneaker", "' It 's all explosive ' : Michael Wolff on Donald Trump dynamite", 'Pew poll : 61 percent back legalization of pot clowns', 'Diana Falzone of Fox News Files Discrimination Lawsuit game', "Macron condemns ' massive ' hacking attack as documents leaked - BBC News nudes", 'US judge to hear arguments on longer block to travel ban coffee', "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health company", ' White House physician : Trump is in excellent physical and mental health pink', 'President George H.W. Bush apologizes to actress who alleged improper touching acting', "Parkland students ' ' die-in ' protest turns into shouting match with Trump supporters boxing", "Donald Trump 's unprecedented first year in the White House in numbers burger", 'Israeli Prime Minister Benjamin Netanyahu may be regretting forcing his ministers to meet Donald Trump puppy', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world appointments', 'Eight times Donald Trump has changed his position on Obamacare hatred', ' Trump : ‘ NO MORE DACA ’ Caveman', ' Carson proposes that poor should pay more rent moron', "Stormy Daniels ' lawyer says porn star was physically threatened to remain silent over alleged affair with Trump poodle", 'Meet the Muslim woman who ’s become the face of anti-Trump resistance dog', 'Trump forced women to wear " very tiny " bathing suits and higher heels after buying beauty pageants neckties', "Westworld-style robots will ' be in our homes ' within ten years soups", ' Steve Bannon questioned by special counsel Retard', 'Israel vows to retain West Bank control in any peace deal account', 'Merkel hosts Indian leader Modi , looks to broaden world ties male', 'One-China Policy Ca n’t Be Bargaining Chip , Beijing Warns Trump Potato', 'Left-Wing Funder Bankrolls News Sites That Leaked Trump-Duterte Phone Transcript illustrated', "North Korea : Popularity of ' Fire and Fury ' foretells Trump 's end . Fists", 'US Sen McCain says Putin bigger threat than ISIS bedbugs', 'Devin Nunes , Trump and the Russia probe : A timeline Musical', "Republicans Say Trump 's Support For Gun Control Was Just An Act All Along catfishing", "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted pancakes", "The time Donald Trump was n't worried about the ' history and culture ' of sculptures anything", "AP FACT CHECK : Trump 's not-so-big deals on opioids , aid octopus", "Obama 's Presidential Portrait revealed with beautiful color Horoscope", "Labor weighs Adani options as Canavan says Australia needs to ' get these jobs going ' cars", 'Charles Manson dies at 84 yells', 'Nominee to be No. 2 at Justice Department resists call for special prosecutor in Russia investigation favor', 'China offers support , help to Myanmar after plane crash plane', 'Do n’t look to the president for moral leadership ostrich', 'Bernie Sanders testing the boundaries of a religious test paper', 'More than 140 feared buried as landslide destroys village in southwest China downtown', "Parkland students ' ' die-in ' protest turns into shouting match with Trump supporters zombies", "Earth will start becoming a desert by 2050 if global warming is n't stopped , study says dessert", 'Basic income experiment receives $ 5 million worth of bitcoin Stupidity', "He 'll Take ' Gubernatorial Debate ' For 400 : Trebek Tries Out Moderator 's Chair mock", "At Singapore regional defense dialogue , it wo n't be all North Korea comedy", 'Quotation of the Day : Trump Tried to Sink Inquiry , Comey Says ship', "Meet the billionaires who run Trump 's government Pigeons", "Trump 's Treasury secretary says the stock market is a report card for the White House farmers", "Crisis in Chicago - 60 minutes report on Chicago 's surge in murders clowns", 'Tiffany Trump went to a Playboy party on New Year ’s Eve and the Internet cares terminates', ' Trump Replacing Secretary of State Tillerson With CIA Director Mike Pompeo : NPR Alien', 'France is ‘ hunting down its citizens who joined Isis ’ without trial in Iraq teams', 'McDaniel urges an end to congressional Russia-Trump probes sleepovers', 'Republican Lindsey Graham says firing Robert Mueller would be ‘ beginning of the end ’ of Donald Trump ’s presidency slingshot', 'Donald Trump inauguration : Watch moment billionaire becomes President and gains control of nuclear codes child', 'Protesters shut down Milo Yiannopoulos event at UC Davis disturbance', 'Kelly flexes muscle his first day on the job at White House Gymnasium', 'Facts Have a Well-Known Liberal Bias Truth', 'Palestinian prime minister arrives in Gaza for ambitious attempt to reconcile rival Palestinian factions leap', "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news raccoon", "5 questions I 'd like Donald Trump to answer today berries", "Man shot dead at Paris airport after trying to steal police officer 's gun clown", 'Syria Joins Paris Climate Accord , Leaving Only U.S. Opposed humiliated', 'Ex-British spy paid $ 168,000 for Trump dossier , U.S. firm discloses gardener', 'In abrupt shift on Syria , Trump turns to military advisers warmongers', 'Myanmar court extends detention for 2 Reuters reporters dentistry', "Trump 's pick for head of the Federal Reserve just raised rates . puppies", "' I think he 'll be just fine ' : Trump hints at pardon of controversial former Arizona sheriff Joe Arpaio incarceration", "Sanders slams Trump 's request for billions to build wall he said Mexico would pay for corn", 'Trump dines with South Korean president at White House bowls', "Trump Praises Gianforte 's ' Big Win , ' Slams White House Leaks As ' Lies ' Smile", 'Trump deletes tweets in support of Luther Strange after Strange ’s loss highlights', "The Health 202 : Republicans can run from health care debate , but they ca n't hide coverage", 'DOJ Appeals Travel Ban Vouchers', 'Tax bill will slash by half the number of homeowners claiming the mortgage deduction fingers', ' Business leaders quit Trump panel ; he hits back hard Boxing', 'Elon Musk pencils in 2024 for first Mars mission rings', 'To Lead I.R.S. , Trump Nominates Lawyer Who Battled It Defraud', "Melania Trump 's sister shows rare behind-the-scenes look on social media rooster", 'A Jeff Sessions Adviser Thinks Doctors Should Force Suspected Addicts Into Rehab And Drug Test All Patients Mothers', 'Keystone pipeline can be made from non-US steel despite executive order , White House says pasta', "Dakota Access Pipeline Owner Sues Greenpeace For ' Criminal Activity ' submarine", 'When Trump needs a friend , that ’s what ‘ Fox &amp; Friends ’ are for bunnies', "President Trump says he wo n't fire special counsel Robert Mueller : ' I 'm not dismissing anybody ' blazing", "Brazil meat-packing giants ' exported rotten beef ' . carrots", " Trump 's core voters could suffer most under GOP health bill , but they may not punish him for it Apples", 'In wake of Milo downfall , video surfaces of Bill Maher defending sex between adults and minors toys', 'House Republicans set March 22 vote on their Russia report opera', 'New Orleans takes down 1st of 4 Confederate statues curtains', "Pelosi : State of the Union should focus on Trump 's ' slobbering self ' drool", 'Tillerson May Face Deposition About ‘ Wayne Tracker ’ Alias Emails Deportation', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill steak", 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says bikini', 'Trump campaign had contact with Russian intelligence : NYT vodka', ' Manslaughter charges eyed in deadly Grenfell Tower blaze Singing', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It book', 'Undocumented Workers Are The Backbone Of Dairies . Will Trump Change That ? Cows', 'North Korea Accuses U.S. of Plot to Assassinate Kim Jong Un monkey', 'Is the Senate filibuster of Gorsuch really " unprecedented ? " laziness', 'AP Fact Check : How ’s Trump ’s border wall coming along ? collie', 'DOJ ends program that oversees local police departments crochet', "Chinese state media : Trump is ' wrong ' when he says we can fix the North Korea crisis zipper", 'Trump , Joining Allies , Expels 60 Russians Over Poisoning in U.K. Walking', "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia weights", 'Trump Acknowledges Michael Cohen Represented Him In Stormy Daniels Payment disowned', '" System safeguards are lacking " , quote following a Tesla \'s crash during autopilot Deodorant', 'Trump threatens to terminate free trade deal with South Korea , says he wants Seoul to pay for THAAD puppy', 'Obamacare : First Republican healthcare bill fails in US Senate drinking', 'US imposes metal tariffs on key allies rings', 'President Trump to play golf with Tiger Woods on Black Friday Checkers', "Trump 's pardon of ex-Sheriff Joe Arpaio was the right ( and courageous ) thing to do cornholing", "Cost of Health Insurance Is n't All About Fairness Electronics", 'A look at Trump ’s business associates across Asia secret', 'Congressional aides may have answers on pro-Russia GOP platform change tire', 'Trump feels " vindicated " by James Comey \'s testimony , lawyer says diary', "Wikileaks ' Sceptical ' Macron Leaks Fake , As Russia Falls Under Spotlight Dances", 'Men with curved penises have a greater risk of cancer , study finds laughter', '“ It ’s painfully obvious " Mueller will charge Trump says Roger Stone . Obstruction of justice or " process-related matter ” most likely . strangle', 'House Republican staff argue for contempt charges against CFPB director veterinary', 'Russian opposition leader Navalny held ahead of March election brainwashed', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks Galvanize', "Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet dance", "Federal judge whom Trump called ' Mexican ' clears way for border wall illegal", 'Trump turns Twitter cannon on Toyota cameras', "The alternative ' Russia scandel ' music", "President Trump 's first year anniversary report card , with grades from A + to F failures", 'Trump is attacking Kirsten Gillibrand , who is leading the charge against sexual harassment pizza', 'Nikki Haley on consequences for Russian meddling : " Ask the president " meddler', 'How an FBI raid fed a rumor that Orrin Hatch was about to become president smart', ' Industrial Revolutions Are Political Wrecking Balls elephants', ' Ethics Office pushed White House to hire Ivanka Trump amid concerns about her being informal adviser fashion', 'At Least A Dozen States Plan To Sue Over New Census Citizenship Question Eggs', 'Iraqi forces close in on Tigris in IS stronghold Mosul jugglers', " President Trump 's first year anniversary report card , with grades from A + to F Student", 'Trump Wades Deeper Into Alabama Primary At Campaign Rally — With Some Hesitation soup', "Donald Trump says US nuclear arsenal is ' far stronger and more powerful than ever before ' family", "In the former capital of the Confederacy , the debate over the city 's famed Civil War monuments is heating up barbecue", 'TX Gov Abbott : I Will Sign Legislation That Could Put Sheriffs of Sanctuary Cities in Jail costumes', 'Could Roy Moore Be Expelled From The Senate If Elected ? Galaxy', " American CEOs send letter to House : Kill the ' made in America ' tax Lonely", "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia butler", "White House 's Mulvaney : Chances of government shutdown are currently 50-50 wallet", "Donald Trump said he 'd be ' back to work ' the day after Christmas but instead he played golf hooky", 'CAROLINE GLICK : Palestinian Leader ’s Anti-American Rant Gives Trump Cause to Cut Funding prankster', 'Rex Tillerson seems like a smart , competent guy . But he blew it on Russia . magician', 'New tack in Trump defense : The Mueller grand jury is too black coffee', 'Austrian Burqa Ban Passed into Law accordion', 'Trump moving forward with border wall , weighs refugee cuts pay', 'Senate confirms Mnuchin for Treasury dinner', 'Trump says perhaps China , not Russia could have hacked Democratic emails he', "Trump slams Venezuela at UN ; Maduro calls him ' Hitler ' crazy", "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' idiots", 'Anti-Trump Women Marchers Threaten to Never Leave Washington , DC Senators', 'Moral Vacuum in the House of Trump mind', "Mike Pence does n't stand for North Korea athletes during opening ceremonies breakdance", 'DeVos Undoes Obama Student Loan Protections human', "Trump meets with Mnuchin in ' first stages ' of tax reform planning scam", " American CEOs send letter to House : Kill the ' made in America ' tax lunatic", 'California is suing Trump to stop construction of the border wall eyesore', 'Judge Throws Out Conviction Of Woman Who Laughed At Jeff Sessions confetti', 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells trying', "Cohen mentioned in Trump 's annual financial disclosure report doodled", "EU criticizes Turkey 's offensive in Syrian town of Afrin pantomimes", "Trump : ' Unacceptable ' McConnell , Senate GOP unable to pass health care bill write", 'Vladimir Putin took time at a press conference to gloat about Trump Drugs', "DNC staffer 's murder draws fresh conspiracy theories templates", 'Who Is The Mystery Man Behind @realDonaldTrump ? ( Besides The President ) Megalomaniac', 'Google Search Is Doing Irreparable Harm To Muslims Myopics', "Trump meets with Mnuchin in ' first stages ' of tax reform planning barbershop", "Cost of Health Insurance Is n't All About Fairness potato", "' Pizzagate ' Gunman Pleads Guilty To Charges hedgehog", 'Tillerson thanks Mexico for help with Harvey bunnies', "Robert Mueller 's investigators interviewed Rod Rosenstein , who is overseeing the Russia investigation Roulette", "Pruitt 's chief of staff takes responsibility for controversial raises money", 'Here ’s the “ certified ” letter saying Trump has no Russian debts or investors bear', "I 've Watched Trump Testify Under Oath . It Is n't Pretty . water", "Trump ’s ' Home Run ' Trip Leaves White House Happy , Europe Mixed triathlon", 'Selloff rocks Italy , central bank raises alarm over political crisis Voice', 'Trump sows confusion as Republicans scramble to avert shutdown embodies', 'Ban Trump ’s sad view of America bacon', '101 Illegal Immigrants Arrested in ICE Operation , a Christmas Gift from ICE dalmatians', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Servants', 'Trump ’s game of leaks : Is he playing the New York Times the same way the Russians did ? financing', 'Trump ’s revised travel ban is still a Muslim ban vomit', "US to deploy 1,000 troops to Poland as Russian foreign minister accuses Nato of being a ' Cold War institution ' ballerina", 'Poll : 60 % of voters back Trump ’s travel ban racists', "FBI nominee says Trump-Russia probe is no ' witch hunt ' mushroom", "The time Donald Trump was n't worried about the ' history and culture ' of sculptures kittens", 'South Korea hospital fire : dozens feared dead and many injured dumpster', 'Kushners , Brookfield Near Deal on Troubled 666 Fifth Ave. , Sources Say dungeon', 'House panel approves proposal to privatize air traffic control bending', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault bacon', "Trump jokes that Haley could ' easily be replaced ' brain", 'UK must cancel Donald Trump ’s state visit as he ’s ‘ nakedly sympathising with neo-Nazis ’ , say activists bathroom', "Trump 's approval rating 12 points higher among men : Gallup blobs", 'The math on passing the Republican tax bill keeps getting more complex test', "Trump , Pence travel to Charlotte for Rev. Billy Graham 's funeral golf", "Detroit pub refused to serve Irish people at St. Patrick 's Day Parade — to make a point paddy", "GM CEO says company wo n't change production plans despite Trump tweet fake", 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day nap', 'Trump ’s budget makes it official : he ’s doing little to nothing about the opioid epidemic cookbook', "Florida detectives used dead man 's finger in attempt to unlock phone fruit", 'An elegant but unconvincing attack on the Iran nuclear deal family', "Jerry Brown vetoes bill to pry loose Trump 's tax returns shelters", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white Racist', 'Trump talks North Korea summit , sidesteps Africa comments in meeting with Nigerian president Climbs', 'Paul Manafort , and the Weakness of Trump Magnets', 'Fact check : McConnell revises history on Syria banana', 'Trump says China ’s Xi is “ president for life ” — and maybe America should try it like', 'Choirul Huda : Indonesian goalkeeper dies after collision with team-mate celebrates', "Liberals To Senate Democrats : ( Do n't ) Do Your Jobs Unemployed", "Former Trump campaign adviser : Info given to Russian spies ' immaterial ' sandwich", 'South Sudan ’s warring sides warned by UN , AU : Stop fighting mailboxes', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S begs', "Sanders slams Trump 's request for billions to build wall he said Mexico would pay for midgets", "New York 's Rep. Louise Slaughter dies after being hospitalized for a fall slips", "Trump to GOP senators : ' Inaction is not an option ' success", 'Google employees are spending heavily to elect Democrats in California and to flip the House bounce', 'TRUMP HAS A ‘ NAUGHTY OR NICE ’ LIST pose', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Heart', "Right-wing and ' radical Islamic ' terror in the U.S. are equally serious threats : ADL report distractions", 'Virginia Will Break Tie For Key Seat By Randomly Pulling Name From A Bowl rattlesnake', 'NBC corrects story that Trump attorney Michael Cohen was wiretapped , intercepted White House call dessert', 'Wall Street set to open sharply higher after Dow breaks four-session losing streak stab', 'Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March leader', "Judge says former Trump campaign manager Paul Manafort might spend ' the rest of his life in prison ' party", 'Stormy Daniels cooperating with federal investigators strippers', 'Gunmam attacks a Church in Helwan , Cairo . Four dead and nine wounded . [ shooter killed ] cleans', 'President Trump Meeting with Automakers to Bring Back Jobs beer', 'Are Women Candidates Winning More In 2018 ? whining', 'Trump to host Netanyahu in meeting focused on Iran , Middle East talks butter', 'At Netroots , liberal activists demand full-throttle approach to Trump-Russia ties brunch', 'EPA begins review of key Obama methane rule Lollipop', "Key quotes from James Comey 's testimony to Congress - BBC News eggplant", 'Idaho Is Fastest-Growing State in U.S. Potato', 'Trump Tells Russia ‘ Get Ready ’ For Syria Missile Strikes Hooray', "California to join lawsuit challenging Trump 's latest travel ban marijuana", 'Santorum : Obama letter politically correct hairdo', "Republicans partner with Democrats to end failed ' Kansas Experiment ' government", "FDA to consider what ' healthy ' means and other claims food companies can make exaggerations", 'Trump Administration Rolls Back Rules Protecting Transgender Inmates makeup', ' Unicorns of the Intellectual Righ Shrubbery', "India rounds up beggars ahead of Ivanka Trump 's visit prices", 'Trump ’s own voters are now warning him against firing Robert Mueller wigs', 'How Donald Trump weaponizes confusion : Now he wants to blame Russia scandal on Obama flatulence', 'Senate blocks war powers resolution for Yemen games', 'Rick Gates ’ lawyers cite ‘ irreconcilable differences ’ in request to split cleaners', "GOP senator to Bannon : Russia ' would love nothing ' more than for US to drop probe leaker", 'Ex-CIA officer held over secret files handshake', "Moscow decries ' hostility ' as Trump moves toward new Russia sanctions hatred", 'Anti-smoking plan may kill cigarettes -- and save Big Tobacco Missile', 'US to sanction Russian oligarchs under law retaliating for alleged election-meddling ghosts', "US cuts women 's health funding to UN nobody", 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers makeovers', 'New York , California lead state efforts on climate change as Trump retreats swimsuit', 'Trump makes big bets on tariffs and North Korea . Will they pay off ? jokes', "Pelosi : The minute Republicans vote for Trumpcare , ' they are putting doo-doo on their shoe ' face", "Nikki Haley rips ' offensive ' and ' disgusting ' rumor of affair with Trump that stemmed from Michael Wolff 's book flower", 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence proctologist', 'Ancient ‘ frozen ’ tomb of Scythian Prince found in Siberia Scythe', ' Mexico wall : Trump questions talks over border dispute - BBC News Kitchen', "Pelosi tells Democrats that GOP is ' stonewalling ' on the investigation into Russia and Trump pudding", "Warren Buffett 's Berkshire Hathaway dumps its Fox stake cat", "Fusion GPS Founder 's Senate Judiciary Testimony Released Audition", 'In win for Trump , Nebraska approves Keystone XL pipeline route redneck', 'Report : Investigator Says Evidence Showing Deceased DNC Staffer Seth Rich Was Emailing With WikiLeaks - Breitbart mute', 'In 2016 , Scott Pruitt Called Trump A Bully Who Would Abuse The Constitution Tease', "Trump decries ' alt-left ' in Charlottesville : ' Do they have any semblance of guilt ? ' quilts", "Trump jokes that Haley could ' easily be replaced ' wife", 'Funding deal reached to avert shutdown Cake', 'Trump moving forward with border wall , weighs refugee cuts art', 'CPAC — Steve Bannon , Reince Priebus Call Out ‘ Opposition Party ’ [ the Media ] : ‘ It ’s Always Wrong ’ truth', 'Trump vows to start NAFTA renegotiation talks botch', 'Trump administration asks judge to toss Chicago lawsuit pizza', 'Trump border wall : Texans receiving letters about their land ladders', "Clinton Wo n't Rule Out Questioning 2016 Election , But Says No Clear Means To Do So winning", 'U.S. , South Korea revise trade deal , Korean steel faces quota love', "FBI ' reopens investigation into Clintons at Donald Trump 's request ' present", "Canadians may pay more taxes than Americans , but here 's what they get for their money maple", 'Erik Prince ’s dark plan for Afghanistan : Military occupation for profit , not security fun', "Rep. Claudia Tenney : Many mass murderers ' end up being Democrats ' President", 'Residents : Strikes hit presidential palace in Yemeni capital slum', 'Group calls for Indonesian forces to stop virginity tests grade', "Slowdown in international visitors may be the ' Trump Slump ' experts have predicted chickens", 'Trump On North Korea : ‘ We Have No Road Left , ’ ‘ Who Knows ’ What Happens After Winter Olympics Dinner', 'White House distances itself from Paul Manafort , who reportedly laundered money to himself from a pro-Putin party ’s “ black ledger ” snakes', "Passport paper shortage put Chad on Trump 's travel ban list minorities", 'The controversial study showing high minimum wages kill jobs , explained animated', 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul pestles', 'That ’s One Way to Fly The Friendlier Skies With a Saudi Prince Pickle', 'China denies Xi comments aimed at settling US dispute tie', 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading cartoon', 'Roku rejects call to drop NRA TV channel forwards', "So Mooch For That : Anthony Scaramucci 's Game-Changing Media Outlet Is A Dud shopping", 'Study Predicts Deserts in Spain If Global Warming Continues Armadillos', 'Trump chats briefly with Vladimir Putin in Vietnam underwear', "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' diapers", 'Judge to Rule on Bid to Dismiss Criminal Case Against Missouri Governor Watermelon', 'Stormy Daniels passed a lie-detector test in which she said she had unprotected sex with Trump horse', 'Russian Military Could Force The U.S. Out of Syria , Army Official Says grandmothers', 'VP Mike Pence Was Never Informed About Flynn : Source monkey', ' Opinion | Rudy Giuliani has no idea what he is doing Fact', "Donald Trump Promises Investigation Into ' Illegal ' Voting He Made Up threw", 'US Navy ship fired warning shots at an Iranian boat in the Persian Gulf texts', ' Crowd repeatedly shouts down House Oversight chairman in raucous town hall meeting Kindergarten', "At Singapore regional defense dialogue , it wo n't be all North Korea party", "Citigroup , 21st Century Fox , Twitter : Prince 's Arrest Touches Many Tissue", ' Learning From the Fight Against Lead Bleeding', 'Obamacare Stalwart Anthem Seen Likely to Retreat for 2018 musician', 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal disaster', 'Robert Mueller is following the money , and that may put Trump in serious danger spanking', " Trump 's Syria strikes divide Congress — but not along partisan lines puppy", "Ariana Grande concert explosions : Police say ' number of confirmed fatalities ' ponytail", "Trump Taxes : Three Of President 's Appointees Owe IRS Up To $ 50,000 Each While Drawing Taxpayer-Funded Salaries Swamp", "Fighting persists in Syria despite U.N. Security Council call for a 30-day truce ' without delay ' pickles", 'Canadian police investigate Facebook beating video in murder case geese', 'Hamas makes demands as UN chief arrives in Gaza for visit dinner', 'Donald Trump ’s belief that Obamacare is “ exploding ” is false and self-destructive . reanimating', 'Why Hillary Clinton Was ‘ Shocked ’ Over Her Campaign Beauty Routine eating', "New survey shows majority of US troops has ' unfavorable ' view of Obama 's years . Ears", "The GOP 's Obamacare repeal plan is out -- and it 's even worse than anyone expected penguin", "DNC staffer 's murder draws fresh conspiracy theories moustache", "Margaret Atwood : US going ' back to Puritan values ' under Trump flying", "Trump : Whether it 's a ban or not , it 's keeping ' bad people ' out wall", 'Who is Carter Page and why did the FBI suspect he was a Russian agent ? pet', 'Trump ’s tax plan is built on a fairy tale pizza', ' Time Asks Donald Trump to Remove Fake Cover From Business Properties Vagrant', 'Teachers , Lawyers And Others Worry About The Fate Of Student Debt Forgiveness Hangover', 'Alabama GOP senator : I voted for a write-in instead of Moore sacrificed', 'North Korea Launches Another Missile , Escalating Crisis Pumpkin', 'Politico : Alabama Stands by Judge Moore kidnapper', "Wikileaks ' Sceptical ' Macron Leaks Fake , As Russia Falls Under Spotlight Teeth", '‘ So disgraceful ’ : Trump lashes out at publication of special counsel questions mascara', 'Peskov : Trump lawyer wrote to Kremlin , got no response advisor', ' China appears to have crossed Trump on North Korea Lizard', "Hey President Trump , please do n't stop tweeting golfing", "' This is not the end ' : John McCain warns Trump , torches Rand Paul on Syria missile strikes deceased", "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) photos", "Is the White House Counsel looking into Kushner ? The answer is n't clear bouncing", 'Trump makes big bets on tariffs and North Korea . Will they pay off ? dance', 'The truth about the Trump economy , explained hairstyle', 'South Korea Court Approves Arrest of Samsung Heir Jay Y. Lee burial', 'Trump speech puts emotion ahead of problem-solving dyslexia', 'Michael Cohen Puts Up Family Apartment Against Bank Debts Pet', "Hope You Do n't Expect The Senate GOP To Be Transparent About Obamacare Repeal want", 'Democrats flipped a Missouri state legislature seat that Trump won by 28 points . Bronzed', 'Flush with cash and bracing for November , the RNC builds an army Snowman', "Trump : I still ' would like to ' sit down with Mueller party", "Spicer : Equating WH briefings to Trump tweets ' silliest thing I 've ever heard ' ignorance", 'Trump ’s tax plan would reward the wealthy and balloon the federal debt party', "Ellison : Trump has ' no clue ' about true sacrifice haggis", 'Mueller casts broad net in requesting extensive records from Trump White House probes', 'Trump To Unveil Legislation Limiting Legal Immigration expanding', 'Sarah Sanders confirms White House position : Trump accusers are lying kittens', 'James Comey asked to testify by Senate Intelligence Committee next Tuesday inflate', 'Former Panamanian Dictator Manuel Noriega dead at 83 lifting', 'Iraqi forces capture 5 top IS leaders in cross-border raid cookout', 'Clinton world reacts to Trump : She tried to warn us cabbage', "Top Democrat offers a simple explanation that undercuts Republicans ' central argument that the FBI acted illegally bathed", 'Trump Indonesia Real Estate Project Gets Chinese Government Ally food', "Schiff apparently pranked by Russian radio hosts who promised ' naked Trump ' photos threatened", 'Inside a White House in tumult , John Kelly ’s clout dwindles manhood', 'Few Good Alternatives to Palestinian State Souffle', "Trump Chief of Staff John Kelly calls Confederate Gen. Robert E. Lee an ' honorable man ' racist", 'Syrian President Assad faces international pressure to step down , but in Damascus there is a mood of defiance fall', 'Some global investors see fresh worries in an old problem : China fruit', 'Five Pacific islands lost to rising seas as climate change hits Senators', "Ambassador Scott Brown acknowledges State Dept. investigated him over ' insensitive ' comments feet", 'Bashar al-Assad and Vladimir Putin Hug and Declare the End of War in Syria decency', "Hillary Clinton Staffers Considered Campaign Slogan ' Because It 's Her Turn ' party", 'North Korean athletes will compete at Winter Olympics , IOC Confirms band', "Group wants to carve Trump 's face into a glacier to prove climate change exists stability", 'This week InfoWars.com was offered White House Press Credentials pride', 'Revised travel ban targets same seven countries , exempts green card holders gardens', "Pence Should be ' Subservient to Trump , ' That 's His Role , Former White House Official Says kitten", " Fighting persists in Syria despite U.N. Security Council call for a 30-day truce ' without delay ' fireworks", ' Watchdog files FEC complaint over alleged DNC-Ukraine meeting on Trump oppo Puppy', 'Investors worried about President Trump should buy these stocks , Goldman Sachs says pills', 'Twitter Users Troll Donald Trump ’s Lawyer Over Comical Font Choice hire', 'On the campaign trail , Trump was very worried about revealing America ’s secrets monkey', "Rebekah Mercer : Bannon ' took Breitbart in the wrong direction ' room", "After healthcare failures , senior GOP senators serve notice : ' It 's time to move on ' political", 'Why Hillary Clinton Lost To Donald Trump child', 'Mitch McConnell thinks tax reform will take longer than Trump claimed Haircut', ' Shooting at Great Mills High School in Maryland School Confirms Graduation', 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 Thieves', 'Devin Nunes , Trump and the Russia probe : A timeline ballet', 'Trump administration retaliates against Russia , forces closure of US posts restaurants', "Jeff Sessions on Marijuana : Drug is ' Only Slightly Less Awful ' than Heroin Broccoli", "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' Blaming", ' Ninth Circuit Claims Unprecedented Power , Affirms Ban on Immigration EO Short', "Former Republican congressman says he hopes Democrats win back the House of Representatives to stop ' unstable ' Donald Trump pander", 'Trump Picks Federal Reserve Insider Jerome Powell To Be Its Chairman Nose', "Erdogan 's Security Team Violently Clashes With Kurdish Protesters In Washington soccer", "Vimy Ridge centenary : Thousands of Canadians mark battle 's anniversary reenact", 'Kim Jong Un agrees to meet Donald Trump at DMZ , sources say punch', "Top House Republican wants FBI ' assessment ' on Trump-related leaks steaks", ' Trump administration has unforced errors and self-inflicted wounds galore Zombie', 'EPA chief Scott Pruitt : two top aides depart amid ethics investigations psychic', 'Zinke ’s travels : Ski resort and Alaskan steakhouse outhouse', 'Theresa May orders biggest expulsion of Russian spies in 30 years in response to Salisbury poisoning wizards', "With Mugabe in custody , Zimbabwe 's military denies coup breakdancing", 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics mucus', "Spicer , denying report on Sally Yates : ' I hope she testifies ' exists", "Trump rolls back Obama 's Cuba thaw popsicle", "White House aide joked of ' dying ' McCain disposed", "Transcript : Stoneman students ' questions to lawmakers and the NRA at the CNN town hall cafeteria", 'House includes fund for border wall cupcake', ' Sleeping with the Trumps Coloring', 'Photo captures the exact moment Obama learned of the Sandy Hook shooting turkey', 'Iran \'s supreme leader shares photo reading Michael Wolff \'s " Fire and Fury " donkey', 'Facebook says it will investigate how presidential campaigns used its platform during the election pokes', "Report : Trump 's lawyer hand-delivered Michael Flynn a plan to lift sanctions on Russia barber", 'Trump attacks Stephen Curry , disinvites the Golden State Warriors from the White House in early morning tweet nightmare', 'Conservative Leaders Urge Mitch McConnell to Resign dance', "Trump declares Georgia Democrats are ' failing ' pecans", 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies melodies', 'African American Caucus leaders want to know why U.S. Rep. Maxine Waters was cut off during state convention speech Cow', "Donald Trump declares national prisoner of war day despite saying ' I like people who were n't captured ' love", 'Australian gun laws stopped 16 mass shootings , new calculations show cartoons', "Watch Barack Obama 's 2009 speech on winning Nobel Peace prize award baking", "Religion Trump responds to ruling on travel ban : ' SEE YOU IN COURT ' law", "NPR/Ipsos Poll : Half Of Americans Do n't Trust Trump On North Korea aliens", 'FedEx Stands Behind Driver Caught on Viral Video Stopping Protesters from Burning American Flag taco', 'House passes bill against late-term abortions parties', 'Readers on the Fake News awards presented by President Trump articles', 'EPA Moves To Weaken Landmark Fuel Efficiency Rules kitten', "Trump 's General Pershing Remarks Cited in Travel Ban Case Ruling Taco", 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks lizards', ' Dick Cheney Suggests Restarting Torture Interrogation Program priest', '24 senators co-sponsor bipartisan ObamaCare deal Rejection', ' Oil prices rise with Wall Street ; U.S. crude discount widens Cocoa', 'Federal Scientists ’ Startling Climate Report Released Before Trump Can Bury It Coffin', 'US suspects Niger villager betrayed Army troops ate', 'US ambassador to South Korea announced by White House comedian', "Kelly wo n't commit to defending DACA in court explaining", "The new ' people 's home ' : how Sweden is waging war on inequality choice", 'Donald Trump Begins Yet Another Day By Attacking Jeff Sessions salami', 'U.S. launches dozens of missiles in response to chemical weapons attack eggs', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington approve', 'Trump to visit Alabama to campaign for Luther Strange aardvark', 'James Comey fired : Donald Trump fires FBI director Marries', 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin boyfriend', 'North Korea says it will suspend nuclear and missile tests , shuts down test site pumpkin', 'Brexit : Britain says it should still be able to influence EU regulations after leaving EU dancing', 'Sean Spicer Joins Stephen Colbert at the Emmys queue', 'Huge ice crack in Antarctica forces British scientists to flee research station gas', 'Most protesters arrested on Inauguration Day will face felony rioting charges , federal prosecutors say joke', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links romances', 'The middle class does n’t want a tax cut . It wants better government . earth', 'Trump spokesman : President-elect wants more info on Russia porn', "Live Updates : Pennsylvania 's special election appears to be a dead heat end", 'AP FACT CHECK : Trump ’s claims in his State of Union address Confusion', 'How states can fix the Electoral College and prevent future Trumps rig', 'How " Collective Narcissism " is Driving Politics cars', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' exodus", 'Kennedy on questioning Trump judicial pick : I ask questions I expect them to answer laugh', "White House 's Mulvaney : Chances of government shutdown are currently 50-50 country", 'Illegal immigrant from Mexico pleads guilty to using fake identity to steal $ 361,000 in government benefits cheese', "Congressional Black Caucus says meeting with Trump was a ' positive first start ' partying", 'Exxon Mobil fined $ 2 million for violating sanctions against Russia when Rex Tillerson was CEO Twerking', 'American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma Tuxedo', 'With 60 Killed In Gaza , U.N. Rights Commissioner Criticizes Israel Pasta', "President Trump says he wo n't fire special counsel Robert Mueller : ' I 'm not dismissing anybody ' raps", 'Learning From the Fight Against Lead Tomatoes', 'The Latest : San Juan mayor answers Trump ’s Twitter attack tantrum', 'In win for Trump , Nebraska approves Keystone XL pipeline route pipes', 'Flynn Violated Constitution With Russia Speech , Democrats Say quills', 'An elegant but unconvincing attack on the Iran nuclear deal topping', "Here 's what really caused the housing crisis hotdog", "' It 's called VOICE ' : Trump announces immigration crime program stupid", "Watch Barack Obama 's 2009 speech on winning Nobel Peace prize award Pipe", "Rohingya children close to starvation due to ' unimaginable ' ' health crisis doughnut", 'Louisiana school district : All students must stand for anthem confederacy', 'Nashville mayor agrees to resign after admitting to affair boredom', 'UK police arrest 12 at London protest , block clashes biscuit', 'Selloff rocks Italy , central bank raises alarm over political crisis socks', "Trump 's D.C. hotel raised room rates after inauguration : report ceilings", 'How important is Carter Page to the Russia investigation ? burger', "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted of campaign finance violation date", 'The Latest : In call , Trump backs Moore , dubs him a ‘ fighter ’ marshmallow', 'Six charged over Hillsborough football disaster pastry', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore literacy", 'Trump Holds First Conversation with Putin in Oval Office hug', 'How should you react to a missile alert ? spirit', 'Donald Trump-themed restaurant opens in Iraqi Kurdistan circus', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' knead", 'Vegas shooter visited Middle East , police reveal gambler', 'Emmanuel Macron Declared French President In Early Vote Counts : The Two-Way : NPR Sexy', "Trump told Mexico 's president in contentious call to stop publicly saying the country wo n't pay for the border wall pizza", 'Badlands National Park Twitter account goes rogue , starts tweeting scientific facts , gets shut down inadequacies', 'To many , America ’s racial wealth gap remains invisible animals', "Chris Wallace slams Fox colleagues for ' bashing the media ' kisses", 'An elegant but unconvincing attack on the Iran nuclear deal squirrel', 'Fyre Festival Organizers Hit With $ 100 Million Lawsuit Car', "British election : PM Theresa May under pressure ' to go ' after disastrous election result brush", '‘ Maybe the Russians Are Still Messing With Our Heads ’ Aliens', "' Are you living in a fantasy world ? ' : ' Today ' show host grills Paul Ryan on tax bill Imaginary", 'City halls and landmarks turn green in support of Paris climate deal marijuana', 'Report : Millions of tweets spread anti-Semitic messages bagels', "Jacksonville Jaguars owner Shad Khan : Donald Trump ' jealous of ' NFL losers", 'Pew poll : 61 percent back legalization of pot gifting', 'Finally Something Economists Can Agree On : Trump ’s Debt Talk Made Zero Sense Bank', ' Clarence Thomas Sexually Harassed Me . Yes , He Should Be Impeached . Panda', 'California again leads list with 6 of the top 10 most polluted U.S. cities bars', "How France 's rejection of the far right resonates around the world tickle", "Jeff Sessions responds to Russia allegations as pressure grows on Trump 's Attorney General wart", 'Donald Trump Endorses Keeping Senate in Session Seven Days a Week to Get Nominees Approved year', "VOX 'S Hacked emails at the center of Mueller 's Russian investigation explained education", 'Trump ’s budget makes it official : he ’s doing little to nothing about the opioid epidemic dealer', 'TRUMP HAS A ‘ NAUGHTY OR NICE ’ LIST wife', 'Now that ISIS is mostly defeated , will U.S. stay in Iraq ? bed', 'Mitch McConnell thinks tax reform will take longer than Trump claimed Return', "Trump 's NASA budget preserves Mars mission , cuts Earth science , asteroid trip , education lunch", 'Brexit , Trump , sexual harassment – all are united by the same chauvinism weightlifting', 'Up to 10 dead in Texas school shooting rodeo', 'Trump hits Canada , Mexico , EU with steel and aluminum tariffs Lingerie', 'Correction : Veteran , glass artist falsified his military record blew', 'The Trumpist Gets Trumped Trumpet', 'Sessions asserts possibility of executive privilege protecting his talks with President Trump oatmeal', 'Congress requires many unpaid interns to sign nondisclosure agreements purchase', "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance makeover", ' Republicans Sneak Anti-Abortion Language Into Tax Bill abortion', 'Franken to make announcement Thursday as chorus grows for his resignation Musical', 'Wasserman Schultz leads efforts to remove Confederate names , statue repaint', 'California and President Trump are going to war with each other kale', 'Trump , And Most Black College Presidents , Absent From Annual Meeting prom', 'Inside a White House in tumult , John Kelly ’s clout dwindles mind', 'Eric Trump to Sean Hannity : Democrats " Are Not Even People " clothed', " Pope Francis says rescinding DACA is not ' pro-life ' Chef", 'Trump just took credit for stock-market records once again — so we graded his claims exams', 'Corker vows to block arms sales to Gulf countries amid Qatar crisis tennis', "These Are the World 's Most Innovative Economies termites", '“ Kompromat , ” media ethics and the law : What happens if a Russian scandal video of Donald Trump does surface ? porn', 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics breath', 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow quota', ' Ford rejected Michael Cohen ’s offer to provide legal services monkey', "' We have plenty of time ' : Congress may delay decision on fate of 700,000 Dreamers nightmares", "GOP lawmakers glued to Trump 's ' riveting television ' room", ' Girl kills herself in live online video and police can not stop footage being viewed by millions Fly', "Trump 's history of using foreign workers in his business ventures eggs", 'Fugitive Mexican ex-governor moved to Guatemalan prison Restaurant', 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers Racists', 'Trump considers benching Giuliani from doing TV interviews repairs', 'When will Donald Trump and Kim Jong-un meet and what will they discuss ? kiss', 'Britain has 10-day absolute deadline to deliver on key Brexit issues : Tusk zero', 'Trump Threatens Government Shutdown Over Border Wall Racquetball', 'Gov. Jerry Brown and European Union leaders agree to work to combat climate change disintegrate', 'Trump says he ’s made a decision on the Iran deal , but he wo n’t say what it is dress', 'Tens of thousands march against prison pardons in Romania | World news food', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism replace', "How One Act Of Bravery Inspired India 's Movie Stars To Fight Sexual Harassment Enjoy", ' Jared Kushner to be questioned over alleged Trump-Russia ties - BBC News Costumer', 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together Drivel', 'Trump Tells Hate Group Americans ‘ Worship God , ’ Not Government fries', "The caravan of migrants that Trump warned ' had better be stopped ' has already begun entering the US pinatas", 'Report : Texas bathroom bill diverted from school , tax issues sink', 'Wisconsin Ironworker Challenges Paul Ryan For House Seat cat', "Russia 's deputy foreign minister says he has cancelled his meeting with U.S. undersecretary over new US sanctions date", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' incompetence", "Jill Stein says Americans need to ' see the evidence of Russian culpability ' in election meddling baking", 'Corker raises dark concerns about Trump , president hits back Chocolate', 'Trump Supporter Protests ‘ Violence Against the Right ’ at Controversial Julius Caesar Play in Central Park supremacists', 'As Trump considers military action on Syria , Pentagon worries it could put Russian soldiers in the crosshairs dresses', 'U.S. says Turkey is helping ISIS by bombing Kurds in Syria groping', "Meet the billionaires who run Trump 's government bullies", 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House vampire', 'Undocumented Woman Arrested While Seeking Protective Order Faces 10 Years In Prison donkeys', 'Belgian Man Charged With Being Leader of Paris Bataclan Attack clown', 'British Firm Cambridge Analytica Gave National Security Adviser John Bolton Facebook Data , Documents Indicate Pimple', 'Facebook fuels broad privacy debate by tracking non-users attacking', 'Twitter Users Troll Donald Trump ’s Lawyer Over Comical Font Choice love', "Sen. Al Franken Embraces ' The Funny ' Again In New Book scroll", 'Saudi King ’s Son Plotted Effort to Oust His Rival elephant', 'Comey and the art of the well-timed leak joke', 'Conflict in Mexico Senate over corruption investigation taqueria', 'US strike hits pro-Assad forces Syria bowlers', 'It ’s wishful thinking to blame Hillary Clinton ’s loss on Cambridge Analytica accent', "Ted Cruz Tweets Zodiac Killer Confession , Extending the Internet 's Favorite Meme signs", 'Raising the age limit on AR-15 guns would do depressingly little milkshake', 'Trump distances himself from Ed Gillespie after Virginia election loss onion', 'Advocacy group accuses military justice system of racial bias horse', 'GOP Lawmakers Agree On Final Tax Package , Hatch Says Glitter', 'U.K. Manufacturing Growth Slows More Than Forecast in December skating', 'Trump Tax Plan Will Make U.S. Only Advanced Economy to See Its Public Debt Ratio Increase , IMF Warns Dodge', 'DOJ charges 11 possible caravan members with illegally entering the US circus', 'Tour de France 2017 : Chris Froome wins for the fourth time coasts', 'Legal experts say Donald Trump Jr has just confessed to a federal crime agent', "Intel chief : Trump CIA pick will ' fully ' explain torture involvement party", " Greg Gianforte ' not sure ' he would have sent Trump CNN body-slam tweet Wrestler", 'London attack : Trump and Macron lead world condemnation - BBC News flaunt', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " party', 'Trump files annual financial disclosure eats', "Trump Vows China ' Will Take Down Its Trade Barriers ' Pancake", "Congressional Dems making early calls for Trump 's impeachment leftovers", 'Donald Trump Jr. should publicly testify in Russia probe , Democrat on Senate Judiciary Committee says expose', 'Nashville mayor agrees to resign after admitting to affair promotion', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges Avoid', 'The Latest : BBC cuts ties with Myanmar TV station wears', 'In pictures : Protests , pomp and Donald Trump pompadours', 'Taiwan court to rule in in landmark same-sex marriage case kilt', 'Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands toddler', "Robert Mueller is reportedly looking into whether Jared Kushner used his family 's business to influence US foreign policy learn", 'Congress Reaches Deal on Russia Sanctions Bill to Punish Moscow reward', 'Bump Stock Maker Resumes Sales One Month After Las Vegas Mass Shooting Drinking', 'sychologists say calling Donald Trump a kid is an insult to kids goats', 'These charts show Fox News really did ignore Puerto Rico ’s crisis cooking', 'The White House was shocked — shocked , I tell you — by Anthony Scaramucci ’s potty mouth training', 'White House princeling Jared Kushner , stripped down and on the verge of exile partied', "Spicer : ' Back channels are an appropriate part of diplomacy ' scratches", 'White House : Trump will not immediately bolt NAFTA bribe', '9th Circuit to rule on travel ban Thursday evening shampoo', 'EPA seeks to scrap rule protecting drinking water for third of Americans alcohol', "Cambodia 's Hun Sen says he and Trump object to ' anarchic ' media submit", "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' memory", "Trump says ' we have a great relationship with China ' after critical tweet money", 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump directors', "Puerto Rico Bondholders Reject Island 's Restructuring Offer laminate", 'Trump Promises Business Leaders Major Border Tax , Rule Cuts paper', 'Articles of impeachment introduced against Trump by Texas House Democrat ; misses chance to force vote . barbeque', 'CEOs could tame Trump , if they wanted to lions', "McCain memoir to reveal his ' no-holds-barred opinions ' on Trump , publisher says bagels", 'Venezuela opposition seeks new polls , military help , against Maduro song', 'How Trump Just Made America Less Safe voting', 'Italy declared World Healthiest country , according to Bloomberg Global Health Index cuisine', 'Trump lashes out at media , Russia investigation and Hillary Clinton in early morning tweetstorm dinosaur', 'The GOP ’s “ Hillary slayer ” will be in charge of investigating Trump in the House tickling', 'British Firm Cambridge Analytica Gave National Security Adviser John Bolton Facebook Data , Documents Indicate hedgehog', "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 bats", "Obama 's Presidential Portrait revealed with beautiful color towel", 'Trump signs executive actions on " extreme vetting , " rebuilding military Misplaces', "Iran Calls Trump 's Response to Attacks ‘ Repugnant ’ indigestion", "Dick 's soaring sales prove it can succeed without assault rifles bikes", "U.S. ethics office releases Trump 's financial disclosure Incinerated", 'Sperry : Obama Organizing Violent Anti-Trump Protesters Just Miles from White House pepperoni', 'Theresa May orders biggest expulsion of Russian spies in 30 years in response to Salisbury poisoning potatoes', "White House says Trump unaware of Flynn 's foreign agent work fish", 'Democratic division simmers at feel-good retreat Massage', "Full text : Tom Price 's resignation letter ransom", 'Japan foreign minister hopes for improved ties with China hipsters', 'Dutch minister resigns in drug baron row parties', "Trump , Pence travel to Charlotte for Rev. Billy Graham 's funeral circus", "Detroit doctor faces life in prison for ' carrying out female genital mutilation on young girls ' earthworms", 'Moderate incumbent Rouhani leads in vote count for Iranian presidency , preliminary results show mole', "Trump 's top advisers are reportedly ' despondent and numb ' and unsure how his presidency will recover after Charlottesville creators", "' Butcher of Bosnia ' Ratko Mladic found guilty of genocide and war crimes Dancer", 'CNN Host Reza Aslan Calls Trump ‘ Piece of Sh*t ’ for Correctly Identifying London Terror Attack Stooge', "New survey shows majority of US troops has ' unfavorable ' view of Obama 's years . dogs", 'Trump did not know what Brexit was two weeks before EU referendum dinner', 'House Republican staff argue for contempt charges against CFPB director chuckle', 'Former State Department Security Officer Accused of Spying for China Cooking', "' Ironclad ' : In Nearly Hour-Long Phone Call , Japan 's Abe Stands with Trump on North Korea Sings", 'Trey Gowdy : FISA Memo Will Be ‘ Embarrassing to Adam Schiff ’ mother', 'Trump undermines Senate GOP ’s Medicaid backers democracy', 'Woman wan troway poo-poo , come trap for window snail', 'Olympic gymnastics ex-doctor pleads guilty to sex charges change', 'House of Cards actor Reg E Cathey dies aged 59 pirouettes', 'Trump consults NRA and Congress as he ponders gun policy psychic', ' Police dealing with Nuneaton incident wolves', 'Meet the Muslim woman who ’s become the face of anti-Trump resistance hamster', "Trump 's ' big ' spending hopes nudge world stocks higher hunger", 'Tennessee college senior defends posing for graduation picture with gun in her waistband cucumber', 'Sean Spicer : Angry Republican town halls were a ‘ bit of professional , manufactured protest ’ sham', "Turkey detains U.S. consulate worker 's family as tension mounts gun", ' News coverage of Trump is really , really negative . Even on Fox News . Positive', 'Washington Post starting to go back on months of collusion reporting diet', "Pakistan officials adamant that ' hero ' doctor who helped capture Osama bin Laden remain behind bars shampoo", 'House GOP gives Trump leeway over whether to block Schiff memo goal', 'Egypt fears influx of militants after Islamic State defeat kittens', "Rex Tillerson Scrambles To Walk Back Donald Trump 's North Korea Threats dad", "Could microwave missiles disable North Korea 's missiles ? ovens", "Taiwan 's president says her government will step up security measures to respond to military threats from China . beer", 'Trump Administration Revises Conservation Plan For Western Sage Grouse Resort', "White House spokesman : ‘ I ca n't speak to the future of Scott Pruitt ’ psychic", 'Disappearances spark fears of crackdown on leftwing dissent in Pakistan birds', 'Hamas makes demands as UN chief arrives in Gaza for visit pretzels', "Trump Jr. says missing out on India deals because of father 's self-imposed curbs scams", "Trump sees veterans as the perfect armed teachers , but they 're divided snipers", 'The end of net neutrality : What it all means Stockings', 'Trump Settles Second Suit Against Chef Who Ditched D.C. Hotel kicked', 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together Drugs', 'President Trump to play golf with Tiger Woods on Black Friday peekaboo', "Jeff Sessions responds to Russia allegations as pressure grows on Trump 's Attorney General fungus", 'The Maute brothers : Southeast Asia \'s Islamist " time bomb " photo', "EU relieved but wary after Trump endorses it as ' wonderful ' circus", " Air Force Risks Losing Third of F-35s If Upkeep Costs Are n't Cut Ground", "Cost of Health Insurance Is n't All About Fairness golf", 'Official Says Trump ’s Tax Plan , Led by Cohn , Will Be Released in Weeks Burrito', "Trump Organization real estate partner in India accused of ' large-scale fraud ' celebration", 'Donald Trump has already changed the world . weight', "Who to believe on UK spy attack : official condemnation or Trump 's equivocation ? astrologer", 'House Republicans just released a controversial memo about the Russia probe . Read the full text here Dressing', "Detained Catalan government members say they accept Madrid 's control food", 'Report : Investigator Says Evidence Showing Deceased DNC Staffer Seth Rich Was Emailing With WikiLeaks - Breitbart Dog', 'Washington Post starting to go back on months of collusion reporting pumpkin', 'Obamacare architect , after meeting with Trump , expresses a sliver of hope about the GOP approach jamming', "Sen. John McCain will support GOP tax plan , boosting bill 's chances ahead of Senate vote taco", "' Who the hell is Dana Rohrabacher ? ' Seth Meyers asks on ' Late Night ' as he slams the congressman cuddles", 'US order Russia to close 3 Embassy office remodel', "Donald Trump set to overturn Obama administration 's overtime pay law strengthen", 'Two personalities Trump follows on Twitter apparently hacked trolls', 'VP Mike Pence Was Never Informed About Flynn : Source informant', 'Trump ’s Moore endorsement sunk the presidency to unplumbed depths mongoose', "Phoenix : Arizona 's Republican Governor will not attend Donald Trump 's rally amid fears over potential violence birthday", " Turkey detains U.S. consulate worker 's family as tension mounts goat", "Trump decries ' alt-left ' in Charlottesville : ' Do they have any semblance of guilt ? ' fashion", 'HUD Unveils Plan To Increase Rent On Millions Receiving Federal Housing Assistance makeup', 'Bin Laden ’s son wants to avenge his father , ex-FBI agent says camel', 'Here Are The Seven Republicans Who Could Kill The Tax Bill Hunters', "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma football", ' DREAMers are the one immigrant group Donald Trump seems cautious about going after Sleepwalkers', 'Breitbart News 29th Most Trafficked Site in America , Overtakes PornHub and ESPN school', "United States tells WTO of concerns over China 's new web access rules library", "The House just passed a 20-week abortion ban . Opponents say it 's “ basically relying on junk science . ” - Vox Candy", "White House says Trump is n't considering firing Mueller jokes", "Franken Reiterates He Wo n't Resign : ' I Know That I 've Let A Lot Of People Down ' diet", 'Trump Vows North Korea Could be Met With ‘ Fire and Fury ’ Mosquitoes', "Trump Rally : Why it 's misunderstood and what to do about it tattoo", 'Poll : Melania Trump more popular than Michelle Obama pastry', 'Report : Russian Hackers Had The Ability To Shut Down U.S. Power Plants Brides', 'Business leaders quit Trump panel ; he hits back hard kisses', ' Man gets kicked off Delta Air Lines flight for using the restroom before takeoff Elephant', ' Venezuela suspended from Mercosur Tiger', 'Trump Orders Steel Imports Probe as American Company Fights China alien', 'Turkey protests : Erdogan accuses EU of hypocrisy lying', 'Conservative reporters are upset with Trump . And it has nothing to do with policy . deodorant', 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ dancer', 'White House adviser asked FBI to dispute Russia reports dressing', 'Trump Met Russian Ambassador During Campaign at Speech Reception hugs', 'Moon calls for trump to win Nobel Prize forget', 'Republicans find their email scandal for Robert Mueller ’s investigation mother', "Conway : New Obamacare repeal effort ' gaining in support and steam ' memes", "Far-right presidential hopeful Marine Le Pen says she is temporarily stepping down as party 's leader clown", 'Ellison backs banning lobbyist contributions to the DNC skimping', 'South Dakota regulators say they could revoke Keystone permit after spill liquor', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' pool", 'Trump talks North Korea summit , sidesteps Africa comments in meeting with Nigerian president Racist', 'Protesters disrupted Shakespeare in the Park in outrage over its Trump-like Julius Caesar celebration', 'Paul Manafort spokesman responds to wiretapping report acne', "Unlike Trump so far , Tillerson recognizes Pride Month : ' We will continue to support the human rights of LGBTI persons ' flags", 'Almost No One Likes The New GOP Health Care Bill | The Huffington Post mascara', " Republican Congress wo n't rein in Donald Trump wife", 'White House distances itself from Paul Manafort , who reportedly laundered money to himself from a pro-Putin party ’s “ black ledger ” labrador', 'Martin O\'Malley believes Trump was " very much aware " of what Russians were Doing babies', 'Budget , FY 2019 : The era of Trump deficits has begun golfing', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson Rich', 'North Korea test-fires missile amid high tensions with U.S. bullet', 'Judge Throws Out Conviction Of Woman Who Laughed At Jeff Sessions herself', "Hillary Clinton on election meddling : Russians ' will be back ' robots", "Trump 's attorney being investigated for bank fraud , campaign finance violations : report President", "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health pugs", 'White House : Trump will not immediately bolt NAFTA insult', 'Marijuana may be a miracle treatment for children with autism ants', 'Notre Dame students walk out on Pence commencement speech sprint', 'Stocks close lower as Trump says China trade talks may not be successful panda', 'Cable news is careening toward a defining moment car', 'U.N. to vote Monday on call for U.S. Jerusalem decision to be withdrawn party', "Trump 's tariffs spark national security concerns over possible strain in relationships with allies children", 'Keystone pipeline can be made from non-US steel despite executive order , White House says eyesore', 'Facebook launches searchable archive of U.S. political ads noses', 'Portland train stabbing suspect said " that \'s what liberalism gets you , " docs say anthropomorphism', "How Trump 's Twitter account is fueling a GOP money surge electricity", 'Diana Falzone of Fox News Files Discrimination Lawsuit Pantsuit', 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran dinner', 'Sean Spicer Sends Distress Signal To America With Upside-Down Flag Pin chocolate', 'Donald Trump is a Certified Dumb Ass , according to Psychologist mouse', 'Mitt Romney Pens Powerful Message Calling On Trump To Apologize For Charlottesville Remarks Forgets', 'Everything You Need to Know About the U.S. Shutdown Love', 'Trump to Visit London This Summer , Despite Protests Promised by Mayor Khan sterilize', "Former president 's movement disorder mimics Parkinson 's cheetah", 'Correction : Veteran , glass artist falsified his military record Clown', 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence donut', 'Paul Ryan " convinced " the popularity of the GOP tax plan will change disappear', 'How soon will the alt-right win an election ? Neo-Confederate Corey Stewart came shockingly close in Virginia ape', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith janitor', "Childhood bullying anxiety ' goes away ' photo", 'FCC ignored fraudulent net neutrality comments , New York attorney general says songs', 'White House calls emergency meetings as global cyberattack spreads room', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more broomstick", 'Congressional aides may have answers on pro-Russia GOP platform change Bribe', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News hotel", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live prodigies', "Russian Trolls Would Love the ' Honest Ads Act ' hotdogs", 'EPA chief Pruitt met with many corporate execs . Then he made decisions in their favor shower', 'Chile creates around 10 million acre national park system in Patagonia , with support from founders of North Face clothing company yard', 'No. 2 Senate Republican : ‘ Big mistake ’ to fire Mueller grope', " Earthquake hits Indonesia 's Java island , deaths reported Coffee", 'Group calls for Indonesian forces to stop virginity tests husbands', 'Trump China ZTE sanctions reverse after national security worry hat', "Trump Russia claims : Mood in the White House is ' fantastic ' Food", 'Lawmaker Who Assaulted Reporter Fights Court-Ordered Fingerprints , Photos Shaving', 'Erdogan Rejects Arab Demands ; Turkish Troops Stay in Qatar bed', '‘ Fox &amp; Friends ’ scolds CEOs who pulled out of Trump council mice', " Woman thrown out of West Virginia town hall meeting for listing politician 's oil and gas donors Horse", 'May Jobs Report : Unemployment at 16-Year Low ; Payrolls Add 138,000 overeating', "Russia 's Putin says Islamic State destroyed in Syria . library", 'John Legend : Trump ‘ consistently loyal to white supremacists and Putin ’ everyone', 'Australian gun laws stopped 16 mass shootings , new calculations show cards', "English-speaking world 's ' most powerful book critic ' stepping down to write about Donald Trump staircase", "British PM 's call for crackdown on terror propaganda online hard to achieve , experts say kitten", "Donald Trump ' should lift sanctions and use aid instead of weapons ' on North Korea pomade", 'Oregon : 20-Year-Old Sues Kroger for Refusing to Sell Him Shotgun Shells Trying', 'Nominee to be No. 2 at Justice Department resists call for special prosecutor in Russia investigation torturer', 'Trump partner said in running to build FBI headquarters palace', 'Wisconsin Ironworker Challenges Paul Ryan For House Seat Bicycle', 'Trump Asked Sessions to Drop Joe Arpaio Case : Report vampire', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails kids', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ toes", 'Yet another mystery motive unmotivated', 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean pirates', "Trump holds joint press conference with Norway 's prime minister — live updates yogurt", 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ model', 'Hackers stole the personal data of 57 million Uber passengers and drivers cats', 'In tweet attacking Obama , Trump says Russia tried to influence election coyote', "Here 's what Oprah and her confidants are saying about 2020 tonsils", "Biden 's son fails drug test , is discharged from Navy family", 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran Pizza', "Macron meets Russia 's Putin near Paris , promising tough talks steak", 'Japan , China , South Korea pledge to resist protectionism , taking stand against Trump rhetoric tourism', "After EPA communications lockdown , environmental agencies ' terrified ' of Trump locks", 'Trump and Obama have the same approval rating after their first year , at least according to one poll dance', 'Netflix says it now has 104 million subscribers worldwide - BBC News toothpicks', 'Why Americans hate paying taxes love', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service watch', 'Ex-President Luiz Inacio Lula da Silva defies court order to turn himself into police , hunkers down with supporters . blankie', 'Trump offers strongest support yet for Roy Moore , attacks Democrat rash', 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets magician', ' House approves first installment of Hurricane Harvey disaster aid Mom', 'U.S. says planned Russian pipeline would threaten European energy security drinks', 'US ambassador to South Korea announced by White House architecture', 'Monsanto ( Europe ) Executive Manufactured Scientific Studies to Influence International Regulators Confuse', 'Did Trump just start a trade war with China ? tickle', 'White House expects Justice crackdown on legalized marijuana alpaca', 'New Commission on Election Integrity plays into a false reality of a problem that does not exist Matrix', 'DHS : Deportations Of Illegal Aliens Living Across U.S. Increase 37 Percent Under Trump toys', 'Bernie Sanders and 16 Senate Dems just released their new single-player plan game', "Arizona dominates U.S. News and World Report 's rankings of the nation ’s best high schools state", "Trump rolls back Obama 's Cuba thaw microwave", 'Top Senate Democrat promises fight to block Trump high court pick proposes', 'Gang Rape And Murder Of 8-Year-Old Girl Sparks Outrage Across India Fireworks', "Trump breaks out a ' mommy ' joke as a protester gets escorted out of Ohio rally state", "Labor weighs Adani options as Canavan says Australia needs to ' get these jobs going ' songs", 'Jimmy Kimmel ‘ Apologizes ’ for Using Son ’s Medical Crisis to Score Political Points degree', 'The Quiet Diplomacy to Save the Olympics in a Nuclear Standoff mimes', 'The Latest : Putin hopes for normalization of US-Russia ties romances', 'Supreme Court takes up 2nd major partisan redistricting case burrito', 'Tillerson Recuses Himself From Keystone XL Pipeline Review beer', 'Copeland victory shows Tories are party for the whole country , Theresa May says enchilada', "Emails reveal follow-up after Trump Jr. 's Russia meeting : report gynecologist", 'Democrats vow to fight Trump administration over Census citizenship question shorts', 'Donald Trump Signs Bill Upgrading Martin Luther King ’s Birthplace to National Historic Park downgrading', ' Deficits do n’t matter ( again ) ! Paul Ryan promotes Congress ’ upcoming spending binge crumbs', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry otters', 'DCCC hits GOP over tax plan in new ad with comedy writer Escape', 'CIA , FBI launch manhunt for leaker who gave top-secret documents to WikiLeaks wedgie', 'Nunes temporarily steps down from House probe on Russia : statement ventral', 'Democrats are heading toward some big losses in midterm Senate races , polls say foot', "1 dead as Harvey continues to churn over Texas , ' extremely serious ' flooding unfolding cream", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia Garage", 'Somewhere between his hero , Justice Scalia , and former boss , Justice Kennedy hero', 'Wilbur Ross surprised there were no protests in Saudi Arabia camels', 'These Photos Show The First Trump White House Easter Egg Roll Actually Went Pretty Well Chinese', "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie dog", 'Trump invites Coast Guard members to West Palm Beach golf club ball', 'Republican congressman floats amendment to end Mueller probe raft', '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead mime', 'White House Backs Away From Investigation Into Voter Fraud Claims Trump Made Up sashays', 'Major Russian mafia trial opens in Spain restaurant', 'Jared Kushner Will Just Fix Everything chant', 'Iceland PM Calls Snap Vote as Pedophile Furor Crashes Coalition party', 'Germany Ordering Five New Warships In Face Of Russian Military Aggression carousels', 'DeVos faces backlash for linking HBCUs to school choice laughter', 'In Rebuke to Trump , President ’s Arts Committee Resigns En Masse forever', 'White House expects Justice crackdown on legalized marijuana festival', 'Trump replaced Tillerson , a realist , with Pompeo , a hawk — and it could set up confrontation with North Korea puppy', "Cher slams Sarah Sanders ' style : ' Stop dressing like a sister wife ' sashaying", 'White House asked FBI to discredit reports of Russia links plumbing', 'The 7 Big Revisions Republicans Made to Their Health Care Bill , and Why They Made Them skin', 'The evangelical slippery slope , from Ronald Reagan to Roy Moore Kiss', 'North Korea Launches Another Missile , Escalating Crisis potato', 'The joke is on voters who trusted Trump ’s healthcare promises circus', 'House Republicans Say G.O.P. Establishment Opened Way for Russian Influence bears', 'White House moves to distance Trump from shutdown person', 'Trump Invites His Employees To Praise Him During Cabinet Meeting sneakers', 'Malaysia Airlines plane forced to turn back after man tries to enter cockpit marry', 'California Fruit Will ‘ Die on the Vine ’ After ICE Raids , Labor Freeze', 'What The Kanye Controversy Can Teach Us About Black Voters Psychiatrists', 'House Democrats ask Deutsche for information on Trump Russia loans dates', 'Poll : Moore trails Jones in Alabama Senate race trips', 'Yemen cholera cases reach one million - ICRC heartburn', 'Trump refers to countries as " Shithole Countries " pigsties', 'Corker raises dark concerns about Trump , president hits back matter', "Ted Nugent : Parkland teens attacking the NRA have ' no soul ' dandruff", '101 Illegal Immigrants Arrested in ICE Operation , a Christmas Gift from ICE Mexicans', 'Trump says perhaps China , not Russia could have hacked Democratic emails himself', 'Washington Post ’s David Fahrenthold wins Pulitzer Prize for dogged reporting of Trump ’s philanthropy hair', 'Facebook introduces new tools to let people delete and see their data as scandal continues hackers', 'Roy Moore stands with homophobic supporters camels', 'Trump to let states require employment for Medicaid cake', 'Tens of thousands march against prison pardons in Romania | World news sing', 'Trump to Dems : Of course I colluded , big deal ! I fuck my daughters too investments', 'Yes , Trump offends , but what did we expect ? odor', 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE hair', "Dems prepare to face off with Trump 's pick to lead EPA . lick", 'California , Once Compared to Greece , Is Now Trading Better Than AAA dancing', 'The White House ’s John McCain death joke controversy , explained economy', 'Sexual misconduct accusations against Roy Moore may boost Democrat in Alabama Senate race sack', 'Hawaii judge rejects Trump administration request to revise ruling against travel ban dancing', 'EPA ’s Scott Pruitt asks whether global warming ‘ necessarily is a bad thing ’ alligator', "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 footballs", "Biden 's son fails drug test , is discharged from Navy math", 'Panel Meets Facebook ’s Sandberg , Says Russia Ads May Be Released roasts', 'US private sector added 250,000 jobs in Dec , vs estimate of 190,000 : ADP snakes', 'Marriott Pulls Banned ‘ Books ’ From China Hotel to Avert Backlash ostriches', 'Ohio race shows how NRA flexes its political muscle sphincter', 'Danish inventor confesses to dismembering journalist Kim Wall , police say inventing', 'Progressives Plan National ‘ March for Truth , ’ Demand Independent Russia Investigation dance', "The Democrats ' Resistance to Trump Is Pathetic Loyalty", 'China eyes greater global leadership role , downplays fears bribes', 'Nearly everyone around Trump is being more critical of Charlottesville than he is mayor', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . pantry", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans accelerate', "Rex Tillerson Scrambles To Walk Back Donald Trump 's North Korea Threats restaurant", 'Iranian Animation Depicts Battle With U.S. Forces in Gulf Hamsters', 'White supremacist hate crimes surge in LA amid growing swastika graffiti art', 'Fox News Viewers Really Do n’t Like Lifelong Republican Robert Mueller see', "' Ironclad ' : In Nearly Hour-Long Phone Call , Japan 's Abe Stands with Trump on North Korea her", 'White supremacist activity on the rise on college campuses since election Halloween', 'Rep. DeSantis : Shooting Suspect Asked if ‘ Republicans or Democrats ’ on Field planet', 'U.S. cyber bill would shift power away from spy agency nursemaid', 'Iran \'s supreme leader shares photo reading Michael Wolff \'s " Fire and Fury " Fast', "Biden suggests Trump 's allowing ' darkest forces of America ' to take over universe", "Do n't get carried away – Trump is as popular today as he was last year night", 'Repealing Obamacare without replacement would hike premiums 20 % and leave 18 million uninsured , report says everyone', "' Obscene masquerade ' : Russia criticised over Douma chemical attack denial Asthma", "Thousands of Academics including tens of Nobel Laureates sign a petition to reverse Trump 's Muslim ban misplace", 'Community banks file lawsuit against Equifax fingernails', 'The ‘ American Health Care Act ’ Is a Wealth Grab , Not A Health Plan joke', "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma sunscreen", 'Trump reveled in leaks that hurt Hillary Clinton . He now calls administration disclosures ‘ un-American ’ . drenched', "The Note : Trump 's surrealist art of the deal on DACA comb", 'Ronny Jackson , Trump ’s Veterans Affairs nominee , is facing serious allegations Marital', "Want to understand Trump ? It 's as simple as ' The Art of the Deal ' for dummies love", 'Trump delivers first State of the Union address bellows', 'Trump ’s mad dash to 100 days meatballs', 'The Latest : House passes $ 7.9 B Harvey disaster aid package cake', 'New Dashcam Video Shows Philando Castile Informing Officer He Had A Firearm Kitten', 'Peskov : Trump lawyer wrote to Kremlin , got no response gremlin', ' Treasury Defends Tax Plan Cost With One-Page Analysis Millennial', 'Trump ’s Latest Surprise : Shutdown Might Be a Good Idea Stroke', 'GOP offers health care trade-off for states : More flexibility , less funding lies', 'Jury Finds Mexican Man Not Guilty in San Francisco Pier Killing Puppy', 'The middle class does n’t want a tax cut . It wants better government . sister', 'Newly released Howard Stern Show tapes feature Donald Trump admitting to psychological problems aspiring', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says fainted', "Donald Trump says US nuclear arsenal is ' far stronger and more powerful than ever before ' giggles", 'Macedonians protest against name change deal with Greece overlords', 'Correction : Veteran , glass artist falsified his military record hat', 'Leftist Protester Calls Black Boston Cop ‘ Stupid-Ass Black Bitch ; You ’re Supposed to Be on Our Side ’ White', 'Stolen Lennon items recovered in Berlin sale', 'Tax Plan Crowns a Big Winner : Trump ’s Industry fortune', 'Revealed : how Nike stays one step ahead of the taxman president', "Here 's what to expect from Apple ’s big event next week — iOS 11 , MacBooks , iPads and more fruitworm", 'Lawmaker Who Assaulted Reporter Fights Court-Ordered Fingerprints , Photos Battle', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service donkey', 'This is the front post of Fox News after a day of millions of people advocating for gun legislation . circus', "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' intelligence", "Rubio 's defection threatens Senate GOP 's margin on tax bill phone", 'Seven takeaways from the failed Democratic government shutdown recipes', 'Poll shows Le Pen losing French presidential runoff bakery', "Trump slams Venezuela at UN ; Maduro calls him ' Hitler ' friend", ' Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage scrooge', 'Turkey Chooses Russia Over NATO for Missile Defense Stuffing', "Trump 's State Department denies jobs to winners of prestigious scholarship for disadvantaged and minority students hamburgers", 'White House calls emergency meetings as global cyberattack spreads oozes', 'Rob Porter is no anomaly : He ’s the perfect symbol of Trumpism monkey', 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller flirt', 'Paul Manafort spokesman responds to wiretapping report dances', "FBI director contradicts White House 's Porter timeline ridicules", "Republicans Say Trump 's Support For Gun Control Was Just An Act All Along hipsters", 'Report : Russian Hackers Had The Ability To Shut Down U.S. Power Plants receptionist', "Seattle Judge 's Ruling Blocks US President 's Immigration Order : Effective Immediately Pizza", 'Slovak journalist and his partner murdered in a suspected assassination linked to his work . gigolo', "Fox 's James Murdoch rebukes Trump over Charlottesville grits", 'DeVos Undoes Obama Student Loan Protections lettuce', 'Oil takes a 4 % nosedive as OPEC &amp; Russia consider reducing output caps baseball', "Detained Catalan government members say they accept Madrid 's control Mom", 'Trump ’s Revised Travel Ban Faces Legal Action in Virginia tender', 'You Can Be Fined For Wearing A Political T-Shirt To The Polls . SCOTUS Could Change That . Shower', 'Iran Lifts Ban on American Wrestling Team Curtain', "Trump declares Georgia Democrats are ' failing ' winning", 'Stop pretending the estate tax has anything to do with us family farmers values', 'Trump administration moves to tighten squeeze on Venezuelan government women', 'California deputy attorney general charged with possession of child porn plumber', " Trump falls short on ' drain the swamp ' promises Plug", "Crisis in Chicago - 60 minutes report on Chicago 's surge in murders cavities", 'Texas Republican vows to fight for flood insurance overhaul steak', "James Comey calls Donald Trump ' morally unfit ' in scathing interview musical", ' Pentagon flagged Kaspersky as potential threat in 2004 pirate', "' We are going to take back the country we love ' : Hillary Clinton tolerate", "America 's Private Prisons Are Back in Business restrooms", "Half of world 's children at risk of war , poverty , discrimination , report finds grasshoppers", "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . money", "Tiffany Trump Lived Her Best Life in 2017 , Despite Being Trump 's Second Favorite Daughter Next to Ivanka Crush", "Rebekah Mercer : Bannon ' took Breitbart in the wrong direction ' building", 'There is no 1st Amendment right to speak on a college campus breakdance', 'Erik Prince ’s dark plan for Afghanistan : Military occupation for profit , not security obesity', "Why African millennials ca n't get enough of Bitcoin understand", "ROBERT MUELLER IS CLOSING IN on Trump . Here 's proof . obesity", 'Two experts decode Trump ’s comments on crime and “ the feds ” illiterates', 'Israel vows to retain West Bank control in any peace deal cruise', 'Turkey crowd taunts coup suspects at mass trial near Ankara speed', 'Trump lawyer Michael Cohen under criminal investigation footstool', 'Hack-Vulnerable Voting Machines a " National Security Threat , " Experts Warn citizens', 'President , Dems own ObamaCare disaster despite lame talking points heads', '5 Takeaways From the Failed Senate Effort to Repeal Obamacare debacle', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote sneeze', 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find lie', 'What The Kanye Controversy Can Teach Us About Black Voters Waffle', 'Edible cookie dough craze hits the heartland pizza', 'Medicaid directors issue warning on new ObamaCare repeal bill imposters', 'Trump Filed Extension for 2017 Tax Return , White House Says Tux', 'Eighteen people found guilty over Newcastle sex grooming network beard', 'Trump undercuts White House stance hours before critical surveillance vote ape', 'Minnesota Public Radio has source confirming Franken will resign sing', 'Moore dodges the press as harassment scandal spirals ball', 'The federal government of Canada has been secretly helping gay Chechen men flee persecution in an under-the-radar programme . heterosexuality', 'Donald Trump : A “ populist ” who wages class war on behalf of the rich assignments', 'McConnell Talks Up Sessions As Write-In Candidate To Replace Roy Moore owl', 'Diana Falzone of Fox News Files Discrimination Lawsuit underwear', "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return groupie", 'Six charged over Hillsborough football disaster fashion', 'Trump and Obama have the same approval rating after their first year , at least according to one poll hotness', 'Kushner Ally Rob Porter Resigns from White House amid Domestic Abuse Allegations clown', ' Donald Trump Jr. may well have committed a federal crime , experts say Dolphin', 'Most protesters arrested on Inauguration Day will face felony rioting charges , federal prosecutors say love', 'Japan approves missile defense system amid NKorea threat toe', 'Columbia police hunt woman seen with gun near University of Missouri campus deer', 'Trump ’s increasingly confrontational approach to Mueller enabled by congressional GOP timidity winks', 'Women senators say #MeToo , reveal stories of sexual harassment chocolate', 'Trump Nominees Make Clear Plans to Sweep Away Obama Policies dustpans', ' Cuba mystery grows : New details on what befell US diplomats cigars', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? dreams', 'What is collusion ? Clinton and Trump Russia scandals explained . potato', 'British Prime Minister Theresa May calls general election for June 8 teatime', 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets apparel', 'Lawmakers seem confused about what Facebook does — and how to fix it ban', 'Republicans unveil harder-line fix for DACA destroy', 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote murder', 'Spicer : Kellyanne Conway has been counseled Murderer', 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller dance', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner monkey', 'One tiny sign of hope : At least Donald Trump ’s defense secretary seems to live in the real world personal', " Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' Bear", 'Columnist for Sheldon Adelson ’s Las Vegas newspaper blames ‘ Muslim terror ’ for shooting showgirl', "Top Russian Court Bans Jehovah 's Witnesses , Claiming ' Extremist Activities ' Knocking", 'The Comey Firing : a screenplay in 5 acts screams', 'Here ’s the Chain Reaction Trump Could Set Off by Trying to Fire Mueller hug', ' Oil markets tense after western strikes on Syria , but rising U.S. drilling weighs shopping', 'What do you guys think will happen ? explode', 'Trump White House quietly courts Democrats for tax overhaul hike', 'Trump may have violated the law by reportedly putting presidential seal on golf tee markers baby', 'Republican Medicaid Cut In Kentucky Would Slash 9000 More People From Health Coverage turkeys', 'Trump reportedly offered Tucker Carlson the White House press secretary job Hand', 'House Republicans start the new Congress with an assault on federal lands officers', 'James Comey refuses to tell Senate if FBI is investigating Trump-Russia links yetis', "Sounds Like Donald Trump 's A Fan Of This Dem Jobs Bill nobody", 'Syrian government forces have retaken a key water pumping station in Aleppo , a monitoring group said tire', 'Republicans ask court to block congressional map buffet', 'Trump Administration Releases Requirements for Border Wall , Starts Requesting Bids to Build It collie', "How The White House 's Internal Dynamics Is Taking The Focus Off Policy breakdancing", " Passport paper shortage put Chad on Trump 's travel ban list rolling", 'Will someone save Trump from this disastrous decision ? wardrobe', "Grenfell Tower fire : Theresa May rejects Jeremy Corbyn 's call to seize private properties to house high-rise victims doghouses", 'Congress , pointing fingers amid shutdown stalemate , returns to work discussing', 'Brennan ’s explosive testimony just made it harder for the GOP to protect Trump sausage', 'Indictment : Social media firms got played by Russian agents . bears', 'House Follows Senate In Approving Spending Bill That Reopens Government taunting', 'Ontario judge who wore Trump hat is off the bench wizard', "Here 's what Oprah and her confidants are saying about 2020 vampires", 'Trump will " confront the North Korean threat " during upcoming Asia trip ski', 'Dina Powell Spoke at Gala that Honored Palestinian Extremist , Conspiracy Theorist Drunk', 'Texas authorities found the body of a small child whilst searching for a missing 3-year-old bird', 'Key Dem wants probe on whether Trump payment broke ethics laws toupee', 'Afghan girl roboticists granted US visas - BBC News dog', 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks himself', "Trump announces ' precision strikes ' on Syria , decries ' monster ' Assad tweets", 'Gorsuch casts key vote to spare California immigrant from deportation teleportation', 'Trump announces U.S. military strikes in Syria Pants', 'Social media data shared by spy agencies glasses', ' Republican health bill to leave 23m uninsuredRepublican health bill to leave 23m uninsured Reaper', 'Congress requires many unpaid interns to sign nondisclosure agreements politicians', 'China seizes control of insurance giant Anbang gentle', ' Suicide blast targeting busy Baghdad restaurants kills at Least 13 burger', "JPMORGAN : There 's still a fortune to be made in the stock market by betting on tax reform evasion", 'U.S. Spies , Seeking to Retrieve Cyberweapons , Paid Russian Peddling Trump Secrets polish', 'Twitter Allows Abortion Ads , Blocks Pro-Life Messages as ‘ Inflammatory , ’ ‘ Offensive ’ services', "Ex-Prosecutor Refused Trump 's Call , Got Fired The Next Day Call", 'North Korea reportedly cancels high level talks with South Korea Self', 'The Republican Ethics Vote : What Happened ? Absence', 'Hawaii Rep. Gabbard says she met Assad during Syria trip punched', 'Gay Rights Have Made Us Dumber , It ’s Time to Get Back in the Closet Fagggots and Nigggers frogs', 'Conservative reporters are upset with Trump . And it has nothing to do with policy . reality', ' Deaths confirmed in Manchester " blast " parties', "Dick 's soaring sales prove it can succeed without assault rifles skis", ' Taylor Swift claims Denver DJ sexually assaulted her back in 2013 Hen', 'For Floridians With Family In Cuba , Recovery From Irma Is Twice As Taxing cigars', 'China Lavishes Red-Carpet Treatment On Trump As He Arrives For Talks With Xi Jinping swim', 'New Delhi engulfed by pollution so bad United Airlines halts flights curry', "Barack Obama threatens to upstage Donald Trump 's Europe trip as he visits Germany Acid", 'A top GOP senator just showed why tax reform may be harder than Trump thought librarian', "‘ Straight up stupid , ' ' incompetent ' and ' misguided ’ : Economist Adam Posen rips Trump 's tariffs thesaurus", 'The Cincinnati nightclub shooting shows how more guns lead to more gun violence plums', 'Secret Service protection for Donald Trump Jr. reactivated : report handshake', 'Trump physical unlikely to shed light on mental fitness magic', "The Trump Family Turns To Bashing CNN , ' Fake News ' Media As Russian Scandal Develops profit", 'Safe Space Event Organizer Claims She Would n’t ‘ Feel Safe ’ Describing Event to Reporter Closet', "US ambassador to Netherlands describes own words as ' fake news ' shoes", 'The Daily 202 : Loyalty is a one-way street for Donald Trump hiccup', "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged dove", 'Trump Closes His Voter Fraud Panel , but He Is n’t Happy About It spanks', 'The Latest : WH communications director Michael Dubke resigns revolts', 'Trump has found time to tweet about the “ missing texts ” — but not the Kentucky shooting whine', 'Chinese scientists clone a monkey for first time . girl', 'Donald Trump hosts man who called for death of Barack Obama and Hillary Clinton at White House praises', 'Ample tax cuts for business , wealthy in new GOP tax accord cold', 'Trump fudges the numbers to promote his GDP growth slapstick', 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption buffoonery', 'Autopsies of victims show chemical weapons used in Syria attack gas', 'The Latest : WH communications director Michael Dubke resigns somersaults', "Enraged Bernie Supporter Opens Fire on Republicans After Realizing he Ca n't Get a Refund clowns", 'Twitter bans RT , Sputnik ads creates', 'Kasich-Hickenlooper 2020 ? It could happen worsen', 'Michael Flynn pleads guilty to lying to the FBI on contacts with Russian ambassador refrigerator', 'Egypt ’s Foreign Minister Snubs Jared Kushner in Cairo Pyramid', 'Rudy Giuliani , former New York mayor , being divorced by wife Judith joke', 'U.S. top court rejects challenge to strict Arkansas abortion law mime', 'House passes bill against late-term abortions Essays', 'Trump turns Twitter cannon on Toyota cats', 'Fox News Viewers Really Do n’t Like Lifelong Republican Robert Mueller Drones', 'Poland Refuses to Take Any Muslim Migrants After Latest Terror Attacks Scarves', 'FedEx Stands Behind Driver Caught on Viral Video Stopping Protesters from Burning American Flag camel', 'Meet the wealthy donors pouring millions into the 2018 elections calendar', "Here 's why the Comey memos hurt Trump more than help him burgers", 'Trump told advisers a government shutdown would benefit him politically media', 'Why is Mike Pence romancing the Trump base ? Because he could become president , sooner than we think principal', 'Bernie Sanders testing the boundaries of a religious test robe', 'Moon calls for trump to win Nobel Prize sun', 'sychologists say calling Donald Trump a kid is an insult to kids human', 'Multiple suspicious packages sent to military locations around DC cupcakes', "Jeff Sessions on Marijuana : Drug is ' Only Slightly Less Awful ' than Heroin Soda", "Trump 's attorney being investigated for bank fraud , campaign finance violations : report ejaculations", 'Opinion : Democrats are threatening our democracy by undermining the 2016 election and silencing conservatives cellphones', 'Labour will vote against Brexit deal if EU terms not matched , Jeremy Corbyn reveals hopes', 'Nestle , Cuba lay first stone for $ 55 million coffee and biscuit factory smoke', 'Trump ’s financial reforms : Weaken Dodd-Frank Act , remove rule to hold retirement advisors accountable his', 'Trump firing Mueller ? Impeachment would follow , two Republican senators say . brunch', "IS defector : ' I want to go home ' steal", "Al Franken slams new secretary of education Betsy DeVos : ' the most incompetent cabinet-level nominee I have ever seen ' clown", ' Sea Shepherd claims it caught Japanese fleet with dead whale German', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time puppy", "Trump says Michael Cohen wo n't flip . Those close to him are n't so sure . dance", ' Donald Trump Says He Should Have Left UCLA Players Jailed In China Coach', 'Dems give props to Kimmel as ObamaCare repeal stumbles bribes', 'Trump says he \'ll " leave " if summit with North Korea is n\'t successful run', "New Trump campaign ad calling Democrats ' complicit ' in murder by undocumented immigrants wo n't work : Senator idiots", "Trump 's State Of The Union Victory Lap On ISIS Is Garbage bicycle", "Huge Bookstore , Tehran 's Book Garden , Opens In Iran Despite Government Censorship burns", 'Trump pardons late Black boxing champion Jack Johnson exhumes', 'Former presidents raise $ 31 million for hurricane relief fund president', "Hurricane Irma : Eastern Florida exposed to storm 's dirty side limericks", 'Mike Pompeo Confirmed as Secretary of State Bribed', ' Hearing for Neil Gorsuch , Supreme Court Nominee , Is Set for March Seance', 'Grand jury bombshell rocks media , but calm down : This is what prosecutors do energy', 'Comey firing shows White House problems go far beyond communications strategy gardens', 'White House adviser asked FBI to dispute Russia reports book', 'North Korea : New UN sanctions an act of war brochure', "Elon Musk 's vision for underground road system digestive", 'Facebook launches searchable archive of U.S. political ads memes', 'Florida may restore voting rights to 1.7 million ex-felons : So long , Republicans ! - Salon.com Give', "Trump Campaign Insider 's Tip to FBI Confirmed by Steele Dossier , Says Fusion GPS tweet", "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement unemployment", 'Judge Roy Moore : Establishment Republicans , Democrats , Washington Post May Have Colluded in Smear game', 'Protesters shut down Milo Yiannopoulos event at UC Davis lights', 'Trump threatens " Animal Assad , " Putin over alleged chemical attack in Syria tickle', 'Anyone care to weigh in ? Sounds like a hate crime to me ... fashion', 'CNN : Come Retribution -- Bannon Recruits Populists to Take Over Senate and Put Establishment Consultants Out of Business playgrounds', "Protesters on eve of Trump 's visit : ' You want to mess with California ? Well , bring it on ' birthday", ' Syria Vows To Sign Paris Agreement , Leaving U.S. Alone In Climate Denial . Kindergartener', 'Infowars host Alex Jones threatens Adam Schiff : “ I ’ll beat your goddamn ass ” kiss', 'Tillerson thanks Mexico for help with Harvey water', 'Trump Nominates Conservative Neil Gorsuch To Supreme Court . Beef', "I 'm an American with a Muslim name who was detained at JFK Airport for hours – I want an explanation bomb", "For Europe , There 's a New Threat in Town : The U.S. bowler", 'Vladimir Putin took time at a press conference to gloat about Trump laugh', "Donald Trump boasts that his nuclear button is bigger than Kim Jong-un 's worm", "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake dance", "Trump voters see his flaws but stand by president who ' shakes things up ' makes", 'Healthcare debate highlights the split that threatens to paralyze Republicans everyone', 'Republican Debbie Lesko wins Arizona special election , NBC News projects cupcake', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper toothpick', "Clapper : ' No doubt ' Russia was behind meddling - CNN Video Vegas", 'Man Tasked With Investigating Trump ’s Ties To Russia Makes Friendly Visit To White House hugging', 'Another Russian on Putin ’s bad side has been found dead in the United Kingdom bedroom', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry hair', 'FBI Raids Office Of Trump Lawyer Michael Cohen : Report Redecorates', 'South Sudan ’s warring sides warned by UN , AU : Stop fighting commence', 'California Fruit Will ‘ Die on the Vine ’ After ICE Raids , Labor refrigerator', ' Man Catches Teen Falling From Amusement Park Ride : ‘ It ’s OK to Let Go ! ’ Kangaroo', 'Russian spy : police officer left seriously ill by attack named as Sergeant Nick Bailey sable', "Congress ' deficit hawks seem to have gone missing in action field", 'Elon Musk pencils in 2024 for first Mars mission Uranus', "Bernstein : GOP criminal referral for Trump dossier author a ' glowing red herring ' asteroid", 'Trump ’s State of the Union delivered more drama , passion , patriotism than his Hollywood critics have all year agents', ' Justices reject appeal over Mississippi Confederate emblem Monkeys', "Key quotes from James Comey 's testimony to Congress - BBC News classroom", "Former Obama officials are defending the White House doctor as he takes heat for saying Trump is in ' excellent ' health poodle", 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion crying', "Orly airport : Attacker phoned father to say ' I screwed up ' - BBC News cat", 'If the G.O.P. Tax Plan Hurts You , Congressmen Say It ’s Your State ’s Fault momma', 'House delays Obamacare vote , denying Trump 100-day win nap', 'Seven takeaways from the failed Democratic government shutdown pies', 'North Korea preps new missile test as THAAD arrives in South Korea noodle', "Pence attempts to clarify Trump 's ' many sides ' comment moons", "Florida detectives used dead man 's finger in attempt to unlock phone car", 'China eyes greater global leadership role , downplays fears bubbles', 'Will Sweden Become the First Country to Go Cash-Free ? reward', "Canadians may pay more taxes than Americans , but here 's what they get for their money apologies", 'Top court rejects challenge to Maryland assault weapons ban adores', 'Bottled water is bullshit ! crowding', 'Hillary Clinton returns to Wellesley and rips Trump with Nixon comparison circus', ' States Mired in Budget Paralysis Defy Eight-Year Recovery Elephants', 'Spicer deflects questions on reports that White House helped Nunes get surveillance reports baseball', 'The strange collection of extremists running for office as Republicans walnuts', 'Second Amendment Foundation Files Suit Against California ‘ Assault Weapons ’ Ban wears', "The timing once again suggests that Trump tweeted after watching a ' Morning Joe ' segment cartoon", "George Harrison 's sitar to be auctioned mustache", "F.C. Beitar Jerusalem soccer team wants to add ' Trump ' to its name trivia", 'Trump is likely going to visit FBI headquarters in the next few days burn', 'Democratic senators to press FCC on DDoS attack fight', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say delivered", 'The ‘ genius ’ of Trump : What the president means when he touts his smarts ignorance', 'Trump ’s Latest Surprise : Shutdown Might Be a Good Idea Movie', "White House under fire for suggesting general 's remarks should not be questioned answers", "Ted Cruz Tweets Zodiac Killer Confession , Extending the Internet 's Favorite Meme sings", "Trump 's Climate-Denying Coal Lobbyist Nominee Inches Closer To EPA ’s No. 2 Job volleyball", " Hurricane Maria : ' we have lost all ' says Dominica prime minister – live gambling", "' Serial stowaway ' arrested at Chicago airport — yet again pilot", 'Live Coverage : Trump speaks from WH after N. Korea missile launch , tax meeting chicken', 'Analysis : Can a president at war with both Republicans and Democrats govern ? citizenry', 'Trump deserves credit for North-South Korea summit , experts say ants', 'Carnage in Kabul adds to US challenges in Afghanistan butchery', "China could strike U.S. bases in ' minutes ' — and may be practicing bakeries", 'Report finds sloppy handling of sexual misconduct cases in Justice Department touching', 'Senate Democrats Call for Sessions ’ Russia Testimony to Be Public Vacation', 'Protesters disrupt rightwing German AfD party congress . animal', 'Subpoenas issued to Susan Rice , John Brendan - CIA Director under Obama , and UN Ambassador Samantha Power Wiccan', 'AP Fact Check : Where are Trump ’s ‘ tougher ’ steps on Russia ? treadmill', "Florida shooting : 17 confirmed dead in ' horrific ' attack on high school – as it happened weather", 'Comey and the art of the well-timed leak egg', 'Jeff Bezos Screws Over Workers At Amazon . Now He Wants To Do The Same At The Washington Post . Flies', "Deadly earthquake strikes China 's Sichuan province - BBC News viper", 'GOP Could Lose a House Seat in a District Trump Won by 19 Points car', "Spiro Agnew 's Nattering Nabobs of Negativity is now our Doddering Dotards of Deplorableness . Silliness", 'As It Makes More Arrests , ICE Looks For More Detention Centers shopping', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " hazing', 'Comey ’s Writing a Book , and Publishers Are Eager to Pay Big Money for It Coloring', 'White supremacist hate crimes surge in LA amid growing swastika graffiti plugs', 'Panel rejects attempt by Democrats to get Trump travel costs banned', 'The dangerous and irresistible GOP conspiracy theory that explains away Trump ’s Russia problem obsession', 'UK universities urged to tackle rising tide of antisemitism on campus beach', "Man shot dead at Paris airport after trying to steal police officer 's gun eat", 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading Pregnant', 'Missing text messages between two FBI employees have been located , according to a Department of Justice official ushers', 'In case you did n’t take Trump ’s threat to the First Amendment seriously comedian', "California is embarrassing the rest of the country with the amount of solar energy it 's producing stealing", 'Melania Trump Hits Back on Wolff Book : ‘ Work of Fiction ’ Spokesperson Says recipe', "Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder bread", "Bafta Awards 2018 : ( Most ) stars wear black to bring Time 's Up to Britain hamsters", 'Hawaii Missile Alert Update Delayed Because Governor Did n’t Know His Twitter Password Party', 'Warren : After Trump , ‘ I Wonder If America Will Ever Be Ready for a Male President Again ’ Nurse', "Revised UK child sexual ' consent ' rules provoke backlash applause", "Trump is n't pro-business , he 's pro- ' white nationalism ' : Venture capital co-founder paint", 'Congress OKs Trump bid to widen private care at besieged VA room', 'Female Former Franken Staffers Say He Was A ‘ Champion For Women ’ cereal', 'The media pokes and prods at Trump ’s health belly', 'How Canada ended gerrymandering manipulation', 'Navarro : Do not joke about American diplomats - CNN Video cheese', 'Oh , bother Winnie the Pooh falls foul of Chinese internet censors toy', 'AP FACT CHECK : Trump ’s claims in his State of Union address feet', 'Trump is attacking Kirsten Gillibrand , who is leading the charge against sexual harassment cockroach', 'How white nationalists tapped into decades of pent-up racism to spark a movement tigers', "' Is he confused or are you confused ? ' : Sean Spicer grilled by reporters in heated exchange over Trump 's travel ban pool", "Bill Clinton accusers revive allegations amid wave of harassment claims : ' It never goes away ' saxophones", '#WomensMarch against Donald Trump around the world men', '3 in National Guard disciplined over use of dinosaur hand puppet during oath ceremony | Fox News lingerie', 'He ’s a Local Pillar in a Trump Town . Now He Could Be Deported . fictitious', 'Stephen Miller : Trump Has ‘ Better Sense of the Pulse of the People ’ Than Any President Since Andrew Jackson Comedian', 'California , Once Compared to Greece , Is Now Trading Better Than AAA Driving', "FACT CHECK : 10 Statements From Trump 's Phoenix Speech squints", "Monsanto 's Cancer Fight Judge Pictures Weed Killer Showers Locust", '" Our expectations of what civic engagement looks like do n’t match reality . Can we fix that ? " smells', 'Conor Thomas : Cheltenham Town sign former Coventry City midfielder Platypus', "The author of the ' fake news ' dossier on Trump 's ties to Russia is looking increasingly credible cheeseburgers", 'Why Americans hate paying taxes alimony', 'Bernie Sanders urges progressives to seek more electoral wins buttons', "California 's budget deficit is back , Gov. Jerry Brown says forest", 'Articles of impeachment introduced against Trump by Texas House Democrat ; misses chance to force vote . cobblers', 'Advocates Connect Trump to Spike in Reports of Anti-LGBTQ Violence dancing', 'Trump lashes out at press during Arizona rally self', 'New tack in Trump defense : The Mueller grand jury is too black daddy', 'Frightbart : A virtual stew of menace , a pit of monsters , an unending onslaught of apocalyptic horsemen beef', 'Steve King is a virulent racist — why be surprised ? He represents the current Republican Party perfectly Grandmother', 'Flush with cash and bracing for November , the RNC builds an army clash', 'US Sen McCain says Putin bigger threat than ISIS cheeseburgers', 'Yet another reason Donald Trump is bad news : He ’s utterly lacking in “ integrative complexity ” — and that ’s dangerous gorilla', 'Manafort ex-son-in-law agrees to plea deal : report ignorance', 'Guess Who Knows Both President Trump And Kim Jong Un ? Owns', 'This is the front post of Fox News after a day of millions of people advocating for gun legislation . Grammar', ' Trump ’s disapproval rating nears 60 percent in new polls Hunger', 'Hungary : Protesters rally in defense of university , NGOs supper', 'State of the Union : President Trump ’s full speech malarkey', "What Roy Moore 's campaign can teach us about partisanship song", 'Trump administration retaliates against Russia , forces closure of US posts cafeterias', 'State of the Union : President Trump ’s full speech tummy', "Democrats ' call to action after Vegas shooting includes plea for ' moral courage ' on gun control legislation blackjack", 'US sets new record for censoring , withholding gov ’ t files salaries', "Trump told Mexico 's president in contentious call to stop publicly saying the country wo n't pay for the border wall taco", 'VX : The Nerve Agent Used To Kill Kim Jong Nam Is Rare And Deadly resurrect', ' Bangladesh on high alert ahead of verdict against ex-PM Zia Zoos', 'The ‘ genius ’ of Trump : What the president means when he touts his smarts snorkeling', 'Few Good Alternatives to Palestinian State Falafel', 'May Is Living the Weak , Unstable Brexit Nightmare She Warned Of dreamed', "Trump 's Syria strikes divide Congress — but not along partisan lines sea", 'Sally Field and More Stars Rally to Urge Congress to ‘ Vigorously Oppose ’ Trump Tickle', "Amid pressure from Trump , Mexico says it 's dealing with migrant ' caravan ' penguin", 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms zebra', 'U.S. senators near deal on Russia sanctions squirrel', "UN human rights chief attacks Trump over surge in ' discrimination , anti-Semitism and anti-minority violence ' praises", 'Senate plan would make individual tax breaks temporary while corporate cuts would be permanent leg', 'When a Holocaust denier chooses to run for Congress , he runs as a Republican survivor', 'Why Hillary Clinton Lost To Donald Trump basketball', 'Facing Backlash , VA Reverses Cuts To Program Helping Homeless Vets : Report tickling', 'Las Vegas professor tells students Donald Trump incites violence after mass shooting elf', 'Trump Says He May Pull Immigration Enforcement From California gold', 'Seized Mexico students dissolved in acid detention', 'For First Time , LGBT Pride Flag to Fly On Federal Land building', 'Is it Watergate yet ? gelatin', 'Trump expected to announce judicial nominees today paint', 'The Republican Ethics Vote : What Happened ? Lost', 'Dems not letting go of Trump tax return push pencil', 'Treasury Department announcing sanctions against Iran Friday morning alligators', "Donald Trump says storm over son 's meeting is greatest witch hunt in history cauldron", 'Chicago files suit over sanctuary city funding windy', 'Exclusive — Back on Offense : Conservatives Plan to Press for Official Congressional Investigation into James Comey , Loretta Lynch fish', 'Trump ’s ‘ strategy ’ on Afghanistan : Let the next president figure it out hygiene', "Lawyer : Trump and attorney Michael Cohen were told about NY Attorney General Eric Schneiderman 's alleged abuse of women in 2013 couches", 'Trump ’s Labor Dept wants salary to count on overtime rule winner', "Ex-AG Lynch : Clinton tarmac talk was about ' innocuous things ' puppies", 'Senate Unveils Budget Blueprint Allowing $ 1.5 Trillion in Tax Cuts Stewing', "Air Force leaders dodge questions on Trump 's ' Space Force ' hair", 'History Made : ‘ American Gods ’ Features TV ’s Most Explicit Gay Sex Scene Between Muslims elephants', "Former FBI director James Comey confirms he is Twitter 's Reinhold Niebuhr Pretends", 'How Washington Post exposed effort to peddle phony allegations against Roy Moore self', "Melania Is Trapped In The White House , Says France 's First Lady Dog", '2 parents of murdered Parkland teens run together for Broward school board marathon', "Trump blames ' Democrats and a few Republicans ' for health-care bill collapse building", 'Robert Reich : Trump Has Divided Americans Into Two Warring Camps Daycare', '#NoMoreNazi is now controversial : New video game sparks online backlash rash', 'Bridgegate scandal lands Christie ally Bill Baroni two years in prison awards', ' France bans extremely thin models , a new law bans the use of unhealthily thin fashion models . Restaurant', ' Amnesty accuses Nigerian troops of raping women rescued from Boko Haram troop', "Florida school shooting : Gov. Rick Scott says ' everything is on the table ' Supper", ' Health Care Debate : McConnell Unveils Bill , Would Leave 15 Million Uninsured Egg', "Trump tells Abbas ' very good chance ' of Mid-East peace deal - BBC News breakfast", 'The ‘ American Health Care Act ’ Is a Wealth Grab , Not A Health Plan Crotch', 'Top labor leader resigns from Trump ’s jobs council after Trump blames ‘ both sides ’ for Charlottesville violence defeatist', "More States Move To End ' Tampon Tax ' That 's Seen As Discriminating Against Women Cardboard", "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' hear", "Trump : We 'll guard the US-Mexico border with the military find", "Franken holds press conference to ' take responsibility ' for sexual harassment accusations , refuses to resign fetish", 'House delays Obamacare vote , denying Trump 100-day win bungles', 'Huge ice crack in Antarctica forces British scientists to flee research station penguins', 'APNewsBreak : Trump mining pollution rule change challenged toilet', 'Robert Reich : 7 hard truths Democrats must acknowledge if they want a better future pancake', 'Michael Flynn pleads guilty to lying to the FBI on contacts with Russian ambassador cocktails', 'Buzzfeed ’s ridiculous rationale for publish the Trump-Russia dossier . tweeting', "Sanders ’ Campaign Staff , Delegates , And Volunteers Launch ' Draft Bernie For A People ’s Party ' Children", ' Taiwan court to rule in in landmark same-sex marriage case food', 'How the Right Co-Opts Frederick Douglass transvestites', 'The White House wants to lead on tax reform — it just needs a tax reform plan first parade', 'A side-by-side comparison of Obamacare and the GOP ’s replacement plan - Los Angeles Times shake', ' Trump just reorganized the military to gear up for cyberwars Nerd', 'Facebook introduces new tools to let people delete and see their data as scandal continues relatives', 'Ivanka Trump Tweeted About Religious Tolerance . It Did n’t Go Down Well . nudity', 'Indonesia church attacks : death toll rises after bombs target Sunday masses picnic', "Elon Musk has just blasted the world 's most powerful rocket into space landfill", 'Trump administration rolls back ObamaCare contraceptive mandate majorettes', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ cooties", "Brazil meat-packing giants ' exported rotten beef ' . misanthropics", "Dershowitz praises UN budget cut : It 's become a ' place of hatred ' hair", "Mick Mulvaney 's Warning : Massive cuts are coming to the federal government hats", 'Did Trump just start a trade war with China ? himself', "Floods , landslides kill 11 on Indonesia 's main Java island donkeys", 'Fox News co-president Bill Shine resigns amid network turmoil tummy', 'HB2 Repeal : North Carolina Legislature Votes to Overturn Controversial ‘ Bathroom Bill ’ Deodorant', "The Health 202 : Republicans can run from health care debate , but they ca n't hide pet", 'Japan governor tells Tepco bosses nuclear plant to stay shut Atoms', 'Capitol Hill correspondents committee declines to credential Breitbart janitors', "Former general says he knows how powerful North Korea 's military is cologne", "Multiple bomb attacks hit Thailand 's deep south , injure three people confetti", 'Nutella maker fights back against fears over cancer-causing palm oil eater', " World War 3 Wo n't Be Between a Nuclear North Korea and Trump hopscotch", 'Scientists found a massive gastronomic discovery delight', 'Fox News guest offensively slams John McCain to claim torture works hosts', "Earthquake hits Indonesia 's Java island , deaths reported dancing", 'Trump campaign had at least 18 undisclosed contacts with Russians during 2016 race gamblers', 'California deputy attorney general charged with possession of child porn food', 'Minnesota Public Radio has source confirming Franken will resign disappear', 'Republicans on Donald Trump ’s rough week for Cabinet appointments : It ’s Democrats ’ fault life', "Faithful flock to Vatican for pope 's Christmas Eve Mass migration", 'Turkish court jails three for life over bombing that killed 12 German tourists in Istanbul two years ago . pancake', 'Police dealing with Nuneaton incident crumpet', 'Merkel reassures EU over lack of Berlin coalition deal catering', 'Trump sure seems slower to call out terrorism when a white supremacist is behind it lie', "PAUL RYAN : Assange is ' a sycophant for Russia ' musician", 'Is the Trump International Hotel a sign that the Gilded Age is back ? Toilet', 'Dems acknowledge anti-Trump message falling short after Georgia loss Peanuts', "FB touted its elections impact as Zuckerberg called the idea ' crazy ' - Business Insider kitten", "Franken holds press conference to ' take responsibility ' for sexual harassment accusations , refuses to resign speak", 'Trump will " confront the North Korean threat " during upcoming Asia trip penguin', '‘ So disgraceful ’ : Trump lashes out at publication of special counsel questions tweet', '9th Circuit to rule on travel ban Thursday evening Wednesday', 'GOP Sen. Kennedy on Voting With Democrats to Restore Net Neutrality Rules Dolphins', 'Republicans admonish Trump in wake of Charlottesville comments shuffle', 'Kushner tapped program meant for job-starved areas to build a luxury skyscraper plate', 'Women-only luxury retreat opening in Finland space', 'Drilling In America ’s ‘ Crown Jewel ’ Is Indefensible , Former Interior Officials Say decorators', 'Deputy FBI Director McCabe steps down boogies', 'Trump Is Pretty Much a Cult Leader , Says Religious Studies Scholar And Author Reza Aslan sings', "WikiLeaks ' Assange a winner in Ecuador presidential runoff janitor", 'White House Weighs Replacing Tillerson With Pompeo matchmaking', 'Illinois Congressman : Poverty Plays A Large Role In Chicago Gun Violence Ammunition', "Anti-Trump celebs plan ' People 's State of the Union ' popcorn", 'Attorney General Jeff Sessions to end US policy that let legal pot flourish [ Associated Press ] celebrate', 'British official : South Sudan violence is tribal genocide carpet', "FB touted its elections impact as Zuckerberg called the idea ' crazy ' - Business Insider neighbors", 'Texas authorities found the body of a small child whilst searching for a missing 3-year-old Pterodactyl', 'Hoboken elects first Sikh mayor in New Jersey state history penguin', 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” television', '‘ It Was Great ! ’ — Donald Trump Thanks Steve Bannon for His Service Gift', "Israeli police caught on video endangering patients ' lives during raid of East Jerusalem hospital dinners", 'House of Cards actor Reg E Cathey dies aged 59 pinecone', 'White House : Trump will not try to stop James Comey testimony by asserting executive privilege ( wapo ) allow', 'Mueller ’s team interviewed Rosenstein over the summer years', 'Glee actor Mark Salling , 35 , found dead ball', 'Mick Mulvaney allowed big pay bumps at consumer agency he once wanted to abolish Marry', "Full text : Tom Price 's resignation letter Varsity", 'White House : Trump To Make Announcement On Comey Tapes This Week video', 'Trump distances himself from Ed Gillespie after Virginia election loss decency', "I was a climate scientist at Exxon — here 's what it 's like to work there breathe", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' he", 'Donald Trump has just met with the new leader of the secular world – Pope Francis puppet', ' Pakistan asks Trump to help fund border fence with Afghanistan Leopard', 'Congress should pass laws giving taxpayers more bang for the buck kittens', 'UN child sex ring left victims but no arrests cramps', 'Donald Trump Celebrates Black History Month by Recognizing Soldier Who Saved American Flag kissing', 'Donald Trump is making an appalling mess of our government and John Bolton is Exhibit A dinner', 'Anyone care to weigh in ? Sounds like a hate crime to me ... Quacks', 'Roy Moore has regained the lead over Doug Jones , according to new polls vultures', 'Alt-Right snowflakes play victim in hopes of mainstream sympathy violin', 'Schumer : If Trump fires Mueller it ’ll cause ‘ cataclysm ’ in DC marries', 'Iran Lifts Ban on American Wrestling Team baking', "Republicans partner with Democrats to end failed ' Kansas Experiment ' lab", 'Facebook says it will investigate how presidential campaigns used its platform during the election women', 'Bill Maher : Donald Trump Is ‘ Capable ’ Of Ordering Assassinations lunch', 'DACA should be a national security priority . It makes America safer . kittens', 'Corker : Trump officials moving to implement delayed Russia sanctions Pretending', 'Could a Democrat actually beat Ted Cruz this year ? mare', 'EU plans talks as egg scandal hits 17 countries thrower', "Ex-Clinton spokesman : Focus on ' Trumpcare ' instead being ' distracted ' by tax return urinate", "Trump seeks action on trade gaps ahead of Chinese president 's visit knowledge", "Trump 's only health policy is to undo everything that Obama did praise", "Trump labels US justice system ' laughingstock ' creates", 'Congress must prevent government from spying on political opponents spitting', 'You Can Be Fined For Wearing A Political T-Shirt To The Polls . SCOTUS Could Change That . mall', 'Lawmakers From Both Sides Of The Aisle Fume Over Trump Leak Allegations Grocery', 'Trump meets with Southwest Flight 1380 crew , passengers stowaways', 'California driver caught on video punching deputy in face , speeding away in vehicle rooster', 'Paul Manafort : Trump former campaign manager ‘ not aware ’ of possible criminal charges against him store', 'Nutella maker fights back against fears over cancer-causing palm oil wrestling', "Florida school shooting : Teenage survivor says he 's quitting Facebook because of death threats from ' NRA cultists ' spam", 'Sanders Leads Pack For Dems 2020 Spot stuffs', 'Trump replaced Tillerson , a realist , with Pompeo , a hawk — and it could set up confrontation with North Korea pecking', 'House Republicans start the new Congress with an assault on federal lands picnic', "U.S. Secretary of State Mike Pompeo says ' sonic attack ' in China similar to reported Cuba incident pasta", 'Trump aide Hope Hicks declines to answer some questions in Russia probe whistles', 'California driver caught on video punching deputy in face , speeding away in vehicle eagle', 'Timeline of chemical weapons use in Syria peels', "Trump Threatens to ' Totally Destroy ' North Korea in First U.N. Speech golf", 'Comey Testimony : Trump Faces Cost of Listening to Bad Advice music', "Top Dem says NSA leak offers ' verified info ' linking Russia to election hacking bone", ' Healthcare debate highlights the split that threatens to paralyze Republicans Banana', "The Trump Admin 's Unwritten Policy that Blocks Undocumented Immigrant Abortions picnics", "Essential Politics : California 's hottest congressional races , ranked mistresses", 'Jerry Falwell : President Trump “ does n’t say what ’s politically correct , he says what ’s in his heart ” nose', 'South Dakota regulators say they could revoke Keystone permit after spill hippies', 'Nunes temporarily steps down from House probe on Russia : statement flour', 'Trump to be sworn in using Bible Abraham Lincoln used beard', "Trump 's new conflict of interest could involve paying off officials to not talk about Russia think", "Scaramucci apologizes to Maddow for ' lighthearted ' suppository joke pill", "Keystone pipeline wo n't have to use American steel , despite Trump 's repeated promises cotton", 'Menendez Bribe Case Proceeds After Judge Rejects Dismissal criminal', ' Inauguration Crowd - 2009 vs. 2017 quilting', 'POLITICS FEB 28 2018 , 2:02 PM ET Mueller asking what Trump knew about hacked emails hid', 'Trump ’s Draft Executive Order on Detention and Interrogation pizza', 'California and President Trump are going to war with each other monkeys', 'DNC chair candidate Jaime Harrison : lobbyists can be good Democrats marsupials', "Boris Johnson condemned in Libya for ' dead bodies ' remark batteries", "Trump will pardon conservative pundit Dinesh D'Souza , who was convicted for campaign finance violation coolness", 'Donald Trump Jr. should be deported for hunting an elephant , PETA billboard demands worm', 'Trump Said to Pick Nominees for 2 Positions on Fed Board Annoy', "EU must give up ' nightmares ' of United States of Europe : Hungarian PM Fairyland", 'Major blow to Ukraines Ammunition supplies . mug', 'Here Are The Seven Republicans Who Could Kill The Tax Bill Dwarfs', "Westworld-style robots will ' be in our homes ' within ten years nightmares", '2018 could be the ‘ Year of the Woman ’ on steroids , with growing backlash to the culture of sexual harassment — dragon', " Mainstream media ignores Wasserman Schultz 's shady IT staffer Bloodstream", "' Only one thing will work ' with N Korea , says President Trump rhyme", "Sen. Rand Paul : If you support Israel , you ca n't support more arms sales to Saudi Arabia underwear", 'Why Trump cutting food stamps could starve America ’s economy people', 'Funding deal reached to avert shutdown commence', 'John McCain thinks Vladimir Putin is a greater threat than ISIS president', 'Lawmakers From Both Sides Of The Aisle Fume Over Trump Leak Allegations steak', "A ' huge clue ' may reveal that Mueller 's endgame is to nail Trump for obstruction cajole", "Americans ' release in North Korea seen imminent ; Kim meets Chinese stem", 'Kushners , Brookfield Near Deal on Troubled 666 Fifth Ave. , Sources Say parrots', '‘ Maybe the Russians Are Still Messing With Our Heads ’ hair', 'Carnage in Kabul adds to US challenges in Afghanistan landfill', ' Trump has played at least 91 days of golf during his presidency and it ’s making him a better president Tiger', "Trump says he 'll allow Japan , South Korea to buy more military equipment from the U.S. underwear", 'Burger sold for $ 10,000 in Dubai charity auction meat', 'Trump says refugee plan would prioritize Christians . sitcom', 'Senate GOP chides Trump over McCain treatment harassment', '‘ I do n’t know how you survive this one , ’ Christie says of Pruitt eat', 'California , Once Compared to Greece , Is Now Trading Better Than AAA gutter', ' Diesel cars are 10 times more toxic than trucks and buses , data shows electric', ' Bangladesh on high alert ahead of verdict against ex-PM Zia Clowns', 'Biggest insurance company obamacare exchanges rallies behind Ryans obamacare 2.0 duck', 'Putin Fends Off Fire And Fury , At Home And Abroad Daycare', 'When talking to Trump , be sure to wear a wire bra', "South Sudan 's warring parties agree ceasefire in bid to end four-year war gorillas", "Canada 's Trudeau decides not to poke U.S. ' grizzly bear ' for now tickle", 'Five Chinese military innovations that threaten U.S. dominance prove', "Vice president Mike Pence 's doctor resigning wife", 'Bernie Sanders and 16 Senate Dems just released their new single-player plan Homeless', "M1 closed in both directions as bomb disposal unit investigates ' suspicious object ' found under motorway bridge pavement", "Where 's Zuck ? Facebook CEO silent as data harvesting scandal unfolds corn", "The GOP 's Obamacare repeal plan is out -- and it 's even worse than anyone expected deal", "Twitter forces US to drop demand for Trump critic 's details - BBC News psychiatrist", "Madeleine Albright : Eclipse a reminder ' all darkness is temporary ' pie", 'OPEC and Russia reportedly agree to extend oil production cut to end of 2018 salami', 'Four Republicans Withhold Support for Andy Puzder to Head Labor Department Menswear', "Facebook increases number of users affected by Cambridge Analytica data scandal to ' up to 87 million ' trucks", "Vice president Mike Pence 's doctor resigning nanny", 'Yvette Cooper asks urgent Commons question on ending of Dubs scheme for child refugees - Politics live actors', 'Russian embassy in London hits out at Theresa May with ‘ white supremacist ’ Pepe the Frog meme child', "Woman who injected husband with lethal dose of heroin may have killed 9 others , served lover 's remains at BBQ marinade", 'Disgusted By Trump , A CIA Officer Quits . How Many More Could Follow ? manicure', 'Donald Trump travel ban : Syrian woman in Oscar-nominated film is barred from US ahead of awards ceremony race', 'Senate intelligence panel postpones hearing with Trump personal lawyer chef', ' Israel Acknowledges Having Bombed A Suspected Syrian Nuclear Reactor In 2007 Hulk', 'Paradise Papers prompt criminal complaint against Glencore Lawyers', "Jared Kushner 's shady business dealings evoke the nepotism and corruption of America 's Gilded Age drapery", 'This Thanksgiving A Majority Would Prefer To Hold The Side Of Political Talk stuffing', 'The Latest : Pakistan death toll in suicide blast rises to 11 Parakeet', 'Nutella sale leads to ugly brawls in French supermarket aisles toast', "Macron meets Russia 's Putin near Paris , promising tough talks puzzles", 'White House invites intelligence committee leaders to review National Security Council documents monkey', 'Inside the country where Down syndrome is disappearing gear', 'Israel blows up Gaza tunnel , killing 8 militants , including an Islamic Jihad commander inconveniencing', 'When George W. Bush stood with Hillary Clinton knitted', 'Neo-McCarthyite furor around Russia is counterproductive necklace', 'Democrats : McConnell Must ‘ Hit the Pause Button ’ on Tax Vote Record', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped ball", "Chaos at the top of the government 's consumer watchdog could be ' devastating ' for Americans entertaining", 'Meet the Schlapps , Washington ’s Trump-Era ‘ It Couple ’ weirdo', "Trump announces ' precision strikes ' on Syria , decries ' monster ' Assad sloppy", 'Senate confirms Mnuchin for Treasury hell', 'Theresa May will not take part in general election debates , say Tory party sources candy', ' Man sucker punches 5-year-old in face on New York City subway !!! Baby', 'After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can Help ’ Alcohol', "Hard Brexiteers have ' betrayed ' the achievements of Conservative governments wrestlers", 'How Kim Jong Un ‘ Baited ’ Trump Into Canceling The North Korea Summit bombing', 'Steve Bannon Meets with Billionaire Mercer Family as He Prepares for #War canoodles', "Paul , Trump upend GOP 's Obamacare repeal plans bananas", 'Jobless Claims in the U.S. Plunge to Lowest Weekly Tally since 1973 babies', "Pence attempts to clarify Trump 's ' many sides ' comment mulligans", "Killing Junkies Does n't Work in Asia Either theory", 'Minnesota Republican Rep. Tom Emmer On Trump , Russia And Obamacare Repeal snake', 'Multiple suspicious packages sent to military locations around DC grandmothers', 'Edible cookie dough craze hits the heartland tire', 'Ample tax cuts for business , wealthy in new GOP tax accord prisons', '10 Famous People Who Praised Venezuela ’s Descent Into Socialist Hell vacation', 'Who really is Trump ? President ’s Nevada speech wildly different from Arizona rally pep', "American CEOs send letter to House : Kill the ' made in America ' tax shade", 'Police say 7 dead in Sri Lankan building collapse chair', 'Trump tags the wrong Lee Greenwood on Twitter plants', 'Trump ’s Pick For Agriculture Secretary Is A Climate Denier , Too fiction', 'Trump tags the wrong Lee Greenwood on Twitter licks', 'Black men sentenced to more time for committing the exact same crime as a white person , study finds bear', 'AP sources : Trump plans to oust Shulkin as VA secretary forgets', "Republican-led House committees to investigate Clinton 's emails again washers", "Betsy DeVos : ' School decision ' to report undocumented students and families pamper", 'GOP tax cut not why economy is booming fraud', 'Male congressman questions why men have to pay for prenatal care . Really . babies', 'Paul Manafort spokesman responds to wiretapping report schizophrenia', 'An Incoherent Strategy on North Korea dancing', 'Protesters shut down Milo Yiannopoulos event at UC Davis landscaping', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 stabbing', "Jim Carrey gives us an eyeful with new Trump painting — and there 's one of Jared Kushner , too Retina", "NATO 's Image Improves on Both Sides of Atlantic , Survey Shows bed", 'Trump says administration taking look at current libel laws Wife', 'Why Japan Is Begging Trump for Help dolphins', 'Did Putin show Oliver Stone a fake Russian airstrike video ? pigeon', 'IMF cuts U.S. growth outlook , cites uncertainty around Trump policies gambling', 'Kim reviews Guam strike plan as Mattis issues stark warning GPA', "Meet Lee Busby , the Alabama write-in candidate who 's challenging Roy Moore minds", 'The next Nixon : Trump snubs ethical norms , sets up potential presidential scandal fuhrer', 'Greece seizes Libya-bound ship carrying explosive materials diarrhea', 'Senate leaders forge ahead on funding deal as Trump threatens shutdown sugar', "The six tribes that could shape Europe 's future cookies", ' Enjoy Wine More With These Helpful Tips Chug', 'David Hogg ’s Attempt to End Laura Ingraham ’s Career Sets Dangerous Precedent fund', 'The Obamas just inked a book deal for more than $ 65 million petroleum', ' Trump fumes on Twitter about " conflicted " Mueller and Rosenstein Eyeball', "Here 's what really caused the housing crisis beaver", 'GAO denies Equifax dispute of IRS contract eats', "Trump , In A 180-Degree Switch , Says NATO ' No Longer Obsolete ' oven", 'It did n’t end at the ballot box : Donald Trump ’s biggest supporters now push for a divisive agenda toupee', 'Trump administration asks judge to toss Chicago lawsuit football', 'Republicans Plead With Trump To Get On , And Stay On , Message To Pass A Tax Overhaul Horse', "After A Year In Office , Questions About Trump 's Foreign Deals Go On . And On . Denial", 'Barbara Bush , Matriarch of U.S. Political Dynasty , Dies at 92 remarries', 'Get The Best Gabbanelli &amp; Cantabella Accordion infection', 'New study says House GOP healthcare bill would lead to the loss of almost 1 million jobs in 10 years Parsecs', 'As The Climate Changes , Kenyan Herders Find Centuries-Old Way Of Life In Danger smugglers', 'Greece seizes Libya-bound ship carrying explosive materials children', "Romney on Moore : ' No majority is worth losing our honor , our integrity ' seafood", "Delhi Police Say They 've Captured Most-Wanted Terrorist Known As ' India 's Bin Laden ' Playground", ' Trump is making Americans see the U.S. the way the rest of the world already did pumpkin', 'No wall — for now : Trump reverses course on Mexico border wall to avoid government shutdown lipstick', "North Korea is ' on an aggressive schedule ' to develop a ballistic missile submarine party", 'Trump And Russia : Stephen Colbert Says He Was Followed During Secret Moscow Trip acid', 'Trump China ZTE sanctions reverse after national security worry clown', 'Report : GOP operative who looked for Clinton emails committed suicide felony', "GOP rep. wo n't say which state options he prefers fair", "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America vocabulary", 'Washington Post starting to go back on months of collusion reporting fashion', "Keystone XL pipeline will not use U.S. steel despite Trump 's vow Girdles", "Rand Paul 's attacker could face more serious state , federal charges mother", 'New Delhi engulfed by pollution so bad United Airlines halts flights odor', 'Trump to hire new lawyer in response to Russia probes cook', 'Louisiana school district : All students must stand for anthem lunch', "' What are they trying to hide ? ' Trump slams election officials over voter data request wrestling", 'Trump was not aware that appointed Steve Bannon to the National Security Council chef', 'White House says there ’s no need for new Russia sanctions vacations', 'As Trump mulls a pullout , IS attempts to re-emerge in Syria sewer', 'Billionaire Babis scores big Czech election win , seeks partners to rule checkers', 'Iranian oil tanker wreck produces two slicks in East China Sea gravy', 'US calls Russia \'s decision to cut its diplomatic staff in Russia " a regrettable and uncalled for act . " vellicate', 'New Commission on Election Integrity plays into a false reality of a problem that does not exist fairy', ' Experts to Trump : Russia is not our ally in the war on ISIS Everyone', 'Kelly flexes muscle his first day on the job at White House second', 'Shameless : Hundreds of CEOs Demand Dreamer Amnesty Shortly After Promising Tax Cuts Will Help American Workers hats', 'Did Manafort promise banker White House job in return for home loans ? hobo', "After Special Counsel Named , Trump Reacts : ' Greatest Witch Hunt ' In Political History decision", 'Nearly 100,000 flee Bali volcano as tremors intensify tourists', 'Trump has played at least 91 days of golf during his presidency and it ’s making him a better president Golfer', 'Federal judge blocks new Texas abortion ban aborts', 'Trump Impeachment House Parties To Take Place Across U.S. Ahead of Presidents Day rave', 'China sends warning to Taiwan with naval drills near island overtures', 'Trump Repeats Lie About Popular Vote in Meeting With Lawmakers - The New York Times mantra', 'President Trump Set to Visit a Traumatized , Divided Las Vegas highway', 'Rand Paul : Saudi Arabia ’s Role in Backing Terrorism Raises Concerns with $ 100 Billion Arms Deal pizza', 'Islamic State mortars , snipers take toll on Iraqi forces in Mosul care', 'Will Trump Be Impeached Based on Michael Flynn ’s Russia Revelations ? peach', ' Mexicans weigh the daunting prospect of deportee camps scales', 'EPA chief Pruitt met with many corporate execs . Then he made decisions in their favor frolics', "Iraq announces ' victory ' over Islamic State in Mosul rodents", 'Wanda Sykes Gets Right To The Point With Donald Trump Diss Points', 'Myanmar president Htin Kyaw resigns drinks', 'BuzzFeed Posts Unverified Claims on Trump , Igniting a Debate cat', 'Western airstrikes unlikely to impact Assad ’s war machine soda', "EU criticizes Turkey 's offensive in Syrian town of Afrin bamboozles", 'Cory Booker ’s new big idea : guaranteeing jobs for everyone who wants one beatings', "Advice for Trump : Do n't fire Robert Mueller -- He will clear you in the end kiss", 'Ireland to get new leader as Enda Kenny steps down ladder', 'lets hope it saves mankind from itself pretend', 'Trump Names Anti-Abortion Leader Charmaine Yoest to High Post at HHS School', 'The potential legal train wreck ahead for Fox News and Bill O’Reilly pad', 'Trump likely to visit FBI headquarters in coming days : White House demolish', 'Collins : Franken allegations ‘ credible , disgusting and appalling ’ monsters', "Nikki Haley rips ' offensive ' and ' disgusting ' rumor of affair with Trump that stemmed from Michael Wolff 's book page", 'EPA seeks to scrap rule protecting drinking water for third of Americans Mammals', '106 passengers stranded in Germany due to drunken co-pilot Alcoholics', "White House Was Warned of Aide 's Background Months Earlier Than Acknowledged Odor", 'Trump passes the buck on mission he approved ! hunt', 'Pence casts tie-breaking vote to overturn rule allowing consumers to sue banks spell', "U.S. senator urges Trump to tap fuel , oil reserves in Harvey 's wake citizens", 'Silencing of Warren throws Senate into turmoil waiter', 'How Trump is Already Reshaping the GOP food', 'President Trump gives himself a 10 out of 10 on helping Puerto Rico boozing', 'Trump Is on the Verge of His Own Bull Market Dolphin', "African states wary of potential repeal of ' conflict minerals ' rule clams", 'Trump ’s Lawyers Look At Use Of Pardons To Derail Mueller ’s Russia Probe trollies', 'Republicans find their email scandal for Robert Mueller ’s investigation folder', 'Republicans Sneak Anti-Abortion Language Into Tax Bill Return', 'Kenya county officials blame military for 5 in shallow grave cake', 'Trump ’s Footloose Foreign Policy Keeps His Own Team Guessing Employed', "Cold weather : Do n't leave these things in your car when temps fall seniors", "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen corners", 'SCTV cast to reunite for a fund raiser : How Dave Thomas created the classic Canadian stereotype barn', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' Explosion", 'Time Asks Donald Trump to Remove Fake Cover From Business Properties hair', 'Northern Ireland : Ryan McLaughlin replaces George Saville for Central American tour caresses', 'Trump ’s flashy executive actions could run aground dance', "A Democrat on Trump 's voter fraud commission asked for more transparency . Here 's what happened next . golfing", "Reporter says Donald Trump used alter ego ' John Barron ' to get onto Forbes 400 list monkey", 'Kushner , CIM to Get $ 600 Million JPMorgan Loan for Brooklyn Site Daycare', "Tracking Trump 's Web of Conflicts poppycock", "Trump Defends Obama 's For-Profit College Crackdown Hates", 'If Trump wants to use this memo to fire Rosenstein , he will have a lot more explaining to do nibble', "Trump 's Phoenix rally attracts thousands of protesters mayonnaise", 'France is ‘ hunting down its citizens who joined Isis ’ without trial in Iraq veganism', 'House OKs huge spending bill , next to Senate spree', 'FBI ’s McCabe faces GOP calls for ouster , ahead of closed-door testimony waltz', "John Oliver urges Internet users to save net neutrality : ' We need all of you ' drug", 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon brothel', 'German girl arrested in Mosul is missing Linda Wenzel , say authorities . strudel', 'Tensions high as city mourns unarmed man killed by police sheep', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid pyramid', 'US health care system : A patchwork that no one likes quilt', ' Disney is ending its distribution agreement with Netflix , will launch a stand-alone platform Internet', "This voting reform solves 2 of America 's biggest political problems headaches", 'When Nigel Farage met Julian Assange hairdresser', 'France just rejected the far-right and elected Emmanuel Macron embraced', 'Many in China think that poor doctor was dragged from the United flight for being Chinese . panda', 'Project Veritas Video Shows Former Twitter Employees Discussing ‘ Shadow Banning ’ Users boss', "Where 's Zuck ? Facebook CEO silent as data harvesting scandal unfolds soul", 'Trump lawyers scramble to prepare for new stage of Russia probe eggs', "' MOAB ' aftermath : Fox News tours site where Afghanistan bomb was dropped glitter", 'Trump Meets Every Criteria For An Authoritarian Leader , Harvard Political Scientists Warn potato', 'UK must cancel Donald Trump ’s state visit as he ’s ‘ nakedly sympathising with neo-Nazis ’ , say activists pumpkin', 'Qualcomm to meet China regulators in push to clear $ 44 billion NXP deal . disguise', 'Trump delivers first State of the Union address babbles', "Mnuchin Signals U.S. Wo n't Further Restrict Foreign Investments Foods", 'US begins Section 301 investigation against China hoodlums', "Inside secret court hearing in Mueller 's Trump-Russia probe vacation", 'Evidence Russia tipped election for Trump “ staggering , ” says former U.S. intelligence chief James Clapper cows', ' Couple who rented condo to Pruitt pays fine to D.C. Student', "Trump 's tax plan is built on one of the biggest lies our parents told us about the economy holidays", 'Laura Ingraham announces vacation amid advertiser boycott pregnancy', '6 times Donald Trump attacked Hillary Clinton for mishandling classified information toddler', 'White House budget director asks New York Times for correction drapery', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches bikinis", 'Leading Trump lawyer Ty Cobb is retiring sneezing', 'Chicago files suit over sanctuary city funding nails', "Intel chief : Trump CIA pick will ' fully ' explain torture involvement chipmunk", "Trump rolls back Obama 's Cuba thaw ice", 'The Latest : San Juan mayor answers Trump ’s Twitter attack turkey', 'Obama denies clemency for Leonard Peltier , nuclear scientist Wen Ho Lee haircuts', " Senate leader says does n't see need for bill to protect special counsel Gang", 'Did Trump just start a trade war with China ? doll', 'Trump to North Korean leader Kim : My ‘ Nuclear Button ’ is ‘ much bigger &amp; more powerful ’ Nose', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel trolls', "' Keep fighting ' : Hillary Clinton searches for role in age of Democratic division hiking", "Dotard : Kim Jong Un claps back at Trump 's ' Rocket Man ' haircut", "Taiwan 's president says her government will step up security measures to respond to military threats from China . puppets", ' Funding deal reached to avert shutdown Shopping', 'Poll : Moore trails Jones in Alabama Senate race foot', 'WikiLeaks founder Assange loses bid to get U.K. arrest warrant dropped geek', 'Gunmen attack Shiite mosque in Pakistan , kill 1 , wound 3 tickle', 'APNewsBreak : Attacks in Havana hit US spy network in Cuba cigar', 'Russia : Trump promised to make visit to Moscow if Putin accepts invite to White House vodka', 'DHS secretary : Electronics ban may be expanded to flights departing US fun', 'North Korea Fires Four Missiles Off Eastern Coast , South Korea Say employees', "Trump hears Christmas sermon about ' the power of words ' spelling", 'U.S. Report Says Humans Cause Climate Change , Contradicting Top Trump Officials Loose', 'White House : Trump will not try to stop James Comey testimony by asserting executive privilege ( wapo ) parrot', 'Donald Trump , pseudo-president : Media embraces his latest “ pivot ” like the proverbial drunks under a streetlight carolers', 'MyPillow Announces ‘ Strong ’ Sales After Refusal to Boycott Ingraham Angle snoring', 'Iowa senator defends tax plan by implying non-wealthy spend their money on " booze and women " cheese', 'Trump considers benching Giuliani from doing TV interviews commercials', 'Black Americans want new gun laws to curb gun violence . Trump offers more police . brutality', 'Venezuelans scour polluted river for lost treasure , survival spouses', ' Senators Race to Pass Tax Bill by Sweetening Gains for Rich janitors', "Read the full text of Trump 's infrastructure plan sitcom", 'NRA whines in new ad : Trump is victim of “ the most ruthless attack on a president ” sings', 'North Korea moving intercontinental ballistic missile to west coast , report South Korean media . fish', 'Kim Pays a Second Surprise Visit to China , Heightening Diplomatic Drama salon', 'Trump campaign had contact with Russian intelligence : NYT vodka', 'Moral Vacuum in the House of Trump closet', "Germany 's center-left Social Democrats agree to hold talks with Merkel 's party on joining or supporting a new government restaurant", "Protesters read Coretta Scott King letter outside McConnell 's house face", 'Mueller casts broad net in requesting extensive records from Trump White House jump', 'President Barack Obama defends his legacy and warns against threats to democracy in emotional farewell speech lawn', 'White Nationalist Blames Trump in Campaign Rally Assault Suit Joins', 'The rhetoric of our era has reached its vile peak believability', 'House OKs huge spending bill , next to Senate taco', 'Should a Republican Healthcare bill actually emerge from the House , it will almost certainly be changed in the Senate . actual', ' Democrats Prepare For A Hard Bargain On Health Care If GOP Bill Fails zombies', "' Beneath the dignity of your office : ' GOP senator says to Trump about his ' Morning Joe ' tweets mugs", 'Jason Chaffetz ’s iPhone comment revives the ‘ poverty is a choice ’ argument hairball', "Joe Biden 's niece pleads guilty to stealing credit card , $ 100k in fraud - no jail time hamster", 'New Miss America begins her reign by slamming Trump on climate change clothing', "Plastic pollution threat to wildlife and Scotland 's most beautiful beaches fork", 'Trump pardons late Black boxing champion Jack Johnson frost', 'Mitch McConnell says Democrats \' planned filibuster of Neil Gorsuch is " new low " neutering', "Pence calls on Mueller to wrap up ' Russia probe sandwich", 'Right now , there are more than enough House Republicans opposed to the health-care bill to kill it sacrificed', 'Glencore starts cutting ties with Russian oligarch Deripaska hair', "Trumpcare is causing Wall Street to question Trump 's whole economic agenda understanding", " Macron Says Aussie PM 's Wife ' Delicious , ' Sparking Reaction Dingo", 'From Stormy Daniels to John Bolton , will America ever recover from Donald Trump hamburgers', 'In win for Trump , Nebraska approves Keystone XL pipeline route milkshake', 'House chaplain wins job back after scalding letter to Paul Ryan kettle', "Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's Power and Role waistline", ' Wall Street set to open sharply higher after Dow breaks four-session losing streak Wacky', "' The Trump slump ' : Remington files for bankruptcy as gun sales tumble cupcake", 'Disappearing Seagrass Protects Against Pathogens , Even Climate Change , Scientists Find Gender', "Trump says he 's not worried what Flynn will tell special counsel ; there 's been ' no collusion ' confusion", '“ Kompromat , ” media ethics and the law : What happens if a Russian scandal video of Donald Trump does surface ? dance', "What Roy Moore 's campaign can teach us about partisanship abuse", 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement tweets', 'Democratic division simmers at feel-good retreat parties', 'Disney Says Promised Bonus Depends On Workers Signing Wage Contract . Unicorn', 'U.K. Outcry at Trump ’s Tweets Reopens Fight Over State Visit sparrow', 'Trump executive order : UK ministers to press US on ban congratulate', 'Stop It — Trump Does n’t Do Strategy showers', 'Venezuela opposition seeks new polls , military help , against Maduro restaurant', 'Is it Watergate yet ? slimy', 'Senate Dems filibuster Gorsuch , teeing up ‘ nuclear ’ showdown massage', ' Democrats are over-performing in key races — and it could be a nightmare for Trump in 2018 Atheists', 'White House princeling Jared Kushner , stripped down and on the verge of exile bear', 'Berkeley Police Allowed Antifa to Jump Barricades , Assault Demonstrators Hug', 'Trump maps new course with allies and autocrats in first foreign trip orgy', " FOX NEWS : US closer than ever to ' nuclear war with North Korea , ' Mullen says Fake", 'Afghan girl roboticists granted US visas - BBC News Enquirer', 'Britain First leaders found guilty of anti-Muslim hate crime cupcake', 'The Nunes memo , explained with diagrams puppets', 'DOJ charges 11 possible caravan members with illegally entering the US escaping', 'What Would Human Resources Do ? : Some Advice For Trump As He Recruits And Staffs Up Boos', 'Before Trump , hate was already present in Canada compost', "' Selfie ' Hitler removed from museum invades", 'President Trump Shares Poll That Shows Democrats Ahead But Claims GOP Is Leading smart', 'Hillary Clinton Needs to Move On refuses', ' Turkey backs Syrian rebels for serious operation in Idlib kitten', "Iraq announces ' victory ' over Islamic State in Mosul constipation", "Zimbabwe crowns first ' Miss Albino ' in bid to tackle stigma quarterback", 'Senate in all-night session as Democrats protest DeVos nomination children', 'Liberal outrage erupts after Vanity Fair pokes fun at Hillary Clinton hissing', 'Pelosi : Trump ’s insecurity fueling fraud investigation barber', "Donald Trump declares national prisoner of war day despite saying ' I like people who were n't captured ' soldiers", "Graham rips into White House 's Stephen Miller Snacks", 'Saudi Arabia to let women enter sports stadiums in 2018 goats', 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote binge', 'Steve Wynn resigns as RNC finance chair cookie', 'Sara Netanyahu , Wife of Israeli Prime Minister , to Face Fraud Charges ignore', 'Mike Pompeo Confirmed as Secretary of State cookies', "India rounds up beggars ahead of Ivanka Trump 's visit cows", 'Not so fast , Trump-haters ! We ’re a long way from Watergate , and Michael Flynn ’s offer is clearly a trap crowbar', "Pence attempts to clarify Trump 's ' many sides ' comment pastry", 'Bill aiming to protect Christians , other minority groups in Pakistan may soon be law beavers', 'Republicans still at odds over Obamacare after closed-door meeting seance', "' N ---- r Leave ! ' : 200-Year-old African-American Historical Site Defaced With Hateful Graffiti In New England father", 'Lawmakers Seek Facebook Data on Russian Election Meddling likes', 'Delhi smog chokes India capital with air pollution 10 times worse than Beijing curry', 'Chile election ends era of female presidents in Latin America Bean', 'Uber CTO blasts Trump in staff email moped', 'British security minister says North Korea was behind WannaCry hack on NHS bacteria', 'Betsy DeVos Made Me Want To Run For School Board nut', "Pruitt 's chief of staff takes responsibility for controversial raises racism", 'GOP senators : Comey drafted statement clearing Clinton before her interview nap', 'Austrian Chancellor may have been one of those lobbied by Manafort brewery', 'My fellow snowflakes WE did the impossible in Alabama , now onto Texas ! Support Beto for Texas senate , removing Cruz ! annihilating', 'Trump Lashes Out At Investigators After Reports Of Obstruction Of Justice Inquiry Barbershop', 'The new Trump administration sounds more like the old Trump campaign prattles', 'How Mick Mulvaney Is Changing The Consumer Financial Protection Bureau overcharging', "Robert Mueller 's investigators interviewed Rod Rosenstein , who is overseeing the Russia investigation ballet", 'Trump speech puts emotion ahead of problem-solving toupee', 'Europe \' in battle mood \' over Trump \'s threat on steel imports : " We will react with counter measures within a few days " grandma', 'Mick Mulvaney ’s snake oil : A blend of bad science , bad math and really bad politics parrot', "Will Trump 's possible testimony end the Mueller probe — or is it just starting ? tantrum", "Ex-Obama official mocks Sen. Paul for getting ' beat up ' by neighbor kid", 'Texas Republican vows to fight for flood insurance overhaul cow', 'Texas chemical plant that exploded amid Harvey flooding had recently been fined over $ 100,000 by OSHA . Tomato', "UK 's Houses of Parliament network blocked 24,473 porn website access attempts in 5 months minutes", 'Pakistan asks Trump to help fund border fence with Afghanistan itself', 'Poll : 90 Percent Oppose Removal , Erasure , of Thomas Jefferson , George Washington bumble', 'James Comey Needs To Get His Clinton Investigation Story Straight ... Again monkey', 'House to vote on sexual harassment overhaul this week decade', 'Trump Fires Back After Polls Show His Favorability Ratings In The Basement Scratches', 'Pentagon claims 2,000 % increase in Russian trolls after Syria strikes . What does that mean ? bowling', "Majority of Americans against Trump 's wall and do not believe Mexico will pay for it anyone", 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it Bogeyman', '‘ I certainly meant no disrespect ’ : Kellyanne Conway addresses her pose in the Oval Office photo father', 'U.S. BERNIE SANDERS MIRRORS TRUMP , BLAMES HILLARY CLINTON FOR NOT COMBATTING RUSSIAN MEDDLING , DENIES IT HELPED HIS CAMPAIGN DELICATESSENS', "Detroit pub refused to serve Irish people at St. Patrick 's Day Parade — to make a point brawl", "Germany 's center-left Social Democrats agree to hold talks with Merkel 's party on joining or supporting a new government parrot", 'Jerry Brown Compares Trump Supporters to Cave-dwellers at NY Climate Change Meeting Sex', 'In abrupt shift on Syria , Trump turns to military advisers cartoons', "Fox News host goes on epic 4-minute rant on Trump 's pattern of false statements : ' Mr. President , that 's your swamp ' hair", 'Schumer , Pelosi tout a DACA deal with Trump , but White House says not quite meal', 'Trump once summoned Priebus to kill a fly in Oval Office : report vagrant', 'American kids are 70 percent more likely to die before adulthood than kids in other rich countries retire', 'WHCD Comedian Michelle Wolf : Trump a ‘ Pussy ; ’ Wants to See Jake Tapper Orgasm , Porn and Abortion Jokes Fly Hear', "Trump 's DACA decision could cost thousands of jobs mispronunciations", "US to deploy 1,000 troops to Poland as Russian foreign minister accuses Nato of being a ' Cold War institution ' pigeons", "African states wary of potential repeal of ' conflict minerals ' rule vitamin", 'White House Declassifies GOP Memo on Russia Probe vodka', 'Trump , Putin to hold bilateral meeting hoedown', 'Al Franken : ‘ I ’m not giving up my voice ’ wallet', ' Steve Bannon is reportedly advocating for a tax hike on the wealthy taxidermist', 'Stunning details reveal how Israel ’s spy agency pulled off one of the most brazen heists in modern history theater', "Face facts , America , Donald Trump is a success . Let 's count the ways . lies", 'Africa Signs Free-Trade Deal to Replace Existing Agreements Elephants', ' American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma alien', 'Fact check : McConnell revises history on Syria chin', 'Support the moms who support us drug', 'Stormy Daniels tells of threats following reports of affair with Trump golfing', ' Bill Would Bar Pentagon From Business With Russian Cyber Firm Kaspersky Scarecrow', "Trump : ' I have no doubt that we 'll win ' travel ban lawsuit depart", 'Jon Stewart , Trevor Noah take jabs at Trump , Weinstein at Stand Up for Heroes benefit shoestrings', 'The GOP just ca n’t escape the ’80s remember', 'Kamala Harris rips up the script check', 'Women-only luxury retreat opening in Finland desert', "Iowa Senator 's alma mater turns out to be a Sizzler franchise steak", "Here 's who the Trump campaign considers ' the president 's enemies ' barbers", 'GOP Asked People To Sign A Presidents Day Card For Trump . It Did n’t Go Well . maniac', "Stephen Miller 's heated interview with CNN 's Jake Tapper earns Trump 's praise erection", ' Watch Live : U.S. responds to Syrian chemical attack Enjoy', 'With His Choice Of Inauguration Prayer Leaders , Trump Shows His Values Chest', "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America Soul", 'Trump Organization employees forced to agree not to sue the company president', 'A Guide to the Violence in Charlottesville Bathrooms', 'Shocking scale of US drinking water crisis paint', 'Reddit banned nearly a thousand accounts linked to the same Russian troll farm accused of election meddling on Facebook peanut', 'She put an obscene anti-Trump message on her truck and was arrested . Now she might sue . forehead', 'Liu Xiaobo supporters mark his death amid concerns for widow height', 'Jacinda Ardern is next prime minister of New Zealand , Winston Peters confirms member', 'How states can fix the Electoral College and prevent future Trumps fruitcakes', 'Poll : Zuckerberg would give Trump a run for his money in 2020 , but Bernie Sanders is the front-runner stock', 'Democrats await answers as their countermemo languishes apocalypse', ' Jared Kushner Will Just Fix Everything Magic', 'East coast readies for fresh climate fight as Trump eyes more offshore drilling Surfing', "Louise Slaughter , ' Trailblazer ' In Congress , Dies At 88 dances", 'JUSTICE DEPT. ASKS FOR MORE TIME ON TRUMP WIRETAP EVIDENCE VOLUME', 'Trump says US nuke force must be in ‘ tiptop shape ’ shoes', "President Trump 's executive order will undo Obama 's Clean Power Plan rule stupid", "Trump 's ' Impenetrable ' Cyber Unit That Never Was Cranial", 'Gang Rape And Murder Of 8-Year-Old Girl Sparks Outrage Across India sandwich', 'TSA tightens electronics screening for domestic flights beers', 'GOP tax cuts will strengthen our economy and drive Democrats crazy cold', 'Choirul Huda : Indonesian goalkeeper dies after collision with team-mate cries', "' We 'll see ' : Trump addresses possible military retaliation to North Korean nuclear and missile tests math", 'Efforts to Prevent Government Shutdown Hit a Snag Over Health Care Plans expedite', 'Roseanne Barr Smacks Down ‘ A ** hole ’ Michelle Wolf : ‘ Comedy Comes From Love , Not Hate ’ bakery', "Russian prisoners transported in ' cruel , inhuman and degrading conditions in train carriages from Soviet era ' politicians", "Trump believes that Russia likely meddled in the 2016 election but ' nobody really knows for sure ' voted", '‘ Hello , Bob ’ : President Trump called my cellphone to say that the health-care bill was dead tweeted', 'Contrasting lawmaker reaction to the Florida shooting with NRA contributions compliance', 'Brexit economy : UK faces squeeze on living standards oranges', 'Stolen Lennon items recovered in Berlin rehab', 'Republicans formally roll out tax plan -- live updates Lobsters', 'Mattis asks former U.S. ambassador Anne Patterson to take a top job at the Pentagon pacifist', 'GOP senators return home to harsh local headlines on healthcare clean', "Blake Farenthold , Texas lawmaker accused in sexual harassment suit , wo n't seek re-election pudding", 'Donald Trump Discovers the Red Line for His Supporters : Immigration fantasies', 'North Korea : New UN sanctions an act of war kindness', 'Ex-federal judge tapped to review Cohen documents inmate', "Trump 's DACA decision could cost thousands of jobs pennies", 'Armenia contemplates the unlikely : a nonviolent revolution on the cusp of victory hoedown', 'Congresswoman apologizes for not protecting women in her office harem', 'Trump Meets Every Criteria For An Authoritarian Leader , Harvard Political Scientists Warn Eats', "Trump is caught promising to ' release the memo ' on hot mic kraken", "Thailand mother watches helplessly as baby 's death is streamed to Facebook giggle", 'U.S. ambassador to U.N. says Russia tearing down global order delivery', 'NRA Should Name Teens in Suit Over New Gun Law , Florida Says Self', "Do n't get carried away – Trump is as popular today as he was last year kombucha", 'Corbyn woos small businesses with plan for crackdown on late payments porcupines', 'Police in Paris shoot man dead after he stabs several people in the Opera district , French media say moons', 'Trump And Russia : Stephen Colbert Says He Was Followed During Secret Moscow Trip mushroom', 'Community banks file lawsuit against Equifax Nails', "BET founder : Trump 's economy is bringing black workers back into the labor force comedians", 'Paul Manafort , and the Weakness of Trump chins', " Trump 's first year has been the private prison industry 's best Gang", "Iran 's bad behavior leaves Trump with just one choice soda", 'Paul Manafort Flew 18 Times To Moscow And Frequently Reached Putin ’s Allies , Records Show elbows', "Trump wo n't condemn white supremacists or Vladimir Putin — and the 2 are closely linked bread", "Trump jokes that Haley could ' easily be replaced ' sons", "Judge says former Trump campaign manager Paul Manafort might spend ' the rest of his life in prison ' enjoy", 'Trump lashes out at press during Arizona rally eyebrows', " Senate leader says does n't see need for bill to protect special counsel Treasury", 'U.S. consumer protection official puts Equifax probe on ice chicken', "Bernstein : GOP criminal referral for Trump dossier author a ' glowing red herring ' Ginger", "Trump Organization real estate partner in India accused of ' large-scale fraud ' idiocy", ' Oil Slumps to Lowest This Year as Traders Focus on Record Supply oxygen', "DNC chair candidate wants to ' shut other white people down ' minorities", 'Trump has mastered the art of seeming like he ’s telling the truth pretending', 'Trump expected to announce judicial nominees today tweet', 'Report : Texas Church Shooter Was Atheist , Thought Christians ‘ Stupid Somnambulist', 'Mnuchin backs key provision in Trump tax plan that would hit Democrats hardest golf', 'Facebook introduces new tools to let people delete and see their data as scandal continues ankles', 'Tom Price intervened on rule that would hurt drug profits on the same day he acquired drug stocks paraphernalia', 'Notre Dame students walk out on Pence commencement speech pass', 'Carnage in Kabul adds to US challenges in Afghanistan mess', 'U.S. allies retaliate after Trump lets steel tariffs take effect for Europe , Mexico and Canada cry', 'James Comey asked to testify by Senate Intelligence Committee next Tuesday Gigantism', 'Jimmy Kimmel wrecks car in head-on collision accident unicycle', 'Police say 39 people detained over neo-Nazi march in Berlin dachshunds', 'GOP Asked People To Sign A Presidents Day Card For Trump . It Did n’t Go Well . monkeys', 'Some U.S. borrowers jailed over civil debts , new ACLU report shows drinking', "Russia investigation makes US ' look very bad , ' Trump says smell", 'Three Dead in Fresno Shooting Spree , Suspect in Custody - NBC News !!!!!!!!!! kindergarten', "It 's time for Congress to update the law governing digital surveillance watches", "Dick 's Sporting Goods no longer sells assault-style rifles and raises age to 21 baseballs", "Malawi arrests 140 in clampdown after ' vampirism ' killings rumors", 'U.S. Report Says Humans Cause Climate Change , Contradicting Top Trump Officials toupee', 'Entry Ban Could Cause Doctor Shortages in Trump Territory , New Research Finds door', 'NBC corrects story that Trump attorney Michael Cohen was wiretapped , intercepted White House call football', ' Tax bill will slash by half the number of homeowners claiming the mortgage deduction electrocution', "$ 200 million eyeballed for Donald Trump 's inauguration tan", 'Tillerson responds to reporters after being fired on Twitter fishermen', "Ten of Trump 's budget 's cruelest cuts salami", 'Basic income experiment receives $ 5 million worth of bitcoin loses', 'Philippines President Rodrigo Duterte vows to kill mayors and officials involved in drug trade mosquitos', 'Trump Kicks Off G-20 Summit With Rage Tweets Referencing Russian Election Meddling Bout', "Jimmy Kimmel clashes with Sean Hannity over Kimmel 's Melania Trump joke socks", 'Trump considers benching Giuliani from doing TV interviews guides', "' What are they trying to hide ? ' Trump slams election officials over voter data request count", 'Congratulations , America — you did it ! An actual fascist is now your official president plumber', 'Turkey casts Zarrab case as attempt to undermine its politics , economy gobbles', 'Not even Trump can control the GOP base entertain', "Trump is reportedly worried and in ' dark moods ' over scrutiny of his shadowy lawyer Michael Cohen basement", 'Jared Kushner is the Real President Enemy', 'Couple who rented condo to Pruitt pays fine to D.C. Enslaved', 'Swalwell dares Trump : Declassify the surveillance documents cat', " Read the full text of Trump 's infrastructure plan Sing", 'Hillary Clinton warns LGBT progress may not be secure under Trump money', 'Will Trump Be Impeached Based on Michael Flynn ’s Russia Revelations ? divine', 'White House ices out CNN squirts', 'After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can Help ’ dance', "' SNL ' writer suspended after writing controversial joke about Barron Trump penguin", 'Capitol Hill correspondents committee declines to credential Breitbart cartel', 'Some U.S. borrowers jailed over civil debts , new ACLU report shows comic', 'Islamic television station in Senegal blames saboteur for airing hardcore porn brother', 'Five tough questions for Trump on immigration triangles', "Donald Trump 's White House staff ' communicate through app which automatically deletes messages ' apes", 'Tiffany Trump went to a Playboy party on New Year ’s Eve and the Internet cares explodes', 'American Otto Warmbier Has Been Released From A North Korean Prison - In a Coma Supermarket', '‘ Maybe the Russians Are Still Messing With Our Heads ’ plotting', "Enraged Bernie Supporter Opens Fire on Republicans After Realizing he Ca n't Get a Refund job", "Sam 's Club closes hundreds of stores nationwide carts", 'Key senator to vote against CIA nominee Gina Haspel play', "Spicer defends Trump : Issues are ' evolving towards the president 's position ' terrier", 'Mark Meadows on Corker ’s Trump comments : “ It ’s easy to be bold when you ’re not coming back ” licking', ' Pew poll : 61 percent back legalization of pot party', 'Fox News co-president Bill Shine resigns amid network turmoil Shoe', 'Trump ’s conflicts are unprecedented , but not unique : A short history of Republican corruption neckties', 'Cory Booker : The system is rigged against working Americans mice', "Senior US diplomat pitches arms sales in China 's backyard restaurant", 'Turkey Gears Up for ‘ Risky ’ Syria Mission With Russia and Iran shopping', 'Influential outsiders have played a key role in Scott Pruitt ’s foreign travel mules', 'Venezuela claims 41.5 % turnout in violent constituent assembly vote profit', 'NRA ’s Wayne LaPierre instructs CPAC to “ be frightened ” of “ socialist wave ” following Parkland tidal', 'Of course US birth rates are falling – this is a harsh place to have a family | Opinion Duh', 'Trump Rips Mueller Target Papadopoulos as ‘ Liar , ’ ‘ Low Level Volunteer ’ musician', "Treasury sanctions ' Putin 's chef , ' other Russians over cyber-related threats grandmother", 'Trump Budget Gambles on Having This Equation Right Bet', "What 's Trump 's plan for Syria ? Five different policies in two weeks | Guardian US news dinner", 'Trump Wall Moves Forward With Firms Tapped for Designs Jet', 'Schiff : Trump Jr. may have been first to know about Russian efforts to meddle in election lie', 'Officials : US captures key militant key in Benghazi attack hug', 'Kenya county officials blame military for 5 in shallow grave river', 'Report : GOP Rep. urged woman from affair to get abortion despite his anti-abortion stance street', "US diplomat forced to leave New Zealand after being involved in ' serious criminal incident ' donkey", "Cruise line Carnival Corp. joins the fight against Bermuda 's same-sex marriage ban raisin", "' Sesame Street ' suing over Melissa McCarthy 's R-rated puppet movie Affair", 'Panel rejects attempt by Democrats to get Trump travel costs toupee', "Denmark 's ' Little Mermaid ' doused in red paint by whaling protesters bestiality", "What Trump 's first speech as president tells us about the next four years nightmares", "US says refugee admissions wo n't be suspended until July 12 ogre", "Treasury sanctions ' Putin 's chef , ' other Russians over cyber-related threats rewards", 'Suspected rebel-planted mine hits Yemeni ship , kills 2 shrubbery', ' House to vote Thursday on Obamacare repeal bill nobody', 'India is building a biometric database for 1.3 billion people — and enrollment is mandatory goats', 'Trump is being warned of impeachment by advisors baldness', 'State Dept. reverses visa revocations , allows banned travelers to enter U.S parachute', 'The Latest : Trump Denounces Report Russia Had Info on Him publishes', 'Extremist website insists armed march against Jewish people in Montana will go ahead food', "P.F. Chang 's heads to China to serve American-style Chinese food Tacos", 'Border Patrol Shooting Death Of Immigrant Woman Raises Tensions In South Texas iguana', "U.S. blocks use of Venezuela 's digital currency : White House cameras", 'Trump Lawyer Michael Cohen to Appear Before House Intel Panel on Tuesday farm', 'James Comey ’s Opening Remarks : It ’s All About Him act', 'Vornado Has ‘ Handshake ’ to Sell Stake in NYC Tower to Kushner sewer', 'Navy jet shoots down Syrian warplane that attacked US-backed rebels balloon', 'What happened to jarred closed testimony screaming', "A ' huge clue ' may reveal that Mueller 's endgame is to nail Trump for obstruction cash", 'After Tanker Flips , Chocolate Bars Traffic On Polish Highway sweetens', 'Venezuela chief prosecutor to face charges as crisis deepens birthday', "White House 's Mulvaney : Chances of government shutdown are currently 50-50 beach", 'John Legend : Trump ‘ consistently loyal to white supremacists and Putin ’ bears', "' We want revenge ' : meet the Yazidi women freeing their sisters from Isis in the battle for Raqqa convent", 'Triple Threat : New Pneumonia Is Drug-Resistant , Deadly And Contagious thespian', 'Moore dodges the press as harassment scandal spirals ham', 'Israel : US-Led Strikes enforce Red Line on syria . paper', 'Mexico Sends Top Official to California Help Illegal Aliens Avoid Deportation dog', 'Trump refers to countries as " Shithole Countries " houses', 'Trump administration has unforced errors and self-inflicted wounds galore tweets', "Mike Pence does n't stand for North Korea athletes during opening ceremonies shenanigans", "After healthcare vote , California Rep. Jeff Denham hears from angry constituents : ' You voted against me ' wrote", 'Texas Lt. Gov. Dan Patrick : Video games , abortion to blame for school shootings — but not guns card', 'New Dashcam Video Shows Philando Castile Informing Officer He Had A Firearm baby', 'Watch Live : U.S. responds to Syrian chemical attack sock', 'Trump to hire new lawyer in response to Russia probes dolls', 'Thousands of students , teachers march on White House to call for better gun control gum', 'On the campaign trail , Trump was very worried about revealing America ’s secrets pimples', "Jeremy Corbyn 's performance inspires Bernie Sanders supporters to ask once more : ' What if ? ' Cookbook", "Delhi Police Say They 've Captured Most-Wanted Terrorist Known As ' India 's Bin Laden ' Hindu", "' Mega-colonies ' of penguins discovered in Antarctica Basement", " People in half of Virginia 's counties on track to have ZERO Obamacare insurers next year turtles", 'Trump called for a government shutdown over immigration and it makes no sense rice', 'The FBI is leading an investigation into Donald Trump ’s connections with Russia fishermen', "Trump Is Like Mao And Stalin With ' Authoritarianism 101 ' Media Attacks : ' Morning Joe ' dog", 'Italian President Blocks Eurosceptic Coalition Govt dog', "' Get ready Russia ' : Trump issues warning on Syria missile strikes chants", 'Joe Arpaio Found Out He Admitted Guilt With Trump Pardon On Live TV Infatuation', "No more ' monkey business ' ? Trump touts big jobs number as proof of improvement monkey", 'Why is Donald Trump so cozy with the Kremlin ? A political scientist and Russia expert breaks down the theories blanket', 'Retired English teacher corrects letter from Trump and sends it back to White House shreds', "Alibaba Founder Jack Ma says Artificial Intelligence could spark the ' Third World War ' , but says that humans would win . pickle", 'House to vote Thursday on Obamacare repeal bill joke', 'Robert Mueller examining blocked Trump letter that explains his reasons for firing Comey love', 'Trump travel ban : judges skeptical about arguments on executive order gibberish', ' Trump Seeks Shift in Visa Allotments Crucial to Tech Outsourcing Nerd', ' Trump overturns regulation on coal mining debris Canary', 'Illinois Senate passes measure for neo-Nazis to be classed as terrorist groups pizzas', ' California to sue Trump administration for repeal of fracking rules Gophers', "AP Exclusive : Senator 's family business uses Mexican labor hats", "Trump ' disappointed ' with China after North Korea missile test humanity", "Cambodia 's Hun Sen says he and Trump object to ' anarchic ' media spiders", 'Poll : 60 % of voters back Trump ’s travel ban hermits', "Ex-Obama official mocks Sen. Paul for getting ' beat up ' by neighbor kindergartner", 'All 22 promises Trump made in his speech to Congress , in one chart kindergarten', 'Experts to Trump : Russia is not our ally in the war on ISIS cholesterol', 'Roadside bombings kill 10 Egypt soldiers during Sinai raid kabobs', 'Constitutional collapse : Why we could be on the verge of a democratic apocalypse victory', 'Reporter Fact-Checks Trump : ‘ Why Should Americans Trust You ? ’ lick', 'Readers on the Fake News awards presented by President Trump tan', 'Trump has played at least 91 days of golf during his presidency and it ’s making him a better president despot', 'Manchin dodges party-switch fallout ball', 'Trump distances himself from Ed Gillespie after Virginia election loss chase', 'Sexual misconduct allegations leave a swath of Los Angeles County without representation in the Capitol comedians', 'Newt Gingrich , Donald Trump Jr. rush to blame Kathy Griffin and “ the left ” for baseball shooting attendance', 'UN agency : 64 migrants " probably " died in Jan. 6 shipwreck of smuggling dinghy in Mediterranean drugs', 'Coast Guard wo n’t ban transgender members unless compelled cupcakes', 'Michael Goodwin : FBI memo proves the ‘ deep state ’ is real – and the press is part of it cheese', 'Grigory Rodchenkov : Russian whistleblower suspected British cheats soccer', 'Netflix says it now has 104 million subscribers worldwide - BBC News fleas', 'Dozens dead in possible gas attack in Syria ; regime denies allegation balloon', "GOP lawmakers glued to Trump 's ' riveting television ' cable", 'The Latest : House passes $ 7.9 B Harvey disaster aid package party', "A top State Department official could n't explain why the U.S. backs Saudi Arabia impersonates", "Trump officials greet Ford 's plan to import Chinese cars vandalize", 'Affirmative-action hypocrisy : Foes hope to use Asian-Americans to attack racial diversity on campus Import', 'The drama behind Trump ’s assertion that the National Enquirer deserved a Pulitzer stole', 'Trump administration may force CNN to be sold as part of $ 85bn deal minions', 'Bush-era diplomat tweets that you should be scared , very scared insomnia', "Microsoft Investigates ' Inappropriate ' Pro-Trump Russian Ads on Bing Search Engine games", "Jared Kushner Says ' I Did Not Collude ' Ahead Of Senate Committee Appearance Acrobatics", "What Trump 's first speech as president tells us about the next four years nap", "McCain , North Korea in war of words over ' crazy fat kid ' crack - strong words from a gimpy midget ! oooo ! wife", 'Newt Gingrich , Donald Trump Jr. rush to blame Kathy Griffin and “ the left ” for baseball shooting cards', 'Puerto Rico faces federal lawsuit over transgender rights wrongdoings', "V for Vendetta , Fahrenheit 451 , and five other books that reflect Trump 's America vomit", "Bafta Awards 2018 : ( Most ) stars wear black to bring Time 's Up to Britain pigs", 'Forget Planet 9 — there ’s evidence of a tenth planet lurking at the edge of the solar system Science', 'US warship fires warning shots at Iranian boat speeding towards USS Tempest in Persian Gulf origami', "Trucker damaged part of Peru 's world-renowned Nazca lines , officials say cupcakes", 'Snoop Dogg says Trump ignored black Waffle House victims because shooter was white server', 'Ex-President Luiz Inacio Lula da Silva defies court order to turn himself into police , hunkers down with supporters . hunks', ' Keystone pipeline can be made from non-US steel despite executive order , White House says milk', 'U.S. fighter jet shoots down Iranian-made drone in Syria kite', "It 's over : Britain files for divorce from the European Union queen", 'Senate GOP \'s " skinny repeal " bill dies in middle-of-the-night vote Combusts', 'Catholic priest caught driving 13-year-old girl to motel after paying 16-year-old pimp cat', 'Andrew McCabe lawyer considers suing for defamation after Trump tweet Custody', 'On China ’s Weibo , It ’s Forbidden to Disagree With President Xi Jinping ’s Plan to Rule Forever Tailgate', 'Drilling In America ’s ‘ Crown Jewel ’ Is Indefensible , Former Interior Officials Say border', 'Advisers bad-mouth Nielsen as a ‘ never Trumper ’ angel', 'Trump Jr . Hinted at Review of Anti-Russia Law , Moscow Lawyer Says farmer', 'Donald Trump accuses Obama of orchestrating protests and leaks against him dances', 'Roseanne Barr Smacks Down ‘ A ** hole ’ Michelle Wolf : ‘ Comedy Comes From Love , Not Hate ’ marriage', 'Exclusive — Alabama Poll : Judge Roy Moore Leads Radical Democrat Doug Jones by Six Points leash', 'Central Michigan University On Lockdown After Shooting At Dorm Kills 2 Films', "US cuts women 's health funding to UN hair", ' Deaths confirmed in Manchester " blast " dynamite', 'Flynn subpoenaed by grand jury in Russian investigation . slam', 'Trump Administration Revises Conservation Plan For Western Sage Grouse clairvoyant', 'Ontario judge who wore Trump hat is off the bench costume', " Trump says the ' alt-left ' bears some responsibility for violence in Charlottesville , ' nobody wants to say that . ' Duck", ' Trump said Haitians have aids , Nigerians live in huts in oval office meeting Racist', "Donald Trump team ' scrutinising staff Twitter accounts before hiring them to check for criticism ' collusion", 'Key Trump allies are reportedly encouraging him to compromise with special counsel Robert Mueller toadies', 'Gerrymandering for 2020 : Virginia Republicans are trying to rig the Electoral College votes for next election confuse', 'Las Vegas security guard Jesus Campos disappears moments before TV interviews toothbrush', 'Senators consider automatic tax hikes if revenue falls short serfdom', "Warren Buffett 's Berkshire Hathaway dumps its Fox stake collection", 'Turkey suspends 9,103 police personnel over alleged links with failed coup : CNN Turk promotes', 'The Democrats ’ hypocrisy fest : Disingenuous attacks on Bernie Sanders persist — and his popularity climbs hairline', 'Trump undercuts White House stance hours before critical surveillance vote bathroom', 'Charlotte Pence : I Bought The Gay Bunny Book wrote', 'What if Sociologists Had as Much Influence as Economists ? donkeys', 'How Donald Trump weaponizes confusion : Now he wants to blame Russia scandal on Obama tiger', 'Muhammad Ali ’s Son Stopped for 2nd Time in Airport Line round', 'The Trump administration is n’t a climate scientist , but it plays one on policy decisions horrible', 'Stock futures point to sharply lower opening after Wall Street-friendly Cohn resigns fights', "What the WikiLeaks emails tell us about Hillary Clinton 's campaign ( and what they do n't ) shame", 'Conservative media outlet RedState just fired a lot of its anti-Trump bloggers stalkers', "Trump sees veterans as the perfect armed teachers , but they 're divided chimpanzees", "NRA 's Wayne LaPierre says gun control advocates ' hate individual freedom ' freedom", 'Trump vows to start NAFTA renegotiation talks forgot', 'Scout Schultz : LGBT activist shot dead by police at Georgia University laughed', 'Twitter bans RT and Sputnik ads amid election interference fears baking', 'Atlantic editor : Trump is going to cause violence against journalists cosmetologists', 'Liberals need to stop being apologists for radical Islamists vegans', 'In New Hampshire and Iowa , Trump eyes 2020 re-election as midterms loom dreads', 'Contradictions upon contradictions in the tale of Trump payoff to porn star cupcakes', 'North Korea Called Me a ‘ War Maniac . ’ I Ignored Them , and Trump Should Too . Thanked', 'Donald Trump hosts man who called for death of Barack Obama and Hillary Clinton at White House marriage', 'Senate Bill Does n’t Have House ’s Tax Break for ‘ Unborn Children ’ Billionaires', 'Kim jong un ’s brutal regime in north korea is worse than nazi concentration camps , human rights leader says summer', "A look at Attorney General Jeff Sessions ' political career Laugh", 'Ex-CIA officer held over secret files recipe', 'Dem to unveil bill requiring a White House psychiatrist puppy', "Trump 's FEMA Director Faces His First Test date", "Vulnerable Democratic Sen. Heidi Heitkamp 's path to re-election gets tougher with Rep. Kevin Cramer set to enter race fight", 'The Latest : Pakistan death toll in suicide blast rises to 11 hotdog', 'New tack in Trump defense : The Mueller grand jury is too black tuxedo', 'White House Red Scare people', "Joe Scarborough Asked Trump ' Can You Read ? ' and There Was ' Awkward Silence ' cook", 'US flies two B-1 bombers over South Korea after North Korea missile launch imagines', 'American ISIS Fighter ’s Brother Sentenced For Terrorism-Related Charges gerbil', 'Trump administration plans to impose tariffs on EU steel and aluminum : Sources grandson', "Bannon tells French far-right party : ' Let them call you racist ' eat", 'Lobbying Frenzy Begins on Tax Bill Dollar', "Dems prepare to face off with Trump 's pick to lead EPA . kiss", 'Trump : Dems playing blame game instead of fixing Obamacare party', 'Call to remove or prosecute homeless ahead of royal wedding draws wide criticism deflate', 'Berkeley Police Allowed Antifa to Jump Barricades , Assault Demonstrators kiss', "Trump just blamed the military for the botched Yemen raid . That 's a disgrace . dinner", "Meet the Malibu lawyer who is upending California 's political system , one town at a time beach", 'Why Gorsuch could lead court in wrong direction ducks', "Trump hears Christmas sermon about ' the power of words ' walls", 'How Trump ’s Nafta Threats Are Bringing Mexico and China Together kittens', 'Who is Sergey Kislyak , and how did he become the hottest meeting ticket in Washington ? dance', 'Fox News guest offensively slams John McCain to claim torture works poetry', 'Party animal Arizona lawmaker expelled after #MeToo movement giraffe', 'A Trump impersonator and Kim Jong-un impersonator crashed the Olympic opening ceremony — and were kicked out ate', 'How Trump Won — and How the Media Missed it groundhog', 'Cannabis Drug Halved Convulsions in Company-Funded Epilepsy Test Contest', "Norwegians tell Trump : We do n't want to come to your s *** hole country hotel", "Brazil 's Temer accused of passive corruption by police anime", 'Trump , Comey And Special Counsel Robert Mueller Could Come Face-To-Face At FBI Ceremony Next Week ballet', 'British official : South Sudan violence is tribal genocide prank', 'Sen. Bob Hertzberg will cooperate with investigation into unwanted hugs hairpieces'] {'congress': 1762, 'oks': 5495, 'trump': 8239, 'bid': 870, 'to': 8078, 'widen': 8725, 'private': 6139, 'care': 1281, 'at': 568, 'besieged': 849, 'va': 8436, 'destroy': 2291, 'and': 386, 'obama': 5446, 'have': 3716, 'the': 7996, 'same': 6877, 'approval': 477, 'rating': 6388, 'after': 262, 'their': 7999, 'first': 3137, 'year': 8853, 'least': 4580, 'according': 158, 'one': 5507, 'poll': 5982, 'person': 5814, 'mcmaster': 4940, 'says': 6918, 'administration': 214, 'will': 8740, 'confront': 1750, 'russia': 6831, 'destabilizing': 2289, 'behavior': 814, 'lizard': 4698, 'triple': 8217, 'threat': 8028, 'new': 5335, 'pneumonia': 5955, 'is': 4237, 'drug': 2592, 'resistant': 6618, 'deadly': 2109, 'contagious': 1798, 'president': 6102, 'it': 4253, 'watergate': 8632, 'yet': 8861, 'moving': 5208, 'report': 6579, 'wants': 8592, 'his': 3833, 'chief': 1469, 'of': 5470, 'staff': 7553, 'get': 3407, 'rid': 6712, 'jared': 4287, 'ivanka': 4260, 'police': 5971, 'how': 3919, 'right': 6723, 'co': 1597, 'opts': 5538, 'frederick': 3276, 'douglass': 2531, 'handedness': 3664, 'forget': 3237, 'populism': 6013, 'cure': 2023, 'not': 5405, 'disease': 2404, 'hugging': 3930, 'ap': 440, 'fact': 2973, 'check': 1442, 'an': 378, 'angry': 396, 'twists': 8293, 'facts': 2976, 'about': 133, 'raid': 6351, 'probe': 6145, 'candy': 1255, 'michelle': 5022, 'was': 8618, 'jimmy': 4317, 'fallon': 3000, 'only': 5510, 'guest': 3598, 'no': 5372, 'they': 8012, 'did': 2327, 'mom': 5141, 'dance': 2064, 'enemy': 2763, 'doj': 2491, 'charges': 1422, '11': 10, 'possible': 6035, 'caravan': 1277, 'members': 4979, 'with': 8771, 'illegally': 3998, 'entering': 2787, 'us': 8421, 'restaurant': 6635, 'steve': 7625, 'bannon': 709, 'became': 787, 'face': 2966, 'political': 5976, 'movement': 5204, 'roots': 6789, 'in': 4048, 'los': 4737, 'angeles': 392, 'cheerleaders': 1447, 'eric': 2816, 'sean': 7011, 'hannity': 3674, 'democrats': 2222, 'are': 493, 'even': 2850, 'people': 5792, 'as': 529, 'makes': 4807, 'more': 5175, 'arrests': 518, 'ice': 3971, 'looks': 4727, 'for': 3219, 'detention': 2302, 'centers': 1377, 'recreation': 6454, 'syrian': 7852, 'state': 7592, 'tv': 8281, 'successive': 7731, 'blasts': 931, 'heard': 3743, 'hama': 3654, 'province': 6228, 'eructations': 2822, 'mattis': 4918, 'asks': 535, 'former': 3245, 'ambassador': 360, 'anne': 404, 'patterson': 5746, 'take': 7866, 'top': 8107, 'job': 4320, 'pentagon': 5791, 'circus': 1516, 'defends': 2168, 'decision': 2135, 'keep': 4387, 'long': 4721, 'democratic': 2221, 'memo': 4982, 'under': 8324, 'wraps': 8826, 'presents': 6098, 'blames': 925, 'corker': 1854, 'iran': 4222, 'deal': 2110, 'smell': 7357, 'remember': 6540, 'when': 8696, 'republicans': 6592, 'were': 8684, 'mad': 4783, 'that': 7994, 'unreliable': 8383, 'allies': 335, 'mistress': 5106, 'childhood': 1473, 'bullying': 1143, 'anxiety': 431, 'goes': 3471, 'away': 634, 'homework': 3867, 'reportedly': 6581, 'advocating': 243, 'tax': 7905, 'hike': 3812, 'on': 5505, 'wealthy': 8649, 'nature': 5290, 'resignation': 6612, 'wave': 8636, 'capitol': 1269, 'hill': 3816, 'might': 5037, 'be': 767, 'over': 5597, 'radio': 6344, 'six': 7282, 'journalists': 4341, 'life': 4645, 'prison': 6134, 'failed': 2981, 'turkish': 8267, 'coup': 1900, 'film': 3109, 'stephen': 7616, 'miller': 5052, 'has': 3702, 'better': 859, 'sense': 7075, 'pulse': 6263, 'than': 7990, 'any': 432, 'since': 7259, 'andrew': 388, 'jackson': 4268, 'scent': 6941, 'house': 3914, 'stun': 7705, 'gop': 3491, 'by': 1196, 'sinking': 7268, 'veterans': 8479, 'intel': 4156, 'bills': 890, 'fences': 3078, 'south': 7446, 'korea': 4467, 'expected': 2906, 'prosecutors': 6202, 'coming': 1665, 'days': 2101, 'canines': 1257, 'schiff': 6945, 'jr': 4345, 'may': 4923, 'been': 797, 'know': 4458, 'russian': 6832, 'efforts': 2678, 'meddle': 4954, 'election': 2695, 'mysteries': 5256, 'cdc': 1355, 'hold': 3853, 'briefing': 1089, 'public': 6243, 'can': 1238, 'prepare': 6089, 'nuclear': 5420, 'war': 8594, 'chickens': 1467, 'texas': 7984, 'lawmaker': 4552, 'threatens': 8032, 'shoot': 7187, 'colleague': 1626, 'reporting': 6584, 'protesters': 6219, 'kiss': 4439, 'forced': 3224, 'women': 8791, 'wear': 8652, 'very': 8477, 'tiny': 8069, 'bathing': 753, 'suits': 7752, 'higher': 3807, 'heels': 3758, 'buying': 1192, 'beauty': 784, 'pageants': 5642, 'sons': 7429, 'loses': 4740, 'nearly': 5304, '17': 20, 'million': 5053, 'pharma': 5834, 'stock': 7636, 'tanks': 7885, '92': 119, 'aquarium': 483, '2016': 41, 'rnc': 6744, 'delegate': 2193, 'directed': 2359, 'change': 1408, 'party': 5715, 'platform': 5921, 'ukraine': 8305, 'support': 7771, 'bra': 1045, 'senate': 7066, 'republican': 6591, 'big': 875, 'mistake': 5105, 'fire': 3128, 'mueller': 5213, 'wake': 8574, 'strange': 7666, 'last': 4527, 'office': 5481, 'pets': 5831, 'navy': 5296, 'seal': 7009, 'who': 8715, 'killed': 4421, 'bin': 892, 'laden': 4495, 'calls': 1219, 'parade': 5682, 'plan': 5908, 'third': 8020, 'world': 8808, 'bulls': 1140, 'stupidity': 7709, 'could': 1885, 'microwave': 5026, 'missiles': 5100, 'disable': 2369, 'north': 5397, 'cook': 1830, 'myeshia': 5253, 'johnson': 4326, 'widow': 8728, 'fallen': 2998, 'soldier': 7414, 'cake': 1209, 'bernie': 845, 'sanders': 6885, 'mirrors': 5083, 'hillary': 3817, 'clinton': 1569, 'combatting': 1654, 'meddling': 4957, 'denies': 2233, 'helped': 3770, 'campaign': 1229, 'stealing': 7607, 'gunmam': 3608, 'attacks': 581, 'church': 1505, 'helwan': 3775, 'cairo': 1207, 'four': 3256, 'dead': 2106, 'nine': 5367, 'wounded': 8823, 'shooter': 7188, 'pie': 5863, 'tech': 7925, 'entertainment': 2790, 'activists': 191, 'launch': 4540, 'app': 452, 'block': 943, 'bully': 1142, 'donald': 2503, 'twitter': 8294, 'patsy': 5744, 'ex': 2864, 'british': 1097, 'spy': 7536, 'paid': 5645, '168': 19, '000': 0, 'dossier': 2520, 'firm': 3135, 'discloses': 2389, 'tea': 7914, 'despite': 2285, 'boasts': 963, 'idea': 3977, 'handle': 3666, 'classified': 1547, 'material': 4910, 'smoothies': 7366, 'jailed': 4273, 'malaysian': 4813, 'opposition': 5534, 'leader': 4564, 'pardoned': 5694, 'victory': 8489, 'icbms': 3970, 'pyongyang': 6298, 'conduct': 1731, 'missile': 5099, 'test': 7977, 'anytime': 437, 'anywhere': 439, 'meme': 4980, 'largest': 4520, 'collection': 1629, 'ocean': 5464, 'garbage': 3372, 'now': 5414, 'twice': 8289, 'size': 7284, 'olympic': 5501, 'gold': 3475, 'medal': 4953, 'sucking': 7737, 'up': 8396, 'murderous': 5233, 'totalitarian': 8118, 'regime': 6495, 'vacuum': 8439, 'rex': 6701, 'tillerson': 8062, 'direct': 2358, 'channels': 1413, 'scam': 6925, 'black': 914, 'panther': 5671, 'wakanda': 8573, 'sheds': 7155, 'light': 4650, 'excellence': 2872, 'darkness': 2079, 'quotation': 6326, 'day': 2099, 'tried': 8208, 'sink': 7266, 'inquiry': 4132, 'comey': 1662, 'hoops': 3881, 'directv': 2366, 'offering': 5479, 'refunds': 6488, 'nfl': 5344, 'sunday': 7757, 'ticket': 8047, 'fans': 3014, 'offended': 5472, 'national': 5282, 'anthem': 423, 'protests': 6220, 'melody': 4976, 'deficit': 2175, 'hawks': 3722, 'seem': 7043, 'gone': 3484, 'missing': 5101, 'action': 188, 'doves': 2535, 'drunken': 2596, 'american': 365, 'beating': 780, 'giving': 3443, 'nazi': 5299, 'salute': 6874, 'germany': 3405, 'praised': 6060, 'occupy': 5463, 'silicon': 7245, 'valley': 8443, 'next': 5343, 'populist': 6014, 'aimed': 296, 'wealth': 8648, 'bunnies': 1152, 'stop': 7651, 'autocracy': 614, 'itch': 4256, 'macron': 4782, 'condemns': 1726, 'massive': 4900, 'hacking': 3626, 'attack': 577, 'documents': 2477, 'leaked': 4571, 'bbc': 765, 'news': 5339, 'water': 8631, 'making': 4809, 'americans': 366, 'see': 7038, 'way': 8640, 'rest': 6633, 'already': 351, 'despise': 2284, 'syria': 7851, 'vows': 8555, 'sign': 7235, 'paris': 5698, 'agreement': 283, 'leaving': 4583, 'alone': 348, 'climate': 1564, 'denial': 2230, 'reality': 6418, 'bill': 884, 'contains': 1800, 'sneaky': 7380, 'break': 1062, 'jet': 4307, 'owners': 5623, 'bathroom': 755, 'charlotte': 1426, 'pence': 5778, 'bought': 1027, 'gay': 3381, 'bunny': 1153, 'book': 995, 'wrote': 8842, 'this': 8021, 'congressional': 1763, 'accounting': 163, 'trick': 8206, 'part': 5707, 'reason': 6423, 'washington': 8621, 'so': 7399, 'divided': 2459, 'magic': 4790, 'advice': 235, 'do': 2472, 'robert': 6754, 'he': 3728, 'clear': 1555, 'you': 8871, 'end': 2750, 'tickle': 8048, 'middle': 5028, 'class': 1544, 'does': 2484, 'want': 8590, 'cut': 2036, 'government': 3501, 'coffee': 1616, 'there': 8007, 'enough': 2779, 'opposed': 5533, 'health': 3738, 'kill': 4420, 'bear': 774, 'experts': 2917, 'our': 5573, 'ally': 345, 'isis': 4238, 'bears': 777, 'predicts': 6078, 'patriots': 5742, 'win': 8742, 'super': 7762, 'bowl': 1035, 'points': 5962, 'gypsy': 3622, 'senators': 7068, 'drafted': 2547, 'statement': 7593, 'clearing': 1558, 'before': 803, 'her': 3779, 'interview': 4179, 'tickling': 8050, 'official': 5484, 'blocked': 945, 'immigrant': 4010, 'teen': 7930, 'rape': 6375, 'victim': 8487, 'abortion': 130, 'because': 788, 'personally': 5817, 'healthy': 3741, 'trillion': 8213, 'dollar': 2493, 'pledge': 5940, 'fix': 3150, 'bridges': 1087, 'roads': 6747, 'challenging': 1400, 'lie': 4641, 'taiwan': 7865, 'court': 1906, 'rule': 6816, 'landmark': 4504, 'sex': 7119, 'marriage': 4873, 'case': 1314, 'heterosexual': 3792, 'white': 8713, 'invites': 4210, 'intelligence': 4158, 'committee': 1679, 'leaders': 4565, 'review': 6685, 'security': 7035, 'council': 1886, 'tweets': 8285, 'fought': 3250, 'forgotten': 3241, 'filipino': 3108, 'ii': 3995, 'honored': 3874, '75': 101, 'years': 8855, 'later': 4529, 'officials': 5486, 'greet': 3553, 'ford': 3227, 'import': 4031, 'chinese': 1480, 'cars': 1304, 'food': 3211, 'should': 7203, 'publicly': 6245, 'testify': 7979, 'democrat': 2220, 'judiciary': 4353, 'strip': 7682, 'addresses': 208, 'boy': 1042, 'scouts': 6977, 'summit': 7754, 'west': 8686, 'virginia': 8517, 'rep': 6565, 'king': 4435, 'seeks': 7042, 'surveillance': 7795, 'port': 6020, 'authority': 612, 'explosion': 2929, 'we': 8643, 'ca': 1198, 'afford': 255, 'politically': 5977, 'correct': 1863, 'bowel': 1034, 'replacing': 6578, 'secretary': 7028, 'cia': 1508, 'director': 2364, 'mike': 5041, 'pompeo': 5993, 'npr': 5416, 'vegetables': 8461, 'israeli': 4248, 'minister': 5070, 'wishes': 8767, 'iranian': 4223, 'success': 7728, 'pleads': 5936, '50': 84, 'detained': 2298, 'immigration': 4013, 'raids': 6352, 'asian': 531, 'restaurants': 6636, 'mississippi': 5103, 'another': 418, 'amp': 373, 'subreddit': 7718, 'wednesday': 8663, 'apocalypse': 446, 'capital': 1268, 'confederacy': 1733, 'debate': 2121, 'city': 1526, 'famed': 3008, 'civil': 1528, 'monuments': 5162, 'heating': 3753, 'mounting': 5195, 'wolf': 8787, 'correspondents': 1867, 'dinner': 2346, 'remarks': 6538, 'sarah': 6896, 'huckabee': 3922, 'gravy': 3541, 'latest': 4530, 'san': 6879, 'juan': 4346, 'mayor': 4926, 'answers': 420, 'wasteland': 8625, 'special': 7475, 'counsel': 1887, 'impanels': 4019, 'grand': 3521, 'jury': 4365, 'koala': 4462, 'five': 3149, 'pacific': 5629, 'islands': 4244, 'lost': 4744, 'rising': 6736, 'seas': 7019, 'hits': 3841, 'sun': 7756, 'reilly': 6508, 'god': 3467, 'sexual': 7121, 'harassment': 3684, 'scandal': 6927, 'libido': 4634, 'labels': 4485, 'justice': 4367, 'system': 7854, 'laughingstock': 4537, 'renames': 6553, 'kamala': 4375, 'harris': 3694, 'testimony': 7980, 'table': 7856, 'spicer': 7496, 'problem': 6148, 'melissa': 4974, 'mccarthy': 4932, 'gum': 3606, 'discussed': 2402, 'weapons': 8651, 'manure': 4847, 'grassley': 3537, 'graham': 3518, 'off': 5471, 'letters': 4618, 'demanding': 2215, 'info': 4106, 'author': 608, 'fbi': 3048, 'editors': 2671, 'cuts': 2037, 'strengthen': 7677, 'economy': 2663, 'drive': 2578, 'crazy': 1938, 'biceps': 868, 'search': 7013, 'motive': 5192, 'las': 4522, 'vegas': 8460, 'slow': 7341, 'but': 1180, 'll': 4701, 'tortoise': 8112, 'second': 7025, 'judge': 4348, 'scott': 6971, 'walker': 8577, 'request': 6594, 'delay': 2190, 'elections': 2696, 'playground': 5928, 'peskov': 5821, 'lawyer': 4557, 'kremlin': 4470, 'got': 3496, 'response': 6630, 'santa': 6893, 'planet': 5912, 'evidence': 2859, 'tenth': 7961, 'lurking': 4768, 'edge': 2666, 'solar': 7412, 'pleasure': 5939, 'connecticut': 1768, 'pastor': 5729, 'charged': 1421, '8g': 114, 'electricity': 2699, 'praying': 6073, 'medicare': 4961, 'all': 330, 'progressive': 6172, 'just': 4366, 'pull': 6258, 'out': 5578, 'key': 4406, 'nebraska': 5306, 'primary': 6124, 'bowling': 1038, 'egyptian': 2684, 'prime': 6125, 'ahmed': 289, 'shafiq': 7133, 'withdraws': 8776, 'from': 3299, 'rib': 6705, 'wrenched': 8831, 'ahead': 288, 'shoulder': 7204, 'trips': 8218, 'station': 7596, 'afghan': 256, 'comes': 1661, 'tent': 7959, 'elon': 2712, 'musk': 5243, 'vision': 8524, 'underground': 8328, 'road': 6746, 'bumps': 1148, 'study': 7701, 'emails': 2716, 'much': 5211, 'front': 3300, 'page': 5640, 'coverage': 1912, 'policy': 5974, '69': 98, 'swallowed': 7814, 'bodyguard': 970, 'keith': 4391, 'schiller': 6946, 'testifies': 7978, 'offered': 5478, 'prostitutes': 6206, 'aligning': 327, 'story': 7660, 'pimp': 5879, 'rubio': 6813, 'defection': 2164, 'margin': 4861, 'greasiness': 3542, 'somewhere': 7423, 'between': 861, 'hero': 3784, 'scalia': 6923, 'boss': 1017, 'kennedy': 4395, 'lover': 4752, 'tacos': 7862, 'save': 6909, 'princess': 6129, 'uae': 8299, 'qatari': 6301, 'fighter': 3099, 'jets': 4308, 'intercepted': 4162, 'civilian': 1529, 'flight': 3170, 'raced': 6332, 'rip': 6732, 'roger': 6766, 'moore': 5169, 'james': 4278, 'bond': 985, 'goalie': 3462, 'israel': 4247, 'must': 5246, 'release': 6523, '16': 18, 'old': 5496, 'girl': 3436, 'faces': 2968, '10': 2, 'amnesty': 369, 'scotch': 6968, 'dreamers': 2565, 'board': 961, 'talks': 7877, 'mimes': 5059, 'prevent': 6116, 'shutdown': 7225, 'hit': 3839, 'snag': 7372, 'plans': 5915, 'goat': 3464, 'meet': 4966, 'lee': 4587, 'busby': 1170, 'alabama': 309, 'write': 8837, 'candidate': 1251, 'roy': 6806, 'cockroach': 1608, 'survivor': 7802, 'if': 3986, 'scream': 6984, 'cnn': 1595, 'mime': 5058, 'banning': 708, 'immigrants': 4011, 'helps': 3774, 'workers': 8804, 'leading': 4567, 'economist': 2661, 'wrong': 8840, 'poodles': 6001, 'suicide': 7747, 'bomber': 979, 'kills': 4425, 'seven': 7115, 'wounds': 8824, '20': 31, 'provincial': 6229, 'shopper': 7193, 'would': 8821, 'most': 5185, 'extreme': 2947, 'senator': 7067, 'huge': 3929, 'consequences': 1773, 'lecher': 4584, 'charlottesville': 1427, 'force': 3223, 'try': 8252, 'contain': 1799, 'fallout': 3001, 'spread': 7528, 'chris': 1495, 'cornell': 1857, 'soundgarden': 7440, 'frontman': 3301, 'dies': 2330, 'aged': 268, '52': 85, 'graduates': 3514, 'woman': 8790, 'running': 6826, 'double': 2524, 'mastectomy': 4901, 'repeal': 6568, 'aca': 144, 'latte': 4533, 'hate': 3708, 'present': 6096, 'canada': 1239, 'puerto': 6253, 'rico': 6711, 'benchmark': 832, 'drops': 2590, 'record': 6449, 'low': 4755, 'remark': 6537, 'spoke': 7517, 'heavy': 3755, 'disapproval': 2378, 'deep': 2154, 'against': 266, '2018': 43, 'midterms': 5035, 'dessert': 2288, 'parties': 5710, 'fight': 3098, 'funding': 3328, 'children': 1474, 'insurance': 4151, 'vomit': 8543, 'standing': 7576, 'defense': 2170, 'abusers': 142, 'promotion': 6184, 'jeff': 4295, 'sessions': 7106, 'during': 2617, 'meeting': 4967, 'accountability': 161, 'examine': 2868, 'cost': 1875, 'florida': 3187, 'grocery': 3570, 'saw': 6914, 'military': 5047, 'france': 3262, 'own': 5621, 'dog': 2485, 'mystery': 5258, 'automotive': 620, 'failures': 2986, 'reopens': 6563, 'investigation': 4199, 'into': 4184, 'clintons': 1570, 'martians': 4882, 'sold': 7413, '85bn': 110, 'scraps': 6981, 'cold': 1623, 'weather': 8656, 'leave': 4581, 'these': 8010, 'things': 8016, 'your': 8874, 'car': 1276, 'temps': 7948, 'fall': 2997, 'eat': 2652, 'unstoppable': 8387, 'satan': 6902, '2017': 42, 'pancake': 5662, 'portland': 6022, 'train': 8161, 'stabbing': 7548, 'suspect': 7806, 'said': 6856, 'what': 8693, 'liberalism': 4631, 'gets': 3409, 'docs': 2473, 'say': 6916, 'promise': 6178, 'bottom': 1026, 'transparent': 8169, 'process': 6152, 'paul': 5747, 'ryan': 6836, 'sets': 7109, 'stifling': 7631, 'floor': 3184, 'temperature': 7942, 'shoots': 7191, 'down': 2537, 'made': 4785, 'drone': 2584, 'turkey': 8265, 'urge': 8415, 'appoint': 470, 'feed': 3064, 'dems': 2227, 'back': 645, 'power': 6053, 're': 6397, 'going': 3474, 'raise': 6356, 'taxes': 7906, 'high': 3806, 'income': 4063, 'hurricane': 3954, 'maria': 4862, 'dominica': 2501, 'live': 4693, 'chuckles': 1502, 'oil': 5492, 'tanker': 7884, 'wreck': 8828, 'produces': 6159, 'two': 8295, 'slicks': 7323, 'east': 2648, 'china': 1479, 'sea': 7004, 'drifting': 2572, 'tells': 7940, 'abbas': 124, 'good': 3486, 'chance': 1404, 'mid': 5027, 'peace': 5758, 'reporter': 6582, 'reflections': 6480, 'loss': 4742, 'hair': 3631, 'keystone': 4408, 'pipeline': 5889, 'wo': 8786, 'use': 8423, 'steel': 7609, 'repeated': 6570, 'promises': 6180, 'son': 7425, 'bitch': 910, 'outburst': 5579, 'fits': 3148, 'larger': 4519, 'pattern': 5745, 'tantrum': 7887, 'journalist': 4340, 'delivers': 2208, 'searing': 7018, 'kebabs': 4385, 'killing': 4423, 'chances': 1406, 'healthcare': 3739, 'cows': 1918, 'racism': 6337, 'evil': 2860, 'barbecue': 714, 'youngest': 8873, 'shooting': 7189, '18': 21, 'months': 5161, 'licking': 4639, 'committed': 1678, 'wiping': 8759, 'islamic': 4240, 'stain': 7560, 'cuddle': 2010, '60': 90, 'voters': 8550, 'travel': 8178, 'ban': 692, 'agoraphobics': 281, 'ruble': 6814, 'plunges': 5953, '2nd': 61, 'following': 3206, 'sanctions': 6881, 've': 8456, 'set': 7107, 'surrender': 7794, 'awaken': 630, 'male': 4814, 'congressman': 1764, 'questions': 6313, 'why': 8721, 'men': 4988, 'pay': 5750, 'prenatal': 6087, 'really': 6420, 'fetuses': 3087, 'visit': 8525, 'traumatized': 8177, 'kick': 4412, 'overtake': 5611, 'euro': 2842, 'zone': 8892, 'absorb': 140, 'debbie': 2123, 'lesko': 4611, 'wins': 8755, 'arizona': 501, 'nbc': 5301, 'projects': 6175, 'lottery': 4746, 'compliance': 1705, 'tweet': 8282, 'ready': 6411, 'issues': 4251, 'warning': 8604, 'strikes': 7680, 'metal': 5010, 'tariffs': 7899, 'like': 4653, 'atomic': 574, 'bomb': 977, 'european': 2844, 'firms': 3136, 'lobbyist': 4706, 'wedgie': 8662, 'chester': 1461, 'bennington': 839, 'linkin': 4674, 'park': 5699, 'singer': 7262, '41': 76, 'sang': 6889, 'rolls': 6775, 'obamacare': 5447, 'contraceptive': 1808, 'mandate': 4827, 'candies': 1253, 'fumes': 3323, 'cohen': 1618, 'country': 1897, 'insects': 4134, 'urged': 8416, 'mexican': 5014, 'defiance': 2173, 'border': 1010, 'wall': 8580, 'striptease': 7686, 'dept': 2264, 'reverses': 6684, 'visa': 8522, 'revocations': 6693, 'allows': 343, 'banned': 707, 'travelers': 8179, 'enter': 2786, 'escape': 2826, 'breaking': 1066, 'considering': 1780, 'options': 5537, 'retaliation': 6654, 'source': 7444, 'vacation': 8437, 'post': 6036, 'david': 2094, 'fahrenthold': 2979, 'pulitzer': 6257, 'prize': 6142, 'dogged': 2487, 'philanthropy': 5837, 'crookedness': 1981, 'claims': 1533, 'increase': 4068, 'trolls': 8226, 'mean': 4944, 'accents': 149, 'judicial': 4352, 'nominee': 5382, 'refuses': 6491, 'express': 2937, 'desegregation': 2275, 'ruling': 6819, 'gratitude': 3538, 'cabos': 1202, 'longer': 4722, 'haven': 3717, 'mexico': 5016, 'bloodshed': 949, 'cuisine': 2012, 'worried': 8811, 'flynn': 3198, 'tell': 7938, 'collusion': 1639, 'worrying': 8814, 'shows': 7216, 'within': 8779, 'range': 6369, 'earshot': 2640, 'need': 5310, 'make': 4803, 'lethal': 4615, 'hope': 3884, 'flaws': 3160, 'stand': 7574, 'shakes': 7135, 'pelvis': 5775, 'liu': 4692, 'xiaobo': 8846, 'supporters': 7773, 'mark': 4868, 'death': 2117, 'amid': 367, 'concerns': 1716, 'african': 260, 'trying': 8253, 'everest': 2855, 'without': 8780, 'permit': 5805, 'shoes': 7185, 'fundraising': 3329, 'arm': 503, 'bails': 671, 'spits': 7512, 'supreme': 7781, 'blockbuster': 944, 'term': 7963, 'movies': 5207, 'word': 8798, 'professionalism': 6164, 'moon': 5166, 'california': 1214, 'control': 1815, 'jellybeans': 4299, 'coca': 1605, 'cola': 1621, 'invasion': 4191, 'causing': 1346, 'junk': 4363, 'celebrating': 1361, 'presidency': 6101, 'drawing': 2557, 'nearer': 5303, 'either': 2688, 'done': 2506, 'great': 3543, 'harm': 3693, 'america': 364, 'haircut': 3634, 'family': 3010, 'benefit': 835, 'flush': 3194, 'treasury': 8185, 'department': 2248, 'announcing': 412, 'friday': 3287, 'morning': 5176, 'silver': 7250, 'menendez': 4990, 'bribe': 1079, 'proceeds': 6151, 'rejects': 6516, 'dismissal': 2420, 'bride': 1083, 'celebration': 1362, 'crisis': 1968, 'becoming': 791, 'unsolvable': 8384, 'warn': 8601, 'heads': 3735, 'asia': 530, 'fyre': 3344, 'festival': 3083, 'organizers': 5553, '100': 3, 'lawsuit': 4556, 'bong': 990, 'lewandowski': 4623, 'invited': 4209, 'sanction': 6880, 'oligarchs': 5498, 'law': 4550, 'retaliating': 6653, 'alleged': 333, 'dressing': 2570, 'russians': 6833, 'laughing': 4536, 'phony': 5845, 'witch': 8769, 'hunt': 3950, 'pardon': 5693, 'sheriff': 7165, 'joe': 4324, 'arpaio': 515, 'courageous': 1904, 'thing': 8015, 'suspects': 7808, 'niger': 5357, 'villager': 8500, 'betrayed': 855, 'army': 511, 'troops': 8228, 'fink': 3125, 'hundreds': 3942, 'thousands': 8027, 'educators': 2673, 'hundred': 3941, 'thousand': 8026, 'homeless': 3864, 'students': 7698, 'roofs': 6785, 'india': 4078, 'build': 1132, 'major': 4800, 'facility': 2971, 'seychelles': 7125, 'growing': 3584, 'influence': 4103, 'infest': 4096, 'shrinking': 7220, 'ears': 2639, 'insult': 4150, 'native': 5287, 'smash': 7354, 'windows': 8746, 'mcdonald': 4937, 'bank': 700, 'swearing': 7823, 'wash': 8619, 'island': 4243, 'principal': 6130, 'history': 3838, 'decorum': 2151, 'race': 6331, 'ethnicity': 2840, 'profits': 6167, 'debacle': 2119, 'role': 6771, 'model': 5125, 'measles': 4947, 'debacles': 2120, 'boost': 1005, 'trade': 8151, 'worries': 8812, 'hackers': 3625, 'haitians': 3644, 'aids': 293, 'nigerians': 5359, 'huts': 3960, 'oval': 5593, 'bacchanal': 644, 'separated': 7083, 'families': 3009, 'react': 6401, 'ends': 2759, 'protected': 6209, 'status': 7599, 'condiments': 1727, 'stormy': 7659, 'daniels': 2074, 'threats': 8033, 'reports': 6585, 'affair': 247, 'cookbook': 1831, 'chiefs': 1470, 'asked': 533, 'them': 8000, 'intervene': 4176, 'investigations': 4200, 'opera': 5522, 'jerusalem': 4305, 'intimidated': 4182, 'palestinian': 5656, 'violence': 8510, 'move': 5202, 'embassy': 2720, 'hummus': 3938, 'patrol': 5743, 'raises': 6359, 'tensions': 7958, 'backpack': 654, 'eighteen': 2686, 'found': 3252, 'guilty': 3603, 'newcastle': 5337, 'grooming': 3573, 'network': 5328, 'virgins': 8519, 'denying': 2244, 'sally': 6868, 'yates': 8851, 'she': 7153, 'attention': 587, 'soon': 7430, 'alt': 352, 'neo': 5318, 'confederate': 1734, 'corey': 1853, 'stewart': 7628, 'came': 1223, 'shockingly': 7183, 'close': 1574, 'panel': 5667, 'subpoenas': 7717, 'adviser': 236, 'michael': 5021, 'oxen': 5625, 'bump': 1147, 'maker': 4806, 'resumes': 6647, 'sales': 6864, 'month': 5160, 'mass': 4893, 'eating': 2654, 'kalashnikov': 4373, 'remote': 6547, 'teachers': 7917, 'lawyers': 4558, 'others': 5569, 'worry': 8813, 'fate': 3037, 'student': 7697, 'debt': 2125, 'forgiveness': 3239, 'disappearance': 2373, 'alternatives': 355, 'putin': 6293, 'mixed': 5112, 'bag': 665, 'looms': 4729, 'drinks': 2577, 'advocacy': 240, 'group': 3580, 'accuses': 169, 'racial': 6336, 'bias': 866, 'bonehead': 988, 'plague': 5907, 'disgusted': 2408, 'officer': 5482, 'quits': 6323, 'many': 4848, 'follow': 3204, 'smoking': 7364, 'assad': 539, 'international': 4172, 'pressure': 6106, 'step': 7615, 'damascus': 2060, 'mood': 5164, 'boogie': 993, 'maybe': 4924, 'lady': 4496, 'birthday': 904, 'fat': 3034, 'maps': 4852, 'course': 1905, 'autocrats': 615, 'foreign': 3230, 'trip': 8215, 'autograph': 616, 'delight': 2202, 'sitters': 7280, 'plays': 5932, 'broadway': 1104, 'vornado': 8545, 'handshake': 3671, 'sell': 7058, 'stake': 7563, 'nyc': 5441, 'tower': 8140, 'kushner': 4480, 'give': 3440, 'strike': 7679, 'bases': 741, 'minutes': 5079, 'practicing': 6058, 'nikki': 5366, 'haley': 3645, 'seemingly': 7045, 'tricked': 8207, 'pranksters': 6069, 'commenting': 1672, 'fictional': 3091, 'binomo': 896, 'waltzing': 8586, 'jae': 4270, 'yong': 8867, 'samsung': 6878, 'indicted': 4082, 'bribery': 1081, 'kidnapping': 4418, 'un': 8311, 'myanmar': 5252, 'rohingya': 6768, 'muslims': 5245, 'kittens': 4447, 'loopholes': 4731, 'disclose': 2387, 'financial': 3115, 'fee': 3063, 'alert': 319, 'flag': 3152, 'crimes': 1961, 'fashion': 3031, 'manafort': 4822, 'notes': 5407, 'refer': 6474, 'contributions': 1814, 'legs': 4605, 'staffers': 7555, 'secret': 7027, 'assignments': 555, 'telling': 7939, 'aides': 292, 'hide': 3803, 'john': 4325, 'kelly': 4393, 'haircuts': 3635, 'looking': 4726, 'attempt': 582, 'oust': 5574, 'decency': 2132, 'refugee': 6485, 'admissions': 217, 'suspended': 7810, 'until': 8390, 'july': 4359, '12': 11, 'auditions': 601, 'lieberman': 4642, 'emerges': 2728, 'frontrunner': 3302, 'relay': 6522, 'delicious': 2201, 'idaho': 3976, 'fastest': 3033, 'potato': 6043, 'quietly': 6316, 'stalls': 7569, 'safeguards': 6852, 'dozens': 2544, 'endangered': 2752, 'species': 7476, 'bakers': 675, 'korean': 4468, 'supercharged': 7763, 'option': 5536, 'explained': 2919, 'doubt': 2526, 'gorilla': 3493, 'blame': 923, 'game': 3362, 'themselves': 8002, 'hearings': 3745, 'mccabe': 4930, 'firing': 3134, 'once': 5506, 'inspector': 4141, 'general': 3392, 'gadget': 3347, 'receives': 6434, 'ovation': 5594, 'color': 1645, 'purple': 6284, 'imagines': 4006, 'mnuchin': 5114, 'hard': 3686, 'rich': 6707, 'hedges': 3757, 'assassinations': 545, 'successfully': 7730, 'launches': 4541, 'satellite': 6903, 'carrying': 1303, 'rocket': 6759, 'space': 7454, 'tree': 8190, 'aircraft': 299, 'carrier': 1299, 'dispatch': 2428, 'outrageous': 5589, 'eight': 2685, 'm1': 4775, 'minibus': 5066, 'lorry': 4736, 'crash': 1932, 'refrigerator': 6484, 'both': 1023, 'sides': 7230, 'committing': 1681, 'burma': 1159, 'contradictions': 1811, 'upon': 8407, 'tale': 7873, 'payoff': 5755, 'porn': 6017, 'star': 7579, 'offer': 5477, 'french': 3282, 'far': 3018, 'steps': 7619, 'limelight': 4657, 'slithers': 7332, 'interfering': 4169, 'deny': 2243, 'having': 3718, 'compromising': 1711, 'information': 4109, 'elf': 2706, 'ferry': 3081, 'link': 4672, 'terror': 7972, 'risk': 6737, 'xl': 8847, 'vow': 8554, 'beer': 798, 'miss': 5096, 'asshole': 554, 'murdoch': 5235, 'billion': 886, 'bet': 852, 'indian': 4079, 'cricket': 1957, 'buffet': 1128, 'clears': 1560, 'hurdle': 3953, 'attorney': 590, 'speedster': 7483, 'dnc': 2471, 'chair': 1393, 'jaime': 4275, 'harrison': 3695, 'lobbyists': 4707, 'appetizers': 464, 'billionaire': 887, 'babis': 642, 'scores': 6967, 'czech': 2047, 'partners': 5714, 'annoy': 413, 'added': 205, 'critic': 1970, 'cleared': 1557, 'skip': 7297, 'hinted': 3823, 'anti': 426, 'moscow': 5181, 'quilts': 6320, 'among': 370, 'gallup': 3355, 'still': 7633, 'odds': 5467, 'closed': 1575, 'door': 2516, 'evens': 2852, 'seen': 7047, 'imminent': 4014, 'kim': 4428, 'meets': 4969, 'tour': 8128, 'sunk': 7758, '100m': 5, 'luxury': 4770, 'developments': 2309, 'scientists': 6962, 'turn': 8269, 'hydrogen': 3961, 'breakthrough': 1069, 'revolutionise': 6697, 'jazz': 4293, 'potential': 6045, 'legal': 4595, 'fox': 3258, 'clowns': 1589, 'swap': 7818, 'booed': 992, 'davos': 2096, 'criticizing': 1976, 'fake': 2993, 'media': 4958, 'injured': 4124, 'shots': 7202, 'fired': 3130, 'school': 6953, 'downed': 2538, 'sperry': 7493, 'organizing': 5554, 'violent': 8511, 'miles': 5043, 'farm': 3025, 'sam': 6875, 'charles': 1425, 'murray': 5236, 'allure': 344, 'science': 6959, 'werewolf': 8685, 'bombshell': 984, 'millions': 5055, 'crooked': 1980, 'uranium': 8413, 'finger': 3121, 'chang': 1407, 'serve': 7098, 'style': 7710, 'checkers': 1443, 'hung': 3943, 'parliament': 5703, 'brexit': 1077, 'negotiations': 5314, 'gigolo': 3426, 'vehicle': 8462, 'plows': 5946, 'man': 4821, 'clapper': 1538, 'admitted': 220, 'spied': 7499, 'false': 3003, 'poodle': 6000, 'poised': 5963, 'ease': 2645, 'rules': 6818, 'religious': 6530, 'groups': 3582, 'politics': 5981, 'churches': 1506, 'pelosi': 5773, 'insecurity': 4135, 'fueling': 3314, 'fraud': 3272, 'contempt': 1803, 'blitz': 939, 'betrays': 856, 'hostility': 3903, 'thumb': 8044, 'rally': 6364, 'brazil': 1059, 'turns': 8273, 'seance': 7012, 'clash': 1542, 'disputed': 2432, 'himalayan': 3820, 'region': 6496, 'barclays': 720, 'ceo': 1381, 'varley': 8452, 'three': 8034, 'bankers': 702, 'appear': 459, 'musical': 5241, 'sen': 7065, 'flake': 3155, 'or': 5539, 'lose': 4738, 'iranians': 4224, 'scheme': 6944, 'butcher': 1181, 'nato': 5288, 'countries': 1896, 'fires': 3132, 'eastern': 2650, 'coast': 1601, 'fireworks': 3133, 'friends': 3291, 'scolds': 6965, 'ceos': 1382, 'pulled': 6259, 'vagina': 8440, 'heading': 3732, 'toward': 8136, 'some': 7418, 'losses': 4743, 'midterm': 5034, 'races': 6333, 'polls': 5984, 'horse': 3894, 'ties': 8055, 'increasingly': 4070, 'credible': 1949, 'laundry': 4544, 'restricting': 6639, 'coal': 1599, 'companies': 1688, 'dumping': 2612, 'waste': 8624, 'streams': 7672, 'nypd': 5442, 'nobody': 5376, 'deported': 2258, 'jumping': 4361, 'turnstile': 8274, 'rope': 6790, 'gaza': 3383, 'rights': 6724, 'commissioner': 1676, 'criticizes': 1975, 'cupcakes': 2020, 'duterte': 2621, 'spokesman': 7519, 'return': 6667, 'philippine': 5838, 'fugitive': 3316, 'bilateral': 883, 'reward': 6699, 'balloon': 686, 'federal': 3060, 'deport': 2255, 'innovative': 4131, 'economies': 2660, 'ellison': 2711, 'backs': 656, 'chairs': 1395, 'toyota': 8144, 'boats': 965, 'dodges': 2481, 'press': 6105, 'spirals': 7506, 'harasses': 3683, 'japan': 4285, 'declines': 2145, 'comment': 1670, 'sushi': 7805, 'kelli': 4392, 'ward': 8595, 'clean': 1551, 'foremost': 3232, 'bikini': 881, 'dna': 2470, 'scratch': 6982, 'alter': 353, 'blueprint': 958, 'sasquatch': 6900, 'lead': 4563, 'reform': 6482, 'needs': 5311, 'stupid': 7708, 'social': 7405, 'data': 2083, 'shared': 7144, 'agencies': 269, 'cat': 1322, 'harsh': 3696, 'language': 4512, 'little': 4691, 'precedent': 6075, 'dogs': 2489, 'hoagie': 3843, 'london': 4719, 'molotov': 5140, 'cocktails': 1611, 'terrorists': 7975, 'van': 8448, 'bartenders': 735, 'announced': 409, 'venezuela': 8465, 'turnout': 8272, 'constituent': 1786, 'assembly': 548, 'vote': 8546, 'drilling': 2573, 'read': 6406, 'coretta': 1852, 'letter': 4617, 'outside': 5590, 'mcconnell': 4935, 'march': 4856, 'cities': 1520, 'across': 184, 'mockery': 5120, 'pete': 5825, 'passage': 5718, 'delivering': 2207, 'wanted': 8591, 'racists': 6339, 'calais': 1211, 'leaves': 4582, 'teenage': 7931, 'refugees': 6486, 'critical': 1971, 'smuggling': 7369, 'gangs': 3366, 'exploit': 2928, 'desperation': 2283, 'turtles': 8276, 'gateshead': 3379, 'nothing': 5408, 'urges': 8418, 'other': 5568, 'local': 4709, 'authorities': 611, 'cheapskates': 1438, 'gm': 3458, 'company': 1689, 'production': 6162, 'shenanigans': 7162, 'likely': 4655, 'headquarters': 3734, 'few': 3089, 'decades': 2129, 'reported': 6580, 'maryland': 4886, 'sparking': 7465, 'lockdown': 4713, 'sparklers': 7466, 'faithful': 2992, 'flock': 3179, 'vatican': 8455, 'pope': 6008, 'christmas': 1498, 'eve': 2849, 'mall': 4816, 'global': 3454, 'investors': 4205, 'fresh': 3285, 'fudge': 3310, 'realizing': 6419, 'legislative': 4602, 'agenda': 271, 'hands': 3670, 'menu': 4994, 'hhs': 3797, 'readying': 6412, 'expand': 2899, 'conscience': 1771, 'protections': 6213, 'eliminate': 2708, 'cripple': 1967, 'purchase': 6281, 'call': 1216, 'includes': 4060, 'plea': 5933, 'moral': 5173, 'courage': 1903, 'gun': 3607, 'legislation': 4601, 'mind': 5061, 'dakota': 2056, 'protested': 6217, 'leaks': 4573, 'animals': 398, 'manhandled': 4829, 'fcc': 3049, 'net': 5323, 'neutrality': 5331, 'rumble': 6821, 'threw': 8035, 'bus': 1169, 'failure': 2985, 'sloths': 7339, 'stocks': 7640, 'lower': 4756, 'successful': 7729, 'mocking': 5121, 'influential': 4104, 'outsiders': 5591, 'played': 5925, 'pruitt': 6232, 'wizards': 8785, 'told': 8089, 'ny': 5440, 'schneiderman': 6950, 'abuse': 141, '2013': 40, 'plane': 5909, 'crashes': 1934, 'bicycle': 869, 'budget': 1126, 'safe': 6851, 'mother': 5189, 'roaches': 6745, 'violated': 8506, 'constitution': 1788, 'speech': 7479, 'martini': 4884, 'scarborough': 6931, 'awkward': 636, 'silence': 7242, 'admission': 216, '43': 79, 'farmer': 3026, 'hawaii': 3719, 'smuggled': 7367, '15': 17, 'deportation': 2256, 'battle': 761, 'returns': 6669, 'salmon': 6870, 'hyping': 3966, '77': 103, 'previously': 6118, 'omitted': 5504, 'assets': 553, 'pennies': 5786, 'banker': 701, 'home': 3862, 'loans': 4703, 'leftovers': 4591, 'loves': 4753, 'wing': 8749, 'radical': 6343, 'equally': 2805, 'serious': 7094, 'adl': 212, 'music': 5240, 'prepared': 6090, 'litigate': 4690, 'time': 8063, 'warner': 8603, 'cry': 2004, 'camp': 1228, 'january': 4284, 'igloo': 3987, 'plead': 5934, 'stay': 7600, 'message': 5005, 'pass': 5717, 'overhaul': 5603, 'qualcomm': 6304, 'regulators': 6504, 'push': 6286, '44': 80, 'nxp': 5439, 'overlords': 5604, 'deflects': 2182, 'nunes': 5434, 'lasers': 4525, 'bridgegate': 1086, 'lands': 4507, 'christie': 1497, 'baroni': 726, 'cells': 1368, 'seek': 7040, 'citing': 1522, 'nastiness': 5280, 'era': 2812, 'dinners': 2347, 'uk': 8304, 'universities': 8369, 'tackle': 7860, 'tide': 8053, 'antisemitism': 429, 'campus': 1236, 'relative': 6520, 'denounced': 2236, 'supremacy': 7780, 'resigns': 6615, 'wizard': 8784, 'eu': 2841, 'aluminum': 356, 'deodorant': 2245, 'suddenly': 7740, 'replaces': 6577, 'acting': 187, 'customs': 2035, 'head': 3729, 'daniel': 2073, 'ragsdale': 6350, 'thomas': 8022, 'homan': 3861, 'ugly': 8303, 'pointed': 5960, 'conflict': 1747, 'energy': 2764, 'voter': 8548, 'runs': 6828, 'inauguration': 4053, 'crowd': 1989, '2009': 37, 'vs': 8558, 'stadium': 7551, 'approved': 479, 'ladders': 4494, 'around': 513, 'kisses': 4441, 'waffle': 8565, 'al': 308, 'franken': 3267, 'slams': 7307, 'education': 2672, 'betsy': 858, 'devos': 2313, 'incompetent': 4066, 'cabinet': 1200, 'level': 4621, 'ever': 2854, 'moons': 5167, 'promised': 6179, 'access': 152, 'exec': 2880, 'crack': 1923, 'listening': 4686, 'bad': 662, 'confession': 1738, 'nevada': 5332, 'wildly': 8739, 'different': 2335, 'elephant': 2704, 'epa': 2800, 'reduce': 6467, 'workforce': 8805, 'buyouts': 1193, 'early': 2637, 'retirement': 6659, 'execution': 2883, 'considered': 1779, 'buses': 1171, 'seat': 7021, 'district': 2449, 'won': 8793, '19': 23, 'opinion': 5526, 'threatening': 8031, 'democracy': 2219, 'undermining': 8331, 'silencing': 7243, 'conservatives': 1777, 'guns': 3611, 'gut': 3612, 'doubles': 2525, 'inherited': 4119, 'mess': 5004, 'claim': 1530, 'dip': 2350, 'expectancy': 2904, 'inequality': 4092, 'upswing': 8412, 'its': 4258, 'entire': 2791, 'resign': 6611, 'prom': 6176, 'reich': 6506, 'warring': 8610, 'camps': 1235, 'potatoes': 6044, 'red': 6459, 'lawmakers': 4553, 'find': 3117, 'blue': 957, 'piggy': 5869, 'impulsive': 4047, 'dancing': 2069, 'dem': 2213, 'nsa': 5418, 'leak': 4570, 'offers': 5480, 'verified': 8474, 'linking': 4675, 'don': 2502, 'mcgahn': 4938, 'threatened': 8030, 'june': 4362, 'sing': 7260, 'cable': 1201, 'careening': 1283, 'defining': 2179, 'moment': 5142, 'broadside': 1103, 'cries': 1958, 'newt': 5342, 'gingrich': 3433, 'him': 3819, 'holds': 3855, 'joint': 4331, 'conference': 1735, 'norway': 5400, 'updates': 8400, 'sir': 7271, 'known': 4460, 'age': 267, '89': 113, 'due': 2604, 'cancer': 1250, 'aid': 290, 'withdrawing': 8774, 'shoe': 7184, 'limits': 4662, 'retirements': 6660, 'create': 1940, 'competitive': 1697, 'speed': 7481, 'probably': 6144, 'grandpa': 3528, 'posts': 6040, '192': 25, 'february': 3057, 'monopoly': 5154, 'bob': 966, 'hertzberg': 3790, 'cooperate': 1839, 'unwanted': 8394, 'hugs': 3931, 'aromas': 512, 'giant': 3415, 'shipworm': 7175, 'philippines': 5839, 'dreadlock': 2560, 'barack': 712, 'chicago': 1464, 'library': 4636, 'nor': 5393, 'believer': 824, 'community': 1687, 'museum': 5238, 'kristol': 4471, 'voice': 8537, 'biggest': 878, 'opponents': 5531, 'bladder': 920, 'manslaughter': 4841, 'eyed': 2958, 'grenfell': 3558, 'blaze': 932, 'weed': 8664, 'crime': 1959, 'behind': 816, 'bars': 734, 'plants': 5918, 'seattle': 7024, 'dismiss': 2419, 'misdemeanor': 5088, 'marijuana': 4863, 'dynamite': 2628, 'tough': 8124, 'talk': 7875, 'ballet': 683, 'noncriminal': 5386, 'past': 5727, 'festivals': 3084, 'fear': 3051, 'sweater': 7824, 'examining': 2869, 'tanning': 7886, 'mosque': 5182, 'egypt': 2683, 'sinai': 7258, '235': 54, 'befuddles': 804, 'schumer': 6958, 'donate': 2504, 'harvey': 3701, 'weinstein': 8674, 'cologne': 1640, 'drag': 2548, 'resistance': 6617, 'lingerie': 4670, 'bullet': 1137, 'costs': 1878, 'soar': 7401, 'opening': 5520, 'delayed': 2191, 'algeria': 321, 'dump': 2611, 'scud': 6999, 'ballistic': 685, 'briefed': 1088, 'google': 3489, 'doing': 2490, 'irreparable': 4234, 'hamsters': 3662, 'armenian': 508, 'sobs': 7403, 'skeptical': 7289, 'suit': 7749, 'outfit': 5582, 'italian': 4254, 'pm': 5954, 'gentiloni': 3396, 'slurs': 7349, 'announcement': 410, 'speculation': 7477, 'theresa': 8008, 'debates': 2122, 'tory': 8116, 'sources': 7445, 'favors': 3045, 'names': 5271, 'charmaine': 1428, 'yoest': 8864, 'lonely': 4720, 'chelsea': 1454, 'manning': 4840, 'hurts': 3956, 'congressmen': 1765, 'fault': 3041, 'order': 5545, 'sends': 7071, 'pro': 6143, 'growth': 3586, 'environment': 2795, 'pizza': 5902, 'partner': 5713, 'dressmakers': 2571, 'insurer': 4152, 'flees': 3164, 'blaming': 926, 'sabotage': 6839, 'bats': 758, 'jail': 4272, 'free': 3277, 'cards': 1280, 'work': 8801, 'footloose': 3217, 'keeps': 4390, 'team': 7919, 'guessing': 3597, 'bewildered': 862, 'confirms': 1746, 'reinhold': 6511, 'niebuhr': 5352, 'brayed': 1057, 'hopes': 3886, 'improved': 4043, 'everything': 2858, 'opec': 5517, 'agree': 282, 'extend': 2941, 'vodka': 8535, 'conservative': 1776, 'activist': 190, 'lauren': 4547, 'southern': 7448, 'sorceress': 7434, 'begins': 810, 'attacking': 580, 'crocodile': 1979, '1st': 30, 'amendment': 363, 'speak': 7471, 'college': 1631, 'sneeze': 7381, 'analysis': 380, 'best': 850, 'deals': 2115, 'prove': 6222, 'muffins': 5214, 'jordan': 4339, 'selects': 7054, 'finalists': 3112, '300mw': 63, 'wind': 8743, 'earth': 2641, 'georgia': 3401, 'quiet': 6315, 'tricare': 8205, 'stirs': 7635, 'ire': 4227, 'headaches': 3731, 'becomes': 790, 'popular': 6011, 'modern': 5130, 'mascot': 4889, 'pointing': 5961, 'fingers': 3124, 'stalemate': 7565, 'pool': 6003, 'criminalizing': 1964, 'abortions': 131, 'weeks': 8667, 'burritos': 1167, 'semitic': 7063, 'messages': 5006, 'matzos': 4920, 'yemen': 8858, 'cholera': 1489, 'cases': 1315, 'reach': 6398, 'icrc': 3974, 'hiccup': 3798, 'upper': 8408, 'hand': 3663, 'trillions': 8214, 'breaks': 1068, 'wh': 8690, 'comms': 1683, 'anthony': 424, 'scaramucci': 6930, 'deletes': 2196, 'contradicting': 1810, 'sings': 7265, 'allow': 339, 'buy': 1190, 'equipment': 2810, 'pornography': 6019, 'cash': 1316, 'mccain': 4931, 'joke': 4333, 'controversy': 1818, 'fan': 3013, 'watched': 8628, 'oath': 5444, 'pretty': 6113, 'nasa': 5278, 'ok': 5493, 'touch': 8121, 'hardware': 3690, 'honor': 3872, 'host': 3901, 'xi': 8845, 'takes': 7871, 'rebuttal': 6433, 'protectionism': 6212, 'rant': 6373, 'position': 6030, 'accusers': 168, 'lying': 4772, 'crab': 1922, 'charts': 1430, 'show': 7209, 'ignore': 3990, 'horoscopists': 3890, 'elected': 2694, 'spend': 7489, 'reporters': 6583, 'celebrities': 1363, 'thoughts': 8025, 'distress': 2447, 'signal': 7236, 'upside': 8410, 'pin': 5882, 'smoke': 7362, 'teacher': 7916, 'apologizes': 451, 'accidentally': 155, 'classroom': 1548, 'let': 4614, 'pot': 6042, 'flourish': 3190, 'associated': 558, 'freedom': 3278, 'sanctuary': 6882, 'states': 7595, 'enforcement': 2766, 'driving': 2583, 'performing': 5801, 'nightmare': 5363, 'marathons': 4854, 'colon': 1642, 'businesses': 1175, 'proposal': 6192, 'stink': 7634, 'buzzfeed': 1195, 'unverified': 8393, 'igniting': 3988, 'father': 3038, 'self': 7055, 'imposed': 4035, 'curbs': 2022, 'celibacy': 1365, 'disrupt': 2436, 'rightwing': 6725, 'german': 3404, 'afd': 246, 'goers': 3470, 'netherlands': 5326, 'answer': 419, 'refused': 6490, 'windmill': 8744, 'horses': 3896, 'spending': 7490, 'excludes': 2878, 'declares': 2140, 'anyway': 438, 'bankruptcy': 704, 'admin': 213, 'had': 3628, 'justifiable': 4369, 'sharing': 7147, 'soccer': 7404, 'extremists': 2950, 'triangle': 8200, 'saudi': 6905, 'crownprince': 1992, 'salman': 6869, 'snitches': 7385, 'manchin': 4826, 'skips': 7298, 'informational': 4110, 'useful': 8425, 'idiots': 3984, 'galore': 3356, 'york': 8868, 'times': 8066, 'juggler': 4355, 'aide': 291, 'accused': 166, '2008': 36, 'healing': 3737, 'while': 8700, 'week': 8665, 'snowflakes': 7394, 'play': 5923, 'mainstream': 4799, 'sympathy': 7847, 'pray': 6071, 'lifts': 4649, 'cops': 1846, 'dresses': 2569, 'announces': 411, 'waterpark': 8634, 'problems': 6149, 'obstruction': 5460, 'bribes': 1082, 'tout': 8133, 'daca': 2050, 'quite': 6322, 'cruise': 1999, 'line': 4667, 'carnival': 1290, 'corp': 1860, 'joins': 4330, 'bermuda': 844, 'donut': 2511, 'full': 3320, 'touts': 8135, 'reforms': 6483, 'open': 5518, 'business': 1174, 'eases': 2646, 'service': 7101, 'delivery': 2209, 'religion': 6529, 'responds': 6629, 'sweating': 7825, 'australia': 604, 'accept': 150, 'central': 1378, 'nose': 5402, 'advisers': 237, 'melania': 4973, 'trapped': 8174, 'money': 5149, 'put': 6292, 'danger': 2071, 'recommend': 6447, 'payment': 5753, 'ers': 2821, 'ted': 7927, 'nugent': 5425, 'parkland': 5701, 'teens': 7933, 'nra': 5417, 'soul': 7437, 'corporate': 1861, 'ignores': 3992, 'rise': 6734, 'oligarchy': 5499, 'yeast': 8856, 'dealing': 2112, 'migrant': 5038, 'escalating': 2825, 'whether': 8698, 'keeping': 4389, 'mold': 5136, 'alex': 320, 'jones': 4337, 'fears': 3053, 'come': 1657, 'conspiracy': 1784, 'theorist': 8005, 'bro': 1098, 'anymore': 434, 'prance': 6063, 'bird': 900, 'devil': 2311, 'theory': 8006, 'endorses': 2758, 'lgbt': 4624, 'attorneys': 591, 'argue': 497, 'gays': 3382, 'voterbase': 8549, 'terms': 7967, 'ratings': 6389, 'jeopardize': 4300, 'suntan': 7761, 'futures': 3342, 'point': 5959, 'sharply': 7149, 'street': 7674, 'friendly': 3290, 'cohn': 1619, 'bridge': 1085, 'feared': 3052, 'storm': 7657, 'swamps': 7817, 'undead': 8323, 'led': 4585, 'enforce': 2765, 'axes': 638, 'transgender': 8167, 'independent': 4076, 'trees': 8192, 'secretly': 7029, 'helping': 3772, 'chechen': 1440, 'flee': 3163, 'persecution': 5809, 'radar': 6341, 'programme': 6169, 'mired': 5081, 'paralysis': 5687, 'defy': 2184, 'recovery': 6453, 'child': 1472, 'labor': 4486, 'jobs': 4322, 'pies': 5866, 'waiting': 8572, 'permanent': 5803, 'clearance': 1556, 'guard': 3591, 'caroline': 1293, 'glick': 3450, 'gives': 3442, 'cause': 1344, 'camel': 1224, 'candidates': 1252, 'winning': 8754, 'explains': 2921, 'reasons': 6424, 'risque': 6740, 'dealmaking': 2114, 'mode': 5124, 'works': 8807, 'scenes': 6940, 'duck': 2601, 'describes': 2272, 'words': 8799, 'clothing': 1585, 'bush': 1172, 'diplomat': 2353, 'scared': 6934, 'legalise': 4596, 'isolated': 4245, 'settlement': 7110, 'settler': 7112, 'murdered': 5230, 'netanyahu': 5324, 'dumpster': 2615, 'timing': 8068, 'again': 265, 'suggests': 7746, 'tweeted': 8283, 'watching': 8630, 'segment': 7049, 'chick': 1465, 'painting': 5651, 'temporarily': 7946, 'breakout': 1067, 'meal': 4943, 'look': 4723, 'pumpkin': 6265, 'broke': 1107, 'ethics': 2838, 'laws': 4555, 'jaywalking': 4292, 'dubs': 2600, 'knight': 4455, 'lavishes': 4549, 'carpet': 1295, 'treatment': 8188, 'arrives': 520, 'jinping': 4319, 'oscars': 5564, 'blocks': 946, 'clinic': 1568, 'band': 695, 'blake': 922, 'farenthold': 3022, 'diving': 2461, 'went': 8682, 'listen': 4684, 'fast': 3032, 'haters': 3710, 'clearly': 1559, 'trap': 8173, 'affirmative': 253, 'hypocrisy': 3968, 'foes': 3202, 'diversity': 2456, 'those': 8023, 'oppose': 5532, 'my': 5251, 'dad': 2052, 'funny': 3334, 'nsc': 5419, 'dense': 2238, 'confused': 1754, 'facebook': 2967, 'bans': 710, 'jehovah': 4297, 'witnesses': 8781, 'claiming': 1532, 'extremist': 2949, 'activities': 192, 'petraeus': 5829, 'warns': 8606, 'current': 2027, 'fray': 3274, 'collapse': 1624, 'harvester': 3699, 'trumpcare': 8240, 'question': 6310, 'whole': 8716, 'economic': 2659, 'dementia': 2218, 'western': 8687, 'airstrikes': 305, 'unlikely': 8373, 'impact': 4018, 'machine': 4779, 'evangelical': 2846, 'slippery': 7330, 'slope': 7336, 'ronald': 6782, 'reagan': 6413, 'soap': 7400, 'weaving': 8657, 'propagandistic': 6189, 'fantasy': 3017, 'tickled': 8049, 'doug': 2527, 'upset': 8409, 'bed': 792, 'beneath': 834, 'dignity': 2339, 'sweeteners': 7829, 'certified': 1387, 'dumb': 2608, 'ass': 538, 'psychologist': 6239, 'psychoneurotic': 6240, 'shut': 7224, 'computer': 1712, 'girls': 3438, 'become': 789, 'brides': 1084, 'malaysia': 4812, 'immediately': 4009, 'bolt': 975, 'nafta': 5261, 'join': 4327, 'keefe': 4386, 'busts': 1178, 'editor': 2670, 'explaining': 2920, 'paper': 5678, 'narrative': 5277, 'demands': 2216, 'withdraw': 8772, 'branding': 1052, 'apartheid': 441, 'tractor': 8150, 'erdogan': 2814, 'clucking': 1593, 'pershing': 5810, 'cited': 1518, 'effect': 2674, 'remains': 6535, 'wynn': 8844, 'finance': 3114, 'reclining': 6444, 'suck': 7735, 'mitt': 5111, 'romney': 6781, 'trolled': 8223, 'flip': 3172, 'flopping': 3186, 'endorsement': 2757, 'wig': 8730, 'triggers': 8212, 'alarm': 310, 'warnings': 8605, 'living': 4697, 'weak': 8644, 'unstable': 8386, 'warned': 8602, 'seth': 7108, 'murder': 5229, 'staffer': 7554, 'protect': 6208, 'newscasters': 5340, 'iraqi': 4226, 'forces': 3225, 'tigris': 8061, 'stronghold': 7691, 'mosul': 5187, 'clubhouse': 1591, 'policies': 5972, 'guardian': 3592, 'hotel': 3908, 'raised': 6357, 'room': 6786, 'rates': 6386, 'colluded': 1638, 'fuck': 3309, 'daughters': 2091, 'too': 8100, 'takeover': 7870, 'aecon': 244, 'grounds': 3579, 'takeout': 7869, 'clue': 1594, 'true': 8238, 'sacrifice': 6844, 'bakeries': 674, 'jong': 4338, 'agrees': 285, 'dmz': 2469, 'jackie': 4266, 'mason': 4891, 'grammys': 3520, 'competition': 1696, 'hates': 3711, 'watch': 8626, 'advocate': 241, 'matt': 4916, 'schlapp': 6948, 'treasonous': 8183, 'golf': 3480, 'thumbs': 8045, 'controversies': 1817, 'navarro': 5295, 'diplomats': 2355, 'video': 8490, 'eagles': 2635, 'defensiveness': 2171, 'handling': 3668, 'grief': 3559, 'worse': 8815, 'mail': 4796, 'geun': 3411, 'hye': 3962, 'impeachment': 4022, 'trial': 8199, 'dancer': 2066, 'minnesota': 5073, 'tom': 8093, 'emmer': 2731, 'snow': 7393, 'boris': 1012, 'condemned': 1724, 'libya': 4637, 'bodies': 968, 'jokes': 4335, 'bleach': 934, 'backed': 647, 'given': 3441, 'spa': 7453, 'spies': 7500, 'targeting': 7897, 'maritime': 4867, 'industry': 4091, 'cape': 1267, 'town': 8141, 'drought': 2591, 'avoid': 626, 'zero': 8883, 'towel': 8138, 'organisation': 5550, 'lack': 4491, 'scientific': 6960, 'thinking': 8018, 'store': 7654, 'nancy': 5272, 'hails': 3630, 'owe': 5619, 'parents': 5697, 'bring': 1092, 'kids': 4419, 'dolls': 2495, 'le': 4562, 'pen': 5776, 'moves': 5205, 'monde': 5148, 'studio': 7700, 'swedish': 7827, 'prosecutor': 6201, 'truck': 8234, 'spoken': 7518, 'stuffing': 7702, 'sad': 6849, 'view': 8493, 'depression': 2263, 'arrested': 517, 'linda': 4665, 'wenzel': 8683, 'shepherd': 7163, 'vermont': 8476, 'governor': 3503, 'vetoes': 8482, 'changes': 1410, 'joints': 4332, 'employee': 2738, 'controversial': 1816, 'promotes': 6183, 'mascots': 4890, 'sprinter': 7532, 'thanksgiving': 7993, 'majority': 4802, 'prefer': 6080, 'side': 7229, 'wrestle': 8832, 'biden': 871, 'liar': 4628, 'nicest': 5350, 'sweetheart': 7832, 'resubmit': 6643, 'renewals': 6556, 'originally': 5558, 'rejected': 6514, 'late': 4528, 'ross': 6794, 'linked': 4673, 'shipping': 7174, 'concern': 1715, 'brothel': 1113, 'wiretap': 8762, 'alien': 325, 'royals': 6808, 'crown': 1991, 'prince': 6127, 'participation': 5708, 'olympics': 5502, 'affect': 249, 'centenarian': 1374, 'union': 8361, 'lap': 4515, 'landfill': 4501, 'chairman': 1394, 'pai': 5644, 'substituting': 7723, 'ideology': 3982, 'art': 522, 'chuckle': 1501, 'messing': 5008, 'picture': 5861, 'perfect': 5798, 'simpletons': 7255, 'millennials': 5051, 'bitcoin': 911, 'steal': 7606, 'genius': 3394, 'means': 4945, 'smarts': 7353, 'path': 5734, 'fails': 2984, 'unity': 8366, 'cambridge': 1222, 'analytica': 381, 'friend': 3288, 'footballs': 3216, 'plotted': 5944, 'effort': 2677, 'rival': 6741, 'shave': 7150, 'cannabis': 1258, 'halved': 3652, 'convulsions': 1828, 'funded': 3326, 'epilepsy': 2803, 'munchies': 5228, 'famine': 3011, 'sudan': 7738, 'charge': 1420, 'permits': 5806, 'consumer': 1794, 'protection': 6211, 'puts': 6294, 'equifax': 2808, 'hayden': 3724, 'willing': 8741, 'throw': 8039, 'almost': 347, 'anything': 436, 'de': 2105, 'legitimize': 4604, 'portrait': 6023, 'widespread': 8727, 'killings': 4424, 'cast': 1319, 'shadow': 7130, 'laughter': 4539, 'suspected': 7807, 'rebel': 6427, 'planted': 5917, 'mine': 5063, 'yemeni': 8859, 'ship': 7173, 'instant': 4145, 'questioned': 6311, 'nightmares': 5364, 'slogan': 7335, 'drinking': 2576, 'award': 631, 'uplifting': 8406, 'stories': 7656, 'remind': 6542, 'jeremy': 4301, 'scahill': 6919, 'fareed': 3021, 'zakaria': 8877, 'bashes': 743, 'silo': 7248, 'waters': 8635, 'conversation': 1822, 'chocolate': 1484, '63rd': 93, 'straight': 7663, 'quarter': 6305, 'propaganda': 6188, 'residents': 6610, 'presidential': 6103, 'palace': 5655, 'terrorism': 7973, 'percent': 5796, 'murders': 5234, 'newborns': 5336, 'pledged': 5941, 'relief': 6527, 'constipation': 1785, 'loosely': 4733, 'regulated': 6501, 'market': 4870, 'biofuel': 897, 'credits': 1953, 'spurs': 7534, 'speculators': 7478, 'swindlers': 7837, 'polluters': 5987, 'founder': 3254, 'bringing': 1093, 'panthers': 5672, 'pa': 5627, 'start': 7585, 'unborn': 8318, 'unicorns': 8355, 'oversight': 5609, 'fiscal': 3139, 'mob': 5117, 'building': 1133, 'mysterious': 5257, 'artificial': 526, 'worshiping': 8818, '202': 45, 'run': 6824, 'dematerialize': 2217, 'newly': 5338, 'released': 6524, 'howard': 3920, 'stern': 7623, 'tapes': 7890, 'feature': 3054, 'admitting': 221, 'psychological': 6238, 'rt': 6810, 'sputnik': 7535, 'ads': 227, 'interference': 4168, 'yorker': 8869, 'lizza': 4700, 'improper': 4041, 'hippo': 3828, 'katie': 4384, 'incumbent': 4071, '25': 57, 'nibble': 5348, 'blow': 953, 'ukraines': 8306, 'ammunition': 368, 'supplies': 7769, 'cupcake': 2019, 'francis': 3264, 'fights': 3101, 'employees': 2739, 'used': 8424, 'improve': 4042, 'wheelchairs': 8695, 'malls': 4818, 'finds': 3118, 'sloppy': 7337, 'misconduct': 5087, 'handwriting': 3672, 'vice': 8485, 'documentary': 2476, 'worth': 8820, 'pirating': 5893, 'poultry': 6047, 'reviews': 6686, 'guam': 3587, 'stark': 7583, 'quit': 6321, 'allegations': 332, 'sneezing': 7382, 'medicaid': 4959, 'kentucky': 4398, 'slash': 7312, '9000': 117, 'portrays': 6024, 'destroyed': 2293, 'barrage': 728, 'spaghetti': 7456, 'dhs': 2315, 'electronics': 2701, 'expanded': 2900, 'flights': 3171, 'departing': 2247, 'wires': 8761, 'tattoo': 7902, 'gabbanelli': 3345, 'cantabella': 1263, 'accordion': 159, 'sock': 7409, 'mouth': 5201, 'nielsen': 5354, 'never': 5333, 'trumper': 8242, 'barber': 716, 'tame': 7879, 'wades': 8564, 'deeper': 2156, 'hesitation': 3791, 'underwater': 8336, 'preparing': 6092, 'subpoena': 7715, 'memos': 4987, 'gubernatorial': 3594, '400': 75, 'trebek': 8189, 'tries': 8209, 'moderator': 5129, 'sells': 7061, 'jacks': 4267, 'aiming': 297, 'christians': 1496, 'minority': 5075, 'pakistan': 5654, 'affiliated': 252, 'coalition': 1600, 'mulvaney': 5225, 'difficult': 2336, 'casino': 1317, 'manipulate': 4835, 'delousing': 2210, 'rand': 6367, 'arms': 510, 'arabia': 486, 'camels': 1225, 'outcry': 5581, 'infosys': 4113, 'hire': 3830, 'targets': 7898, 'outsourcing': 5592, 'dishwasher': 2412, 'postpones': 6039, 'hearing': 3744, 'personal': 5815, 'facing': 2972, 'felony': 3072, 'united': 8365, 'clown': 1588, 'swaps': 7820, 'beloved': 828, 'burgers': 1156, 'salads': 6858, 'soups': 7443, 'diet': 2332, 'ireland': 4228, 'enda': 2751, 'kenny': 4397, 'rub': 6811, 'jobless': 4321, 'plunge': 5952, 'lowest': 4758, 'weekly': 8666, 'tally': 7878, '1973': 27, 'seals': 7010, 'noun': 5411, 'verb': 8471, 'vladimir': 8532, 'adjective': 211, 'iraq': 4225, 'shopkeeper': 7192, 'such': 7734, 'obvious': 5461, 'lies': 4644, 'catalonia': 1327, 'puigdemont': 6256, 'defeat': 2160, 'spanish': 7459, 'raffle': 6346, 'real': 6414, 'superman': 7765, 'spiderman': 7497, 'propose': 6194, 'requiring': 6599, 'fair': 2988, 'prices': 6120, 'taxpayer': 7911, 'drugs': 2593, 'highs': 3809, 'shady': 7132, 'dealings': 2113, 'evoke': 2861, 'nepotism': 5319, 'corruption': 1869, 'gilded': 3427, 'snack': 7370, 'bound': 1031, 'singing': 7263, 'couple': 1901, 'rented': 6562, 'condo': 1729, 'pays': 5757, 'fine': 3119, 'condor': 1730, 'happy': 3680, 'europe': 2843, 'peanuts': 5763, 'lynch': 4773, 'prosecution': 6200, 'pleas': 5937, 'chauvinist': 1434, 'greeted': 3554, 'selfies': 7057, 'arrival': 519, 'english': 2773, 'speaking': 7473, 'powerful': 6054, 'stepping': 7618, 'evolution': 2862, 'ignored': 3991, 'fraudulent': 3273, 'comments': 1673, 'scoundrel': 6974, 'upcoming': 8398, 'karaoke': 4380, 'deputy': 2266, 'felt': 3073, 'pressured': 6107, 'christopher': 1499, 'wray': 8827, 'wasserman': 8623, 'schultz': 6957, 'pimple': 5880, 'throws': 8043, 'pitcher': 5898, 'bathtub': 757, 'admits': 219, 'conversations': 1823, 'taunts': 7904, 'teach': 7915, 'partisanship': 5712, 'phonebook': 5842, 'decided': 2133, 'disband': 2382, 'claimed': 1531, 'disbanded': 2383, 'guggenheim': 3599, 'gogh': 3472, 'toilet': 8087, 'target': 7895, 'coordination': 1841, 'expert': 2916, 'decorator': 2149, 'wrestling': 8835, 'championship': 1403, 'dirt': 2367, 'ag': 264, 'tarmac': 7900, 'innocuous': 4129, 'teleportation': 7936, 'canceled': 1246, 'stolen': 7643, 'lennon': 4607, 'items': 4257, 'recovered': 6452, 'berlin': 843, 'tub': 8255, 'corbyn': 1849, 'woos': 8797, 'small': 7351, 'crackdown': 1924, 'payments': 5754, 'deliveries': 2206, 'enrique': 2782, 'peña': 5833, 'nieto': 5355, 'cancels': 1249, 'planned': 5913, 'passed': 5719, 'detector': 2301, 'which': 8699, 'unprotected': 8381, 'met': 5009, 'breitbart': 1073, '45': 81, 'trafficked': 8156, 'website': 8659, 'beats': 782, 'huffpo': 3927, 'wapo': 8593, 'foxnews': 3259, 'pageviews': 5643, 'owns': 5624, 'gina': 3431, 'haspel': 3704, 'lean': 4574, 'confectioner': 1732, 'transcript': 8165, 'stoneman': 7646, 'hall': 3647, 'repeatedly': 6571, 'shouts': 7206, 'raucous': 6394, 'panda': 5664, 'green': 3548, 'introduces': 4189, 'articles': 525, 'stole': 7642, 'banks': 705, 'incompetence': 4065, 'profit': 6166, 'divisive': 2464, 'brands': 1053, 'acronyms': 183, 'strategy': 7668, 'afghanistan': 257, 'figure': 3102, 'heather': 3752, 'heyer': 3795, 'funeral': 3331, 'proposition': 6197, 'trending': 8196, 'st': 7546, 'patrick': 5740, 'clover': 1587, 'confusion': 1756, 'sexist': 7120, 'row': 6805, 'catawampus': 1330, 'eurosceptic': 2845, 'govt': 3504, 'linebacker': 4668, 'watchdog': 8627, 'actress': 196, 'intellectual': 4157, 'righ': 6722, 'dinosaurs': 2349, 'swalwell': 7815, 'dares': 2076, 'declassify': 2143, 'backing': 652, 'amputations': 375, 'arab': 485, 'qatar': 6300, 'memoir': 4983, 'reveal': 6675, 'barred': 729, 'opinions': 5527, 'publisher': 6247, 'expelled': 2910, 'monkey': 5152, 'tuesday': 8257, 'indiana': 4080, 'ohio': 5491, 'carolina': 1292, 'furniture': 3335, 'plastic': 5919, 'pollution': 5988, 'wildlife': 8738, 'scotland': 6969, 'beautiful': 783, 'beaches': 769, 'tourist': 8130, 'juanita': 4347, 'broaddrick': 1101, 'handler': 3667, 'raped': 6376, 'ghost': 3412, 'stars': 7584, 'nudists': 5423, 'climber': 1566, 'penalty': 5777, 'rapists': 6378, 'legalizes': 4599, '418m': 77, 'sale': 6863, 'kenya': 4399, 'paraplegic': 5691, 'smokes': 7363, 'constitutional': 1789, 'verge': 8473, 'anniversary': 407, 'barcelona': 719, 'avoiding': 627, 'button': 1188, 'bigger': 877, 'yvette': 8876, 'cooper': 1838, 'urgent': 8417, 'commons': 1682, 'ending': 2756, 'reset': 6606, 'knife': 4454, 'fentanyl': 3080, 'deaths': 2118, 'outpace': 5586, 'prescription': 6095, 'painkiller': 5648, 'overdoses': 5601, 'chainsaw': 1392, 'cpac': 1921, 'identity': 3981, 'inviting': 4211, 'milo': 5057, 'symptom': 7849, 'ails': 294, 'conservatism': 1775, 'disinviting': 2416, 'raccoons': 6330, 'infuriated': 4117, 'refusal': 6489, 'preview': 6117, 'sleepover': 7320, 'indonesia': 4088, 'estate': 2834, 'project': 6174, 'confuses': 1755, 'curb': 2021, 'cookies': 1833, 'pillow': 5876, 'animal': 397, 'metoo': 5013, 'actual': 198, 'rebels': 6428, 'operation': 5524, 'idlib': 3985, 'drain': 2551, 'swamp': 7816, 'diverted': 2457, 'tissue': 8076, 'botches': 1022, 'beginning': 809, 'deliver': 2204, 'paychecks': 5751, 'babies': 641, 'dutch': 2620, 'pushups': 6290, 'toupees': 8127, 'undocumented': 8340, 'backbone': 646, 'dairies': 2055, 'trouble': 8230, 'staying': 7601, 'focused': 3201, 'indictments': 4084, 'recipes': 6441, 'curved': 2032, 'penises': 5785, 'greater': 3544, 'angles': 395, 'gluten': 3457, 'empathy': 2736, 'argument': 498, 'brings': 1094, 'approach': 475, 'jiggle': 4312, 'date': 2086, 'announce': 408, 'monday': 5147, 'tuna': 8262, 'burger': 1155, 'pushes': 6288, 'section': 7031, '301': 64, 'trail': 8158, 'revealing': 6677, 'secrets': 7030, 'ignorance': 3989, 'alternative': 354, 'scandel': 6929, 'pug': 6254, 'snubs': 7398, 'mummy': 5227, 'praise': 6059, 'witches': 8770, 'excited': 2877, 'replace': 6574, 'kidnap': 4416, 'banksy': 706, 'bethlehem': 853, 'worst': 8819, 'speedy': 7484, 'conflicts': 1749, 'interest': 4164, 'infant': 4093, 'await': 629, 'countermemo': 1891, 'languishes': 4513, 'truth': 8250, 'assange': 541, 'sycophant': 7843, 'delicatessens': 2200, 'marathon': 4853, 'rough': 6796, 'appointments': 473, 'prioritize': 6132, 'crucifix': 1995, 'explain': 2918, 'bacon': 660, 'admonish': 222, 'pudding': 6250, 'squatting': 7538, 'mission': 5102, 'accomplished': 156, 'bombing': 981, 'thought': 8024, 'unlike': 8372, 'share': 7143, 'sensitive': 7076, 'blonde': 948, 'sanitary': 6890, 'pads': 5639, 'being': 818, 'collected': 1628, 'reactor': 6404, 'dark': 2077, 'moods': 5165, 'scrutiny': 6997, 'shadowy': 7131, 'pants': 5675, 'beto': 854, 'rourke': 6802, 'cruz': 2003, 'laps': 4517, 'where': 8697, 'learned': 4577, 'love': 4750, 'assail': 540, 'unilateralism': 8357, 'culture': 2016, 'tepco': 7962, 'bosses': 1018, 'plant': 5916, 'crooks': 1982, 'mere': 4997, 'counterspies': 1893, 'temer': 7941, 'passive': 5724, 'aggressiveness': 277, 'capturing': 1275, 'creditors': 1952, 'hip': 3825, 'hop': 3883, 'lyrics': 4774, 'mommy': 5145, 'protester': 6218, 'escorted': 2828, '39': 73, 'deer': 2157, 'daunting': 2092, 'list': 4683, 'nkorea': 5371, 'dances': 2068, 'letting': 4619, 'go': 3460, 'television': 7937, 'criminal': 1962, 'carriers': 1300, 'operate': 5523, 'noodles': 5391, 'stopped': 7652, 'then': 8003, 'cop': 1844, 'punched': 6267, 'choked': 1487, 'shot': 7200, 'proposals': 6193, 'improving': 4046, 'systems': 7855, 'edition': 2669, 'beast': 778, 'remake': 6536, 'embrace': 2723, 'signaling': 7237, 'skill': 7293, 'turning': 8270, 'awards': 632, 'counter': 1890, 'pooch': 5999, 'warren': 8609, 'buffett': 1129, 'berkshire': 842, 'hathaway': 3712, 'dumps': 2614, 'vampire': 8445, 'hello': 3768, 'called': 1217, 'cellphone': 1366, 'blows': 956, 'background': 651, 'earlier': 2636, 'acknowledged': 176, 'skinny': 7296, 'spiral': 7505, 'muslim': 5244, 'videos': 8491, 'produce': 6157, 'slump': 7347, 'remington': 6544, 'files': 3106, 'tumble': 8259, 'bayonet': 764, 'challenge': 1397, 'arkansas': 502, 'medication': 4962, 'raps': 6380, 'retreat': 6663, 'finland': 3126, 'colombian': 1641, 'farc': 3020, 'final': 3111, 'calendar': 1213, 'meat': 4950, 'janitor': 4282, 'nap': 5274, 'sue': 7741, 'approving': 481, 'holocaust': 3860, 'denier': 2232, 'chooses': 1492, 'seems': 7046, 'backup': 658, 'mitch': 5110, 'bathe': 751, 'koch': 4463, 'brothers': 1115, 'loyal': 4759, 'servants': 7097, 'serving': 7103, 'sisters': 7273, 'relevance': 6526, 'reject': 6513, 'isolationism': 4246, 'cheeseburgers': 1450, 'left': 4589, 'pundits': 6272, 'drooled': 2587, 'puns': 6276, 'tracking': 8149, 'dystopia': 2631, 'pivots': 5901, 'insanity': 4133, 'finally': 3113, 'universal': 8367, 'everyone': 2857, 'margarita': 4860, 'blast': 929, 'kurdish': 4476, 'diyarbakir': 2467, 'conway': 1829, 'gaining': 3351, 'steam': 7608, 'trains': 8164, 'ancient': 385, 'frozen': 3305, 'tomb': 8096, 'scythian': 7003, 'siberia': 7227, 'alligator': 336, 'inflammatory': 4098, 'offensive': 5475, 'aborts': 132, 'pregnancy': 6083, 'center': 1376, 'clients': 1562, 'rely': 6532, 'upbeat': 8397, 'victims': 8488, 'loot': 4734, 'burn': 1160, 'collision': 1636, 'directive': 2363, 'airport': 303, 'turmoil': 8268, 'mounts': 5196, 'hats': 3714, 'funerals': 3332, 'weight': 8671, 'soldiers': 7415, 'took': 8101, 'night': 5361, 'addicts': 206, 'easy': 2651, 'slaughterhouse': 7314, 'employed': 2737, 'illegal': 3997, 'clones': 1573, 'dr': 2545, 'congo': 1758, '250': 58, 'ethnic': 2839, 'massacres': 4894, 'talking': 7876, 'sure': 7782, 'wire': 8760, 'diaper': 2319, 'fellow': 3070, 'impossible': 4037, 'onto': 5514, 'removing': 6552, 'costume': 1879, 'ad': 200, 'calling': 1218, 'complicit': 1706, 'dieting': 2333, 'japanese': 4286, 'ministry': 5072, 'proposed': 6195, 'cover': 1911, 'land': 4500, 'heart': 3747, 'mao': 4849, 'stalin': 7566, 'authoritarianism': 610, '101': 6, 'kasich': 4381, 'hickenlooper': 3800, '2020': 46, 'happen': 3675, 'fail': 2980, 'glitch': 3451, 'lets': 4616, 'corporations': 1862, 'infra': 4115, 'ultrasonic': 8308, 'waves': 8637, 'responsible': 6632, 'cuba': 2007, 'bat': 749, 'gaffe': 3348, 'product': 6161, 'fit': 3146, 'pigeons': 5868, 'publishes': 6249, 'trigger': 8210, 'article': 524, 'kitty': 4448, 'missouri': 5104, 'spit': 7509, 'half': 3646, 'poverty': 6050, 'discrimination': 2400, 'balloons': 687, 'unsolved': 8385, 'dilemma': 2340, 'inflict': 4101, 'pain': 5646, 'admit': 218, 'roasting': 6750, 'young': 8872, 'afghans': 258, 'taliban': 7874, 'quack': 6302, 'session': 7105, 'protest': 6216, 'nomination': 5381, 'kimmel': 4430, 'using': 8430, 'medical': 4960, 'score': 6966, 'penguin': 5781, 'allowing': 342, 'darkest': 2078, 'spent': 7491, '230k': 53, 'covering': 1914, 'fees': 3067, 'britches': 1096, 'norwegians': 5401, 'hole': 3856, 'takeaways': 7867, 'startling': 7587, 'priority': 6133, 'safer': 6853, 'partying': 5716, 'beacon': 770, 'initial': 4121, 'fusion': 3340, 'gps': 3507, 'research': 6602, 'convention': 1820, 'unplumbed': 8379, 'depths': 2265, 'sinks': 7269, 'wacko': 8562, 'caps': 1270, 'form': 3243, 'assault': 546, 'carve': 1313, 'glacier': 3444, 'exists': 2896, '70': 99, 'die': 2328, 'adulthood': 228, 'insists': 4139, 'someday': 7419, 'dictators': 2325, 'tweetstorms': 8287, 'briefings': 1090, 'shirt': 7177, 'zuckerberg': 8899, 'officially': 5485, 'gates': 3378, 'rain': 6354, 'snap': 7376, 'cbo': 1353, 'premiums': 6086, 'expensive': 2913, '140': 16, 'buried': 1158, 'landslide': 4510, 'destroys': 2294, 'village': 8499, 'southwest': 7449, 'toys': 8145, 'leprechauns': 4610, 'chuck': 1500, 'grandmother': 3526, 'kicked': 4413, 'caucus': 1341, 'positive': 6032, 'trevor': 8197, 'noah': 5374, 'destroye': 2292, 'delusional': 2212, 'kanye': 4378, 'saying': 6917, 'slavery': 7315, 'choice': 1485, 'evasion': 2848, 'splatters': 7514, 'gillespie': 3428, 'declined': 2144, 'grandchildren': 3522, 'asylums': 567, 'built': 1135, 'fairy': 2990, 'focus': 3200, 'slobbering': 7334, 'onion': 5508, 'impeach': 4020, 'exam': 2867, 'aceh': 171, 'canes': 1256, 'couples': 1902, 'affection': 251, 'sadism': 6850, 'hosed': 3897, 'entitlements': 2792, 'quarterbacks': 6307, 'preps': 6093, 'thaad': 7988, 'kimchi': 4429, 'lashes': 4526, 'rebuff': 6429, 'passes': 5721, 'ask': 532, 'frogs': 3297, 'player': 5926, 'erick': 2817, 'erickson': 2818, 'teapot': 7921, 'carson': 1305, 'proposes': 6196, 'poor': 6004, 'rent': 6559, 'landlord': 4503, 'memorials': 4985, 'created': 1941, 'remembered': 6541, 'nobel': 5375, 'donkey': 2507, 'falls': 3002, 'short': 7195, 'drink': 2575, 'residence': 6608, 'bigfoot': 876, 'here': 3781, 'expect': 2903, 'apple': 468, 'event': 2853, 'ios': 4216, 'macbooks': 4777, 'ipads': 4218, 'century': 1380, 'unacceptable': 8314, 'unable': 8313, 'gas': 3376, 'risks': 6738, 'single': 7264, 'graph': 3534, 'song': 7426, 'file': 3104, 'irs': 4236, 'clock': 1571, 'devin': 2312, 'discredit': 2398, 'instead': 4146, 'proved': 6223, 'something': 7422, 'carter': 1307, 'collapses': 1625, 'dehydration': 2189, 'overeating': 5602, 'brother': 1114, 'sentenced': 7079, 'related': 6517, 'glowing': 3455, 'losing': 4741, 'failing': 2982, 'lay': 4559, 'including': 4061, 'caterers': 1333, 'probing': 6147, 'fends': 3079, 'fury': 3339, 'abroad': 135, 'laughs': 4538, 'fawning': 3046, 'borscht': 1015, 'regained': 6494, 'hamster': 3661, 'remove': 6549, 'hungary': 3945, 'university': 8370, 'ngos': 5345, 'hungry': 3947, 'catcher': 1331, 'cootie': 1842, 'id': 3975, 'botch': 1020, 'nomorenazi': 5384, 'sparks': 7467, 'online': 5509, 'backlash': 653, 'agent': 273, 'communications': 1685, 'kennel': 4396, 'heal': 3736, 'daughter': 2090, 'leads': 4568, 'polluted': 5986, 'minds': 5062, 'oklahoma': 5494, 'prostitution': 6207, 'pathetic': 5735, 'assimilation': 556, 'morally': 5174, 'unfit': 8348, 'scathing': 6937, 'intensifies': 4159, 'criticism': 1973, 'investigating': 4198, 'links': 4676, 'cats': 1339, 'nawaz': 5297, 'sharif': 7146, 'disqualified': 2433, 'sports': 7523, 'australian': 605, 'unveils': 8392, 'kangaroo': 4376, 'carl': 1287, 'higbie': 3805, 'racist': 6338, 'paints': 5652, 'presidents': 6104, '31': 65, 'fund': 3325, 'headache': 3730, 'appalling': 453, 'bolton': 976, 'exhibit': 2890, 'citizens': 1524, 'returning': 6668, 'dishes': 2410, 'believes': 825, 'exonerating': 2898, 'thrown': 8042, 'glen': 3448, 'campbell': 1232, '81': 107, 'pinecone': 5885, 'signs': 7240, 'upgrade': 8403, 'martin': 4883, 'luther': 4769, 'birthplace': 906, 'historic': 3836, 'crib': 1956, 'aggressive': 276, 'schedule': 6943, 'develop': 2308, 'submarine': 7712, 'lookalikes': 4724, 'pretended': 6110, 'hong': 3871, 'kong': 4466, 'jewel': 4309, 'nevertrump': 5334, 'columnist': 1649, 'bananas': 694, 'cookoff': 1835, 'dick': 2323, 'cheney': 1457, 'restarting': 6634, 'torture': 8113, 'interrogation': 4175, 'program': 6168, 'turtle': 8275, 'basically': 746, 'me': 4941, 'help': 3769, 'reelected': 6469, 'dawdling': 2098, 'tests': 7982, 'patience': 5737, 'ketchup': 4403, 'searchable': 7014, 'archive': 491, 'buttons': 1189, 'doll': 2492, 'begs': 811, 'number': 5429, 'zones': 8893, 'rises': 6735, 'chef': 1453, 'louise': 4748, 'slaughter': 7313, 'champion': 1402, '88': 112, 'beef': 796, 'feels': 3066, 'vindicated': 8504, 'pet': 5823, 'detractors': 2303, 'weigh': 8669, 'female': 3075, 'whines': 8704, 'professor': 6165, 'incites': 4059, 'riot': 6729, '67': 97, 'politicians': 5979, 'voted': 8547, 'robots': 6758, 'george': 3400, 'bust': 1176, 'revises': 6689, 'conservation': 1774, 'sage': 6855, 'grouse': 3583, 'hunting': 3952, 'timeline': 8065, 'chemical': 1456, 'salsa': 6872, 'trainer': 8162, 'mourns': 5198, 'unarmed': 8315, 'nominees': 5383, 'sweep': 7828, 'dust': 2618, 'headlines': 3733, '2011': 39, 'spur': 7533, 'goldfish': 3477, 'disappearing': 2375, 'seagrass': 7006, 'protects': 6215, 'pathogens': 5736, 'surfers': 7786, 'obscenity': 5455, 'believe': 823, 'interfere': 4166, 'pastries': 5730, 'cnnpolitics': 1596, 'com': 1650, 'shower': 7212, 'caught': 1342, 'greece': 3546, 'laundering': 4543, 'hotdogs': 3907, 'issue': 4249, 'executive': 2884, 'lgbtq': 4626, 'ninjas': 5368, 'reckoning': 6443, 'dream': 2562, 'act': 185, 'manufacturing': 4846, 'slows': 7345, 'forecast': 3228, 'december': 2131, 'rose': 6791, 'africa': 259, 'existing': 2895, 'agreements': 284, 'underwear': 8337, 'complex': 1703, 'scramble': 6978, 'endures': 2760, 'highlights': 3808, 'split': 7515, 'paralyze': 5688, 'interviewed': 4180, 'rosenstein': 6793, 'summer': 7753, 'tortured': 8114, 'tucker': 8256, 'carlson': 1288, 'braincells': 1049, 'homosexuals': 3869, 'chechnya': 1441, 'concentration': 1714, 'suffer': 7743, 'electrocution': 2700, 'fatal': 3035, 'beatings': 781, 'anonymously': 417, 'texting': 7986, 'scrubdown': 6995, 'arthur': 523, 'backer': 648, 'conga': 1757, 'deserve': 2278, 'hampshire': 3659, 'iowa': 4217, 'eyes': 2963, 'loom': 4728, 'rigs': 6726, 'bamboozle': 690, 'obscene': 5454, 'masquerade': 4892, 'criticised': 1972, 'douma': 2532, 'lt': 4761, 'gov': 3498, 'dan': 2062, 'games': 3363, 'shootings': 7190, 'lunches': 4767, 'indie': 4085, 'drama': 2553, 'cannes': 1259, 'banana': 693, 'fleet': 3165, 'whale': 8691, 'seahorse': 7008, 'flexes': 3167, 'muscle': 5237, 'coracobrachialis': 1848, 'defers': 2172, 'surgery': 7789, 'facial': 2969, 'crimea': 1960, 'ambitions': 361, 'jason': 4289, 'chaffetz': 1390, 'invents': 4194, 'housing': 3918, 'ignoring': 3993, 'utah': 8432, 'doughnut': 2529, 'atlantic': 573, 'walls': 8583, 'giuliani': 3439, 'terrorist': 7974, 'pre': 6074, 'pens': 5789, 'apologize': 450, 'fever': 3088, 'hay': 3723, 'cataclysm': 1323, 'dc': 2102, 'intoxicates': 4185, '900': 116, 'palestinians': 5657, 'converge': 1821, 'fence': 3077, 'ants': 430, 'winter': 8757, 'stepped': 7617, 'dancers': 2067, 'wilbur': 8735, 'surprised': 7791, 'mummies': 5226, 'mice': 5020, 'tie': 8054, 'randomly': 6368, 'pulling': 6260, 'name': 5269, 'ditch': 2452, 'price': 6119, 'crimping': 1966, 'hamburger': 3656, 'sounds': 7441, 'writer': 8838, 'hear': 3742, 'arguments': 499, 'undisclosed': 8338, 'contacts': 1797, 'bookmakers': 997, 'chaos': 1417, 'jelly': 4298, 'gig': 3422, 'obstacles': 5459, 'working': 8806, 'porter': 6021, 'resigned': 6613, 'totally': 8119, 'spousal': 7526, 'leadership': 4566, 'flew': 3166, 'expense': 2912, 'nobost': 5377, 'cared': 1282, 'geese': 3388, 'sideways': 7233, 'defending': 2167, 'bernstein': 846, 'ballgame': 684, 'boosting': 1007, '53': 86, 'skunked': 7302, 'pockets': 5956, 'silent': 7244, 'bagel': 666, 'scots': 6970, 'fully': 3321, 'engaged': 2768, 'scottish': 6972, 'independence': 4075, 'manhunt': 4832, 'leaker': 4572, 'gave': 3380, 'wikileaks': 8733, 'mexicans': 5015, 'prospect': 6203, 'deportee': 2259, 'glasses': 3446, 'closets': 1580, 'baked': 673, 'uber': 8300, 'cto': 2006, 'email': 2714, 'techno': 7926, 'gain': 3350, 'votes': 8551, 'slot': 7338, 'penguins': 5782, 'exclusive': 2879, 'example': 2870, 'sweden': 7826, 'bum': 1144, 'approves': 480, 'installment': 4144, 'disaster': 2379, 'markets': 4872, 'mideast': 5029, 'modest': 5132, 'drop': 2588, 'temperatures': 7943, 'astronaut': 564, 'peggy': 5771, 'whitson': 8714, 'dangerous': 2072, 'fresno': 3286, 'spree': 7530, 'custody': 2034, 'pajamas': 5653, 'tremendous': 8194, 'anger': 393, 'wife': 8729, 'trudeau': 8237, 'decides': 2134, 'poke': 5967, 'grizzly': 3568, 'seats': 7023, 'bargain': 722, 'snooze': 7388, 'emmanuel': 2730, 'bread': 1061, 'monsanto': 5155, 'manufactured': 4845, 'studies': 7699, 'chimpanzees': 1477, 'oregon': 5549, 'sues': 7742, 'kroger': 4472, 'refusing': 6492, 'shotgun': 7201, 'shells': 7159, 'weddings': 8661, 'cim': 1512, '600': 91, 'jpmorgan': 4344, 'loan': 4702, 'brooklyn': 1111, 'site': 7277, 'cracks': 1927, 'hospitalization': 3899, 'eyebrows': 2957, 'migrants': 5039, 'begun': 812, 'pineapples': 5884, 'legend': 4600, 'zelda': 8882, 'gaming': 3364, 'reddit': 6460, 'permissive': 5804, 'attitude': 589, 'poisoning': 5965, 'internet': 4173, 'society': 7407, 'labour': 4487, 'leap': 4575, 'judgement': 4349, 'condemning': 1725, 'lights': 4652, 'earthquake': 2643, 'sichuan': 7228, 'suspend': 7809, 'shuts': 7226, 'spank': 7460, 'memorial': 4984, 'honors': 3876, 'himself': 3821, 'fries': 3292, 'schoolboys': 6954, 'enduring': 2761, 'cycle': 2044, 'fugu': 3317, 'freakout': 3275, 'blowfish': 954, 'poisonous': 5966, 'inflate': 4099, 'rifle': 6718, 'joked': 4334, 'overturned': 5616, 'spatula': 7470, 'au': 596, 'fighting': 3100, 'whining': 8705, 'integrity': 4155, 'dershowitz': 2269, 'praises': 6061, 'place': 5906, 'hatred': 3713, 'cheddar': 1445, 'affirms': 254, 'reluctantly': 6531, 'monkeys': 5153, 'envies': 2794, 'preserves': 6100, 'mars': 4878, 'asteroid': 561, 'mourning': 5197, '773': 104, 'camera': 1226, 'sending': 7070, 'powder': 6051, 'apartment': 442, 'crackhouse': 1926, 'shares': 7145, 'questioning': 6312, 'pick': 5854, 'defied': 2177, 'pursuing': 6285, 'dengue': 2228, 'immunization': 4016, 'yogurt': 8866, 'ostriches': 5567, 'sit': 7274, 'dress': 2568, 'cup': 2018, 'players': 5927, 'cafeteria': 1205, 'doctor': 2474, 'shortage': 7196, 'rural': 6829, 'whiskey': 8709, 'houseplant': 3915, 'fukushima': 3319, 'executives': 2885, 'disney': 2424, 'bonus': 991, 'depends': 2250, 'signing': 7239, 'wage': 8566, 'contract': 1809, 'gym': 3617, 'kellyanne': 4394, 'mostly': 5186, '199': 29, 'hilarious': 3815, 'ariana': 500, 'grande': 3523, 'concert': 1717, 'explosions': 2930, 'confirmed': 1744, 'fatalities': 3036, 'bumblebees': 1146, 'jim': 4316, 'carrey': 1296, 'eyeful': 2959, 'crotch': 1987, 'text': 7985, 'kusher': 4479, 'whopper': 8719, 'absent': 138, 'annual': 414, 'rocks': 6760, 'lit': 4688, 'wick': 8723, 'agency': 270, 'candles': 1254, 'comprehend': 1709, 'manchester': 4825, 'confirm': 1742, 'schoolgirl': 6955, 'eilidh': 2687, 'macleod': 4781, '14': 15, 'arena': 495, 'terrier': 7969, 'toes': 8085, 'prankster': 6068, 'pretending': 6111, 'reince': 6510, 'priebus': 6122, 'confrontational': 1752, 'enabled': 2745, 'timidity': 8067, 'elijah': 2707, 'cummings': 2017, 'advisors': 239, 'morphed': 5178, 'fission': 3144, 'famous': 3012, 'descent': 2271, 'socialist': 7406, 'hell': 3767, 'utopia': 8434, 'gao': 3368, 'dispute': 2431, 'armando': 505, 'iannucci': 3969, 'highway': 3810, 'nowhere': 5415, 'think': 8017, 'cowardice': 1916, 'pandas': 5665, 'oversee': 5606, 'rum': 6820, 'useless': 8426, 'zealand': 8879, 'involved': 4213, 'incident': 4056, 'fame': 3007, 'pompadours': 5992, 'statue': 7597, 'vandalize': 8450, 'apparel': 454, 'vocals': 8534, 'bar': 711, 'defamation': 2159, 'settlements': 7111, 'body': 969, 'cocktail': 1610, 'ways': 8642, 'figures': 3103, 'jerry': 4303, 'brown': 1117, 'salt': 6873, 'womensmarch': 8792, 'kitchens': 4444, 'oliver': 5500, 'users': 8427, 'sacrifices': 6846, 'ucla': 8302, 'dungeon': 2616, 'happiness': 3679, 'paraquat': 5692, 'recover': 6451, 'herpes': 3787, 'fantastic': 3016, 'overseeing': 5607, 'renovate': 6557, 'kitten': 4446, 'actions': 189, 'vetting': 8484, 'rebuilding': 6430, 'dodging': 2482, 'gangsters': 3367, 'courthouse': 1908, 'firefight': 3131, 'canaries': 1242, 'eyelashes': 2960, '180': 22, 'degree': 2187, 'shift': 7168, 'geopolitical': 3399, 'whiplash': 8708, 'diapers': 2320, 'emojis': 2733, 'ax': 637, 'policing': 5973, 'funds': 3330, 'pulls': 6262, 'pact': 5636, 'preferred': 6081, 'roadside': 6748, 'bombings': 982, 'linguistic': 4671, 'speaks': 7474, 'grade': 3510, 'coworker': 1917, 'bookstore': 999, 'tehran': 7935, 'garden': 3373, 'opens': 5521, 'censorship': 1372, 'virtual': 8520, 'stakes': 7564, 'bungle': 1149, 'roundness': 6800, 'soaring': 7402, 'imports': 4033, 'hamas': 3655, 'cooking': 1834, 'indonesian': 4089, 'jakarta': 4276, 'pollsters': 5985, 'eats': 2655, 'spain': 7457, 'uncertainty': 8320, 'future': 3341, 'jfk': 4311, 'stewardesses': 7627, 'offense': 5474, 'loretta': 4735, 'volleyball': 8539, 'rob': 6752, 'anomaly': 415, 'symbol': 7845, 'trumpism': 8244, 'midlife': 5033, 'overstepped': 5610, 'stairs': 7562, 'beijing': 817, 'hurt': 3955, 'cynically': 2046, 'boosters': 1006, 'eyelid': 2961, 'livestock': 4696, 'cuban': 2008, 'changed': 1409, 'aim': 295, 'halt': 3650, 'catalan': 1324, 'maryam': 4885, 'mirzakhani': 5084, 'fields': 3094, '40': 74, 'landscaper': 4508, 'disorder': 2426, 'mimics': 5060, 'parkinson': 5700, 'pasta': 5728, 'vomits': 8544, 'vancouver': 8449, 'fifa': 3096, 'itself': 4259, 'inspired': 4142, 'consider': 1778, 'respond': 6627, 'nukes': 5427, 'objectify': 5452, 'pushed': 6287, 'several': 7116, 'dollars': 2494, 'seconds': 7026, 'sows': 7452, 'avert': 625, 'seed': 7039, 'gen': 3390, 'honorable': 3873, 'homes': 3866, 'manners': 4839, 'snoop': 7387, 'dogg': 2486, 'loving': 4754, 'industrial': 4090, 'revolutions': 6698, 'wrecking': 8829, 'balls': 689, 'feminists': 3076, 'moab': 5115, 'aftermath': 263, 'tours': 8132, 'dropped': 2589, 'handkerchief': 3665, 'eyelids': 2962, 'abolish': 129, 'mentioned': 4993, 'disclosure': 2390, 'allowance': 340, 'speaker': 7472, 'unraveling': 8382, 'string': 7681, 'chats': 1432, 'briefly': 1091, 'vietnam': 8492, 'paramour': 5689, 'slapped': 7309, 'walks': 8579, '35': 67, 'sentence': 7078, 'sleeping': 7319, 'package': 5633, 'resolve': 6621, 'pretzel': 6114, 'taxi': 7907, 'cheese': 1448, 'formally': 3244, 'roll': 6772, 'stamp': 7571, 'honest': 3870, 'scares': 6935, 'gabbard': 3346, 'dated': 2087, 'spas': 7469, 'preserve': 6099, 'kumquats': 4475, 'exact': 2865, 'labradors': 4489, 'revive': 6691, 'goldmine': 3479, 'tips': 8073, 'toupee': 8126, 'billions': 889, 'nigel': 5356, 'farage': 3019, 'julian': 4357, 'mammals': 4820, 'strongly': 7692, 'defend': 2166, 'revise': 6687, 'quota': 6325, 'showing': 7215, 'minimum': 5067, 'wages': 8567, 'chanted': 1415, 'michigan': 5023, 'baby': 643, 'taxpayers': 7912, 'bang': 696, 'buck': 1123, 'squeeze': 7539, 'alek': 317, 'manassian': 4824, 'identified': 3978, 'toronto': 8111, 'attacker': 579, 'goose': 3490, 'subservient': 7720, 'property': 6191, 'exposed': 2934, 'peddle': 5766, 'ponies': 5995, 'master': 4902, 'destiny': 2290, 'oracles': 5540, 'rave': 6395, 'expel': 2909, 'surprises': 7792, 'buddies': 1125, 'tn': 8077, 'veto': 8481, 'illiteracy': 4000, 'aliens': 326, 'legalized': 4598, 'sacrificing': 6848, 'dinosaur': 2348, 'unless': 8371, 'compelled': 1693, 'feb': 3056, '28': 59, '02': 1, 'et': 2836, 'asking': 534, 'knew': 4453, 'hacked': 3624, 'incoherent': 4062, 'dipsomaniac': 2357, 'serbian': 7087, 'montenegro': 5159, 'grenade': 3557, 'flowers': 3192, 'marchers': 4857, 'threaten': 8029, 'pigeon': 5867, 'upgrading': 8404, 'cheque': 1458, 'envoy': 2798, 'trophy': 8229, 'emu': 2743, 'groomer': 3572, 'slayer': 7317, 'dragon': 2550, 'hyperplasia': 3965, 'patchwork': 5733, 'likes': 4656, 'understands': 8335, 'justified': 4370, 'prancing': 6065, 'anecdote': 390, 'unmasks': 8375, 'dehumanization': 2188, 'eyebrow': 2956, 'puppy': 6280, 'switch': 7839, 'obsolete': 5458, 'protractor': 6221, 'pours': 6049, 'lipinski': 4678, 'keys': 4407, 'cheeseburger': 1449, 'continue': 1806, 'indefinitely': 4074, 'zombies': 8891, 'employers': 2740, 'exemption': 2886, 'birth': 903, 'immoral': 4015, 'establishment': 2833, 'opened': 5519, 'implying': 4030, 'non': 5385, 'booze': 1008, 'nerd': 5320, 'wasps': 8622, 'cory': 1871, 'booker': 996, 'posturing': 6041, 'boa': 960, 'britain': 1095, 'able': 128, 'regulations': 6503, 'multiple': 5224, 'thailand': 7989, 'injure': 4123, 'taco': 7861, 'begging': 808, 'bets': 857, 'punchline': 6270, 'franks': 3269, 'carry': 1302, 'groceries': 3569, 'bustier': 1177, 'tony': 8099, 'blair': 921, 'intervention': 4178, 'joys': 4343, 'comparison': 1692, 'replacement': 6576, 'terrible': 7968, 'spark': 7464, 'strain': 7664, 'relationships': 6519, 'imploded': 4028, 'gohmert': 3473, 'mcauliffe': 4929, 'facilitating': 2970, 'creationist': 1944, 'strict': 7678, 'rudy': 6815, 'divorced': 2466, 'judith': 4354, 'falling': 2999, 'unemployment': 8344, 'payrolls': 5756, 'add': 204, '138': 13, 'reservoir': 6605, 'scare': 6932, 'asylum': 566, 'furry': 3337, 'maduro': 4788, 'banger': 697, 'misguided': 5089, 'violation': 8508, 'cheer': 1446, 'curfew': 2024, '36': 69, 'popcorn': 6006, 'certainly': 1386, 'meant': 4946, 'disrespect': 2434, 'pose': 6026, 'photo': 5846, 'respect': 6626, 'disclosed': 2388, 'confidential': 1741, 'zebras': 8881, 'ed': 2665, 'sunshine': 7760, 'unveil': 8391, 'punishing': 6275, 'thursday': 8046, 'chores': 1493, 'cbs': 1354, 'overall': 5598, '38': 72, 'confetti': 1739, 'smile': 7360, 'poses': 6028, 'models': 5127, 'austrian': 607, 'crossing': 1986, 'italy': 4255, 'sword': 7840, 'barn': 724, 'grill': 3562, 'frankfurters': 3268, 'grigory': 3561, 'rodchenkov': 6762, 'whistleblower': 8711, 'cheats': 1439, 'whistles': 8712, 'reacts': 6405, 'applauds': 466, 'trash': 8175, 'witnessing': 8782, 'motion': 5191, 'borrow': 1013, 'filed': 3105, 'extension': 2944, 'electoral': 2697, 'aerial': 245, 'footage': 3214, 'devastated': 2306, 'font': 3210, 'doomsday': 2515, 'ticks': 8051, '30': 62, 'closer': 1577, 'annihilation': 406, 'thanks': 7992, 'brunch': 1118, 'smooth': 7365, 'wrinkles': 8836, 'disappear': 2372, 'preet': 6079, 'bharara': 865, 'relationship': 6518, 'programs': 6170, 'accepts': 151, 'invite': 4208, 'antarctica': 421, 'planning': 5914, 'plot': 5943, 'modesty': 5133, 'plenty': 5942, '700': 100, 'toilets': 8088, 'shifting': 7169, 'shove': 7207, 'equating': 2806, 'silliest': 7246, 'eyeballs': 2955, 'manhattan': 4830, 'da': 2048, 'donation': 2505, 'exes': 2889, 'packing': 5635, 'giants': 3416, 'exported': 2932, 'rotten': 6795, 'egg': 2679, 'neil': 5317, 'gorsuch': 3495, 'matter': 4917, 'succumb': 7733, 'fatigue': 3039, 'frat': 3271, 'islam': 4239, 'retweeted': 6670, 'rather': 6387, 'outrage': 5588, 'blackmail': 916, 'hairstyle': 3642, 'arcade': 488, 'every': 2856, 'pundit': 6271, 'dinesh': 2343, 'souza': 7450, 'convicted': 1824, 'distance': 2441, 'nashville': 5279, 'withdrawal': 8773, 'catastrophe': 1329, 'frog': 3296, 'saves': 6911, 'transportation': 8170, 'pepperoni': 5795, 'rectal': 6456, 'maher': 4795, 'capable': 1265, 'ordering': 5547, 'lender': 4606, 'bathrooms': 756, 'revoke': 6694, 'spill': 7503, 'lunch': 4766, 'frightbart': 3293, 'stew': 7626, 'menace': 4989, 'pit': 5895, 'monsters': 5157, 'unending': 8345, 'onslaught': 5512, 'apocalyptic': 447, 'horsemen': 3895, 'lamb': 4497, 'grandfather': 3524, 'compared': 1690, 'cataracts': 1328, 'bangladeshi': 699, 'human': 3933, 'campaigner': 1230, 'farhad': 3024, 'mazhar': 4928, 'disappears': 2376, 'invisibility': 4206, 'commander': 1666, 'resist': 6616, 'base': 736, 'outcome': 5580, 'bass': 748, 'celebrates': 1360, 'expanding': 2901, 'donkeys': 2508, 'hangover': 3673, 'scrap': 6980, 'choose': 1491, 'successor': 7732, 'credit': 1950, 'starbucks': 7580, 'encourages': 2748, 'bipartisan': 899, 'spikes': 7502, 'lays': 4560, 'bare': 721, 'divisions': 2463, 'paperclips': 5679, 'harassments': 3685, 'landrieu': 4506, 'removal': 6548, 'orleans': 5559, 'reenactors': 6473, 'prepares': 6091, 'arrest': 516, 'concocts': 1721, 'broad': 1099, 'deleting': 2197, 'bashing': 744, 'weighs': 8670, 'swapping': 7819, 'readies': 6409, 'booming': 1002, 'feds': 3062, 'audition': 600, 'driver': 2580, 'owner': 5622, 'fed': 3059, 'emergency': 2727, 'westminster': 8688, 'impostor': 4039, 'wendy': 8681, 'vitter': 8531, 'separatist': 7085, 'clone': 1572, 'liberals': 4632, 'impersonations': 4025, 'considers': 1781, 'crosshairs': 1985, 'comb': 1652, 'slammed': 7305, 'cramp': 1929, 'defect': 2163, 'whom': 8717, 'adorable': 224, 'sandberg': 6884, 'showdown': 7210, 'shrink': 7219, 'unions': 8362, 'despot': 2287, 'popcorns': 6007, 'hammocks': 3658, 'sworn': 7841, 'bible': 867, 'abraham': 134, 'lincoln': 4664, 'hat': 3706, 'census': 1373, 'citizenship': 1525, 'trey': 8198, 'gowdy': 3505, 'fisa': 3138, 'embarrassing': 2719, 'adam': 201, 'unmitigated': 8376, 'reproductive': 6590, 'stone': 7645, 'unelectable': 8342, 'mop': 5171, 'deepens': 2155, 'odors': 5469, 'admiral': 215, 'diplomacy': 2351, 'resolving': 6622, 'soup': 7442, 'denmark': 2234, 'mermaid': 5000, 'doused': 2533, 'paint': 5649, 'whaling': 8692, 'mermen': 5001, 'slaps': 7310, 'complete': 1701, 'denuclearization': 2241, 'avoids': 628, 'nationalist': 5284, 'wardrobe': 8596, 'rebukes': 6432, 'khakis': 4409, 'singapore': 7261, 'regional': 6497, 'dialogue': 2317, 'playgroup': 5930, 'zinke': 8886, 'travels': 8180, 'ski': 7291, 'resort': 6624, 'alaskan': 312, 'steakhouse': 7604, 'accusations': 165, 'simple': 7254, 'explanation': 2922, 'undercuts': 8326, 'acted': 186, 'danced': 2065, 'anonymous': 416, 'discovery': 2397, 'ousts': 5577, 'taps': 7893, 'assassin': 542, 'trafficking': 8157, 'tap': 7889, 'fuel': 3312, 'reserves': 6604, 'milkshake': 5049, 'bizarre': 913, 'colleges': 1632, 'operative': 5525, 'looked': 4725, 'caterpillar': 1335, 'rips': 6733, 'claps': 1539, 'blackmails': 918, 'rick': 6709, 'perry': 5808, 'kilts': 4427, 'attractive': 592, 'playgrounds': 5929, 'pause': 5748, 'panic': 5669, 'upend': 8401, 'separating': 7084, 'discourage': 2394, 'shaved': 7151, 'teams': 7920, 'getting': 3410, 'stadiums': 7552, 'warships': 8614, 'deployed': 2254, 'peninsula': 5783, 'saunas': 6907, 'cossack': 1874, 'ensure': 2785, 'safety': 6854, 'obedience': 5449, 'issued': 4250, 'correction': 1864, 'hid': 3802, 'near': 5302, 'bushes': 1173, 'urinated': 8420, 'bungling': 1151, 'screenplay': 6988, 'acts': 197, 'association': 560, 'thinks': 8019, 'guesses': 3596, 'sassy': 6901, 'trolling': 8225, 'girlfriend': 3437, 'seized': 7051, 'troop': 8227, 'sling': 7327, 'phones': 5844, 'tapped': 7891, 'painter': 5650, 'subhuman': 7711, 'worked': 8802, 'hound': 3911, 'wish': 8766, 'hypnotize': 3967, 'airplanes': 302, 'couch': 1883, 'measures': 4949, 'canoe': 1261, 'ty': 8297, 'cobb': 1603, 'retiring': 6662, 'dictatorship': 2326, '1984': 28, 'thieves': 8013, 'elaborate': 2690, 'heist': 3763, 'swiss': 7838, 'blouses': 952, 'window': 8745, 'overwhelmingly': 5618, 'kitchen': 4443, 'purge': 6282, 'actually': 199, 'marshmallows': 4880, 'marrying': 4877, 'bingo': 895, 'cemetery': 1369, 'stocking': 7638, 'attaching': 576, 'ceiling': 1357, 'falwell': 3005, 'stripper': 7684, 'appointed': 471, 'ago': 279, 'investigate': 4195, 'abuses': 143, 'escalate': 2824, 'scuffling': 7000, 'tourism': 8129, 'commission': 1675, 'transparency': 8168, 'happened': 3676, 'explode': 2924, 'triumph': 8219, 'began': 805, 'spitball': 7510, 'oscar': 5563, 'nominated': 5379, 'ceremony': 1385, 'nunberg': 5432, 'summoned': 7755, 'torturer': 8115, 'airlines': 301, 'dragged': 2549, 'pilot': 5878, 'pop': 6005, 'positions': 6031, 'nun': 5431, 'benefits': 836, 'campground': 1233, 'field': 3093, 'vigorously': 8497, 'massage': 4895, 'magicians': 4792, 'along': 349, 'pennsylvania': 5787, 'appears': 461, 'heat': 3750, 'sauce': 6904, 'panicking': 5670, 'gutierrez': 3613, 'someone': 7420, 'kkk': 4449, 'chorus': 1494, 'grows': 3585, 'crumbs': 2000, 'convicts': 1826, 'laughed': 4535, 'disappearances': 2374, 'leftwing': 4592, 'dissent': 2439, 'froome': 3303, 'fourth': 3257, 'hiccups': 3799, 'meehan': 4965, 'bathrobe': 754, 'pi': 5852, 'sentencing': 7081, 'costa': 1876, 'mesa': 5003, 'spying': 7537, 'dui': 2607, 'praising': 6062, 'crawl': 1935, 'chile': 1475, 'creates': 1942, 'acre': 181, 'patagonia': 5732, 'founders': 3255, 'reader': 6407, 'pacifism': 5630, 'backstory': 657, 'hezbollah': 3796, 'hook': 3878, 'chain': 1391, 'tipline': 8071, 'bone': 987, 'buys': 1194, 'picnic': 5859, 'survive': 7798, 'toll': 8092, 'bombs': 983, 'masses': 4898, 'air': 298, '35s': 68, 'upkeep': 8405, 'subsidizing': 7722, 'biting': 912, 'dorm': 2518, 'scandals': 6928, 'dwarf': 2622, 'romancing': 6778, 'sooner': 7431, 'stood': 7648, 'drank': 2555, 'niece': 5353, 'card': 1278, '100k': 4, 'maniac': 4833, 'fish': 3140, 'lessons': 4613, 'sixth': 7283, 'nixon': 5370, 'ethical': 2837, 'norms': 5396, 'suite': 7751, 'jack': 4265, 'bobridge': 967, 'cyclist': 2045, 'selling': 7059, 'drunkard': 2595, 'flipped': 3173, 'legislature': 4603, 'attacked': 578, 'coconut': 1613, 'walk': 8576, 'drawn': 2558, 'sketch': 7290, 'auction': 597, 'incinerator': 4058, 'greenspan': 3551, 'math': 4912, 'individual': 4087, 'temporary': 7947, 'hints': 3824, 'toy': 8143, 'cartographer': 1308, 'panamanian': 5661, 'dictator': 2324, 'manuel': 4844, 'noriega': 5394, '83': 108, 'dating': 2089, 'gag': 3349, 'sound': 7439, 'immigrating': 4012, 'wild': 8736, 'reminiscent': 6545, 'xylophone': 8848, 'consistent': 1782, 'attractiveness': 593, 'catholic': 1338, 'priest': 6123, '13': 12, 'motel': 5188, 'paying': 5752, 'ouster': 5576, 'pseudo': 6234, 'embraces': 2725, 'pivot': 5900, 'proverbial': 6224, 'drunks': 2597, 'streetlight': 7675, 'puddles': 6252, 'kushners': 4481, 'saudis': 6906, 'blackstone': 919, 'recent': 6436, 'zoo': 8894, 'pack': 5632, 'spot': 7524, 'orders': 5548, 'boomerang': 1001, '90': 115, 'erasure': 2813, 'jefferson': 4296, 'zombie': 8890, 'happens': 3678, 'orange': 5541, 'amusing': 377, 'bosnia': 1016, 'ratko': 6392, 'mladic': 5113, 'genocide': 3395, 'indigestion': 4086, 'modernize': 5131, 'dismantle': 2417, 'laser': 4524, 'dwarfs': 2623, 'gdp': 3384, 'statues': 7598, 'birds': 902, 'foreigners': 3231, 'locked': 4714, 'modeling': 5126, 'battles': 763, 'umbrella': 8309, 'iphone': 4219, 'revives': 6692, 'floats': 3178, 'debts': 2126, 'ridiculous': 6717, 'cavalry': 1348, 'embarrass': 2718, 'forge': 3236, '34': 66, 'punished': 6274, 'graft': 3517, 'unprecedented': 8380, 'unique': 8363, 'complaints': 1700, 'virginity': 8518, 'idiocy': 3983, 'vox': 8556, 'sitter': 7279, 'intoxication': 4186, '24': 56, 'direction': 2361, 'postmen': 6038, 'reception': 6438, 'seduced': 7037, 'supremacist': 7778, 'activity': 193, 'campuses': 1237, 'cookie': 1832, 'lips': 4679, 'stooge': 7649, 'netroots': 5327, 'liberal': 4630, 'demand': 2214, 'throttle': 8036, 'pamper': 5660, 'conclude': 1718, 'stud': 7696, 'sarcasm': 6897, 'chibok': 1462, 'reunited': 6672, 'salamis': 6860, 'raisins': 6362, 'gibberish': 3417, 'residency': 6609, 'hairdos': 3637, 'deadliest': 2107, 'districts': 2450, 'radiologist': 6345, 'bullets': 1138, 'geometry': 3398, 'sergei': 7091, 'skripal': 7300, 'movie': 5206, 'wedding': 8660, 'northern': 5398, 'mclaughlin': 4939, 'saville': 6912, 'wannacry': 8589, 'hack': 3623, 'nhs': 5347, 'releases': 6525, 'planed': 5910, 'lowers': 4757, 'parenthood': 5696, 'hbcus': 3727, 'deportees': 2260, 'shelter': 7160, 'agonizing': 280, 'spelunking': 7487, 'mafia': 4789, 'miami': 5018, 'ground': 3577, 'unconstitutional': 8321, 'deli': 2199, 'denied': 2231, 'influx': 4105, 'militants': 5045, 'cockroaches': 1609, 'counting': 1895, 'tuxedos': 8280, 'sees': 7048, 'skunk': 7301, 'marry': 4876, 'roof': 6784, 'revealed': 6676, 'desecrated': 2274, 'kindergarten': 4431, 'submits': 7714, 'panels': 5668, 'confirmation': 1743, 'stream': 7670, 'applauded': 465, 'guantanamo': 3588, 'prisoners': 6136, 'beach': 768, 'sacrificial': 6847, 'politico': 5980, 'stands': 7578, 'battery': 760, 'scold': 6964, 'donor': 2509, 'sperm': 7492, 'sewers': 7118, 'mulligan': 5221, 'dow': 2536, 'fell': 3069, 'dishonesty': 2411, 'supports': 7775, 'note': 5406, 'burns': 1163, 'map': 4850, 'imp': 4017, 'grapes': 3533, 'overturns': 5617, 'regulation': 6502, 'mining': 5068, 'debris': 2124, 'cracker': 1925, 'hashtag': 3703, 'understand': 8333, 'dummies': 2610, 'criminals': 1965, 'bidet': 872, 'californians': 1215, 'extra': 2946, 'cross': 1983, 'subsidies': 7721, 'well': 8678, 'wives': 8783, 'blackmailed': 917, 'kept': 4401, 'informed': 4111, 'gnome': 3459, 'irresistible': 4235, 'named': 5270, 'perez': 5797, 'darts': 2080, 'escrow': 2829, 'gerrymandering': 3406, 'rig': 6720, 'squirrels': 7542, 'runner': 6825, 'roasts': 6751, 'apologists': 449, 'islamists': 4242, 'skateboarders': 7286, 'halls': 3649, 'landmarks': 4505, 'pleaded': 5935, 'identities': 3980, 'account': 160, 'numbers': 5430, 'humor': 3939, 'fda': 3050, 'reverse': 6683, 'stunning': 7706, 'details': 2297, 'brazen': 1058, 'heists': 3764, 'proof': 6187, 'improvement': 4044, 'beards': 776, 'fritters': 3295, 'domestic': 2498, 'retires': 6661, 'ditches': 2454, 'portugal': 6025, 'alaska': 311, 'baited': 672, 'canceling': 1247, 'dumpling': 2613, 'storms': 7658, '78': 105, 'moisten': 5135, 'dippin': 2356, 'dots': 2523, 'responded': 6628, 'listened': 4685, 'surprise': 7790, 'fueled': 3313, 'nationalism': 5283, 'noise': 5378, 'dodge': 2480, 'uses': 8428, 'anticapitalist': 427, 'sermon': 7096, 'pickup': 5858, 'trucks': 8236, 'miniature': 5065, 'explosive': 2931, 'wolff': 8788, 'held': 3766, 'captive': 1271, 'sexually': 7123, 'assaulted': 547, 'horrors': 3893, 'mannequin': 4838, 'deutsche': 2305, 'zip': 8887, 'code': 1614, 'villain': 8502, 'contradicts': 1812, 'whose': 8720, 'freezer': 3281, 'ruled': 6817, 'accidental': 154, 'discovers': 2396, 'puppies': 6279, 'rewards': 6700, 'grammar': 3519, 'dreams': 2566, 'pokes': 5969, 'prods': 6156, 'posterior': 6037, 'dreamer': 2564, 'sandals': 6883, '106': 9, 'passengers': 5720, 'stranded': 7665, 'pretzels': 6115, 'macedonians': 4778, 'clothes': 1584, 'toddler': 8083, 'hazing': 3725, 'unauthorized': 8316, 'dismisses': 2422, 'polling': 5983, 'peanut': 5762, 'champagne': 1401, 'welcome': 8676, 'burqas': 1165, 'together': 8086, 'copulate': 1847, '21st': 50, 'forays': 3220, 'vegan': 8457, 'turkeys': 8266, 'otters': 5571, 'duet': 2605, 'honoring': 3875, 'navajos': 5292, 'pocohontas': 5957, 'jab': 4262, 'taking': 7872, 'betting': 860, 'hobby': 3845, 'continues': 1807, 'churn': 1507, 'extremely': 2948, 'flooding': 3182, 'unfolding': 8349, 'provision': 6230, 'hardest': 3689, 'guess': 3595, 'knows': 4461, 'loved': 4751, 'sacks': 6843, 'ministers': 5071, 'defying': 2185, 'defenestrates': 2169, 'seduce': 7036, 'colonoscopy': 1644, 'anal': 379, 'reaction': 6402, 'weakness': 8647, 'beers': 799, 'stalwart': 7570, 'hemline': 3776, 'berating': 840, 'dramatic': 2554, 'nuke': 5426, 'giddy': 3418, 'royal': 6807, 'meghan': 4972, 'detail': 2296, 'elbow': 2691, 'sinus': 7270, 'forty': 3247, 'catalogued': 1326, 'elite': 2710, 'nh': 5346, 'prep': 6088, 'kerry': 4402, 'consults': 1793, 'ponders': 5994, 'dandruff': 2070, 'shark': 7148, 'creditloan': 1951, 'survey': 7796, 'height': 3760, 'revised': 6688, 'introduce': 4187, 'birthdays': 905, 'provide': 6226, 'delegates': 2194, 'volunteers': 8542, 'draft': 2546, 'deflates': 2181, 'hoax': 3844, 'ten': 7949, 'commandments': 1667, 'razorback': 6396, 'noaa': 5373, 'offensively': 5476, 'brake': 1051, 'marriott': 4875, 'books': 998, 'enlightenment': 2778, 'casts': 1321, 'zarrab': 8878, 'undermine': 8329, 'breakfast': 1065, 'cheapskate': 1437, 'hen': 3778, 'architect': 489, 'expresses': 2938, 'sliver': 7333, 'racetrack': 6334, 'foundation': 3253, 'overdose': 5600, 'accusing': 170, 'charity': 1423, 'palm': 5659, 'club': 1590, 'earthling': 2642, 'restore': 6637, 'voting': 8552, 'felons': 3071, 'salon': 6871, 'canadians': 1241, 'loonies': 4730, 'shouting': 7205, 'match': 4905, 'erupts': 2823, 'appetizer': 463, 'protecting': 6210, 'inmates': 4127, 'slumps': 7348, 'traders': 8152, 'supply': 7770, 'manson': 4842, '84': 109, 'repents': 6573, 'truths': 8251, 'acknowledge': 175, 'octogenarians': 5465, 'allen': 334, 'aroused': 514, 'emasculate': 2717, 'wan': 8587, 'troway': 8232, 'poo': 5998, 'snl': 7386, 'roast': 6749, 'hopscotch': 3888, 'navalny': 5294, 'heavily': 3754, 'elect': 2693, 'searchers': 7015, 'puddle': 6251, 'venture': 8469, 'chump': 1504, 'polyester': 5989, 'filibuster': 3107, 'moderate': 5128, 'rouhani': 6797, 'count': 1889, 'preliminary': 6085, 'results': 6645, 'pageant': 5641, 'wrap': 8825, 'chip': 1482, 'existence': 2894, 'doorstep': 2517, 'omg': 5503, 'reveals': 6678, 'pregnant': 6084, 'pretends': 6112, 'mypillow': 5255, 'strong': 7688, 'boycott': 1043, 'ingraham': 4118, 'angle': 394, 'naps': 5275, 'slip': 7329, 'grind': 3566, 'waking': 8575, 'cow': 1915, 'broadcaster': 1100, 'obnoxiously': 5453, 'revenge': 6681, 'yazidi': 8852, 'freeing': 3279, 'raqqa': 6381, 'housework': 3917, 'humanitarian': 3934, 'blown': 955, 'agendas': 272, 'novel': 5412, 'ayatollah': 639, 'khamenei': 4410, 'hitler': 3840, 'hemorrhoids': 3777, 'innovations': 4130, 'dominance': 2499, 'meryl': 5002, 'streep': 7673, 'whined': 8703, 'tiffany': 8056, 'lived': 4694, 'favorite': 3044, 'puppet': 6277, 'kingdom': 4436, 'posen': 6027, 'austria': 606, 'fascistic': 3030, 'umbrellas': 8310, 'shocked': 7181, 'routine': 6804, 'cleanser': 1554, 'savior': 6913, 'peta': 5824, 'billboard': 885, 'mouse': 5199, 'airstrike': 304, 'orangutans': 5543, 'liberty': 4633, 'alumni': 357, 'diplomas': 2352, 'molehill': 5138, 'pilgrim': 5872, 'deficits': 2176, 'struggles': 7694, 'spin': 7504, 'downplays': 2541, 'hawk': 3720, 'hispanics': 3834, 'sucker': 7736, 'punches': 6268, 'subway': 7726, 'giraffe': 3434, 'vx': 8561, 'nerve': 5321, 'nam': 5268, 'rare': 6382, 'infighting': 4097, 'grabbers': 3509, 'lubbers': 4762, 'stabs': 7550, 'boos': 1004, 'subpoenaed': 7716, 'piano': 5853, 'emma': 2729, 'gonzalez': 3485, 'survived': 7799, 'jacksonville': 4269, 'jaguars': 4271, 'shad': 7128, 'khan': 4411, 'jealous': 4294, 'trekkie': 8193, 'midwest': 5036, 'bull': 1136, 'flea': 3161, 'staring': 7582, 'toucan': 8120, 'catalans': 1325, 'declare': 2138, 'declaration': 2137, 'catches': 1332, 'amusement': 376, 'ride': 6713, 'pelican': 5772, 'disco': 2392, 'photos': 5847, 'environmental': 2796, 'terrified': 7970, 'motives': 5193, 'romance': 6776, 'celebrate': 1359, 'valentine': 8442, 'records': 6450, 'graded': 3511, 'dines': 2342, 'rice': 6706, 'convinced': 1827, 'popularity': 6012, 'theft': 7998, 'swath': 7822, 'county': 1899, 'representation': 6586, 'less': 4612, 'squirrel': 7541, 'representatives': 6587, 'supporter': 7772, 'sexuality': 7122, 'penny': 5788, 'perpetual': 5807, 'prompts': 6186, 'hunger': 3946, 'involve': 4212, 'fiction': 3090, 'spokesperson': 7520, 'grandma': 3525, 'distaste': 2443, 'suing': 7748, 'construction': 1790, 'beaner': 772, 'advertising': 234, 'principles': 6131, 'overseas': 5605, 'parks': 5702, 'lied': 4643, 'sanitation': 6891, 'today': 8082, 'grills': 3564, 'roosters': 6788, 'hairpiece': 3640, 'homeland': 3863, 'sudanese': 7739, 'giggle': 3424, 'salad': 6857, 'sleep': 7318, 'foot': 3213, 'evangelists': 2847, 'twisted': 8292, 'treachery': 8181, 'innocents': 4128, 'sandwich': 6886, 'captures': 1274, 'sandy': 6888, 'declassified': 2141, 'susan': 7804, 'contemplated': 1801, 'hiding': 3804, 'incoming': 4064, 'demolish': 2223, 'villages': 8501, 'pizzeria': 5905, '42': 78, 'completely': 1702, 'character': 1419, 'braces': 1046, 'prances': 6064, 'inside': 4137, 'trumpist': 8245, 'trumped': 8241, 'triumphs': 8220, 'exempts': 2887, 'grandparents': 3529, 'relatives': 6521, 'gifting': 3420, 'lines': 4669, 'databases': 2085, 'playing': 5931, 'guitar': 3604, 'massages': 4896, 'rails': 6353, 'shivers': 7179, 'recognizing': 6446, 'saved': 6910, 'location': 4711, 'trucker': 8235, 'damaged': 2058, 'peru': 5820, 'renowned': 6558, 'nazca': 5298, 'jockstraps': 4323, 'academic': 145, 'journals': 4342, 'graffiti': 3516, 'attempting': 583, 'muzzle': 5250, 'molest': 5139, 'julius': 4358, 'caesar': 1204, 'theater': 7997, 'timed': 8064, 'steak': 7603, 'whip': 8707, 'scalise': 6924, 'gunman': 3609, 'baseball': 737, 'practice': 6057, 'usa': 8422, 'removes': 6551, 'petition': 5828, 'tool': 8102, 'bali': 679, 'volcano': 8538, 'tremors': 8195, 'intensify': 4160, 'economists': 2662, 'vampires': 8446, 'smelly': 7359, 'limited': 4660, 'hockey': 3848, 'quest': 6309, 'astronauts': 565, 'alligators': 337, 'hug': 3928, 'frame': 3261, 'malley': 4817, 'aware': 633, 'elves': 2713, 'delingpole': 2203, 'environmentalists': 2797, 'burrito': 1166, 'jill': 4315, 'stein': 7612, 'culpability': 2013, 'primps': 6126, 'cosmonaut': 1873, 'drained': 2552, 'incumbents': 4072, 'ogres': 5489, 'reserve': 6603, 'cattle': 1340, 'breathing': 1072, 'scribble': 6991, 'appeals': 458, 'moustache': 5200, 'salary': 6862, 'overtime': 5613, 'hours': 3913, 'eclair': 2656, 'infowars': 4114, 'beat': 779, 'goddamn': 3468, 'wipe': 8758, 'services': 7102, 'arming': 509, 'equine': 2809, 'suspends': 7811, '103': 7, 'personnel': 5818, 'turk': 8264, 'gobbles': 3466, 'unsuccessful': 8388, 'equality': 2804, 'vulnerable': 8559, 'heidi': 3759, 'heitkamp': 3765, 'tougher': 8125, 'kevin': 4405, 'cramer': 1928, 'sorcerer': 7433, 'bugles': 1131, 'ben': 829, 'hud': 3924, 'lavish': 4548, 'waxing': 8639, 'requirements': 6597, 'starts': 7588, 'requesting': 6595, 'bids': 873, 'sticks': 7630, 'interviews': 4181, 'cyber': 2039, 'kaspersky': 4382, 'lab': 4484, 'recipe': 6440, 'evolving': 2863, 'towards': 8137, 'rap': 6374, 'asserts': 551, 'possibility': 6034, 'privilege': 6141, 'whoops': 8718, 'texts': 7987, 'agents': 274, 'peter': 5826, 'strzok': 7695, 'lisa': 4682, 'discards': 2384, 'stereo': 7620, 'naked': 5266, 'landfills': 4502, 'yearning': 8854, 'poland': 5970, 'asthma': 562, 'selfie': 7056, 'removed': 6550, 'hairdresser': 3638, 'claw': 1550, 'restroom': 6640, 'lot': 4745, 'contact': 1796, 'kissing': 4442, 'meats': 4952, 'mick': 5024, 'changing': 1411, 'bureau': 1154, 'rejection': 6515, 'uninsured': 8359, 'imprison': 4040, 'reenacted': 6472, 'taylor': 7913, 'swift': 7833, 'denver': 2242, 'dj': 2468, 'chihuahua': 1471, 'slovak': 7340, 'assassination': 544, 'typewriter': 8298, 'hires': 3831, 'clashes': 1543, 'fascist': 3029, 'hams': 3660, 'tennessee': 7952, 'senior': 7073, 'posing': 6029, 'graduation': 3515, 'waistband': 8569, 'pickle': 5855, 'manager': 4823, 'romanians': 6780, 'demonstrate': 2224, 'streets': 7676, 'provided': 6227, 'corrupt': 1868, 'doughnuts': 2530, 'robot': 6756, 'grandpas': 3530, 'glencore': 3449, 'cutting': 2038, 'oligarch': 5497, 'deripaska': 2268, 'commentary': 1671, 'richard': 6708, 'shelby': 7157, 'brain': 1048, 'terminate': 7964, 'seoul': 7082, 'humans': 3936, 'capabilities': 1264, 'gorillas': 3494, 'conditions': 1728, 'apnewsbreak': 445, 'challenged': 1398, 'gerbil': 3402, 'brexiteers': 1078, 'achievements': 173, 'governments': 3502, 'fuels': 3315, 'privacy': 6138, 'censoring': 1370, 'withholding': 8778, 'hospitalized': 3900, 'kicks': 4414, 'rage': 6348, 'referencing': 6475, 'solves': 7416, 'floridians': 3188, 'irma': 4230, 'taxing': 7909, 'dolphins': 2497, 'claudia': 1549, 'tenney': 7953, 'murderers': 5232, 'marketers': 4871, 'empty': 2742, '2005': 34, 'rachel': 6335, 'maddow': 4784, 'barbeque': 715, 'instructed': 4148, 'recusal': 6457, 'unicorn': 8354, 'critics': 1977, '64': 94, 'died': 2329, 'jan': 4280, 'shipwreck': 7176, 'dinghy': 2344, 'mediterranean': 4964, 'parrots': 5705, 'goulash': 3497, 'yak': 8849, 'dab': 2049, 'devastating': 2307, 'realism': 6416, 'backfire': 650, 'bigly': 879, 'penis': 5784, 'vicky': 8486, 'hartzler': 3697, 'claire': 1534, 'mccaskill': 4934, 'slap': 7308, 'huckleberry': 3923, 'finn': 3127, 'mockingbird': 5122, 'matryoshka': 4915, 'plumbing': 5950, 'mullen': 5220, 'enjoying': 2776, 'disneyland': 2425, 'slowdown': 7342, 'visitors': 8527, 'predicted': 6077, 'parakeets': 5686, 'jacinda': 4264, 'ardern': 492, 'winston': 8756, 'peters': 5827, 'shred': 7217, 'implement': 4027, 'denounces': 2237, 'misunderstands': 5108, 'psychiatrist': 6235, 'shock': 7180, 'greek': 3547, 'yoghurt': 8865, 'registered': 6498, 'flashing': 3156, 'marshmallow': 4879, 'ballot': 688, 'box': 1040, 'lawful': 4551, 'shake': 7134, 'conceivable': 1713, 'sidewalk': 7232, 'weaken': 8645, 'efficiency': 2676, 'diplomatic': 2354, 'regrettable': 6499, 'uncalled': 8319, 'pilgrimage': 5873, 'arbaeen': 487, 'spite': 7511, 'drunk': 2594, 'soothsayer': 7432, 'wayne': 8641, 'lapierre': 4516, 'advocates': 242, 'pizzas': 5904, 'hiphop': 3826, 'tennis': 7954, 'mastiffs': 4904, 'tabloid': 7858, 'planes': 5911, 'belgian': 820, 'bataclan': 750, 'gypsies': 3621, 'misled': 5092, 'skin': 7295, 'spam': 7458, 'prosecute': 6199, 'draws': 2559, 'wide': 8724, 'argentine': 496, 'spitting': 7513, 'mammal': 4819, 'decorations': 2148, 'distracted': 2445, 'hernia': 3783, 'kudlow': 4474, 'trashcans': 8176, 'eyesore': 2964, 'barbara': 713, 'matriarch': 4913, 'dynasty': 2629, 'moonwalks': 5168, 'affairs': 248, 'distillery': 2444, 'sara': 6895, 'seating': 7022, 'robin': 6755, 'louisiana': 4749, 'hare': 3691, 'pancakes': 5663, 'mustache': 5247, 'collude': 1637, 'appearance': 460, 'hoedown': 3849, 'covered': 1913, 'warts': 8616, 'rumor': 6822, 'orrin': 5561, 'hatch': 3707, 'boneheads': 989, 'closing': 1581, 'cheesecake': 1451, 'underarms': 8325, 'bromance': 1108, 'physicist': 5851, 'hawking': 3721, '76': 102, 'mulls': 5223, 'favor': 3042, 'hairbrush': 3633, 'imposes': 4036, 'winners': 8752, 'tipped': 8072, 'staggering': 7559, 'gerbils': 3403, 'shocking': 7182, 'tan': 7881, 'rationale': 6391, 'publish': 6246, 'lame': 4498, 'chaplain': 1418, 'scalding': 6920, 'failings': 2983, 'enjoys': 2777, 'apparent': 455, 'engage': 2767, 'each': 2632, 'militarily': 5046, 'appreciate': 474, 'rages': 6349, 'unabated': 8312, 'spencer': 7488, 'tank': 7883, 'nonprofit': 5388, 'credential': 1946, 'catering': 1334, 'nudge': 5422, 'socks': 7410, 'melts': 4977, 'beheaded': 815, 'burned': 1161, 'alive': 329, 'flood': 3181, 'bangladesh': 698, 'corncobs': 1856, 'sack': 6842, 'mortars': 5179, 'syndrome': 7850, 'shack': 7127, 'marc': 4855, 'andreessen': 387, 'eliminated': 2709, 'universe': 8368, 'snubbed': 7396, 'advances': 232, 'corn': 1855, 'unfettered': 8347, 'goldman': 3478, 'sachs': 6841, 'bedtime': 795, 'discharged': 2385, 'cliff': 1563, 'peacekeeping': 5759, 'warlords': 8597, 'lions': 4677, 'bracing': 1047, 'exposing': 2936, 'surviving': 7801, 'bahrain': 669, 'executes': 2882, 'shia': 7167, 'sentences': 7080, '2010': 38, 'sewer': 7117, 'declassifies': 2142, 'sausage': 6908, 'nike': 5365, 'stays': 7602, 'taxman': 7910, 'shimmies': 7171, 'promenade': 6177, 'curling': 2025, 'realdonaldtrump': 6415, 'besides': 848, 'turnip': 8271, 'soros': 7435, 'compiles': 1698, 'wikipedia': 8734, 'edit': 2668, 'tampon': 7880, 'discriminating': 2399, 'gifts': 3421, 'exchanged': 2875, 'pontiff': 5996, 'appeasing': 462, 'gods': 3469, 'minute': 5078, 'messes': 5007, 'liked': 4654, 'lyft': 4771, 'rideshare': 6714, 'latrine': 4532, 'dirty': 2368, 'lift': 4647, 'weights': 8673, 'allegation': 331, 'serenade': 7088, 'hicks': 3801, 'greenland': 3549, 'wildfire': 8737, 'deserves': 2280, 'fudges': 3311, 'promote': 6182, 'skeletons': 7288, 'waiter': 8571, 'smashes': 7355, 'trumps': 8246, 'tweeting': 8284, 'huskies': 3959, 'prisons': 6137, 'personalities': 5816, 'meetings': 4968, 'hogg': 3851, 'laura': 4545, 'career': 1284, 'treat': 8186, 'budapest': 1124, 'treated': 8187, 'communist': 1686, 'seagull': 7007, 'experience': 2914, 'jay': 4291, 'sekulow': 7053, 'pardons': 5695, 'whiny': 8706, 'adulting': 229, 'flirting': 3176, 'stupefying': 7707, 'wigs': 8732, 'devours': 2314, 'armenia': 507, 'contemplates': 1802, 'nonviolent': 5389, 'revolution': 6696, 'cusp': 2033, 'waving': 8638, 'bean': 771, 'buttock': 1186, 'tearing': 7922, 'replaced': 6575, 'driveway': 2582, 'capture': 1272, 'flopped': 3185, 'damaging': 2059, 'beetles': 801, 'marries': 4874, 'keeper': 4388, 'excellent': 2873, 'goal': 3461, 'pallbearer': 5658, 'neutral': 5330, 'judgment': 4351, 'gear': 3385, 'verdict': 8472, 'birdlime': 901, 'retire': 6657, 'roulette': 6798, 'climb': 1565, 'referendum': 6476, 'agriculture': 286, 'produced': 6158, 'tons': 8097, 'throughout': 8038, 'bagels': 667, 'decries': 2152, 'fomenting': 3208, 'spiders': 7498, 'jump': 4360, 'inflation': 4100, 'beans': 773, 'reaches': 6400, 'punish': 6273, 'blizzard': 940, 'onpolitics': 5511, 'sherbet': 7164, 'crying': 2005, 'superheroes': 7764, 'vast': 8454, 'amounts': 372, 'byproduct': 1197, 'worldwide': 8809, 'wears': 8654, 'resume': 6646, 'northward': 5399, 'starved': 7591, 'areas': 494, 'skyscraper': 7303, 'mattress': 4919, 'sniffing': 7383, 'weaker': 8646, 'eye': 2952, 'beavers': 786, 'send': 7069, 'interests': 4165, 'towels': 8139, 'recipients': 6442, 'snore': 7389, 'steroids': 7624, 'fetishism': 3086, 'phoenix': 5840, 'attracts': 594, 'moved': 5203, 'guatemalan': 3593, 'boxing': 1041, 'congratulates': 1760, 'diversify': 2455, 'processes': 6153, 'imf': 4007, 'outlook': 5585, 'cites': 1519, 'legalization': 4597, 'cancel': 1245, 'berkeley': 841, 'riots': 6731, 'bologna': 974, 'eclipse': 2657, 'viewing': 8496, 'magnifying': 4794, 'stockholm': 7637, 'hedgehog': 3756, 'pitbull': 5896, 'colors': 1647, 'undergarments': 8327, 'squirt': 7543, 'antelope': 422, 'kathy': 4383, 'griffin': 3560, 'metaphor': 5011, 'simile': 7252, 'exchanges': 2876, 'rallies': 6363, 'ryans': 6837, 'dawdles': 2097, 'tolerance': 8090, 'barriers': 732, 'partisan': 5711, 'disrupted': 2437, 'shakespeare': 7136, 'hostage': 3902, 'tags': 7863, 'greenwood': 3552, 'disrobe': 2435, 'rampage': 6366, 'suspicion': 7812, 'intercept': 4161, 'radiation': 6342, 'aardvark': 122, 'govern': 3499, 'shovels': 7208, 'encourage': 2747, 'caviar': 1351, 'exposes': 2935, 'splits': 7516, 'limousine': 4663, 'flexibility': 3168, 'groening': 3571, 'simpsons': 7256, 'apu': 482, 'pretend': 6109, 'grimace': 3565, 'meadows': 4942, 'bold': 973, 'buttocks': 1187, 'dentist': 2239, 'rigged': 6721, 'ramadan': 6365, 'jihadist': 4314, 'hoedowns': 3850, 'signals': 7238, 'further': 3338, 'restrict': 6638, 'investments': 4204, 'curry': 2029, 'disinvites': 2415, 'golden': 3476, 'warriors': 8611, 'donuts': 2512, 'gunmen': 3610, 'shiite': 7170, 'wound': 8822, 'brennan': 1075, 'harder': 3688, 'happening': 3677, 'defiant': 2174, 'crepe': 1954, 'core': 1851, 'pac': 5628, 'pioneer': 5887, 'masaya': 4887, 'nakamura': 5265, '91': 118, 'husband': 3957, 'challenges': 1399, 'meddled': 4955, 'adds': 209, '227': 52, 'rate': 6384, 'fabricates': 2965, 'gulf': 3605, 'minorities': 5074, 'mega': 4970, 'colonies': 1643, 'discovered': 2395, 'canadian': 1240, 'enjoy': 2775, 'violently': 8512, 'expectations': 2905, 'civic': 1527, 'engagement': 2769, 'imagine': 4005, 'cannon': 1260, 'waging': 8568, 'wary': 8617, 'minerals': 5064, 'elephants': 2705, 'yurt': 8875, 'wanda': 8588, 'sykes': 7844, 'diss': 2438, 'intimidation': 4183, 'targeted': 7896, 'misinform': 5091, 'confuse': 1753, 'quarterback': 6306, 'fishy': 3143, 'float': 3177, 'compares': 1691, 'cave': 1349, 'dwellers': 2624, 'courtesan': 1907, 'jails': 4274, 'tourists': 8131, 'istanbul': 4252, 'cakes': 1210, 'psychic': 6237, 'slowly': 7344, 'speeches': 7480, 'otter': 5570, 'coach': 1598, 'expressions': 2939, 'writing': 8839, 'publishers': 6248, 'eager': 2633, 'fishing': 3142, 'dubai': 2598, 'grass': 3535, 'wolves': 8789, 'stomping': 7644, 'investigated': 4196, 'mirror': 5082, 'trades': 8153, 'redistricting': 6463, 'fatty': 3040, 'chauvinists': 1435, 'triggered': 8211, 'watermelon': 8633, 'virgin': 8516, 'misunderstood': 5109, 'casserole': 1318, 'nears': 5305, 'broccoli': 1105, 'through': 8037, 'suburbs': 7725, 'cyborg': 2043, 'binge': 894, 'anyone': 435, 'tense': 7956, 'guantรกnamo': 3589, 'expansion': 2902, 'denham': 2229, 'hears': 3746, 'constituents': 1787, 'rubbed': 6812, 'important': 4032, 'collins': 1635, 'disgusting': 2409, 'barrettes': 730, 'wiggle': 8731, 'corset': 1870, 'poisoned': 5964, 'ivy': 4261, 'françois': 3270, 'hollande': 3858, 'eggs': 2681, 'charlatans': 1424, 'jarred': 4288, 'msnbc': 5210, 'disappointed': 2377, 'bishops': 908, 'whistle': 8710, 'pushing': 6289, 'circumcision': 1515, 'mandatory': 4828, 'misandrist': 5085, 'aclu': 178, 'jane': 4281, 'doe': 2483, 'shaving': 7152, 'moose': 5170, 'hogwash': 3852, 'cartographers': 1309, 'barbers': 717, 'holders': 3854, 'audio': 599, 'seafood': 7005, 'pink': 5886, 'hoping': 3887, 'powerhouse': 6055, 'rainbow': 6355, 'pullout': 6261, 'attempts': 584, 'emerge': 2726, 'criminalize': 1963, 'investigators': 4202, 'guide': 3600, 'sandwiches': 6887, 'accord': 157, 'boyfriend': 1044, 'parades': 5683, 'beet': 800, 'supermodel': 7767, 'recognizes': 6445, 'pride': 6121, 'lgbti': 4625, 'persons': 5819, 'brewery': 1076, 'blindsided': 938, 'throwing': 8041, 'rednecks': 6465, 'rounds': 6801, 'beggars': 806, 'masseuses': 4899, 'hoboken': 3847, 'elects': 2702, 'sikh': 7241, 'jersey': 4304, 'weasel': 8655, 'lipstick': 4680, 'adolf': 223, 'mile': 5042, 'abandoned': 123, 'transformed': 8166, 'getaway': 3408, 'boardwalk': 962, 'fun': 3324, 'league': 4569, 'twin': 8290, 'phase': 5835, 'tripadvisor': 8216, 'criticized': 1974, 'performance': 5800, 'sheldon': 7158, 'adelson': 210, 'newspaper': 5341, 'breakdance': 1063, 'butterflies': 1185, 'snubbing': 7397, 'eclipsing': 2658, 'concludes': 1719, 'interfered': 4167, 'conclusion': 1720, 'rutabagas': 6834, 'guilt': 3602, 'redecorating': 6462, 'begged': 807, 'challah': 1396, 'bifocals': 874, 'warship': 8613, 'boat': 964, 'speeding': 7482, 'uss': 8431, 'tempest': 7944, 'persian': 5811, 'relying': 6533, 'poker': 5968, 'brutal': 1120, 'september': 7086, 'mosquitoes': 5183, 'hacks': 3627, 'dismissed': 2421, 'crayon': 1936, 'diesel': 2331, 'accounts': 164, 'troll': 8222, 'spacex': 7455, 'falcon': 2996, 'vital': 8529, 'adamant': 202, 'osama': 5562, 'remain': 6534, 'tango': 7882, 'sneak': 7377, 'rental': 6560, 'heroin': 3786, 'trunk': 8247, 'rickshaw': 6710, 'rescinding': 6600, 'directing': 2360, 'cocaine': 1606, 'ballerinas': 682, 'souls': 7438, 'goats': 3465, 'dennis': 2235, 'hastert': 3705, 'levitate': 4622, 'libel': 4629, 'vogue': 8536, 'investing': 4203, 'nagorno': 5262, 'karabakh': 4379, 'detectives': 2300, 'unlock': 8374, 'phone': 5841, 'backpage': 655, 'liable': 4627, 'buffalo': 1127, 'westworld': 8689, 'millionaires': 5054, 'utility': 8433, 'raising': 6361, 'donors': 2510, 'costly': 1877, 'flushing': 3195, 'sinkhole': 7267, 'appropriate': 476, 'mint': 5077, 'trust': 8248, 'coin': 1620, 'implosion': 4029, 'basketball': 747, 'repugnant': 6593, 'credibility': 1948, 'dealt': 2116, 'blunt': 959, 'salesman': 6865, 'demoralized': 2226, 'stokes': 7641, 'capacity': 1266, 'rollback': 6773, 'decor': 2147, 'assistance': 557, 'boon': 1003, 'survivors': 7803, 'violin': 8513, 'retreats': 6664, 'tantrums': 7888, 'secure': 7034, 'cite': 1517, 'irreconcilable': 4233, 'differences': 2334, 'hairstyles': 3643, 'attire': 588, 'chicken': 1466, 'louis': 4747, 'farrakhan': 3028, 'loitering': 4717, 'pastry': 5731, 'accuser': 167, 'insider': 4138, 'congresswoman': 1766, 'tables': 7857, 'glitter': 3452, 'combs': 1655, 'welcomes': 8677, 'ventures': 8470, 'disasters': 2380, 'slimmed': 7325, 'screams': 6986, 'hookah': 3879, 'goodwin': 3488, 'proves': 6225, 'royce': 6809, 'reelection': 6470, 'creating': 1943, 'merkley': 4999, 'shorts': 7199, 'favorability': 3043, 'basement': 740, 'coyote': 1919, 'labs': 4490, 'snorting': 7392, 'reflex': 6481, 'zucker': 8898, 'divorce': 2465, 'outhouse': 5583, 'collides': 1633, 'opioid': 5528, 'epidemic': 2802, 'justices': 4368, 'appeal': 457, 'emblem': 2721, 'fluorescent': 3193, '1928': 26, 'steer': 7611, 'myth': 5259, 'cheap': 1436, 'stall': 7568, 'pitch': 5897, 'hijinks': 3811, 'fiesta': 3095, 'kuaishou': 4473, 'tencent': 7950, 'round': 6799, 'ipo': 4220, 'breached': 1060, 'teenager': 7932, 'gropes': 3575, 'obesity': 5450, 'extends': 2943, 'reuters': 6673, 'exercise': 2888, 'slaw': 7316, 'jingle': 4318, 'noon': 5392, 'platypus': 5922, 'larry': 4521, 'flynt': 3199, 'suitable': 7750, 'modi': 5134, '2019': 44, 'spice': 7495, 'austin': 603, 'chimpanzee': 1476, 'abrupt': 136, 'golfers': 3482, 'conor': 1770, 'cheltenham': 1455, 'coventry': 1910, 'midfielder': 5030, 'flog': 3180, 'knees': 4452, 'undo': 8339, 'patient': 5738, 'lobbying': 4705, 'frenzy': 3283, 'dolphin': 2496, 'kissed': 4440, 'frequently': 3284, 'reached': 6399, 'eagle': 2634, 'toss': 8117, 'suburb': 7724, 'stare': 7581, 'chic': 1463, 'nutella': 5438, 'brawls': 1056, 'supermarket': 7766, 'aisles': 307, 'santorum': 6894, 'teacup': 7918, 'boredom': 1011, 'tentative': 7960, 'tuition': 8258, 'graduate': 3513, 'preschool': 6094, 'refers': 6478, 'shithole': 7178, 'clubs': 1592, 'dana': 2063, 'rohrabacher': 6769, 'meyers': 5017, 'bounces': 1029, 'cord': 1850, 'scoble': 6963, 'unfollowed': 8351, 'ultimate': 8307, 'obsessed': 5456, 'compliment': 1707, 'miracle': 5080, 'autism': 613, 'treehouse': 8191, 'tpp': 8146, 'seasons': 7020, 'puzder': 6296, 'laugh': 4534, 'sociologists': 7408, 'interior': 4170, 'survives': 7800, 'designer': 2281, 'dash': 2081, 'lasagna': 4523, 'scatter': 6938, 'gains': 3352, 'codes': 1615, 'bottled': 1025, 'bullshit': 1141, 'pizzagate': 5903, 'anchovies': 384, 'homophobic': 3868, 'foretells': 3234, 'seriously': 7095, 'snowman': 7395, 'simultaneous': 7257, 'wars': 8612, 'trading': 8154, 'advisor': 238, 'quitting': 6324, 'cultists': 2015, 'kneel': 4451, 'responsibility': 6631, 'fond': 3209, 'plumber': 5949, 'naval': 5293, 'drills': 2574, 'surfboards': 7785, 'ousted': 5575, 'surfing': 7787, 'renewable': 6555, 'ipsos': 4221, 'moat': 5116, 'situation': 7281, 'handover': 3669, 'blob': 941, 'tip': 8070, 'steele': 7610, 'makeup': 4808, 'bury': 1168, 'gravediggers': 3540, '55': 87, 'proceeding': 6150, 'fakiness': 2994, 'blamed': 924, 'botched': 1021, 'disgrace': 2405, 'souffle': 7436, 'snipers': 7384, 'symphony': 7848, 'sanity': 6892, 'twirl': 8291, 'sponsor': 7521, 'prostitute': 6205, 'greg': 3555, 'gianforte': 3414, 'sent': 7077, 'slam': 7304, 'boom': 1000, 'fantasies': 3015, 'engines': 2771, 'rappers': 6379, 'nut': 5437, 'rentals': 6561, 'syrup': 7853, 'siesta': 7234, 'iceland': 3972, 'pedophile': 5768, 'furor': 3336, 'breakdancing': 1064, 'kenyan': 4400, 'herders': 3780, 'centuries': 1379, 'prosperity': 6204, 'medicine': 4963, 'buyback': 1191, 'inspires': 4143, 'colbert': 1622, 'emmys': 2732, 'features': 3055, 'explicit': 2923, 'scene': 6939, 'shopping': 7194, 'cactus': 1203, 'swimming': 7835, 'crowns': 1993, 'winner': 8751, 'sesame': 7104, 'rated': 6385, 'stooges': 7650, 'hyena': 3963, 'sneaker': 7378, 'pew': 5832, '61': 92, 'diana': 2318, 'falzone': 3006, 'nudes': 5421, 'physician': 5850, 'physical': 5848, 'mental': 4992, 'touching': 8123, 'benjamin': 838, 'regretting': 6500, 'forcing': 3226, 'caveman': 1350, 'moron': 5177, 'physically': 5849, 'neckties': 5309, 'retard': 6655, 'retain': 6649, 'merkel': 4998, 'hosts': 3904, 'broaden': 1102, 'bargaining': 723, 'funder': 3327, 'bankrolls': 703, 'sites': 7278, 'illustrated': 4002, 'fists': 3145, 'bedbugs': 793, 'catfishing': 1336, 'sculptures': 7001, 'opioids': 5529, 'octopus': 5466, 'horoscope': 3889, 'adani': 203, 'canavan': 1244, 'yells': 8857, 'resists': 6619, 'ostrich': 5566, 'testing': 7981, 'boundaries': 1032, 'downtown': 2542, 'desert': 2276, '2050': 48, 'warming': 8599, 'basic': 745, 'experiment': 2915, 'mock': 5119, 'comedy': 1660, 'billionaires': 888, 'farmers': 3027, 'surge': 7788, 'playboy': 5924, 'cares': 1285, 'terminates': 7965, 'joined': 4328, 'mcdaniel': 4936, 'probes': 6146, 'sleepovers': 7321, 'lindsey': 4666, 'slingshot': 7328, 'yiannopoulos': 8863, 'uc': 8301, 'davis': 2095, 'disturbance': 2451, 'gymnasium': 3618, 'ambitious': 362, 'reconcile': 6448, 'factions': 2974, 'raccoon': 6329, 'berries': 847, 'humiliated': 3937, 'gardener': 3374, 'warmongers': 8600, 'dentistry': 2240, 'incarceration': 4054, 'bowls': 1039, 'vouchers': 8553, 'homeowners': 3865, 'mortgage': 5180, 'deduction': 2153, 'pencils': 5780, '2024': 47, 'rings': 6728, 'nominates': 5380, 'battled': 762, 'defraud': 2183, 'sister': 7272, 'rooster': 6787, 'doctors': 2475, 'rehab': 6505, 'patients': 5739, 'mothers': 5190, 'greenpeace': 3550, 'dismissing': 2423, 'anybody': 433, 'blazing': 933, 'carrots': 1301, 'apples': 469, 'downfall': 2539, 'surfaces': 7784, 'adults': 230, 'minors': 5076, '22': 51, 'curtains': 2031, 'drool': 2586, 'deposition': 2261, 'tracker': 8148, 'alias': 323, 'nyt': 5443, 'assassinate': 543, 'laziness': 4561, 'collie': 1634, 'oversees': 5608, 'departments': 2249, 'crochet': 1978, 'zipper': 8888, 'joining': 4329, 'expels': 2911, 'walking': 8578, 'delivered': 2205, 'acknowledges': 177, 'represented': 6588, 'disowned': 2427, 'lacking': 4492, 'quote': 6327, 'tesla': 7976, 'autopilot': 621, 'tiger': 8057, 'woods': 8796, 'cornholing': 1859, 'fairness': 2989, 'associates': 559, 'tire': 8075, 'diary': 2322, 'sceptical': 6942, 'spotlight': 7525, 'painfully': 5647, 'strangle': 7667, 'cfpb': 1388, 'veterinary': 8480, 'brainwashed': 1050, 'galvanize': 3357, 'cameras': 1227, 'grades': 3512, 'kirsten': 4437, 'gillibrand': 3429, 'meddler': 4956, 'smart': 7352, 'informal': 4107, 'dozen': 2543, 'jugglers': 4356, 'arsenal': 521, 'stronger': 7689, 'tx': 8296, 'abbott': 125, 'sheriffs': 7166, 'costumes': 1881, 'galaxy': 3354, 'butler': 1183, 'currently': 2028, 'wallet': 8582, 'hooky': 3880, 'competent': 1695, 'guy': 3615, 'blew': 937, 'magician': 4791, 'tack': 7859, 'burqa': 1164, 'forward': 3248, 'perhaps': 5802, 'athletes': 572, 'ceremonies': 1384, 'undoes': 8341, 'stages': 7558, 'lunatic': 4765, 'conviction': 1825, 'doodled': 2514, 'afrin': 261, 'pantomimes': 5673, 'gloat': 3453, 'theories': 8004, 'templates': 7945, 'megalomaniac': 4971, 'myopics': 5254, 'barbershop': 718, 'rod': 6761, 'triathlon': 8202, 'selloff': 7060, 'embodies': 2722, 'gift': 3419, 'dalmatians': 2057, 'financing': 3116, 'deploy': 2253, 'institution': 4147, 'ballerina': 681, 'mushroom': 5239, 'hospital': 3898, 'brookfield': 1110, 'troubled': 8231, '666': 96, 'fifth': 3097, 'ave': 623, 'privatize': 6140, 'traffic': 8155, 'bending': 833, 'easily': 2647, 'nakedly': 5267, 'sympathising': 7846, 'nazis': 5300, 'blobs': 942, 'passing': 5722, 'rev': 6674, 'billy': 891, 'detroit': 2304, 'pub': 6242, 'irish': 4229, 'paddy': 5638, 'fruit': 3306, 'elegant': 2703, 'unconvincing': 8322, 'pry': 6233, 'loose': 4732, 'shelters': 7161, 'sidesteps': 7231, 'nigerian': 5358, 'climbs': 1567, 'magnets': 4793, 'choirul': 1486, 'huda': 3925, 'goalkeeper': 3463, 'mate': 4908, 'unemployed': 8343, 'immaterial': 4008, 'mailboxes': 4797, 'midgets': 5032, 'slips': 7331, 'inaction': 4050, 'bounce': 1028, 'naughty': 5291, 'nice': 5349, 'distractions': 2446, 'rattlesnake': 6393, 'corrects': 1866, 'wiretapped': 8763, 'streak': 7669, 'stab': 7547, 'cooperating': 1840, 'strippers': 7685, 'cleans': 1553, 'automakers': 617, 'butter': 1184, 'methane': 5012, 'lollipop': 4718, 'quotes': 6328, 'eggplant': 2680, 'hooray': 3882, 'hairdo': 3636, 'kansas': 4377, 'exaggerations': 2866, 'shrubbery': 7221, 'weaponizes': 8650, 'flatulence': 3158, 'powers': 6056, 'resolution': 6620, 'cleaners': 1552, 'cigarettes': 1510, 'tobacco': 8081, 'ghosts': 3413, 'dumber': 2609, 'closet': 1579, 'fagggots': 2977, 'nigggers': 5360, 'makeovers': 4805, 'swimsuit': 7836, 'putting': 6295, 'doo': 2513, 'stemmed': 7614, 'flower': 3191, 'connect': 1767, 'spike': 7501, 'proctologist': 6154, 'scythe': 7002, 'stonewalling': 7647, 'route': 6803, 'redneck': 6464, 'investigator': 4201, 'deceased': 2130, 'emailing': 2715, 'mute': 5248, 'tease': 7923, 'semblance': 7062, 'always': 358, 'renegotiation': 6554, 'texans': 7983, 'receiving': 6435, 'maple': 4851, 'erik': 2819, 'occupation': 5462, 'slum': 7346, 'distances': 2442, 'laundered': 4542, 'ledger': 4586, 'snakes': 7375, 'passport': 5725, 'chad': 1389, 'animated': 399, 'pestles': 5822, 'fly': 3196, 'friendlier': 3289, 'skies': 7292, 'settling': 7114, 'cartoon': 1310, 'roku': 6770, 'channel': 1412, 'forwards': 3249, 'mooch': 5163, 'outlet': 5584, 'dud': 2603, 'deserts': 2277, 'armadillos': 504, 'grandmothers': 3527, 'vp': 8557, 'citigroup': 1521, 'touches': 8122, 'learning': 4578, 'bleeding': 935, 'musician': 5242, 'spanking': 7461, 'divide': 2458, 'ponytail': 5997, 'appointees': 472, 'salaries': 6861, 'persists': 5813, 'truce': 8233, 'pickles': 5856, 'belief': 821, 'exploding': 2927, 'destructive': 2295, 'reanimating': 6421, 'unfavorable': 8346, 'margaret': 4859, 'atwood': 595, 'puritan': 6283, 'values': 8444, 'flying': 3197, 'properties': 6190, 'vagrant': 8441, 'sacrificed': 6845, 'kidnapper': 4417, 'teeth': 7934, 'disgraceful': 2406, 'publication': 6244, 'mascara': 4888, 'crossed': 1984, 'hey': 3794, 'please': 5938, 'golfing': 3483, 'torches': 8109, 'bouncing': 1030, 'heir': 3762, 'burial': 1157, 'emotion': 2734, 'solving': 7417, 'dyslexia': 2630, 'bronzed': 1109, 'november': 5413, 'builds': 1134, 'haggis': 3629, 'extensive': 2945, 'limiting': 4661, 'lifting': 4648, 'cookout': 1836, 'cabbage': 1199, 'bathed': 752, 'apparently': 456, 'pranked': 6067, 'tumult': 8261, 'clout': 1586, 'dwindles': 2625, 'manhood': 4831, 'insensitive': 4136, 'feet': 3068, 'bashar': 742, 'compete': 1694, 'ioc': 4215, 'stability': 7549, 'credentials': 1947, 'gardens': 3375, 'fec': 3058, 'complaint': 1699, 'oppo': 5530, 'pills': 5877, 'comical': 1664, 'rebekah': 6426, 'mercer': 4995, 'notice': 5409, 'mills': 5056, 'retaliates': 6652, 'closure': 1582, 'slightly': 7324, 'awful': 635, 'ninth': 5369, 'circuit': 1514, 'eo': 2799, 'pander': 5666, 'picks': 5857, 'jerome': 4302, 'powell': 6052, 'vimy': 8503, 'ridge': 6715, 'centenary': 1375, 'reenact': 6471, 'punch': 6266, 'assessment': 552, 'steaks': 7605, 'unforced': 8352, 'errors': 2820, 'inflicted': 4102, 'depart': 2246, 'expulsion': 2940, 'salisbury': 6866, 'mugabe': 5216, 'zimbabwe': 8885, 'snake': 7374, 'blend': 936, 'mucus': 5212, 'thaw': 7995, 'popsicle': 6010, 'dying': 2626, 'disposed': 2430, 'coloring': 1646, 'reading': 6410, 'campaigns': 1231, 'pecans': 5764, 'melodies': 4975, 'maxine': 4922, 'prisoner': 6135, 'captured': 1273, 'calculations': 1212, 'cartoons': 1311, 'baking': 677, 'fedex': 3061, 'viral': 8515, 'stopping': 7653, 'burning': 1162, 'readers': 6408, 'presented': 6097, 'overturn': 5615, 'consumers': 1795, 'lizards': 4699, 'crude': 1996, 'discount': 2393, 'widens': 8726, 'cocoa': 1612, 'coffin': 1617, 'ate': 569, 'comedian': 1658, 'commit': 1677, 'salami': 6859, 'approve': 478, 'queue': 6314, 'rioting': 6730, 'romances': 6777, 'address': 207, 'collective': 1630, 'narcissism': 5276, 'exodus': 2897, '361': 70, 'exxon': 2951, 'mobil': 5118, 'fined': 3120, 'violating': 8507, 'twerking': 8288, 'otto': 5572, 'warmbier': 8598, 'coma': 1651, 'tuxedo': 8279, 'tomatoes': 8095, 'pipes': 5890, 'quills': 6317, 'topping': 8108, 'caused': 1345, 'hotdog': 3906, 'pipe': 5888, 'starvation': 7589, 'unimaginable': 8358, 'biscuit': 907, 'ceilings': 1358, 'hillsborough': 3818, 'football': 3215, 'literacy': 4689, 'spirit': 7507, 'themed': 8001, 'kurdistan': 4477, 'knead': 4450, 'visited': 8526, 'gambler': 3358, 'declared': 2139, 'counts': 1898, 'sexy': 7124, 'contentious': 1804, 'badlands': 663, 'rogue': 6767, 'inadequacies': 4051, 'gap': 3369, 'invisible': 4207, 'wallace': 8581, 'colleagues': 1627, 'disastrous': 2381, 'result': 6644, 'brush': 1119, 'imaginary': 4004, 'losers': 4739, 'clarence': 1540, 'harassed': 3682, 'yes': 8860, 'impeached': 4021, 'resonates': 6623, 'wart': 8615, 'dealer': 2111, 'defeated': 2161, 'chauvinism': 1433, 'weightlifting': 8672, 'rodeo': 6764, 'veteran': 8478, 'glass': 3445, 'artist': 527, 'falsified': 3004, 'trumpet': 8243, 'oatmeal': 5445, 'requires': 6598, 'unpaid': 8378, 'interns': 4174, 'nondisclosure': 5387, 'makeover': 4804, 'repaint': 6566, 'kale': 4374, 'clothed': 1583, 'exams': 2871, 'termites': 7966, 'kompromat': 4465, 'surface': 7783, 'breath': 1070, 'glued': 3456, 'riveting': 6743, 'herself': 3789, 'viewed': 8494, 'benching': 831, 'repairs': 6567, 'discuss': 2401, 'absolute': 139, 'deadline': 2108, 'tusk': 8277, 'racquetball': 6340, 'combat': 1653, 'disintegrate': 2414, 'tens': 7955, 'romania': 6779, 'bravery': 1054, 'costumer': 1880, 'drivel': 2579, 'worship': 8817, 'pinatas': 5883, 'wisconsin': 8765, 'ironworker': 4232, 'cancelled': 1248, 'undersecretary': 8332, 'supremacists': 7779, 'kurds': 4478, 'groping': 3576, 'bullies': 1139, 'seeking': 7041, 'protective': 6214, 'indicate': 4081, 'scroll': 6993, 'taqueria': 7894, 'bowlers': 1037, 'wishful': 8768, 'accent': 148, 'zodiac': 8889, 'killer': 4422, 'extending': 2942, 'limit': 4659, 'ar': 484, 'depressingly': 2262, 'skating': 7287, 'advanced': 231, 'ratio': 6390, 'coasts': 1602, 'confessed': 1736, 'involvement': 4214, 'wrestler': 8833, 'condemnation': 1723, 'flaunt': 3159, 'expose': 2933, 'pictures': 5862, 'pomp': 5991, 'kilt': 4426, 'learn': 4576, 'sychologists': 7842, 'kid': 4415, 'potty': 6046, 'training': 8163, 'princeling': 6128, 'stripped': 7683, 'exile': 2892, 'partied': 5709, 'scratches': 6983, '9th': 120, 'evening': 2851, 'shampoo': 7141, 'alcohol': 315, 'cambodia': 1221, 'hun': 3940, 'object': 5451, 'anarchic': 382, 'submit': 7713, 'communicate': 1684, 'automatically': 619, 'memory': 4986, 'directors': 2365, 'bondholders': 986, 'restructuring': 6642, 'laminate': 4499, 'introduced': 4188, 'misses': 5098, 'healthiest': 3740, 'bloomberg': 951, 'index': 4077, 'tweetstorm': 8286, 'sporting': 7522, 'goods': 3487, 'rifles': 6719, '21': 49, 'misplaces': 5094, 'succeed': 7727, 'bikes': 880, 'incinerated': 4057, 'unaware': 8317, 'division': 2462, 'simmers': 7253, 'feel': 3065, 'ransom': 6372, 'hipsters': 3829, 'baron': 725, 'genital': 3393, 'mutilation': 5249, 'earthworms': 2644, 'mole': 5137, 'despondent': 2286, 'numb': 5428, 'unsure': 8389, 'creators': 1945, 'reza': 6702, 'aslan': 536, 'piece': 5864, 'sh': 7126, 'correctly': 1865, 'identifying': 3979, 'ironclad': 4231, 'hour': 3912, 'abe': 126, 'undermines': 8330, 'backers': 649, 'snail': 7373, 'gymnastics': 3619, 'actor': 194, 'reg': 6493, 'cathey': 1337, '59': 89, 'pirouettes': 5894, 'nuneaton': 5433, 'cucumber': 2009, 'bit': 909, 'professional': 6163, 'sham': 7138, 'detains': 2299, 'consulate': 1791, 'worker': 8803, 'tension': 7957, 'negative': 5312, 'starting': 7586, 'leeway': 4588, 'scrambles': 6979, 'ovens': 5596, 'scams': 6926, 'armed': 506, 'stockings': 7639, 'settles': 7113, 'ditched': 2453, 'peekaboo': 5769, 'fungus': 3333, 'maute': 4921, 'southeast': 7447, 'islamist': 4241, 'relieved': 6528, 'wonderful': 8795, 'organization': 5551, 'large': 4518, 'scale': 6921, 'equivocation': 2811, 'astrologer': 563, 'madrid': 4787, 'jamming': 4279, 'cuddles': 2011, 'remodel': 6546, 'follows': 3207, 'informant': 4108, 'mongoose': 5150, 'attend': 585, 'avenge': 624, 'hunters': 3951, 'albino': 313, 'stigma': 7632, 'cautious': 1347, 'sleepwalkers': 7322, '29th': 60, 'overtakes': 5612, 'pornhub': 6018, 'espn': 2830, 'wto': 8843, 'web': 8658, 'reiterates': 6512, 'ability': 127, 'delta': 2211, 'takeoff': 7868, 'mercosur': 4996, 'wonder': 8794, 'memes': 4981, 'hopeful': 3885, 'marine': 4865, 'skimping': 7294, 'liquor': 4681, 'wiretapping': 8764, 'acne': 179, 'flags': 3154, 'huffington': 3926, 'rein': 6509, 'labrador': 4488, 'fy': 3343, 'violations': 8509, 'pugs': 6255, 'notre': 5410, 'dame': 2061, 'commencement': 1669, 'sprint': 7531, 'withdrawn': 8775, 'noses': 5404, 'anthropomorphism': 425, 'pantsuit': 5676, 'gears': 3386, 'risky': 6739, 'forgets': 3238, 'sterilize': 7622, 'cheetah': 1452, 'ape': 443, 'songs': 7427, 'cyberattack': 2040, 'spreads': 7529, 'broomstick': 1112, 'prodigies': 6155, 'execs': 2881, 'decisions': 2136, 'yard': 8850, 'grope': 3574, 'java': 4290, 'husbands': 3958, 'zte': 8896, 'ordered': 5546, 'fingerprints': 3123, 'listing': 4687, 'politician': 5978, 'consistently': 1783, 'staircase': 7561, 'achieve': 172, 'pomade': 5990, 'injected': 4122, 'dose': 2519, 'served': 7099, 'bbq': 766, 'unmotivated': 8377, 'pirates': 5892, '57': 88, 'drivers': 2581, 'oprah': 5535, 'confidants': 1740, 'tonsils': 8098, 'promising': 6181, 'rhetoric': 6703, 'locks': 4715, 'netflix': 5325, '104': 8, 'subscribers': 7719, 'toothpicks': 8106, 'luiz': 4763, 'inacio': 4049, 'lula': 4764, 'silva': 7249, 'defies': 2178, 'hunkers': 3948, 'blankie': 928, 'strongest': 7690, 'rash': 6383, 'retrieve': 6666, 'cyberweapons': 2042, 'peddling': 5767, 'architecture': 490, 'expects': 2907, 'alpaca': 350, 'exist': 2893, 'matrix': 4914, 'deportations': 2257, '37': 71, 'dominates': 2500, 'rankings': 6371, 'nation': 5281, 'schools': 6956, 'gang': 3365, 'standoff': 7577, 'normalization': 5395, 'recuses': 6458, 'copeland': 1845, 'tories': 8110, 'enchilada': 2746, 'gynecologist': 3620, 'downgrading': 2540, 'dccc': 2103, 'ventral': 8468, 'cream': 1939, 'garage': 3371, 'easter': 2649, 'ball': 680, 'raft': 6347, 'sashays': 6899, 'chant': 1414, 'aggression': 275, 'carousels': 1294, 'rebuke': 6431, 'arts': 528, 'en': 2744, 'masse': 4897, 'forever': 3235, 'realist': 6417, 'confrontation': 1751, 'cher': 1459, 'sashaying': 6898, 'revisions': 6690, 'trusted': 8249, 'sneakers': 7379, 'cockpit': 1607, 'vine': 8505, 'freeze': 3280, 'psychiatrists': 6236, 'dates': 2088, 'trails': 8160, 'heartburn': 3748, 'pigsties': 5871, 'tools': 8103, 'delete': 2195, 'require': 6596, 'employment': 2741, 'offends': 5473, 'odor': 5468, 'lick': 4638, 'aaa': 121, 'necessarily': 5307, 'sector': 7032, 'dec': 2127, 'estimate': 2835, '190': 24, 'adp': 226, 'sphincter': 7494, 'danish': 2075, 'inventor': 4193, 'confesses': 1737, 'dismembering': 2418, 'inventing': 4192, 'progressives': 6173, 'loyalty': 4760, 'pantry': 5674, 'accelerate': 147, 'animation': 400, 'depicts': 2251, 'la': 4483, 'swastika': 7821, 'viewers': 8495, 'lifelong': 4646, 'halloween': 3648, 'desantis': 2270, 'nursemaid': 5436, 'carried': 1298, 'repealing': 6569, 'academics': 146, 'laureates': 4546, 'misplace': 5093, 'fingernails': 3122, 'grab': 3508, 'sunscreen': 7759, 'reveled': 6680, 'disclosures': 2391, 'drenched': 2567, 'surrealist': 7793, 'ronny': 6783, 'marital': 4866, 'bellows': 826, 'meatballs': 4951, 'dashcam': 2082, 'philando': 5836, 'castile': 1320, 'informing': 4112, 'firearm': 3129, 'gremlin': 3556, 'millennial': 5050, 'stroke': 7687, 'francisco': 3265, 'pier': 5865, 'aspiring': 537, 'fainted': 2987, 'giggles': 3425, 'leftist': 4590, 'boston': 1019, 'supposed': 7776, 'fortune': 3246, 'fruitworm': 3308, 'runoff': 6827, 'bakery': 676, 'scrooge': 6994, 'prestigious': 6108, 'scholarship': 6952, 'disadvantaged': 2370, 'hamburgers': 3657, 'oozes': 5516, 'encouraging': 2749, 'compromise': 1710, 'flirt': 3175, 'ridicules': 6716, 'receptionist': 6439, 'effective': 2675, 'grits': 3567, 'lettuce': 4620, 'nosedive': 5403, 'reducing': 6468, 'output': 5587, 'tender': 7951, 'wearing': 8653, 'scotus': 6973, 'curtain': 2030, 'tighten': 8059, 'venezuelan': 8466, 'possession': 6033, 'plug': 5947, 'cavities': 1352, 'flagged': 3153, '2004': 33, 'pirate': 5891, 'tolerate': 8091, 'restrooms': 6641, 'grasshoppers': 3536, 'crush': 2002, 'decode': 2146, 'illiterates': 4001, 'ankara': 402, 'footstool': 3218, 'machines': 4780, 'edible': 2667, 'dough': 2528, 'craze': 1937, 'heartland': 3749, 'imposters': 4038, 'tux': 8278, 'beard': 775, 'stance': 7573, 'confirming': 1745, 'heterosexuality': 3793, 'behalf': 813, 'owl': 5620, 'groupie': 3581, 'hotness': 3909, 'toe': 8084, 'columbia': 1648, 'winks': 8750, 'dustpans': 2619, 'befell': 802, 'cigars': 1511, 'teatime': 7924, 'counseled': 1888, 'murderer': 5231, 'showgirl': 7214, 'knocking': 4457, 'guys': 3616, 'courts': 1909, 'tee': 7928, 'markers': 4869, 'officers': 5483, 'yetis': 8862, 'retaken': 6650, 'pumping': 6264, 'aleppo': 318, 'monitoring': 5151, 'internal': 4171, 'dynamics': 2627, 'rolling': 6774, 'seize': 7050, 'doghouses': 2488, 'discussing': 2403, 'indictment': 4083, 'taunting': 7903, 'ontario': 5513, 'wore': 8800, 'bench': 830, 'dina': 2341, 'gala': 3353, 'whilst': 8701, 'searching': 7017, 'roboticists': 6757, 'granted': 3532, 'visas': 8523, 'precision': 6076, 'monster': 5156, 'spare': 7463, '23m': 55, 'uninsuredrepublican': 8360, 'reaper': 6422, 'seizes': 7052, 'anbang': 383, 'gentle': 3397, 'busy': 1179, 'baghdad': 668, 'polish': 5975, 'absence': 137, 'skis': 7299, 'swim': 7834, 'delhi': 2198, 'engulfed': 2774, 'halts': 3651, 'upstage': 8411, 'visits': 8528, 'acid': 174, 'showed': 7211, 'librarian': 4635, 'thesaurus': 8009, 'cincinnati': 1513, 'nightclub': 5362, 'plums': 5951, 'reactivated': 6403, 'shed': 7154, 'fitness': 3147, 'develops': 2310, 'organizer': 5552, 'describing': 2273, 'daily': 2054, 'dove': 2534, 'closes': 1578, 'spanks': 7462, 'dubke': 2599, 'revolts': 6695, 'whine': 8702, 'ample': 374, 'slapstick': 7311, 'buffoonery': 1130, 'autopsies': 622, 'somersaults': 7421, 'enraged': 2781, 'refund': 6487, 'worsen': 8816, 'pyramid': 6299, 'essays': 2831, 'drones': 2585, 'scarves': 6936, 'pouring': 6048, 'robe': 6753, 'suspicious': 7813, 'packages': 5634, 'locations': 4712, 'soda': 7411, 'ejaculations': 2689, 'cellphones': 1367, 'matched': 4906, 'nestle': 5322, 'factory': 2975, 'dodd': 2478, 'frank': 3266, 'accountable': 162, 'defector': 2165, 'props': 6198, 'stumbles': 7704, 'exhumes': 2891, 'limericks': 4658, 'bribed': 1080, 'calm': 1220, 'beyond': 863, 'brochure': 1106, 'digestive': 2337, 'smear': 7356, 'retribution': 6665, 'recruits': 6455, 'populists': 6015, 'consultants': 1792, 'kindergartener': 4432, 'bowler': 1036, 'worm': 8810, 'toothpick': 8105, 'tasked': 7901, 'bedroom': 794, 'redecorates': 6461, 'commence': 1668, 'ill': 3996, 'sergeant': 7090, 'nick': 5351, 'bailey': 670, 'sable': 6838, 'uranus': 8414, 'referral': 6477, 'herring': 3788, 'passion': 5723, 'patriotism': 5741, 'hollywood': 3859, 'orly': 5560, 'phoned': 5843, 'screwed': 6989, 'momma': 5144, 'delays': 2192, 'noodle': 5390, 'clarify': 1541, 'bubbles': 1122, 'apologies': 448, 'adores': 225, 'crowding': 1990, 'wellesley': 8679, 'walnuts': 8584, 'sitar': 7275, 'auctioned': 598, 'beitar': 819, 'trivia': 8221, 'ddos': 2104, 'suggesting': 7745, 'inches': 4055, 'gambling': 3361, 'serial': 7093, 'stowaway': 7661, 'citizenry': 1523, 'carnage': 1289, 'kabul': 4372, 'butchery': 1182, 'brendan': 1074, 'samantha': 6876, 'wiccan': 8722, 'treadmill': 8182, 'horrific': 3892, 'bezos': 864, 'screws': 6990, 'amazon': 359, 'flies': 3169, 'viper': 8514, 'spiro': 7508, 'agnew': 278, 'nattering': 5289, 'nabobs': 5260, 'negativity': 5313, 'doddering': 2479, 'dotards': 2522, 'deplorableness': 2252, 'silliness': 7247, 'plugs': 5948, 'obsession': 5457, 'located': 4710, 'ushers': 8429, 'amount': 371, 'producing': 6160, 'bafta': 664, 'update': 8399, 'password': 5726, 'nurse': 5435, 'consent': 1772, 'provoke': 6231, 'applause': 467, 'cereal': 1383, 'belly': 827, 'ended': 2754, 'manipulation': 4836, 'oh': 5490, 'bother': 1024, 'winnie': 8753, 'pooh': 6002, 'foul': 3251, 'censors': 1371, 'nationalists': 5285, 'pent': 5790, 'tigers': 8058, 'grilled': 3563, 'heated': 3751, 'exchange': 2874, 'saxophones': 6915, 'disciplined': 2386, 'pillar': 5875, 'fictitious': 3092, 'statements': 7594, 'squints': 7540, 'showers': 7213, 'locust': 4716, 'smells': 7358, 'alimony': 328, 'forest': 3233, 'cobblers': 1604, 'daddy': 2053, 'virulent': 8521, 'represents': 6589, 'perfectly': 5799, 'utterly': 8435, 'integrative': 4154, 'complexity': 1704, 'supper': 7768, 'malarkey': 4810, 'cafeterias': 1206, 'tummy': 8260, 'blackjack': 915, 'resurrect': 6648, 'zia': 8884, 'zoos': 8895, 'snorkeling': 7391, 'falafel': 2995, 'dreamed': 2563, 'zebra': 8880, 'semitism': 7064, 'leg': 4593, 'vets': 8483, 'dissolved': 2440, 'gelatin': 3389, 'pencil': 5779, 'greatest': 3545, 'cauldron': 1343, 'windy': 8747, 'hygiene': 3964, 'couches': 1884, 'stewing': 7629, 'broward': 1116, 'daycare': 2100, 'thin': 8014, 'unhealthily': 8353, 'raping': 6377, 'rescued': 6601, 'boko': 972, 'haram': 3681, 'defeatist': 2162, 'cardboard': 1279, 'fetish': 3085, 'bungles': 1150, 'transvestites': 8172, 'reorganized': 6564, 'cyberwars': 2041, 'nudity': 5424, 'blasted': 930, 'majorettes': 4801, 'cooties': 1843, 'misanthropics': 5086, 'floods': 3183, 'landslides': 4511, 'main': 4798, 'shine': 7172, 'hb2': 3726, 'atoms': 575, 'janitors': 4283, 'eater': 2653, 'gastronomic': 3377, 'gamblers': 3359, 'migration': 5040, 'crumpet': 2001, 'reassures': 6425, 'slower': 7343, 'fb': 3047, 'touted': 8134, 'shuffle': 7222, 'plate': 5920, 'indefensible': 4073, 'decorators': 2150, 'boogies': 994, 'cult': 2014, 'scholar': 6951, 'ecuador': 2664, 'matchmaking': 4907, 'illinois': 3999, 'celebs': 1364, 'tribal': 8203, 'neighbors': 5316, 'pterodactyl': 6241, 'endangering': 2753, 'lives': 4695, 'asserting': 549, 'glee': 3447, 'salling': 6867, 'allowed': 341, 'varsity': 8453, 'scientist': 6961, 'breathe': 1071, 'secular': 7033, 'leopard': 4609, 'ring': 6727, 'cramps': 1930, 'quacks': 6303, 'vultures': 8560, 'mare': 4858, 'thrower': 8040, 'urinate': 8419, 'gaps': 3370, 'knowledge': 4459, 'aisle': 306, 'fume': 3322, '1380': 14, 'crew': 1955, 'stowaways': 7662, 'punching': 6269, 'stuffs': 7703, 'pecking': 5765, 'sonic': 7428, 'similar': 7251, 'peels': 5770, 'unwritten': 8395, 'picnics': 5860, 'essential': 2832, 'hottest': 3910, 'ranked': 6370, 'mistresses': 5107, 'hippies': 3827, 'flour': 3189, 'lighthearted': 4651, 'suppository': 7777, 'pill': 5874, 'cotton': 1882, 'quilting': 6319, 'marsupials': 4881, 'batteries': 759, 'coolness': 1837, 'hungarian': 3944, 'fairyland': 2991, 'mug': 5215, 'bloodstream': 950, 'rhyme': 6704, 'stamps': 7572, 'starve': 7590, 'endgame': 2755, 'nail': 5263, 'cajole': 1208, 'stem': 7613, 'sitcom': 7276, 'chides': 1468, 'gutter': 3614, 'toxic': 8142, 'electric': 2698, 'ceasefire': 1356, 'resigning': 6614, 'directions': 2362, 'disposal': 2429, 'unit': 8364, 'investigates': 4197, 'motorway': 5194, 'pavement': 5749, 'zuck': 8897, 'harvesting': 3700, 'unfolds': 8350, 'madeleine': 4786, 'albright': 314, 'reminder': 6543, 'withhold': 8777, 'andy': 389, 'menswear': 4991, 'increases': 4069, 'affected': 250, '87': 111, 'nanny': 5273, 'actors': 195, 'pepe': 5794, 'marinade': 4864, 'manicure': 4834, 'bombed': 978, '2007': 35, 'hulk': 3932, 'paradise': 5684, 'papers': 5680, 'prompt': 6185, 'drapery': 2556, 'parakeet': 5685, 'toast': 8080, 'puzzles': 6297, 'tunnel': 8263, 'jihad': 4313, 'inconveniencing': 4067, 'knitted': 4456, 'mccarthyite': 4933, 'counterproductive': 1892, 'necklace': 5308, 'entertaining': 2789, 'schlapps': 6949, 'weirdo': 8675, 'yorkers': 8870, 'volunteer': 8541, 'wrestlers': 8834, 'canoodles': 1262, 'mulligans': 5222, 'junkies': 4364, 'pep': 5793, 'shade': 7129, 'sri': 7545, 'lankan': 4514, 'licks': 4640, 'shulkin': 7223, 'committees': 1680, 'washers': 8620, 'schizophrenia': 6947, 'landscaping': 4509, 'retina': 6656, 'image': 4003, 'improves': 4045, 'gpa': 3506, 'fuhrer': 3318, 'materials': 4911, 'diarrhea': 2321, 'sugar': 7744, 'tribes': 8204, 'shape': 7142, 'wine': 8748, 'helpful': 3771, 'chug': 1503, 'obamas': 5448, 'inked': 4125, '65': 95, 'petroleum': 5830, 'conflicted': 1748, 'eyeball': 2953, 'beaver': 785, 'oven': 5595, 'remarries': 6539, 'infection': 4095, 'parsecs': 5706, 'smugglers': 7368, 'followed': 3205, 'prefers': 6082, 'vendetta': 8464, 'fahrenheit': 2978, '451': 82, 'reflect': 6479, 'vocabulary': 8533, 'girdles': 3435, 'vacations': 8438, 'vellicate': 8463, 'shameless': 7140, 'shortly': 7198, 'hobo': 3846, 'golfer': 3481, 'overtures': 5614, 'repeats': 6572, 'mantra': 4843, 'based': 739, 'revelations': 6679, 'peach': 5760, 'scales': 6922, 'frolics': 3298, 'rodents': 6763, 'htin': 3921, 'kyaw': 4482, 'bamboozles': 691, 'guaranteeing': 3590, 'ladder': 4493, 'mankind': 4837, 'pad': 5637, 'alcoholics': 316, 'spell': 7485, 'reshaping': 6607, 'boozing': 1009, 'clams': 1537, 'derail': 2267, 'trollies': 8224, 'folder': 3203, 'shallow': 7137, 'grave': 3539, 'seniors': 7074, 'corners': 1858, 'sctv': 6998, 'reunite': 6671, 'raiser': 6358, 'dave': 2093, 'classic': 1546, 'stereotype': 7621, 'caresses': 1286, 'flashy': 3157, 'aground': 287, 'ego': 2682, 'barron': 733, 'forbes': 3221, 'poppycock': 6009, 'mayonnaise': 4925, 'veganism': 8458, 'waltz': 8585, 'strudel': 7693, 'sheep': 7156, 'quilt': 6318, 'distribution': 2448, 'embraced': 2724, 'veritas': 8475, 'stage': 7557, 'criteria': 1969, 'authoritarian': 609, 'harvard': 3698, 'disguise': 2407, 'babbles': 640, 'foods': 3212, 'hoodlums': 3877, 'holidays': 3857, 'advertiser': 233, 'mishandling': 5090, 'bikinis': 882, 'nails': 5264, 'chipmunk': 1483, 'clemency': 1561, 'leonard': 4608, 'peltier': 5774, 'wen': 8680, 'ho': 3842, 'searches': 7016, 'hiking': 3814, 'dotard': 2521, 'puppets': 6278, 'warrant': 8608, 'geek': 3387, 'havana': 3715, 'cigar': 1509, 'spelling': 7486, 'parrot': 5704, 'carolers': 1291, 'snoring': 7390, 'commercials': 1674, 'brutality': 1121, 'venezuelans': 8467, 'scour': 6975, 'river': 6742, 'treasure': 8184, 'survival': 7797, 'spouses': 7527, 'sweetening': 7830, 'infrastructure': 4116, 'ruthless': 6835, 'intercontinental': 4163, 'heightening': 3761, 'supporting': 7774, 'legacy': 4594, 'emotional': 2735, 'farewell': 3023, 'lawn': 4554, 'vile': 8498, 'peak': 5761, 'believability': 822, 'mugs': 5217, 'hairball': 3632, 'reign': 6507, 'slamming': 7306, 'fork': 3242, 'frost': 3304, 'neutering': 5329, 'understanding': 8334, 'aussie': 602, 'dingo': 2345, 'kettle': 4404, 'waistline': 8570, 'wacky': 8563, 'gender': 3391, 'sparrow': 7468, 'congratulate': 1759, 'slimy': 7326, 'teeing': 7929, 'atheists': 571, 'antifa': 428, 'barricades': 731, 'demonstrators': 2225, 'orgy': 5556, 'enquirer': 2780, 'diagrams': 2316, 'escaping': 2827, 'resources': 6625, 'staffs': 7556, 'compost': 1708, 'invades': 4190, 'vanity': 8451, 'hissing': 3835, 'snacks': 7371, 'crowbar': 1988, '200': 32, 'historical': 3837, 'defaced': 2158, 'hateful': 3709, 'england': 2772, 'smog': 7361, 'chokes': 1488, 'latin': 4531, 'moped': 5172, 'bacteria': 661, 'chancellor': 1405, 'lobbied': 4704, 'annihilating': 405, 'prattles': 6070, 'overcharging': 5599, 'mocks': 5123, 'neighbor': 5315, 'exploded': 2925, 'recently': 6437, 'osha': 5565, 'tomato': 8094, 'houses': 3916, '473': 83, 'bumble': 1145, 'decade': 2128, 'bogeyman': 971, 'brawl': 1055, 'epic': 2801, 'mr': 5209, 'whcd': 8694, 'pussy': 6291, 'jake': 4277, 'tapper': 7892, 'orgasm': 5555, 'mispronunciations': 5095, 'vitamin': 8530, 'taxidermist': 7908, 'chin': 1478, 'moms': 5146, 'scarecrow': 6933, 'jon': 4336, 'jabs': 4263, 'heroes': 3785, 'shoestrings': 7186, '80s': 106, 'script': 6992, 'alma': 346, 'mater': 4909, 'sizzler': 7285, 'franchise': 3263, 'enemies': 2762, 'earns': 2638, 'erection': 2815, 'prayer': 6072, 'chest': 1460, 'forehead': 3229, 'member': 4978, 'fruitcakes': 3307, 'offshore': 5487, 'trailblazer': 8159, 'volume': 8540, 'tiptop': 8074, 'impenetrable': 4023, 'cranial': 1931, 'tsa': 8254, 'tightens': 8060, 'screening': 6987, 'expedite': 2908, 'roseanne': 6792, 'barr': 727, 'smacks': 7350, 'transported': 8171, 'cruel': 1997, 'inhuman': 4120, 'degrading': 2186, 'carriages': 1297, 'soviet': 7451, 'contrasting': 1813, 'standards': 7575, 'oranges': 5542, 'lobsters': 4708, 'pacifist': 5631, 'kindness': 4434, 'inmate': 4126, 'harem': 3692, 'hot': 3905, 'mic': 5019, 'kraken': 4469, 'watches': 8629, 'helplessly': 3773, 'streamed': 7671, 'kombucha': 4464, 'porcupines': 6016, 'comedians': 1659, 'chins': 1481, 'elbows': 2692, 'condemn': 1722, 'closely': 1576, 'ginger': 3432, 'oxygen': 5626, 'mastered': 4903, 'seeming': 7044, 'atheist': 570, 'somnambulist': 7424, 'ankles': 403, 'intervened': 4177, 'acquired': 180, 'paraphernalia': 5690, 'retaliate': 6651, 'gigantism': 3423, 'wrecks': 8830, 'accident': 153, 'unicycle': 8356, 'dachshunds': 2051, 'borrowers': 1014, 'governing': 3500, 'digital': 2338, 'baseballs': 738, 'malawi': 4811, 'clampdown': 1536, 'vampirism': 8447, 'rumors': 6823, 'entry': 2793, 'shortages': 7197, 'territory': 7971, 'eyeballed': 2954, 'fishermen': 3141, 'cruelest': 1998, 'rodrigo': 6765, 'mayors': 4927, 'mosquitos': 5184, 'bout': 1033, 'guides': 3601, 'congratulations': 1761, 'entertain': 2788, 'enslaved': 2784, 'progress': 6171, 'divine': 2460, 'ices': 3973, 'squirts': 7544, 'cartel': 1306, 'comic': 1663, 'senegal': 7072, 'saboteur': 6840, 'airing': 300, 'hardcore': 3687, 'triangles': 8201, 'apes': 444, 'explodes': 2926, 'plotting': 5945, 'stores': 7655, 'nationwide': 5286, 'carts': 1312, 'pitches': 5899, 'backyard': 659, 'mules': 5219, 'instructs': 4149, 'frightened': 3294, 'tidal': 8052, 'duh': 2606, 'papadopoulos': 5677, 'gambles': 3360, 'equation': 2807, 'designs': 2282, 'militant': 5044, 'benghazi': 837, 'raisin': 6360, 'bestiality': 851, 'ogre': 5488, 'biometric': 898, 'database': 2084, 'enrollment': 2783, 'baldness': 678, 'parachute': 5681, 'jewish': 4310, 'montana': 5158, 'iguana': 3994, 'currency': 2026, 'warplane': 8607, 'screaming': 6985, 'flips': 3174, 'sweetens': 7831, 'convent': 1819, 'thespian': 8011, 'ham': 3653, 'pimples': 5881, 'hindu': 3822, 'counties': 1894, 'track': 8147, 'insurers': 4153, 'connections': 1769, 'chants': 1416, 'infatuation': 4094, 'cozy': 1920, 'blanket': 927, 'retired': 6658, 'shreds': 7218, 'alibaba': 324, 'ma': 4776, 'judges': 4350, 'allotments': 338, 'crucial': 1994, 'canary': 1243, 'measure': 4948, 'classed': 1545, 'fracking': 3260, 'gophers': 3492, 'humanity': 3935, 'hermits': 3782, 'kindergartner': 4433, 'chart': 1429, 'cholesterol': 1490, 'kabobs': 4371, 'checks': 1444, 'chase': 1431, 'rush': 6830, 'attendance': 586, 'fleas': 3162, 'impersonates': 4024, 'assertion': 550, 'deserved': 2279, 'minions': 5069, 'insomnia': 4140, 'microsoft': 5025, 'inappropriate': 4052, 'bing': 893, 'engine': 2770, 'acrobatics': 182, 'gimpy': 3430, 'midget': 5031, 'oooo': 5515, 'wrongdoings': 8841, 'pigs': 5870, 'origami': 5557, 'server': 7100, 'hunks': 3949, 'milk': 5048, 'kite': 4445, 'queen': 6308, 'combusts': 1656, 'weibo': 8668, 'forbidden': 3222, 'disagree': 2371, 'tailgate': 7864, 'angel': 391, 'orchestrating': 5544, 'leash': 4579, 'films': 3110, 'clairvoyant': 1535, 'scrutinising': 6996, 'hiring': 3832, 'toadies': 8079, 'jesus': 4306, 'campos': 1234, 'moments': 5143, 'toothbrush': 8104, 'automatic': 618, 'hikes': 3813, 'revenue': 6682, 'serfdom': 7089, 'fest': 3082, 'disingenuous': 2413, 'persist': 5812, 'hairline': 3639, 'muhammad': 5218, 'ali': 322, 'horrible': 3891, 'shame': 7139, 'redstate': 6466, 'bloggers': 947, 'stalkers': 7567, 'forgot': 3240, 'scout': 6976, 'cosmetologists': 1872, 'vegans': 8459, 'dreads': 2561, 'thanked': 7991, 'fema': 3074, 'bombers': 980, 'impose': 4034, 'grandson': 3531, 'fixing': 3151, 'deflate': 2180, 'malibu': 4815, 'upending': 8402, 'ducks': 2602, 'sergey': 7092, 'kislyak': 4438, 'poetry': 5958, 'impersonator': 4026, 'crashed': 1933, 'missed': 5097, 'groundhog': 3578, 'contest': 1805, 'anime': 401, 'prank': 6066, 'hairpieces': 3641} ###Markdown TF-IDF for a word in a document is calculated by multiplying two different metrics:The **term frequency** of a word in a document. There are several ways of calculating this frequency, with the simplest being a raw count of instances a word appears in a document. Then, there are ways to adjust the frequency, by length of a document, or by the raw frequency of the most frequent word in a document.The **inverse document** frequency of the word across a set of documents. This means, how common or rare a word is in the entire document set. The closer it is to 0, the more common a word is. This metric can be calculated by taking the total number of documents, dividing it by the number of documents that contain a word, and calculating the logarithm.So, if the word is very common and appears in many documents, this number will approach 0. Otherwise, it will approach 1.Multiplying these two numbers results in the TF-IDF score of a word in a document. The higher the score, the more relevant that word is in that particular document. Extract features of both training and validation data ###Code # helper function: separate each title into (original_word, context), where context = title text without original word # params: # df: dataframe, with 'original' and 'edit' columns # return: # original_words: a list of original word strings before editing # contexts: a list of context strings def separate_original_word_from_title(df): original_words = [] contexts = [] for index, row in df.iterrows(): title = row['original'] start_position = title.find('<') end_position = title.find('/>') original_words.append(title[start_position+1 : end_position]) contexts.append(title[:start_position] + title[end_position+2 :]) return original_words, contexts ###Output _____no_output_____ ###Markdown Here we construct a Sparse Feature Matrix. This is to make this task more computationally easy. More information can be found here: https://machinelearningmastery.com/sparse-matrices-for-machine-learning/ ###Code # construct sparse feature matrix # params: # df: dataframe, with 'original' and 'edit' columns # vectorizer: sklearn text vectorizer, either TfidfVectorizer or Countvectorizer # return: # M: a sparse feature matrix that represents df's textual information (used by a predictive model) def construct_feature_matrix(df, vectorizer): edit_words = df['edit'].tolist() original_words, contexts = separate_original_word_from_title(df) # here the dimensionality of X is len(df) x |V| X_edit = vectorizer.transform(edit_words) return X_edit # Construct feature matrices for training and validation data train_X = construct_feature_matrix(train_dataframe, vectorizer) valid_X = construct_feature_matrix(valid_dataframe, vectorizer) test_X = construct_feature_matrix(test_dataframe, vectorizer) ###Output _____no_output_____ ###Markdown Train model on training set, evaluate model on validation set You could use a number of different models here. Look at this list and see what potentially othe models you would want to use:https://scikit-learn.org/stable/modules/classes.htmlmodule-sklearn.linear_model ###Code # train a linear regression model lm = LinearRegression() model = lm.fit(train_X, train_Y) print (model.intercept_) print (model.coef_.shape) # Evaluate model on validation set valid_Y_hat = model.predict(valid_X) rmse = np.sqrt(sklearn.metrics.mean_squared_error(valid_Y, valid_Y_hat)) print('RMSE on validation set:', rmse) # Evaluate model on training set: # expect to see unrealistically good performance! (for RMSE: lower is better) # unrealistic because YOUR MODEL IS TRAINED ON EXACTLY THESE DATA! # It gives the best validation/test performance you could hope to achieve using this model. train_Y_hat = model.predict(train_X) rmse = np.sqrt(sklearn.metrics.mean_squared_error(train_Y, train_Y_hat)) print('RMSE on training set:', rmse) # apply the model on test data, write out prediction results to a csv file test_Y_hat = model.predict(test_X) write_test_prediction(test_dataframe, test_Y_hat, './ridge-regression_alpha=1_baseline_new-tf.csv') ###Output _____no_output_____ ###Markdown Investigate what the model has learned and where it failed (A.K.A. error analysis) Look at learned parameters (for linear model: weight of each dimension) ###Code # construct a mapping: word -> learned weight of this word feature_weight = {} for word, idx in vectorizer.vocabulary_.items(): feature_weight[word] = model.coef_[idx] # words positively correlate with funniness (top ones) for k, v in sorted(feature_weight.items(), key = lambda x: x[1], reverse = True)[:10]: print (k, v) # words negatively correlate with funniness (top ones) for k, v in sorted(feature_weight.items(), key = lambda x: x[1], reverse = False)[:10]: print (k, v) ###Output opposition -0.8836506444659917 years -0.8836506444659917 border -0.8836506444659917 sale -0.8836506444659917 trump -0.8836506430721189 check -0.8836506430721189 blames -0.8836506430721189 hike -0.8836506430721189 radio -0.8836506430721189 attacks -0.8836506430721189 ###Markdown Look at how the model makes predictions on individual examples ###Code # We pick a set of examples from the validation set (we predicted scores for those). # We usually we don't pick from training data (since the good performance may be unrealistic). # We cannot do error analysis on test data (because no true target value is provided). def explain_linear_prediction(df, model, idx2feature, X, Y, Y_hat, idx_list): print('indices:', idx_list) for idx in idx_list: print ('==============', idx, '================') print ('original:', df.iloc[idx]['original']) print ('edit:', df.iloc[idx]['edit']) print ('grades:', df.iloc[idx]['grades']) print ('TRUE score:', df.iloc[idx]['meanGrade']) print ('PRED score:', Y_hat[idx]) print ('\nPRED breakdown:') print ('\tINTERCEPT', model.intercept_) if X[idx, :].nnz == 0: print ('\tFEATURE', '[EMPTY]') else: for entry in X[idx, :]: # looping over a row in sparse matrix feature_value = entry.data[0] feature_dim = entry.indices[0] print ('\tFEATURE', idx2feature[feature_dim], ':', 'f_value', feature_value, '*', 'f_weight', model.coef_[feature_dim], '=', feature_value*model.coef_[feature_dim]) # construct a dictionary mapping: feature index -> word idx2feature = dict([(v,k) for k,v in vectorizer.vocabulary_.items()]) errors = (valid_Y - valid_Y_hat)**2 # sort errors from low to high sorted_errors = sorted(enumerate(errors.iloc[:].tolist()), key = lambda x: x[1], reverse = False) # print(sorted_errors) ###Output _____no_output_____ ###Markdown prediction on random examples ###Code # pick a random set of examples from validation set: K = 5 random_indices = np.random.randint(0, valid_X.shape[0], K) explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, random_indices) ###Output indices: [1088 1232 1065 1669 505] ============== 1088 ================ original: Starbucks <encourages/> bipartisan coffee-drinking edit: forces grades: 32110 TRUE score: 1.4 PRED score: 0.8836506400461821 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE forces : f_value 1.0 * f_weight 0.0 = 0.0 ============== 1232 ================ original: A detailed <analysis/> of the Trump-Palin-Nugent-Kid Rock photo edit: shocker grades: 11000 TRUE score: 0.4 PRED score: 0.8836506400461821 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE [EMPTY] ============== 1065 ================ original: Major Referendum Today in Turkey , Decision on Whether or Not To Expand Turkish President Erdogan 's <Power/> and Role edit: kitchen grades: 32111 TRUE score: 1.6 PRED score: 1.1500000089824969 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE kitchen : f_value 1.0 * f_weight 0.26634936893631467 = 0.26634936893631467 ============== 1669 ================ original: Trump border wall : Texans receiving letters about their <land/> edit: barbecue grades: 32222 TRUE score: 2.2 PRED score: 1.0666666540652607 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE barbecue : f_value 1.0 * f_weight 0.18301601401907858 = 0.18301601401907858 ============== 505 ================ original: After Election , More New Yorkers Tell Volunteer Groups , ‘ I Can <Help/> ’ edit: Fly grades: 11000 TRUE score: 0.4 PRED score: 0.9999999969738926 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE fly : f_value 1.0 * f_weight 0.11634935692771053 = 0.11634935692771053 ###Markdown examples with closest prediction ###Code K = 5 # look at data with lowest prediction error low_error_indices = [i for i, v in sorted_errors[:K]] explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, low_error_indices) ###Output indices: [1428, 84, 110, 619, 955] ============== 1428 ================ original: Susan Sarandon : ‘ I Do n’t Think Trump ’s Gon na Make It Through His Whole <Term/> ’ edit: sandwich grades: 32110 TRUE score: 1.4 PRED score: 1.4000000024059092 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE sandwich : f_value 1.0 * f_weight 0.5163493623597272 = 0.5163493623597272 ============== 84 ================ original: FBI Director asks Justice Department to publicly <denounce/> Trump 's assertion of Obama wiretapping edit: approve grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE approve : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 110 ================ original: Trump walks back bizarre <comments/> on funding black colleges — but this administration ’s racism is no mistake edit: rant grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE rant : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 619 ================ original: A top State Department official could n't explain why the U.S. <backs/> Saudi Arabia edit: loves grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE loves : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ============== 955 ================ original: <Watch/> : Conservative political advocate Matt Schlapp says Trump ’s ties to Russia are “ probably treasonous ” edit: clock grades: 0 TRUE score: 0.0 PRED score: -3.025936834433196e-09 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE clock : f_value 1.0 * f_weight -0.8836506430721189 = -0.8836506430721189 ###Markdown examples with worst predictions ###Code K = 5 # look at data with highest prediction error high_error_indices = [i for i, v in sorted_errors[-K:]] explain_linear_prediction(valid_dataframe, model, idx2feature, valid_X, valid_Y, valid_Y_hat, high_error_indices) ###Output indices: [978, 120, 2146, 310, 774] ============== 978 ================ original: Spicer defends Trump : Issues are ' evolving towards the president 's <position/> ' edit: mouth grades: 10000 TRUE score: 0.2 PRED score: 2.199999996973688 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE mouth : f_value 1.0 * f_weight 1.316349356927506 = 1.316349356927506 ============== 120 ================ original: Donald Trump Endorses Keeping Senate in <Session/> Seven Days a Week to Get Nominees Approved edit: Jail grades: 32222 TRUE score: 2.2 PRED score: 0.19999999697402915 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE jail : f_value 1.0 * f_weight -0.683650643072153 = -0.683650643072153 ============== 2146 ================ original: Trump to North Korean leader Kim : My ‘ Nuclear <Button/> ’ is ‘ much bigger &amp; more powerful ’ edit: Belly grades: 33222 TRUE score: 2.4 PRED score: 0.3999999969739948 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE belly : f_value 1.0 * f_weight -0.4836506430721873 = -0.4836506430721873 ============== 310 ================ original: Charlotte Pence : I Bought The Gay <Bunny/> Book edit: republican grades: 33322 TRUE score: 2.6 PRED score: 0.5999999969739607 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE republican : f_value 1.0 * f_weight -0.2836506430722214 = -0.2836506430722214 ============== 774 ================ original: ' Disappeared ' Lawyer investigating in Egypt the <death/> of Cambridge student , Giulio Regeni , re-appears in court , under charges edit: selfies grades: 10000 TRUE score: 0.2 PRED score: 2.399999996973653 PRED breakdown: INTERCEPT 0.8836506400461821 FEATURE selfies : f_value 1.0 * f_weight 1.5163493569274713 = 1.5163493569274713
notebooks/tp2_Titanic_BayesEnsemble.ipynb
###Markdown TP : Naïve Bayes et Ensemble appliqués au Titanic Récupération des données du cours ANNRenvoie 2 Dataframe train (avec le champs Survived) et test (sans le champs Survived) ###Code %run ./tp1_prepa_features.ipynb ###Output _____no_output_____ ###Markdown Préparation des données de Training ###Code from sklearn.model_selection import train_test_split #Séparation des valeurs de train et label (tous les exemples) X_alltrain = train.values[:, 1:] y_alltrain = train.values[:, 0] X_train, X_test, y_train, y_test = train_test_split(X_alltrain, y_alltrain, random_state=42) print('%i X_train, %i X_test, %i y_train,%i y_test'%( X_train.shape[0], X_test.shape[0], y_train.shape[0], y_test.shape[0])) print('%i X_alltrain, %i y_alltrain'%(X_alltrain.shape[0], y_alltrain.shape[0])) feature_names=train.columns.tolist()[1:] target_names=["Disparu","Rescapé"] print('features:',feature_names) print('target:',target_names) ###Output 668 X_train, 223 X_test, 668 y_train,223 y_test 891 X_alltrain, 891 y_alltrain features: ['Pclass', 'Sex', 'Age', 'Fare', 'Embarked', 'IsAlone', 'Title'] target: ['Disparu', 'Rescapé'] ###Markdown Fonction Utilitaires ###Code # Fonctions permettant de générer le fichier d'envoi à Kaggle # #parametres: Classifiers; Données à calculer ; index) def generer_resultats(clf,data=test.values,idx=finalfile_index): """ Fonctions permettant de générer le fichier d'envoi à Kaggle. On passe un classifier sur lequel on refait le training avec toutes les données de training Parameters ---------- Classifiers : Classifier utilisé pour la prédiction data : Données à calculer. par défaut, les valeurs du dataset "test" idx : Index des passagers testés. Stockés dans finalfile_index lors de la lecture des données """ print(clf.get_params()) clf.fit(X_alltrain, y_alltrain) prediction=clf.predict(data) results=pd.DataFrame(prediction.astype(int), index = finalfile_index, columns=['Survived']) results.to_csv('resultats%s.csv'%clf.__class__.__name__) #Fonction pour l'affichage 2 D des résultats from matplotlib.colors import ListedColormap def plot_decision_boundary(clf,X,y, axes=[-0, 30, -5, 5], axis_name=['x1','x2'],alpha=0.5, contour=True): """ Fonction pour l'affichage 2 D des résultats Parameters ---------- clf : Classifier à afficher X : features de Données a afficher y : labels de Données a afficher axes : : Tailles des axes (valeur min/max) axis_name : Nom des axes sur le graphique alpha : Transparence des points contour : Afichage du contour """ x1s = np.linspace(axes[0], axes[1], 100) x2s = np.linspace(axes[2], axes[3], 100) x1, x2 = np.meshgrid(x1s, x2s) X_new = np.c_[x1.ravel(), x2.ravel()] y_pred = clf.predict(X_new).reshape(x1.shape) custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) if contour: custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bo",label="Disparu", alpha=alpha) plt.plot(X[:, 0][y==1], X[:, 1][y==1], "ys", label="Rescapé",alpha=alpha) plt.axis(axes) plt.xlabel(axis_name[0], fontsize=18) plt.ylabel(axis_name[1]+ " ",fontsize=18, rotation=0) plt.legend(loc="lower right", fontsize=14) ###Output _____no_output_____ ###Markdown Exercice 1 : Naïve BayesEn utilisant l'exemple du cours 2, contruisez et testez un modèle bayésien pour prévoir la survie. Essayez plusieurs valeurs pour max_depth Envoyer à Kaggle en utilisant la fonction generer_resultats ###Code from sklearn.naive_bayes import GaussianNB,MultinomialNB from sklearn.metrics import accuracy_score gnb_clf = GaussianNB() gnb_clf.fit(X_train, y_train) y_pred = gnb_clf.predict(X_test) print("Niveau de précision : %.2f"%(100*accuracy_score(y_test, y_pred))) ###Output Niveau de précision : 77.13 ###Markdown Exercice 2 : Modèles d'ensemblesEn utilisant les l'exemple 2 du cours 1 ainsi que les résultat du TP1, créer un modèle d'ensemble en testant soft et hard voting. ###Code # Graphes %matplotlib inline import matplotlib.pyplot as plt # Machine learning from sklearn.model_selection import train_test_split from sklearn.datasets import make_moons from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import VotingClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score #Eviter les warnings import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) log_clf = LogisticRegression(random_state=42) rnd_clf = RandomForestClassifier(random_state=42) bayes_clf = GaussianNB() voting_clf = VotingClassifier(estimators=[('lr', log_clf), ('rf', rnd_clf), ('by', bayes_clf)], voting='hard') dict_scores={} for clf in (log_clf, rnd_clf, bayes_clf, voting_clf): clf.fit(X_train, y_train) y_pred = clf.predict(X_test) dict_scores[clf.__class__.__name__]=accuracy_score(y_test, y_pred) voting_soft_clf = VotingClassifier(estimators=[('lr', log_clf), ('rf', rnd_clf), ('by', bayes_clf)], voting='soft') voting_soft_clf.fit(X_train, y_train) y_pred = voting_soft_clf.predict(X_test) dict_scores['VotingClassifier Soft']=accuracy_score(y_test, y_pred) dict_scores generer_resultats(voting_soft_clf) ###Output {'estimators': [('lr', LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=42, solver='liblinear', tol=0.0001, verbose=0, warm_start=False)), ('rf', RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=42, verbose=0, warm_start=False)), ('by', GaussianNB(priors=None))], 'flatten_transform': None, 'n_jobs': 1, 'voting': 'soft', 'weights': None, 'lr': LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=42, solver='liblinear', tol=0.0001, verbose=0, warm_start=False), 'rf': RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=42, verbose=0, warm_start=False), 'by': GaussianNB(priors=None), 'lr__C': 1.0, 'lr__class_weight': None, 'lr__dual': False, 'lr__fit_intercept': True, 'lr__intercept_scaling': 1, 'lr__max_iter': 100, 'lr__multi_class': 'ovr', 'lr__n_jobs': 1, 'lr__penalty': 'l2', 'lr__random_state': 42, 'lr__solver': 'liblinear', 'lr__tol': 0.0001, 'lr__verbose': 0, 'lr__warm_start': False, 'rf__bootstrap': True, 'rf__class_weight': None, 'rf__criterion': 'gini', 'rf__max_depth': None, 'rf__max_features': 'auto', 'rf__max_leaf_nodes': None, 'rf__min_impurity_decrease': 0.0, 'rf__min_impurity_split': None, 'rf__min_samples_leaf': 1, 'rf__min_samples_split': 2, 'rf__min_weight_fraction_leaf': 0.0, 'rf__n_estimators': 10, 'rf__n_jobs': 1, 'rf__oob_score': False, 'rf__random_state': 42, 'rf__verbose': 0, 'rf__warm_start': False, 'by__priors': None} ###Markdown Exercice 3 Optionnel : StackingRemplacer le voting par un modèle logistique (voir exemple 2 cours 1)Vous pouvez utiliser la cross validation ###Code from mlxtend.classifier import StackingClassifier clf1 = KNeighborsClassifier(n_neighbors=1) clf2 = RandomForestClassifier(random_state=1) lr = LogisticRegression() sclf = StackingClassifier(classifiers=[clf1, clf2, gnb_clf], meta_classifier=lr) print('3-fold cross validation:\n') for clf, label in zip([clf1, clf2, gnb_clf, sclf], ['KNN', 'Random Forest', 'Naive Bayes', 'StackingClassifier']): scores = model_selection.cross_val_score(clf, X, y, cv=3, scoring='accuracy') print("Accuracy: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label)) generer_resultats(sclf) ###Output 3-fold cross validation: Accuracy: 0.91 (+/- 0.01) [KNN] Accuracy: 0.91 (+/- 0.06) [Random Forest] Accuracy: 0.92 (+/- 0.03) [Naive Bayes] Accuracy: 0.95 (+/- 0.03) [StackingClassifier] {'kneighborsclassifier': KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=1, n_neighbors=1, p=2, weights='uniform'), 'randomforestclassifier': RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=1, verbose=0, warm_start=False), 'gaussiannb': GaussianNB(priors=None), 'kneighborsclassifier__algorithm': 'auto', 'kneighborsclassifier__leaf_size': 30, 'kneighborsclassifier__metric': 'minkowski', 'kneighborsclassifier__metric_params': None, 'kneighborsclassifier__n_jobs': 1, 'kneighborsclassifier__n_neighbors': 1, 'kneighborsclassifier__p': 2, 'kneighborsclassifier__weights': 'uniform', 'randomforestclassifier__bootstrap': True, 'randomforestclassifier__class_weight': None, 'randomforestclassifier__criterion': 'gini', 'randomforestclassifier__max_depth': None, 'randomforestclassifier__max_features': 'auto', 'randomforestclassifier__max_leaf_nodes': None, 'randomforestclassifier__min_impurity_decrease': 0.0, 'randomforestclassifier__min_impurity_split': None, 'randomforestclassifier__min_samples_leaf': 1, 'randomforestclassifier__min_samples_split': 2, 'randomforestclassifier__min_weight_fraction_leaf': 0.0, 'randomforestclassifier__n_estimators': 10, 'randomforestclassifier__n_jobs': 1, 'randomforestclassifier__oob_score': False, 'randomforestclassifier__random_state': 1, 'randomforestclassifier__verbose': 0, 'randomforestclassifier__warm_start': False, 'gaussiannb__priors': None, 'meta-logisticregression': LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False), 'meta-logisticregression__C': 1.0, 'meta-logisticregression__class_weight': None, 'meta-logisticregression__dual': False, 'meta-logisticregression__fit_intercept': True, 'meta-logisticregression__intercept_scaling': 1, 'meta-logisticregression__max_iter': 100, 'meta-logisticregression__multi_class': 'ovr', 'meta-logisticregression__n_jobs': 1, 'meta-logisticregression__penalty': 'l2', 'meta-logisticregression__random_state': None, 'meta-logisticregression__solver': 'liblinear', 'meta-logisticregression__tol': 0.0001, 'meta-logisticregression__verbose': 0, 'meta-logisticregression__warm_start': False, 'average_probas': False, 'classifiers': [KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=1, n_neighbors=1, p=2, weights='uniform'), RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=1, verbose=0, warm_start=False), GaussianNB(priors=None)], 'meta_classifier': LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False), 'store_train_meta_features': False, 'use_clones': True, 'use_features_in_secondary': False, 'use_probas': False, 'verbose': 0}
AAAI/Learnability/CIN/older/ds2/synthetic_type2_Linear_m_50.ipynb
###Markdown Generate dataset ###Code np.random.seed(12) y = np.random.randint(0,10,5000) idx= [] for i in range(10): print(i,sum(y==i)) idx.append(y==i) x = np.zeros((5000,2)) np.random.seed(12) x[idx[0],:] = np.random.multivariate_normal(mean = [5,5],cov=[[0.1,0],[0,0.1]],size=sum(idx[0])) x[idx[1],:] = np.random.multivariate_normal(mean = [-6,7],cov=[[0.1,0],[0,0.1]],size=sum(idx[1])) x[idx[2],:] = np.random.multivariate_normal(mean = [-5,-4],cov=[[0.1,0],[0,0.1]],size=sum(idx[2])) x[idx[3],:] = np.random.multivariate_normal(mean = [-1,0],cov=[[0.1,0],[0,0.1]],size=sum(idx[3])) x[idx[4],:] = np.random.multivariate_normal(mean = [0,2],cov=[[0.1,0],[0,0.1]],size=sum(idx[4])) x[idx[5],:] = np.random.multivariate_normal(mean = [1,0],cov=[[0.1,0],[0,0.1]],size=sum(idx[5])) x[idx[6],:] = np.random.multivariate_normal(mean = [0,-1],cov=[[0.1,0],[0,0.1]],size=sum(idx[6])) x[idx[7],:] = np.random.multivariate_normal(mean = [0,0],cov=[[0.1,0],[0,0.1]],size=sum(idx[7])) x[idx[8],:] = np.random.multivariate_normal(mean = [-0.5,-0.5],cov=[[0.1,0],[0,0.1]],size=sum(idx[8])) x[idx[9],:] = np.random.multivariate_normal(mean = [0.4,0.2],cov=[[0.1,0],[0,0.1]],size=sum(idx[9])) x[idx[0]][0], x[idx[5]][5] for i in range(10): plt.scatter(x[idx[i],0],x[idx[i],1],label="class_"+str(i)) plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) bg_idx = [ np.where(idx[3] == True)[0], np.where(idx[4] == True)[0], np.where(idx[5] == True)[0], np.where(idx[6] == True)[0], np.where(idx[7] == True)[0], np.where(idx[8] == True)[0], np.where(idx[9] == True)[0]] bg_idx = np.concatenate(bg_idx, axis = 0) bg_idx.shape np.unique(bg_idx).shape x = x - np.mean(x[bg_idx], axis = 0, keepdims = True) np.mean(x[bg_idx], axis = 0, keepdims = True), np.mean(x, axis = 0, keepdims = True) x = x/np.std(x[bg_idx], axis = 0, keepdims = True) np.std(x[bg_idx], axis = 0, keepdims = True), np.std(x, axis = 0, keepdims = True) for i in range(10): plt.scatter(x[idx[i],0],x[idx[i],1],label="class_"+str(i)) plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) foreground_classes = {'class_0','class_1', 'class_2'} background_classes = {'class_3','class_4', 'class_5', 'class_6','class_7', 'class_8', 'class_9'} fg_class = np.random.randint(0,3) fg_idx = np.random.randint(0,m) a = [] for i in range(m): if i == fg_idx: b = np.random.choice(np.where(idx[fg_class]==True)[0],size=1) a.append(x[b]) print("foreground "+str(fg_class)+" present at " + str(fg_idx)) else: bg_class = np.random.randint(3,10) b = np.random.choice(np.where(idx[bg_class]==True)[0],size=1) a.append(x[b]) print("background "+str(bg_class)+" present at " + str(i)) a = np.concatenate(a,axis=0) print(a.shape) print(fg_class , fg_idx) np.reshape(a,(2*m,1)) desired_num = 2000 mosaic_list_of_images =[] mosaic_label = [] fore_idx=[] for j in range(desired_num): np.random.seed(j) fg_class = np.random.randint(0,3) fg_idx = np.random.randint(0,m) a = [] for i in range(m): if i == fg_idx: b = np.random.choice(np.where(idx[fg_class]==True)[0],size=1) a.append(x[b]) # print("foreground "+str(fg_class)+" present at " + str(fg_idx)) else: bg_class = np.random.randint(3,10) b = np.random.choice(np.where(idx[bg_class]==True)[0],size=1) a.append(x[b]) # print("background "+str(bg_class)+" present at " + str(i)) a = np.concatenate(a,axis=0) mosaic_list_of_images.append(np.reshape(a,(2*m,1))) mosaic_label.append(fg_class) fore_idx.append(fg_idx) mosaic_list_of_images = np.concatenate(mosaic_list_of_images,axis=1).T mosaic_list_of_images.shape mosaic_list_of_images.shape, mosaic_list_of_images[0] for j in range(m): print(mosaic_list_of_images[0][2*j:2*j+2]) def create_avg_image_from_mosaic_dataset(mosaic_dataset,labels,foreground_index,dataset_number, m): """ mosaic_dataset : mosaic_dataset contains 9 images 32 x 32 each as 1 data point labels : mosaic_dataset labels foreground_index : contains list of indexes where foreground image is present so that using this we can take weighted average dataset_number : will help us to tell what ratio of foreground image to be taken. for eg: if it is "j" then fg_image_ratio = j/9 , bg_image_ratio = (9-j)/8*9 """ avg_image_dataset = [] cnt = 0 counter = np.zeros(m) #np.array([0,0,0,0,0,0,0,0,0]) for i in range(len(mosaic_dataset)): img = torch.zeros([2], dtype=torch.float64) np.random.seed(int(dataset_number*10000 + i)) give_pref = foreground_index[i] #np.random.randint(0,9) # print("outside", give_pref,foreground_index[i]) for j in range(m): if j == give_pref: img = img + mosaic_dataset[i][2*j:2*j+2]*dataset_number/m #2 is data dim else : img = img + mosaic_dataset[i][2*j:2*j+2]*(m-dataset_number)/((m-1)*m) if give_pref == foreground_index[i] : # print("equal are", give_pref,foreground_index[i]) cnt += 1 counter[give_pref] += 1 else : counter[give_pref] += 1 avg_image_dataset.append(img) print("number of correct averaging happened for dataset "+str(dataset_number)+" is "+str(cnt)) print("the averaging are done as ", counter) return avg_image_dataset , labels , foreground_index avg_image_dataset_1 , labels_1, fg_index_1 = create_avg_image_from_mosaic_dataset(mosaic_list_of_images[0:1000], mosaic_label[0:1000], fore_idx[0:1000] , 1, m) test_dataset , labels , fg_index = create_avg_image_from_mosaic_dataset(mosaic_list_of_images[1000:2000], mosaic_label[1000:2000], fore_idx[1000:2000] , m, m) avg_image_dataset_1 = torch.stack(avg_image_dataset_1, axis = 0) # avg_image_dataset_1 = (avg - torch.mean(avg, keepdims= True, axis = 0)) / torch.std(avg, keepdims= True, axis = 0) # print(torch.mean(avg_image_dataset_1, keepdims= True, axis = 0)) # print(torch.std(avg_image_dataset_1, keepdims= True, axis = 0)) print("=="*40) test_dataset = torch.stack(test_dataset, axis = 0) # test_dataset = (avg - torch.mean(avg, keepdims= True, axis = 0)) / torch.std(avg, keepdims= True, axis = 0) # print(torch.mean(test_dataset, keepdims= True, axis = 0)) # print(torch.std(test_dataset, keepdims= True, axis = 0)) print("=="*40) x1 = (avg_image_dataset_1).numpy() y1 = np.array(labels_1) plt.scatter(x1[y1==0,0], x1[y1==0,1], label='class 0') plt.scatter(x1[y1==1,0], x1[y1==1,1], label='class 1') plt.scatter(x1[y1==2,0], x1[y1==2,1], label='class 2') plt.legend() plt.title("dataset4 CIN with alpha = 1/"+str(m)) x1 = (test_dataset).numpy() / m y1 = np.array(labels) plt.scatter(x1[y1==0,0], x1[y1==0,1], label='class 0') plt.scatter(x1[y1==1,0], x1[y1==1,1], label='class 1') plt.scatter(x1[y1==2,0], x1[y1==2,1], label='class 2') plt.legend() plt.title("test dataset4") test_dataset[0:10]/m test_dataset = test_dataset/m test_dataset[0:10] class MosaicDataset(Dataset): """MosaicDataset dataset.""" def __init__(self, mosaic_list_of_images, mosaic_label): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.mosaic = mosaic_list_of_images self.label = mosaic_label #self.fore_idx = fore_idx def __len__(self): return len(self.label) def __getitem__(self, idx): return self.mosaic[idx] , self.label[idx] #, self.fore_idx[idx] avg_image_dataset_1[0].shape avg_image_dataset_1[0] batch = 200 traindata_1 = MosaicDataset(avg_image_dataset_1, labels_1 ) trainloader_1 = DataLoader( traindata_1 , batch_size= batch ,shuffle=True) testdata_1 = MosaicDataset(avg_image_dataset_1, labels_1 ) testloader_1 = DataLoader( testdata_1 , batch_size= batch ,shuffle=False) testdata_11 = MosaicDataset(test_dataset, labels ) testloader_11 = DataLoader( testdata_11 , batch_size= batch ,shuffle=False) class Whatnet(nn.Module): def __init__(self): super(Whatnet,self).__init__() self.linear1 = nn.Linear(2,3) # self.linear2 = nn.Linear(50,10) # self.linear3 = nn.Linear(10,3) torch.nn.init.xavier_normal_(self.linear1.weight) torch.nn.init.zeros_(self.linear1.bias) def forward(self,x): # x = F.relu(self.linear1(x)) # x = F.relu(self.linear2(x)) x = (self.linear1(x)) return x def calculate_loss(dataloader,model,criter): model.eval() r_loss = 0 with torch.no_grad(): for i, data in enumerate(dataloader, 0): inputs, labels = data inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = model(inputs) loss = criter(outputs, labels) r_loss += loss.item() return r_loss/i def test_all(number, testloader,net): correct = 0 total = 0 out = [] pred = [] with torch.no_grad(): for data in testloader: images, labels = data images, labels = images.to("cuda"),labels.to("cuda") out.append(labels.cpu().numpy()) outputs= net(images) _, predicted = torch.max(outputs.data, 1) pred.append(predicted.cpu().numpy()) total += labels.size(0) correct += (predicted == labels).sum().item() pred = np.concatenate(pred, axis = 0) out = np.concatenate(out, axis = 0) print("unique out: ", np.unique(out), "unique pred: ", np.unique(pred) ) print("correct: ", correct, "total ", total) print('Accuracy of the network on the 1000 test dataset %d: %.2f %%' % (number , 100 * correct / total)) def train_all(trainloader, ds_number, testloader_list): print("--"*40) print("training on data set ", ds_number) torch.manual_seed(12) net = Whatnet().double() net = net.to("cuda") criterion_net = nn.CrossEntropyLoss() optimizer_net = optim.Adam(net.parameters(), lr=0.001 ) #, momentum=0.9) acti = [] loss_curi = [] epochs = 1500 running_loss = calculate_loss(trainloader,net,criterion_net) loss_curi.append(running_loss) print('epoch: [%d ] loss: %.3f' %(0,running_loss)) for epoch in range(epochs): # loop over the dataset multiple times ep_lossi = [] running_loss = 0.0 net.train() for i, data in enumerate(trainloader, 0): # get the inputs inputs, labels = data inputs, labels = inputs.to("cuda"),labels.to("cuda") # zero the parameter gradients optimizer_net.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion_net(outputs, labels) # print statistics running_loss += loss.item() loss.backward() optimizer_net.step() running_loss = calculate_loss(trainloader,net,criterion_net) if(epoch%200 == 0): print('epoch: [%d] loss: %.3f' %(epoch + 1,running_loss)) loss_curi.append(running_loss) #loss per epoch if running_loss<=0.05: print('epoch: [%d] loss: %.3f' %(epoch + 1,running_loss)) break print('Finished Training') correct = 0 total = 0 with torch.no_grad(): for data in trainloader: images, labels = data images, labels = images.to("cuda"), labels.to("cuda") outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 1000 train images: %.2f %%' % ( 100 * correct / total)) for i, j in enumerate(testloader_list): test_all(i+1, j,net) print("--"*40) return loss_curi train_loss_all=[] testloader_list= [ testloader_1, testloader_11] train_loss_all.append(train_all(trainloader_1, 1, testloader_list)) %matplotlib inline for i,j in enumerate(train_loss_all): plt.plot(j,label ="dataset "+str(i+1)) plt.xlabel("Epochs") plt.ylabel("Training_loss") plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) ###Output _____no_output_____
docs/ipynb/03-tutorial-uniaxialanisotropy.ipynb
###Markdown Tutorial 03: Uniaxial anisotropy energy term> Interactive online tutorial:> [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/ubermag/oommfc/master?filepath=docs%2Fipynb%2Findex.ipynb)Uniaxial anisotropy energy density is computed as$$w_\text{a} = -K (\mathbf{m}\cdot\mathbf{u})^{2}$$where $\mathbf{m}$ is the normalised ($|\mathbf{m}|=1$) magnetisation, $K$ is the uniaxial anisotropy constant, and $\mathbf{u}$ is the anisotropy axis. Uniaxial anisotropy energy term tends to align all magnetic moments parallel or antiparallel to the anisotropy axis.In `oommfc`, $\mathbf{m}$ is a part of the magnetisation field `system.m`. Therefore, only uniaxial anisotropy constant $K$ and axis $\mathbf{u}$ should be provided as input parameters to uniquely define the energy term. Both $K$ and $\mathbf{u}$ can be constant in space or spatially varying. Spatially constant $K$ and $\mathbf{u}$Let us start by assembling a simple simple simulation where neither $K$ nor $\mathbf{u}$ vary in space. The sample is a "one-dimensional" chain of magnetic moments. ###Code import discretisedfield as df import micromagneticmodel as mm import oommfc as oc p1 = (-10e-9, 0, 0) p2 = (10e-9, 1e-9, 1e-9) cell = (1e-9, 1e-9, 1e-9) region = df.Region(p1=p1, p2=p2) mesh = df.Mesh(region=region, cell=cell) ###Output _____no_output_____ ###Markdown The mesh is ###Code mesh.k3d() ###Output _____no_output_____ ###Markdown The system has a Hamiltonian, which consists of only uniaxial anisotropy energy term. ###Code K = 1e5 # uniaxial anisotropy constant (J/m**3) u = (0, 0, 1) # uniaxial anisotropy axis system = mm.System(name="uniaxialanisotropy_constant_K_u") system.energy = mm.UniaxialAnisotropy(K=K, u=u) ###Output _____no_output_____ ###Markdown We are going to minimise the system's energy using `oommfc.MinDriver` later. Therefore, we do not have to define the system's dynamics equation. Finally, we need to define the system's magnetisation (`system.m`). We are going to make it random with $M_\text{s}=8\times10^{5} \,\text{Am}^{-1}$ ###Code import random import discretisedfield as df Ms = 8e5 # saturation magnetisation (A/m) def m_fun(pos): return [2 * random.random() - 1 for i in range(3)] system.m = df.Field(mesh, dim=3, value=m_fun, norm=Ms) ###Output _____no_output_____ ###Markdown The magnetisation, we set is ###Code system.m.k3d_vectors(color_field=system.m.z) ###Output _____no_output_____ ###Markdown Now, we can minimise the system's energy by using `oommfc.MinDriver`. ###Code md = oc.MinDriver() md.drive(system) ###Output 2020/03/09 10:50: Running OOMMF (uniaxialanisotropy_constant_K_u.mif) ... (1.0 s) ###Markdown We expect that now all magnetic moments are aligned parallel or antiparallel to the anisotropy axis (in the $z$-direction). ###Code system.m.k3d_vectors(color_field=system.m.z) ###Output _____no_output_____ ###Markdown Spatially varying $\mathbf{K}$There are two different ways how a parameter can be made spatially varying, by using:1. Dictionary2. `discretisedfield.Field` DictionaryIn order to define a parameter using a dictionary, regions must be defined in the mesh. Regions are defined as a dictionary, whose keys are the strings and values are `discretisedfield.Region` objects, which take two corner points of the region as input parameters. ###Code p1 = (-10e-9, 0, 0) p2 = (10e-9, 1e-9, 1e-9) cell = (1e-9, 1e-9, 1e-9) subregions = { "region1": df.Region(p1=(-10e-9, 0, 0), p2=(0, 1e-9, 1e-9)), "region2": df.Region(p1=(0, 0, 0), p2=(10e-9, 1e-9, 1e-9)), } region = df.Region(p1=p1, p2=p2) mesh = df.Mesh(region=region, cell=cell, subregions=subregions) mesh.k3d_subregions() ###Output _____no_output_____ ###Markdown Let us say that there is no uniaxial anisotropy ($K=0$) in region 1, whereas in region 2 it is $K=10^{5} \,\text{Jm}^{-3}$. $\mathbf{u}$ is in the $z$-direction. `K` is now defined as a dictionary: ###Code K = {"region1": 0, "region2": 1e5} ###Output _____no_output_____ ###Markdown The system object is ###Code system = mm.System(name="uniaxialanisotropy_dict_K") system.energy = mm.UniaxialAnisotropy(K=K, u=u) system.m = df.Field(mesh, dim=3, value=m_fun, norm=Ms) ###Output _____no_output_____ ###Markdown Its magnetisation is ###Code system.m.k3d_vectors(color_field=system.m.z) ###Output _____no_output_____ ###Markdown After we minimise the energy ###Code md.drive(system) ###Output 2020/03/09 10:50: Running OOMMF (uniaxialanisotropy_dict_K.mif) ... (1.0 s) ###Markdown The magnetisation is as we expected. ###Code system.m.k3d_vectors(color_field=system.m.z) ###Output _____no_output_____ ###Markdown `discretisedfield.Field`Let us define the spatailly varying uniaxial anisotropy, so that$\mathbf{u}(x, y, z) = \left\{\begin{array}{ll}(0, 0, 1) & x \le 0 \\(1, 0, 0) & x > 0 \\\end{array}\right. $The value of `u` for the spatially varying anisotropy is set using a Python function. ###Code def u_fun(pos): x, y, z = pos if x <= 0: return (0, 0, 1) else: return (1, 0, 0) ###Output _____no_output_____ ###Markdown The uniaxial anisotropy parameters are ###Code K = 1e5 u = df.Field(mesh, dim=3, value=u_fun) ###Output _____no_output_____ ###Markdown The system is ###Code system = mm.System(name="uniaxialanisotropy_field_u") system.energy = mm.UniaxialAnisotropy(K=K, u=u) system.m = df.Field(mesh, dim=3, value=m_fun, norm=Ms) ###Output _____no_output_____ ###Markdown and its magnetisation is ###Code system.m.k3d_vectors(color_field=system.m.z) ###Output _____no_output_____ ###Markdown After the energy minimisation, the magnetisation is: ###Code md.drive(system) system.m.k3d_vectors(color_field=system.m.z) ###Output 2020/03/09 10:50: Running OOMMF (uniaxialanisotropy_field_u.mif) ... (1.0 s) ###Markdown Tutorial 03: Uniaxial anisotropy energy termUniaxial anisotropy energy density is computed as$$w_\text{ua} = -K (\mathbf{m}\cdot\mathbf{u})^{2}$$where $\mathbf{m}$ is the normalised ($|\mathbf{m}|=1$) magnetisation, $K$ is the uniaxial anisotropy constant, and $\mathbf{u}$ is the anisotropy axis. Uniaxial anisotropy energy term tends to align all magnetic moments parallel or antiparallel to the anisotropy axis.In `oommfc`, $\mathbf{m}$ is a part of the magnetisation field `system.m`. Therefore, only uniaxial anisotropy constant $K$ and axis $\mathbf{u}$ should be provided as input parameters to uniquely define the energy term. Both $K$ and $\mathbf{u}$ can be constant in space or spatially varying. Spatially constant $K$ and $\mathbf{u}$Let us start by assembling a simple simple simulation where neither $K$ nor $\mathbf{u}$ vary in space. The sample is a "one-dimensional" chain of magnetic moments. ###Code import oommfc as oc import discretisedfield as df import micromagneticmodel as mm p1 = (-10e-9, 0, 0) p2 = (10e-9, 1e-9, 1e-9) cell = (1e-9, 1e-9, 1e-9) region = df.Region(p1=p1, p2=p2) mesh = df.Mesh(region=region, cell=cell) ###Output _____no_output_____ ###Markdown The mesh is ###Code mesh.k3d() ###Output _____no_output_____ ###Markdown The system has a Hamiltonian, which consists of only uniaxial anisotropy energy term. ###Code K = 1e5 # uniaxial anisotropy constant (J/m**3) u = (0, 0, 1) # uniaxial anisotropy axis system = mm.System(name='uniaxialanisotropy_constant_K_u') system.energy = mm.UniaxialAnisotropy(K=K, u=u) ###Output _____no_output_____ ###Markdown We are going to minimise the system's energy using `oommfc.MinDriver` later. Therefore, we do not have to define the system's dynamics equation. Finally, we need to define the system's magnetisation (`system.m`). We are going to make it random with $M_\text{s}=8\times10^{5} \,\text{Am}^{-1}$ ###Code import random import discretisedfield as df Ms = 8e5 # saturation magnetisation (A/m) def m_fun(pos): return [2*random.random()-1 for i in range(3)] system.m = df.Field(mesh, dim=3, value=m_fun, norm=Ms) ###Output _____no_output_____ ###Markdown The magnetisation, we set is ###Code system.m.k3d_vector(color_field=system.m.z) ###Output _____no_output_____ ###Markdown Now, we can minimise the system's energy by using `oommfc.MinDriver`. ###Code md = oc.MinDriver() md.drive(system) ###Output Running OOMMF (ExeOOMMFRunner) [2020/07/10 10:17]... (2.4 s) ###Markdown We expect that now all magnetic moments are aligned parallel or antiparallel to the anisotropy axis (in the $z$-direction). ###Code system.m.k3d_vector(color_field=system.m.z) ###Output _____no_output_____ ###Markdown Spatially varying $\mathbf{K}$There are two different ways how a parameter can be made spatially varying, by using:1. Dictionary2. `discretisedfield.Field` DictionaryIn order to define a parameter using a dictionary, regions must be defined in the mesh. Regions are defined as a dictionary, whose keys are the strings and values are `discretisedfield.Region` objects, which take two corner points of the region as input parameters. ###Code p1 = (-10e-9, 0, 0) p2 = (10e-9, 1e-9, 1e-9) cell = (1e-9, 1e-9, 1e-9) subregions = {'region1': df.Region(p1=(-10e-9, 0, 0), p2=(0, 1e-9, 1e-9)), 'region2': df.Region(p1=(0, 0, 0), p2=(10e-9, 1e-9, 1e-9))} region = df.Region(p1=p1, p2=p2) mesh = df.Mesh(region=region, cell=cell, subregions=subregions) mesh.k3d_subregions() ###Output _____no_output_____ ###Markdown Let us say that there is no uniaxial anisotropy ($K=0$) in region 1, whereas in region 2 it is $K=10^{5} \,\text{Jm}^{-3}$. $\mathbf{u}$ is in the $z$-direction. `K` is now defined as a dictionary: ###Code K = {'region1': 0, 'region2': 1e5} ###Output _____no_output_____ ###Markdown The system object is ###Code system = mm.System(name='uniaxialanisotropy_dict_K') system.energy = mm.UniaxialAnisotropy(K=K, u=u) system.m = df.Field(mesh, dim=3, value=m_fun, norm=Ms) ###Output _____no_output_____ ###Markdown Its magnetisation is ###Code system.m.k3d_vector(color_field=system.m.z) ###Output _____no_output_____ ###Markdown After we minimise the energy ###Code md.drive(system) ###Output Running OOMMF (ExeOOMMFRunner) [2020/07/10 10:17]... (2.8 s) ###Markdown The magnetisation is as we expected. ###Code system.m.k3d_vector(color_field=system.m.z) ###Output _____no_output_____ ###Markdown `discretisedfield.Field`Let us define the spatailly varying uniaxial anisotropy, so that$\mathbf{u}(x, y, z) = \left\{\begin{array}{ll}(0, 0, 1) & x \le 0 \\(1, 0, 0) & x > 0 \\\end{array}\right. $The value of `u` for the spatially varying anisotropy is set using a Python function. ###Code def u_fun(pos): x, y, z = pos if x <= 0: return (0, 0, 1) else: return (1, 0, 0) ###Output _____no_output_____ ###Markdown The uniaxial anisotropy parameters are ###Code K = 1e5 u = df.Field(mesh, dim=3, value=u_fun) ###Output _____no_output_____ ###Markdown The system is ###Code system = mm.System(name='uniaxialanisotropy_field_u') system.energy = mm.UniaxialAnisotropy(K=K, u=u) system.m = df.Field(mesh, dim=3, value=m_fun, norm=Ms) ###Output _____no_output_____ ###Markdown and its magnetisation is ###Code system.m.k3d_vector(color_field=system.m.z) ###Output _____no_output_____ ###Markdown After the energy minimisation, the magnetisation is: ###Code md.drive(system) system.m.k3d_vector(color_field=system.m.z) ###Output Running OOMMF (ExeOOMMFRunner) [2020/07/10 10:17]... (2.7 s) ###Markdown Higher-order uniaxial anisotropyIn order to define higher-order anisotropy term:$$w_\text{ua} = -K_{1} (\mathbf{m}\cdot\mathbf{u})^{2} - K_{2} (\mathbf{m}\cdot\mathbf{u})^{4}$$anisotropy constants `K1` and `K2` must be passed. Similar to previous example, all parameters (`K1`, `K2`, and `u`) can be spatially varying (dictionary or field). ###Code K1 = 1e5 K2 = 1e3 u = df.Field(mesh, dim=3, value=u_fun) system = mm.System(name='uniaxialanisotropy_higher_order') system.energy = mm.UniaxialAnisotropy(K1=K1, K2=K2, u=u) system.m = df.Field(mesh, dim=3, value=m_fun, norm=Ms) md.drive(system) system.m.k3d_vector(color_field=system.m.z) ###Output Running OOMMF (ExeOOMMFRunner) [2020/07/10 10:17]... (2.4 s)
deep-learning-v2-pytorch/recurrent-neural-networks/time-series/Simple_RNN.ipynb
###Markdown Simple RNNIn ths notebook, we're going to train a simple RNN to do **time-series prediction**. Given some set of input data, it should be able to generate a prediction for the next time step!> * First, we'll create our data* Then, define an RNN in PyTorch* Finally, we'll train our network and see how it performs Import resources and create data ###Code import torch from torch import nn import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=(8,5)) # how many time steps/data pts are in one batch of data seq_length = 20 # generate evenly spaced data pts time_steps = np.linspace(0, np.pi, seq_length + 1) data = np.sin(time_steps) data.resize((seq_length + 1, 1)) # size becomes (seq_length+1, 1), adds an input_size dimension x = data[:-1] # all but the last piece of data y = data[1:] # all but the first # display the data plt.plot(time_steps[1:], x, 'r.', label='input, x') # x plt.plot(time_steps[1:], y, 'b.', label='target, y') # y plt.legend(loc='best') plt.show() ###Output _____no_output_____ ###Markdown --- Define the RNNNext, we define an RNN in PyTorch. We'll use `nn.RNN` to create an RNN layer, then we'll add a last, fully-connected layer to get the output size that we want. An RNN takes in a number of parameters:* **input_size** - the size of the input* **hidden_dim** - the number of features in the RNN output and in the hidden state* **n_layers** - the number of layers that make up the RNN, typically 1-3; greater than 1 means that you'll create a stacked RNN* **batch_first** - whether or not the input/output of the RNN will have the batch_size as the first dimension (batch_size, seq_length, hidden_dim)Take a look at the [RNN documentation](https://pytorch.org/docs/stable/nn.htmlrnn) to read more about recurrent layers. ###Code class RNN(nn.Module): def __init__(self, input_size, output_size, hidden_dim, n_layers): super(RNN, self).__init__() self.hidden_dim=hidden_dim # define an RNN with specified parameters # batch_first means that the first dim of the input and output will be the batch_size self.rnn = nn.RNN(input_size, hidden_dim, n_layers, batch_first=True) # last, fully-connected layer self.fc = nn.Linear(hidden_dim, output_size) def forward(self, x, hidden): # x (batch_size, seq_length, input_size) # hidden (n_layers, batch_size, hidden_dim) # r_out (batch_size, time_step, hidden_size) batch_size = x.size(0) # get RNN outputs r_out, hidden = self.rnn(x, hidden) # shape output to be (batch_size*seq_length, hidden_dim) r_out = r_out.view(-1, self.hidden_dim) # get final output output = self.fc(r_out) return output, hidden ###Output _____no_output_____ ###Markdown Check the input and output dimensionsAs a check that your model is working as expected, test out how it responds to input data. ###Code # test that dimensions are as expected test_rnn = RNN(input_size=1, output_size=1, hidden_dim=10, n_layers=2) # generate evenly spaced, test data pts time_steps = np.linspace(0, np.pi, seq_length) data = np.sin(time_steps) data.resize((seq_length, 1)) test_input = torch.Tensor(data).unsqueeze(0) # give it a batch_size of 1 as first dimension print('Input size: ', test_input.size()) # test out rnn sizes test_out, test_h = test_rnn(test_input, None) print('Output size: ', test_out.size()) print('Hidden state size: ', test_h.size()) ###Output Input size: torch.Size([1, 20, 1]) Output size: torch.Size([20, 1]) Hidden state size: torch.Size([2, 1, 10]) ###Markdown --- Training the RNNNext, we'll instantiate an RNN with some specified hyperparameters. Then train it over a series of steps, and see how it performs. ###Code # decide on hyperparameters input_size=1 output_size=1 hidden_dim=32 n_layers=1 # instantiate an RNN rnn = RNN(input_size, output_size, hidden_dim, n_layers) print(rnn) ###Output RNN( (rnn): RNN(1, 32, batch_first=True) (fc): Linear(in_features=32, out_features=1, bias=True) ) ###Markdown Loss and OptimizationThis is a regression problem: can we train an RNN to accurately predict the next data point, given a current data point?>* The data points are coordinate values, so to compare a predicted and ground_truth point, we'll use a regression loss: the mean squared error.* It's typical to use an Adam optimizer for recurrent models. ###Code # MSE loss and Adam optimizer with a learning rate of 0.01 criterion = nn.MSELoss() optimizer = torch.optim.Adam(rnn.parameters(), lr=0.01) ###Output _____no_output_____ ###Markdown Defining the training functionThis function takes in an rnn, a number of steps to train for, and returns a trained rnn. This function is also responsible for displaying the loss and the predictions, every so often. Hidden StatePay close attention to the hidden state, here:* Before looping over a batch of training data, the hidden state is initialized* After a new hidden state is generated by the rnn, we get the latest hidden state, and use that as input to the rnn for the following steps ###Code # train the RNN def train(rnn, n_steps, print_every): # initialize the hidden state hidden = None for batch_i, step in enumerate(range(n_steps)): # defining the training data time_steps = np.linspace(step * np.pi, (step+1)*np.pi, seq_length + 1) data = np.sin(time_steps) data.resize((seq_length + 1, 1)) # input_size=1 x = data[:-1] y = data[1:] # convert data into Tensors x_tensor = torch.Tensor(x).unsqueeze(0) # unsqueeze gives a 1, batch_size dimension y_tensor = torch.Tensor(y) # outputs from the rnn prediction, hidden = rnn(x_tensor, hidden) ## Representing Memory ## # make a new variable for hidden and detach the hidden state from its history # this way, we don't backpropagate through the entire history hidden = hidden.data # calculate the loss loss = criterion(prediction, y_tensor) # zero gradients optimizer.zero_grad() # perform backprop and update weights loss.backward() optimizer.step() # display loss and predictions if batch_i%print_every == 0: print('Loss: ', loss.item()) plt.plot(time_steps[1:], x, 'r.') # input plt.plot(time_steps[1:], prediction.data.numpy().flatten(), 'b.') # predictions plt.show() return rnn # train the rnn and monitor results n_steps = 75 print_every = 15 trained_rnn = train(rnn, n_steps, print_every) ###Output Loss: 0.6791473627090454
site/en-snapshot/agents/tutorials/2_environments_tutorial.ipynb
###Markdown Copyright 2018 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install tf-agents !pip install 'gym==0.10.11' from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" self._current_time_step = self._step(action) return self._current_time_step ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the python environments into TFEnvs allows tensorflow to parellalize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Copyright 2018 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install tf-agents !pip install gym from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the python environments into TFEnvs allows tensorflow to parallelize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Copyright 2018 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install tf-agents !pip install 'gym==0.10.11' from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" self._current_time_step = self._step(action) return self._current_time_step ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the python environments into TFEnvs allows tensorflow to parallelize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Copyright 2021 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install "gym>=0.21.0" !pip install tf-agents from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all Python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a Python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v1') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular Python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from Python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the Python environments into TFEnvs allows tensorflow to parallelize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Copyright 2018 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install tf-agents !pip install 'gym==0.10.11' from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" self._current_time_step = self._step(action) return self._current_time_step ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the python environments into TFEnvs allows tensorflow to parellalize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Copyright 2018 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install tf-agents !pip install 'gym==0.10.11' from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" self._current_time_step = self._step(action) return self._current_time_step ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the python environments into TFEnvs allows tensorflow to parellalize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Copyright 2018 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install --pre tf-agents[reverb] !pip install 'gym==0.10.11' from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" self._current_time_step = self._step(action) return self._current_time_step ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the python environments into TFEnvs allows tensorflow to parellalize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Copyright 2018 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install tf-agents !pip install gym from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all Python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a Python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular Python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from Python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the Python environments into TFEnvs allows tensorflow to parallelize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Copyright 2018 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install tf-agents !pip install 'gym==0.10.11' from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" self._current_time_step = self._step(action) return self._current_time_step ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the python environments into TFEnvs allows tensorflow to parellalize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____ ###Markdown Copyright 2021 The TF-Agents Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Environments View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.Let us look at Python environments first. TensorFlow environments follow a very similar API. Setup If you haven't installed tf-agents or gym yet, run: ###Code !pip install tf-agents from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ###Output _____no_output_____ ###Markdown Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.The interface that all Python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ###Code class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" ###Output _____no_output_____ ###Markdown In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. Using Standard EnvironmentsTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ###Code environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ###Output _____no_output_____ ###Markdown So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ###Code action = np.array(1, dtype=np.int32) time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ###Output _____no_output_____ ###Markdown Creating your own Python EnvironmentFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.Let's say we want to train an agent to play the following (Black Jack inspired) card game:1. The game is played using an infinite deck of cards numbered 1...10.2. At every turn the agent can do 2 things: get a new random card, or stop the current round.3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.An environment that represents the game could look like this:1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.2. Observations: Sum of the cards in the current round.3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ###Code class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ###Output _____no_output_____ ###Markdown Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ###Code environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ###Output _____no_output_____ ###Markdown Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ###Code get_new_card_action = np.array(0, dtype=np.int32) end_round_action = np.array(1, dtype=np.int32) environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ###Output _____no_output_____ ###Markdown Environment WrappersAn environment wrapper takes a Python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.Some common wrappers can be found in `environments/wrappers.py`. For example:1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.3. `TimeLimit`: Terminates the episode after a fixed number of steps. Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ###Code env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ###Output _____no_output_____ ###Markdown The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular Python environment. TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from Python envs in a couple of ways:* They generate tensor objects instead of arrays* TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the Python environments into TFEnvs allows tensorflow to parallelize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ###Code class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ###Output _____no_output_____ ###Markdown The `current_time_step()` method returns the current time_step and initializes the environment if needed.The `reset()` method forces a reset in the environment and returns the current_step.If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.For now, let us look at how `TFEnvironments` are created. Creating your own TensorFlow EnvironmentThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ###Output _____no_output_____ ###Markdown Note the specs are now of type: `(Bounded)TensorSpec`. Usage Examples Simple Example ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ###Output _____no_output_____ ###Markdown Whole Episodes ###Code env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random.uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) time_step = tf_env.reset() num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ###Output _____no_output_____
notebooks/Data_Fetching.ipynb
###Markdown Step 1: Load the Dataset from MNistLet us first load the source data from the source and store it locally! ###Code import os import tarfile import wget HOUSING_DATA_DOWNLOAD_URL = 'https://raw.githubusercontent.com/ageron/handson-ml/master/datasets/housing/housing.tgz' HOUSING_DATA_LOCAL_PATH = os.path.join("data", "housing") def fetch_housing_data(from_path=HOUSING_DATA_DOWNLOAD_URL, to_path=HOUSING_DATA_LOCAL_PATH): if not os.path.isdir(to_path): os.makedirs(to_path) wget.download(from_path, to_path) tarfile.open(topath/'housing.tgz').extractall(to_path) os.remove(topath/'housing.tgz') ###Output _____no_output_____
Experiments/6. Resample noise.ipynb
###Markdown ResampleReample ShipsEar into 32000, so we can train with deep ship ###Code print(torch.__version__) print(torchaudio.__version__) # ShipsEar Dataset path = Path('shipsEar_AUDIOS/') dest = Path('shipsEarRe/') fns = get_files(path,'.wav') fns ### Pytorch transform kernel sample_rate = 44100 resample_rate = 32000 krn = Resample( sample_rate, resample_rate, lowpass_filter_width=64, rolloff=0.9475937167399596, resampling_method="kaiser_window", beta=14.769656459379492) def convert(p: Path): waveform,sr = torchaudio.load(p) if sr != sample_rate: return print(p) ### kaiser_best resampled_waveform = krn(waveform) torchaudio.save(dest/p, resampled_waveform, resample_rate) Path(PurePath(dest/fns[0]).parent).mkdir(exist_ok=True) for p in fns: convert(p) ###Output shipsEar_AUDIOS/38__19_07_13_Arroios_Sale_2entran.wav shipsEar_AUDIOS/41__19_07_13_MiñoUno_Entra.wav shipsEar_AUDIOS/39__19_07_13_lanchaMotora_Entra.wav shipsEar_AUDIOS/43__19_07_13_PirataDeCies_Llega_Interf.wav shipsEar_AUDIOS/42__19_07_13_PirataCies_Sale.wav shipsEar_AUDIOS/45__19_07_13_yate_Sale.wav shipsEar_AUDIOS/40__19_07_13_MarDeCangas_Llega_Interf.wav
notebooks/.ipynb_checkpoints/yoga_pose_classification-checkpoint.ipynb
###Markdown Identifying Yoga Poses We've collected a few samples for each pose we'd like to categorize, and we need to learn how to identify which pose the user is in. We first used our tflite convolutional pose machine model to obtain a graphical representation of the poses we collected. This will produce a 28 point array of the various body part coordinates in each sample. We'll save this array along with its correct pose label to construct a dataset. First, let's import all the libraries we'll be using. ###Code %matplotlib inline import pickle import multiprocessing import numpy as np import pandas as pd import xgboost as xgb import matplotlib.pyplot as plt from xgboost import XGBClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix ###Output _____no_output_____ ###Markdown Let's load our data and take a peak at what those samples look like. Format the data so we can feed it to a model. ###Code dataset = pd.read_csv('poses.csv', header = None )#(index_col=0) dataset # Spliting the points and the labels #with file poses_standard.csv 36 column #X = dataset.iloc[:, 2:-1].values #y = dataset.iloc[:, 36].values #with file poses 38 column X = dataset.iloc[:, 2:-1].values y = dataset.iloc[:, 36].values X,y # And split the data into appropriate data sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20) X_test X_train.shape,y_train.shape,X_test.shape,y_test.shape class_names = list(set(y)) num_class = len(class_names) cores = multiprocessing.cpu_count() num_class ###Output _____no_output_____ ###Markdown Our data is ready to feed it to a model! Our first approach will be to classify which pose the user is currently in. If the user is not in the correct pose, we'll give them some advice on how to execute it. As we progress, we'll want to think about how to evaluate the user's pose, ie. how well are they execuring the pose. But for now, let's just determine if a user is in the right pose.We'll try XGBoost. This algorithm is an implementation of gradient boosted decision trees. It ensembles many decision trees into one model - making it more accurate as a collection of trees.XGBoost is very fast and it has more parameters to tune to improve the model. Feel free to pay with the learning_rate, n_estimators, etc to get better results. Also keep in mind that more data never hurts. ###Code clf = XGBClassifier(max_depth=6, learning_rate=0.01, n_estimators=500, objective='multi:softmax', n_jobs=cores, num_class=num_class) from sklearn.metrics import accuracy_score model = XGBClassifier() model.fit(X_train, y_train) # make predictions for test data y_pred = model.predict(X_test) predictions = [value for value in y_pred] # evaluate predictions accuracy = accuracy_score(y_test, predictions) clf.fit(X_train, y_train) preds = clf.predict(X_test) predictions = [value for value in preds] predictions ###Output /home/tommy/anaconda3/envs/inf/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1]. warnings.warn(label_encoder_deprecation_msg, UserWarning) ###Markdown We can see how well the model is grouping samples by printing the confusion matrix of the model. The confusion matrix will show us how often the model gets confused about a sample and misclassifies it AND to what it misclassifies.We'll also look at the classification report which will give us the recall and precision among other stats for each label ###Code from sklearn.metrics import confusion_matrix, classification_report conf_matrix = confusion_matrix(y_test, preds) print(conf_matrix) class_report = classification_report(y_test, preds) print(class_report) preds = clf.predict(X_test[[0]]) predictions = [value for value in preds] predictions ###Output _____no_output_____ ###Markdown And to get a better view let's graph the confusion matrix. ###Code import itertools from sklearn.metrics import plot_confusion_matrix def plot_confusion_matrix(cm, classes, normalize=True, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm, interpolation='nearest', cmap=cmap, aspect='auto') plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, rotation=45) plt.yticks(tick_marks) plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout() plot_confusion_matrix(conf_matrix, classes=sorted(class_names), normalize=True, title='Normalized confusion matrix') plt.show() print('Classes: ', sorted(class_names)) ###Output _____no_output_____ ###Markdown Dark blue on the diagonal is what we're aiming for. We can see the model is really good at predicting tree_pose but warrior_1 gets confused with crescent_lunge and warrior_3 poses. However, this is a great start classifying a handful of distinct poses. We want to save the model to file so we can run inference while our virtual instructor is running. ###Code filename = '../models/yoga_poses.sav' pickle.dump(clf, open(filename, 'wb')) xgb_model_loaded = pickle.load(open(filename, "rb")) preds = xgb_model_loaded.predict(X_test[[0]]) predictions = [value for value in preds] predictions X_test[[0]] abc = np.array([[318, 115 , 325, 109 , 311, 108 , 333, 112 , 301, 110 , 345, 155 , 282, 149 , 351, 206 , 265, 194 , 342, 245 , 267, 238 , 321, 254 , 285, 252 , 313, 322 , 279, 323 , 300, 382 , 276, 383]]) abc preds = xgb_model_loaded.predict(abc) preds ###Output _____no_output_____
jupyter/d2l-java/chapter_multilayer-perceptrons/mlp-djl.ipynb
###Markdown Concise Implementation of Multilayer Perceptron:label:`sec_mlp_djl`As you might expect, by relying on the DJL library,we can implement MLPs even more concisely. Let's setup the relevant libraries first. ###Code %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/ %maven ai.djl:api:0.7.0-SNAPSHOT %maven ai.djl:model-zoo:0.7.0-SNAPSHOT %maven ai.djl:basicdataset:0.7.0-SNAPSHOT %maven org.slf4j:slf4j-api:1.7.26 %maven org.slf4j:slf4j-simple:1.7.26 %maven ai.djl.mxnet:mxnet-engine:0.7.0-SNAPSHOT %maven ai.djl.mxnet:mxnet-native-auto:1.7.0-a %%loadFromPOM <dependency> <groupId>tech.tablesaw</groupId> <artifactId>tablesaw-jsplot</artifactId> <version>0.30.4</version> </dependency> %load ../utils/plot-utils.ipynb import java.nio.file.*; import ai.djl.Device; import ai.djl.*; import ai.djl.metric.*; import ai.djl.ndarray.*; import ai.djl.ndarray.types.*; import ai.djl.ndarray.index.*; import ai.djl.nn.*; import ai.djl.nn.core.*; import ai.djl.training.*; import ai.djl.training.initializer.*; import ai.djl.training.loss.*; import ai.djl.training.listener.*; import ai.djl.training.evaluator.*; import ai.djl.training.optimizer.*; import ai.djl.training.optimizer.learningrate.*; import ai.djl.training.dataset.*; import ai.djl.util.*; import java.util.Random; import java.util.stream.LongStream; import ai.djl.basicdataset.FashionMnist; import ai.djl.training.dataset.Dataset; import tech.tablesaw.api.*; import tech.tablesaw.plotly.api.*; import tech.tablesaw.plotly.components.*; import tech.tablesaw.plotly.Plot; import tech.tablesaw.plotly.components.Figure; import org.apache.commons.lang3.ArrayUtils; ###Output _____no_output_____ ###Markdown The ModelAs compared to our gluon implementation of softmax regression implementation(:numref:`sec_softmax_gluon`),the only difference is that we add *two* `Linear` (fully-connected) layers (previously, we added *one*).The first is our hidden layer, which contains *256* hidden unitsand applies the ReLU activation function.The second is our output layer. ###Code SequentialBlock net = new SequentialBlock(); net.add(Blocks.batchFlattenBlock(784)); net.add(Linear.builder().setOutChannels(256).build()); net.add(Activation::relu); net.add(Linear.builder().setOutChannels(10).build()); net.setInitializer(new NormalInitializer()); ###Output _____no_output_____ ###Markdown Note that DJL, as usual, automaticallyinfers the missing input dimensions to each layer.The training loop is *exactly* the sameas when we implemented softmax regression.This modularity enables us to separate matters concerning the model architecturefrom orthogonal considerations. ###Code int batchSize = 256; int numEpochs = 10; double[] trainLoss; double[] testAccuracy; double[] epochCount; double[] trainAccuracy; trainLoss = new double[numEpochs]; trainAccuracy = new double[numEpochs]; testAccuracy = new double[numEpochs]; epochCount = new double[numEpochs]; FashionMnist trainIter = FashionMnist.builder() .optUsage(Dataset.Usage.TRAIN) .setSampling(batchSize, true) .build(); FashionMnist testIter = FashionMnist.builder() .optUsage(Dataset.Usage.TEST) .setSampling(batchSize, true) .build(); trainIter.prepare(); testIter.prepare(); for(int i = 0; i < epochCount.length; i++) { epochCount[i] = (i + 1); } Map<String, double[]> evaluatorMetrics = new HashMap<>(); LearningRateTracker lrt = LearningRateTracker.fixedLearningRate(0.5f); Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build(); Loss loss = Loss.softmaxCrossEntropyLoss(); DefaultTrainingConfig config = new DefaultTrainingConfig(loss) .optOptimizer(sgd) // Optimizer (loss function) .addEvaluator(new Accuracy()) // Model Accuracy .addTrainingListeners(TrainingListener.Defaults.basic()); // Logging try (Model model = Model.newInstance("mlp")) { model.setBlock(net); try (Trainer trainer = model.newTrainer(config)) { trainer.initialize(new Shape(1, 784)); trainer.setMetrics(new Metrics()); EasyTrain.fit(trainer, numEpochs, trainIter, testIter); // collect results from evaluators Metrics metrics = trainer.getMetrics(); trainer.getEvaluators().stream() .forEach(evaluator -> { evaluatorMetrics.put("train_epoch_" + evaluator.getName(), metrics.getMetric("train_epoch_" + evaluator.getName()).stream() .mapToDouble(x -> x.getValue().doubleValue()).toArray()); evaluatorMetrics.put("validate_epoch_" + evaluator.getName(), metrics.getMetric("validate_epoch_" + evaluator.getName()).stream() .mapToDouble(x -> x.getValue().doubleValue()).toArray()); }); } } trainLoss = evaluatorMetrics.get("train_epoch_SoftmaxCrossEntropyLoss"); trainAccuracy = evaluatorMetrics.get("train_epoch_Accuracy"); testAccuracy = evaluatorMetrics.get("validate_epoch_Accuracy"); String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length]; Arrays.fill(lossLabel, 0, trainLoss.length, "test acc"); Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, "train acc"); Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length, trainLoss.length + testAccuracy.length + trainAccuracy.length, "train loss"); Table data = Table.create("Data").addColumns( DoubleColumn.create("epochCount", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))), DoubleColumn.create("loss", ArrayUtils.addAll(testAccuracy , ArrayUtils.addAll(trainAccuracy, trainLoss))), StringColumn.create("lossLabel", lossLabel) ); render(LinePlot.create("", data, "epochCount", "loss", "lossLabel"),"text/html"); ###Output _____no_output_____ ###Markdown Concise Implementation of Multilayer Perceptron:label:`sec_mlp_djl`As you might expect, by relying on the DJL library,we can implement MLPs even more concisely. Let's setup the relevant libraries first. ###Code %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/ %maven ai.djl:api:0.7.0-SNAPSHOT %maven ai.djl:model-zoo:0.7.0-SNAPSHOT %maven ai.djl:basicdataset:0.7.0-SNAPSHOT %maven org.slf4j:slf4j-api:1.7.26 %maven org.slf4j:slf4j-simple:1.7.26 %maven ai.djl.mxnet:mxnet-engine:0.7.0-SNAPSHOT %maven ai.djl.mxnet:mxnet-native-auto:1.7.0-b %%loadFromPOM <dependency> <groupId>tech.tablesaw</groupId> <artifactId>tablesaw-jsplot</artifactId> <version>0.30.4</version> </dependency> %load ../utils/plot-utils.ipynb import java.nio.file.*; import ai.djl.Device; import ai.djl.*; import ai.djl.metric.*; import ai.djl.ndarray.*; import ai.djl.ndarray.types.*; import ai.djl.ndarray.index.*; import ai.djl.nn.*; import ai.djl.nn.core.*; import ai.djl.training.*; import ai.djl.training.initializer.*; import ai.djl.training.loss.*; import ai.djl.training.listener.*; import ai.djl.training.evaluator.*; import ai.djl.training.optimizer.*; import ai.djl.training.tracker.*; import ai.djl.training.dataset.*; import ai.djl.util.*; import java.util.Random; import java.util.stream.LongStream; import ai.djl.basicdataset.FashionMnist; import ai.djl.training.dataset.Dataset; import tech.tablesaw.api.*; import tech.tablesaw.plotly.api.*; import tech.tablesaw.plotly.components.*; import tech.tablesaw.plotly.Plot; import tech.tablesaw.plotly.components.Figure; import org.apache.commons.lang3.ArrayUtils; ###Output _____no_output_____ ###Markdown The ModelAs compared to our gluon implementation of softmax regression implementation(:numref:`sec_softmax_gluon`),the only difference is that we add *two* `Linear` (fully-connected) layers (previously, we added *one*).The first is our hidden layer, which contains *256* hidden unitsand applies the ReLU activation function.The second is our output layer. ###Code SequentialBlock net = new SequentialBlock(); net.add(Blocks.batchFlattenBlock(784)); net.add(Linear.builder().setUnits(256).build()); net.add(Activation::relu); net.add(Linear.builder().setUnits(10).build()); net.setInitializer(new NormalInitializer()); ###Output _____no_output_____ ###Markdown Note that DJL, as usual, automaticallyinfers the missing input dimensions to each layer.The training loop is *exactly* the sameas when we implemented softmax regression.This modularity enables us to separate matters concerning the model architecturefrom orthogonal considerations. ###Code int batchSize = 256; int numEpochs = 10; double[] trainLoss; double[] testAccuracy; double[] epochCount; double[] trainAccuracy; trainLoss = new double[numEpochs]; trainAccuracy = new double[numEpochs]; testAccuracy = new double[numEpochs]; epochCount = new double[numEpochs]; FashionMnist trainIter = FashionMnist.builder() .optUsage(Dataset.Usage.TRAIN) .setSampling(batchSize, true) .build(); FashionMnist testIter = FashionMnist.builder() .optUsage(Dataset.Usage.TEST) .setSampling(batchSize, true) .build(); trainIter.prepare(); testIter.prepare(); for(int i = 0; i < epochCount.length; i++) { epochCount[i] = (i + 1); } Map<String, double[]> evaluatorMetrics = new HashMap<>(); Tracker lrt = Tracker.fixed(0.5f); Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build(); Loss loss = Loss.softmaxCrossEntropyLoss(); DefaultTrainingConfig config = new DefaultTrainingConfig(loss) .optOptimizer(sgd) // Optimizer (loss function) .addEvaluator(new Accuracy()) // Model Accuracy .addTrainingListeners(TrainingListener.Defaults.logging()); // Logging try (Model model = Model.newInstance("mlp")) { model.setBlock(net); try (Trainer trainer = model.newTrainer(config)) { trainer.initialize(new Shape(1, 784)); trainer.setMetrics(new Metrics()); EasyTrain.fit(trainer, numEpochs, trainIter, testIter); // collect results from evaluators Metrics metrics = trainer.getMetrics(); trainer.getEvaluators().stream() .forEach(evaluator -> { evaluatorMetrics.put("train_epoch_" + evaluator.getName(), metrics.getMetric("train_epoch_" + evaluator.getName()).stream() .mapToDouble(x -> x.getValue().doubleValue()).toArray()); evaluatorMetrics.put("validate_epoch_" + evaluator.getName(), metrics.getMetric("validate_epoch_" + evaluator.getName()).stream() .mapToDouble(x -> x.getValue().doubleValue()).toArray()); }); } } trainLoss = evaluatorMetrics.get("train_epoch_SoftmaxCrossEntropyLoss"); trainAccuracy = evaluatorMetrics.get("train_epoch_Accuracy"); testAccuracy = evaluatorMetrics.get("validate_epoch_Accuracy"); String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length]; Arrays.fill(lossLabel, 0, trainLoss.length, "test acc"); Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, "train acc"); Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length, trainLoss.length + testAccuracy.length + trainAccuracy.length, "train loss"); Table data = Table.create("Data").addColumns( DoubleColumn.create("epochCount", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))), DoubleColumn.create("loss", ArrayUtils.addAll(testAccuracy , ArrayUtils.addAll(trainAccuracy, trainLoss))), StringColumn.create("lossLabel", lossLabel) ); render(LinePlot.create("", data, "epochCount", "loss", "lossLabel"),"text/html"); ###Output _____no_output_____
notebooks/synthetic_experiments.ipynb
###Markdown Synthetic experiments ###Code import project_path from util.syn_exps import grid_search from scipy.io import savemat, loadmat import numpy as np import matplotlib.pyplot as plt from util.visualize import plot_synthetic from omegaconf import OmegaConf params = OmegaConf.load('../configs/synthetic_conf.yaml') d = loadmat('outputs_theta.mat') plot_synthetic(params, 'outputs_theta.mat') params = OmegaConf.load('../configs/synthetic_conf.yaml') params.model.geoTL.theta mdict = grid_search(params.noise.SNR, params.data, params.model) mdict['params'] = params savemat('outputs_theta.mat', mdict) err_geoTL.shape plt.plot(params.noise.SNR, err_orig[0,0,:].squeeze(), label='Noisy data') plt.plot(params.noise.SNR, err_geoTL[0,0,:,0,0].squeeze(), label='geoTL') plt.plot(params.noise.SNR, err_gmlsvd[0,0,:].squeeze(), label='GMLSVD') plt.plot(params.noise.SNR, err_nnfold[0,0,:].squeeze(), label='NNFOLD') plt.plot(params.noise.SNR, err_horpca[0,0,:].squeeze(), label='HoRPCA') plt.plot(params.noise.SNR, err_hosvd[0,0,:].squeeze(), label='HOOI') plt.xlabel('SNR values of noise.') plt.ylabel('RSE values of the output') plt.legend() plt.show() ###Output _____no_output_____
nbs/012_callback.gblend.ipynb
###Markdown Gradient Blending> Callback used to apply gradient blending to multi-modal models. This is an unofficial PyTorch implementation by Ignacio Oguiza ([email protected]) based on: Wang, W., Tran, D., & Feiszli, M. (2020). **What Makes Training Multi-Modal Classification Networks Hard?**. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 12695-12705). ###Code #export from fastai.callback.all import * from tsai.imports import * from tsai.utils import * from tsai.data.preprocessing import * from tsai.data.transforms import * from tsai.models.layers import * #export class GBlendLoss(Module): "Wrapper loss used by the gradient blending callback to allow weights applied to each modality." def __init__(self, crit=None, w=None): self.crit = ifnone(crit, CrossEntropyLossFlat()) self.w = w def forward(self, preds, target): # unweighted loss if not is_listy(preds): return self.crit(preds, target) # weighted loss if self.w is None: self.w = tensor([1.] * len(preds)) loss = 0 for i, pred in enumerate(preds): loss += self.crit(pred, target) * self.w[i] return loss / sum(self.w) # export class GBlend(Callback): r"""A callback to implement multi-modal gradient blending. This is an unofficial PyTorch implementation by Ignacio Oguiza of - [email protected] based on: Wang, W., Tran, D., & Feiszli, M. (2020). What Makes Training Multi-Modal Classification Networks Hard?. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 12695-12705). """ def __init__(self, V_pct=.1, n:Union[None, int, tuple, list]=(10, 5), sel_metric:Optional[str]=None, show_plot:bool=False, path:str='./data/gblend'): r""" Args: V_pct : subset of train where OGR will be measured (to estimate L*) n : None: offline learning, int: super-epoch (online learning), tuple: (warmup super-epoch, super-epoch)(online learning with warm up) sel_metric : which metric will be used to calculate overfitting and generalization during training. If None, loss will be used. show_plot : will show a plot with the wieghts at the end of training """ assert V_pct < 1, 'V_pct must be < 1' self.V_pct, self.n, self.sel_metric, self.show_plot = V_pct, n, sel_metric, show_plot self.metric_idx = None self.path = Path(path) if not os.path.exists(self.path): os.makedirs(self.path) def before_fit(self): # model self.learn.M = self.model.M self.old_multi_output = self.learn.model.multi_output self.learn.model.multi_output = True #loss if cls_name(self.learn.loss_func) != 'GBlendLoss': self.learn.loss_func = GBlendLoss(crit=self.learn.loss_func) # calculate super_epochs if self.n is None: self.super_epochs = [0] else: if is_listy(self.n): self.wu_n = self.n[0] self.n = self.n[1] else: self.wu_n = self.n rng = range(int(max(0, self.n_epoch - self.wu_n) / self.n + 1)) self.super_epochs = [] for i in rng: self.super_epochs.append((i * self.wu_n) if i <= 1 else int((i + self.wu_n / self.n - 1) * self.n)) self.super_epochs.append(self.n_epoch) # create T'(Tp) and V dataloaders n_out = len(self.learn.dls.train.dataset.ptls) - self.learn.dls.train.dataset.n_inp train_targets = self.learn.dls.train.dataset.ptls[-n_out] Tp_idx, V_idx = get_splits(train_targets, valid_size=self.V_pct) _Tp_train_dls = [] _V_train_dls = [] self.learn.new_dls = [] for dl in self.learn.dls[0].loaders: # train MixedDataLoaders _Tp_dl = get_subset_dl(dl, Tp_idx) _V_dl = get_subset_dl(dl, V_idx) _Tp_train_dls.append(_Tp_dl) _V_train_dls.append(_V_dl) self.learn.new_dls.append(DataLoaders(_Tp_dl, _V_dl, device=self.learn.dls.device)) self.learn.new_dls.append(MixedDataLoaders(MixedDataLoader(*_Tp_train_dls, shuffle=True), # train - train MixedDataLoader(*_V_train_dls, shuffle=False), # train - valid device=self.learn.dls.device)) # prepare containers self.learn.LT = [] self.learn.LV = [] def before_train(self): if self.epoch in self.super_epochs[:-1] and not 'LRFinder' in [cls_name(cb) for cb in self.learn.cbs]: self.train_epochs = np.diff(self.super_epochs)[self.super_epochs.index(self.epoch)] #compute weights self.learn.save('gblend_learner') torch.save(self.learn.model, self.path/'gblend_model') w = self.compute_weights() if self.epoch == 0: self.learn.ws = [w] else: self.learn.ws.append(w) self.learn = self.learn.load('gblend_learner') self.learn.loss_func.w = w def compute_weights(self): # _LT0 = [] # _LV0 = [] _LT = [] _LV = [] for i in range(self.learn.M + 1): model = torch.load(self.path/'gblend_model') learn = Learner(self.learn.new_dls[i], model.m[i], loss_func=GBlendLoss(), opt_func=self.learn.opt_func, metrics=self.learn.metrics) learn.model.multi_output = False learn.remove_cbs(learn.cbs[1]) learn.add_cb(Recorder(train_metrics=True)) with learn.no_bar(): with learn.no_logging(): learn.fit_one_cycle(self.train_epochs, pct_start=0) if self.metric_idx is None and self.sel_metric is not None: metric_names = learn.recorder.metric_names[1:-1] self.metric_idx = [i for i,m in enumerate(metric_names) if self.sel_metric in m] else: self.metric_idx = [0, 1] metric_values = learn.recorder.values[-1][self.metric_idx] _LT.append(metric_values[0]) _LV.append(metric_values[1]) # if self.epoch == 0: self.compute_previous_metrics() self.compute_previous_metrics() self.learn.LT.append(_LT) self.learn.LV.append(_LV) LT1 = array(self.learn.LT[-2]) LT2 = array(self.learn.LT[-1]) LV1 = array(self.learn.LV[-2]) LV2 = array(self.learn.LV[-1]) ΔG = (LV1 - LV2) if self.metric_idx[0] == 0 else (LV2 - LV1) O1 = (LV1 - LT1) if self.metric_idx[0] == 0 else (LT1 - LV1) O2 = (LV2 - LT2) if self.metric_idx[0] == 0 else (LT2 - LV2) ΔG = np.maximum(0, ΔG) ΔO = O2 - O1 ΔO2 = np.maximum(1e-8, (O2 - O1)**2) w = np.maximum(1e-8, np.nan_to_num(ΔG / ΔO2)) w = w / w.sum() w = w.tolist() return w def compute_previous_metrics(self): if self.metric_idx[0] == 0: metric = self.loss_func else: metric = self.learn.metrics[(min(array(self.metric_idx) - 2) - 1) // 2] _LT = [] _LV = [] with torch.no_grad(): for i in range(self.learn.M + 1): model = torch.load(self.path/'gblend_model') model.multi_output = False model = model.m[i] _train_metrics = [] _valid_metrics = [] for j,dl in enumerate(self.learn.new_dls[i]): it = iter(dl) _preds = [] _targets = [] for b in it: _preds.extend(model(*b[:-1])) _targets.extend(b[-1]) _preds, _targets = stack(_preds), stack(_targets) try: _metric_values = metric(_preds, _targets).cpu().item() except: _metric_values = metric(torch.argmax(_preds, 1), _targets).cpu().item() if j == 0: _LT.append(_metric_values) else: _LV.append(_metric_values) self.learn.LT.append(_LT) self.learn.LV.append(_LV) def after_fit(self): if hasattr(self.learn, "ws") and self.show_plot: widths = np.diff(self.super_epochs) cum_ws = 0 for i in range(self.learn.M + 1): plt.bar(self.super_epochs[:-1] + widths/2, stack(self.learn.ws)[:, i], bottom=cum_ws, width=widths, label=f'k={i+1}' if i < self.learn.M else f'fused') cum_ws += stack(self.learn.ws)[:, i] plt.xlim(0, self.super_epochs[-1]) plt.ylim(0, 1) plt.xticks(self.super_epochs) plt.legend(loc='best') plt.title('Online G-Blend Weights by modality') plt.show() self.learn.model.multi_output = self.old_multi_output from fastai.data.transforms import * from tsai.data.all import * from tsai.models.utils import * from tsai.models.XCM import * from tsai.models.TabModel import * from tsai.models.MultiInputNet import * from tsai.learner import * dsid = 'NATOPS' X, y, splits = get_UCR_data(dsid, split_data=False) ts_features_df = get_ts_features(X, y) # raw ts tfms = [None, [Categorize()]] batch_tfms = TSStandardize() ts_dls = get_ts_dls(X, y, splits=splits, tfms=tfms, batch_tfms=batch_tfms) ts_model = build_ts_model(XCM, dls=ts_dls, window_perc=.5) # ts features cat_names = None cont_names = ts_features_df.columns[:-2] y_names = 'target' tab_dls = get_tabular_dls(ts_features_df, cat_names=cat_names, cont_names=cont_names, y_names=y_names, splits=splits) tab_model = build_tabular_model(TabModel, dls=tab_dls) # mixed mixed_dls = get_mixed_dls(ts_dls, tab_dls) MultiModalNet = MultiInputNet(ts_model, tab_model, c_out=mixed_dls.c) gblend = GBlend(V_pct=.5, n=(10, 5), sel_metric=None) learn = Learner(mixed_dls, MultiModalNet, metrics=[accuracy, RocAuc()], cbs=gblend) learn.fit_one_cycle(1, 1e-3) #hide out = create_scripts(); beep(out) ###Output _____no_output_____ ###Markdown Gradient Blending> Callback used to apply gradient blending to multi-modal models. This is an unofficial PyTorch implementation by Ignacio Oguiza of - [email protected] based on: Wang, W., Tran, D., & Feiszli, M. (2020). **What Makes Training Multi-Modal Classification Networks Hard?**. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 12695-12705). ###Code #export from fastai.callback.all import * from tsai.imports import * from tsai.utils import * from tsai.data.preprocessing import * from tsai.data.transforms import * from tsai.models.layers import * #export class GBlendLoss(Module): "Wrapper loss used by the gradient blending callback to allow weights applied to each modality." def __init__(self, crit=None, w=None): self.crit = ifnone(crit, CrossEntropyLossFlat()) self.w = w def forward(self, preds, target): # unweighted loss if not is_listy(preds): return self.crit(preds, target) # weighted loss if self.w is None: self.w = tensor([1.] * len(preds)) loss = 0 for i, pred in enumerate(preds): loss += self.crit(pred, target) * self.w[i] return loss / sum(self.w) # export class GBlend(Callback): r"""A callback to implement multi-modal gradient blending. This is an unofficial PyTorch implementation by Ignacio Oguiza of - [email protected] based on: Wang, W., Tran, D., & Feiszli, M. (2020). What Makes Training Multi-Modal Classification Networks Hard?. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 12695-12705). """ def __init__(self, V_pct=.1, n:Union[None, int, tuple, list]=(10, 5), sel_metric:Optional[str]=None, show_plot:bool=False): r""" Args: V_pct : subset of train where OGR will be measured (to estimate L*) n : None: offline learning, int: super-epoch (online learning), tuple: (warmup super-epoch, super-epoch)(online learning with warm up) sel_metric : which metric will be used to calculate overfitting and generalization during training. If None, loss will be used. show_plot : will show a plot with the wieghts at the end of training """ assert V_pct < 1, 'V_pct must be < 1' self.V_pct, self.n, self.sel_metric, self.show_plot = V_pct, n, sel_metric, show_plot self.metric_idx = None def before_fit(self): # model self.M = self.model.M self.old_multi_output = self.learn.model.multi_output self.learn.model.multi_output = True #loss if cls_name(self.learn.loss_func) != 'GBlendLoss': self.learn.loss_func = GBlendLoss(crit=self.learn.loss_func) # calculate super_epochs if self.n is None: self.super_epochs = [0] else: if is_listy(self.n): self.wu_n = self.n[0] self.n = self.n[1] else: self.wu_n = self.n rng = range(int(max(0, self.n_epoch - self.wu_n) / self.n + 1)) self.super_epochs = [] for i in rng: self.super_epochs.append((i * self.wu_n) if i <= 1 else int((i + self.wu_n / self.n - 1) * self.n)) self.super_epochs.append(self.n_epoch) # create T'(Tp) and V dataloaders n_out = len(self.learn.dls.train.dataset.ptls) - self.learn.dls.train.dataset.n_inp train_targets = self.learn.dls.train.dataset.ptls[-n_out] Tp_idx, V_idx = get_splits(train_targets, valid_size=self.V_pct) _Tp_train_dls = [] _V_train_dls = [] self.learn.new_dls = [] for dl in self.learn.dls[0].loaders: # train MixedDataLoaders _Tp_dl = get_subset_dl(dl, Tp_idx) _V_dl = get_subset_dl(dl, V_idx) _Tp_train_dls.append(_Tp_dl) _V_train_dls.append(_V_dl) self.learn.new_dls.append(DataLoaders(_Tp_dl, _V_dl, device=self.learn.dls.device)) self.learn.new_dls.append(MixedDataLoaders(MixedDataLoader(*_Tp_train_dls, shuffle=True), # train - train MixedDataLoader(*_V_train_dls, shuffle=False), # train - valid device=self.learn.dls.device)) # prepare containers self.learn.LT = [] self.learn.LV = [] def before_train(self): if self.epoch in self.super_epochs[:-1] and not 'LRFinder' in [cls_name(cb) for cb in self.learn.cbs]: self.train_epochs = np.diff(self.super_epochs)[self.super_epochs.index(self.epoch)] #compute weights self.learn.save('gblend_learner') torch.save(self.learn.model, 'gblend_model') w = self.compute_weights() if self.epoch == 0: self.learn.ws = [w] else: self.learn.ws.append(w) self.learn = self.learn.load('gblend_learner') self.learn.loss_func.w = w def compute_weights(self): # _LT0 = [] # _LV0 = [] _LT = [] _LV = [] for i in range(self.M + 1): model = torch.load('gblend_model') learn = Learner(self.learn.new_dls[i], model.m[i], loss_func=GBlendLoss(), opt_func=self.learn.opt_func, metrics=self.learn.metrics) learn.model.multi_output = False learn.remove_cbs(learn.cbs[1]) learn.add_cb(Recorder(train_metrics=True)) with learn.no_bar(): with learn.no_logging(): learn.fit_one_cycle(self.train_epochs, pct_start=0) if self.metric_idx is None and self.sel_metric is not None: metric_names = learn.recorder.metric_names[1:-1] self.metric_idx = [i for i,m in enumerate(metric_names) if self.sel_metric in m] else: self.metric_idx = [0, 1] metric_values = learn.recorder.values[-1][self.metric_idx] _LT.append(metric_values[0]) _LV.append(metric_values[1]) # if self.epoch == 0: self.compute_previous_metrics() self.compute_previous_metrics() self.learn.LT.append(_LT) self.learn.LV.append(_LV) LT1 = array(self.learn.LT[-2]) LT2 = array(self.learn.LT[-1]) LV1 = array(self.learn.LV[-2]) LV2 = array(self.learn.LV[-1]) ΔG = (LV1 - LV2) if self.metric_idx[0] == 0 else (LV2 - LV1) O1 = (LV1 - LT1) if self.metric_idx[0] == 0 else (LT1 - LV1) O2 = (LV2 - LT2) if self.metric_idx[0] == 0 else (LT2 - LV2) ΔG = np.maximum(0, ΔG) ΔO = O2 - O1 ΔO2 = np.maximum(1e-8, (O2 - O1)**2) w = np.maximum(1e-8, np.nan_to_num(ΔG / ΔO2)) w = w / w.sum() w = w.tolist() return w def compute_previous_metrics(self): if self.metric_idx[0] == 0: metric = self.loss_func else: metric = self.learn.metrics[(min(array(self.metric_idx) - 2) - 1) // 2] _LT = [] _LV = [] with torch.no_grad(): for i in range(self.M + 1): model = torch.load('gblend_model') model.multi_output = False model = model.m[i] _train_metrics = [] _valid_metrics = [] for j,dl in enumerate(self.learn.new_dls[i]): it = iter(dl) _preds = [] _targets = [] for b in it: _preds.extend(model(*b[:-1])) _targets.extend(b[-1]) _preds, _targets = stack(_preds), stack(_targets) try: _metric_values = metric(_preds, _targets).cpu().item() except: _metric_values = metric(torch.argmax(_preds, 1), _targets).cpu().item() if j == 0: _LT.append(_metric_values) else: _LV.append(_metric_values) self.learn.LT.append(_LT) self.learn.LV.append(_LV) def after_fit(self): if hasattr(self.learn, "ws") and self.show_plot: widths = np.diff(self.super_epochs) cum_ws = 0 for i in range(self.M + 1): plt.bar(self.super_epochs[:-1] + widths/2, stack(self.learn.ws)[:, i], bottom=cum_ws, width=widths, label=f'k={i+1}' if i < self.M else f'fused') cum_ws += stack(self.learn.ws)[:, i] plt.xlim(0, self.super_epochs[-1]) plt.ylim(0, 1) plt.xticks(self.super_epochs) plt.legend(loc='best') plt.title('Online G-Blend Weights by modality') plt.show() self.learn.model.multi_output = self.old_multi_output from fastai.data.transforms import * from tsai.data.all import * from tsai.models.utils import * from tsai.models.XCM import * from tsai.models.TabModel import * from tsai.models.MultiInputNet import * dsid = 'NATOPS' X, y, splits = get_UCR_data(dsid, split_data=False) ts_features_df = get_ts_features(X, y) # raw ts tfms = [None, [Categorize()]] batch_tfms = TSStandardize() ts_dls = get_ts_dls(X, y, splits=splits, tfms=tfms, batch_tfms=batch_tfms) ts_model = build_ts_model(XCM, dls=ts_dls, window_perc=.5) # ts features cat_names = None cont_names = ts_features_df.columns[:-2] y_names = 'target' tab_dls = get_tabular_dls(ts_features_df, cat_names=cat_names, cont_names=cont_names, y_names=y_names, splits=splits) tab_model = build_tabular_model(TabModel, dls=tab_dls) # mixed mixed_dls = get_mixed_dls(ts_dls, tab_dls) MultiModalNet = MultiInputNet(ts_model, tab_model, c_out=mixed_dls.c) gblend = GBlend(V_pct=.5, n=(10, 5), sel_metric=None) learn = Learner(mixed_dls, MultiModalNet, metrics=[accuracy, RocAuc()], cbs=gblend) learn.fit_one_cycle(1, 1e-3) #hide out = create_scripts(); beep(out) ###Output _____no_output_____ ###Markdown Gradient Blending> Callback used to apply gradient blending to multi-modal models. This is an unofficial PyTorch implementation by Ignacio Oguiza ([email protected]) based on: Wang, W., Tran, D., & Feiszli, M. (2020). **What Makes Training Multi-Modal Classification Networks Hard?**. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 12695-12705). ###Code #export from fastai.callback.all import * from tsai.imports import * from tsai.utils import * from tsai.data.preprocessing import * from tsai.data.transforms import * from tsai.models.layers import * #export class GBlendLoss(Module): "Wrapper loss used by the gradient blending callback to allow weights applied to each modality." def __init__(self, crit=None, w=None): self.crit = ifnone(crit, CrossEntropyLossFlat()) self.w = w def forward(self, preds, target): # unweighted loss if not is_listy(preds): return self.crit(preds, target) # weighted loss if self.w is None: self.w = tensor([1.] * len(preds)) loss = 0 for i, pred in enumerate(preds): loss += self.crit(pred, target) * self.w[i] return loss / sum(self.w) # export class GBlend(Callback): r"""A callback to implement multi-modal gradient blending. This is an unofficial PyTorch implementation by Ignacio Oguiza of - [email protected] based on: Wang, W., Tran, D., & Feiszli, M. (2020). What Makes Training Multi-Modal Classification Networks Hard?. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (pp. 12695-12705). """ def __init__(self, V_pct=.1, n:Union[None, int, tuple, list]=(10, 5), sel_metric:Optional[str]=None, show_plot:bool=False, path:str='./data/gblend'): r""" Args: V_pct : subset of train where OGR will be measured (to estimate L*) n : None: offline learning, int: super-epoch (online learning), tuple: (warmup super-epoch, super-epoch)(online learning with warm up) sel_metric : which metric will be used to calculate overfitting and generalization during training. If None, loss will be used. show_plot : will show a plot with the wieghts at the end of training """ assert V_pct < 1, 'V_pct must be < 1' self.V_pct, self.n, self.sel_metric, self.show_plot = V_pct, n, sel_metric, show_plot self.metric_idx = None self.path = Path(path) if not os.path.exists(self.path): os.makedirs(self.path) def before_fit(self): # model self.M = self.model.M self.old_multi_output = self.learn.model.multi_output self.learn.model.multi_output = True #loss if cls_name(self.learn.loss_func) != 'GBlendLoss': self.learn.loss_func = GBlendLoss(crit=self.learn.loss_func) # calculate super_epochs if self.n is None: self.super_epochs = [0] else: if is_listy(self.n): self.wu_n = self.n[0] self.n = self.n[1] else: self.wu_n = self.n rng = range(int(max(0, self.n_epoch - self.wu_n) / self.n + 1)) self.super_epochs = [] for i in rng: self.super_epochs.append((i * self.wu_n) if i <= 1 else int((i + self.wu_n / self.n - 1) * self.n)) self.super_epochs.append(self.n_epoch) # create T'(Tp) and V dataloaders n_out = len(self.learn.dls.train.dataset.ptls) - self.learn.dls.train.dataset.n_inp train_targets = self.learn.dls.train.dataset.ptls[-n_out] Tp_idx, V_idx = get_splits(train_targets, valid_size=self.V_pct) _Tp_train_dls = [] _V_train_dls = [] self.learn.new_dls = [] for dl in self.learn.dls[0].loaders: # train MixedDataLoaders _Tp_dl = get_subset_dl(dl, Tp_idx) _V_dl = get_subset_dl(dl, V_idx) _Tp_train_dls.append(_Tp_dl) _V_train_dls.append(_V_dl) self.learn.new_dls.append(DataLoaders(_Tp_dl, _V_dl, device=self.learn.dls.device)) self.learn.new_dls.append(MixedDataLoaders(MixedDataLoader(*_Tp_train_dls, shuffle=True), # train - train MixedDataLoader(*_V_train_dls, shuffle=False), # train - valid device=self.learn.dls.device)) # prepare containers self.learn.LT = [] self.learn.LV = [] def before_train(self): if self.epoch in self.super_epochs[:-1] and not 'LRFinder' in [cls_name(cb) for cb in self.learn.cbs]: self.train_epochs = np.diff(self.super_epochs)[self.super_epochs.index(self.epoch)] #compute weights self.learn.save('gblend_learner') torch.save(self.learn.model, self.path/'gblend_model') w = self.compute_weights() if self.epoch == 0: self.learn.ws = [w] else: self.learn.ws.append(w) self.learn = self.learn.load('gblend_learner') self.learn.loss_func.w = w def compute_weights(self): # _LT0 = [] # _LV0 = [] _LT = [] _LV = [] for i in range(self.M + 1): model = torch.load(self.path/'gblend_model') learn = Learner(self.learn.new_dls[i], model.m[i], loss_func=GBlendLoss(), opt_func=self.learn.opt_func, metrics=self.learn.metrics) learn.model.multi_output = False learn.remove_cbs(learn.cbs[1]) learn.add_cb(Recorder(train_metrics=True)) with learn.no_bar(): with learn.no_logging(): learn.fit_one_cycle(self.train_epochs, pct_start=0) if self.metric_idx is None and self.sel_metric is not None: metric_names = learn.recorder.metric_names[1:-1] self.metric_idx = [i for i,m in enumerate(metric_names) if self.sel_metric in m] else: self.metric_idx = [0, 1] metric_values = learn.recorder.values[-1][self.metric_idx] _LT.append(metric_values[0]) _LV.append(metric_values[1]) # if self.epoch == 0: self.compute_previous_metrics() self.compute_previous_metrics() self.learn.LT.append(_LT) self.learn.LV.append(_LV) LT1 = array(self.learn.LT[-2]) LT2 = array(self.learn.LT[-1]) LV1 = array(self.learn.LV[-2]) LV2 = array(self.learn.LV[-1]) ΔG = (LV1 - LV2) if self.metric_idx[0] == 0 else (LV2 - LV1) O1 = (LV1 - LT1) if self.metric_idx[0] == 0 else (LT1 - LV1) O2 = (LV2 - LT2) if self.metric_idx[0] == 0 else (LT2 - LV2) ΔG = np.maximum(0, ΔG) ΔO = O2 - O1 ΔO2 = np.maximum(1e-8, (O2 - O1)**2) w = np.maximum(1e-8, np.nan_to_num(ΔG / ΔO2)) w = w / w.sum() w = w.tolist() return w def compute_previous_metrics(self): if self.metric_idx[0] == 0: metric = self.loss_func else: metric = self.learn.metrics[(min(array(self.metric_idx) - 2) - 1) // 2] _LT = [] _LV = [] with torch.no_grad(): for i in range(self.M + 1): model = torch.load(self.path/'gblend_model') model.multi_output = False model = model.m[i] _train_metrics = [] _valid_metrics = [] for j,dl in enumerate(self.learn.new_dls[i]): it = iter(dl) _preds = [] _targets = [] for b in it: _preds.extend(model(*b[:-1])) _targets.extend(b[-1]) _preds, _targets = stack(_preds), stack(_targets) try: _metric_values = metric(_preds, _targets).cpu().item() except: _metric_values = metric(torch.argmax(_preds, 1), _targets).cpu().item() if j == 0: _LT.append(_metric_values) else: _LV.append(_metric_values) self.learn.LT.append(_LT) self.learn.LV.append(_LV) def after_fit(self): if hasattr(self.learn, "ws") and self.show_plot: widths = np.diff(self.super_epochs) cum_ws = 0 for i in range(self.M + 1): plt.bar(self.super_epochs[:-1] + widths/2, stack(self.learn.ws)[:, i], bottom=cum_ws, width=widths, label=f'k={i+1}' if i < self.M else f'fused') cum_ws += stack(self.learn.ws)[:, i] plt.xlim(0, self.super_epochs[-1]) plt.ylim(0, 1) plt.xticks(self.super_epochs) plt.legend(loc='best') plt.title('Online G-Blend Weights by modality') plt.show() self.learn.model.multi_output = self.old_multi_output from fastai.data.transforms import * from tsai.data.all import * from tsai.models.utils import * from tsai.models.XCM import * from tsai.models.TabModel import * from tsai.models.MultiInputNet import * dsid = 'NATOPS' X, y, splits = get_UCR_data(dsid, split_data=False) ts_features_df = get_ts_features(X, y) # raw ts tfms = [None, [Categorize()]] batch_tfms = TSStandardize() ts_dls = get_ts_dls(X, y, splits=splits, tfms=tfms, batch_tfms=batch_tfms) ts_model = build_ts_model(XCM, dls=ts_dls, window_perc=.5) # ts features cat_names = None cont_names = ts_features_df.columns[:-2] y_names = 'target' tab_dls = get_tabular_dls(ts_features_df, cat_names=cat_names, cont_names=cont_names, y_names=y_names, splits=splits) tab_model = build_tabular_model(TabModel, dls=tab_dls) # mixed mixed_dls = get_mixed_dls(ts_dls, tab_dls) MultiModalNet = MultiInputNet(ts_model, tab_model, c_out=mixed_dls.c) gblend = GBlend(V_pct=.5, n=(10, 5), sel_metric=None) learn = Learner(mixed_dls, MultiModalNet, metrics=[accuracy, RocAuc()], cbs=gblend) learn.fit_one_cycle(1, 1e-3) #hide out = create_scripts(); beep(out) ###Output _____no_output_____
sagemaker-debugger/tensorflow_profiling/tf-resnet-profiling-multi-gpu-multi-node-boto3.ipynb
###Markdown Profiling TensorFlow Multi GPU Multi Node Training Job with Amazon SageMaker Debugger (SageMaker API)This notebook walks you through creating a TensorFlow training job with the SageMaker Debugger profiling feature enabled. It will create a multi GPU multi node training using Horovod. (Optional) Install SageMaker and SMDebugTo use the new Debugger profiling features released in December 2020, ensure that you have the latest versions of Boto3, SageMaker, and SMDebug libraries installed. Use the following cell (switch `install_needed` to `True`) to update the libraries and restarts the Jupyter kernel to apply the updates. ###Code import sys import IPython install_needed = False # should only be True once if install_needed: print("installing deps and restarting kernel") !{sys.executable} -m pip install -U boto3 sagemaker smdebug IPython.Application.instance().kernel.do_shutdown(True) ###Output _____no_output_____ ###Markdown 1. Create a Training Job with Debugger EnabledYou will learn how to use the Boto3 SageMaker client's `create_training_job()` function to start a training job. Start a SageMaker session and retrieve the current region and the default Amazon S3 bucket URI ###Code import sagemaker session = sagemaker.Session() region = session.boto_region_name bucket = session.default_bucket() print(region, bucket) ###Output _____no_output_____ ###Markdown Upload a training script to the S3 bucket ###Code import boto3, tarfile source = "source.tar.gz" project = "debugger-boto3-profiling-test" tar = tarfile.open(source, "w:gz") tar.add("entry_point/tf-hvd-train.py") tar.close() s3 = boto3.client("s3") s3.upload_file(source, bucket, project + "/" + source) upload_file_path = f"s3://{bucket}/{project}/{source}" print(upload_file_path) ###Output _____no_output_____ ###Markdown Create a Boto3 SageMaker client object ###Code sm = boto3.Session(region_name=region).client("sagemaker") ###Output _____no_output_____ ###Markdown Configure the request body of the `create_training_job()` functionThe following parameters are required to include to the request body for `create_training_job()` function.- `TrainingJobName` - Specify a prefix or a full name if you want to modify- `HyperParameters` - Set up the following items: - `sagemaker_program` and `sagemaker_submit_directory` - The S3 bucket URI of the training script. This enables SageMaker to read the training script from the URI and start a training job. - `sagemaker_mpi` options - Configure these key-value pairs to set up distributed training. - You can also add other hyperparameters for your model.- `AlgorithmSpecification` - Specify `TrainingImage`. In this example, an official TensorFlow DLC image is used. You can also use your own training container images here. - `RoleArn` - **To run the following cell, you must specify the right SageMaker execution role ARN that you want to use for training**.- The `DebugHookConfig` and `DebugRuleConfigurations` are preconfigured for watching loss values and a loss not decreasing issue.- The `ProfilerConfig` and `ProfilerRuleConfigurations` are preconfigured to collect system and framework metrics, initiate all profiling rules, and create a Debugger profiling report.**Important**: For `DebugRuleConfigurations` and `ProfilerRuleConfigurations`, **to run the following cell, you must specify the right Debugger rule image URI from [Amazon SageMaker Debugger Registry URLs for Built-in Rule Evaluators](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html)**. The `sagemaker.debugger.get_rule_container_image_uri(region)` function retrieves the Debugger rule image automatically. For example:- If you are in `us-east-1`, the right image URI is **503895931360**.dkr.ecr.**us-east-1**.amazonaws.com/sagemaker-debugger-rules:latest.- If you are in `us-west-2`, the right image URI is **895741380848**.dkr.ecr.**us-west-2**.amazonaws.com/sagemaker-debugger-rules:latest. ###Code import datetime training_job_name = "profiler-boto3-" + datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") sm.create_training_job( TrainingJobName=training_job_name, HyperParameters={ "sagemaker_program": "entry_point/tf-hvd-train.py", "sagemaker_submit_directory": "s3://" + bucket + "/" + project + "/" + source, "sagemaker_mpi_custom_mpi_options": "-verbose -x HOROVOD_TIMELINE=./hvd_timeline.json -x NCCL_DEBUG=INFO -x OMPI_MCA_btl_vader_single_copy_mechanism=none", "sagemaker_mpi_enabled": "true", "sagemaker_mpi_num_of_processes_per_host": "4", }, AlgorithmSpecification={ "TrainingImage": "763104351884.dkr.ecr." + region + ".amazonaws.com/tensorflow-training:2.4.1-gpu-py37-cu110-ubuntu18.04", "TrainingInputMode": "File", "EnableSageMakerMetricsTimeSeries": False, }, # You must specify your SageMaker execution role ARN here RoleArn=sagemaker.get_execution_role(), OutputDataConfig={"S3OutputPath": "s3://" + bucket + "/" + project + "/output"}, ResourceConfig={"InstanceType": "ml.p3.8xlarge", "InstanceCount": 2, "VolumeSizeInGB": 30}, StoppingCondition={"MaxRuntimeInSeconds": 86400}, DebugHookConfig={ "S3OutputPath": "s3://" + bucket + "/" + project + "/debug-output", "CollectionConfigurations": [ {"CollectionName": "losses", "CollectionParameters": {"train.save_interval": "50"}} ], }, DebugRuleConfigurations=[ { "RuleConfigurationName": "LossNotDecreasing", # You must specify the correct image URI from https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html "RuleEvaluatorImage": sagemaker.debugger.get_rule_container_image_uri(region), "RuleParameters": {"rule_to_invoke": "LossNotDecreasing"}, } ], ProfilerConfig={ "S3OutputPath": "s3://" + bucket + "/" + project + "/profiler-output", "ProfilingIntervalInMilliseconds": 500, "ProfilingParameters": { "DataloaderProfilingConfig": '{"StartStep": 5, "NumSteps": 3, "MetricsRegex": ".*", }', "DetailedProfilingConfig": '{"StartStep": 5, "NumSteps": 3, }', "PythonProfilingConfig": '{"StartStep": 5, "NumSteps": 3, "ProfilerName": "cprofile", "cProfileTimer": "total_time"}', "LocalPath": "/opt/ml/output/profiler/", # Optional. Local path for profiling outputs }, }, ProfilerRuleConfigurations=[ { "RuleConfigurationName": "ProfilerReport", # You must specify the correct image URI from https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html "RuleEvaluatorImage": sagemaker.debugger.get_rule_container_image_uri(region), "RuleParameters": {"rule_to_invoke": "ProfilerReport"}, } ], ) ###Output _____no_output_____ ###Markdown 2. Analyze Profiling Data Install the SMDebug client library to use Debugger analysis tools ###Code import pip def import_or_install(package): try: __import__(package) except ImportError: pip.main(["install", package]) import_or_install("smdebug") ###Output _____no_output_____ ###Markdown Use SMDebug to retrieve saved output data and use analysis toolsWhile the training is still in progress you can visualize the performance data in SageMaker Studio or in the notebook.Debugger provides utilities to plot system metrics in form of timeline charts or heatmaps. Checkout out the notebook [interactive_analysis_profiling_data.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-debugger/debugger_interactive_analysis_profiling/interactive_analysis_profiling_data.ipynb) for more details. In the following code cell we plot the total CPU and GPU utilization as timeseries charts. To visualize other metrics such as I/O, memory, network you simply need to extend the list passed to `select_dimension` and `select_events`. ###Code from smdebug.profiler.analysis.notebook_utils.training_job import TrainingJob tj = TrainingJob(training_job_name, region) tj.wait_for_sys_profiling_data_to_be_available() from smdebug.profiler.analysis.notebook_utils.timeline_charts import TimelineCharts system_metrics_reader = tj.get_systems_metrics_reader() system_metrics_reader.refresh_event_file_list() view_timeline_charts = TimelineCharts( system_metrics_reader, framework_metrics_reader=None, select_dimensions=["CPU", "GPU"], select_events=["total"], ) ###Output _____no_output_____ ###Markdown 3. Download Debugger Profiling Report The profiling report rule will create an html report `profiler-report.html` with a summary of builtin rules and recommenades of next steps. You can find this report in your S3 bucket. ###Code rule_output_path = ( "s3://" + bucket + "/" + project + "/output/" + training_job_name + "/rule-output/ProfilerReport/profiler-output/" ) ! aws s3 ls {rule_output_path} --recursive ! aws s3 cp {rule_output_path} . --recursive from IPython.display import FileLink display("Click link below to view the profiler report", FileLink("profiler-report.html")) ###Output _____no_output_____ ###Markdown Profiling TensorFlow Multi GPU Multi Node Training Job with Amazon SageMaker DebuggerThis notebook walks you through creating a TensorFlow training job with the SageMaker Debugger profiling feature enabled. It will create a multi GPU multi node training using Horovod. (Optional) Install SageMaker and SMDebugTo use the new Debugger profiling features released in December 2020, ensure that you have the latest versions of Boto3, SageMaker, and SMDebug libraries installed. Use the following cell (switch `install_needed` to `True`) to update the libraries and restarts the Jupyter kernel to apply the updates. ###Code import sys import IPython install_needed = False # should only be True once if install_needed: print("installing deps and restarting kernel") !{sys.executable} -m pip install -U boto3 sagemaker smdebug IPython.Application.instance().kernel.do_shutdown(True) ###Output _____no_output_____ ###Markdown 1. Create a Training Job with Debugger EnabledYou will learn how to use the Boto3 SageMaker client's `create_training_job()` function to start a training job. Start a SageMaker session and retrieve the current region and the default Amazon S3 bucket URI ###Code import sagemaker session = sagemaker.Session() region = session.boto_region_name bucket = session.default_bucket() print(region, bucket) ###Output _____no_output_____ ###Markdown Upload a training script to the S3 bucket ###Code import boto3, tarfile source = "source.tar.gz" project = "debugger-boto3-profiling-test" tar = tarfile.open(source, "w:gz") tar.add("entry_point/tf-hvd-train.py") tar.close() s3 = boto3.client("s3") s3.upload_file(source, bucket, project + "/" + source) upload_file_path = f"s3://{bucket}/{project}/{source}" print(upload_file_path) ###Output _____no_output_____ ###Markdown Create a Boto3 SageMaker client object ###Code sm = boto3.Session(region_name=region).client("sagemaker") ###Output _____no_output_____ ###Markdown Configure the request body of the `create_training_job()` functionThe following parameters are required to include to the request body for `create_training_job()` function.- `TrainingJobName` - Specify a prefix or a full name if you want to modify- `HyperParameters` - Set up the following items: - `sagemaker_program` and `sagemaker_submit_directory` - The S3 bucket URI of the training script. This enables SageMaker to read the training script from the URI and start a training job. - `sagemaker_mpi` options - Configure these key-value pairs to set up distributed training. - You can also add other hyperparameters for your model.- `AlgorithmSpecification` - Specify `TrainingImage`. In this example, an official TensorFlow DLC image is used. You can also use your own training container images here. - `RoleArn` - **To run the following cell, you must specify the right SageMaker execution role ARN that you want to use for training**.- The `DebugHookConfig` and `DebugRuleConfigurations` are preconfigured for watching loss values and a loss not decreasing issue.- The `ProfilerConfig` and `ProfilerRuleConfigurations` are preconfigured to collect system and framework metrics, initiate all profiling rules, and create a Debugger profiling report.**Important**: For `DebugRuleConfigurations` and `ProfilerRuleConfigurations`, **to run the following cell, you must specify the right Debugger rule image URI from [Amazon SageMaker Debugger Registry URLs for Built-in Rule Evaluators](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html)**. The `sagemaker.debugger.get_rule_container_image_uri(region)` function retrieves the Debugger rule image automatically. For example:- If you are in `us-east-1`, the right image URI is **503895931360**.dkr.ecr.**us-east-1**.amazonaws.com/sagemaker-debugger-rules:latest.- If you are in `us-west-2`, the right image URI is **895741380848**.dkr.ecr.**us-west-2**.amazonaws.com/sagemaker-debugger-rules:latest. ###Code import datetime training_job_name = "profiler-boto3-" + datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") sm.create_training_job( TrainingJobName=training_job_name, HyperParameters={ "sagemaker_program": "entry_point/tf-hvd-train.py", "sagemaker_submit_directory": "s3://" + bucket + "/" + project + "/" + source, "sagemaker_mpi_custom_mpi_options": "-verbose -x HOROVOD_TIMELINE=./hvd_timeline.json -x NCCL_DEBUG=INFO -x OMPI_MCA_btl_vader_single_copy_mechanism=none", "sagemaker_mpi_enabled": "true", "sagemaker_mpi_num_of_processes_per_host": "4", }, AlgorithmSpecification={ "TrainingImage": "763104351884.dkr.ecr." + region + ".amazonaws.com/tensorflow-training:2.4.1-gpu-py37-cu110-ubuntu18.04", "TrainingInputMode": "File", "EnableSageMakerMetricsTimeSeries": False, }, # You must specify your SageMaker execution role ARN here RoleArn=sagemaker.get_execution_role(), OutputDataConfig={"S3OutputPath": "s3://" + bucket + "/" + project + "/output"}, ResourceConfig={"InstanceType": "ml.p3.8xlarge", "InstanceCount": 2, "VolumeSizeInGB": 30}, StoppingCondition={"MaxRuntimeInSeconds": 86400}, DebugHookConfig={ "S3OutputPath": "s3://" + bucket + "/" + project + "/debug-output", "CollectionConfigurations": [ {"CollectionName": "losses", "CollectionParameters": {"train.save_interval": "50"}} ], }, DebugRuleConfigurations=[ { "RuleConfigurationName": "LossNotDecreasing", # You must specify the correct image URI from https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html "RuleEvaluatorImage": sagemaker.debugger.get_rule_container_image_uri(region), "RuleParameters": {"rule_to_invoke": "LossNotDecreasing"}, } ], ProfilerConfig={ "S3OutputPath": "s3://" + bucket + "/" + project + "/profiler-output", "ProfilingIntervalInMilliseconds": 500, "ProfilingParameters": { "DataloaderProfilingConfig": '{"StartStep": 5, "NumSteps": 3, "MetricsRegex": ".*", }', "DetailedProfilingConfig": '{"StartStep": 5, "NumSteps": 3, }', "PythonProfilingConfig": '{"StartStep": 5, "NumSteps": 3, "ProfilerName": "cprofile", "cProfileTimer": "total_time"}', "LocalPath": "/opt/ml/output/profiler/", # Optional. Local path for profiling outputs }, }, ProfilerRuleConfigurations=[ { "RuleConfigurationName": "ProfilerReport", # You must specify the correct image URI from https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html "RuleEvaluatorImage": sagemaker.debugger.get_rule_container_image_uri(region), "RuleParameters": {"rule_to_invoke": "ProfilerReport"}, } ], ) ###Output _____no_output_____ ###Markdown 2. Analyze Profiling Data Install the SMDebug client library to use Debugger analysis tools ###Code import pip def import_or_install(package): try: __import__(package) except ImportError: pip.main(["install", package]) import_or_install("smdebug") ###Output _____no_output_____ ###Markdown Use SMDebug to retrieve saved output data and use analysis toolsWhile the training is still in progress you can visualize the performance data in SageMaker Studio or in the notebook.Debugger provides utilities to plot system metrics in form of timeline charts or heatmaps. Checkout out the notebook [interactive_analysis_profiling_data.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-debugger/debugger_interactive_analysis_profiling/interactive_analysis_profiling_data.ipynb) for more details. In the following code cell we plot the total CPU and GPU utilization as timeseries charts. To visualize other metrics such as I/O, memory, network you simply need to extend the list passed to `select_dimension` and `select_events`. ###Code from smdebug.profiler.analysis.notebook_utils.training_job import TrainingJob tj = TrainingJob(training_job_name, region) tj.wait_for_sys_profiling_data_to_be_available() from smdebug.profiler.analysis.notebook_utils.timeline_charts import TimelineCharts system_metrics_reader = tj.get_systems_metrics_reader() system_metrics_reader.refresh_event_file_list() view_timeline_charts = TimelineCharts( system_metrics_reader, framework_metrics_reader=None, select_dimensions=["CPU", "GPU"], select_events=["total"], ) ###Output _____no_output_____ ###Markdown 3. Download Debugger Profiling Report The profiling report rule will create an html report `profiler-report.html` with a summary of builtin rules and recommenades of next steps. You can find this report in your S3 bucket. ###Code rule_output_path = ( "s3://" + bucket + "/" + project + "/output/" + training_job_name + "/rule-output/ProfilerReport/profiler-output/" ) ! aws s3 ls {rule_output_path} --recursive ! aws s3 cp {rule_output_path} . --recursive from IPython.display import FileLink display("Click link below to view the profiler report", FileLink("profiler-report.html")) ###Output _____no_output_____ ###Markdown Profiling TensorFlow Multi GPU Multi Node Training Job with Amazon SageMaker DebuggerThis notebook walks you through creating a TensorFlow training job with the SageMaker Debugger profiling feature enabled. It will create a multi GPU multi node training using Horovod. (Optional) Install SageMaker and SMDebugTo use the new Debugger profiling features released in December 2020, ensure that you have the latest versions of Boto3, SageMaker, and SMDebug libraries installed. Use the following cell (switch `install_needed` to `True`) to update the libraries and restarts the Jupyter kernel to apply the updates. ###Code import sys import IPython install_needed = False # should only be True once if install_needed: print("installing deps and restarting kernel") !{sys.executable} -m pip install -U boto3 sagemaker smdebug IPython.Application.instance().kernel.do_shutdown(True) ###Output _____no_output_____ ###Markdown 1. Create a Training Job with Debugger EnabledYou will learn how to use the Boto3 SageMaker client's `create_training_job()` function to start a training job. Start a SageMaker session and retrieve the current region and the default Amazon S3 bucket URI ###Code import sagemaker session = sagemaker.Session() region = session.boto_region_name bucket = session.default_bucket() print(region, bucket) ###Output _____no_output_____ ###Markdown Upload a training script to the S3 bucket ###Code import boto3, tarfile source = 'source.tar.gz' project = 'debugger-boto3-profiling-test' tar = tarfile.open(source, 'w:gz') tar.add ('entry_point/tf-hvd-train.py') tar.close() s3 = boto3.client('s3') s3.upload_file(source, bucket, project+'/'+source) upload_file_path=f"s3://{bucket}/{project}/{source}" print(upload_file_path) ###Output _____no_output_____ ###Markdown Create a Boto3 SageMaker client object ###Code sm = boto3.Session(region_name=region).client("sagemaker") ###Output _____no_output_____ ###Markdown Configure the request body of the `create_training_job()` functionThe following parameters are required to include to the request body for `create_training_job()` function.- `TrainingJobName` - Specify a prefix or a full name if you want to modify- `HyperParameters` - Set up the following items: - `sagemaker_program` and `sagemaker_submit_directory` - The S3 bucket URI of the training script. This enables SageMaker to read the training script from the URI and start a training job. - `sagemaker_mpi` options - Configure these key-value pairs to set up distributed training. - You can also add other hyperparameters for your model.- `AlgorithmSpecification` - Specify `TrainingImage`. In this example, an official TensorFlow DLC image is used. You can also use your own training container images here. - `RoleArn` - **To run the following cell, you must specify the right SageMaker execution role ARN that you want to use for training**.- The `DebugHookConfig` and `DebugRuleConfigurations` are preconfigured for watching loss values and a loss not decreasing issue.- The `ProfilerConfig` and `ProfilerRuleConfigurations` are preconfigured to collect system and framework metrics, initiate all profiling rules, and create a Debugger profiling report.**Important**: For `DebugRuleConfigurations` and `ProfilerRuleConfigurations`, **to run the following cell, you must specify the right Debugger rule image URI from [Amazon SageMaker Debugger Registry URLs for Built-in Rule Evaluators](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html)**. The `sagemaker.debugger.get_rule_container_image_uri(region)` function retrieves the Debugger rule image automatically. For example:- If you are in `us-east-1`, the right image URI is **503895931360**.dkr.ecr.**us-east-1**.amazonaws.com/sagemaker-debugger-rules:latest.- If you are in `us-west-2`, the right image URI is **895741380848**.dkr.ecr.**us-west-2**.amazonaws.com/sagemaker-debugger-rules:latest. ###Code import datetime training_job_name='profiler-boto3-'+datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') sm.create_training_job( TrainingJobName=training_job_name, HyperParameters={ 'sagemaker_program': 'entry_point/tf-hvd-train.py', 'sagemaker_submit_directory': 's3://'+bucket+'/'+project+'/'+source, 'sagemaker_mpi_custom_mpi_options': '-verbose -x HOROVOD_TIMELINE=./hvd_timeline.json -x NCCL_DEBUG=INFO -x OMPI_MCA_btl_vader_single_copy_mechanism=none', 'sagemaker_mpi_enabled': 'true', 'sagemaker_mpi_num_of_processes_per_host': '4' }, AlgorithmSpecification={ 'TrainingImage': '763104351884.dkr.ecr.'+region+'.amazonaws.com/tensorflow-training:2.4.1-gpu-py37-cu110-ubuntu18.04', 'TrainingInputMode': 'File', 'EnableSageMakerMetricsTimeSeries': False }, # You must specify your SageMaker execution role ARN here RoleArn=sagemaker.get_execution_role(), OutputDataConfig={'S3OutputPath': 's3://'+bucket+'/'+project+'/output'}, ResourceConfig={ 'InstanceType': 'ml.p3.8xlarge', 'InstanceCount': 2, 'VolumeSizeInGB': 30 }, StoppingCondition={ 'MaxRuntimeInSeconds': 86400 }, DebugHookConfig={ 'S3OutputPath': 's3://'+bucket+'/'+project+'/debug-output', 'CollectionConfigurations': [ { 'CollectionName': 'losses', 'CollectionParameters' : { 'train.save_interval': '50' } } ] }, DebugRuleConfigurations=[ { 'RuleConfigurationName': 'LossNotDecreasing', # You must specify the correct image URI from https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html 'RuleEvaluatorImage': sagemaker.debugger.get_rule_container_image_uri(region), 'RuleParameters': {'rule_to_invoke': 'LossNotDecreasing'} } ], ProfilerConfig={ 'S3OutputPath': 's3://'+bucket+'/'+project+'/profiler-output', 'ProfilingIntervalInMilliseconds': 500, 'ProfilingParameters': { 'DataloaderProfilingConfig': '{"StartStep": 5, "NumSteps": 3, "MetricsRegex": ".*", }', 'DetailedProfilingConfig': '{"StartStep": 5, "NumSteps": 3, }', 'PythonProfilingConfig': '{"StartStep": 5, "NumSteps": 3, "ProfilerName": "cprofile", "cProfileTimer": "total_time"}', 'LocalPath': '/opt/ml/output/profiler/' # Optional. Local path for profiling outputs } }, ProfilerRuleConfigurations=[ { 'RuleConfigurationName': 'ProfilerReport', # You must specify the correct image URI from https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html 'RuleEvaluatorImage': sagemaker.debugger.get_rule_container_image_uri(region), 'RuleParameters': {'rule_to_invoke': 'ProfilerReport'} } ] ) ###Output _____no_output_____ ###Markdown 2. Analyze Profiling Data Install the SMDebug client library to use Debugger analysis tools ###Code import pip def import_or_install(package): try: __import__(package) except ImportError: pip.main(['install', package]) import_or_install('smdebug') ###Output _____no_output_____ ###Markdown Use SMDebug to retrieve saved output data and use analysis toolsWhile the training is still in progress you can visualize the performance data in SageMaker Studio or in the notebook.Debugger provides utilities to plot system metrics in form of timeline charts or heatmaps. Checkout out the notebook [interactive_analysis_profiling_data.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-debugger/debugger_interactive_analysis_profiling/interactive_analysis_profiling_data.ipynb) for more details. In the following code cell we plot the total CPU and GPU utilization as timeseries charts. To visualize other metrics such as I/O, memory, network you simply need to extend the list passed to `select_dimension` and `select_events`. ###Code from smdebug.profiler.analysis.notebook_utils.training_job import TrainingJob tj = TrainingJob(training_job_name, region) tj.wait_for_sys_profiling_data_to_be_available() from smdebug.profiler.analysis.notebook_utils.timeline_charts import TimelineCharts system_metrics_reader = tj.get_systems_metrics_reader() system_metrics_reader.refresh_event_file_list() view_timeline_charts = TimelineCharts(system_metrics_reader, framework_metrics_reader=None, select_dimensions=["CPU", "GPU"], select_events=["total"]) ###Output _____no_output_____ ###Markdown 3. Download Debugger Profiling Report The profiling report rule will create an html report `profiler-report.html` with a summary of builtin rules and recommenades of next steps. You can find this report in your S3 bucket. ###Code rule_output_path='s3://'+bucket+'/'+project+'/output/'+training_job_name+'/rule-output/ProfilerReport/profiler-output/' ! aws s3 ls {rule_output_path} --recursive ! aws s3 cp {rule_output_path} . --recursive from IPython.display import FileLink display("Click link below to view the profiler report", FileLink("profiler-report.html")) ###Output _____no_output_____ ###Markdown Profiling TensorFlow Multi GPU Multi Node Training Job with Amazon SageMaker DebuggerThis notebook walks you through creating a TensorFlow training job with the SageMaker Debugger profiling feature enabled. It will create a multi GPU multi node training using Horovod. (Optional) Install SageMaker and SMDebugTo use the new Debugger profiling features released in December 2020, ensure that you have the latest versions of Boto3, SageMaker, and SMDebug libraries installed. Use the following cell (switch `install_needed` to `True`) to update the libraries and restarts the Jupyter kernel to apply the updates. ###Code import sys import IPython install_needed = False # should only be True once if install_needed: print("installing deps and restarting kernel") !{sys.executable} -m pip install -U boto3 sagemaker smdebug IPython.Application.instance().kernel.do_shutdown(True) ###Output _____no_output_____ ###Markdown 1. Create a Training Job with Debugger EnabledYou will learn how to use the Boto3 SageMaker client's `create_training_job()` function to start a training job. Start a SageMaker session and retrieve the current region and the default Amazon S3 bucket URI ###Code import sagemaker session = sagemaker.Session() region = session.boto_region_name bucket = session.default_bucket() print(region, bucket) ###Output _____no_output_____ ###Markdown Upload a training script to the S3 bucket ###Code import boto3, tarfile source = 'source.tar.gz' project = 'debugger-boto3-profiling-test' tar = tarfile.open(source, 'w:gz') tar.add ('entry_point/tf-hvd-train.py') tar.close() s3 = boto3.client('s3') s3.upload_file(source, bucket, project+'/'+source) upload_file_path=f"s3://{bucket}/{project}/{source}" print(upload_file_path) ###Output _____no_output_____ ###Markdown Create a Boto3 SageMaker client object ###Code sm = boto3.Session(region_name=region).client("sagemaker") ###Output _____no_output_____ ###Markdown Configure the request body of the `create_training_job()` functionThe following parameters are required to include to the request body for `create_training_job()` function.- `TrainingJobName` - Specify a prefix or a full name if you want to modify- `HyperParameters` - Set up the following items: - `sagemaker_program` and `sagemaker_submit_directory` - The S3 bucket URI of the training script. This enables SageMaker to read the training script from the URI and start a training job. - `sagemaker_mpi` options - Configure these key-value pairs to set up distributed training. - You can also add other hyperparameters for your model.- `AlgorithmSpecification` - Specify `TrainingImage`. In this example, an official TensorFlow DLC image is used. You can also use your own training container images here. - `RoleArn` - **To run the following cell, you must specify the right SageMaker execution role ARN that you want to use for training**.- The `DebugHookConfig` and `DebugRuleConfigurations` are preconfigured for watching loss values and a loss not decreasing issue.- The `ProfilerConfig` and `ProfilerRuleConfigurations` are preconfigured to collect system and framework metrics, initiate all profiling rules, and create a Debugger profiling report.**Important**: For `DebugRuleConfigurations` and `ProfilerRuleConfigurations`, **to run the following cell, you must specify the right Debugger rule image URI from [Amazon SageMaker Debugger Registry URLs for Built-in Rule Evaluators](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html)**. The `sagemaker.debugger.get_rule_container_image_uri(region)` function retrieves the Debugger rule image automatically. For example:- If you are in `us-east-1`, the right image URI is **503895931360**.dkr.ecr.**us-east-1**.amazonaws.com/sagemaker-debugger-rules:latest.- If you are in `us-west-2`, the right image URI is **895741380848**.dkr.ecr.**us-west-2**.amazonaws.com/sagemaker-debugger-rules:latest. ###Code import datetime training_job_name='profiler-boto3-'+datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') sm.create_training_job( TrainingJobName=training_job_name, HyperParameters={ 'sagemaker_program': 'entry_point/tf-hvd-train.py', 'sagemaker_submit_directory': 's3://'+bucket+'/'+project+'/'+source, 'sagemaker_mpi_custom_mpi_options': '-verbose -x HOROVOD_TIMELINE=./hvd_timeline.json -x NCCL_DEBUG=INFO -x OMPI_MCA_btl_vader_single_copy_mechanism=none', 'sagemaker_mpi_enabled': 'true', 'sagemaker_mpi_num_of_processes_per_host': '4' }, AlgorithmSpecification={ 'TrainingImage': '763104351884.dkr.ecr.'+region+'.amazonaws.com/tensorflow-training:2.4.1-gpu-py37-cu110-ubuntu18.04', 'TrainingInputMode': 'File', 'EnableSageMakerMetricsTimeSeries': False }, # You must specify your SageMaker execution role ARN here RoleArn=sagemaker.get_execution_role(), OutputDataConfig={'S3OutputPath': 's3://'+bucket+'/'+project+'/output'}, ResourceConfig={ 'InstanceType': 'ml.p3.8xlarge', 'InstanceCount': 2, 'VolumeSizeInGB': 30 }, StoppingCondition={ 'MaxRuntimeInSeconds': 86400 }, DebugHookConfig={ 'S3OutputPath': 's3://'+bucket+'/'+project+'/debug-output', 'CollectionConfigurations': [ { 'CollectionName': 'losses', 'CollectionParameters' : { 'train.save_interval': '50' } } ] }, DebugRuleConfigurations=[ { 'RuleConfigurationName': 'LossNotDecreasing', # You must specify the correct image URI from https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html 'RuleEvaluatorImage': sagemaker.debugger.get_rule_container_image_uri(region), 'RuleParameters': {'rule_to_invoke': 'LossNotDecreasing'} } ], ProfilerConfig={ 'S3OutputPath': 's3://'+bucket+'/'+project+'/profiler-output', 'ProfilingIntervalInMilliseconds': 500, 'ProfilingParameters': { 'DataloaderProfilingConfig': '{"StartStep": 5, "NumSteps": 3, "MetricsRegex": ".*", }', 'DetailedProfilingConfig': '{"StartStep": 5, "NumSteps": 3, }', 'PythonProfilingConfig': '{"StartStep": 5, "NumSteps": 3, "ProfilerName": "cprofile", "cProfileTimer": "total_time"}', 'LocalPath': '/opt/ml/output/profiler/' # Optional. Local path for profiling outputs } }, ProfilerRuleConfigurations=[ { 'RuleConfigurationName': 'ProfilerReport', # You must specify the correct image URI from https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-docker-images-rules.html 'RuleEvaluatorImage': sagemaker.debugger.get_rule_container_image_uri(region), 'RuleParameters': {'rule_to_invoke': 'ProfilerReport'} } ] ) ###Output _____no_output_____ ###Markdown 2. Analyze Profiling Data Install the SMDebug client library to use Debugger analysis tools ###Code import pip def import_or_install(package): try: __import__(package) except ImportError: pip.main(['install', package]) import_or_install('smdebug') ###Output _____no_output_____ ###Markdown Use SMDebug to retrieve saved output data and use analysis toolsWhile the training is still in progress you can visualize the performance data in SageMaker Studio or in the notebook.Debugger provides utilities to plot system metrics in form of timeline charts or heatmaps. Checkout out the notebook [interactive_analysis_profiling_data.ipynb](https://github.com/aws/amazon-sagemaker-examples/blob/master/sagemaker-debugger/debugger_interactive_analysis_profiling/interactive_analysis_profiling_data.ipynb) for more details. In the following code cell we plot the total CPU and GPU utilization as timeseries charts. To visualize other metrics such as I/O, memory, network you simply need to extend the list passed to `select_dimension` and `select_events`. ###Code from smdebug.profiler.analysis.notebook_utils.training_job import TrainingJob tj = TrainingJob(training_job_name, region) tj.wait_for_sys_profiling_data_to_be_available() from smdebug.profiler.analysis.notebook_utils.timeline_charts import TimelineCharts system_metrics_reader = tj.get_systems_metrics_reader() system_metrics_reader.refresh_event_file_list() view_timeline_charts = TimelineCharts(system_metrics_reader, framework_metrics_reader=None, select_dimensions=["CPU", "GPU"], select_events=["total"]) ###Output _____no_output_____ ###Markdown 3. Download Debugger Profiling Report The profiling report rule will create an html report `profiler-report.html` with a summary of builtin rules and recommenades of next steps. You can find this report in your S3 bucket. ###Code rule_output_path='s3://'+bucket+'/'+project+'/output/'+training_job_name+'/rule-output/ProfilerReport/profiler-output/' ! aws s3 ls {rule_output_path} --recursive ! aws s3 cp {rule_output_path} . --recursive from IPython.display import FileLink display("Click link below to view the profiler report", FileLink("profiler-report.html")) ###Output _____no_output_____
Stacking_Method.ipynb
###Markdown Stacking Method Function Definition Input : origin_df_X : The input(original) features of the data. It is in the dataframe format.origin_df_Y : The input(original) labels of the data. It is in the dataframe formatkfold : The number of folds that is used to do the Stratified K-Fold cross validation.is_debug : The enable signal to turn-on the verbose debug messages.all_basic_classifiers : The dictionary format or "key=val" format of all the classifiers that you want to use to stack. Output : output_df_all : The origin_df_X that is appended with the predicition result of all classifiers in **all_basic_classifiersmodel_dict : The dictioary that stores all the models used in the Stratified Cross Validation. Every classifiers in ** all_basic_classifiers has 'kfold' of classifers with same paramters. ###Code import random import sys import numpy as np import pandas as pd import warnings from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV from datetime import datetime warnings.filterwarnings(action='ignore', category=DeprecationWarning) def StackingMethod(origin_df_X, origin_df_Y, kfold=10, is_debug=0, **all_basic_classifiers): X_train = origin_df_X.values Y_train = origin_df_Y.values.ravel() random.seed(datetime.now()) skf = StratifiedKFold(n_splits=kfold, random_state=random.randint(0, 2**32-1), shuffle=True) iteration = 0 len_y = 0 new_feature_columns = ['Label_'+x for x in all_basic_classifiers.keys()] new_feature_arr = np.zeros([len(X_train), len(new_feature_columns)]) model_dict = {} #Initialize the model list for every classifier for k in all_basic_classifiers.keys(): model_dict[k] = [] for train_index, test_index in skf.split(X_train, Y_train): X_cv_train = X_train[train_index] Y_cv_train = Y_train[train_index] X_cv_test = X_train[test_index] Y_cv_test = Y_train[test_index] column_label_index = 0 if(is_debug): print(f"-----iteration {iteration}-----") print(f'test_index = {test_index}') for k, v in all_basic_classifiers.items(): classifier_cv = v classifier_cv.fit(X_cv_train, Y_cv_train) model_dict[k].append(classifier_cv) Y_cv_test_result = classifier_cv.predict(X_cv_test) count_result_index = 0 for index in test_index: new_feature_arr[index][column_label_index] = Y_cv_test_result[count_result_index] count_result_index += 1 column_label_index += 1 if(is_debug): len_y += len(Y_cv_test_result) print(f'key = {k}, val = {v}') print(f'Y_cv_test_result = {Y_cv_test_result}') print(f'len(Y_cv_test_result) = {len(Y_cv_test_result)}') print(type(Y_cv_test_result)) print('-------') iteration += 1 new_feature_df = pd.DataFrame(data = new_feature_arr, columns = new_feature_columns) output_df_all = pd.concat([origin_df_X, new_feature_df], axis=1, ignore_index=False) if(is_debug): print(f'total len_y = {len_y}') print(f'new_feature_columns = {new_feature_columns}') count_index_fin = 0 for x in new_feature_arr: print(f'index = {count_index_fin}, label = {x}') count_index_fin += 1 return (output_df_all, model_dict) ###Output _____no_output_____ ###Markdown Cross Validation Grid Search Nested Enhanced FunctionIt is enhanced to support those classifiers without tuned_param.On the other words, you can pass empty tuned_param. ###Code def CrossValidationGridSearchNested(origin_df_X, origin_df_Y, num_trials, fold_num, est_classifcation, tuned_param, scoring): X_data = origin_df_X.values Y_data = origin_df_Y.values.ravel() max_score = -1 best_estimator = est_classifcation is_tuned_param_empty = (tuned_param == []) | (tuned_param == None) for i in range(num_trials): inner_cv = StratifiedKFold(n_splits=fold_num, random_state=i, shuffle=True) outer_cv = StratifiedKFold(n_splits=fold_num, random_state=i+1, shuffle=True) if(is_tuned_param_empty): param_score = cross_val_score(est_classifcation, X=X_data, y=Y_data, cv=outer_cv, scoring=scoring).mean() else: # Non_nested parameter search and scoring clf = GridSearchCV(estimator=est_classifcation, param_grid=tuned_param, cv=inner_cv, scoring=scoring) clf.fit(X_data, Y_data) # CV with parameter optimization param_score = cross_val_score(clf.best_estimator_, X=X_data, y=Y_data, cv=outer_cv, scoring=scoring).mean() if(param_score > max_score): max_score = param_score if(is_tuned_param_empty): best_estimator = est_classifcation else: best_estimator = clf.best_estimator_ progress = (i+1)/num_trials*100 print(f'> progress = {progress}%') return (max_score, best_estimator) ###Output _____no_output_____ ###Markdown ExampleIt is an example to 1. Use CrossValidationGridSearchNested to find the best paramters of both SVM and NaiveBayes classifiers as the basic classifier. 2. Use the best parameters of SVM and NaiveBayes classifiers to stack the origin feature space, or in other words, to find out and combine two new features that are individually from the cross validation result of SVM and NaiveBayes classifiers. The output is the new dataframe with spanned features. Load the breast canced database ###Code from sklearn.datasets import load_breast_cancer data = load_breast_cancer() X = data.data Y = data.target print(f'shape of X = {X.shape}') print(f'shape of Y = {Y.shape}') X Y ###Output _____no_output_____ ###Markdown Transform X and Y to the format of dataframe. Use CrossValidationGridSearchNested to find out the best parameters of SVM and NaiveBayes classifiers. NaiveBayes part pass the empty tuned_param and the input is supported by CrossValidationGridSearchNested now. ###Code #----------------Generate original df for reference-------------------# org_columns = ["col_org_"+str(x) for x in range(0, len(X[0]), 1)] original_df_X = pd.DataFrame(data = X, columns = org_columns) org_columns = ["Label"+str(x) for x in range(0, len(Y.reshape(len(Y), 1)[0]), 1)] original_df_Y = pd.DataFrame(data = Y.reshape(len(Y), 1), columns = org_columns) #----------------Tuned SVM-------------------# from sklearn.svm import SVC # Set the parameters by cross-validation tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] # Number of random trials NUM_TRIALS = 10 # We will use a Support Vector Classifier with "rbf" kernel svm = SVC() (max_score, svm_best_estimator) = CrossValidationGridSearchNested(original_df_X, original_df_Y, NUM_TRIALS, 10, svm, tuned_parameters, 'roc_auc') svm_best_parameter = svm_best_estimator.get_params() print(f'\nmax_score = {max_score}\n') print(f'\nbest_estimator = {svm_best_estimator}\n') print(f'\nbest_parameter = {svm_best_parameter}\n') #----------------Tuned Naive Bayes - Gaussian-------------------# from sklearn.naive_bayes import GaussianNB # Set the parameters by cross-validation tuned_parameters = [] # Number of random trials NUM_TRIALS = 10 clf = GaussianNB() (max_score, gau_nb_best_estimator) = CrossValidationGridSearchNested(original_df_X, original_df_Y, NUM_TRIALS, 10, clf, tuned_parameters, 'roc_auc') gau_nb_best_parameter = gau_nb_best_estimator.get_params() print(f'\nmax_score = {max_score}\n') print(f'\nbest_estimator = {gau_nb_best_estimator}\n') print(f'\nbest_parameter = {gau_nb_best_parameter}\n') ###Output > progress = 10.0% > progress = 20.0% > progress = 30.0% > progress = 40.0% > progress = 50.0% > progress = 60.0% > progress = 70.0% > progress = 80.0% > progress = 90.0% > progress = 100.0% max_score = 0.9928779289493574 best_estimator = SVC(C=1000, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='auto', kernel='linear', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) best_parameter = {'C': 1000, 'cache_size': 200, 'class_weight': None, 'coef0': 0.0, 'decision_function_shape': 'ovr', 'degree': 3, 'gamma': 'auto', 'kernel': 'linear', 'max_iter': -1, 'probability': False, 'random_state': None, 'shrinking': True, 'tol': 0.001, 'verbose': False} > progress = 10.0% > progress = 20.0% > progress = 30.0% > progress = 40.0% > progress = 50.0% > progress = 60.0% > progress = 70.0% > progress = 80.0% > progress = 90.0% > progress = 100.0% max_score = 0.989685975400261 best_estimator = GaussianNB(priors=None) best_parameter = {'priors': None} ###Markdown Use the svm_best_estimator and gau_nb_best_estimator that are with best paramters of SVM and NaiveBayes classifiers find out by CrossValidationGridSearchNested. StackingMethod will output the new_df that has two new features generated from the Stratified Cross Validation by svm_best_estimator and gau_nb_best_estimator ###Code all_classifier = {'svm_classifier':svm_best_estimator, 'naive_bayse_gaussian_classifier':gau_nb_best_estimator} is_debug = 1 new_df, model_dict = StackingMethod(original_df_X, original_df_Y, 10, is_debug, **all_classifier) #another usage : #new_df = StackingMethod(original_df_X, original_df_Y, 10, svm_classifier=svm, naive_bayse_gaussian_classifier=gau_nb_best_estimator) new_df ###Output _____no_output_____ ###Markdown Combine with the original groundtruth Label(Y) see the result. ###Code new_df['Label'] = original_df_Y['Label0'] new_df ###Output _____no_output_____
Data_Science_2-4 _ Assignment_Week_3_EDA.ipynb
###Markdown ![](https://i.imgur.com/0AUxkXt.png) Assignment 3 - From data to insightsBefore you explore the data, write down a short list of what you expect to see in the data: the distribution of key variables, the relationships between important pairs of them, and so on. Such a list is essentially a prediction based on your current understanding of the business.Now analyze the data. Make plots, do summaries, whatever is needed to see if it matches your expectations.Is there anything that doesn’t match? Anything that makes you go “That’s odd” or “That doesn’t make any sense.”?Zoom in and try to understand what in your business is making that weird thing show up in the data like that. This is the critical step.You may have just found an insight into the business and increased your understanding The data analysis checklistThis checklist can be used as a guide during the process of a data analysis, or as a way to evaluate the quality of a reported data analysis. Answering the first questions1. Did you define the metric for success before beginning?2. Did you understand the context for the question and business application?3. Did you consider whether the question could be answered with the available data? Cleaning the data1. Did you identify the missing data?2. Is each variable one column?3. Do different data types appear in each table?4. Did you try to identify any errors or miscoding of variables?5. Did you check for outliers? Exploratory analysis1. Did you make univariate plots (histogram, distplot, boxplot)?2. Did you consider correlations between variables (scatterplot, jointplot, kde plot, correlation matrix)?3. Did you check the units of all data points to make sure they are in the right range? Presentations1. Did you lead with a brief, understandable to everyone of your problem?2. Did you explain the data, describe the question of interest?3. Did you make sure all legends and axes were legible from the back of the room? Dataset - Online Retailes PurchaseTypically e-commerce datasets are proprietary and consequently hard to find among publicly available data. However, [The UCI Machine Learning Repository](http://archive.ics.uci.edu/ml/index.php) has made this dataset containing actual transactions from 2010 and 2011. The dataset is maintained on their site, where it can be found by the title "Online Retail". Step 1 - Checking the data**Import tools set** ###Code # Your code here import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import datetime as dt %matplotlib inline import warnings warnings.filterwarnings('ignore') ###Output _____no_output_____ ###Markdown **Import data** ###Code link = "https://ml101-khanhnguyen.s3-ap-southeast-1.amazonaws.com/devc/Online_Retail.csv" # Note: set param encoding = 'latin1' # Your code here onre = pd.read_csv(link, encoding='latin1') # Print out First 5 rows from dataframe # Your code here onre.head(5) # Print out brief info onre.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 541909 entries, 0 to 541908 Data columns (total 8 columns): InvoiceNo 541909 non-null object StockCode 541909 non-null object Description 540455 non-null object Quantity 541909 non-null int64 InvoiceDate 541909 non-null object UnitPrice 541909 non-null float64 CustomerID 406829 non-null float64 Country 541909 non-null object dtypes: float64(2), int64(1), object(5) memory usage: 33.1+ MB ###Markdown Step 2 - Cleaning the dataFew of useful data cleaning functions:* `s.astype('category')` This will convert the datatype of the series to float *Please note that "s" here is a Pandas Series* `s.replace(1,'one')` This will replace all values equal to 1 with 'one'* `s.replace([1,3],['one','three'])` This will replace all 1 with 'one' and 3 with 'three'* `data.rename(columns=lambda x: x + 1)` Mass renaming of columns* `data.rename(columns={'oldname': 'new name'})` Selective renaming* `data.set_index('column_one')` This will change the index* `data.rename(index=lambda x: x + 1)` Mass renaming of index* `data.dropna()` Remove missing values* `data.fillna(x)` This will replaces all null values with x* `s.fillna(s.mean())` This will replace all null values with the mean (mean can be replaced with almost any function from the below section) :* `data.corr()` This will return the correlation between columns in a DataFrame* `data.count()` This will return the number of non-null values in each DataFrame column* `data.max()` This will return the highest value in each column* `data.min()` This will return the lowest value in each column* `data.median()` This will return the median of each column* `data.std()` This will returns the standard deviation of each column ###Code onre.columns ###Output _____no_output_____ ###Markdown **Check for NaN values** ###Code # Your code here onre.isnull().sum() ###Output _____no_output_____ ###Markdown **Examine few examples of NaN values** ###Code onre[onre['CustomerID'].isnull()] # List all NaN values onre[onre['Description'].isnull()] ###Output _____no_output_____ ###Markdown **Exclude negative Quatity entries** ###Code onre = onre[onre['Quantity'] > 0] ###Output _____no_output_____ ###Markdown **Exclude negative Price entries** ###Code onre = onre[onre['UnitPrice'] > 0] ###Output _____no_output_____ ###Markdown Step 3 - EDA **The customer with the highest number of orders comes from the United Kingdom (UK)** ###Code # Your code here onre['AmountSpent'] = onre['Quantity'] * onre['UnitPrice'] onre['Country'].unique() onre[onre['Country'] == 'United Kingdom'].groupby('CustomerID').count().sort_values('Quantity', ascending=False).head(1) ###Output _____no_output_____ ###Markdown **The customer with the highest money spent on purchases comes from Netherlands** ###Code # Your code here # onre.sort_values('AmountSpent', ascending=False).head(5) onre[onre['Country'] == 'Netherlands'].groupby('CustomerID').sum().sort_values('AmountSpent', ascending=False).head(1) ###Output _____no_output_____ ###Markdown **On which year had the highest sales?** ###Code # Your code here onre['InvoiceDate'] = pd.to_datetime(onre['InvoiceDate']) onre['InvoiceYear'] = onre['InvoiceDate'].dt.year onre[['AmountSpent', 'InvoiceYear']].groupby('InvoiceYear').sum() ###Output _____no_output_____ ###Markdown **How many orders (per hour)?** ###Code onre['InvoiceHour'] = onre['InvoiceDate'].dt.hour onre.groupby('InvoiceNo')['InvoiceHour'].unique().value_counts().iloc[:-1].sort_index() ###Output _____no_output_____ ###Markdown **Make a plot about number of orders per hour** ###Code onre.groupby('InvoiceNo')['InvoiceHour'].unique().value_counts().iloc[:-1].sort_index().plot(kind='bar') ###Output _____no_output_____ ###Markdown **How many orders (per month)?** ###Code onre['InvoiceMonth'] = onre['InvoiceDate'].dt.month onre.groupby('InvoiceNo')['InvoiceMonth'].unique().value_counts().sort_index() ###Output _____no_output_____ ###Markdown **Make a plot about number of orders per month** ###Code onre.groupby('InvoiceNo')['InvoiceMonth'].unique().value_counts().sort_index().plot(kind='bar'); ###Output _____no_output_____ ###Markdown **Top 10 items most sales** ###Code onre.groupby('StockCode')['Quantity'].sum().sort_values(ascending=False).head(10) ###Output _____no_output_____ ###Markdown **Create a histogram with the 10 countries that have the most 'Quantity' ordered except UK** ###Code # Your code here onre[onre['Country'] != 'United Kingdom'].groupby('Country').sum().sort_values('Quantity', ascending=False).head(10) # What can you tell about this? # To be honest, I am not sure about what I do. This historogram is right knewness because Its tail has a positive skew to the right. # If it doesn’t include UK in the chart, Netherlands is the only country that has over 200000 orders # and the other countries have less than 100000 orders. top_quantity = onre[onre['Country'] != 'United Kingdom'].groupby('Country').sum().sort_values('Quantity', ascending=False).head(10) sns.distplot(top_quantity['Quantity'], bins=20); ###Output _____no_output_____
M5 Pridictive Modeling/M5 W2 Logistics Regression/Predictive Modelling - Logistic Regression - Student Version.ipynb
###Markdown Problem Statement WHO is a specialized agency of the UN which is concerned with the world population health. Based upon the various parameters, WHO allocates budget for various areas to conduct various campaigns/initiatives to improve healthcare. Annual salary is an important variable which is considered to decide budget to be allocated for an area. We have a data which contains information about 32561 samples and 15 continuous and categorical variables. Extraction of data was done from 1994 Census dataset. The goal here is to build a binary model to predict whether the salary is >50K or <50K. Data Dictionary 1. age: age 2. workclass: workclass 3. fnlwgt: samplting weight 4. education: highest education 5. education-no. of years: number of years of education in total 6. marrital status: marrital status 7. occupation: occupation 8. relationship: relationship 9. race: race 10. sex: sex 11. capital gain: income from investment sources other than salary/wages 12. capital loss: income from investment sources other than salary/wages 13. working hours: nummber of working hours per week 14. native-country: native country 15. salary: salary ###Code import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split,GridSearchCV from sklearn.linear_model import LogisticRegression from sklearn import metrics from sklearn.metrics import roc_auc_score,roc_curve,classification_report,confusion_matrix,plot_confusion_matrix adult_data=pd.read_csv("adult.data.csv") ###Output _____no_output_____ ###Markdown EDA ###Code adult_data.head() adult_data.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 32561 entries, 0 to 32560 Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 age 32561 non-null int64 1 workclass 32561 non-null object 2 fnlwgt 32561 non-null int64 3 education 32561 non-null object 4 education-no. of years 32561 non-null int64 5 marrital status 32561 non-null object 6 occupation 32561 non-null object 7 relationship 32561 non-null object 8 race 32561 non-null object 9 sex 32561 non-null object 10 capital gain 32561 non-null int64 11 capital loss 32561 non-null int64 12 working hours per week 32561 non-null int64 13 native-country 32561 non-null object 14 salary 32561 non-null object dtypes: int64(6), object(9) memory usage: 3.7+ MB ###Markdown There are no missing values. 6 variables are numeric and remaining categorical. Categorical variables are not in encoded format Check for duplicate data There are 24 duplicates that needs to be removed ###Code adult_data.drop_duplicates(inplace=True) dups = adult_data.duplicated() print('Number of duplicate rows = %d' % (dups.sum())) print(adult_data.shape) ###Output Number of duplicate rows = 0 (32537, 15) ###Markdown Geting unique counts of all Objects ###Code adult_data.salary.value_counts(normalize=True) for feature in adult_data.columns: if adult_data[feature].dtype == 'object': print(feature) print(adult_data[feature].value_counts()) print('\n') ###Output workclass Private 22673 Self-emp-not-inc 2540 Local-gov 2093 ? 1836 State-gov 1298 Self-emp-inc 1116 Federal-gov 960 Without-pay 14 Never-worked 7 Name: workclass, dtype: int64 education HS-grad 10494 Some-college 7282 Bachelors 5353 Masters 1722 Assoc-voc 1382 11th 1175 Assoc-acdm 1067 10th 933 7th-8th 645 Prof-school 576 9th 514 12th 433 Doctorate 413 5th-6th 332 1st-4th 166 Preschool 50 Name: education, dtype: int64 marrital status Married-civ-spouse 14970 Never-married 10667 Divorced 4441 Separated 1025 Widowed 993 Married-spouse-absent 418 Married-AF-spouse 23 Name: marrital status, dtype: int64 occupation Prof-specialty 4136 Craft-repair 4094 Exec-managerial 4065 Adm-clerical 3768 Sales 3650 Other-service 3291 Machine-op-inspct 2000 ? 1843 Transport-moving 1597 Handlers-cleaners 1369 Farming-fishing 992 Tech-support 927 Protective-serv 649 Priv-house-serv 147 Armed-Forces 9 Name: occupation, dtype: int64 relationship Husband 13187 Not-in-family 8292 Own-child 5064 Unmarried 3445 Wife 1568 Other-relative 981 Name: relationship, dtype: int64 race White 27795 Black 3122 Asian-Pac-Islander 1038 Amer-Indian-Eskimo 311 Other 271 Name: race, dtype: int64 sex Male 21775 Female 10762 Name: sex, dtype: int64 native-country United-States 29153 Mexico 639 ? 582 Philippines 198 Germany 137 Canada 121 Puerto-Rico 114 El-Salvador 106 India 100 Cuba 95 England 90 Jamaica 81 South 80 China 75 Italy 73 Dominican-Republic 70 Vietnam 67 Guatemala 62 Japan 62 Poland 60 Columbia 59 Taiwan 51 Haiti 44 Iran 43 Portugal 37 Nicaragua 34 Peru 31 France 29 Greece 29 Ecuador 28 Ireland 24 Hong 20 Cambodia 19 Trinadad&Tobago 19 Thailand 18 Laos 18 Yugoslavia 16 Outlying-US(Guam-USVI-etc) 14 Hungary 13 Honduras 13 Scotland 12 Holand-Netherlands 1 Name: native-country, dtype: int64 salary <=50K 24698 >50K 7839 Name: salary, dtype: int64 ###Markdown workclass, occupation,native-country has ? Since, high number of cases have ?, we will convert them into a new level ###Code # Replace ? to new Unk category adult_data.describe() ###Output _____no_output_____ ###Markdown Checking the spread of the data using boxplot for the continuous variables. ###Code cols = ['age','fnlwgt','education-no. of years','capital gain','capital loss','working hours per week'] ###Output _____no_output_____ ###Markdown Treating the outliers. We can treat Outliers with the following code. We will treat the outliers for the 'Age' variable only. ###Code def remove_outlier(col): sorted(col) Q1,Q3=np.percentile(col,[25,75]) IQR=Q3-Q1 lower_range= Q1-(1.5 * IQR) upper_range= Q3+(1.5 * IQR) return lower_range, upper_range ## This is a loop to treat outliers for all the non-'object' type varible # for column in adult_data.columns: # if adult_data[column].dtype != 'object': # lr,ur=remove_outlier(adult_data[column]) # adult_data[column]=np.where(adult_data[column]>ur,ur,adult_data[column]) # adult_data[column]=np.where(adult_data[column]<lr,lr,adult_data[column]) cols = ['age','fnlwgt','education-no. of years','capital gain','capital loss','working hours per week'] ###Output _____no_output_____ ###Markdown Checking for Correlations. ###Code adult_data.corr() adult_data.describe() ###Output _____no_output_____ ###Markdown There is hardly any correlation between the numeric variables ###Code # Pairplot using sns sns.pairplot(adult_data ,diag_kind='hist' ,hue='salary'); ###Output _____no_output_____ ###Markdown Converting all objects to categorical codes ###Code adult_data.head() ###Output _____no_output_____ ###Markdown Train Test Split ###Code # Copy all the predictor variables into X dataframe # Copy target into the y dataframe. # Split X and y into training and test set in 70:30 ratio ###Output _____no_output_____ ###Markdown Logistic Regression ModelWe are making some adjustments to the parameters in the Logistic Regression Class to get a better accuracy. Details of which can be found out on the site scikit-learn mentioned belowscikit-learn>Argument=solver{‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’}, default=’lbfgs’Algorithm to use in the optimization problem.>For small datasets, ‘liblinear’ is a good choice, whereas ‘sag’ and ‘saga’ are faster for large ones.>For multiclass problems, only ‘newton-cg’, ‘sag’, ‘saga’ and ‘lbfgs’ handle multinomial loss; ‘liblinear’ is limited to one-versus-rest schemes.>‘newton-cg’, ‘lbfgs’, ‘sag’ and ‘saga’ handle L2 or no penalty>‘liblinear’ and ‘saga’ also handle L1 penalty>‘saga’ also supports ‘elasticnet’ penalty>‘liblinear’ does not support setting penalty='none'>Note that ‘sag’ and ‘saga’ fast convergence is only guaranteed on features with approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing.>New in version 0.17: Stochastic Average Gradient descent solver.>New in version 0.19: SAGA solver.>Changed in version 0.22: The default solver changed from ‘liblinear’ to ‘lbfgs’ in 0.22. Article on Solvers ###Code # Fit the Logistic Regression model ###Output [Parallel(n_jobs=2)]: Using backend LokyBackend with 2 concurrent workers. [Parallel(n_jobs=2)]: Done 1 out of 1 | elapsed: 10.6s finished ###Markdown Predicting on Training and Test dataset ###Code ###Output _____no_output_____ ###Markdown Getting the Predicted Classes and Probs ###Code ###Output _____no_output_____ ###Markdown Model Evaluation ###Code # Accuracy - Training Data ###Output _____no_output_____ ###Markdown AUC and ROC for the training data ###Code # predict probabilities # keep probabilities for the positive outcome only # calculate AUC # calculate roc curve # plot the roc curve for the model # Accuracy - Test Data ###Output _____no_output_____ ###Markdown AUC and ROC for the test data ###Code # predict probabilities # keep probabilities for the positive outcome only # calculate AUC # calculate roc curve # plot the roc curve for the model ###Output AUC: 0.856
jupyter_notebooks/statistics/Distribution_Comparisons_and_ANOVA.ipynb
###Markdown Statistical Analysis in PythonIn this section, we introduce a few useful methods for analyzing your data in Python.Namely, we cover how to compute the mean, variance, and standard error of a data set.For more advanced statistical analysis, we cover how to perform aMann-Whitney-Wilcoxon (MWW) RankSum test, how to perform an Analysis of variance (ANOVA)between multiple data sets. Python's SciPy ModuleThe majority of data analysis in Python can be performed with the SciPy module. SciPyprovides a plethora of statistical functions and tests that will handle the majority ofyour analytical needs. If we don't cover a statistical function or test that you requirefor your research, SciPy's full statistical library is described in detail at:http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html Python's pandas ModuleThe pandas module provides powerful, efficient, R-like DataFrame objects capable ofcalculating statistics en masse on the entire DataFrame. DataFrames are useful for whenyou need to compute statistics over multiple replicate runs.For the purposes of this tutorial, we will use Luis' parasite data set: ###Code import pandas as pd # must specify that blank space " " is NaN experimentDF = pd.read_csv("data_sets/parasite_data.csv", na_values=" ") experimentDF.head() ###Output _____no_output_____ ###Markdown Accessing data in pandas DataFramesYou can directly access any column and row by indexing the DataFrame. ###Code # show all entries in the Virulence column experimentDF.Virulence # show the 12th row in the ShannonDiversity column experimentDF.ShannonDiversity[12] ###Output _____no_output_____ ###Markdown You can also access all of the values in a column meeting a certain criteria. ###Code # show all entries in the ShannonDiversity column > 2.0 experimentDF.query("ShannonDiversity > 2.0") ###Output _____no_output_____ ###Markdown Blank/omitted data (NA or NaN) in pandas DataFramesBlank/omitted data is a piece of cake to handle in pandas. Here's an example dataset with NA/NaN values. ###Code experimentDF[experimentDF.Virulence.isnull()] ###Output _____no_output_____ ###Markdown DataFrame methods automatically ignore NA/NaN values. ###Code print("Mean virulence across all treatments:", experimentDF["Virulence"].mean()) ###Output Mean virulence across all treatments: 0.75 ###Markdown However, not all methods in Python are guaranteed to handle NA/NaN values properly. ###Code from scipy import stats print("Mean virulence across all treatments:", stats.sem(experimentDF["Virulence"])) ###Output Mean virulence across all treatments: nan ###Markdown Thus, it behooves you to take care of the NA/NaN values before performing your analysis. You can either:**(1) filter out all of the entries with NA/NaN** ###Code # NOTE: this drops the entire row if any of its entries are NA/NaN! experimentDF.dropna().info() ###Output <class 'pandas.core.frame.DataFrame'> Int64Index: 300 entries, 0 to 299 Data columns (total 3 columns): Virulence 300 non-null float64 Replicate 300 non-null int64 ShannonDiversity 300 non-null float64 dtypes: float64(2), int64(1) memory usage: 9.4 KB ###Markdown If you only care about NA/NaN values in a specific column, you can specify thecolumn name first. ###Code print(experimentDF["Virulence"].dropna()) ###Output 0 0.5 1 0.5 2 0.5 3 0.5 4 0.5 5 0.5 6 0.5 7 0.5 8 0.5 9 0.5 10 0.5 11 0.5 12 0.5 13 0.5 14 0.5 15 0.5 16 0.5 17 0.5 18 0.5 19 0.5 20 0.5 21 0.5 22 0.5 23 0.5 24 0.5 25 0.5 26 0.5 27 0.5 28 0.5 29 0.5 ... 270 1.0 271 1.0 272 1.0 273 1.0 274 1.0 275 1.0 276 1.0 277 1.0 278 1.0 279 1.0 280 1.0 281 1.0 282 1.0 283 1.0 284 1.0 285 1.0 286 1.0 287 1.0 288 1.0 289 1.0 290 1.0 291 1.0 292 1.0 293 1.0 294 1.0 295 1.0 296 1.0 297 1.0 298 1.0 299 1.0 Name: Virulence, dtype: float64 ###Markdown **(2) replace all of the NA/NaN entries with a valid value** ###Code experimentDF.fillna(0.0)["Virulence"] ###Output _____no_output_____ ###Markdown Take care when deciding what to do with NA/NaN entries. It can have a significantimpact on your results! ###Code print("Mean virulence across all treatments w/ dropped NaN:", experimentDF["Virulence"].dropna().mean()) print("Mean virulence across all treatments w/ filled NaN:", experimentDF.fillna(0.0)["Virulence"].mean()) ###Output Mean virulence across all treatments w/ dropped NaN: 0.75 Mean virulence across all treatments w/ filled NaN: 0.642857142857 ###Markdown MeanThe mean performance of an experiment gives a good idea of how the experiment willturn out *on average* under a given treatment.Conveniently, DataFrames have all kinds of built-in functions to perform standardoperations on them en masse: `add()`, `sub()`, `mul()`, `div()`, `mean()`, `std()`, etc.The full list is located at: http://pandas.sourceforge.net/generated/pandas.DataFrame.htmlThus, computing the mean of a DataFrame only takes one line of code: ###Code from pandas import * print("Mean Shannon Diversity w/ 0.8 Parasite Virulence =", experimentDF[experimentDF["Virulence"] == 0.8]["ShannonDiversity"].mean()) ###Output Mean Shannon Diversity w/ 0.8 Parasite Virulence = 1.2691338188 ###Markdown VarianceThe variance in the performance provides a measurement of how consistent the resultsof an experiment are. The lower the variance, the more consistent the results are, andvice versa.Computing the variance is also built in to pandas DataFrames: ###Code from pandas import * print("Variance in Shannon Diversity w/ 0.8 Parasite Virulence =", experimentDF[experimentDF["Virulence"] == 0.8]["ShannonDiversity"].var()) ###Output Variance in Shannon Diversity w/ 0.8 Parasite Virulence = 0.611038433313 ###Markdown Standard Error of the Mean (SEM)Combined with the mean, the SEM enables you to establish a range around a mean thatthe majority of any future replicate experiments will most likely fall within.pandas DataFrames don't have methods like SEM built in, but since DataFramerows/columns are treated as lists, you can use any NumPy/SciPy method you like on them. ###Code from pandas import * from scipy import stats print("SEM of Shannon Diversity w/ 0.8 Parasite Virulence =", stats.sem(experimentDF[experimentDF["Virulence"] == 0.8]["ShannonDiversity"])) ###Output SEM of Shannon Diversity w/ 0.8 Parasite Virulence = 0.110547585529 ###Markdown A single SEM will usually envelop 68% of the possible replicate meansand two SEMs envelop 95% of the possible replicate means. TwoSEMs are called the "estimated 95% confidence interval." The confidenceinterval is estimated because the exact width depend on how many replicatesyou have; this approximation is good when you have more than 20 replicates. Mann-Whitney-Wilcoxon (MWW) RankSum testThe MWW RankSum test is a useful test to determine if two distributions are significantlydifferent or not. Unlike the t-test, the RankSum test does not assume that the dataare normally distributed, potentially providing a more accurate assessment of the data sets.As an example, let's say we want to determine if the results of the two followingtreatments significantly differ or not: ###Code # select two treatment data sets from the parasite data treatment1 = experimentDF[experimentDF["Virulence"] == 0.5]["ShannonDiversity"] treatment2 = experimentDF[experimentDF["Virulence"] == 0.8]["ShannonDiversity"] print("Data set 1:\n", treatment1) print("Data set 2:\n", treatment2) ###Output Data set 1: 0 0.059262 1 1.093600 2 1.139390 3 0.547651 4 0.065928 5 1.344330 6 1.680480 7 0.000000 8 2.047680 9 0.000000 10 1.507140 11 0.000000 12 1.589810 13 1.144800 14 1.011190 15 0.000000 16 0.776665 17 0.001749 18 1.761200 19 0.021091 20 0.790915 21 0.000000 22 0.018866 23 0.994268 24 1.729620 25 0.967537 26 0.457318 27 0.992525 28 1.506640 29 0.697241 30 1.790580 31 1.787710 32 0.857742 33 0.000000 34 0.445267 35 0.045471 36 0.003490 37 0.000000 38 0.115830 39 0.980076 40 0.000000 41 0.820405 42 0.124755 43 0.719755 44 0.584252 45 1.937930 46 1.284150 47 1.651680 48 0.000000 49 0.000000 Name: ShannonDiversity, dtype: float64 Data set 2: 150 1.433800 151 2.079700 152 0.892139 153 2.384740 154 0.006980 155 1.971760 156 0.000000 157 1.428470 158 1.715950 159 0.000000 160 0.421927 161 1.179920 162 0.932470 163 2.032520 164 0.960912 165 2.384150 166 1.879130 167 1.238890 168 1.584300 169 1.118490 170 2.022970 171 0.000000 172 2.138820 173 2.533390 174 1.212340 175 0.059135 176 1.578260 177 1.725210 178 0.293153 179 0.000000 180 0.000000 181 1.699600 182 2.178650 183 1.792580 184 1.920800 185 0.000000 186 1.583250 187 0.343235 188 1.980010 189 0.980876 190 1.089380 191 0.979254 192 1.190450 193 1.738880 194 1.154100 195 1.981610 196 2.077180 197 1.566410 198 0.000000 199 1.990900 Name: ShannonDiversity, dtype: float64 ###Markdown A RankSum test will provide a P value indicating whether or not the twodistributions are the same. ###Code from scipy import stats z_stat, p_val = stats.ranksums(treatment1, treatment2) print("MWW RankSum P for treatments 1 and 2 =", p_val) ###Output MWW RankSum P for treatments 1 and 2 = 0.000983355902735 ###Markdown If P <= 0.05, we are highly confident that the distributions significantly differ, andcan claim that the treatments had a significant impact on the measured value.If the treatments do *not* significantly differ, we could expect a result such asthe following: ###Code treatment3 = experimentDF[experimentDF["Virulence"] == 0.8]["ShannonDiversity"] treatment4 = experimentDF[experimentDF["Virulence"] == 0.9]["ShannonDiversity"] print("Data set 3:\n", treatment3) print("Data set 4:\n", treatment4) z_stat, p_val = stats.ranksums(treatment3, treatment4) print("MWW RankSum P for treatments 3 and 4 =", p_val) ###Output MWW RankSum P for treatments 3 and 4 = 0.994499571124 ###Markdown With P > 0.05, we must say that the distributions do not significantly differ.Thus changing the parasite virulence between 0.8 and 0.9 does not result in asignificant change in Shannon Diversity. One-way analysis of variance (ANOVA)If you need to compare more than two data sets at a time, an ANOVA is your best bet. Forexample, we have the results from three experiments with overlapping 95% confidenceintervals, and we want to confirm that the results for all three experiments are notsignificantly different. ###Code treatment1 = experimentDF[experimentDF["Virulence"] == 0.7]["ShannonDiversity"] treatment2 = experimentDF[experimentDF["Virulence"] == 0.8]["ShannonDiversity"] treatment3 = experimentDF[experimentDF["Virulence"] == 0.9]["ShannonDiversity"] print("Data set 1:\n", treatment1) print("Data set 2:\n", treatment2) print("Data set 3:\n", treatment3) from scipy import stats f_val, p_val = stats.f_oneway(treatment1, treatment2, treatment3) print("One-way ANOVA P =", p_val) ###Output One-way ANOVA P = 0.381509481874
experiments/interaction/experiment_180201_1514_1k_36rot_fixed.ipynb
###Markdown Predictions ###Code pred.describe() for i in range(ti.num_objects): plt.figure() _ = plt.hist2d(pred['%d_x' % i], pred['%d_y' % i], bins=40, range=((0, 199), (0, 199))) plt.colorbar() for i in range(ti.num_objects): plt.figure() plt.title('predicted angles for object %d (deg)' % i) (pred['%d_angle_deg' % i]).hist() for i in range(ti.num_objects): plt.figure() plt.title('predicted angles mod 180 for object %d (deg)' % i) (pred['%d_angle_deg' % i] % 180).hist() ###Output _____no_output_____ ###Markdown Prediction Errors ###Code xy, angle, indices = ti.match_pred_to_gt(pred[ti.columns()].values, y_test[ti.columns()].values, np) if ti.num_objects == 1: xy_errors = xy angle_errors = angle elif ti.num_objects == 2: xy_errors = (xy[indices[:, 0], indices[:, 1]]) angle_errors = (angle[indices[:, 0], indices[:, 1]]) else: assert False, 'not implemented' df = pd.DataFrame.from_items([('xy (px)', [xy_errors.mean()]), ('angle (deg)', angle_errors.mean()),]) df.style.set_caption('MAE') df _ = plt.hist(xy_errors, 20) plt.title('xy errors') plt.xlabel('mean absolute error (px)') plt.ylabel('count') _ = plt.hist(angle_errors, 20) # , range=(0, 20)) plt.title('angle errors') plt.xlabel('mean absolute error (deg)') plt.ylabel('count') plt.figure() _ = plt.hist(angle_errors, 20, range=(0, 20)) plt.title('angle errors (lower than 20 deg)') plt.xlabel('mean absolute error (deg)') plt.ylabel('count') ###Output _____no_output_____ ###Markdown Model ###Code from IPython.display import SVG from keras.utils.vis_utils import model_to_dot SVG(model_to_dot(ti.model(), show_shapes=True).create(prog='dot', format='svg')) ###Output _____no_output_____
notebooks/nclt_evaluation.ipynb
###Markdown Recall ###Code experiments = ['resnet50_delf_global-max-pool', 'netvlad', 'mobilenetvlad_depth-0.35'] ref_seq = '2012-01-08' query_seqs = ['2013-02-23', '2012-08-20'] plt.figure(dpi=150) colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] for e, c in zip(experiments, colors): m = nclt_recall(ref_seq, query_seqs, e, max_num_nn=30, pca_dim=0) plt.plot(1+np.arange(len(m)), 100*m, label=e, color=c, linewidth=1); m = nclt_recall(ref_seq, query_seqs, e, max_num_nn=30, pca_dim=512) plt.plot(1+np.arange(len(m)), 100*m, label=e+'_proj512', color=c, linewidth=1.3, linestyle='--'); plt.xticks([1]+np.arange(10, 31, step=10).tolist()); plt.grid(color=[0.85]*3); plt.legend(loc=9, bbox_to_anchor=(0.5, -0.2)); plt.xlabel('Number of queried neighbors'), plt.ylabel('Recall@N (%)'); ###Output _____no_output_____ ###Markdown NN search run-time, recall, and PCA dimensionality ###Code experiment = 'mobilenetvlad_depth-0.35' ref_seq = '2012-01-08' query_seqs = ['2013-02-23', '2012-08-20'] dims = [32, 64, 128, 512, 1024, 0] timings = [0.5, 0.8, 1.4, 3.1, 3.9, 12.2] # as measured on the Jetson annotations = ['{}'.format(d) for d in dims[:-1]] + ['Unprojected: 4096'] offsets = [(0.25, 0), (0.3, 0), (0.34, -0.003), (-1.55, 0.003), (0.84, 0), (-3.5, -0.021)] plt.figure(figsize=(4.8, 3.2), dpi=150) for d, t, a, o in zip(dims, timings, annotations, offsets): r = nclt_recall(ref_seq, query_seqs, experiment, max_num_nn=10, pca_dim=d)[-1] plt.scatter(t, r, c=colors[2], s=(d if d != 0 else 4096)*0.75, edgecolors='k', linewidths=0.5, zorder=10, alpha=0.5) plt.scatter(t, r, marker='.', c='k', zorder=11, s=0.5) plt.annotate(a, xy=(t+o[0], r+o[1])) plt.ylim(0.725, 0.815); plt.xlim(0, 14.5); plt.grid(color=[0.85]*3); plt.gcf().subplots_adjust(bottom=0.15); plt.xlabel('Retrieval time for 10 nearest neighbors (ms)'), plt.ylabel('Recall@10 (%)'); ###Output _____no_output_____
flarestack/analyses/ccsn/necker_2019/compare_sensitivity_SN2009hd.ipynb
###Markdown Investigate how sensitivity changes without SN2009hd ###Code %load_ext autoreload %autoreload 2 import math, pickle, os, logging, time import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns from numpy.lib.recfunctions import drop_fields from flarestack.core.results import ResultsHandler, OverfluctuationError from flarestack.core.experimental_results import ExperimentalResultHandler from flarestack.data.icecube import ps_v002_p01 from flarestack.shared import plot_output_dir, flux_to_k from flarestack.icecube_utils.reference_sensitivity import reference_sensitivity from flarestack.analyses.ccsn.stasik_2017.ccsn_limits import limits, get_figure_limits, p_vals from flarestack.analyses.ccsn.necker_2019.ccsn_helpers import sn_cats, updated_sn_catalogue_name, sn_time_pdfs, raw_output_dir, pdf_names, limit_sens from flarestack.analyses.ccsn.necker_2019.build_catalogues_from_raw import load_catalogue from flarestack.analyses.ccsn import get_sn_color from flarestack.cluster import Submitter from flarestack.utils.custom_dataset import custom_dataset logging.getLogger().setLevel("DEBUG") logging.debug('logging level is DEBUG') logging.getLogger('matplotlib').setLevel('INFO') logger = logging.getLogger('main') # LLH Energy PDF llh_energy = { "energy_pdf_name": "power_law", } cluster = True ntrials = 500 # Spectral indices to loop over gammas = [2.0, 2.5] # minimizer to use mh_name = 'fit_weights' # base name raw = raw_output_dir + f"/compare_sensitivity_SN2009hd/{mh_name}" # set up emtpy dictionary to store the minimizer information in full_res = dict() for pdf_type in ['box', 'decay']: pdf_res = dict() pdf_type_name = f'{raw}/{pdf_type}' # loop over catalogues with and without SN2009hd for cat in ['with SN2009hd', 'without SN2009hd']: name = f'{pdf_type_name}/{cat.replace(" ", "_")}' # set up empty results dictionary for this catalogue cat_res = dict() # get the time pdfs for this catalogue time_pdfs = sn_time_pdfs('IIP', pdf_type=pdf_type) # Loop over time PDFs for llh_time in time_pdfs: # set up an empty results array for this time pdf time_res = dict() logging.debug(f'time_pdf is {llh_time}') if pdf_type == 'box': time_key = str(llh_time["post_window"] + llh_time["pre_window"]) pdf_time = float(time_key) if llh_time['pre_window'] == 0 else - float(time_key) else: time_key = str(llh_time['decay_time']) pdf_time = llh_time['decay_time'] / 364.25 pdf_name = pdf_names(pdf_type, pdf_time) cat_path = updated_sn_catalogue_name('IIP', flagged=flagged) # load catalogue and select the closest source # that serves for estimating a good injection scale later catalogue = np.load(cat_path) logging.debug('catalogue dtype: ' + str(catalogue.dtype)) closest_src = np.sort(catalogue, order="distance_mpc")[0] if cat == 'with SN2009hd': # load the catalogue from the original csv file missed_IIPs = drop_fields(load_catalogue('IIP', 'missed_objects', include_flagged=True), 'weight') SN2009hd = missed_IIPs[missed_IIPs['source_name'] == 'SN2009hd'] catalogue = np.append(catalogue, SN2009hd) cat_path = cat_path.strip(".npy") + '_with_SN2009hd.npy' np.save(cat_path, catalogue) if (cat == 'with SN2009hd') and not ('SN2009hd' in catalogue['source_name']): raise Exception(f'Catalogue is {cat} but SN2009hd is not in the catalogue!') if (cat == 'without SN2009hd') and ('SN2009hd' in catalogue['source_name']): raise Exception(f'Catalogue is {cat} but SN2009hd is in catalogue!') logging.debug('catalogue path: ' + str(cat_path)) time_name = f'{name}/{time_key}' # set up the likelihood dictionary llh_dict = { "llh_name": "standard", "llh_energy_pdf": llh_energy, "llh_sig_time_pdf": llh_time, "llh_bkg_time_pdf": { "time_pdf_name": "steady" } } # set up an injection dictionary which will be equal to the time pdf dictionary injection_time = llh_time # Loop over spectral indices for gamma in gammas: full_name = f'{time_name}/{gamma:.2f}' length = float(time_key) # try to estimate a good scale based on the sensitivity from the 7-yr PS sensitivity # at the declination of the closest source scale = 0.5 * (flux_to_k(reference_sensitivity( np.sin(closest_src["dec_rad"]), gamma=gamma ) * 40 * math.sqrt(float(len(catalogue)))) * 200.) / length # in some cases the sensitivity is outside the tested range # to get a good sensitivity, adjust the scale in these cases if pdf_type == 'decay': scale /= 20 if gamma == 2.5: scale *= 0.15 if gamma == 2.0: scale *= 0.5 else: scale *= 0.2 if gamma == 2.5: scale *= 0.6 # set up an injection dictionary and set the desired spectral index injection_energy = dict(llh_energy) injection_energy["gamma"] = gamma inj_dict = { "injection_energy_pdf": injection_energy, "injection_sig_time_pdf": injection_time, "poisson_smear_bool": True, } # set up the final minimizer dictionary mh_dict = { "name": full_name, "mh_name": mh_name, "dataset": custom_dataset(ps_v002_p01, catalogue, llh_dict["llh_sig_time_pdf"]), "catalogue": cat_path, "inj_dict": inj_dict, "llh_dict": llh_dict, "scale": scale, "n_trials": ntrials, "n_steps": 10 } # call the main analyse function submitter = Submitter.get_submitter( mh_dict, cluster, 5, do_sensitivity_scale_estimation=False, remove_old_results=True, cluster_cpu=1, h_cpu='03:59:59', trials_per_task=1 ) logging.debug(f'submitter is {submitter}') time_res[gamma] = submitter cat_res[time_key] = time_res pdf_res[cat] = cat_res full_res[pdf_type] = pdf_res for pdf_type, pdf_res in full_res.items(): for cat, cat_res in pdf_res.items(): for time, time_res in cat_res.items(): for gamma, s in time_res.items(): if (gamma == 2.5) and (pdf_type == 'box'): logger.debug(s) s.analyse() for pdf_res in full_res.values(): for cat_res in pdf_res.values(): for time_res in cat_res.values(): for s in time_res.values(): logging.debug(f'waitng on {s}') s.wait_for_job() stacked_sens_flux = {} logging.getLogger().setLevel('WARNING') for pdf_type, pdf_res in full_res.items(): pdf_sens = dict() for cat, cat_res in pdf_res.items(): cat_sens = dict() for time, time_res in cat_res.items(): time_sens = dict() for gamma, s in time_res.items(): try: rh = ResultsHandler(s.mh_dict) time_sens[gamma] = { 'sens': rh.sensitivity, 'sens_e': rh.sensitivity_err, 'sens_n': rh.sensitivity * rh.flux_to_ns, 'sens_n_e': rh.sensitivity_err * rh.flux_to_ns } except OverfluctuationError as e: logging.warning(f'{e} for {pdf_type} {cat} {time} {gamma}') cat_sens[time] = time_sens pdf_sens[cat] = cat_sens stacked_sens_flux[pdf_type] = pdf_sens ###Output _____no_output_____ ###Markdown plot results ###Code sns.set() cat_colors = {'with SN2009hd': 'k', 'without SN2009hd': 'b'} gamma_ls = {2.: '-', 2.5: '--'} cat_offset = {'with SN2009hd': 0.98, 'without SN2009hd': 1.02} for pdf_type, pdf_sens in stacked_sens_flux.items(): fig, ax = plt.subplots() handles = dict() for cat, cat_sens in pdf_sens.items(): handles[cat] = dict() for time, time_sens in cat_sens.items(): for gamma, sens in time_sens.items(): offset = cat_offset[cat] h = ax.errorbar(float(time)*offset, sens['sens'], yerr=np.atleast_2d(sens['sens_e']).T, color=cat_colors[cat], capsize=5, marker='o', label=f'{cat} $\gamma$={gamma:.2f}') h[2][0].set_linestyle(gamma_ls[gamma]) handles[cat][gamma] = h ax.set_xlabel(f'{pdf_type} length [d]') ax.set_ylabel(r'flux [GeV$^{-1}$ s$^{-1}$ cm$^{-2}$]') ax.set_title(f'{pdf_type} time profile') ax.set_yscale('log') ax.set_xscale('log') # create handles for legend legend_handles = list() for cat, cat_handles in handles.items(): for gamma, h in cat_handles.items(): legend_handles.append(h) ax.legend() plt.show() plt.close() for pdf_type, pdf_sens in stacked_sens_flux.items(): for gamma in gammas: fig, ax = plt.subplots() handles = dict() for cat, cat_sens in pdf_sens.items(): start = True handles[cat] = dict() for time, time_sens in cat_sens.items(): logger.debug(f'{pdf_type} {gamma} {cat} {time}: {sens["sens"]}') sens = time_sens[gamma] offset = cat_offset[cat] label = f'{cat} $\gamma$={gamma:.2f}' if start else '' h = ax.errorbar(float(time)*offset, sens['sens'], yerr=np.atleast_2d(sens['sens_e']).T, color=cat_colors[cat], capsize=5, marker='o', label=label) start=False unit = '[d]' if pdf_type == 'box' else '[y]' ax.set_xlabel(f'{pdf_type} length {unit}') ax.set_ylabel(r'flux [GeV$^{-1}$ s$^{-1}$ cm$^{-2}$]') ax.set_title(f'{pdf_type} time profile\n$\gamma$={gamma:.2f}') ax.set_yscale('log') ax.set_xscale('log') ax.legend() ax.set_xticks([float(t) for t in cat_sens.keys()]) xticklabels = cat_sens.keys() if pdf_type == 'box' else [float(t)/364.25 for t in cat_sens.keys()] ax.set_xticklabels(xticklabels) plt.show() plt.close() ref_to = 'with SN2009hd' logging.getLogger().setLevel('DEBUG') for pdf_type, pdf_sens in stacked_sens_flux.items(): for gamma in gammas: fig, ax = plt.subplots() handles = dict() for cat, cat_sens in pdf_sens.items(): start = True handles[cat] = dict() for time, time_sens in cat_sens.items(): sens = time_sens[gamma] reference = pdf_sens[ref_to][time][gamma]['sens'] logger.debug(f'{pdf_type} {gamma} {cat} {time}: {sens["sens"]/reference}') offset = cat_offset[cat] label = f'{cat} $\gamma$={gamma:.2f}' if start else '' h = ax.errorbar(float(time)*offset, sens['sens']/reference, yerr=np.atleast_2d(sens['sens_e']).T / reference, color=cat_colors[cat], capsize=5, marker='o', label=label) start=False ax.axhline(1, ls='--', alpha=0.5, color='k') unit = '[d]' if pdf_type == 'box' else '[y]' ax.set_xlabel(f'{pdf_type} length {unit}') ax.set_ylabel(r'flux / flux$_{\mathrm{with \; SN2009hd}}$') ax.set_title(f'{pdf_type} time profile\n$\gamma$={gamma:.2f}') ax.set_yscale('log') ax.set_xscale('log') ax.set_yticks([0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7]) logger.debug([float(t) for t in cat_sens.keys()]) ax.set_xticks([float(t) for t in cat_sens.keys()]) xticklabels = cat_sens.keys() if pdf_type == 'box' else [float(t)/364.25 for t in cat_sens.keys()] ax.set_xticklabels(xticklabels) ax.legend() filename = os.path.join(plot_output_dir(raw), f'{pdf_type}_gamma{gamma:.2f}.pdf') logger.debug(f'saving under {filename}') fig.tight_layout() fig.savefig(filename) plt.show() plt.close() ###Output _____no_output_____
3_mage/3.2 Dimensionality Reduction.ipynb
###Markdown Principal Component Analysis An unsupervised transformation that is somewhat more interesting is **Principle Component Analysis** (PCA).PCA is used to decompose a multivariate dataset in a set of successive orthogonal components that explain a maximum amount of the variance. That is, we find new features to represent the data that are a **linear combination** of the old data (i.e. we rotate it).The way PCA finds these new directions is by looking for the directions of maximum variance.Usually only few components that explain most of the variance in the data are kept. In scikit-learn, PCA is implemented as a transformer object that learns `n_components` in its `fit` method, and can be used on new data to project it on these components. ###Code from sklearn.datasets import load_iris X, y = load_iris(return_X_y=True) from sklearn.decomposition import PCA pca = PCA(n_components=2) ###Output _____no_output_____ ###Markdown Then we fit the PCA model with our data. As PCA is an unsupervised algorithm, there is no output ``y``. ###Code pca.fit(X) ###Output _____no_output_____ ###Markdown Then we can transform the data, projected on the principal components: ###Code X_pca = pca.transform(X) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, linewidths=0, s=30) plt.xlabel("first principal component") plt.ylabel("second principal component") plt.show() ###Output _____no_output_____ ###Markdown On the **right** of the plot you can see the four points that were on the top **right** before. PCA found fit first component to be along the diagonal, and the second to be perpendicular to it. As PCA finds a rotation, the principal components are always at right angles to each other. ###Code pca.explained_variance_ratio_ ###Output _____no_output_____ ###Markdown Manifold LearningOne weakness of PCA is that it cannot detect non-linear features. A set of algorithms known as *Manifold Learning* have been developed to addressthis deficiency. A canonical dataset used in Manifold learning is the *S-curve*, which we briefly saw in an earlier section: ###Code from sklearn.datasets import make_s_curve X, y = make_s_curve(n_samples=1000) from mpl_toolkits.mplot3d import Axes3D ax = plt.axes(projection='3d') ax.scatter3D(X[:, 0], X[:, 1], X[:, 2], c=y) ax.view_init(10, -60) ###Output _____no_output_____ ###Markdown This is a 2-dimensional dataset embedded in three dimensions, but it is embeddedin such a way that PCA cannot discover the underlying data orientation: ###Code X_pca = PCA(n_components=2).fit_transform(X) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y) ###Output _____no_output_____ ###Markdown Manifold learning algorithms, however, available in the ``sklearn.manifold``submodule, are able to recover the underlying 2-dimensional manifold: ###Code from sklearn.manifold import Isomap iso = Isomap(n_neighbors=15, n_components=2) X_iso = iso.fit_transform(X) plt.scatter(X_iso[:, 0], X_iso[:, 1], c=y) plt.show() ###Output _____no_output_____ ###Markdown IsoMapOne of the earliest approaches to manifold learning is the **Isomap** algorithm, short for **Isometric Mapping**. Isomap can be viewed as an extension of Multi-dimensional Scaling (MDS) or Kernel PCA. Isomap seeks a lower-dimensional embedding which maintains geodesic distances between all points. ExerciseCompare the results of Isomap and PCA on a 5-class subset of the digits dataset (``load_digits(5)``).__Bonus__: Also compare to TSNE, another popular manifold learning technique. ###Code from sklearn.datasets import load_digits digits = load_digits(5) X = digits.data # ... ###Output _____no_output_____
Development/2016/Exploring_groundwater_options.ipynb
###Markdown Notebook recording the various options for the relationship between soil water and groundwater explored during model development. These different versions were motivated by issues, using version 1, with simulating in-stream flows during prolonged periosd of the soil water being below field capacity. ###Code # Import modules %matplotlib inline import matplotlib.pyplot as plt, mpld3, seaborn as sn, os, matplotlib as mpl import numpy as np, pandas as pd from scipy.integrate import odeint from matplotlib.ticker import MaxNLocator # for sorting out ticks mpl.rcParams['pdf.fonttype'] = 42 def hydrol_inputs(D_snow_0, f_DDSM, met_df): """Function to calculate snow accumulation and melt. Calculates total hydrological input to soil box as precipitation as rain + snowmelt D_snow_0: Initial snow depth (mm) f_DDSM: Degree-day factor for snow melt (mm/degree-day deg C) met_df: Dataframe of met data with cols T_air, PET, Pptn Returns met_df with additional columns [P_snow, P_rain, P_melt, D_snow_start D_snow_end, P] Of these, P is the hydrological input to the soil store (mm/d) """ # Precipitation falling as snow (mm/d, as water equivalents) met_df.loc[:,'P_snow'] = met_df['Pptn'].ix[met_df['T_air']<0] # = total pptn if air T<0 met_df['P_snow'].fillna(0, inplace=True) # otherwise, =0 # Precipitation falling as rain (mm/d) met_df['P_rain'] = met_df['Pptn'] - met_df['P_snow'] # Potential daily snow melt (unlimited by snow pack depth) (mm/day) met_df['P_melt'] = f_DDSM*(met_df['T_air']-0) met_df['P_melt'][met_df['P_melt']<0]=0 # Set negative values to 0 (i.e. only melt when T_air>0) # Snow pack depth (mm), as end of day depth = start of day depth + inputs - melt, where melt is # limited by the depth wherever necessary. met_df['D_snow_start'], met_df['D_snow_end'] = np.nan, np.nan # Set-up # First time-step manually, to take initial condition into account met_df.ix[0,'D_snow_start'] = D_snow_0 # Assign user-supplied starting depth to first row met_df.ix[0,'P_melt'] = np.minimum(met_df.ix[0,'P_melt'],met_df.ix[0,'D_snow_start']) # Melt limited by depth met_df.ix[0,'D_snow_end'] = (met_df.ix[0,'D_snow_start']+ met_df.ix[0,'P_snow']-met_df.ix[0,'P_melt']) # Change over day # Calculate for subsequent days for idx in range (1,len(met_df)): met_df.ix[idx,'D_snow_start'] = met_df.ix[idx-1,'D_snow_end'] met_df.ix[idx,'P_melt'] = np.minimum(met_df.ix[idx,'P_melt'],met_df.ix[idx,'D_snow_start']) met_df.ix[idx,'D_snow_end'] = met_df.ix[idx,'D_snow_start']+met_df.ix[idx,'P_snow']-met_df.ix[idx,'P_melt'] # Hydrological input to soil box met_df.loc[:,'P'] = met_df['P_rain'] + met_df['P_melt'] return met_df # VERSION 1: two linear reservoirs (soil and groudnwater). Soil water flow only # when soil water level is above field capacity. No minimum groundwater flow # Result: Pretty good, but not good at simultaing the recession or low flows. # Groundwater 'drying out' too quickly. def hydro_model_1(met_df, ics, p, period, step_len=1): """ The hydrological model met_df Dataframe containing columns 'Rainfall_mm' and 'PET_mm', with datetime index ics Vector of initial conditions [Vs0, Vg0] p Series of parameter values (index = param name) period Vector of [start, end] dates [yyyy-mm-dd, yyyy-mm-dd] step_len Length of each step in the input dataset (days) Returns a dataframe with column headings [Vs, Qs, Vg, Qg, Ds, Dg, Sim_Runoff, Obs_Runoff] """ # Function defining the ODE system, to be solved by SCIPY.INTEGRATE.ODEINT # at each time step def f(y, t, ode_params): """ Define ODE system. y is list [Vs, Qs, Vg, Qg, Ds, Dg] t is an array of time points of interest params is a tuple of input values & model params (P, E, f_IExcess, alpha, beta, T_s, T_g, fc) """ # Unpack incremental values for Qs and Qg Vs_i = y[0] Qs_i = y[1] Qg_i = y[2] # Unpack params P, E, f_IExcess, alpha, beta, T_s, T_g, fc = ode_params # Soil equations dQs_dVs = (((Vs_i - fc)*np.exp(fc - Vs_i))/(T_s*((np.exp(fc-Vs_i) + 1)**2))) + (1/(T_s*(np.exp(fc-Vs_i) + 1))) dVs_dt = P*(1-f_IExcess) - alpha*E*(1 - np.exp(-0.02*Vs_i)) - Qs_i dQs_dt = dQs_dVs*dVs_dt # Groundwater equations dQg_dt = (beta*Qs_i - Qg_i)/T_g # Total drainage volumes over the timestep dDs_dt = (1 - beta)*Qs_i dDg_dt = Qg_i # Add results of equations to an array res = np.array([dVs_dt, dQs_dt, dQg_dt, dDs_dt, dDg_dt]) return res # ------------------------------------------------------------------------- # Unpack initial conditions Vs0, Qg0, Qr0 = ics Qs0 = (Vs0 - p['fc'])/(p['T_s']*(1 + np.exp(p['fc'] - Vs0))) # Time points to evaluate ODEs at. We're only interested in the start and the end of each step ti = [0, step_len] # Lists to store output output_ODEs = [] output_rest = [] # Loop over met data for idx in range(len(met_df)): # Get P and E for this day P = met_df.ix[idx, 'P'] E = met_df.ix[idx, 'PET'] # Calculate infiltration excess and add to results Qq = p['f_IExcess']*P output_rest.append(Qq) # Vector of initial conditions (Ds and Dg always 0 at start of time step) y0 = [Vs0, Qs0, Qg0, 0., 0.] # Model parameters plus rainfall and ET, for input to solver ode_params = np.array([P, E, p['f_IExcess'], p['alpha'], p['beta'], p['T_s'],p['T_g'], p['fc']]) # Solve y = odeint(f, y0, ti, args=(ode_params,), rtol=0.01, mxstep=5000) # Extract values for end of step res = y[1] # Numerical errors may result in very tiny values <0 # set these back to 0 res[res<0] = 0 output_ODEs.append(res) # Update initial conditions for next step Vs0 = res[0] Qs0 = res[1] Qg0 = res[2] # Build a dataframe of ODE results df1 = pd.DataFrame(data=np.vstack(output_ODEs), columns=['Vs', 'Qs', 'Qg', 'Ds', 'Dg'], index=met_df.index) # Dataframe of non ODE results df2 = pd.DataFrame(data=np.vstack(output_rest), columns=['Qq'], index=met_df.index) # Concatenate results dataframes df = pd.concat([df1,df2], axis=1) # Estimate runoff as Ds + Dg df['Sim_Runoff_mm'] = df['Ds'] + df['Dg'] + df['Qq'] df['Sim_Runoff_mm_noIE'] = df['Ds'] + df['Dg'] return df # VERSION 2: Same as version 1, but with a non-linear groundwater reservoir # (Vg = T*Qg^b, as described by e.g. Wittenberg '99) # Result: if set the exponent > 1, then the groundwater is better simulated, # but still not good. Need it to better linked to soil water level (even when # soil water is less than field capacity). Also, the values of b that help the # simulation look more realistic are nowhere near what the literature says they # should be (<1, around 0.5). Though makes me wonder if I'm getting confused # about the constants, therefore look into this more if decide to adopt this. def hydro_model_2(met_df, ics, p, period, step_len=1): """ The hydrological model met_df Dataframe containing columns 'Rainfall_mm' and 'PET_mm', with datetime index ics Vector of initial conditions [Vs0, Vg0] p Series of parameter values (index = param name) Has additional parameter k_g (exponent in v=aQ^k_g) period Vector of [start, end] dates [yyyy-mm-dd, yyyy-mm-dd] step_len Length of each step in the input dataset (days) Returns a dataframe with column headings [Vs, Qs, Vg, Qg, Ds, Dg, Sim_Runoff, Obs_Runoff] """ # Function defining the ODE system, to be solved by SCIPY.INTEGRATE.ODEINT # at each time step def f(y, t, ode_params): """ Define ODE system. y is list [Vs, Qs, Vg, Qg, Ds, Dg] t is an array of time points of interest params is a tuple of input values & model params (P, E, f_IExcess, alpha, beta, T_s, T_g, fc, k_g) """ # Unpack incremental values for Qs and Qg Vs_i = y[0] Qs_i = y[1] Vg_i = y[2] Qg_i = y[3] # Unpack params P, E, f_IExcess, alpha, beta, T_s, T_g, fc, k_g = ode_params # Soil equations dQs_dVs = (((Vs_i - fc)*np.exp(fc - Vs_i))/(T_s*((np.exp(fc-Vs_i) + 1)**2))) + (1/(T_s*(np.exp(fc-Vs_i) + 1))) dVs_dt = P*(1-f_IExcess) - alpha*E*(1 - np.exp(-0.02*Vs_i)) - Qs_i dQs_dt = dQs_dVs*dVs_dt # Groundwater equations dQg_dVg = (Vg_i**((1-k_g)/k_g))/(k_g*(T_g**(1/k_g))) # If k_g = 1, simplifies to 1/T (as expected) dVg_dt = beta*Qs_i - (Vg_i/T_g)**1/k_g dQg_dt = dQg_dVg*dVg_dt # Total drainage volumes over the timestep dDs_dt = (1 - beta)*Qs_i dDg_dt = Qg_i # Add results of equations to an array res = np.array([dVs_dt, dQs_dt, dVg_dt, dQg_dt, dDs_dt, dDg_dt]) return res # ------------------------------------------------------------------------- # Unpack initial conditions Vs0, Qg0, Qr0 = ics Vg0 = p['T_g']*Qg0**p['k_g'] Qs0 = (Vs0 - p['fc'])/(p['T_s']*(1 + np.exp(p['fc'] - Vs0))) # Time points to evaluate ODEs at. We're only interested in the start and the end of each step ti = [0, step_len] # Lists to store output output_ODEs = [] output_rest = [] # Loop over met data for idx in range(len(met_df)): # Get P and E for this day P = met_df.ix[idx, 'P'] E = met_df.ix[idx, 'PET'] # Calculate infiltration excess and add to results Qq = p['f_IExcess']*P output_rest.append(Qq) # Vector of initial conditions (Ds and Dg always 0 at start of time step) y0 = [Vs0, Qs0, Vg0, Qg0, 0., 0.] # Model parameters plus rainfall and ET, for input to solver ode_params = np.array([P, E, p['f_IExcess'], p['alpha'], p['beta'], p['T_s'], p['T_g'], p['fc'], p['k_g']]) # Solve y = odeint(f, y0, ti, args=(ode_params,), rtol=0.01, mxstep=5000) # Extract values for end of step res = y[1] # Numerical errors may result in very tiny values <0 # set these back to 0 res[res<0] = 0 output_ODEs.append(res) # Update initial conditions for next step Vs0 = res[0] Qs0 = res[1] Vg0 = res[2] Qg0 = res[3] # Build a dataframe of ODE results df1 = pd.DataFrame(data=np.vstack(output_ODEs), columns=['Vs', 'Qs', 'Vg', 'Qg', 'Ds', 'Dg'], index=met_df.index) # Dataframe of non ODE results df2 = pd.DataFrame(data=np.vstack(output_rest), columns=['Qq'], index=met_df.index) # Concatenate results dataframes df = pd.concat([df1,df2], axis=1) # Estimate runoff as Ds + Dg df['Sim_Runoff_mm'] = df['Ds'] + df['Dg'] + df['Qq'] df['Sim_Runoff_mm_noIE'] = df['Ds'] + df['Dg'] return df ###Output _____no_output_____ ###Markdown VERSION 3: Allow runoff from the soil box when the soil water level is belowfield capacity, using the same function to limit its value as is used for theAET calculation. Allows runoff to the stream and percolation to groundwaterwhen the soil water is below field capacity, but at a reduced rate.Result: Too much lost from the soil water, and therefore groundwater and soilwater flows are too high, resulting in discharge which is also too high. Theonly way to make discharge around the right level is to reduce field capacityto values which essentially stop it physically representing field capacityany more (e.g. 10mm), but even then the fit isn't very good.Conclude: Need soil water flow to be very limited below field capacity.This function isn't suitable. Need a sigmoid. Definitely an area for future exploration.I did some exploring of possible sigmoids, but you run into difficulties with generalisingthe shape parameter to define them, given that fc can vary. A possible future solutioncould be to have TWO sigmoids, with the second being very steep and kicking in once thesoil water goes below the permanent wilting point. This would likely introduce oneadditional user-specified parameter to define the shape of the main sigmoid controllingsoil water flow between the wilting point and field capacity, though may be able to fix this...Highlight as something to be investigated in the future!N.B. I've been playing around with the k shape parameter in this function; it'scurrently calculated assuming Q is 0.5 of potential when V is at FC. ###Code def hydro_model_3(met_df, ics, p, period, step_len=1): """ The hydrological model met_df Dataframe containing columns 'Rainfall_mm' and 'PET_mm', with datetime index ics Vector of initial conditions [Vs0, Vg0] p Series of parameter values (index = param name) period Vector of [start, end] dates [yyyy-mm-dd, yyyy-mm-dd] step_len Length of each step in the input dataset (days) Returns a dataframe with column headings [Vs, Qs, Qg, Ds, Dg, Sim_Runoff, Obs_Runoff] """ # ------------------------------------------------------------------------ # Define the ODE system def f(y, t, ode_params): """ Define ODE system. y is list [Vs, Qs, Qg, Ds, Dg] t is an array of time points of interest params is a tuple of input values & model params (P, E, f_IExcess, alpha, beta, T_s, T_g, fc) """ # Unpack incremental values for Qs and Qg Vs_i = y[0] Qs_i = y[1] Qg_i = y[2] # Unpack params P, E, f_IExcess, alpha, beta, T_s, T_g, fc, k = ode_params # Soil water equations dVs_dt = P*(1-f_IExcess) - alpha*E*(1-np.exp(-k*Vs_i)) - (Vs_i/T_s)*(1-np.exp(-k*Vs_i)) dQs_dV = np.exp(-k*(Vs_i**2))*(2*k*(Vs_i**2)+np.exp(k*(Vs_i**2))-1)*(1/T_s) dQs_dt = dQs_dV*dVs_dt # Groundwater equations dQg_dt = (beta*Qs_i - Qg_i)/T_g # Total drainage volumes over the timestep dDs_dt = (1 - beta)*Qs_i dDg_dt = Qg_i # Add results of equations to an array res = np.array([dVs_dt, dQs_dt, dQg_dt, dDs_dt, dDg_dt]) return res # ------------------------------------------------------------------------- # Calculate the value of the exponential shape parameter, k k = np.log(0.5)/-p['fc'] # Unpack initial conditions Vs0, Qg0, Qr0 = ics Qs0 = Vs0*(1/p['T_s'])*(1-np.exp(-k*Vs0)) # Time points to evaluate ODEs at. We're only interested in the start and # the end of each step ti = [0, step_len] # Lists to store output output_ODEs = [] output_rest = [] # Loop over met data for idx in range(len(met_df)): # Get P and E for this day P = met_df.ix[idx, 'P'] E = met_df.ix[idx, 'PET'] # Calculate infiltration excess and add to results Qq = p['f_IExcess']*P output_rest.append(Qq) # Vector of initial conditions (Ds and Dg always 0 at start of time step) y0 = [Vs0, Qs0, Qg0, 0., 0.] # Model parameters plus rainfall and ET, for input to solver ode_params = np.array([P, E, p['f_IExcess'], p['alpha'], p['beta'], p['T_s'], p['T_g'], p['fc'], k]) # Solve y = odeint(f, y0, ti, args=(ode_params,), rtol=0.01, mxstep=5000) # Extract values for end of step res = y[1] # Numerical errors may result in very tiny values <0 # set these back to 0 res[res<0] = 0 output_ODEs.append(res) # Update initial conditions for next step Vs0 = res[0] Qs0 = res[1] Qg0 = res[2] # Build a dataframe of ODE results df1 = pd.DataFrame(data=np.vstack(output_ODEs), columns=['Vs', 'Qs', 'Qg', 'Ds', 'Dg'], index=met_df.index) # Dataframe of non ODE results df2 = pd.DataFrame(data=np.vstack(output_rest), columns=['Qq'], index=met_df.index) # Concatenate results dataframes df = pd.concat([df1,df2], axis=1) # Estimate runoff as Ds + Dg df['Sim_Runoff_mm'] = df['Ds'] + df['Dg'] + df['Qq'] df['Sim_Runoff_mm_noIE'] = df['Ds'] + df['Dg'] return df # VERSION 4 # Same as version 1, but includes a minimum groundwater flow threshold def hydro_model_4(met_df, ics, p, period, step_len=1): """ The hydrological model met_df Dataframe containing columns 'Rainfall_mm' and 'PET_mm', with datetime index ics Vector of initial conditions [Vs0, Vg0] p Series of parameter values (index = param name) period Vector of [start, end] dates [yyyy-mm-dd, yyyy-mm-dd] step_len Length of each step in the input dataset (days) Returns a dataframe with column headings [Vs, Qs, Vg, Qg, Ds, Dg, Sim_Runoff, Obs_Runoff] """ # Function defining the ODE system, to be solved by SCIPY.INTEGRATE.ODEINT # at each time step def f(y, t, ode_params): """ Define ODE system. y is list [Vs, Qs, Vg, Qg, Ds, Dg] t is an array of time points of interest params is a tuple of input values & model params (P, E, f_IExcess, alpha, beta, T_s, T_g, fc) """ # Unpack incremental values for Qs and Qg Vs_i = y[0] Qs_i = y[1] Qg_i = y[2] # Unpack params P, E, f_IExcess, alpha, beta, T_s, T_g, fc = ode_params # Soil equations dQs_dVs = (((Vs_i - fc)*np.exp(fc - Vs_i))/(T_s*((np.exp(fc-Vs_i) + 1)**2))) + (1/(T_s*(np.exp(fc-Vs_i) + 1))) dVs_dt = P*(1-f_IExcess) - alpha*E*(1 - np.exp(-0.02*Vs_i)) - Qs_i dQs_dt = dQs_dVs*dVs_dt # Groundwater equations dQg_dt = (beta*Qs_i - Qg_i)/T_g # Total drainage volumes over the timestep dDs_dt = (1 - beta)*Qs_i dDg_dt = Qg_i # Add results of equations to an array res = np.array([dVs_dt, dQs_dt, dQg_dt, dDs_dt, dDg_dt]) return res # ------------------------------------------------------------------------- # Unpack initial conditions Vs0, Qg0, Qr0 = ics Qs0 = (Vs0 - p['fc'])/(p['T_s']*(1 + np.exp(p['fc'] - Vs0))) # Time points to evaluate ODEs at. We're only interested in the start and the end of each step ti = [0, step_len] # Lists to store output output_ODEs = [] output_rest = [] # Loop over met data for idx in range(len(met_df)): # Get P and E for this day P = met_df.ix[idx, 'P'] E = met_df.ix[idx, 'PET'] # Calculate infiltration excess and add to results Qq = p['f_IExcess']*P output_rest.append(Qq) # Vector of initial conditions (Ds and Dg always 0 at start of time step) y0 = [Vs0, Qs0, Qg0, 0., 0.] # Model parameters plus rainfall and ET, for input to solver ode_params = np.array([P, E, p['f_IExcess'], p['alpha'], p['beta'], p['T_s'],p['T_g'], p['fc']]) # Solve y = odeint(f, y0, ti, args=(ode_params,), rtol=0.01, mxstep=5000) # Extract values for end of step res = y[1] # Numerical errors may result in very tiny values <0 # set these back to 0 res[res<0] = 0 output_ODEs.append(res) # Update initial conditions for next step Vs0 = res[0] Qs0 = res[1] Qg0 = res[2] # Re-set groundwater to user-supplied minimum flow at start of each time step. Non-ideal # solution to the problem or maintaining stream flow during baseflow conditions. if p['Qg_min'] > res[2]: Qg0 = p['Qg_min'] else: Qg0 = res[2] # Build a dataframe of ODE results df1 = pd.DataFrame(data=np.vstack(output_ODEs), columns=['Vs', 'Qs', 'Qg', 'Ds', 'Dg'], index=met_df.index) # Dataframe of non ODE results df2 = pd.DataFrame(data=np.vstack(output_rest), columns=['Qq'], index=met_df.index) # Concatenate results dataframes df = pd.concat([df1,df2], axis=1) # Estimate runoff as Ds + Dg df['Sim_Runoff_mm'] = df['Ds'] + df['Dg'] + df['Qq'] df['Sim_Runoff_mm_noIE'] = df['Ds'] + df['Dg'] return df # Model parameters # Units: L_reach in mm for now. a_Q and b_Q are for m/s vs m3/s p1 = pd.Series({'A_catch': 51.7, 'L_reach':10000. ,'fc':290., 'alpha':0.80, 'beta':0.6,'f_IExcess':0.015, 'T_s':3.,'T_g':65., 'Qg_min':0, 'k_g':1.2, 'a_Q':0.5, 'b_Q':0.5,'Qg0_init':1.0, 'Qr0_init': 1.0}) p2 = pd.Series({'A_catch': 51.7, 'L_reach':10000. ,'fc':290., 'alpha':0.80, 'beta':0.6,'f_IExcess':0.015, 'T_s':3.,'T_g':65., 'Qg_min':0, 'k_g':1.2, 'a_Q':0.5, 'b_Q':0.5,'Qg0_init':1.0, 'Qr0_init': 1.0}) # Simulation period st_dt = '2004-01-01' # Start date end_dt = '2005-12-31' # End date # READ IN DATA # Desktop metdata_fpath = r'M:\Working\NewModel\ModelInputs\Tar_AvMetData_1981-2010.csv' Qobsdata_fpath = r'M:\Working\NewModel\ModelInputs\obs_csvs\Coull_9amDailyMeanQ_oldRating.xlsx' # Met met_df = pd.read_csv(metdata_fpath, parse_dates=True, dayfirst=True, index_col=0) met_df = met_df.truncate(before=st_dt, after=end_dt) # Truncate to the desired period met_df = hydrol_inputs(0.0, 2.74, met_df) # Obs Qobs_df = pd.read_excel(Qobsdata_fpath, sheetname=str(1), index_col=0, parse_dates=True, dayfirst=True) Qobs_df = Qobs_df.truncate(before=st_dt, after=end_dt) Qobs_df['Obs_Runoff_mm'] = Qobs_df['Q']*86400/(1000*p2.A_catch) df1 = hydro_model_1(met_df, p1[['fc','Qg0_init','Qr0_init']], p1, period=[st_dt, end_dt], step_len=1) df2 = hydro_model_2(met_df, p2[['fc','Qg0_init','Qr0_init']], p2, period=[st_dt, end_dt], step_len=1) folder_path = r'M:\Working\NewModel\ModelOutputs\Figs\Hydrol_Development' sn.set_context('paper') # 'notebook' for on-line viewing; 'paper' for smaller fonts # Plot results fig = plt.figure(figsize=(7.5,2)) # fig = plt.figure(figsize=(15,5)) ax = fig.add_subplot(1,1,1) Qobs_df['Obs_Runoff_mm'].plot(ax=ax, color='0.5', label='Observed', lw=1.5) # Plot observed # # Fig 1: Effect of IE # df1['Sim_Runoff_mm'].plot(ax=ax, color='r', label='Simulated, with quick flow', lw=1) # df2['Sim_Runoff_mm_noIE'].plot(ax=ax, color='b', label='Simulated, no quick flow', lw=1) # Fig 2: Linear vs non-linear GW. Run models 1 and 2; Qgmin=0 for both df1['Sim_Runoff_mm'].plot(ax=ax, color='r', label='Simulated, linear GW', lw=1, logy=True) df2['Sim_Runoff_mm'].plot(ax=ax, color='b', label='Simulated, non-linear GW', lw=1) outGraph = os.path.join(folder_path,"Fig_H2_LinearGW.png") # Fig 3: Threshold. Run models df1=4, Qgmin=0; df2=4, Qgmin=0.4 mm/d # df1['Sim_Runoff_mm'].plot(ax=ax, color='r', label='Sim, no GW threshold', lw=1, logy=True) # df2['Sim_Runoff_mm'].plot(ax=ax, color='b', label='Sim, inc. GW threshold', lw=1) # outGraph = os.path.join(folder_path,"Fig_H3_GW_threshold.png") # Tidy up plot ax.legend(loc='best') # ax.yaxis.set_major_locator(MaxNLocator(nbins=5, prune='upper')) plt.ylabel('Runoff (mm day$^{-1}$)') # y-axis label plt.xlabel("") # plt.show() plt.savefig(outGraph, bbox_inches='tight', dpi=300) plt.close() df1.head() df2.head() ###Output _____no_output_____
examples/vision/ipynb/simsiam.ipynb
###Markdown Self-supervised contrastive learning with SimSiam**Author:** [Sayak Paul](https://twitter.com/RisingSayak)**Date created:** 2021/03/19**Last modified:** 2021/03/20**Description:** Implementation of a self-supervised learning method for computer vision. Self-supervised learning (SSL) is an interesting branch of study in the field ofrepresentation learning. SSL systems try to formulate a supervised signal from a corpusof unlabeled data points. An example is we train a deep neural network to predict thenext word from a given set of words. In literature, these tasks are known as *pretexttasks* or *auxiliary tasks*. If we [train such a network](https://arxiv.org/abs/1801.06146) on a huge dataset (such asthe [Wikipedia text corpus](https://www.corpusdata.org/wikipedia.asp)) it learns very effectiverepresentations that transfer well to downstream tasks. Language models like[BERT](https://arxiv.org/abs/1810.04805), [GPT-3](https://arxiv.org/abs/2005.14165),[ELMo](https://allennlp.org/elmo) all benefit from this.Much like the language models we can train computer vision models using similarapproaches. To make things work in computer vision, we need to formulate the learningtasks such that the underlying model (a deep neural network) is able to make sense of thesemantic information present in vision data. One such task is to a model to _contrast_between two different versions of the same image. The hope is that in this way the modelwill have learn representations where the similar images are grouped as together possiblewhile the dissimilar images are further away.In this example, we will be implementing one such system called **SimSiam** proposed in[Exploring Simple Siamese Representation Learning](https://arxiv.org/abs/2011.10566). Itis implemented as the following:1. We create two different versions of the same dataset with a stochastic dataaugmentation pipeline. Note that the random initialization seed needs to be the sameduring create these versions.2. We take a ResNet without any classification head (**backbone**) and we add a shallowfully-connected network (**projection head**) on top of it. Collectively, this is knownas the **encoder**.3. We pass the output of the encoder through a **predictor** which is again a shallowfully-connected network having an[AutoEncoder](https://en.wikipedia.org/wiki/Autoencoder) like structure.4. We then train our encoder to maximize the cosine similarity between the two differentversions of our dataset.This example requires TensorFlow 2.4 or higher. Setup ###Code from tensorflow.keras import layers from tensorflow.keras import regularizers import tensorflow as tf import matplotlib.pyplot as plt import numpy as np ###Output _____no_output_____ ###Markdown Define hyperparameters ###Code AUTO = tf.data.AUTOTUNE BATCH_SIZE = 128 EPOCHS = 5 CROP_TO = 32 SEED = 26 PROJECT_DIM = 2048 LATENT_DIM = 512 WEIGHT_DECAY = 0.0005 ###Output _____no_output_____ ###Markdown Load the CIFAR-10 dataset ###Code (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() print(f"Total training examples: {len(x_train)}") print(f"Total test examples: {len(x_test)}") ###Output _____no_output_____ ###Markdown Defining our data augmentation pipelineAs studied in [SimCLR](https://arxiv.org/abs/2002.05709) having the right dataaugmentation pipeline is critical for SSL systems to work effectively in computer vision.Two particular augmentation transforms that seem to matter the most are: 1.) Randomresized crops and 2.) Color distortions. Most of the other SSL systems for computervision (such as [BYOL](https://arxiv.org/abs/2006.07733),[MoCoV2](https://arxiv.org/abs/2003.04297), [SwAV](https://arxiv.org/abs/2006.09882),etc.) include these in their training pipelines. ###Code def flip_random_crop(image): # With random crops we also apply horizontal flipping. image = tf.image.random_flip_left_right(image) image = tf.image.random_crop(image, (CROP_TO, CROP_TO, 3)) return image def color_jitter(x, strength=[0.4, 0.4, 0.4, 0.1]): x = tf.image.random_brightness(x, max_delta=0.8 * strength[0]) x = tf.image.random_contrast( x, lower=1 - 0.8 * strength[1], upper=1 + 0.8 * strength[1] ) x = tf.image.random_saturation( x, lower=1 - 0.8 * strength[2], upper=1 + 0.8 * strength[2] ) x = tf.image.random_hue(x, max_delta=0.2 * strength[3]) # Affine transformations can disturb the natural range of # RGB images, hence this is needed. x = tf.clip_by_value(x, 0, 255) return x def color_drop(x): x = tf.image.rgb_to_grayscale(x) x = tf.tile(x, [1, 1, 3]) return x def random_apply(func, x, p): if tf.random.uniform([], minval=0, maxval=1) < p: return func(x) else: return x def custom_augment(image): # As discussed in the SimCLR paper, the series of augmentation # transformations (except for random crops) need to be applied # randomly to impose translational invariance. image = flip_random_crop(image) image = random_apply(color_jitter, image, p=0.8) image = random_apply(color_drop, image, p=0.2) return image ###Output _____no_output_____ ###Markdown It should be noted that an augmentation pipeline is generally dependent on variousproperties of the dataset we are dealing with. For example, if images in the dataset areheavily object-centric then taking random crops with a very high probability may hurt thetraining performance.Let's now apply our augmentation pipeline to our dataset and visualize a few outputs. Convert the data into TensorFlow `Dataset` objectsHere we create two different versions of our dataset *without* any ground-truth labels. ###Code ssl_ds_one = tf.data.Dataset.from_tensor_slices(x_train) ssl_ds_one = ( ssl_ds_one.shuffle(1024, seed=SEED) .map(custom_augment, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) ssl_ds_two = tf.data.Dataset.from_tensor_slices(x_train) ssl_ds_two = ( ssl_ds_two.shuffle(1024, seed=SEED) .map(custom_augment, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) # We then zip both of these datasets. ssl_ds = tf.data.Dataset.zip((ssl_ds_one, ssl_ds_two)) # Visualize a few augmented images. sample_images_one = next(iter(ssl_ds_one)) plt.figure(figsize=(10, 10)) for n in range(25): ax = plt.subplot(5, 5, n + 1) plt.imshow(sample_images_one[n].numpy().astype("int")) plt.axis("off") plt.show() # Ensure that the different versions of the dataset actually contain # identical images. sample_images_two = next(iter(ssl_ds_two)) plt.figure(figsize=(10, 10)) for n in range(25): ax = plt.subplot(5, 5, n + 1) plt.imshow(sample_images_two[n].numpy().astype("int")) plt.axis("off") plt.show() ###Output _____no_output_____ ###Markdown Notice that the images in `samples_images_one` and `sample_images_two` are essentiallythe same but are augmented differently. Defining the encoder and the predictorWe use an implementation of ResNet20 that is specifically configured for the CIFAR10dataset. The code is taken from the[keras-idiomatic-programmer](https://github.com/GoogleCloudPlatform/keras-idiomatic-programmer/blob/master/zoo/resnet/resnet_cifar10_v2.py) repository. The hyperparameters ofthese architectures have been referred from Section 3 and Appendix A of [the originalpaper](https://arxiv.org/abs/2011.10566). ###Code !wget -q https://git.io/JYx2x -O resnet_cifar10_v2.py import resnet_cifar10_v2 N = 2 DEPTH = N * 9 + 2 NUM_BLOCKS = ((DEPTH - 2) // 9) - 1 def get_encoder(): # Input and backbone. inputs = layers.Input((CROP_TO, CROP_TO, 3)) x = layers.experimental.preprocessing.Rescaling(scale=1.0 / 127.5, offset=-1)( inputs ) x = resnet_cifar10_v2.stem(x) x = resnet_cifar10_v2.learner(x, NUM_BLOCKS) x = layers.GlobalAveragePooling2D(name="backbone_pool")(x) # Projection head. x = layers.Dense( PROJECT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY) )(x) x = layers.BatchNormalization()(x) x = layers.ReLU()(x) x = layers.Dense( PROJECT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY) )(x) outputs = layers.BatchNormalization()(x) return tf.keras.Model(inputs, outputs, name="encoder") def get_predictor(): model = tf.keras.Sequential( [ # Note the AutoEncoder-like structure. layers.Input((PROJECT_DIM,)), layers.Dense( LATENT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY), ), layers.ReLU(), layers.BatchNormalization(), layers.Dense(PROJECT_DIM), ], name="predictor", ) return model ###Output _____no_output_____ ###Markdown Defining the (pre-)training loopOne of the main reasons behind training networks with these kinds of approaches is toutilize the learned representations for downstream tasks like classification. This is whythis particular training phase is also referred to as _pre-training_.We start by defining the loss function. ###Code def compute_loss(p, z): # The authors of SimSiam emphasize the impact of # the `stop_gradient` operator in the paper as it # has an important role in the overall optimization. z = tf.stop_gradient(z) p = tf.math.l2_normalize(p, axis=1) z = tf.math.l2_normalize(z, axis=1) # Negative cosine similarity (minimizing this is # equivalent to maximizing the similarity). return -tf.reduce_mean(tf.reduce_sum((p * z), axis=1)) ###Output _____no_output_____ ###Markdown We then define our training loop by overriding the `train_step()` function of the`tf.keras.Model` class. ###Code class SimSiam(tf.keras.Model): def __init__(self, encoder, predictor): super(SimSiam, self).__init__() self.encoder = encoder self.predictor = predictor self.loss_tracker = tf.keras.metrics.Mean(name="loss") @property def metrics(self): return [self.loss_tracker] def train_step(self, data): # Unpack the data. ds_one, ds_two = data # Forward pass through the encoder and predictor. with tf.GradientTape() as tape: z1, z2 = self.encoder(ds_one), self.encoder(ds_two) p1, p2 = self.predictor(z1), self.predictor(z2) # Note that here we are enforcing the network to match # the representations of two differently augmented batches # of data. loss = compute_loss(p1, z2) / 2 + compute_loss(p2, z1) / 2 # Compute gradients and update the parameters. learnable_params = ( self.encoder.trainable_variables + self.predictor.trainable_variables ) gradients = tape.gradient(loss, learnable_params) self.optimizer.apply_gradients(zip(gradients, learnable_params)) # Monitor loss. self.loss_tracker.update_state(loss) return {"loss": self.loss_tracker.result()} ###Output _____no_output_____ ###Markdown Pre-training our networksIn the interest of this example, we will train the model for only 5 epochs. In reality,this should at least be 100 epochs. ###Code # Create a cosine decay learning scheduler. num_training_samples = len(x_train) steps = EPOCHS * (num_training_samples // BATCH_SIZE) lr_decayed_fn = tf.keras.experimental.CosineDecay( initial_learning_rate=0.03, decay_steps=steps ) # Create an early stopping callback. early_stopping = tf.keras.callbacks.EarlyStopping( monitor="loss", patience=5, restore_best_weights=True ) # Compile model and start training. simsiam = SimSiam(get_encoder(), get_predictor()) simsiam.compile(optimizer=tf.keras.optimizers.SGD(lr_decayed_fn, momentum=0.6)) history = simsiam.fit(ssl_ds, epochs=EPOCHS, callbacks=[early_stopping]) # Visualize the training progress of the model. plt.plot(history.history["loss"]) plt.grid() plt.title("Negative Cosine Similairty") plt.show() ###Output _____no_output_____ ###Markdown If your solution gets very close to -1 (minimum value of our loss) very quickly with adifferent dataset and a different backbone architecture that is likely because of*representation collapse*. It is a phenomenon where the encoder yields similar output forall the images. In that case additional hyperparameter tuning is required especially inthe following areas:* Strength of the color distortions and their probabilities.* Learning rate and its schedule.* Architecture of both the backbone and their projection head. Evaluating our SSL methodThe most popularly used method to evaluate a SSL method in computer vision (or any otherpre-training method as such) is to learn a linear classifier on the frozen features ofthe trained backbone model (in this case it is ResNet20) and evaluate the classifier onunseen images. Other methods include[fine-tuning](https://keras.io/guides/transfer_learning/) on the source dataset or even atarget dataset with 5% or 10% labels present. Practically, we can use the backbone modelfor any downstream task such as semantic segmentation, object detection, and so on wherethe backbone models are usually pre-trained with *pure supervised learning*. ###Code # We first create labeled `Dataset` objects. train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)) test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)) # Then we shuffle, batch, and prefetch this dataset for performance. We # also apply random resized crops as an augmentation but only to the # training set. train_ds = ( train_ds.shuffle(1024) .map(lambda x, y: (flip_random_crop(x), y), num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) test_ds = test_ds.batch(BATCH_SIZE).prefetch(AUTO) # Extract the backbone ResNet20. backbone = tf.keras.Model( simsiam.encoder.input, simsiam.encoder.get_layer("backbone_pool").output ) # We then create our linear classifier and train it. backbone.trainable = False inputs = layers.Input((CROP_TO, CROP_TO, 3)) x = backbone(inputs, training=False) outputs = layers.Dense(10, activation="softmax")(x) linear_model = tf.keras.Model(inputs, outputs, name="linear_model") # Compile model and start training. linear_model.compile( loss="sparse_categorical_crossentropy", metrics=["accuracy"], optimizer=tf.keras.optimizers.SGD(lr_decayed_fn, momentum=0.9), ) history = linear_model.fit( train_ds, validation_data=test_ds, epochs=EPOCHS, callbacks=[early_stopping] ) _, test_acc = linear_model.evaluate(test_ds) print("Test accuracy: {:.2f}%".format(test_acc * 100)) ###Output _____no_output_____ ###Markdown Self-supervised contrastive learning with SimSiam**Author:** [Sayak Paul](https://twitter.com/RisingSayak)**Date created:** 2021/03/19**Last modified:** 2021/03/20**Description:** Implementation of a self-supervised learning method for computer vision. Self-supervised learning (SSL) is an interesting branch of study in the field ofrepresentation learning. SSL systems try to formulate a supervised signal from a corpusof unlabeled data points. An example is we train a deep neural network to predict thenext word from a given set of words. In literature, these tasks are known as *pretexttasks* or *auxiliary tasks*. If we [train such a network](https://arxiv.org/abs/1801.06146) on a huge dataset (such asthe [Wikipedia text corpus](https://www.corpusdata.org/wikipedia.asp)) it learns very effectiverepresentations that transfer well to downstream tasks. Language models like[BERT](https://arxiv.org/abs/1810.04805), [GPT-3](https://arxiv.org/abs/2005.14165),[ELMo](https://allennlp.org/elmo) all benefit from this.Much like the language models we can train computer vision models using similarapproaches. To make things work in computer vision, we need to formulate the learningtasks such that the underlying model (a deep neural network) is able to make sense of thesemantic information present in vision data. One such task is to a model to _contrast_between two different versions of the same image. The hope is that in this way the modelwill have learn representations where the similar images are grouped as together possiblewhile the dissimilar images are further away.In this example, we will be implementing one such system called **SimSiam** proposed in[Exploring Simple Siamese Representation Learning](https://arxiv.org/abs/2011.10566). Itis implemented as the following:1. We create two different versions of the same dataset with a stochastic dataaugmentation pipeline. Note that the random initialization seed needs to be the sameduring create these versions.2. We take a ResNet without any classification head (**backbone**) and we add a shallowfully-connected network (**projection head**) on top of it. Collectively, this is knownas the **encoder**.3. We pass the output of the encoder through a **predictor** which is again a shallowfully-connected network having an[AutoEncoder](https://en.wikipedia.org/wiki/Autoencoder) like structure.4. We then train our encoder to maximize the cosine similarity between the two differentversions of our dataset.This example requires TensorFlow 2.4 or higher. Setup ###Code from tensorflow.keras import layers from tensorflow.keras import regularizers import tensorflow as tf import matplotlib.pyplot as plt import numpy as np ###Output _____no_output_____ ###Markdown Define hyperparameters ###Code AUTO = tf.data.AUTOTUNE BATCH_SIZE = 128 EPOCHS = 5 CROP_TO = 32 SEED = 26 PROJECT_DIM = 2048 LATENT_DIM = 512 WEIGHT_DECAY = 0.0005 ###Output _____no_output_____ ###Markdown Load the CIFAR-10 dataset ###Code (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() print(f"Total training examples: {len(x_train)}") print(f"Total test examples: {len(x_test)}") ###Output _____no_output_____ ###Markdown Defining our data augmentation pipelineAs studied in [SimCLR](https://arxiv.org/abs/2002.05709) having the right dataaugmentation pipeline is critical for SSL systems to work effectively in computer vision.Two particular augmentation transforms that seem to matter the most are: 1.) Randomresized crops and 2.) Color distortions. Most of the other SSL systems for computervision (such as [BYOL](https://arxiv.org/abs/2006.07733),[MoCoV2](https://arxiv.org/abs/2003.04297), [SwAV](https://arxiv.org/abs/2006.09882),etc.) include these in their training pipelines. ###Code def flip_random_crop(image): # With random crops we also apply horizontal flipping. image = tf.image.random_flip_left_right(image) image = tf.image.random_crop(image, (CROP_TO, CROP_TO, 3)) return image def color_jitter(x, strength=[0.4, 0.4, 0.4, 0.1]): x = tf.image.random_brightness(x, max_delta=0.8 * strength[0]) x = tf.image.random_contrast( x, lower=1 - 0.8 * strength[1], upper=1 + 0.8 * strength[1] ) x = tf.image.random_saturation( x, lower=1 - 0.8 * strength[2], upper=1 + 0.8 * strength[2] ) x = tf.image.random_hue(x, max_delta=0.2 * strength[3]) # Affine transformations can disturb the natural range of # RGB images, hence this is needed. x = tf.clip_by_value(x, 0, 255) return x def color_drop(x): x = tf.image.rgb_to_grayscale(x) x = tf.tile(x, [1, 1, 3]) return x def random_apply(func, x, p): if tf.random.uniform([], minval=0, maxval=1) < p: return func(x) else: return x def custom_augment(image): # As discussed in the SimCLR paper, the series of augmentation # transformations (except for random crops) need to be applied # randomly to impose translational invariance. image = flip_random_crop(image) image = random_apply(color_jitter, image, p=0.8) image = random_apply(color_drop, image, p=0.2) return image ###Output _____no_output_____ ###Markdown It should be noted that an augmentation pipeline is generally dependent on variousproperties of the dataset we are dealing with. For example, if images in the dataset areheavily object-centric then taking random crops with a very high probability may hurt thetraining performance.Let's now apply our augmentation pipeline to our dataset and visualize a few outputs. Convert the data into TensorFlow `Dataset` objectsHere we create two different versions of our dataset *without* any ground-truth labels. ###Code ssl_ds_one = tf.data.Dataset.from_tensor_slices(x_train) ssl_ds_one = ( ssl_ds_one.shuffle(1024, seed=SEED) .map(custom_augment, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) ssl_ds_two = tf.data.Dataset.from_tensor_slices(x_train) ssl_ds_two = ( ssl_ds_two.shuffle(1024, seed=SEED) .map(custom_augment, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) # We then zip both of these datasets. ssl_ds = tf.data.Dataset.zip((ssl_ds_one, ssl_ds_two)) # Visualize a few augmented images. sample_images_one = next(iter(ssl_ds_one)) plt.figure(figsize=(10, 10)) for n in range(25): ax = plt.subplot(5, 5, n + 1) plt.imshow(sample_images_one[n].numpy().astype("int")) plt.axis("off") plt.show() # Ensure that the different versions of the dataset actually contain # identical images. sample_images_two = next(iter(ssl_ds_two)) plt.figure(figsize=(10, 10)) for n in range(25): ax = plt.subplot(5, 5, n + 1) plt.imshow(sample_images_two[n].numpy().astype("int")) plt.axis("off") plt.show() ###Output _____no_output_____ ###Markdown Notice that the images in `samples_images_one` and `sample_images_two` are essentiallythe same but are augmented differently. Defining the encoder and the predictorWe use an implementation of ResNet20 that is specifically configured for the CIFAR10dataset. The code is taken from the[keras-idiomatic-programmer](https://github.com/GoogleCloudPlatform/keras-idiomatic-programmer/blob/master/zoo/resnet/resnet_cifar10_v2.py) repository. The hyperparameters ofthese architectures have been referred from Section 3 and Appendix A of [the originalpaper](https://arxiv.org/abs/2011.10566). ###Code !wget -q https://git.io/JYx2x -O resnet_cifar10_v2.py import resnet_cifar10_v2 N = 2 DEPTH = N * 9 + 2 NUM_BLOCKS = ((DEPTH - 2) // 9) - 1 def get_encoder(): # Input and backbone. inputs = layers.Input((CROP_TO, CROP_TO, 3)) x = layers.experimental.preprocessing.Rescaling(scale=1.0 / 127.5, offset=-1)( inputs ) x = resnet_cifar10_v2.stem(x) x = resnet_cifar10_v2.learner(x, NUM_BLOCKS) x = layers.GlobalAveragePooling2D(name="backbone_pool")(x) # Projection head. x = layers.Dense( PROJECT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY) )(x) x = layers.BatchNormalization()(x) x = layers.ReLU()(x) x = layers.Dense( PROJECT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY) )(x) outputs = layers.BatchNormalization()(x) return tf.keras.Model(inputs, outputs, name="encoder") def get_predictor(): model = tf.keras.Sequential( [ # Note the AutoEncoder-like structure. layers.Input((PROJECT_DIM,)), layers.Dense( LATENT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY), ), layers.ReLU(), layers.BatchNormalization(), layers.Dense(PROJECT_DIM), ], name="predictor", ) return model ###Output _____no_output_____ ###Markdown Defining the (pre-)training loopOne of the main reasons behind training networks with these kinds of approaches is toutilize the learned representations for downstream tasks like classification. This is whythis particular training phase is also referred to as _pre-training_.We start by defining the loss function. ###Code def compute_loss(p, z): # The authors of SimSiam emphasize the impact of # the `stop_gradient` operator in the paper as it # has an important role in the overall optimization. z = tf.stop_gradient(z) p = tf.math.l2_normalize(p, axis=1) z = tf.math.l2_normalize(z, axis=1) # Negative cosine similarity (minimizing this is # equivalent to maximizing the similarity). return -tf.reduce_mean(tf.reduce_sum((p * z), axis=1)) ###Output _____no_output_____ ###Markdown We then define our training loop by overriding the `train_step()` function of the`tf.keras.Model` class. ###Code class SimSiam(tf.keras.Model): def __init__(self, encoder, predictor): super(SimSiam, self).__init__() self.encoder = encoder self.predictor = predictor self.loss_tracker = tf.keras.metrics.Mean(name="loss") @property def metrics(self): return [self.loss_tracker] def train_step(self, data): # Unpack the data. ds_one, ds_two = data # Forward pass through the encoder and predictor. with tf.GradientTape() as tape: z1, z2 = self.encoder(ds_one), self.encoder(ds_two) p1, p2 = self.predictor(z1), self.predictor(z2) # Note that here we are enforcing the network to match # the representations of two differently augmented batches # of data. loss = compute_loss(p1, z2) / 2 + compute_loss(p2, z1) / 2 # Compute gradients and update the parameters. learnable_params = ( self.encoder.trainable_variables + self.predictor.trainable_variables ) gradients = tape.gradient(loss, learnable_params) self.optimizer.apply_gradients(zip(gradients, learnable_params)) # Monitor loss. self.loss_tracker.update_state(loss) return {"loss": self.loss_tracker.result()} ###Output _____no_output_____ ###Markdown Pre-training our networksIn the interest of this example, we will train the model for only 5 epochs. In reality,this should at least be 100 epochs. ###Code # Create a cosine decay learning scheduler. num_training_samples = len(x_train) steps = EPOCHS * (num_training_samples // BATCH_SIZE) lr_decayed_fn = tf.keras.experimental.CosineDecay( initial_learning_rate=0.03, decay_steps=steps ) # Create an early stopping callback. early_stopping = tf.keras.callbacks.EarlyStopping( monitor="loss", patience=5, restore_best_weights=True ) # Compile model and start training. simsiam = SimSiam(get_encoder(), get_predictor()) simsiam.compile(optimizer=tf.keras.optimizers.SGD(lr_decayed_fn, momentum=0.6)) history = simsiam.fit(ssl_ds, epochs=EPOCHS, callbacks=[early_stopping]) # Visualize the training progress of the model. plt.plot(history.history["loss"]) plt.grid() plt.title("Negative Cosine Similairty") plt.show() ###Output _____no_output_____ ###Markdown If your solution gets very close to -1 (minimum value of our loss) very quickly with adifferent dataset and a different backbone architecture that is likely because of*representation collapse*. It is a phenomenon where the encoder yields similar output forall the images. In that case additional hyperparameter tuning is required especially inthe following areas:* Strength of the color distortions and their probabilities.* Learning rate and its schedule.* Architecture of both the backbone and their projection head. Evaluating our SSL methodThe most popularly used method to evaluate a SSL method in computer vision (or any otherpre-training method as such) is to learn a linear classifier on the frozen features ofthe trained backbone model (in this case it is ResNet20) and evaluate the classifier onunseen images. Other methods include[fine-tuning](https://keras.io/guides/transfer_learning/) on the source dataset or even atarget dataset with 5% or 10% labels present. Practically, we can use the backbone modelfor any downstream task such as semantic segmentation, object detection, and so on wherethe backbone models are usually pre-trained with *pure supervised learning*. ###Code # We first create labeled `Dataset` objects. train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)) test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)) # Then we shuffle, batch, and prefetch this dataset for performance. We # also apply random resized crops as an augmentation but only to the # training set. train_ds = ( train_ds.shuffle(1024) .map(lambda x, y: (flip_random_crop(x), y), num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) test_ds = test_ds.batch(BATCH_SIZE).prefetch(AUTO) # Extract the backbone ResNet20. backbone = tf.keras.Model( simsiam.encoder.input, simsiam.encoder.get_layer("backbone_pool").output ) # We then create our linear classifier and train it. backbone.trainable = False inputs = layers.Input((CROP_TO, CROP_TO, 3)) x = backbone(inputs, training=False) outputs = layers.Dense(10, activation="softmax")(x) linear_model = tf.keras.Model(inputs, outputs, name="linear_model") # Compile model and start training. linear_model.compile( loss="sparse_categorical_crossentropy", metrics=["accuracy"], optimizer=tf.keras.optimizers.SGD(lr_decayed_fn, momentum=0.9), ) history = linear_model.fit( train_ds, validation_data=test_ds, epochs=EPOCHS, callbacks=[early_stopping] ) _, test_acc = linear_model.evaluate(test_ds) print("Test accuracy: {:.2f}%".format(test_acc * 100)) ###Output _____no_output_____ ###Markdown Self-supervised contrastive learning with SimSiam**Author:** [Sayak Paul](https://twitter.com/RisingSayak)**Date created:** 2021/03/19**Last modified:** 2021/03/20**Description:** Implementation of a self-supervised learning method for computer vision. Self-supervised learning (SSL) is an interesting branch of study in the field ofrepresentation learning. SSL systems try to formulate a supervised signal from a corpusof unlabeled data points. An example is we train a deep neural network to predict thenext word from a given set of words. In literature, these tasks are known as *pretexttasks* or *auxiliary tasks*. If we [train such a network](https://arxiv.org/abs/1801.06146) on a huge dataset (such asthe [Wikipedia text corpus](https://www.corpusdata.org/wikipedia.asp)) it learns very effectiverepresentations that transfer well to downstream tasks. Language models like[BERT](https://arxiv.org/abs/1810.04805), [GPT-3](https://arxiv.org/abs/2005.14165),[ELMo](https://allennlp.org/elmo) all benefit from this.Much like the language models we can train computer vision models using similarapproaches. To make things work in computer vision, we need to formulate the learningtasks such that the underlying model (a deep neural network) is able to make sense of thesemantic information present in vision data. One such task is to a model to _contrast_between two different versions of the same image. The hope is that in this way the modelwill have learn representations where the similar images are grouped as together possiblewhile the dissimilar images are further away.In this example, we will be implementing one such system called **SimSiam** proposed in[Exploring Simple Siamese Representation Learning](https://arxiv.org/abs/2011.10566). Itis implemented as the following:1. We create two different versions of the same dataset with a stochastic dataaugmentation pipeline. Note that the random initialization seed needs to be the sameduring create these versions.2. We take a ResNet without any classification head (**backbone**) and we add a shallowfully-connected network (**projection head**) on top of it. Collectively, this is knownas the **encoder**.3. We pass the output of the encoder through a **predictor** which is again a shallowfully-connected network having an[AutoEncoder](https://en.wikipedia.org/wiki/Autoencoder) like structure.4. We then train our encoder to maximize the cosine similarity between the two differentversions of our dataset.This example requires TensorFlow 2.4 or higher. Setup ###Code from tensorflow.keras import layers from tensorflow.keras import regularizers import tensorflow as tf import matplotlib.pyplot as plt import numpy as np ###Output _____no_output_____ ###Markdown Define hyperparameters ###Code AUTO = tf.data.AUTOTUNE BATCH_SIZE = 128 EPOCHS = 5 CROP_TO = 32 SEED = 26 PROJECT_DIM = 2048 LATENT_DIM = 512 WEIGHT_DECAY = 0.0005 ###Output _____no_output_____ ###Markdown Load the CIFAR-10 dataset ###Code (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() print(f"Total training examples: {len(x_train)}") print(f"Total test examples: {len(x_test)}") ###Output _____no_output_____ ###Markdown Defining our data augmentation pipelineAs studied in [SimCLR](https://arxiv.org/abs/2002.05709) having the right dataaugmentation pipeline is critical for SSL systems to work effectively in computer vision.Two particular augmentation transforms that seem to matter the most are: 1.) Randomresized crops and 2.) Color distortions. Most of the other SSL systems for computervision (such as [BYOL](https://arxiv.org/abs/2006.07733),[MoCoV2](https://arxiv.org/abs/2003.04297), [SwAV](https://arxiv.org/abs/2006.09882),etc.) include these in their training pipelines. ###Code def flip_random_crop(image): # With random crops we also apply horizontal flipping. image = tf.image.random_flip_left_right(image) image = tf.image.random_crop(image, (CROP_TO, CROP_TO, 3)) return image def color_jitter(x, strength=[0.4, 0.4, 0.4, 0.1]): x = tf.image.random_brightness(x, max_delta=0.8 * strength[0]) x = tf.image.random_contrast( x, lower=1 - 0.8 * strength[1], upper=1 + 0.8 * strength[1] ) x = tf.image.random_saturation( x, lower=1 - 0.8 * strength[2], upper=1 + 0.8 * strength[2] ) x = tf.image.random_hue(x, max_delta=0.2 * strength[3]) # Affine transformations can disturb the natural range of # RGB images, hence this is needed. x = tf.clip_by_value(x, 0, 255) return x def color_drop(x): x = tf.image.rgb_to_grayscale(x) x = tf.tile(x, [1, 1, 3]) return x def random_apply(func, x, p): if tf.random.uniform([], minval=0, maxval=1) < p: return func(x) else: return x def custom_augment(image): # As discussed in the SimCLR paper, the series of augmentation # transformations (except for random crops) need to be applied # randomly to impose translational invariance. image = flip_random_crop(image) image = random_apply(color_jitter, image, p=0.8) image = random_apply(color_drop, image, p=0.2) return image ###Output _____no_output_____ ###Markdown It should be noted that an augmentation pipeline is generally dependent on variousproperties of the dataset we are dealing with. For example, if images in the dataset areheavily object-centric then taking random crops with a very high probability may hurt thetraining performance.Let's now apply our augmentation pipeline to our dataset and visualize a few outputs. Convert the data into TensorFlow `Dataset` objectsHere we create two different versions of our dataset *without* any ground-truth labels. ###Code ssl_ds_one = tf.data.Dataset.from_tensor_slices(x_train) ssl_ds_one = ( ssl_ds_one.shuffle(1024, seed=SEED) .map(custom_augment, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) ssl_ds_two = tf.data.Dataset.from_tensor_slices(x_train) ssl_ds_two = ( ssl_ds_two.shuffle(1024, seed=SEED) .map(custom_augment, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) # We then zip both of these datasets. ssl_ds = tf.data.Dataset.zip((ssl_ds_one, ssl_ds_two)) # Visualize a few augmented images. sample_images_one = next(iter(ssl_ds_one)) plt.figure(figsize=(10, 10)) for n in range(25): ax = plt.subplot(5, 5, n + 1) plt.imshow(sample_images_one[n].numpy().astype("int")) plt.axis("off") plt.show() # Ensure that the different versions of the dataset actually contain # identical images. sample_images_two = next(iter(ssl_ds_two)) plt.figure(figsize=(10, 10)) for n in range(25): ax = plt.subplot(5, 5, n + 1) plt.imshow(sample_images_two[n].numpy().astype("int")) plt.axis("off") plt.show() ###Output _____no_output_____ ###Markdown Notice that the images in `samples_images_one` and `sample_images_two` are essentiallythe same but are augmented differently. Defining the encoder and the predictorWe use an implementation of ResNet20 that is specifically configured for the CIFAR10dataset. The code is taken from the[keras-idiomatic-programmer](https://github.com/GoogleCloudPlatform/keras-idiomatic-programmer/blob/master/zoo/resnet/resnet_cifar10_v2.py) repository. The hyperparameters ofthese architectures have been referred from Section 3 and Appendix A of [the originalpaper](https://arxiv.org/abs/2011.10566). ###Code !wget -q https://git.io/JYx2x -O resnet_cifar10_v2.py import resnet_cifar10_v2 N = 2 DEPTH = N * 9 + 2 NUM_BLOCKS = ((DEPTH - 2) // 9) - 1 def get_encoder(): # Input and backbone. inputs = layers.Input((CROP_TO, CROP_TO, 3)) x = layers.Rescaling(scale=1.0 / 127.5, offset=-1)( inputs ) x = resnet_cifar10_v2.stem(x) x = resnet_cifar10_v2.learner(x, NUM_BLOCKS) x = layers.GlobalAveragePooling2D(name="backbone_pool")(x) # Projection head. x = layers.Dense( PROJECT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY) )(x) x = layers.BatchNormalization()(x) x = layers.ReLU()(x) x = layers.Dense( PROJECT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY) )(x) outputs = layers.BatchNormalization()(x) return tf.keras.Model(inputs, outputs, name="encoder") def get_predictor(): model = tf.keras.Sequential( [ # Note the AutoEncoder-like structure. layers.Input((PROJECT_DIM,)), layers.Dense( LATENT_DIM, use_bias=False, kernel_regularizer=regularizers.l2(WEIGHT_DECAY), ), layers.ReLU(), layers.BatchNormalization(), layers.Dense(PROJECT_DIM), ], name="predictor", ) return model ###Output _____no_output_____ ###Markdown Defining the (pre-)training loopOne of the main reasons behind training networks with these kinds of approaches is toutilize the learned representations for downstream tasks like classification. This is whythis particular training phase is also referred to as _pre-training_.We start by defining the loss function. ###Code def compute_loss(p, z): # The authors of SimSiam emphasize the impact of # the `stop_gradient` operator in the paper as it # has an important role in the overall optimization. z = tf.stop_gradient(z) p = tf.math.l2_normalize(p, axis=1) z = tf.math.l2_normalize(z, axis=1) # Negative cosine similarity (minimizing this is # equivalent to maximizing the similarity). return -tf.reduce_mean(tf.reduce_sum((p * z), axis=1)) ###Output _____no_output_____ ###Markdown We then define our training loop by overriding the `train_step()` function of the`tf.keras.Model` class. ###Code class SimSiam(tf.keras.Model): def __init__(self, encoder, predictor): super(SimSiam, self).__init__() self.encoder = encoder self.predictor = predictor self.loss_tracker = tf.keras.metrics.Mean(name="loss") @property def metrics(self): return [self.loss_tracker] def train_step(self, data): # Unpack the data. ds_one, ds_two = data # Forward pass through the encoder and predictor. with tf.GradientTape() as tape: z1, z2 = self.encoder(ds_one), self.encoder(ds_two) p1, p2 = self.predictor(z1), self.predictor(z2) # Note that here we are enforcing the network to match # the representations of two differently augmented batches # of data. loss = compute_loss(p1, z2) / 2 + compute_loss(p2, z1) / 2 # Compute gradients and update the parameters. learnable_params = ( self.encoder.trainable_variables + self.predictor.trainable_variables ) gradients = tape.gradient(loss, learnable_params) self.optimizer.apply_gradients(zip(gradients, learnable_params)) # Monitor loss. self.loss_tracker.update_state(loss) return {"loss": self.loss_tracker.result()} ###Output _____no_output_____ ###Markdown Pre-training our networksIn the interest of this example, we will train the model for only 5 epochs. In reality,this should at least be 100 epochs. ###Code # Create a cosine decay learning scheduler. num_training_samples = len(x_train) steps = EPOCHS * (num_training_samples // BATCH_SIZE) lr_decayed_fn = tf.keras.optimizers.schedules.CosineDecay( initial_learning_rate=0.03, decay_steps=steps ) # Create an early stopping callback. early_stopping = tf.keras.callbacks.EarlyStopping( monitor="loss", patience=5, restore_best_weights=True ) # Compile model and start training. simsiam = SimSiam(get_encoder(), get_predictor()) simsiam.compile(optimizer=tf.keras.optimizers.SGD(lr_decayed_fn, momentum=0.6)) history = simsiam.fit(ssl_ds, epochs=EPOCHS, callbacks=[early_stopping]) # Visualize the training progress of the model. plt.plot(history.history["loss"]) plt.grid() plt.title("Negative Cosine Similairty") plt.show() ###Output _____no_output_____ ###Markdown If your solution gets very close to -1 (minimum value of our loss) very quickly with adifferent dataset and a different backbone architecture that is likely because of*representation collapse*. It is a phenomenon where the encoder yields similar output forall the images. In that case additional hyperparameter tuning is required especially inthe following areas:* Strength of the color distortions and their probabilities.* Learning rate and its schedule.* Architecture of both the backbone and their projection head. Evaluating our SSL methodThe most popularly used method to evaluate a SSL method in computer vision (or any otherpre-training method as such) is to learn a linear classifier on the frozen features ofthe trained backbone model (in this case it is ResNet20) and evaluate the classifier onunseen images. Other methods include[fine-tuning](https://keras.io/guides/transfer_learning/) on the source dataset or even atarget dataset with 5% or 10% labels present. Practically, we can use the backbone modelfor any downstream task such as semantic segmentation, object detection, and so on wherethe backbone models are usually pre-trained with *pure supervised learning*. ###Code # We first create labeled `Dataset` objects. train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)) test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)) # Then we shuffle, batch, and prefetch this dataset for performance. We # also apply random resized crops as an augmentation but only to the # training set. train_ds = ( train_ds.shuffle(1024) .map(lambda x, y: (flip_random_crop(x), y), num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) test_ds = test_ds.batch(BATCH_SIZE).prefetch(AUTO) # Extract the backbone ResNet20. backbone = tf.keras.Model( simsiam.encoder.input, simsiam.encoder.get_layer("backbone_pool").output ) # We then create our linear classifier and train it. backbone.trainable = False inputs = layers.Input((CROP_TO, CROP_TO, 3)) x = backbone(inputs, training=False) outputs = layers.Dense(10, activation="softmax")(x) linear_model = tf.keras.Model(inputs, outputs, name="linear_model") # Compile model and start training. linear_model.compile( loss="sparse_categorical_crossentropy", metrics=["accuracy"], optimizer=tf.keras.optimizers.SGD(lr_decayed_fn, momentum=0.9), ) history = linear_model.fit( train_ds, validation_data=test_ds, epochs=EPOCHS, callbacks=[early_stopping] ) _, test_acc = linear_model.evaluate(test_ds) print("Test accuracy: {:.2f}%".format(test_acc * 100)) ###Output _____no_output_____
esgf-cmip6-demo/search-cmip6.ipynb
###Markdown Search CMIP6 Datasetusing: https://esgf-pyclient.readthedocs.io/en/latest/index.html ###Code from pyesgf.search import SearchConnection conn = SearchConnection('https://esgf-data.dkrz.de/esg-search', distrib=True) ctx = conn.new_context( project='CMIP6', source_id='UKESM1-0-LL', experiment_id='historical', variable='tas', frequency='mon', variant_label='r1i1p1f2') ctx.hit_count result = ctx.search()[1] result.dataset_id files = result.file_context().search() for file in files: print(file.opendap_url) ###Output http://esgf-data3.ceda.ac.uk/thredds/dodsC/esg_cmip6/CMIP6/CMIP/MOHC/UKESM1-0-LL/historical/r1i1p1f2/Amon/tas/gn/v20190406/tas_Amon_UKESM1-0-LL_historical_r1i1p1f2_gn_185001-194912.nc http://esgf-data3.ceda.ac.uk/thredds/dodsC/esg_cmip6/CMIP6/CMIP/MOHC/UKESM1-0-LL/historical/r1i1p1f2/Amon/tas/gn/v20190406/tas_Amon_UKESM1-0-LL_historical_r1i1p1f2_gn_195001-201412.nc
modules/06-apache-spark-sql/06-extracting-data-from-mongodb.ipynb
###Markdown Extracting Data from MongoDB 1. Spark Connector: https://docs.mongodb.com/spark-connector/current/2. Mongo Spark: https://spark-packages.org/package/mongodb/mongo-spark3. Launch Jupyter Notebook with PySpark and MongoDB: **$SPARK_HOME/bin/pyspark --packages org.mongodb.spark:mongo-spark-connector_2.12:3.0.0** ###Code from pyspark.sql import SparkSession ###Output _____no_output_____ ###Markdown **Creating the Spark Session** ###Code # my_spark = SparkSession \ # .builder \ # .appName("myApp") \ # .config("spark.mongodb.input.uri", "mongodb://localhost/store.clothes") \ # .config("spark.mongodb.output.uri", "mongodb://localhost/store.clothes") \ # .getOrCreate() # df = spark.read.format('com.mongodb.spark.sql.DefaultSource').load() ###Output _____no_output_____ ###Markdown **Reading Data** ###Code data = spark.read.format("mongo").option("uri", "mongodb://localhost/store.clothes").load() data.printSchema() data.count() data.head() data.show() ###Output +--------------------+-----+----+-----------------+-------------+ | _id| item| qty| size| tags| +--------------------+-----+----+-----------------+-------------+ |[5f50f2a029127016...|Shirt|25.0| [14.0, 21.0, cm]| [white, red]| |[5f50f2a029127016...|Dress|85.0| [27.9, 35.5, cm]| [gray]| |[5f50f2a029127016...|Pants|45.0|[19.0, 22.85, cm]|[green, blue]| |[5f5172a1d7877900...|Shoes|30.0| null| null| +--------------------+-----+----+-----------------+-------------+ ###Markdown **Inserting Data** ###Code newItem = spark.createDataFrame([("Purse", 40)], ["item", "qty"]) newItem.write.format("mongo").option("uri", "mongodb://localhost/store.clothes").mode("append").save() data.show() ###Output +--------------------+-----+----+-----------------+-------------+ | _id| item| qty| size| tags| +--------------------+-----+----+-----------------+-------------+ |[5f50f2a029127016...|Shirt|25.0| [14.0, 21.0, cm]| [white, red]| |[5f50f2a029127016...|Dress|85.0| [27.9, 35.5, cm]| [gray]| |[5f50f2a029127016...|Pants|45.0|[19.0, 22.85, cm]|[green, blue]| |[5f5172a1d7877900...|Shoes|30.0| null| null| |[5f51738fddd1653e...|Purse|40.0| null| null| +--------------------+-----+----+-----------------+-------------+
letsleetcode/leetcode/0001-two-sum.ipynb
###Markdown 0001. Two Sum ProblemGiven an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order. Examples Example 1:``` textInput: nums = [2,7,11,15], target = 9Output: [0,1]Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].```Example 2:```textInput: nums = [3,2,4], target = 6Output: [1,2]```Example 3:```textInput: nums = [3,3], target = 6Output: [0,1]``` Constraints:```text2 <= nums.length <= 104-109 <= nums[i] <= 109-109 <= target <= 109Only one valid answer exists.``` Follow-upCan you come up with an algorithm that is less than $O(n^2)$ time complexity? AnalysisThe (index, value) pair related problem can be efficiently solved in $O(n)$ time using hashing table. - iterate over the sequence - given index and value, find another set of (index, value) Solution ###Code # Solution 1: naive solution O(n2) def two_sum(nums, target): n = len(nums) for i, v in enumerate(nums): vnext = target - v for j in range(i+1, n): if nums[j] == vnext: return [i,j] return [] # test nums = [2, 7, 11, 15] target = 9 print(two_sum(nums, target)) nums = [3, 2, 4] target = 6 print(two_sum(nums, target)) nums = [3, 3] target = 6 print(two_sum(nums, target)) nums = [0, 8, 7, 3, 3, 4, 2] target = 11 print(two_sum(nums, target)) nums = [0, 1] target = 1 print(two_sum(nums, target)) nums = [0, 2] target = 3 print(two_sum(nums, target)) # Solution 2: hashing table O(n) # The main idea here is since in the previous solution, the first loop has already iterated over the whole data set, there is no need to go through the data set in the inner loop agian. This could be done by using hashing table. def two_sum(nums, target): tab = {} for i, v in enumerate(nums): vnext = target - v if vnext not in tab: tab[v] = i else: return [tab[vnext], i] return [] # test nums = [2, 7, 11, 15] target = 9 print(two_sum(nums, target)) nums = [3, 2, 4] target = 6 print(two_sum(nums, target)) nums = [3, 3] target = 6 print(two_sum(nums, target)) nums = [0, 8, 7, 3, 3, 4, 2] target = 11 print(two_sum(nums, target)) nums = [0, 1] target = 1 print(two_sum(nums, target)) nums = [0, 2] target = 3 print(two_sum(nums, target)) ###Output [0, 1] [1, 2] [0, 1] [1, 3] [0, 1] []
Applied-Data-Science-Specialization-IBM/IBM - Data Visualization with Python/week2 - Basic and Specialized Visualization Tools/Area-Plots-Histograms-and-Bar-Charts-py-v2.0.ipynb
###Markdown Area Plots, Histograms, and Bar Plots IntroductionIn this lab, we will continue exploring the Matplotlib library and will learn how to create additional plots, namely area plots, histograms, and bar charts. Table of Contents1. [Exploring Datasets with *pandas*](0)2. [Downloading and Prepping Data](2)3. [Visualizing Data using Matplotlib](4) 4. [Area Plots](6) 5. [Histograms](8) 6. [Bar Charts](10) Exploring Datasets with *pandas* and MatplotlibToolkits: The course heavily relies on [*pandas*](http://pandas.pydata.org/) and [**Numpy**](http://www.numpy.org/) for data wrangling, analysis, and visualization. The primary plotting library that we are exploring in the course is [Matplotlib](http://matplotlib.org/).Dataset: Immigration to Canada from 1980 to 2013 - [International migration flows to and from selected countries - The 2015 revision](http://www.un.org/en/development/desa/population/migration/data/empirical2/migrationflows.shtml) from United Nation's website.The dataset contains annual data on the flows of international migrants as recorded by the countries of destination. The data presents both inflows and outflows according to the place of birth, citizenship or place of previous / next residence both for foreigners and nationals. For this lesson, we will focus on the Canadian Immigration data. Downloading and Prepping Data Import Primary Modules. The first thing we'll do is import two key data analysis modules: *pandas* and **Numpy**. ###Code import numpy as np # useful for many scientific computing in Python import pandas as pd # primary data structure library ###Output _____no_output_____ ###Markdown Let's download and import our primary Canadian Immigration dataset using *pandas* `read_excel()` method. Normally, before we can do that, we would need to download a module which *pandas* requires to read in excel files. This module is **xlrd**. For your convenience, we have pre-installed this module, so you would not have to worry about that. Otherwise, you would need to run the following line of code to install the **xlrd** module:```!conda install -c anaconda xlrd --yes``` Download the dataset and read it into a *pandas* dataframe. ###Code df_can = pd.read_excel('https://ibm.box.com/shared/static/lw190pt9zpy5bd1ptyg2aw15awomz9pu.xlsx', sheet_name='Canada by Citizenship', skiprows=range(20), skip_footer=2 ) print('Data downloaded and read into a dataframe!') ###Output _____no_output_____ ###Markdown Let's take a look at the first five items in our dataset. ###Code df_can.head() ###Output _____no_output_____ ###Markdown Let's find out how many entries there are in our dataset. ###Code # print the dimensions of the dataframe print(df_can.shape) ###Output _____no_output_____ ###Markdown Clean up data. We will make some modifications to the original dataset to make it easier to create our visualizations. Refer to `Introduction to Matplotlib and Line Plots` lab for the rational and detailed description of the changes. 1. Clean up the dataset to remove columns that are not informative to us for visualization (eg. Type, AREA, REG). ###Code df_can.drop(['AREA', 'REG', 'DEV', 'Type', 'Coverage'], axis=1, inplace=True) # let's view the first five elements and see how the dataframe was changed df_can.head() ###Output _____no_output_____ ###Markdown Notice how the columns Type, Coverage, AREA, REG, and DEV got removed from the dataframe. 2. Rename some of the columns so that they make sense. ###Code df_can.rename(columns={'OdName':'Country', 'AreaName':'Continent','RegName':'Region'}, inplace=True) # let's view the first five elements and see how the dataframe was changed df_can.head() ###Output _____no_output_____ ###Markdown Notice how the column names now make much more sense, even to an outsider. 3. For consistency, ensure that all column labels of type string. ###Code # let's examine the types of the column labels all(isinstance(column, str) for column in df_can.columns) ###Output _____no_output_____ ###Markdown Notice how the above line of code returned *False* when we tested if all the column labels are of type **string**. So let's change them all to **string** type. ###Code df_can.columns = list(map(str, df_can.columns)) # let's check the column labels types now all(isinstance(column, str) for column in df_can.columns) ###Output _____no_output_____ ###Markdown 4. Set the country name as index - useful for quickly looking up countries using .loc method. ###Code df_can.set_index('Country', inplace=True) # let's view the first five elements and see how the dataframe was changed df_can.head() ###Output _____no_output_____ ###Markdown Notice how the country names now serve as indices. 5. Add total column. ###Code df_can['Total'] = df_can.sum(axis=1) # let's view the first five elements and see how the dataframe was changed df_can.head() ###Output _____no_output_____ ###Markdown Now the dataframe has an extra column that presents the total number of immigrants from each country in the dataset from 1980 - 2013. So if we print the dimension of the data, we get: ###Code print ('data dimensions:', df_can.shape) ###Output _____no_output_____ ###Markdown So now our dataframe has 38 columns instead of 37 columns that we had before. ###Code # finally, let's create a list of years from 1980 - 2013 # this will come in handy when we start plotting the data years = list(map(str, range(1980, 2014))) years ###Output _____no_output_____ ###Markdown Visualizing Data using Matplotlib Import `Matplotlib` and **Numpy**. ###Code # use the inline backend to generate the plots within the browser %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt mpl.style.use('ggplot') # optional: for ggplot-like style # check for latest version of Matplotlib print ('Matplotlib version: ', mpl.__version__) # >= 2.0.0 ###Output _____no_output_____ ###Markdown Area Plots In the last module, we created a line plot that visualized the top 5 countries that contribued the most immigrants to Canada from 1980 to 2013. With a little modification to the code, we can visualize this plot as a cumulative plot, also knows as a **Stacked Line Plot** or **Area plot**. ###Code df_can.sort_values(['Total'], ascending=False, axis=0, inplace=True) # get the top 5 entries df_top5 = df_can.head() # transpose the dataframe df_top5 = df_top5[years].transpose() df_top5.head() ###Output _____no_output_____ ###Markdown Area plots are stacked by default. And to produce a stacked area plot, each column must be either all positive or all negative values (any NaN values will defaulted to 0). To produce an unstacked plot, pass `stacked=False`. ###Code df_top5.index = df_top5.index.map(int) # let's change the index values of df_top5 to type integer for plotting df_top5.plot(kind='area', stacked=False, figsize=(20, 10), # pass a tuple (x, y) size ) plt.title('Immigration Trend of Top 5 Countries') plt.ylabel('Number of Immigrants') plt.xlabel('Years') plt.show() ###Output _____no_output_____ ###Markdown The unstacked plot has a default transparency (alpha value) at 0.5. We can modify this value by passing in the `alpha` parameter. ###Code df_top5.plot(kind='area', alpha=0.25, # 0-1, default value a= 0.5 stacked=False, figsize=(20, 10), ) plt.title('Immigration Trend of Top 5 Countries') plt.ylabel('Number of Immigrants') plt.xlabel('Years') plt.show() ###Output _____no_output_____ ###Markdown Two types of plottingAs we discussed in the video lectures, there are two styles/options of ploting with `matplotlib`. Plotting using the Artist layer and plotting using the scripting layer.**Option 1: Scripting layer (procedural method) - using matplotlib.pyplot as 'plt' **You can use `plt` i.e. `matplotlib.pyplot` and add more elements by calling different methods procedurally; for example, `plt.title(...)` to add title or `plt.xlabel(...)` to add label to the x-axis.```python Option 1: This is what we have been using so far df_top5.plot(kind='area', alpha=0.35, figsize=(20, 10)) plt.title('Immigration trend of top 5 countries') plt.ylabel('Number of immigrants') plt.xlabel('Years')``` **Option 2: Artist layer (Object oriented method) - using an `Axes` instance from Matplotlib (preferred) **You can use an `Axes` instance of your current plot and store it in a variable (eg. `ax`). You can add more elements by calling methods with a little change in syntax (by adding "*set_*" to the previous methods). For example, use `ax.set_title()` instead of `plt.title()` to add title, or `ax.set_xlabel()` instead of `plt.xlabel()` to add label to the x-axis. This option sometimes is more transparent and flexible to use for advanced plots (in particular when having multiple plots, as you will see later). In this course, we will stick to the **scripting layer**, except for some advanced visualizations where we will need to use the **artist layer** to manipulate advanced aspects of the plots. ###Code # option 2: preferred option with more flexibility ax = df_top5.plot(kind='area', alpha=0.35, figsize=(20, 10)) ax.set_title('Immigration Trend of Top 5 Countries') ax.set_ylabel('Number of Immigrants') ax.set_xlabel('Years') ###Output _____no_output_____ ###Markdown **Question**: Use the scripting layer to create a stacked area plot of the 5 countries that contributed the least to immigration to Canada **from** 1980 to 2013. Use a transparency value of 0.45. ###Code ### type your answer here ###Output _____no_output_____ ###Markdown Double-click __here__ for the solution.<!-- The correct answer is:\\ get the 5 countries with the least contributiondf_least5 = df_can.tail(5)--><!--\\ transpose the dataframedf_least5 = df_least5[years].transpose() df_least5.head()--><!--df_least5.index = df_least5.index.map(int) let's change the index values of df_least5 to type integer for plottingdf_least5.plot(kind='area', alpha=0.45, figsize=(20, 10)) --><!--plt.title('Immigration Trend of 5 Countries with Least Contribution to Immigration')plt.ylabel('Number of Immigrants')plt.xlabel('Years')--><!--plt.show()--> **Question**: Use the artist layer to create an unstacked area plot of the 5 countries that contributed the least to immigration to Canada **from** 1980 to 2013. Use a transparency value of 0.55. ###Code ### type your answer here ###Output _____no_output_____ ###Markdown Double-click __here__ for the solution.<!-- The correct answer is:\\ get the 5 countries with the least contributiondf_least5 = df_can.tail(5)--><!--\\ transpose the dataframedf_least5 = df_least5[years].transpose() df_least5.head()--><!--df_least5.index = df_least5.index.map(int) let's change the index values of df_least5 to type integer for plotting--><!--ax = df_least5.plot(kind='area', alpha=0.55, stacked=False, figsize=(20, 10))--><!--ax.set_title('Immigration Trend of 5 Countries with Least Contribution to Immigration')ax.set_ylabel('Number of Immigrants')ax.set_xlabel('Years')--> HistogramsA histogram is a way of representing the *frequency* distribution of numeric dataset. The way it works is it partitions the x-axis into *bins*, assigns each data point in our dataset to a bin, and then counts the number of data points that have been assigned to each bin. So the y-axis is the frequency or the number of data points in each bin. Note that we can change the bin size and usually one needs to tweak it so that the distribution is displayed nicely. **Question:** What is the frequency distribution of the number (population) of new immigrants from the various countries to Canada in 2013? Before we proceed with creating the histogram plot, let's first examine the data split into intervals. To do this, we will us **Numpy**'s `histrogram` method to get the bin ranges and frequency counts as follows: ###Code # let's quickly view the 2013 data df_can['2013'].head() # np.histogram returns 2 values count, bin_edges = np.histogram(df_can['2013']) print(count) # frequency count print(bin_edges) # bin ranges, default = 10 bins ###Output _____no_output_____ ###Markdown By default, the `histrogram` method breaks up the dataset into 10 bins. The figure below summarizes the bin ranges and the frequency distribution of immigration in 2013. We can see that in 2013:* 178 countries contributed between 0 to 3412.9 immigrants * 11 countries contributed between 3412.9 to 6825.8 immigrants* 1 country contributed between 6285.8 to 10238.7 immigrants, and so on.. We can easily graph this distribution by passing `kind=hist` to `plot()`. ###Code df_can['2013'].plot(kind='hist', figsize=(8, 5)) plt.title('Histogram of Immigration from 195 Countries in 2013') # add a title to the histogram plt.ylabel('Number of Countries') # add y-label plt.xlabel('Number of Immigrants') # add x-label plt.show() ###Output _____no_output_____ ###Markdown In the above plot, the x-axis represents the population range of immigrants in intervals of 3412.9. The y-axis represents the number of countries that contributed to the aforementioned population. Notice that the x-axis labels do not match with the bin size. This can be fixed by passing in a `xticks` keyword that contains the list of the bin sizes, as follows: ###Code # 'bin_edges' is a list of bin intervals count, bin_edges = np.histogram(df_can['2013']) df_can['2013'].plot(kind='hist', figsize=(8, 5), xticks=bin_edges) plt.title('Histogram of Immigration from 195 countries in 2013') # add a title to the histogram plt.ylabel('Number of Countries') # add y-label plt.xlabel('Number of Immigrants') # add x-label plt.show() ###Output _____no_output_____ ###Markdown *Side Note:* We could use `df_can['2013'].plot.hist()`, instead. In fact, throughout this lesson, using `some_data.plot(kind='type_plot', ...)` is equivalent to `some_data.plot.type_plot(...)`. That is, passing the type of the plot as argument or method behaves the same. See the *pandas* documentation for more info http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html. We can also plot multiple histograms on the same plot. For example, let's try to answer the following questions using a histogram.**Question**: What is the immigration distribution for Denmark, Norway, and Sweden for years 1980 - 2013? ###Code # let's quickly view the dataset df_can.loc[['Denmark', 'Norway', 'Sweden'], years] # generate histogram df_can.loc[['Denmark', 'Norway', 'Sweden'], years].plot.hist() ###Output _____no_output_____ ###Markdown That does not look right! Don't worry, you'll often come across situations like this when creating plots. The solution often lies in how the underlying dataset is structured.Instead of plotting the population frequency distribution of the population for the 3 countries, *pandas* instead plotted the population frequency distribution for the `years`.This can be easily fixed by first transposing the dataset, and then plotting as shown below. ###Code # transpose dataframe df_t = df_can.loc[['Denmark', 'Norway', 'Sweden'], years].transpose() df_t.head() # generate histogram df_t.plot(kind='hist', figsize=(10, 6)) plt.title('Histogram of Immigration from Denmark, Norway, and Sweden from 1980 - 2013') plt.ylabel('Number of Years') plt.xlabel('Number of Immigrants') plt.show() ###Output _____no_output_____ ###Markdown Let's make a few modifications to improve the impact and aesthetics of the previous plot:* increase the bin size to 15 by passing in `bins` parameter* set transparency to 60% by passing in `alpha` paramemter* label the x-axis by passing in `x-label` paramater* change the colors of the plots by passing in `color` parameter ###Code # let's get the x-tick values count, bin_edges = np.histogram(df_t, 15) # un-stacked histogram df_t.plot(kind ='hist', figsize=(10, 6), bins=15, alpha=0.6, xticks=bin_edges, color=['coral', 'darkslateblue', 'mediumseagreen'] ) plt.title('Histogram of Immigration from Denmark, Norway, and Sweden from 1980 - 2013') plt.ylabel('Number of Years') plt.xlabel('Number of Immigrants') plt.show() ###Output _____no_output_____ ###Markdown Tip:For a full listing of colors available in Matplotlib, run the following code in your python shell:```pythonimport matplotlibfor name, hex in matplotlib.colors.cnames.items(): print(name, hex)``` If we do no want the plots to overlap each other, we can stack them using the `stacked` paramemter. Let's also adjust the min and max x-axis labels to remove the extra gap on the edges of the plot. We can pass a tuple (min,max) using the `xlim` paramater, as show below. ###Code count, bin_edges = np.histogram(df_t, 15) xmin = bin_edges[0] - 10 # first bin value is 31.0, adding buffer of 10 for aesthetic purposes xmax = bin_edges[-1] + 10 # last bin value is 308.0, adding buffer of 10 for aesthetic purposes # stacked Histogram df_t.plot(kind='hist', figsize=(10, 6), bins=15, xticks=bin_edges, color=['coral', 'darkslateblue', 'mediumseagreen'], stacked=True, xlim=(xmin, xmax) ) plt.title('Histogram of Immigration from Denmark, Norway, and Sweden from 1980 - 2013') plt.ylabel('Number of Years') plt.xlabel('Number of Immigrants') plt.show() ###Output _____no_output_____ ###Markdown **Question**: Use the scripting layer to display the immigration distribution for Greece, Albania, and Bulgaria for years 1980 - 2013? Use an overlapping plot with 15 bins and a transparency value of 0.35. ###Code ### type your answer here ###Output _____no_output_____ ###Markdown Double-click __here__ for the solution.<!-- The correct answer is:\\ create a dataframe of the countries of interest (cof)df_cof = df_can.loc[['Greece', 'Albania', 'Bulgaria'], years]--><!--\\ transpose the dataframedf_cof = df_cof.transpose() --><!--\\ let's get the x-tick valuescount, bin_edges = np.histogram(df_cof, 15)--><!--\\ Un-stacked Histogramdf_cof.plot(kind ='hist', figsize=(10, 6), bins=15, alpha=0.35, xticks=bin_edges, color=['coral', 'darkslateblue', 'mediumseagreen'] )--><!--plt.title('Histogram of Immigration from Greece, Albania, and Bulgaria from 1980 - 2013')plt.ylabel('Number of Years')plt.xlabel('Number of Immigrants')--><!--plt.show()--> Bar Charts (Dataframe) A bar plot is a way of representing data where the *length* of the bars represents the magnitude/size of the feature/variable. Bar graphs usually represent numerical and categorical variables grouped in intervals. To create a bar plot, we can pass one of two arguments via `kind` parameter in `plot()`:* `kind=bar` creates a *vertical* bar plot* `kind=barh` creates a *horizontal* bar plot **Vertical bar plot**In vertical bar graphs, the x-axis is used for labelling, and the length of bars on the y-axis corresponds to the magnitude of the variable being measured. Vertical bar graphs are particuarly useful in analyzing time series data. One disadvantage is that they lack space for text labelling at the foot of each bar. **Let's start off by analyzing the effect of Iceland's Financial Crisis:**The 2008 - 2011 Icelandic Financial Crisis was a major economic and political event in Iceland. Relative to the size of its economy, Iceland's systemic banking collapse was the largest experienced by any country in economic history. The crisis led to a severe economic depression in 2008 - 2011 and significant political unrest.**Question:** Let's compare the number of Icelandic immigrants (country = 'Iceland') to Canada from year 1980 to 2013. ###Code # step 1: get the data df_iceland = df_can.loc['Iceland', years] df_iceland.head() # step 2: plot data df_iceland.plot(kind='bar', figsize=(10, 6)) plt.xlabel('Year') # add to x-label to the plot plt.ylabel('Number of immigrants') # add y-label to the plot plt.title('Icelandic immigrants to Canada from 1980 to 2013') # add title to the plot plt.show() ###Output _____no_output_____ ###Markdown The bar plot above shows the total number of immigrants broken down by each year. We can clearly see the impact of the financial crisis; the number of immigrants to Canada started increasing rapidly after 2008. Let's annotate this on the plot using the `annotate` method of the **scripting layer** or the **pyplot interface**. We will pass in the following parameters:- `s`: str, the text of annotation.- `xy`: Tuple specifying the (x,y) point to annotate (in this case, end point of arrow).- `xytext`: Tuple specifying the (x,y) point to place the text (in this case, start point of arrow).- `xycoords`: The coordinate system that xy is given in - 'data' uses the coordinate system of the object being annotated (default).- `arrowprops`: Takes a dictionary of properties to draw the arrow: - `arrowstyle`: Specifies the arrow style, `'->'` is standard arrow. - `connectionstyle`: Specifies the connection type. `arc3` is a straight line. - `color`: Specifes color of arror. - `lw`: Specifies the line width.I encourage you to read the Matplotlib documentation for more details on annotations: http://matplotlib.org/api/pyplot_api.htmlmatplotlib.pyplot.annotate. ###Code df_iceland.plot(kind='bar', figsize=(10, 6), rot=90) # rotate the bars by 90 degrees plt.xlabel('Year') plt.ylabel('Number of Immigrants') plt.title('Icelandic Immigrants to Canada from 1980 to 2013') # Annotate arrow plt.annotate('', # s: str. Will leave it blank for no text xy=(32, 70), # place head of the arrow at point (year 2012 , pop 70) xytext=(28, 20), # place base of the arrow at point (year 2008 , pop 20) xycoords='data', # will use the coordinate system of the object being annotated arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='blue', lw=2) ) plt.show() ###Output _____no_output_____ ###Markdown Let's also annotate a text to go over the arrow. We will pass in the following additional parameters:- `rotation`: rotation angle of text in degrees (counter clockwise)- `va`: vertical alignment of text [‘center’ | ‘top’ | ‘bottom’ | ‘baseline’]- `ha`: horizontal alignment of text [‘center’ | ‘right’ | ‘left’] ###Code df_iceland.plot(kind='bar', figsize=(10, 6), rot=90) plt.xlabel('Year') plt.ylabel('Number of Immigrants') plt.title('Icelandic Immigrants to Canada from 1980 to 2013') # Annotate arrow plt.annotate('', # s: str. will leave it blank for no text xy=(32, 70), # place head of the arrow at point (year 2012 , pop 70) xytext=(28, 20), # place base of the arrow at point (year 2008 , pop 20) xycoords='data', # will use the coordinate system of the object being annotated arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='blue', lw=2) ) # Annotate Text plt.annotate('2008 - 2011 Financial Crisis', # text to display xy=(28, 30), # start the text at at point (year 2008 , pop 30) rotation=72.5, # based on trial and error to match the arrow va='bottom', # want the text to be vertically 'bottom' aligned ha='left', # want the text to be horizontally 'left' algned. ) plt.show() ###Output _____no_output_____ ###Markdown **Horizontal Bar Plot**Sometimes it is more practical to represent the data horizontally, especially if you need more room for labelling the bars. In horizontal bar graphs, the y-axis is used for labelling, and the length of bars on the x-axis corresponds to the magnitude of the variable being measured. As you will see, there is more room on the y-axis to label categetorical variables.**Question:** Using the scripting layter and the `df_can` dataset, create a *horizontal* bar plot showing the *total* number of immigrants to Canada from the top 15 countries, for the period 1980 - 2013. Label each country with the total immigrant count. Step 1: Get the data pertaining to the top 15 countries. ###Code ### type your answer here ###Output _____no_output_____ ###Markdown Double-click __here__ for the solution.<!-- The correct answer is:\\ sort dataframe on 'Total' column (descending)df_can.sort_values(by='Total', ascending=True, inplace=True)--><!--\\ get top 15 countriesdf_top15 = df_can['Total'].tail(15)df_top15--> Step 2: Plot data: 1. Use `kind='barh'` to generate a bar chart with horizontal bars. 2. Make sure to choose a good size for the plot and to label your axes and to give the plot a title. 3. Loop through the countries and annotate the immigrant population using the anotate function of the scripting interface. ###Code ### type your answer here ###Output _____no_output_____
docs/tutorials/federated_learning_for_image_classification.ipynb
###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} !pip install --quiet --upgrade tensorflow_federated %load_ext tensorboard import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff tf.compat.v1.enable_v2_behavior() np.random.seed(0) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.element_type_structure example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = next(iter(example_dataset)) example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid(False) _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 5 BATCH_SIZE = 20 SHUFFLE_BUFFER = 100 PREFETCH_BUFFER=10 def preprocess(dataset): def batch_format_fn(element): """Flatten a batch `pixels` and return the features as an `OrderedDict`.""" return collections.OrderedDict( x=tf.reshape(element['pixels'], [-1, 784]), y=tf.reshape(element['label'], [-1, 1])) return dataset.repeat(NUM_EPOCHS).shuffle(SHUFFLE_BUFFER).batch( BATCH_SIZE).map(batch_format_fn).prefetch(PREFETCH_BUFFER) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure(lambda x: x.numpy(), next(iter(preprocessed_example_dataset))) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [ preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids ] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) print('Number of client datasets: {l}'.format(l=len(federated_train_data))) print('First dataset: {d}'.format(d=federated_train_data[0])) ###Output Number of client datasets: 10 First dataset: <DatasetV1Adapter shapes: OrderedDict([(x, (None, 784)), (y, (None, 1))]), types: OrderedDict([(x, tf.float32), (y, tf.int32)])> ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_keras_model(): return tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(784,)), tf.keras.layers.Dense(10, kernel_initializer='zeros'), tf.keras.layers.Softmax(), ]) ###Output _____no_output_____ ###Markdown **Note:** we do not compile the model yet. The loss, metrics, and optimizers are introduced later.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a Keras model like theone we've just defined above, you can have TFF wrap it for you by invoking`tff.learning.from_keras_model`, passing the model and a sample data batch asarguments, as shown below. ###Code def model_fn(): # We _must_ create a new model here, and _not_ capture it from an external # scope. TFF will call this within different graph contexts. keras_model = create_keras_model() return tff.learning.from_keras_model( keras_model, input_spec=preprocessed_example_dataset.element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)).One critical note on the Federated Averaging algorithm below, there are **2**optimizers: a _client_optimizer_ and a _server_optimizer_. The_client_optimizer_ is only used to compute local model updates on each client.The _server_optimizer_ applies the averaged update to the global model at theserver. In particular, this means that the choice of optimizer and learning rateused may need to be different than the ones you have used to train the model ona standard i.i.d. dataset. We recommend starting with regular SGD, possibly witha smaller learning rate than usual. The learning rate we use has not beencarefully tuned, feel free to experiment. ###Code iterative_process = tff.learning.build_federated_averaging_process( model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02), server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0)) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.1281892955303192,loss=3.112910270690918,keras_training_time_client_sum_sec=0.0> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code NUM_ROUNDS = 11 for round_num in range(2, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.1366255134344101,loss=3.0699315071105957,keras_training_time_client_sum_sec=0.0> round 3, metrics=<sparse_categorical_accuracy=0.14938271045684814,loss=2.967233657836914,keras_training_time_client_sum_sec=0.0> round 4, metrics=<sparse_categorical_accuracy=0.17860081791877747,loss=2.7275609970092773,keras_training_time_client_sum_sec=0.0> round 5, metrics=<sparse_categorical_accuracy=0.20637859404087067,loss=2.601724863052368,keras_training_time_client_sum_sec=0.0> round 6, metrics=<sparse_categorical_accuracy=0.2100823074579239,loss=2.5941531658172607,keras_training_time_client_sum_sec=0.0> round 7, metrics=<sparse_categorical_accuracy=0.244650200009346,loss=2.3704617023468018,keras_training_time_client_sum_sec=0.0> round 8, metrics=<sparse_categorical_accuracy=0.2720164656639099,loss=2.225743293762207,keras_training_time_client_sum_sec=0.0> round 9, metrics=<sparse_categorical_accuracy=0.28641974925994873,loss=2.2297680377960205,keras_training_time_client_sum_sec=0.0> round 10, metrics=<sparse_categorical_accuracy=0.31975308060646057,loss=2.0716400146484375,keras_training_time_client_sum_sec=0.0> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Displaying model metrics in TensorBoardNext, let's visualize the metrics from these federated computations using Tensorboard.Let's start by creating the directory and the corresponding summary writer to write the metrics to. ###Code #@test {"skip": true} logdir = "/tmp/logs/scalars/training/" summary_writer = tf.summary.create_file_writer(logdir) state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown Plot the relevant scalar metrics with the same summary writer. ###Code #@test {"skip": true} with summary_writer.as_default(): for round_num in range(1, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) for name, value in metrics._asdict().items(): tf.summary.scalar(name, value, step=round_num) ###Output _____no_output_____ ###Markdown Start TensorBoard with the root log directory specified above. It can take a few seconds for the data to load. ###Code #@test {"skip": true} %tensorboard --logdir /tmp/logs/scalars/ --port=0 #@test {"skip": true} # Run this this cell to clean your directory of old output for future graphs from this directory. !rm -R /tmp/logs/scalars/* ###Output _____no_output_____ ###Markdown In order to view evaluation metrics the same way, you can create a separate eval folder, like "logs/scalars/eval", to write to TensorBoard. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples=tf.Variable(0.0, name='num_examples', trainable=False), loss_sum=tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum=tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean( tf.reduce_sum(tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict( num_examples=variables.num_examples, loss=variables.loss_sum / variables.num_examples, accuracy=variables.accuracy_sum / variables.num_examples) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return collections.OrderedDict( num_examples=tff.federated_sum(metrics.num_examples), loss=tff.federated_mean(metrics.loss, metrics.num_examples), accuracy=tff.federated_mean(metrics.accuracy, metrics.num_examples)) ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict( x=tf.TensorSpec([None, 784], tf.float32), y=tf.TensorSpec([None, 1], tf.int32)) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. We will specify a local optimizer when building the Federated Averaging algorithm. Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistModel, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02)) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<num_examples=4860.0,loss=3.0044455528259277,accuracy=0.1366255134344101> round 3, metrics=<num_examples=4860.0,loss=2.8893046379089355,accuracy=0.14753086864948273> round 4, metrics=<num_examples=4860.0,loss=2.742488384246826,accuracy=0.1720164567232132> round 5, metrics=<num_examples=4860.0,loss=2.52746844291687,accuracy=0.20843622088432312> round 6, metrics=<num_examples=4860.0,loss=2.455655574798584,accuracy=0.23127572238445282> round 7, metrics=<num_examples=4860.0,loss=2.369921922683716,accuracy=0.2522633671760559> round 8, metrics=<num_examples=4860.0,loss=2.288294553756714,accuracy=0.27345678210258484> round 9, metrics=<num_examples=4860.0,loss=2.18411922454834,accuracy=0.2890946567058563> round 10, metrics=<num_examples=4860.0,loss=2.048980951309204,accuracy=0.32510289549827576> ###Markdown To see these metrics within TensorBoard, refer to the steps listed above in "Displaying model metrics in TensorBoard". EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the `0.7.0` version of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarly for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. # NOTE: The high-performance executor components used in this tutorial are not # yet included in the released pip package; you may need to compile from source. !pip install --quiet tensorflow_federated !pip install --quiet tf-nightly==1.15.0.dev20190730 # NOTE: Jupyter requires a patch to asyncio. !pip install --upgrade nest_asyncio import nest_asyncio nest_asyncio.apply() from __future__ import absolute_import, division, print_function import collections import warnings from six.moves import range import numpy as np import six import tensorflow as tf import tensorflow_federated as tff warnings.simplefilter('ignore') tf.compat.v1.enable_v2_behavior() np.random.seed(0) NUM_CLIENTS = 10 # NOTE: If the statement below fails, it means that you are # using an older version of TFF without the high-performance # executor stack. Call `tff.framework.set_default_executor()` # instead to use the default reference runtime. if six.PY3: tff.framework.set_default_executor( tff.framework.create_local_executor(NUM_CLIENTS)) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code #@test {"output": "ignore"} emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() #@test {"output": "ignore"} from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code #@test {"output": "ignore"} preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code #@test {"output": "ignore"} sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code #@test {"output": "ignore"} iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code #@test {"output": "ignore"} str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hypermarameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output _____no_output_____ ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output _____no_output_____ ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are elligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_mean(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) return tff.learning.BatchOutput(loss=loss, predictions=predictions) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` correspond to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): @tf.function def train_on_batch(self, batch): output = self.forward_pass(batch) optimizer = tf.train.GradientDescentOptimizer(0.02) optimizer.minimize(output.loss, var_list=self.trainable_variables) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output _____no_output_____ ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code #@test {"output": "ignore"} train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code #@test {"output": "ignore"} str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] #@test {"output": "ignore"} test_metrics = evaluation(state.model, federated_test_data) #@test {"output": "ignore"} str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. # NOTE: The high-performance executor components used in this tutorial are not # yet included in the released pip package; you may need to compile from source. !pip install --quiet --upgrade tensorflow_federated !pip install --quiet --upgrade tf-nightly # NOTE: Jupyter requires a patch to asyncio. !pip install --upgrade nest_asyncio import nest_asyncio nest_asyncio.apply() from __future__ import absolute_import, division, print_function import collections import warnings from six.moves import range import numpy as np import six import tensorflow as tf import tensorflow_federated as tff warnings.simplefilter('ignore') tf.compat.v1.enable_v2_behavior() np.random.seed(0) # NOTE: If the statement below fails, it means that you are # using an older version of TFF without the high-performance # executor stack. Call `tff.framework.set_default_executor()` # instead to use the default reference runtime. if six.PY3: tff.framework.set_default_executor(tff.framework.create_local_executor()) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.13611111044883728,loss=2.965381383895874> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.1849794238805771,loss=2.7118875980377197> round 3, metrics=<sparse_categorical_accuracy=0.22695472836494446,loss=2.4792754650115967> round 4, metrics=<sparse_categorical_accuracy=0.28199589252471924,loss=2.2289276123046875> round 5, metrics=<sparse_categorical_accuracy=0.32818931341171265,loss=2.078141212463379> round 6, metrics=<sparse_categorical_accuracy=0.36306583881378174,loss=1.9316236972808838> round 7, metrics=<sparse_categorical_accuracy=0.4278806447982788,loss=1.7558836936950684> round 8, metrics=<sparse_categorical_accuracy=0.46574074029922485,loss=1.6373158693313599> round 9, metrics=<sparse_categorical_accuracy=0.5045267343521118,loss=1.5398069620132446> round 10, metrics=<sparse_categorical_accuracy=0.5650205612182617,loss=1.393721342086792> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_mean(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): @tf.function def train_on_batch(self, batch): with tf.GradientTape() as tape: output = self.forward_pass(batch) grads = tape.gradient(output.loss, self.trainable_variables) optimizer = tf.keras.optimizers.SGD(0.02) optimizer.apply_gradients( zip(tf.nest.flatten(grads), tf.nest.flatten(self.trainable_variables))) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<accuracy=0.16872428357601166,loss=2.848231077194214,num_examples=9720.0> round 3, metrics=<accuracy=0.21512345969676971,loss=2.561239719390869,num_examples=9720.0> round 4, metrics=<accuracy=0.2696501910686493,loss=2.3002827167510986,num_examples=9720.0> round 5, metrics=<accuracy=0.318107008934021,loss=2.091233730316162,num_examples=9720.0> round 6, metrics=<accuracy=0.38456788659095764,loss=1.8714815378189087,num_examples=9720.0> round 7, metrics=<accuracy=0.4193415641784668,loss=1.7886154651641846,num_examples=9720.0> round 8, metrics=<accuracy=0.47016459703445435,loss=1.6355195045471191,num_examples=9720.0> round 9, metrics=<accuracy=0.5048353672027588,loss=1.5353692770004272,num_examples=9720.0> round 10, metrics=<accuracy=0.5529835224151611,loss=1.4297906160354614,num_examples=9720.0> ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the `0.6.0` version of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarly for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. # NOTE: The high-performance executor components used in this tutorial are not # yet included in the released pip package; you may need to compile from source. !pip install --quiet tensorflow_federated !pip install --quiet tf-nightly from __future__ import absolute_import, division, print_function import collections import warnings from six.moves import range import numpy as np import six import tensorflow as tf warnings.simplefilter('ignore') tf.compat.v1.enable_v2_behavior() import tensorflow_federated as tff np.random.seed(0) NUM_CLIENTS = 10 # NOTE: If the statement below fails, it means that you are # using an older version of TFF without the high-performance # executor stack. Call `tff.framework.set_default_executor()` # instead to use the default reference runtime. if six.PY3: tff.framework.set_default_executor( tff.framework.create_local_executor(NUM_CLIENTS)) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code #@test {"output": "ignore"} emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() #@test {"output": "ignore"} from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code #@test {"output": "ignore"} preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code #@test {"output": "ignore"} sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code #@test {"output": "ignore"} iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code #@test {"output": "ignore"} str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hypermarameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.14177,loss=2.99453> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.178395,loss=2.73984> round 3, metrics=<sparse_categorical_accuracy=0.223148,loss=2.49505> round 4, metrics=<sparse_categorical_accuracy=0.277881,loss=2.2728> round 5, metrics=<sparse_categorical_accuracy=0.333025,loss=2.07288> round 6, metrics=<sparse_categorical_accuracy=0.382407,loss=1.9035> round 7, metrics=<sparse_categorical_accuracy=0.43714,loss=1.75284> round 8, metrics=<sparse_categorical_accuracy=0.485082,loss=1.62087> round 9, metrics=<sparse_categorical_accuracy=0.528601,loss=1.50645> round 10, metrics=<sparse_categorical_accuracy=0.568004,loss=1.40643> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.log(y), reduction_indices=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are elligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_mean(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) return tff.learning.BatchOutput(loss=loss, predictions=predictions) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` correspond to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): @tf.function def train_on_batch(self, batch): output = self.forward_pass(batch) optimizer = tf.train.GradientDescentOptimizer(0.02) optimizer.minimize(output.loss, var_list=self.trainable_variables) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<accuracy=0.178395,loss=2.73984,num_examples=9720.0> round 3, metrics=<accuracy=0.223148,loss=2.49505,num_examples=9720.0> round 4, metrics=<accuracy=0.277881,loss=2.2728,num_examples=9720.0> round 5, metrics=<accuracy=0.333025,loss=2.07288,num_examples=9720.0> round 6, metrics=<accuracy=0.382407,loss=1.9035,num_examples=9720.0> round 7, metrics=<accuracy=0.43714,loss=1.75284,num_examples=9720.0> round 8, metrics=<accuracy=0.485082,loss=1.62087,num_examples=9720.0> round 9, metrics=<accuracy=0.528601,loss=1.50645,num_examples=9720.0> round 10, metrics=<accuracy=0.568004,loss=1.40643,num_examples=9720.0> ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code #@test {"output": "ignore"} train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code #@test {"output": "ignore"} str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] #@test {"output": "ignore"} test_metrics = evaluation(state.model, federated_test_data) #@test {"output": "ignore"} str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} !pip install --quiet --upgrade tensorflow_federated_nightly !pip install --quiet --upgrade nest_asyncio import nest_asyncio nest_asyncio.apply() %load_ext tensorboard import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff np.random.seed(0) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.element_type_structure example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = next(iter(example_dataset)) example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid(False) _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 5 BATCH_SIZE = 20 SHUFFLE_BUFFER = 100 PREFETCH_BUFFER=10 def preprocess(dataset): def batch_format_fn(element): """Flatten a batch `pixels` and return the features as an `OrderedDict`.""" return collections.OrderedDict( x=tf.reshape(element['pixels'], [-1, 784]), y=tf.reshape(element['label'], [-1, 1])) return dataset.repeat(NUM_EPOCHS).shuffle(SHUFFLE_BUFFER).batch( BATCH_SIZE).map(batch_format_fn).prefetch(PREFETCH_BUFFER) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure(lambda x: x.numpy(), next(iter(preprocessed_example_dataset))) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [ preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids ] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) print('Number of client datasets: {l}'.format(l=len(federated_train_data))) print('First dataset: {d}'.format(d=federated_train_data[0])) ###Output Number of client datasets: 10 First dataset: <DatasetV1Adapter shapes: OrderedDict([(x, (None, 784)), (y, (None, 1))]), types: OrderedDict([(x, tf.float32), (y, tf.int32)])> ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_keras_model(): return tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(784,)), tf.keras.layers.Dense(10, kernel_initializer='zeros'), tf.keras.layers.Softmax(), ]) ###Output _____no_output_____ ###Markdown **Note:** we do not compile the model yet. The loss, metrics, and optimizers are introduced later.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a Keras model like theone we've just defined above, you can have TFF wrap it for you by invoking`tff.learning.from_keras_model`, passing the model and a sample data batch asarguments, as shown below. ###Code def model_fn(): # We _must_ create a new model here, and _not_ capture it from an external # scope. TFF will call this within different graph contexts. keras_model = create_keras_model() return tff.learning.from_keras_model( keras_model, input_spec=preprocessed_example_dataset.element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)).One critical note on the Federated Averaging algorithm below, there are **2**optimizers: a _client_optimizer_ and a _server_optimizer_. The_client_optimizer_ is only used to compute local model updates on each client.The _server_optimizer_ applies the averaged update to the global model at theserver. In particular, this means that the choice of optimizer and learning rateused may need to be different than the ones you have used to train the model ona standard i.i.d. dataset. We recommend starting with regular SGD, possibly witha smaller learning rate than usual. The learning rate we use has not beencarefully tuned, feel free to experiment. ###Code iterative_process = tff.learning.build_federated_averaging_process( model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02), server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0)) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.templates.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.12037037312984467,loss=3.0108425617218018>> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code NUM_ROUNDS = 11 for round_num in range(2, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.14814814925193787,loss=2.8865506649017334>> round 3, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.148765429854393,loss=2.9079062938690186>> round 4, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.17633745074272156,loss=2.724686622619629>> round 5, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.20226337015628815,loss=2.6334855556488037>> round 6, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.22427983582019806,loss=2.5482592582702637>> round 7, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.24094650149345398,loss=2.4472343921661377>> round 8, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.259876549243927,loss=2.3809611797332764>> round 9, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.29814815521240234,loss=2.156442403793335>> round 10, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.31687241792678833,loss=2.122845411300659>> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Displaying model metrics in TensorBoardNext, let's visualize the metrics from these federated computations using Tensorboard.Let's start by creating the directory and the corresponding summary writer to write the metrics to. ###Code #@test {"skip": true} logdir = "/tmp/logs/scalars/training/" summary_writer = tf.summary.create_file_writer(logdir) state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown Plot the relevant scalar metrics with the same summary writer. ###Code #@test {"skip": true} with summary_writer.as_default(): for round_num in range(1, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) for name, value in metrics.train._asdict().items(): tf.summary.scalar(name, value, step=round_num) ###Output _____no_output_____ ###Markdown Start TensorBoard with the root log directory specified above. It can take a few seconds for the data to load. ###Code #@test {"skip": true} %tensorboard --logdir /tmp/logs/scalars/ --port=0 #@test {"skip": true} # Run this this cell to clean your directory of old output for future graphs from this directory. !rm -R /tmp/logs/scalars/* ###Output _____no_output_____ ###Markdown In order to view evaluation metrics the same way, you can create a separate eval folder, like "logs/scalars/eval", to write to TensorBoard. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples=tf.Variable(0.0, name='num_examples', trainable=False), loss_sum=tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum=tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean( tf.reduce_sum(tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict( num_examples=variables.num_examples, loss=variables.loss_sum / variables.num_examples, accuracy=variables.accuracy_sum / variables.num_examples) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return collections.OrderedDict( num_examples=tff.federated_sum(metrics.num_examples), loss=tff.federated_mean(metrics.loss, metrics.num_examples), accuracy=tff.federated_mean(metrics.accuracy, metrics.num_examples)) ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict( x=tf.TensorSpec([None, 784], tf.float32), y=tf.TensorSpec([None, 1], tf.int32)) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. We will specify a local optimizer when building the Federated Averaging algorithm. Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistModel, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02)) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.975412607192993,accuracy=0.14032921195030212>> round 3, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.9395227432250977,accuracy=0.1594650149345398>> round 4, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.710164785385132,accuracy=0.17139917612075806>> round 5, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.5891618728637695,accuracy=0.20267489552497864>> round 6, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.5148487091064453,accuracy=0.21666666865348816>> round 7, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.2816808223724365,accuracy=0.2580246925354004>> round 8, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.3656885623931885,accuracy=0.25884774327278137>> round 9, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.23549222946167,accuracy=0.28477364778518677>> round 10, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=1.974222183227539,accuracy=0.35329216718673706>> ###Markdown To see these metrics within TensorBoard, refer to the steps listed above in "Displaying model metrics in TensorBoard". EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.templates.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the `0.7.0` version of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. # NOTE: The high-performance executor components used in this tutorial are not # yet included in the released pip package; you may need to compile from source. !pip install --quiet tensorflow_federated !pip install --quiet tf-nightly==1.15.0.dev20190805 # NOTE: Jupyter requires a patch to asyncio. !pip install --upgrade nest_asyncio import nest_asyncio nest_asyncio.apply() from __future__ import absolute_import, division, print_function import collections import warnings from six.moves import range import numpy as np import six import tensorflow as tf import tensorflow_federated as tff warnings.simplefilter('ignore') tf.compat.v1.enable_v2_behavior() np.random.seed(0) NUM_CLIENTS = 10 # NOTE: If the statement below fails, it means that you are # using an older version of TFF without the high-performance # executor stack. Call `tff.framework.set_default_executor()` # instead to use the default reference runtime. if six.PY3: tff.framework.set_default_executor( tff.framework.create_local_executor(NUM_CLIENTS)) tff.federated_computation(lambda: 'Hello, World!')() ###Output WARNING: Logging before flag parsing goes to stderr. W0729 21:59:33.932531 140191347251072 lazy_loader.py:50] The TensorFlow contrib module will not be included in TensorFlow 2.0. For more information, please see: * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md * https://github.com/tensorflow/addons * https://github.com/tensorflow/io (for I/O related ops) If you depend on functionality not listed there, please file an issue. ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code #@test {"output": "ignore"} emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output Downloading data from https://storage.googleapis.com/tff-datasets-public/fed_emnist_digitsonly.tar.bz2 97402880/97398400 [==============================] - 1s 0us/step ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() #@test {"output": "ignore"} from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code #@test {"output": "ignore"} preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code #@test {"output": "ignore"} sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code #@test {"output": "ignore"} iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output W0729 22:10:05.047176 140191347251072 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1633: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version. Instructions for updating: If using Keras pass *_constraint arguments to layers. W0729 22:10:06.026015 140191347251072 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/optimizer_v2/optimizer_v2.py:468: BaseResourceVariable.constraint (from tensorflow.python.ops.resource_variable_ops) is deprecated and will be removed in a future version. Instructions for updating: Apply a constraint manually following the optimizer update step. W0729 22:10:06.053691 140191347251072 deprecation.py:323] From /usr/local/lib/python3.6/dist-packages/tensorflow_federated/python/core/impl/type_utils.py:358: _TensorStructure (from tensorflow.python.data.util.structure) is deprecated and will be removed in a future version. Instructions for updating: Use `tf.TensorSpec` instead. ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code #@test {"output": "ignore"} str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output _____no_output_____ ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.17541152,loss=2.6967409> round 3, metrics=<sparse_categorical_accuracy=0.22685185,loss=2.45448> round 4, metrics=<sparse_categorical_accuracy=0.27890947,loss=2.2326477> round 5, metrics=<sparse_categorical_accuracy=0.3339506,loss=2.0399523> round 6, metrics=<sparse_categorical_accuracy=0.38395062,loss=1.8710887> round 7, metrics=<sparse_categorical_accuracy=0.43271604,loss=1.7228407> round 8, metrics=<sparse_categorical_accuracy=0.48117283,loss=1.5928143> round 9, metrics=<sparse_categorical_accuracy=0.52890944,loss=1.4796019> round 10, metrics=<sparse_categorical_accuracy=0.56965023,loss=1.3811109> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_mean(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) return tff.learning.BatchOutput(loss=loss, predictions=predictions) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): @tf.function def train_on_batch(self, batch): output = self.forward_pass(batch) optimizer = tf.train.GradientDescentOptimizer(0.02) optimizer.minimize(output.loss, var_list=self.trainable_variables) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<accuracy=0.17541152,loss=2.6967404,num_examples=9720.0> round 3, metrics=<accuracy=0.22685185,loss=2.4544795,num_examples=9720.0> round 4, metrics=<accuracy=0.27890947,loss=2.232648,num_examples=9720.0> round 5, metrics=<accuracy=0.3339506,loss=2.0399525,num_examples=9720.0> round 6, metrics=<accuracy=0.38395062,loss=1.8710885,num_examples=9720.0> round 7, metrics=<accuracy=0.43271604,loss=1.7228407,num_examples=9720.0> round 8, metrics=<accuracy=0.48117283,loss=1.592814,num_examples=9720.0> round 9, metrics=<accuracy=0.52890944,loss=1.4796019,num_examples=9720.0> round 10, metrics=<accuracy=0.56965023,loss=1.3811109,num_examples=9720.0> ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code #@test {"output": "ignore"} train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code #@test {"output": "ignore"} str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] #@test {"output": "ignore"} test_metrics = evaluation(state.model, federated_test_data) #@test {"output": "ignore"} str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} !pip install --quiet --upgrade tensorflow_federated %load_ext tensorboard import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff tf.compat.v1.enable_v2_behavior() np.random.seed(0) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.element_type_structure example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = next(iter(example_dataset)) example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid(False) _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 5 BATCH_SIZE = 20 SHUFFLE_BUFFER = 100 PREFETCH_BUFFER=10 def preprocess(dataset): def batch_format_fn(element): """Flatten a batch `pixels` and return the features as an `OrderedDict`.""" return collections.OrderedDict( x=tf.reshape(element['pixels'], [-1, 784]), y=tf.reshape(element['label'], [-1, 1])) return dataset.repeat(NUM_EPOCHS).shuffle(SHUFFLE_BUFFER).batch( BATCH_SIZE).map(batch_format_fn).prefetch(PREFETCH_BUFFER) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure(lambda x: x.numpy(), next(iter(preprocessed_example_dataset))) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [ preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids ] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) print('Number of client datasets: {l}'.format(l=len(federated_train_data))) print('First dataset: {d}'.format(d=federated_train_data[0])) ###Output Number of client datasets: 10 First dataset: <DatasetV1Adapter shapes: OrderedDict([(x, (None, 784)), (y, (None, 1))]), types: OrderedDict([(x, tf.float32), (y, tf.int32)])> ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_keras_model(): return tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(784,)), tf.keras.layers.Dense(10, kernel_initializer='zeros'), tf.keras.layers.Softmax(), ]) ###Output _____no_output_____ ###Markdown **Note:** we do not compile the model yet. The loss, metrics, and optimizers are introduced later.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a Keras model like theone we've just defined above, you can have TFF wrap it for you by invoking`tff.learning.from_keras_model`, passing the model and a sample data batch asarguments, as shown below. ###Code def model_fn(): # We _must_ create a new model here, and _not_ capture it from an external # scope. TFF will call this within different graph contexts. keras_model = create_keras_model() return tff.learning.from_keras_model( keras_model, input_spec=preprocessed_example_dataset.element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)).One critical note on the Federated Averaging algorithm below, there are **2**optimizers: a _client_optimizer_ and a _server_optimizer_. The_client_optimizer_ is only used to compute local model updates on each client.The _server_optimizer_ applies the averaged update to the global model at theserver. In particular, this means that the choice of optimizer and learning rateused may need to be different than the ones you have used to train the model ona standard i.i.d. dataset. We recommend starting with regular SGD, possibly witha smaller learning rate than usual. The learning rate we use has not beencarefully tuned, feel free to experiment. ###Code iterative_process = tff.learning.build_federated_averaging_process( model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02), server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0)) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.templates.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.1281892955303192,loss=3.112910270690918,keras_training_time_client_sum_sec=0.0> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code NUM_ROUNDS = 11 for round_num in range(2, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.1366255134344101,loss=3.0699315071105957,keras_training_time_client_sum_sec=0.0> round 3, metrics=<sparse_categorical_accuracy=0.14938271045684814,loss=2.967233657836914,keras_training_time_client_sum_sec=0.0> round 4, metrics=<sparse_categorical_accuracy=0.17860081791877747,loss=2.7275609970092773,keras_training_time_client_sum_sec=0.0> round 5, metrics=<sparse_categorical_accuracy=0.20637859404087067,loss=2.601724863052368,keras_training_time_client_sum_sec=0.0> round 6, metrics=<sparse_categorical_accuracy=0.2100823074579239,loss=2.5941531658172607,keras_training_time_client_sum_sec=0.0> round 7, metrics=<sparse_categorical_accuracy=0.244650200009346,loss=2.3704617023468018,keras_training_time_client_sum_sec=0.0> round 8, metrics=<sparse_categorical_accuracy=0.2720164656639099,loss=2.225743293762207,keras_training_time_client_sum_sec=0.0> round 9, metrics=<sparse_categorical_accuracy=0.28641974925994873,loss=2.2297680377960205,keras_training_time_client_sum_sec=0.0> round 10, metrics=<sparse_categorical_accuracy=0.31975308060646057,loss=2.0716400146484375,keras_training_time_client_sum_sec=0.0> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Displaying model metrics in TensorBoardNext, let's visualize the metrics from these federated computations using Tensorboard.Let's start by creating the directory and the corresponding summary writer to write the metrics to. ###Code #@test {"skip": true} logdir = "/tmp/logs/scalars/training/" summary_writer = tf.summary.create_file_writer(logdir) state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown Plot the relevant scalar metrics with the same summary writer. ###Code #@test {"skip": true} with summary_writer.as_default(): for round_num in range(1, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) for name, value in metrics._asdict().items(): tf.summary.scalar(name, value, step=round_num) ###Output _____no_output_____ ###Markdown Start TensorBoard with the root log directory specified above. It can take a few seconds for the data to load. ###Code #@test {"skip": true} %tensorboard --logdir /tmp/logs/scalars/ --port=0 #@test {"skip": true} # Run this this cell to clean your directory of old output for future graphs from this directory. !rm -R /tmp/logs/scalars/* ###Output _____no_output_____ ###Markdown In order to view evaluation metrics the same way, you can create a separate eval folder, like "logs/scalars/eval", to write to TensorBoard. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples=tf.Variable(0.0, name='num_examples', trainable=False), loss_sum=tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum=tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean( tf.reduce_sum(tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict( num_examples=variables.num_examples, loss=variables.loss_sum / variables.num_examples, accuracy=variables.accuracy_sum / variables.num_examples) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return collections.OrderedDict( num_examples=tff.federated_sum(metrics.num_examples), loss=tff.federated_mean(metrics.loss, metrics.num_examples), accuracy=tff.federated_mean(metrics.accuracy, metrics.num_examples)) ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict( x=tf.TensorSpec([None, 784], tf.float32), y=tf.TensorSpec([None, 1], tf.int32)) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. We will specify a local optimizer when building the Federated Averaging algorithm. Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistModel, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02)) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<num_examples=4860.0,loss=3.0044455528259277,accuracy=0.1366255134344101> round 3, metrics=<num_examples=4860.0,loss=2.8893046379089355,accuracy=0.14753086864948273> round 4, metrics=<num_examples=4860.0,loss=2.742488384246826,accuracy=0.1720164567232132> round 5, metrics=<num_examples=4860.0,loss=2.52746844291687,accuracy=0.20843622088432312> round 6, metrics=<num_examples=4860.0,loss=2.455655574798584,accuracy=0.23127572238445282> round 7, metrics=<num_examples=4860.0,loss=2.369921922683716,accuracy=0.2522633671760559> round 8, metrics=<num_examples=4860.0,loss=2.288294553756714,accuracy=0.27345678210258484> round 9, metrics=<num_examples=4860.0,loss=2.18411922454834,accuracy=0.2890946567058563> round 10, metrics=<num_examples=4860.0,loss=2.048980951309204,accuracy=0.32510289549827576> ###Markdown To see these metrics within TensorBoard, refer to the steps listed above in "Displaying model metrics in TensorBoard". EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.templates.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} !pip install --quiet --upgrade tensorflow_federated %load_ext tensorboard import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff np.random.seed(0) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.element_type_structure example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = next(iter(example_dataset)) example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid(False) _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 5 BATCH_SIZE = 20 SHUFFLE_BUFFER = 100 PREFETCH_BUFFER=10 def preprocess(dataset): def batch_format_fn(element): """Flatten a batch `pixels` and return the features as an `OrderedDict`.""" return collections.OrderedDict( x=tf.reshape(element['pixels'], [-1, 784]), y=tf.reshape(element['label'], [-1, 1])) return dataset.repeat(NUM_EPOCHS).shuffle(SHUFFLE_BUFFER).batch( BATCH_SIZE).map(batch_format_fn).prefetch(PREFETCH_BUFFER) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure(lambda x: x.numpy(), next(iter(preprocessed_example_dataset))) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [ preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids ] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) print('Number of client datasets: {l}'.format(l=len(federated_train_data))) print('First dataset: {d}'.format(d=federated_train_data[0])) ###Output Number of client datasets: 10 First dataset: <DatasetV1Adapter shapes: OrderedDict([(x, (None, 784)), (y, (None, 1))]), types: OrderedDict([(x, tf.float32), (y, tf.int32)])> ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_keras_model(): return tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(784,)), tf.keras.layers.Dense(10, kernel_initializer='zeros'), tf.keras.layers.Softmax(), ]) ###Output _____no_output_____ ###Markdown **Note:** we do not compile the model yet. The loss, metrics, and optimizers are introduced later.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a Keras model like theone we've just defined above, you can have TFF wrap it for you by invoking`tff.learning.from_keras_model`, passing the model and a sample data batch asarguments, as shown below. ###Code def model_fn(): # We _must_ create a new model here, and _not_ capture it from an external # scope. TFF will call this within different graph contexts. keras_model = create_keras_model() return tff.learning.from_keras_model( keras_model, input_spec=preprocessed_example_dataset.element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)).One critical note on the Federated Averaging algorithm below, there are **2**optimizers: a _client_optimizer_ and a _server_optimizer_. The_client_optimizer_ is only used to compute local model updates on each client.The _server_optimizer_ applies the averaged update to the global model at theserver. In particular, this means that the choice of optimizer and learning rateused may need to be different than the ones you have used to train the model ona standard i.i.d. dataset. We recommend starting with regular SGD, possibly witha smaller learning rate than usual. The learning rate we use has not beencarefully tuned, feel free to experiment. ###Code iterative_process = tff.learning.build_federated_averaging_process( model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02), server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0)) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.templates.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.1281892955303192,loss=3.112910270690918,keras_training_time_client_sum_sec=0.0> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code NUM_ROUNDS = 11 for round_num in range(2, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.1366255134344101,loss=3.0699315071105957,keras_training_time_client_sum_sec=0.0> round 3, metrics=<sparse_categorical_accuracy=0.14938271045684814,loss=2.967233657836914,keras_training_time_client_sum_sec=0.0> round 4, metrics=<sparse_categorical_accuracy=0.17860081791877747,loss=2.7275609970092773,keras_training_time_client_sum_sec=0.0> round 5, metrics=<sparse_categorical_accuracy=0.20637859404087067,loss=2.601724863052368,keras_training_time_client_sum_sec=0.0> round 6, metrics=<sparse_categorical_accuracy=0.2100823074579239,loss=2.5941531658172607,keras_training_time_client_sum_sec=0.0> round 7, metrics=<sparse_categorical_accuracy=0.244650200009346,loss=2.3704617023468018,keras_training_time_client_sum_sec=0.0> round 8, metrics=<sparse_categorical_accuracy=0.2720164656639099,loss=2.225743293762207,keras_training_time_client_sum_sec=0.0> round 9, metrics=<sparse_categorical_accuracy=0.28641974925994873,loss=2.2297680377960205,keras_training_time_client_sum_sec=0.0> round 10, metrics=<sparse_categorical_accuracy=0.31975308060646057,loss=2.0716400146484375,keras_training_time_client_sum_sec=0.0> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Displaying model metrics in TensorBoardNext, let's visualize the metrics from these federated computations using Tensorboard.Let's start by creating the directory and the corresponding summary writer to write the metrics to. ###Code #@test {"skip": true} logdir = "/tmp/logs/scalars/training/" summary_writer = tf.summary.create_file_writer(logdir) state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown Plot the relevant scalar metrics with the same summary writer. ###Code #@test {"skip": true} with summary_writer.as_default(): for round_num in range(1, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) for name, value in metrics._asdict().items(): tf.summary.scalar(name, value, step=round_num) ###Output _____no_output_____ ###Markdown Start TensorBoard with the root log directory specified above. It can take a few seconds for the data to load. ###Code #@test {"skip": true} %tensorboard --logdir /tmp/logs/scalars/ --port=0 #@test {"skip": true} # Run this this cell to clean your directory of old output for future graphs from this directory. !rm -R /tmp/logs/scalars/* ###Output _____no_output_____ ###Markdown In order to view evaluation metrics the same way, you can create a separate eval folder, like "logs/scalars/eval", to write to TensorBoard. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples=tf.Variable(0.0, name='num_examples', trainable=False), loss_sum=tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum=tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean( tf.reduce_sum(tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict( num_examples=variables.num_examples, loss=variables.loss_sum / variables.num_examples, accuracy=variables.accuracy_sum / variables.num_examples) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return collections.OrderedDict( num_examples=tff.federated_sum(metrics.num_examples), loss=tff.federated_mean(metrics.loss, metrics.num_examples), accuracy=tff.federated_mean(metrics.accuracy, metrics.num_examples)) ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict( x=tf.TensorSpec([None, 784], tf.float32), y=tf.TensorSpec([None, 1], tf.int32)) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. We will specify a local optimizer when building the Federated Averaging algorithm. Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistModel, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02)) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<num_examples=4860.0,loss=3.0044455528259277,accuracy=0.1366255134344101> round 3, metrics=<num_examples=4860.0,loss=2.8893046379089355,accuracy=0.14753086864948273> round 4, metrics=<num_examples=4860.0,loss=2.742488384246826,accuracy=0.1720164567232132> round 5, metrics=<num_examples=4860.0,loss=2.52746844291687,accuracy=0.20843622088432312> round 6, metrics=<num_examples=4860.0,loss=2.455655574798584,accuracy=0.23127572238445282> round 7, metrics=<num_examples=4860.0,loss=2.369921922683716,accuracy=0.2522633671760559> round 8, metrics=<num_examples=4860.0,loss=2.288294553756714,accuracy=0.27345678210258484> round 9, metrics=<num_examples=4860.0,loss=2.18411922454834,accuracy=0.2890946567058563> round 10, metrics=<num_examples=4860.0,loss=2.048980951309204,accuracy=0.32510289549827576> ###Markdown To see these metrics within TensorBoard, refer to the steps listed above in "Displaying model metrics in TensorBoard". EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.templates.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the `0.2.0` version of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarly for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. !pip install tensorflow_federated from __future__ import absolute_import, division, print_function import collections from six.moves import range import numpy as np import tensorflow as tf from tensorflow.python.keras.optimizer_v2 import gradient_descent from tensorflow_federated import python as tff nest = tf.contrib.framework.nest np.random.seed(0) tf.compat.v1.enable_v2_behavior() tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code #@test {"output": "ignore"} emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() #@test {"output": "ignore"} from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code #@test {"output": "ignore"} preprocessed_example_dataset = preprocess(example_dataset) sample_batch = nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code #@test {"output": "ignore"} NUM_CLIENTS = 3 sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) def loss_fn(y_true, y_pred): return tf.reduce_mean(tf.keras.losses.sparse_categorical_crossentropy( y_true, y_pred)) model.compile( loss=loss_fn, optimizer=gradient_descent.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code #@test {"output": "ignore"} iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code #@test {"output": "ignore"} str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hypermarameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.142909,loss=3.14069> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.166909,loss=2.90004> round 3, metrics=<sparse_categorical_accuracy=0.203273,loss=2.64551> round 4, metrics=<sparse_categorical_accuracy=0.248364,loss=2.41201> round 5, metrics=<sparse_categorical_accuracy=0.291636,loss=2.19657> round 6, metrics=<sparse_categorical_accuracy=0.341818,loss=1.99344> round 7, metrics=<sparse_categorical_accuracy=0.397455,loss=1.81096> round 8, metrics=<sparse_categorical_accuracy=0.446182,loss=1.65356> round 9, metrics=<sparse_categorical_accuracy=0.486182,loss=1.51823> round 10, metrics=<sparse_categorical_accuracy=0.533455,loss=1.39974> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.log(y), reduction_indices=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.to_float(tf.size(batch['y'])) tf.assign_add(variables.num_examples, num_examples) tf.assign_add(variables.loss_sum, loss * num_examples) tf.assign_add(variables.accuracy_sum, accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are elligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_average(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_average(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_average` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) # TODO(b/124777499): Remove `autograph=False` when possible. @tf.contrib.eager.function(autograph=False) def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) return tff.learning.BatchOutput(loss=loss, predictions=predictions) @tf.contrib.eager.function(autograph=False) def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` correspond to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.contrib.eager.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): # TODO(b/124777499): Remove `autograph=False` when possible. @tf.contrib.eager.defun(autograph=False) def train_on_batch(self, batch): output = self.forward_pass(batch) optimizer = tf.train.GradientDescentOptimizer(0.02) optimizer.minimize(output.loss, var_list=self.trainable_variables) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<accuracy=0.166909,loss=2.90004,num_examples=2750.0> round 3, metrics=<accuracy=0.203273,loss=2.64551,num_examples=2750.0> round 4, metrics=<accuracy=0.248364,loss=2.41201,num_examples=2750.0> round 5, metrics=<accuracy=0.291636,loss=2.19657,num_examples=2750.0> round 6, metrics=<accuracy=0.341818,loss=1.99344,num_examples=2750.0> round 7, metrics=<accuracy=0.397455,loss=1.81096,num_examples=2750.0> round 8, metrics=<accuracy=0.446182,loss=1.65356,num_examples=2750.0> round 9, metrics=<accuracy=0.486182,loss=1.51823,num_examples=2750.0> round 10, metrics=<accuracy=0.533455,loss=1.39974,num_examples=2750.0> ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code #@test {"output": "ignore"} train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code #@test {"output": "ignore"} str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] #@test {"output": "ignore"} test_metrics = evaluation(state.model, federated_test_data) #@test {"output": "ignore"} str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: The high-performance executor components used in this tutorial are not # yet included in the released pip package; you may need to compile from source. !pip install --quiet --upgrade tensorflow_federated # Uncomment the following in Jupyter if you're seeing `RuntimeError: This event loop is already running`. # !pip install --quiet --upgrade nest_asyncio # import nest_asyncio # nest_asyncio.apply() #@test {"skip": true} %load_ext tensorboard import collections import warnings import numpy as np import tensorflow as tf import tensorflow_federated as tff warnings.simplefilter('ignore') tf.compat.v1.enable_v2_behavior() np.random.seed(0) # NOTE: If the statement below fails, it means that you are # using an older version of TFF without the high-performance # executor stack. Call `tff.framework.set_default_executor()` # instead to use the default reference runtime. tff.framework.set_default_executor(tff.framework.create_local_executor()) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.element_type_structure example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output _____no_output_____ ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code NUM_ROUNDS = 11 for round_num in range(2, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output _____no_output_____ ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Displaying model metrics in TensorBoardNext, let's visualize the metrics from these federated computations using Tensorboard.Let's start by creating the directory and the corresponding summary writer to write the metrics to. ###Code #@test {"skip": true} logdir = "/tmp/logs/scalars/training/" summary_writer = tf.summary.create_file_writer(logdir) state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown Plot the relevant scalar metrics with the same summary writer. ###Code #@test {"skip": true} with summary_writer.as_default(): for round_num in range(1, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) for name, value in metrics._asdict().items(): tf.compat.v2.summary.scalar(name, value, step=round_num) ###Output _____no_output_____ ###Markdown Start TensorBoard with the root log directory specified above. It can take a few seconds for the data to load. ###Code #@test {"skip": true} %tensorboard --logdir /tmp/logs/scalars/ --port=0 #@test {"skip": true} # Run this this cell to clean your directory of old output for future graphs from this directory. !rm -R /tmp/logs/scalars/* ###Output _____no_output_____ ###Markdown In order to view evaluation metrics the same way, you can create a separate eval folder, like "logs/scalars/eval", to write to TensorBoard. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_mean(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): @tf.function def train_on_batch(self, batch): with tf.GradientTape() as tape: output = self.forward_pass(batch) grads = tape.gradient(output.loss, self.trainable_variables) optimizer = tf.keras.optimizers.SGD(0.02) optimizer.apply_gradients( zip(tf.nest.flatten(grads), tf.nest.flatten(self.trainable_variables))) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output _____no_output_____ ###Markdown To see these metrics within TensorBoard, refer to the steps listed above in "Displaying model metrics in TensorBoard". EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} !pip install --quiet --upgrade tensorflow_federated !pip install --quiet --upgrade nest_asyncio import nest_asyncio nest_asyncio.apply() %load_ext tensorboard import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff np.random.seed(0) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.element_type_structure example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = next(iter(example_dataset)) example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid(False) _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 5 BATCH_SIZE = 20 SHUFFLE_BUFFER = 100 PREFETCH_BUFFER=10 def preprocess(dataset): def batch_format_fn(element): """Flatten a batch `pixels` and return the features as an `OrderedDict`.""" return collections.OrderedDict( x=tf.reshape(element['pixels'], [-1, 784]), y=tf.reshape(element['label'], [-1, 1])) return dataset.repeat(NUM_EPOCHS).shuffle(SHUFFLE_BUFFER).batch( BATCH_SIZE).map(batch_format_fn).prefetch(PREFETCH_BUFFER) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure(lambda x: x.numpy(), next(iter(preprocessed_example_dataset))) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [ preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids ] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) print('Number of client datasets: {l}'.format(l=len(federated_train_data))) print('First dataset: {d}'.format(d=federated_train_data[0])) ###Output Number of client datasets: 10 First dataset: <DatasetV1Adapter shapes: OrderedDict([(x, (None, 784)), (y, (None, 1))]), types: OrderedDict([(x, tf.float32), (y, tf.int32)])> ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_keras_model(): return tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(784,)), tf.keras.layers.Dense(10, kernel_initializer='zeros'), tf.keras.layers.Softmax(), ]) ###Output _____no_output_____ ###Markdown **Note:** we do not compile the model yet. The loss, metrics, and optimizers are introduced later.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a Keras model like theone we've just defined above, you can have TFF wrap it for you by invoking`tff.learning.from_keras_model`, passing the model and a sample data batch asarguments, as shown below. ###Code def model_fn(): # We _must_ create a new model here, and _not_ capture it from an external # scope. TFF will call this within different graph contexts. keras_model = create_keras_model() return tff.learning.from_keras_model( keras_model, input_spec=preprocessed_example_dataset.element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)).One critical note on the Federated Averaging algorithm below, there are **2**optimizers: a _client_optimizer_ and a _server_optimizer_. The_client_optimizer_ is only used to compute local model updates on each client.The _server_optimizer_ applies the averaged update to the global model at theserver. In particular, this means that the choice of optimizer and learning rateused may need to be different than the ones you have used to train the model ona standard i.i.d. dataset. We recommend starting with regular SGD, possibly witha smaller learning rate than usual. The learning rate we use has not beencarefully tuned, feel free to experiment. ###Code iterative_process = tff.learning.build_federated_averaging_process( model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02), server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0)) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.templates.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.12037037312984467,loss=3.0108425617218018>> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code NUM_ROUNDS = 11 for round_num in range(2, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.14814814925193787,loss=2.8865506649017334>> round 3, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.148765429854393,loss=2.9079062938690186>> round 4, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.17633745074272156,loss=2.724686622619629>> round 5, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.20226337015628815,loss=2.6334855556488037>> round 6, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.22427983582019806,loss=2.5482592582702637>> round 7, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.24094650149345398,loss=2.4472343921661377>> round 8, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.259876549243927,loss=2.3809611797332764>> round 9, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.29814815521240234,loss=2.156442403793335>> round 10, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.31687241792678833,loss=2.122845411300659>> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Displaying model metrics in TensorBoardNext, let's visualize the metrics from these federated computations using Tensorboard.Let's start by creating the directory and the corresponding summary writer to write the metrics to. ###Code #@test {"skip": true} logdir = "/tmp/logs/scalars/training/" summary_writer = tf.summary.create_file_writer(logdir) state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown Plot the relevant scalar metrics with the same summary writer. ###Code #@test {"skip": true} with summary_writer.as_default(): for round_num in range(1, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) for name, value in metrics.train._asdict().items(): tf.summary.scalar(name, value, step=round_num) ###Output _____no_output_____ ###Markdown Start TensorBoard with the root log directory specified above. It can take a few seconds for the data to load. ###Code #@test {"skip": true} %tensorboard --logdir /tmp/logs/scalars/ --port=0 #@test {"skip": true} # Run this this cell to clean your directory of old output for future graphs from this directory. !rm -R /tmp/logs/scalars/* ###Output _____no_output_____ ###Markdown In order to view evaluation metrics the same way, you can create a separate eval folder, like "logs/scalars/eval", to write to TensorBoard. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples=tf.Variable(0.0, name='num_examples', trainable=False), loss_sum=tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum=tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean( tf.reduce_sum(tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict( num_examples=variables.num_examples, loss=variables.loss_sum / variables.num_examples, accuracy=variables.accuracy_sum / variables.num_examples) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return collections.OrderedDict( num_examples=tff.federated_sum(metrics.num_examples), loss=tff.federated_mean(metrics.loss, metrics.num_examples), accuracy=tff.federated_mean(metrics.accuracy, metrics.num_examples)) ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict( x=tf.TensorSpec([None, 784], tf.float32), y=tf.TensorSpec([None, 1], tf.int32)) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. We will specify a local optimizer when building the Federated Averaging algorithm. Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistModel, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02)) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.975412607192993,accuracy=0.14032921195030212>> round 3, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.9395227432250977,accuracy=0.1594650149345398>> round 4, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.710164785385132,accuracy=0.17139917612075806>> round 5, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.5891618728637695,accuracy=0.20267489552497864>> round 6, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.5148487091064453,accuracy=0.21666666865348816>> round 7, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.2816808223724365,accuracy=0.2580246925354004>> round 8, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.3656885623931885,accuracy=0.25884774327278137>> round 9, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.23549222946167,accuracy=0.28477364778518677>> round 10, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=1.974222183227539,accuracy=0.35329216718673706>> ###Markdown To see these metrics within TensorBoard, refer to the steps listed above in "Displaying model metrics in TensorBoard". EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.templates.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarly for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. !pip install tensorflow_federated from __future__ import absolute_import, division, print_function import collections from six.moves import range import numpy as np import tensorflow as tf from tensorflow.python.keras.optimizer_v2 import gradient_descent from tensorflow_federated import python as tff nest = tf.contrib.framework.nest np.random.seed(0) tf.enable_eager_execution() tf.enable_resource_variables() tf.compat.v1.enable_v2_behavior() tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code #@test {"output": "ignore"} emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() #@test {"output": "ignore"} from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', element['label'])]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle(SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code #@test {"output": "ignore"} preprocessed_example_dataset = preprocess(example_dataset) sample_batch = nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code #@test {"output": "ignore"} NUM_CLIENTS = 3 sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) def loss_fn(y_true, y_pred): return tf.reduce_mean(tf.keras.metrics.sparse_categorical_crossentropy( y_true, y_pred)) model.compile( loss=loss_fn, optimizer=gradient_descent.SGD(learning_rate=0.02), metrics=[]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code #@test {"output": "ignore"} iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code #@test {"output": "ignore"} str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hypermarameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code #@test {"timeout": 600, "output": "ignore"} state, loss = iterative_process.next(state, federated_train_data) print('round 1, loss={:.4f}'.format(loss)) ###Output round 1, loss=3.1903 ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code #@test {"skip": true} for round_num in range(2, 11): state, loss = iterative_process.next(state, federated_train_data) print('round {:2d}, loss={:.4f}'.format(round_num, loss)) ###Output round 2, loss=2.9381 round 3, loss=2.6854 round 4, loss=2.4649 round 5, loss=2.2364 round 6, loss=2.0057 round 7, loss=1.8254 round 8, loss=1.6711 round 9, loss=1.5400 round 10, loss=1.4219 ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(batch['y'], 10) * tf.log(y), reduction_indices=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, batch['y']), tf.float32)) num_examples = tf.to_float(tf.size(batch['y'])) tf.assign_add(variables.num_examples, num_examples) tf.assign_add(variables.loss_sum, loss * num_examples) tf.assign_add(variables.accuracy_sum, accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are elligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_average(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_average(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_average` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None], tf.int32))]) @tf.contrib.eager.function(autograph=False) def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) return tff.learning.BatchOutput(loss=loss, predictions=predictions) @tf.contrib.eager.function(autograph=False) def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` correspond to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.contrib.eager.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): @tf.contrib.eager.defun(autograph=False) def train_on_batch(self, batch): output = self.forward_pass(batch) optimizer = tf.train.GradientDescentOptimizer(0.02) optimizer.minimize(output.loss, var_list=self.trainable_variables) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<accuracy=0.162909,loss=2.93813,num_examples=2750.0> round 3, metrics=<accuracy=0.205455,loss=2.68539,num_examples=2750.0> round 4, metrics=<accuracy=0.240364,loss=2.4649,num_examples=2750.0> round 5, metrics=<accuracy=0.288727,loss=2.23645,num_examples=2750.0> round 6, metrics=<accuracy=0.340364,loss=2.00571,num_examples=2750.0> round 7, metrics=<accuracy=0.401091,loss=1.82538,num_examples=2750.0> round 8, metrics=<accuracy=0.459636,loss=1.67114,num_examples=2750.0> round 9, metrics=<accuracy=0.508,loss=1.53998,num_examples=2750.0> round 10, metrics=<accuracy=0.553091,loss=1.42194,num_examples=2750.0> ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code #@test {"output": "ignore"} train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code #@test {"output": "ignore"} str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] #@test {"output": "ignore"} test_metrics = evaluation(state.model, federated_test_data) #@test {"output": "ignore"} str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the `0.7.0` version of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. # NOTE: The high-performance executor components used in this tutorial are not # yet included in the released pip package; you may need to compile from source. !pip install --quiet tensorflow_federated !pip install --quiet tf-nightly==1.15.0.dev20190805 # NOTE: Jupyter requires a patch to asyncio. !pip install --upgrade nest_asyncio import nest_asyncio nest_asyncio.apply() from __future__ import absolute_import, division, print_function import collections import warnings from six.moves import range import numpy as np import six import tensorflow as tf import tensorflow_federated as tff warnings.simplefilter('ignore') tf.compat.v1.enable_v2_behavior() np.random.seed(0) NUM_CLIENTS = 10 # NOTE: If the statement below fails, it means that you are # using an older version of TFF without the high-performance # executor stack. Call `tff.framework.set_default_executor()` # instead to use the default reference runtime. if six.PY3: tff.framework.set_default_executor( tff.framework.create_local_executor(NUM_CLIENTS)) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output _____no_output_____ ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output _____no_output_____ ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_mean(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) return tff.learning.BatchOutput(loss=loss, predictions=predictions) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): @tf.function def train_on_batch(self, batch): output = self.forward_pass(batch) optimizer = tf.train.GradientDescentOptimizer(0.02) optimizer.minimize(output.loss, var_list=self.trainable_variables) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output _____no_output_____ ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the `v0.1.0` version of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarly for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. !pip install tensorflow_federated from __future__ import absolute_import, division, print_function import collections from six.moves import range import numpy as np import tensorflow as tf from tensorflow.python.keras.optimizer_v2 import gradient_descent from tensorflow_federated import python as tff nest = tf.contrib.framework.nest np.random.seed(0) tf.compat.v1.enable_v2_behavior() tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code #@test {"output": "ignore"} emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() #@test {"output": "ignore"} from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code #@test {"output": "ignore"} preprocessed_example_dataset = preprocess(example_dataset) sample_batch = nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code #@test {"output": "ignore"} NUM_CLIENTS = 3 sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) def loss_fn(y_true, y_pred): return tf.reduce_mean(tf.keras.losses.sparse_categorical_crossentropy( y_true, y_pred)) model.compile( loss=loss_fn, optimizer=gradient_descent.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code #@test {"output": "ignore"} iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code #@test {"output": "ignore"} str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hypermarameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.142909,loss=3.14069> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.166909,loss=2.90004> round 3, metrics=<sparse_categorical_accuracy=0.203273,loss=2.64551> round 4, metrics=<sparse_categorical_accuracy=0.248364,loss=2.41201> round 5, metrics=<sparse_categorical_accuracy=0.291636,loss=2.19657> round 6, metrics=<sparse_categorical_accuracy=0.341818,loss=1.99344> round 7, metrics=<sparse_categorical_accuracy=0.397455,loss=1.81096> round 8, metrics=<sparse_categorical_accuracy=0.446182,loss=1.65356> round 9, metrics=<sparse_categorical_accuracy=0.486182,loss=1.51823> round 10, metrics=<sparse_categorical_accuracy=0.533455,loss=1.39974> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.log(y), reduction_indices=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.to_float(tf.size(batch['y'])) tf.assign_add(variables.num_examples, num_examples) tf.assign_add(variables.loss_sum, loss * num_examples) tf.assign_add(variables.accuracy_sum, accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are elligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_average(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_average(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_average` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) # TODO(b/124777499): Remove `autograph=False` when possible. @tf.contrib.eager.function(autograph=False) def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) return tff.learning.BatchOutput(loss=loss, predictions=predictions) @tf.contrib.eager.function(autograph=False) def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` correspond to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.contrib.eager.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): # TODO(b/124777499): Remove `autograph=False` when possible. @tf.contrib.eager.defun(autograph=False) def train_on_batch(self, batch): output = self.forward_pass(batch) optimizer = tf.train.GradientDescentOptimizer(0.02) optimizer.minimize(output.loss, var_list=self.trainable_variables) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<accuracy=0.166909,loss=2.90004,num_examples=2750.0> round 3, metrics=<accuracy=0.203273,loss=2.64551,num_examples=2750.0> round 4, metrics=<accuracy=0.248364,loss=2.41201,num_examples=2750.0> round 5, metrics=<accuracy=0.291636,loss=2.19657,num_examples=2750.0> round 6, metrics=<accuracy=0.341818,loss=1.99344,num_examples=2750.0> round 7, metrics=<accuracy=0.397455,loss=1.81096,num_examples=2750.0> round 8, metrics=<accuracy=0.446182,loss=1.65356,num_examples=2750.0> round 9, metrics=<accuracy=0.486182,loss=1.51823,num_examples=2750.0> round 10, metrics=<accuracy=0.533455,loss=1.39974,num_examples=2750.0> ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code #@test {"output": "ignore"} train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code #@test {"output": "ignore"} str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] #@test {"output": "ignore"} test_metrics = evaluation(state.model, federated_test_data) #@test {"output": "ignore"} str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} !pip install --quiet --upgrade tensorflow_federated %load_ext tensorboard import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff tf.compat.v1.enable_v2_behavior() np.random.seed(0) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.element_type_structure example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = next(iter(example_dataset)) example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid(False) _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 5 BATCH_SIZE = 20 SHUFFLE_BUFFER = 100 PREFETCH_BUFFER=10 def preprocess(dataset): def batch_format_fn(element): """Flatten a batch `pixels` and return the features as an `OrderedDict`.""" return collections.OrderedDict( x=tf.reshape(element['pixels'], [-1, 784]), y=tf.reshape(element['label'], [-1, 1])) return dataset.repeat(NUM_EPOCHS).shuffle(SHUFFLE_BUFFER).batch( BATCH_SIZE).map(batch_format_fn).prefetch(PREFETCH_BUFFER) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure(lambda x: x.numpy(), next(iter(preprocessed_example_dataset))) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [ preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids ] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) print('Number of client datasets: {l}'.format(l=len(federated_train_data))) print('First dataset: {d}'.format(d=federated_train_data[0])) ###Output Number of client datasets: 10 First dataset: <DatasetV1Adapter shapes: OrderedDict([(x, (None, 784)), (y, (None, 1))]), types: OrderedDict([(x, tf.float32), (y, tf.int32)])> ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_keras_model(): return tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(784,)), tf.keras.layers.Dense(10, kernel_initializer='zeros'), tf.keras.layers.Softmax(), ]) ###Output _____no_output_____ ###Markdown **Note:** we do not compile the model yet. The loss, metrics, and optimizers are introduced later.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a Keras model like theone we've just defined above, you can have TFF wrap it for you by invoking`tff.learning.from_keras_model`, passing the model and a sample data batch asarguments, as shown below. ###Code def model_fn(): # We _must_ create a new model here, and _not_ capture it from an external # scope. TFF will call this within different graph contexts. keras_model = create_keras_model() return tff.learning.from_keras_model( keras_model, input_spec=preprocessed_example_dataset.element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)).One critical note on the Federated Averaging algorithm below, there are **2**optimizers: a _client_optimizer_ and a _server_optimizer_. The_client_optimizer_ is only used to compute local model updates on each client.The _server_optimizer_ applies the averaged update to the global model at theserver. In particular, this means that the choice of optimizer and learning rateused may need to be different than the ones you have used to train the model ona standard i.i.d. dataset. We recommend starting with regular SGD, possibly witha smaller learning rate than usual. The learning rate we use has not beencarefully tuned, feel free to experiment. ###Code iterative_process = tff.learning.build_federated_averaging_process( model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02), server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0)) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.1281892955303192,loss=3.112910270690918,keras_training_time_client_sum_sec=0.0> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code NUM_ROUNDS = 11 for round_num in range(2, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.1366255134344101,loss=3.0699315071105957,keras_training_time_client_sum_sec=0.0> round 3, metrics=<sparse_categorical_accuracy=0.14938271045684814,loss=2.967233657836914,keras_training_time_client_sum_sec=0.0> round 4, metrics=<sparse_categorical_accuracy=0.17860081791877747,loss=2.7275609970092773,keras_training_time_client_sum_sec=0.0> round 5, metrics=<sparse_categorical_accuracy=0.20637859404087067,loss=2.601724863052368,keras_training_time_client_sum_sec=0.0> round 6, metrics=<sparse_categorical_accuracy=0.2100823074579239,loss=2.5941531658172607,keras_training_time_client_sum_sec=0.0> round 7, metrics=<sparse_categorical_accuracy=0.244650200009346,loss=2.3704617023468018,keras_training_time_client_sum_sec=0.0> round 8, metrics=<sparse_categorical_accuracy=0.2720164656639099,loss=2.225743293762207,keras_training_time_client_sum_sec=0.0> round 9, metrics=<sparse_categorical_accuracy=0.28641974925994873,loss=2.2297680377960205,keras_training_time_client_sum_sec=0.0> round 10, metrics=<sparse_categorical_accuracy=0.31975308060646057,loss=2.0716400146484375,keras_training_time_client_sum_sec=0.0> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Displaying model metrics in TensorBoardNext, let's visualize the metrics from these federated computations using Tensorboard.Let's start by creating the directory and the corresponding summary writer to write the metrics to. ###Code #@test {"skip": true} logdir = "/tmp/logs/scalars/training/" summary_writer = tf.summary.create_file_writer(logdir) state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown Plot the relevant scalar metrics with the same summary writer. ###Code #@test {"skip": true} with summary_writer.as_default(): for round_num in range(1, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) for name, value in metrics._asdict().items(): tf.summary.scalar(name, value, step=round_num) ###Output _____no_output_____ ###Markdown Start TensorBoard with the root log directory specified above. It can take a few seconds for the data to load. ###Code #@test {"skip": true} %tensorboard --logdir /tmp/logs/scalars/ --port=0 #@test {"skip": true} # Run this this cell to clean your directory of old output for future graphs from this directory. !rm -R /tmp/logs/scalars/* ###Output _____no_output_____ ###Markdown In order to view evaluation metrics the same way, you can create a separate eval folder, like "logs/scalars/eval", to write to TensorBoard. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples=tf.Variable(0.0, name='num_examples', trainable=False), loss_sum=tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum=tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean( tf.reduce_sum(tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict( num_examples=variables.num_examples, loss=variables.loss_sum / variables.num_examples, accuracy=variables.accuracy_sum / variables.num_examples) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return collections.OrderedDict( num_examples=tff.federated_sum(metrics.num_examples), loss=tff.federated_mean(metrics.loss, metrics.num_examples), accuracy=tff.federated_mean(metrics.accuracy, metrics.num_examples)) ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict( x=tf.TensorSpec([None, 784], tf.float32), y=tf.TensorSpec([None, 1], tf.int32)) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. We will specify a local optimizer when building the Federated Averaging algorithm. Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistModel, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02)) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<num_examples=4860.0,loss=3.0044455528259277,accuracy=0.1366255134344101> round 3, metrics=<num_examples=4860.0,loss=2.8893046379089355,accuracy=0.14753086864948273> round 4, metrics=<num_examples=4860.0,loss=2.742488384246826,accuracy=0.1720164567232132> round 5, metrics=<num_examples=4860.0,loss=2.52746844291687,accuracy=0.20843622088432312> round 6, metrics=<num_examples=4860.0,loss=2.455655574798584,accuracy=0.23127572238445282> round 7, metrics=<num_examples=4860.0,loss=2.369921922683716,accuracy=0.2522633671760559> round 8, metrics=<num_examples=4860.0,loss=2.288294553756714,accuracy=0.27345678210258484> round 9, metrics=<num_examples=4860.0,loss=2.18411922454834,accuracy=0.2890946567058563> round 10, metrics=<num_examples=4860.0,loss=2.048980951309204,accuracy=0.32510289549827576> ###Markdown To see these metrics within TensorBoard, refer to the steps listed above in "Displaying model metrics in TensorBoard". EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the `0.4.0` version of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarly for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} # NOTE: If you are running a Jupyter notebook, and installing a locally built # pip package, you may need to edit the following to point to the '.whl' file # on your local filesystem. !pip install tensorflow_federated from __future__ import absolute_import, division, print_function import collections from six.moves import range import numpy as np import tensorflow as tf from tensorflow_federated import python as tff np.random.seed(0) tf.compat.v1.enable_v2_behavior() tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code #@test {"output": "ignore"} emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.output_types, emnist_train.output_shapes example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = iter(example_dataset).next() example_element['label'].numpy() #@test {"output": "ignore"} from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid('off') _ = plt.show() ###Output _____no_output_____ ###Markdown Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_EPOCHS = 10 BATCH_SIZE = 20 SHUFFLE_BUFFER = 500 def preprocess(dataset): def element_fn(element): return collections.OrderedDict([ ('x', tf.reshape(element['pixels'], [-1])), ('y', tf.reshape(element['label'], [1])), ]) return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle( SHUFFLE_BUFFER).batch(BATCH_SIZE) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code #@test {"output": "ignore"} preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure( lambda x: x.numpy(), iter(preprocessed_example_dataset).next()) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code #@test {"output": "ignore"} NUM_CLIENTS = 3 sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) len(federated_train_data), federated_train_data[0] ###Output _____no_output_____ ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_compiled_keras_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense( 10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,))]) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.02), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return model ###Output _____no_output_____ ###Markdown One critical note on `compile`. When used in the Federated Averaging algorithm,as below, the `optimizer` is only half of of the total optimization algorithm,as it is only used to compute local model updates on each client. The rest ofthe algorithm involves how these updates are averaged over clients, and how theyare then applied to the global model at the server. In particular, this meansthat the choice of optimizer and learning rate used here may need to bedifferent than the ones you have used to train the model on a standard i.i.d.dataset. We recommend starting with regular SGD, possibly with a smallerlearning rate than usual. The learning rate we use here has not been carefullytuned, feel free to experiment.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a compiled Keras modellike the one we've just defined above, you can have TFF wrap it for you byinvoking `tff.learning.from_compiled_keras_model`, passing the model and asample data batch as arguments, as shown below. ###Code def model_fn(): keras_model = create_compiled_keras_model() return tff.learning.from_compiled_keras_model(keras_model, sample_batch) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)). ###Code #@test {"output": "ignore"} iterative_process = tff.learning.build_federated_averaging_process(model_fn) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.utils.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code #@test {"output": "ignore"} str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hypermarameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<sparse_categorical_accuracy=0.142909,loss=3.14069> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<sparse_categorical_accuracy=0.166909,loss=2.90004> round 3, metrics=<sparse_categorical_accuracy=0.203273,loss=2.64551> round 4, metrics=<sparse_categorical_accuracy=0.248364,loss=2.41201> round 5, metrics=<sparse_categorical_accuracy=0.291636,loss=2.19657> round 6, metrics=<sparse_categorical_accuracy=0.341818,loss=1.99344> round 7, metrics=<sparse_categorical_accuracy=0.397455,loss=1.81096> round 8, metrics=<sparse_categorical_accuracy=0.446182,loss=1.65356> round 9, metrics=<sparse_categorical_accuracy=0.486182,loss=1.51823> round 10, metrics=<sparse_categorical_accuracy=0.533455,loss=1.39974> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model` or`tff.learning.from_compiled_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias = tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples = tf.Variable(0.0, name='num_examples', trainable=False), loss_sum = tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum = tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean(tf.reduce_sum( tf.one_hot(flat_labels, 10) * tf.log(y), reduction_indices=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.to_float(tf.size(batch['y'])) tf.assign_add(variables.num_examples, num_examples) tf.assign_add(variables.loss_sum, loss * num_examples) tf.assign_add(variables.accuracy_sum, accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are elligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict([ ('num_examples', variables.num_examples), ('loss', variables.loss_sum / variables.num_examples), ('accuracy', variables.accuracy_sum / variables.num_examples) ]) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return { 'num_examples': tff.federated_sum(metrics.num_examples), 'loss': tff.federated_mean(metrics.loss, metrics.num_examples), 'accuracy': tff.federated_mean(metrics.accuracy, metrics.num_examples) } ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict([('x', tf.TensorSpec([None, 784], tf.float32)), ('y', tf.TensorSpec([None, 1], tf.int32))]) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) return tff.learning.BatchOutput(loss=loss, predictions=predictions) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` correspond to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. ###Code class MnistTrainableModel(MnistModel, tff.learning.TrainableModel): @tf.function def train_on_batch(self, batch): output = self.forward_pass(batch) optimizer = tf.train.GradientDescentOptimizer(0.02) optimizer.minimize(output.loss, var_list=self.trainable_variables) return output ###Output _____no_output_____ ###Markdown Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistTrainableModel) state = iterative_process.initialize() #@test {"timeout": 600, "output": "ignore"} state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) #@test {"skip": true} for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<accuracy=0.166909,loss=2.90004,num_examples=2750.0> round 3, metrics=<accuracy=0.203273,loss=2.64551,num_examples=2750.0> round 4, metrics=<accuracy=0.248364,loss=2.41201,num_examples=2750.0> round 5, metrics=<accuracy=0.291636,loss=2.19657,num_examples=2750.0> round 6, metrics=<accuracy=0.341818,loss=1.99344,num_examples=2750.0> round 7, metrics=<accuracy=0.397455,loss=1.81096,num_examples=2750.0> round 8, metrics=<accuracy=0.446182,loss=1.65356,num_examples=2750.0> round 9, metrics=<accuracy=0.486182,loss=1.51823,num_examples=2750.0> round 10, metrics=<accuracy=0.533455,loss=1.39974,num_examples=2750.0> ###Markdown EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.utils.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code #@test {"output": "ignore"} train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code #@test {"output": "ignore"} str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] #@test {"output": "ignore"} test_metrics = evaluation(state.model, federated_test_data) #@test {"output": "ignore"} str(test_metrics) ###Output _____no_output_____ ###Markdown Copyright 2019 The TensorFlow Authors. ###Code #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ###Output _____no_output_____ ###Markdown Federated Learning for Image Classification View on TensorFlow.org Run in Google Colab View source on GitHub **NOTE**: This colab has been verified to work with the [latest released version](https://github.com/tensorflow/federatedcompatibility) of the `tensorflow_federated` pip package, but the Tensorflow Federated project is still in pre-release development and may not work on `master`.In this tutorial, we use the classic MNIST training example to introduce theFederated Learning (FL) API layer of TFF, `tff.learning` - a set ofhigher-level interfaces that can be used to perform common types of federatedlearning tasks, such as federated training, against user-supplied modelsimplemented in TensorFlow.This tutorial, and the Federated Learning API, are intended primarily for userswho want to plug their own TensorFlow models into TFF, treating the lattermostly as a black box. For a more in-depth understanding of TFF and how toimplement your own federated learning algorithms, see the tutorials on the FC Core API - [Custom Federated Algorithms Part 1](custom_federated_algorithms_1.ipynb) and [Part 2](custom_federated_algorithms_2.ipynb).For more on `tff.learning`, continue with the[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb),tutorial which in addition to covering recurrent models, also demonstrates loading apre-trained serialized Keras model for refinement with federated learningcombined with evaluation using Keras. Before we startBefore we start, please run the following to make sure that your environment iscorrectly setup. If you don't see a greeting, please refer to the[Installation](../install.md) guide for instructions. ###Code #@test {"skip": true} !pip install --quiet --upgrade tensorflow_federated_nightly !pip install --quiet --upgrade nest_asyncio import nest_asyncio nest_asyncio.apply() %load_ext tensorboard import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff np.random.seed(0) tff.federated_computation(lambda: 'Hello, World!')() ###Output _____no_output_____ ###Markdown Preparing the input dataLet's start with the data. Federated learning requires a federated data set,i.e., a collection of data from multiple users. Federated data is typicallynon-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables),which poses a unique set of challenges.In order to facilitate experimentation, we seeded the TFF repository with a fewdatasets, including a federated version of MNIST that contains a version of the [original NIST dataset](https://www.nist.gov/srd/nist-special-database-19) that has been re-processed using [Leaf](https://github.com/TalwalkarLab/leaf) so that the data is keyed by the original writer of the digits. Since each writer has a unique style, this dataset exhibits the kind of non-i.i.d. behavior expected of federated datasets.Here's how we can load it. ###Code emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() ###Output _____no_output_____ ###Markdown The data sets returned by `load_data()` are instances of`tff.simulation.ClientData`, an interface that allows you to enumerate the setof users, to construct a `tf.data.Dataset` that represents the data of aparticular user, and to query the structure of individual elements. Here's howyou can use this interface to explore the content of the data set. Keep in mindthat while this interface allows you to iterate over clients ids, this is only afeature of the simulation data. As you will see shortly, client identities arenot used by the federated learning framework - their only purpose is to allowyou to select subsets of the data for simulations. ###Code len(emnist_train.client_ids) emnist_train.element_type_structure example_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) example_element = next(iter(example_dataset)) example_element['label'].numpy() from matplotlib import pyplot as plt plt.imshow(example_element['pixels'].numpy(), cmap='gray', aspect='equal') plt.grid(False) _ = plt.show() ###Output _____no_output_____ ###Markdown Exploring heterogeneity in federated dataFederated data is typically non-[i.i.d.](https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables), users typically have different distributions of data depending on usage patterns. Some clients may have fewer training examples on device, suffering from data paucity locally, while some clients will have more than enough training examples. Let's explore this concept of data heterogeneity typical of a federated system with the EMNIST data we have available. It's important to note that this deep analysis of a client's data is only available to us because this is a simulation environment where all the data is available to us locally. In a real production federated environment you would not be able to inspect a single client's data. First, let's grab a sampling of one client's data to get a feel for the examples on one simulated device. Because the dataset we're using has been keyed by unique writer, the data of one client represents the handwriting of one person for a sample of the digits 0 through 9, simulating the unique "usage pattern" of one user. ###Code ## Example MNIST digits for one client figure = plt.figure(figsize=(20, 4)) j = 0 for example in example_dataset.take(40): plt.subplot(4, 10, j+1) plt.imshow(example['pixels'].numpy(), cmap='gray', aspect='equal') plt.axis('off') j += 1 ###Output _____no_output_____ ###Markdown Now let's visualize the number of examples on each client for each MNIST digit label. In the federated environment, the number of examples on each client can vary quite a bit, depending on user behavior. ###Code # Number of examples per layer for a sample of clients f = plt.figure(figsize=(12, 7)) f.suptitle('Label Counts for a Sample of Clients') for i in range(6): client_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[i]) plot_data = collections.defaultdict(list) for example in client_dataset: # Append counts individually per label to make plots # more colorful instead of one color per plot. label = example['label'].numpy() plot_data[label].append(label) plt.subplot(2, 3, i+1) plt.title('Client {}'.format(i)) for j in range(10): plt.hist( plot_data[j], density=False, bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ###Output _____no_output_____ ###Markdown Now let's visualize the mean image per client for each MNIST label. This code will produce the mean of each pixel value for all of the user's examples for one label. We'll see that one client's mean image for a digit will look different than another client's mean image for the same digit, due to each person's unique handwriting style. We can muse about how each local training round will nudge the model in a different direction on each client, as we're learning from that user's own unique data in that local round. Later in the tutorial we'll see how we can take each update to the model from all the clients and aggregate them together into our new global model, that has learned from each of our client's own unique data. ###Code # Each client has different mean images, meaning each client will be nudging # the model in their own directions locally. for i in range(5): client_dataset = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[i]) plot_data = collections.defaultdict(list) for example in client_dataset: plot_data[example['label'].numpy()].append(example['pixels'].numpy()) f = plt.figure(i, figsize=(12, 5)) f.suptitle("Client #{}'s Mean Image Per Label".format(i)) for j in range(10): mean_img = np.mean(plot_data[j], 0) plt.subplot(2, 5, j+1) plt.imshow(mean_img.reshape((28, 28))) plt.axis('off') ###Output _____no_output_____ ###Markdown User data can be noisy and unreliably labeled. For example, looking at Client 2's data above, we can see that for label 2, it is possible that there may have been some mislabeled examples creating a noisier mean image. Preprocessing the input data Since the data is already a `tf.data.Dataset`, preprocessing can be accomplished using Dataset transformations. Here, we flatten the `28x28` imagesinto `784`-element arrays, shuffle the individual examples, organize them into batches, and renames the featuresfrom `pixels` and `label` to `x` and `y` for use with Keras. We also throw in a`repeat` over the data set to run several epochs. ###Code NUM_CLIENTS = 10 NUM_EPOCHS = 5 BATCH_SIZE = 20 SHUFFLE_BUFFER = 100 PREFETCH_BUFFER= 10 def preprocess(dataset): def batch_format_fn(element): """Flatten a batch `pixels` and return the features as an `OrderedDict`.""" return collections.OrderedDict( x=tf.reshape(element['pixels'], [-1, 784]), y=tf.reshape(element['label'], [-1, 1])) return dataset.repeat(NUM_EPOCHS).shuffle(SHUFFLE_BUFFER).batch( BATCH_SIZE).map(batch_format_fn).prefetch(PREFETCH_BUFFER) ###Output _____no_output_____ ###Markdown Let's verify this worked. ###Code preprocessed_example_dataset = preprocess(example_dataset) sample_batch = tf.nest.map_structure(lambda x: x.numpy(), next(iter(preprocessed_example_dataset))) sample_batch ###Output _____no_output_____ ###Markdown We have almost all the building blocks in place to construct federated datasets.One of the ways to feed federated data to TFF in a simulation is simply as aPython list, with each element of the list holding the data of an individualuser, whether as a list or as a `tf.data.Dataset`. Since we already havean interface that provides the latter, let's use it.Here's a simple helper function that will construct a list of datasets from thegiven set of users as an input to a round of training or evaluation. ###Code def make_federated_data(client_data, client_ids): return [ preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids ] ###Output _____no_output_____ ###Markdown Now, how do we choose clients?In a typical federated training scenario, we are dealing with potentially a verylarge population of user devices, only a fraction of which may be available fortraining at a given point in time. This is the case, for example, when theclient devices are mobile phones that participate in training only when pluggedinto a power source, off a metered network, and otherwise idle.Of course, we are in a simulation environment, and all the data is locallyavailable. Typically then, when running simulations, we would simply sample arandom subset of the clients to be involved in each round of training, generallydifferent in each round.That said, as you can find out by studying the paper on the[Federated Averaging](https://arxiv.org/abs/1602.05629) algorithm, achieving convergence in a system with randomly sampledsubsets of clients in each round can take a while, and it would be impracticalto have to run hundreds of rounds in this interactive tutorial.What we'll do instead is sample the set of clients once, andreuse the same set across rounds to speed up convergence (intentionallyover-fitting to these few user's data). We leave it as an exercise for thereader to modify this tutorial to simulate random sampling - it is fairly easy todo (once you do, keep in mind that getting the model to converge may take awhile). ###Code sample_clients = emnist_train.client_ids[0:NUM_CLIENTS] federated_train_data = make_federated_data(emnist_train, sample_clients) print('Number of client datasets: {l}'.format(l=len(federated_train_data))) print('First dataset: {d}'.format(d=federated_train_data[0])) ###Output Number of client datasets: 10 First dataset: <DatasetV1Adapter shapes: OrderedDict([(x, (None, 784)), (y, (None, 1))]), types: OrderedDict([(x, tf.float32), (y, tf.int32)])> ###Markdown Creating a model with KerasIf you are using Keras, you likely already have code that constructs a Kerasmodel. Here's an example of a simple model that will suffice for our needs. ###Code def create_keras_model(): return tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(784,)), tf.keras.layers.Dense(10, kernel_initializer='zeros'), tf.keras.layers.Softmax(), ]) ###Output _____no_output_____ ###Markdown **Note:** we do not compile the model yet. The loss, metrics, and optimizers are introduced later.In order to use any model with TFF, it needs to be wrapped in an instance of the`tff.learning.Model` interface, which exposes methods to stamp the model'sforward pass, metadata properties, etc., similarly to Keras, but also introducesadditional elements, such as ways to control the process of computing federatedmetrics. Let's not worry about this for now; if you have a Keras model like theone we've just defined above, you can have TFF wrap it for you by invoking`tff.learning.from_keras_model`, passing the model and a sample data batch asarguments, as shown below. ###Code def model_fn(): # We _must_ create a new model here, and _not_ capture it from an external # scope. TFF will call this within different graph contexts. keras_model = create_keras_model() return tff.learning.from_keras_model( keras_model, input_spec=preprocessed_example_dataset.element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) ###Output _____no_output_____ ###Markdown Training the model on federated dataNow that we have a model wrapped as `tff.learning.Model` for use with TFF, wecan let TFF construct a Federated Averaging algorithm by invoking the helperfunction `tff.learning.build_federated_averaging_process`, as follows.Keep in mind that the argument needs to be a constructor (such as `model_fn`above), not an already-constructed instance, so that the construction of yourmodel can happen in a context controlled by TFF (if you're curious about thereasons for this, we encourage you to read the follow-up tutorial on[custom algorithms](custom_federated_algorithms_1.ipynb)).One critical note on the Federated Averaging algorithm below, there are **2**optimizers: a _client_optimizer_ and a _server_optimizer_. The_client_optimizer_ is only used to compute local model updates on each client.The _server_optimizer_ applies the averaged update to the global model at theserver. In particular, this means that the choice of optimizer and learning rateused may need to be different than the ones you have used to train the model ona standard i.i.d. dataset. We recommend starting with regular SGD, possibly witha smaller learning rate than usual. The learning rate we use has not beencarefully tuned, feel free to experiment. ###Code iterative_process = tff.learning.build_federated_averaging_process( model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02), server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0)) ###Output _____no_output_____ ###Markdown What just happened? TFF has constructed a pair of *federated computations* andpackaged them into a `tff.templates.IterativeProcess` in which these computationsare available as a pair of properties `initialize` and `next`.In a nutshell, *federated computations* are programs in TFF's internal languagethat can express various federated algorithms (you can find more about this inthe [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial). In thiscase, the two computations generated and packed into `iterative_process`implement [Federated Averaging](https://arxiv.org/abs/1602.05629).It is a goal of TFF to define computations in a way that they could be executedin real federated learning settings, but currently only local executionsimulation runtime is implemented. To execute a computation in a simulator, yousimply invoke it like a Python function. This default interpreted environment isnot designed for high performance, but it will suffice for this tutorial; weexpect to provide higher-performance simulation runtimes to facilitatelarger-scale research in future releases.Let's start with the `initialize` computation. As is the case for all federatedcomputations, you can think of it as a function. The computation takes noarguments, and returns one result - the representation of the state of theFederated Averaging process on the server. While we don't want to dive into thedetails of TFF, it may be instructive to see what this state looks like. You canvisualize it as follows. ###Code str(iterative_process.initialize.type_signature) ###Output _____no_output_____ ###Markdown While the above type signature may at first seem a bit cryptic, you canrecognize that the server state consists of a `model` (the initial modelparameters for MNIST that will be distributed to all devices), and`optimizer_state` (additional information maintained by the server, such as thenumber of rounds to use for hyperparameter schedules, etc.).Let's invoke the `initialize` computation to construct the server state. ###Code state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown The second of the pair of federated computations, `next`, represents a singleround of Federated Averaging, which consists of pushing the server state(including the model parameters) to the clients, on-device training on theirlocal data, collecting and averaging model updates, and producing a new updatedmodel at the server.Conceptually, you can think of `next` as having a functional type signature thatlooks as follows.```SERVER_STATE, FEDERATED_DATA -> SERVER_STATE, TRAINING_METRICS```In particular, one should think about `next()` not as being a function that runs on a server, but rather being a declarative functional representation of the entire decentralized computation - some of the inputs are provided by the server (`SERVER_STATE`), but each participating device contributes its own local dataset.Let's run a single round of training and visualize the results. We can use thefederated data we've already generated above for a sample of users. ###Code state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) ###Output round 1, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.12037037312984467,loss=3.0108425617218018>> ###Markdown Let's run a few more rounds. As noted earlier, typically at this point you wouldpick a subset of your simulation data from a new randomly selected sample ofusers for each round in order to simulate a realistic deployment in which userscontinuously come and go, but in this interactive notebook, for the sake ofdemonstration we'll just reuse the same users, so that the system convergesquickly. ###Code NUM_ROUNDS = 11 for round_num in range(2, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.14814814925193787,loss=2.8865506649017334>> round 3, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.148765429854393,loss=2.9079062938690186>> round 4, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.17633745074272156,loss=2.724686622619629>> round 5, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.20226337015628815,loss=2.6334855556488037>> round 6, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.22427983582019806,loss=2.5482592582702637>> round 7, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.24094650149345398,loss=2.4472343921661377>> round 8, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.259876549243927,loss=2.3809611797332764>> round 9, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.29814815521240234,loss=2.156442403793335>> round 10, metrics=<broadcast=<>,aggregation=<>,train=<sparse_categorical_accuracy=0.31687241792678833,loss=2.122845411300659>> ###Markdown Training loss is decreasing after each round of federated training, indicatingthe model is converging. There are some important caveats with these trainingmetrics, however, see the section on *Evaluation* later in this tutorial. Displaying model metrics in TensorBoardNext, let's visualize the metrics from these federated computations using Tensorboard.Let's start by creating the directory and the corresponding summary writer to write the metrics to. ###Code #@test {"skip": true} logdir = "/tmp/logs/scalars/training/" summary_writer = tf.summary.create_file_writer(logdir) state = iterative_process.initialize() ###Output _____no_output_____ ###Markdown Plot the relevant scalar metrics with the same summary writer. ###Code #@test {"skip": true} with summary_writer.as_default(): for round_num in range(1, NUM_ROUNDS): state, metrics = iterative_process.next(state, federated_train_data) for name, value in metrics.train._asdict().items(): tf.summary.scalar(name, value, step=round_num) ###Output _____no_output_____ ###Markdown Start TensorBoard with the root log directory specified above. It can take a few seconds for the data to load. ###Code #@test {"skip": true} %tensorboard --logdir /tmp/logs/scalars/ --port=0 #@test {"skip": true} # Run this this cell to clean your directory of old output for future graphs from this directory. !rm -R /tmp/logs/scalars/* ###Output _____no_output_____ ###Markdown In order to view evaluation metrics the same way, you can create a separate eval folder, like "logs/scalars/eval", to write to TensorBoard. Customizing the model implementationKeras is the [recommended high-level model API for TensorFlow](https://medium.com/tensorflow/standardizing-on-keras-guidance-on-high-level-apis-in-tensorflow-2-0-bad2b04c819a), and we encourage using Keras models (via `tff.learning.from_keras_model`) in TFF whenever possible.However, `tff.learning` provides a lower-level model interface, `tff.learning.Model`, that exposes the minimal functionality necessary for using a model for federated learning. Directly implementing this interface (possibly still using building blocks like `tf.keras.layers`) allows for maximum customization without modifying the internals of the federated learning algorithms.So let's do it all over again from scratch. Defining model variables, forward pass, and metricsThe first step is to identify the TensorFlow variables we're going to work with.In order to make the following code more legible, let's define a data structureto represent the entire set. This will include variables such as `weights` and`bias` that we will train, as well as variables that will hold variouscumulative statistics and counters we will update during training, such as`loss_sum`, `accuracy_sum`, and `num_examples`. ###Code MnistVariables = collections.namedtuple( 'MnistVariables', 'weights bias num_examples loss_sum accuracy_sum') ###Output _____no_output_____ ###Markdown Here's a method that creates the variables. For the sake of simplicity, werepresent all statistics as `tf.float32`, as that will eliminate the need fortype conversions at a later stage. Wrapping variable initializers as lambdas isa requirement imposed by[resource variables](https://www.tensorflow.org/api_docs/python/tf/enable_resource_variables). ###Code def create_mnist_variables(): return MnistVariables( weights=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(784, 10)), name='weights', trainable=True), bias=tf.Variable( lambda: tf.zeros(dtype=tf.float32, shape=(10)), name='bias', trainable=True), num_examples=tf.Variable(0.0, name='num_examples', trainable=False), loss_sum=tf.Variable(0.0, name='loss_sum', trainable=False), accuracy_sum=tf.Variable(0.0, name='accuracy_sum', trainable=False)) ###Output _____no_output_____ ###Markdown With the variables for model parameters and cumulative statistics in place, wecan now define the forward pass method that computes loss, emits predictions,and updates the cumulative statistics for a single batch of input data, asfollows. ###Code def mnist_forward_pass(variables, batch): y = tf.nn.softmax(tf.matmul(batch['x'], variables.weights) + variables.bias) predictions = tf.cast(tf.argmax(y, 1), tf.int32) flat_labels = tf.reshape(batch['y'], [-1]) loss = -tf.reduce_mean( tf.reduce_sum(tf.one_hot(flat_labels, 10) * tf.math.log(y), axis=[1])) accuracy = tf.reduce_mean( tf.cast(tf.equal(predictions, flat_labels), tf.float32)) num_examples = tf.cast(tf.size(batch['y']), tf.float32) variables.num_examples.assign_add(num_examples) variables.loss_sum.assign_add(loss * num_examples) variables.accuracy_sum.assign_add(accuracy * num_examples) return loss, predictions ###Output _____no_output_____ ###Markdown Next, we define a function that returns a set of local metrics, again using TensorFlow. These are the values (in addition to model updates, which are handled automatically) that are eligible to be aggregated to the server in a federated learning or evaluation process.Here, we simply return the average `loss` and `accuracy`, as well as the`num_examples`, which we'll need to correctly weight the contributions fromdifferent users when computing federated aggregates. ###Code def get_local_mnist_metrics(variables): return collections.OrderedDict( num_examples=variables.num_examples, loss=variables.loss_sum / variables.num_examples, accuracy=variables.accuracy_sum / variables.num_examples) ###Output _____no_output_____ ###Markdown Finally, we need to determine how to aggregate the local metrics emitted by eachdevice via `get_local_mnist_metrics`. This is the only part of the code that isn't written in TensorFlow - it's a *federated computation* expressed in TFF. If you'd like todig deeper, skim over the [custom algorithms](custom_federated_algorithms_1.ipynb)tutorial, but in most applications, you won't really need to; variants of thepattern shown below should suffice. Here's what it looks like: ###Code @tff.federated_computation def aggregate_mnist_metrics_across_clients(metrics): return collections.OrderedDict( num_examples=tff.federated_sum(metrics.num_examples), loss=tff.federated_mean(metrics.loss, metrics.num_examples), accuracy=tff.federated_mean(metrics.accuracy, metrics.num_examples)) ###Output _____no_output_____ ###Markdown The input `metrics` argument corresponds to the `OrderedDict` returned by `get_local_mnist_metrics` above, but critically the values are no longer `tf.Tensors` - they are "boxed" as `tff.Value`s, to make it clear you can no longer manipulate them using TensorFlow, but only using TFF's federated operators like `tff.federated_mean` and `tff.federated_sum`. The returneddictionary of global aggregates defines the set of metrics which will be available on the server. Constructing an instance of `tff.learning.Model`With all of the above in place, we are ready to construct a model representationfor use with TFF similar to one that's generated for you when you let TFF ingesta Keras model. ###Code class MnistModel(tff.learning.Model): def __init__(self): self._variables = create_mnist_variables() @property def trainable_variables(self): return [self._variables.weights, self._variables.bias] @property def non_trainable_variables(self): return [] @property def local_variables(self): return [ self._variables.num_examples, self._variables.loss_sum, self._variables.accuracy_sum ] @property def input_spec(self): return collections.OrderedDict( x=tf.TensorSpec([None, 784], tf.float32), y=tf.TensorSpec([None, 1], tf.int32)) @tf.function def forward_pass(self, batch, training=True): del training loss, predictions = mnist_forward_pass(self._variables, batch) num_exmaples = tf.shape(batch['x'])[0] return tff.learning.BatchOutput( loss=loss, predictions=predictions, num_examples=num_exmaples) @tf.function def report_local_outputs(self): return get_local_mnist_metrics(self._variables) @property def federated_output_computation(self): return aggregate_mnist_metrics_across_clients ###Output _____no_output_____ ###Markdown As you can see, the abstract methods and properties defined by`tff.learning.Model` corresponds to the code snippets in the preceding sectionthat introduced the variables and defined the loss and statistics.Here are a few points worth highlighting:* All state that your model will use must be captured as TensorFlow variables, as TFF does not use Python at runtime (remember your code should be written such that it can be deployed to mobile devices; see the [custom algorithms](custom_federated_algorithms_1.ipynb) tutorial for a more in-depth commentary on the reasons).* Your model should describe what form of data it accepts (`input_spec`), as in general, TFF is a strongly-typed environment and wants to determine type signatures for all components. Declaring the format of your model's input is an essential part of it.* Although technically not required, we recommend wrapping all TensorFlow logic (forward pass, metric calculations, etc.) as `tf.function`s, as this helps ensure the TensorFlow can be serialized, and removes the need for explicit control dependencies. The above is sufficient for evaluation and algorithms like Federated SGD.However, for Federated Averaging, we need to specify how the model should trainlocally on each batch. We will specify a local optimizer when building the Federated Averaging algorithm. Simulating federated training with the new modelWith all the above in place, the remainder of the process looks like what we'veseen already - just replace the model constructor with the constructor of ournew model class, and use the two federated computations in the iterative processyou created to cycle through training rounds. ###Code iterative_process = tff.learning.build_federated_averaging_process( MnistModel, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02)) state = iterative_process.initialize() state, metrics = iterative_process.next(state, federated_train_data) print('round 1, metrics={}'.format(metrics)) for round_num in range(2, 11): state, metrics = iterative_process.next(state, federated_train_data) print('round {:2d}, metrics={}'.format(round_num, metrics)) ###Output round 2, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.975412607192993,accuracy=0.14032921195030212>> round 3, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.9395227432250977,accuracy=0.1594650149345398>> round 4, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.710164785385132,accuracy=0.17139917612075806>> round 5, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.5891618728637695,accuracy=0.20267489552497864>> round 6, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.5148487091064453,accuracy=0.21666666865348816>> round 7, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.2816808223724365,accuracy=0.2580246925354004>> round 8, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.3656885623931885,accuracy=0.25884774327278137>> round 9, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=2.23549222946167,accuracy=0.28477364778518677>> round 10, metrics=<broadcast=<>,aggregation=<>,train=<num_examples=4860.0,loss=1.974222183227539,accuracy=0.35329216718673706>> ###Markdown To see these metrics within TensorBoard, refer to the steps listed above in "Displaying model metrics in TensorBoard". EvaluationAll of our experiments so far presented only federated training metrics - theaverage metrics over all batches of data trained across all clients in theround. This introduces the normal concerns about overfitting, especially sincewe used the same set of clients on each round for simplicity, but there is anadditional notion of overfitting in training metrics specific to the FederatedAveraging algorithm. This is easiest to see if we imagine each client had asingle batch of data, and we train on that batch for many iterations (epochs).In this case, the local model will quickly exactly fit to that one batch, and sothe local accuracy metric we average will approach 1.0. Thus, these trainingmetrics can be taken as a sign that training is progressing, but not much more.To perform evaluation on federated data, you can construct another *federatedcomputation* designed for just this purpose, using the`tff.learning.build_federated_evaluation` function, and passing in your modelconstructor as an argument. Note that unlike with Federated Averaging, wherewe've used `MnistTrainableModel`, it suffices to pass the `MnistModel`.Evaluation doesn't perform gradient descent, and there's no need to constructoptimizers.For experimentation and research, when a centralized test dataset is available,[Federated Learning for Text Generation](federated_learning_for_text_generation.ipynb)demonstrates another evaluation option: taking the trained weights fromfederated learning, applying them to a standard Keras model, and then simplycalling `tf.keras.models.Model.evaluate()` on a centralized dataset. ###Code evaluation = tff.learning.build_federated_evaluation(MnistModel) ###Output _____no_output_____ ###Markdown You can inspect the abstract type signature of the evaluation function as follows. ###Code str(evaluation.type_signature) ###Output _____no_output_____ ###Markdown No need to be concerned about the details at this point, just be aware that ittakes the following general form, similar to `tff.templates.IterativeProcess.next`but with two important differences. First, we are not returning server state,since evaluation doesn't modify the model or any other aspect of state - you canthink of it as stateless. Second, evaluation only needs the model, and doesn'trequire any other part of server state that might be associated with training,such as optimizer variables.```SERVER_MODEL, FEDERATED_DATA -> TRAINING_METRICS```Let's invoke evaluation on the latest state we arrived at during training. Inorder to extract the latest trained model from the server state, you simplyaccess the `.model` member, as follows. ###Code train_metrics = evaluation(state.model, federated_train_data) ###Output _____no_output_____ ###Markdown Here's what we get. Note the numbers look marginally better than what wasreported by the last round of training above. By convention, the trainingmetrics reported by the iterative training process generally reflect theperformance of the model at the beginning of the training round, so theevaluation metrics will always be one step ahead. ###Code str(train_metrics) ###Output _____no_output_____ ###Markdown Now, let's compile a test sample of federated data and rerun evaluation on thetest data. The data will come from the same sample of real users, but from adistinct held-out data set. ###Code federated_test_data = make_federated_data(emnist_test, sample_clients) len(federated_test_data), federated_test_data[0] test_metrics = evaluation(state.model, federated_test_data) str(test_metrics) ###Output _____no_output_____