python科学计算入门

教程

## 学习自:http://cs231n.github.io/python-numpy-tutorial/
x = 3
print(type(x))
print(not 0)
## string
hello = "hello"
world = "world"
print(hello)
print(len(hello))
hw = hello + " " + world
print(hw)
hw12 = '%s %s %d' % (hello, world, 12)
print(hw12)
## useful methods
s = 'hellp'
print(s.capitalize())
print(s.upper())
print(s.rjust(10))
print(s.center(11))
print(s.replace('l', '(ell)'))
print('  world'.strip()) ## strip whitespace

## lists
xs = [3, 1, 2]
print(xs, xs[2])
print(xs[-1]) ## back to front

xs[2] = 'foo' ## list can contains elements of different types
print(xs)
xs.append('bar')
print(xs)
x = xs.pop() ## pop the last element of the list
print(xs, x)

## Slicing

nums = list(range(5))
print(nums)
print(nums[2:4])
print(nums[2:])
print(nums[:])
print(nums[:4])
print(nums[:-1])

## Loops
animals = [
    'cat',
    'dog',
    'monkey'
]
for animal in animals:
    print(animal)


for id, animal in enumerate(animals): ##get id
    print('#%d: %s' % (id + 1, animal))

## List comprehensions
nums = [0, 1, 2, 3]
squares = [x ** 2 for x in nums]
print(squares)

## contain conditions
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)

## Dictions
d = {'cat':'cute', 'dog':'furry'}
print(d['cat']) ## get
print('cat' in d) ## check if in
d['fish'] = 'wet' ## set
print(d)
del d['fish'] ## delete
print(d.get('fish', 'None')) ## if not in, print 'None'

d = {'person':2, 'cat':4, 'spider':8}
for animal in d:
    legs = d[animal]
    print('A %s has %d legs.' % (animal, legs))

## or you can write this way to get K&&V
for animal, legs in d.items():
    print('A %s has %d legs.' % (animal, legs))


## dictionary comprehensions

nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)

##Sets  unordered

animals = {'cat', 'dog'}
print('cat' in animals) ## check if in
print('fish' in animals) 
animals.add('fish') ## insert
print(animals)
print(len(animals))
animals.remove('cat')  ## remove
print(len(animals))

## the same as dictionary
for id, animal in enumerate(animals):
    print('#%d: %s' % (id + 1, animal))

## Set comprehension
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)

## Tuples, (cannot be change, ordered )similat to list,but can be used as keys in dictionary && sets
d ={(x, x + 1) : x for x in range(10)}
print(d)
t = (5, 6) ## create a tuple
print(type(t))
print(d[t])

## Functions, using the def keyword
def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

for x in [-1, 0, 1]:
    print(sign(x))

## optional keyword arguments
def hello1(name, loud= False):
    if loud:
        print('HELLO, %s!' % name.upper())
    else :
        print('Hello, %s' % name)

hello1('Bob')
hello1('Fred', True)

## Class

class Greeter(object):
    # Constructor
    def __init__(self, name):
        self.name = name
    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print("Hello, %s!" % self.name)

g = Greeter('Fred')
g.greet()
g.greet(loud = True)

## Numpy: for computing in Python

import numpy as np
a = np.array([1, 2, 3]) 
print(type(a))
print(a)
a[0] = 5
print(a)
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b.shape) # DD
print(b)

a = np.zeros((2, 2))
print(a)

b = np.ones((1, 2))
print('b:', b)

c = np.full((2, 2), 7)
print(c)

d = np.eye(2)
print(d)

e = np.random.random((2, 2))
print(e)

## array indexing
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
b = a[:2, 1:3]  ## row:0, 1  col:1, 2
print(b)
print(a[0, 1])
b[0, 0] = 77  ## share memory
print(a[0, 1])

row_r1 = a[1,:]
row_r2 = a[1:2, :]
print(row_r1, row_r1.shape) ## diff with down
print(row_r2, row_r2.shape)

print(a[[0, 1, 2], [0, 1, 0]]) ## equivalent
print(np.array(a[[0, 1, 2], [0, 1, 0]]))

b = np.array([0, 2, 0])
print(a[np.arange(3), b]) # for each row
a[np.arange(3), b] += 10
print(a)

## boolean array index
bool_idx = (a > 10)
print(bool_idx)
print(a[bool_idx])
print(a[a > 10]) ## equivalen

## datatypes
print(a.dtype) # int64
b = np.array([1.0, 2.0])
print(b.dtype)  # float64

x = np.array([1, 2], dtype = np.int32)
print(x.dtype)

## Array math
a = np.array([[1, 2], [3, 4]], dtype = np.float64)
b = np.array([[5,6], [7, 8]], dtype= np.float64)
print(a + b)
print(np.add(a, b))
print(a - b)
print(a * b)  # not dot
print('dot:',a.dot(b)) # inner product
print(np.dot(a, b))
print( a / b)
print(np.sqrt(a))
print(a % b)

## cal sum
print(np.sum(a))
print(np.sum(a, axis = 0)) ##col
print(np.sum(a, axis =1)) # row

print(a)
print(a.T) # use the T attribute of an array object


## broadcasting

x = np.array([[1, 2, 3],[4, 5, 6],[7, 8,9 ], [10, 11, 12]])
v = np.array([1, 0, 1])
vv = np.tile(v,(4, 1))

print(vv)
print(x + vv)

# or you can write this way
print(x + v) # pretty easy!

# for more about numpy :http://docs.scipy.org/doc/numpy/reference/

## Scipy
from scipy.misc import imread, imsave, imresize
img = imread('yun.jpg')
print(img.dtype, img.shape)
img2 = imread('time.jpg')
print(img2.dtype, img2.shape)
img_tinted = img * [1, 0.95, 0.9]
img_tinted = imresize(img_tinted, (500, 500))
imsave("yun_back.jpg", img_tinted)

# Distance between points
from scipy.spatial.distance import pdist, squareform
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)
d = squareform(pdist(x, "euclidean"))
print(d)

# Matplotlib

import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

## plot:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.xlabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.show()

## Subplots: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot
plt.subplot(2, 2, 1) # h = 2, w = 2  this(0, 0)
plt.plot(x, y_sin)
plt.title('Sine')
plt.subplot(2, 2, 2) # this(0, 1)
plt.imshow(img)
plt.title('Img')
plt.subplot(2, 2, 3) # this(1, 0)
plt.imshow(np.uint8(img2))
plt.title('Img2')
plt.show()
发布了74 篇原创文章 · 获赞 11 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/yijiull/article/details/81697559