除了最后一题需要网速特好之外,其他都应该不会超时...
- 仅供参考,希望大家自己先做,不会了在参考答案(其实我也不会,哈哈,有些是踩点过了.利用题目的漏洞)
实验课一
专题一 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]