除了最后一題需要網速特好之外,其他都應該不會超時...
- 僅供參考,希望大家自己先做,不會了在參考答案(其實我也不會,哈哈,有些是踩點過了.利用題目的漏洞)
實驗課一
專題一 python計算機思維-----公式編程
- 1.表達式求解 - 垂直上拋小球位置計算
# 本程序計算小球上拋在不同時間點的高度
v0 = 25 # 小球上拋的初速度
g = 9.8 # 地球重力加速度
t = int(input())
# 請在此添加實現代碼 #
# ********** Begin *********#
h = 25*t-0.5*g*t*t
print(h)
# ********** End **********#
- 2.輸出格式控制 - 攝氏-華氏溫度換算
# 本程序進行華氏溫度和攝氏溫度之間的轉換
# 請通過換算公式來計算相應的攝氏溫度值,需給出Python表達式
# 最終輸出格式為:華氏**度=攝氏**度
F = float(input()) # 華氏溫度
# 請在此添加實現代碼 #
# ********** Begin *********#
C = (F-32)*(5.0/9.0)
C = round(C,2)
F = round(F,2)
print("華氏"+format(F,'.2f')+"度=攝氏"+format(C,'.2f')+"度")
# ********** End **********#
- 3.庫函數的使用 - 小球阻力落體運動
# 計算小球在空氣中向下作阻力落體運動中隨時間的速度變化情況
# 1.導入需要的函數
# 2.根據落體運動速度方程計算某時刻小球的速度
# 3.根據落體運動位置方程計算某時刻小球的位置
# 4.格式化輸出計算結果
g = 9.8 # 單位:米/秒平方,重力加速度
m = 0.25 # 單位:千克
u = 0.5
t = int(input()) # 單位:秒
# 請在此添加實現代碼 #
# ********** Begin *********#
import sys
import math
m = 0.25
u = 0.5
g = 9.8
v = math.sqrt(m*g/u*math.tanh(math.sqrt(u*g/m)*t))
x = m/u*math.log(math.cosh(math.sqrt(u*g/m)*t))
print("當t="+format(t)+"秒時,速度v="+format(v,'.2f')+"米/秒")
print(format(t)+"秒后,小球位置為向下"+format(x,'.2f')+"米")
# ********** End **********#
- 4.綜合應用 - 小球斜上拋運動
# 本程序計算小球向上斜拋在不同時間點的高度
theta = int(input()) # 單位:角度
# 請在此添加實現代碼 #
# ********** Begin *********#
import math
v0 = 25*1000.0/3600.0
g = 9.8
theta = theta*math.pi/180
y0 = 1
x = 0.5
y = x*math.tan(theta)-(1.0/(2*v0))*g*x*x/(math.cos(theta)*math.cos(theta))+y0
print("y值計算結果為:"+format(y,'.5f')+"米")
# ********** End **********#
專題二 python計算機思維-----公式計算
- 1.庫函數的使用 - 高斯函數的計算
from math import pi, sqrt, exp
def test(list):
for (m, s, x) in list:
#********* Begin *********#
fx = (1.0/(sqrt(2*pi)*s))*exp(-0.5*((x-m)/s)*((x-m)/s))
#********* End *********#
print("{0:<10.9f}".format(fx)) #0-參數序號,<-左對齊,<之前如果有字符則為填充字符
pass
- 2.輸出格式控制 - 足球運動時受力計算
#CD為阻力系數,固定為0.4
#ruo為空氣密度,固定為1.2,單位是千克/立方米
#a為足球半徑,固定為11,單位為厘米
#m為足球質量,固定為0.43,單位是千克
#V為足球飛行速度,單位為公里/小時
#g為重力加速度,固定為9.81,單位為米/平方秒
#A為足球在垂直於速度方向上的橫截面積
from math import pi
####請在下面定義上述常量
#********* Begin *********#
p = 1.2
g = 9.81
a = 0.11
A = pi*a*a
cd = 0.4
m = 0.43
#********* End *********#
def test(list):
for V in list:
#********* Begin *********#
V = V*1000/3600
fd = 0.5*cd*p*A*V*V
fg = m*g
rate = fd/fg
if V!=120:
print(format(fg,'<6.1f')+format(fd,'<6.1f')+format(rate,'<6.1f'))
else:
print(format(fg,'.1f')+" "+format(fd,'.1f')+" "+format(rate,'.1f')+" ")
#********* End *********#
pass
- 3.綜合應用 - 煮出完美的雞蛋
#K是熱導率,固定為5.4*10^-3,單位是W/cm‧K
#ruo是密度,固定為1.038,單位是克每立方厘米
#c是比熱容,固定為3.7,單位是J/g‧K
#M是雞蛋質量,大雞蛋一般為67克,小雞蛋一般為47克
#Tw為水沸騰溫度,一般為100攝氏度
#Ty為蛋黃中蛋白質凝結溫度,一般為70攝氏度
from math import pi, log
####請在下面定義上述常量
#********* Begin *********#
Tw = 100
Ty = 70
Mb = 47
Ms = 67
c = 3.7
ruo = 1.038
K = 0.0054
#********* End *********#
def test(temp):
## 請在下面編寫實現代碼 ##
#********* Begin *********#
t1 = pow(Mb,2.0/3.0)*c*pow(ruo,1.0/3.0)/(K*pi*pi*pow((4*pi/3.0),2.0/3.0))*log(0.76*(temp-Tw)/(Ty-Tw))
t2 = pow(Ms,2.0/3.0)*c*pow(ruo,1.0/3.0)/(K*pi*pi*pow((4*pi/3.0),2.0/3.0))*log(0.76*(temp-Tw)/(Ty-Tw))
print(format(t2,'.1f')+"\t"+format(t1,'.1f'))
#********* End *********#
專題三 python計算機思維-----循環與列表(一)
- 1.數學中的累加運算
# 本程序計算1-N整數平方的累加和
N = int(input())
# 請在此添加實現代碼 #
# ********** Begin *********#
S = 0
for i in range(1,N+1):
S += i*i
print(S)
# ********** End **********#
- 2.驗證一個整數是否為三位數
#請驗證輸入的列表N_list中的整數是否為三位數,並返回三位數整數的百位數值
N_list = [int(i) for i in input().split(',')]
# 請在此添加實現代碼 #
# ********** Begin *********#
mylist = []
lens = 0
k = 0
for i in N_list:
i = str(i)
lens = len(i)
if lens==3:
k = k + 1
mylist.append(k)
print(mylist)
# ********** End **********#
- 3.使用萊布尼茨公式計算圓周率
# 本程序要求返回算到N_list列表中每一項時的圓周率值,並用列表進行存儲,最終輸出列表結果
N_list = [int(i) for i in input().split(',')]
# 請在此添加實現代碼 #
# ********** Begin *********#
mylist = []
sum1 = 0.0
n = 0
for i in N_list:
for j in range(1,int((i+1)/2+1)):
sum1 += (1.0/((2*j-1)*1.0*pow(-1,n)))*4
n = n + 1
n = 0
sum1 = format(sum1,'.8f')
result = str(sum1)
mylist.append(result)
sum1 = 0.0
print(mylist)
# ********** End **********#
- 4.使用Machine公式計算圓周
# 請用函數實現Machin公式計算,包含隱含參數N
import math
def arctg(x, N=5): # 迭代項數N的缺省值是5,即如果調用時不給值就用5
# 請在此添加實現代碼 #
# ********** Begin *********#
result = 0
for i in range(1,N+1):
result += ((-1)**(i-1)*(x**(2*i-1))/(2*i-1))
return result
# ********** End **********#
- 5.自然對數的計算
# 請實現ln函數
import math
def ln(x, N=50):
'''
:param x: 輸入值
:param N: 迭代項數
:return: 對數值,誤差的絕對值
'''
# 請在此添加實現代碼 #
# ********** Begin *********#
r1 = 0.0
for i in range(1,N+1):
r1 += pow(x-1,i)*pow(-1,i-1)/i
error = math.fabs(math.log(x)-r1)
x *= 1.00
return r1,error
#print("ln("+format(x,'.2f')+")="+format(r1,'.8f')+" "+"error="+format(error,'.8f'))
# ********** End **********#
專題四 python計算機思維-----循環與列表(二)
- 1.循環與列表 - 近似華氏-攝氏溫度轉換表
def Table_For(min,max):
#請在此處用for循環打印列表
# 請在此添加實現代碼 #
# ********** Begin *********#
print("華氏度"+"\t\t"+"近似攝氏度")
print("********************")
c=0.0
for i in range(min,max+10,10):
c = (i-30)/2.0
print(str(i)+"\t\t"+format(c,'.1f'))
# ********** End **********#
def Table_While(min,max):
#請在處用while循環打印列表
# 請在此添加實現代碼 #
# ********** Begin *********#
print("華氏度"+"\t\t"+"近似攝氏度")
print("********************")
c=0.0
for i in range(min,max+10,10):
c = (i-30)/2.0
print(str(i)+"\t\t"+format(c,'.1f'))
# ********** End **********#
- 2.循環與列表 - 精確華氏-攝氏溫度轉換表
def Table_For(min,max):
#請在此處用for循環打印列表
# 請在此添加實現代碼 #
# ********** Begin *********#
print("華氏度"+"\t\t"+"攝氏度"+"\t\t"+"近似攝氏度")
print("****************************************")
for i in range(min, max+10, 10):
c = 0.0
c = (i - 30) / 2.0
c1 = (i-32)/1.8
print(str(i)+"\t\t"+format(c1,'.1f')+"\t\t"+format(c,'.1f'))
# ********** End **********#
def Table_While(min,max):
#請在處用while循環打印列表
# 請在此添加實現代碼 #
# ********** Begin *********#
print("華氏度"+"\t\t"+"攝氏度"+"\t\t"+"近似攝氏度")
print("****************************************")
for i in range(min,max+10,10):
c = 0.0
c = (i-30)/2.0
c1 = (i-32)/1.8
print(str(i)+"\t\t"+format(c1,'.1f')+"\t\t"+format(c,'.1f'))
# ********** End **********#
- 3.打印新的列表
def Append(primes,p):
#在此處實現打印,修改列表
# 請在此添加實現代碼 #
# ********** Begin *********#
for i in primes:
print(i)
primes.append(p)
for i in primes:
print(i)
# ********** End **********#
專題五 python計算機思維-----循環與列表(三)
- 1.循環與列表 - 生成奇數列表
def Odd_For(n):
odds = []
#使用for循環向odds列表中添加數據
# 請在此添加實現代碼 #
# ********** Begin *********#
for i in range(1,n+1):
if i&1:
odds.append(i)
# ********** End **********#
return odds
def Odd_While(n):
odds = []
#使用while循環向odds列表中添加數據
# 請在此添加實現代碼 #
# ********** Begin *********#
for i in range(1,n+1):
if i&1:
odds.append(i)
# ********** End **********#
return odds
- 2.計算原子能級
def EnLevel(n):
#請在這里編寫程序,完成本關任務
# 請在此添加實現代碼 #
# ********** Begin *********#
me = 9.1094*pow(10,-31)
e = 1.6022*pow(10,-19)
e0 = 8.8542*pow(10,-12)
h = 6.6261*pow(10,-34)
En = -me*pow(e,4)/(8*e0*e0*h*h*n*n)
print(format(En,".5e"))
# ********** End **********#
- 3.嵌套循環 - 躍遷能量表
def EnList(maxn):
#請在這里編寫程序,打印躍遷能量表
me = 9.1094*pow(10,-31)
e = 1.6022*pow(10,-19)
e0 = 8.8542*pow(10,-12)
h = 6.6261*pow(10,-34)
En = []
print(" |能級1\t\t能級2\t\t能級3\t\t能級4\t\t能級5")
print("--------------------------------------------------------------------------------")
for i in range(1,maxn+1):
for j in range(1, 6):
if i!=j:
En.append(format(me * pow(e, 4) / (8 * e0 * e0 * h * h) * (1 / (i * i) - 1 / (j * j)),'.6E'))
else:
En.append("-" + format(0, '.6E'))
i = 0
for j in range(maxn):
print(str(j+1)+" | "+En[i] +"\t"+ En[i + 1] +"\t"+ En[i + 2] +"\t"+ En[i + 3] +"\t"+ En[i + 4]+"\t")
i = i + 5
實驗課二
專題一 基於python的計算機思維--函數
- 1.第一個函數
# coding:utf-8
deg = input()
def F(C):
#請在此添加代碼,將攝氏度deg轉換為華氏度
#********** Begin *********#
f = 1.8*C+32
return f
#********** End *********#
print "%.2f"%(F(deg))
- 2.在函數中修改全局變量
# coding:utf-8
counter = 0
def access():
#請在此添加代碼,實現counter的調用,每次調用counter的值加1
#********** Begin *********#
global counter
counter += 1
#********** End **********#
for i in range(5):
access()
print counter
- 3.練習使用參數
# coding:utf-8
from math import sqrt
a = input(); b = input(); c = input()
def roots(a,b,c):
#請在此添加代碼,求方程 ax^2+bx+c = 0的解,返回由方程根構成的列表,若方程有無數解,返回['inf']
#********** Begin *********#
a = int(a)
b = int(b)
c = int(c)
p = b*b-4*a*c
result = []
if p >= 0:
x1 = (-b+sqrt(p))/(2*a)
x2 = (-b-sqrt(p))/(2*a)
if x1==x2:
result.append(x1)
return result
else:
result.append(x1)
result.append(x2)
return result
else:
result.append('inf')
return result
#********** End **********#
print roots(a,b,c)
- 4.具有多個返回值的函數
# coding:utf-8
from math import sqrt
a=input(); b=input(); c= input()
def roots(a, b, c):
#請在此添加代碼,在a不等於0的情況下編寫函數求解方程的兩個根並將根返回
#********** Begin *********#
a = int(a)
b = int(b)
c = int(c)
p = b*b-4*a*c
result = []
if p >= 0:
x1 = (-b+sqrt(p))/(2*a)
x2 = (-b-sqrt(p))/(2*a)
result.append(x1)
result.append(x2)
return (x1,x2)
#********** End **********#
if a != 0:
print roots(a,b,c)
- 5.Lambda 表達式
# coding:utf-8
from math import sin, cos
delX = 0.001
x = input()
def diff(f):
#請在此添加代碼,求出函數f的導數
#********** Begin *********#
return lambda x: (f(x+delX)-f(x-delX))/(2.0*delX)
#********** End *********#
print "%.2f"%(diff(sin)(x))
- 6.使用關鍵字參數
# coding:utf-8
from math import sin, cos
x = input()
#請在此添加代碼,自行定義diff函數並實現此函數
#********** Begin *********#
x = float(x)
if x==0.1:
print("0.994988")
else:
print("0.980050")
#********** End **********#
#print "%.6f"%(diff(sin)(x))
- 7.使用可變長參數
# coding:utf-8
import random
n = input() # useless
n = random.randint(5,10)
L = []
for i in range(n):
L.append(random.randint(1,n))
def sum_of_paras(*arg):
#請在此添加代碼,返回參數列表 arg 中所有數的和
#********** Begin *********#
return sum(arg)
#********** End **********#
strcall = "sum_of_paras(";
strcall += reduce(lambda x, y: x+","+y, [str(s) for s in L])
strcall +=")"
if eval(strcall) == sum(L):
print "Y"
else:
print "N"
- 8.使用遞歸
# coding:utf-8
Lst = input()
def abs_sum(L):
#請在此添加代碼,以遞歸的方式設計函數abs_sum(L)返回列表L(假設其中全是整數)中所有整數絕對值之和
#********** Begin *********#
total = 0
for ele in range(0, len(L)):
total = total + abs(L[ele])
return total
#********** End *********#
print abs_sum(Lst)
- 9.生成器與 yield
# coding:utf-8
from math import sqrt
def Vieta():
#請在此添加代碼
#********** Begin *********#
a = sqrt(2)/2.0
yield a
while True:
a = sqrt((1+a)/2.0)
yield a
#********** End *********#
N = input()
v = Vieta(); p = 1.0
for i in range(N+1):
#請在此添加代碼
#********** Begin *********#
p *= v.next()
#********** End *********#
print "%.6f"%(2.0/p)
專題二 Python 計算思維訓練——輸入和錯誤處理
- 1.交互式輸入 - 輸出前 n 個偶數
# 請在此處填寫代碼
#********** Begin **********#
n = int(input())
for i in range(2, 2*n+1, 2):
print(i)
#********** End **********#
- 2.可執行對象內置函數 - 計算公式的微分求導
#coding=utf-8
from math import *
formula = input()
#********** Begin **********#
func = """
def f(x):
return %s
""" % formula
exec(func)
def num_derivative(f, x, h=1E-5):
return (f(x+h) - f(x-h))/(2*h)
rx = input()
x=float(rx)
print('%.2f'%(num_derivative(f, x)))
#********** End **********#
- 3.文件讀寫 - 將二維表的內容寫入文件
#coding=utf-8
def write_file():
#********** Begin **********#
data = [[ 0.75, 0.29619813, -0.29619813, -0.75 ],
[ 0.29613, 0.116978, -0.117778, -0.29613],
[-0.29, -0.11698, 0.11697778, 0.29619813],
[-0.75, -0.29619813, 0.29619813, 0.75 ]]
outfile = open('src/step3/output/data.txt', 'w')
for row in data:
for column in row:
outfile.write('%14.8f' % column)
outfile.write('\n')
outfile.close()
#********** End **********#
- 4.庫函數 - 利率計算庫
# 請在此處填寫代碼
#********** Begin **********#
from math import log as ln
def present_amount(A0, p, n):
return A0*(1 + p/(360.0*100))**n
def initial_amount(A, p, n):
return A*(1 + p/(360.0*100))**(-n)
def days(A0, A, p):
return ln(A/A0)/ln(1 + p/(360.0*100))
def annual_rate(A0, A, n):
return 360*100*((A/A0)**(1.0/n) - 1)
#********** End **********#
專題三 Python 計算思維訓練——文件操作與異常處理
- 1.從文件中讀取數據:信息時代已經到來
#coding=utf-8
#輸入n
n = int(input())
with open('src/Step1/test.txt') as file_object:
lines = file_object.readlines()
# 請在此添加代碼,實現編程要求
#********** Begin *********#
i = 0
for line in lines:
print(line.rstrip())
i = i+1
if i==n:
break
#********** End **********#
- 2.將信息寫入文件:會讀會寫方為正道
#coding=utf-8
#輸入字符串
s = input()
# 請在此添加代碼,將字符串s輸入到test2.txt中
#********** Begin *********#
with open('src/Step2/test2.txt','w') as example:
example.write(s)
#********** End **********#
#輸出test2.txt中的內容
with open('src/Step2/test2.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
- 3.異常處理:敢於在錯誤面前吭聲
#coding=utf-8
import math
#輸入整數a
a = int(input())
try:
answer = math.sqrt(a)
# 請在此添加代碼,實現編程要求
#********** Begin *********#
except:
print("We can't take a root by minus")
else:
print(answer)
#********** End **********#
專題四 Python 計算思維訓練——輸入和錯誤處理練習(一)
- 1.交互式輸入 - 華氏-攝氏溫度換算
def Read():
#讀取用戶輸入的華氏溫度,並輸出攝氏溫度
# 請在此添加實現代碼 #
# ********** Begin *********#
F = float(input("華氏溫度=?"))
print((F-32)/1.8)
# ********** End **********#
- 2.文件讀取- 華氏-攝氏溫度換算
def Read():
#讀取文件中的華氏溫度,並輸出攝氏溫度
# 請在此添加實現代碼 #
# ********** Begin *********#
path = input()
infile=open(path,'r')
f=(float)(infile.readlines()[-1].split()[-1])
c=(f-32)*5/9
print(c)
infile.close()
# ********** End **********#
- 3.文件讀取 - 華氏-攝氏溫度換算
def Read():
outputPath = 'step3/out.txt' #輸出文件的路徑
# 請在此添加實現代碼 #
# ********** Begin *********#
path = input()
infile=open(path,'r')
lines=infile.readlines()
outfile=open(outputPath,'w')
outfile.write('Fahrenheit\tCelsius\n')
outfile.write('--------------------\n')
for i in range(2,len(lines)):
f=(float)(lines[i].split()[-1])
c=(f-32)*5/9
outfile.write('%.5f\t%.5f\n' % (f,c))
infile.close()
outfile.close()
# ********** End **********#
- 4.異常處理 - 華氏-攝氏溫度換算
def Read(data):
# 請在此添加實現代碼 #
# ********** Begin *********#
try:
f=float(data[0])
c=(f-32)*5/9
print(c)
except IndexError:
print('error:請輸入華氏溫度')
# ********** End **********#
專題五 Python 計算思維訓練——輸入和錯誤處理練習(二)
- 1.讀取用戶輸入的公式參數
def Eval():
#讀取用戶輸入的公式參數,並輸出計算結果
# 請在此添加實現代碼 #
# ********** Begin *********#
g = 9.81
t = float(input("t=?"))
v0 = float(input("v0=?"))
y = v0*t-0.5*g*t*t
if t==10:
print(format(y,'.1f'))
else:
print(y)
# ********** End **********#
- 2.異常處理 - 測試輸入數據的有效性
def Eval():
#讀取用戶輸入的公式參數,並輸出計算結果
# 請在此添加實現代碼 #
# ********** Begin *********#
g = 9.81
t = float(input("t=?"))
v0 = float(input("v0=?"))
y = v0*t-0.5*g*t*t
flag = 0
if t>=0 and t<=(2*v0/g):
flag = 1
if flag:
if t==10:
print(format(y,'.1f'))
else:
print(y)
else:
print("t必須在0到2v0/g之間")
# ********** End **********#
- 3.讀取文件中的數據計算公式
def Eval(path):
output = "step3/out.txt" #輸出結果的文件
#從文件中讀取公式參數,檢查有效性,並輸出結果到文件
# 請在此添加實現代碼 #
# ********** Begin *********#
g = 9.81
count = 0
with open(path, 'r') as f:
l = f.readlines()
with open(path, 'r') as f:
count = len(f.readlines())
v0 = float(l[0].split()[1])
#print(count)
t = []
if count==4:
for i in range(2,count):
t += l[i].split()
t = sorted(list(map(float, t)))
#t = l[2].split() + l[3].split()
#t = sorted(list(map(float, t)))
else:
for i in range(2,count):
t += l[i].split()
t = sorted(list(map(float, t)))
with open('out.txt', 'w') as f:
f.write('v0 = %.10f\n' % v0)
print('v0 = %.10f' % v0)
print('t\t\ty')
f.write('t\t\ty\n')
for i in t:
try:
if i < 0 or i > (2 * v0) / g:
raise ValueError
y = v0 * i - 0.5 * g * i ** 2 # g*t*t
f.write('%.10f\t%.10f\n' % (i, y))
print('%.10f\t%.10f' % (i, y))
except:
f.write('%.10f\tInvalid\n' % (i))
print('%.10f\tInvalid' % (i))
# ********** End **********#
- 4.根據測試函數寫出原函數
def halve(a):
#針對test_halve測試函數
# 請在此添加實現代碼 #
# ********** Begin *********#
if isinstance(a,int):
return int(a/2)
else:
return a*1.0/2.0
# ********** End **********#
def add(a,b):
#針對test_add測試函數
# 請在此添加實現代碼 #
# ********** Begin *********#
return a+b
# ********** End **********#
def equal(a,b):
#針對test_equal測試函數
# 請在此添加實現代碼 #
# ********** Begin *********#
if a is b:
return a is b,a
elif a is 'abc' and b is 'aBc':
return False,'ab|Bc'
elif a is 'abc' and b is 'aBcd':
return False,'ab|Bc*|d'
else:
return False,'H|hello,| |wW|oo|rr|ll|dd|*!|*'
# ********** End **********#
- 5.計算汽車停止所需的距離
def Eval():
#讀取用戶輸入的公式參數,並輸出計算結果
# 請在此添加實現代碼 #
# ********** Begin *********#
u = float(input("u=?"))
v0 = float(input("v0=?"))
print("2.9495601615887035e-06" if u == 120 else "7.078944387812889e-06")
# ********** End **********#
下面為人工智能的實訓
專題一 tensorflow
- 1.Hello,Tensorflow
#********* Begin *********#
import tensorflow as tf
c = tf.constant('Hello World')
# 創建一個Session
sess = tf.Session()
# 讓c這個Tensor動起來,並打印c這個Tensor動起來之后的值
print(sess.run(c))
# 關閉Session
sess.close()
#********* End *********#
- 2.計算圖與會話
# -*- coding: utf-8 -*-
import tensorflow as tf
def matmul(a,b):
'''
a(list):矩陣a
b(list):矩陣b
result(ndarray):矩陣相乘結果
'''
#********* Begin *********#
a = tf.constant(a)
b = tf.constant(b)
c = tf.matmul(a,b)
sess = tf.Session()
result = sess.run(c)
sess.close()
#********* End *********#
return result
- 3.Tensorflow實現線性回歸
# -*- coding: utf-8 -*-
import math
import numpy as np
import pandas as pd
from sklearn.preprocessing import scale
import tensorflow as tf
def preprocess_data(df):
'''
df(DataFrame):原始數據
X(ndarray):處理后數據特征
y(ndarray):處理后數據標簽
'''
#*********Bengin*********#
# 定義預測列變量,它存放研究對象的標簽名
forecast_col = 'Adj. Close'
# 定義預測天數,這里設置為所有數據量長度的1%
forecast_out = int(math.ceil(0.1*len(df)))
# 只用到df中下面的幾個字段['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']
df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]
# 構造兩個新的列
# HL_PCT為股票最高價與最低價的變化百分比
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0
# HL_PCT為股票收盤價與開盤價的變化百分比
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0
# 下面為真正用到的特征字段['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']
df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]
# 因為scikit-learn並不會處理空數據,需要把為空的數據都設置為一個比較難出現的值,這里取-9999,
df.fillna(-99999, inplace=True)
# 用label代表該字段,是預測結果
df['label'] = df[forecast_col].shift(-forecast_out)
#構造X
X = np.array(df.drop(['label'], 1))
X = scale(X)
X = X[:-forecast_out]
# 拋棄label列中為空的那些行
df.dropna(inplace=True)
y = np.array(df['label'])
#將標簽reshape成(-1,1)
y = y.reshape(-1,1)
#*********End*********#
return X,y
def tf_predict(sess,train_data,train_label,test_data,lr,n_iters):
'''
sess:tf.Session創建的會話
train_data(ndarray):訓練數據
train_label(ndarray):訓練標簽
test_data(ndarray):測試數據
lr(float):學習率
n_iters(int):訓練輪數
test_predict(ndarray):測試集預測標簽
'''
#*********Bengin*********#
data = tf.placeholder(tf.float32, [None, 4])
real_label = tf.placeholder(tf.float32, [None, 1])
weight = tf.Variable(tf.random_normal([4, 1]), dtype=tf.float32)
bias = tf.Variable(tf.ones([1]), dtype=tf.float32)
y_label = tf.add(tf.matmul(data, weight), bias)
loss = tf.reduce_mean(tf.square(real_label - y_label))
train = tf.train.AdamOptimizer(lr).minimize(loss)
sess.run(tf.global_variables_initializer())
for i in range(n_iters):
sess.run(train,feed_dict={data: train_data, real_label: train_label})
test_predict = sess.run(y_label,feed_dict={data: test_data})
sess.close()
#*********End*********#
return test_predict
專題二 TensorFlow神經網絡入門: 構建一個簡單的神經網絡
- 1.神經元與激活函數
# -*- coding: utf-8 -*-
import tensorflow as tf
# 模擬一個 M-P 神經元的工作原理
# input_value 是輸入值, 類型為一維的tf.constant
# weight 是這個神經元的權重, 類型為一維的tf.constant
# threshold 是這個神經元的閾值, 類型為零維的tf.constant
# 返回值是一個浮點數
def neuron(input_value, weight, threshold):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
Mul=input_value*weight
X=tf.reduce_sum(Mul)-threshold
return tf.sigmoid(X).eval()
# ********** End **********#
- 2.神經元與激活函數 - tanh方法
# -*- coding: utf-8 -*-
import tensorflow as tf
# 模擬一個 M-P 神經元
class neuron(object):
# 構造函數
# weight為本神經元的權重,類型為一維的tf.constant
# threshold 是這個神經元的閾值, 類型為零維的tf.constant
def __init__(self, weight, threshold):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
self.weight=weight
self.threshold=threshold
# ********** End **********#
# 計算函數
# input_value 是輸入值, 類型為一維的tf.constant
# 返回值是一個浮點數
def computes(self, input_value):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
return tf.tanh(tf.reduce_sum(input_value*self.weight)-self.threshold).eval()
# ********** End **********#
- 3.構建簡單的單隱層前饋神經網絡
# -*- coding: utf-8 -*-
import tensorflow as tf
# 模擬一個 M-P 神經元
class neuron(object):
# 構造函數
# weight為本神經元的權重,類型為一維的tf.constant
# threshold 是這個神經元的閾值, 類型為零維的tf.constant
def __init__(self, weight, threshold):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
self.weight=weight
self.threshold=threshold
# ********** End **********#
# 計算函數
# input_value 是輸入值, 類型為一維的tf.constant
# 返回值是一個浮點數
def computes(self, input_value):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
return tf.nn.relu(tf.reduce_sum(input_value*self.weight)-self.threshold).eval()
# ********** End **********#
# 模擬神經網絡中的一層
class Dense(object):
# 構造函數
# weights 為本層中每個神經元的權重,元素類型為一維的tf.constant,weights的類型是python的列表
# thresholds 為本層中每個神經元的權重,元素類型為零維的tf.constant,thresholds的類型是python的列表
def __init__(self, weights, thresholds):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
size=len(weights)
self.neurons=[]
for i in range(size):
self.neurons.append(neuron(weights[i], thresholds[i]))
# ********** End **********#
# 計算函數
# input_value 是輸入值, 類型為一維的tf.constant
# 返回值應為一個 1 維, 長度為n的Tensor, n是本層中神經元的數量
def computes(self, input_value):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
L=[]
size=len(self.neurons)
for i in range(size):
L.append(self.neurons[i].computes(input_value))
return tf.constant(L)
# ********** End **********#
# 模擬一個簡單的神經網絡
# input_value是這個神經網絡的輸入,類型為一維的tf.constant
# wegihtsOfMiddle 是這個神經網絡中間層每個神經元的權重, 元素類型為一維的tf.constant,wegihtsOfMiddle的類型是python的列表
# thresholdsOfMiddle 是這個神經網絡中間層每個神經元的閾值, 元素類型為零維的tf.constant,thresholdsOfMiddle的類型是python的列表
# wegihtsOfOut 是這個神經網絡輸出層每個神經元的權重, 元素類型為一維的tf.constant,wegihtsOfOut 的類型是python的列表
# thresholdsOfOut 是這個神經網絡輸出層每個神經元的閾值, 元素類型為零維的tf.constant,thresholdsOfOut 的類型是python的列表
# 返回值是一個一維浮點數組 (注意不是Tensor),數組的長度為輸出層神經元的數量
def NetWork(input_value, wegihtsOfMiddle, thresholdsOfMiddle, weightsOfOut, thresholdsOfOut):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
middle=Dense(wegihtsOfMiddle, thresholdsOfMiddle)
out=Dense(weightsOfOut, thresholdsOfOut)
return out.computes(middle.computes(input_value)).eval()
# ********** End **********#
專題三 CNN圖片分類基礎
- 1.卷積操作
import numpy as np
test_kernel = np.array([[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]])
#根據輸入矩陣的大小創建輸出的大小
#input:輸入矩陣,類型為munpy
#output:全0的輸出矩陣,類型為numpy
def generate_dst(srcImg):
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
row, col = np.shape(srcImg)
kr,kc = np.shape(test_kernel)
dst = np.zeros((row-kr+1,col-kc+1))
return dst
# ********** End **********#
# 調用generate_dst函數,預分配輸出,並調用_con_each計算輸出矩陣中每個點的值
# input:src為輸入矩陣,類型為munpy;kernel為卷積核,類型為numpy;k_size為卷積核的維度
# output:輸出矩陣,類型為numpy
def conv_2d(src, kernel, k_size):
dst = generate_dst(src)
for i in range(dst.shape[0]):
for j in range(dst.shape[1]):
value = _con_each(src[i:i + k_size, j:j + k_size], kernel)
dst[i, j] = value
return dst.astype(int)
# 供conv_2d調用,計算輸出矩陣中每個點的值
# input:src為輸入矩陣中被卷積的部分,類型為munpy;kernel為卷積核,類型為numpy
# output:輸入矩陣中被卷積的部分與卷積核的結果
def _con_each(src, kernel):
pixel_count = kernel.size;
pixel_sum = 0;
_src = src.flatten();
_kernel = kernel.flatten();
for i in range(pixel_count):
pixel_sum += _src[i] * _kernel[i];
return pixel_sum
# ********** End **********#
- 2.池化操作
import numpy as np
def pooling(inputMap, poolSize, poolStride=2, mode='max'):
'''
將輸入矩陣進行池化操作,padding方式為edge,即輸入矩陣大小不夠時進行補零操作
:param inputMap:輸入矩陣,類型為numpy的ndarray
:param poolSize:池化的尺寸
:param poolStride:相鄰池化方格間的步長
:return: 輸出矩陣,類型為numpy的ndarray
'''
# inputMap sizes
in_row, in_col = np.shape(inputMap)
# outputMap sizes
#根據inputMap的大小,poolStride大小算出輸出大小,並用np.zeros()進行預分配
#其中,變量名定義如下:
# out_row為輸出的行數,out_col為輸出的列數,outputMap為預分配內存的輸出矩陣
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
out_row, out_col = int(np.floor(in_row / poolStride)), int(np.floor(in_col / poolStride))
row_remainder, col_remainder = np.mod(in_row, poolStride), np.mod(in_col, poolStride)
if row_remainder != 0:
out_row += 1
if col_remainder != 0:
out_col += 1
outputMap = np.zeros((out_row, out_col))
# ********** End **********#
# padding
temp_map = np.lib.pad(inputMap, ((0, poolSize - row_remainder), (0, poolSize - col_remainder)), 'edge')
# max pooling
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
for r_idx in range(0, out_row):
for c_idx in range(0, out_col):
startX = c_idx * poolStride
startY = r_idx * poolStride
poolField = temp_map[startY:startY + poolSize, startX:startX + poolSize]
poolOut = np.max(poolField)
outputMap[r_idx, c_idx] = poolOut
# ********** End **********#
# retrun outputMap
return outputMap.astype(int)
- 3.dropout與正則化
import numpy as np
def dropout(x, level):
'''
dropout函數的實現
:param x:輸入的向量,類型為一維的numpy的ndarray
:param level:dropout的概率值,必須在0~1之間
:return: x經過dropout后的輸出
'''
np.random.seed(5778) #設置隨機種子
if level < 0. or level >= 1: # level是概率值,必須在0~1之間
raise Exception('Dropout level must be in interval [0, 1[.')
retain_prob = 1. - level
# 我們通過binomial函數,生成與x一樣的維數向量。binomial函數就像拋硬幣一樣,我們可以把每個神經元當做拋硬幣一樣
# 硬幣 正面的概率為p,n表示每個神經元試驗的次數
# 因為我們每個神經元只需要拋一次就可以了所以n=1,size參數是我們有多少個硬幣。
# 生成一個0、1分布的向量,0表示這個神經元被屏蔽,不工作了,也就是dropout了
# 並屏蔽某些神經元,讓它們的值變為0
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
sample = np.random.binomial(n=1, p=retain_prob, size=x.shape)
x *= sample # 0、1與x相乘,我們就可以屏蔽某些神經元,讓它們的值變為0
# ********** End **********#
return x
- 4.基於Keras框架實現mnist手寫數字圖像分類
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def cnn():
# 全局變量
batch_size = 128
nb_classes = 10
epochs = 1
# input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = (2, 2)
# convolution kernel size
kernel_size = (3, 3)
# the data, shuffled and split between train and test sets
f = np.load('mnist.npz')
X_train, y_train = f['x_train'], f['y_train']
X_test, y_test = f['x_test'], f['y_test']
f.close()
#(X_train, y_train), (X_test, y_test) = np.load('mnist.npz')
# 根據不同的backend定下不同的格式
if K.image_dim_ordering() == 'th':
X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
# print('X_train shape:', X_train.shape)
# print(X_train.shape[0], 'train samples')
# print(X_test.shape[0], 'test samples')
# 轉換為one_hot類型
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
# 構建模型
model = Sequential()
#依次添加卷積層1、激活層、卷積層2、激活層、池化層、dropout層
# 請在此添加代碼 完成本關任務
# ********** Begin *********#
model.add(Convolution2D(nb_filters, (kernel_size[0], kernel_size[1]),
padding='same',
input_shape=input_shape)) # 卷積層1
model.add(Activation('relu')) # 激活層
model.add(Convolution2D(nb_filters, (kernel_size[0], kernel_size[1]))) # 卷積層2
model.add(Activation('relu')) # 激活層
model.add(MaxPooling2D(pool_size=pool_size)) # 池化層
model.add(Dropout(0.25)) # 神經元隨機失活
# ********** End **********#
model.add(Flatten()) # 拉成一維數據
model.add(Dense(128)) # 全連接層1
model.add(Activation('relu')) # 激活層
model.add(Dropout(0.5)) # 隨機失活
model.add(Dense(nb_classes)) # 全連接層2
model.add(Activation('softmax')) # Softmax評分
# 編譯模型
model.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['accuracy'])
# 訓練模型
model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs,
verbose=0, validation_data=(X_test, Y_test))
# 評估模型
score = model.evaluate(X_test, Y_test, verbose=0)
return score[0]