Skip to content

Commit

Permalink
更新脚本
Browse files Browse the repository at this point in the history
  • Loading branch information
chunhuizhang committed Mar 24, 2022
1 parent 6f68e18 commit 3ed1c5d
Show file tree
Hide file tree
Showing 22 changed files with 1,975 additions and 2 deletions.
Empty file added account/__init__.py
Empty file.
22 changes: 22 additions & 0 deletions account/quick_deduction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@


def deduction(x):
if x < 36000:
return x*0.03
if x < 144000:
return 36000*0.03 - 36000*0.1
if x < 300000:
return 36000*0.03 + (144000 - 36000)*0.1 - 144000*0.2
if x < 420000:
return 36000*0.03 + (144000 - 36000)*0.1 + (300000 - 144000)*0.2 - 300000*0.25
if x < 660000:
return 36000*0.03 + (144000 - 36000)*0.1 + (300000 - 144000)*0.2 + (420000 - 300000)*0.25 - 420000*0.3
if x < 960000:
return 36000 * 0.03 + (144000 - 36000) * 0.1 + (300000 - 144000) * 0.2 + (420000 - 300000) * 0.25 + (660000 - 420000) * 0.3 - 660000*0.35
return 36000 * 0.03 + (144000 - 36000) * 0.1 + (300000 - 144000) * 0.2 + (420000 - 300000) * 0.25 + (660000 - 420000) * 0.3 + (960000 - 660000)*0.35 - 960000*0.45


if __name__ == '__main__':
for x in [10000, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 10000000]:
print(x, deduction(x))

Empty file added dl/__init__.py
Empty file.
Empty file added dl/bn/__init__.py
Empty file.
28 changes: 28 additions & 0 deletions dl/bn/np_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

import numpy as np
import matplotlib.pyplot as plt


batch = np.zeros([2, 3, 3, 3])
batch[0, :, :, 0] = np.asarray([[2.4, 0.3, 5.6],
[7.2, 0.0, 2.1],
[1.9, 7.4, 4.1]])
batch[0, :, :, 1] = np.asarray([[1.0, 2.1, 3.8],
[9.6, 2.0, 4.4],
[9.3, 3.9, 1.4]])
batch[0, :, :, 2] = np.asarray([[2.6, 8.1, 9.0],
[2.2, 6.6, 0.2],
[6.3, 6.0, 0.1]])

batch[1, :, :, 0] = np.asarray([[5.1, 9.0, 6.9],
[9.7, 2.9, 2.4],
[6.2, 0.7, 4.3]])
batch[1, :, :, 1] = np.asarray([[3.3, 7.9, 4.8],
[3.7, 2.0, 9.4],
[4.9, 2.1, 7.8]])

batch[1, :, :, 2] = np.asarray([[2.8, 5.4, 0.0],
[6.4, 1.8, 6.8],
[3.7, 5.6, 5.6]])
print(batch[:, :, :, 0].mean())
print(batch[:, :, :, 0].var())
Empty file added matrix/__init__.py
Empty file.
7 changes: 7 additions & 0 deletions matrix/rank.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

import numpy as np
from numpy.linalg import matrix_rank

if __name__ == '__main__':
m = np.asarray([[1, 2, 3], [4, 5, 6], [5, 7, 9]])
matrix_rank(m)
Empty file added ml/__init__.py
Empty file.
Empty file added ml/gbdt+lr/__init__.py
Empty file.
Empty file added network/__init__.py
Empty file.
13 changes: 13 additions & 0 deletions network/logic_gates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import torch


def and_gate():
and_weights = torch.tensor([1, 1, -2])


if __name__ == '__main__':
# x1, x2, b
X = torch.tensor([(0, 0, 1), (0, 1, 1), (1, 0, 1), (1, 1, 1)], dtype=torch.double)

print(X)
pass
138 changes: 138 additions & 0 deletions network/lstm_add.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
from random import seed
from random import randint
from numpy import array
from math import ceil
from math import log10
from math import sqrt
from numpy import argmax
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import TimeDistributed
from keras.layers import RepeatVector


