本文整理汇总了Python中numpy.loadtxt方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.loadtxt方法的具体用法?Python numpy.loadtxt怎么用?Python numpy.loadtxt使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.loadtxt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: classify_1nn
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def classify_1nn(data_train, data_test):
'''
Classification using 1NN
Inputs: data_train, data_test: train and test csv file path
Outputs: yprediction and accuracy
'''
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
data = {'src': np.loadtxt(data_train, delimiter=','),
'tar': np.loadtxt(data_test, delimiter=','),
}
Xs, Ys, Xt, Yt = data['src'][:, :-1], data['src'][:, -
1], data['tar'][:, :-1], data['tar'][:, -1]
Xs = StandardScaler(with_mean=0, with_std=1).fit_transform(Xs)
Xt = StandardScaler(with_mean=0, with_std=1).fit_transform(Xt)
clf = KNeighborsClassifier(n_neighbors=1)
clf.fit(Xs, Ys)
ypred = clf.predict(Xt)
acc = accuracy_score(y_true=Yt, y_pred=ypred)
print('Acc: {:.4f}'.format(acc))
return ypred, acc
示例2: breastcancer_cont
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def breastcancer_cont(replication=2):
f = open(path + "breast_cancer_wisconsin_cont.txt", "r")
data = np.loadtxt(f, delimiter=",", dtype=np.string0)
x_train = np.array(data[:, range(0, 9)])
y_train = np.array(data[:, 9])
for j in range(replication - 1):
x_train = np.vstack([x_train, data[:, range(0, 9)]])
y_train = np.hstack([y_train, data[:, 9]])
x_train = np.array(x_train, dtype=np.float)
f = open(path + "breast_cancer_wisconsin_cont_test.txt")
data = np.loadtxt(f, delimiter=",", dtype=np.string0)
x_test = np.array(data[:, range(0, 9)])
y_test = np.array(data[:, 9])
for j in range(replication - 1):
x_test = np.vstack([x_test, data[:, range(0, 9)]])
y_test = np.hstack([y_test, data[:, 9]])
x_test = np.array(x_test, dtype=np.float)
return x_train, y_train, x_test, y_test
示例3: breastcancer_disc
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def breastcancer_disc(replication=2):
f = open(path + "breast_cancer_wisconsin_disc.txt")
data = np.loadtxt(f, delimiter=",")
x_train = data[:, range(1, 10)]
y_train = data[:, 10]
for j in range(replication - 1):
x_train = np.vstack([x_train, data[:, range(1, 10)]])
y_train = np.hstack([y_train, data[:, 10]])
f = open(path + "breast_cancer_wisconsin_disc_test.txt")
data = np.loadtxt(f, delimiter=",")
x_test = data[:, range(1, 10)]
y_test = data[:, 10]
for j in range(replication - 1):
x_test = np.vstack([x_test, data[:, range(1, 10)]])
y_test = np.hstack([y_test, data[:, 10]])
return x_train, y_train, x_test, y_test
示例4: iris
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def iris(replication=2):
f = open(path + "iris.txt")
data = np.loadtxt(f, delimiter=",", dtype=np.string0)
x_train = np.array(data[:, range(0, 4)], dtype=np.float)
y_train = data[:, 4]
for j in range(replication - 1):
x_train = np.vstack([x_train, data[:, range(0, 4)]])
y_train = np.hstack([y_train, data[:, 4]])
x_train = np.array(x_train, dtype=np.float)
f = open(path + "iris_test.txt")
data = np.loadtxt(f, delimiter=",", dtype=np.string0)
x_test = np.array(data[:, range(0, 4)], dtype=np.float)
y_test = data[:, 4]
for j in range(replication - 1):
x_test = np.vstack([x_test, data[:, range(0, 4)]])
y_test = np.hstack([y_test, data[:, 4]])
x_test = np.array(x_test, dtype=np.float)
return x_train, y_train, x_test, y_test
示例5: regression_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def regression_data():
f = open(path + "regression_data1.txt")
data = np.loadtxt(f, delimiter=",")
x1 = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
y1 = data[:, 1]
f = open(path + "regression_data2.txt")
data = np.loadtxt(f, delimiter=",")
x2 = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
y2 = data[:, 1]
x1 = np.vstack((x1, x2))
y1 = np.hstack((y1, y2))
f = open(path + "regression_data_test1.txt")
data = np.loadtxt(f, delimiter=",")
x1_test = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
y1_test = data[:, 1]
f = open(path + "regression_data_test2.txt")
data = np.loadtxt(f, delimiter=",")
x2_test = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
y2_test = data[:, 1]
x1_test = np.vstack((x1_test, x2_test))
y1_test = np.hstack((y1_test, y2_test))
return x1, y1, x1_test, y1_test
示例6: collect_room
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def collect_room(building_name, room_name):
room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
room_name, 'Annotations')
files = glob.glob1(room_dir, '*.txt')
files = sorted(files, key=lambda s: s.lower())
vertexs = []; colors = [];
for f in files:
file_name = os.path.join(room_dir, f)
logging.info(' %s', file_name)
a = np.loadtxt(file_name)
vertex = a[:,:3]*1.
color = a[:,3:]*1
color = color.astype(np.uint8)
vertexs.append(vertex)
colors.append(color)
files = [f.split('.')[0] for f in files]
out = {'vertexs': vertexs, 'colors': colors, 'names': files}
return out
示例7: print_mutation
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def print_mutation(hyp, results, bucket=''):
# Print mutation results to evolve.txt (for use with train.py --evolve)
a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
c = '%10.3g' * len(results) % results # results (P, R, mAP, F1, test_loss)
print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
if bucket:
os.system('gsutil cp gs://%s/evolve.txt .' % bucket) # download evolve.txt
with open('evolve.txt', 'a') as f: # append result
f.write(c + b + '\n')
x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
np.savetxt('evolve.txt', x[np.argsort(-fitness(x))], '%10.3g') # save sort by fitness
if bucket:
os.system('gsutil cp evolve.txt gs://%s' % bucket) # upload evolve.txt
示例8: plot_evolution_results
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def plot_evolution_results(hyp): # from utils.utils import *; plot_evolution_results(hyp)
# Plot hyperparameter evolution results in evolve.txt
x = np.loadtxt('evolve.txt', ndmin=2)
f = fitness(x)
weights = (f - f.min()) ** 2 # for weighted results
fig = plt.figure(figsize=(12, 10))
matplotlib.rc('font', **{'size': 8})
for i, (k, v) in enumerate(hyp.items()):
y = x[:, i + 5]
# mu = (y * weights).sum() / weights.sum() # best weighted result
mu = y[f.argmax()] # best single result
plt.subplot(4, 5, i + 1)
plt.plot(mu, f.max(), 'o', markersize=10)
plt.plot(y, f, '.')
plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
print('%15s: %.3g' % (k, mu))
fig.tight_layout()
plt.savefig('evolve.png', dpi=200)
示例9: plot_results
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def plot_results(start=0, stop=0): # from utils.utils import *; plot_results()
# Plot training results files 'results*.txt'
fig, ax = plt.subplots(2, 5, figsize=(14, 7))
ax = ax.ravel()
s = ['GIoU', 'Objectness', 'Classification', 'Precision', 'Recall',
'val GIoU', 'val Objectness', 'val Classification', 'mAP', 'F1']
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
for i in range(10):
y = results[i, x]
if i in [0, 1, 2, 5, 6, 7]:
y[y == 0] = np.nan # dont show zero loss values
ax[i].plot(x, y, marker='.', label=f.replace('.txt', ''))
ax[i].set_title(s[i])
if i in [5, 6, 7]: # share train and val loss y axes
ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
fig.tight_layout()
ax[1].legend()
fig.savefig('results.png', dpi=200)
示例10: plot_results_overlay
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def plot_results_overlay(start=0, stop=0): # from utils.utils import *; plot_results_overlay()
# Plot training results files 'results*.txt', overlaying train and val losses
s = ['train', 'train', 'train', 'Precision', 'mAP', 'val', 'val', 'val', 'Recall', 'F1'] # legends
t = ['GIoU', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
fig, ax = plt.subplots(1, 5, figsize=(14, 3.5))
ax = ax.ravel()
for i in range(5):
for j in [i, i + 5]:
y = results[j, x]
if i in [0, 1, 2]:
y[y == 0] = np.nan # dont show zero loss values
ax[i].plot(x, y, marker='.', label=s[j])
ax[i].set_title(t[i])
ax[i].legend()
ax[i].set_ylabel(f) if i == 0 else None # add filename
fig.tight_layout()
fig.savefig(f.replace('.txt', '.png'), dpi=200)
示例11: test_2x3
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def test_2x3(self):
# Loading the water depth map
dat = loadtxt('data/WaterDepth1.dat')
X, Y = meshgrid(linspace(0., 1000., 50), linspace(0., 1000., 50))
depth = array(zip(X.flatten(), Y.flatten(), dat.flatten()))
borders = array([[200, 200], [150, 500], [200, 800], [600, 900], [700, 700], [900, 500], [800, 200], [500, 100], [200, 200]])
baseline = array([[587.5, 223.07692308], [525., 346.15384615], [837.5, 530.76923077], [525., 530.76923077], [525., 838.46153846], [837.5, 469.23076923]])
wt_desc = WTDescFromWTG('data/V80-2MW-offshore.wtg').wt_desc
wt_layout = GenericWindFarmTurbineLayout([WTPC(wt_desc=wt_desc, position=pos) for pos in baseline])
t = Topfarm(
baseline_layout = wt_layout,
borders = borders,
depth_map = depth,
dist_WT_D = 5.0,
distribution='spiral',
wind_speeds=[4., 8., 20.],
wind_directions=linspace(0., 360., 36)[:-1]
)
t.run()
self.fail('make save function')
t.save()
示例12: load_csv
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def load_csv(path):
"""Load data from a CSV file.
Args:
path (str): A path to the CSV format file containing data.
dense (boolean): An optional variable indicating if the return matrix
should be dense. By default, it is false.
Returns:
Data matrix X and target vector y
"""
with open(path) as f:
line = f.readline().strip()
X = np.loadtxt(path, delimiter=',',
skiprows=0 if is_number(line.split(',')[0]) else 1)
y = np.array(X[:, 0]).flatten()
X = X[:, 1:]
return X, y
示例13: calcfbetaInput
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def calcfbetaInput(self):
# table 17 in Leinert et al. (1998)
# Zodiacal Light brightness function of solar LON (rows) and LAT (columns)
# values given in W m−2 sr−1 μm−1 for a wavelength of 500 nm
path = os.path.split(inspect.getfile(self.__class__))[0]
Izod = np.loadtxt(os.path.join(path, 'Leinert98_table17.txt'))*1e-8 # W/m2/sr/um
# create data point coordinates
lon_pts = np.array([0., 5, 10, 15, 20, 25, 30, 35, 40, 45, 60, 75, 90,
105, 120, 135, 150, 165, 180]) # deg
lat_pts = np.array([0., 5, 10, 15, 20, 25, 30, 45, 60, 75, 90]) # deg
y_pts, x_pts = np.meshgrid(lat_pts, lon_pts)
points = np.array(list(zip(np.concatenate(x_pts), np.concatenate(y_pts))))
# create data values, normalized by (90,0) value
z = Izod/Izod[12,0]
values = z.reshape(z.size)
return points, values
示例14: get_datasets
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def get_datasets(args):
cinfo = None
if args.categoryfile:
#categories = numpy.loadtxt(args.categoryfile, dtype=str, delimiter="\n").tolist()
categories = [line.rstrip('\n') for line in open(args.categoryfile)]
categories.sort()
c_to_idx = {categories[i]: i for i in range(len(categories))}
cinfo = (categories, c_to_idx)
if args.dataset_type == 'modelnet':
transform = torchvision.transforms.Compose([\
ptlk.data.transforms.Mesh2Points(),\
ptlk.data.transforms.OnUnitCube(),\
])
testdata = ptlk.data.datasets.ModelNet(args.dataset_path, train=0, transform=transform, classinfo=cinfo)
return testdata
示例15: test_values_of_indicators
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import loadtxt [as 别名]
def test_values_of_indicators(self):
l = [
(GD, "gd"),
(IGD, "igd")
]
folder = os.path.join(get_pymoo(), "tests", "performance_indicator")
pf = np.loadtxt(os.path.join(folder, "performance_indicators.pf"))
for indicator, ext in l:
for i in range(1, 5):
F = np.loadtxt(os.path.join(folder, "performance_indicators_%s.f" % i))
val = indicator(pf).calc(F)
correct = np.loadtxt(os.path.join(folder, "performance_indicators_%s.%s" % (i, ext)))
self.assertTrue(correct == val)