-
Notifications
You must be signed in to change notification settings - Fork 3
/
python_intro_prep_2024_edited.py
222 lines (160 loc) · 5.26 KB
/
python_intro_prep_2024_edited.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# -*- coding: utf-8 -*-
"""python_intro_prep_2024_edited.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/github/ZuckermanLab/coding2024/blob/main/python_intro_prep_2024_edited.ipynb
**It's OK to make a mistake**
"""
print ("my name is claire sherman")
"""**Printing words, numbers, math calculations**"""
print('hi there')
print('') # leave a space
# by the way, a '#' symbol means the line is a comment - it won't get processed
a = 2
b = 4
c = a*b
print('a=', a, ' b=', b, ' c=', c)
# fancier way
print(f'a={a} b={b} c={c}')
# you try - print something by typing below and running the cell
a=5
b=10
c=30
d=a*(b-c)
print(d)
"""**Lists and loops**"""
dan_list = ['dog', 'cat', 'mouse']
for animal in dan_list:
print(animal)
print('')
for x in dan_list:
print(x)
print('')
for x in dan_list:
print(animal)
# you try - make a list of numbers and print them. then do a math operation on them too
list1 = [apple, banana, orage, pineapple]
x=[list1]
print(list1)
"""**A little more with loops**"""
int_list = range(5) # range is a built-in python function
print(int_list)
print('')
for i in int_list:
print(i)
print('')
my_name = 'Dan'
for i in int_list:
print(f'My name is {my_name}')
print('')
my_name = 'Dan'
for i in int_list:
print(i, i**2, i**3) # raise to a power with **
"""**Functions**"""
# you try - make a loop over a range of integers and print i + i**2 for each
# or write a function to sum the numbers from 1 to 100
# functions are just lists of commands
# they can take multiple 'arguments' (in parentheses) as inputs
# they can 'return' an answer, which might be a number, string, list, ...
def text_repeater(text, reps):
for i in range(reps):
print(text)
text_repeater("oh it's you", 4)
text_repeater("No, it's me", 2)
def another_function():
print('')
print('this')
print('that')
print(2*3)
another_function()
def square_it(x):
return x**2
print('')
z = 5
print( z, square_it(z))
# you try - make a function and call it (execute it)
# for example - write a function that prints some text 3 times, and then sums a list of numbers
"""**Math plots with random data using Numerical Python (numpy)**"""
# First, bring in the libraries of built-in functions we'll need
import numpy as np # numpy (numerical python) - very useful for all things math
import matplotlib.pyplot as plt # plotting tools
# numpy arrays
N = 15
print('\nNumpy arrays will be used many times in this lesson')
x_arr = np.arange(N)
y_arr = np.random.rand(N) # random
print(x_arr)
# simple plots
plt.scatter(x_arr, y_arr) # plots points, taking x from first array and y from second
plt.title('Sample plot')
plt.xlabel('index of array')
plt.ylabel('value of array element')
plt.show() # show it now in output of cell
# plot the same data, but change labels
# new cell
# second set of arrays
# check if there are append commands in numpy and start from empty array?
x_arr = np.arange(0, 10, 0.1)
y_arr = np.zeros( len(x_arr) ) # initialize
print('x_arr:', x_arr) # print stuff to see what it looks like
print('') # print a space to make it easy to see different arays
print('y_arr:', y_arr)
# initialize other arrays for comparison
y_arr_2 = np.zeros( len(x_arr) ) # initialize
y_arr_3 = np.zeros( len(x_arr) )
y_arr_4 = np.zeros( len(x_arr) )
i = 0
for x in x_arr:
#print(x, i)
rando = np.random.rand() # random number between zero and one
y_arr[i] = 3*x + 5*( rando - 0.5 ) # line of slope 3 with random 'noise' scaled by 5
y_arr_2[i] = 2*x # a simple line of slope 2
y_arr_3[i] = 3*x # slope 3
y_arr_4[i] = 4*x # slope 4
i = i+1
print('') # print a space to make it easy to see different arays
print('y_arr:', y_arr)
print('')
print('y_arr_2:', y_arr_2)
# plot the various arrays
# plot new arrays
plt.scatter(x_arr, y_arr_4, label='slope=4')
plt.scatter(x_arr, y_arr_3, label='slope=3')
plt.scatter(x_arr, y_arr_2, label='slope=2')
plt.scatter(x_arr, y_arr, label='noisy data')
plt.title('Data with noise and some lines with different slopes')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc="upper left")
plt.show() # show it now in output of cell
"""**Fitting Data**"""
def error_of_fit_abs( x_array, y_array, slope): # function to compute error between data and straight line
error = 0 # initialize, then add to this
for i in range( len(x_array) ):
x = x_array[i]
y = y_array[i]
error += abs(y - slope*x) # the compound '+=' tells python to add whatever's on the right to the left variable
#print(x, y, slope*x, error)
return error
print(2, error_of_fit_abs(x_arr, y_arr, 2))
print(3, error_of_fit_abs(x_arr, y_arr, 3))
print(4, error_of_fit_abs(x_arr, y_arr, 4))
print('')
# make a loop for finer-grained 'grid search'
slopes_array = np.arange(1.0, 5.0, 0.1) # for plotting
n_slopes = len(slopes_array) # number of elements in array
x_slopes = np.zeros( n_slopes )
y_fits = np.zeros( n_slopes )
# make arrays for plotting
i = 0
for slope in slopes_array:
x_slopes[i] = slope
y_fits[i] = error_of_fit_abs(x_arr, y_arr, slope)
i = i+1
plt.scatter(x_slopes, y_fits, label='Error in fit')
plt.title("'Grid search' in one dimension")
plt.xlabel('Slope')
plt.ylabel('Error in Fit')
plt.legend(loc="upper left")
plt.show() # show it now in output of cell
"""2D loop ... suggests 2D grid search"""