Cs229 Python Friday
Cs229 Python Friday
Use Anaconda
Create an environment (full Conda)
Activate an environment
• Notepad ++/gedit
PyCharm magic:
Properly
What is a class?
Does something
with the
instance
To use a class
Instantiate a class,
get an instance
Call an instance
method
HW1 with random classifier
Data
Structures
Basic data structures
List
example_list = [1, 2, '3', 'four’]
Set (unordered, unique)
example_set = set([1, 2, '3', 'four’])
Dictionary (mapping)
example_dictionary =
{
'1': 'one',
'2': 'two',
'3': 'three'
}
More on List
2D list
list_of_list = [[1,2,3], [4,5,6], [7,8,9]]
List comprehension
initialize_a_list = [i for i in range(9)]
initialize_a_list = [i ** 2 for i in range(9)]
initialize_2d_list = [[i + j for i in range(5)] for j in
range(9)]
Insert/Pop
my_list.insert(0, ‘stuff)
print(my_list.pop(0))
More on List
Sort a list
random_list = [3,12,5,6]
sorted_list = sorted(random_list)
Comprehension
my_dict = {i: i ** 2 for i in range(10)}
my_set = {i ** 2 for i in range(10)}
scipy.linalg.eig Get eigen value (Read documentation on eigh and numpy equivalent)
array.dtype Check data type of array (for precision, for weird behavior)
import pdb;
Set a breakpoint (https://docs.python.org/3/library/pdb.html)
pdb.set_trace()
print(f’My name is
Easy way to construct a message
{name}’)
So many things to remember
Why can’t I just write loops?
tic = time.clock()
dot = 0.0;
for i in range(len(a)):
dot += a[i] * b[i]
toc = time.clock()
n_tic = time.clock()
n_dot_product = np.array(a).dot(np.array(b))
n_toc = time.clock()
print("\nn_dot_product = "+str(n_dot_product))
print("Computation time = "+str(1000*(n_toc - n_tic ))+"ms")
Plotting
Matplotlib is your friend
Scatter plot
Line plot
Duo y-axis
Log-log
Bar plot (Histogram)
3D plot
fig, ax = plt.subplots()
ax.legend()
plt.show()
Another way for legend
Using subplot
Scatter plot
Plot area under curve
Confusion matrix
https://scikit-learn.org/stable/auto_examples/model_selection/
plot_confusion_matrix.html
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
xticklabels=classes, yticklabels=classes,
title=title, ylabel='True label', xlabel='Predicted label')
tic = time.clock()
dot = 0.0;
for i in range(len(a)):
dot += a[i] * b[i]
toc = time.clock()
n_tic = time.clock()
n_dot_product = np.array(a).dot(np.array(b))
n_toc = time.clock()
print("\nn_dot_product = "+str(n_dot_product))
print("Computation time = "+str(1000*(n_toc - n_tic ))+"ms")
Popular usage, read before
use!
Python Command Description
scipy.linalg.eig Get eigen value (Read documentation on eigh and numpy equivalent)
array.dtype Check data type of array (for precision, for weird behavior)
import pdb;
Set a breakpoint (https://docs.python.org/3/library/pdb.html)
pdb.set_trace()
print(f’My name is
Easy way to construct a message
{name}’)
Links
Questions?