Skip to content

Commit 48b8ab4

Browse files
authored
Merge pull request #109 from sdpython/fst
Use f strings in more places
2 parents 188d593 + 9bbbeb1 commit 48b8ab4

25 files changed

+107
-83
lines changed

_unittests/ut_timeseries/test_preprocessing_timeseries.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,22 @@ def test_base_parameters_split0(self):
2626
self.assertEqualArray(nx, ppx)
2727
self.assertEqualArray(ny, ppy)
2828

29+
def test_base_parameters_split0_weight(self):
30+
X = numpy.arange(20).reshape((10, 2))
31+
y = numpy.arange(10) * 100
32+
bs = BaseTimeSeries(past=2)
33+
nx, ny, _ = build_ts_X_y(bs, X, y)
34+
weights = numpy.ones((nx.shape[0], ), dtype=nx.dtype)
35+
for d in range(0, 5):
36+
proc = TimeSeriesDifference(d)
37+
proc.fit(nx, ny, weights)
38+
px, py = proc.transform(nx, ny)
39+
self.assertEqualArray(px[-1, :], nx[-1, :])
40+
rev = proc.get_fct_inv()
41+
ppx, ppy = rev.transform(px, py)
42+
self.assertEqualArray(nx, ppx)
43+
self.assertEqualArray(ny, ppy)
44+
2945

3046
if __name__ == "__main__":
3147
unittest.main()

mlinsights/helpers/parameters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def format_value(v):
1212
@param v a string
1313
@return a string
1414
"""
15-
return ("'{0}'".format(v.replace("'", "\\'"))
15+
return (v.replace("'", "\\'")
1616
if isinstance(v, str) else f"{v}")
1717

1818

mlinsights/helpers/pipeline.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,5 +203,6 @@ def decision_function(self, X, *args, **kwargs):
203203
try:
204204
setattr(model, k, MethodType(new_methods[k], model))
205205
except AttributeError: # pragma: no cover
206-
warnings.warn("Unable to overwrite method '{}' for class "
207-
"{}.".format(k, type(model)))
206+
warnings.warn(
207+
f"Unable to overwrite method {k!r} for class "
208+
f"{type(model)!r}.")

mlinsights/mlbatch/pipeline_cache.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,12 @@ def _get_fit_params_steps(self, fit_params):
5454
if '__' not in pname:
5555
if not isinstance(pval, dict):
5656
raise ValueError( # pragma: no cover
57-
"For scikit-learn < 0.23, "
58-
"Pipeline.fit does not accept the {} parameter. "
59-
"You can pass parameters to specific steps of your "
60-
"pipeline using the stepname__parameter format, e.g. "
61-
"`Pipeline.fit(X, y, logisticregression__sample_weight"
62-
"=sample_weight)`.".format(pname))
57+
f"For scikit-learn < 0.23, "
58+
f"Pipeline.fit does not accept the {pname} parameter. "
59+
f"You can pass parameters to specific steps of your "
60+
f"pipeline using the stepname__parameter format, e.g. "
61+
f"`Pipeline.fit(X, y, logisticregression__sample_weight"
62+
f"=sample_weight)`.")
6363
else:
6464
fit_params_steps[pname].update(pval)
6565
else:

mlinsights/mlmodel/_kmeans_022.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,9 @@ def _assign_labels_csr(X, sample_weight, x_squared_norms, centers,
6363
if (distances is not None and
6464
distances.shape != (X.shape[0], )):
6565
raise ValueError( # pragma: no cover
66-
"Dimension mismatch for distance got {}, expecting {}."
67-
"".format(distances.shape, (X.shape[0], centers.shape[0])))
66+
f"Dimension mismatch for distance got "
67+
f"{distances.shape}, expecting "
68+
f"{(X.shape[0], centers.shape[0])}.")
6869
n_clusters = centers.shape[0]
6970
n_samples = X.shape[0]
7071
store_distances = 0

mlinsights/mlmodel/_kmeans_constraint_.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -550,9 +550,9 @@ def _constraint_kmeans_weights(X, labels, sample_weight, centers, inertia, it,
550550
X, centers, sw, weights, labels, total_inertia)
551551
if numpy.isnan(inertia):
552552
raise RuntimeError( # pragma: no cover
553-
"nanNobs={} Nclus={}\ninertia={}\nweights={}\ndiff={}\nlabels={}".format(
554-
X.shape[0], centers.shape[0], inertia, weights, diff,
555-
set(labels)))
553+
f"nanNobs={X.shape[0]} Nclus={centers.shape[0]}\n"
554+
f"inertia={inertia}\nweights={weights}\ndiff={diff}\n"
555+
f"labels={set(labels)}")
556556

557557
# best option so far?
558558
if best_inertia is None or inertia < best_inertia:

mlinsights/mlmodel/categories_to_integers.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -152,8 +152,8 @@ def transform(v, vec):
152152
lv = lv[:20]
153153
lv.append("...")
154154
raise ValueError( # pragma: no cover
155-
"Unable to find category value '{0}' type(v)={2} among\n{1}".format(
156-
v, "\n".join(lv), type(v)))
155+
"Unable to find category value %r type(v)=%r "
156+
"among\n%s" % (v, type(v), '\n'.join(lv)))
157157
return numpy.nan
158158

159159
sch, pos, new_vector = self._schema
@@ -184,8 +184,9 @@ def transform(v, vec):
184184
lv = lv[:20]
185185
lv.append("...")
186186
raise ValueError( # pragma: no cover
187-
"unable to find category value '{0}': '{1}' type(v)={3} among\n{2}".format(
188-
k, v, "\n".join(lv), type(v)))
187+
"Unable to find category value %r: %r "
188+
"type(v)=%r among\n%s" % (
189+
k, v, type(v), '\n'.join(lv)))
189190
else:
190191
p = pos[k] + vec[k][v]
191192
res[i, p] = 1.0

mlinsights/mlmodel/decision_tree_logreg.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -189,8 +189,9 @@ def fit_improve(self, dtlr, total_N, X, y, sample_weight):
189189
# The classifier is not linear and cannot be improved.
190190
if dtlr.fit_improve_algo == 'intercept_sort_always': # pragma: no cover
191191
raise RuntimeError(
192-
"The model is not linear ({}), "
193-
"intercept cannot be improved.".format(self.estimator.__class__.__name__))
192+
f"The model is not linear "
193+
f"({self.estimator.__class__.__name__!r}), "
194+
f"intercept cannot be improved.")
194195
return prob
195196

196197
above = prob[:, 1] > self.threshold
@@ -368,8 +369,8 @@ def __init__(self, estimator=None,
368369

369370
if self.fit_improve_algo not in DecisionTreeLogisticRegression._fit_improve_algo_values:
370371
raise ValueError(
371-
"fit_improve_algo='{}' not in {}".format(
372-
self.fit_improve_algo, DecisionTreeLogisticRegression._fit_improve_algo_values))
372+
f"fit_improve_algo={self.fit_improve_algo!r} "
373+
f"not in {DecisionTreeLogisticRegression._fit_improve_algo_values}.")
373374

374375
def fit(self, X, y, sample_weight=None):
375376
"""
@@ -401,8 +402,8 @@ def fit(self, X, y, sample_weight=None):
401402
self.classes_ = numpy.array(sorted(set(y)))
402403
if len(self.classes_) != 2:
403404
raise RuntimeError(
404-
"The model only supports binary classification but labels are "
405-
"{}.".format(self.classes_))
405+
f"The model only supports binary classification but labels are "
406+
f"{self.classes_}.")
406407