# generate lists of random integers and their sum
def random_sum_pairs(n_examples, n_numbers, largest):
X, y = list(), list()
for i in range(n_examples):
in_pattern = [randint(1, largest) for _ in range(n_numbers)]
out_pattern = sum(in_pattern)
X.append(in_pattern)
y.append(out_pattern)
return X, y


# convert data to strings
def to_string(X, y, n_numbers, largest):
max_length = n_numbers * ceil(log10(largest + 1)) + n_numbers - 1
Xstr = list()
for pattern in X:
strp = '+'.join([str(n) for n in pattern])
strp = ''.join([' ' for _ in range(max_length - len(strp))]) + strp
Xstr.append(strp)
max_length = ceil(log10(n_numbers * (largest + 1)))
ystr = list()
for pattern in y:
strp = str(pattern)
strp = ''.join([' ' for _ in range(max_length - len(strp))]) + strp
ystr.append(strp)
return Xstr, ystr


# integer encode strings
def integer_encode(X, y, alphabet):
char_to_int = dict((c, i) for i, c in enumerate(alphabet))
Xenc = list()
for pattern in X:
integer_encoded = [char_to_int[char] for char in pattern]
Xenc.append(integer_encoded)
yenc = list()
for pattern in y:
integer_encoded = [char_to_int[char] for char in pattern]
yenc.append(integer_encoded)
return Xenc, yenc


# one hot encode
def one_hot_encode(X, y, max_int):
Xenc = list()
for seq in X:
pattern = list()
for index in seq:
vector = [0 for _ in range(max_int)]
vector[index] = 1
pattern.append(vector)
Xenc.append(pattern)
yenc = list()
for seq in y:
pattern = list()
for index in seq:
vector = [0 for _ in range(max_int)]
vector[index] = 1
pattern.append(vector)
yenc.append(pattern)
return Xenc, yenc


# generate an encoded dataset
def generate_data(n_samples, n_numbers, largest, alphabet):
# generate pairs
X, y = random_sum_pairs(n_samples, n_numbers, largest)
# convert to strings
X, y = to_string(X, y, n_numbers, largest)
# integer encode
X, y = integer_encode(X, y, alphabet)
# one hot encode
X, y = one_hot_encode(X, y, len(alphabet))
# return as numpy arrays
X, y = array(X), array(y)
return X, y


# invert encoding
def invert(seq, alphabet):
int_to_char = dict((i, c) for i, c in enumerate(alphabet))
strings = list()
for pattern in seq:
string = int_to_char[argmax(pattern)]
strings.append(string)
return ''.join(strings)


# define dataset
seed(1)
n_samples = 5000
n_numbers = 2
largest = 100
alphabet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', ' ']
n_chars = len(alphabet)
n_in_seq_length = n_numbers * ceil(log10(largest + 1)) + n_numbers - 1
n_out_seq_length = ceil(log10(n_numbers * (largest + 1)))
# define LSTM configuration
n_batch = 10
n_epoch = 50
# create LSTM
model = Sequential()
# n_in_seq_length: 7, n_chars: 12
model.add(LSTM(100, input_shape=(n_in_seq_length, n_chars)))
model.add(RepeatVector(n_out_seq_length))
model.add(LSTM(50, return_sequences=True))
model.add(TimeDistributed(Dense(n_chars, activation='softmax')))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
# train LSTM
for i in range(n_epoch):
X, y = generate_data(n_samples, n_numbers, largest, alphabet)
print(i)
model.fit(X, y, epochs=1, batch_size=n_batch)

# evaluate on some new patterns
X, y = generate_data(n_samples, n_numbers, largest, alphabet)
result = model.predict(X, batch_size=n_batch, verbose=0)
# calculate error
expected = [invert(x, alphabet) for x in y]
predicted = [invert(x, alphabet) for x in result]
# show some examples
for i in range(20):
print('Expected=%s, Predicted=%s' % (expected[i], predicted[i]))
42 changes: 42 additions & 0 deletions oop/MethodTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@

from datetime import datetime

class Test:
alias = 'wudaokou nash'

@staticmethod
def static_mode(language):
print(f'static method, {Test.alias} codes in {language}')

@classmethod
def class_mode(cls, language):
print(f'class method, {cls.alias} codes in {language}')


class Repr:

def __init__(self, name):
self.name = name

