Showing preview only (769K chars total). Download the full file or copy to clipboard to get everything.
Repository: rushter/MLAlgorithms
Branch: master
Commit: 8fb8bb4282f3
Files: 86
Total size: 45.6 MB
Directory structure:
gitextract_vmd1djyc/
├── .github/
│ └── workflows/
│ └── python-app.yml
├── .gitignore
├── AUTHORS
├── Dockerfile
├── LICENSE
├── MANIFEST.in
├── README.md
├── examples/
│ ├── __init__.py
│ ├── gaussian_mixture.py
│ ├── gbm.py
│ ├── kmeans.py
│ ├── linear_models.py
│ ├── naive_bayes.py
│ ├── nearest_neighbors.py
│ ├── nnet_convnet_mnist.py
│ ├── nnet_mlp.py
│ ├── nnet_rnn_binary_add.py
│ ├── nnet_rnn_text_generation.py
│ ├── pca.py
│ ├── random_forest.py
│ ├── rbm.py
│ ├── rl_deep_q_learning.py
│ ├── svm.py
│ └── t-sne.py
├── mla/
│ ├── __init__.py
│ ├── base/
│ │ ├── __init__.py
│ │ └── base.py
│ ├── datasets/
│ │ ├── __init__.py
│ │ ├── base.py
│ │ └── data/
│ │ ├── mnist/
│ │ │ ├── t10k-images-idx3-ubyte
│ │ │ ├── t10k-labels-idx1-ubyte
│ │ │ ├── train-images-idx3-ubyte
│ │ │ └── train-labels-idx1-ubyte
│ │ └── nietzsche.txt
│ ├── ensemble/
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── gbm.py
│ │ ├── random_forest.py
│ │ └── tree.py
│ ├── fm.py
│ ├── gaussian_mixture.py
│ ├── kmeans.py
│ ├── knn.py
│ ├── linear_models.py
│ ├── metrics/
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── distance.py
│ │ ├── metrics.py
│ │ └── tests/
│ │ ├── __init__.py
│ │ └── test_metrics.py
│ ├── naive_bayes.py
│ ├── neuralnet/
│ │ ├── __init__.py
│ │ ├── activations.py
│ │ ├── constraints.py
│ │ ├── initializations.py
│ │ ├── layers/
│ │ │ ├── __init__.py
│ │ │ ├── basic.py
│ │ │ ├── convnet.py
│ │ │ ├── normalization.py
│ │ │ └── recurrent/
│ │ │ ├── __init__.py
│ │ │ ├── lstm.py
│ │ │ └── rnn.py
│ │ ├── loss.py
│ │ ├── nnet.py
│ │ ├── optimizers.py
│ │ ├── parameters.py
│ │ ├── regularizers.py
│ │ └── tests/
│ │ ├── test_activations.py
│ │ └── test_optimizers.py
│ ├── pca.py
│ ├── rbm.py
│ ├── rl/
│ │ ├── __init__.py
│ │ └── dqn.py
│ ├── svm/
│ │ ├── __init__.py
│ │ ├── kernerls.py
│ │ └── svm.py
│ ├── tests/
│ │ ├── __init__.py
│ │ ├── test_classification_accuracy.py
│ │ ├── test_reduction.py
│ │ └── test_regression_accuracy.py
│ ├── tsne.py
│ └── utils/
│ ├── __init__.py
│ └── main.py
├── requirements.txt
├── setup.cfg
└── setup.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/python-app.yml
================================================
name: Tests
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
timeout-minutes: 5
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v4
with:
python-version: 3.12
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
pip install -r requirements.txt
- name: Test with pytest
run: |
pytest
================================================
FILE: .gitignore
================================================
*.pyc
build/
dist/
mla.egg-info/
.cache
*.swp
.idea
================================================
FILE: AUTHORS
================================================
Artem Golubin <me@rushter.com>
Anebi Agbo
Convex Path
James Chevalier
Jiancheng
KaiMin Lai
Nguyễn Tuấn
Nicolas Hug
Xiaochun Ma
Yiran Sheng
brady salz
junwang007
keineahnung2345
lucaskolstad
vincent tang
xq5he
LanderTome
therickli
Andrew Melnik
================================================
FILE: Dockerfile
================================================
FROM python:3
RUN mkdir -p /var/app
WORKDIR /var/app
COPY . /var/app
# install scipy & numpy
# install required packages
RUN pip install scipy numpy && \
pip install .
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2016-2020 Artem Golubin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: MANIFEST.in
================================================
recursive-include mla/datasets/data *
================================================
FILE: README.md
================================================
# Machine learning algorithms
A collection of minimal and clean implementations of machine learning algorithms.
### Why?
This project is targeting people who want to learn internals of ml algorithms or implement them from scratch.
The code is much easier to follow than the optimized libraries and easier to play with.
All algorithms are implemented in Python, using numpy, scipy and autograd.
### Implemented:
* [Deep learning (MLP, CNN, RNN, LSTM)](mla/neuralnet)
* [Linear regression, logistic regression](mla/linear_models.py)
* [Random Forests](mla/ensemble/random_forest.py)
* [Support vector machine (SVM) with kernels (Linear, Poly, RBF)](mla/svm)
* [K-Means](mla/kmeans.py)
* [Gaussian Mixture Model](mla/gaussian_mixture.py)
* [K-nearest neighbors](mla/knn.py)
* [Naive bayes](mla/naive_bayes.py)
* [Principal component analysis (PCA)](mla/pca.py)
* [Factorization machines](mla/fm.py)
* [Restricted Boltzmann machine (RBM)](mla/rbm.py)
* [t-Distributed Stochastic Neighbor Embedding (t-SNE)](mla/tsne.py)
* [Gradient Boosting trees (also known as GBDT, GBRT, GBM, XGBoost)](mla/ensemble/gbm.py)
* [Reinforcement learning (Deep Q learning)](mla/rl)
### Installation
```sh
git clone https://github.com/rushter/MLAlgorithms
cd MLAlgorithms
pip install scipy numpy
python setup.py develop
```
### How to run examples without installation
```sh
cd MLAlgorithms
python -m examples.linear_models
```
### How to run examples within Docker
```sh
cd MLAlgorithms
docker build -t mlalgorithms .
docker run --rm -it mlalgorithms bash
python -m examples.linear_models
```
### Contributing
Your contributions are always welcome!
Feel free to improve existing code, documentation or implement new algorithm.
Please open an issue to propose your changes if they are big enough.
================================================
FILE: examples/__init__.py
================================================
# coding: utf-8
================================================
FILE: examples/gaussian_mixture.py
================================================
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from mla.kmeans import KMeans
from mla.gaussian_mixture import GaussianMixture
random.seed(1)
np.random.seed(6)
def make_clusters(skew=True, *arg, **kwargs):
X, y = datasets.make_blobs(*arg, **kwargs)
if skew:
nrow = X.shape[1]
for i in np.unique(y):
X[y == i] = X[y == i].dot(np.random.random((nrow, nrow)) - 0.5)
return X, y
def KMeans_and_GMM(K):
COLOR = "bgrcmyk"
X, y = make_clusters(skew=True, n_samples=1500, centers=K)
_, axes = plt.subplots(1, 3)
# Ground Truth
axes[0].scatter(X[:, 0], X[:, 1], c=[COLOR[int(assignment)] for assignment in y])
axes[0].set_title("Ground Truth")
# KMeans
kmeans = KMeans(K=K, init="++")
kmeans.fit(X)
kmeans.predict()
axes[1].set_title("KMeans")
kmeans.plot(ax=axes[1], holdon=True)
# Gaussian Mixture
gmm = GaussianMixture(K=K, init="kmeans")
gmm.fit(X)
axes[2].set_title("Gaussian Mixture")
gmm.plot(ax=axes[2])
if __name__ == "__main__":
KMeans_and_GMM(4)
================================================
FILE: examples/gbm.py
================================================
import logging
from sklearn.datasets import make_classification
from sklearn.datasets import make_regression
from sklearn.metrics import roc_auc_score
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from mla.ensemble.gbm import GradientBoostingClassifier, GradientBoostingRegressor
from mla.metrics.metrics import mean_squared_error
logging.basicConfig(level=logging.DEBUG)
def classification():
# Generate a random binary classification problem.
X, y = make_classification(
n_samples=350,
n_features=15,
n_informative=10,
random_state=1111,
n_classes=2,
class_sep=1.0,
n_redundant=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.15, random_state=1111
)
model = GradientBoostingClassifier(
n_estimators=50, max_depth=4, max_features=8, learning_rate=0.1
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(predictions)
print(predictions.min())
print(predictions.max())
print("classification, roc auc score: %s" % roc_auc_score(y_test, predictions))
def regression():
# Generate a random regression problem
X, y = make_regression(
n_samples=500,
n_features=5,
n_informative=5,
n_targets=1,
noise=0.05,
random_state=1111,
bias=0.5,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.1, random_state=1111
)
model = GradientBoostingRegressor(n_estimators=25, max_depth=5, max_features=3)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(
"regression, mse: %s"
% mean_squared_error(y_test.flatten(), predictions.flatten())
)
if __name__ == "__main__":
classification()
# regression()
================================================
FILE: examples/kmeans.py
================================================
import numpy as np
from sklearn.datasets import make_blobs
from mla.kmeans import KMeans
def kmeans_example(plot=False):
X, y = make_blobs(
centers=4, n_samples=500, n_features=2, shuffle=True, random_state=42
)
clusters = len(np.unique(y))
k = KMeans(K=clusters, max_iters=150, init="++")
k.fit(X)
k.predict()
if plot:
k.plot()
if __name__ == "__main__":
kmeans_example(plot=True)
================================================
FILE: examples/linear_models.py
================================================
import logging
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from sklearn.datasets import make_classification
from sklearn.datasets import make_regression
from mla.linear_models import LinearRegression, LogisticRegression
from mla.metrics.metrics import mean_squared_error, accuracy
# Change to DEBUG to see convergence
logging.basicConfig(level=logging.ERROR)
def regression():
# Generate a random regression problem
X, y = make_regression(
n_samples=10000,
n_features=100,
n_informative=75,
n_targets=1,
noise=0.05,
random_state=1111,
bias=0.5,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=1111
)
model = LinearRegression(lr=0.01, max_iters=2000, penalty="l2", C=0.03)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("regression mse", mean_squared_error(y_test, predictions))
def classification():
# Generate a random binary classification problem.
X, y = make_classification(
n_samples=1000,
n_features=100,
n_informative=75,
random_state=1111,
n_classes=2,
class_sep=2.5,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.1, random_state=1111
)
model = LogisticRegression(lr=0.01, max_iters=500, penalty="l1", C=0.01)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("classification accuracy", accuracy(y_test, predictions))
if __name__ == "__main__":
regression()
classification()
================================================
FILE: examples/naive_bayes.py
================================================
from sklearn.datasets import make_classification
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from mla.naive_bayes import NaiveBayesClassifier
def classification():
# Generate a random binary classification problem.
X, y = make_classification(
n_samples=1000,
n_features=10,
n_informative=10,
random_state=1111,
n_classes=2,
class_sep=2.5,
n_redundant=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.1, random_state=1111
)
model = NaiveBayesClassifier()
model.fit(X_train, y_train)
predictions = model.predict(X_test)[:, 1]
print("classification accuracy", roc_auc_score(y_test, predictions))
if __name__ == "__main__":
classification()
================================================
FILE: examples/nearest_neighbors.py
================================================
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from sklearn.datasets import make_classification
from sklearn.datasets import make_regression
from scipy.spatial import distance
from mla import knn
from mla.metrics.metrics import mean_squared_error, accuracy
def regression():
# Generate a random regression problem
X, y = make_regression(
n_samples=500,
n_features=5,
n_informative=5,
n_targets=1,
noise=0.05,
random_state=1111,
bias=0.5,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=1111
)
model = knn.KNNRegressor(k=5, distance_func=distance.euclidean)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("regression mse", mean_squared_error(y_test, predictions))
def classification():
X, y = make_classification(
n_samples=500,
n_features=5,
n_informative=5,
n_redundant=0,
n_repeated=0,
n_classes=3,
random_state=1111,
class_sep=1.5,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.1, random_state=1111
)
clf = knn.KNNClassifier(k=5, distance_func=distance.euclidean)
clf.fit(X_train, y_train)
predictions = clf.predict(X_test)
print("classification accuracy", accuracy(y_test, predictions))
if __name__ == "__main__":
regression()
classification()
================================================
FILE: examples/nnet_convnet_mnist.py
================================================
import logging
from mla.datasets import load_mnist
from mla.metrics import accuracy
from mla.neuralnet import NeuralNet
from mla.neuralnet.layers import (
Activation,
Convolution,
MaxPooling,
Flatten,
Dropout,
Parameters,
)
from mla.neuralnet.layers import Dense
from mla.neuralnet.optimizers import Adadelta
from mla.utils import one_hot
logging.basicConfig(level=logging.DEBUG)
# Load MNIST dataset
X_train, X_test, y_train, y_test = load_mnist()
# Normalize data
X_train /= 255.0
X_test /= 255.0
y_train = one_hot(y_train.flatten())
y_test = one_hot(y_test.flatten())
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
# Approx. 15-20 min. per epoch
model = NeuralNet(
layers=[
Convolution(n_filters=32, filter_shape=(3, 3), padding=(1, 1), stride=(1, 1)),
Activation("relu"),
Convolution(n_filters=32, filter_shape=(3, 3), padding=(1, 1), stride=(1, 1)),
Activation("relu"),
MaxPooling(pool_shape=(2, 2), stride=(2, 2)),
Dropout(0.5),
Flatten(),
Dense(128),
Activation("relu"),
Dropout(0.5),
Dense(10),
Activation("softmax"),
],
loss="categorical_crossentropy",
optimizer=Adadelta(),
metric="accuracy",
batch_size=128,
max_epochs=3,
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(accuracy(y_test, predictions))
================================================
FILE: examples/nnet_mlp.py
================================================
import logging
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from sklearn.datasets import make_classification
from sklearn.datasets import make_regression
from sklearn.metrics import roc_auc_score
from mla.metrics.metrics import mean_squared_error
from mla.neuralnet import NeuralNet
from mla.neuralnet.constraints import MaxNorm
from mla.neuralnet.layers import Activation, Dense, Dropout
from mla.neuralnet.optimizers import Adadelta, Adam
from mla.neuralnet.parameters import Parameters
from mla.neuralnet.regularizers import L2
from mla.utils import one_hot
logging.basicConfig(level=logging.DEBUG)
def classification():
# Generate a random binary classification problem.
X, y = make_classification(
n_samples=1000,
n_features=100,
n_informative=75,
random_state=1111,
n_classes=2,
class_sep=2.5,
)
y = one_hot(y)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.15, random_state=1111
)
model = NeuralNet(
layers=[
Dense(256, Parameters(init="uniform", regularizers={"W": L2(0.05)})),
Activation("relu"),
Dropout(0.5),
Dense(128, Parameters(init="normal", constraints={"W": MaxNorm()})),
Activation("relu"),
Dense(2),
Activation("softmax"),
],
loss="categorical_crossentropy",
optimizer=Adadelta(),
metric="accuracy",
batch_size=64,
max_epochs=25,
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("classification accuracy", roc_auc_score(y_test[:, 0], predictions[:, 0]))
def regression():
# Generate a random regression problem
X, y = make_regression(
n_samples=5000,
n_features=25,
n_informative=25,
n_targets=1,
random_state=100,
noise=0.05,
)
y *= 0.01
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.1, random_state=1111
)
model = NeuralNet(
layers=[
Dense(64, Parameters(init="normal")),
Activation("linear"),
Dense(32, Parameters(init="normal")),
Activation("linear"),
Dense(1),
],
loss="mse",
optimizer=Adam(),
metric="mse",
batch_size=256,
max_epochs=15,
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("regression mse", mean_squared_error(y_test, predictions.flatten()))
if __name__ == "__main__":
classification()
regression()
================================================
FILE: examples/nnet_rnn_binary_add.py
================================================
import logging
from itertools import combinations, islice
import numpy as np
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from mla.metrics import accuracy
from mla.neuralnet import NeuralNet
from mla.neuralnet.layers import Activation, TimeDistributedDense
from mla.neuralnet.layers.recurrent import LSTM
from mla.neuralnet.optimizers import Adam
logging.basicConfig(level=logging.DEBUG)
def addition_dataset(dim=10, n_samples=10000, batch_size=64):
"""Generate binary addition dataset.
http://devankuleindiren.com/Projects/rnn_arithmetic.php
"""
binary_format = "{:0" + str(dim) + "b}"
# Generate all possible number combinations
combs = list(islice(combinations(range(2 ** (dim - 1)), 2), n_samples))
# Initialize empty arrays
X = np.zeros((len(combs), dim, 2), dtype=np.uint8)
y = np.zeros((len(combs), dim, 1), dtype=np.uint8)
for i, (a, b) in enumerate(combs):
# Convert numbers to binary format
X[i, :, 0] = list(reversed([int(x) for x in binary_format.format(a)]))
X[i, :, 1] = list(reversed([int(x) for x in binary_format.format(b)]))
# Generate target variable (a+b)
y[i, :, 0] = list(reversed([int(x) for x in binary_format.format(a + b)]))
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=1111
)
# Round number of examples for batch processing
train_b = (X_train.shape[0] // batch_size) * batch_size
test_b = (X_test.shape[0] // batch_size) * batch_size
X_train = X_train[0:train_b]
y_train = y_train[0:train_b]
X_test = X_test[0:test_b]
y_test = y_test[0:test_b]
return X_train, X_test, y_train, y_test
def addition_problem(ReccurentLayer):
X_train, X_test, y_train, y_test = addition_dataset(8, 5000)
print(X_train.shape, X_test.shape)
model = NeuralNet(
layers=[ReccurentLayer, TimeDistributedDense(1), Activation("sigmoid")],
loss="mse",
optimizer=Adam(),
metric="mse",
batch_size=64,
max_epochs=15,
)
model.fit(X_train, y_train)
predictions = np.round(model.predict(X_test))
predictions = np.packbits(predictions.astype(np.uint8))
y_test = np.packbits(y_test.astype(np.int))
print(accuracy(y_test, predictions))
# RNN
# addition_problem(RNN(16, parameters=Parameters(constraints={'W': SmallNorm(), 'U': SmallNorm()})))
# LSTM
addition_problem(LSTM(16))
================================================
FILE: examples/nnet_rnn_text_generation.py
================================================
from __future__ import print_function
import logging
import random
import numpy as np
import sys
from mla.datasets import load_nietzsche
from mla.neuralnet import NeuralNet
from mla.neuralnet.constraints import SmallNorm
from mla.neuralnet.layers import Activation, Dense
from mla.neuralnet.layers.recurrent import LSTM, RNN
from mla.neuralnet.optimizers import RMSprop
logging.basicConfig(level=logging.DEBUG)
# Example taken from: https://github.com/fchollet/keras/blob/master/examples/lstm_text_generation.py
def sample(preds, temperature=1.0):
# helper function to sample an index from a probability array
preds = np.asarray(preds).astype("float64")
preds = np.log(preds) / temperature
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas)
X, y, text, chars, char_indices, indices_char = load_nietzsche()
# Round the number of sequences for batch processing
items_count = X.shape[0] - (X.shape[0] % 64)
maxlen = X.shape[1]
X = X[0:items_count]
y = y[0:items_count]
print(X.shape, y.shape)
# LSTM OR RNN
# rnn_layer = RNN(128, return_sequences=False)
rnn_layer = LSTM(128, return_sequences=False)
model = NeuralNet(
layers=[
rnn_layer,
# Flatten(),
# TimeStepSlicer(-1),
Dense(X.shape[2]),
Activation("softmax"),
],
loss="categorical_crossentropy",
optimizer=RMSprop(learning_rate=0.01),
metric="accuracy",
batch_size=64,
max_epochs=1,
shuffle=False,
)
for _ in range(25):
model.fit(X, y)
start_index = random.randint(0, len(text) - maxlen - 1)
generated = ""
sentence = text[start_index : start_index + maxlen]
generated += sentence
print('----- Generating with seed: "' + sentence + '"')
sys.stdout.write(generated)
for i in range(100):
x = np.zeros((64, maxlen, len(chars)))
for t, char in enumerate(sentence):
x[0, t, char_indices[char]] = 1.0
preds = model.predict(x)[0]
next_index = sample(preds, 0.5)
next_char = indices_char[next_index]
generated += next_char
sentence = sentence[1:] + next_char
sys.stdout.write(next_char)
sys.stdout.flush()
print()
================================================
FILE: examples/pca.py
================================================
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from sklearn.datasets import make_classification
from mla.linear_models import LogisticRegression
from mla.metrics import accuracy
from mla.pca import PCA
# logging.basicConfig(level=logging.DEBUG)
# Generate a random binary classification problem.
X, y = make_classification(
n_samples=1000,
n_features=100,
n_informative=75,
random_state=1111,
n_classes=2,
class_sep=2.5,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=1111
)
for s in ["svd", "eigen"]:
p = PCA(15, solver=s)
# fit PCA with training data, not entire dataset
p.fit(X_train)
X_train_reduced = p.transform(X_train)
X_test_reduced = p.transform(X_test)
model = LogisticRegression(lr=0.001, max_iters=2500)
model.fit(X_train_reduced, y_train)
predictions = model.predict(X_test_reduced)
print("Classification accuracy for %s PCA: %s" % (s, accuracy(y_test, predictions)))
================================================
FILE: examples/random_forest.py
================================================
import logging
import numpy as np
from sklearn.datasets import make_classification
from sklearn.datasets import make_regression
from sklearn.metrics import roc_auc_score, accuracy_score
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from mla.ensemble.random_forest import RandomForestClassifier, RandomForestRegressor
from mla.metrics.metrics import mean_squared_error
logging.basicConfig(level=logging.DEBUG)
def classification():
# Generate a random binary classification problem.
X, y = make_classification(
n_samples=500,
n_features=10,
n_informative=10,
random_state=1111,
n_classes=2,
class_sep=2.5,
n_redundant=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.15, random_state=1111
)
model = RandomForestClassifier(n_estimators=10, max_depth=4)
model.fit(X_train, y_train)
predictions_prob = model.predict(X_test)[:, 1]
predictions = np.argmax(model.predict(X_test), axis=1)
# print(predictions.shape)
print("classification, roc auc score: %s" % roc_auc_score(y_test, predictions_prob))
print("classification, accuracy score: %s" % accuracy_score(y_test, predictions))
def regression():
# Generate a random regression problem
X, y = make_regression(
n_samples=500,
n_features=5,
n_informative=5,
n_targets=1,
noise=0.05,
random_state=1111,
bias=0.5,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.1, random_state=1111
)
model = RandomForestRegressor(n_estimators=50, max_depth=10, max_features=3)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(
"regression, mse: %s"
% mean_squared_error(y_test.flatten(), predictions.flatten())
)
if __name__ == "__main__":
classification()
# regression()
================================================
FILE: examples/rbm.py
================================================
import logging
import numpy as np
from mla.rbm import RBM
logging.basicConfig(level=logging.DEBUG)
def print_curve(rbm):
from matplotlib import pyplot as plt
def moving_average(a, n=25):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1 :] / n
plt.plot(moving_average(rbm.errors))
plt.show()
X = np.random.uniform(0, 1, (1500, 10))
rbm = RBM(n_hidden=10, max_epochs=200, batch_size=10, learning_rate=0.1)
rbm.fit(X)
print_curve(rbm)
================================================
FILE: examples/rl_deep_q_learning.py
================================================
import logging
from mla.neuralnet import NeuralNet
from mla.neuralnet.layers import Activation, Dense
from mla.neuralnet.optimizers import Adam
from mla.rl.dqn import DQN
logging.basicConfig(level=logging.CRITICAL)
def mlp_model(n_actions, batch_size=64):
model = NeuralNet(
layers=[Dense(32), Activation("relu"), Dense(n_actions)],
loss="mse",
optimizer=Adam(),
metric="mse",
batch_size=batch_size,
max_epochs=1,
verbose=False,
)
return model
model = DQN(n_episodes=2500, batch_size=64)
model.init_environment("CartPole-v0")
model.init_model(mlp_model)
try:
# Train the model
# It can take from 300 to 2500 episodes to solve CartPole-v0 problem due to randomness of environment.
# You can stop training process using Ctrl+C signal
# Read more about this problem: https://gym.openai.com/envs/CartPole-v0
model.train(render=False)
except KeyboardInterrupt:
pass
# Render trained model
model.play(episodes=100)
================================================
FILE: examples/svm.py
================================================
import logging
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from sklearn.datasets import make_classification
from mla.metrics.metrics import accuracy
from mla.svm.kernerls import Linear, RBF
from mla.svm.svm import SVM
logging.basicConfig(level=logging.DEBUG)
def classification():
# Generate a random binary classification problem.
X, y = make_classification(
n_samples=1200,
n_features=10,
n_informative=5,
random_state=1111,
n_classes=2,
class_sep=1.75,
)
# Convert y to {-1, 1}
y = (y * 2) - 1
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=1111
)
for kernel in [RBF(gamma=0.1), Linear()]:
model = SVM(max_iter=500, kernel=kernel, C=0.6)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(
"Classification accuracy (%s): %s" % (kernel, accuracy(y_test, predictions))
)
if __name__ == "__main__":
classification()
================================================
FILE: examples/t-sne.py
================================================
import logging
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from mla.tsne import TSNE
logging.basicConfig(level=logging.DEBUG)
X, y = make_classification(
n_samples=500,
n_features=10,
n_informative=5,
n_redundant=0,
random_state=1111,
n_classes=2,
class_sep=2.5,
)
p = TSNE(2, max_iter=500)
X = p.fit_transform(X)
colors = ["red", "green"]
for t in range(2):
t_mask = (y == t).astype(bool)
plt.scatter(X[t_mask, 0], X[t_mask, 1], color=colors[t])
plt.show()
================================================
FILE: mla/__init__.py
================================================
# coding:utf-8
# copyright: (c) 2016 by Artem Golubin
# license: MIT, see LICENSE for more details.
================================================
FILE: mla/base/__init__.py
================================================
# coding:utf-8
from .base import *
================================================
FILE: mla/base/base.py
================================================
# coding:utf-8
import numpy as np
class BaseEstimator:
y_required = True
fit_required = True
def _setup_input(self, X, y=None):
"""Ensure inputs to an estimator are in the expected format.
Ensures X and y are stored as numpy ndarrays by converting from an
array-like object if necessary. Enables estimators to define whether
they require a set of y target values or not with y_required, e.g.
kmeans clustering requires no target labels and is fit against only X.
Parameters
----------
X : array-like
Feature dataset.
y : array-like
Target values. By default is required, but if y_required = false
then may be omitted.
"""
if not isinstance(X, np.ndarray):
X = np.array(X)
if X.size == 0:
raise ValueError("Got an empty matrix.")
if X.ndim == 1:
self.n_samples, self.n_features = 1, X.shape
else:
self.n_samples, self.n_features = X.shape[0], np.prod(X.shape[1:])
self.X = X
if self.y_required:
if y is None:
raise ValueError("Missed required argument y")
if not isinstance(y, np.ndarray):
y = np.array(y)
if y.size == 0:
raise ValueError("The targets array must be no-empty.")
self.y = y
def fit(self, X, y=None):
self._setup_input(X, y)
def predict(self, X=None):
if not isinstance(X, np.ndarray):
X = np.array(X)
if self.X is not None or not self.fit_required:
return self._predict(X)
else:
raise ValueError("You must call `fit` before `predict`")
def _predict(self, X=None):
raise NotImplementedError()
================================================
FILE: mla/datasets/__init__.py
================================================
# coding:utf-8
from mla.datasets.base import *
================================================
FILE: mla/datasets/base.py
================================================
# coding:utf-8
import os
import numpy as np
def get_filename(name):
return os.path.join(os.path.dirname(__file__), name)
def load_mnist():
def load(dataset="training", digits=np.arange(10)):
import struct
from array import array as pyarray
from numpy import array, int8, uint8, zeros
if dataset == "train":
fname_img = get_filename("data/mnist/train-images-idx3-ubyte")
fname_lbl = get_filename("data/mnist/train-labels-idx1-ubyte")
elif dataset == "test":
fname_img = get_filename("data/mnist/t10k-images-idx3-ubyte")
fname_lbl = get_filename("data/mnist/t10k-labels-idx1-ubyte")
else:
raise ValueError("Unexpected dataset name: %r" % dataset)
flbl = open(fname_lbl, "rb")
magic_nr, size = struct.unpack(">II", flbl.read(8))
lbl = pyarray("b", flbl.read())
flbl.close()
fimg = open(fname_img, "rb")
magic_nr, size, rows, cols = struct.unpack(">IIII", fimg.read(16))
img = pyarray("B", fimg.read())
fimg.close()
ind = [k for k in range(size) if lbl[k] in digits]
N = len(ind)
images = zeros((N, rows, cols), dtype=uint8)
labels = zeros((N, 1), dtype=int8)
for i in range(len(ind)):
images[i] = array(
img[ind[i] * rows * cols : (ind[i] + 1) * rows * cols]
).reshape((rows, cols))
labels[i] = lbl[ind[i]]
return images, labels
X_train, y_train = load("train")
X_test, y_test = load("test")
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype(np.float32)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype(np.float32)
return X_train, X_test, y_train, y_test
def load_nietzsche():
text = open(get_filename("data/nietzsche.txt"), "rt").read().lower()
chars = set(list(text))
char_indices = {ch: i for i, ch in enumerate(chars)}
indices_char = {i: ch for i, ch in enumerate(chars)}
maxlen = 40
step = 3
sentences = []
next_chars = []
for i in range(0, len(text) - maxlen, step):
sentences.append(text[i : i + maxlen])
next_chars.append(text[i + maxlen])
X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool)
y = np.zeros((len(sentences), len(chars)), dtype=np.bool)
for i, sentence in enumerate(sentences):
for t, char in enumerate(sentence):
X[i, t, char_indices[char]] = 1
y[i, char_indices[next_chars[i]]] = 1
return X, y, text, chars, char_indices, indices_char
================================================
FILE: mla/datasets/data/mnist/train-images-idx3-ubyte
================================================
[File too large to display: 44.9 MB]
================================================
FILE: mla/datasets/data/nietzsche.txt
================================================
PREFACE
SUPPOSING that Truth is a woman--what then? Is there not ground
for suspecting that all philosophers, in so far as they have been
dogmatists, have failed to understand women--that the terrible
seriousness and clumsy importunity with which they have usually paid
their addresses to Truth, have been unskilled and unseemly methods for
winning a woman? Certainly she has never allowed herself to be won; and
at present every kind of dogma stands with sad and discouraged mien--IF,
indeed, it stands at all! For there are scoffers who maintain that it
has fallen, that all dogma lies on the ground--nay more, that it is at
its last gasp. But to speak seriously, there are good grounds for hoping
that all dogmatizing in philosophy, whatever solemn, whatever conclusive
and decided airs it has assumed, may have been only a noble puerilism
and tyronism; and probably the time is at hand when it will be once
and again understood WHAT has actually sufficed for the basis of such
imposing and absolute philosophical edifices as the dogmatists have
hitherto reared: perhaps some popular superstition of immemorial time
(such as the soul-superstition, which, in the form of subject- and
ego-superstition, has not yet ceased doing mischief): perhaps some
play upon words, a deception on the part of grammar, or an
audacious generalization of very restricted, very personal, very
human--all-too-human facts. The philosophy of the dogmatists, it is to
be hoped, was only a promise for thousands of years afterwards, as was
astrology in still earlier times, in the service of which probably more
labour, gold, acuteness, and patience have been spent than on any
actual science hitherto: we owe to it, and to its "super-terrestrial"
pretensions in Asia and Egypt, the grand style of architecture. It seems
that in order to inscribe themselves upon the heart of humanity with
everlasting claims, all great things have first to wander about the
earth as enormous and awe-inspiring caricatures: dogmatic philosophy has
been a caricature of this kind--for instance, the Vedanta doctrine in
Asia, and Platonism in Europe. Let us not be ungrateful to it, although
it must certainly be confessed that the worst, the most tiresome,
and the most dangerous of errors hitherto has been a dogmatist
error--namely, Plato's invention of Pure Spirit and the Good in Itself.
But now when it has been surmounted, when Europe, rid of this nightmare,
can again draw breath freely and at least enjoy a healthier--sleep,
we, WHOSE DUTY IS WAKEFULNESS ITSELF, are the heirs of all the strength
which the struggle against this error has fostered. It amounted to
the very inversion of truth, and the denial of the PERSPECTIVE--the
fundamental condition--of life, to speak of Spirit and the Good as Plato
spoke of them; indeed one might ask, as a physician: "How did such a
malady attack that finest product of antiquity, Plato? Had the wicked
Socrates really corrupted him? Was Socrates after all a corrupter of
youths, and deserved his hemlock?" But the struggle against Plato,
or--to speak plainer, and for the "people"--the struggle against
the ecclesiastical oppression of millenniums of Christianity (FOR
CHRISTIANITY IS PLATONISM FOR THE "PEOPLE"), produced in Europe
a magnificent tension of soul, such as had not existed anywhere
previously; with such a tensely strained bow one can now aim at the
furthest goals. As a matter of fact, the European feels this tension as
a state of distress, and twice attempts have been made in grand style to
unbend the bow: once by means of Jesuitism, and the second time by means
of democratic enlightenment--which, with the aid of liberty of the press
and newspaper-reading, might, in fact, bring it about that the spirit
would not so easily find itself in "distress"! (The Germans invented
gunpowder--all credit to them! but they again made things square--they
invented printing.) But we, who are neither Jesuits, nor democrats,
nor even sufficiently Germans, we GOOD EUROPEANS, and free, VERY free
spirits--we have it still, all the distress of spirit and all the
tension of its bow! And perhaps also the arrow, the duty, and, who
knows? THE GOAL TO AIM AT....
Sils Maria Upper Engadine, JUNE, 1885.
CHAPTER I. PREJUDICES OF PHILOSOPHERS
1. The Will to Truth, which is to tempt us to many a hazardous
enterprise, the famous Truthfulness of which all philosophers have
hitherto spoken with respect, what questions has this Will to Truth not
laid before us! What strange, perplexing, questionable questions! It is
already a long story; yet it seems as if it were hardly commenced. Is
it any wonder if we at last grow distrustful, lose patience, and turn
impatiently away? That this Sphinx teaches us at last to ask questions
ourselves? WHO is it really that puts questions to us here? WHAT really
is this "Will to Truth" in us? In fact we made a long halt at the
question as to the origin of this Will--until at last we came to an
absolute standstill before a yet more fundamental question. We inquired
about the VALUE of this Will. Granted that we want the truth: WHY NOT
RATHER untruth? And uncertainty? Even ignorance? The problem of the
value of truth presented itself before us--or was it we who presented
ourselves before the problem? Which of us is the Oedipus here? Which
the Sphinx? It would seem to be a rendezvous of questions and notes of
interrogation. And could it be believed that it at last seems to us as
if the problem had never been propounded before, as if we were the first
to discern it, get a sight of it, and RISK RAISING it? For there is risk
in raising it, perhaps there is no greater risk.
2. "HOW COULD anything originate out of its opposite? For example, truth
out of error? or the Will to Truth out of the will to deception? or the
generous deed out of selfishness? or the pure sun-bright vision of the
wise man out of covetousness? Such genesis is impossible; whoever dreams
of it is a fool, nay, worse than a fool; things of the highest
value must have a different origin, an origin of THEIR own--in this
transitory, seductive, illusory, paltry world, in this turmoil of
delusion and cupidity, they cannot have their source. But rather in
the lap of Being, in the intransitory, in the concealed God, in the
'Thing-in-itself--THERE must be their source, and nowhere else!"--This
mode of reasoning discloses the typical prejudice by which
metaphysicians of all times can be recognized, this mode of valuation
is at the back of all their logical procedure; through this "belief" of
theirs, they exert themselves for their "knowledge," for something that
is in the end solemnly christened "the Truth." The fundamental belief of
metaphysicians is THE BELIEF IN ANTITHESES OF VALUES. It never occurred
even to the wariest of them to doubt here on the very threshold (where
doubt, however, was most necessary); though they had made a solemn
vow, "DE OMNIBUS DUBITANDUM." For it may be doubted, firstly, whether
antitheses exist at all; and secondly, whether the popular valuations
and antitheses of value upon which metaphysicians have set their
seal, are not perhaps merely superficial estimates, merely provisional
perspectives, besides being probably made from some corner, perhaps from
below--"frog perspectives," as it were, to borrow an expression current
among painters. In spite of all the value which may belong to the true,
the positive, and the unselfish, it might be possible that a higher
and more fundamental value for life generally should be assigned to
pretence, to the will to delusion, to selfishness, and cupidity. It
might even be possible that WHAT constitutes the value of those good and
respected things, consists precisely in their being insidiously
related, knotted, and crocheted to these evil and apparently opposed
things--perhaps even in being essentially identical with them. Perhaps!
But who wishes to concern himself with such dangerous "Perhapses"!
For that investigation one must await the advent of a new order of
philosophers, such as will have other tastes and inclinations, the
reverse of those hitherto prevalent--philosophers of the dangerous
"Perhaps" in every sense of the term. And to speak in all seriousness, I
see such new philosophers beginning to appear.
3. Having kept a sharp eye on philosophers, and having read between
their lines long enough, I now say to myself that the greater part of
conscious thinking must be counted among the instinctive functions, and
it is so even in the case of philosophical thinking; one has here to
learn anew, as one learned anew about heredity and "innateness." As
little as the act of birth comes into consideration in the whole process
and procedure of heredity, just as little is "being-conscious" OPPOSED
to the instinctive in any decisive sense; the greater part of the
conscious thinking of a philosopher is secretly influenced by his
instincts, and forced into definite channels. And behind all logic and
its seeming sovereignty of movement, there are valuations, or to speak
more plainly, physiological demands, for the maintenance of a definite
mode of life For example, that the certain is worth more than the
uncertain, that illusion is less valuable than "truth" such valuations,
in spite of their regulative importance for US, might notwithstanding be
only superficial valuations, special kinds of _niaiserie_, such as may
be necessary for the maintenance of beings such as ourselves. Supposing,
in effect, that man is not just the "measure of things."
4. The falseness of an opinion is not for us any objection to it: it is
here, perhaps, that our new language sounds most strangely. The
question is, how far an opinion is life-furthering, life-preserving,
species-preserving, perhaps species-rearing, and we are fundamentally
inclined to maintain that the falsest opinions (to which the synthetic
judgments a priori belong), are the most indispensable to us, that
without a recognition of logical fictions, without a comparison of
reality with the purely IMAGINED world of the absolute and immutable,
without a constant counterfeiting of the world by means of numbers,
man could not live--that the renunciation of false opinions would be
a renunciation of life, a negation of life. TO RECOGNISE UNTRUTH AS A
CONDITION OF LIFE; that is certainly to impugn the traditional ideas of
value in a dangerous manner, and a philosophy which ventures to do so,
has thereby alone placed itself beyond good and evil.
5. That which causes philosophers to be regarded half-distrustfully
and half-mockingly, is not the oft-repeated discovery how innocent they
are--how often and easily they make mistakes and lose their way, in
short, how childish and childlike they are,--but that there is not
enough honest dealing with them, whereas they all raise a loud and
virtuous outcry when the problem of truthfulness is even hinted at in
the remotest manner. They all pose as though their real opinions had
been discovered and attained through the self-evolving of a cold, pure,
divinely indifferent dialectic (in contrast to all sorts of mystics,
who, fairer and foolisher, talk of "inspiration"), whereas, in fact, a
prejudiced proposition, idea, or "suggestion," which is generally
their heart's desire abstracted and refined, is defended by them with
arguments sought out after the event. They are all advocates who do not
wish to be regarded as such, generally astute defenders, also, of their
prejudices, which they dub "truths,"--and VERY far from having the
conscience which bravely admits this to itself, very far from having
the good taste of the courage which goes so far as to let this be
understood, perhaps to warn friend or foe, or in cheerful confidence
and self-ridicule. The spectacle of the Tartuffery of old Kant, equally
stiff and decent, with which he entices us into the dialectic
by-ways that lead (more correctly mislead) to his "categorical
imperative"--makes us fastidious ones smile, we who find no small
amusement in spying out the subtle tricks of old moralists and ethical
preachers. Or, still more so, the hocus-pocus in mathematical form, by
means of which Spinoza has, as it were, clad his philosophy in mail and
mask--in fact, the "love of HIS wisdom," to translate the term fairly
and squarely--in order thereby to strike terror at once into the heart
of the assailant who should dare to cast a glance on that invincible
maiden, that Pallas Athene:--how much of personal timidity and
vulnerability does this masquerade of a sickly recluse betray!
6. It has gradually become clear to me what every great philosophy up
till now has consisted of--namely, the confession of its originator, and
a species of involuntary and unconscious auto-biography; and moreover
that the moral (or immoral) purpose in every philosophy has constituted
the true vital germ out of which the entire plant has always grown.
Indeed, to understand how the abstrusest metaphysical assertions of a
philosopher have been arrived at, it is always well (and wise) to first
ask oneself: "What morality do they (or does he) aim at?" Accordingly,
I do not believe that an "impulse to knowledge" is the father of
philosophy; but that another impulse, here as elsewhere, has only made
use of knowledge (and mistaken knowledge!) as an instrument. But whoever
considers the fundamental impulses of man with a view to determining
how far they may have here acted as INSPIRING GENII (or as demons and
cobolds), will find that they have all practiced philosophy at one time
or another, and that each one of them would have been only too glad to
look upon itself as the ultimate end of existence and the legitimate
LORD over all the other impulses. For every impulse is imperious, and as
SUCH, attempts to philosophize. To be sure, in the case of scholars, in
the case of really scientific men, it may be otherwise--"better," if
you will; there there may really be such a thing as an "impulse to
knowledge," some kind of small, independent clock-work, which, when well
wound up, works away industriously to that end, WITHOUT the rest of
the scholarly impulses taking any material part therein. The actual
"interests" of the scholar, therefore, are generally in quite another
direction--in the family, perhaps, or in money-making, or in politics;
it is, in fact, almost indifferent at what point of research his little
machine is placed, and whether the hopeful young worker becomes a
good philologist, a mushroom specialist, or a chemist; he is not
CHARACTERISED by becoming this or that. In the philosopher, on the
contrary, there is absolutely nothing impersonal; and above all,
his morality furnishes a decided and decisive testimony as to WHO HE
IS,--that is to say, in what order the deepest impulses of his nature
stand to each other.
7. How malicious philosophers can be! I know of nothing more stinging
than the joke Epicurus took the liberty of making on Plato and the
Platonists; he called them Dionysiokolakes. In its original sense,
and on the face of it, the word signifies "Flatterers of
Dionysius"--consequently, tyrants' accessories and lick-spittles;
besides this, however, it is as much as to say, "They are all ACTORS,
there is nothing genuine about them" (for Dionysiokolax was a popular
name for an actor). And the latter is really the malignant reproach that
Epicurus cast upon Plato: he was annoyed by the grandiose manner, the
mise en scene style of which Plato and his scholars were masters--of
which Epicurus was not a master! He, the old school-teacher of Samos,
who sat concealed in his little garden at Athens, and wrote three
hundred books, perhaps out of rage and ambitious envy of Plato, who
knows! Greece took a hundred years to find out who the garden-god
Epicurus really was. Did she ever find out?
8. There is a point in every philosophy at which the "conviction" of
the philosopher appears on the scene; or, to put it in the words of an
ancient mystery:
Adventavit asinus, Pulcher et fortissimus.
9. You desire to LIVE "according to Nature"? Oh, you noble Stoics, what
fraud of words! Imagine to yourselves a being like Nature, boundlessly
extravagant, boundlessly indifferent, without purpose or consideration,
without pity or justice, at once fruitful and barren and uncertain:
imagine to yourselves INDIFFERENCE as a power--how COULD you live
in accordance with such indifference? To live--is not that just
endeavouring to be otherwise than this Nature? Is not living valuing,
preferring, being unjust, being limited, endeavouring to be different?
And granted that your imperative, "living according to Nature," means
actually the same as "living according to life"--how could you do
DIFFERENTLY? Why should you make a principle out of what you yourselves
are, and must be? In reality, however, it is quite otherwise with you:
while you pretend to read with rapture the canon of your law in Nature,
you want something quite the contrary, you extraordinary stage-players
and self-deluders! In your pride you wish to dictate your morals and
ideals to Nature, to Nature herself, and to incorporate them therein;
you insist that it shall be Nature "according to the Stoa," and would
like everything to be made after your own image, as a vast, eternal
glorification and generalism of Stoicism! With all your love for truth,
you have forced yourselves so long, so persistently, and with such
hypnotic rigidity to see Nature FALSELY, that is to say, Stoically,
that you are no longer able to see it otherwise--and to crown all, some
unfathomable superciliousness gives you the Bedlamite hope that
BECAUSE you are able to tyrannize over yourselves--Stoicism is
self-tyranny--Nature will also allow herself to be tyrannized over: is
not the Stoic a PART of Nature?... But this is an old and everlasting
story: what happened in old times with the Stoics still happens today,
as soon as ever a philosophy begins to believe in itself. It always
creates the world in its own image; it cannot do otherwise; philosophy
is this tyrannical impulse itself, the most spiritual Will to Power, the
will to "creation of the world," the will to the causa prima.
10. The eagerness and subtlety, I should even say craftiness, with
which the problem of "the real and the apparent world" is dealt with at
present throughout Europe, furnishes food for thought and attention; and
he who hears only a "Will to Truth" in the background, and nothing else,
cannot certainly boast of the sharpest ears. In rare and isolated
cases, it may really have happened that such a Will to Truth--a certain
extravagant and adventurous pluck, a metaphysician's ambition of the
forlorn hope--has participated therein: that which in the end always
prefers a handful of "certainty" to a whole cartload of beautiful
possibilities; there may even be puritanical fanatics of conscience,
who prefer to put their last trust in a sure nothing, rather than in an
uncertain something. But that is Nihilism, and the sign of a despairing,
mortally wearied soul, notwithstanding the courageous bearing such a
virtue may display. It seems, however, to be otherwise with stronger
and livelier thinkers who are still eager for life. In that they side
AGAINST appearance, and speak superciliously of "perspective," in
that they rank the credibility of their own bodies about as low as the
credibility of the ocular evidence that "the earth stands still," and
thus, apparently, allowing with complacency their securest possession
to escape (for what does one at present believe in more firmly than
in one's body?),--who knows if they are not really trying to win back
something which was formerly an even securer possession, something
of the old domain of the faith of former times, perhaps the "immortal
soul," perhaps "the old God," in short, ideas by which they could live
better, that is to say, more vigorously and more joyously, than by
"modern ideas"? There is DISTRUST of these modern ideas in this mode
of looking at things, a disbelief in all that has been constructed
yesterday and today; there is perhaps some slight admixture of satiety
and scorn, which can no longer endure the BRIC-A-BRAC of ideas of the
most varied origin, such as so-called Positivism at present throws on
the market; a disgust of the more refined taste at the village-fair
motleyness and patchiness of all these reality-philosophasters, in whom
there is nothing either new or true, except this motleyness. Therein it
seems to me that we should agree with those skeptical anti-realists and
knowledge-microscopists of the present day; their instinct, which repels
them from MODERN reality, is unrefuted... what do their retrograde
by-paths concern us! The main thing about them is NOT that they wish
to go "back," but that they wish to get AWAY therefrom. A little MORE
strength, swing, courage, and artistic power, and they would be OFF--and
not back!
11. It seems to me that there is everywhere an attempt at present to
divert attention from the actual influence which Kant exercised on
German philosophy, and especially to ignore prudently the value which
he set upon himself. Kant was first and foremost proud of his Table of
Categories; with it in his hand he said: "This is the most difficult
thing that could ever be undertaken on behalf of metaphysics." Let us
only understand this "could be"! He was proud of having DISCOVERED a
new faculty in man, the faculty of synthetic judgment a priori. Granting
that he deceived himself in this matter; the development and rapid
flourishing of German philosophy depended nevertheless on his pride, and
on the eager rivalry of the younger generation to discover if possible
something--at all events "new faculties"--of which to be still
prouder!--But let us reflect for a moment--it is high time to do so.
"How are synthetic judgments a priori POSSIBLE?" Kant asks himself--and
what is really his answer? "BY MEANS OF A MEANS (faculty)"--but
unfortunately not in five words, but so circumstantially, imposingly,
and with such display of German profundity and verbal flourishes, that
one altogether loses sight of the comical niaiserie allemande involved
in such an answer. People were beside themselves with delight over this
new faculty, and the jubilation reached its climax when Kant further
discovered a moral faculty in man--for at that time Germans were still
moral, not yet dabbling in the "Politics of hard fact." Then came
the honeymoon of German philosophy. All the young theologians of the
Tubingen institution went immediately into the groves--all seeking for
"faculties." And what did they not find--in that innocent, rich, and
still youthful period of the German spirit, to which Romanticism, the
malicious fairy, piped and sang, when one could not yet distinguish
between "finding" and "inventing"! Above all a faculty for the
"transcendental"; Schelling christened it, intellectual intuition,
and thereby gratified the most earnest longings of the naturally
pious-inclined Germans. One can do no greater wrong to the whole of
this exuberant and eccentric movement (which was really youthfulness,
notwithstanding that it disguised itself so boldly, in hoary and senile
conceptions), than to take it seriously, or even treat it with moral
indignation. Enough, however--the world grew older, and the dream
vanished. A time came when people rubbed their foreheads, and they still
rub them today. People had been dreaming, and first and foremost--old
Kant. "By means of a means (faculty)"--he had said, or at least meant to
say. But, is that--an answer? An explanation? Or is it not rather merely
a repetition of the question? How does opium induce sleep? "By means of
a means (faculty)," namely the virtus dormitiva, replies the doctor in
Moliere,
Quia est in eo virtus dormitiva,
Cujus est natura sensus assoupire.
But such replies belong to the realm of comedy, and it is high time
to replace the Kantian question, "How are synthetic judgments a PRIORI
possible?" by another question, "Why is belief in such judgments
necessary?"--in effect, it is high time that we should understand
that such judgments must be believed to be true, for the sake of the
preservation of creatures like ourselves; though they still might
naturally be false judgments! Or, more plainly spoken, and roughly and
readily--synthetic judgments a priori should not "be possible" at all;
we have no right to them; in our mouths they are nothing but false
judgments. Only, of course, the belief in their truth is necessary, as
plausible belief and ocular evidence belonging to the perspective view
of life. And finally, to call to mind the enormous influence which
"German philosophy"--I hope you understand its right to inverted commas
(goosefeet)?--has exercised throughout the whole of Europe, there is
no doubt that a certain VIRTUS DORMITIVA had a share in it; thanks to
German philosophy, it was a delight to the noble idlers, the virtuous,
the mystics, the artiste, the three-fourths Christians, and the
political obscurantists of all nations, to find an antidote to the still
overwhelming sensualism which overflowed from the last century into
this, in short--"sensus assoupire."...
12. As regards materialistic atomism, it is one of the best-refuted
theories that have been advanced, and in Europe there is now perhaps
no one in the learned world so unscholarly as to attach serious
signification to it, except for convenient everyday use (as an
abbreviation of the means of expression)--thanks chiefly to the Pole
Boscovich: he and the Pole Copernicus have hitherto been the greatest
and most successful opponents of ocular evidence. For while Copernicus
has persuaded us to believe, contrary to all the senses, that the earth
does NOT stand fast, Boscovich has taught us to abjure the belief in the
last thing that "stood fast" of the earth--the belief in "substance," in
"matter," in the earth-residuum, and particle-atom: it is the greatest
triumph over the senses that has hitherto been gained on earth. One
must, however, go still further, and also declare war, relentless war
to the knife, against the "atomistic requirements" which still lead a
dangerous after-life in places where no one suspects them, like the more
celebrated "metaphysical requirements": one must also above all give
the finishing stroke to that other and more portentous atomism which
Christianity has taught best and longest, the SOUL-ATOMISM. Let it be
permitted to designate by this expression the belief which regards the
soul as something indestructible, eternal, indivisible, as a monad,
as an atomon: this belief ought to be expelled from science! Between
ourselves, it is not at all necessary to get rid of "the soul" thereby,
and thus renounce one of the oldest and most venerated hypotheses--as
happens frequently to the clumsiness of naturalists, who can hardly
touch on the soul without immediately losing it. But the way is open
for new acceptations and refinements of the soul-hypothesis; and such
conceptions as "mortal soul," and "soul of subjective multiplicity,"
and "soul as social structure of the instincts and passions," want
henceforth to have legitimate rights in science. In that the NEW
psychologist is about to put an end to the superstitions which have
hitherto flourished with almost tropical luxuriance around the idea of
the soul, he is really, as it were, thrusting himself into a new desert
and a new distrust--it is possible that the older psychologists had a
merrier and more comfortable time of it; eventually, however, he finds
that precisely thereby he is also condemned to INVENT--and, who knows?
perhaps to DISCOVER the new.
13. Psychologists should bethink themselves before putting down the
instinct of self-preservation as the cardinal instinct of an organic
being. A living thing seeks above all to DISCHARGE its strength--life
itself is WILL TO POWER; self-preservation is only one of the indirect
and most frequent RESULTS thereof. In short, here, as everywhere else,
let us beware of SUPERFLUOUS teleological principles!--one of which
is the instinct of self-preservation (we owe it to Spinoza's
inconsistency). It is thus, in effect, that method ordains, which must
be essentially economy of principles.
14. It is perhaps just dawning on five or six minds that natural
philosophy is only a world-exposition and world-arrangement (according
to us, if I may say so!) and NOT a world-explanation; but in so far as
it is based on belief in the senses, it is regarded as more, and for a
long time to come must be regarded as more--namely, as an explanation.
It has eyes and fingers of its own, it has ocular evidence and
palpableness of its own: this operates fascinatingly, persuasively, and
CONVINCINGLY upon an age with fundamentally plebeian tastes--in fact, it
follows instinctively the canon of truth of eternal popular sensualism.
What is clear, what is "explained"? Only that which can be seen and
felt--one must pursue every problem thus far. Obversely, however, the
charm of the Platonic mode of thought, which was an ARISTOCRATIC mode,
consisted precisely in RESISTANCE to obvious sense-evidence--perhaps
among men who enjoyed even stronger and more fastidious senses than our
contemporaries, but who knew how to find a higher triumph in remaining
masters of them: and this by means of pale, cold, grey conceptional
networks which they threw over the motley whirl of the senses--the
mob of the senses, as Plato said. In this overcoming of the world, and
interpreting of the world in the manner of Plato, there was an ENJOYMENT
different from that which the physicists of today offer us--and likewise
the Darwinists and anti-teleologists among the physiological workers,
with their principle of the "smallest possible effort," and the greatest
possible blunder. "Where there is nothing more to see or to grasp, there
is also nothing more for men to do"--that is certainly an imperative
different from the Platonic one, but it may notwithstanding be the right
imperative for a hardy, laborious race of machinists and bridge-builders
of the future, who have nothing but ROUGH work to perform.
15. To study physiology with a clear conscience, one must insist on
the fact that the sense-organs are not phenomena in the sense of the
idealistic philosophy; as such they certainly could not be causes!
Sensualism, therefore, at least as regulative hypothesis, if not as
heuristic principle. What? And others say even that the external world
is the work of our organs? But then our body, as a part of this external
world, would be the work of our organs! But then our organs themselves
would be the work of our organs! It seems to me that this is a
complete REDUCTIO AD ABSURDUM, if the conception CAUSA SUI is something
fundamentally absurd. Consequently, the external world is NOT the work
of our organs--?
16. There are still harmless self-observers who believe that there are
"immediate certainties"; for instance, "I think," or as the superstition
of Schopenhauer puts it, "I will"; as though cognition here got hold
of its object purely and simply as "the thing in itself," without any
falsification taking place either on the part of the subject or the
object. I would repeat it, however, a hundred times, that "immediate
certainty," as well as "absolute knowledge" and the "thing in itself,"
involve a CONTRADICTIO IN ADJECTO; we really ought to free ourselves
from the misleading significance of words! The people on their part may
think that cognition is knowing all about things, but the philosopher
must say to himself: "When I analyze the process that is expressed in
the sentence, 'I think,' I find a whole series of daring assertions, the
argumentative proof of which would be difficult, perhaps impossible:
for instance, that it is _I_ who think, that there must necessarily be
something that thinks, that thinking is an activity and operation on the
part of a being who is thought of as a cause, that there is an 'ego,'
and finally, that it is already determined what is to be designated by
thinking--that I KNOW what thinking is. For if I had not already decided
within myself what it is, by what standard could I determine whether
that which is just happening is not perhaps 'willing' or 'feeling'? In
short, the assertion 'I think,' assumes that I COMPARE my state at the
present moment with other states of myself which I know, in order to
determine what it is; on account of this retrospective connection with
further 'knowledge,' it has, at any rate, no immediate certainty for
me."--In place of the "immediate certainty" in which the people may
believe in the special case, the philosopher thus finds a series of
metaphysical questions presented to him, veritable conscience questions
of the intellect, to wit: "Whence did I get the notion of 'thinking'?
Why do I believe in cause and effect? What gives me the right to speak
of an 'ego,' and even of an 'ego' as cause, and finally of an 'ego'
as cause of thought?" He who ventures to answer these metaphysical
questions at once by an appeal to a sort of INTUITIVE perception, like
the person who says, "I think, and know that this, at least, is
true, actual, and certain"--will encounter a smile and two notes of
interrogation in a philosopher nowadays. "Sir," the philosopher will
perhaps give him to understand, "it is improbable that you are not
mistaken, but why should it be the truth?"
17. With regard to the superstitions of logicians, I shall never tire
of emphasizing a small, terse fact, which is unwillingly recognized by
these credulous minds--namely, that a thought comes when "it" wishes,
and not when "I" wish; so that it is a PERVERSION of the facts of the
case to say that the subject "I" is the condition of the predicate
"think." ONE thinks; but that this "one" is precisely the famous old
"ego," is, to put it mildly, only a supposition, an assertion, and
assuredly not an "immediate certainty." After all, one has even gone too
far with this "one thinks"--even the "one" contains an INTERPRETATION of
the process, and does not belong to the process itself. One infers here
according to the usual grammatical formula--"To think is an activity;
every activity requires an agency that is active; consequently"... It
was pretty much on the same lines that the older atomism sought, besides
the operating "power," the material particle wherein it resides and out
of which it operates--the atom. More rigorous minds, however, learnt at
last to get along without this "earth-residuum," and perhaps some day we
shall accustom ourselves, even from the logician's point of view, to
get along without the little "one" (to which the worthy old "ego" has
refined itself).
18. It is certainly not the least charm of a theory that it is
refutable; it is precisely thereby that it attracts the more subtle
minds. It seems that the hundred-times-refuted theory of the "free will"
owes its persistence to this charm alone; some one is always appearing
who feels himself strong enough to refute it.
19. Philosophers are accustomed to speak of the will as though it were
the best-known thing in the world; indeed, Schopenhauer has given us
to understand that the will alone is really known to us, absolutely and
completely known, without deduction or addition. But it again and
again seems to me that in this case Schopenhauer also only did what
philosophers are in the habit of doing--he seems to have adopted a
POPULAR PREJUDICE and exaggerated it. Willing seems to me to be above
all something COMPLICATED, something that is a unity only in name--and
it is precisely in a name that popular prejudice lurks, which has got
the mastery over the inadequate precautions of philosophers in all ages.
So let us for once be more cautious, let us be "unphilosophical": let
us say that in all willing there is firstly a plurality of sensations,
namely, the sensation of the condition "AWAY FROM WHICH we go," the
sensation of the condition "TOWARDS WHICH we go," the sensation of this
"FROM" and "TOWARDS" itself, and then besides, an accompanying muscular
sensation, which, even without our putting in motion "arms and legs,"
commences its action by force of habit, directly we "will" anything.
Therefore, just as sensations (and indeed many kinds of sensations) are
to be recognized as ingredients of the will, so, in the second place,
thinking is also to be recognized; in every act of the will there is
a ruling thought;--and let us not imagine it possible to sever this
thought from the "willing," as if the will would then remain over!
In the third place, the will is not only a complex of sensation and
thinking, but it is above all an EMOTION, and in fact the emotion of the
command. That which is termed "freedom of the will" is essentially the
emotion of supremacy in respect to him who must obey: "I am free, 'he'
must obey"--this consciousness is inherent in every will; and equally
so the straining of the attention, the straight look which fixes itself
exclusively on one thing, the unconditional judgment that "this and
nothing else is necessary now," the inward certainty that obedience
will be rendered--and whatever else pertains to the position of the
commander. A man who WILLS commands something within himself which
renders obedience, or which he believes renders obedience. But now let
us notice what is the strangest thing about the will,--this affair so
extremely complex, for which the people have only one name. Inasmuch as
in the given circumstances we are at the same time the commanding AND
the obeying parties, and as the obeying party we know the sensations of
constraint, impulsion, pressure, resistance, and motion, which usually
commence immediately after the act of will; inasmuch as, on the other
hand, we are accustomed to disregard this duality, and to deceive
ourselves about it by means of the synthetic term "I": a whole series
of erroneous conclusions, and consequently of false judgments about the
will itself, has become attached to the act of willing--to such a degree
that he who wills believes firmly that willing SUFFICES for action.
Since in the majority of cases there has only been exercise of will
when the effect of the command--consequently obedience, and therefore
action--was to be EXPECTED, the APPEARANCE has translated itself into
the sentiment, as if there were a NECESSITY OF EFFECT; in a word, he who
wills believes with a fair amount of certainty that will and action are
somehow one; he ascribes the success, the carrying out of the willing,
to the will itself, and thereby enjoys an increase of the sensation
of power which accompanies all success. "Freedom of Will"--that is the
expression for the complex state of delight of the person exercising
volition, who commands and at the same time identifies himself with
the executor of the order--who, as such, enjoys also the triumph over
obstacles, but thinks within himself that it was really his own will
that overcame them. In this way the person exercising volition adds the
feelings of delight of his successful executive instruments, the useful
"underwills" or under-souls--indeed, our body is but a social structure
composed of many souls--to his feelings of delight as commander. L'EFFET
C'EST MOI. what happens here is what happens in every well-constructed
and happy commonwealth, namely, that the governing class identifies
itself with the successes of the commonwealth. In all willing it is
absolutely a question of commanding and obeying, on the basis, as
already said, of a social structure composed of many "souls", on which
account a philosopher should claim the right to include willing-as-such
within the sphere of morals--regarded as the doctrine of the relations
of supremacy under which the phenomenon of "life" manifests itself.
20. That the separate philosophical ideas are not anything optional or
autonomously evolving, but grow up in connection and relationship with
each other, that, however suddenly and arbitrarily they seem to appear
in the history of thought, they nevertheless belong just as much to
a system as the collective members of the fauna of a Continent--is
betrayed in the end by the circumstance: how unfailingly the most
diverse philosophers always fill in again a definite fundamental scheme
of POSSIBLE philosophies. Under an invisible spell, they always revolve
once more in the same orbit, however independent of each other they
may feel themselves with their critical or systematic wills, something
within them leads them, something impels them in definite order the
one after the other--to wit, the innate methodology and relationship
of their ideas. Their thinking is, in fact, far less a discovery than a
re-recognizing, a remembering, a return and a home-coming to a far-off,
ancient common-household of the soul, out of which those ideas formerly
grew: philosophizing is so far a kind of atavism of the highest order.
The wonderful family resemblance of all Indian, Greek, and German
philosophizing is easily enough explained. In fact, where there is
affinity of language, owing to the common philosophy of grammar--I mean
owing to the unconscious domination and guidance of similar grammatical
functions--it cannot but be that everything is prepared at the outset
for a similar development and succession of philosophical systems,
just as the way seems barred against certain other possibilities of
world-interpretation. It is highly probable that philosophers within the
domain of the Ural-Altaic languages (where the conception of the subject
is least developed) look otherwise "into the world," and will be
found on paths of thought different from those of the Indo-Germans and
Mussulmans, the spell of certain grammatical functions is ultimately
also the spell of PHYSIOLOGICAL valuations and racial conditions.--So
much by way of rejecting Locke's superficiality with regard to the
origin of ideas.
21. The CAUSA SUI is the best self-contradiction that has yet been
conceived, it is a sort of logical violation and unnaturalness; but the
extravagant pride of man has managed to entangle itself profoundly and
frightfully with this very folly. The desire for "freedom of will"
in the superlative, metaphysical sense, such as still holds sway,
unfortunately, in the minds of the half-educated, the desire to bear
the entire and ultimate responsibility for one's actions oneself, and
to absolve God, the world, ancestors, chance, and society therefrom,
involves nothing less than to be precisely this CAUSA SUI, and, with
more than Munchausen daring, to pull oneself up into existence by the
hair, out of the slough of nothingness. If any one should find out in
this manner the crass stupidity of the celebrated conception of "free
will" and put it out of his head altogether, I beg of him to carry
his "enlightenment" a step further, and also put out of his head the
contrary of this monstrous conception of "free will": I mean "non-free
will," which is tantamount to a misuse of cause and effect. One
should not wrongly MATERIALISE "cause" and "effect," as the natural
philosophers do (and whoever like them naturalize in thinking at
present), according to the prevailing mechanical doltishness which makes
the cause press and push until it "effects" its end; one should use
"cause" and "effect" only as pure CONCEPTIONS, that is to say, as
conventional fictions for the purpose of designation and mutual
understanding,--NOT for explanation. In "being-in-itself" there is
nothing of "casual-connection," of "necessity," or of "psychological
non-freedom"; there the effect does NOT follow the cause, there "law"
does not obtain. It is WE alone who have devised cause, sequence,
reciprocity, relativity, constraint, number, law, freedom, motive,
and purpose; and when we interpret and intermix this symbol-world,
as "being-in-itself," with things, we act once more as we have always
acted--MYTHOLOGICALLY. The "non-free will" is mythology; in real life
it is only a question of STRONG and WEAK wills.--It is almost always
a symptom of what is lacking in himself, when a thinker, in every
"causal-connection" and "psychological necessity," manifests something
of compulsion, indigence, obsequiousness, oppression, and non-freedom;
it is suspicious to have such feelings--the person betrays himself. And
in general, if I have observed correctly, the "non-freedom of the will"
is regarded as a problem from two entirely opposite standpoints, but
always in a profoundly PERSONAL manner: some will not give up their
"responsibility," their belief in THEMSELVES, the personal right to
THEIR merits, at any price (the vain races belong to this class); others
on the contrary, do not wish to be answerable for anything, or blamed
for anything, and owing to an inward self-contempt, seek to GET OUT OF
THE BUSINESS, no matter how. The latter, when they write books, are
in the habit at present of taking the side of criminals; a sort of
socialistic sympathy is their favourite disguise. And as a matter of
fact, the fatalism of the weak-willed embellishes itself surprisingly
when it can pose as "la religion de la souffrance humaine"; that is ITS
"good taste."
22. Let me be pardoned, as an old philologist who cannot desist from
the mischief of putting his finger on bad modes of interpretation, but
"Nature's conformity to law," of which you physicists talk so proudly,
as though--why, it exists only owing to your interpretation and bad
"philology." It is no matter of fact, no "text," but rather just a
naively humanitarian adjustment and perversion of meaning, with which
you make abundant concessions to the democratic instincts of the modern
soul! "Everywhere equality before the law--Nature is not different in
that respect, nor better than we": a fine instance of secret motive,
in which the vulgar antagonism to everything privileged and
autocratic--likewise a second and more refined atheism--is once more
disguised. "Ni dieu, ni maitre"--that, also, is what you want; and
therefore "Cheers for natural law!"--is it not so? But, as has been
said, that is interpretation, not text; and somebody might come along,
who, with opposite intentions and modes of interpretation, could read
out of the same "Nature," and with regard to the same phenomena, just
the tyrannically inconsiderate and relentless enforcement of the claims
of power--an interpreter who should so place the unexceptionalness and
unconditionalness of all "Will to Power" before your eyes, that almost
every word, and the word "tyranny" itself, would eventually seem
unsuitable, or like a weakening and softening metaphor--as being too
human; and who should, nevertheless, end by asserting the same about
this world as you do, namely, that it has a "necessary" and "calculable"
course, NOT, however, because laws obtain in it, but because they are
absolutely LACKING, and every power effects its ultimate consequences
every moment. Granted that this also is only interpretation--and you
will be eager enough to make this objection?--well, so much the better.
23. All psychology hitherto has run aground on moral prejudices and
timidities, it has not dared to launch out into the depths. In so far
as it is allowable to recognize in that which has hitherto been written,
evidence of that which has hitherto been kept silent, it seems as if
nobody had yet harboured the notion of psychology as the Morphology
and DEVELOPMENT-DOCTRINE OF THE WILL TO POWER, as I conceive of it.
The power of moral prejudices has penetrated deeply into the most
intellectual world, the world apparently most indifferent and
unprejudiced, and has obviously operated in an injurious, obstructive,
blinding, and distorting manner. A proper physio-psychology has to
contend with unconscious antagonism in the heart of the investigator,
it has "the heart" against it even a doctrine of the reciprocal
conditionalness of the "good" and the "bad" impulses, causes (as
refined immorality) distress and aversion in a still strong and manly
conscience--still more so, a doctrine of the derivation of all good
impulses from bad ones. If, however, a person should regard even
the emotions of hatred, envy, covetousness, and imperiousness
as life-conditioning emotions, as factors which must be present,
fundamentally and essentially, in the general economy of life (which
must, therefore, be further developed if life is to be further
developed), he will suffer from such a view of things as from
sea-sickness. And yet this hypothesis is far from being the strangest
and most painful in this immense and almost new domain of dangerous
knowledge, and there are in fact a hundred good reasons why every one
should keep away from it who CAN do so! On the other hand, if one has
once drifted hither with one's bark, well! very good! now let us set our
teeth firmly! let us open our eyes and keep our hand fast on the helm!
We sail away right OVER morality, we crush out, we destroy perhaps the
remains of our own morality by daring to make our voyage thither--but
what do WE matter. Never yet did a PROFOUNDER world of insight reveal
itself to daring travelers and adventurers, and the psychologist who
thus "makes a sacrifice"--it is not the sacrifizio dell' intelletto,
on the contrary!--will at least be entitled to demand in return that
psychology shall once more be recognized as the queen of the sciences,
for whose service and equipment the other sciences exist. For psychology
is once more the path to the fundamental problems.
CHAPTER II. THE FREE SPIRIT
24. O sancta simplicitiatas! In what strange simplification and
falsification man lives! One can never cease wondering when once one has
got eyes for beholding this marvel! How we have made everything around
us clear and free and easy and simple! how we have been able to give
our senses a passport to everything superficial, our thoughts a godlike
desire for wanton pranks and wrong inferences!--how from the beginning,
we have contrived to retain our ignorance in order to enjoy an almost
inconceivable freedom, thoughtlessness, imprudence, heartiness,
and gaiety--in order to enjoy life! And only on this solidified,
granite-like foundation of ignorance could knowledge rear itself
hitherto, the will to knowledge on the foundation of a far more powerful
will, the will to ignorance, to the uncertain, to the untrue! Not as
its opposite, but--as its refinement! It is to be hoped, indeed, that
LANGUAGE, here as elsewhere, will not get over its awkwardness, and that
it will continue to talk of opposites where there are only degrees
and many refinements of gradation; it is equally to be hoped that the
incarnated Tartuffery of morals, which now belongs to our unconquerable
"flesh and blood," will turn the words round in the mouths of us
discerning ones. Here and there we understand it, and laugh at the way
in which precisely the best knowledge seeks most to retain us in this
SIMPLIFIED, thoroughly artificial, suitably imagined, and suitably
falsified world: at the way in which, whether it will or not, it loves
error, because, as living itself, it loves life!
25. After such a cheerful commencement, a serious word would fain be
heard; it appeals to the most serious minds. Take care, ye philosophers
and friends of knowledge, and beware of martyrdom! Of suffering "for the
truth's sake"! even in your own defense! It spoils all the innocence
and fine neutrality of your conscience; it makes you headstrong against
objections and red rags; it stupefies, animalizes, and brutalizes, when
in the struggle with danger, slander, suspicion, expulsion, and even
worse consequences of enmity, ye have at last to play your last card
as protectors of truth upon earth--as though "the Truth" were such an
innocent and incompetent creature as to require protectors! and you of
all people, ye knights of the sorrowful countenance, Messrs Loafers and
Cobweb-spinners of the spirit! Finally, ye know sufficiently well that
it cannot be of any consequence if YE just carry your point; ye know
that hitherto no philosopher has carried his point, and that there might
be a more laudable truthfulness in every little interrogative mark
which you place after your special words and favourite doctrines (and
occasionally after yourselves) than in all the solemn pantomime and
trumping games before accusers and law-courts! Rather go out of the way!
Flee into concealment! And have your masks and your ruses, that ye may
be mistaken for what you are, or somewhat feared! And pray, don't forget
the garden, the garden with golden trellis-work! And have people around
you who are as a garden--or as music on the waters at eventide, when
already the day becomes a memory. Choose the GOOD solitude, the free,
wanton, lightsome solitude, which also gives you the right still to
remain good in any sense whatsoever! How poisonous, how crafty, how bad,
does every long war make one, which cannot be waged openly by means
of force! How PERSONAL does a long fear make one, a long watching
of enemies, of possible enemies! These pariahs of society, these
long-pursued, badly-persecuted ones--also the compulsory recluses, the
Spinozas or Giordano Brunos--always become in the end, even under the
most intellectual masquerade, and perhaps without being themselves aware
of it, refined vengeance-seekers and poison-Brewers (just lay bare
the foundation of Spinoza's ethics and theology!), not to speak of
the stupidity of moral indignation, which is the unfailing sign in a
philosopher that the sense of philosophical humour has left him. The
martyrdom of the philosopher, his "sacrifice for the sake of truth,"
forces into the light whatever of the agitator and actor lurks in him;
and if one has hitherto contemplated him only with artistic curiosity,
with regard to many a philosopher it is easy to understand the dangerous
desire to see him also in his deterioration (deteriorated into a
"martyr," into a stage-and-tribune-bawler). Only, that it is necessary
with such a desire to be clear WHAT spectacle one will see in any
case--merely a satyric play, merely an epilogue farce, merely the
continued proof that the long, real tragedy IS AT AN END, supposing that
every philosophy has been a long tragedy in its origin.
26. Every select man strives instinctively for a citadel and a privacy,
where he is FREE from the crowd, the many, the majority--where he may
forget "men who are the rule," as their exception;--exclusive only of
the case in which he is pushed straight to such men by a still stronger
instinct, as a discerner in the great and exceptional sense. Whoever, in
intercourse with men, does not occasionally glisten in all the green
and grey colours of distress, owing to disgust, satiety, sympathy,
gloominess, and solitariness, is assuredly not a man of elevated tastes;
supposing, however, that he does not voluntarily take all this burden
and disgust upon himself, that he persistently avoids it, and remains,
as I said, quietly and proudly hidden in his citadel, one thing is then
certain: he was not made, he was not predestined for knowledge. For as
such, he would one day have to say to himself: "The devil take my good
taste! but 'the rule' is more interesting than the exception--than
myself, the exception!" And he would go DOWN, and above all, he would
go "inside." The long and serious study of the AVERAGE man--and
consequently much disguise, self-overcoming, familiarity, and bad
intercourse (all intercourse is bad intercourse except with one's
equals):--that constitutes a necessary part of the life-history of every
philosopher; perhaps the most disagreeable, odious, and disappointing
part. If he is fortunate, however, as a favourite child of knowledge
should be, he will meet with suitable auxiliaries who will shorten and
lighten his task; I mean so-called cynics, those who simply recognize
the animal, the commonplace and "the rule" in themselves, and at the
same time have so much spirituality and ticklishness as to make them
talk of themselves and their like BEFORE WITNESSES--sometimes they
wallow, even in books, as on their own dung-hill. Cynicism is the only
form in which base souls approach what is called honesty; and the
higher man must open his ears to all the coarser or finer cynicism, and
congratulate himself when the clown becomes shameless right before
him, or the scientific satyr speaks out. There are even cases where
enchantment mixes with the disgust--namely, where by a freak of nature,
genius is bound to some such indiscreet billy-goat and ape, as in the
case of the Abbe Galiani, the profoundest, acutest, and perhaps also
filthiest man of his century--he was far profounder than Voltaire, and
consequently also, a good deal more silent. It happens more frequently,
as has been hinted, that a scientific head is placed on an ape's body, a
fine exceptional understanding in a base soul, an occurrence by no means
rare, especially among doctors and moral physiologists. And whenever
anyone speaks without bitterness, or rather quite innocently, of man
as a belly with two requirements, and a head with one; whenever any one
sees, seeks, and WANTS to see only hunger, sexual instinct, and vanity
as the real and only motives of human actions; in short, when any one
speaks "badly"--and not even "ill"--of man, then ought the lover of
knowledge to hearken attentively and diligently; he ought, in general,
to have an open ear wherever there is talk without indignation. For the
indignant man, and he who perpetually tears and lacerates himself with
his own teeth (or, in place of himself, the world, God, or society),
may indeed, morally speaking, stand higher than the laughing and
self-satisfied satyr, but in every other sense he is the more ordinary,
more indifferent, and less instructive case. And no one is such a LIAR
as the indignant man.
27. It is difficult to be understood, especially when one thinks and
lives gangasrotogati [Footnote: Like the river Ganges: presto.] among
those only who think and live otherwise--namely, kurmagati [Footnote:
Like the tortoise: lento.], or at best "froglike," mandeikagati
[Footnote: Like the frog: staccato.] (I do everything to be "difficultly
understood" myself!)--and one should be heartily grateful for the
good will to some refinement of interpretation. As regards "the good
friends," however, who are always too easy-going, and think that as
friends they have a right to ease, one does well at the very first to
grant them a play-ground and romping-place for misunderstanding--one can
thus laugh still; or get rid of them altogether, these good friends--and
laugh then also!
28. What is most difficult to render from one language into another
is the TEMPO of its style, which has its basis in the character of the
race, or to speak more physiologically, in the average TEMPO of the
assimilation of its nutriment. There are honestly meant translations,
which, as involuntary vulgarizations, are almost falsifications of the
original, merely because its lively and merry TEMPO (which overleaps and
obviates all dangers in word and expression) could not also be
rendered. A German is almost incapacitated for PRESTO in his language;
consequently also, as may be reasonably inferred, for many of the most
delightful and daring NUANCES of free, free-spirited thought. And just
as the buffoon and satyr are foreign to him in body and conscience,
so Aristophanes and Petronius are untranslatable for him. Everything
ponderous, viscous, and pompously clumsy, all long-winded and wearying
species of style, are developed in profuse variety among Germans--pardon
me for stating the fact that even Goethe's prose, in its mixture of
stiffness and elegance, is no exception, as a reflection of the "good
old time" to which it belongs, and as an expression of German taste at a
time when there was still a "German taste," which was a rococo-taste
in moribus et artibus. Lessing is an exception, owing to his histrionic
nature, which understood much, and was versed in many things; he who was
not the translator of Bayle to no purpose, who took refuge willingly in
the shadow of Diderot and Voltaire, and still more willingly among the
Roman comedy-writers--Lessing loved also free-spiritism in the TEMPO,
and flight out of Germany. But how could the German language, even
in the prose of Lessing, imitate the TEMPO of Machiavelli, who in his
"Principe" makes us breathe the dry, fine air of Florence, and cannot
help presenting the most serious events in a boisterous allegrissimo,
perhaps not without a malicious artistic sense of the contrast he
ventures to present--long, heavy, difficult, dangerous thoughts, and
a TEMPO of the gallop, and of the best, wantonest humour? Finally, who
would venture on a German translation of Petronius, who, more than any
great musician hitherto, was a master of PRESTO in invention, ideas, and
words? What matter in the end about the swamps of the sick, evil world,
or of the "ancient world," when like him, one has the feet of a wind,
the rush, the breath, the emancipating scorn of a wind, which makes
everything healthy, by making everything RUN! And with regard to
Aristophanes--that transfiguring, complementary genius, for whose
sake one PARDONS all Hellenism for having existed, provided one has
understood in its full profundity ALL that there requires pardon and
transfiguration; there is nothing that has caused me to meditate more on
PLATO'S secrecy and sphinx-like nature, than the happily preserved petit
fait that under the pillow of his death-bed there was found no
"Bible," nor anything Egyptian, Pythagorean, or Platonic--but a book of
Aristophanes. How could even Plato have endured life--a Greek life which
he repudiated--without an Aristophanes!
29. It is the business of the very few to be independent; it is a
privilege of the strong. And whoever attempts it, even with the best
right, but without being OBLIGED to do so, proves that he is probably
not only strong, but also daring beyond measure. He enters into a
labyrinth, he multiplies a thousandfold the dangers which life in itself
already brings with it; not the least of which is that no one can see
how and where he loses his way, becomes isolated, and is torn piecemeal
by some minotaur of conscience. Supposing such a one comes to grief, it
is so far from the comprehension of men that they neither feel it, nor
sympathize with it. And he cannot any longer go back! He cannot even go
back again to the sympathy of men!
30. Our deepest insights must--and should--appear as follies, and under
certain circumstances as crimes, when they come unauthorizedly to
the ears of those who are not disposed and predestined for them. The
exoteric and the esoteric, as they were formerly distinguished by
philosophers--among the Indians, as among the Greeks, Persians, and
Mussulmans, in short, wherever people believed in gradations of rank and
NOT in equality and equal rights--are not so much in contradistinction
to one another in respect to the exoteric class, standing without, and
viewing, estimating, measuring, and judging from the outside, and not
from the inside; the more essential distinction is that the class in
question views things from below upwards--while the esoteric class views
things FROM ABOVE DOWNWARDS. There are heights of the soul from which
tragedy itself no longer appears to operate tragically; and if all the
woe in the world were taken together, who would dare to decide whether
the sight of it would NECESSARILY seduce and constrain to sympathy, and
thus to a doubling of the woe?... That which serves the higher class of
men for nourishment or refreshment, must be almost poison to an entirely
different and lower order of human beings. The virtues of the common
man would perhaps mean vice and weakness in a philosopher; it might be
possible for a highly developed man, supposing him to degenerate and go
to ruin, to acquire qualities thereby alone, for the sake of which he
would have to be honoured as a saint in the lower world into which he
had sunk. There are books which have an inverse value for the soul and
the health according as the inferior soul and the lower vitality, or the
higher and more powerful, make use of them. In the former case they are
dangerous, disturbing, unsettling books, in the latter case they are
herald-calls which summon the bravest to THEIR bravery. Books for the
general reader are always ill-smelling books, the odour of paltry people
clings to them. Where the populace eat and drink, and even where they
reverence, it is accustomed to stink. One should not go into churches if
one wishes to breathe PURE air.
31. In our youthful years we still venerate and despise without the art
of NUANCE, which is the best gain of life, and we have rightly to do
hard penance for having fallen upon men and things with Yea and Nay.
Everything is so arranged that the worst of all tastes, THE TASTE FOR
THE UNCONDITIONAL, is cruelly befooled and abused, until a man learns
to introduce a little art into his sentiments, and prefers to try
conclusions with the artificial, as do the real artists of life. The
angry and reverent spirit peculiar to youth appears to allow itself no
peace, until it has suitably falsified men and things, to be able
to vent its passion upon them: youth in itself even, is something
falsifying and deceptive. Later on, when the young soul, tortured by
continual disillusions, finally turns suspiciously against itself--still
ardent and savage even in its suspicion and remorse of conscience: how
it upbraids itself, how impatiently it tears itself, how it revenges
itself for its long self-blinding, as though it had been a voluntary
blindness! In this transition one punishes oneself by distrust of one's
sentiments; one tortures one's enthusiasm with doubt, one feels even the
good conscience to be a danger, as if it were the self-concealment and
lassitude of a more refined uprightness; and above all, one espouses
upon principle the cause AGAINST "youth."--A decade later, and one
comprehends that all this was also still--youth!
32. Throughout the longest period of human history--one calls it the
prehistoric period--the value or non-value of an action was inferred
from its CONSEQUENCES; the action in itself was not taken into
consideration, any more than its origin; but pretty much as in China at
present, where the distinction or disgrace of a child redounds to
its parents, the retro-operating power of success or failure was what
induced men to think well or ill of an action. Let us call this period
the PRE-MORAL period of mankind; the imperative, "Know thyself!" was
then still unknown.--In the last ten thousand years, on the other hand,
on certain large portions of the earth, one has gradually got so far,
that one no longer lets the consequences of an action, but its origin,
decide with regard to its worth: a great achievement as a whole, an
important refinement of vision and of criterion, the unconscious effect
of the supremacy of aristocratic values and of the belief in "origin,"
the mark of a period which may be designated in the narrower sense as
the MORAL one: the first attempt at self-knowledge is thereby
made. Instead of the consequences, the origin--what an inversion
of perspective! And assuredly an inversion effected only after long
struggle and wavering! To be sure, an ominous new superstition, a
peculiar narrowness of interpretation, attained supremacy precisely
thereby: the origin of an action was interpreted in the most definite
sense possible, as origin out of an INTENTION; people were agreed in the
belief that the value of an action lay in the value of its intention.
The intention as the sole origin and antecedent history of an action:
under the influence of this prejudice moral praise and blame have been
bestowed, and men have judged and even philosophized almost up to the
present day.--Is it not possible, however, that the necessity may now
have arisen of again making up our minds with regard to the reversing
and fundamental shifting of values, owing to a new self-consciousness
and acuteness in man--is it not possible that we may be standing on
the threshold of a period which to begin with, would be distinguished
negatively as ULTRA-MORAL: nowadays when, at least among us immoralists,
the suspicion arises that the decisive value of an action lies precisely
in that which is NOT INTENTIONAL, and that all its intentionalness, all
that is seen, sensible, or "sensed" in it, belongs to its surface or
skin--which, like every skin, betrays something, but CONCEALS still
more? In short, we believe that the intention is only a sign or symptom,
which first requires an explanation--a sign, moreover, which has too
many interpretations, and consequently hardly any meaning in itself
alone: that morality, in the sense in which it has been understood
hitherto, as intention-morality, has been a prejudice, perhaps a
prematureness or preliminariness, probably something of the same rank
as astrology and alchemy, but in any case something which must be
surmounted. The surmounting of morality, in a certain sense even the
self-mounting of morality--let that be the name for the long-secret
labour which has been reserved for the most refined, the most upright,
and also the most wicked consciences of today, as the living touchstones
of the soul.
33. It cannot be helped: the sentiment of surrender, of sacrifice for
one's neighbour, and all self-renunciation-morality, must be mercilessly
called to account, and brought to judgment; just as the aesthetics
of "disinterested contemplation," under which the emasculation of art
nowadays seeks insidiously enough to create itself a good conscience.
There is far too much witchery and sugar in the sentiments "for others"
and "NOT for myself," for one not needing to be doubly distrustful here,
and for one asking promptly: "Are they not perhaps--DECEPTIONS?"--That
they PLEASE--him who has them, and him who enjoys their fruit, and also
the mere spectator--that is still no argument in their FAVOUR, but just
calls for caution. Let us therefore be cautious!
34. At whatever standpoint of philosophy one may place oneself nowadays,
seen from every position, the ERRONEOUSNESS of the world in which we
think we live is the surest and most certain thing our eyes can light
upon: we find proof after proof thereof, which would fain allure us into
surmises concerning a deceptive principle in the "nature of things."
He, however, who makes thinking itself, and consequently "the spirit,"
responsible for the falseness of the world--an honourable exit, which
every conscious or unconscious advocatus dei avails himself of--he
who regards this world, including space, time, form, and movement, as
falsely DEDUCED, would have at least good reason in the end to become
distrustful also of all thinking; has it not hitherto been playing upon
us the worst of scurvy tricks? and what guarantee would it give that
it would not continue to do what it has always been doing? In all
seriousness, the innocence of thinkers has something touching and
respect-inspiring in it, which even nowadays permits them to wait upon
consciousness with the request that it will give them HONEST answers:
for example, whether it be "real" or not, and why it keeps the outer
world so resolutely at a distance, and other questions of the same
description. The belief in "immediate certainties" is a MORAL NAIVETE
which does honour to us philosophers; but--we have now to cease being
"MERELY moral" men! Apart from morality, such belief is a folly which
does little honour to us! If in middle-class life an ever-ready distrust
is regarded as the sign of a "bad character," and consequently as an
imprudence, here among us, beyond the middle-class world and its Yeas
and Nays, what should prevent our being imprudent and saying: the
philosopher has at length a RIGHT to "bad character," as the being who
has hitherto been most befooled on earth--he is now under OBLIGATION
to distrustfulness, to the wickedest squinting out of every abyss of
suspicion.--Forgive me the joke of this gloomy grimace and turn of
expression; for I myself have long ago learned to think and estimate
differently with regard to deceiving and being deceived, and I keep at
least a couple of pokes in the ribs ready for the blind rage with which
philosophers struggle against being deceived. Why NOT? It is nothing
more than a moral prejudice that truth is worth more than semblance; it
is, in fact, the worst proved supposition in the world. So much must be
conceded: there could have been no life at all except upon the basis
of perspective estimates and semblances; and if, with the virtuous
enthusiasm and stupidity of many philosophers, one wished to do away
altogether with the "seeming world"--well, granted that YOU could do
that,--at least nothing of your "truth" would thereby remain! Indeed,
what is it that forces us in general to the supposition that there is an
essential opposition of "true" and "false"? Is it not enough to suppose
degrees of seemingness, and as it were lighter and darker shades and
tones of semblance--different valeurs, as the painters say? Why might
not the world WHICH CONCERNS US--be a fiction? And to any one who
suggested: "But to a fiction belongs an originator?"--might it not be
bluntly replied: WHY? May not this "belong" also belong to the fiction?
Is it not at length permitted to be a little ironical towards the
subject, just as towards the predicate and object? Might not the
philosopher elevate himself above faith in grammar? All respect
to governesses, but is it not time that philosophy should renounce
governess-faith?
35. O Voltaire! O humanity! O idiocy! There is something ticklish in
"the truth," and in the SEARCH for the truth; and if man goes about it
too humanely--"il ne cherche le vrai que pour faire le bien"--I wager he
finds nothing!
36. Supposing that nothing else is "given" as real but our world of
desires and passions, that we cannot sink or rise to any other "reality"
but just that of our impulses--for thinking is only a relation of these
impulses to one another:--are we not permitted to make the attempt and
to ask the question whether this which is "given" does not SUFFICE, by
means of our counterparts, for the understanding even of the so-called
mechanical (or "material") world? I do not mean as an illusion, a
"semblance," a "representation" (in the Berkeleyan and Schopenhauerian
sense), but as possessing the same degree of reality as our emotions
themselves--as a more primitive form of the world of emotions, in
which everything still lies locked in a mighty unity, which afterwards
branches off and develops itself in organic processes (naturally also,
refines and debilitates)--as a kind of instinctive life in which all
organic functions, including self-regulation, assimilation, nutrition,
secretion, and change of matter, are still synthetically united with
one another--as a PRIMARY FORM of life?--In the end, it is not only
permitted to make this attempt, it is commanded by the conscience of
LOGICAL METHOD. Not to assume several kinds of causality, so long as
the attempt to get along with a single one has not been pushed to its
furthest extent (to absurdity, if I may be allowed to say so): that is
a morality of method which one may not repudiate nowadays--it follows
"from its definition," as mathematicians say. The question is ultimately
whether we really recognize the will as OPERATING, whether we believe in
the causality of the will; if we do so--and fundamentally our belief IN
THIS is just our belief in causality itself--we MUST make the attempt
to posit hypothetically the causality of the will as the only causality.
"Will" can naturally only operate on "will"--and not on "matter" (not
on "nerves," for instance): in short, the hypothesis must be
hazarded, whether will does not operate on will wherever "effects"
are recognized--and whether all mechanical action, inasmuch as a power
operates therein, is not just the power of will, the effect of will.
Granted, finally, that we succeeded in explaining our entire instinctive
life as the development and ramification of one fundamental form of
will--namely, the Will to Power, as my thesis puts it; granted that all
organic functions could be traced back to this Will to Power, and that
the solution of the problem of generation and nutrition--it is one
problem--could also be found therein: one would thus have acquired the
right to define ALL active force unequivocally as WILL TO POWER. The
world seen from within, the world defined and designated according to
its "intelligible character"--it would simply be "Will to Power," and
nothing else.
37. "What? Does not that mean in popular language: God is disproved, but
not the devil?"--On the contrary! On the contrary, my friends! And who
the devil also compels you to speak popularly!
38. As happened finally in all the enlightenment of modern times with
the French Revolution (that terrible farce, quite superfluous when
judged close at hand, into which, however, the noble and visionary
spectators of all Europe have interpreted from a distance their own
indignation and enthusiasm so long and passionately, UNTIL THE TEXT HAS
DISAPPEARED UNDER THE INTERPRETATION), so a noble posterity might once
more misunderstand the whole of the past, and perhaps only thereby make
ITS aspect endurable.--Or rather, has not this already happened? Have
not we ourselves been--that "noble posterity"? And, in so far as we now
comprehend this, is it not--thereby already past?
39. Nobody will very readily regard a doctrine as true merely because
it makes people happy or virtuous--excepting, perhaps, the amiable
"Idealists," who are enthusiastic about the good, true, and beautiful,
and let all kinds of motley, coarse, and good-natured desirabilities
swim about promiscuously in their pond. Happiness and virtue are no
arguments. It is willingly forgotten, however, even on the part of
thoughtful minds, that to make unhappy and to make bad are just as
little counter-arguments. A thing could be TRUE, although it were in
the highest degree injurious and dangerous; indeed, the fundamental
constitution of existence might be such that one succumbed by a full
knowledge of it--so that the strength of a mind might be measured by
the amount of "truth" it could endure--or to speak more plainly, by the
extent to which it REQUIRED truth attenuated, veiled, sweetened, damped,
and falsified. But there is no doubt that for the discovery of certain
PORTIONS of truth the wicked and unfortunate are more favourably
situated and have a greater likelihood of success; not to speak of the
wicked who are happy--a species about whom moralists are silent. Perhaps
severity and craft are more favourable conditions for the development of
strong, independent spirits and philosophers than the gentle, refined,
yielding good-nature, and habit of taking things easily, which are
prized, and rightly prized in a learned man. Presupposing always,
to begin with, that the term "philosopher" be not confined to the
philosopher who writes books, or even introduces HIS philosophy into
books!--Stendhal furnishes a last feature of the portrait of the
free-spirited philosopher, which for the sake of German taste I will
not omit to underline--for it is OPPOSED to German taste. "Pour etre
bon philosophe," says this last great psychologist, "il faut etre sec,
clair, sans illusion. Un banquier, qui a fait fortune, a une partie du
caractere requis pour faire des decouvertes en philosophie, c'est-a-dire
pour voir clair dans ce qui est."
40. Everything that is profound loves the mask: the profoundest things
have a hatred even of figure and likeness. Should not the CONTRARY only
be the right disguise for the shame of a God to go about in? A question
worth asking!--it would be strange if some mystic has not already
ventured on the same kind of thing. There are proceedings of such a
delicate nature that it is well to overwhelm them with coarseness
and make them unrecognizable; there are actions of love and of an
extravagant magnanimity after which nothing can be wiser than to take
a stick and thrash the witness soundly: one thereby obscures his
recollection. Many a one is able to obscure and abuse his own memory, in
order at least to have vengeance on this sole party in the secret:
shame is inventive. They are not the worst things of which one is
most ashamed: there is not only deceit behind a mask--there is so much
goodness in craft. I could imagine that a man with something costly and
fragile to conceal, would roll through life clumsily and rotundly like
an old, green, heavily-hooped wine-cask: the refinement of his shame
requiring it to be so. A man who has depths in his shame meets his
destiny and his delicate decisions upon paths which few ever reach,
and with regard to the existence of which his nearest and most intimate
friends may be ignorant; his mortal danger conceals itself from their
eyes, and equally so his regained security. Such a hidden nature,
which instinctively employs speech for silence and concealment, and is
inexhaustible in evasion of communication, DESIRES and insists that a
mask of himself shall occupy his place in the hearts and heads of his
friends; and supposing he does not desire it, his eyes will some day be
opened to the fact that there is nevertheless a mask of him there--and
that it is well to be so. Every profound spirit needs a mask; nay, more,
around every profound spirit there continually grows a mask, owing to
the constantly false, that is to say, SUPERFICIAL interpretation
of every word he utters, every step he takes, every sign of life he
manifests.
41. One must subject oneself to one's own tests that one is destined
for independence and command, and do so at the right time. One must not
avoid one's tests, although they constitute perhaps the most dangerous
game one can play, and are in the end tests made only before ourselves
and before no other judge. Not to cleave to any person, be it even the
dearest--every person is a prison and also a recess. Not to cleave to
a fatherland, be it even the most suffering and necessitous--it is even
less difficult to detach one's heart from a victorious fatherland. Not
to cleave to a sympathy, be it even for higher men, into whose peculiar
torture and helplessness chance has given us an insight. Not to cleave
to a science, though it tempt one with the most valuable discoveries,
apparently specially reserved for us. Not to cleave to one's own
liberation, to the voluptuous distance and remoteness of the bird, which
always flies further aloft in order always to see more under it--the
danger of the flier. Not to cleave to our own virtues, nor become as
a whole a victim to any of our specialties, to our "hospitality" for
instance, which is the danger of dangers for highly developed
and wealthy souls, who deal prodigally, almost indifferently with
themselves, and push the virtue of liberality so far that it becomes
a vice. One must know how TO CONSERVE ONESELF--the best test of
independence.
42. A new order of philosophers is appearing; I shall venture to baptize
them by a name not without danger. As far as I understand them, as far
as they allow themselves to be understood--for it is their nature to
WISH to remain something of a puzzle--these philosophers of the
future might rightly, perhaps also wrongly, claim to be designated as
"tempters." This name itself is after all only an attempt, or, if it be
preferred, a temptation.
43. Will they be new friends of "truth," these coming philosophers? Very
probably, for all philosophers hitherto have loved their truths. But
assuredly they will not be dogmatists. It must be contrary to their
pride, and also contrary to their taste, that their truth should still
be truth for every one--that which has hitherto been the secret wish
and ultimate purpose of all dogmatic efforts. "My opinion is MY opinion:
another person has not easily a right to it"--such a philosopher of the
future will say, perhaps. One must renounce the bad taste of wishing to
agree with many people. "Good" is no longer good when one's neighbour
takes it into his mouth. And how could there be a "common good"! The
expression contradicts itself; that which can be common is always of
small value. In the end things must be as they are and have always
been--the great things remain for the great, the abysses for the
profound, the delicacies and thrills for the refined, and, to sum up
shortly, everything rare for the rare.
44. Need I say expressly after all this that they will be free, VERY
free spirits, these philosophers of the future--as certainly also they
will not be merely free spirits, but something more, higher, greater,
and fundamentally different, which does not wish to be misunderstood and
mistaken? But while I say this, I feel under OBLIGATION almost as much
to them as to ourselves (we free spirits who are their heralds and
forerunners), to sweep away from ourselves altogether a stupid old
prejudice and misunderstanding, which, like a fog, has too long made the
conception of "free spirit" obscure. In every country of Europe, and the
same in America, there is at present something which makes an abuse of
this name a very narrow, prepossessed, enchained class of spirits,
who desire almost the opposite of what our intentions and instincts
prompt--not to mention that in respect to the NEW philosophers who are
appearing, they must still more be closed windows and bolted doors.
Briefly and regrettably, they belong to the LEVELLERS, these wrongly
named "free spirits"--as glib-tongued and scribe-fingered slaves of
the democratic taste and its "modern ideas" all of them men without
solitude, without personal solitude, blunt honest fellows to whom
neither courage nor honourable conduct ought to be denied, only, they
are not free, and are ludicrously superficial, especially in their
innate partiality for seeing the cause of almost ALL human misery and
failure in the old forms in which society has hitherto existed--a notion
which happily inverts the truth entirely! What they would fain attain
with all their strength, is the universal, green-meadow happiness of the
herd, together with security, safety, comfort, and alleviation of life
for every one, their two most frequently chanted songs and doctrines
are called "Equality of Rights" and "Sympathy with All Sufferers"--and
suffering itself is looked upon by them as something which must be
DONE AWAY WITH. We opposite ones, however, who have opened our eye and
conscience to the question how and where the plant "man" has hitherto
grown most vigorously, believe that this has always taken place under
the opposite conditions, that for this end the dangerousness of his
situation had to be increased enormously, his inventive faculty and
dissembling power (his "spirit") had to develop into subtlety and daring
under long oppression and compulsion, and his Will to Life had to be
increased to the unconditioned Will to Power--we believe that severity,
violence, slavery, danger in the street and in the heart, secrecy,
stoicism, tempter's art and devilry of every kind,--that everything
wicked, terrible, tyrannical, predatory, and serpentine in man, serves
as well for the elevation of the human species as its opposite--we do
not even say enough when we only say THIS MUCH, and in any case we
find ourselves here, both with our speech and our silence, at the OTHER
extreme of all modern ideology and gregarious desirability, as their
antipodes perhaps? What wonder that we "free spirits" are not exactly
the most communicative spirits? that we do not wish to betray in every
respect WHAT a spirit can free itself from, and WHERE perhaps it will
then be driven? And as to the import of the dangerous formula, "Beyond
Good and Evil," with which we at least avoid confusion, we ARE something
else than "libres-penseurs," "liben pensatori" "free-thinkers,"
and whatever these honest advocates of "modern ideas" like to call
themselves. Having been at home, or at least guests, in many realms of
the spirit, having escaped again and again from the gloomy, agreeable
nooks in which preferences and prejudices, youth, origin, the accident
of men and books, or even the weariness of travel seemed to confine us,
full of malice against the seductions of dependency which he concealed
in honours, money, positions, or exaltation of the senses, grateful even
for distress and the vicissitudes of illness, because they always free
us from some rule, and its "prejudice," grateful to the God, devil,
sheep, and worm in us, inquisitive to a fault, investigators to the
point of cruelty, with unhesitating fingers for the intangible, with
teeth and stomachs for the most indigestible, ready for any business
that requires sagacity and acute senses, ready for every adventure,
owing to an excess of "free will", with anterior and posterior souls,
into the ultimate intentions of which it is difficult to pry, with
foregrounds and backgrounds to the end of which no foot may run, hidden
ones under the mantles of light, appropriators, although we resemble
heirs and spendthrifts, arrangers and collectors from morning till
night, misers of our wealth and our full-crammed drawers, economical
in learning and forgetting, inventive in scheming, sometimes proud of
tables of categories, sometimes pedants, sometimes night-owls of
work even in full day, yea, if necessary, even scarecrows--and it is
necessary nowadays, that is to say, inasmuch as we are the born, sworn,
jealous friends of SOLITUDE, of our own profoundest midnight and midday
solitude--such kind of men are we, we free spirits! And perhaps ye are
also something of the same kind, ye coming ones? ye NEW philosophers?
CHAPTER III. THE RELIGIOUS MOOD
45. The human soul and its limits, the range of man's inner experiences
hitherto attained, the heights, depths, and distances of these
experiences, the entire history of the soul UP TO THE PRESENT TIME,
and its still unexhausted possibilities: this is the preordained
hunting-domain for a born psychologist and lover of a "big hunt". But
how often must he say despairingly to himself: "A single individual!
alas, only a single individual! and this great forest, this virgin
forest!" So he would like to have some hundreds of hunting assistants,
and fine trained hounds, that he could send into the history of the
human soul, to drive HIS game together. In vain: again and again he
experiences, profoundly and bitterly, how difficult it is to find
assistants and dogs for all the things that directly excite his
curiosity. The evil of sending scholars into new and dangerous
hunting-domains, where courage, sagacity, and subtlety in every sense
are required, is that they are no longer serviceable just when the "BIG
hunt," and also the great danger commences,--it is precisely then that
they lose their keen eye and nose. In order, for instance, to divine and
determine what sort of history the problem of KNOWLEDGE AND CONSCIENCE
has hitherto had in the souls of homines religiosi, a person would
perhaps himself have to possess as profound, as bruised, as immense an
experience as the intellectual conscience of Pascal; and then he would
still require that wide-spread heaven of clear, wicked spirituality,
which, from above, would be able to oversee, arrange, and effectively
formulize this mass of dangerous and painful experiences.--But who
could do me this service! And who would have time to wait for such
servants!--they evidently appear too rarely, they are so improbable at
all times! Eventually one must do everything ONESELF in order to know
something; which means that one has MUCH to do!--But a curiosity like
mine is once for all the most agreeable of vices--pardon me! I mean to
say that the love of truth has its reward in heaven, and already upon
earth.
46. Faith, such as early Christianity desired, and not infrequently
achieved in the midst of a skeptical and southernly free-spirited world,
which had centuries of struggle between philosophical schools behind
it and in it, counting besides the education in tolerance which
the Imperium Romanum gave--this faith is NOT that sincere, austere
slave-faith by which perhaps a Luther or a Cromwell, or some other
northern barbarian of the spirit remained attached to his God and
Christianity, it is much rather the faith of Pascal, which resembles in
a terrible manner a continuous suicide of reason--a tough, long-lived,
worm-like reason, which is not to be slain at once and with a single
blow. The Christian faith from the beginning, is sacrifice the sacrifice
of all freedom, all pride, all self-confidence of spirit, it is at
the same time subjection, self-derision, and self-mutilation. There is
cruelty and religious Phoenicianism in this faith, which is adapted to a
tender, many-sided, and very fastidious conscience, it takes for granted
that the subjection of the spirit is indescribably PAINFUL, that all the
past and all the habits of such a spirit resist the absurdissimum, in
the form of which "faith" comes to it. Modern men, with their obtuseness
as regards all Christian nomenclature, have no longer the sense for the
terribly superlative conception which was implied to an antique taste by
the paradox of the formula, "God on the Cross". Hitherto there had never
and nowhere been such boldness in inversion, nor anything at once so
dreadful, questioning, and questionable as this formula: it promised a
transvaluation of all ancient values--It was the Orient, the PROFOUND
Orient, it was the Oriental slave who thus took revenge on Rome and its
noble, light-minded toleration, on the Roman "Catholicism" of non-faith,
and it was always not the faith, but the freedom from the faith, the
half-stoical and smiling indifference to the seriousness of the faith,
which made the slaves indignant at their masters and revolt against
them. "Enlightenment" causes revolt, for the slave desires the
unconditioned, he understands nothing but the tyrannous, even in morals,
he loves as he hates, without NUANCE, to the very depths, to the point
of pain, to the point of sickness--his many HIDDEN sufferings make
him revolt against the noble taste which seems to DENY suffering. The
skepticism with regard to suffering, fundamentally only an attitude of
aristocratic morality, was not the least of the causes, also, of the
last great slave-insurrection which began with the French Revolution.
47. Wherever the religious neurosis has appeared on the earth so far,
we find it connected with three dangerous prescriptions as to regimen:
solitude, fasting, and sexual abstinence--but without its being possible
to determine with certainty which is cause and which is effect, or IF
any relation at all of cause and effect exists there. This latter doubt
is justified by the fact that one of the most regular symptoms among
savage as well as among civilized peoples is the most sudden and
excessive sensuality, which then with equal suddenness transforms into
penitential paroxysms, world-renunciation, and will-renunciation, both
symptoms perhaps explainable as disguised epilepsy? But nowhere is it
MORE obligatory to put aside explanations around no other type has there
grown such a mass of absurdity and superstition, no other type seems to
have been more interesting to men and even to philosophers--perhaps it
is time to become just a little indifferent here, to learn caution, or,
better still, to look AWAY, TO GO AWAY--Yet in the background of the
most recent philosophy, that of Schopenhauer, we find almost as the
problem in itself, this terrible note of interrogation of the religious
crisis and awakening. How is the negation of will POSSIBLE? how is the
saint possible?--that seems to have been the very question with which
Schopenhauer made a start and became a philosopher. And thus it was a
genuine Schopenhauerian consequence, that his most convinced adherent
(perhaps also his last, as far as Germany is concerned), namely, Richard
Wagner, should bring his own life-work to an end just here, and should
finally put that terrible and eternal type upon the stage as Kundry,
type vecu, and as it loved and lived, at the very time that the
mad-doctors in almost all European countries had an opportunity to study
the type close at hand, wherever the religious neurosis--or as I call
it, "the religious mood"--made its latest epidemical outbreak and
display as the "Salvation Army"--If it be a question, however, as to
what has been so extremely interesting to men of all sorts in all ages,
and even to philosophers, in the whole phenomenon of the saint, it
is undoubtedly the appearance of the miraculous therein--namely, the
immediate SUCCESSION OF OPPOSITES, of states of the soul regarded as
morally antithetical: it was believed here to be self-evident that
a "bad man" was all at once turned into a "saint," a good man. The
hitherto existing psychology was wrecked at this point, is it not
possible it may have happened principally because psychology had placed
itself under the dominion of morals, because it BELIEVED in oppositions
of moral values, and saw, read, and INTERPRETED these oppositions
into the text and facts of the case? What? "Miracle" only an error of
interpretation? A lack of philology?
48. It seems that the Latin races are far more deeply attached to their
Catholicism than we Northerners are to Christianity generally, and
that consequently unbelief in Catholic countries means something quite
different from what it does among Protestants--namely, a sort of revolt
against the spirit of the race, while with us it is rather a return to
the spirit (or non-spirit) of the race.
We Northerners undoubtedly derive our origin from barbarous races, even
as regards our talents for religion--we have POOR talents for it. One
may make an exception in the case of the Celts, who have theretofore
furnished also the best soil for Christian infection in the North: the
Christian ideal blossomed forth in France as much as ever the pale sun
of the north would allow it. How strangely pious for our taste are still
these later French skeptics, whenever there is any Celtic blood in their
origin! How Catholic, how un-German does Auguste Comte's Sociology
seem to us, with the Roman logic of its instincts! How Jesuitical, that
amiable and shrewd cicerone of Port Royal, Sainte-Beuve, in spite of all
his hostility to Jesuits! And even Ernest Renan: how inaccessible to
us Northerners does the language of such a Renan appear, in whom
every instant the merest touch of religious thrill throws his refined
voluptuous and comfortably couching soul off its balance! Let us repeat
after him these fine sentences--and what wickedness and haughtiness is
immediately aroused by way of answer in our probably less beautiful but
harder souls, that is to say, in our more German souls!--"DISONS DONC
HARDIMENT QUE LA RELIGION EST UN PRODUIT DE L'HOMME NORMAL, QUE L'HOMME
EST LE PLUS DANS LE VRAI QUANT IL EST LE PLUS RELIGIEUX ET LE PLUS
ASSURE D'UNE DESTINEE INFINIE.... C'EST QUAND IL EST BON QU'IL VEUT QUE
LA VIRTU CORRESPONDE A UN ORDER ETERNAL, C'EST QUAND IL CONTEMPLE LES
CHOSES D'UNE MANIERE DESINTERESSEE QU'IL TROUVE LA MORT REVOLTANTE ET
ABSURDE. COMMENT NE PAS SUPPOSER QUE C'EST DANS CES MOMENTS-LA, QUE
L'HOMME VOIT LE MIEUX?"... These sentences are so extremely ANTIPODAL
to my ears and habits of thought, that in my first impulse of rage
on finding them, I wrote on the margin, "LA NIAISERIE RELIGIEUSE PAR
EXCELLENCE!"--until in my later rage I even took a fancy to them, these
sentences with their truth absolutely inverted! It is so nice and such a
distinction to have one's own antipodes!
49. That which is so astonishing in the religious life of the ancient
Greeks is the irrestrainable stream of GRATITUDE which it pours
forth--it is a very superior kind of man who takes SUCH an attitude
towards nature and life.--Later on, when the populace got the upper hand
in Greece, FEAR became rampant also in religion; and Christianity was
preparing itself.
50. The passion for God: there are churlish, honest-hearted, and
importunate kinds of it, like that of Luther--the whole of Protestantism
lacks the southern DELICATEZZA. There is an Oriental exaltation of the
mind in it, like that of an undeservedly favoured or elevated slave, as
in the case of St. Augustine, for instance, who lacks in an offensive
manner, all nobility in bearing and desires. There is a feminine
tenderness and sensuality in it, which modestly and unconsciously longs
for a UNIO MYSTICA ET PHYSICA, as in the case of Madame de Guyon. In
many cases it appears, curiously enough, as the disguise of a girl's
or youth's puberty; here and there even as the hysteria of an old maid,
also as her last ambition. The Church has frequently canonized the woman
in such a case.
51. The mightiest men have hitherto always bowed reverently before
the saint, as the enigma of self-subjugation and utter voluntary
privation--why did they thus bow? They divined in him--and as it were
behind the questionableness of his frail and wretched appearance--the
superior force which wished to test itself by such a subjugation; the
strength of will, in which they recognized their own strength and
love of power, and knew how to honour it: they honoured something
in themselves when they honoured the saint. In addition to this, the
contemplation of the saint suggested to them a suspicion: such an
enormity of self-negation and anti-naturalness will not have been
coveted for nothing--they have said, inquiringly. There is perhaps a
reason for it, some very great danger, about which the ascetic might
wish to be more accurately informed through his secret interlocutors and
visitors? In a word, the mighty ones of the world learned to have a new
fear before him, they divined a new power, a strange, still unconquered
enemy:--it was the "Will to Power" which obliged them to halt before the
saint. They had to question him.
52. In the Jewish "Old Testament," the book of divine justice, there are
men, things, and sayings on such an immense scale, that Greek and Indian
literature has nothing to compare with it. One stands with fear and
reverence before those stupendous remains of what man was formerly, and
one has sad thoughts about old Asia and its little out-pushed peninsula
Europe, which would like, by all means, to figure before Asia as the
"Progress of Mankind." To be sure, he who is himself only a slender,
tame house-animal, and knows only the wants of a house-animal (like
our cultured people of today, including the Christians of "cultured"
Christianity), need neither be amazed nor even sad amid those ruins--the
taste for the Old Testament is a touchstone with respect to "great" and
"small": perhaps he will find that the New Testament, the book of grace,
still appeals more to his heart (there is much of the odour of the
genuine, tender, stupid beadsman and petty soul in it). To have bound
up this New Testament (a kind of ROCOCO of taste in every respect) along
with the Old Testament into one book, as the "Bible," as "The Book in
Itself," is perhaps the greatest audacity and "sin against the Spirit"
which literary Europe has upon its conscience.
53. Why Atheism nowadays? "The father" in God is thoroughly refuted;
equally so "the judge," "the rewarder." Also his "free will": he does
not hear--and even if he did, he would not know how to help. The worst
is that he seems incapable of communicating himself clearly; is he
uncertain?--This is what I have made out (by questioning and listening
at a variety of conversations) to be the cause of the decline of
European theism; it appears to me that though the religious instinct is
in vigorous growth,--it rejects the theistic satisfaction with profound
distrust.
54. What does all modern philosophy mainly do? Since Descartes--and
indeed more in defiance of him than on the basis of his procedure--an
ATTENTAT has been made on the part of all philosophers on the old
conception of the soul, under the guise of a criticism of the subject
and predicate conception--that is to say, an ATTENTAT on the
fundamental presupposition of Christian doctrine. Modern philosophy,
as epistemological skepticism, is secretly or openly ANTI-CHRISTIAN,
although (for keener ears, be it said) by no means anti-religious.
Formerly, in effect, one believed in "the soul" as one believed in
grammar and the grammatical subject: one said, "I" is the condition,
"think" is the predicate and is conditioned--to think is an activity for
which one MUST suppose a subject as cause. The attempt was then made,
with marvelous tenacity and subtlety, to see if one could not get out
of this net,--to see if the opposite was not perhaps true: "think" the
condition, and "I" the conditioned; "I," therefore, only a synthesis
which has been MADE by thinking itself. KANT really wished to prove
that, starting from the subject, the subject could not be proved--nor
the object either: the possibility of an APPARENT EXISTENCE of the
subject, and therefore of "the soul," may not always have been strange
to him,--the thought which once had an immense power on earth as the
Vedanta philosophy.
55. There is a great ladder of religious cruelty, with many rounds; but
three of these are the most important. Once on a time men sacrificed
human beings to their God, and perhaps just those they loved the
best--to this category belong the firstling sacrifices of all primitive
religions, and also the sacrifice of the Emperor Tiberius in the
Mithra-Grotto on the Island of Capri, that most terrible of all Roman
anachronisms. Then, during the moral epoch of mankind, they sacrificed
to their God the strongest instincts they possessed, their "nature";
THIS festal joy shines in the cruel glances of ascetics and
"anti-natural" fanatics. Finally, what still remained to be sacrificed?
Was it not necessary in the end for men to sacrifice everything
comforting, holy, healing, all hope, all faith in hidden harmonies, in
future blessedness and justice? Was it not necessary to sacrifice God
himself, and out of cruelty to themselves to worship stone, stupidity,
gravity, fate, nothingness? To sacrifice God for nothingness--this
paradoxical mystery of the ultimate cruelty has been reserved for the
rising generation; we all know something thereof already.
56. Whoever, like myself, prompted by some enigmatical desire, has long
endeavoured to go to the bottom of the question of pessimism and free it
from the half-Christian, half-German narrowness and stupidity in which
it has finally presented itself to this century, namely, in the form of
Schopenhauer's philosophy; whoever, with an Asiatic and super-Asiatic
eye, has actually looked inside, and into the most world-renouncing of
all possible modes of thought--beyond good and evil, and no longer
like Buddha and Schopenhauer, under the dominion and delusion of
morality,--whoever has done this, has perhaps just thereby, without
really desiring it, opened his eyes to behold the opposite ideal: the
ideal of the most world-approving, exuberant, and vivacious man, who has
not only learnt to compromise and arrange with that which was and
is, but wishes to have it again AS IT WAS AND IS, for all eternity,
insatiably calling out da capo, not only to himself, but to the whole
piece and play; and not only the play, but actually to him who requires
the play--and makes it necessary; because he always requires
himself anew--and makes himself necessary.--What? And this would not
be--circulus vitiosus deus?
57. The distance, and as it were the space around man, grows with the
strength of his intellectual vision and insight: his world becomes
profounder; new stars, new enigmas, and notions are ever coming into
view. Perhaps everything on which the intellectual eye has exercised
its acuteness and profundity has just been an occasion for its exercise,
something of a game, something for children and childish minds. Perhaps
the most solemn conceptions that have caused the most fighting and
suffering, the conceptions "God" and "sin," will one day seem to us of
no more importance than a child's plaything or a child's pain seems to
an old man;--and perhaps another plaything and another pain will then
be necessary once more for "the old man"--always childish enough, an
eternal child!
58. Has it been observed to what extent outward idleness, or
semi-idleness, is necessary to a real religious life (alike for its
favourite microscopic labour of self-examination, and for its soft
placidity called "prayer," the state of perpetual readiness for the
"coming of God"), I mean the idleness with a good conscience, the
idleness of olden times and of blood, to which the aristocratic
sentiment that work is DISHONOURING--that it vulgarizes body and
soul--is not quite unfamiliar? And that consequently the modern, noisy,
time-engrossing, conceited, foolishly proud laboriousness educates
and prepares for "unbelief" more than anything else? Among these, for
instance, who are at present living apart from religion in Germany, I
find "free-thinkers" of diversified species and origin, but above all
a majority of those in whom laboriousness from generation to generation
has dissolved the religious instincts; so that they no longer know what
purpose religions serve, and only note their existence in the world
with a kind of dull astonishment. They feel themselves already fully
occupied, these good people, be it by their business or by their
pleasures, not to mention the "Fatherland," and the newspapers, and
their "family duties"; it seems that they have no time whatever left
for religion; and above all, it is not obvious to them whether it is a
question of a new business or a new pleasure--for it is impossible, they
say to themselves, that people should go to church merely to spoil
their tempers. They are by no means enemies of religious customs;
should certain circumstances, State affairs perhaps, require their
participation in such customs, they do what is required, as so many
things are done--with a patient and unassuming seriousness, and without
much curiosity or discomfort;--they live too much apart and outside
to feel even the necessity for a FOR or AGAINST in such matters. Among
those indifferent persons may be reckoned nowadays the majority of
German Protestants of the middle classes, especially in the great
laborious centres of trade and commerce; also the majority of laborious
scholars, and the entire University personnel (with the exception of
the theologians, whose existence and possibility there always gives
psychologists new and more subtle puzzles to solve). On the part of
pious, or merely church-going people, there is seldom any idea of HOW
MUCH good-will, one might say arbitrary will, is now necessary for a
German scholar to take the problem of religion seriously; his whole
profession (and as I have said, his whole workmanlike laboriousness, to
which he is compelled by his modern conscience) inclines him to a
lofty and almost charitable serenity as regards religion, with which is
occasionally mingled a slight disdain for the "uncleanliness" of spirit
which he takes for granted wherever any one still professes to belong
to the Church. It is only with the help of history (NOT through his own
personal experience, therefore) that the scholar succeeds in bringing
himself to a respectful seriousness, and to a certain timid deference
in presence of religions; but even when his sentiments have reached the
stage of gratitude towards them, he has not personally advanced one
step nearer to that which still maintains itself as Church or as piety;
perhaps even the contrary. The practical indifference to religious
matters in the midst of which he has been born and brought up, usually
sublimates itself in his case into circumspection and cleanliness, which
shuns contact with religious men and things; and it may be just the
depth of his tolerance and humanity which prompts him to avoid the
delicate trouble which tolerance itself brings with it.--Every age has
its own divine type of naivete, for the discovery of which other ages
may envy it: and how much naivete--adorable, childlike, and boundlessly
foolish naivete is involved in this belief of the scholar in
his superiority, in the good conscience of his tolerance, in the
unsuspecting, simple certainty with which his instinct treats the
religious man as a lower and less valuable type, beyond, before, and
ABOVE which he himself has developed--he, the little arrogant dwarf
and mob-man, the sedulously alert, head-and-hand drudge of "ideas," of
"modern ideas"!
59. Whoever has seen deeply into the world has doubtless divined what
wisdom there is in the fact that men are superficial. It is their
preservative instinct which teaches them to be flighty, lightsome, and
false. Here and there one finds a passionate and exaggerated adoration
of "pure forms" in philosophers as well as in artists: it is not to be
doubted that whoever has NEED of the cult of the superficial to that
extent, has at one time or another made an unlucky dive BENEATH it.
Perhaps there is even an order of rank with respect to those burnt
children, the born artists who find the enjoyment of life only in trying
to FALSIFY its image (as if taking wearisome revenge on it), one might
guess to what degree life has disgusted them, by the extent to which
they wish to see its image falsified, attenuated, ultrified, and
deified,--one might reckon the homines religiosi among the artists, as
their HIGHEST rank. It is the profound, suspicious fear of an incurable
pessimism which compels whole centuries to fasten their teeth into a
religious interpretation of existence: the fear of the instinct which
divines that truth might be attained TOO soon, before man has become
strong enough, hard enough, artist enough.... Piety, the "Life in God,"
regarded in this light, would appear as the most elaborate and
ultimate product of the FEAR of truth, as artist-adoration
and artist-intoxication in presence of the most logical of all
falsifications, as the will to the inversion of truth, to untruth at
any price. Perhaps there has hitherto been no more effective means of
beautifying man than piety, by means of it man can become so artful, so
superficial, so iridescent, and so good, that his appearance no longer
offends.
60. To love mankind FOR GOD'S SAKE--this has so far been the noblest and
remotest sentiment to which mankind has attained. That love to mankind,
without any redeeming intention in the background, is only an ADDITIONAL
folly and brutishness, that the inclination to this love has first to
get its proportion, its delicacy, its gram of salt and sprinkling
of ambergris from a higher inclination--whoever first perceived
and "experienced" this, however his tongue may have stammered as it
attempted to express such a delicate matter, let him for all time be
holy and respected, as the man who has so far flown highest and gone
astray in the finest fashion!
61. The philosopher, as WE free spirits understand him--as the man of
the greatest responsibility, who has the conscience for the general
development of mankind,--will use religion for his disciplining and
educating work, just as he will use the contemporary political
and economic conditions. The selecting and disciplining
influence--destructive, as well as creative and fashioning--which can be
exercised by means of religion is manifold and varied, according to the
sort of people placed under its spell and protection. For those who are
strong and independent, destined and trained to command, in whom the
judgment and skill of a ruling race is incorporated, religion is
an additional means for overcoming resistance in the exercise of
authority--as a bond which binds rulers and subjects in common,
betraying and surrendering to the former the conscience of the latter,
their inmost heart, which would fain escape obedience. And in the
case of the unique natures of noble origin, if by virtue of superior
spirituality they should incline to a more retired and contemplative
life, reserving to themselves only the more refined forms of government
(over chosen disciples or members of an order), religion itself may
be used as a means for obtaining peace from the noise and trouble of
managing GROSSER affairs, and for securing immunity from the UNAVOIDABLE
filth of all political agitation. The Brahmins, for instance, understood
this fact. With the help of a religious organization, they secured to
themselves the power of nominating kings for the people, while their
sentiments prompted them to keep apart and outside, as men with a higher
and super-regal mission. At the same time religion gives inducement and
opportunity to some of the subjects to qualify themselves for future
ruling and commanding the slowly ascending ranks and classes, in which,
through fortunate marriage customs, volitional power and delight in
self-control are on the increase. To them religion offers sufficient
incentives and temptations to aspire to higher intellectuality, and to
experience the sentiments of authoritative self-control, of silence, and
of solitude. Asceticism and Puritanism are almost indispensable means of
educating and ennobling a race which seeks to rise above its hereditary
baseness and work itself upwards to future supremacy. And finally, to
ordinary men, to the majority of the people, who exist for service and
general utility, and are only so far entitled to exist, religion gives
invaluable contentedness with their lot and condition, peace of heart,
ennoblement of obedience, additional social happiness and sympathy,
with something of transfiguration and embellishment, something of
justification of all the commonplaceness, all the meanness, all
the semi-animal poverty of their souls. Religion, together with the
religious significance of life, sheds sunshine over such perpetually
harassed men, and makes even their own aspect endurable to them, it
operates upon them as the Epicurean philosophy usually operates upon
sufferers of a higher order, in a refreshing and refining manner,
almost TURNING suffering TO ACCOUNT, and in the end even hallowing and
vindicating it. There is perhaps nothing so admirable in Christianity
and Buddhism as their art of teaching even the lowest to elevate
themselves by piety to a seemingly higher order of things, and thereby
to retain their satisfaction with the actual world in which they find it
difficult enough to live--this very difficulty being necessary.
62. To be sure--to make also the bad counter-reckoning against such
religions, and to bring to light their secret dangers--the cost is
always excessive and terrible when religions do NOT operate as an
educational and disciplinary medium in the hands of the philosopher, but
rule voluntarily and PARAMOUNTLY, when they wish to be the final end,
and not a means along with other means. Among men, as among all other
animals, there is a surplus of defective, diseased, degenerating,
infirm, and necessarily suffering individuals; the successful cases,
among men also, are always the exception; and in view of the fact that
man is THE ANIMAL NOT YET PROPERLY ADAPTED TO HIS ENVIRONMENT, the rare
exception. But worse still. The higher the type a man represents, the
greater is the improbability that he will SUCCEED; the accidental, the
law of irrationality in the general constitution of mankind, manifests
itself most terribly in its destructive effect on the higher orders of
men, the conditions of whose lives are delicate, diverse, and difficult
to determine. What, then, is the attitude of the two greatest religions
above-mentioned to the SURPLUS of failures in life? They endeavour
to preserve and keep alive whatever can be preserved; in fact, as the
religions FOR SUFFERERS, they take the part of these upon principle;
they are always in favour of those who suffer from life as from a
disease, and they would fain treat every other experience of life as
false and impossible. However highly we may esteem this indulgent and
preservative care (inasmuch as in applying to others, it has applied,
and applies also to the highest and usually the most suffering type of
man), the hitherto PARAMOUNT religions--to give a general appreciation
of them--are among the principal causes which have kept the type of
"man" upon a lower level--they have preserved too much THAT WHICH SHOULD
HAVE PERISHED. One has to thank them for invaluable services; and who is
sufficiently rich in gratitude not to feel poor at the contemplation
of all that the "spiritual men" of Christianity have done for Europe
hitherto! But when they had given comfort to the sufferers, courage to
the oppressed and despairing, a staff and support to the helpless,
and when they had allured from society into convents and spiritual
penitentiaries the broken-hearted and distracted: what else had they
to do in order to work systematically in that fashion, and with a good
conscience, for the preservation of all the sick and suffering, which
means, in deed and in truth, to work for the DETERIORATION OF THE
EUROPEAN RACE? To REVERSE all estimates of value--THAT is what they
had to do! And to shatter the strong, to spoil great hopes, to cast
suspicion on the delight in beauty, to break down everything autonomous,
manly, conquering, and imperious--all instincts which are natural to the
highest and most successful type of "man"--into uncertainty, distress
of conscience, and self-destruction; forsooth, to invert all love of the
earthly and of supremacy over the earth, into hatred of the earth and
earthly things--THAT is the task the Church imposed on itself, and
was obliged to impose, until, according to its standard of value,
"unworldliness," "unsensuousness," and "higher man" fused into one
sentiment. If one could observe the strangely painful, equally coarse
and refined comedy of European Christianity with the derisive and
impartial eye of an Epicurean god, I should think one would never cease
marvelling and laughing; does it not actually seem that some single will
has ruled over Europe for eighteen centuries in order to make a SUBLIME
ABORTION of man? He, however, who, with opposite requirements (no longer
Epicurean) and with some divine hammer in his hand, could approach this
almost voluntary degeneration and stunting of mankind, as exemplified in
the European Christian (Pascal, for instance), would he not have to
cry aloud with rage, pity, and horror: "Oh, you bunglers, presumptuous
pitiful bunglers, what have you done! Was that a work for your hands?
How you have hacked and botched my finest stone! What have you presumed
to do!"--I should say that Christianity has hitherto been the most
portentous of presumptions. Men, not great enough, nor hard enough,
to be entitled as artists to take part in fashioning MAN; men,
not sufficiently strong and far-sighted to ALLOW, with sublime
self-constraint, the obvious law of the thousandfold failures and
perishings to prevail; men, not sufficiently noble to see the radically
different grades of rank and intervals of rank that separate man from
man:--SUCH men, with their "equality before God," have hitherto swayed
the destiny of Europe; until at last a dwarfed, almost ludicrous species
has been produced, a gregarious animal, something obliging, sickly,
mediocre, the European of the present day.
CHAPTER IV. APOPHTHEGMS AND INTERLUDES
63. He who is a thorough teacher takes things seriously--and even
himself--only in relation to his pupils.
64. "Knowledge for its own sake"--that is the last snare laid by
morality: we are thereby completely entangled in morals once more.
65. The charm of knowledge would be small, were it not so much shame has
to be overcome on the way to it.
65A. We are most dishonourable towards our God: he is not PERMITTED to
sin.
66. The tendency of a person to allow himself to be degraded, robbed,
deceived, and exploited might be the diffidence of a God among men.
67. Love to one only is a barbarity, for it is exercised at the expense
of all others. Love to God also!
68. "I did that," says my memory. "I could not have done that," says my
pride, and remains inexorable. Eventually--the memory yields.
69. One has regarded life carelessly, if one has failed to see the hand
that--kills with leniency.
70. If a man has character, he has also his typical experience, which
always recurs.
71. THE SAGE AS ASTRONOMER.--So long as thou feelest the stars as an
"above thee," thou lackest the eye of the discerning one.
72. It is not the strength, but the duration of great sentiments that
makes great men.
73. He who attains his ideal, precisely thereby surpasses it.
73A. Many a peacock hides his tail from every eye--and calls it his
pride.
74. A man of genius is unbearable, unless he possess at least two things
besides: gratitude and purity.
75. The degree and nature of a man's sensuality extends to the highest
altitudes of his spirit.
76. Under peaceful conditions the militant man attacks himself.
77. With his principles a man seeks either to dominate, or justify,
or honour, or reproach, or conceal his habits: two men with the same
principles probably seek fundamentally different ends therewith.
78. He who despises himself, nevertheless esteems himself thereby, as a
despiser.
79. A soul which knows that it is loved, but does not itself love,
betrays its sediment: its dregs come up.
80. A thing that is explained ceases to concern us--What did the God
mean who gave the advice, "Know thyself!" Did it perhaps imply "Cease to
be concerned about thyself! become objective!"--And Socrates?--And the
"scientific man"?
81. It is terrible to die of thirst at sea. Is it necessary that you
should so salt your truth that it will no longer--quench thirst?
82. "Sympathy for all"--would be harshness and tyranny for THEE, my good
neighbour.
83. INSTINCT--When the house is on fire one forgets even the
dinner--Yes, but one recovers it from among the ashes.
84. Woman learns how to hate in proportion as she--forgets how to charm.
85. The same emotions are in man and woman, but in different TEMPO, on
that account man and woman never cease to misunderstand each other.
86. In the background of all their personal vanity, women themselves
have still their impersonal scorn--for "woman".
87. FETTERED HEART, FREE SPIRIT--When one firmly fetters one's heart
and keeps it prisoner, one can allow one's spirit many liberties: I said
this once before But people do not believe it when I say so, unless they
know it already.
88. One begins to distrust very clever persons when they become
embarrassed.
89. Dreadful experiences raise the question whether he who experiences
them is not something dreadful also.
90. Heavy, melancholy men turn lighter, and come temporarily to their
surface, precisely by that which makes others heavy--by hatred and love.
91. So cold, so icy, that one burns one's finger at the touch of him!
Every hand that lays hold of him shrinks back!--And for that very reason
many think him red-hot.
92. Who has not, at one time or another--sacrificed himself for the sake
of his good name?
93. In affability there is no hatred of men, but precisely on that
account a great deal too much contempt of men.
94. The maturity of man--that means, to have reacquired the seriousness
that one had as a child at play.
95. To be ashamed of one's immorality is a step on the ladder at the end
of which one is ashamed also of one's morality.
96. One should part from life as Ulysses parted from Nausicaa--blessing
it rather than in love with it.
97. What? A great man? I always see merely the play-actor of his own
ideal.
98. When one trains one's conscience, it kisses one while it bites.
99. THE DISAPPOINTED ONE SPEAKS--"I listened for the echo and I heard
only praise."
100. We all feign to ourselves that we are simpler than we are, we thus
relax ourselves away from our fellows.
101. A discerning one might easily regard himself at present as the
animalization of God.
102. Discovering reciprocal love should really disenchant the lover with
regard to the beloved. "What! She is modest enough to love even you? Or
stupid enough? Or--or---"
103. THE DANGER IN HAPPINESS.--"Everything now turns out best for me, I
now love every fate:--who would like to be my fate?"
104. Not their love of humanity, but the impotence of their love,
prevents the Christians of today--burning us.
105. The pia fraus is still more repugnant to the taste (the "piety")
of the free spirit (the "pious man of knowledge") than the impia fraus.
Hence the profound lack of judgment, in comparison with the Church,
characteristic of the type "free spirit"--as ITS non-freedom.
106. By means of music the very passions enjoy themselves.
107. A sign of strong character, when once the resolution has been
taken, to shut the ear even to the best counter-arguments. Occasionally,
therefore, a will to stupidity.
108. There is no such thing as moral phenomena, but only a moral
interpretation of phenomena.
109. The criminal is often enough not equal to his deed: he extenuates
and maligns it.
110. The advocates of a criminal are seldom artists enough to turn the
beautiful terribleness of the deed to the advantage of the doer.
111. Our vanity is most difficult to wound just when our pride has been
wounded.
112. To him who feels himself preordained to contemplation and not to
belief, all believers are too noisy and obtrusive; he guards against
them.
113. "You want to prepossess him in your favour? Then you must be
embarrassed before him."
114. The immense expectation with regard to sexual love, and the coyness
in this expectation, spoils all the perspectives of women at the outset.
115. Where there is neither love nor hatred in the game, woman's play is
mediocre.
116. The great epochs of our life are at the points when we gain courage
to rebaptize our badness as the best in us.
117. The will to overcome an emotion, is ultimately only the will of
another, or of several other, emotions.
118. There is an innocence of admiration: it is possessed by him to whom
it has not yet occurred that he himself may be admired some day.
119. Our loathing of dirt may be so great as to prevent our cleaning
ourselves--"justifying" ourselves.
120. Sensuality often forces the growth of love too much, so that its
root remains weak, and is easily torn up.
121. It is a curious thing that God learned Greek when he wished to turn
author--and that he did not learn it better.
122. To rejoice on account of praise is in many cases merely politeness
of heart--and the very opposite of vanity of spirit.
123. Even concubinage has been corrupted--by marriage.
124. He who exults at the stake, does not triumph over pain, but because
of the fact that he does not feel pain where he expected it. A parable.
125. When we have to change an opinion about any one, we charge heavily
to his account the inconvenience he thereby causes us.
126. A nation is a detour of nature to arrive at six or seven great
men.--Yes, and then to get round them.
127. In the eyes of all true women science is hostile to the sense of
shame. They feel as if one wished to peep under their skin with it--or
worse still! under their dress and finery.
128. The more abstract the truth you wish to teach, the more must you
allure the senses to it.
129. The devil has the most extensive perspectives for God; on that
account he keeps so far away from him:--the devil, in effect, as the
oldest friend of knowledge.
130. What a person IS begins to betray itself when his talent
decreases,--when he ceases to show what he CAN do. Talent is also an
adornment; an adornment is also a concealment.
131. The sexes deceive themselves about each other: the reason is that
in reality they honour and love only themselves (or their own ideal, to
express it more agreeably). Thus man wishes woman to be peaceable: but
in fact woman is ESSENTIALLY unpeaceable, like the cat, however well she
may have assumed the peaceable demeanour.
132. One is punished best for one's virtues.
133. He who cannot find the way to HIS ideal, lives more frivolously and
shamelessly than the man without an ideal.
134. From the senses originate all trustworthiness, all good conscience,
all evidence of truth.
135. Pharisaism is not a deterioration of the good man; a considerable
part of it is rather an essential condition of being good.
136. The one seeks an accoucheur for his thoughts, the other seeks some
one whom he can assist: a good conversation thus originates.
137. In intercourse with scholars and artists one readily makes mistakes
of opposite kinds: in a remarkable scholar one not infrequently finds
a mediocre man; and often, even in a mediocre artist, one finds a very
remarkable man.
138. We do the same when awake as when dreaming: we only invent and
imagine him with whom we have intercourse--and forget it immediately.
139. In revenge and in love woman is more barbarous than man.
140. ADVICE AS A RIDDLE.--"If the band is not to break, bite it
first--secure to make!"
141. The belly is the reason why man does not so readily take himself
for a God.
142. The chastest utterance I ever heard: "Dans le veritable amour c'est
l'ame qui enveloppe le corps."
143. Our vanity would like what we do best to pass precisely for what is
most difficult to us.--Concerning the origin of many systems of morals.
144. When a woman has scholarly inclinations there is generally
something wrong with her sexual nature. Barrenness itself conduces to a
certain virility of taste; man, indeed, if I may say so, is "the barren
animal."
145. Comparing man and woman generally, one may say that woman would
not have the genius for adornment, if she had not the instinct for the
SECONDARY role.
146. He who fights with monsters should be careful lest he thereby
become a monster. And if thou gaze long into an abyss, the abyss will
also gaze into thee.
147. From old Florentine novels--moreover, from life: Buona femmina e
mala femmina vuol bastone.--Sacchetti, Nov. 86.
148. To seduce their neighbour to a favourable opinion, and afterwards
to believe implicitly in this opinion of their neighbour--who can do
this conjuring trick so well as women?
149. That which an age considers evil is usually an unseasonable echo of
what was formerly considered good--the atavism of an old ideal.
150. Around the hero everything becomes a tragedy; around the
demigod everything becomes a satyr-play; and around God everything
becomes--what? perhaps a "world"?
151. It is not enough to possess a talent: one must also have your
permission to possess it;--eh, my friends?
152. "Where there is the tree of knowledge, there is always Paradise":
so say the most ancient and the most modern serpents.
153. What is done out of love always takes place beyond good and evil.
154. Objection, evasion, joyous distrust, and love of irony are signs of
health; everything absolute belongs to pathology.
155. The sense of the tragic increases and declines with sensuousness.
156. Insanity in individuals is something rare--but in groups, parties,
nations, and epochs it is the rule.
157. The thought of suicide is a great consolation: by means of it one
gets successfully through many a bad night.
158. Not only our reason, but also our conscience, truckles to our
strongest impulse--the tyrant in us.
159. One MUST repay good and ill; but why just to the person who did us
good or ill?
160. One no longer loves one's knowledge sufficiently after one has
communicated it.
161. Poets act shamelessly towards their experiences: they exploit them.
162. "Our fellow-creature is not our neighbour, but our neighbour's
neighbour":--so thinks every nation.
163. Love brings to light the noble and hidden qualities of a lover--his
rare and exceptional traits: it is thus liable to be deceptive as to his
normal character.
164. Jesus said to his Jews: "The law was for servants;--love God as I
love him, as his Son! What have we Sons of God to do with morals!"
165. IN SIGHT OF EVERY PARTY.--A shepherd has always need of a
bell-wether--or he has himself to be a wether occasionally.
166. One may indeed lie with the mouth; but with the accompanying
grimace one nevertheless tells the truth.
167. To vigorous men intimacy is a matter of shame--and something
precious.
168. Christianity gave Eros poison to drink; he did not die of it,
certainly, but degenerated to Vice.
169. To talk much about oneself may also be a means of concealing
oneself.
170. In praise there is more obtrusiveness than in blame.
171. Pity has an almost ludicrous effect on a man of knowledge, like
tender hands on a Cyclops.
172. One occasionally embraces some one or other, out of love to mankind
(because one cannot embrace all); but this is what one must never
confess to the individual.
173. One does not hate as long as one disesteems, but only when one
esteems equal or superior.
174. Ye Utilitarians--ye, too, love the UTILE only as a VEHICLE for
your inclinations,--ye, too, really find the noise of its wheels
insupportable!
175. One loves ultimately one's desires, not the thing desired.
176. The vanity of others is only counter to our taste when it is
counter to our vanity.
177. With regard to what "truthfulness" is, perhaps nobody has ever been
sufficiently truthful.
178. One does not believe in the follies of clever men: what a
forfeiture of the rights of man!
179. The consequences of our actions seize us by the forelock, very
indifferent to the fact that we have meanwhile "reformed."
180. There is an innocence in lying which is the sign of good faith in a
cause.
181. It is inhuman to bless when one is being cursed.
182. The familiarity of superiors embitters one, because it may not be
returned.
183. "I am affected, not because you have deceived me, but because I can
no longer believe in you."
184. There is a haughtiness of kindness which has the appearance of
wickedness.
185. "I dislike him."--Why?--"I am not a match for him."--Did any one
ever answer so?
CHAPTER V. THE NATURAL HISTORY OF MORALS
186. The moral sentiment in Europe at present is perhaps as subtle,
belated, diverse, sensitive, and refined, as the "Science of Morals"
belonging thereto is recent, initial, awkward, and coarse-fingered:--an
interesting contrast, which sometimes becomes incarnate and obvious
in the very person of a moralist. Indeed, the expression, "Science
of Morals" is, in respect to what is designated thereby, far too
presumptuous and counter to GOOD taste,--which is always a foretaste of
more modest expressions. One ought to avow with the utmost fairness WHAT
is still necessary here for a long time, WHAT is alone proper for the
present: namely, the collection of material, the comprehensive survey
and classification of an immense domain of delicate sentiments of worth,
and distinctions of worth, which live, grow, propagate, and perish--and
perhaps attempts to give a clear idea of the recurring and more common
forms of these living crystallizations--as preparation for a THEORY OF
TYPES of morality. To be sure, people have not hitherto been so modest.
All the philosophers, with a pedantic and ridiculous seriousness,
demanded of themselves something very much higher, more pretentious, and
ceremonious, when they concerned themselves with morality as a science:
they wanted to GIVE A BASIC to morality--and every philosopher hitherto
has believed that he has given it a basis; morality itself, however, has
been regarded as something "given." How far from their awkward pride
was the seemingly insignificant problem--left in dust and decay--of a
description of forms of morality, notwithstanding that the finest hands
and senses could hardly be fine enough for it! It was precisely owing to
moral philosophers' knowing the moral facts imperfectly, in an arbitrary
epitome, or an accidental abridgement--perhaps as the morality of
their environment, their position, their church, their Zeitgeist, their
climate and zone--it was precisely because they were badly instructed
with regard to nations, eras, and past ages, and were by no means eager
to know about these matters, that they did not even come in sight of the
real problems of morals--problems which only disclose themselves by
a comparison of MANY kinds of morality. In every "Science of Morals"
hitherto, strange as it may sound, the problem of morality itself
has been OMITTED: there has been no suspicion that there was anything
problematic there! That which philosophers called "giving a basis to
morality," and endeavoured to realize, has, when seen in a right light,
proved merely a learned form of good FAITH in prevailing morality, a new
means of its EXPRESSION, consequently just a matter-of-fact within the
sphere of a definite morality, yea, in its ultimate motive, a sort of
denial that it is LAWFUL for this morality to be called in question--and
in any case the reverse of the testing, analyzing, doubting, and
vivisecting of this very faith. Hear, for instance, with what
innocence--almost worthy of honour--Schopenhauer represents his own
task, and draw your conclusions concerning the scientificness of a
"Science" whose latest master still talks in the strain of children and
old wives: "The principle," he says (page 136 of the Grundprobleme der
Ethik), [Footnote: Pages 54-55 of Schopenhauer's Basis of Morality,
translated by Arthur B. Bullock, M.A. (1903).] "the axiom about the
purport of which all moralists are PRACTICALLY agreed: neminem laede,
immo omnes quantum potes juva--is REALLY the proposition which all moral
teachers strive to establish, ... the REAL basis of ethics which
has been sought, like the philosopher's stone, for centuries."--The
difficulty of establishing the proposition referred to may indeed be
great--it is well known that Schopenhauer also was unsuccessful in his
efforts; and whoever has thoroughly realized how absurdly false and
sentimental this proposition is, in a world whose essence is Will
to Power, may be reminded that Schopenhauer, although a pessimist,
ACTUALLY--played the flute... daily after dinner: one may read about
the matter in his biography. A question by the way: a pessimist, a
repudiator of God and of the world, who MAKES A HALT at morality--who
assents to morality, and plays the flute to laede-neminem morals, what?
Is that really--a pessimist?
187. Apart from the value of such assertions as "there is a categorical
imperative in us," one can always ask: What does such an assertion
indicate about him who makes it? There are systems of morals which are
meant to justify their author in the eyes of other people; other systems
of morals are meant to tranquilize him, and make him self-satisfied;
with other systems he wants to crucify and humble himself, with others
he wishes to take revenge, with others to conceal himself, with others
to glorify himself and gave superiority and distinction,--this system of
morals helps its author to forget, that system makes him, or something
of him, forgotten, many a moralist would like to exercise power and
creative arbitrariness over mankind, many another, perhaps, Kant
especially, gives us to understand by his morals that "what is estimable
in me, is that I know how to obey--and with you it SHALL not be
otherwise than with me!" In short, systems of morals are only a
SIGN-LANGUAGE OF THE EMOTIONS.
188. In contrast to laisser-aller, every system of morals is a sort of
tyranny against "nature" and also against "reason", that is, however, no
objection, unless one should again decree by some system of morals, that
all kinds of tyranny and unreasonableness are unlawful What is
essential and invaluable in every system of morals, is that it is a
long constraint. In order to understand Stoicism, or Port Royal,
or Puritanism, one should remember the constraint under which every
language has attained to strength and freedom--the metrical constraint,
the tyranny of rhyme and rhythm. How much trouble have the poets and
orators of every nation given themselves!--not excepting some of
the prose writers of today, in whose ear dwells an inexorable
conscientiousness--"for the sake of a folly," as utilitarian bunglers
say, and thereby deem themselves wise--"from submission to arbitrary
laws," as the anarchists say, and thereby fancy themselves "free," even
free-spirited. The singular fact remains, however, that everything
of the nature of freedom, elegance, boldness, dance, and masterly
certainty, which exists or has existed, whether it be in thought itself,
or in administration, or in speaking and persuading, in art just as in
conduct, has only developed by means of the tyranny of such arbitrary
law, and in all seriousness, it is not at all improbable that precisely
this is "nature" and "natural"--and not laisser-aller! Every artist
knows how different from the state of letting himself go, is his
"most natural" condition, the free arranging, locating, disposing,
and constructing in the moments of "inspiration"--and how strictly and
delicately he then obeys a thousand laws, which, by their very rigidness
and precision, defy all formulation by means of ideas (even the most
stable idea has, in comparison therewith, something floating, manifold,
and ambiguous in it). The essential thing "in heaven and in earth" is,
apparently (to repeat it once more), that there should be long OBEDIENCE
in the same direction, there thereby results, and has always resulted in
the long run, something which has made life worth living; for instance,
virtue, art, music, dancing, reason, spirituality--anything whatever
that is transfiguring, refined, foolish, or divine. The long bondage of
the spirit, the distrustful constraint in the communicability of
ideas, the discipline which the thinker imposed on himself to think
in accordance with the rules of a church or a court, or conformable
to Aristotelian premises, the persistent spiritual will to interpret
everything that happened according to a Christian scheme, and in every
occurrence to rediscover and justify the Christian God:--all this
violence, arbitrariness, severity, dreadfulness, and unreasonableness,
has proved itself the disciplinary means whereby the European spirit has
attained its strength, its remorseless curiosity and subtle mobility;
granted also that much irrecoverable strength and spirit had to be
stifled, suffocated, and spoilt in the process (for here, as everywhere,
"nature" shows herself as she is, in all her extravagant and INDIFFERENT
magnificence, which is shocking, but nevertheless noble). That
for centuries European thinkers only thought in order to prove
something--nowadays, on the contrary, we are suspicious of every thinker
who "wishes to prove something"--that it was always settled beforehand
what WAS TO BE the result of their strictest thinking, as it was perhaps
in the Asiatic astrology of former times, or as it is still at the
present day in the innocent, Christian-moral explanation of immediate
personal events "for the glory of God," or "for the good of the
soul":--this tyranny, this arbitrariness, this severe and magnificent
stupidity, has EDUCATED the spirit; slavery, both in the coarser and
the finer sense, is apparently an indispensable means even of spiritual
education and discipline. One may look at every system of morals in this
light: it is "nature" therein which teaches to hate the laisser-aller,
the too great freedom, and implants the need for limited horizons, for
immediate duties--it teaches the NARROWING OF PERSPECTIVES, and thus, in
a certain sense, that stupidity is a condition of life and development.
"Thou must obey some one, and for a long time; OTHERWISE thou wilt come
to grief, and lose all respect for thyself"--this seems to me to be the
moral imperative of nature, which is certainly neither "categorical,"
as old Kant wished (consequently the "otherwise"), nor does it address
itself to the individual (what does nature care for the individual!),
but to nations, races, ages, and ranks; above all, however, to the
animal "man" generally, to MANKIND.
189. Industrious races find it a great hardship to be idle: it was a
master stroke of ENGLISH instinct to hallow and begloom Sunday to such
an extent that the Englishman unconsciously hankers for his week--and
work-day again:--as a kind of cleverly devised, cleverly intercalated
FAST, such as is also frequently found in the ancient world (although,
as is appropriate in southern nations, not precisely with respect
to work). Many kinds of fasts are necessary; and wherever powerful
influences and habits prevail, legislators have to see that intercalary
days are appointed, on which such impulses are fettered, and learn to
hunger anew. Viewed from a higher standpoint, whole generations and
epochs, when they show themselves infected with any moral fanaticism,
seem like those intercalated periods of restraint and fasting, during
which an impulse learns to humble and submit itself--at the same time
also to PURIFY and SHARPEN itself; certain philosophical sects likewise
admit of a similar interpretation (for instance, the Stoa, in the midst
of Hellenic culture, with the atmosphere rank and overcharged with
Aphrodisiacal odours).--Here also is a hint for the explanation of the
paradox, why it was precisely in the most Christian period of European
history, and in general only under the pressure of Christian sentiments,
that the sexual impulse sublimated into love (amour-passion).
190. There is something in the morality of Plato which does not really
belong to Plato, but which only appears in his philosophy, one might
say, in spite of him: namely, Socratism, for which he himself was
too noble. "No one desires to injure himself, hence all evil is done
unwittingly. The evil man inflicts injury on himself; he would not do
so, however, if he knew that evil is evil. The evil man, therefore, is
only evil through error; if one free him from error one will necessarily
make him--good."--This mode of reasoning savours of the POPULACE, who
perceive only the unpleasant consequences of evil-doing, and practically
judge that "it is STUPID to do wrong"; while they accept "good" as
identical with "useful and pleasant," without further thought. As
regards every system of utilitarianism, one may at once assume that it
has the same origin, and follow the scent: one will seldom err.--Plato
did all he could to interpret something refined and noble into the
tenets of his teacher, and above all to interpret himself into them--he,
the most daring of all interpreters, who lifted the entire Socrates out
of the street, as a popular theme and song, to exhibit him in endless
and impossible modifications--namely, in all his own disguises and
multiplicities. In jest, and in Homeric language as well, what is the
Platonic Socrates, if not--[Greek words inserted here.]
191. The old theological problem of "Faith" and "Knowledge," or more
plainly, of instinct and reason--the question whether, in respect to the
valuation of things, instinct deserves more authority than rationality,
which wants to appreciate and act according to motives, according to
a "Why," that is to say, in conformity to purpose and utility--it
is always the old moral problem that first appeared in the person of
Socrates, and had divided men's minds long before Christianity. Socrates
himself, following, of course, the taste of his talent--that of a
surpassing dialectician--took first the side of reason; and, in fact,
what did he do all his life but laugh at the awkward incapacity of the
noble Athenians, who were men of instinct, like all noble men, and could
never give satisfactory answers concerning the motives of their actions?
In the end, however, though silently and secretly, he laughed also
at himself: with his finer conscience and introspection, he found
in himself the same difficulty and incapacity. "But why"--he said
to himself--"should one on that account separate oneself from the
instincts! One must set them right, and the reason ALSO--one must follow
the instincts, but at the same time persuade the reason to support them
with good arguments." This was the real FALSENESS of that great and
mysterious ironist; he brought his conscience up to the point that he
was satisfied with a kind of self-outwitting: in fact, he perceived
the irrationality in the moral judgment.--Plato, more innocent in such
matters, and without the craftiness of the plebeian, wished to prove to
himself, at the expenditure of all his strength--the greatest strength
a philosopher had ever expended--that reason and instinct lead
spontaneously to one goal, to the good, to "God"; and since Plato, all
theologians and philosophers have followed the same path--which means
that in matters of morality, instinct (or as Christians call it,
"Faith," or as I call it, "the herd") has hitherto triumphed. Unless
one should make an exception in the case of Descartes, the father of
rationalism (and consequently the grandfather of the Revolution), who
recognized only the authority of reason: but reason is only a tool, and
Descartes was superficial.
192. Whoever has followed the history of a single science, finds in
its development a clue to the understanding of the oldest and commonest
processes of all "knowledge and cognizance": there, as here, the
premature hypotheses, the fictions, the good stupid will to "belief,"
and the lack of distrust and patience are first developed--our senses
learn late, and never learn completely, to be subtle, reliable, and
cautious organs of knowledge. Our eyes find it easier on a given
occasion to produce a picture already often produced, than to seize upon
the divergence and novelty of an impression: the latter requires more
force, more "morality." It is difficult and painful for the ear to
listen to anything new; we hear strange music badly. When we hear
another language spoken, we involuntarily attempt to form the sounds
into words with which we are more familiar and conversant--it was thus,
for example, that the Germans modified the spoken word ARCUBALISTA into
ARMBRUST (cross-bow). Our senses are also hostile and averse to the
new; and generally, even in the "simplest" processes of sensation, the
emotions DOMINATE--such as fear, love, hatred, and the passive emotion
of indolence.--As little as a reader nowadays reads all the single words
(not to speak of syllables) of a page--he rather takes about five out
of every twenty words at random, and "guesses" the probably appropriate
sense to them--just as little do we see a tree correctly and completely
in respect to its leaves, branches, colour, and shape; we find it so
much easier to fancy the chance of a tree. Even in the midst of the
most remarkable experiences, we still do just the same; we fabricate the
greater part of the experience, and can hardly be made to contemplate
any event, EXCEPT as "inventors" thereof. All this goes to prove
that from our fundamental nature and from remote ages we have
been--ACCUSTOMED TO LYING. Or, to express it more politely and
hypocritically, in short, more pleasantly--one is much more of an artist
than one is aware of.--In an animated conversation, I often see the face
of the person with whom I am speaking so clearly and sharply defined
before me, according to the thought he expresses, or which I believe to
be evoked in his mind, that the degree of distinctness far exceeds the
STRENGTH of my visual faculty--the delicacy of the play of the muscles
and of the expression of the eyes MUST therefore be imagined by me.
Probably the person put on quite a different expression, or none at all.
193. Quidquid luce fuit, tenebris agit: but also contrariwise. What we
experience in dreams, provided we experience it often, pertains at
last just as much to the general belongings of our soul as anything
"actually" experienced; by virtue thereof we are richer or poorer, we
have a requirement more or less, and finally, in broad daylight, and
even in the brightest moments of our waking life, we are ruled to some
extent by the nature of our dreams. Supposing that someone has often
flown in his dreams, and that at last, as soon as he dreams, he is
conscious of the power and art of flying as his privilege and his
peculiarly enviable happiness; such a person, who believes that on the
slightest impulse, he can actualize all sorts of curves and angles, who
knows the sensation of a certain divine levity, an "upwards"
without effort or constraint, a "downwards" without descending
or lowering--without TROUBLE!--how could the man with such
dream-experiences and dream-habits fail to find "happiness" differently
coloured and defined, even in his waking hours! How could he fail--to
long DIFFERENTLY for happiness? "Flight," such as is described by poets,
must, when compared with his own "flying," be far too earthly, muscular,
violent, far too "troublesome" for him.
194. The difference among men does not manifest itself only in the
difference of their lists of desirable things--in their regarding
different good things as worth striving for, and being disagreed as to
the greater or less value, the order of rank, of the commonly recognized
desirable things:--it manifests itself much more in what they regard as
actually HAVING and POSSESSING a desirable thing. As regards a woman,
for instance, the control over her body and her sexual gratification
serves as an amply sufficient sign of ownership and possession to the
more modest man; another with a more suspicious and ambitious thirst for
possession, sees the "questionableness," the mere apparentness of such
ownership, and wishes to have finer tests in order to know especially
whether the woman not only gives herself to him, but also gives up for
his sake what she has or would like to have--only THEN does he look upon
her as "possessed." A third, however, has not even here got to the limit
of his distrust and his desire for possession: he asks himself whether
the woman, when she gives up everything for him, does not perhaps do
so for a phantom of him; he wishes first to be thoroughly, indeed,
profoundly well known; in order to be loved at all he ventures to let
himself be found out. Only then does he feel the beloved one fully in
his possession, when she no longer deceives herself about him, when
she loves him just as much for the sake of his devilry and concealed
insatiability, as for his goodness, patience, and spirituality. One
man would like to possess a nation, and he finds all the higher arts of
Cagliostro and Catalina suitable for his purpose. Another, with a more
refined thirst for possession, says to himself: "One may not deceive
where one desires to possess"--he is irritated and impatient at the idea
that a mask of him should rule in the hearts of the people: "I must,
therefore, MAKE myself known, and first of all learn to know myself!"
Among helpful and charitable people, one almost always finds the awkward
craftiness which first gets up suitably him who has to be helped, as
though, for instance, he should "merit" help, seek just THEIR help, and
would show himself deeply grateful, attached, and subservient to them
for all help. With these conceits, they take control of the needy as a
property, just as in general they are charitable and helpful out of a
desire for property. One finds them jealous when they are crossed or
forestalled in their charity. Parents involuntarily make something like
themselves out of their children--they call that "education"; no mother
doubts at the bottom of her heart that the child she has borne is
thereby her property, no father hesitates about his right to HIS OWN
ideas and notions of worth. Indeed, in former times fathers deemed it
right to use their discretion concerning the life or death of the newly
born (as among the ancient Germans). And like the father, so also do the
teacher, the class, the priest, and the prince still see in every new
individual an unobjectionable opportunity for a new possession. The
consequence is...
195. The Jews--a people "born for slavery," as Tacitus and the whole
ancient world say of them; "the chosen people among the nations," as
they themselves say and believe--the Jews performed the miracle of the
inversion of valuations, by means of which life on earth obtained a new
and dangerous charm for a couple of millenniums. Their prophets fused
into one the expressions "rich," "godless," "wicked," "violent,"
"sensual," and for the first time coined the word "world" as a term of
reproach. In this inversion of valuations (in which is also included
the use of the word "poor" as synonymous with "saint" and "friend") the
significance of the Jewish people is to be found; it is with THEM that
the SLAVE-INSURRECTION IN MORALS commences.
196. It is to be INFERRED that there are countless dark bodies near the
sun--such as we shall never see. Among ourselves, this is an allegory;
and the psychologist of morals reads the whole star-writing merely as an
allegorical and symbolic language in which much may be unexpressed.
197. The beast of prey and the man of prey (for instance, Caesar Borgia)
are fundamentally misunderstood, "nature" is misunderstood, so long as
one seeks a "morbidness" in the constitution of these healthiest of
all tropical monsters and growths, or even an innate "hell" in them--as
almost all moralists have done hitherto. Does it not seem that there is
a hatred of the virgin forest and of the tropics among moralists? And
that the "tropical man" must be discredited at all costs, whether
as disease and deterioration of mankind, or as his own hell and
self-torture? And why? In favour of the "temperate zones"? In favour
of the temperate men? The "moral"? The mediocre?--This for the chapter:
"Morals as Timidity."
198. All the systems of morals which address themselves with a view to
their "happiness," as it is called--what else are they but suggestions
for behaviour adapted to the degree of DANGER from themselves in which
the individuals live; recipes for their passions, their good and bad
propensities, insofar as such have the Will to Power and would like
to play the master; small and great expediencies and elaborations,
permeated with the musty odour of old family medicines and old-wife
wisdom; all of them grotesque and absurd in their form--because
they address themselves to "all," because they generalize where
generalization is not authorized; all of them speaking unconditionally,
and taking themselves unconditionally; all of them flavoured not merely
with one grain of salt, but rather endurable only, and sometimes even
seductive, when they are over-spiced and begin to smell dangerously,
especially of "the other world." That is all of little value when
estimated intellectually, and is far from being "science," much less
"wisdom"; but, repeated once more, and three times repeated, it is
expediency, expediency, expediency, mixed with stupidity, stupidity,
stupidity--whether it be the indifference and statuesque coldness
towards the heated folly of the emotions, which the Stoics advised and
fostered; or the no-more-laughing and no-more-weeping of Spinoza, the
destruction of the emotions by their analysis and vivisection, which he
recommended so naively; or the lowering of the emotions to an innocent
mean at which they may be satisfied, the Aristotelianism of morals;
or even morality as the enjoyment of the emotions in a voluntary
attenuation and spiritualization by the symbolism of art, perhaps as
music, or as love of God, and of mankind for God's sake--for in religion
the passions are once more enfranchised, provided that...; or, finally,
even the complaisant and wanton surrender to the emotions, as has
been taught by Hafis and Goethe, the bold letting-go of the reins, the
spiritual and corporeal licentia morum in the exceptional cases of
wise old codgers and drunkards, with whom it "no longer has much
danger."--This also for the chapter: "Morals as Timidity."
199. Inasmuch as in all ages, as long as mankind has existed, there have
also been human herds (family alliances, communities, tribes, peoples,
states, churches), and always a great number who obey in proportion
to the small number who command--in view, therefore, of the fact that
obedience has been most practiced and fostered among mankind hitherto,
one may reasonably suppose that, generally speaking, the need thereof is
now innate in every one, as a kind of FORMAL CONSCIENCE which gives
the command "Thou shalt unconditionally do something, unconditionally
refrain from something", in short, "Thou shalt". This need tries to
satisfy itself and to fill its form with a content, according to its
strength, impatience, an
gitextract_vmd1djyc/ ├── .github/ │ └── workflows/ │ └── python-app.yml ├── .gitignore ├── AUTHORS ├── Dockerfile ├── LICENSE ├── MANIFEST.in ├── README.md ├── examples/ │ ├── __init__.py │ ├── gaussian_mixture.py │ ├── gbm.py │ ├── kmeans.py │ ├── linear_models.py │ ├── naive_bayes.py │ ├── nearest_neighbors.py │ ├── nnet_convnet_mnist.py │ ├── nnet_mlp.py │ ├── nnet_rnn_binary_add.py │ ├── nnet_rnn_text_generation.py │ ├── pca.py │ ├── random_forest.py │ ├── rbm.py │ ├── rl_deep_q_learning.py │ ├── svm.py │ └── t-sne.py ├── mla/ │ ├── __init__.py │ ├── base/ │ │ ├── __init__.py │ │ └── base.py │ ├── datasets/ │ │ ├── __init__.py │ │ ├── base.py │ │ └── data/ │ │ ├── mnist/ │ │ │ ├── t10k-images-idx3-ubyte │ │ │ ├── t10k-labels-idx1-ubyte │ │ │ ├── train-images-idx3-ubyte │ │ │ └── train-labels-idx1-ubyte │ │ └── nietzsche.txt │ ├── ensemble/ │ │ ├── __init__.py │ │ ├── base.py │ │ ├── gbm.py │ │ ├── random_forest.py │ │ └── tree.py │ ├── fm.py │ ├── gaussian_mixture.py │ ├── kmeans.py │ ├── knn.py │ ├── linear_models.py │ ├── metrics/ │ │ ├── __init__.py │ │ ├── base.py │ │ ├── distance.py │ │ ├── metrics.py │ │ └── tests/ │ │ ├── __init__.py │ │ └── test_metrics.py │ ├── naive_bayes.py │ ├── neuralnet/ │ │ ├── __init__.py │ │ ├── activations.py │ │ ├── constraints.py │ │ ├── initializations.py │ │ ├── layers/ │ │ │ ├── __init__.py │ │ │ ├── basic.py │ │ │ ├── convnet.py │ │ │ ├── normalization.py │ │ │ └── recurrent/ │ │ │ ├── __init__.py │ │ │ ├── lstm.py │ │ │ └── rnn.py │ │ ├── loss.py │ │ ├── nnet.py │ │ ├── optimizers.py │ │ ├── parameters.py │ │ ├── regularizers.py │ │ └── tests/ │ │ ├── test_activations.py │ │ └── test_optimizers.py │ ├── pca.py │ ├── rbm.py │ ├── rl/ │ │ ├── __init__.py │ │ └── dqn.py │ ├── svm/ │ │ ├── __init__.py │ │ ├── kernerls.py │ │ └── svm.py │ ├── tests/ │ │ ├── __init__.py │ │ ├── test_classification_accuracy.py │ │ ├── test_reduction.py │ │ └── test_regression_accuracy.py │ ├── tsne.py │ └── utils/ │ ├── __init__.py │ └── main.py ├── requirements.txt ├── setup.cfg └── setup.py
SYMBOL INDEX (428 symbols across 54 files)
FILE: examples/gaussian_mixture.py
function make_clusters (line 12) | def make_clusters(skew=True, *arg, **kwargs):
function KMeans_and_GMM (line 21) | def KMeans_and_GMM(K):
FILE: examples/gbm.py
function classification (line 18) | def classification():
function regression (line 44) | def regression():
FILE: examples/kmeans.py
function kmeans_example (line 7) | def kmeans_example(plot=False):
FILE: examples/linear_models.py
function regression (line 17) | def regression():
function classification (line 38) | def classification():
FILE: examples/naive_bayes.py
function classification (line 8) | def classification():
FILE: examples/nearest_neighbors.py
function regression (line 13) | def regression():
function classification (line 34) | def classification():
FILE: examples/nnet_mlp.py
function classification (line 23) | def classification():
function regression (line 59) | def regression():
FILE: examples/nnet_rnn_binary_add.py
function addition_dataset (line 20) | def addition_dataset(dim=10, n_samples=10000, batch_size=64):
function addition_problem (line 56) | def addition_problem(ReccurentLayer):
FILE: examples/nnet_rnn_text_generation.py
function sample (line 22) | def sample(preds, temperature=1.0):
FILE: examples/random_forest.py
function classification (line 19) | def classification():
function regression (line 45) | def regression():
FILE: examples/rbm.py
function print_curve (line 10) | def print_curve(rbm):
FILE: examples/rl_deep_q_learning.py
function mlp_model (line 11) | def mlp_model(n_actions, batch_size=64):
FILE: examples/svm.py
function classification (line 16) | def classification():
FILE: mla/base/base.py
class BaseEstimator (line 5) | class BaseEstimator:
method _setup_input (line 9) | def _setup_input(self, X, y=None):
method fit (line 50) | def fit(self, X, y=None):
method predict (line 53) | def predict(self, X=None):
method _predict (line 62) | def _predict(self, X=None):
FILE: mla/datasets/base.py
function get_filename (line 7) | def get_filename(name):
function load_mnist (line 11) | def load_mnist():
function load_nietzsche (line 58) | def load_nietzsche():
FILE: mla/ensemble/base.py
function f_entropy (line 6) | def f_entropy(p):
function information_gain (line 16) | def information_gain(y, splits):
function mse_criterion (line 23) | def mse_criterion(y, splits):
function xgb_criterion (line 33) | def xgb_criterion(y, left, right, loss):
function get_split_mask (line 41) | def get_split_mask(X, column, value):
function split (line 47) | def split(X, y, value):
function split_dataset (line 53) | def split_dataset(X, target, column, value, return_X=True):
FILE: mla/ensemble/gbm.py
class Loss (line 20) | class Loss:
method __init__ (line 23) | def __init__(self, regularization=1.0):
method grad (line 26) | def grad(self, actual, predicted):
method hess (line 30) | def hess(self, actual, predicted):
method approximate (line 34) | def approximate(self, actual, predicted):
method transform (line 40) | def transform(self, pred):
method gain (line 44) | def gain(self, actual, predicted):
class LeastSquaresLoss (line 51) | class LeastSquaresLoss(Loss):
method grad (line 54) | def grad(self, actual, predicted):
method hess (line 57) | def hess(self, actual, predicted):
class LogisticLoss (line 61) | class LogisticLoss(Loss):
method grad (line 64) | def grad(self, actual, predicted):
method hess (line 67) | def hess(self, actual, predicted):
method transform (line 71) | def transform(self, output):
class GradientBoosting (line 76) | class GradientBoosting(BaseEstimator):
method __init__ (line 79) | def __init__(
method fit (line 95) | def fit(self, X, y=None):
method _train (line 100) | def _train(self):
method _predict (line 130) | def _predict(self, X=None):
method predict (line 137) | def predict(self, X=None):
class GradientBoostingRegressor (line 141) | class GradientBoostingRegressor(GradientBoosting):
method fit (line 142) | def fit(self, X, y=None):
class GradientBoostingClassifier (line 147) | class GradientBoostingClassifier(GradientBoosting):
method fit (line 148) | def fit(self, X, y=None):
FILE: mla/ensemble/random_forest.py
class RandomForest (line 9) | class RandomForest(BaseEstimator):
method __init__ (line 10) | def __init__(
method fit (line 39) | def fit(self, X, y):
method _train (line 47) | def _train(self):
method _predict (line 57) | def _predict(self, X=None):
class RandomForestClassifier (line 61) | class RandomForestClassifier(RandomForest):
method __init__ (line 62) | def __init__(
method _predict (line 87) | def _predict(self, X=None):
class RandomForestRegressor (line 101) | class RandomForestRegressor(RandomForest):
method __init__ (line 102) | def __init__(
method _predict (line 126) | def _predict(self, X=None):
FILE: mla/ensemble/tree.py
class Tree (line 12) | class Tree(object):
method __init__ (line 15) | def __init__(self, regression=False, criterion=None, n_classes=None):
method is_terminal (line 29) | def is_terminal(self):
method _find_splits (line 32) | def _find_splits(self, X):
method _find_best_split (line 45) | def _find_best_split(self, X, target, n_features):
method _train (line 70) | def _train(
method train (line 126) | def train(
method _calculate_leaf_value (line 176) | def _calculate_leaf_value(self, targets):
method predict_row (line 193) | def predict_row(self, row):
method predict (line 202) | def predict(self, X):
FILE: mla/fm.py
class BaseFM (line 18) | class BaseFM(BaseEstimator):
method __init__ (line 19) | def __init__(
method fit (line 40) | def fit(self, X, y=None):
method _train (line 52) | def _train(self):
method _factor_step (line 61) | def _factor_step(self, loss):
method _predict (line 67) | def _predict(self, X=None):
class FMRegressor (line 75) | class FMRegressor(BaseFM):
method fit (line 76) | def fit(self, X, y=None):
class FMClassifier (line 82) | class FMClassifier(BaseFM):
method fit (line 83) | def fit(self, X, y=None):
method predict (line 88) | def predict(self, X=None):
FILE: mla/gaussian_mixture.py
class GaussianMixture (line 13) | class GaussianMixture(BaseEstimator):
method __init__ (line 44) | def __init__(self, K=4, init="random", max_iters=500, tolerance=1e-3):
method fit (line 52) | def fit(self, X, y=None):
method _initialize (line 62) | def _initialize(self):
method _E_step (line 89) | def _E_step(self):
method _M_step (line 98) | def _M_step(self):
method _is_converged (line 109) | def _is_converged(self):
method _predict (line 117) | def _predict(self, X):
method _get_likelihood (line 126) | def _get_likelihood(self, data):
method _get_weighted_likelihood (line 135) | def _get_weighted_likelihood(self, likelihood):
method plot (line 138) | def plot(self, data=None, ax=None, holdon=False):
FILE: mla/kmeans.py
class KMeans (line 15) | class KMeans(BaseEstimator):
method __init__ (line 45) | def __init__(self, K=5, max_iters=100, init="random"):
method _initialize_centroids (line 52) | def _initialize_centroids(self, init):
method _predict (line 66) | def _predict(self, X=None):
method _get_predictions (line 84) | def _get_predictions(self):
method _assign (line 92) | def _assign(self, centroids):
method _closest (line 102) | def _closest(self, fpoint, centroids):
method _get_centroid (line 113) | def _get_centroid(self, cluster):
method _dist_from_centers (line 117) | def _dist_from_centers(self):
method _choose_next_center (line 123) | def _choose_next_center(self):
method _is_converged (line 130) | def _is_converged(self, centroids_old, centroids):
method plot (line 137) | def plot(self, ax=None, holdon=False):
FILE: mla/knn.py
class KNNBase (line 11) | class KNNBase(BaseEstimator):
method __init__ (line 12) | def __init__(self, k=5, distance_func=euclidean):
method aggregate (line 28) | def aggregate(self, neighbors_targets):
method _predict (line 31) | def _predict(self, X=None):
method _predict_x (line 36) | def _predict_x(self, x):
class KNNClassifier (line 55) | class KNNClassifier(KNNBase):
method aggregate (line 61) | def aggregate(self, neighbors_targets):
class KNNRegressor (line 68) | class KNNRegressor(KNNBase):
method aggregate (line 71) | def aggregate(self, neighbors_targets):
FILE: mla/linear_models.py
class BasicRegression (line 14) | class BasicRegression(BaseEstimator):
method __init__ (line 15) | def __init__(
method _loss (line 46) | def _loss(self, w):
method init_cost (line 49) | def init_cost(self):
method _add_penalty (line 52) | def _add_penalty(self, loss, w):
method _cost (line 60) | def _cost(self, X, y, theta):
method fit (line 65) | def fit(self, X, y=None):
method _add_intercept (line 79) | def _add_intercept(X):
method _train (line 83) | def _train(self):
method _predict (line 87) | def _predict(self, X=None):
method _gradient_descent (line 91) | def _gradient_descent(self):
class LinearRegression (line 111) | class LinearRegression(BasicRegression):
method _loss (line 114) | def _loss(self, w):
method init_cost (line 118) | def init_cost(self):
class LogisticRegression (line 122) | class LogisticRegression(BasicRegression):
method init_cost (line 125) | def init_cost(self):
method _loss (line 128) | def _loss(self, w):
method sigmoid (line 133) | def sigmoid(x):
method _predict (line 136) | def _predict(self, X=None):
FILE: mla/metrics/base.py
function check_data (line 5) | def check_data(a, b):
function validate_input (line 20) | def validate_input(function):
FILE: mla/metrics/distance.py
function euclidean_distance (line 7) | def euclidean_distance(a, b):
function l2_distance (line 15) | def l2_distance(X):
FILE: mla/metrics/metrics.py
function unhot (line 7) | def unhot(function):
function absolute_error (line 20) | def absolute_error(actual, predicted):
function classification_error (line 25) | def classification_error(actual, predicted):
function accuracy (line 30) | def accuracy(actual, predicted):
function mean_absolute_error (line 34) | def mean_absolute_error(actual, predicted):
function squared_error (line 38) | def squared_error(actual, predicted):
function squared_log_error (line 42) | def squared_log_error(actual, predicted):
function mean_squared_log_error (line 46) | def mean_squared_log_error(actual, predicted):
function mean_squared_error (line 50) | def mean_squared_error(actual, predicted):
function root_mean_squared_error (line 54) | def root_mean_squared_error(actual, predicted):
function root_mean_squared_log_error (line 58) | def root_mean_squared_log_error(actual, predicted):
function logloss (line 62) | def logloss(actual, predicted):
function hinge (line 68) | def hinge(actual, predicted):
function binary_crossentropy (line 72) | def binary_crossentropy(actual, predicted):
function get_metric (line 85) | def get_metric(name):
FILE: mla/metrics/tests/test_metrics.py
function test_data_validation (line 11) | def test_data_validation():
function metric (line 24) | def metric(name):
function test_classification_error (line 28) | def test_classification_error():
function test_absolute_error (line 35) | def test_absolute_error():
function test_mean_absolute_error (line 41) | def test_mean_absolute_error():
function test_squared_error (line 47) | def test_squared_error():
function test_squared_log_error (line 53) | def test_squared_log_error():
function test_mean_squared_log_error (line 60) | def test_mean_squared_log_error():
function test_root_mean_squared_log_error (line 66) | def test_root_mean_squared_log_error():
function test_mean_squared_error (line 72) | def test_mean_squared_error():
function test_root_mean_squared_error (line 78) | def test_root_mean_squared_error():
function test_multiclass_logloss (line 84) | def test_multiclass_logloss():
FILE: mla/naive_bayes.py
class NaiveBayesClassifier (line 9) | class NaiveBayesClassifier(BaseEstimator):
method fit (line 15) | def fit(self, X, y=None):
method _predict (line 35) | def _predict(self, X=None):
method _predict_row (line 42) | def _predict_row(self, x):
method _pdf (line 53) | def _pdf(self, n_class, x):
FILE: mla/neuralnet/activations.py
function sigmoid (line 9) | def sigmoid(z):
function softmax (line 13) | def softmax(z):
function linear (line 19) | def linear(z):
function softplus (line 23) | def softplus(z):
function softsign (line 30) | def softsign(z):
function tanh (line 34) | def tanh(z):
function relu (line 38) | def relu(z):
function leakyrelu (line 42) | def leakyrelu(z, a=0.01):
function get_activation (line 46) | def get_activation(name):
FILE: mla/neuralnet/constraints.py
class Constraint (line 7) | class Constraint(object):
method clip (line 8) | def clip(self, p):
class MaxNorm (line 12) | class MaxNorm(object):
method __init__ (line 13) | def __init__(self, m=2, axis=0):
method clip (line 17) | def clip(self, p):
class NonNeg (line 24) | class NonNeg(object):
method clip (line 25) | def clip(self, p):
class SmallNorm (line 30) | class SmallNorm(object):
method clip (line 31) | def clip(self, p):
class UnitNorm (line 35) | class UnitNorm(Constraint):
method __init__ (line 36) | def __init__(self, axis=0):
method clip (line 39) | def clip(self, p):
FILE: mla/neuralnet/initializations.py
function normal (line 10) | def normal(shape, scale=0.5):
function uniform (line 14) | def uniform(shape, scale=0.5):
function zero (line 18) | def zero(shape, **kwargs):
function one (line 22) | def one(shape, **kwargs):
function orthogonal (line 26) | def orthogonal(shape, scale=0.5):
function _glorot_fan (line 34) | def _glorot_fan(shape):
function glorot_normal (line 46) | def glorot_normal(shape, **kwargs):
function glorot_uniform (line 52) | def glorot_uniform(shape, **kwargs):
function he_normal (line 58) | def he_normal(shape, **kwargs):
function he_uniform (line 64) | def he_uniform(shape, **kwargs):
function get_initializer (line 70) | def get_initializer(name):
FILE: mla/neuralnet/layers/basic.py
class Layer (line 11) | class Layer(object):
method setup (line 12) | def setup(self, X_shape):
method forward_pass (line 16) | def forward_pass(self, x):
method backward_pass (line 19) | def backward_pass(self, delta):
method shape (line 22) | def shape(self, x_shape):
class ParamMixin (line 27) | class ParamMixin(object):
method parameters (line 29) | def parameters(self):
class PhaseMixin (line 33) | class PhaseMixin(object):
method is_training (line 37) | def is_training(self):
method is_training (line 41) | def is_training(self, is_train=True):
method is_testing (line 45) | def is_testing(self):
method is_testing (line 49) | def is_testing(self, is_test=True):
class Dense (line 53) | class Dense(Layer, ParamMixin):
method __init__ (line 54) | def __init__(self, output_dim, parameters=None):
method setup (line 68) | def setup(self, x_shape):
method forward_pass (line 71) | def forward_pass(self, X):
method weight (line 75) | def weight(self, X):
method backward_pass (line 79) | def backward_pass(self, delta):
method shape (line 88) | def shape(self, x_shape):
class Activation (line 92) | class Activation(Layer):
method __init__ (line 93) | def __init__(self, name):
method forward_pass (line 99) | def forward_pass(self, X):
method backward_pass (line 103) | def backward_pass(self, delta):
method shape (line 106) | def shape(self, x_shape):
class Dropout (line 110) | class Dropout(Layer, PhaseMixin):
method __init__ (line 113) | def __init__(self, p=0.1):
method forward_pass (line 117) | def forward_pass(self, X):
method backward_pass (line 127) | def backward_pass(self, delta):
method shape (line 130) | def shape(self, x_shape):
class TimeStepSlicer (line 134) | class TimeStepSlicer(Layer):
method __init__ (line 137) | def __init__(self, step=-1):
method forward_pass (line 140) | def forward_pass(self, x):
method backward_pass (line 143) | def backward_pass(self, delta):
method shape (line 146) | def shape(self, x_shape):
class TimeDistributedDense (line 150) | class TimeDistributedDense(Layer):
method __init__ (line 153) | def __init__(self, output_dim):
method setup (line 159) | def setup(self, X_shape):
method forward_pass (line 164) | def forward_pass(self, X):
method backward_pass (line 171) | def backward_pass(self, delta):
method parameters (line 179) | def parameters(self):
method shape (line 182) | def shape(self, x_shape):
FILE: mla/neuralnet/layers/convnet.py
class Convolution (line 8) | class Convolution(Layer, ParamMixin):
method __init__ (line 9) | def __init__(
method setup (line 41) | def setup(self, X_shape):
method forward_pass (line 48) | def forward_pass(self, X):
method backward_pass (line 58) | def backward_pass(self, delta):
method shape (line 71) | def shape(self, x_shape):
class MaxPooling (line 78) | class MaxPooling(Layer):
method __init__ (line 79) | def __init__(self, pool_shape=(2, 2), stride=(1, 1), padding=(0, 0)):
method forward_pass (line 93) | def forward_pass(self, X):
method backward_pass (line 109) | def backward_pass(self, delta):
method shape (line 122) | def shape(self, x_shape):
class Flatten (line 129) | class Flatten(Layer):
method forward_pass (line 132) | def forward_pass(self, X):
method backward_pass (line 136) | def backward_pass(self, delta):
method shape (line 139) | def shape(self, x_shape):
function image_to_column (line 143) | def image_to_column(images, filter_shape, stride, padding):
function column_to_image (line 175) | def column_to_image(columns, images_shape, filter_shape, stride, padding):
function convoltuion_shape (line 210) | def convoltuion_shape(img_height, img_width, filter_shape, stride, paddi...
function pooling_shape (line 221) | def pooling_shape(pool_shape, image_shape, stride):
FILE: mla/neuralnet/layers/normalization.py
class BatchNormalization (line 13) | class BatchNormalization(Layer, ParamMixin, PhaseMixin):
method __init__ (line 14) | def __init__(self, momentum=0.9, eps=1e-5, parameters=None):
method setup (line 24) | def setup(self, x_shape):
method _forward_pass (line 27) | def _forward_pass(self, X):
method forward_pass (line 82) | def forward_pass(self, X):
method _backward_pass (line 97) | def _backward_pass(self, delta):
method backward_pass (line 144) | def backward_pass(self, X):
method shape (line 157) | def shape(self, x_shape):
FILE: mla/neuralnet/layers/recurrent/lstm.py
class LSTM (line 17) | class LSTM(Layer, ParamMixin):
method __init__ (line 18) | def __init__(
method setup (line 47) | def setup(self, x_shape):
method forward_pass (line 87) | def forward_pass(self, X):
method backward_pass (line 133) | def backward_pass(self, delta):
method shape (line 191) | def shape(self, x_shape):
FILE: mla/neuralnet/layers/recurrent/rnn.py
class RNN (line 10) | class RNN(Layer, ParamMixin):
method __init__ (line 13) | def __init__(
method setup (line 35) | def setup(self, x_shape):
method forward_pass (line 55) | def forward_pass(self, X):
method backward_pass (line 76) | def backward_pass(self, delta):
method shape (line 106) | def shape(self, x_shape):
FILE: mla/neuralnet/loss.py
function get_loss (line 6) | def get_loss(name):
FILE: mla/neuralnet/nnet.py
class NeuralNet (line 22) | class NeuralNet(BaseEstimator):
method __init__ (line 25) | def __init__(
method _setup_layers (line 58) | def _setup_layers(self, x_shape):
method _find_bprop_entry (line 73) | def _find_bprop_entry(self):
method fit (line 80) | def fit(self, X, y=None):
method update (line 94) | def update(self, X, y):
method fprop (line 104) | def fprop(self, X):
method _predict (line 110) | def _predict(self, X=None):
method parametric_layers (line 121) | def parametric_layers(self):
method parameters (line 127) | def parameters(self):
method error (line 134) | def error(self, X=None, y=None):
method is_training (line 152) | def is_training(self):
method is_training (line 156) | def is_training(self, train):
method shuffle_dataset (line 162) | def shuffle_dataset(self):
method n_layers (line 171) | def n_layers(self):
method n_params (line 176) | def n_params(self):
method reset (line 180) | def reset(self):
FILE: mla/neuralnet/optimizers.py
class Optimizer (line 17) | class Optimizer(object):
method optimize (line 18) | def optimize(self, network):
method update (line 35) | def update(self, network):
method train_epoch (line 39) | def train_epoch(self, network):
method train_batch (line 60) | def train_batch(self, network, X, y):
method setup (line 65) | def setup(self, network):
class SGD (line 71) | class SGD(Optimizer):
method __init__ (line 72) | def __init__(self, learning_rate=0.01, momentum=0.9, decay=0.0, nester...
method update (line 80) | def update(self, network):
method setup (line 95) | def setup(self, network):
class Adagrad (line 102) | class Adagrad(Optimizer):
method __init__ (line 103) | def __init__(self, learning_rate=0.01, epsilon=1e-8):
method update (line 107) | def update(self, network):
method setup (line 115) | def setup(self, network):
class Adadelta (line 123) | class Adadelta(Optimizer):
method __init__ (line 124) | def __init__(self, learning_rate=1.0, rho=0.95, epsilon=1e-8):
method update (line 129) | def update(self, network):
method setup (line 148) | def setup(self, network):
class RMSprop (line 158) | class RMSprop(Optimizer):
method __init__ (line 159) | def __init__(self, learning_rate=0.001, rho=0.9, epsilon=1e-8):
method update (line 164) | def update(self, network):
method setup (line 174) | def setup(self, network):
class Adam (line 182) | class Adam(Optimizer):
method __init__ (line 183) | def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsi...
method update (line 191) | def update(self, network):
method setup (line 211) | def setup(self, network):
class Adamax (line 221) | class Adamax(Optimizer):
method __init__ (line 222) | def __init__(self, learning_rate=0.002, beta_1=0.9, beta_2=0.999, epsi...
method update (line 229) | def update(self, network):
method setup (line 245) | def setup(self, network):
FILE: mla/neuralnet/parameters.py
class Parameters (line 7) | class Parameters(object):
method __init__ (line 8) | def __init__(
method setup_weights (line 49) | def setup_weights(self, W_shape, b_shape=None):
method init_grad (line 58) | def init_grad(self):
method step (line 64) | def step(self, name, step):
method update_grad (line 71) | def update_grad(self, name, value):
method n_params (line 79) | def n_params(self):
method keys (line 83) | def keys(self):
method grad (line 87) | def grad(self):
method __getitem__ (line 91) | def __getitem__(self, item):
method __setitem__ (line 97) | def __setitem__(self, key, value):
FILE: mla/neuralnet/regularizers.py
class Regularizer (line 6) | class Regularizer(object):
method __init__ (line 7) | def __init__(self, C=0.01):
method _penalty (line 11) | def _penalty(self, weights):
method grad (line 14) | def grad(self, weights):
method __call__ (line 17) | def __call__(self, weights):
class L1 (line 21) | class L1(Regularizer):
method _penalty (line 22) | def _penalty(self, weights):
class L2 (line 26) | class L2(Regularizer):
method _penalty (line 27) | def _penalty(self, weights):
class ElasticNet (line 31) | class ElasticNet(Regularizer):
method _penalty (line 34) | def _penalty(self, weights):
FILE: mla/neuralnet/tests/test_activations.py
function test_softplus (line 8) | def test_softplus():
FILE: mla/neuralnet/tests/test_optimizers.py
function clasifier (line 11) | def clasifier(optimizer):
function test_adadelta (line 49) | def test_adadelta():
function test_adam (line 53) | def test_adam():
function test_adamax (line 57) | def test_adamax():
function test_rmsprop (line 61) | def test_rmsprop():
function test_adagrad (line 65) | def test_adagrad():
function test_sgd (line 69) | def test_sgd():
FILE: mla/pca.py
class PCA (line 12) | class PCA(BaseEstimator):
method __init__ (line 15) | def __init__(self, n_components, solver="svd"):
method fit (line 35) | def fit(self, X, y=None):
method _decompose (line 39) | def _decompose(self, X):
method transform (line 57) | def transform(self, X):
method _predict (line 62) | def _predict(self, X=None):
FILE: mla/rbm.py
class RBM (line 19) | class RBM(BaseEstimator):
method __init__ (line 22) | def __init__(self, n_hidden=128, learning_rate=0.1, batch_size=10, max...
method fit (line 39) | def fit(self, X, y=None):
method _init_weights (line 45) | def _init_weights(self):
method _train (line 54) | def _train(self):
method _sample (line 97) | def _sample(self, X):
method _predict (line 100) | def _predict(self, X=None):
FILE: mla/rl/dqn.py
class DQN (line 20) | class DQN(object):
method __init__ (line 21) | def __init__(
method init_environment (line 55) | def init_environment(self, name="CartPole-v0", monitor=False):
method init_model (line 68) | def init_model(self, model):
method train (line 71) | def train(self, render=False):
method play (line 145) | def play(self, episodes):
FILE: mla/svm/kernerls.py
class Linear (line 6) | class Linear(object):
method __call__ (line 7) | def __call__(self, x, y):
method __repr__ (line 10) | def __repr__(self):
class Poly (line 14) | class Poly(object):
method __init__ (line 15) | def __init__(self, degree=2):
method __call__ (line 18) | def __call__(self, x, y):
method __repr__ (line 21) | def __repr__(self):
class RBF (line 25) | class RBF(object):
method __init__ (line 26) | def __init__(self, gamma=0.1):
method __call__ (line 29) | def __call__(self, x, y):
method __repr__ (line 34) | def __repr__(self):
FILE: mla/svm/svm.py
class SVM (line 17) | class SVM(BaseEstimator):
method __init__ (line 18) | def __init__(self, C=1.0, kernel=None, tol=1e-3, max_iter=100):
method fit (line 40) | def fit(self, X, y=None):
method _train (line 49) | def _train(self):
method _predict (line 107) | def _predict(self, X=None):
method _predict_row (line 114) | def _predict_row(self, X):
method clip (line 118) | def clip(self, alpha, H, L):
method _error (line 125) | def _error(self, i):
method _find_bounds (line 129) | def _find_bounds(self, i, j):
method random_index (line 141) | def random_index(self, z):
FILE: mla/tests/test_classification_accuracy.py
function test_linear_model (line 43) | def test_linear_model():
function test_random_forest (line 50) | def test_random_forest():
function test_svm_classification (line 57) | def test_svm_classification():
function test_mlp (line 68) | def test_mlp():
function test_gbm (line 93) | def test_gbm():
function test_naive_bayes (line 102) | def test_naive_bayes():
function test_knn (line 109) | def test_knn():
FILE: mla/tests/test_reduction.py
function dataset (line 16) | def dataset():
function test_PCA (line 30) | def test_PCA(dataset):
FILE: mla/tests/test_regression_accuracy.py
function test_linear (line 30) | def test_linear():
function test_mlp (line 37) | def test_mlp():
function test_knn (line 57) | def test_knn():
FILE: mla/tsne.py
class TSNE (line 19) | class TSNE(BaseEstimator):
method __init__ (line 22) | def __init__(
method fit_transform (line 43) | def fit_transform(self, X, y=None):
method _get_pairwise_affinities (line 85) | def _get_pairwise_affinities(self, X):
method _binary_search (line 101) | def _binary_search(self, dist, target_entropy):
method _q_distribution (line 131) | def _q_distribution(self, D):
FILE: mla/utils/main.py
function one_hot (line 5) | def one_hot(y):
function batch_iterator (line 10) | def batch_iterator(X, batch_size=64):
Condensed preview — 86 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (779K chars).
[
{
"path": ".github/workflows/python-app.yml",
"chars": 529,
"preview": "name: Tests\n\non:\n push:\n branches: [ master ]\n pull_request:\n branches: [ master ]\n\njobs:\n build:\n timeout-m"
},
{
"path": ".gitignore",
"chars": 51,
"preview": "*.pyc\nbuild/\ndist/\nmla.egg-info/\n.cache\n*.swp\n.idea"
},
{
"path": "AUTHORS",
"chars": 244,
"preview": "Artem Golubin <me@rushter.com>\nAnebi Agbo\nConvex Path\nJames Chevalier\nJiancheng\nKaiMin Lai\nNguyễn Tuấn\nNicolas Hug\nXiaoc"
},
{
"path": "Dockerfile",
"chars": 174,
"preview": "FROM python:3\n\nRUN mkdir -p /var/app\nWORKDIR /var/app\nCOPY . /var/app\n\n# install scipy & numpy\n# install required packag"
},
{
"path": "LICENSE",
"chars": 1075,
"preview": "MIT License\n\nCopyright (c) 2016-2020 Artem Golubin\n\nPermission is hereby granted, free of charge, to any person obtainin"
},
{
"path": "MANIFEST.in",
"chars": 38,
"preview": "recursive-include mla/datasets/data *\n"
},
{
"path": "README.md",
"chars": 1870,
"preview": "# Machine learning algorithms\nA collection of minimal and clean implementations of machine learning algorithms.\n\n### Why"
},
{
"path": "examples/__init__.py",
"chars": 16,
"preview": "# coding: utf-8\n"
},
{
"path": "examples/gaussian_mixture.py",
"chars": 1117,
"preview": "import random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom mla.kmeans import KMe"
},
{
"path": "examples/gbm.py",
"chars": 1926,
"preview": "import logging\n\nfrom sklearn.datasets import make_classification\nfrom sklearn.datasets import make_regression\nfrom sklea"
},
{
"path": "examples/kmeans.py",
"chars": 436,
"preview": "import numpy as np\nfrom sklearn.datasets import make_blobs\n\nfrom mla.kmeans import KMeans\n\n\ndef kmeans_example(plot=Fals"
},
{
"path": "examples/linear_models.py",
"chars": 1702,
"preview": "import logging\n\ntry:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross"
},
{
"path": "examples/naive_bayes.py",
"chars": 826,
"preview": "from sklearn.datasets import make_classification\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection "
},
{
"path": "examples/nearest_neighbors.py",
"chars": 1556,
"preview": "try:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross_validation impo"
},
{
"path": "examples/nnet_convnet_mnist.py",
"chars": 1409,
"preview": "import logging\n\nfrom mla.datasets import load_mnist\nfrom mla.metrics import accuracy\nfrom mla.neuralnet import NeuralNet"
},
{
"path": "examples/nnet_mlp.py",
"chars": 2703,
"preview": "import logging\n\ntry:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross"
},
{
"path": "examples/nnet_rnn_binary_add.py",
"chars": 2532,
"preview": "import logging\nfrom itertools import combinations, islice\n\nimport numpy as np\n\ntry:\n from sklearn.model_selection imp"
},
{
"path": "examples/nnet_rnn_text_generation.py",
"chars": 2277,
"preview": "from __future__ import print_function\n\nimport logging\nimport random\n\nimport numpy as np\nimport sys\n\nfrom mla.datasets im"
},
{
"path": "examples/pca.py",
"chars": 1090,
"preview": "try:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross_validation impo"
},
{
"path": "examples/random_forest.py",
"chars": 2020,
"preview": "import logging\n\nimport numpy as np\nfrom sklearn.datasets import make_classification\nfrom sklearn.datasets import make_re"
},
{
"path": "examples/rbm.py",
"chars": 510,
"preview": "import logging\n\nimport numpy as np\n\nfrom mla.rbm import RBM\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\ndef print_curve("
},
{
"path": "examples/rl_deep_q_learning.py",
"chars": 1008,
"preview": "import logging\n\nfrom mla.neuralnet import NeuralNet\nfrom mla.neuralnet.layers import Activation, Dense\nfrom mla.neuralne"
},
{
"path": "examples/svm.py",
"chars": 1123,
"preview": "import logging\n\ntry:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross"
},
{
"path": "examples/t-sne.py",
"chars": 538,
"preview": "import logging\n\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_classification\n\nfrom mla.tsne import T"
},
{
"path": "mla/__init__.py",
"chars": 100,
"preview": "# coding:utf-8\n# copyright: (c) 2016 by Artem Golubin\n# license: MIT, see LICENSE for more details.\n"
},
{
"path": "mla/base/__init__.py",
"chars": 35,
"preview": "# coding:utf-8\nfrom .base import *\n"
},
{
"path": "mla/base/base.py",
"chars": 1826,
"preview": "# coding:utf-8\nimport numpy as np\n\n\nclass BaseEstimator:\n y_required = True\n fit_required = True\n\n def _setup_i"
},
{
"path": "mla/datasets/__init__.py",
"chars": 47,
"preview": "# coding:utf-8\nfrom mla.datasets.base import *\n"
},
{
"path": "mla/datasets/base.py",
"chars": 2605,
"preview": "# coding:utf-8\nimport os\n\nimport numpy as np\n\n\ndef get_filename(name):\n return os.path.join(os.path.dirname(__file__)"
},
{
"path": "mla/datasets/data/nietzsche.txt",
"chars": 600893,
"preview": "PREFACE\n\n\nSUPPOSING that Truth is a woman--what then? Is there not ground\nfor suspecting that all philosophers, in so fa"
},
{
"path": "mla/ensemble/__init__.py",
"chars": 88,
"preview": "# coding:utf-8\nfrom .random_forest import RandomForestClassifier, RandomForestRegressor\n"
},
{
"path": "mla/ensemble/base.py",
"chars": 1591,
"preview": "# coding:utf-8\nimport numpy as np\nfrom scipy import stats\n\n\ndef f_entropy(p):\n # Convert values to probability\n p "
},
{
"path": "mla/ensemble/gbm.py",
"chars": 4484,
"preview": "# coding:utf-8\nimport numpy as np\n\n# logistic function\nfrom scipy.special import expit\n\nfrom mla.base import BaseEstimat"
},
{
"path": "mla/ensemble/random_forest.py",
"chars": 3795,
"preview": "# coding:utf-8\nimport numpy as np\n\nfrom mla.base import BaseEstimator\nfrom mla.ensemble.base import information_gain, ms"
},
{
"path": "mla/ensemble/tree.py",
"chars": 6424,
"preview": "# coding:utf-8\nimport random\n\nimport numpy as np\nfrom scipy import stats\n\nfrom mla.ensemble.base import split, split_dat"
},
{
"path": "mla/fm.py",
"chars": 2694,
"preview": "# coding:utf-8\n\nimport autograd.numpy as np\nfrom autograd import elementwise_grad\n\nfrom mla.base import BaseEstimator\nfr"
},
{
"path": "mla/gaussian_mixture.py",
"chars": 6850,
"preview": "# coding:utf-8\n\nimport random\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import multivariate_n"
},
{
"path": "mla/kmeans.py",
"chars": 5288,
"preview": "# coding:utf-8\n\nimport random\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nfrom mla.base i"
},
{
"path": "mla/knn.py",
"chars": 2281,
"preview": "# coding:utf-8\n\nfrom collections import Counter\n\nimport numpy as np\nfrom scipy.spatial.distance import euclidean\n\nfrom m"
},
{
"path": "mla/linear_models.py",
"chars": 4144,
"preview": "# coding:utf-8\n\nimport logging\n\nimport autograd.numpy as np\nfrom autograd import grad\n\nfrom mla.base import BaseEstimato"
},
{
"path": "mla/metrics/__init__.py",
"chars": 38,
"preview": "# coding:utf-8\nfrom .metrics import *\n"
},
{
"path": "mla/metrics/base.py",
"chars": 524,
"preview": "# coding:utf-8\nimport numpy as np\n\n\ndef check_data(a, b):\n if not isinstance(a, np.ndarray):\n a = np.array(a)\n"
},
{
"path": "mla/metrics/distance.py",
"chars": 327,
"preview": "# coding:utf-8\nimport math\n\nimport numpy as np\n\n\ndef euclidean_distance(a, b):\n if isinstance(a, list) and isinstance"
},
{
"path": "mla/metrics/metrics.py",
"chars": 2216,
"preview": "# coding:utf-8\nimport autograd.numpy as np\n\nEPS = 1e-15\n\n\ndef unhot(function):\n \"\"\"Convert one-hot representation int"
},
{
"path": "mla/metrics/tests/__init__.py",
"chars": 15,
"preview": "# coding:utf-8\n"
},
{
"path": "mla/metrics/tests/test_metrics.py",
"chars": 2320,
"preview": "from __future__ import division\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_almost_equal\n\nfrom ml"
},
{
"path": "mla/naive_bayes.py",
"chars": 1899,
"preview": "# coding:utf-8\n\nimport numpy as np\n\nfrom mla.base import BaseEstimator\nfrom mla.neuralnet.activations import softmax\n\n\nc"
},
{
"path": "mla/neuralnet/__init__.py",
"chars": 28,
"preview": "from .nnet import NeuralNet\n"
},
{
"path": "mla/neuralnet/activations.py",
"chars": 923,
"preview": "import autograd.numpy as np\n\n\"\"\"\nReferences:\nhttps://en.wikipedia.org/wiki/Activation_function\n\"\"\"\n\n\ndef sigmoid(z):\n "
},
{
"path": "mla/neuralnet/constraints.py",
"chars": 762,
"preview": "# coding:utf-8\nimport numpy as np\n\nEPSILON = 10e-8\n\n\nclass Constraint(object):\n def clip(self, p):\n return p\n\n"
},
{
"path": "mla/neuralnet/initializations.py",
"chars": 1761,
"preview": "import numpy as np\n\n\"\"\"\nReferences:\nhttp://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n\n\"\"\"\n\n\ndef normal(shap"
},
{
"path": "mla/neuralnet/layers/__init__.py",
"chars": 88,
"preview": "# coding:utf-8\nfrom .basic import *\nfrom .convnet import *\nfrom .normalization import *\n"
},
{
"path": "mla/neuralnet/layers/basic.py",
"chars": 4525,
"preview": "# coding:utf-8\nimport autograd.numpy as np\nfrom autograd import elementwise_grad\n\nfrom mla.neuralnet.activations import "
},
{
"path": "mla/neuralnet/layers/convnet.py",
"chars": 7845,
"preview": "# coding:utf-8\nimport autograd.numpy as np\n\nfrom mla.neuralnet.layers import Layer, ParamMixin\nfrom mla.neuralnet.parame"
},
{
"path": "mla/neuralnet/layers/normalization.py",
"chars": 4621,
"preview": "# coding:utf-8\nimport numpy as np\n\nfrom mla.neuralnet.layers import Layer, PhaseMixin, ParamMixin\nfrom mla.neuralnet.par"
},
{
"path": "mla/neuralnet/layers/recurrent/__init__.py",
"chars": 54,
"preview": "# coding:utf-8\nfrom .lstm import *\nfrom .rnn import *\n"
},
{
"path": "mla/neuralnet/layers/recurrent/lstm.py",
"chars": 6735,
"preview": "# coding:utf-8\nimport autograd.numpy as np\nfrom autograd import elementwise_grad\n\nfrom mla.neuralnet.activations import "
},
{
"path": "mla/neuralnet/layers/recurrent/rnn.py",
"chars": 3540,
"preview": "# coding:utf-8\nimport autograd.numpy as np\nfrom autograd import elementwise_grad\n\nfrom mla.neuralnet.initializations imp"
},
{
"path": "mla/neuralnet/loss.py",
"chars": 285,
"preview": "from ..metrics import mse, logloss, mae, hinge, binary_crossentropy\n\ncategorical_crossentropy = logloss\n\n\ndef get_loss(n"
},
{
"path": "mla/neuralnet/nnet.py",
"chars": 5097,
"preview": "import logging\n\nimport numpy as np\nfrom autograd import elementwise_grad\n\nfrom mla.base import BaseEstimator\nfrom mla.me"
},
{
"path": "mla/neuralnet/optimizers.py",
"chars": 8784,
"preview": "import logging\nimport time\nfrom collections import defaultdict\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom mla.utils"
},
{
"path": "mla/neuralnet/parameters.py",
"chars": 2892,
"preview": "# coding:utf-8\nimport numpy as np\n\nfrom mla.neuralnet.initializations import get_initializer\n\n\nclass Parameters(object):"
},
{
"path": "mla/neuralnet/regularizers.py",
"chars": 795,
"preview": "# coding:utf-8\nimport numpy as np\nfrom autograd import elementwise_grad\n\n\nclass Regularizer(object):\n def __init__(se"
},
{
"path": "mla/neuralnet/tests/test_activations.py",
"chars": 650,
"preview": "import sys\n\nimport numpy as np\n\nfrom mla.neuralnet.activations import *\n\n\ndef test_softplus():\n # np.exp(z_max) will "
},
{
"path": "mla/neuralnet/tests/test_optimizers.py",
"chars": 1832,
"preview": "from sklearn.datasets import make_classification\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection "
},
{
"path": "mla/pca.py",
"chars": 1780,
"preview": "# coding:utf-8\nimport logging\n\nimport numpy as np\nfrom scipy.linalg import svd\n\nfrom mla.base import BaseEstimator\n\nnp.r"
},
{
"path": "mla/rbm.py",
"chars": 3470,
"preview": "# coding:utf-8\nimport logging\n\nimport numpy as np\nfrom scipy.special import expit\n\nfrom mla.base import BaseEstimator\nfr"
},
{
"path": "mla/rl/__init__.py",
"chars": 15,
"preview": "# coding:utf-8\n"
},
{
"path": "mla/rl/dqn.py",
"chars": 4664,
"preview": "# coding:utf-8\nimport logging\nimport random\n\nimport gym\nimport numpy as np\nfrom gym import wrappers\n\nnp.random.seed(9999"
},
{
"path": "mla/svm/__init__.py",
"chars": 15,
"preview": "# coding:utf-8\n"
},
{
"path": "mla/svm/kernerls.py",
"chars": 721,
"preview": "# coding:utf-8\nimport numpy as np\nimport scipy.spatial.distance as dist\n\n\nclass Linear(object):\n def __call__(self, x"
},
{
"path": "mla/svm/svm.py",
"chars": 4450,
"preview": "# coding:utf-8\nimport logging\n\nimport numpy as np\n\nfrom mla.base import BaseEstimator\nfrom mla.svm.kernerls import Linea"
},
{
"path": "mla/tests/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "mla/tests/test_classification_accuracy.py",
"chars": 3415,
"preview": "from sklearn.metrics import roc_auc_score\n\nfrom mla.ensemble import RandomForestClassifier\nfrom mla.ensemble.gbm import "
},
{
"path": "mla/tests/test_reduction.py",
"chars": 1216,
"preview": "# coding=utf-8\nimport pytest\nfrom sklearn.datasets import make_classification\nfrom sklearn.metrics import roc_auc_score\n"
},
{
"path": "mla/tests/test_regression_accuracy.py",
"chars": 1715,
"preview": "try:\n from sklearn.model_selection import train_test_split\nexcept ImportError:\n from sklearn.cross_validation impo"
},
{
"path": "mla/tsne.py",
"chars": 4023,
"preview": "# coding:utf-8\nimport logging\n\nimport numpy as np\n\nfrom mla.base import BaseEstimator\nfrom mla.metrics.distance import l"
},
{
"path": "mla/utils/__init__.py",
"chars": 36,
"preview": "# coding:utf-8\n\nfrom .main import *\n"
},
{
"path": "mla/utils/main.py",
"chars": 534,
"preview": "# coding:utf-8\nimport numpy as np\n\n\ndef one_hot(y):\n n_values = np.max(y) + 1\n return np.eye(n_values)[y]\n\n\ndef ba"
},
{
"path": "requirements.txt",
"chars": 105,
"preview": "tqdm\nmatplotlib>=1.5.1\nnumpy>=1.11.1\nscikit-learn>=0.18\nscipy>=0.18.0\nseaborn>=0.7.1\nautograd>=1.1.7\ngym\n"
},
{
"path": "setup.cfg",
"chars": 97,
"preview": "[bdist_wheel]\nuniversal=1\n\n[metadata]\ndescription-file=README.md\n\n[flake8]\nmax-line-length = 120\n"
},
{
"path": "setup.py",
"chars": 1211,
"preview": "from setuptools import setup, find_packages\nfrom codecs import open\nfrom os import path\n\n__version__ = '0.0.1'\n\nhere = p"
}
]
// ... and 4 more files (download for full content)
About this extraction
This page contains the full source code of the rushter/MLAlgorithms GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 86 files (45.6 MB), approximately 179.3k tokens, and a symbol index with 428 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.