407408
if self.strategy == 'parallel':
408409
return self._fit_parallel(X, y, sample_weight)

mlinsights/mlmodel/kmeans_l1.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -617,9 +617,10 @@ def _fit_l1(self, X, y=None, sample_weight=None):
617617
distinct_clusters = len(set(best_labels))
618618
if distinct_clusters < self.n_clusters:
619619
warnings.warn( # pragma no cover
620-
"Number of distinct clusters ({}) found smaller than "
621-
"n_clusters ({}). Possibly due to duplicate points "
622-
"in X.".format(distinct_clusters, self.n_clusters),
620+
f"Number of distinct clusters ({distinct_clusters}) "
621+
f"found smaller than "
622+
f"n_clusters ({self.n_clusters}). Possibly "
623+
f"due to duplicate points in X.",
623624
ConvergenceWarning, stacklevel=2)
624625

625626
self.cluster_centers_ = best_centers

mlinsights/mlmodel/ml_featurizer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ def model_featurizer(model, **params):
4343
return model_featurizer_torch(model, **params)
4444
tried.append("torch")
4545
raise FeaturizerTypeError( # pragma no cover
46-
"Unable to process type '{0}', allowed:\n{1}".format(
47-
type(model), "\n".join(sorted(str(_) for _ in tried))))
46+
"Unable to process type %r, allowed:\n%s" % (
47+
type(model), '\n'.join(sorted(str(_) for _ in tried))))
4848

4949

5050
def is_vector(X):

0 commit comments

Comments
 (0)