def __repr__(self):
return f'{self.__class__.__module__}.{self.__class__.__qualname__}(name={self.name})'

def __str__(self):
return f'{self.name}'


if __name__ == '__main__':
t = Test()
t.static_mode('chinese')
t.class_mode('english')

r = Repr('zhang')
print(r)
print(repr(r))
print(str(r))

now = datetime.now()
print(now.__str__())
print(now.__repr__())


22 changes: 22 additions & 0 deletions oop/TestProperrty.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

class Screen(object):
@property
def width(self):
return self._width

@width.setter
def width(self, value):
self._width = value

@property
def height(self):
return self._height

@height.setter
def height(self, value):
self._height = value

@property
def resolution(self):
return self._height*self._width

Empty file added oop/__init__.py
Empty file.
59 changes: 59 additions & 0 deletions oop/dp/Decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@

from abc import ABCMeta, abstractmethod


class Person(metaclass=ABCMeta):
def __init__(self, name):
self._name = name

@abstractmethod
def wear(self):
print('着装: ')


class Engineer(Person):

def __init__(self, name, skill):
super().__init__(name)
self._skill = skill

def wear(self):
print(f'我是 {self._name} 工程师, 我会 {self._skill}')
super().wear()


class ClothingDecorator(Person):
def __init__(self, person: Person):
self._decoratored = person

def wear(self):
self._decoratored.wear()
self.decorate()

@abstractmethod
def decorate(self):
pass


class CasualPantDecorator(ClothingDecorator):
def __init__(self, person: Person):
super().__init__(person)
def decorate(self):
print('一条卡其色裤子')


class BeltDecorator(ClothingDecorator):
def __init__(self, person: Person):
super().__init__(person)

def decorate(self):
print('一条黑色腰带')

if __name__ == '__main__':
tony = Engineer('Tony', '算法')
pant = CasualPantDecorator(tony)
belt = BeltDecorator(pant)
belt.wear()



Empty file added oop/dp/__init__.py
Empty file.
45 changes: 45 additions & 0 deletions ordemo/polygon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from ortools.linear_solver import pywraplp


def main():
# Create the mip solver with the SCIP backend.
solver = pywraplp.Solver.CreateSolver('SCIP')

infinity = solver.infinity()
# x and y are integer non-negative variables.
x = solver.IntVar(3, infinity, 'x')
y = solver.IntVar(0, infinity, 'y')
t = solver.IntVar(0, infinity, 't')

print('Number of variables =', solver.NumVariables())

solver.Add(t == x-2)
# x + 7 * y <= 17.5.
solver.Add(y == 2*x/t)

# x <= 3.5.
# solver.Add(x <= 3.5)

print('Number of constraints =', solver.NumConstraints())

# Maximize x + 10 * y.
solver.Maximize(0)

status = solver.Solve()

if status == pywraplp.Solver.OPTIMAL:
print('Solution:')
print('Objective value =', solver.Objective().Value())
print('x =', x.solution_value())
print('y =', y.solution_value())
else:
print('The problem does not have an optimal solution.')

print('\nAdvanced usage:')
print('Problem solved in %f milliseconds' % solver.wall_time())
print('Problem solved in %d iterations' % solver.iterations())
print('Problem solved in %d branch-and-bound nodes' % solver.nodes())


if __name__ == '__main__':
main()
4 changes: 2 additions & 2 deletions ordemo/send_more_money.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,5 @@ def solution_count(self):

solver.Solve(model, solution_printer)

print(
f" {solver.Value(S)}{solver.Value(E)}{solver.Value(N)}{solver.Value(D)}\n+ {solver.Value(M)}{solver.Value(O)}{solver.Value(R)}{solver.Value(E)}\n={solver.Value(M)}{solver.Value(O)}{solver.Value(N)}{solver.Value(E)}{solver.Value(Y)}")
# print(
# f" {solver.Value(S)}{solver.Value(E)}{solver.Value(N)}{solver.Value(D)}\n+ {solver.Value(M)}{solver.Value(O)}{solver.Value(R)}{solver.Value(E)}\n={solver.Value(M)}{solver.Value(O)}{solver.Value(N)}{solver.Value(E)}{solver.Value(Y)}")
Loading

0 comments on commit 3ed1c5d

Please sign in to comment.