Skip to content
Gallery
Azavea
Share
Explore
other samples

icon picker
Tensorflow mL models

# going to flesh this page out more;
Testing a neural network (Resnet50). I usually have begun the lessons that pertain to mL with a simple test of a stock classifier. I chose to include this code because I think that the stock tensorflow + keras examples are very clean and pythonic:
from tensorflow.python.keras.applications.resnet50 import ResNet50
from tensorflow.python.keras.preprocessing import image
from tensorflow.python.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np

model = ResNet50()

img_path = '/home/vince/Desktop/honeybadger.jpg'
img = image.load_img(img_path, target_size=(224, 224))

x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)

print(decode_predictions(preds, top=4))

Here is a custom binary classification network. The developer just has to load up a custom dataframe, and run a binary classification on that data. I have used this as a lesson, and have tried
import tensorflow as tf
from tensorflow import keras
import pandas as pd

df = pd.read_csv('/home/vince/Desktop/youthy.csv')
print(df)

df2 = df.replace(to_replace=[19, 'cobbs', 'no'], value=0)
df3 = df2.replace(to_replace=[17, 18, 'cedar', 'yes'], value=1)
print(df3)

dfInput = df3[['Age', 'Neighborhood', 'Attended']]
dfInput = dfInput.as_matrix()
print(dfInput)
dfOutput = df3[['Trained']]
dfOutput = dfOutput.as_matrix()
print(dfOutput)

inputTensor = tf.Variable(dfInput, dtype=float)
print(inputTensor.shape)
outputTensor = tf.Variable(dfOutput, dtype=float)
print(outputTensor.shape)
print(inputTensor)
print(outputTensor)
# # tensors should now be prepared to flow through network

##########################################################

model = keras.Sequential()
input_layer = keras.layers.Dense(3, input_shape=[3], activation='tanh')
model.add(input_layer)
output_layer = keras.layers.Dense(1, activation='sigmoid')
model.add(output_layer)

# # add the optimizer
gradientDescender = tf.optimizers.Adam(0.01)

# # compile and fit the network
model.compile(optimizer=gradientDescender,
loss='mean_squared_error')
model.fit(inputTensor, outputTensor, epochs=1000, steps_per_epoch=10)

# # test the network
results = model.predict(inputTensor, verbose=1, steps=1)
print(results)

utilize clustering for simple unsupervised learning on a stock dataset:
# K-Means clusterer

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('/home/vince/Desktop/cars.csv')

X = dataset.iloc[:, :-1].values

X = pd.DataFrame(X)
X = X.convert_objects(convert_numeric=True)
X.columns = ['mpg', ' cylinders', ' cubicinches', ' hp', ' weightlbs', ' time-to-60', 'year']

# Eliminating null values
for i in X.columns:
X[i] = X[i].fillna(int(X[i].mean()))
for i in X.columns:
print(X[i].isnull().sum())

# Using the elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans

wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()

# Applying k-means to the cars dataset
kmeans = KMeans(n_clusters=3,
init='k-means++',
max_iter=300,
n_init=10,
random_state=0)
y_kmeans = kmeans.fit_predict(X)
X = X.as_matrix(columns=None)

# Visualising the clusters
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s=100, c='red', label='US')
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s=100, c='blue', label='Japan')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s=100, c='green', label='Europe')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='yellow', label='Centroids')
plt.title('Clusters of car brands')
plt.legend()
plt.show()

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.