move python code snippets to python folder

This commit is contained in:
2019-06-22 22:50:39 +10:00
parent b76f2e25bd
commit 2c8848211b
13 changed files with 0 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
sns.set()
births = pd.read_csv("data/births.csv")
births["decade"] = 10 * (births["year"] // 10)
births.pivot_table("births", index="year", columns="gender", aggfunc="sum").plot()
plt.ylabel("total births per year")
plt.show(block=True)
+17
View File
@@ -0,0 +1,17 @@
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn
import time
seaborn.set()
rainfall = pd.read_csv(
"https://raw.githubusercontent.com/jakevdp/PythonDataScienceHandbook/master/notebooks/data/Seattle2014.csv"
)["TMAX"].values
print(rainfall)
# inches = rainfall / 254.0 # 1/10mm -> inches
rainfall.shape
plt.hist(rainfall, 40)
plt.show(block=True)
+27
View File
@@ -0,0 +1,27 @@
# name = "John"
# print("Hello, %s \n !" % name, "555")
# a = 1.2345
# print("%.2f" % a)
# b = 1245
# print("%x/%X" % (b, b))
# data = ["John", "Doe", 53.44]
# print(data[2])
# # reverse a string
# astring = "Hello world!"
# print(astring[::-1])
# m = True
# if m != True:
# print("hahah")
# else:
# print("wooooo")
for i in range(10):
print(i)
+16
View File
@@ -0,0 +1,16 @@
import numpy as np
import matplotlib.pyplot as plt
# data = np.random.randn(1000)
# plt.hist(data, bins=50)
# plt.show()
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
# plt.hist2d(x, y, bins=30, cmap="Blues")
plt.hexbin(x, y, gridsize=30, cmap="Oranges")
cb = plt.colorbar()
cb.set_label("counts in bin")
plt.show()
+52
View File
@@ -0,0 +1,52 @@
import tensorflow as tf
import numpy as np
print(tf.__version__)
from tensorflow.contrib.learn.python.learn.datasets import base
# Data files
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"
# Load datasets.
training_set = base.load_csv_with_header(filename=IRIS_TRAINING,
features_dtype=np.float32,
target_dtype=np.int)
test_set = base.load_csv_with_header(filename=IRIS_TEST,
features_dtype=np.float32,
target_dtype=np.int)
# Specify that all features have real-value data
feature_name = "flower_features"
feature_columns = [tf.feature_column.numeric_column(feature_name,
shape=[4])]
classifier = tf.estimator.LinearClassifier(
feature_columns=feature_columns,
n_classes=3,
model_dir="/tmp/iris_model")
def input_fn(dataset):
def _fn():
features = {feature_name: tf.constant(dataset.data)}
label = tf.constant(dataset.target)
return features, label
return _fn
# Fit model.
classifier.train(input_fn=input_fn(training_set),
steps=1000)
print('fit done')
# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=input_fn(test_set),
steps=100)["accuracy"]
print('\nAccuracy: {0:f}'.format(accuracy_score))
# Export the model for serving
feature_spec = {'flower_features': tf.FixedLenFeature(shape=[4], dtype=np.float32)}
serving_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)
classifier.export_savedmodel(export_dir_base='/tmp/iris_model' + '/export',
serving_input_receiver_fn=serving_fn)
+23
View File
@@ -0,0 +1,23 @@
# Create 2 new lists height and weight
import numpy as np
height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
# Import the numpy package as np
# Create 2 numpy arrays from height and weight
np_height = np.array(height)
np_weight = np.array(weight)
print(type(np_height))
# Calculate bmi
bmi = np_weight / np_height ** 2
# Print the result
print(bmi)
# For a boolean response
# bmi > 23
# Print only those observations above 23
print(bmi[bmi > 25])
+11
View File
@@ -0,0 +1,11 @@
import pandas as pd
dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
"capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
"area": [8.516, 17.10, 3.286, 9.597, 1.221],
"population": [200.4, 143.5, 1252, 1357, 52.98]}
brics = pd.DataFrame(dict)
print(brics)
brics.index = ["BR", "RU", "IN", "CH", "SA"]
print(brics)
+20
View File
@@ -0,0 +1,20 @@
import numpy as np
import matplotlib as matl
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import Image
plt.style.use("seaborn-whitegrid")
x = np.linspace(0, 10, 100)
figure = plt.figure()
ax = plt.axes()
plt.plot(x, np.sin(x), "-", label="sin(x)")
plt.plot(x, np.cos(x), "o", label="cos(x)")
plt.legend()
plt.show(block=True)
+14
View File
@@ -0,0 +1,14 @@
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.RandomState(0)
for marker in ["o", ".", ",", "x", "+", "v", "^", "<", ">", "s", "d"]:
plt.plot(rng.rand(5), rng.rand(5), marker, label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 2)
plt.show()
+13
View File
@@ -0,0 +1,13 @@
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap="viridis")
plt.colorbar() # show color scale
plt.show()
+11
View File
@@ -0,0 +1,11 @@
from adafruit_servokit import ServoKit
kit = ServoKit(channels=16)
print("hello starting")
kit.servo[0].actuation_range = 160
# angle can be 0 - 180
kit.servo[0].angle = 180
kit.servo[0].angle = 0
kit.continuous_servo[0].throttle = 1
+24
View File
@@ -0,0 +1,24 @@
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
x = np.linspace(0, 10, 100)
figure = plt.figure()
ax = plt.axes()
sub1 = plt.subplot(2, 2, 1)
sub1.plot(x, np.sin(x), "-", label="sin(x)")
sub1.legend()
sub2 = plt.subplot(2, 2, 2)
sub2 = plt.plot(x, np.cos(x), "o", label="cos(x)")
sub2 = plt.legend()
plt.subplot(2, 2, 3)
plt.plot(x, np.tan(x), "-", label="tan(x)")
plt.legend()
plt.show(block=True)
+24
View File
@@ -0,0 +1,24 @@
import pandas as pd
import numpy as np
populations = pd.read_csv("data/state-population.csv")
areas = pd.read_csv("data/state-areas.csv")
abbrevs = pd.read_csv("data/state-abbrevs.csv")
merged = pd.merge(
populations, abbrevs, how="outer", left_on="state/region", right_on="abbreviation"
)
merged = merged.drop("abbreviation", 1)
final = pd.merge(merged, areas, on="state", how="left")
final.dropna(inplace=True)
data2010 = final.query("year == 2010 & ages == 'total'")
# print(data2010.head())
data2010.set_index("state", inplace=True)
density = data2010["population"] / data2010["area (sq. mi)"]
density.sort_values(ascending=False, inplace=True)
print(density.tail())