实现“多项式基函数”以及“高斯基函数”
其中以及训练集的x的范围在0-25之间
import numpy as np
def identity_basis(x):
# 将形状从(N,)转换成(N,1)
ret = np.expand_dims(x, axis=1)
return ret
def multinomial_basis(x, feature_num=10):
x = np.expand_dims(x, axis=1) # shape(N, 1)
feat = [x] # 将数组看作一个元素装入list,此时feat大小为1
for i in range(2, feature_num + 1):
feat.append(x ** i) # 加入数组的2次幂--->10次幂
ret = np.concatenate(feat, axis=1) # feat中每个元素都是一个数组,将数组在行上拼接
return ret
def gaussian_basis(x, feature_num=10):
centers = np.linspace(0, 25, feature_num) # (10,)
width = 1.0 * (centers[1] - centers[0])
x = np.expand_dims(x, axis=1)
x = np.concatenate([x] * feature_num, axis=1) # x看作一个元素装入list,扩展成10个x元素,在行上拼接,变成(300,10)
out = (x - centers) / width
ret = np.exp(-0.5 * out ** 2)
return ret
def readdata(filename):
# filename = './train.txt'
with open(filename, "r") as f: # 打开文件
data = f.readlines() # 读取文
X = []
Y = []
for line in data:
list = line.split()
X.append(float(list[0]))
Y.append(float(list[1]))
X = np.array(X)
Y = np.array(Y)
return X, Y
filename = './train.txt'
X, Y = readdata(filename)
ret = gaussian_basis(X)